Legal Information

DirectX 8.1
Programmer's Reference

Information in this document, including URL and other Internet Web site references, is subject to change without notice. The entire risk of the use or the results of the use of this document remains with the user. 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.

All public network IDs or addresses referenced in this document are for demonstration/example purposes only. Microsoft's inclusion of such IDs and addresses in this document does not grant you any express or implied right to test or otherwise use or access any such network ID or address.

The links in this area will let you leave Microsoft's product and/or Web site. The linked sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement by Microsoft of the site.

For your convenience, Microsoft may make available on this service or in its software products, tools and utilities for use and/or download. Microsoft does not make any assurances with regard to the accuracy of the results or output that derives from such use of any such tools and utilities. Please respect the intellectual property rights of others when using the tools and utilities made available on this service or in Microsoft software products.

© 1995-2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, Direct3D, DirectAnimation, DirectDraw, DirectInput, DirectMusic, DirectPlay, DirectShow, DirectSound, DirectX, Natural, and Win32 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

Roland GS Sound Set/Microsoft (R) 1996 Roland Corporation U.S.

Roland is a registered trademark of the Roland Corporation.

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

Note: Manufacturers of telecommunications devices implementing this API must ensure compliance with section 255 of the telecommunications act of 1996.

Copyright Warning

Special Note and Warning The Roland GS Sound Set/Microsoft, the "Sample Set", incorporates the SoundCanvas Sound Set. Roland Corporation U.S. owns the Sample Set and all copyrights pertaining thereto and has licensed the Sample Set for use solely on Microsoft Operating Systems Products and Microsoft Application Products.

Roland reserves all rights to the Sample Set not expressly granted by Roland Corporation U.S. or by Microsoft under the terms of Microsoft's End User License Agreement.

The Sample Set may only be redistributed with your software application as an integral component of a Microsoft Operating System Product and under the terms of Microsoft's End User License Agreement. All other uses of the Sample Set require a separate written license from Roland Corporation U.S.

The Sample Set may not be used, copied or redistributed in hardware ROM or similar technology of any device without prior express written permission from an authorized representative of Roland Corporation U.S. The Sample Set may not be redistributed with any Musical Instrument. A "Musical Instrument" is any device that is capable of generating musical sounds without being directly connected to a computer with a licensed Microsoft Operating System. You may not modify the Sample Set under any circumstances.


Introducing DirectX 8.1

Microsoft® DirectX® is a set of low-level application programming interfaces (APIs) for creating games and other high-performance multimedia applications. It includes support for two-dimensional (2-D) and three-dimensional (3-D) graphics, sound effects, music, input devices, and networked applications such as multiplayer games.

This document provides introductory information about DirectX 8.1. Information is divided into the following sections.

  • What's New in DirectX 8.1
  • DirectX 8.1 Components
  • Using the DirectX 8.1 Documentation
  • DirectX Tools
  • Programming DirectX with Visual Basic
    •
  • Further Information


What's New in DirectX 8.1

Microsoft® DirectX® 8.1 is a major release primarily for graphics. It includes several new features for graphics, and bug fixes for Microsoft DirectInput® and Microsoft DirectPlay®.

New Features in DirectX Graphics

  • Expanded pixel shader functionality with new version 1.2, 1.3, and 1.4.
  • Expanded the functionality of the Direct3DX (D3DX) utility library for meshes, textures, bump mapping, textures, and quaternions.
  • MeshView. This tool provides an easy way to load, view, and modify meshes, and generally exercise D3DX functionality on progressive meshes. For more information about the tool, see Mesh View Help.
  • Added new samples.
  • Reorganized the documentation into reference and programming guides. Expanded shaders and effects sections.

For more information see What's New in Graphics, or see each of the components.

New Features in DirectInput

Version 8.1 primarily includes performance improvements for DirectInput.

For more information, see What's New in DirectInput.

New Features in DirectPlay

Version 8.1 primarily includes performance improvements for DirectPlay.

For more information, see What's New in DirectPlay.

New Features in DirectX 8.0

Complete integration of DirectDraw and Direct3D
Microsoft DirectDraw® and Microsoft Direct3D® are merged into a single DirectX Graphics component. The application programming interface (API) has been extensively updated to make it even easier to use and to support the latest graphics hardware.
DirectMusic and DirectSound more integrated
Microsoft DirectMusic® and Microsoft DirectSound® are more tightly integrated than with DirectX 7.0. Wave files or resources can now be loaded by the DirectMusic loader and played through the DirectMusic performance, synchronized with MIDI notes.
DirectPlay updated
The DirectPlay component has been extensively updated to increase its capabilities and improve its ease-of-use. In particular, DirectPlay now supports voice communication between players.
DirectInput updated
DirectInput introduces one major new feature: action mapping. Action mapping enables you to establish a connection between input actions and input devices, which does not depend on the existence of particular device objects. It simplifies the input loop and reduces the need for custom game drivers, custom device profilers, and custom configuration of user interfaces in games.
Debug build available
You can use the DirectX Control Panel Application to switch between the debug and retail builds of DirectInput, Direct3D, and DirectMusic. To enable this feature, select Debug when you install the software development kit (SDK). This option installs both debug and retail dynamic-link libraries (DLLs) on your system. The Retail option installs only the retail DLLs.


DirectX 8.1 Components

Microsoft® DirectX® 8.1 is made up of the following components.

  • DirectX Graphics combines the Microsoft DirectDraw® and Microsoft Direct3D® components of previous DirectX versions into a single application programming interface (API) that you can use for all graphics programming. The component includes the Direct3DX utility library that simplifies many graphics programming tasks.
  • DirectX Audio combines the Microsoft DirectSound® and Microsoft DirectMusic® components of previous DirectX versions into a single API that you can use for all audio programming.
  • Microsoft DirectInput® provides support for a variety of input devices, including full support for force-feedback technology.
  • Microsoft DirectPlay® provides support for multiplayer networked games.
  • Microsoft DirectSetup is a simple API that provides one-call installation of the DirectX components.


Using the DirectX 8.1 Documentation

The following conventions are used in the syntax of methods, functions, and other API elements, as well as in explanatory material and sample code.

Convention | Meaning
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.
Bold text | Denotes a function, procedure, structure, macro, interface, method, data type, or other keyword in the programming interface or language.
[] | Encloses optional parameters.
... | Specifies that the preceding item may be repeated.
FULL BOLD CAPITALS | Used for most type and structure names.
FULL CAPITALS | Used for enumeration values, flags, and constants.
monospace | Used for code examples and syntax spacing.
. . . | Represents an omitted portion of a sample application.


DirectX Tools

The following tools can be useful in developing and troubleshooting Microsoft® DirectX® applications.

  • DirectX Caps Viewer
  • DirectX Control Panel Application
  • DirectX Diagnostic Tool
  • Kill Help Utility
  • Testing Network Performance with DP8Sim
  • Monitoring DirectPlay Network Traffic with Netmon


DirectX Caps Viewer

Description

The Microsoft® DirectX® Caps Viewer tool shows information for the following components of DirectX.

  • Microsoft® DirectMusic® capabilities (for DirectMusic ports).
  • Microsoft® DirectInput® devices and their capabilities.
  • Microsoft® DirectPlay® connections (server provider information).
  • Microsoft® DirectSound® capture devices and capabilities.
  • Microsoft® Direct3D® devices and capabilities.

The DirectX Caps Viewer screen shot below shows the general Microsoft® DirectDraw® capabilites of the primary display adapter.

Screen shot of DirectX Caps Viewer

Devlopers should use this tool to verify the capabilites of their development and test machines to make sure that DirectX applications correctly test for current machine capabilities and react accordingly. It is suggested that applications be designed with fallback strategies if the required features are not available.

Path

Executable: (SDK root)\Bin\DXUtils\DXCapsViewer.exe

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 Application

You can use the Microsoft® DirectX® Control Panel utility, which is installed with the software development kit (SDK), to examine and modify the properties of DirectX components. This utility contains tabs for each DirectX component.

Using this utility you can:

  • Obtain version information for DirectX 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 DirectX components.
  • Toggle between debug and retail versions of the run times for Microsoft® Direct3D®, Microsoft® DirectMusic®, and Microsoft® DirectInput®.


DirectX Diagnostic Tool

Description

Microsoft® DirectX® Diagnostic Tool gathers information on the system and the DirectX components installed on it, as well as providing a number of tests to ensure that components are working properly. A special version of this tool installed with the DirectX SDK enables developers to report problems directly to the DirectX development team.

Path

Executable: (SDK root)\Bin\DXUtils\Dxdiag.exe

User's Guide

To display the DirectX Diagnostic Tool Help file, click the Help button.


Kill Help Utility

Description

Kill Help is a utility for developers who are working on Microsoft® Windows® 9x. Sometimes when a Microsoft® DirectX® application crashes, the ddhelp process remains active. When this happens, it prevents other Microsoft® DirectDraw® or Microsoft® Direct3D® applications from working until it is terminated or the machine is rebooted. This utility will terminate the ddhelp process and spare developers from having to reboot their machine.

Path

Executable: (SDK root)\Bin\DXUtils\KillHelp.exe

User's Guide

Run this application to terminate the ddhelp process. If the ddhelp process is not active, then nothing happens.


Testing Network Performance with the DP8Sim

Microsoft DirectX 8.1 (Visual Basic)

Testing Network Performance with DP8Sim

The DP8Sim tool is a simulated Microsoft® DirectPlay® 8.1 service provider that allows you to test your DirectPlay application in a variety of network conditions, such as high latency and packet loss. DP8Sim is not a replacement for testing in the real deployment environment, but it can help you predict how your application will perform.

Note DP8Sim is implemented on top of the existing DirectPlay8 TCP/IP Service Provider. The settings are also applied on top of the existing network characteristics. Therefore, it is intended to be used on a high-speed local area network (LAN) where normal latency and packet loss are negligible.

Path

Executable: (SDK Root)\bin\dp8simui.exe

DLL: (SDK Root)\bin\dp8sim.dll

User's Guide

The configuration utility, dp8simui.exe, is the user interface for controlling dp8sim.dll. Both files must reside in the same directory. When you start the configuration utility, it will automatically register the dp8sim.dll component object model (COM) objects. You can also manually register the dynamic link library (DLL) by typing the following command at your Microsoft MS-DOS® prompt.

regsvr32.exe dp8sim.dll

When you run the configuration utility, it will prompt you to enable the network simulator for the DirectPlay TCP/IP service provider. Any existing DirectPlay sessions will not use the network simulator if the DirectPlay interface was created prior to enabling the simulator.

Once the simulator is enabled, you can control various network options. There are also predefined network settings that may be useful.

The options for sending (receiving) are:

  • Bandwidth (bytes/second). The total available outbound (inbound) bandwidth for all players in bytes per second. All packets have their latency increased in proportion to their size according to this value. If the application sends (receives) more than this amount, later packets are queued behind earlier ones. Use 0 (zero) for unlimited bandwidth, up to the real underlying network bandwidth.
  • Drop percentage (0 to 100 percent). The random frequency as a percentage for an individual outbound (inbound) packet to be dropped. Each packet stands the same chance of being dropped, regardless of other packets. Note that this does not necessarily model the behavior of all networks. Packet loss on the Internet, for example, tends to be erratic, with packet loss high at some times and low at others. A value of 1 means that an average of 1 out of every 100 packets is dropped. A value of 100 means every packet is dropped. Use 0 if you do not want to drop any packets other than loss due to the real underlying network.
  • Minimum latency (milliseconds). The minimum delay in milliseconds for outbound (inbound) packets. The actual delay for an individual packet is chosen randomly between this minimum value and the maximum latency value. Note that the delay is applied on top of any delay imposed by bandwidth limitations. Use 0 if you do not want to have a lower bound for artificial latency beyond the real underlying network.
  • Maximum latency (milliseconds). The maximum delay in milliseconds for outbound (inbound) packets. The actual delay for an individual packet is chosen randomly between the minimum latency value and this maximum value. If this value is lower than the minimum latency value, it is automatically set to equal the minimum value. Note that the delay is applied on top of any delay imposed by bandwidth limitations. Use 0 if you do not want to have an upper bound for artificial latency beyond the real underlying network.

Note These options apply for in-game data only. Host enumerations and responses are not subject to the simulation.

To make modifications, use the Apply and Revert buttons. Click Apply to change the settings and Revert to restore the previous settings.

At the bottom of the configuration utility window, the send and receive statistics for all affected DirectPlay interfaces are displayed. The Refresh button updates the statistics and Clear resets the statistics to 0.

When you close the configuration utility, you will be asked if you want to disable the network simulator. Disabling the simulator prevents subsequent DirectPlay sessions from being affected by DP8Sim, but existing sessions will continue to use the existing network settings. If you leave DP8Sim enabled, subsequent DirectPlay sessions will continue to use the existing network settings even when the configuration utility is not running.

To unregister dp8sim.dll, type the following at the MS-DOS command prompt.

regsvr32.exe /u dp8sim.dll

For more information about network performance, see Optimizing Network Usage.


Monitoring DirectPlay Network Traffic with Netmon

During game development, you might find it useful to monitor Microsoft® DirectPlay® network traffic, especially when trying to understand bugs. The network monitor (Netmon) is a standard utility for analyzing network traffic. DirectPlay includes a set of parsers, that allow you to use Netmon to analyze four components of DirectPlay messaging: the service provider layer, the transport layer, the session layer, and the voice layer.

How Netmon Works With DirectPlay

The DirectPlay protocol stack has three basic layers.

  • The voice and session layers share the top level of the stack. Normal messaging passes through the session layer, and voice-related messaging passes through the voice layer.
  • The transport layer is the middle of the stack. Both voice and session traffic passes through this layer, which is responsible for such tasks as fragmentation and reassembly of messages and retransmission of lost packets.
  • The service provider layer is at the bottom of the stack. All messaging is handled by this layer, which is responsible for communicating with the network. For example, for TCP/IP networking, the service provider uses the Winsock API to communicate with the network stack. Netmon can only parse network traffic that is carried on an IP or IPX service provider.

By installing the DirectPlay parsers, you can use Netmon to analyze the network traffic as it passes through any of these four layers. You can see all DirectPlay traffic by selecting the service provider parser. However, by selecting one of the higher level parsers, you can filter out traffic that might not be of interest.

With the transport layer parser, you see all voice and session traffic, but not low-level traffic such as connection handshaking. Be aware that the transport layer breaks messages that are longer than the network's Maximum Transfer Unit (MTU) into one or more fragments.

The session and voice layer parsers allow you to analyze session and voice-related traffic separately. Both of these parsers are aware of fragmentation, and notify the user, but cannot parse fragmented packets.

Configuring Netmon for DirectPlay

If you have a Windows 2000 Server system, Netmon is already installed. For Windows 2000 Professional, you must purchase a copy of Systems Management Server (SMS). See the Netmon documentation for a general discussion of how to use Netmon. To configure Netmon to handle DirectPlay traffic:

  1. Copy Dp8parse.dll from (SDK root)\bin\DXUtils to the appropriate folder. The Netmon root folder is normally installed in the \Winnt\System32 folder. If you have installed SMS, the root folder will be called NetMonFull. For Windows 2000 Server, the root folder will be called NetMon. Depending on which version of Netmon you are using, copy the parser DLL to either the ...\NetMonFull\Parsers, or ...\NetMon\parsers folder.
  2. Start Netmon
  3. Set the adapter to capture from (Capture|Networks...|Local Computer). Be sure to choose the adapter with the "Dial-up Connection" property set to FALSE.

You are now ready to start capturing traffic.

Capturing DirectPlay Network Traffic

To start the capture process, click the Start Capture button on the Netmon toolbar to open the capture view. Initially, you will see all the traffic that is passing through your adapter. You can filter that raw traffic stream to focus on only those packets that are of interest. By installing the DirectPlay parsers, you essentially add four filters to Netmon oriented to DirectPlay, which allow you to filter everything but DirectPlay traffic from your capture view.

To select a filter:

  1. Click the Edit Display Filter button on the Netmon toolbar.
  2. Double-click "Protocol == Any".
  3. Click "Disable All".
  4. Under "Disabled Protocols", double-click DPLAYSESSION, DPLAYSP, DPLAYTRANSPORT, and DPLAYVOICE.

Click OK twice to return to the capture view, and you are ready to start viewing DirectPlay traffic.

You can also apply a filter to the capture process itself, rather than to the capture view. This allows you, for instance, to capture only IP packets with specified source and destination ports. See the Netmon documentation for details.

Tips for Using Netmon with DirectPlay

Here are a few tips to using Netmon with DirectPlay :

  • By default, Netmon only captures 1MB of the most recent traffic. You will probably want to increase this value to at least 10-20 MB.
  • Netmon doesn't stream to the hard drive, so all you can see is what is in the capture buffer. To stream captured traffic to a hard drive, you will need to implement your own capturer. See MSDN for details.
  • By default, DirectPlay parsing uses the [2302,2400]U{6073} port/socket range to filter IP and IPX packets. To parse ports other than the default DirectPlay ports, create two new DWORD values under the HKEY_CURRENT_USER\Microsoft\DirectPlay\Parsers key, as shown in the following example.
    MinUserPort = x
MaxUserPort = y

    The x and y data values define the range to parse in addition to the default DirectPlay ports. They can be the same value if you only need one custom port.

  • Because the DirectPlay and RTP protocols are both layered on top of the UDP protocol, their parsers might conflict. You should disable the RTP parser when analyzing DirectPlay traffic, and vice versa.


Programming DirectX with Visual Basic

This section is an introduction to developing applications with Microsoft® DirectX® for Microsoft Visual Basic®.

The following topics are covered:

  • Creating DirectX Objects
  • Using GUIDs
  • Passing Arrays to Methods
  • Using Flags
  • Using Bitmasks
  • DirectX Enumerations
  • The IUnknown Data Type
  • Error Handling
  • DirectX Class Reference

Referencing the Type Library

To use Microsoft® DirectX® for Microsoft Visual Basic® in a project, you must first ensure that the project has access to the type library.

To make sure that the project has access to the type library

  1. In Microsoft Visual Studio®, on the Project menu, click References.
  2. Select DirectX 8 for Visual Basic Type Library, and then click OK.


Creating DirectX Objects

Every Microsoft® DirectX® for Microsoft Visual Basic® application must have a DirectX8 object. This is the parent object whose methods are used to create the principal objects for each DirectX component. The DirectX8 object has many other methods, such as methods to perform calculations for Microsoft Direct3D®.

To create a DirectX8 object, declare it as a new object. For example:

Public gObjDX As New DirectX8

Many of the primary DirectX component objects, such as DirectSound8 are not created directly. Instead, you must create those objects by calling the appropriate DirectX8 method. For example, to create a DirectSound8 object, create a variable and assign it the return value of DirectX8.DirectSoundCreate.

Public gObjDSound As DirectSound8
Set gObjDSound = DirectX8.DirectSoundCreate(vbNullString)

The following objects must be created by calling the appropriate DirectX8 method. See the DirectX Class Reference for details.

  • Direct3D8
  • DirectInput8
  • DirectMusicComposer8
  • DirectMusicLoader8
  • DirectMusicPerformance8
  • DirectPlay8Address
  • DirectPlay8Client
  • DirectPlay8LobbiedApplication
  • DirectPlay8LobbyClient
  • DirectPlay8Peer
  • DirectPlay8Server
  • DirectPlayVoiceClient8
  • DirectPlayVoiceServer8
  • DirectPlayVoiceTest8
  • DirectSoundCapture8
  • DirectSound8
  • DirectSoundEnum8
  • DirectXFile


Using GUIDs

Microsoft® DirectX® uses globally unique identifiers (GUIDs) extensively for purposes such as identifying objects. GUIDs are actually 128-bit structures, but they are commonly represented by their equivalent string, such as {AC330441-9B71-11D2-9AAB-0020781461AC}.

DirectX8 has a number of predefined GUIDs that are used to identify entities such as particular properties. If a method requires you to pass in a predefined GUID, it is handled as a String data type, and the string form of the GUID is expected. The most convenient approach is to use a string alias, if one exists. For example, the DirectInput8.CreateDevice method enables you to create a device for the standard keyboard by passing in GUID_SysKeyboard rather than the actual GUID string. You can also use the actual string, for example by copying and pasting it from a C++ header file.

To create a GUID

  1. In the \Samples\Multimedia\VBSamples\DXMisc\Bin folder of the DirectX SDK, run Vbguidgen.exe.
  2. Paste the GUID into your Microsoft Visual Basic® application, and place quotation marks around it.

You can also generate GUIDs at run time by calling the DirectX8.CreateNewGuid method.


Passing Arrays to Methods

Some methods, such as DirectInputDevice8.SendDeviceData, take a typed array as a parameter. For example, in the following code fragment, formatArray is an array of DIDEVICEOBJECTDATA types, lCount contains the number of elements in the array, and lFlags is a flag parameter that controls how the data is sent.

MyDevice.SendDeviceData(lCount, formatArray(), lFlags)

A few DirectX8 methods use parameters with an Any type to return data. An example is the DirectSoundCaptureBuffer8.ReadBuffer method's buffer parameter. Typically you will want such methods to return their data as an array of bytes. However, you cannot simply pass the name of the array to the method because Microsoft® Visual Basic® arrays contain extra information ahead of the actual data. Instead, you must pass the first element of the array. For example, in the following code fragment, dsCaptureBuffer is a DirectSoundCaptureBuffer8 object, nBytes is a Long value containing the number of bytes to be read, and buffer is a zero-based array of bytes:

ReDim buffer(nBytes)
Call dsCaptureBuffer.ReadBuffer(0, nBytes, buffer(0), 0)


Using Flags

Many object methods in Microsoft® DirectX® for Microsoft Visual Basic® have a parameter with the Long data type named flags or something similar. Types may also have one or more flag members. These flag fields are a compact way to select from a variety of options and are often used to specify the exact behavior of a method. For example, the flags parameter of DirectInput8.GetDevicesBySemantics enables you to define the scope of the enumeration by selecting from one of several options.

A flag is a single yes-no bit of information. In a flag field, each bit of the integer corresponds to a separate flag that represents an independent piece of information. If the bit is set, the flag is enabled. If the bit is zero, the flag is disabled. Flag fields typically contain a set of related flags that are represented by an enumeration. Normally, the numerical value of each member of the enumeration represents a different bit in the flag field. However, some members may represent combinations of two or more flags.

A common use of flag fields is to enable you to select one option from a variety of options. You normally do so by assigning the appropriate enumerated value to the flag parameter. However, because each flag corresponds to a different bit, flag fields can also be used to select two or more options from a list. To do so, set all the relevant bits by combining the enumerated values of the selected flags with the Or operator. For example, the DirectInputDevice8.SetCooperativeLevel method has a flag field that is used to specify the device's cooperative level. The following code fragment selects a combination of foreground and exclusive cooperative levels by combining the DISCL_FOREGROUND and DISCL_EXCLUSIVE flags.

' diDevice is a DirectInputDevice8 object, and hwnd is a window handle
diDevice.SetCooperativeLevel(hwnd, _
    DISCL_FOREGROUND Or DISCL_EXCLUSIVE)

Note Examine the reference page carefully to determine how the flag field is to be used. Setting multiple flags in a flag field that is designed to have only one flag set may have unpredictable results.

You should not use the addition operator instead of the Or operator to combine flags. While the two operations are often equivalent, using the addition operator will sometimes lead to incorrect results. In particular, the two operators are usually not equivalent if one of the flags represents a combination of two or more flags. The following example illustrates this case. The CF_PURPLE flag represents a combination of CF_RED and CF_BLUE.

Enum COLORFLAGS
    CF_RED    = 1
    CF_BLUE   = 2
    CF_PURPLE = 3
    CF_GREEN  = 4
End Enum

Dim Color As Integer
Color = CF_RED Or CF_PURPLE

The value of Color is now 3. Setting CF_RED has no effect, as that bit was already set by CF_PURPLE.

The following operation, on the other hand, sets an incorrect value:

' This is wrong!
Color = CF_RED + CF_PURPLE

Adding the two flag values sets Color to 4, which is equivalent to CF_GREEN.

When you retrieve a value for flags, you can determine whether an individual flag is set by combining the flag value with the flag field using the And operator. If the bit in the flag field represented by a flag constant is set, an And operation will return a nonzero value indicating that the flag is "on". If the And operation returns zero, the flag is "off". For example the caps parameter of DirectInputDevice8.GetCapabilities method is used to return a DIDEVCAPS type that contains the device capabilities. The lFlags member of this type is a flag field that may have one or more of the flags specified by the CONST_DIDEVCAPSFLAGS enumeration set. If the DIDC_ATTACHED flag is set, the device is physically attached to the system. The following code fragment illustrates how to check whether the device is attached by examining the value of an And operation that combines the lFlags member with DIDC_ATTACHED.

Dim IsAttached As Boolean
IsAttached = diDevCaps.lFlags And DIDC_ATTACHED

Note that you should not simply test whether lFlags is equal to DIDC_ATTACHED. This flag field may have more than one flag set. If multiple flags are set, the following test will fail, even if DIDC_ATTACHED is set.

' This is wrong!
IsAttached = (diDevCaps.lFlags = DIDC_ATTACHED)


Using Bitmasks

Some Microsoft® DirectX® types, such as D3DCAPS8 have Long members that serve as bitmasks. Bitmasks are similar to flag fields, but they are normally used to mask off certain bits in a field. It is customary to use hexadecimal format to assign values to these bitmasks because it is easier to determine which bits will be affected. However, doing so may cause an error because Microsoft Visual Basic® normally attempts to convert hexadecimal constants to the shortest type. For example, &HFF would be converted to an Integer with a value of -1. If this value is then passed back to DirectX for Visual Basic, where a Long is expected, it is converted to &HFFFFFFFF.

To ensure that a hexadecimal bitmask is properly converted, place a second ampersand after the expression. For example:

DDSD.ddpfPixelFormat.lRBitMask = &HFF&


DirectX Enumerations

Most Microsoft® DirectX® applications must enumerate available resources, usually during initialization. For example, an application that uses DirectX Graphics might need to find out what display modes are available, or an application using Microsoft DirectInput® might need to enumerate the available buttons and axes on a joystick.

In DirectX for Microsoft Visual Basic®, applications handle enumeration by obtaining the appropriate enumeration object. When an enumeration object is created, it builds a collection that exists as long as the object exists. Your application can then access that collection by using enumeration object's methods.

DirectX supports many enumeration objects, each tailored to a specific task. You normally obtain an enumeration object by calling a method. For example, the DirectX8 class contains two such methods. One of them, DirectX8.GetDSEnum returns a DirectSoundEnum8 enumeration object. This object enables you to enumerate Microsoft DirectSound® devices to obtain a GUID for a suitable device. You can then use this GUID to create a DirectSound8 object.

Other enumeration objects are obtained through various DirectX component objects. For example, you can call the DirectInput8.GetDIDevices method to obtain an enumeration object for input devices.

The following sample code illustrates how to enumerate all input devices attached to the system. The di variable is a DirectInput8 object. The first step is to obtain a DirectInputEnumDevices8 enumeration object.

Dim diEnum As DirectInputEnumDevices8
Set diEnum = di.GetDIDevices(0, DIEDFL_ATTACHEDONLY)

Next, use the DirectInputEnumDevices8 methods to iterate through the attached devices. Examine each device to determine if it has the particular capabilities you need. In the following example, the names of the devices are put in a list box:

Dim diDevice As DirectInputDeviceInstance
Dim X As Integer

For X = 1 To diEnum.GetCount
    Set diDevice = diEnum.GetItem(X)
    Call List1.AddItem(diDevice.ProductName)
    'Examine device capabilities
    '...
Next X

Note All collections created by DirectX enumerations are 1-based.


The IUnknown Data Type

The IUnknown interface is exposed by all COM objects. The interface is used by C++ developers to gain access to an object's functionality and to manage the object's lifetime. Microsoft® Visual Basic® developers rarely have to make use of IUnknown. However, an object's IUnknown interface is represented in Visual Basic by the IUnknown data type.

A handful of Microsoft DirectX® 8.1 Visual Basic methods have return values or parameters that are declared as Unknown. The type of these values is undefined, and will be either an IUnknown type, or another object type. DirectX 8.1 uses Unknown declarations for two cases.

  • When an object is not represented by a class. Such objects expose no methods or properties to your application. However, a reference may be passed to your application by one method so that you can then pass that reference to another method. For example, the return value of the DirectMusicSegment8.GetAudioPathConfig is declared as Unknown. The method returns an IUnknown value that is a reference to a configuration object that is not represented by a class. Your application then passes the object reference to another method as a parameter.
  • When a parameter needs to accept more than one object type. Declaring a parameter as Unknown allows it to accept any object type. For example, the first parameter of DirectMusicBand8.Unload is declared as Unknown. The parameter can accept either a DirectMusicAudioPath8 or a DirectMusicPerformance8 object reference.

    Note An Unknown declaration is similar to an Any declaration. When a parameter or return value is declared as Any, you can pass or set any data type. Similarly, when a parameter or return value is declared as Unknown, you can pass or set any object type. You must be careful to use the correct object type, however, or the results will be unpredictable.

An IUnknown variable does not provide direct access to an object's methods or to the QueryInterface, Addref, and Release methods that are used in C++. When you have an object reference in an IUnknown variable, you must set that variable to an appropriately declared class variable in order to use the object's methods.

The following code fragment illustrates how to use the IUnknown data type.

'dmSeg is a DirectMusicSegment8 object
'dmPerf is a DirectMusicPerformance8 object

Dim config as IUnknown
Dim audioPath As DirectMusicAudioPath

Set config = dmSeg.GetAudioPathConfig
Set audioPath = dmPerf.CreateAudioPath(config)

The value that is returned by DirectMusicSegment8.GetAudioPathConfig is a reference to a configuration object that is not represented by a class. All you need to do with this object reference is pass it to another method, in this case, DirectMusicPerformance8.CreateAudioPath.

The following use of the IUnknown data type is incorrect.

'objDiDev is a DirectInputDevice8 object

Dim unk As IUnknown
Set unk = objDiDev
NumItems = unk.GetDeviceData(diDeviceData,0) 'Incorrect!

The attempt to call the DirectInputDevice8.GetDeviceData method will raise a "method not found" error.


Error Handling

In Microsoft® Visual Basic® a method call either succeeds or it fails. If the call fails, an error is raised, and an error number is set in the global Visual Basic Err object. Your application must then branch to an error handler that examines the Err object and deals with the error, or execution terminates. However, underlying every Microsoft DirectX® Visual Basic method is a C++ method that handles errors somewhat differently. In some cases, you will need to know something about C++ return values to interpret Visual Basic errors.

In C and C++, every method call returns an HRESULT value. This value is an integer with a specific format that indicates the outcome of the operation. In some cases, the HRESULT that a method returns simply indicates whether the operation succeeded or failed. However, methods may sometimes use many HRESULT values to indicate a variety of success or failure modes. There may, in fact, be more than one return value that indicates success. Many of HRESULT values are system standards, and are defined in the Winerror.h header file. System standard values typically use an S_ prefix for success codes and an E_ prefix for failure. For example, S_OK and E_FAIL are commonly used codes for success and failure, respectively. When the C++ code that typically underlies a Visual Basic method returns a standard HRESULT value, the Visual Basic run time traps that value, and sets a standard Visual Basic error code.

Many DirectX methods also support one or more non-standard HRESULT values. These values are normally defined in an enumeration, and the meaning of each value is given in the method reference. Because they are not standard values, there is no corresponding Visual Basic error code. Instead, the Visual Basic run time sets Err.Number to the HRESULT value. Refer to the method reference for the meaning of the value. For more information on HRESULT values, see the COM documentation in the Microsoft Platform Software Development Kit (SDK).


DirectX Class Reference

This section contains references for the following classes that are common to all components of Microsoft® DirectX®.

  • DirectX8
  • DirectXEvent8


DirectX8

The DirectX8 class serves as a starting point for the Microsoft® DirectX® component technologies. It contains methods that create the primary objects for the various DirectX components as well as some methods that are used by multiple components. This class is usually the first object created in your DirectX application.

The methods of the DirectX8 class can be organized into the following groups:

Object Creation | Direct3DCreate
 | DirectInputCreate
 | DirectMusicComposerCreate
 | DirectMusicLoaderCreate
 | DirectMusicPerformanceCreate
 | DirectPlayAddressCreate
 | DirectPlayClientCreate
 | DirectPlayLobbiedApplicationCreate
 | DirectPlayLobbyClientCreate
 | DirectPlayPeerCreate
 | DirectPlayServerCreate
 | DirectPlayVoiceClientCreate
 | DirectPlayVoiceServerCreate
 | DirectPlayVoiceSetupCreate
 | DirectSoundCaptureCreate
 | DirectSoundCreate
 | DirectXFileCreate
Enumeration | GetDSCaptureEnum
 | GetDSEnum
Event Handling | CreateEvent
 | DestroyEvent
 | SetEvent
GUID Creation | CreateNewGuid


DirectX8.CreateEvent

Creates a handle for the form's event object.

object.CreateEvent( _
    event As DirectXEvent8 _
) As Long

Parts

object
Object expression that resolves to a DirectX8 object.
event
The form's DirectXEvent8 object.

Return Values

Returns a Long value set to the form's event handle.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

A DirectXEvent object must be implemented by a form in order to receive notifications from Microsoft® DirectX®. This method creates an event handle for this object that is used by the notification methods of Microsoft DirectSound®, DirectMusic®, DirectPlay®, and DirectInput®.

DirectX automatically sets the event object to be signaled when an appropriate event occurs. You can also set the event manually by calling the DirectX8.SetEvent method. This procedure is normally used to test the event-handling code.

Applications must explicitly destroy all the events they create by calling the DirectX8.DestroyEvent method. Failure to do so will cause unpredictable results.


DirectX8.CreateNewGuid

Generates a new globally unique identifier (GUID).

object.CreateNewGuid() As String

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a String value containing the new GUID.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DestroyEvent

Deletes an event handle created by the DirectX8.CreateEvent method.

object.DestroyEvent( _
    eventid As Long)

Parts

object
Object expression that resolves to a DirectX8 object.
eventid
Long value set to the event handle to be destroyed. This handle must have been created by calling DirectX8.CreateEvent.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.Direct3DCreate

Creates a Direct3D8 object.

object.Direct3DCreate() As Direct3D8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a Direct3D8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

This function succeeds in all cases except out-of-memory conditions. It creates a Direct3D8 object that supports enumeration and enables the creation of Direct3DDevice8 objects.

Note that calling this method samples the current set of active display adapters. If the user dynamically adds adapters, either by adding devices to the desktop or by hot-docking a laptop, then those devices will not be enumerated for the lifetime of this Direct3D8 object. Creating a new Direct3D8 object will expose the new devices.


DirectX8.DirectInputCreate

Creates a DirectInput8 object.

object.DirectInputCreate() As DirectInput8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectInput8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following Microsoft® DirectInput® Error Codes:

  • DIERR_BETADIRECTINPUTVERSION
  • DIERR_INVALIDPARAM
  • DIERR_OLDDIRECTINPUTVERSION
  • DIERR_OUTOFMEMORY


DirectX8.DirectMusicComposerCreate

Creates a DirectMusicComposer8 object.

object.DirectMusicComposerCreate() As DirectMusicComposer8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectMusicComposer8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectMusicLoaderCreate

Creates a DirectMusicLoader8 object.

object.DirectMusicLoaderCreate() As DirectMusicLoader8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectMusicLoader8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectMusicPerformanceCreate

Creates a DirectMusicPerformance8 object.

object.DirectMusicPerformanceCreate() _
    As DirectMusicPerformance8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectMusicPerformance8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectPlayAddressCreate

Creates a DirectPlay8Address object.

object.DirectPlayAddressCreate() As DirectPlay8Address

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectPlay8Address object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectPlayClientCreate

Creates a DirectPlay8Client object.

object.DirectPlayClientCreate() As DirectPlay8Client

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectPlay8Client object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectPlayLobbiedApplicationCreate

Creates a DirectPlay8LobbiedApplication object.

object.DirectPlayLobbiedApplicationCreate() _
    As DirectPlay8LobbiedApplication

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectPlay8LobbiedApplication object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectPlayLobbyClientCreate

Creates a DirectPlay8LobbyClient object.

object.DirectPlayLobbyClientCreate() _
    As DirectPlay8LobbyClient

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectPlay8LobbyClient object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectPlayPeerCreate

Creates a DirectPlay8Peer object.

object.DirectPlayPeerCreate() As DirectPlay8Peer

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectPlay8Peer object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectPlayServerCreate

Creates a DirectPlay8Server object.

object.DirectPlayServerCreate() As DirectPlay8Server

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectPlay8Server object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectPlayVoiceClientCreate

Creates a DirectPlayVoiceClient8 object.

object.DirectPlayVoiceClientCreate() _
    As DirectPlayVoiceClient8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectPlayVoiceClient8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectPlayVoiceServerCreate

Creates a DirectPlayVoiceServer8 object.

object.DirectPlayVoiceServerCreate() _
    As DirectPlayVoiceServer8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectPlayVoiceServer8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectPlayVoiceSetupCreate

Creates a DirectPlayVoiceTest8 object.

object.DirectPlayVoiceSetupCreate() As DirectPlayVoiceSetup8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectPlayVoiceSetup8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.DirectSoundCaptureCreate

Creates a DirectSoundCapture8 object.

object.DirectSoundCaptureCreate( _
    guid As String _
) As DirectSoundCapture8

Parts

object
Object expression that resolves to a DirectX8 object.
guid
A GUID string that identifies the sound capture device. The value of this parameter must be one of the GUIDs returned by DirectX8.getDSCaptureEnum, vbNullString for the default device, or one of the following values:
DSDEVID_DEFAULTCAPTURE
System-wide default audio capture device.
DSDEVID_DEFAULTVOICECAPTURE
Default voice capture device.

Return Values

Returns a DirectSoundCapture8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following Microsoft® DirectSound® error codes:

  • DSERR_INVALIDPARAM
  • DSERR_NOAGGREGATION
  • DSERR_OUTOFMEMORY

Remarks

This method could fail on some sound cards that do not support full duplex. Calling DirectX8.DirectSoundCreate may set the capture device to an unsupported capture frequency, which will cause DirectX8.DirectSoundCaptureCreate to fail.


DirectX8.DirectSoundCreate

Creates a DirectSound8 object.

object.DirectSoundCreate( _
    guid As String _
) As DirectSound8

Parts

object
Object expression that resolves to a DirectX8 object.
guid
A GUID string that identifies the sound capture device. The value of this parameter must be one of the GUIDs returned by DirectSoundEnum8.GetGuid, vbNullString for the default device, or one of the following values:
DSDEVID_DEFAULTPLAYBACK
System-wide default audio playback device.
DSDEVID_DEFAULTVOICEPLAYBACK
Default voice playback device.

Return Values

Returns a DirectSound8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following Microsoft® DirectSound® error codes:

  • DSERR_ALLOCATED
  • DSERR_INVALIDPARAM
  • DSERR_NOAGGREGATION
  • DSERR_NODRIVER
  • DSERR_OUTOFMEMORY


DirectX8.DirectXFileCreate

Creates a DirectXFile object.

object.DirectXFileCreate() As DirectXFile

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectXFile object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX8.GetDSCaptureEnum

Creates a DirectSoundEnum8 object.

object.GetDSCaptureEnum() As DirectSoundEnum8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectSoundEnum8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_OUTOFMEMORY.

Remarks

The DirectSoundEnum8 object returned by this method is used to enumerate the DirectSoundCapture8 objects installed on the system.

See Also

DirectX8.GetDSEnum


DirectX8.GetDSEnum

Creates a DirectSoundEnum8 object.

object.GetDSEnum() As DirectSoundEnum8

Parts

object
Object expression that resolves to a DirectX8 object.

Return Values

Returns a DirectSoundEnum8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_OUTOFMEMORY.

Remarks

The DirectSoundEnum8 object returned by this method is used to enumerate the Microsoft® DirectSound® drivers installed on the system.

See Also

DirectX8.GetDSCaptureEnum


DirectX8.SetEvent

Sets the state of an event object to signaled.

object.SetEvent( _
    eventid As Long)

Parts

object
Object expression that resolves to a DirectX8 object.
eventid
Long value containing the event handle. This handle must have been created by DirectX8.CreateEvent.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

This method is used primarily for testing purposes. Microsoft® DirectX® automatically sets all created event objects to be signaled when an appropriate event occurs.


DirectXEvent8

The DirectXEvent8 class creates event objects used in Microsoft® DirectSound®, DirectMusic®, DirectPlay, and DirectInput®. The purpose of this class is to provide a callback method for handling notification events. DirectXEvent8 objects are created by implementing the class in a form.

The DirectXEvent8 class has one method, DirectXEvent8.DXCallback.


DirectXEvent8.DXCallback

A callback routine for event handles.

object.DXCallback( _
    eventid As Long)

Parts

object
Object expression that resolves to a DirectXEvent8 object.
eventid
Long value containing the event handle. This handle must have been created by DirectX8.CreateEvent.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

When you implement DirectXEvent8 in a form, you must also supply an implementation of the DirectXEvent.DXCallback method. The declaration and end of the method are automatically placed in the Code window when you select DirectXEvent8 in the Object box and DXCallback in the Procedures/Events box. The method takes the following form:

Private Sub DirectXEvent8_DXCallBack(ByVal eventid as Long)
  ' Add your own event-handling code
  .
  .
  .
End Sub

The event handle passed to the method must have been created by DirectX8.CreateEvent.

See Also

DirectX8.SetEvent


Further Information

You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft® DirectX® documentation, as well as information on Microsoft® Windows® programming in general, in the following sources:

  • Bargen, Bradley and Peter Donnelly, Inside DirectX, Microsoft® Press®, 1998.
  • Begault, Durand R., 3-D Sound for Virtual Reality and Multimedia, Academic Press, 1994.
  • Blinn, James, Jim Blinn's Corner: A Trip Down the Graphics Pipeline, Morgan Kaufmann, 1996.
  • Dodge, Charles and Thomas A. Jerse, Computer Music: Synthesis, Composition, and Performance, Schirmer Books, 1997 (2nd edition).
  • Foley, James D., Computer Graphics: Principles and Practice, Addison-Wesley, 1991 (2nd edition).
  • Hearn, Donald and M. Pauline Baker, Computer Graphics, Prentice-Hall, 1986.
  • Kientzle, Tim, A Programmer's Guide to Sound, Addison-Wesley Developers Press, 1998.
  • Kovach, Peter J., Inside Direct3D, Microsoft Press, 2000.
  • Petzold, Charles, Programming Windows 98, Microsoft Press, 1998 (5th edition).
  • Thompson, Nigel, 3D Graphics Programming for Windows, Microsoft Press, 1996.
  • Watt, Alan H., and Mark Watt, Advanced Animation and Rendering Techniques, Addison-Wesley, 1992.

Additional sources for the concepts and terms associated with COM can be found in the following sources:

  • Brockschmidt, Kraig, Inside OLE 2, Microsoft Press, 1995 (2nd edition).
  • Rogerson, Dale E., Inside COM, Microsoft Press, 1997.


DirectX Graphics

This section provides information about using the Microsoft® DirectX® Graphics application programming interfaces (APIs).

As with other components of DirectX, DirectX Graphics can be used with C, C++, and Microsoft® Visual Basic®.

Roadmap

Discover the features of Microsoft® DirectX 8.1® in three ways.

  • What's New in DirectX Graphics

    This section highlights new features and functionality of this component in DirectX 8.1. If you have used Microsoft® Direct3D® or Microsoft® DirectDraw® before, read this section first because much has changed since DirectX 7.0.

  • Programmers Guide

    This section contains architecture descriptions, functional block diagrams, descriptions of the building blocks in the pipeline, code snippets, and sample applications.

  • Reference

    This section contains the reference pages for the Direct3D application programming interface (API). This includes the syntax for the API methods, functions, instructions, and data structures. It includes an explanation of how the API method works, and often includes code snippets.


What's New in DirectX Graphics

This section describes Microsoft® DirectX® graphics features that are new in DirectX 8.x.

To see what's new in all of DirectX, see What's new in DirectX 8.1.

New Features in DirectX 8.1

Pixel Shaders

  • Added pixel shader versions 1.2, 1.3, and 1.4. These new versions expand existing functionality through a more powerful set of instructions, registers, and modifiers for programming pixel shaders.

New D3DX Functionality

MeshView Tool

  • This tool provides an easy way to load, view, and modify meshes, and generally exercise Direct3DX (D3DX) functionality on progressive meshes. This tool is installed as part of the software development kit (SDK) install and can be accessed from Start/Programs/Microsoft DirectX 8.1 SDK/DirectX Utilities/DirectX MeshView. For more information about the tool, see Mesh View Help.

Effect Framework

  • Effects. Added string support, added comments, and removed FourCC constraints.

Texture Library

  • Implemented a higher quality DXTn encoding algorithm.
  • Use D3DXGetImageInfoFrom to get image information before loading it.
  • Includes support for dynamic textures.
  • D3DPOOL_SCRATCH allows creation of resources that are not limited by device capabilities. They can be created and destroyed, locked and unlocked. These resources can be set to a device and used in rendering. Use with D3DX to convert to something useable such as loading a high-precision height field and converting to a normal map.

Math Library

  • Math library. Added CPU specific optimizations for most important functions for 3DNow, SSE, and SSE2.
  • Support for 16-byte aligned matrices using D3DXMATRIXA16.

Samples

  • Several new samples have been included to demonstrate culling, lighting, volume fog, and self-shadowing using a shadow volume.
  • A new screen saver sample is included that is built on the screen saver sample framework. The new framework includes support for multiple monitors.

Documentation Upgrades

  • DXGraphics SDK Docs. The graphics SDK documentation has been reorganized into two sections: a Reference section and a Programmers Guide.
  • The global illumination equations and the Mathematics of Lighting section have been rewritten and examples included.

New Features in DirectX 8.0

This version maintains backward compatibility by exposing and supporting objects and interfaces offered by previous releases of DirectX. However, many new features and performance enhancements have also been added to the Microsoft Direct3D® API interfaces.

Pixel and Vertex Shaders

  • The two programmable sections of the Direct3D architecture are vertex shaders and pixel shaders. Vertex shaders are invoked prior to vertex assembly and operate on vertices. Pixel shaders are invoked after any DrawPrimitive or DrawIndexedPrimitive calls and generate the pixels that are written to the render target. The addition of programmable shaders for vertex and pixel operations provides the framework for real-time programmable effects that rival movie quality. The innovative freedom that this programmability gives back to game developers—by allowing them to implement whatever effect they see fit with the programmable pipeline—has the potential to unlock a new round of incredible games. Pixel and vertex shaders can be written using ASCII files, thus the shader files can be updated at runtime without recompiling the source application.

Complete Integration of DirectDraw and Direct3D

  • Simplifies application initialization and improves data allocation and management performance, which reduces the memory footprint. Also, the integration of the graphics APIs enable parallel vertex input streams for more flexible rendering.

Multisampling Rendering Support

  • Enables full-scene antialiasing and multisampling effects, such as motion blur and depth-of-field.

Point Sprites

  • Enables high-performance rendering of particle systems for sparks, explosions, rain, snow, and so on.

3-D Volumetric Textures

  • Enables range-attenuation in per-pixel lighting and volumetric atmospheric effects, and can be applied to more intricate geometry.

Higher-Order Primitive Support

  • Enhances the appearance of three-dimensional (3-D) content and facilitates the mapping of content from major 3-D authoring tools.

Higher-Level Technologies

  • Includes 3-D content-creation tool plug-ins (for export to Direct3D) for skinned meshes that use a variety of Direct3D techniques, multiresolution level-of-detail (LOD) geometry, and higher-order surface data.

Indexed Vertex Blending

  • Extends geometry blending support to allow the matrices used for vertex blending to be referred to using a matrix index.

Expansion of the Direct3DX Utility Library

  • Contains a wealth of new functionality. The Direct3DX utility library is a helper layer that sits on top of Direct3D to simplify common tasks encountered by 3-D graphics developers. Includes a skinning library, support for working with meshes, and functions to assemble vertex and pixel shaders. About 20 new functions have been added for DirectX 8.1. Note that the functionality supplied by D3D_OVERLOADS, first introduced with DirectX 5.0, has been moved to the Direct3DX utility library.


Programmers Guide

This guide contains a description of the graphics pipeline implemented by Microsoft® Direct3D®. It is a guide for developers who are implementing three-dimensional (3-D) 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 with Direct3D

    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.

  • Using Direct3D

    This section explains how to use the fixed function pipeline. Included here are the basic functional steps in the graphics pipeline: converting geometry, adding lighting, and rendering output.

  • Programmable Pipeline

    This section covers the new programmable extensions to the pipeline. Included here are details about using vertex shaders for manipulating object geometry, pixel shaders for controlling pixel shading.

    •
  • 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, and tweening show how to apply leading-edge special effects to your application.

  • Samples

    This section contains sample applications.

    •
  • Direct3D Appendix

    This section contains details on additional topics, such as X Files and graphics state.

For more information about specific API methods, see the Reference pages.


Getting Started with Direct3D

This section provides a brief introduction to the three-dimensional (3-D) graphics functionality in the Microsoft® Direct3D® application programmer interface (API). Here you will find an overview of the graphics pipeline and tutorials to help you get basic Direct3D functionality up and running quickly.

  • Direct3D Architecture
  • DirectX Graphics Visual Basic Tutorials
    •


Direct3D Architecture

This section contains general information about the relationship between the Microsoft® Direct3D® component and the rest of Microsoft DirectX®, the operating system, and the system hardware. The following topics are discussed.

  • Architectural Overview for Direct3D
  • Hardware Abstraction Layer
  • System Integration
  • Programmable Vertex Shader Architecture
  • Programmable Pixel Shader Architecture


Architectural Overview for Direct3D

This is an illustration of the graphics pipeline. The functionality in each of the blocks is introduced below and contains links to more information.

For more information on the architecture of the programmable sections of the Direct3D, see Vertex Shader Architecture and Pixel Shader Architecture.


Hardware Abstraction Layer

Microsoft® Direct3D® provides device independence through the hardware abstraction layer (HAL). The HAL is a device-specific interface, provided by the device manufacturer, that Direct3D uses to work directly with the display hardware. Applications never interact with the HAL. Rather, with the infrastructure that the HAL provides, Direct3D exposes a consistent set of interfaces and methods that an application uses to display graphics. The device manufacturer implements the HAL in a combination of 16-bit and 32-bit code under Microsoft Windows®. Under Windows NT® and Windows 2000, the HAL is always implemented in 32-bit code. The HAL can be part of the display driver or a separate dynamic-link library (DLL) that communicates with the display driver through a private interface that driver's creator defines.

The Direct3D HAL is implemented by the chip manufacturer, board producer, or original equipment manufacturer (OEM). The HAL implements only device-dependent code and performs no emulation. If a function is not performed by the hardware, the HAL does not report it as a hardware capability. Additionally, the HAL does not validate parameters; Direct3D does this before the HAL is invoked.

In DirectX 8.x, the HAL can have three different vertex processing modes: software vertex processing, hardware vertex processing, and mixed vertex processing on the same device. The pure device mode is a variant of the HAL device. The pure device type supports hardware vertex processing only, and allows only a small subset of the device state to be queried by the application. Additionally, the pure device is available only on adapters that have a minimum level of capabilities.


System Integration

The following diagram shows the relationships between Microsoft® Direct3D®, the graphics device interface (GDI), the hardware abstraction layer (HAL), and the hardware.

As the preceding diagram shows, Direct3D applications exist alongside GDI applications and both have access to the graphics hardware through the device driver for the graphics card. Unlike GDI, Direct3D can take advantage of hardware features when a HAL device is selected. HAL devices provide hardware acceleration based on the feature set supported by the graphics card. You are provided with a Direct3D method to determine at run time if a device is capable of the task.

For more information on devices supported by Direct3D, see Device Types.


Programmable Vertex Shader Architecture

The following diagram illustrates the vertex shader architecture. The vertex shader architecture streams vertex data into the shader from the graphics pipeline, performs operations on the data using an arithmetic logic unit (ALU), and outputs the transformed vertex data to the graphics pipeline for further processing.

Registers are used for inputting data, outputting data, and to hold a temporary result. Each register holds four fixed point numbers. The vertex shader architecture defines several types of registers, each operating on a different type of data.

  • v0–v15. Vertex registers are used to stream vertex data into the shader ALU. Vertex data is defined by an application and can contain any data.
  • r0–r11. Temporary registers are used to hold intermediate results.
  • a0. Version 1.1 supports one address register; version 1.0 does not have one. An address register can be used to provide an integer offset during the lookup of any register.
  • c0–c95. Constant value registers are designed to input constant values to the shader.
  • oDn, oFog, oPos, oPts, oTn. Output registers output data from the vertex shader to the graphics pipeline for further processing. The registers contain transformed position data, texture coordinates, diffuse color, and specular color.

    • For more information about vertex shader registers, see Registers.

    For more information about the vertex shader instruction set, see the Vertex Shader Reference.


Programmable Pixel Shader Architecture

The following diagram illustrates the pixel shader architecture. This architecture uses pixel data from a series of input registers, performs operations on the data using an arithmetic logic unit (ALU), and outputs the transformed pixel data to the graphics pipeline for further processing.

ALU data input and output is done with four types of pixel shader registers:

  • Color Registers - These registers stream iterated vertex color data from a vertex shader or the fixed function vertex pipeline to a pixel shader.
  • Constant Registers - These registers provide user defined constants to the shader.
  • Output/Temporary Registers - These registers provide temporary storage for intermediate calculations. The r0 register also provides the output of the pixel shader.
  • Texture Registers - provide texture data to the pixel shader ALU. Data from a texture is sampled using both texture coordinates and the current texture stage attributes. For more information, see Pixel Shader Texture Addressing.

    • For ps 1.0 - 1.3, texture registers can be written to by the ALU, which means that texture registers can also be used as temporary registers to store intermediate results.

    For ps 1.4, texture registers serve a different purpose, as read-only texture coordinate registers. To accomodate this, ps 1.4 also has more temporary registers than previous versions, and texture data can go directly into these temporary registers. This eliminates the need for texture registers.

Texture Addressing - uses texture coordinates to sample textures. For more information, see Pixel Shader Texture Addressing.

The Pixel Shader ALU provides arithmetic and texture addressing instructions. Arithmetic instructions preform basic mathematic operations on data, texture addressing instructions can be used to sample textures, or perturb texture coordinates. For more information about how instructions are the ALU pipeline, see the Pixel Shader ALU.


DirectX Graphics Visual Basic Tutorials

The tutorials in this section show how to use Microsoft® Direct3D® and Direct3DX in a Microsoft Visual Basic® application for common tasks by dividing those tasks into required steps. In some cases, steps are organized into substeps for clarity. The following tutorials are presented.

  • 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

Note The sample code in these tutorials is from source projects whose location is provided in each tutorial.

Some comments in the included sample code might differ from the source files in the SDK. Changes are made for brevity only, and are limited to comments to avoid changing the behavior of the code.

See Also

DirectX Graphics Visual Basic Samples


Tutorial 1: Creating a Device

To use Microsoft® Direct3D® in Microsoft Visual Basic®, you first create a form for your application window, then create and initialize Direct3D objects. You use these objects through their defined methods, which are also used to create other objects required to render a scene. The CreateDevice sample project upon 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 create a form, set up Direct3D, render a scene, and eventually shut down.

  • Step 1: Creating a Form
  • Step 2: Initializing Direct3D
  • Step 3: Rendering and Displaying a Scene
  • Step 4: Shutting Down

Note The path of the CreateDevice sample project is:

(SDK root)\Samples\Multimedia\VBSamples\Direct3D\Tutorials\Tut01_CreateDevice.


Step 1: Creating a Form

A Microsoft® Visual Basic® form serves as your application window. Set the properties for your form in the following manner:

BorderStyle     =   2 - Sizeable
Caption         =   "Create Device"
Height          =   3600
Left            =   0
Top             =   0
Width           =   4800
LinkTopic       =   "Form1"
MaxButton       =   True
MinButton       =   True
ScaleHeight     =   3195
ScaleMode       =   1 - Twip
ScaleWidth      =   254
StartUpPosition =   3 - Windows Default

To display your application window, include the following line in your Form_Load procedure:

Me.Show

With the application window ready, you can begin initializing the main Microsoft DirectX® objects, as described in Step 2: Initializing Direct3D.


Step 2: Initializing Direct3D

The CreateDevice sample project performs system initialization in its InitD3D application-defined function called from Form_Load after the form is shown. After you display a form for the application, you are ready to initialize the Microsoft® Direct3D® device that you will use to render the scene. This process includes creating a Direct3D object, setting the presentation parameters, and finally creating the Direct3D device.

To create a Direct3D object, use the DirectX8.Direct3DCreate method. You can use this Direct3D object to enumerate devices, types, modes, and so on.

Set g_D3D = g_DX.Direct3DCreate()
If g_D3D Is Nothing Then Exit Function

The next step is to retrieve the current display mode by using the Direct3D8.GetAdapterDisplayMode method as shown in the code fragment below.

Dim Mode As D3DDISPLAYMODE
g_D3D.GetAdapterDisplayMode D3DADAPTER_DEFAULT, mode

The Format member of the D3DDISPLAYMODE type will be used when creating the Direct3D device. To run in windowed mode, the Format member is used to create a back buffer that matches the adapter's current mode.

By filling in the fields of the D3DPRESENT_PARAMETERS object, you can specify how you want your 3-D application to behave. The CreateDevice sample project sets its Windowed member to 1(True), its SwapEffect member to D3DSWAPEFFECT_COPY_VSYNC, and its BackBufferFormat member to mode.Format.

Dim d3dpp As D3DPRESENT_PARAMETERS
d3dpp.Windowed = 1
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY_VSYNC
d3dpp.BackBufferFormat = mode.Format

The final step is to use Direct3D8.CreateDevice to create the Direct3D device, as illustrated in the following code example.

Set g_D3DDevice = g_D3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, _
                                     D3DCREATE_SOFTWARE_VERTEXPROCESSING, d3dpp)
If g_D3DDevice Is Nothing Then Exit Function

The preceding code 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 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 required Direct3D objects have been created, the next step, to execute the rendering loop, is described in Step 3: Rendering and Displaying a Scene.


Step 3: Rendering and Displaying a Scene

The CreateDevice sample project uses a timer to render the screen at a given interval. The sample sets the timer's Interval property to 40. This means that every forty milliseconds the function Timer1_Timer will fire. When the timer fires, it calls the application-defined function Render, which renders and displays the scene. The CreateDevice sample project 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 render a scene, start by calling the Direct3DDevice8.Clear method.

g_D3DDevice.Clear 0, ByVal 0, D3DCLEAR_TARGET, &HFF&, 1#, 0

The first two parameters accepted by Clear inform Microsoft® 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 will use a single rectangle that covers the entire rendering target. This is done by setting the first parameter to 0 and the second parameter to ByVal 0. 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 (&HFF&). The final two parameters are ignored by the 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_D3DDevice.BeginScene

' Rendering of scene objects occur here.

' End the scene.
g_D3DDevice.EndScene

The Direct3DDevice8.BeginScene and Direct3DDevice8.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 Direct3DDevice8.Present method.

g_D3DDevice.Present ByVal 0, ByVal 0, 0, ByVal 0

The first two parameters accepted by Present are a source rectangle and a destination rectangle. This sample presents the entire back buffer to the front buffer by setting these two parameters to ByVal 0. The third parameter sets the destination window for this presentation. Because this parameter is set to 0, the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is used. The fourth parameter is the DirtyRegion parameter and in most cases should be set to ByVal 0.

The final step for this tutorial, shutting down the application, is described in Step 4: Shutting Down.


Step 4: Shutting Down

At some point during execution, your application must shut down. When shutting down a Microsoft® DirectX® application, you need to disassociate any DirectX objects your application used by setting them to Nothing. The CreateDevice sample project calls Cleanup, an application-defined function, to handle this cleanup. Cleanup is called from Form_Unload when the form is unloading.

Private Sub Form_Unload(Cancel As Integer)

    Set g_D3D = Nothing
    Set g_D3DDevice = Nothing

End Sub

The preceding function sets its Microsoft Direct3D® objects to Nothing, which in turn disassociates the variable from the actual object. In addition to shut down, 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 Direct3D objects in use. As a result, it's handy 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 Microsoft® Direct3D® use vertices to draw geometric shapes. Each 3-D scene inclides 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 covers how to select a custom vertex type, set up a vertex buffer, and render vertices to the display.

This tutorial shows how to use vertices to create a triangle with the following 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\Multimedia\VBSamples\Direct3D\Tutorials\Tut01_Vertices.

The code in the Vertices sample project is nearly identical to the code in CreateDevice sample project. This tutorial focuses only on the code unique to vertices and does not cover initializing Direct3D, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device


Step 1: Defining a Custom Vertex Type

The Vertices sample project renders a 2-D triangle by using three vertices. This introduces the concept of the vertex buffer, which is a Microsoft® Direct3D® object that is used to store and render vertices. Vertices can be defined many different ways by specifying a custom vertex structure and corresponding custom flexible vector format (FVF). The format of the vertices in the Vertices sample project is shown in the following code fragment.

Private Type CUSTOMVERTEX
    x As Single         'x in screen space.
    y As Single         'y in screen space.
    z As Single         'normalized z.
    rhw As Single       'normalized z rhw.
    color As Long       'vertex color.
End Type

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.

Const D3DFVF_CUSTOMVERTEX = (D3DFVF_XYZRHW Or D3DFVF_DIFFUSE)

The Flexible Vertex Format Flags describes what type of custom vertex is being used. The Vertices sample project uses the D3DFVF_XYZRHW and D3DFVF_DIFFUSE flags, which tells the vertex buffer that the custom vertex type has a transformed point followed by a color component.

Now that the custom vertex 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, meaning that they are already in 2-D window coordinates. This means that the point (0,0) is at the top left hand corner and the positive x-axis is right and the positive y-axis is down. These vertices are also lit, which means 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 Microsoft® Direct3D® objects. The code following fragment initializes the values for three custom vertices.

With Vertices(0): .x = 150: .y =  50: .z = 0.5: .rhw = 1: .color = &HFFFF0000: End With
With Vertices(1): .x = 250: .y = 250: .z = 0.5: .rhw = 1: .color = &HFF00FF00: End With
With Vertices(2): .x =  50: .y = 250: .z = 0.5: .rhw = 1: .color = &HFF00FFFF: End With

The preceding code 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 (&HFFFF0000). The second point is at (250, 250) and emits the color green (&HFF00FF00). The third point is at (50, 250) and emits the color blue-green (&HFF00FFFF). Each of these points has a pixel depth of 0.5 and an RHW of 1. For more information on this vector format see Transformed and Lit Vertices

The next step is to call Direct3DDevice8.CreateVertexBuffer to create a vertex buffer as shown in the following code fragment.

Set g_VB = g_D3DDevice.CreateVertexBuffer(VertexSizeInBytes * 3, _
                 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT)
If g_VB Is Nothing Then Exit Function

The first two parameters for 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 FVF that the Vertices sample project specified earlier. The D3DPOOL_DEFAULT flag tells Direct3D to create the vertex buffer in the memory 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 by calling the D3DVertexBuffer8SetData method as shown in the following code fragment.

D3DVertexBuffer8SetData g_VB, 0, VertexSizeInBytes * 3, 0, Vertices(0)

The first parameter that D3DVertexBuffer8SetData accepts is the vertex buffer to place the data in. The second parameter is offset, in bytes, from the start of the buffer where data is set. The third parameter is the size of the buffer, in bytes. The fourth flag is a combination of one or more flags that describe how to lock the buffer. The sample sets this parameter to 0, which tells the function to send default flags to the lock. The fifth parameter is the buffer that contains the data to place in the vertex buffer.

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_D3DDevice.Clear 0, ByVal 0, D3DCLEAR_TARGET, &HFF&, 1#, 0
g_D3DDevice.BeginScene

Rendering vertex data from a vertex buffer is divided into 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 Direct3DDevice8.SetStreamSource.

g_D3DDevice.SetStreamSource 0, g_VB, sizeOfVertex

The first parameter of SetStreamSource tells Microsoft® 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.

The next step is to let Direct3D know what vertex shader to use by calling Direct3DDevice8.SetVertexShader. Full, custom vertex shaders are an advanced topic, but in most cases the vertex shader is just the FVF. This lets Direct3D know what types of vertices it is dealing with. The following code fragment sets the vertex shader.

g_D3DDevice.SetVertexShader D3DFVF_CUSTOMVERTEX

The only parameter for SetVertexShader is a handle to the vertex shader to use. The value for this parameter can be a handle returned by Direct3DDevice8.CreateVertexShader, or a FVF code. Here, the FVF code defined by D3DFVF_CUSTOMVERTEX is used.

For more information on vertex shaders, see Vertex Shaders.

The next step is to use Direct3DDevice8.DrawPrimitive to render the vertices in the vertex buffer as shown in the following code fragment.

g_D3DDevice.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 on different kinds of primitives, see 3-D Primitives.

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_D3DDevice.EndScene
g_D3DDevice.Present ByVal 0, ByVal 0, 0, ByVal 0

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 2-D vertices to draw a triangle. However, in this tutorial you work with transformations of vertices in 3-D. Matrices are also used to set up cameras and viewports. For more information on working with transformation matrices, see Transforms.

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 3-D triangle. Typically, three different types of transformation are applied to a 3-D scene. Steps for creating each one of these typical transformations are listed below.

  • Step 1: Defining the World Transformation Matrix
  • Step 2: Defining the View Transformation Matrix
  • Step 3: Defining the Projection Transformation Matrix

For more information on matrices and transformations, see Matrices.

Note The path of the Matrices sample project is:

(SDK root)\Samples\Multimedia\VBSamples\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 code in the Matrices sample project is nearly identical to the code in Vertices sample project. This tutorial focuses only on the code unique to matrices and does not cover initializing Direct3D, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device.

This tutorial also uses custom vertices and a vertex buffer to display geometry. For more information on selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.


Step 1: Defining the World Transformation Matrix

The world transformation matrix defines how to translate, scale, and rotate geometry in 3-D model space.

The following code fragment rotates the triangle on the y-axis and then sets the current world transformation for the Microsoft® Direct3D® device.

Dim matWorld As D3DMATRIX
D3DXMatrixRotationY matWorld, Timer * 4
g_D3DDevice.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 D3DMATRIX type that contains the returned matrix. The second parameter is the angle of rotation in radians.

The next step is to call Direct3DDevice8.SetTransform to set the current world transformation for the Direct3D device. The first parameter accepted by SetTransform tells which transformation to set. This sample uses the D3DTS_WORLD flag 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 on world transformations, see World Transformation.

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 to the Microsoft® Direct3D® device.

Dim matView As D3DMATRIX
D3DXMatrixLookAtLH matView, vec3(0#, 3#, -5#), _
                            vec3(0#, 0#,  0#), _
                            vec3(0#, 1#,  0#)

g_D3DDevice.SetTransform D3DTS_VIEW, matView

The first step is to define the view matrix by calling D3DXMatrixLookAtLH. The first parameter is a D3DMATRIX type that contains the returned matrix. The second, third, and fourth parameters define the eye point, look at point, and "up" direction. 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 Direct3DDevice8.SetTransform to set the current view transformation for the Direct3D device. The first parameter accepted by SetTransform tells 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 on view transformations, see View Transformation.

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 will be transformed from 3-D view space to 2-D viewport space.

The following code fragment creates the projection transformation matrix and then applies the transformation to the Microsoft® Direct3D® device.

Dim matProj As D3DMATRIX
D3DXMatrixPerspectiveFovLH matProj, g_pi / 4, 1, 1, 1000
g_D3DDevice.SetTransform D3DTS_PROJECTION, matProj

The first step is to call D3DXMatrixPerspectiveFovLH to set up the projection matrix. The first parameter is a D3DMATRIX type that contains the returned matrix. 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 parameter 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 Direct3DDevice8.SetTransform to set the current projection transformation for the Direct3D device. The first parameter accepted by SetTransform tells 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 on projection transformations, see Projection Transformation.

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

Microsoft® Direct3D® lights add more realism to 3-D objects. When used, each geometric object in the scene will be lit based on the location and type of lights that are used. The Lights sample project introduces the topics of lights and materials.

This tutorial takes the following step to create and use materials and lights.

  • Step 1: Initializing Scene Geometry
  • Step 2: Setting up Material and Light

Note The path of the Lights sample project is:

(SDK root)\Samples\Multimedia\VBSamples\Direct3D\Tutorials\Tut04_Lights.

The code in the Lights sample project is nearly identical to the code in the Matrices sample project. This tutorial focuses only on the code unique to lights and does not cover initializing Direct3D, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device.

This tutorial also uses custom vertices and a vertex buffer to display geometry. For more information on selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial also makes use of matrices to transform geometry. For more information on 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 3-D position and a surface normal. The surface normal is used internally by Microsoft® Direct3D for lighting calculations.

' A structure for the custom vertex type.
Private Type CUSTOMVERTEX
    postion As D3DVECTOR    '3d position for vertex
    normal As D3DVECTOR     'surface normal for vertex
End Type

' The custom FVF, which describes the custom vertex structure.
Const D3DFVF_CUSTOMVERTEX = (D3DFVF_XYZ Or D3DFVF_NORMAL)

Now that the correct vector format is defined, the Lights sample project calls InitGeometry, which is an application-defined function that creates a cylinder. The first step is to fill the vertex buffer with the points of the cylinder. Note that in the following code fragment, each point is defined by a position and a normal.

For i = 0 To 49
    theta = (2 * g_pi * i) / (50 - 1)
    Vertices(2 * i + 0).postion = vec3(Sin(theta), -1, Cos(theta))
    Vertices(2 * i + 0).normal = vec3(Sin(theta), 0, Cos(theta))
    Vertices(2 * i + 1).postion = vec3(Sin(theta), 1, Cos(theta))
    Vertices(2 * i + 1).normal = vec3(Sin(theta), 0, Cos(theta))
Next

The second step is to create a vertex buffer that stores the points of the cylinder as shown in the following code fragment.

Set g_VB = g_D3DDevice.CreateVertexBuffer(VertexSizeInBytes * 50 * 2, _
                 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT)
If g_VB Is Nothing Then Exit Function

Now fill the vertex buffer with the vertices for the cylinder and the vertex buffer is ready for rendering. But first, the material and light for this scene must be set up before rendering the cylinder, as described in Step 2: Setting up Material and Light.


Step 2: Setting up Material and Light

To use lighting in Microsoft® 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 an application-defined function named SetupLights to set up one material and one directional light. This function takes the following steps to create a material and a light.

  • Step 2.1: Creating a Material
  • Step 2.2: Creating a Light


Step 2.1: 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 D3DMATERIAL8 structure to create a material that is yellow.

Dim mtrl As D3DMATERIAL8
With col:    .r = 1: .g = 1: .b = 0: .a = 1:   End With
mtrl.diffuse = col
mtrl.Ambient = col
g_D3DDevice.SetMaterial mtrl

The diffuse color and ambient color for the material are set to yellow. The call to the Direct3DDevice8.SetMaterial method applies the material to the Microsoft® Direct3D® device used to render the scene. The only parameter that 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 SetMaterial that specifies a different material.

Now that material has been applied to the scene, the next step is to create a light. This is described in Step 2.2: Creating a Light.


Step 2.2: Creating a Light

There are three types of lights available in Microsoft® Direct3D®. These are point lights, directional lights, and spotlights. The Lights sample project creates a directional light, which is a light that goes in one direction and oscillates the direction of the light.

The following code fragment uses the D3DLIGHT8 type to define a directional light.

Dim light As D3DLIGHT8
light.Type = D3DLIGHT_DIRECTIONAL

The following code fragment sets the diffuse color for this light to white.

light.diffuse.r = 1#
light.diffuse.g = 1#
light.diffuse.b = 1#

The following code fragment rotates the direction of the light around in a circle.

light.Direction.x = Cos(Timer * 2)
light.Direction.y = 1#
light.Direction.z = Sin(Timer * 2)

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#

The following code fragment assigns the light to the Direct3D device by calling Direct3DDevice8.SetLight.

g_D3DDevice.SetLight 0, light     'Let Direct3D know about the light.

The first parameter that SetLight accepts is the index that this light will be assigned to. Note that if a light already exists at that location, then 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 code following fragment enables the light by calling Direct3DDevice8.LightEnable.

g_D3DDevice.LightEnable 0, 1

The first parameter that LightEnable accepts is the index of the light to enable. The second parameter is a value that tells whether to turn the light on (1) or off (0). In the Lights sample project, the light at index 0 is turned on.

The next step that this sample takes is to turn on ambient lighting by calling Direct3DDevice8.SetRenderState.

g_D3DDevice.SetRenderState D3DRS_AMBIENT, &H202020

The two parameters that SetRenderState accepts is which device state variable to modify and what value to set it to. The sample sets the D3DRS_AMBIENT device variable to a light gray color (&H202020). Ambient lighting will light up all objects by the given color.

Before using lights in Direct3D, they must be enabled. The following code fragment tells Direct3D to render lights by calling SetRenderState.

g_D3DDevice.SetRenderState D3DRS_LIGHTING, 1    'Make sure lighting is enabled.

This sample sets the D3DRS_LIGHTING device variable to 1(True), which has the effect of enabling the rendering of lights.

For more information on lighting, see Mathematics of Direct3D Lighting.

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 put a wood texture on a cube to make it look like the cube is actually made of wood. The Texture sample project adds a banana peel texture to the cylinder created in the Lights sample. This tutorial covers how to load textures, set up vertices, and display objects with texture.

This tutorial implements textures with the following steps:

  • Step 1: Defining a Custom Vertex Format
  • Step 2: Initializing Screen Geometry
  • Step 3: Rendering the Scene

Note The path of the Textures sample project is:

(SDK root)\Samples\Multimedia\VBSamples\Direct3D\Tutorials\Tut05_Textures.

The code in the Texture sample project is nearly identical to the code in the Lights sample project, except that the Texture sample project does not create a material or a light. This tutorial focuses only on the code unique to textures and does not cover initializing Microsoft® Direct3D®, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device.

This tutorial also uses custom vertices and a vertex buffer to display geometry. For more information on selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial also makes use of matrices to transform geometry. For more information on 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 tells Microsoft® 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-hand side of the texture and (1.0, 1.0) represents the bottom right-hand side of the texture.

The following code fragment shows how the Texture sample project sets up it's custom vertex format to include texture coordinates.

' Custom vertex type.
Private Type CUSTOMVERTEX
    postion As D3DVECTOR    '3-D position for vertex.
    color As Long           'Color of the vertex.
    tu As Single            'Texture map coordinate.
    tv As Single            'Texture map coordinate.
End Type

' Custom FVF.
Const D3DFVF_CUSTOMVERTEX = (D3DFVF_XYZ Or D3DFVF_DIFFUSE Or D3DFVF_TEX1)

For more information on texture coordinates, see Texture Coordinates.

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 an application-defined function, InitGeometry, to create a texture and set up the geometry for a cylinder.

Textures are created from file-based images. The following code fragment uses D3DX8.CreateTextureFromFile to create a texture from Banana.bmp that will be used to cover the surface of the cylinder.

Set g_Texture = g_D3DX.CreateTextureFromFile(g_D3DDevice, App.Path + "\banana.bmp")
If g_Texture Is Nothing Then Exit Function

The first parameter that CreateTextureFromFile accepts is the Microsoft® Direct3D® device that will be used to render the texture. The second parameter is a string that specifies the filename from which to create the texture. This sample specifies Banana.bmp to load the image from that file.

The banana texture is loaded and ready to use. The next step is to create the cylinder. The following code fills the vertex buffer with a cylinder. Note that each point has the texture coordinate (tu, tv).

For i = 0 To 49
    theta = (2 * g_pi * i) / (50 - 1)

    Vertices(2 * i + 0).position = vec3(Sin(theta), -1, Cos(theta))
    Vertices(2 * i + 0).color = &HFFFFFFFF  'White.
    Vertices(2 * i + 0).tu = i / (50 - 1)
    Vertices(2 * i + 0).tv = 1

    Vertices(2 * i + 1).position = vec3(Sin(theta), 1, Cos(theta))
    Vertices(2 * i + 1).color = &HFF808080  'Grey.
    Vertices(2 * i + 1).tu = i / (50 - 1)
    Vertices(2 * i + 1).tv = 0
Next

Each vertex includes a position, color, and texture coordinates. The Texture sample project 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 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 Microsoft® Direct3D® device will use to render with Direct3DDevice8.SetTexture.

g_D3DDevice.SetTexture 0, g_Texture

The first parameter that 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. This sample only has one texture and places it at stage 0. The second parameter is a pointer to a texture object. This sample uses the texture object that it created in its InitGeometry application-defined function.

The following code fragment sets the texture stage state values by calling the Direct3DDevice8.SetTextureStageState method.

g_D3DDevice.SetTextureStageState 0, D3DTSS_COLOROP, D3DTOP_MODULATE
g_D3DDevice.SetTextureStageState 0, D3DTSS_COLORARG1, D3DTA_TEXTURE
g_D3DDevice.SetTextureStageState 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE
g_D3DDevice.SetTextureStageState 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE

The first parameter that SetTextureState accepts is the stage index for the state variable to be set. This sample is changing the values for the texture at stage 0, so it puts a 0 here. The next parameter is the texture state to set. For a list of all valid texture states and their meaning, see CONST_D3DTEXTURESTAGESTATETYPE. The next parameter is the value to set the texture state to. 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 with texture added to the surface.

Another way to use texture coordinates is to have them automatically generated. 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. The code fragment for creating the matrix is shown below.

Dim mat As D3DMATRIX

mat.m11 = 0.25: mat.m12 = 0#:     mat.m13 = 0#: mat.m14 = 0#
mat.m21 = 0#:   mat.m22 = -0.25:  mat.m23 = 0#: mat.m24 = 0#
mat.m31 = 0#:   mat.m32 = 0#:     mat.m33 = 1#: mat.m34 = 0#
mat.m41 = 0.5:  mat.m42 = 0.5:    mat.m43 = 0#: mat.m44 = 1#

After the matrix is created, it must be set by calling SetTransform, as shown in the following code segment.

g_D3DDevice.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 code fragment below.

g_D3DDevice.SetTextureStageState 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2
g_D3DDevice.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 on textures, see Textures.

This tutorial has shown you how to use textures for surfaces. Tutorial 6: Using Meshes shows you how to use complex geometric shapes with meshes.


Tutorial 6: Using Meshes

Complicated geometry is usually modeled using 3-D modeling software and saved to a file. A example of this is the .x file format. Microsoft® Direct3D® uses meshes to load the objects from these files. Meshes are somewhat involved, but Microsoft® Direct3DX contains functions to help out. 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 and render a mesh with the following steps.

  • Step 1: Loading a Mesh Object
  • Step 2: Rendering a Mesh Object

The path of the Meshes sample project is:

(SDK root)\Samples\Multimedia\VBSamples\Direct3D\Tutorials\Tut06_Meshes.

The code in the Meshes sample project is nearly identical to the code in the Lights sample project, except that the Meshes sample project does not create a material or a light. This tutorial focuses only on the code unique to Meshes and does not cover initializing Direct3D, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device.

This tutorial also uses custom vertices and a vertex buffer to display geometry. For more information on selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial also makes use of matrices to transform geometry. For more information on matrices and transformations, see Tutorial 3: Using Matrices.

This tutorial also uses textures to cover the surface of the mesh. For more information on loading and using textures, see Tutorial 5: Using Texture Maps.


Step 1: Loading a Mesh Object

A Microsoft® 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 information about all the materials and textures that will be used. The function starts by declaring a material buffer.

Dim MtrlBuffer As D3DXBuffer

The Meshes sample project uses the D3DX8.LoadMeshFromX method to load the mesh, as shown in the code below.

Set g_Mesh = g_D3DX.LoadMeshFromX(App.Path + "\Tiger.x", D3DXMESH_MANAGED, _
                               g_D3DDevice, Nothing, MtrlBuffer, g_NumMaterials)

If g_Mesh Is Nothing Then Exit Function

The first parameter that D3DXLoadMeshFromX accepts is a string that tells the name of the Microsoft DirectX® file to load. This sample loads the tiger mesh from Tiger.x. The second parameter tells Direct3D how to create the mesh. The sample uses the D3DXMESH_MANAGED flag, which tells Direct3D to use the D3DPOOL_MANAGED memory class for the index buffers. The third parameter is the Direct3D device that will be used to render the mesh. The fourth parameter takes a D3DXBuffer 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 Nothing. The fifth parameter also takes a pointer to a D3DXBuffer object. After this method is finished, this object will be filled with D3DXMATERIAL structures for the mesh. The sixth parameter takes a variable of type Long that will tell the number of D3DXMATERIAL structures placed into the RetMaterials parameter after this method returns.

After loading the mesh object and material information, you need to extract the material properties and texture names from the material buffer.

Before getting this information from the material buffer, the material and texture arrays must be resized to fit all the materials and textures for this mesh.

ReDim g_MeshMaterials(g_NumMaterials)
ReDim g_MeshTextures(g_NumMaterials)

For each material in the mesh the following steps occur.

The first step is to use D3DX8.BufferGetMaterial to copy the material, as shown in the code fragment below.

g_D3DX.BufferGetMaterial MtrlBuffer, i, g_MeshMaterials(i)

The first parameter that BufferGetMaterial accepts is the material object, which in this case is MtrlBuffer. The second parameter is the index of the material to retrieve. The third parameter is the location to place the material.

The second step is to set the ambient color for the material, as shown in the following code fragment.

g_MeshMaterials(i).Ambient = g_MeshMaterials(i).diffuse

The final step is to create the texture for the material, as shown in the following code fragment.

strTexName = g_D3DX.BufferGetTextureName(MtrlBuffer, i)
If strTexName <> "" Then
    Set g_MeshTextures(i) = g_D3DX.CreateTextureFromFile(g_D3DDevice, App.Path + "\" + strTexName)
End If

After loading all the materials, you need to let Direct3D know that you are finished with the material buffer by setting it to Nothing.

Set MtrlBuffer = Nothing

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

The mesh is loaded and ready to be rendered. The mesh is divided into a subsets 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_D3DDevice.SetMaterial g_MeshMaterials(i)

The second step in the loop is to set the texture for the subset, as shown in the following code fragment.

g_D3DDevice.SetTexture 0, g_MeshTextures(i)

After setting the material and texture, the subset is drawn with the D3DXBaseMesh.DrawSubset method, as shown in the following code fragment.

g_Mesh.DrawSubset i

The DrawSubset method takes a Long value that specifies which subset of the mesh to draw. This sample uses the value that is incremented each time the loop runs.

This loop will run until each subset in the mesh has been rendered.

This tutorial has shown you how to load and render meshes. This is the last tutorial in this section. To find out how a typical Microsoft® Direct3D® application is written in Microsoft Visual Basic®, check the DirectX Graphics Visual Basic Samples.


Using Direct3D

This section explains the operation of the Microsoft® Direct3D® fixed function pipeline. The pipeline consists of several building blocks. These blocks are detailed in the following sections.

  • Vertex Data

  • Transforms

  • Viewports and Clipping

  • Lights and Materials

  • Textures

  • Rendering

  • About Devices


Vertex Data

Vertex data is presented to the pipeline in the form of object primitives. The following topics discuss three-dimensional (3-D) coordinates, how coordinates make up vertex data for an object, and how the vertex data declaration determines how the pipeline functions.

  • 3-D Coordinate Systems and Geometry
  • Fixed Function Vertex and Pixel Processing
  • Programmable Vertex and Pixel Processing
  • Programmable Stream Model
  • Device-Supported Primitive Types


3-D Coordinate Systems and Geometry

Programming Microsoft® Direct3D® applications requires a working familiarity with 3-D geometric principles. This section introduces the most important geometric concepts for creating 3-D scenes. The following topics are covered.

  • 3-D Coordinate Systems
  • 3-D Primitives
  • Rectangles
  • Vectors, Vertices, and Quaternions
  • Face and Vertex Normal Vectors
  • Triangle Interpolants
  • Triangle Rasterization Rules

These topics provide you with a high-level understanding of the basic concepts employed by a Direct3D application. For more information about these topics, see Further Information.


3-D Coordinate Systems

Typically 3-D 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.

Microsoft® 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 type 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 3-D software. For example, it is not unusual for 3-D 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. In this case, right-handedness is defined as any positive axis (x, y, or z) pointing toward the viewer. Left-handedness is defined as any positive axis (x, y, or z) pointing away from the viewer. If you are porting a left-handed modeling application where the z-axis points up, you must do a rotation on all the vertex data in addition to the previous steps.

The essential operations performed on objects defined in a 3-D coordinate system are translation, rotation, and scaling. You can combine these basic transformations to create a transform matrix. For details, see 3-D Transformations.

When you combine these operations, the results are not commutative—the order in which you multiply matrices is important.


3-D Primitives

A 3-D primitive is a collection of vertices that form a single 3-D entity. The simplest primitive is a collection of points in a 3-D coordinate system, which is called a point list.

Often, 3-D primitives are polygons. A polygon is a closed 3-D 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 and Textures.

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.


Rectangles

Throughout Microsoft® Direct3D® and Microsoft Windows® 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 top-left corner and bottom-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 Microsoft Visual Basic®, the RECT type has the following definition.

Type RECT
    Left As Long     ' This is the top-left corner x-coordinate.
    Top As Long      ' The top-left corner y-coordinate.
    Right As Long    ' The bottom-right corner x-coordinate.
    Bottom As Long   ' The bottom-right corner y-coordinate.
End Type

In the preceding example, the left and top members are the x- and y-coordinates of a bounding rectangle's top-left corner. Similarly, the right and bottom members make up the coordinates of the bottom-right corner. The following diagram illustrates how you can visualize these values.

In the interest of efficiency, consistency, and ease of use, all Direct3D presentation functions work with rectangles.


Vectors, Vertices, and Quaternions

Throughout Microsoft® 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 3-D rotations. A quaternion represents an axis in 3-D 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 Direct3DX 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 D3DQUATERNION type. 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
  • 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 with the Math Functions supplied by the Direct3DX utility library.


Face and Vertex Normal Vectors

Each face in a mesh has a perpendicular 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 Microsoft® 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 for more information.

Direct3D uses the vertex 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 3-D 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.


Triangle Interpolants

During rendering, the pipeline interpolates vertex data across each triangle. Five possible types of data can be interpolated:

  • Diffuse color
  • Specular color
  • Diffuse alpha (triangle opacity)
  • Specular alpha
  • Fog factor (taken from specular alpha for fixed function vertex pipeline and from fog register for programmable vertex pipeline)

The interpolation of the vertex data 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 interpolants, 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 color and specular interpolants 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 interpolant because device drivers can implement transparency in two different ways: by using texture blending or by using stippling.

Use the ShadeCaps member of the D3DCAPS8 type to determine what forms of interpolation the current device driver supports.


Triangle Rasterization Rules

Often, the points specified for vertices do not precisely match the pixels on the screen. When this happens, Microsoft® Direct3D® applies triangle rasterization rules to decide which pixels apply to a given triangle.

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.

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.

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.

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.

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.

For both rectangles, the same pixels are affected.


Fixed Function Vertex and Pixel Processing

The part of Microsoft® Direct3D® that pushes geometry through the fixed function geometry pipeline is the transformation engine. It locates the model and viewer in the world, projects vertices for display on the screen, and clips vertices to the viewport. The transformation engine also performs lighting computations to determine diffuse and specular components at each vertex.

The geometry pipeline takes vertices as input. The transformation engine applies three transformations—the world, view, and projection transformations—to the vertices, clips the result, and passes everything to the rasterizer. The following image illustrates the sequence of steps.

At the head of the pipeline, no transformations have been applied, so all of 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 transformation. 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 3-D 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 transformation.

The next stage is the projection transformation. 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 transformation as projection space. Some graphics books might refer to projection space as post-perspective homogeneous space. Not all projection transformations 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.

More information on the vertex formats is contained in Vertex Formats.

More information on legacy vertex formats is contained in Legacy FVF Format.


Vertex Formats

A flexible vertex format (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.

Microsoft® 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 Flexible Vertex Format Flags.

The FVF specification includes formats for point size, specified by D3DFVF_PSIZE. This size is expressed in camera space units for non-TL vertices, and in device-space units for TL vertices.

The Direct3DDevice8 Microsoft® Visual Basic® class includes methods that accept a combination of these flags, and uses them to determine how to render primitives. Basically, these flags tell the system which vertex components—position, vertex blending weights, normal, colors, 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 D3DFVFCAPS_DONOTSTRIPELEMENTS and D3DFVFCAPS_TEXCOORDCOUNTMASK flexible vertex format flags. For more information, see the FVFCaps member of the D3DCAPS8 structure.

One significant requirement that the system places on how you format your vertices is on the order in which the data appears. The following illustration depicts the required order for all possible vertex components in memory, and their associated data types.

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 2-D projected texture coordinates. Use the D3DFVF_TEXCOORDSIZEn set of helper functions from Math.bas to create bit patterns that identify the texture coordinate formats that your vertex format uses. The Math.bas Visual Basic code module is included with this SDK.

No real application will use every single 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 the flexibility is there. There are several restrictions on which flags you can use with other flags. These are mostly common sense. 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. 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.

The following code samples shows the difference between an FVF code that uses the D3DFVF_LASTBETA_UBYTE4 flag and one that doesn't. The FVF defined below does not use the D3DFVF_LASTBETA_UBYTE4 flag. The flag D3DFVF_XYZ3 is present when four blending indices are used because you always use (1 - the sum of the first three) for the fourth.

Const D3DFVF_BLENDVERTEX = (D3DFVF_XYZB3 Or D3DFVF_NORMAL Or D3DFVF_TEX1)

Private Type BLENDVERTEX
    v As D3DXVECTOR  ' Referenced as v0 in the vertex shader
    blend1 As Single ' Referenced as v1.x in the vertex shader
    blend2 As Single ' Referenced as v1.y in the vertex shader
    blend3 As Single ' Referenced as v1.z in the vertex shader
                     ' v1.w = 1.0 - (v1.x + v1.y + v1.z)
    n As D3DXVECTOR  ' Referenced as v3 in the vertex shader
    tu as Single     ' tu and tv referenced as v7 in the vertex shader
    tv As Single     '
End Type

The FVF defined below uses the D3DFVF_LAST_UBYTE4 flag.

Const D3DFVF_BLENDVERTEX = (D3DFVF_XYZB4 Or D3DFVF_LASTBETA_UBYTE4 Or _
                            D3DFVF_NORMAL Or D3DFVF_TEX1)
Private Type BLENDVERTEX
    v As D3DXVECTOR    'Referenced as v0 in the vertex shader
    blend1 As Single   ' Referenced as v1.x in the vertex shader
    blend2 As Single   ' Referenced as v1.y in the vertex shader
    blend3 As Single   ' Referenced as v1.z in the vertex shader
                       ' v1.w = 1.0 - (v1.x + v1.y + v1.z)
    indices As Long    ' Referenced as v2.xyzw in the vertex shader
    n As D3DXVECTOR    ' Referenced as v3 in the vertex shader
    tu As Single       ' tu and tv referenced as v7 in the vertex shader
    tv As Single
End Type

Use the following topics for additional information about the various formats your application can use to declare vertices.

  • Untransformed and Unlit Vertices
  • Untransformed and Lit Vertices
  • Transformed and Lit Vertices
  • Transformed and Lit Vertex Functionality
  • Flexible Vertex Formats and Vertex Shaders


Untransformed and Unlit Vertices

Many applications use this vertex type, as it frees them from implementing their own transformation and lighting engines. However, because the system is making calculations for you, it requires that you provide a certain amount of information with each vertex.

  • You are required to specify vertices in untransformed model coordinates. The system then applies world, view, and projection transformations to the model coordinates to position them in your scene and determine their final locations on the screen.
  • You can include a vertex normal for more realistic lighting effects. Vertices lit by the system that don't include a vertex normal will use a dot product of 0 in all lighting calculations. These vertices are assumed to receive no incident light. The system uses the vertex normal, along with the current material, in its lighting calculations. For details, see Face and Vertex Normal Vectors, Lights and Materials.

When you define your own vertex format, remember which vertex components your application needs, and make sure they appear in the required order by declaring a properly ordered structure. The following code example declares a valid vertex format structure that includes a position, a vertex normal, a diffuse color, and two sets of texture coordinates.

'
' The vertex format description for this vertex would be:
' (D3DFVF_XYZ Or D3DFVF_NORMAL Or D3DFVF_DIFFUSE Or D3DFVF_TEX2)
'
Type UNLITVERTEX
    x As Single      ' Position
    y As Single
    z As Single
    nx As Single     ' Normal
    ny As Single
    nz As Single
    Diffuse As Long  ' diffuse color
    tu1 As Single    ' texture coordinates
    tv1 As Single
    tu2 As Single    ' texture coordinates
    tv2 As Single
End Type

The vertex description for the preceding structure is a combination of the D3DFVF_XYZ, D3DFVF_NORMAL, D3DFVF_DIFFUSE, and D3DFVF_TEX2 flexible vertex format flags.

For more information, see Vertex Formats.


Untransformed and Lit Vertices

If you include the D3DFVF_XYZ flag, but not the D3DFVF_NORMAL flag, in the vertex format description you use with the Microsoft® Direct3D® rendering methods, you are identifying your vertices as untransformed but already lit. For information about other dependencies and exclusions, see the description for the Flexible Vertex Format Flags.

By using untransformed and lit vertices, your application requests that Direct3D not perform any lighting calculations on your vertices, but it should still transform them using the previously set world, view, and projection matrices. Because the system isn't doing lighting calculations, it doesn't need a vertex normal. The system uses the diffuse and specular components at each vertex for shading. These colors might be arbitrary, or they might be computed using your own lighting formulas. If you don't include a diffuse or specular component, the system uses the default colors. The default value for the diffuse color is 0xFFFFFFFF, and the default value for the specular color is 0x0.

Like the other vertex types, except for including a position and some amount of color information, you are free to include or disregard the texture coordinate sets in the unlit vertex format.

When you define your own vertex format, remember which vertex components your application needs, and make sure they appear in the required order by declaring a properly ordered structure. The following code example declares a valid untransformed and lit vertex, with diffuse and specular vertex colors, and three sets of texture coordinates.

'
' The vertex format description for this vertex
' would be: (D3DFVF_XYZ Or D3DFVF_DIFFUSE Or
'    D3DFVF_SPECULAR Or D3DFVF_TEX3)
'
Type LITVERTEX
    x As Single      ' position
    y As Single
    z As Single
    Diffuse As Long  ' diffuse color
    Specular As Long ' specular color
    tu1 As Single ' texture coordinates
    tv1 As Single
    tu2 As Single
    tv2 As Single
    tu3 As Single
    tv3 As Single
End Type

The vertex description for the preceding structure is a combination of the D3DFVF_XYZ, D3DFVF_DIFFUSE, D3DFVF_SPECULAR, and D3DFVF_TEX3 flexible vertex format flags.


Transformed and Lit Vertices

If you include the D3DFVF_XYZRHW flag in your vertex format description, you are telling the system that your application is using transformed and lit vertices. This means that Microsoft® Direct3D® doesn't transform your vertices with the world, view, or projection matrices, nor does it perform any lighting calculations. It assumes that your application has taken care of these steps. This fact makes transformed and lit vertices common when porting existing 3-D applications to Direct3D. In short, Direct3D does not modify transformed and lit vertices at all. It passes them directly to the driver to be rasterized.

The vertex format flags associated with untransformed vertices and lighting (D3DFVF_XYZ and D3DFVF_NORMAL) are not allowed if D3DFVF_XYZRHW is present. For more about flag dependencies and exclusions, see the description for each of the Flexible Vertex Format Flags.

The system requires that the vertex position you specify be already transformed. The x and y values must be in screen coordinates, and z must be the depth value of the pixel to be used in the z-buffer. Z values can range from 0.0 to 1.0, where 0.0 is the closest possible position to the user, and 1.0 is the farthest position still visible within the viewing area. Immediately following the position, transformed and lit vertices must include a reciprocal of homogeneous W (RHW) value. RHW is the reciprocal of the W coordinate from the homogeneous point (x,y,z,w) at which the vertex exists in projection space. This value often works out to be the distance from the eyepoint to the vertex, taken along the z-axis.

Other than the position and RHW requirements, this vertex format is similar to an untransformed and lit vertex. To recap:

  • The system doesn't do any lighting calculations with this format, so it doesn't need a vertex normal.
  • You can specify a diffuse or specular color. If you don't, the system uses 0x0 for specular color and 0xFFFFFFFF for diffuse color.
  • You can use up to eight sets of texture coordinates, or none at all.

When you define your own vertex format, remember which vertex components your application needs, and make sure they appear in the required order by declaring a properly ordered structure. The following code example declares a valid transformed and lit vertex, with diffuse and specular vertex colors, and one set of texture coordinates.

'
' The vertex format description for this vertex would be
' (D3DFVF_XYZRHW Or D3DFVF_DIFFUSE Or D3DFVF_SPECULAR Or D3DFVF_TEX1)
'
Type TRANSLITVERTEX
    x As Single       ' screen position
    y As Single
    z As Single       ' Z-buffer depth
    rhw As Single     ' reciprocal homogeneous W
    Diffuse As Long   ' diffuse color
    Specular As Long  ' specular color
    tu1 As Single     ' texture coordinates
    tv1 As Single
End Type

The vertex description for the preceding structure would be a combination of the D3DFVF_XYZRHW, D3DFVF_DIFFUSE, D3DFVF_SPECULAR, and D3DFVF_TEX1 flexible vertex format flags.

For more information, see Vertex Formats.


Transformed and Lit Vertex Functionality

Vertex data specified with a flexible vertex format (FVF) code has the property of being either transformed or nontransformed. The terminology used for FVF-specified transformed vertices is TL (transformed and lit) vertices. Microsoft® Direct3D® continues to support TL vertex data, as in previous releases. However, TL vertices are subject to some conditions that are not applicable to nontransformed vertices.

TL vertex data is possible only for vertices specified by an FVF code, and it is not valid as input for a programmable vertex shader. Programmable vertex shaders have the flexibility to take various forms of transformed vertex data, but this is different from FVF-TL vertex data because the interpretation is part of the shader, not a property of the vertex data. Because it is defined by an FVF code, TL vertex data is also inherently single stream.

TL vertex data is not guaranteed to be clipped by Direct3D, thus it is required that TL vertex primitives be clipped prior to sending them to Direct3D for rendering. The x and y values are required to be clipped to the viewport, or, if available, the device guardband. The z values for TL vertices are required to be between 0. and 1, inclusive. It is also required that the RHW values be within the range [0 < 1/D3DCAPS8.MaxVertexW]. The RHW requirement is to guarantee that the w values are within the supported range of the hardware rasterization device. Note that the w, and RHW, range of vertices resulting from a perspective projection transformation can be modified by applying a scale to all values in the projection matrix.

Note If D3DPMISCCAPS_CLIPTLVERTS is set, then the device clips post-transformed vertex data to the z and (x, y) viewport limits. Clipping to user-defined clip planes is not supported for post-transformed vertex data. If the D3DPMISCCAPS_CLIPTLVERTS capability is not set, then the application is required to clip these primitives to the z limit and at least to the guardband extent in x and y. On the other hand, clipping for pre-transformed vertices is fully supported in both drawing and vertex processing calls to a destination vertex buffer followed by another drawing call. This includes user-defined clip planes as well as the z and (x, y) viewport limits.

TL vertex data is always passed directly to the driver for rendering. When using vertex buffers with TL vertex data, there can be significant performance advantages to having the driver allocate these vertex buffers in AGP or video memory. Note that the allocation of a TL vertex buffer may be driver-allocated even when non-TL vertex data —either FVF or non-FVF—is not allowed to be driver-allocated, as would be the case when running on a hardware device that does not support transformation and lighting.

For more information, see Transformed and Lit Vertices.


Flexible Vertex Formats and Vertex Shaders

Microsoft® Direct3D® has a simplified programming model for using the fixed function vertex processing pipeline with a single input stream, providing functionality very similar to that of previous DirectX releases. In this case, the vertex shader consists of a flexible vertex format (FVF) code that is passed in place of a vertex shader handle when setting the current vertex shader. The handle space for vertex shaders is managed by the run-time library so that handles that are valid FVF codes are reserved for this usage.

Setting an FVF code as the current vertex shader causes the vertex processing to load from stream zero only, and to interpret the vertex elements as defined in the FVF code.

The following code example illustrates how to use an FVF code as a vertex shader in your C++ application.

First, define a structure for your custom vertex type and initialize the vertices. In this case, three vertices are initialized for rendering a triangle.

' This code example assumes that d3dDeviceis a valid reference
' to a Direct3DDevice8 object.

Private Type CUSTOMVERTEX
    x As Single         'x in screen space
    y As Single         'y in screen space
    z  As Single        'Normalized z
    rhw As Single       'Normalized z rhw
    color As Long       'Vertex color
End Type

Const D3DFVF_CUSTOMVERTEX = (D3DFVF_XYZRHW Or D3DFVF_DIFFUSE)

Dim Vertices(2) As CUSTOMVERTEX
Dim VertexSizeInBytes As Long

VertexSizeInBytes = Len(Vertices(0))

With Vertices(0): .x = 150: .y =  50: .z = 0.5: .rhw = 1: .color = &HFFFF0000: End With
With Vertices(1): .x = 250: .y = 250: .z = 0.5: .rhw = 1: .color = &HFF00FF00: End With
With Vertices(2): .x =  50: .y = 250: .z = 0.5: .rhw = 1: .color = &HFF00FFFF: End With

Then, render the primitive using stream zero.

sizeOfVertex = Len(v)
d3dDevice.SetStreamSource 0, g_VB, sizeOfVertex
d3dDevice.SetVertexShader D3DFVF_CUSTOMVERTEX
d3dDevice.DrawPrimitive D3DPT_TRIANGLELIST, 0, 1

For more information, see Vertex Shaders.


Legacy FVF Format

To use legacy FVF formats, use an FVF instead of a handle when calling the Direct3DDevice8.SetVertexShader method as shown in the code example below.

Call m_D3DDevice.SetVertexShader(CUSTOM_FVF)

This following topics cover legacy FVF format types.

  • Vertex Legacy Type
  • LVertex Legacy Type
  • TLVertex Legacy Type


Vertex Legacy Type

This topic shows the steps necessary to initialize and use vertices that have a position, a normal, and texture coordinates.

The first step is to define the custom vertex type and FVF as shown in the code example below.

Private Type Vertex
    x As Single
    y As Single
    z As Single
    nx As Single
    ny As Single
    nz As Single
    tu As Single
    tv As Single
End Type

Const VertexFVF = (D3DFVF_XYZ Or D3DFVF_NORMAL Or D3DFVF_TEX1)

The next step is to create a vertex buffer with enough room for four vertices by using the Direct3DDevice8.CreateVertexBuffer method as shown in the code example below.

Set BigSquareVB = m_D3DDevice.CreateVertexBuffer( _
                                  4*len(Vertex), VertexFVF, _
                                  D3DUSAGE_WRITEONLY, _
                                  D3DPOOL_DEFAULT)

The next step is to manipulate the values for each vertex as shown in the code example below.

Dim v(4) As Vertex
Call BigSquareVB.Lock(0, 0, v(), 0)

v(0).x  = 0.0: v(0).y  = 10.0: v(0).z  = 10.0
v(0).nx = 0.0: v(0).ny = 1.0: v(0).nz = 0.0
v(0).tu = 0.0: v(0).tv = 0.0

v(1).x  = 0.0: v(1).y  = 0.0:  v(1).z  = 10.0
v(1).nx = 0.0: v(1).ny = 1.0:  v(1).nz = 0.0
v(1).tu = 0.0: v(1).tv = 0.0

v(2).x  = 10.0: v(2).y  = 10.0: v(2).z  = 10.0
v(2).nx = 0.0: v(2).ny = 1.0:  v(2).nz = 0.0
v(2).tu = 0.0: v(2).tv = 0.0

v(3).x  = 0.0: v(3).y  = 10.0: v(3).z = 10.0
v(3).nx = 0.0: v(3).ny = 1.0: v(3).nz = 0.0
v(3).tu = 0.0: v(3).tv = 0.0

BigSquareVB.Unlock

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.

Call m_D3DDevice.SetVertexShader(VertexFVF)
Call m_D3DDevice.SetStreamSource(0, BigSquareVB, 4*len(Vertex))
Call m_D3DDevice.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0 ,2)

Passing an FVF to the Direct3DDevice8.SetVertexShader method tells Direct3D that a legacy FVF is being used and that stream 0 is the only valid stream.


LVertex Legacy Type

This topic shows the steps necessary to initialize and use vertices that have a position, diffuse color, specular color, and texture coordinates.

The first step is to define the custom vertex type and FVF as shown in the code example below.

Private Type LVertex
    x As Single
    y As Single
    z As Single
    diffuse As Long
    specular As Long
    tu As Single
    tv As Single
End Type

Const VertexFVF = (D3DFVF_XYZ Or D3DFVF_DIFFUSE Or _
                   D3DFVF_SPECULAR Or D3DFVF_TEX1)

The next step is to create a vertex with enough room for four vertices buffer by using the Direct3DDevice8.CreateVertexBuffer method as shown in the code example below.

Set BigSquareVB = m_D3DDevice.CreateVertexBuffer( _
                                  4*len(LVertex), VertexFVF, _
                                  D3DUSAGE_WRITEONLY, _
                                  D3DPOOL_DEFAULT)

The next step is to manipulate the values for each vertex as shown in the code example below.

Dim v(4) As LVertex
Call BigSquareVB.Lock(0, 0, v(), 0)

v(0).x  = 0.0: v(0).y  = 10.0: v(0).z  = 10.0
v(0).diffuse = &HFFFF0000;
v(0).specular = &HFF00FF00;
v(0).tu = 0.0: v(0).tv = 0.0

v(1).x  = 0.0: v(1).y  = 0.0:  v(1).z  = 10.0
v(1).diffuse  = &HFF00FF00;
v(1).specular = &HFF00FFFF;
v(1).tu = 0.0: v(1).tv = 0.0

v(2).x  = 10.0: v(2).y  = 10.0: v(2).z  = 10.0
v(2).diffuse  = &HFFFF00FF;
v(2).specular = &HFF000000;
v(2).tu = 0.0: v(2).tv = 0.0

v(3).x  = 0.0: v(3).y  = 10.0: v(3).z = 10.0
v(3).diffuse  = &HFFFFFF00;
v(3).specular = &HFFFF0000;
v(3).tu = 0.0: v(3).tv = 0.0

BigSquareVB.Unlock

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.

Call m_D3DDevice.SetVertexShader(VertexFVF)
Call m_D3DDevice.SetStreamSource(0, BigSquareVB, 4*len(LVertex))
Call m_D3DDevice.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0 ,2)

Passing an FVF to the Direct3DDevice8.SetVertexShader method tells Direct3D that a legacy FVF is being used and that stream 0 is the only valid stream.


TLVertex Legacy Type

The topic shows the steps necessary to initialize and use vertices that have a transformed position, diffuse color, specular color, and texture coordinates.

The first step is to define the custom vertex type and FVF as shown in the code example below.

Private Type TLVertex
    x As Single
    y As Single
    z As Single
    rhw As Single
    diffuse As Long
    specular As Long
    tu As Single
    tv As Single
End Type

Const VertexFVF = (D3DFVF_XYZRHW Or D3DFVF_DIFFUSE Or _
                   D3DFVF_SPECULAR Or D3DFVF_TEX1)

The next step is to create a vertex buffer with enough room for four vertices by using the Direct3DDevice8.CreateVertexBuffer method as shown in the code example below.

Set BigSquareVB = m_D3DDevice.CreateVertexBuffer( _
                                  4*len(TLVertex), VertexFVF, _
                                  D3DUSAGE_WRITEONLY, D3DPOOL_DEFAULT)

The next step is to manipulate the values for each vertex as shown in the code example below.

Dim v(4) As TLVertex
Call BigSquareVB.Lock(0, 0, v(), 0)

v(0).x  = 0.0: v(0).y  = 10.0: v(0).z  = 10.0: v(0).rhw = 1.0
v(0).diffuse = &HFFFF0000;
v(0).specular = &HFF00FF00;
v(0).tu = 0.0: v(0).tv = 0.0

v(1).x  = 0.0: v(1).y  = 0.0:  v(1).z  = 10.0: v(1).rhw = 1.0
v(1).diffuse  = &HFF00FF00;
v(1).specular = &HFF00FFFF;
v(1).tu = 0.0: v(1).tv = 0.0

v(2).x  = 10.0: v(2).y  = 10.0: v(2).z  = 10.0: v(2).rhw = 1.0
v(2).diffuse  = &HFFFF00FF;
v(2).specular = &HFF000000;
v(2).tu = 0.0: v(2).tv = 0.0

v(3).x  = 0.0: v(3).y  = 10.0: v(3).z = 10.0: v(3).rhw = 1.0
v(3).diffuse  = &HFFFFFF00;
v(3).specular = &HFFFF0000;
v(3).tu = 0.0: v(3).tv = 0.0

BigSquareVB.Unlock

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.

Call m_D3DDevice.SetVertexShader(VertexFVF)
Call m_D3DDevice.SetStreamSource(0, BigSquareVB, 4*len(TLVertex))
Call m_D3DDevice.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0 ,2)

Passing an FVF to the Direct3DDevice8.SetVertexShader method tells Direct3D that a legacy FVF is being used and that stream 0 is the only valid stream.


Programmable Vertex and Pixel Processing

Microsoft® DirectX® 8.x features a new kind of graphics pipeline, featuring a high degree of programmability. The following diagram illustrates the major components and data flow in the programmable vertex and pixel pipeline. The transformation and lighting engine and DirectX 6.0 and 7.0 multitexturing modules have been replaced in the programmable pipeline by vertex and pixel shaders.

The first new part of the pipeline is the high-order primitive module, which works to tessellate high-order primitives such as bézier and B-splines. The vertex shader is a programmable module used to execute geometric operations on the vertex data. The vertex shader can perform a variety of functions which includes standard transformation and lighting. The pixel shader module is a programmable pixel processor. Pixel shaders control the color and alpha blending operations and the texture addressing operations.

For general information on programmable shaders, see Introduction to Procedural Shaders.

For information on how the Microsoft Direct3D® pipeline for DirectX 8.x compares to previous versions, see Integration of Vertex Shaders into the Geometry Pipeline.

For information on the nonprogrammable sections of the pipeline, which have remained unchanged from DirectX 6.0 and 7.0, see Viewports and Clipping.


Introduction to Procedural Shaders

In Microsoft® Direct3D® procedural models are used for specifying the behavior of the vertex transformation and lighting pipeline and the pixel texture blending pipeline. There are many advantages to a program model-based syntax for specifying the behavior of the hardware.

First, a procedural model allows a more general syntax for specifying common operations. Fixed-function, as opposed to programmable, APIs must define modes, flags, and so on for an increasing number of operations that need to be expressed. Further, with the increasing power of the hardware—more colors, more textures, more vertex streams, an so on—the token space for the operations multiplied by the data inputs becomes complex. A programmability model, on the other hand, enables even simple operations such as getting the right color and right texture into the right part of the lighting model in a more direct fashion. You do not have to search through all the possible modes; you just have to learn the machine architecture and specify the desired algorithm to be performed.

For example, the following well-known features can be supported.

  • Basic geometry transformations
  • Simple lighting models
  • Vertex blending for skinning
  • Vertex morphing (tweening)
  • Texture transforms
  • Texture generation
  • Environment mapping

Second, a procedural model provides an easy mechanism for developing new operations. There are many operations that developers find they need that are not supported in current APIs. In most cases, this is not due to limitations in the capabilities of the hardware but rather to restrictions in the APIs. In general, these operations are also simpler and therefore faster than trying to extract the same behavior by contorting a fixed function API to an extent beyond its designer's expectations.

Examples of new features expected to be commonly implemented include the following:

  • Matrix Palette Skinning. Character animation with 8-10 bones per mesh.
  • Anisotropic Lighting. Lighting that currently can be done only at the cost of textures for look-up tables.
  • Membrane Shaders. Shaders for balloons, skin, and so on (1/cos(eye DOT normal).
  • Kubelka-Munk Shaders. Shaders that take into account light that penetrates the surface.
  • Procedural Geometry. Compositing meshes with procedural ones (spheres) to simulate muscles moving under the skin.
  • Displacement Mapping. Modifying a mesh with a wave pattern or hump that can be tiled/repeated.

Third, a procedural model provides for scalability and evolvability. Hardware capabilities are continuing to evolve rapidly, and programmatic representations can help adapt the API because they scale very well. New features and capabilities can be easily exposed in an incremental way by the following operations.

  • Adding new instructions
  • Adding new data inputs
  • Adding new capabilities from the fixed-function to the programmable portion of the pipeline

Code is the representation that has the best scaling properties for representing complexity. Further, the amount of code that must change inside Direct3D is very small for new features added to the programmable shaders.

Fourth, a procedural model offers familiarity. Software developers understand programming better than they do hardware. An API that truly caters to software developers should map hardware functionality into a code paradigm.

Fifth, a procedural model follows in the footsteps of a photo-real rendering heritage. There has been a tradition of using programmable shaders in high-end photo-real rendering for many years. In general, this area is unconstrained by performance, so programmable shaders represent the ultimate no-compromise goal for rendering technologies.

Lastly, a procedural model enables direct mapping to the hardware. Most current 3-D hardware, at the vertex processing stage at least, is actually fairly programmable. The programmability through the API enables the application to map directly to this hardware. This enables an you to manage the hardware resources according to their requirements. With a limited set of registers or instructions that can be executed, it is difficult to make a fixed-function implementation that can have all its features enabled independently. If you turn on too many features that require a shared resource, they can stop working in unexpected ways. The programmable API model follows in the DirectX tradition of eliminating this problem by letting the application developer talk directly to the hardware, making any such limitations transparent.


Integration of Vertex Shaders into the Geometry Pipeline

When in operation, a programmable vertex shader replaces the transformation and lighting module in the Microsoft® Direct3D® geometry pipeline. In effect, state information regarding transformation and lighting operations are ignored. However, when the vertex shader is disabled and fixed function processing is returned, all current state settings apply.

Any tessellation of high-order primitives should be done before execution of the vertex shader. 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. Because no semantic information is normally provided before the shader, a special token is used to identify which input stream component represents the base position relative to which all other components are interpolated. No noninterpolable data channels are supported.

On output, the vertex shader must generate vertex positions in homogeneous clip space. Additional data that can be generated includes texture coordinates, colors, fog factors and so on.

The standard graphics pipeline processes the vertices output by the shader, including the following tasks.

  • Primitive assembly
  • Clipping against the frustum and user clipping planes
  • Homogeneous divide
  • Viewport scaling
  • Backface and viewport culling
  • Triangle setup
  • Rasterization

Note that the clipping space for DirectX 8.x vertex shaders is the same as for DirectX 7.0 and DirectX 8.x fixed function vertex processing. For details, see Clipping Volumes.

Programmable geometry is a mode within the Direct3D application programming interface (API). When it is enabled, it partially replaces the vertex pipeline. When it is disabled, the API has normal control—operating as in DirectX 6.0 and 7.0. Execution of vertex shaders does not change the internal Direct3D state, and no Direct3D state is available for shaders.

Calling Direct3DDevice8.CreateVertexShader with the FunctionTokenArray parameter equal to ByVal 0, is used to create a shader for the fixed-function pipeline. When FunctionTokenArray is not ByVal 0, the shader is programmable. A call to Direct3DDevice8.SetVertexShader sets the current active shader, which defines whether the rendering pipeline should use programmable or fixed-function vertex processing.


Programmable Stream Model

This following sections cover shaders that can be used for the programmable stream model.

  • ColorVertex Shader
  • SingleTexture Shader
  • MultiTexture Shader


ColorVertex Shader

This topic shows the steps necessary to initialize and use a simple vertex shader that uses a position and a diffuse color.

The first step is to declare the structures that hold the position and color as shown in the code example below.

Private Type XYZBuffer
    x As Single
    y As Single
    z As Single
End Type

Private Type ColBuffer
    color As Long
End Type

The next step is to create a vertex shader declaration as shown in the code below.

Dim decl(5) As Long

decl(0) = D3DVSD_STREAM(0)
decl(1) = D3DVSD_REG(D3DVSDE_POSITION, D3DVSDT_FLOAT3)
decl(2) = D3DVSD_STREAM(1)
decl(3) = D3DVSD_REG(D3DVSDE_DIFFUSE, D3DVSDT_UBYTE)
decl(4) = D3DVSD_END()

The next step is to call the Direct3DDevice8.CreateVertexShader method to create the vertex shader.

Call m_D3DDevice.CreateVertexShader(decl, ByVal 0, vShader, 0)

Passing ByVal 0 to the second parameter of CreateVertexShader tells Direct3D that this vertex shader will use a fixed function pipeline.

After creating the vertex buffer and vertex shader, they are ready to use. The code example below shows how to set the vertex shader, set the stream source, and then draw a triangle list that uses the new vertex shader.

Call m_D3DDevice.SetVertexShader(vShader)
Call m_D3DDevice.SetStreamSource(0, xyzbuf, len(XYZBuffer))
Call m_D3DDevice.SetStreamSource(1, colbuf, len(ColBuffer))
Call m_D3DDevice.SetIndices(IB, 0)
Call m_D3DDevice.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, max - min + 1, 0, count / 3)


SingleTexture Shader

This topic shows the steps necessary to initialize and use a simple vertex shader that uses a position and texture coordinates.

The first step is to declare the structures that hold the position and color as shown in the code example below.

Private Type XYZBuffer
    x As Single
    y As Single
    z As Single
End Type

Private Type Tex0Buffer
    tu As Single
    tv As Single
End Type

The next step is to create a vertex shader declaration as shown in the code below.

Dim decl(5) As Long

decl(0) = D3DVSD_STREAM(0)
decl(1) = D3DVSD_REG(D3DVSDE_POSITION, D3DVSDT_FLOAT3)
decl(2) = D3DVSD_STREAM(1)
decl(3) = D3DVSD_REG(D3DVSDE_TEXCOORD0, D3DVSDT_FLOAT2)
decl(4) = D3DVSD_END()

The next step is to call the Direct3DDevice8.CreateVertexShader method to create the vertex shader.

Call m_D3DDevice.CreateVertexShader( decl, ByVal 0, vShader, 0)

Passing ByVal 0 to the second parameter of CreateVertexShader tells Direct3D that this vertex shader will use a fixed function pipeline.

After creating the vertex buffer and vertex shader, they are ready to use. The code example below shows how to set the vertex shader, set the stream source, and then draw a triangle list that uses the new vertex shader.

Call m_D3DDevice.SetVertexShader( vShader )
Call m_D3DDevice.SetStreamSource( 0, xyzbuf, len(XYZBuffer))
Call m_D3DDevice.SetStreamSource( 1, tex0buf, len(Tex0Buffer))
Call m_D3DDevice.SetIndices( IB, 0 )
Call m_D3DDevice.DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, max - min + 1, 0, count / 3 )


MultiTexture Shader

This topic shows the steps necessary to initialize and use a simple vertex shader that uses a position and multiple texture coordinates for multiple textures.

The first step is to declare the structures that holds the position and color as shown in the code example below.

Private Type XYZBuffer
    x As Single
    y As Single
    z As Single
End Type

Private Type Tex0Buffer
    tu As Single
    tv As Single
End Type

Private Type Tex1Buffer
    tu2 As Single
    tv2 As Single
End Type

The next step is to create a vertex shader declaration as shown in the code below.

Dim decl(7) As Long

decl(0) = D3DVSD_STREAM(0)
decl(1) = D3DVSD_REG(D3DVSDE_POSITION, D3DVSDT_FLOAT3)
decl(2) = D3DVSD_STREAM(1)
decl(3) = D3DVSD_REG(D3DVSDE_TEXCOORD0, D3DVSDT_FLOAT2)
decl(4) = D3DVSD_STREAM(2)
decl(5) = D3DVSD_REG(D3DVSDE_TEXCOORD1, D3DVSDT_FLOAT2)
decl(6) = D3DVSD_END()

The next step is to call the Direct3DDevice8.CreateVertexShader method to create the vertex shader.

Call m_D3DDevice.CreateVertexShader( decl, ByVal 0, vShader, 0)

Passing ByVal 0 to the second parameter of CreateVertexShader tells Direct3D that this vertex shader will use a fixed function pipeline.

After creating the vertex buffer and vertex shader, they are ready to use. The code example below shows how to set the vertex shader, set the stream source, and then draw a triangle list that uses the new vertex shader.

Call m_D3DDevice.SetVertexShader(vShader)
Call m_D3DDevice.SetStreamSource(0, xyzbuf, len(XYZBuffer))
Call m_D3DDevice.SetStreamSource(1, tex0buf, len(Tex0Buffer))
Call m_D3DDevice.SetStreamSource(2, tex0buf, len(Tex1Buffer))
Call m_D3DDevice.SetIndices(IB, 0)
Call m_D3DDevice.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, max - min + 1, 0, count / 3)


Device-Supported Primitive Types

Microsoft® Direct3D® devices can create and manipulate the following types of primitives.

  • Point Lists
  • Line Lists
  • Line Strips
  • Triangle Lists
  • Triangle Strips
  • Triangle Fans

You can render primitive types from a Microsoft Visual Basic® application with any of the rendering methods of the Direct3DDevice8 class.

Note that you cannot render point lists with the indexed-primitive rendering methods.


Point Lists

A point list is a collection of vertices that are rendered as isolated points. Your application can use them in 3-D 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.

Private Type CUSTOMVERTEX
    x As Single
    y As Single
    z As Single
End Type

Dim Vertices(5) As CUSTOMVERTEX
With Vertices(0): .x = -5.0: .y = -5.0: .z = 0.0: End With
With Vertices(1): .x =  0.0: .y =  5.0: .z = 0.0: End With
With Vertices(2): .x =  5.0: .y = -5.0: .z = 0.0: End With
With Vertices(3): .x = 10.0: .y =  5.0: .z = 0.0: End With
With Vertices(4): .x = 15.0: .y = -5.0: .z = 0.0: End With
With Vertices(5): .x = 20.0: .y =  5.0: .z = 0.0: End With


Line Lists

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 3-D scene. Applications create a line list by filling an array of vertices, and 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.

Private Type CUSTOMVERTEX
    x As Single
    y As Single
    z As Single
End Type

Dim Vertices(5) As CUSTOMVERTEX
With Vertices(0): .x = -5.0: .y = -5.0: .z = 0.0: End With
With Vertices(1): .x =  0.0: .y =  5.0: .z = 0.0: End With
With Vertices(2): .x =  5.0: .y = -5.0: .z = 0.0: End With
With Vertices(3): .x = 10.0: .y =  5.0: .z = 0.0: End With
With Vertices(4): .x = 15.0: .y = -5.0: .z = 0.0: End With
With Vertices(5): .x = 20.0: .y =  5.0: .z = 0.0: End With


Line Strips

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.

Private Type CUSTOMVERTEX
    x As Single
    y As Single
    z As Single
End Type

Dim Vertices(5) As CUSTOMVERTEX
With Vertices(0): .x = -5.0: .y = -5.0: .z = 0.0: End With
With Vertices(1): .x =  0.0: .y =  5.0: .z = 0.0: End With
With Vertices(2): .x =  5.0: .y = -5.0: .z = 0.0: End With
With Vertices(3): .x = 10.0: .y =  5.0: .z = 0.0: End With
With Vertices(4): .x = 15.0: .y = -5.0: .z = 0.0: End With
With Vertices(5): .x = 20.0: .y =  5.0: .z = 0.0: End With


Triangle Lists

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. 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 3-D 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.

The following illustration depicts a rendered triangle list.

The following code shows how to create vertices for this triangle list.

Private Type CUSTOMVERTEX
    x As Single
    y As Single
    z As Single
End Type

Dim Vertices(5) As CUSTOMVERTEX
With Vertices(0): .x = -5.0: .y = -5.0: .z = 0.0: End With
With Vertices(1): .x =  0.0: .y =  5.0: .z = 0.0: End With
With Vertices(2): .x =  5.0: .y = -5.0: .z = 0.0: End With
With Vertices(3): .x = 10.0: .y =  5.0: .z = 0.0: End With
With Vertices(4): .x = 15.0: .y = -5.0: .z = 0.0: End With
With Vertices(5): .x = 20.0: .y =  5.0: .z = 0.0: End With


Triangle Strips

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. When flat shading is enabled, the system shades a triangle with the color from its first vertex.

Most objects in 3-D 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.

The following code shows how to create vertices for this triangle strip.

Private Type CUSTOMVERTEX
    x As Single
    y As Single
    z As Single
End Type

Dim Vertices(5) As CUSTOMVERTEX
With Vertices(0): .x = -5.0: .y = -5.0: .z = 0.0: End With
With Vertices(1): .x =  0.0: .y =  5.0: .z = 0.0: End With
With Vertices(2): .x =  5.0: .y = -5.0: .z = 0.0: End With
With Vertices(3): .x = 10.0: .y =  5.0: .z = 0.0: End With
With Vertices(4): .x = 15.0: .y = -5.0: .z = 0.0: End With
With Vertices(5): .x = 20.0: .y =  5.0: .z = 0.0: End With


Triangle Fans

A triangle fan is similar to a triangle strip, except that all the triangles share one vertex, as 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 a triangle with the color from its second vertex.

This illustration depicts a rendered triangle fan.

The following code shows how to create vertices for this triangle fan.

Private Type CUSTOMVERTEX
    x As Single
    y As Single
    z As Single
End Type

Dim Vertices(5) As CUSTOMVERTEX
With Vertices(0): .x =  0.0: .y =  0.0: .z = 0.0: End With
With Vertices(1): .x = -5.0: .y =  5.0: .z = 0.0: End With
With Vertices(2): .x = -3.0: .y =  7.0: .z = 0.0: End With
With Vertices(3): .x =  0.0: .y = 10.0: .z = 0.0: End With
With Vertices(4): .x =  3.0: .y =  7.0: .z = 0.0: End With
With Vertices(5): .x =  5.0: .y =  5.0: .z = 0.0: End With


Transforms

Transformations are used to convert object geoemtry from one coordinate space to another. The most common transformations are done using matrices. A matrix is an essential tool for holding the transformation values and applying them to the data. The topics below introduce matrices, and explain how to use them to generate the world, view and projection transformations.

  • Matrices
  • World Transformation

    Convert from world coordinates to view coordinates

  • View Transformation

    Convert from view coordinates to projection coordinates

  • Projection Transformation

    Convert from projection coordinates to screen coordinates


Matrices

Microsoft® Direct3D® uses matrices to perform 3-D transformations. This section explains how matrices create 3-D transformations, describes some common uses for transformations, and details how you can combine matrices to produce a single matrix that encompasses multiple transformations. Information is divided into the following topics.

  • 3-D Transformations
  • Translation and Scaling
  • Rotation
  • Matrix Concatenation


3-D Transformations

In applications that work with 3-D graphics, you can use geometrical transformations 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 into another point by using a 4×4 matrix. In the following example, a matrix is reinterprets the point (x, y, z), producing the new point (x', y', z').

Perform the following operations on (x, y, z) and the matrix to produce the point (x', y', z').

The most common transformations are translation, rotation, and scaling. You can combine the matrices that produce these effects into a single matrix to calculate several transformations at once. For example, you can build a single matrix to translate and rotate a series of points. For more information, see Matrix Concatenation.

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 Microsoft® Visual Basic®, Microsoft Direct3D® uses matrices declared as a two-dimensional array, using the D3DMATRIX type. The following example shows how to initialize a variable of type D3DMATRIX to act as a uniform scaling matrix.

' In this example, s is a variable of type Single.

Dim ScaleMatrix As D3DMATRIX

    With ScaleMatrix
        .m11 = s
        .m22 = s
        .m33 = s
        .m44 = 1
    End With


Translation and Scaling

Translation

The following transformation translates the point (x, y, z) to a new point (x', y', z').

You can create a translation matrix by hand in Microsoft® Visual Basic®. The following example shows the source code for a function that creates a matrix to translate vertices.

Sub TranslateMatrix(m As D3DMATRIX, v As D3DVECTOR)
    D3DXMatrixIdentity m  ' Implemented by Direct3DX.
    m.m41 = v.x
    m.m42 = v.y
    m.m43 = v.z
End Sub

For convenience, the Direct3DX utility library supplies the D3DXMatrixTranslation function.

Scaling

The following transformation scales the point (x, y, z) by arbitrary values in the x-, y-, and z-directions to a new point (x', y', z').


Rotation

The transformations described here are for left-handed coordinate systems, and so may be different from transformation matrices that you have seen elsewhere. For more information, see 3-D Coordinate Systems.

The following transformation rotates the point (x, y, z) around the x-axis, producing a new point (x', y', z').

The following transformation rotates the point around the y-axis.

The following transformation rotates the point around the z-axis.

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 Microsoft® Visual Basic® application, use the D3DXMatrixRotationX, D3DXMatrixRotationY, and D3DXMatrixRotationZ functions supplied by the Direct3DX utility library to create rotation matrices.

If you manually create a matrix for rotation about an axis—in this case, the x-axis—the source code looks something like the following:

Sub CreateXRotation(ret As D3DMATRIX, rads As Single)
    Dim cosine As Single
    Dim sine As Single
    cosine = Cos(rads)
    sine = Sin(rads)

    D3DXMatrixIdentity ret  ' Implemented by Direct3DX.

    ret.m22 = cosine
    ret.m23 = sine
    ret.m32 = -sine
    ret.m33 = cosine
End Sub


Matrix Concatenation

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.

In this formula, C is the composite matrix being created, and M1 through Mn are the individual transformations that matrix C contains. 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 transformation matrix is shown the following example. Imagine that you are creating the world transformation 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 Transformation

The discussion of the world transformation introduces basic concepts and provides details on how to set up a world transformation matrix in a Microsoft® Direct3D® application.

What Is a World Transformation?

A world transformation 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 transformation 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 transformation can include any combination of translations, rotations, and scalings. For a discussion of the mathematics of transformations, see 3-D Transformations.

Setting Up a World Matrix

As with any other transformation, you create the world transformation by concatenating a series of transformation 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 3-D model class written in Microsoft ® Visual Basic® uses the helper functions included in the Direct3DX 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_sPitch, m_sYaw, and m_sRoll variables are Singles that
' contain the model's orientation in terms of pitch, yaw, and roll
' angles, in radians.
'
Public Function MakeWorldMatrix() As D3DMATRIX
    Dim matWorld As D3DMATRIX   ' World matrix to return.
    Dim matTemp As D3DMATRIX    ' Temp matrix to hold rotations.
    Dim matRot As D3DMATRIX     ' Temp rotation matrix.

    ' Modify matWorld to create a translation matrix.
    D3DXMatrixIdentity matWorld
    matWorld.m41 = m_xPos
    matWorld.m42 = m_yPos
    matWorld.m43 = m_zPos

    D3DXMatrixIdentity matRot ' Sets up the rotation matrix.

    '
    ' Using the left-to-right order of matrix concatenation,
    ' apply the translation to the object's world position
    ' before applying the rotations.
    '

    ' Produce and combine the rotation matrices.
    If (m_sPitch <> 0) Or (m_sYaw <> 0) Or (m_sRoll <> 0) Then
       ' First, pitch.
        D3DXMatrixRotationX matTemp, m_sPitch
        D3DXMatrixMultiply matRot, matRot, matTemp

       ' Then, yaw.
        D3DXMatrixRotationY matTemp, m_sYaw
        D3DXMatrixMultiply matRot, matRot, matTemp

        ' Finally, roll.
        D3DXMatrixRotationZ matTemp, m_sRoll
        D3DXMatrixMultiply matRot, matRot, matTemp

        ' Apply the rotation matrices to the translation already in
        ' matWorld to complete the world matrix.
        D3DXMatrixMultiply matWorld, matRot, matWorld
    End If

    MakeWorldMatrix = matWorld
End Function

After you prepare the world transformation matrix, call the Direct3DDevice8.SetTransform method to set it, specifying the D3DTS_WORLD flag in the first parameter. For more information, see Setting Transformations.

Note Microsoft® 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 expensive. 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 Transformation

This section introduces the basic concepts of the view transformation and provides details on how to set up a view transformation matrix in a Microsoft® Direct3D® application. This information is organized into the following topics.

What Is a View Transformation?

The view transformation 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 Microsoft® 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 the 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.

Another approach involves creating the composite view matrix directly. The D3DXMatrixLookAtLH and D3DXMatrixLookAtRH methods use this technique. This approach uses the camera's world space position and a look-at point in the scene to derive vectors that describe the orientation of the camera space coordinate axes. The camera position is subtracted from the look-at point to produce a vector for the camera's direction vector (vector n). Then the cross product of the vector n and the y-axis of world space is taken and normalized to produce a right vector (vector u). Next, the cross product of the vectors u and n is taken to determine an up vector (vector v). The right (u), up (v), and view-direction (n) vectors describe the orientation of the coordinate axes for camera space in terms of world space. The x, y, and z translation factors are computed by taking the negative of the dot product between the camera position and the u, v, and n vectors.

These values are put into the following matrix to produce the view matrix.

In this matrix, u, v, and n are the up, right, and view-direction vectors, and c is the camera's world space position. This matrix contains all the elements needed to translate and rotate vertices from world space to camera space. After creating this matrix, you can also apply a matrix for rotation around the z-axis to allow the camera to roll.

For information on implementing this technique, see Setting Up a View Matrix.

Setting Up a View Matrix

Microsoft® Visual Basic® applications use the D3DXMatrixLookAtLH and D3DXMatrixLookAtRH helper functions to create a view matrix based on the camera location, a look-at point, and an up vector (usually 0,1,0).

The following example code, written in Visual Basic, shows how you can use the D3DXMatrixLookAtLH function.

    ' This example assumes that g_D3DDevice is a valid reference
    ' to a Direct3DDevice8 object.

    Dim matView As D3DMATRIX

    ' Set the eyepoint five units back along the z-axis
    ' and up three units.
    D3DXMatrixLookAtLH matView, vec3(0#, 3#, -5#), _
                                 vec3(0#, 0#, 0#), _
                                 vec3(0#, 1#, 0#)

    g_D3DDevice.SetTransform D3DTS_VIEW, matView

As with the world transformation, you call the Direct3DDevice8.SetTransform method to set the view transformation, specifying the D3DTS_VIEW flag in the first parameter. See Setting Transformations, for more information.

Performance Optimization Note Microsoft® 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, 20,000 times per frame—is computationally expensive. 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, Direct3D samples rarely employ this optimization.


Projection Transformation

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.

  • What Is the Projection Transformation?
  • Setting Up a Projection Matrix
  • A W-Friendly Projection Matrix


What Is the Projection Transformation?

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 transformation 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 following illustration shows how the perspective transformation 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 transformation, 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 fovh 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 Microsoft® Visual Basic® application, these two dimensions correspond directly to the Width and Height members of the D3DVIEWPORT8 type.

Whatever formula you decide to use, it's important that you set Zn to as large a value as possible, as z-values extremely close to the camera don't vary by much, making depth comparisons using 16-bit z-buffers tricky.

As with the world and view transformations, you call the Direct3DDevice8.SetTransform method to set the projection transformation; for more information, see Setting Transformations.


Setting Up a Projection Matrix

Applications written in Microsoft® Visual Basic® can create a projection matrix as described in the What Is the Projection Transformation? topic. However, the Direct3DX utility library provides the following functions to help you set up your projections matrix.

  • D3DXMatrixPerspectiveLH
  • D3DXMatrixPerspectiveRH
  • D3DXMatrixPerspectiveFovLH
  • D3DXMatrixPerspectiveFovRH
  • D3DXMatrixPerspectiveOffCenterLH
  • D3DXMatrixPerspectiveOffCenterRH

The following Visual Basic code example shows how D3DXMatrixPerspectiveLH is commonly used.

    ' This example assumes that g_D3DDevice is a valid reference
    ' to a Direct3DDevice8 object.

    ' For the projection matrix, set up a perspective transform, which
    ' transforms geometry from 3-D view space to 2-D viewport space,
    ' with a perspective divide that makes objects smaller in the
    ' distance. To build a perspective transform, you need the field
    ' of view (1/4 pi is common), the aspect ratio, and the near and
    ' far clipping planes, which define the distances at which
    ' geometry should be no longer be rendered.

    Dim matProj As D3DMATRIX

    D3DXMatrixPerspectiveFovLH matProj, g_pi / 4, 1, 1, 1000
    g_D3DDevice.SetTransform D3DTS_PROJECTION, matProj

After you create the matrix, you must set it in a call to the Direct3DDevice8.SetTransform method, specifying D3DTRANSFORMSTATE_PROJECTION in the first parameter. For details, see Setting Transformations.


A W-Friendly Projection Matrix

Microsoft® 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 projection matrix recommended in What Is the Projection Transformation? is compliant with w-based calculations.

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

Note 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 the Direct3D transformation pipeline.


Viewports and Clipping

Conceptually, a viewport is a two-dimensional (2-D) rectangle into which a three-dimensional (3-D) scene is projected. In Microsoft® 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.

You use a viewport in Direct3D to specify the following features in your application.

  • The screen-space viewport to which the rendering will be confined.
  • The range of depth values on a render-target surface into which a scene will be rendered (usually 0.0 to 1.0).

This section discusses clipping, the last stage of the geometry pipeline. The discussion is organized into the following topics.

  • Viewport Rectangle
  • The Viewing Frustum
  • Clipping Volumes
  • Viewport Scaling
  • Using Viewports

Direct3D implements clipping by way of a set of viewport parameters set in the device.


Viewport Rectangle

You define the viewport rectangle in a Microsoft® Visual Basic® application by using the D3DVIEWPORT8 type. The D3DVIEWPORT8 type is used with the following viewport manipulation methods offered by the Direct3DDevice8 class.

  • Direct3DDevice8.GetViewport
  • Direct3DDevice8.SetViewport

The D3DVIEWPORT8 type contains four members—x, y, Width, and Height—that define the area of the render-target surface into which a scene will be rendered, called the viewport rectangle.

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, and Height members of the D3DVIEWPORT8 type are screen coordinates relative to the upper-left corner of the render-target surface. The type defines two additional members (MinZ and MaxZ) indicate the depth-ranges into which the scene will be rendered.

Microsoft® 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. In Microsoft DirectX® 8.x, as in previous releases of DirectX, you can adjust for viewport aspect ratio before clipping, during the projection transformation. This task is covered by topics in Projection Transformation.


The Viewing Frustum

A viewing frustum is 3-D 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 What Is the Projection Transformation?


Clipping Volumes

The results of the projection matrix determine the clipping volume in projection space. Microsoft® Direct3D® defines the clipping volume in projection space as:

In the preceding formulas, Xc, Yc, Zc, and Wc 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 and Programmable Vertex Processing.

Direct3D does not clip transformed vertices of a primitive from a vertex buffer unless it comes from Direct3DDevice8.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 (TL-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 rhw and the viewport information. Clipping is then performed. Not all devices are capable of performing this back-transform in order to clip TL-vertices.

The D3DPMISCCAPS_CLIPTLVERTS device capability indicates whether or not the device is capable of clipping TL-Vertices. If this capability is not set, then the application is responsible for clipping the TL-vertices that it intends to send down to the device to be rendered. The device is always capable of clipping TL-Vertices in the software vertex processing mode (either when the device itself is created in the software vertex processing mode or switched to the software vertex processing mode when created as a mixed mode vertex processing device using the D3DRS_SOFTWAREVERTEXPROCESSING renderstate).


Viewport Scaling

The dimensions used in the x, y, Width, and Height members of the D3DVIEWPORT8 type 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.

Microsoft® 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 simply 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. This is performed by way of simple division.


Using Viewports

This section provides details about working with viewports. Information is divided into the following topics.

  • Setting the Viewport Clipping Volume
  • Clearing a Viewport
  • Manually Transforming Vertices


Setting the Viewport Clipping Volume

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.

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.

The following Microsoft® Visual Basic® code creates settings in a D3DVIEWPORT8 type to achieve this.

Dim viewData As D3DVIEWPORT8

With viewData
    .x = 0: .y = 0
    .Width = Width: .Height = Height
    .MinZ = 0#: .MaxZ = 1#
End With

After setting values in the D3DVIEWPORT8 type, apply the viewport parameters to the device by calling its Direct3DDevice8.SetViewport method.

' The d3dDevice variable contains a valid reference to a
' Direct3DDevice8 object.
Call d3dDevice.SetViewport(viewData)

After the call, 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 D3DVIEWPORT8 type and call SetViewport again.


Clearing a Viewport

Clearing the viewport resets the contents of the viewport rectangle on the render-target surface as well as the rectangle in the depth and stencil buffer surfaces, if specified. Typically, you clear the viewport before rendering a new frame to ensure that graphics and other data is ready to accept new rendered objects without displaying artifacts.

The Direct3DDevice8 Microsoft® Visual Basic® class offers the Direct3DDevice8.Clear method to clear the viewport. The method accepts one or more rectangles that define the area or areas on the surfaces being cleared. In cases where the scene being rendered includes motion throughout the entire viewport rectangle—in a first-person perspective game, for example—you might want to clear the entire viewport each frame. In this situation, you set the Count parameter to 1, and the ClearD3DRect parameter to a single-element array of D3DRECT variables, where the first and only element describes a rectangle that covers the entire area of the render-target surface.

The Clear method is flexible, and it provides support for clearing stencil bits within a depth buffer. The Flags parameter accepts three flags that determine how it clears the render target and any associated depth or stencil buffers. If you include the D3DCLEAR_TARGET flag, the method clears the viewport using an arbitrary RGBA color that you provide in the Color parameter (not the material color). If you include the D3DCLEAR_ZBUFFER flag, the method clears the depth buffer to an arbitrary depth you specify in Z:. 0.0 is the closest distance, and 1.0 is the farthest. Including the D3DCLEAR_STENCIL flag causes the method to reset the stencil bits to the value you provide in the Stencil parameter. You can use integers that range from 0 to 2n-1, where n is the stencil buffer bit depth.

In some situations, you might only be rendering 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 an array of rectangles in the ClearD3DRect parameter.


Manually Transforming Vertices

You can use three kinds of vertices in your Microsoft® Direct3D® application. Read Vertex Formats for more details on the vertex formats.

Untransformed and Unlit Vertices
Vertices that your application doesn't light or transform. Although you specify lighting parameters and transformation matrices, Direct3D computes these values.
Untransformed and Lit Vertices
Vertices that your application lights but does not transform.
Transformed and Lit Vertices
Vertices that your application both lights and transforms.

You can change from simple to complex vertex types by using vertex buffers. Vertex buffers are objects used to efficiently contain and process batches of vertices for rapid rendering, and are optimized to exploit processor-specific features. Use the Direct3DDevice8.ProcessVertices method to perform vertex transformations for you. ProcessVertices accepts only untransformed vertices and can optionally light and clip vertices as well. Lighting is performed at the time you call the ProcessVertices methods, but clipping is performed at render time.

After processing the vertices, you can use special rendering methods to render the vertices, or you can access them directly by locking the vertex buffer memory. For more information about using vertex buffers, see Vertex Buffers.


Lights and Materials

Lights are used to illuminate objects in a scene. When lighting is enabled, Microsoft® 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.

Additional information is contained in the following topics:

  • Direct3D Light Model vs. Nature
  • Color Values for Lights and Materials
  • Direct Light vs. Ambient Light
  • Light Properties
  • Using Lights
  • Mathematics of Lighting
  • Materials


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 3-D graphics. Therefore, with speed in mind, the Microsoft® 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.

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. For more information, see Lights and Materials.

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.


Color Values for Lights and Materials

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; for more information, see Material Properties.

Color values for ambient light are different from those used for direct light sources and materials. For more information, see Direct Light vs. Ambient Light.


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.

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 Microsoft® Direct3D®. For more information, see Color Values for Lights and Materials.


Light Properties

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. Microsoft® Direct3D® uses the D3DLIGHT8 type 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.

  • Light Type
  • Light Color
  • Color Vertices
  • Light Position, Range, and Attenuation
  • Light Direction


Light Type

The light type property defines which type of light source you're using. The light type is set by using a value from the CONST_D3DLIGHTTYPE Microsoft Visual Basic® enumeration in the Type member of the light's D3DLIGHT8 type. There are three types of lights in Microsoft® 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, Microsoft® 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 Microsoft® 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 expensive of all lights in Microsoft Direct3D®.

The D3DLIGHT8 Microsoft® Visual Basic® type 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.

  • Spotlight Model

    • This page contains more information about how a spotlight works.


Spotlight Model

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 ammount of light a vertex receives is based on the vertex's location in the inner or outer cones. Microsoft® Direct3D® computes the dot product of the spotlight's direction vector (L) and the vector from the vertex to the light (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.

Next, the system compares this value to the cosine of the spotlight's inner and outer cone angles. In the light's D3DLIGHT8 type, 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, Direct3D 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 Direct3D calculates falloff for the vertex by using the following formula.

In the formula, If is light intensity, after falloff, for the vertex being lit, α is the angle between vectors L and D, φ is half of the outer cone angle, θ is half of the inner cone angle, and p is the spotlight's falloff property Falloff in the D3DLIGHT8 structure. 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 p value corresponds to the Falloff member of the D3DLIGHT8 structure and controls the shape of the falloff curve. The following illustration shows how different Falloff values can affect the falloff curve.

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 Color

Lights in Microsoft® 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.

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. For more information, see Color Values for Lights and Materials.


Color Vertices

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 Direct3DDevice8.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 Position, Range, and Attenuation

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 VB, these are contained in a light's D3DLIGHT8 type.

Position

Light position is described using a D3DVECTOR type in the Position member of the D3DLIGHT8 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.

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.

Attenuation

Attenuation controls how a light's intensity decreases toward the maximum distance specified by the range property. Three D3DLIGHT8 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.


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.

VB applications set the light direction in the Direction member of the light's D3DLIGHT8 structure. The 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.


Using Lights

Setting and Retrieving Light Properties

Your Microsoft Visual Basic® application sets lighting properties by preparing a D3DLIGHT8 type and then calling the Direct3DDevice8.SetLight method. The 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 D3DLIGHT8 type that defines those properties. You can call 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 SetLight method with an index that has never had properties assigned. 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 D3DCAPS8 type 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 code example prepares and sets properties for a white point-light whose emitted light will not attenuate over distance.

'
' For this example, the d3dDevice variable contains a valid reference
' to a Direct3DDevice8 object.
'
Dim LightDesc As D3DLIGHT8
Dim c As D3DCOLORVALUE
Dim vPos As D3DVECTOR

' Use the same color settings for all emitted light color.
With c
    .r = 1#: .g = 1#: .b = 1#
    .a = 1# ' The alpha component isn't used for lights.
End With

With vPos
    .x = 0: .y = 1000: .z = -100
End With

With LightDesc
    .Type = D3DLIGHT_POINT
    .Position = vPos
    .Ambient = c: .diffuse = c: .specular = c
    .Attenuation0 = 1# ' Don't attenuate the light
End With

d3dDevice.SetLight 0, LightDesc

You can update a set of light properties with another call to SetLight at any time. Just specify the index of the set of light properties to update and the address of the D3DLIGHT8 structure that contains the new properties.

A Microsoft® Visual Basic® application retrieves the properties for an existing light source by calling the Direct3DDevice8.GetLight method for the device. When calling the GetLight method, pass in the first parameter the zero-based index of the light source for which the properties will be retrieved, and a variable of type D3DLIGHT8 as the second parameter. The device fills the D3DLIGHT8 type to describe the lighting properties it uses for the light source at that index.

The following code example illustrates this process.

'
' For the purposes of this example, the d3dDevice variable contains
' a valid reference to a Direct3DDevice8 object.
'
Dim lightDesc As D3DLIGHT8

' Get the property information for the first light.
Call d3dDevice.GetLight(0, lightDesc)
If Err.Number <> D3D_OK Then
    ' Code to handle the error goes here.
End If

If you supply an index outside the range of the light sources assigned in the device, the GetLight method fails, and the value of Err.Number is D3DERR_INVALIDCALL.

Enabling and Disabling Lights

Once you assign a set of light properties for a light source in a scene, the light source can be activated by calling the Direct3DDevice8.LightEnable method for the device. New light sources are disabled by default. The 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 1 to enable the light or 0 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.

'
' For the purposes of this example, the d3dDevice variable contains
' a valid reference to Direct3DDevice8 object.
'
On Local Error Resume Next

Call d3dDevice.LightEnable(0, 1)
If Err.Number <> D3D_OK Then
    'Code to handle the error goes here.
End If

Check the MaxActiveLights member of the D3DCAPS8 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 Direct3DDevice8.SetLight, the LightEnable method creates a light source with the properties listed in following table and enables or disables it.

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


Mathematics of Lighting

The Microsoft® 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 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.

Diffuse lighting 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 (3-D) depth. To see how diffuse lighting is calculated in Direct3D, see Diffuse Lighting.

Specular lighting 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.

Emissive lighting is light that is emitted by an object, for example, a glow. To see how emissive lighting is calculated in Direct3D, see Emissive Lighting.

Realistic lighting can be accomplished by applying each of these types of lighting to a 3-D scene. 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.

All lighting computations are made in model space by transforming the light source's position and direction, along with the camera position, to model space using the inverse of the world matrix. As a result, if the world or view matrices introduce non-uniform scaling, the resultant lighting might be inaccurate. To see how lighting transformations are calculated, see Camera Space Transformations.

Diffuse and specular light values can be affected by a given light's attenuation and spotlight characteristics. Terms for both of these are included in the diffuse and specular equations. For more information, see Attenuation and Spotlight Terms.


Ambient Lighting

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. Microsoft® 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 = Mc*[Ga + sum(Lai)]

The parameters are defined in the following table.

Parameter | Default value | Type | Description
Mc | (0,0,0,0) | D3DCOLORVALUE | Material ambient color.
Ga | (0,0,0,0) | D3DCOLORVALUE | Global ambient color.
Lai | (0,0,0,0) | D3DVECTOR | Light ambient color, of the ith light.
sum | N/A | N/A | Summation of the ambient light from the light objects.

The value for Mc is one of three values: one of the two possible vertex colors in a vertex declaration, or the material ambient color. The value is:

  • 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(D3DRENDERSTATE_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.


Diffuse Lighting

After adjusting the light intensity for any attenuation effects, Microsoft® Direct3D® 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. Direct3D 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[Vd*Ld*(N.Ldir)*Atten*Spot]
The parameters are defined in the following table.
Parameter | Default value | Type | Description
sum | N/A | N/A | Summation of each light's diffuse component.
Vd | (0,0,0,0) | D3DCOLORVALUE | Vertex diffuse color.
Ld | (0,0,0,0) | D3DCOLORVALUE | Light diffuse color.
N | N/A | D3DVECTOR | Vertex normal.
Ldir | (0,0,0,0) | D3DCOLORVALUE | Direction vector from object vertex to the light.
Atten | (0,0,0,0) | D3DCOLORVALUE | Light attenuation.
Spot | (0,0,0,0) | D3DVECTOR | Characteristics of the spotlight cone.

The value for Vd is one of three values: one of the two possible vertex colors in a vertex declaration, or the material diffuse color. The value is:

  • 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 Terms

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.


Specular Lighting

Modeling specular reflection requires that the system not only know the direction that 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 the D3DRS_SPECULARENABLE to TRUE.

Specular Lighting is described by the following equation.

Specular Lighting = Vs*sum[Ls*(N.H)P*Atten*Spot]
The parameters are defined in the following table.
Parameter | Default value | Type | Description
Vs | (0,0,0,0) | D3DCOLORVALUE | Vertex specular color.
sum | N/A | N/A | Summation of each light's specular component.
N | N/A | D3DVECTOR | Vertex normal.
H | (0,0,0,0) | D3DCOLORVALUE | Half way vector.
P | (0,0,0,0) | D3DCOLORVALUE | Specular reflection power. Range is -infinity to +infinity
Ls | (0,0,0,0) | D3DCOLORVALUE | Light specular color.
Atten | (0,0,0,0) | D3DCOLORVALUE | Light attenuation.
Spot | (0,0,0,0) | D3DVECTOR | Characteristics of the spotlight cone.

The value for Vc is one of three values: one of the two possible vertex colors in a vertex declaration, or the material specular color. The value is:

  • vertex color1, if SPECULARMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if SPECULARMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material specular color

Note: If either SPECULARMATERIALSOURCE option is used, and the vertex color is not provided, then the material specular color is used.

To calculate the attenuation (Atten) or the spotlight characteristics (Spot), see Attenuation and Spotlight Terms

The halfway vector (H) exists midway between the vector from an object vertex to the light source and the vector from an object vertex and the camera position. Microsoft® 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) where the parameters are defined in the following table:

Parameter | Default value | Type | Description
Cp | (0,0,0,0) | D3DVECTOR | Camera position.
Vp | (0,0,0,0) | D3DVECTOR | Vertex position.
Ldir | (0,0,0,0) | D3DVECTOR | Direction vector from vertex position to the light position.

When D3DRS_LOCALVIEWER is set to TRUE, Direct3D determines the halfway vector by the following formula.

H = norm(norm(- Vp) + Ldir)

Determining the halfway vector in this manner can be computationally intensive. As an alternative, setting D3DRS_LOCALVIEWER to FALSE instructs the system to act as though the viewpoint is infinitely distant on the z-axis. This setting is less computationally intensive, but much less accurate, so it is best used by applications that use orthogonal projection.

Specular components are clamped to be from 0 to 255, after all lights are processed and interpolated separately.


Emissive Lighting

Emissive lighting is described by a single term.

Emissive Lighting = Me

The parameter is defined in the following table.

Parameter | Default value | Type | Description
Me | (0,0,0,0) | D3DCOLORVALUE | Material emissive color.

The value for Me is one of three values: one of the two possible vertex colors in a vertex declaration, or the material emissive color. The value is:

  • 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.


Camera Space Transformations

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 symmetrical.

N = N * (wvMatrix-1)T

The matrix inversion and matrix transpose operate on a 4×4 matrix. The multiply combines the normal with the 3×3 portion of the resulting 4×4 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 * vMatrix)

For the D3DLIGHT_POINT and D3DLIGHT_SPOT the direction to light is computed as follows:

Ldir = norm(Ldir), where the parameters are defined in the following table.

Parameter | Default value | Type | Description
Ldir | (0,0,0,0) | D3DCOLORVALUE | Direction vector from object vertex to the light
V | (0,0,0,0) | D3DVECTOR | Vertex position
wvMatrix | Identity | D3DMATRIX | Composite matrix containing the world and view transforms
N | (0,0,0,0) | D3DVECTOR | Vertex normal
Lp | (0,0,0,0) | D3DVECTOR | Light position
vMatrix | Identity | D3DMATRIX | Matrix containing the view transform


Attenuation and Spotlight Terms

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 Term

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 three equations.

  • 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.
  • Atten = 1/( att0i + att1i*d + att2i*di2).
Parameter | Default value | Type | Description
att0i | (0,0,0,0) | FLOAT | Linear attenuation factor
att1i | (0,0,0,0) | FLOAT | Squared attenuation factor
att2i | (0,0,0,0) | FLOAT | Exponential attenuation factor
di | (0,0,0,0) | FLOAT | Distance from vertex position to light position

The att0, att1, att2 values are specified by the Attenuation0, Attenuation1, and Attenuation2 members of the D3DLIGHT8 structure.

The distance between the light and the vertex position is always positive.
di = ||Ldir||
where:

Parameter | Default value | Type | Description
Ldir | 0.0 | D3DVECTOR | Direction vector from vertex position to the light position

If di is greater than the light's range—the Range member of a D3DLIGHT8 type—Direct3D makes no further attenuation calculations and applies no effects from the light to the vertex.

 The dvAttenuation0, dvAttenuation1, and dvAttenuation2 values are the light's attenuation constants as specified by the members of a light object's D3DLIGHT8 structure. The corresponding structure members are Attenuation0, Attenuation1, and Attenuation2.

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 Attenuation0 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 Term

Parameter | Default value | Type | Description
rho | 0.0 | N/A | Angle
phi | 0.0 | FLOAT | Penumbra angle of spotlight in radians. Range: [thetaI, p)
theta | 0.0 | FLOAT | Umbra angle of spotlight in radians. Range: [0, p)
falloff | 0.0 | FLOAT | Falloff factor. Range: (-infinity, +infinity)

where:

rho = norm(Ldcs).norm(Ldir)
Parameter | Default value | Type | Description
Ldcs | 0.0 | D3DVECTOR | Direction vector from origin to the light position in camera space
Ldir | 0.0 | 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 Model.


Materials

Materials describe how polygons reflect light or appear to emit light in a 3-D scene. Essentially, a material is a set of properties that tell Microsoft® Direct3D® the following things about the polygons it is rendering.

  • How they reflect ambient and diffuse light
  • What their specular highlights look like
  • Whether the polygons appear to emit light

Direct3D applications written in Microsoft® Visual Basic® use the D3DMATERIAL8 type to describe material properties. For more information, see Material Properties.

Setting Material Properties

Microsoft® Direct3D® rendering devices can render with one set of material properties at a time.

In a Microsoft® Visual Basic® application, set the material properties that the system uses by preparing a D3DMATERIAL8 type, then calling the Direct3DDevice8.SetMaterial method.

To prepare the D3DMATERIAL8 type for use, set the property information in the structure to create the desired effect during rendering. The following code example sets up the D3DMATERIAL8 type for a purple material with sharp white specular highlights.

Dim mat As D3DMATERIAL8

' Set the RGBA for diffuse reflection.
mat.diffuse.r = 0.5
mat.diffuse.g = 0#
mat.diffuse.b = 0.5
mat.diffuse.a = 1#

' Set the RGBA for ambient reflection.
mat.ambient.r = 0.5
mat.ambient.g = 0#
mat.ambient.b = 0.5
mat.ambient.a = 1#

' Set the color and sharpness of specular highlights.
mat.specular.r = 1#
mat.specular.g = 1#
mat.specular.b = 1#
mat.specular.a = 1#
mat.power = 50#

' Set the RGBA for emissive color.
mat.Emissive.r = 0#
mat.Emissive.g = 0#
mat.Emissive.b = 0#
mat.Emissive.a = 0#

After preparing the D3DMATERIAL8 type, apply the properties by calling the SetMaterial method of the rendering device. This method accepts the address of a prepared D3DMATERIAL8 type as its only parameter. You can call 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 d3dDevice is
' assumed to contain a valid reference to a Direct3DDevice8
' object.
On Local Error Resume Next

Call d3dDevice.SetMaterial(mat)
If Err.Number <> D3D_OK Then
    ' Code to handle the error goes here.
End If

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 Direct3DDevice8.GetMaterial method for the device. Unlike the Direct3DDevice8.SetMaterial method, GetMaterial doesn't require preparation. The GetMaterial method accepts a variable of type D3DMATERIAL8, and fills it with information describing the current material properties before returning.

' For this example, the d3dDevice variable is assumed to
' contain a valid reference to a Direct3DDevice8 object.
On Local Error Resume Next
Dim mat As D3DMATERIAL8

Call d3dDevice.GetMaterial(mat)
If Err.Number <> D3D_OK Then
    ' Code to handle the error goes here.
End If

For more information about material properties see:

  • Material Properties

Default Material Properties 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.


Material Properties

Material properties detail a material's diffuse reflection, ambient reflection, light emission, and specular highlight characteristics. Microsoft® Direct3D® uses the D3DMATERIAL8 type to carry all material property information. Material properties affect the colors that Direct3D uses to rasterize polygons that use the material. 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—the alpha component of the RGBA color. The material's specular property is described in two parts: color and power. For more information, see Color Values for Lights and Materials.

Diffuse and Ambient Reflection

The Diffuse and Ambient members of the D3DMATERIAL8 type 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 Direct3DDevice8.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 D3DMATERIAL8 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 D3DMATERIAL8 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.


Textures

Textures are a powerful tool in creating realism in computer-generated 3-D images. Microsoft® Direct3D® supports an extensive texturing feature set, providing developers with easy access to advanced texturing techniques. This section discusses the purposes and uses of textures in Direct3D. The information is presented in the following topics.

  • Basic Texturing Concepts
  • Texture Coordinates
  • Texture Resources
  • Texture Filtering
  • Texture Wrapping
  • Compressed Texture Resources
  • Volume Texture Resources
  • Automatic Texture Management
  • Hardware Considerations for Texturing
  • Texture Blending
  • Surfaces
  • Using Dynamic Textures


Basic Texturing Concepts

Early computer-generated 3-D 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 3-D objects realistic visual complexity. In recent years, textures have gained popularity among developers as a tool for enhancing the realism of computer-generated 3-D 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 Microsoft® 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 3-D 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 and Light Mapping with Textures.

If your application creates a hardware abstraction layer (HAL) device or a software device, it can use 8-, 16-, 24-, or 32-bit textures.

Additional information is contained in the following topics.

  • Texture Addressing Modes
  • Texture Dirty Regions
  • Texture Palettes


Texture Addressing Modes

Your Microsoft® Direct3D® application can assign texture coordinates to any vertex of any primitive. For details, see Texture Coordinates. 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. The following topics contain additional details.

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.

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 Direct3DDevice8.SetTextureStageState method. Specify the desired texture stage identifier in the first parameter. Set the second parameter to D3DTSS_ADDRESSU, D3DTSS_ADDRESSV, or D3DTSS_ADDRESSW values to update the u-, v-, or w-addressing modes individually. The third parameter you pass to SetTextureStageState determines which mode is being set. This can be any member of the CONST_D3DTEXTUREADDRESS enumeration.

To retrieve the current texture address mode for a given texture stage, call Direct3DDevice8.GetTextureStageState, using the D3DTSS_ADDRESSU, D3DTSS_ADDRESSV, or D3DTSS_ADDRESSW members of the CONST_D3DTEXTURESTAGESTATETYPE enumeration to 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 D3DCAPS8 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 of D3DCAPS8 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 value 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 on the texture addressing modes is contained in the following topics.

  • Wrap Texture Address Mode
  • Mirror Texture Address Mode
  • Clamp Texture Address Mode
  • Border Color Texture Address Mode


Wrap Texture Address Mode

The wrap texture address mode, identified by the D3DTADDRESS_WRAP member of the CONST_D3DTEXTUREADDRESS enumeration, makes Microsoft® 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.

This is illustrated in the following figure.

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.


Mirror Texture Address Mode

The mirror texture address mode, identified by the D3DTADDRESS_MIRROR member of the CONST_D3DTEXTUREADDRESS enumeration, causes Microsoft® 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.

This is illustrated in the following figure.

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.


Clamp Texture Address Mode

The clamp texture address mode, identified by the D3DTADDRESS_CLAMP member of the CONST_D3DTEXTUREADDRESS enumeration, causes Microsoft® 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 instance, 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

The border color texture address mode, identified by the D3DTADDRESS_BORDER member of the CONST_D3DTEXTUREADDRESS enumeration, causes Microsoft® 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.

Microsoft Visual Basic® applications set the border color by calling Direct3DDevice8.SetTextureStageState. Set the first parameter for the call to the desired texture stage identifier, the second parameter to the D3DTSS_BORDERCOLOR stage state value, and the third parameter to the new RGBA border color.


Texture Dirty Regions

Applications can optimize what subset of a texture is copied by specifying dirty regions on textures. Only those regions marked as dirty are copies by a call to Direct3DDevice8.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 four 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 the texture as a destination in Direct3DDevice8.CopyRects marks the entire texture as dirty.
  • Using the texture as a source in UpdateTexture clears all the dirty regions on the source texture.

Dirty regions are set on the top level of a mipmapped texture, and 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. 2-D textures use dirty rectangle, and volume textures use boxes.

  • Direct3DCubeTexture8.AddDirtyRect
  • Direct3DTexture8.AddDirtyRect
  • Direct3DVolumeTexture8.AddDirtyBox

Passing ByVal 0 for the DirtyRect or DirtyBox 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.

Applications should use D3DLOCK_NO_DIRTY_UPDATE when further information about the true set of regions changed during a lock operation is available. You should note that a lock or copy to only a sublevel—that is, without locking or copying to the top level—of texture 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

Microsoft® Direct3D® 8.x supports paletted textures through a set of 256 entry palettes associated with the Direct3DDevice8 object. A palette is made current by calling the Direct3DDevice8.SetCurrentTexturePalette method. The current palette is used for translating all paletted textures for all active texture stages. Direct3DDevice8.SetPaletteEntries updates all of a palette's 256 entries. Each entry is a PALETTEENTRY type of the format D3DFMT_A8R8G8B8. All entries default to 0xFFFFFFFF.

The Direct3DDevice8 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 16,384 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

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. 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 3-D space, its texel addresses must be mapped into object coordinates. They must then be translated into screen coordinates, or pixel locations.

Microsoft® 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.

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 2-D 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.

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.

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 onto the 3-D primitive in object space. The shape of the pixel is often distorted because of the shape of the primitive in 3-D 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.

Your application can assign texture coordinates directly to vertices. This capability gives you control over which portion of a texture is mapped onto 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 bottom 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.

If, instead, you decide to assign texture coordinates to make Direct3D use the bottom 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.0), (1.0,0.0), (1.0,0.5), and (0.0,0.5). Direct3D applies the bottom 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 further information, see Texture Addressing Modes.

Additional information is contained in the following topics.

  • Directly Mapping Texels to Pixels
  • Texture Coordinate Formats
  • Texture Coordinate Processing


Directly Mapping Texels to Pixels

Applications often need to apply textures to geometry in a scene so that texels map directly to on-screen pixels. For example, take an application that needs to display text within a texture on an object within a scene. In order to clearly display textual information in a texture, the application needs some way to ensure that the textured geometry receives texels undisrupted by texture filtering. Failing this, the resulting image is often blurred, or in the case of point-sampled texture filtering, can cause rough edges.

Because the Microsoft® Direct3D® pixel and texture sampling rules are carefully defined to unify pixel and texture sampling while supporting image and texture filtering, getting the texels in a texture to map directly to on-screen pixels can be a significant and often frustrating challenge. Overcoming this challenge requires a clear understanding of how Direct3D maps the floating-point texture coordinates for a vertex to the integer pixel coordinates used by the rasterizer.

Direct3D performs the following computations to map floating point texture coordinates to texel addresses.

In these formulas, Tx and Ty are the horizontal and vertical output texel coordinates, and u and v are the horizontal and vertical texture coordinates supplied for the vertex. The Mx and My elements represent the number of horizontal or vertical texels at the current mipmap level. The remainder of this discussion targets horizontal mapping of texels to pixels; keep in mind that mapping in the vertical is identical to the horizontal case.

Placing the texture coordinate limits 0.0 and 1.0 into these formulas maps a texture coordinate of 0.0 halfway between the first and last texels of a repeated texture map. The coordinate 1.0 is mapped halfway between the last texel of the current iteration of the texture map and the next iteration. For a repeated texture that's four texels wide, at mipmap level 0, the following illustration shows where the system maps the coordinates 0.0 and 1.0.

Given an understanding of this mapping, you can apply a simple bias to your screen-space geometry coordinates to force the system to map each texel to a corresponding pixel. For example, to draw a four-sided polygon that maps each texel from the preceding texture to one, and only one, pixel on the screen, you must force geometry coordinates to overlap the pixels, effectively placing the center of each texel at the center of each pixel. The result is the 1-to-1 mapping often sought-after by applications.

To map the texture with a 4-texel width to the pixel coordinates 0 through 3, draw a four-sided polygon, from two triangles, that has screen-space coordinates of –0.5 to 3.5 and texture coordinates of 0.0 to 1.0. For example, take the pixel at screen coordinate 0.0. Because 0.0 is one-half pixel away from the first vertex, at -0.5, and the total width is 4.0, the iterated texture coordinate is 0.125. Scaling this by the texture size, which is 4, results in the coordinate 0.5. Subtracting this 0.5 bias produces a texture address of 0.0, which fully maps to the first texel in the map.

To summarize, texture coordinates overlap the texture map evenly on both sides. The following illustration shows the mapping of a texture that is four texels wide.

The system normalizes pixel coordinates in the same way it normalizes texel coordinates. Therefore, if the vertices overlap the pixels into which to render, and if the vertices use texture coordinates of 0.0 and 1.0, the pixels and texels line up. If both are of similar size and properly aligned, they match exactly, texel to pixel, as shown in the following figure.


Texture Coordinate Formats

Texture coordinates in Microsoft® Direct3D® can include one, two, three, or four floating point elements to address textures with varying levels of dimension. A 1-D texture—a texture surface with dimensions of 1-by-n texels—is addressed by one texture coordinate. The most common case, 2-D textures, are addressed with two texture coordinates commonly called u and v. Direct3D supports two types of 3-D textures, cubic-environment maps and volume textures. Cubic environment maps aren't truly 3-D, but they are addressed with a 3-element vector. For details, see Cubic Environment Mapping.

Each texture coordinate set can have between one and four elements. Use the D3DFVF_TEXCOORDSIZEn set of helper functions in the Math.bas source file that ships with this SDK to generate bit patterns that describe the number of elements used by a 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.

Private Sub Form_Load()
' 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:
'     lFVF = D3DFVF_XYZ Or D3DFVF_NORMAL Or D3DFVF_DIFFUSE Or D3DFVF_TEX2 Or _
'            D3DFVF_TEXCOORDSIZE2(0) Or D3DFVF_TEXCOORDSIZE1(1)
'
Type CustomVertexFormat
    position As D3DVECTOR
    normal As D3DVECTOR
    diffuse  As D3DVECTOR
    ' 1st set, 2-D
    u As Single
    v As Single
    ' 2nd set, 1-D
    t As Single
End Type

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 nth) element. For more information, see Texture Coordinate Transformations.


Texture Coordinate Processing

The following figure shows the path taken by the texture coordinates from their source, through processing, and to the rasterizer.

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 Microsoft® Direct3D®. For details about the latter case, see Automatically Generated Texture Coordinates. 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 CONST_D3DTEXTURETRANSFORMFLAGS enumeration 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 2-D texture coordinates required to address a 2-D 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 2-D texture coordinates for a 1-D texture.

Additional information is contained in the following topics.

  • Automatically Generated Texture Coordinates
  • Texture Coordinate Transformations
  • Special Effects


Automatically Generated Texture Coordinates

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 Microsoft® Visual Basic®, the D3DTSS_TEXCOORDINDEX texture-stage state (from the CONST_D3DTEXTURESTAGESTATETYPE enumeration) 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 preceding flags are mutually exclusive. If you include one flag, you can still specify an index value, which the system uses to determine the texture wrapping mode.

The following code example shows how these flags are used in Visual Basic.

'
' For this example, the D3DDevice variable is a valid
' reference to a Direct3DDevice8 object.
'
' Use the vertex position (camera-space) as the input
' texture coordinates for this texture stage, and the
' wrap mode set in the D3DRENDERSTATE_WRAP1 render state.
'
Call D3DDevice.SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, _
                                    D3DTSS_TCI_CAMERASPACEPOSITION Or 1 )

Note 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.

See Also

Texture Coordinate Transformations, Cubic Environment Mapping


Texture Coordinate Transformations

Microsoft® Direct3D® devices can transform the texture coordinates for vertices by applying a 4×4 matrix. The system applies transformations to texture coordinates in the same manner as geometry, and any transformations that can be communicated in a 4×4 matrix—scales, rotations, translations, projections, shears, or any combination of these—can be applied.

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 (TnLHAL 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

The following code sets a matrix to apply to the texture coordinates for texture stage 0.

' For this example, the D3DDevice variable contains a
' valid reference to a Direct3DDevice8 object, and
' dx contains a valid reference to a DirectX8 object.

Dim matTrans As D3DMATRIX

Call D3DXMatrixIdentity( matTrans )

' 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 CONST_D3DTEXTURETRANSFORMFLAGS enumeration.

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 example disables them.

' For this example, the D3DDevice variable contains a
' valid reference to a Direct3DDevice8 object.

Call D3DDevice.SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, _
                                    D3DTTFF_DISABLE)

The other values defined in CONST_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, the D3DDevice variable contains a
' valid reference to a Direct3DDevice8 object.

Call 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, the D3DDevice variable contains a
' valid pointer to an IDirect3DDevice8 interface.

Call 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 2-D texture coordinates needed to address the texture.


Special Effects

The following list contains examples of special effects accomplished with texture coordinate processing.

Animating textures (by translation or rotation) on a model

  • Define 2-D texture coordinates in your vertex format.
    ' Use a single texture, with 2-D texture coordinates. This
' bit-pattern should be expanded to include position, normal,
' and color information as needed.
lFVFTex = (D3FVF_TEX1 Or D3DFVF_TEXCOORDSIZE2(0))
  • Configure the rasterizer to use 2-D 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  0  0 (du and dv change each frame)
'      0   0  0  0
dx.IdentityMatrix(M)
M.rc31 = du
M.ec32 = 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 2-D 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 Resources

Texture resources are implemented in the Direct3DTexture8 class. To obtain a texture object, call the Direct3DDevice8.CreateTexture method or any of the following D3DX functions.

  • D3DX8.CreateTexture
  • D3DX8.CreateTextureFromFile
  • D3DX8.CreateTextureFromFileEx
  • D3DX8.CreateTextureFromFileInMemory
  • D3DX8.CreateTextureFromFileInMemoryEx
  • D3DX8.CreateTextureFromResource
  • D3DX8.CreateTextureFromResourceEx

The following code example uses D3DX.CreateTextureFromFile to load a texture from Tiger.bmp.

'
' The following code example assumes that d3dDevice
' is a valid Direct3DDevice8 object and that g_D3DX is a valid
' D3DX8 object.
'
Dim Texture As Direct3DTexture8

Set Texture = g_D3DX.CreateTextureFromFile( d3dDevice, App.Path + "\tiger.bmp" )

The first parameter that CreateTextureFromFile accepts is a Direct3DDevice8 object. The second parameter tells Microsoft® Direct3D® the name of the file from which to load the texture. This method returns a texture object, which is assigned to Texture.

Rendering with Texture Resources

Microsoft® 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. The state of each texture is encapsulated in its texture stage.

In Microsoft® Visual Basic®, the state of each texture must be set with the Direct3DDevice8.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 CONST_D3DTEXTURESTAGESTATETYPE enumeration. The final parameter is the state value for the particular texture state.

Applications can render a blend of up to eight textures. Set the current textures by invoking the Direct3DDevice8.SetTexture method. Direct3D blends all current textures onto the primitives that it renders.

Note When the texture is no longer needed, you should set the texture at the appropriate stage to Nothing. If you fail to do this, the memory for the surface may be lost when your application closes.

Your application can set the texture wrapping state for the current textures by calling the Direct3DDevice8.SetRenderState method. Pass a value from D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7 as the value of the first parameter and use a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags from the CONST_D3D enumeration 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.


Texture Filtering

When Microsoft® Direct3D® renders a primitive, it maps the 3-D primitive onto a 2-D screen. If the primitive has a texture, Direct3D must use that texture to produce a color for each pixel in the primitive's 2-D 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 onto 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.

Microsoft® Visual Basic® applications should set the current texture filtering method by calling the Direct3DDevice8.SetTextureStageState 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 CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMINFILTER, or CONST_D3DTEXTUREMIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to the value from CONST_D3DTEXTUREFILTERTYPE to set the magnification, minification, or mipmapping filter.

This section presents the texture filtering methods that Direct3D supports. It is organized into the following topics.

  • Nearest-Point Sampling
  • Linear Texture Filtering
  • Anisotropic Texture Filtering
  • Texture Filtering with Mipmaps


Nearest-Point Sampling

Applications are not required to use texture filtering. Microsoft® Direct3D® can be set so that it computes the texel address, which often does not evaluate to integers, and simply 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 Microsoft® Visual Basic® application can select nearest-point sampling by calling the Direct3DDevice8.SetTextureStageState 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 CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMINFILTER, or CONST_D3DTEXTUREMIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass a member of the CONST_D3DTEXTUREFILTERTYPE enumeration type for the third parameter to set the magnification, minification, or mipmapping filter.

You should use nearest-point sampling carefully, as 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.

Notice that the two squares in the top-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.

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 0th 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 nth texel instead of the 0th 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 expensive, 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

Microsoft® Direct3D® uses a form of linear texture filtering called bilinear filtering. Like Nearest-Point Sampling, 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 Direct3DDevice8.SetTextureStageState 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 CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMINFILTER, or CONST_D3DTEXTUREMIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to D3DTEXF_LINEAR.


Anisotropic Texture Filtering

Anisotropy is the distortion visible in the texels of a 3-D object whose surface is oriented at an angle with respect to the plane of the screen. When a pixel from an anisotropic primitive is mapped to texels, its shape is distorted. Microsoft® 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 Direct3DDevice8.SetTextureStageState 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 CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMINFILTER, or CONST_D3DTEXTUREMIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to D3DTEXF_ANISOTROPIC.

You must also set the degree of anisotropy to a value greater than one. Do this by calling the Direct3DDevice8.SetTextureStageState 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 D3DTSS_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 D3DCAPS8 structure to determine the possible range of values for the degree of anisotropy.


Texture Filtering with Mipmaps

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.

Microsoft® 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 3-D, 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 computationally lower-overhead 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.

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 D3DTFP_POINT enumerated value to select this. Direct3D can produce better filtering results if your application uses the D3DTFP_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 3-D 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 Direct3DDevice8.CreateTexture to build a chain of five mipmap levels: 256×256, 128×128, 64×64, 32×32, and 16×16.

' This code example assumes that the variable m_D3D contains
' a valid reference to a Direct3DDevice8 object.
Dim DDMipmap as Direct3DTexture8

Set DDMipmap = m_D3D.CreateTexture(256, 256, 5, 0, D3DFMT_R8G8B8, D3DPOOL_DEFAULT)

The first two parameters that are accepted by 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, Microsoft® 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 CONST_D3DFORMAT enumerated type for this parameter. The sixth parameter specifies a member of the CONST_D3DPOOL enumerated type indicating the memory class into which to place the created resource. Unless you are using dynamic textures, D3DPOOL_MANAGED is recommended.

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 256×128, the dimensions of the second-level mipmap are 128×64, the third-level is 64×32, and so on, down to 1×1. 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 4×2 top-level mipmap surface, the maximum value allowed for Levels is three. The top-level dimensions are 4×2, the second-level dimensions are 2×1, and the dimensions for the third level are 1×1. 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 Direct3DDevice8.SetTexture method to set the mipmap texture set as the first texture in the list of current textures. For more information, see Texture Blending.

After your application selects the mipmap texture set, it must assign values from the CONST_D3DTEXTUREFILTERTYPE enumerated type to the D3DTSS_MIPFILTER texture stage state. Microsoft® Direct3D® then automatically performs mipmap texture filtering. Enabling mipmap texture filtering is demonstrated in the following code example.

m_D3D.SetTexture(0, DDMipMap)
m_D3D.SetTextureStateState(0, D3DTSS_MIPFILTER, D3DTEXF_POINT)

Your application can also manually traverse a chain of mipmap surfaces by using the Direct3DTexture8.GetSurfaceLevel method and specifying the mipmap level to retrieve. The following example traverses a mipmap chain from highest to lowest resolutions.

Dim DDLevel As Direct3DSurface8
Dim cLevels As Long

cLevels = DDMipMap.GetLevelCount

For iLevel = 0 to cLevels
    Set DDLevel = DDMipMap.GetSurfaceLevel(iLevel)

    'Process this level.

    Set DDLevel = Nothing
Next


Texture Wrapping

In short, texture wrapping changes the basic way that Microsoft® 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 2-D 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.

Note that the shortest distance between A and B in this illustration runs roughly through the middle of the texture. Enabling u- or v-texture coordinate wrapping changes how Direct3D perceives the shortest route between texture coordinates in the u- and v-directions. 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- and v-directions is a 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.

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's 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.

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.

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 Direct3DDevice8.SetRenderState method as shown in the code example below.

m_D3D.SetRenderState(D3DRS_WRAP0, D3DWRAPCOORD_0)

The first parameter accepted by 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.

Note Do not confuse texture wrapping with the similarly named texture addressing modes. For more information, see Texture Addressing Modes.


Compressed Texture Resources

Texture maps are digitized images drawn on three-dimensional shapes to add visual detail. They are mapped onto 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, Microsoft® Direct3D® supports the compression of texture surfaces. Some Direct3D devices support compressed texture surfaces natively. On such devices, once 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 3-D object.

Storage Efficiency and Texture Compression

All texture compression formats are powers of 2. While this does not mean that a texture is necessarily square, it does mean that both X and Y are powers of 2. For example, if a texture is originally 512×128 bytes, then the next mipmapping would be 256×64 and so on, with each level decreasing by a power of 2. At lower levels, where the texture is filtered to 16×2 and 8×1, there will be wasted bits because the compression block is always a 4×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×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 one-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, once 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.

Microsoft® Direct3D® provides services to compress surfaces that are used for texturing 3-D models. This section provides information on creating and manipulating the data in a compressed texture surface.

Information is contained in the following topics.

  • Opaque and One-bit Alpha Textures
  • Textures with Alpha Channels
  • Compressed Texture Formats
  • Using Compressed Textures


Opaque and One-Bit Alpha Textures

Texture format DXT1 is for textures that are opaque or have a single transparent color.

For each opaque or one-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 two 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 one-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 one-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 two-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.

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

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]

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 the following graphic.

This looks like the following series of colors.

Example of One-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.

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.


Textures with Alpha Channels

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 four 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 simply 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.

Note The compression method of Microsoft® 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]

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 is that in the DXT2 format it is assumed that the color data has been premultiplied by alpha. In the DXT3 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, simply 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 memory layout of the alpha block is as follows:

Byte | Alpha
0 | Alpha_0
1 | Alpha_1
2 | [0][2] (2 LSBs), [0][1], [0][0]
3 | [1][1] (1 LSB), [1][0], [0][3], [0][2] (1 MSB)
4 | [1][3], [1][2], [1][1] (2 MSBs)
5 | [2][2] (2 LSBs), [2][1], [2][0]
6 | [3][1] (1 LSB), [3][0], [2][3], [2][2] (1 MSB)
7 | [3][3], [3][2], [3][1] (2 MSBs)

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 simply 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

This section contains information on the internal organization of compressed texture formats. You do not need these details to use compressed textures, because you can use Direct3DX functions for conversion to and from compressed formats. However, this information is useful if you want to operate on compressed surface data directly.

Microsoft® Direct3D® uses a compression format that divides texture maps into 4×4 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 One-Bit Alpha Textures
  • Textures with Alpha Channels

Note 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, once 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. It now refers the pitch of a row of 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

Determining Support for Compressed Textures

Before your application creates a rendering device, it can determine if the device supports texturing from compressed texture surfaces by calling Direct3D8.CheckDeviceFormat. This method determines whether a surface format can be used as a texture on a device representing the adapter. To test the adapter, specify any pixel format that uses the DXT1, DXT2, DXT3, DXT4, or DXT5 four character codes (FOURCCs). If 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 Microsoft® Direct3D® by calling the Direct3DDevice8.SetTexture method. 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.

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 Direct3DDevice8.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 Direct3DTexture8.GetSurfaceLevel method.

Now you can use any Direct3DX function that begins with D3DXLoadSurface to load an image into the surface that was retrieved by using GetSurfaceLevel. These functions handle conversion to and from compressed texture formats.

You can create and convert compressed texture (DDS) files using the DXTex Tool supplied with the SDK. You can also create your own DDS files.

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 on how the data is stored, see Compressed Texture Formats. You only need this information if you are writing your own compression routines.

FOURCC | Description | Alpha-premultiplied?
DXT1 | Opaque / one-bit alpha | N/A
DXT2 | Explicit alpha | Yes
DXT3 | Explicit alpha | No
DXT4 | Interpolated alpha | Yes
DXT5 | Interpolated alpha | No

Note When you transfer data from a non-premultiplied format to a premultiplied format, Direct3D scales the colors based on the alpha values. Transferring data from a premultiplied format to a non-premultiplied format is not supported. If you try to transfer data from a premultiplied-alpha source to a non-premultiplied-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.


Volume Texture Resources

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 2-D 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.

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.

Private Type VOLUMEVERTEX
    Dim x As Single
    Dim y As Single
    Dim z As Single
    Dim color As Long
    Dim tu As Single
    Dim tv As Single
    Dim tw As Single
};

Const D3DFVF_VOLUMEVERTEX = (D3DFVF_XYZ Or D3DFVF_DIFFUSE Or _
                             D3DFVF_TEX1 Or D3DFVF_TEXCOORDSIZE3_0)

Next, fill the vertices with data.

Dim Vertices(3) As VOLUMEVERTEX

With Vertices(0):
    .x = 1.0: .y = 1.0: .z = 0.0: .color = &HFFFFFFFF .tu = 1.0: .tv = 1.0: .tw = 0.0
End With

With Vertices(1):
    .x = -1.0: .y = 1.0: .z = 0.0: .color = &HFFFFFFFF .tu = 0.0: .tv = 1.0: .tw = 0.0
End With

With Vertices(2):
    .x = 1.0: .y = -1.0: .z = 0.0: .color = &HFFFFFFFF .tu = 1.0: .tv = 0.0: .tw = 0.0
End With

With Vertices(3):
    .x = -1.0: .y = -1.0: .z = 0.0: .color = &HFFFFFFFF .tu = 0.0: .tv = 0.0: .tw = 0.0
End With

Now, create a vertex buffer and fill it with data from the vertices.

The next step is to use the Direct3DDevice8.CreateVolumeTexture method to create a volume texture, as shown in the code example below.

Dim volTexture As Direct3DVolumeTexture8

Set volTexture = m_D3DDevice.CreateVolumeTexture(8, 4, 4, 1, 0, _
                                                 D3DFMT_R8G8B8, _
                                                 D3DPOOL_MANAGED)

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.

d3dDevice.BeginScene

// Draw the quad, with the volume texture.
Call d3dDevice.SetTexture(0, volTexture)
Call d3dDevice.SetVertexShader(D3DFVF_VOLUMEVERTEX)
Call d3dDevice.SetStreamSource(0, VB, len(Vertices(0))
Call d3dDevice.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2)

// End the scene.
d3dDevice.EndScene


Automatic Texture Management

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.

Microsoft® 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 Microsoft® Visual Basic® application, create a texture resource by calling Direct3DDevice8.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 Direct3DDevice8.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 Direct3DResource8.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 may need to flush all managed textures from video memory. You can explicitly request to remove all managed textures by calling the Direct3DDevice8.ResourceManagerDiscardBytes method and specifying a value of 0 for the Bytes parameter. When you call this method, Direct3D destroys any cached local and nonlocal video-memory textures, but leaves the original system-memory copies untouched.

For more information on resource management, see Managing Resources.


Hardware Considerations for Texturing

Current hardware does not necessarily implement all the functionality that the Microsoft® Direct3D® interface enables. Your application must test user hardware and adjust its rendering strategies accordingly.

Many 3-D 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 3-D 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.

Due to limitations in much of today's hardware, few display adapters can perform trilinear mipmap interpolation through the multiple texture blending interface offered by Direct3DDevice8. Specifically, there is little support for setting the D3DTSS_MIPFILTER texture stage state to D3DTEXF_LINEAR. 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.


Texture Blending

Microsoft® 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 D3DCAPS8 structure. For details on how to query the user's hardware for texture blending capabilities, see Direct3DDevice8.GetDeviceCaps.

Texture Stages and the Texture Blending Cascade

Microsoft® 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.

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.

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.

Optimization 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
  • Assigning the Current Textures
  • Creating Blending Stages
  • Alpha Texture Blending
  • Multipass Texture Blending
  • Light Mapping with Textures


Texture Blending Operations and Arguments

Applications associate a blending stage with each texture in the set of current textures. Microsoft® 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 Direct3DDevice8.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, and alpha operations by using D3DTSS_ALPHAOP. Both stage states use values from the CONST_D3DTEXTUREOP enumeration.

Texture blending arguments use the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHARG1, and D3DTSS_ALPHARG2 members of the CONST_D3DTEXTURESTAGESTATETYPE enumeration. The corresponding argument values are identified using Texture Argument Flags.

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 D3DCAPS8 type.


Assigning the Current Textures

Microsoft® 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 written in Microsoft® Visual Basic® call Direct3DDevice8.SetTexture to assign textures to 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 Visual Basic code example demonstrates how a texture can be assigned into the set of current textures.

' This code example assumes that the variable d3dDevice is a
' valid reference to a Direct3DDevice8 object and d3dTexture
' is a valid reference to a Direct3DBaseTexture8 object.

' Set the third texture.
Call d3dDevice.SetTexture(2, d3dTexture)

Note Software devices do not support assigning a texture to more than one texture stage at a time.


Creating Blending Stages

A blending stage is a set of texture operations and their arguments that define how textures are blended. When making a blending stage, Microsoft® Visual Basic® applications invoke the Direct3DDevice8.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 d3dDevice is a valid reference to a
' Direct3DDevice7 object.

' Set the color operation for the first texture.
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_ADD)

' Set argument 1 to the texture color.
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE)

' Set argument 2 to the iterated diffuse color.
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE)

Texel data in textures contains 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 CONST_D3DTEXTURESTAGESTATETYPE.


Alpha Texture Blending

When Microsoft® Direct3D® renders a primitive, it generates a color for the primitive based on the primitive's material, or the colors of its vertices, and lighting information. For details, see Lights and Materials. If an application enables texture blending, Direct3D must then combine the color value of the processed polygon pixel with the pixel already stored in the frame buffer. Direct3D uses the following formula to determine the final color for each pixel in the primitive's image.

FinalColor = TexelColor × SourceBlendFactor + PixelColor × DestBlendFactor

In this formula, FinalColor is the final pixel color that is output to the target rendering surface. TexelColor represents the incoming color value, after texture filtering, that corresponds to the current pixel. For details on how Direct3D maps texels to pixels, see Texture Filtering. SourceBlendFactor is a calculated value that Direct3D uses to determine the percentage of the incoming color value to apply to the final color. PixelColor is the color of the pixel currently stored in the primitive's image. DestBlendFactor represents the percentage of the current pixel's color that will be used in the final rendered pixel. The values of SourceBlendFactor and DestBlendFactor range from 0.0 to 1.0 inclusive.

As you can see from the preceding formula, the final rendered pixel is not rendered as transparent if the SourceBlendFactor is D3DBLEND_ONE and the DestBlendFactor is D3DBLEND_ZERO. It is completely transparent if the SourceBlendFactor is D3DBLEND_ZERO and the DestBlendFactor is D3DBLEND_ONE. If an application sets these factors to any other values, the resulting final rendered pixel is blended with some degree of transparency.

After texture filtering, every pixel color value has red, green, and blue color values. By default, Direct3D uses D3DBLEND_SRCALPHA as the SourceBlendFactor and D3DBLEND_INVSRCALPHA as the DestBlendFactor. Therefore, applications can control the transparency of processed pixels by setting the alpha values in textures.

A Visual Basic application controls the blending factors with the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states. Invoke the Direct3DDevice8.SetRenderState method and pass either render state value as the value of the first parameter. The second parameter must be a member of the CONST_D3DBLEND enumeration.


Multipass Texture Blending

Microsoft® 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.

Note Some devices are capable of applying multiple textures to primitives in a single pass. For details, see Texture Blending.

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 Visual Basic application.

  1. Set a texture in texture stage 0 by calling the Direct3DDevice8.SetTexture method.
  2. Select the desired color and alpha blending arguments and operations with the Direct3DDevice8.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

For an application to realistically render a 3-D 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. Microsoft® 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 3-D 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
  • Color Light Maps
  • Specular Light Maps
  • Diffuse Light Maps


Monochrome Light Maps

Some older 3-D accelerator boards do not support texture blending using the alpha value of the destination pixel. See Alpha Texture Blending 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 Microsoft® 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 C++ code example illustrates how an application can use a texture as a monochrome light map.

' This example assumes that D3DDevice is a valid reference to a
' Direct3DDevice8 object and that texLightMap is a valid reference
' to a Direct3DTexture8 object that contains monochrome light map data.

' Set the light map texture as the current texture.
Call D3DDevice.SetTexture(0, texLightMap)

' Set the color operation.
Call D3DDevice.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1)

' Set argument 1 to the color operation.
Call D3DDevice.SetTextureStageState(0, D3DTSS_COLORARG1, _
 D3DTA_TEXTURE Or 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 3-D 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

Your application will usually render 3-D 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 Microsoft® Visual Basic® code example demonstrates light mapping with RGB color data.

' This example assumes that D3DDevice is a valid reference to a
' Direct3DDevice8 object and that texLightMap is a valid reference
' to a 3DBaseTexture8 object that contains RGB light map data.

' Set the light map texture as the first texture.
D3DDevice.SetTexture 0, texLightMap

D3DDevice.SetTextureStageState 0, D3DTSS_COLOROP, D3DTOP_MODULATE
D3DDevice.SetTextureStageState 0, D3DTSS_COLORARG1, D3DTA_TEXTURE
D3DDevice.SetTextureStageState 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE

This sample 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

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 Microsoft® Direct3D® applications apply specular light maps to primitives.

To perform specular light mapping, first modulate the specular light map with the primitive's existing texture. Then add the monochrome or RGB light map.

The following Microsoft® Visual Basic® code example illustrates this process.

' This example assumes that d3dDevice is a valid reference to an
' Direct3DDevice8 object.
' texBaseTexture is a valid reference to a texture.
' texSpecLightMap is a valid reference to a texture that contains RGB
' specular light map data.
' texLightMap is a valid reference to a texture that contains RGB
' light map data.

' Set the base texture.
Call d3dDevice.SetTexture(0, texBaseTexture)

' Set the base texture operation and args.
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE)
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE)

' Set the specular light map.
Call d3dDevice.SetTexture(1, texSpecLightMap)

' Set the specular light map operation and args.
Call d3dDevice.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_ADD)
Call d3dDevice.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDevice.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT)

' Set the RGB light map.
Call d3dDevice.SetTexture(2, texLightMap)

' Set the RGB light map operation and args
Call d3dDevice.SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_MODULATE)
Call d3dDevice.SetTextureStageState(2, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDevice.SetTextureStageState(2, D3DTSS_COLORARG2, D3DTA_CURRENT)


Diffuse Light Maps

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 Microsoft® Visual Basic® code example.

' This example assumes that d3dDevice is a valid reference to
' a Direct3DDevice7 object.
' texBaseTexture is a valid reference to a texture.
' texDiffuseLightMap is a valid reference to a texture that contains
' RGB diffuse light map data.

' Set the base texture.
Call d3dDevice.SetTexture(0, texBaseTexture)

' Set the base texture operation and args.
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE)
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE)

' Set the diffuse light map.
Call d3dDevice.SetTexture(1, texDiffuseLightMap)

' Set the blend stage.
Call d3dDevice.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE)
Call d3dDevice.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDevice.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT)


Surfaces

A surface represents a linear area of display memory. A surface usually resides in the display memory of the display card, although surfaces can exist in system memory. Surface objects are contained in the Direct3DSurface8 object.

A Direct3DSurface8 class is obtained by calling one of the following methods.

  • Direct3DCubeTexture8.GetCubeMapSurface
  • Direct3DDevice8.CreateDepthStencilSurface
  • Direct3DDevice8.CreateImageSurface
  • Direct3DDevice8.CreateRenderTarget
  • Direct3DDevice8.GetBackBuffer
  • Direct3DDevice8.GetDepthStencilSurface
  • Direct3DDevice8.GetFrontBuffer
  • Direct3DDevice8.GetRenderTarget
  • Direct3DSwapChain8.GetBackBuffer
  • Direct3DTexture8.GetSurfaceLevel

    • The Direct3DSurface8 object enables you to indirectly access memory through the Direct3DDevice8.CopyRects method. This method allows you to copy a rectangular region of pixels from one Direct3DSurface8 object to another specified rectangular region on another Direct3DSurface8 object. The surface object also has methods to directly access display memory. For example, you can use the Direct3DSurface8.LockRect method to lock a rectangular region of display memory. It is important to call Direct3DSurface8.UnlockRect after you are done working with the locked rectangular region on the surface.

    Surface formats dictate how data for each pixel in surface memory is interpreted. Microsoft® Direct3D® uses the CONST_D3DFORMAT member of the D3DSURFACE_DESC type to describe a surface format. You can retrieve the format of an existing surface by calling the Direct3DSurface8.GetDesc method.

    Additional information can be found in the following topics.

    • Width vs. Pitch
    • Flipping Surfaces
    • Page Flipping and Back Buffering
    • Copying To Surfaces
    • Copying Surfaces
    • Accessing Surface Memory Directly
    • Private Surface Data
    • Gamma Controls


Width vs. Pitch

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 Microsoft® Direct3D® uses to describe them.

HREF="..\..\VB\D3D\Types\d3dsurface_desc.htm">D3DSURFACE_DESC type to carry information describing a surface. Among other things, this type contains information about a surface's dimensions, as well as how those dimensions are represented in memory. It 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×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 Direct3DSurface8.LockRect method, the method fills in aD3DLOCKED_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 640×480×8 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 simply the width multiplied by the number of bytes per pixel. Rather, visualize the difference between width and pitch as shown in the following illustration.

In this figure, the front buffer and back buffer are both 640×480×8, and the cache is 384×480×8.

Pitch values are only useful when you are directly accessing surface memory. For example, after calling the LockRect method, the pBits member of the associated D3DLOCKED_RECT structure contains the address of the top-left pixel of the locked area of the surface, and the Pitch member is the surface pitch. You access pixels horizontally by incrementing or decrementing the surface pointer by the number of bytes per pixel, and you move up or down by adding the pitch value to, or subtracting it from, the current surface pointer.

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 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.


Flipping Surfaces

A Microsoft® 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 the D3DPRESENT_PARAMETERS type, which tells Direct3D the number of back buffers that will be in the swap chain. The call to Direct3D8.CreateDevice then creates the Direct3D device and corresponding swap chain.

When you use the Direct3DDevice8.Present method 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 Direct3DDevice8.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. CreateAdditionalSwapChain takes a D3DPRESENT_PARAMETERS type and returns a Direct3DSwapChain8 object. You can then use Direct3DSwapChain8.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 Direct3DDevice8.GetBackBuffer or Direct3DSwapChain8.GetBackBuffer methods, which return a Direct3DSurface8 object that represents the returned back buffer surface.

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 is 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 DirectX 8, 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, D3DSWAPEFFECT_COPY and D3DSWAPEFFECT_COPY_VSYNC swap effects.

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 CONST_D3DSWAPEFFECT.


Page Flipping and Back Buffering

Page flipping is key in multimedia, animation, and game software. Software page flipping 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 very similar to this process. Microsoft® 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 are designed to flip to the screen the way the artist's paper flips to the next page. The first buffer is referred to as the color front buffer and 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 quickly and efficiently.

Direct3D makes it easy to set up page flipping schemes, from a relatively simple double-buffered scheme—a color front buffer with one back buffer—to more sophisticated schemes that add additional back buffers.


Copying To Surfaces

When using the Direct3DDevice8.CopyRects method, you pass the first element of an array of rectangles on the source surface or Nothing to specify the entire surface. You also pass an array of points on the destination surface to which the top-left-position of each rectangle on the source image is copied. You can pass ByVal 0 to copy the rectangles with the same top-left position as the source. This method does not support clipping. The operation will fail unless all the source rectangles and their corresponding destination rectangles 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 source and destination surfaces must be distinct.

CopyRects 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 IDirect3DDevice8 object.
'-Source and Dest are valid Direct3DSurface8 objects.

Dim rcSource(1) As RECT
Dim ptDest(1) As Point

rcSource(0).left = 0
rcSource(0).top = 0
rcSource(0).right= 0
rcSource(0).bottom = 0

rcSource(1).left = 50
rcSource(1).top = 50
rcSource(1).right = 100
rcSource(1).bottom = 100

ptDest(0).x = 0
ptDest(0).y = 0

ptDest(1).x = 150
ptDest(1).y = 150

d3dDevice.CopyRects Source, rcSource, 2, Dest, ptDest

The following methods are also available in Microsoft® Visual Basic® for copying images to a Microsoft Direct3D® surface.

  • D3DX8.LoadSurfaceFromFile
  • D3DX8.LoadSurfaceFromFileInMemory
  • D3DX8.LoadSurfaceFromMemory
  • D3DX8.LoadSurfaceFromResource
  • D3DX8.LoadSurfaceFromSurface
  • Direct3DDevice8.CopyRects


Copying Surfaces

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 Microsoft® DirectX® 8.x as the primary mechanism for moving large rectangles of pixels on a per-frame basis, the mechanism behind the copy-oriented Direct3DDevice8.Present method. The transportation of artwork in the blit operation is performed by the Direct3DDevice8.UpdateTexture method. Artwork can also be copied in DirectX 8.x by using the Direct3DDevice8.CopyRects method, which copies a rectangular subset of pixels.

Note Microsoft® Direct3DX functions enable you to load artwork from files, apply color conversion, and resize artwork. For more information on the available functions see the D3DX8.class and look under methods for textures.


Accessing Surface Memory Directly

You can directly access the surface memory by using the Direct3DSurface8.LockRect method. When you call this method, the RECT parameter is a RECT type that describes the rectangle on the surface to access directly. To request that the entire surface be locked, set RECT to Nothing. 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 LockRect method fills a D3DLOCKED_RECT type with all the information to properly access the surface memory. The structure includes information about the pitch and has the locked bits. When you finish accessing the surface memory, call the Direct3DSurface8.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 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 Microsoft® Direct3D® driver. For more information, see Width vs. Pitch.
  • 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. Microsoft® Windows® 95 and Windows 98 use 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 private (FOURCC) driver format. Back buffer surfaces, which may be accessed using the Direct3DDevice8.GetBackBuffer and Direct3DSwapChain8.GetBackBuffer methods, may be locked only if the swap chain was created with the Flags member of the D3DPRESENT_PARAMETERS type set to include D3DPRESENTFLAG_LOCKABLE_BACKBUFFER.


Private Surface Data

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 the Direct3DSurface8.SetPrivateData method, passing a buffer that contains data to associate with the surface, the size of the data buffer, and an application-defined DXGUID for the data.

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 Direct3DSurface8.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 Direct3DSurface8.GetPrivateData method, passing the DXGUID that was assigned to the data by SetPrivateData. You are responsible for freeing any dynamic memory you use for this buffer.

If you don't know how big a buffer to allocate, first call GetPrivateData with zero in SizeOfData. If the method fails with D3DERR_MOREDATA, it returns the necessary number of bytes for the buffer in SizeOfData.


Gamma Controls

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 Microsoft® Direct3D® applies to data as it leaves a surface and before it is rendered on the screen.

Gamma controls are simply 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 Microsoft® Direct3D® for Microsoft DirectX® 8.x 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 VSYNC operation.

The Direct3DDevice8.SetGammaRamp and Direct3DDevice8.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 Microsoft® 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 digital-to-analog converter (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 Microsoft® Direct3D® uses to map the frame buffer color components to new levels that will be displayed. You set and retrieve ramp levels for the primary surface by calling the Direct3DDevice8.SetGammaRamp and Direct3DDevice8.GetGammaRamp methods. SetGammaRamp accepts two parameters and GetGammaRamp accepts one parameter. For SetGammaRamp, the first parameter is either D3DSGR_CALIBRATE or D3DSGR_NO_CALIBRATION. The second parameter, pRamp, takes a D3DGAMMARAMP type. The D3DGAMMARAMP type contains three 256-element arrays of DWORDs, one array each to contain the red, green, and blue gamma ramps. GetGammaRamp has one parameter that takes a D3DGAMMARAMP type that will be filled with the current gamma ramp.

You can include the D3DSGR_CALIBRATE value for the first parameter of 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 Direct3DDevice8.GetDeviceCaps, and examine the Caps2 member of the associated D3DCAPS8 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 D3DCAPS8 type to determine the capabilities of the device and whether a calibrator is installed.


Rendering

Applications use the DrawPrimitive family of methods to render a 3-D scene. The following topics discuss rendering with DrawPrimitive.

  • Shading
  • Clearing Surfaces
  • Beginning and Ending a Scene
  • Presenting a Scene
  • Rendering Primitives
  • Fog, Alpha Blending, and Depth Buffers


Shading

This section describes techniques used in Microsoft® Direct3D® to control the shading of 3-D polygons.

  • Shading Modes
  • Comparing Shading Modes
  • Setting the Shading Mode


Shading Modes

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. Microsoft® Direct3D® supports two shading modes:

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. 3-D 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 computationally the least expensive form of shading.

Gouraud Shading

When Microsoft® 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.

Gouraud shading can also be used to display objects with sharp edges.

For more information, see Face and Vertex Normal Vectors.


Comparing Shading Modes

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.

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

Microsoft® Direct3D® enables one shading mode to be selected at a time. By default, Gouraud shading is selected. In Microsoft Visual Basic®, you can change the shading mode by calling the Direct3DDevice8.SetRenderState method. Set the State parameter to D3DRS_SHADEMODE. The State parameter must be set to a member of the CONST_D3DSHADEMODE enumeration. The following code example illustrates 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 d3dDev is a valid reference to
'  a Direct3DDevice8 object.
On Local Error Resume Next
Call d3dDev.SetRenderState(D3DRS_SHADEMODE, _
                           D3DSHADE_FLAT)

' Check for an error.
If Err.Number <> D3D_OK Then
    ' Handle the error.
End If

' Set to Gouraud shading. this is the default for Direct3D.
Call d3dDev.SetRenderState(D3DRS_SHADEMODE, _
                           D3DSHADE_GOURAUD)

If Err.Number <> D3D_OK Then
    ' Handle the error.
End If


Clearing Surfaces

Before rendering objects in a scene, clear the viewport on the render-target surface or a subset of the viewport. Clearing the viewport causes the system to set the desired portion of the render-target surface and any attached depth or stencil buffers to a desired state. This resets the areas of the surface that will be rendered again, and it resets the corresponding areas of the depth and stencil buffers, if any are in use. Clearing a render-target surface can set the desired region to a default color or texture. For depth and stencil buffers, this can set a depth or stencil value.

Use the Direct3DDevice8.Clear method to clear the viewport.

For more information about using this method, see Clearing a Viewport.

Optimization Note Applications that render scenes covering the entire area of the render-target surface can improve performance by clearing the attached depth and stencil buffer surfaces, if any, instead of the render target. In this case, clearing the depth buffer causes Microsoft® Direct3D® to rewrite the render target on the next rendered frame, making an explicit clear operation on the render target redundant. However, if your application renders only to a portion of the render-target surface, explicit clear operations are required.


Beginning and Ending a Scene

Microsoft® Visual Basic® applications notify Microsoft Direct3D® that scene rendering is about to begin by calling the Direct3DDevice8.BeginScene method. BeginScene causes the system to check its internal data structures and the availability and validity of rendering surfaces. It also sets an internal flag to signal that a scene is in progress. After you begin a scene, you can call the various rendering methods to render the primitives or individual vertices that make up the objects in the scene. Attempts to call rendering methods when a scene is not in progress fail. For more information, see Rendering Primitives.

After you complete the scene, call the Direct3DDevice8.EndScene method. The EndScene method flushes cached data, verifies the integrity of rendering surfaces, and clears an internal flag that signals when a scene is in progress.

All rendering methods must be bracketed by calls to the BeginScene and EndScene methods. If surfaces are lost or internal errors occur, the scene methods fail and Err.Number is set to an error code. If BeginScene fails, the scene does not begin, and subsequent calls to EndScene will fail. When surfaces are lost during rendering, EndScene will fail.

To summarize these cases:

  • If BeginScene returns any error, you must not call EndScene because the scene has not successfully begun.
  • If BeginScene succeeds, but you get an error while rendering the scene, you must call EndScene.
  • If EndScene fails, for any reason, you need not call it again.

For example, some simple scene code might look like the following example.

On Local Error Resume Next

Call d3dDevice.BeginScene
If Err.Number = DD_OK Then
    ' Render primitives only if the scene
    ' starts successfully.

    ' Close the scene.
    Call d3dDevice.EndScene
    If Err.Number <> DD_OK Then
        ' Code to handle error goes here.
    End If
End If

You cannot embed scenes; that is, you must complete rendering a scene before you can begin another one. Calling EndScene when BeginScene has not been called returns an error value. Likewise, calling BeginScene when a previous scene has not been completed with the EndScene method results in an error.

Do not attempt to call GDI functions on Direct3D surfaces, such as the render target or textures, while a scene is being rendered—is between BeginScene and EndScene calls. Attempts to do so can prevent the results of the GDI operations from being visible. If your application uses GDI functions, be sure that all GDI calls are made outside the scene functions.


Presenting a Scene

This section introduces the presentation application programming interfaces (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
  • Multiple Views in Windowed Mode
  • Multiple-Monitor Operations
  • Manipulating the Depth Buffer
  • Accessing the Color Front Buffer


Introduction to Presenting a Scene

The presentation application programming interfaces (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.

  • Direct3DDevice8.Present
  • Direct3DDevice8.Reset
  • Direct3DDevice8.GetGammaRamp
  • Direct3DDevice8.SetGammaRamp
  • Direct3DDevice8.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 DDI, and a windowed swap chain presents images with the blitting DDI.

Because Microsoft® Direct3D® Microsoft for DirectX® 8.x has one swap chain as a property of the device, there is always at least one swap chain per device. The Direct3DDevice8 class 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 the Direct3D API for DirectX 8.x. As a result, applications cannot lock or render to the front buffer. For details, see Accessing the Color Front Buffer.

Note DirectX 7.x provided a number of presentation APIs that were called together. A good example of this is the DirectDraw7.SetCooperativeLevel, DirectDraw7.SetDisplayMode, and DirectDraw7.CreateSurface sequence. Additionally, the DirectDrawSurface7.Flip and DirectDrawSurface7.Blt methods signaled the transport of rendered frames to the monitor. DirectX 8.x 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 Blt.

A call to Direct3D8.CreateDevice represents an implicit reset of the device. The DirectX 8.x API has no notion of a primary surface; you cannot to 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 Direct3DDevice8.GetGammaRamp and Direct3DDevice8.SetGammaRamp methods.


Multiple Views in Windowed Mode

In addition to the swap chain that is owned and manipulated through the Direct3DDevice object, an application can use the Direct3DDevice8.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 Direct3DDevice8.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

When a device is successfully reset (Direct3DDevice8.Reset) or created (Direct3D8.CreateDevice) in full-screen operations, the Microsoft® 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.

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

Depth buffers are associated with the device. Applications are required to move the depth buffers when they set render targets. The Direct3DDevice8.GetDepthStencilSurface and Direct3DDevice8.SetRenderTarget methods are used to manipulate depth buffers.


Accessing the Color Front Buffer

Accessing the front buffer is allowed through the Direct3DDevice8.GetFrontBuffer method. This method is the only way to get a screenshot of an antialiased scene.


Rendering Primitives

The following topics introduce the DrawPrimitive rendering methods and provide information about using them in your application.

  • Vertex Data Streams
  • Setting the Stream Source
  • Rendering from Vertex and Index Buffers
  • Rendering from User Memory Pointers


Vertex Data Streams

The rendering interfaces for Microsoft® 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 DrawPrimitive method to render from those streams. Identification of vertex elements within these component streams is specified by the vertex shader. For details, see Vertex Shaders.

The 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.


Setting the Stream Source

The Direct3DDevice8.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 Direct3DDevice8.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.


Rendering from Vertex and Index Buffers

Both indexed and nonindexed drawing methods are supported by Microsoft® Direct3D®. The indexed methods use a single set of indices for all vertex components. Vertex data is presented to the Direct3D application programming interface (API) in vertex buffers, and index data for the indexed drawing methods is presented in index buffers. For more information, see the following reference topics.

  • Direct3DDevice8.DrawPrimitive
  • Direct3DDevice8.DrawIndexedPrimitive

These methods draw primitives from the current set of data input streams. For details on setting the current index array to an index buffer, see the Direct3DDevice8.SetIndices method.


Rendering from User Memory Pointers

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.

  • Direct3DDevice8.DrawPrimitiveUP
  • Direct3DDevice8.DrawIndexedPrimitiveUP

These methods render with data specified by user memory pointers, instead of vertex and index buffers.


Fog, Alpha Blending, and Depth Buffers

After the texture maps and/or the pixel shaders have calculated per pixel colors, some effects can be applied to an entire frame to produce the final pixel color value. These effects are illustrated in the topics below.

  • Fog
  • Alpha Blending
  • Depth Buffers


Fog

Adding fog to a 3-D scene can enhance realism, provide ambiance or set a mood, and obscure artifacts sometimes caused when distant geometry comes into view. Microsoft® 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 and Vertex Fog. In short, pixel fog—also called table fog—is implemented in the device driver, and vertex fog is implemented in the Direct3D lighting engine.

Note Regardless of which type of fog—pixel or vertex—you use, 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 A W-Friendly Projection Matrix.

The following topics introduce fog and present information about using various fog features in Microsoft® Direct3D® applications.

  • 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

Applications written in Microsoft® Visual Basic® can control how fog affects the color of objects in a scene by changing how Microsoft Direct3D® computes fog effects over distance. The CONST_D3DFOGMODE enumeration 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.

D3DFOG_LINEAR

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.

Linear and exponential formulas are supported for both pixel fog and vertex fog.

D3DFOG_EXP

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.

D3DFOG_EXP2

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 Ci by the fog factor f, and adds the product to the fog color Cf, 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

Fog parameters are controlled through device render states. Both pixel and vertex fog types support all the fog formulas introduced in Fog Formulas. The CONST_D3DFOGMODE enumeration 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.

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. Use the D3DColorXRGB function to generate valid values for this render state. For more information, see Fog Color and Fog Blending.


Fog Blending

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. The D3DRS_FOGENABLE render state controls fog blending. Set this render state to 1 to enable fog blending as shown in the following example code. The default is 0.

'
' For this example, d3dDevice contains a valid
' reference to a Direct3DDevice8 object.
'
On Local Error Resume Next

Call d3dDevice.SetRenderState(D3DRS_FOGENABLE, 1)

If Err.Number <> D3D_OK Then
    ' Code to handle error goes here.
End If

You must enable fog blending for both pixel fog and vertex fog. For information about using these types of fog, see Pixel Fog and Vertex Fog.


Fog Color

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, as returned by the D3DColorXRGB function.

The following Microsoft® Visual Basic® example sets the fog color to white.

'
' For this example, the d3dDevice variable is
' a valid reference to a Direct3DDevice8 object.
'
On Local Error Resume Next

Call d3dDevice.SetRenderState( _
                    D3DRS_FOGCOLOR, _
                    D3DColorXRGB(1#, 1#, 1#))

If Err.Number <> D3D_OK Then
    ' Code to handle error goes here.
End If


Vertex Fog

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 Microsoft® Direct3D® lighting and transformation engine. For more information, see Fog Parameters.

If your application does not use Direct3D for transformation and lighting, it must perform fog calculations on its own. In this case, your application can place the fog factor that it computes 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 do not use Direct3D transformation and lighting need not set vertex fog parameters, but must still enable fog and set the fog color through the associated render states. For more information, see Fog Parameters.

Note When using a vertex shader, you must use vertex fog. The vertex shader must write the per-vertex fog intensity to oFog. This is then used after the pixel shader to linearly interpolate with the fog color. This intensity is not available in a pixel shader.

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 and Fog Color.

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.

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 capability flag in the RasterCaps member of the D3DCAPS8 type when you call the Direct3DDevice8.GetDeviceCaps method. To enable range-based fog, set the D3DRS_RANGEFOGENABLE render state to 1.

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 1.
  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 CONST_D3DFOGMODE enumeration.
  4. Set the fog parameters as desired for the selected fog formula in the render states.

The following Microsoft® Visual Basic® example code shows what these steps might look like.

' 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, d3dDevice is a valid
' reference to a Direct3DDevice8 object.
Sub SetupVertexFog(Color As Long, Mode As CONST_D3DFOGMODE, _
                   UseRange As Boolean, Optional Density As Single)

    Dim StartFog As Single, _
        EndFog As Single

    ' Set linear fog distances
    StartFog = 0.5: EndFog = 0.8

    ' Enable fog blending.
    Call d3dDevice.SetRenderState(D3DRS_FOGENABLE, 1)

    ' Set the fog color.
    Call d3dDevice.SetRenderState(D3DRS_FOGCOLOR, Color)

    ' Set fog parameters.
    If Mode = D3DFOG_LINEAR Then
        Call d3dDevice.SetRenderState(D3DRS_FOGVERTEXMODE, Mode)
        Call d3dDevice.SetRenderStateSingle(D3DRS_FOGSTART, StartFog)
        Call d3dDevice.SetRenderStateSingle(D3DRS_FOGEND, EndFog)
    Else
        Call d3dDevice.SetRenderState(D3DRS_FOGVERTEXMODE, Mode)
        Call d3dDevice.SetRenderStateSingle(D3DRS_FOGDENSITY, Density)
    End If

    ' Enable range-based fog if desired (only supported for vertex
    ' fog). For this example, it is assumed that UseRange is set to
    ' 1 only if the driver exposes the D3DPRASTERCAPS_FOGRANGE
    ' capability.
    ' Note: This is slightly more performance intensive
    '       than non-range-based fog.
    If UseRange = 1 Then
        Call d3dDevice.SetRenderState(D3DRS_RANGEFOGENABLE, 1)
    End If
End Sub


Pixel Fog

Pixel fog gets its name from the fact that it is calculated on a per-pixel basis in the device driver, unlike vertex fog, in which Microsoft® Direct3D® computes fog effects when it performs transformation and lighting. Pixel fog is sometimes called table fog because some drivers use a precalculated look-up table to determine the fog factor, using the depth of each pixel, to apply in blending computations.

Pixel fog can be applied using any fog formula identified by members of the CONST_D3DFOGMODE enumeration. Pixel-fog formula implementations are driver-specific, and if a driver doesn't support a complex fog formula, it should degrade to a less complex formula.

Note Pixel fog is not supported when using a vertex shader.

Eye-Relative vs. Z-Based Depth

To alleviate fog-related graphic artifacts caused by uneven distribution of z-values within 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 D3DCAPS8 type when you call the Direct3DDevice8.GetDeviceCaps method.

Note 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 use 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 Direct3DDevice8.SetTransform method, using the D3DTS_PROJECTION value from CONST_D3DTRANSFORMSTATETYPE and passing a D3DMATRIX type 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 A W-Friendly Projection Matrix. The perspective projection matrix provided in What Is the Projection Transformation? produces a compliant projection matrix.

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.

Use the following steps to enable pixel fog in your application.

To enable pixel fog in a Visual Basic application

  1. Enable fog blending by setting the D3DRS_FOGENABLE render state to 1.
  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 CONST_D3DFOGMODE enumeration.
  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, d3dDevice is a valid
' reference to a Direct3DDevice8 object.
Sub SetupPixelFog(Color As Long, Mode As CONST_D3DFOGMODE)
    Dim StartFog As Single, _
        EndFog As Single, _
        Density As Single

    ' For linear mode
    StartFog = 0.5: EndFog = 0.8

    ' For exponential mode
    Density = 0.66

    ' Enable fog blending.
    Call d3dDevice.SetRenderState(D3DRS_FOGENABLE, 1)

    ' Set the fog color.
    Call d3dDevice.SetRenderState(D3DRS_FOGCOLOR, Color)

    ' Set fog parameters.
    If Mode = D3DFOG_LINEAR Then
        Call d3dDevice.SetRenderState(D3DRS_FOGTABLEMODE, Mode)
        Call d3dDevice.SetRenderState(D3DRS_FOGSTART, StartFog)
        Call d3dDevice.SetRenderState(D3DRS_FOGEND, EndFog)
    Else
        Call d3dDevice.SetRenderState(D3DRS_FOGTABLEMODE, Mode)
        Call d3dDevice.SetRenderState(D3DRS_FOGDENSITY, Density)
    End If
End Sub


Alpha Blending

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

When creating 3-D scenes, an application can sometimes gain performance advantages by rendering 2-D objects in a way that makes them appear to be 3-D 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 3-D graphics is an extension of this. The goal is to make 2-D objects appear to be 3-D. 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 3-D maze, he or she may see weapons or rewards that can be picked up. These are typically 2-D 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 2-D rather than 3-D.


Clouds, Smoke, and Vapor Trails

Clouds, smoke, and vapor trails can all be created by an extension of the billboarding technique. See Billboarding. By rotating the billboard on two axes instead of one, your application can enable the user to look at 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. 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.

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

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 3-D 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 3-D 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 and Line Strips.

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.


Depth Buffers

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 Microsoft® Direct3D®. When Direct3D renders a 3-D 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 3-D 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.

Nearly all 3-D 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% of the depth buffer range is spent on the first 10% 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 1000 to 10000. At a ratio of 1000, 98% of the range is spent on the 1st 2% 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.

Z-buffering requires overhead during rendering. Various techniques can be used to optimized rendering when using z-buffers. For details, see Z-Buffer Performance.

Note The actual interpretation of a depth value is specific to the 3-D renderer.

This section presents information on using depth buffers for hidden line and hidden surface removal.

Additional information is contained in the following topics.

  • Querying for Depth Buffer Support
  • Creating a Depth Buffer
  • Enabling Depth Buffering
  • Retrieving a Depth Buffer
  • Clearing Depth Buffers
  • Changing Depth Buffer Write Access
  • Changing Depth Buffer Comparison Functions
  • Using Z-Bias


Querying for Depth Buffer Support

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 Microsoft® 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 Direct3D8.CheckDeviceFormat method, as shown in the following code example.

' The following example assumes that g_D3D, AdapterOrdinal,
' DeviceType, and Format are properly initialized values.
g_D3D.CheckDeviceFormat AdapterOrdinal, DeviceType, Format, _
                        D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, _
                        D3DFMT_D16

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.

In addition, you can use Direct3D8.CheckDepthStencilMatch to determine whether a supported depth-stencil format is compatible with the render target format in the display mode, particularly if a depth format must be equal to the render target format.

Once 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 Direct3DDevice8.GetDeviceCaps method, passing an initialized D3DCAPS8 type.
  2. After the call, the LineCaps member contains information about the driver's support for rendering primitives.
  3. If the RasterCaps member of this type contains the D3DPRASTERCAPS_WBUFFER flag, then the driver supports w-based depth buffering for that primitive type.


Creating a Depth Buffer

A depth buffer is a property of the device. To create a depth buffer that is managed by Microsoft® Direct3D®, set the appropriate members of the D3DPRESENT_PARAMETERS structure as shown in the following code example.

Dim d3dpp As D3DPRESENT_PARAMETERS

d3dpp.Windowed = 1
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY_VSYNC
d3dpp.EnableAutoDepthStencil = 1
d3dpp.AutoDepthStencilFormat = D3DFMT_D16

By setting the EnableAutoDepthStencil member to a nonzero value (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 Direct3D8.CreateDevice method creates a device that then creates a depth buffer.

Set d3dDevice = g_D3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, _
                                     D3DCREATE_SOFTWARE_VERTEXPROCESSING, d3dpp)
If d3dDevice Is Nothing Then Exit Function

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 recreated in the new size.

To create a new depth buffer surface, use the Direct3DDevice8.CreateDepthStencilSurface method.

To set a new depth-buffer surface for the device, use the Direct3DDevice8.SetRenderTarget method.

To use the depth buffer in your application, you need to enable the depth buffer. For details, see Enabling Depth Buffering.


Enabling Depth Buffering

After you create a depth buffer, as described in Creating a Depth Buffer, you enable depth buffering by calling the Direct3DDevice8.SetRenderState method. Set the D3DRS_ZENABLE render state to enable depth-buffering. Use the D3DZB_TRUE member of the CONST_D3DZBUFFERTYPE enumeration to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE to disable depth buffering altogether.

Note To use w-buffering, your application must set a compliant projection matrix even if it doesn't use the Microsoft® Direct3D® transformation pipeline. For information about providing an appropriate projection matrix, see A W-Friendly Projection Matrix. The projection matrix discussed in What Is the Projection Transformation? is compliant.


Retrieving a Depth Buffer

The following code example shows how to use the Direct3DDevice8.GetDepthStencilSurface method to retrieve the depth buffer-surface owned by the device.

    Dim ZBuffer As Direct3DSurface8

    Set ZBuffer = d3dDevice.GetDepthStencilSurface


Clearing Depth Buffers

Many Microsoft® Visual Basic® applications clear the depth buffer before rendering each new frame. You can explicitly clear the depth buffer through Microsoft® Direct3D® by calling Direct3DDevice8.Clear and specifying D3DCLEAR_ZBUFFER for the Flags parameter. The Clear method allows you to specify an arbitrary depth value in the Z parameter.


Changing Depth Buffer Write Access

By default, the Microsoft® 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 a Microsoft Visual Basic® application by calling the Direct3DDevice8.SetRenderState method with the State parameter set to D3DRS_ZWRITEENABLE and the Value parameter set to 0.


Changing Depth Buffer Comparison Functions

By default, when depth testing is performed on a rendering surface, the Microsoft® 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 Microsoft® Visual Basic®, you can change how the system performs comparisons on depth values by calling the Direct3DDevice8.SetRenderState method with the State parameter set to D3DRS_ZFUNC. The Value parameter should be set to a value in the CONST_D3DCMPFUNC enumeration.


Using Z-Bias

Polygons that are coplanar in your 3-D 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.

A Microsoft® Visual Basic® 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 Direct3DDevice8.SetRenderState method just before rendering them, setting the State parameter to D3DRS_ZBIAS, 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.


About Devices

A Microsoft® 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. Architecturally, Direct3D devices contain a transformation module, a lighting module, and a rasterizing module, as the following illustration shows.

Direct3D currently supports two main types of Direct3D devices: a hardware abstraction layer (HAL) device with hardware-accelerated rasterization and shading with both hardware and software vertex processing; and 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 3-D hardware that is installed in the computer or by emulating the capabilities of 3-D 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 Microsoft® DirectX® 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 and the type of a device. The Direct3D8.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 the D3DDEVTYPE_SW member of the CONST_D3DDEVTYPE enumeration on a device created with the D3DCREATE_PUREDEVICE member of the CONST_D3DCREATEFLAGS enumeration.

Additional information is contained in the following topics.

  • Device Types
  • Lost Devices
  • Direct3D Object
  • Using Devices

Direct3D enables applications that use custom transformation and lighting models to bypass the Direct3D device's transformation and lighting modules. For details, see Vertex Shaders.

For more information, see

  • Device States


Device Types

HAL Device

The primary device type is the hardware abstraction layer (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 Microsoft® Direct3D®, your application should use it for 3-D operations. Direct3D HAL devices implement all or part of the transformation, lighting, and rasterizing modules in hardware.

Applications do not access 3-D cards 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 from Microsoft Visual Basic®, call the Direct3D8.CreateDevice method, and pass D3DDEVTYPE_HAL constant as the device type.

Note Hardware devices cannot render to 8-bit render-target surfaces.

Reference Device

Microsoft® Direct3D® supports an additional device type called a reference device or reference rasterizer. Unlike a software device, the reference rasterizer supports every Direct3D feature. 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 from Microsoft Visual Basic®, call the Direct3D8.CreateDevice method, and pass the D3DDEVTYPE_REF constant as the device type.


Lost Devices

A Microsoft® Direct3D® device can be in either an operational state or a lost state. The operational state is the normal state of the device; the device executes 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 Direct3DDevice8.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 Direct3DDevice8.Reset puts the device into a lost state.

Note The only methods that are guaranteed to work after a device is lost are Direct3DDevice8.TestCooperativeLevel, IDirect3DDevice8::Reset

Responding to a Lost Device

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 Direct3DDevice8.Reset. Reset is the only method that has an effect when the 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 Direct3DDevice8.CreateRenderTarget and Direct3DDevice8.CreateDepthStencilSurface methods.

For the most part, the high-frequency calls of Direct3D do not return information about whether the device has been lost. The application can continue to call rendering methods, such as Direct3DDevice8.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 Direct3DDevice8.TestCooperativeLevel method.

  • If the method returns D3D_OK, the device is operational.
  • If the device is lost but cannot be restored at the current time, the return value is D3DERR_DEVICELOST. This is the case when the user presses ALT+TAB, causing a full-screen device to lose focus. Applications should respond by pausing until the device can be reset. A D3DERR_DEVICENOTRESET return code from TestCooperativeLevel indicates this situation.
  • If the device is lost and can be restored, the return code from TestCooperativeLevel is D3DERR_DEVICENOTRESET. Note that the return code from the Direct3DDevice8.Present method is still D3DERR_DEVICELOST.

In all cases, destroying video-memory resources is a prerequisite to calling Reset, even if the device has not been lost.

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 Direct3DDevice8.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 Direct3DDevice8.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 IDirect3DDevice8::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.

The copy operation Direct3DDevice8.CopyRects can return D3DERR_DEVICELOST when the source object is in volatile memory (D3DPOOL_DEFAULT) and the destination object is in nonvolatile memory (D3DPOOL_SYSTEMMEM or D3DPOOL_MANAGED). Another copy operation, Direct3DDevice8.GetFrontBuffer, can fail due to retrieving data from the primary surface. Note that these cases are the only instance of D3DERR_DEVICELOST outside of the Direct3DDevice8.Present, Direct3DDevice8.TestCooperativeLevel, and Direct3DDevice8.Reset methods.

Programmable Shaders

In Microsoft® DirectX® 8.1, programmable vertex shaders and programmable pixel shaders don't need to be recreated after Reset. They will be remembered. In previous versions of DirectX, a lost device required shaders to be recreated.


Direct3D Object

Microsoft® Direct3D® is implemented through COM objects and interfaces. Applications written in C++ access these interfaces and objects directly, whereas Microsoft Visual Basic® applications interact with a layer of code—visible as the Microsoft DirectX® for Visual Basic Classes—that marshals data from a Visual Basic application to the DirectX run time.

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 Direct3D device are accessible through the Direct3D object. This enables applications to select devices without creating them.

When a Microsoft® Direct3D® application written in Microsoft Visual Basic® starts, it must obtain a reference to the Direct3D8 class to access Direct3D functionality.

The following code example shows how to use the DirectX8.Direct3DCreate method to retrieve a reference to the Direct3D class.

Dim g_DX As New DirectX8
Dim g_D3D As Direct3D8

    Set g_D3D = g_DX.Direct3DCreate()

    If g_D3D Is Nothing Then Exit Function

To navigate from the Direct3DDevice object to the Direct3D object that created the device, use the Direct3DDevice8.GetDirect3D method.


Using Devices

This section provides information about using Microsoft® Direct3D® devices in an application. Information is divided into the following topics.

  • Determining Hardware Support
  • Selecting a Device
  • Creating a Device
  • Setting Transformations
  • Processing Vertex Data
  • Working with Mouse Cursors
  • Direct3D Resources


Determining Hardware Support

Microsoft® Direct3D® provides the following functions to determine hardware support.

Direct3D8.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.
Direct3D8.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.
Direct3D8.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 CheckDeviceFormat on both the depth-stencil and render-target formats.


Selecting a Device

Applications can query hardware to detect the supported Microsoft® Direct3D® device types. This section contains information on 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. 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-head display. Applications that are not concerned with multimonitor support can disregard this step, and pass D3DADAPTER_DEFAULT to the Direct3D8.EnumAdapterModes method in step 2.
  2. For each adapter, the application enumerates the supported display modes by calling EnumAdapterModes.
  3. If required, the application checks for the presence of hardware acceleration in each enumerated display mode by calling Direct3D8.CheckDeviceType. Note that this is only one of the possible uses for CheckDeviceType. For details see Determining Hardware Support.
  4. The application checks for the desired level of functionality for the device on this adapter by calling the Direct3D8.GetDeviceCaps method. This method filters out those devices that do not support the required functionality. The device capability returned by GetDeviceCaps is guaranteed to be constant for a device across all display modes verified by 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 Direct3D8.CheckDeviceFormat. If the device can render to the format, then it is guaranteed that all capabilities returned by 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 Direct3D8.CheckDeviceMultiSampleType method.

After completing the above 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 it offers to a user, or it should attempt to consume less memory by reducing the number of back buffers or using a less expensive 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 steps one and two 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 CheckDeviceType to determine if the device can support rendering to a back buffer of the specified format while in desktop mode. Direct3D8.GetAdapterDisplayMode can be used to determine the desktop display format.


Creating a Device

Note All rendering devices created by a given Microsoft® Direct3D® object share the same physical resources. Although your application can create multiple rendering devices from a single Direct3D object, because they share the same hardware, extreme performance penalties will be incurred.

To create a Direct3D device in a Microsoft Visual Basic® application, your application must first create a Direct3D object, as explained in Direct3D Object.

First, initialize values for the D3DPRESENT_PARAMETERS type 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 on VSYNC only.

Dim d3dDevice As Direct3DDevice8

    Dim d3dpp As D3DPRESENT_PARAMETERS

    d3dpp.Windowed = 1
    d3dpp.SwapEffect = D3DSWAPEFFECT_COPY_VSYNC

Next, create the Direct3D device. The following Direct3D8.CreateDevice call specifies the default adapter, a hardware abstraction layer (HAL) device, and software vertex processing.

    Set d3dDevice = g_D3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, _
                                      D3DCREATE_SOFTWARE_VERTEXPROCESSING, d3dpp)
    If d3dDevice Is Nothing Then Exit Function

After creating the device, set its state.


Setting Transformations

In Microsoft® Visual Basic®, transformations are applied by using the Direct3DDevice8.SetTransform method. For example, you could use code like the following to set the view transformation.

On Local Error Resume Next
Dim view As D3DMATRIX

' Fill in the view matrix.

Call d3dDevice.SetTransform(D3DTS_VIEW, view)

If Err.Number <> DD_OK Then
    ' Code to handle the error goes here.
End If

There are several possible settings for the first parameter in a call to SetTransform. The most common are D3DTS_WORLD, D3DTS_VIEW, and D3DTS_PROJECTION. These transformation states are defined by the CONST_D3DTRANSFORMSTATETYPE enumeration. This enumeration also contains the states D3DTS_TEXTURE1 through D3DTS_TEXTURE7, which you can use to apply transformations to texture coordinates.


Processing Vertex Data

The Direct3DDevice8 class 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_MODE_VERTEXPROCESSING

Specify one of the vertex processing behavior flags when calling Direct3D8.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.

You can consult the VertexProcessingCaps member of the D3DCAPS8 structure to determine the hardware vertex processing capabilities of the device. For software vertex processing the following capabilities are supported.

  • D3DVTXPCAPS_DIRECTIONALLIGHTS
  • D3DVTXPCAPS_LOCALVIEWER
  • D3DVTXPCAPS_MATERIALSOURCE7
  • D3DVTXPCAPS_POSITIONALLIGHTS
  • D3DVTXPCAPS_TEXGEN
  • D3DVTXPCAPS_TWEENING

In addition, the following table lists the values that are set for members of the D3DCAPS8 structure for a device in software vertex processing mode.

Member | Software Vertex Processing Capabilities
MaxActiveLights | Unlimited
MaxUserClipPlanes | 6
MaxVertexBlendMatrices | 4
MaxStreams | 16
MaxVertexIndex | 0xFFFFFFFF

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, 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.

Note The performance of hardware vertex processing is comparable to that of software vertex processing. For this reason, it's a good idea to provide, within a single device type, both hardware- and software-emulation functionality for vertex processing. This is not the case for rasterization, for which host processors are much slower than specialized graphics hardware. Thus both hardware- and software-emulated rasterization is not provided within a single device type. Software vertex processing is the only instance of functionality duplicated between the run time and the hardware (driver) within a single device. Thus all other device capabilities represent potentially variable functionality provided by the driver.


Working with Mouse Cursors

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 Microsoft® Win32® API–supported system mouse cursor. For more information on how to use a mouse cursor in your Microsoft® Direct3D® application, see the following reference topics.

  • Direct3DDevice8.ShowCursor
  • Direct3DDevice8.SetCursorPosition
  • Direct3DDevice8.SetCursorProperties

Direct3D ensures that the mouse will be supported either by hardware implementations or by the Direct3D run time performing hardware-accelerated blitting operations when calling Direct3DDevice8.Present.


Direct3D Resources

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. For more information on specific resource types, see Textures, Vertex Buffers, and Index Buffers.

All resources, including the geometry resources Direct3DIndexBuffer8 and Direct3DVertexBuffer8, implement the methods of the Direct3DResource8 class. The texture resources, Direct3DCubeTexture8, Direct3DTexture8, and Direct3DVolumeTexture8, also implement the methods of the Direct3DBaseTexture8 class.

Additional information is divided into the following topics.

  • Resource Properties
  • Resource Relationships
  • Managing Resources
  • Application-Managed Resources and Allocation Strategies
  • Manipulating Resources
  • Locking Resources


Resource Properties

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 2-D 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. The following usages are defined for resources.

  • D3DUSAGE_DEPTHSTENCIL
  • D3DUSAGE_DONOTCLIP
  • D3DUSAGE_DYNAMIC
  • D3DUSAGE_RTPATCHES
  • D3DUSAGE_NPATCHES
  • D3DUSAGE_POINTS
  • D3DUSAGE_RENDERTARGET
  • D3DUSAGE_SOFTWAREPROCESSING
  • D3DUSAGE_WRITEONLY

The D3DUSAGE_RTPATCHES, D3DUSAGE_NPATCHES, and D3DUSAGE_POINTS flags 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, then 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 on the usage flags and how they relate to specific resources, see the reference pages on the individual resource creation methods.

For information on the surface format of resources, see the CONST_D3DFORMAT enumeration.

The resources types are set implicitly at run time when the application calls a resource creation method such as Direct3DDevice8.CreateCubeTexture. Resource types are defined by the CONST_D3DRESOURCETYPE enumeration. Applications can query these types at run time; however, it is expected that most scenarios will not require run-time type checking.


Resource Relationships

The following diagram illustrates the operations that are syntactically possible on specific resources and their contents. For more information on how to use resources, see Manipulating Resources.

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

Resource management is the process where resources are promoted from system-memory storage to device-accessible storage and discarded from device-accessible storage. The Microsoft® 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 within a single frame—between Direct3DDevice8.BeginScene and Direct3DDevice8.EndScene calls.

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. The device can be restored with a call to Direct3DDevice8.Reset, and such resources continue to function normally without being reloaded with artwork. However, if the device must be destroyed and recreated, all resources created using D3DPOOL_MANAGED must be recreated.

Use the D3DPOOL_DEFAULT flag at creation time to specify that a resource be placed in the default pool. 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 recreated.

For more information on the lost state of a device, see Lost Devices.

Note that resource management is not supported for all types and usages. For example, objects created with the D3DUSAGE_RENDERTARGET flag are not supported. In addition, resource management is not recommended for objects whose contents are changing with high frequency. For example, a managed vertex buffer that changes every frame can significantly degrade performance for some hardware. However, this is not a problem for texture resources.


Application-Managed Resources and Allocation Strategies

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 as well as data pulled in from BSP 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. Because there are only a few different vertex strides that an application will use simultaneously, and a different vertex buffer is required only for each unique stride, the total number of dynamic vertex buffers is small. When managing dynamic resources in this way, it is important to ensure that high-frequency demands on the resources do not significantly decrease the application's performance.

When simultaneously using both D3D-managed and application-managed resources, all application managed resources should be allocated in D3DPOOL_DEFAULT memory prior to creating any managed resources. Allocating resources in D3DPOOL_DEFAULT memory after allocating resources in D3DPOOL_MANAGED memory will give the Microsoft® Direct3D® memory manager an inaccurate account of available memory.


Manipulating Resources

Your application manipulates resources in order to render a scene. First, the application creates texture resources by using the following methods.

  • Direct3DDevice8.CreateCubeTexture
  • Direct3DDevice8.CreateTexture
  • Direct3DDevice8.CreateVolumeTexture

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.

The application gains access to the contained surfaces, for the purpose of loading artwork, by calling the following methods. For details, see Locking Resources.

  • Direct3DCubeTexture8.LockRect
  • Direct3DTexture8.LockRect
  • Direct3DVolumeTexture8.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.

In addition, the application creates geometry-oriented resources by using the following methods.

  • Direct3DDevice8.CreateIndexBuffer
  • Direct3DDevice8.CreateVertexBuffer
  • D3DIndexBuffer8SetData
  • D3DVertexBuffer8SetData

If your application is allowing the Microsoft® Direct3D® run time to manage these resources, then the resource creation process ends here. Otherwise, the application manages the promotion of system memory resources to device-accessible resources, where the hardware accelerator can use them, by calling Direct3DDevice8.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 Direct3DDevice8.CreateDepthStencilSurface method. The application associates a device and its depth and color buffer with a call to Direct3DDevice8.SetRenderTarget.

For details on presenting the final image, see Presenting a Scene.


Locking Resources

Locking a resource means granting CPU access to its storage. The following locking methods 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. An application that specifies D3DUSAGE_WRITEONLY but then reads from the resource should expect a significant performance penalty. 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. Two-dimensional 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 DXT set of compressed texture formats, which store pixels in encoded 4×4 blocks, can only be locked on 4×4 boundaries.


Programmable Pipeline

Using shaders and effects, developers can now program the pipeline. These topics are covered in the following sections.

  • Vertex Shaders
  • Pixel Shaders


Vertex Shaders

Previous to Microsoft® DirectX® 8.n, Microsoft® Direct3D® operated a fixed function pipeline for converting three-dimensional (3-D) geometry to rendered screen pixels. The user sets attributes of the pipeline that control how Direct3D transforms, lights, and renders pixels. The fixed function vertex format is declared at compile time and determines the input vertex format. Once defined, the user has little control over pipeline changes during runtime.

Programmable shaders add a new dimension to the graphics pipeline by allowing the transform, lighting, and rendering functionality to be modified at runtime. A shader is declared at runtime but, once done, the user is free to change which shader is active as well as to control the shader data dynamically using streaming data. This gives the user a new level of dynamic flexibility over the way that pixels are rendered.

A vertex shader file contains vertex shader instructions. Vertex shaders can control vertex color and how textures are applied to vertices. Lighting can be added through the use of vertex shader instructions. The shader instruction file contains ASCII text so it is readable and in some ways looks similar to assembly language. A vertex shader is invoked after any DrawPrimitive or DrawIndexedPrimitive call. Shaders can be dynamically switched using SetVertexShader to specify a new shader file, or by changing the instructions in the ASCII text shader file using the streaming data inputs. The Vertex Shader Assembler Reference has a complete listing of shader instructions.

For additional information, see Debugging.


Pixel Shaders

Before Microsoft® DirectX® 8.x, Microsoft® Direct3D® used a fixed function pipeline for converting three-dimensional (3-D) geometry to rendered screen pixels. The user sets attributes of the pipeline that control how Direct3D transforms, lights, and renders pixels. The fixed function vertex format is declared at compile time and determines the input vertex format. Once defined, the user has little control over pipeline changes during run time.

Shaders add a new dimension to the graphics pipeline by allowing the vertex transform, lighting, and individual pixel coloring functionality to be programmed. Pixel shaders are short programs that execute for each pixel when triangles are rasterized. This gives the user a new level of dynamic flexibility over the way that pixels are rendered.

A pixel shader contains pixel shader instructions made up of ASCII text. Arithmetic instructions can be used to apply diffuse and/or specular color. Texture addressing instructions provide a variety of operations for reading and applying texture data. Functionality is available for masking and swapping color components. The shader ASCII text looks similar to assembly language and is assembled using Direct3DX assembler functions from either a text string or a file. The assembler output is a series of opcodes that an application may provide to Direct3D by means of Direct3DDevice8.CreatePixelShader. The Pixel Shader Reference has a complete listing of shader instructions.

To understand more about pixel shaders, see the following sections.

  • Texture Considerations details the texture stage states that are ignored during pixel shaders.
  • Confirming Pixel Shader Support gives a more detailed explanation of the structures for enumerating pixel shader support.
  • Converting Texture Operations gives examples of converting texture operations to pixel shader instructions.
  • Debugging provides debugging information.


Texture Considerations

The pixel shader completely replaces the pixel-blending functionality specified by the Microsoft® DirectX® 6.0 and 7.0 multi-texturing application programming interfaces (APIs), specifically those operations defined by the D3DTSS_COLOROP, D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAOP, D3DTSS_ALPHAARG1, and D3DTSS_ALPHAARG2 texture stage states, and associated arguments and modifiers. When a procedural pixel shader is set, these states are ignored.

Pixel Shaders and Texture Stage States

When pixel shaders are in operation, the following texture stage states are still observed.

  • D3DTSS_ADDRESSU
  • D3DTSS_ADDRESSV
  • D3DTSS_ADDRESSW
  • D3DTSS_BUMPENVMAT00
  • D3DTSS_BUMPENVMAT01
  • D3DTSS_BUMPENVMAT10
  • D3DTSS_BUMPENVMAT11
  • D3DTSS_BORDERCOLOR
  • D3DTSS_MAGFILTER
  • D3DTSS_MINFILTER
  • D3DTSS_MIPFILTER
  • D3DTSS_MIPMAPLODBIAS
  • D3DTSS_MAXMIPLEVEL
  • D3DTSS_MAXANISOTROPY
  • D3DTSS_BUMPENVLSCALE
  • D3DTSS_BUMPENVLOFFSET
  • D3DTSS_TEXCOORDINDEX
  • D3DTSS_TEXTURETRANSFORMFLAGS

Because these texture stage states are not part of the pixel shader, they are not available at shader compile time so the driver can make no assumptions about them. For example, the driver cannot differentiate between bilinear and trilinear filtering at that time. The application is free to change these states without requiring the regeneration of the currently bound shader.

Pixel Shaders and Texture Sampling

Texture sampling and filtering operations are controlled by the standard texture stage states for minification, magnification, mip filtering, and the wrap addressing modes. For more information, see Texture Stage States. This information is not available to the driver at shader compile time, so shaders must be able to continue operation when this state changes. The application is responsible for setting textures of the correct type (image map, cube map, volume map, etc.) needed by the pixel shader. Setting a texture of the incorrect type will produce unexpected results.

Post-Shader Pixel Processing

Other pixel operations—such as fog blending, stencil operations, and render target blending—occur after execution of the shader. Render target blending syntax is updated to support new features as described in this topic.

Pixel Shader Inputs

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

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.


Confirming Pixel Shader Support

You can query members of D3DCAPS8 to determine the level of support for operations involving pixel shaders. The following table lists the device capabilities related to programmable pixel processing in Microsoft® DirectX® 8.1.

Device capability | Description
MaxPixelShaderValue | Range of values that may be stored in registers is [-MaxPixelShaderValue, MaxPixelShaderValue].
MaxSimultaneousTextures | Number of texture stages that can be used in the programmable pixel shader.
PixelShaderVersion | Level of support for pixel shaders.

The PixelShaderVersion capability indicates the level of pixel shader supported. Only pixel shaders with version numbers equal to or less than this value will be successfully created. The major version number is encoded in the second byte of PixelShaderVersion. The low byte contains a minor version number. The pixel shader version is indicated by the first token in each shader.

Each implementation sets the PixelShaderVersion member to indicate the maximum pixel shader version that it can fully support. This implies that implementations should never fail the creation of a valid shader of the version less than or equal to the version reported by PixelShaderVersion.

Setting Pixel Shader Texture Inputs

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 can be associated with any stage, using either of the following two techniques. When using a fixed function vertex shader, the texture stage state flag TSS_TEXCOORDINDEX can be used in Direct3DDevice8.SetTextureStageState to associate coordinates with a stage. Otherwise, the texture coordinates are input by the vertex shader when using a programmable vertex shader.

Setting the Pixel Shader Constant Registers

You can use the following methods to set and retrieve the values in the pixel shader constant registers.

  • Direct3DDevice8.GetPixelShaderConstant
  • Direct3DDevice8.SetPixelShaderConstant

In addition, you can use the def instruction to set the constant registers of a pixel shader, inside a pixel shader. This instruction must come before all other instructions except the version instruction.

Compiling and Creating a Pixel Shader

The Direct3DX utility library provides a set of functions to compile pixel shaders. The following functions are provided.

  • D3DX8.AssembleShader
  • D3DX8.AssembleShaderFromFile

The Direct3DDevice8.CreatePixelShader create a pixel shader in DirectX 8.1 from a compiled shader declaration. The compiled shader declaration is obtained from D3DX8.AssembleShader.

A given shader might fail creation because of the restraints of the DirectX 8.1 hardware model.


Converting Texture Operations

Pixel shaders extend and generalize the multi-texture capabilities of Microsoft® DirectX® 6.0 and 7.0 in the following ways.

  • A set of general read/write registers is added to enable more flexible expression. The serial cascade using D3DTA_CURRENT requires the specification of a separate result register argument for each stage.
  • The D3DTOP_MODULATE2X and D3DTOP_MODULATE4X texture operations are broken into separate modifiers applicable to any instruction orthogonally. This eliminates the need for separate D3DTOP_MODULATE and D3DTOP_MODULATE2X operations.
  • The bias and unbias texture operation modifiers are orthogonal. This eliminates the need for separate add and add bias operations.
  • An optional third argument is added to modulate add, so the procedural pixel shader can do arg1×arg2 + arg0. This eliminates the D3DTOP_MODULATEALPHA_ADDCOLOR and D3DTOP_MODULATECOLOR_ADDALPHA texture operations.
  • An optional third argument is added to the blend operation, so the procedural pixel shader can use arg0 as the blend proportion between arg1 and arg2. This eliminates the D3DTOP_BLENDDIFFUSEALPHA, D3DTOP_BLENDTEXTUREALPHA, D3DTOP_BLENDFACTORALPHA, D3DTOP_BLENDTEXTUREALPHAPM, and D3DTOP_BLENDCURRENTALPHA texture operations.
  • Texture address modifying operations, such as D3DTOP_BUMPENVMAP, are broken out from the color and alpha operations and defined as a third operation type, specifically for operating on texture addresses.

To support this increased flexibility efficiently, the application programming interface (API) syntax is changed from DWORD pairs to an ASCII assemble code syntax. This exposes the functionality offered by procedural pixel shaders.

Note When you use pixel shaders, specular add is not specifically controlled by a render state, and it is up to the pixel shader to implement if needed. However, fog blending is still applied by the fixed function pipeline.


Debugging

As an example, run the application and type the following instructions in the instruction window.

ps.1.0
tex t0
mov r0, t0

This results in the Microsoft® DirectX® 5 logo image in the rendered view window.

This shader applies a texture map. Notice that the compilation result text window says Success, which indicates that all the instructions are valid.

Next, remove the second instruction, which is the texture declaration. Once this is deleted, the compilation result says:

(Statement 2) (Validation Error) Read of uninitialized components(*) in t0: *R/X/0 *G/Y/1 *B/Z/2 *A/W/3

This error identifies the statement that fails, Statement 2, and why it fails Uninitialized component in t0. You can fix this problem by adding Statement 2 again. When you do this, the shader works again.

This is a simple example but it illustrates the usefulness of the tool. By trying different instructions, registers, and instruction sequences, you can better understand pixel shaders and vertex shaders. The sample application also has an Open button, which supports loading of a shader file so that you can load any shader files you have already created.

Shader Debuggers

Some graphics chip companies provide a shader debugging tool on their Web sites. Find these tools by searching the Web or by reading the article listed below. You can attach a debugger to a program while it is running and use the debugger to step through a shader. By setting breakpoints, you can step through the shader code one line at a time and watch register state changes. For more information about vertex shaders and debugging tips, see Using Vertex Shaders: Part 1.

Texture Blending Debugging

Another sample application that is part of the software development kit (SDK) installation is MFCTex. This Microsoft Foundation Classes (MFC) application is a good way to learn how to perform multi-texture blending operations in the fixed function pipeline.

Diagnostic Support

Another option for help with debugging DirectX problems is to use the DirectX Diagnostic Viewer (DXDiag.exe) to create a dump of your machine. This is done by running DxDiag.exe after your machine has crashed and sending the dump to Microsoft, using either the Report button on the More Help tab or by sending it to directx@microsoft.com. The dump can be used to track down and reproduce the problem.

Additional debug information can be found at http://msdn.microsoft.com/directx


Advanced Topics

Microsoft® Direct3D® provides a powerful set of tools that you can use to increase the realistic appearance of a 3-D scene. This section presents information on common special effects that can be produced with Direct3D, but the range of possible effects is not limited to those presented here. The discussion in this section is organized into the following topics.

  • Antialiasing
  • Bump Mapping
  • Environment Mapping
  • Geometry Blending
  • Indexed Vertex Blending
  • Stencil Buffer Techniques
  • Vertex Tweening
  • Object Geometry


Antialiasing

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.

Microsoft® Direct3D® supports two antialiasing techniques: edge antialiasing and full-surface antialiasing. Which technique is best for your application depends on your requirements for performance and visual fidelity.

  • Full-Scene Antialiasing

The section below shows how to use special effects to simulate or use antialiasing.

  • Motion Blur


Full-Scene Antialiasing

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, only affects triangles and groups of triangles; lines cannot be antialiased by using Microsoft® 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 Direct3D8.CreateDevice method, you must determine if full-scene antialiasing is supported. Do this by calling the Direct3D8.CheckDeviceMultiSampleType method as shown in the code example below.

'
' The code below assumes that D3D is a valid pointer
' to a Direct3D8 object.
'

Call D3D.CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
                                     D3DFMT_R8G8B8, 0,
                                     D3DMULTISAMPLE_2_SAMPLES )

The first parameter that 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 CONST_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 (1) or full-scene antialiasing (0). This sample uses 0 to tell Direct3D that it is inquiring about full-scene antialiasing. The last parameter specifies the multisampling technique to test. Use a value from the CONST_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 D3D is a valid Direct3D8
' object and D3DDevice is a valid Direct3DDevice8 object.
'

Dim d3dpp As D3DPRESENT_PARAMETER
d3dpp.Windowed = FALSE
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD
d3dpp.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES
Set D3DDevice = D3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                 D3DCREATE_SOFTWARE_VERTEXPROCESSING, d3dpp )

Note 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 Direct3DDevice8.SetRenderState method and setting the D3DRS_MULTISAMPLEANTIALIAS to 1. After setting this value to 1, any rendering that you do has multisampling applied to it. You might want to enable and disable multisampling depending on what you are rendering to the scene.


Motion Blur

You can enhance the perceived speed of an object in a 3-D scene by blurring the object and leaving a blurred trail of object images behind the object. Microsoft® 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 Direct3DDevice8.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 3-D 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 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.


Bump Mapping

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. The following image, based on the C++ BumpEarth Sample, demonstrates bump mapping effects.

The globe on the left is a sphere textured with an image of the Earth's surface, with a specular environment map applied. The globe on the right is exactly the same, but also has a bump map applied. The polygon count for the second globe is unchanged from that of the first globe.

Bump mapping in Microsoft® 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. For more information, see Bump Map Pixel Formats.

The BumpEarth sample uses a height map to store contour data. When the sample starts, it processes the pixels in the height map to compute the appropriate u and v delta values, based on the relative height of each pixel to the four neighboring pixels.

Direct3D does not natively support height maps; they are merely a convenient format in which to store and visualize contour data. The preceding image is based on the height map used by the BumpEarth sample to produce the bump map it supplies to Direct3D. and is included here for descriptive purposes. Your application can store contour information in any format.

This is the height map image that the BumpEarth sample uses to compute the delta values encoded in the pixel format of the bump map texture.

Bump mapping relies completely on multiple texture blending services, and requires that the device 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 a base texture map, the most common case. The following figure shows the relationships between the base texture, the bump map, and the environment map in the texture blending cascade.

You must prepare the texture stages appropriately to enable bump mapping. This task is the topic of Configuring Bump Mapping Parameters.

This section provides information about performing bump mapping with Microsoft® Direct3D®. The following topics introduce bump mapping, identify and define its key concepts, and provide details about how you can use bump-mapping in your applications.

  • Bump Map Pixel Formats
  • Bump Mapping Formulas
  • Using Bump Mapping


Bump Map Pixel Formats

A bump map is a IDirect3DTexture8 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 topic.

You can specify a bump map pixel format by setting the CONST_D3DFORMAT enumerated type to one of the following bump map pixel formats.

Format | Description
D3DFMT_V8U8 | 16-bit bump-map format.
D3DFMT_L6V5U5 | 16-bit bump-map format with luminance.
D3DFMT_X8L8V8U8 | 32-bit bump-map format with luminance where 8 bits are reserved for each element.
D3DFMT_Q8W8V8U8 | 32-bit bump-map format.
D3DFMT_V16U16 | 32-bit bump-map format.
D3DFMT_W11V11U10 | 32-bit bump-map format.

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, you should check if the particular format is supported. For more information, see Detecting Support for Bump Mapping.


Bump Mapping Formulas

Microsoft® Direct3D® applies the following formulas to the Du and Dv components in each bump map pixel.

In these formulas, the Du and Dv variables are taken directly from a bump map pixel and transformed by a 2×2 matrix to produce the output delta values Du' and Dv'. 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.

In this formula, L' is the output luminance being computed; L' is clamped to the range of 0.0 to 1.0, inclusive. 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

Detecting Support for Bump Mapping

A Microsoft® Direct3D® device can perform bump mapping if it supports either the D3DTOP_BUMPENVMAP or D3DTOP_BUMPENVMAPLUMINANCE texture blending operation. 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.

Function SupportsBumpMapping As Bool
{
    Dim d3dCaps As D3DCAPS8

    m_D3DDevice.GetDeviceCaps d3dCaps

    // Does this device support the two bump mapping blend operations?
    If ( d3dCaps.TextureOpsCaps And _
         ( D3DTEXOPCAPS_BUMPENVMAP Or D3DTEXOPCAPS_BUMPENVMAPLUMINANCE ) = 0) Then
         SupportBumpMapping = 0
    End If

    // Does this device support up to three blending stages?
    If d3dCaps.MaxTextureBlendStages < 3 Then
        SupportBumpMapping = 0
    End If

    SupportBumpMapping = 1
}

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.

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.

' Create the bump map texture.
' Set the color operations and arguments to prepare for bump mapping.
' Stage 0: the base texture.
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE)
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE)
Call d3dDevice.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1)
Call d3dDevice.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE)
Call d3dDevice.SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 1)

' Stage 1: the bump map - Use luminance for this example.
Call d3dDevice.SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1)
Call d3dDevice.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_BUMPENVMAPLUMINANCE)
Call d3dDevice.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDevice.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT)

' Stage 2: a specular environment map.
Call d3dDevice.SetTextureStageState(2, D3DTSS_TEXCOORDINDEX, 0)
Call d3dDevice.SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_ADD)
Call d3dDevice.SetTextureStageState(2, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDevice.SetTextureStageState(2, D3DTSS_COLORARG2, D3DTA_CURRENT)

Once the blending operations and arguments are set, the following code example sets the 2×2 bump mapping matrix to the identity matrix, by setting the D3DTSS_BUMPENVMAT00 and D3DTSS_BUMPENVMAT11 texture stage states 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.
Call d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVMAT00, 1#)
Call d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVMAT01, 0#)
Call d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVMAT10, 0#)
Call d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVMAT11, 1#)

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.

' 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.
Call d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVLSCALE, 0.5)
Call d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVLOFFSET, 0#)

After your application configures bump mapping parameters, it can render as normal, and the rendered polygons receive bump mapping effects.

Note 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.


Environment Mapping

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 expensive computations involved in ray tracing.

The following image is taken from the C++ SphereMap Sample, which, as its name implies, uses a type of environment mapping called spherical environment mapping. For details, see Spherical Environment Mapping.

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 Microsoft® 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

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.

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.

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 Direct3DDevice8.CreateCubeTexture method to the number of levels that you want. You can envision the topography of these surfaces as shown in the following graphic.

Applications that create mipmapped cubic environment maps can access each face by calling the Direct3DCubeTexture8.GetCubeMapSurface method. Start by setting the appropriate value from the D3DCUBEMAP_FACES enumerated type, as discussed in Accessing Cubic Environment Map Faces. Next, select the level to retrieve by setting the Level parameter to the mipmap level that you want. Remember that 0 corresponds with the top-level image.

Texture Coordinates for Cubic Environment Maps

'
' Create a flexible vertex format descriptor for a vertex that
' contains a position, normal, and one set of 3-D texture
' coordinates.
'/
Const D3DFVF CUSTOMVERTEX = (D3DFVF_XYZ Or D3DFVF_NORMAL Or _
                             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 TnLHAL Device, it can be significantly faster than the computations 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 flag and the index of a texture coordinate set. In some situations, like diffuse light mapping, you might use the D3DTSS_TCI_CAMERASPACENORMAL flag, 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 Direct3DDevice8 object.
'
' 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 Or 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:

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.

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 topics.

  • Creating Cubic Environment Map Surfaces


Creating Cubic Environment Map Surfaces

You create a cubic environment map texture by calling the D3DX8.CreateCubeTexture method. Cubic environment map textures must be square, with dimensions that are a power of two.

The following code shows how your Microsoft® Visual Basic® application might create a simple cubic environment map.

'
' For this example, d3dDevice is a valid Direct3DDevice8
' object and g_D3DX is a valid Direct3DX object.
'
Dim CubeMap As Direct3DCubeTexture8 CubeTexture

Set CubeMap = g_D3DX.CreateCubeTexture( d3dDevice, 256, 1, D3DUSAGE_RENDERTARGET, _
                                        D3DFMT_R8G8B8, D3DPOOL_MANAGED )

Accessing Cubic Environment Map Faces

You can navigate between faces of a cubic environment map by using the Direct3DCubeTexture8.GetCubeMapSurface method.

The following code example uses GetCubeMapSurface to retrieve the cube-map surface used for the positive-y face (face 2).

'
' For this example, CubeMap is a valid
' Direct3DCubeTexture8 object.
'
Dim Face2 As Direct3DSurface8

Set Face2 = CubeMap.GetCubeMapSurface( D3DCUBEMAP_FACE_POSITIVE_Y, 0 )

The first parameter that GetAttachedSurface accepts is a CONST_D3DCUBEMAP_FACES enumerated value that describes the attached surface that the method should retrieve. The second parameter tells Microsoft® Direct3D® which level of a mipmapped cube texture to retrieve. Because this cube-map is not mipmapped, 0 is used here.

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 Microsoft® Visual Basic® code example prepares and sets a view matrix according to the face being rendered.

'
' For this example, CubeMap is a valid Direct3DCubeTexture8 object
' and m_D3DDevice is a valid Direct3DDevice8 object.
'
Sub RenderFaces

    ' Save transformation matrices of the device.
    Dim matProjSave As D3DMATRIX, _
        matViewSave As D3DMATRIX
    m_D3DDevice.GetTransform D3DTS_VIEW, matViewSave
    m_D3DDevice.GetTransform D3DTS_PROJECTION, matProjSave

    ' Store the current back buffer and z-buffer.
    Dim BackBuffer As Direct3DSurface8, _
        Zbuffer As Direct3DSurface8
    Set BackBuffer = m_D3DDevice.GetRenderTarget()
    Set Zbuffer = m_D3DDevice.GetDepthStencilSurface()

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.
    Dim matProj As D3DMATRIX
    D3DXMatrixPerspectiveFovLH matProj, g_pi/4, 1, 1/2, 1000
    m_D3DDevice.SetTransform D3DTS_PROJECTION, matProj

    ' Loop through the six faces of the cube map.
    Dim i As Integer
    For i = 0 To 6

        'Standard view that will be overridden below.
        Dim vEnvEyePt As D3DVECTOR, _
            vLookatPt As D3DVECTOR, _
            vUpVec As D3DVECTOR

        Select Case i

            case D3DCUBEMAP_FACE_POSITIVE_X:
                vLookatPt.x = 1#: vUpVec.y = 1#

            case D3DCUBEMAP_FACE_NEGATIVE_X:
                vLookatPt.x = -1#: vUpVec.y = 1#

            case D3DCUBEMAP_FACE_POSITIVE_Y:
                vLookatPt.y = 1#: vUpVec.z = -1#

            case D3DCUBEMAP_FACE_NEGATIVE_Y:
                vLookatPt.y = -1#: vUpVec.z = 1#

            case D3DCUBEMAP_FACE_POSITIVE_Z:
                vLookatPt.z = 1#: vUpVec.y = 1#

            case D3DCUBEMAP_FACE_NEGATIVE_Z:
                vLookatPt.z = -1#: vUpVec.y = 1#

        End Select

        Dim matView As D3DMATRIX
        D3DXMatrixLookAtLH matView, vEnvEyePt, vLookatPt, vUpVec
        m_D3DDevice.SetTransform D3DTS_VIEW, matView

Once 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 cube surface in order to render to it.
        Dim Face As Direct3DSurface8
        Set Face = CubeMap.GetCubeMapSurface i, 0
        m_D3DDevice.SetRenderTarget Face, Zbuffer
        Set Face = Nothing

        m_D3DDevice.BeginScene
        ' Render scene here.
        m_D3DDevice.EndScene

    Next

    ' Change the render target back to the main back buffer.
    m_D3DDevice.SetRenderTarget BackBuffer, pZBuffer
    Set BackBuffer = Nothing
    Set Zbuffer = Nothing

    // Restore the original transformation matrices.
    m_D3DDevice.SetTransform D3DTS_VIEW, matViewSave
    m_D3DDevice.SetTransform D3DTS_PROJECTION, matProjSave

End Sub

Note the call to the Direct3DDevice8.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 method.


Spherical Environment Mapping

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 topic shows the reflection effects you can achieve with sphere mapping.

A sphere map is a 2-D representation of the full 360-degree view of the scene surrounding of an object, as if taken through a fish-eye lens. The following illustration is the sphere map used by the C++ SphereMap Sample.

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.

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 Direct3DDevice8.SetTexture method. Set the first parameter to the index for the desired texture stage, and set the second parameter to the address of the Direct3DTexture8 object 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.


Geometry Blending

Microsoft® 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.

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 1.

Without geometry blending, dynamic articulated models are often rendered in segments. For instance, consider a 3-D 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.

Type Arm
    upper_arm_verts(200) As D3DVERTEX
    matWorld_Upper As D3DMATRIX

    lower_arm_verts(200) As D3DVERTEX
    matWorld_Lower As D3DMATRIX
End Type

Dim MyArm As Arm ' This needs to be initialized.

To render the arm, two rendering calls are made, as shown in the following code.

' Render the upper arm.
Call d3DDevice.SetTransform(D3DTS_WORLD, MyArm.matWorld_Upper)
Call 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)
Call d3DDevice.SetTransform(D3DTS_WORLD, MyArm.matWorld_Lower)
Call d3DDevice.DrawPrimitive(D3DPT_TRIANGLELIST, 0, numFaces)

The following image is a banana, modified to use this technique.

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 Direct3DDevice8.SetTransform method recognizes the D3DTS_WORLD, D3DTS_WORLD1, D3DTS_WORLD2, and D3DTS_WORLD3 members of the CONST_D3DTRANSFORMSTATETYPE enumeration to identify the matrices between which geometry will be blended. The D3DTS_WORLD member might be thought of as D3DTS_WORLD0.

The CONST_D3DRENDERSTATETYPE enumeration includes the D3DRS_VERTEXBLEND render state to enable and control geometry blending. Valid values for this render state are defined by the CONST_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.

The system performs a linear blend between the weighted results of the blend matrices. The following is the complete blending formula.

In the preceding formula, vBlend is the output vertex, the v-elements are the vertices produced by the applied world matrix. The W elements are the corresponding weight values within the vertex format. A vertex blended between n matrices can have n–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.

These are the simplified forms of the complete blending formula for the two, three, and four blend matrix cases.

Note Although Direct3D includes flexible vertex format descriptors to define vertices that contain up to five blending weights, only three can be used in this release of Microsoft DirectX®.

Additional information is contained in the following topic.

  • Using Geometry Blending


Using Geometry Blending

The following user-defined structure can be used for vertices that will be blended between two matrices.

'
' The flexible vertex format descriptor for this vertex would be:
'
'     FVF = (D3DFVF_XYZB1 Or D3DFVF_NORMAL Or D3DFVF_TEX1)
'
Type D3DBLENDVERTEX
    v As D3DVECTOR
    blend As Single
    n As D3DVECTOR
    tu As Single
    tv As Single
End Type

The blend weight must appear after the position and RHW data in the flexible vertex format, 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_WORLD and D3DTS_WORLD1 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 Direct3DDevice8.SetTransform method. Set the first parameter to a D3DTS_WORLD member from the CONST_D3DTRANSFORMSTATETYPE enumeration, and set the second parameter to the address of the matrix to be set.

The following Microsoft® Visual Basic® code example sets two world matrices between which geometry will be blended to create the illusion of a jointed arm.

' For this example, the d3dDevice variable is assumed to be a valid
' reference to a Direct3DDevice8 object for an initialized 3-D scene.
' The dx variable is a valid reference to a DirectX7 object.
Dim BendAngle As Single
Dim matUpperArm As D3DMATRIX, _
    matLowerArm As D3DMATRIX

BendAngle = 3.1415926 / 4#  ' 45 degrees

' The upper arm is immobile. Use the identity matrix.
D3DXMatrixIdentity matUpperArm
Call d3dDevice.SetTransform(D3DTS_WORLD, matUpperArm)

' The lower arm rotates about the x-axis, attached to the upper arm.
D3DXMatrixRotationX matLowerArm, -nBendAngle
Call d3dDevice.SetTransform(D3DTS_WORLD1, 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 Direct3DDevice8.SetRenderState method to set the D3DRS_VERTEXBLEND render state to a value from the CONST_D3DVERTEXBLENDFLAGS enumeration. The following code example shows what this call might look like when setting the render state for a blend between two world matrices.

Call d3dDevice.SetRenderState(D3DRS_VERTEXBLEND, D3DVBF_1WEIGHT)

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 Microsoft® Direct3D® rendering methods.

When enabled, the system performs geometry blending for all objects rendered by the DrawPrimitive rendering methods.

See Also

Vertex Formats


Indexed Vertex Blending

Indexed vertex blending extends the vertex blending support in Microsoft® 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.

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.

The following formula determines the general case for how matrices effect a vertex.

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.

Additional information is contained in the following topic.

  • Using Indexed Vertex Blending


Using Indexed Vertex Blending

Transform and Render States

Transform states 256-511 are reserved to store up to 256 matrices that can be indexed using 8-bit indices. Use the function below to map indices 0-255 to the corresponding transform states.

Function D3DTS_WORLDMATRIX(index as Long) As Long
    D3DTS_WORLDMATRIX=(index + 256)
End Function

The following code example shows how to use the Direct3DDevice8.SetTransform method to set the matrix at transform state number 256 to an identity matrix.

Dim matBlend1 As D3DMATRIX

Call D3DXMatrixIdentity(matBlend1)
Call m_D3DDevice.SetTransform(D3DTS_WORLDMATRIX(0), matBlend)

To enable or disable indexed vertex blending, set the D3DRS_INDEXVERTEXBLENDENABLE render state to 1. When the render state is enabled, you must pass matrix indices as packed Longs 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 Direct3DDevice8.SetRenderState method to enable indexed vertex blending.

Call m_D3DDevice.SetRenderState(D3DRS_INDEXVERTEXBLENDENABLE, 1)

To enable or disable vertex blending, set the D3DRS_VERTEXBLEND 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 SetRenderState to enable vertex blending with three weights for each vertex.

Call m_D3DDevice.SetRenderState(D3DRS_VERTEXBLEND, D3DVBF_3WEIGHTS)

Determining Indexed Vertex Blending Support

Dim d3dCaps As D3DCAPS8

Call D3DDevice.GetDeviceCaps(d3dCaps)
IndexedMatrixMaxSize = d3dCaps.MaxVertexBlendMatrixIndex

If the value set in MaxVertexBlendMatrix is 0, then 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 Microsoft® Direct3D® by using legacy vertex shaders (FVF) or declarations.

The code example below shows how to use legacy vertex shaders.

Private Type VERTEX
    x As Single
    y As Single
    z As Single
    weight As Single
    matrixIndices As Long
    normal(2) As Single
End Type

Const D3DFVF_CUSTOMVERTEX = (D3DFVF_XYZB2 Or D3DFVF_NORMAL Or _
                             D3DFVF_LASTBETA_UBYTE4)

When a legacy vertex shader is used, matrix indices are passed together with vertex positions using D3DFVF_XYZBn flags. Matrix indices are passed as a packed byte and must be present immediately after the last vertex weight. Vertex weights are also passed using D3DFVF_XYZBn. A packed byte contains index3, index2, index1, and index0, where index0 is located in the lowest byte of the byte. 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.

Private Type VERTEX
    x As Single
    y As Single
    z As Single
    matrixIndices As Long
    weight As Single
    normal(2) As Single
End Type

Dim decl(5) As Long

decl(0) = D3DVSD_STREAM(0)
decl(1) = D3DVSD_REG(D3DVSDE_POSITION, D3DVSDT_FLOAT3)
decl(2) = D3DVSD_REG(D3DVSDE_BLENDINDICES, D3DVSDT_PACKEDBYTE)
decl(3) = D3DVSD_REG(D3DVSDE_BLENDWEIGHT, D3DVSDT_FLOAT1)
decl(4) = D3DVSD_REG(D3DVSDE_NORMAL, D3DVSDT_FLOAT3)
decl(5) = D3DVSD_END()


Stencil Buffer Techniques

Applications use the stencil buffer to mask pixels in an image. The mask controls whether the pixel is drawn.

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 Direct3D8.CheckDeviceFormat to check for hardware stencil support, as shown in the following code example.

' The following example assumes that g_D3D, AdapterOrdinal,
' DeviceType, and Format are properly initialized values.

g_D3D.CheckDeviceFormat AdapterOrdinal, DeviceType, Format, _
                        D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, _
                        D3DFMT_D24S8
If Err.Number <> D3D_OK Then
    ' Handle the error.
End If

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 set Err.Number to an error value. Note that this is only one possible use for CheckDeviceFormat; for details see Determining Hardware Support.

To determine the stencil buffer limitations of a device, query the StencilCaps member of the D3DCAPS8 structure for its supported stencil buffer operations.

How the Stencil Buffer Works

Microsoft® 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 And StencilMask) CompFunc (StencilBufferValue And 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 CONST_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 Microsoft® Direct3D® takes when the stencil test passes or fails. For more information, see Stencil Buffer State.

Microsoft® Direct3D® applications can achieve a wide range of special effects with the stencil buffer. Some of the more common effects are discussed in this section.

  • Dissolves, Fades, and Swipes
  • Decaling
  • Compositing
  • Outlines and Silhouettes


Dissolves, Fades, and Swipes

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 Microsoft® 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 3-D scene. Fading out is the opposite, your application starts with a rendering of a 3-D 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.


Decaling

Microsoft® 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.


Compositing

Your application can use the stencil buffer to composite 2-D or 3-D images onto a 3-D scene. A mask in the stencil buffer is used to occlude an area of the rendering target surface. Stored 2-D information, such as text or bitmaps, can then be written to the occluded area. Alternately, your application can render additional 3-D primitives to the stencil-masked region of the rendering target surface. It can even render an entire scene.

Games often composite multiple 3-D scenes together. For instance, driving games typically display a rear-view mirror. The mirror contains the view of the 3-D scene behind the driver. It is essentially a second 3-D scene composited with the driver's forward view.


Outlines and Silhouettes

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.


Vertex Tweening

Vertex tweening is used to blend two user-provided positions or normal streams. It can be used only with declarations. Tweening is enabled by setting D3DRS_VERTEXBLEND to D3DVBF_TWEENING. Vertex blending using weights and vertex blending tweening are mutually exclusive.

The Visual Basic Dolphin Sample uses vertex tweening to animate a dolphin so that it appears to move through the water. The images below show the dolphin at two different points. Notice that the dolphin's tail has gone from an up position to a down position and its nose points downward more in the right image.

›

Tweening is performed before lighting and clipping. The resulting vertex position (normal) is computed as follows:

POSITION = POSITION1 * (1.0 - TWEENFACTOR) + POSITION2 * TWEENFACTOR, and likewise for normals.

Additional information is contained in the following topic.

  • Using Vertex Tweening

Vertex Shader Tweening

Call d3dDevice.CreateVertexShader(decl, vsFunction, handle, 0)

The second parameter for CreateVertexShader takes a pointer to a vertex shader function token array. This function can be created by calling any of the following functions.

  • D3DX8.AssembleShader
  • D3DX8.AssembleShaderFromFile

The code example below assembles a vertex shader from the file AppTween.vsh.

Set vsFunction = d3dx.AssembleShaderFromFile( "AppTween.vsh", 0, ErrorLog, vsFunction)


Using Vertex Tweening

Determining Support for Vertex Tweening

To determine if Microsoft® Direct3D® supports vertex tweening, check for the D3DVTXPCAPS_TWEENING flag in the VertexProcessingCaps member of the D3DCAPS8 structure. The following code example uses the Direct3DDevice8.GetDeviceCaps method to determine if tweening is supported.

'
' This example assumes that d3dDevice
' is a valid Direct3DDevice object.
'
Dim d3dCaps As D3DCAPS8

d3dDevice.GetDeviceCaps d3dCaps
If 0 <> (d3dCaps.VertexProcessingCaps & D3DVTXPCAPS_TWEENING) Then
    'Vertex tweening is supported.
End If

Setting Vertex Declaration

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.

Private Type TEX_VERTEX
    Position As D3DVECTOR
    Normal As D3DVECTOR
    Position2 As D3DVECTOR
    Normal2 As D3DVECTOR

' 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.

Dim decl(5) As Long

decl(0) = D3DVSD_STREAM(0)
decl(1) = D3DVSD_REG( D3DVSDE_POSITION, D3DVSDT_FLOAT3 ) 'Position 1
decl(2) = D3DVSD_REG( D3DVSDE_NORMAL, D3DVSDT_FLOAT3 )   'Normal 1
decl(3) = D3DVSD_REG( D3DVSDE_POSITION2, D3DVSDT_FLOAT3) 'Position 2
decl(4) = D3DVSD_REG( D3DVSDE_NORMAL2, D3DVSDT_FLOAT3 )  'Normal 2
decl(5) = D3DVSD_END()

For more information on creating a custom vertex type and a vertex buffer, see Creating a Vertex Buffer.

Notes When vertex tweening is enabled, a second position or a second normal must be present in the current declaration.

Fixed-Function Tweening

The code example below shows how to implement fixed-function vertex tweening after a vertex type and declaration are set.

' Variables used for this example
Dim handle As Long
Dim TweenFactor As Float

TweenFactor = 0.3

The first step is to use the Direct3DDevice8.CreateVertexShader method to create a vertex shader, as shown in the code example below.

Call d3dDevice.CreateVertexShader(decl, ByVal 0, handle, 0)

The first parameter accepted by CreateVertexShader is a vector shader declaration. This example uses the declaration declared above. The second parameter accepts a vertex shader function array. This example does not use a vertex shader function, so this parameter is set to ByVal 0. The third parameter accepts a vertex shader handle representing the returned vertex. The fourth parameter specifies the usage controls for the vertex shader. You can use the D3DUSAGE_SOFTWAREPROCESSING flag to indicate that the vertex shader should use software vertex processing. This example sets this parameter to zero to indicate that vertex processing should be done in hardware.

The next step is to set the current vertex shader by calling the Direct3DDevice8.SetVertexShader method as shown in the code example below.

Call d3dDevice.SetVertexShader(handle)

SetVertexShader accepts a handle to a vertex shader. The value for this parameter can be a handle returned by CreateVertexShader or an FVF code. This example uses the handle returned from CreateVertexShader called in the last step.

The next step is to set the current render state to enable vertex tweening, set the tween factor, and set the stream source. The code example below uses Direct3DDevice8.SetRenderState and Direct3DDevice8.SetStreamSource to accomplish this.

Call d3dDevice.SetRenderState(D3DRS_VERTEXBLEND, D3DVBF_TWEENING)
Call d3dDevice.SetRenderState(D3DRS_TWEENFACTOR, TweenFactor)
Call d3dDevice.SetStreamSource(0 ,vb, 12*Len(vb(0))

If you have more than one stream specified for the current vertex shader, you need to call SetStreamSource for each stream that will be used for the tweening effect. At this point, vertex tweening is enabled. A call to any rendering function automatically has vertex tweening applied to it.


Object Geometry

Direct3D supports several higher leverl abstractions for handling geometry. These are broken down into the following topics.

  • Index Buffers
  • Vertex Buffers
  • Higher-Order Primitives
  • Point Sprites


Index Buffers

Index buffers, represented by the Direct3DIndexBuffer8 class, are memory buffers that contain index data. Index data, or indices, are integer offsets into vertex buffers and are used for rendering primitives using the Direct3DDevice8.DrawIndexedPrimitive method.

VertexBuffers and index buffers are orthogonal concepts, that is, you can use indexed primitives with or without vertex buffers, or you can use a vertex buffer with or without indexed primitives.

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. For more information about this task, see Access the Contents of an 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 simply stores the size, in bytes, of the vertex buffer data.

Additional information is contained in the following topics.

  • Create an Index Buffer
  • Access the Contents of an Index Buffer
  • Render from an Index Buffer


Create an Index Buffer

Create an index buffer object by calling the Direct3DDevice8.CreateIndexBuffer method, which accepts five 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 CONST_D3DFORMAT enumerated type that specifies the size of each index.

The fourth parameter is a member of the CONST_D3DPOOL enumerated type that tells the system where in memory to place the new index buffer.

The following Visual Basic code example shows what creating a index buffer might look like in code.

'
' For the purposes of this example, the m_D3DDevice variable is
' an IDirect3DDevice8 interface exposed by a Direct3DDevice
' object. IB is a variable of type Direct3DIndexBuffer8.
'

Set IB = m_D3DDevice.CreateIndexBuffer(16834, D3DUSAGE_WRITEONLY,
                                       D3DFMT_INDEX16, D3DPOOL_DEFAULT)

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, nonlocal video memory, or system memory.

Setting the D3DUSAGE_SOFTWAREPROCESSING behavior flag when calling the Direct3DDevice8.CreateIndexBuffer method specifies that the vertex 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 expend video memory or expand large amounts of page-locked RAM when the driver is putting vertex or index buffers into AGP memory.


Access the Contents of an Index Buffer

Index buffers enable Microsoft® Visual Basic® applications to easily update the index data they contain. To lock, fill, and unlock index buffers use the D3DIndexBuffer8SetData helper function. D3DIndexBuffer8SetData accepts five parameters, The first, Ibuffer, is the Direct3DIndexBuffer8 object that contains the index data. The second parameter, Offset, is the offset into the index data. The third parameter is the size, measured in bytes, of the index data.

The fourth 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 Microsoft® Direct3D® to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

The last parameter accepted by the D3DIndexBuffer8SetData helper function, Data, is the first element of an array of data to load into the index buffer. Note this parameter is of type Any. To use it properly, you must specify the first element of the array for Data, as shown in the following code example.

Dim Indices(2) As CUSTOMINDEX
Dim IndexSizeInBytes As Long

'Determine the length of the index data.
IndexSizeInBytes = Len(Indices(0))

'Copy indices into the index buffer.
D3DIndexBuffer8SetData VB, 0, IndexSizeInBytes * 3, 0, Indices(0)

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.

See Using Dynamic Vertex and Index Buffers for information on using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

To lock, read, and unlock the contents of index buffers, use the D3DIndexBuffer8GetData helper function.

Retrieving Index Buffer Descriptions

Retrieve information about an index buffer by calling the Direct3DIndexBuffer8.GetDesc method. This method fills the members of the D3DINDEXBUFFER_DESC structure with information about the vertex buffer.


Render from an Index Buffer

Rendering index data from an index buffer requires a few steps. First, you must set the stream source by calling the Direct3DDevice8.SetStreamSource method.

Call m_D3DDevice.SetStreamSource( 0, VB, len(CUSTOMVERTEX) )

The first parameter of 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 call the Direct3DDevice8.SetIndices method to set the source of the index data.

Call m_D3DDevice.SetIndices( IB, 0 )

The first parameter that SetIndices accepts is the address of the index buffer to set. The second parameter is the starting point in the vertex stream.

After setting the stream and index sources, use the Direct3DDevice8.DrawIndexedPrimitive method to render vertices that use indices from the index buffer.

Call m_D3DDevice.DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, dwVertices, _
                                       0, dwIndices / 3)

The second parameter that DrawPrimitive accepts is the minimum vertex index for vertices used during this call. The third parameter is the number of indices to use during this call starting from BaseVertexIndex + MinIndex. The fourth parameter is the location in the index buffer to start reading indices. The final parameter that DrawPrimitive accepts is the number of primitives to render. This parameter is a function of the primitive count and the primitive type. The code sample above uses triangles, so the number of primitives to render is the number of indices divided by three.


Vertex Buffers

Vertex buffers, represented by the Direct3DVertexBuffer8 class, 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 use of the rendering methods in the Direct3DDevice8 class. You can process the vertices in a vertex buffer to perform operations such as transformation, lighting, or generating clipping flags. Transformation is always performed.

IndexBuffers and vertex buffers are orthogonal concepts - that is, you can use indexed primitives with or without vertex buffers, or you can use a vertex buffer with or without indexed primitives.

A vertex buffer is simply a structure for storing vertex data. It's better than using just a user allocated chunk of memory, because a vertex buffer can be allocated in a way that is friendly to the device being used, and because the locking semantics of the vertex buffer allow for concurrency and the elimination of a redundant copy operation. Vertex buffers are therefore virtually always a good thing to use.

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

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 type.

Vertex buffer descriptions tell your application how an existing buffer was created and if it has been optimized since being created. You provide an empty description structure for the system to fill with the capabilities of a previously created vertex buffer. For more information about this task, see Accessing the Contents of a Vertex Buffer.

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.

Memory Pool and Usage

You can create vertex buffers with the Direct3DDevice8.CreateVertexBuffer method, which takes pool (memory class) and usage parameters. CreateVertexBuffer can also be created with a specified flexible vertex format (FVF) code for use in fixed function vertex processing, or as the output of process vertices. For details, see FVF Vertex Buffers.

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 Microsoft® Direct3D® application. Information is divided into the following sections.

  • Creating a Vertex Buffer
  • Accessing the Contents of a Vertex Buffer
  • Rendering from a Vertex Buffer
  • FVF Vertex Buffers
  • Fixed Function Vertex Processing
  • Programmable Vertex Processing
  • Device Types and Vertex Processing Requirements


Creating a Vertex Buffer

You create a vertex buffer object by calling the Direct3DDevice8.CreateVertexBuffer method, which accepts five parameters. The first parameter specifies the vertex buffer length, in bytes. Use the Len Microsoft Visual Basic® function to determine the size of a vertex format, in bytes. Consider the following custom vertex format.

Private Type CUSTOMVERTEX
    x As Single         ' x in screen space
    y As Single         ' y in screen space
    z  As Single        ' normalized z
    rhw As Single       ' normalized z rhw
    color As Long       ' vertex color
    tu As Single        ' texture coordinate
    tv As Single        ' texture coordinate
End Type

' Custom FVF, which describes the custom vertex structure.
Const D3DFVF_CUSTOMVERTEX = (D3DFVF_XYZRHW Or D3DFVF_DIFFUSE Or 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 if 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 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 Flexible Vertex Format Flags 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. The fourth parameter describes the memory class into which to place the vertex buffer.

The final parameter that CreateVertexBuffer accepts is the address of a variable to fill with a pointer to the new Direct3DVertexBuffer8 interface of the vertex buffer object, if the call succeeds.

Note You cannot produce clip flags for a vertex buffer that was created without support for them.

The following Visual Basic code example shows what creating a vertex buffer might look like in code.

'
' For the purposes of this example, the m_d3dDevice variable is
' a valid Direct3DDevice8 object.
'

' The custom vertex type
Private Type CUSTOMVERTEX
    x As Single
    y As Single
    z As Single
    rhw As Single
    color As Long
    tu As Single
    tv As Single
End Type

Const 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.
VB = m_d3dDevice.CreateVertexBuffer( 3*len(CUSTOMVERTEX), _
                                     0 /* Usage */, D3DFVF_CUSTOMVERTEX, _
                                     D3DPOOL_DEFAULT)


Accessing the Contents of a Vertex Buffer

Vertex buffers enable Microsoft® Visual Basic® applications to easily update the vertex data they contain. To lock, fill, and unlock vertex buffers use the D3DVertexBuffer8SetData helper function. D3DVertexBuffer8SetData accepts five parameters, The first, Vbuffer, is the Direct3DVertexBuffer8 object that contains the vertex data. The second parameter, OffsetToLock, is the offset into the vertex data. The third parameter is the size, measured in bytes, of the vertex data.

The fourth parameter, Flags, tells the system how the memory should be locked. You can use it to indicate how the application will access the data in the buffer. Specify constants for the Flags parameter according to the way the vertex 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 vertex buffer memory. Including this flag enables Microsoft® Direct3D® to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

The last parameter accepted by the D3DVertexBuffer8SetData helper function, Data, is the first element of an array of data to be loaded into the vertex buffer. This parameter is of type Any. To use it properly you must specify the first element of the array for Data, as shown in the following code example.

Dim Vertices(3) As CUSTOMVERTEX
Dim VertexSizeInBytes As Long

' Determine the length of the vertex data.
VertexSizeInBytes = Len(Vertices(0))

' Fill the vertices with data.
       .
       .
       .

' This code example assumes that g_VB is a variable containing a
' valid reference to a Direct3DVertexBuffer8 object.

' VBuffer=g_VB             The vertex buffer to fill with data.
' Offset=0                 Start filling from the start of the buffer.
' Size=VertSizeInBytes*3   Copy three CUSTOMVERTEX types to the buffer.
' Flags=0                  Send default flags to the lock operation.
' data=Vertices(0)         This parameter is of type Any. In order
'                          to use it, send the first element in
'                          the array.

D3DVertexBuffer8SetData g_VB, 0, VertexSizeInBytes * 3, 0, Vertices(0)

The vertex buffer memory is a simple array of vertices specified in flexible vertex format. The number of texture coordinates present in the vertex format is described by the D3DFVF_TEXn 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.

Performance Notes 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, given that access to the memory will be read-only.

See Using Dynamic Vertex and Index Buffers for information on using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

To lock, read, and unlock the contents of vertex buffers, use the D3DVertexBuffer8GetData helper function.

Retrieving Vertex Buffer Descriptions

Retrieve information about a vertex buffer by calling the Direct3DVertexBuffer8.GetDesc method. This method fills the members of the D3DVERTEXBUFFER_DESC structure with information about the vertex buffer.


Rendering from a Vertex Buffer

Rendering vertex data from a vertex buffer requires a few steps. First, you need to set the stream source by calling the Direct3DDevice8.SetStreamSource method, as shown in the following code example.

Call m_D3Device.SetStreamSource(0, VB, len(CUSTOMVERTEX))

The first parameter of 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 Direct3DDevice8.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.

Call m_D3DDevice.SetVertexShader(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 Direct3DDevice8.DrawPrimitive method.

Call m_D3DDevice.DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1)

The second parameter that DrawPrimitive accepts is the index of the first vector in the vertex buffer to load.


FVF Vertex Buffers

Setting the FVF parameter of the Direct3DDevice8.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 Direct3DDevice8 require FVF vertex buffers, and others require non-FVF vertex buffers. FVF vertex buffers are required as the destination vertex buffer argument for Direct3DDevice8.ProcessVertices.

FVF vertex buffers can be bound to a source data stream for any stream number. However, FVF vertex buffers are not allowed to be used for inputs to programmed vertex shaders

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 ProcessVertices destination vertex buffers must be post-processed. Vertex buffers used for fixed function shader inputs can be either pre- or post-processed. 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 application programming interface (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

Processing the vertices in a vertex buffer applies the current transformation matrices for the device, and it can optionally apply vertex operations such as lighting, generating clip flags, and updating extents. 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 Direct3DDevice8 class exposes the Direct3DDevice8.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 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 in the destination buffer at which the vertices will be placed, and the total number of vertices to process and place in the destination buffer. The fourth parameter, DestBuffer, should be set to the Direct3DVertexBuffer8 of the vertex buffer object that will receive the source vertices. The SrcStartIndex 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. 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, ProcessVertices does not overwrite color and texture coordinate information in the destination buffer unless this data is generated by Microsoft® Direct3D®. Diffuse color is generated when lighting is enabled, that is, D3DRS_LIGHTING is set to 1. Specular color is generated when lighting is enabled and specular is enabled, that is, D3DRS_SPECULARENABLE and D3DRS_LIGHTING are set to 1. Specular color is also generated when fog is enabled. Texture coordinates are generated when texture transform or texture generation is enabled. ProcessVertices uses the current render states to determine what vertex processing should be done.

To determine the vertex processing limitations of a device, query the VertexProcessingCaps member of the D3DCAPS8 structure for its supported vertex processing capabilities.

FVF Usage Settings for Destination Vertex Buffers

The Direct3DDevice8.ProcessVertices method requires specific settings for the Flexible Vertex Format Flags of the destination vertex buffer. The flexible vertex format (FVF) usage settings must be compatible with the current settings for vertex processing.

For fixed function vertex processing, ProcessVertices requires the following FVF settings.

  • Position type is always D3DFVF_XYZRHW; so, 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 1.
    • Lighting is enabled, that is, D3DRS_LIGHTING is 1.
    • Lighting is disabled, and 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 of the following conditions returns 1.
    • Lighting is enabled and specular color is enabled, that is, D3DRS_SPECULARENABLE is 1.
    • Lighting is disabled, and 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 DrawPrimitive calls, but is not visible to the application programmer. In this case, Microsoft® 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 1.

  • 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 post -processed texture coordinates. Note that the reprogramming of the D3DTSS_TEXCOORDINDEX setting occurs when the processed vertex buffer is used in subsequent Direct3DDevice8.DrawPrimitive and Direct3DDevice8.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 3 float values.

When 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

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. Direct3DDevice8.ProcessVertices will fail if the application writes to elements that are not present in the destination vertex buffer.


Device Types and Vertex Processing Requirements

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 behavior flag when calling the Direct3DDevice8.CreateVertexBuffer method specifies that the vertex buffer is to be used with software vertex processing. This flag is required for software vertex processing in mixed vertex processing mode. This flag is allowed in software vertex processing mode and disallowed in hardware vertex processing mode. Vertex buffers used with software vertex processing include the following:

  • All input streams for Direct3DDevice8.ProcessVertices.
  • All input streams for Direct3DDevice8.DrawPrimitive and Direct3DDevice8.DrawIndexedPrimitive when software vertex processing. For more information, see D3DRS_SOFTWAREVERTEXPROCESSING.

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.

Note Microsoft® Direct3D® supports standalone processing of vertices, without rendering any primitive with the 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 Direct3DDevice8.SetStreamSource must be created with the D3DUSAGE_SOFTWAREPROCESSING flag. The functionality provided by ProcessVertices is identical to that of the Direct3DDevice8.DrawPrimitive and Direct3DDevice8.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 is a number of additional optimizations that may be done based on the flags D3DUSAGE_DYNAMIC and D3DUSAGE_WRITEONLY. See Direct3DDevice8.CreateVertexBuffer for more information on using these flags.


Higher-Order Primitives

Microsoft® Direct3D® for Microsoft DirectX® 8.1 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 DirectX 8.1, 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 application programming interface (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

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 for DirectX 8.1 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 application programming interface (API). To meet this requirement, a new entry point has been added that interprets the incoming vertex data stream as a 2-D array of control points and tessellates it to the desired resolution.

  • Using Higher-Order Primitives


Using Higher-Order Primitives

This section shows you how to use higher-order primitives in your application.

Determining Higher-Order Primitive Support

The DevCaps member of D3DCAPS8 contains values from the CONST_D3DDEVCAPSFLAGS enumeration which 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 Microsoft® DirectX® 8.1.

Device capability | Description
D3DDEVCAPS_NPATCHES | Device supports N-patches.
D3DDEVCAPS_QUINTICRTPATCHES | Device supports quintic Bézier curves and B-splines.
D3DDEVCAPS_RTPATCHES | Device supports rectangular and triangular (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

You can use the following methods to draw patches in Microsoft® Direct3D® for DirectX 8.1.

  • Direct3DDevice8.DrawRectPatch. To better understand how the patch data is referenced in the vertex buffer, see D3DRECTPATCH_INFO.
  • Direct3DDevice8.DrawTriPatch. To better understand how the patch data is referenced in the vertex buffer, see D3DTRIPATCH_INFO.

DrawRectPatch draws a rectangular high-order patch specified by the Surface 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 Surface. This makes it possible to precompute and cache forward difference coefficients or other information, which in turn enables subsequent calls to DrawRectPatch using the same handle to execute efficiently.

It is intended that for static patches, an application would set the vertex shader and appropriate streams, supply patch information in the Surface parameter, and specify a handle so that Direct3D can capture and cache information. The application can then call DrawRectPatch with Surface set to ByVal 0 to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. However, you can override the cached NumSegments by specifying new values for NumSegments. 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 NumSegments values and does not cache any information. It is not valid to simultaneously set Handle to 0 and Surface to ByVal 0.

By respecifying Surface for the same handle, the application can overwrite the previously cached information.

If NumSegments is set to ByVal 0, then the tessellator uses D3DRS_PATCHSEGMENTS to control the amount of tessellation. In this case, obviously, the same tessellation is used for all sides. There are no special methods for N-patches. Tessellation is simply controlled by D3DRS_PATCHSEGMENTS. It is necessary to supply normals.

DrawTriPatch is similar to 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 to Direct3D or have Direct3D calculate them for you. To have Direct3D generate normals for you, add D3DVSD_TESSNORMAL and D3DVSD_STREAM_TESS to your vertex declaration. D3DVSD_STREAM_TESS is a delimiter that begins the virtual stream section. One or more tokens (D3DVSD_TESSNORMAL or D3DVSD_TESSUV) can follow this delimiter. The code sample below shows the vertex declaration that you would use to have Direct3D generate normals.

Dim decl(4) As Long

'Vertex data
decl(0) = D3DVSD_STREAM(0)
decl(1) = D3DVSD_REG(D3DVSDE_POSITION, D3DVSDT_FLOAT3)

' Data generation section implemented as a virtual stream
decl(2) = D3DVSD_STREAM_TESS()

' Generate normal using the position input and
'   copy it to the normal register (output).
decl(3) = D3DVSD_TESSNORMAL(D3DVSDE_POSITION, D3DVSDE_NORMAL)

decl(4) = D3DVSD_END()

To have texture coordinates automatically generated, add the D3DVSD_TESSUV to your declaration after the D3DVSD_STREAM_TESS delimiter.

Dim decl(4) As Long

'Vertex data
decl(0) = D3DVSD_STREAM(0)
decl(1) = D3DVSD_REG(D3DVSDE_POSITION, D3DVSDT_FLOAT3)

' Data generation section implemented as a virtual stream
decl(2) = D3DVSD_STREAM_TESS()

' Generate texture coordinates
decl(3) = D3DVSD_TESSUV(D3DVSDE_TEXCOORD0)

decl(4) = D3DVSD_END()

The coordinates generated for rectangular patches are spline based coordinates as illustrated by the images below.

Spline based coordinates

The coordinates generated for triangular patches are barycentric spline-based coordinates as illustrated by the images below.

Barycentric spline based coordinates

If an application wants to change the range of the generated texture coordinates, this can be done using texture transforms.


Point Sprites

Support for point sprites in Microsoft® Direct3D® for Microsoft DirectX® 8.1 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

Microsoft® Direct3D® for Microsoft DirectX® 8.1 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 1, 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 0, 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 0, the application-specified point size is used as the screen-space (post-transformed) size. Vertices that are passed to Microsoft® Direct3D® in screen space do not have point sizes computed; the specified point size is interpreted as screen-space size.

If D3DRS_POINTSCALEENABLE is 1, Direct3D computes the screen-space point size according to the following formula. The application-specified point size is expressed in camera space units.

Ss = Vh * Si * sqrt(1/(A + B*De + C*(De2)))

In this formula, the input point size, Si, 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, Vh, is the Height member of the D3DVIEWPORT8 type representing the viewport. De, 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.

De = sqrt (Xe2 + Ye2 + Ze2)

The maximum point size, Pmax, is determined by taking the smaller of either the MaxPointSize member of D3DCAPS8 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 = Pmax
  • if Ss < Pmin, then S = Pmin
  • Otherwise, S = Ss

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 0, then the vertex texture coordinates are duplicated at each vertex. If D3DRS_POINTSPRITEENABLE is set to 1, then the texture coordinates at the four vertices are set to the following values.

(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)

This is shown in the following diagram.

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 D3DVIEWPORT8 type—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 the D3DPMISCCAPS_CLIPPLANESCALEDPOINTS is not set in the PrimitiveMiscCaps member of D3DCAPS8, then 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 you create a device with D3DCREATE_HARDWARE_VERTEXPROCESSING on a HAL Device(D3DDEVTYPE_HAL) that has the MaxPointSize member of its D3DCAPS8 type 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 flexible vertex format (FVF) TL (transformed and lit) vertices or software vertex processing (D3DCREATE_SOFTWARE_VERTEXPROCESSING), in which case the Microsoft® Direct3D® run time emulates the point sprite rendering. For details on FVF TL vertices, see Transformed and Lit Vertex Functionality.

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_POINTSIZE for TL vertices.


Microsoft DirectX 8.1 (Visual Basic)

Samples

DirectX Graphics Visual Basic Samples

The following sample applications demonstrate the use and capabilities of the Microsoft® Direct3D® and Direct3DX application programming interfaces.

  • AnimKeys Sample
  • AutoParts Sample
  • BarGraph Sample
  • Billboard Sample
  • Dolphin Sample
  • Donuts Sample
  • DXTex Tool
  • PixelShader Sample
  • PointSprites Sample
  • ScatterGraph Sample
  • SkinnedMesh Sample
  • VertexBlend Sample
  • VertexShader Sample

See Also

DirectX Graphics Visual Basic Tutorials


AnimKeys Sample

Description

The AnimKeys sample illustrates how to use the Microsoft® Direct3D® framework to load and play key-framed animation with an .x file. The animation information is contained in the .x file.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\AnimKeys

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented.

Key | Action
F2 | Prompts you to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The last argument passed to D3DUtil_LoadFromFile is a CD3DAnimation class that is the parent to any animations that are in the .x file. Subsequently Animation.SetTime can be used to pose the model.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


AutoParts Sample

Description

The AutoParts sample illustrates the use of picking against a 3-D database.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Autoparts

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

Choose Click here in the tree view on the left side to load the engine model. You can rotate the model by holding the mouse button and dragging. When you click on a part, its description appears in the lower-left corner.

The Add and Remove from Invoice button manages the invoice list, but the Order button has no function.

Programming Notes

Each object in the Engine model is named. These names are unique and can be used to cross-reference a database. In this example, a custom text database is used so as not to require installing MDAC. From that database, more detailed information, such as price and part number, is gathered on the part.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


BarGraph Sample

Description

The BarGraph sample describes how you can use Microsoft® Direct3D® for graphic visualization. It uses the RenderToSurface features of the Microsoft® Direct3DX framework to render text and bitmaps dynamically.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\AnimKeys

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

Right-click on the sample window to display a shortcut menu. From this menu you can load new data from a .csv (comma-delimited) file. You can export a .csv file from Microsoft Excel or any spreadsheet program.

The file must be formatted so that the first row and columns are headers that title the data. A header can contain the tag TEXTURE:filename.bmp to indicate that it contains a picture. The rest of the data must be numeric. See Bargraphdata.csv in (SDK root)\Samples\Multimedia\VBSamples\Media for an example.

Holding the mouse button and dragging rotates the graph.

The following table lists the keys that are implemented.

Key | Action
RIGHT ARROW | Moves the camera right.
LEFT ARROW | Moves the camera left.
UP ARROW | Moves the camera up.
DOWN ARROW | Moves the camera down.
W | Moves the camera forward.
S | Moves the camera backward.
E | Rotates the camera right.
Q | Rotates the camera left.
A | Rotates the camera up.
Z | Rotates the camera down.

Programming Notes

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


Billboard Sample

Description

The Billboard sample illustrates the billboarding technique. Rather than rendering complex 3-D models, such as a high-polygon tree model, billboarding renders a 2-D image of the model and rotates it so that it always faces the eyepoint. This technique is commonly used to render trees, clouds, smoke, explosions, and so on. For more information, see Billboarding.

In the Billboard sample, a camera flies around a 3-D scene with a tree-covered hill. The trees look like 3-D objects, but they are actually 2-D billboarded images that are rotated toward the eyepoint. The hilly terrain and the skybox, a six-sided cube containing sky textures, are objects loaded from .x files. They are used for visual effect and are unrelated to the billboarding technique.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Billboard

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented.

Key | Action
F2 | Prompts you to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The billboarding technique is the focus of this sample. The camera is moved in each frame, so that the viewpoint changes accordingly. As the viewpoint changes, a rotation matrix is generated to rotate the billboards about the y-axis so that they face the new viewpoint. The computation of the billboard matrix occurs in the FrameMove function. The trees are also sorted in that function, as required for proper alpha blending, because billboards typically have some transparent pixels. The trees are rendered from a vertex buffer in the DrawTrees function.

The billboards in this sample are constrained to rotate about the y-axis only. Otherwise the tree trunks would not appear to be fixed to the ground. In a 3-D flight simulation or space shooter, for effects like explosions, billboards are typically not constrained to one axis.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


Dolphin Sample

Description

The Dolphin sample shows an underwater scene of a dolphin swimming, with caustic effects on the dolphin and sea floor. The dolphin is animated using a technique called tweening. The underwater effect uses fog, and the water caustics use an animated set of textures.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Dolphin

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented.

Key | Action
F2 | Prompts you to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Several things are happening in this sample. First, the use of fog gives an underwater effect. The fog parameters are set in the InitDeviceObjects function.

The water caustics are achieved by animating a set of 32 textures (Caust00.tga through Caust31.tga). The caustics can be blended into the scene using multitexturing or multipass blending techniques. Because the bottom of the dolphin should not have caustic effects, a separate pass is done in which ambient light is removed and the dolphin is lit from above, and then the diffuse color is blended with the caustic texture.

Using tweening, the dolphin model's vertices are linearly blended from multiple sets of vertices. The source models for these other sets of vertices are loaded from Dolphin_group.x, which consists of the dolphin model in three positions. For each frame, a destination mesh is generated by blending some combination of the positions and normals from these meshes together.

For more information on tweening, see Vertex Tweening.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


Donuts Sample

Description

The Donuts sample illustrates how to use Microsoft® Direct3D® to create a two-dimensional sprite engine.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Donuts

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented.

Key | Action
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The background is rendered with two TLVertex (screen space) triangles. The sprites are defined as an array of user-defined type that is a container for sprite properties such as position, direction, speed, and size. Each sprite is rendered as two TLVertex triangles in each frame.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


DXTex Tool

Description

The DXTex tool enables you to create texture maps that use the new DXTn compression formats. Creating a DXTn-compressed texture is not difficult. However, Microsoft® Direct3D® can do the conversion for you when using the Direct3DTexture8 object. Advanced developers can write tools that meet their specific needs, but the DXTex tool provides useful basic functionality.

Functionality

  • Opens .bmp and Microsoft® DirectDraw® surface (.dds) files. For more information, see DDS File Format below.
  • Opens .bmp files as alpha channel, either explicitly or implicitly, using a <filename>_a.bmp naming convention.
  • Saves textures in .dds format.
  • Supports conversion to all five DXTn compression formats.
  • Supports generation of mipmaps, using a box filter.
  • Supports visualization of alpha channel as a grayscale image or through a user-selectable background color.
  • Supports easy visual comparison of image quality between formats.

Path

Source: (SDK root)\Samples\Multimedia\Direct3D\DXTex

Executable: (SDK root)\Bin\DXUtils

User Interface

DxTex uses a fairly traditional user interface (UI) in that each texture map is a document, and several documents can be open at a time. However, each document can hold the texture in either one or two formats simultaneously while the document is open in DxTex. For example, you can import a .bmp file, which automatically creates a 32-bit ARGB texture. You can then convert the texture to DXT1 format. The document now has the image open in both formats, and you can switch between the formats by clicking the window or choosing Original View or New View on the View menu. This makes it easy for you to observe any artifacts introduced by image compression, and to try several compression formats without progressive degradation of the image. For example, if this technique is not used and you convert an image from ARGB to DXT1, all but one bit of alpha is lost.

If you then decide to convert to DXT2, there are still only two alpha levels. Using the DxTex system, the second conversion is done from the original ARGB format, and the DXT2 image contains all 16 levels of alpha supported by DXT2. When the image is saved, the original format is discarded, and only the new format is stored.

Keep in mind the following when using the DxTex interface.

  • If no format conversion has been requested since the document was opened, the one format is the original format—that is, the format in which the image will be written when the document is saved.
  • If format conversion has been requested since the document was opened, the converted format is the new format—that is, the format in which the image will be written when the document is saved.
  • If a second format conversion is requested, the new format from the first conversion is replaced with the second format. The original format is unchanged.
  • Generating mipmaps applies to both formats simultaneously.
  • If the original format has multiple mipmaps, and conversion to a new format is requested, the new format automatically has multiple mipmaps as well.

Performance

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

DDS File Format

See DDS File Format for more detailed information on the .dds file format.

Mipmaps

Mipmapping is a technique that improves image quality and reduces texture memory bandwidth by providing prefiltered versions of the texture image at multiple resolutions.

To generate mipmaps in DxTex, the width and height of the source image must both be powers of 2. To do this, click Generate Mip Maps on the Format menu. Filtering is done through a simple box filter. That is, the four nearest pixels are averaged to produce each destination pixel.

Alpha

Many texture formats include an alpha channel, which provides opacity information at each pixel. DxTex fully supports alpha in textures. When importing a .bmp file, if there are two files of the same size and one of the file names ends in "_a" (for example, Sample.bmp and Sample_a.bmp), the second file will be loaded as an alpha channel. The blue channel of the second .bmp is stored in the alpha channel. Once a document is open, you can explicitly load a .bmp file as the alpha channel by, on the File menu, clicking Open As Alpha Channel.

To view the alpha channel directly without the RGB channels, click Alpha Channel Only on the View menu. The alpha channel appears as a grayscale image. If no alpha channel has been loaded, every pixel has a full alpha channel and the image appears solid white when viewing "Alpha Channel Only". To turn off alpha channel viewing, click the Alpha Channel Only command a second time.

In the usual view, the effect of the alpha channel is visible because the window has a solid background color that shows through the texture where the alpha channel is less than 100 percent. You can change this background color by clicking the View menu, and then clicking Change Background Color. This choice does not affect the texture itself or the data that is written when the file is saved.

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. Therefore, some DxTex operations—such as 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.

Command Line Options

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 program 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 and,
                          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 is 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.


PixelShader Sample

Description

This sample shows some effects that can be achieved using pixel shaders. Each of the eight thumbnails is the result of using a different pixel shader to render a rectangle. Pixel shaders use a set of instructions, executed by the 3-D device on a per-pixel basis, that can affect the color of the pixel based on a variant of inputs. Pixel shaders can be used in place of the texture stage pipeline.

Not all cards support all features for pixel shaders. For more information on pixel shaders, see Pixel Shaders.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\PixelShader

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

Programming Notes

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


PointSprites Sample

Description

The PointSprites sample shows how to use the new Microsoft® Direct3D® point sprites feature. A point sprite is a forward-facing, textured quad that is referenced only by (x,y,z) position coordinates. Point sprites are most often used for particle systems and related effects.

Not all cards support all features for point sprites. For more information on point sprites, see Point Sprites.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\PointSprites

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented.

Key | Action
F2 | Prompts you to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Without the Direct3D support, point sprites can be implemented with four vertices that are oriented each frame towards the eyepoint, much like a billboard. With Direct3D, however, you can refer to each point sprite just by its center position and a radius. This saves on processor computation time and on bandwidth when uploading vertex information to the graphics card.

In this sample, a particle system is implemented using point sprites in which each particle is implemented using multiple alpha-blended point sprites, giving the particle a motion-blur effect.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


ScatterGraph Sample

Description

The ScatterGraph sample describes how you can use Microsoft® Direct3D® for graphic visualization. It uses the RenderToSurface features of the Microsoft® Direct3DX framework to render text and bitmaps dynamically.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\AnimKeys

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

Right-click the sample's interface to display a shortcut menu. The following table list the available menu commands.

Command | Action
Load Data From File | Loads new data from a .csv (comma-delimited) file. A .csv file can be exported from Microsoft Excel or any spreadsheet program.
Reset Orientation | Resets the viewpoint to a known state.
Show Connecting Lines | Connects the data points if the order of the data is important.
Show Height Lines | Makes it easier to see the y-value in comparison to the other values.
Show Foot Lines | Makes it easier to see the x-z relationship.
Show Base Plane | Shows the plane where y=0.
Auto Rotate | Turns rotation on and off.

The file must be formatted so that the first row and columns are headers that title the data. A header can contain the tag TEXTURE:filename.bmp to indicate that it contains a picture. The rest of the data must be numeric. See Bargraphdata.csv in (SDK root)\Samples\Multimedia\VBSamples\Media for an example.

Holding the mouse button and dragging rotates the graph.

The following table lists the keys that are implemented.

Key | Action
RIGHT ARROW | Moves the camera right.
LEFT ARROW | Moves the camera left.
UP ARROW | Moves the camera up.
DOWN ARROW | Moves the camera down.
W | Moves the camera forward.
S | Moves the camera backward.
E | Rotates the camera right.
Q | Rotates the camera left.
A | Rotates the camera up.
Z | Rotates the camera down.

Programming Notes

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


SkinnedMesh Sample

Description

The SkinnedMesh sample illustrates how to use the Microsoft® Direct3D® framework to load an .x file with skinning and animation information in it.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\SkinnedMesh

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented.

Key | Action
F2 | Prompts you to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The last argument passed to D3DUtil_LoadFromFileAsSkin is a CD3DAnimation class that is the parent to any animations that are found in the .x file.

Animation.SetTime must be called but does not pose the model.

Character.UpdateFrames computes the matrices for all joints on the character.

Character.RenderSkin renders the character using the loaded skin.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.

The modeling exporters in the Extras directory of the DirectX SDK can export to .x files with skinning information.


VertexBlend Sample

Description

The VertexBlend sample demonstrates a technique called vertex blending, also known as surface skinning. It displays a file-based object that is made to bend at various points. Surface skinning is an impressive technique used for effects such as smooth joints and bulging muscles in character animations.

Not all display cards support all features for vertex blending. For more information on vertex blending, see Indexed Vertex Blending.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\VertexBlend

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented.

Key | Action
F2 | Prompts you to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Vertex blending requires each vertex to have an associated blend weight. Multiple world transforms are set up using SetTransformState, and the blend weights determine how much contribution each world matrix has when positioning each vertex.

In this sample, a mesh is loaded using the common helper code. Note how a custom vertex and a custom FVF is declared and used to build the mesh; see the SetFVF call for the mesh object. Without using the mesh helper code, the technique is the same. Create a vertex buffer full of vertices that have a blend weight, and use the appropriate FVF.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


VertexShader Sample

Description

The VertexShader sample shows some effects that you can achieve using vertex shaders. Vertex shaders use a set of instructions, executed by the 3-D device on a per-vertex basis, that can affect the properties of the vertex—positions, normal, color, texture coordinates, and so on—in interesting ways.

Not all cards support all features for vertex shaders. For more information on vertex shaders, see Vertex Shaders.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\VertexShader

Executable: (SDK root)\Samples\Multimedia\VBSamples\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented.

Key | Action
F2 | Prompts you 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 common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples on the DirectX SDK. You can find the common source code in (SDK root)\Samples\Multimedia\VBSamples.


Direct3D Appendix

This section contains additional material that covers topics such as file formats and tips for performance improvements.

  • DDS File Format

    This section explains the DDS file format in detail.

  • Device States

    This section explains device states, which are used to set rendering and texturing attributes.

  • Programming Tips

    These tips are derived from lessons learned from programming topics such as troubleshooting a program, implementing multithreading, or optimizing code for performance.

  • X Files

    This section explains X files in depth, including their architecture, the file format, and some samples of file loading and saving.

  • Mesh View Help

    This section outlines the functionality that is available in the mesh view executable. This handy executable can be used to experiment with meshes by applying different mesh utility operations. This application is part of the SDK install.


DDS File Format

The Microsoft® 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 Microsoft DirectX® Texture tool (DXTex Tool), as well as some third party tools, and by the Microsoft Direct3DX library.

This format was introduced with DirectX 7.0. In DirectX 8.0, 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 four-character code 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 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 and either DDSD_PITCH or DDSD_LINEARSIZE.
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] |
DDPIXELFORMAT ddpfPixelFormat | A 32-byte value that specifies the pixel format structure.
DDCAPS2 ddsCaps | A 16-byte value that specifies the capabilities structure.
DWORD dwReserved2 |

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 Microsoft 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, this contains 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] |

Note that as of DirectX 8.0, cubic environment maps are always written with all faces defined.

The following topics show the layout.
  • 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, the 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 × 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. For example, a 256-by-256 main image, with a pixel format of R8G8B8 (three bytes per pixel) and all mipmap levels, would contain the following:

"DDS ", (256, 256), (pitch=768), (pixel format=R8G8B8, bitcount=24), (mipmapcount=9), (TEXTURE, PITCH, COMPLEX, MIPMAP, RGB) | 128 bytes
256 x 256 main image | 196608 bytes
128 x 128 mipmap image | 49152 bytes
64 x 64 mipmap image | 12288 bytes
32 x 32 mipmap image | 3072 bytes
16 x 16 mipmap image | 768 bytes
8 x 8 mipmap image | 192 bytes
4 x 4 mipmap image | 48 bytes
2 x 2 mipmap image | 12 bytes
1 x 1 mipmap image | 4 bytes

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:

"DDS ", (256, 256), (linearsize=32768), (pixel format=DXT1), (mipmapcount=9), (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, FOURCC) | 128 bytes
256 x 256 main image | 32768 bytes
128 x 128 mipmap image | 8192 bytes
64 x 64 mipmap image | 2048 bytes
32 x 32 mipmap image | 512 bytes
16 x 16 mipmap image | 128 bytes
8 x 8 mipmap image | 32 bytes
4 x 4 mipmap image | 8 bytes
2 x 2 mipmap image | 8 bytes
1 x 1 mipmap image | 8 bytes

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) × max(1, height ÷ 4) × 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:

"DDS ", (256, 64), (linearsize=8192), (pixel format=DXT1), (mipmapcount=9), (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, FOURCC) | 128 bytes
256 x 64 main image | 8192 bytes
128 x 32 mipmap image | 2048 bytes
64 x 16 mipmap image | 512 bytes
32 x 8 mipmap image | 128 bytes
16 x 4 mipmap image | 32 bytes
8 x 2 mipmap image | 16 bytes
4 x 1 mipmap image | 8 bytes
2 x 1 mipmap image | 8 bytes
1 x 1 mipmap image | 8 bytes


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:

"DDS ", (256, 256), (linearsize=32768), (pixel format=DXT1), (mipmapcount=9), (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, CUBEMAP, POSITIVEX, NEGATIVEY, POSITIVEZ, FOURCC) | 128 bytes
256 x 256 positive X main image | 32768 bytes
128 x 128 positive X mipmap image | 8192 bytes
64 x 64 positive X mipmap image | 2048 bytes
32 x 32 positive X mipmap image | 512 bytes
16 x 16 positive X mipmap image | 128 bytes
8 x 8 positive X mipmap image | 32 bytes
4 x 4 positive X mipmap image | 8 bytes
2 x 2 positive X mipmap image | 8 bytes
1 x 1 positive X mipmap image | 8 bytes
256 x 256 negative Y main image | 32768 bytes
128 x 128 negative Y mipmap image | 8192 bytes
64 x 64 negative Y mipmap image | 2048 bytes
32 x 32 negative Y mipmap image | 512 bytes
16 x 16 negative Y mipmap image | 128 bytes
8 x 8 negative Y mipmap image | 32 bytes
4 x 4 negative Y mipmap image | 8 bytes
2 x 2 negative Y mipmap image | 8 bytes
1 x 1 negative Y mipmap image | 8 bytes
256 x 256 positive Z main image | 32768 bytes
128 x 128 positive Z mipmap image | 8192 bytes
64 x 64 positive Z mipmap image | 2048 bytes
32 x 32 positive Z mipmap image | 512 bytes
16 x 16 positive Z mipmap image | 128 bytes
8 x 8 positive Z mipmap image | 32 bytes
4 x 4 positive Z mipmap image | 8 bytes
2 x 2 positive Z mipmap image | 8 bytes
1 x 1 positive Z mipmap image | 8 bytes

Note that as of Microsoft® 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 Microsoft® DirectX® 8.x, 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 DirectX 8.0.

For example, a 64 x 64 x 4 volume map, a pixel format of R8G8B8 (3 bytes per pixel), and all mipmap levels would contain:

"DDS ", (64, 64, 4), (pitch=768), (pixel format=R8G8B8, bitcount=24), (mipmapcount=7), (DEPTH, TEXTURE, PITCH, COMPLEX, MIPMAP, VOLUME, RGB) | 128 bytes
64 x 64 slice 1 of 4 main image. | 12288 bytes
64 x 64 slice 2 of 4 main image. | 12288 bytes
64 x 64 slice 3 of 4 main image. | 12288 bytes
64 x 64 slice 4 of 4 main image. | 12288 bytes
32 x 32 slice 1 of 2 mipmap image. | 3072 bytes
32 x 32 slice 2 of 2 mipmap image. | 3072 bytes
16 x 16 slice 1 of 1 mipmap image. | 768 bytes
8 x 8 slice 1 of 1 mipmap image. | 192 bytes
4 x 4 slice 1 of 1 mipmap image. | 48 bytes
2 x 2 slice 1 of 1 mipmap image. | 12 bytes
1 x 1 slice 1 of 1 mipmap image. | 4 bytes


DDS Bit Flag Values

A number of fields make use of the standard Microsoft® DirectDraw® bit flags. Those that are used for 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.

The dwFlags member of the modified 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
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


Device States

A Microsoft® Direct3D® device is a state computer. Applications set up the state of the lighting, rendering, and transformation modules and then pass data through them during rendering.

This section describes render states, provides details about each render state used in Direct3D, and contains information about device state blocks, which applications can use to manipulate groups of devices states in a single call. The following topics are discussed.

  • Render States
  • Texture Stage States
  • State Blocks


Render States

Device render states control the behavior of the Microsoft® Direct3D® device's rasterization module. They do this by altering the attributes of the rendering state, what type of shading is used, fog attributes, and other rasterizer operations.

Microsoft® Visual Basic® applications control the characteristics of the rendering state by invoking the Direct3DDevice8.SetRenderState method. The CONST_D3DRENDERSTATETYPE enumeration specifies all possible rendering states. Your application passes a value from the CONST_D3DRENDERSTATETYPE enumeration as the first parameter to the SetRenderState method.

Fixed function vertex processing is controlled by the SetRenderState method and the following device render states. Most of these controls do not have any effect when using programmed vertex shaders.

  • D3DRS_SPECULARENABLE
  • D3DRS_FOGSTART
  • D3DRS_FOGEND
  • D3DRS_FOGDENSITY
  • D3DRS_RANGEFOGENABLE
  • D3DRS_LIGHTING
  • D3DRS_AMBIENT
  • D3DRS_FOGVERTEXMODE
  • D3DRS_COLORVERTEX
  • D3DRS_LOCALVIEWER
  • D3DRS_NORMALIZENORMALS
  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE
  • D3DRS_VERTEXBLEND

In addition, the fixed-function vertex processing pipeline uses the following methods to set transforms, materials, and lights.

  • Direct3DDevice8.SetTransform
  • Direct3DDevice8.SetMaterial
  • Direct3DDevice8.SetLight
  • Direct3DDevice8.LightEnable

Note D3DRS_SPECULARENABLE controls the addition of specular color in the pixel pipeline. D3DRS_FOGSTART, D3DRS_FOGEND, and D3DRS_FOGDENSITY control the start, end, and density of pixel fog density computation.

Additional information is contained in the following topics.

  • Alpha Blending State
  • Alpha Testing State
  • Ambient Lighting State
  • Antialiasing State
  • Culling State
  • Depth Buffering State
  • Fog State
  • Lighting State
  • Outline and Fill State
  • Per-Vertex Color State
  • Primitive Clipping State
  • Shading State
  • Stencil Buffer State
  • Texture Wrapping State


Alpha Blending State

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 and Texture Blending.

Microsoft® Visual Basic® applications use the D3DRS_ALPHABLENDENABLE render state to enable alpha transparency blending. The Microsoft® Direct3D® API allows many types of alpha blending. However, it is important to note the user's 3-D 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 contains
' a reference to a Direct3DDevice8 object.

' Set the source blend state.
d3dDevice.SetRenderState D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR

' Set the destination blend state.
d3dDevice.SetRenderState D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR

As a result of the calls in the preceding code example, Direct3D performs a linear blend between the source color—the color of the primitive that is rendered at the current location—and the destination color—the color at the current location in the frame buffer. This gives an appearance similar to tinted glass. Some of the color of the destination object seems to be transmitted through the source object. The rest of the color appears to be absorbed.

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 3-D 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

Applications written in Microsoft® Visual Basic® 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 Microsoft® 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 example assumes that Caps is a
' D3DCAPS8 type that was filled with a
' previous call to Direct3D8.GetDeviceCaps.
If (Caps.AlphaCmpCaps And D3DPCMPCAPS_GREATEREQUAL) Then
    Call dev.SetRenderState(D3DRS_ALPHAREF, &H1)
    Call dev.SetRenderState(D3DRS_ALPHATESTENABLE, 1)
    Call dev.SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL)
End If


Ambient Lighting State

Ambient light is surrounding light that radiates from all directions.

For specific information on how Microsoft® Direct3D® uses ambient light, see Direct Light vs. Ambient Light, and Mathematics of Lighting.

A Microsoft Visual Basic® application sets the color of ambient lighting by invoking the Direct3DDevice8.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 contains a valid
' reference to a Direct3DDevice8 object.

' Set the ambient light.
Call D3DDevice.SetRenderState(D3DRS_AMBIENT, &H202020)


Antialiasing State

Antialiasing is a method of making lines and edges appear smoother on the screen. Microsoft® Direct3D® supports two antialiasing methods: edge antialiasing and full-scene antialiasing.

For details about these techniques, see Antialiasing.

By default, Direct3D does not perform antialiasing. To enable edge-antialiasing, which requires a second rendering pass, set the D3DRS_EDGEANTIALIAS render state to 1. To disable it, set D3DRS_EDGEANTIALIAS to 0.

To enable full-scene antialiasing, set the D3DRS_MULTISAMPLEANTIALIAS to 1. To disable it, set D3DRS_MULTISAMPLEANTIALIAS to 0.


Culling State

As Microsoft® Direct3D® renders primitives, it culls primitives that are facing away from the user.

Microsoft Visual Basic® applications set the culling mode by using the D3DRS_CULLMODE render state, which can be set to a member of the CONST_D3DCULL enumeration. By default, Direct3D culls back faces with counterclockwise vertices.

The following code sample illustrates the process of setting the culling mode to cull back faces with clockwise vertices.

' This code example assumes that d3dDevice contains a valid
' reference to a Direct3DDevice8 object.

' Set the culling state.
Call d3dDevice.SetRenderState(D3DRENDERSTATE_CULLMODE, D3DCULL_CW)


Depth Buffering State

Depth buffering is a method of removing hidden lines and surfaces. By default, Microsoft® Direct3D® does not use depth buffering.

For a conceptual overview of depth buffers, see Depth Buffers.

Microsoft Visual Basic® applications update the depth-buffering state with the D3DRS_ZENABLE render state, using a member of the CONST_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 render state, specifying D3DZB_FALSE as the second parameter for the call to Direct3DDevice8.SetRenderState.

The following Visual Basic code example shows how the depth-buffer state is set to enable z-buffering.

' This code example assumes that d3dDevice contains a valid
' reference to a Direct3DDevice8 object.

' Enable z-buffering.
Call 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_ZBIAS).


Fog State

Fog effects can give a 3-D 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.

A Microsoft® Visual Basic® application controls fog through device rendering states. The CONST_D3DRENDERSTATETYPE enumeration 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 1. 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 CONST_D3DFOGMODE enumeration. 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.


Lighting State

Applications that use the Microsoft® Direct3D® geometry pipeline can enable or disable lighting calculations. Only vertices that contain a vertex normal are properly lit; vertices with no normal will use a dot product of zero in all lighting computations. Therefore, a vertex that does not use a normal receives no light.

For more information, see Mathematics of Lighting.

Applications enable Direct3D lighting by setting the D3DRS_LIGHTING render state to 1, which is the default setting, and they disable Direct3D lighting by setting the render state to 0.

The lighting render state is entirely independent of lighting computations that can be performed on vertices within a vertex buffer. The Direct3DDevice8.ProcessVertices method accepts its own flags to control lighting calculations during vertex processing.


Outline and Fill State

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 CONST_D3DFILLMODE enumeration for the D3DRS_FILLMODE render state.

To enable dithering, your application must pass the D3DRS_DITHERENABLE enumerated value as the first parameter to Direct3DDevice8.SetRenderState. It must set the second parameter to 1 to enable dithering, and 0 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.

By default, Microsoft® Direct3D® devices use a solid outline for primitives. The outline pattern can be changed using the D3DLINEPATTERN type. For details, see the D3DRS_LINEPATTERN render state.


Per-Vertex Color State

The following vertex types cannot contain both color and normal information.

  • D3DLVERTEX
  • D3DLVERTEX2
  • D3DTLVERTEX
  • D3DTLVERTEX2
  • D3DVERTEX
  • D3DVERTEX2

Because the default shading mode is Gouraud shading, which depends on both vertex color and normal information, Microsoft® Direct3D® does not use vertex color in lighting calculations involving the predefined vertex types.

However, when you use flexible vertex format (FVF) codes, vertices can contain both vertex color and vertex normal information. By default, Direct3D uses this information when it calculates lighting. To disable use of vertex color lighting information, invoke the Direct3DDevice8.SetRenderState method and pass D3DRS_COLORVERTEX as the first parameter. Set the second parameter to 0 to disable vertex color lighting, or 1 to enable it.

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 CONST_D3DMATERIALCOLORSOURCE enumeration, 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

Microsoft® Direct3D® can clip primitives that render partially outside the viewport. When using Microsoft Visual Basic®, Direct3D clipping is controlled by the D3DRS_CLIPPING render state. Set this render state to 1 (the default value) to enable primitive clipping. Set it to 0 to disable Direct3D clipping services.


Shading State

Microsoft® Direct3D® supports both flat and Gouraud shading. The default is Gouraud shading. To control the current shading mode, your Visual Basic application specifies a member of the CONST_D3DSHADEMODE enumerated type for the D3DRS_SHADEMODE render state.

The following Visual Basic code example demonstrates the process of setting the shading state to flat shading mode.

' This example assumes that d3dDevice is a valid
' reference to a Direct3DDevice8 object.

' Set the shading state.
Call d3dDevice.SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT)


Stencil Buffer State

Applications use the stencil buffer to determine whether a pixel is written to the rendering target surface.

For details, see Stencil Buffer Techniques.

Applications written in Microsoft Visual Basic® enable or disable stenciling by calling the Direct3DDevice8.SetRenderState method. Pass D3DRS_STENCILENABLE as the value of the first parameter. Set the value of the second parameter to 1 or 0 to enable or disable stenciling, respectively.

Set the comparison function that Microsoft® Direct3D® uses to perform the stencil test by calling SetRenderState. Set the value of the first parameter to D3DRS_STENCILFUNC. Pass a member of the CONST_D3DCMPFUNC enumeration as the value of the second parameter.

The stencil reference value is the value in the stencil buffer that the stencil function uses for its test. By default, the stencil reference value is zero. Your application can set the value by calling SetRenderState. Pass D3DRS_STENCILREF as the value of the first parameter. Set the value of the second parameter to the new reference value.

Before Direct3D module performs the stencil test for a pixel, it performs a bitwise AND operation of the stencil reference value and a stencil mask value. The result is compared against the contents of the stencil buffer using the stencil comparison function. Your application can set the stencil mask by calling SetRenderState. Pass D3DRS_STENCILMASK as the value of the first parameter. Set the value of the second parameter to the new stencil mask.

To set the action that Direct3D takes when the stencil test fails, call SetRenderState and pass D3DRS_STENCILFAIL as the first parameter. The second parameter must be a member of the CONST_D3DSTENCILOP enumeration.

Your application can also control how Direct3D responds when the stencil test passes but the z-buffer test fails. Call SetRenderState and pass D3DRS_STENCILZFAIL as the first parameter and use a member of the CONST_D3DSTENCILOP enumeration for the second parameter.

In addition, your application can control what Direct3D does when both the stencil test and the z-buffer test pass. Call SetRenderState and pass D3DRS_STENCILPASS as the first parameter. Again, the second parameter must be a member of the CONST_D3DSTENCILOP enumeration.

A write mask can be applied to the values written into the stencil buffer. To set a stencil buffer write mask, call SetRenderState and pass D3DRS_STENCILWRITEMASK as the first parameter. Pass the value of the write mask as the second parameter.


Texture Wrapping State

The D3DRS_WRAP0 through D3DRS_WRAP7 render states control texture 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 values from the CONST_D3DWRAPFLAGS enumeration 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.


Texture Stage States

Texture stage states control the style of texturing and how texture filtering is done.

Microsoft® Visual Basic® applications control the characteristics of the texture-related rendering states by invoking the Direct3DDevice8.SetTextureStageState method. The CONST_D3DTEXTURESTAGESTATETYPE enumeration specifies all possible texture-related rendering states. Your application passes a value from the CONST_D3DRENDERSTATETYPE enumeration as the first parameter to the SetTextureStageState method.

Applications set the texture for a stage by calling the Direct3DDevice8.SetTexture method.

Additional information is contained in the following topics.

  • Texture Addressing State
  • Texture Border State
  • Texture Filtering State
  • Texture Blending State


Texture Addressing State

Microsoft® Visual Basic® applications use the D3DTSS_ADDRESSU, D3DTSS_ADDRESSV, and D3DTSS_ADDRESSW texture stage states to set texture addressing.


Texture Border State

Microsoft® Visual Basic® applications use the D3DTSS_BORDERCOLOR texture stage state to set border color texture addressing.

For more information, see Border Color Texture Address Mode.


Texture Filtering State

Microsoft® Visual Basic® applications use the D3DTSS_MAGFILTER, D3DTSS_MINFILTER, and D3DTSS_MIPFILTER, and texture-stage states to control texture filtering.


Texture Blending State

Microsoft® Visual Basic® applications use the texture blending states defined by the D3DTSS_COLOROP and D3DTSS_ALPHAOP texture stage states to control texture blending.

For more information, see Texture Blending.


State Blocks

A state block in Microsoft® Direct3D® is a group of device states—render states, lighting and material parameters, transformation states, texture stage states, and current texture information. The state block is a snapshot of the device's current state, or it is explicitly recorded. The snapshot can be applied to a device in a single call. Device-state blocks can be optimized by the rendering device to accelerate the common sequences of state changes that your application requires, or they can simply make applying device states easier.

In Microsoft Visual Basic®, you receive a state-block handle when you finish recording a state block by calling the Direct3DDevice8.EndStateBlock method, and when you capture a predefined set of device state data by calling the Direct3DDevice8.CreateStateBlock method.

Additional information is contained in the following topics.

  • Recording State Blocks
  • Capturing State Blocks
  • Applying State Blocks
  • Creating Predefined State Blocks
  • Deleting State Blocks


Recording State Blocks

The Direct3DDevice8 object offers the Direct3DDevice8.BeginStateBlock method to record device states in a state block as your application calls for them. The BeginStateBlock method causes the system to start recording device state changes in a state block, rather than applying them to the device. After you call BeginStateBlock, calls to any of the following methods are recorded in a device state block.

  • Direct3DDevice8.LightEnable
  • Direct3DDevice8.SetClipPlane
  • Direct3DDevice8.SetLight
  • Direct3DDevice8.SetMaterial
  • Direct3DDevice8.SetRenderState
  • Direct3DDevice8.SetTexture
  • Direct3DDevice8.SetTextureStageState
  • Direct3DDevice8.SetTransform
  • Direct3DDevice8.SetViewport

When you are done recording the state block, notify the system to stop recording by calling the Direct3DDevice8.EndStateBlock method. The EndStateBlock method places the handle of the state block in the method's return value. Your application uses this handle to apply the state block to the device as needed, to capture new state data into the block, and to delete the state block when it is no longer required.

Performance Note For best results, group all state changes tightly between a BeginStateBlock and EndStateBlock pair.

It is important to check the error code from the EndStateBlock method. If the method fails, it is likely because the display mode has changed. Design your application to recover from this type of failure by recreating its surfaces and recording the state block again.


Capturing State Blocks

The Direct3DDevice8.CaptureStateBlock method updates the values in an existing state block to reflect the current state of the device. The method accepts a single parameter, Token, that identifies the state block that will receive the current state of the device if the call succeeds.

The CaptureStateBlock method is especially useful to update a state block that your application has already recorded to include slightly different state settings. To do so, apply the existing state block, change the necessary settings, then capture the state of the system back to the state block, as shown in the following code example.

' The Token variable contains a handle to a device state block for
' a previously recorded set of device states.

' Set the current state block.
Call d3dDevice.ApplyStateBlock(Token)

' Change device states as needed.
.
.
.

' Capture the modified device state data back to the existing block.
Call d3dDevice.CaptureStateBlock(Token)

The CaptureStateBlock method doesn't capture the entire state of the device; it only updates the values for the states already in the state block. For example, imagine a state block that contains the two operations shown in the following code example.

Call d3dDevice.SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD)
Call d3dDevice.SetTexture(0, Texture)

If your application changed either of these settings since the state block was originally recorded, the CaptureStateBlock method will update the states within the block—and only those states—to their new values.


Applying State Blocks

The Direct3DDevice8.ApplyStateBlock method applies an existing state block to the device. The ApplyStateBlock method accepts a single parameter, Token, that identifies the state block to apply.

Note You cannot apply a state block while recording another state block—that is, between calls to Direct3DDevice8.BeginStateBlock and Direct3DDevice8.EndStateBlock. Attempts to do so will fail.


Creating Predefined State Blocks

The Direct3DDevice8.CreateStateBlock method creates a new state block that contains the entire set of device states or only those device states related to vertex or pixel processing. The CreateStateBlock method accepts two parameters. The first parameter identifies the type of state information to capture in the new state block, and the second parameter is the address of a variable that will receive a valid state-block handle if the call succeeds.

Valid values for the first parameter are defined by the CONST_D3DSTATEBLOCKTYPE enumeration, which includes members that you can use to capture the entire set of device states (D3DSBT_ALL), or only those states that pertain to vertex or pixel processing (D3DSBT_VERTEXSTATE or D3DSBT_PIXELSTATE). The following list summarizes the states that the system captures when you pass the D3DSBT_VERTEXSTATE or D3DSBT_PIXELSTATE values.

  • Vertex-related states (D3DSBT_VERTEXSTATE)
  • State (enabled or disabled) of all lights
  • Transformation matrices
  • User-defined clipping planes
    These values are set for the following render states.
    D3DRS_AMBIENT

    D3DRS_AMBIENTMATERIALSOURCE

    D3DRS_CLIPPING

    D3DRS_CLIPPLANEENABLE

    D3DRS_COLORVERTEX

    D3DRS_CULLMODE

    D3DRS_DIFFUSEMATERIALSOURCE

    D3DRS_EMISSIVEMATERIALSOURCE

    D3DRS_FOGCOLOR

    D3DRS_FOGDENSITY

    D3DRS_FOGENABLE

    D3DRS_FOGEND

    D3DRS_FOGSTART

    D3DRS_FOGTABLEMODE

    D3DRS_FOGVERTEXMODE

    D3DRS_INDEXVERTEXBLENDENABLE

    D3DRS_LIGHTING

    D3DRS_LOCALVIEWER

    D3DRS_NORMALIZENORMALS

    D3DRS_POINTSCALE_A

    D3DRS_POINTSCALE_B

    D3DRS_POINTSCALE_C

    D3DRS_POINTSIZE

    D3DRS_POINTSIZE_MAX

    D3DRS_POINTSIZE_MIN

    D3DRS_POINTSCALEENABLE

    D3DRS_POINTSPRITEENABLE

    D3DRS_PATCHSEGMENTS

    D3DRS_RANGEFOGENABLE

    D3DRS_SHADEMODE

    D3DRS_SOFTWAREVERTEXPROCESSING

    D3DRS_SPECULARENABLE

    D3DRS_SPECULARMATERIALSOURCE

    D3DRS_TWEENFACTOR

    D3DRS_VERTEXBLEND

    These values are set for the following texture-stage states.
    D3DTSS_TEXCOORDINDEX

    D3DTSS_TEXTURETRANSFORMFLAGS

  • Pixel-related States (D3DSBT_PIXELSTATE)
    These values are set for the following render states.
    D3DRS_ALPHABLENDENABLE

    D3DRS_ALPHAFUNC

    D3DRS_ALPHAREF

    D3DRS_ALPHATESTENABLE

    D3DRS_COLORWRITEENABLE

    D3DRS_DESTBLEND

    D3DRS_DITHERENABLE

    D3DRS_EDGEANTIALIAS

    D3DRS_FILLMODE

    D3DRS_FOGDENSITY

    D3DRS_FOGEND

    D3DRS_FOGSTART

    D3DRS_LASTPIXEL

    D3DRS_LINEPATTERN

    D3DRS_MULTISAMPLEANTIALIAS

    D3DRS_MULTISAMPLEMASK

    D3DRS_SHADEMODE

    D3DRS_SRCBLEND

    D3DRS_STENCILENABLE

    D3DRS_STENCILFAIL

    D3DRS_STENCILFUNC

    D3DRS_STENCILMASK

    D3DRS_STENCILPASS

    D3DRS_STENCILREF

    D3DRS_STENCILWRITEMASK

    D3DRS_STENCILZFAIL

    D3DRS_TEXTUREFACTOR

    D3DRS_WRAP0 through D3DRS_WRAP7

    D3DRS_ZBIAS

    D3DRS_ZENABLE

    D3DRS_ZFUNC

    D3DRS_ZWRITEENABLE

    These values are set for the following texture-stage states.
    D3DTSS_ADDRESSU

    D3DTSS_ADDRESSV

    D3DTSS_ADDRESSW

    D3DTSS_ALPHAARG1

    D3DTSS_ALPHAARG2

    D3DTSS_ALPHAOP

    D3DTSS_BORDERCOLOR

    D3DTSS_BUMPENVLOFFSET

    D3DTSS_BUMPENVLSCALE

    D3DTSS_BUMPENVMAT00

    D3DTSS_BUMPENVMAT01

    D3DTSS_BUMPENVMAT10

    D3DTSS_BUMPENVMAT11

    D3DTSS_COLORARG1

    D3DTSS_COLORARG2

    D3DTSS_COLOROP

    D3DTSS_MAGFILTER

    D3DTSS_MAXANISOTROPY

    D3DTSS_MAXMIPLEVEL

    D3DTSS_MINFILTER

    D3DTSS_MIPFILTER

    D3DTSS_MIPMAPLODBIAS

    D3DTSS_TEXCOORDINDEX

    D3DTSS_TEXTURETRANSFORMFLAGS

Note It is important to check the error code from the CreateStateBlock method. If the method fails, it is likely because the display mode has changed. Your application should recover from this type of failure by recreating its surfaces, and then recreating the state block.


Deleting State Blocks

The Direct3DDevice8.DeleteStateBlock deletes a state block, deallocating the memory used to contain it. The DeleteStateBlock method accepts the handle to the state block to delete at its only parameter. After deleting a state block, any handles to it are invalid, and can no longer be used.


Programming Tips

This section contains information to help you develop Microsoft® DirectX® Graphics applications efficiently. The following topics are covered.

  • Performance Optimizations
  • Troubleshooting
  • Working with Device Windows
  • Working with Earlier Drivers
  • Working with Multiple Monitor Systems
  • Presenting Multiple Views in Windowed Mode


Performance Optimizations

Every developer who creates real-time applications that use three-dimensional (3-D) graphics is concerned about performance optimization. This section provides you with guidelines about getting the best performance from your code.

General Performance Tips

Follow these general guidelines to increase the performance of your application.

  • 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, choose a vertex format size that is a multiple of 32 bits. Otherwise, select the smallest appropriate format.
  • Draw using indexed primitives. This may 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.
  • Do not copy to output registers unless necessary in shaders. For example:
    mad oD0, r1, v0, c[3]

    rather than:

    mad r1, v0, c0
mov oD0, r1

Databases and Culling

Building a reliable database of the objects in your world is key to excellent performance in Microsoft® 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 achieve significant performance improvements 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. If you only need to increase the overall lighting level, use the ambient light instead of adding a new light source. It's much cheaper.
  • Directional lights are cheaper 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 cheaper than point lights, because the area outside the cone of light is calculated quickly. Whether spotlights are cheaper 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; simply 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 256×256 are the fastest. If your application uses four 128×128 textures, for example, try to ensure that they use the same palette and place them all into one 256×256 texture. This technique also reduces the amount of texture swapping. Of course, you should not use 256×256 textures unless your application requires that much texturing because, as mentioned, textures should be kept as small as possible.

Using Dynamic Textures

Dynamic textures are a new Microsoft® DirectX® 8.1 feature. To find out if the driver supports dynamic textures, check the D3DCAPS2_DYNAMICTEXTURES flag of the D3DCAPS8 structure.

Keep the following things in mind when working with dynamic textures.

  • They cannot be managed. For example, their pool cannot be D3DPOOOL_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, LOCK_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 since overhead of calling driver every DISCARD
    // will not justify the performance gain. Experimentation is encouraged.
    pTex->Lock(DISCARD);
    <Overwrite *entire* texture>
    pTex->Unlock();
    pDev->SetTexture();
    pDev->DrawPrimitive();
}

Using Dynamic Vertex and Index Buffers

Dynamic vertex and index buffers have a difference in performance based the size and usage. The usage styles below help to determine whether to use D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

Usage Style 1:

for loop()
{
    pBuffer->Lock(...D3DLOCK_DISCARD...); //Ensures that hardware
                                          //doesn't stall by returning
                                          //a new pointer.
    Fill data (optimally 1000s of vertices/indices, no fewer) in pBuffer.
    pBuffer->Unlock()
    Change state(s).
    DrawPrimitive() or DrawIndexedPrimitive()
}

Usage Style 2:

for loop()
{
    pVB->Lock(...D3DLOCK_DISCARD...); //Ensures that hardware doesn't
                                      //stall by returning a new
                                      //pointer.
    Fill data (optimally 1000s of vertices/indices, no fewer) in pBuffer.
    pBuffer->Unlock
    for loop( 100s of times )
    {
        Change State
        DrawPrimitive() or DrawIndexPrimitives() //Tens of primitives
    }
}

Usage Style 3:

for loop()
{
    If there is space in the buffer
    {
        // Append vertices/indices.
        pBuffer->Lock(…D3DLOCK_NOOVERWRITE…);
    }
    Else
    {
        // Reset to beginning.
        pBuffer->Lock(…D3DLOCK_DISCARD…);
    }
    Fill few 10s of vertices/indices in pBuffer
    pBuffer->Unlock
    Change State
    DrawPrimitive() or DrawIndexedPrimitive() // A few primitives

    }

Style 1 is faster than either style 2 or 3, but is generally not very practical. Style 2 is usually faster than style 3, provided that the application fills at least a couple thousand vertices/indices for every Lock, on average. If the application fills fewer than that on average, then style 3 is faster. There is no guaranteed answer as to which lock method is faster and the best way to find out is to experiment.

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 legacy hardware also.

Direct3DX 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 simply used by Direct3DX to classify the mesh into subsets. The application sets per-face attributes using the LockAttributeBuffer call. The 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 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 Optimize method. The attribute sort is data sensitive, so if the application knows that a mesh is attribute sorted, it still needs to call Optimize to generate the attribute table.

The following topics describes 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 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 32bits, 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 Optimize. If no attribute table is present, 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 Optimize with attribute sorting or stronger optimization enabled. The attribute table is used to quickly initiate a single draw primitive call to 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 includes a great deal of overdraw. Overdraw is the average number of times that a screen pixel is written to. Overdraw is difficult to calculate exactly, but you can often make a close approximation. If the overdraw averages less than 2, you can achieve the best performance by turning z-buffering off and rendering the scene from back to front.

On faster personal computers, software rendering to system memory is often faster than rendering to video memory although it has the disadvantage of not being able to use double buffering or hardware-accelerated clear operations. If your application can render to either system or video memory, and if you include a routine that tests which is faster, you can take advantage of the best approach on the current system. The Direct3D sample code in this software development kit (SDK) demonstrates this strategy. It is necessary to implement both methods because there is no other way to test the speed. Speeds can vary enormously from computer to computer, depending on the main-memory architecture and the type of graphics adapter being used.


Troubleshooting

This topic lists common categories of problems that you might encounter when writing Microsoft® 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 DLLs and review output messages under the debugger.

Using Lit Vertices

Applications that use lit vertices, analogous to the D3DLVERTEX type, should disable the Microsoft® Direct3D® lighting engine by setting the D3DRS_LIGHTING render state to 0. 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 such as D3DLVERTEX 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 0.

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 Microsoft® 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 Microsoft® 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 Microsoft® 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.

If your application encounters unexplained failures when running with the retail Direct3D Immediate Mode run-time file, test against the debug version and look closely for cases where your application passes invalid parameters.


Working with Device Windows

This section lists issues that you might encounter when working with device windows in Microsoft® 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.
  • For any application, multiple monitor or single monitor, at least one device window must be the focus window. In practical terms, this means that you cannot use a child window of your focus window as the device window in single monitor systems. You must use the parent focus window as both the focus and device windows. For a multiple monitor system, at least one monitor must use the focus window as its device window.


Working with Earlier Drivers

This section lists issues that may be encountered when working with Microsoft® DirectX® 8.x on drivers written for versions of DirectX earlier than DirectX 8.x.

  • When working with a TnLHAL 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.

You can detect a driver not written for DirectX 8.x by querying the MaxStream member of D3DCAPS8. If this value is 0, then it is not a DirectX 8.x driver.


Working with Multiple Monitor Systems

The concept of exclusive full-screen mode is retained in Microsoft® DirectX® 8.x, but it is kept entirely implicit in the Direct3D8.CreateDevice and Direct3DDevice8.Reset method calls. Whenever a device is successfully reset or created in full-screen operation, the Direct3D8 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 Direct3D8 object can neither assume full-screen operation nor allocate video memory. In addition, when a Direct3D8 object assumes exclusive mode, all devices other than the device that went full-screen are placed into the lost state. For information on how to handle lost devices, see Lost Devices.

Along with exclusive mode, the Direct3D8 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 Direct3D8 object is either reset to windowed mode or destroyed.

Devices can be divided into two categories when a Direct3D8 object owns exclusive mode. The first category of devices are those that were created by the same Direct3D8 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 Direct3D8 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 Direct3D8 object, and all share the same focus window.

Note When you create a new device using the same Direct3D8 object and focus window, your original device will lose its surfaces. You will need to call Direct3DDevice8.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.


Presenting Multiple Views in Windowed Mode

In addition to the swap chain owned and manipulated through the Direct3DDevice8 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 Direct3DDevice8.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.


X Files

The X file format refers to files with the .x file name extension. X files were introduced with Microsoft® 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 rich, 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.

This section discusses the structure of .x files and how to use them in your applications.

Information is divided into the following topics.

  • X File Interface Hierarchy
  • X File Architecture
  • Using X Files

For more information on the X File format, see X File Format Reference.


X File Interface Hierarchy

The following table illustrate the relationship between the .x file classes.

Class | Derives from
DirectXFileBinary | DirectXFileObject
DirectXFileData | DirectXFileObject
DirectXFileReference | DirectXFileObject


X File Architecture

The Microsoft® 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 Software Development Kit (SDK).

  • Reserved Words, Header, and Comments
  • Templates
  • Data
  • Use of Commas and Semicolons


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
 |  |  | "02" | Major version 2
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 number sign (#). The comment runs to the next new line. The following example shows valid comments.

#  This is a comment.
// This is another comment.


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.


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;;
}


Using X Files

This section contains information about using .x files in a Microsoft® Direct3D® application. Information is divided into the following topics.

  • Loading an X File
  • Saving to an X File
  • Creating a Cube
  • Converting and Exporting 3-D Models to X Files


Loading an X File

Use the following procedure to load an .x file.

  1. Use the DirectX8.DirectXFileCreate method to create a DirectXFile object.
  2. If templates are present in the Microsoft® DirectX® file that you will load, use the DirectXFile.RegisterTemplates method to register those templates.
  3. Use the DirectXFile.CreateEnumObject method to create a DirectXFileEnum enumerator object.
  4. Loop through the objects in the file. For each object, perform the following steps.
    1. Use the DirectXFileEnum.GetNextDataObject method to retrieve each DirectXFileData object.
    2. Use the DirectXFileData.GetType method to retrieve the data's type.
    3. Load the data using the DirectXFileData.GetData method.
    4. If the object has optional members, retrieve the optional members by calling the DirectXFileData.GetNextObject method.
    5. Set the DirectXFileData object variable to Nothing.
  5. Set the DirectXFileEnum object variable to Nothing.
  6. Set the DirectXFile object variable to Nothing.


Saving to an X File

Use the following procedure to save .x file templates and data to an .x file.

  1. Use the DirectX8.DirectXFileCreate method to create a DirectXFile object.
  2. Use the DirectXFile.RegisterTemplates method to inform the Microsoft® DirectX® file system about any templates that you will use.
  3. Use the DirectXFile.CreateSaveObject method to create an DirectXFileSave object.
  4. Use the DirectXFileSave.SaveTemplates method to save templates, if desired.
  5. Loop through the objects to save. For each top-level object, perform the following steps.
    1. Use the DirectXFileSave.CreateDataObject method to create a DirectXFileData 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 as defined in the next step.
    2. Each DirectXFileData object can have optional child objects if its template allows it. The child objects can be any of the three types of objects: DirectXFileData, DirectXFileReference, or DirectXFileBinary. 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 DirectXFileSave.CreateDataObject method to create an DirectXFileData object, and then call the DirectXFileData.AddDataObject method to add it as a child of the object. If the object type is Data Reference, call the DirectXFileData.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 DirectXFileData.AddBinaryObject method to create and add the binary object as a child of the object.
    3. Call the DirectXFileSave.SaveData method to save the data object and all its children.
    4. Set the DirectXFileData object variable to Nothing.
  6. Set the DirectXFileSave object variable to Nothing.
  7. Set the DirectXFileobject to Nothing.


Creating a Cube

This section describes a simple cube and shows how to add textures, frames, and animations.

  • Defining a Simple Cube
  • Adding Textures
  • Adding Frames and Animations


Defining a Simple Cube

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

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

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 AnimationSets and 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&em;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.


Converting and Exporting 3-D Models to X Files

Microsoft® Direct3D® supplies the following tools to convert and export 3-D models to the .x file format.

  • Conv3ds.exe
  • XSkinExp.dle


Conv3ds.exe

The Conv3ds.exe utility converts three-dimensional (3-D) models produced by Autodesk 3-D Studio and other modeling packages to the Microsoft® DirectX® file format. By default, the utility produces binary .x files with no templates.

Running Conv3ds.exe

You can run Conv3ds.exe with no options, and it will produce an .x file containing a hierarchy of frames. For example, the following command produces an .x file called File.x from the .3ds file.

conv3ds File.3ds

To run Conv3ds.exe with options, see Specifying Optional Arguments for Conv3ds.exe.

Information is divided into the following sections.

  • Specifying Optional Arguments for Conv3ds.exe
  • Producing 3DS Files from Lightwave Objects
  • Hints and Tips


Specifying Optional Arguments for Conv3ds.exe

If the .3ds file contains key frame data, you can use the -A option to produce an .x file that contains an animation set. The following command would do this.

conv3ds -A File.3ds

The File.3ds parameter is the name of the file to be converted.

Use the -m option to make an .x file that contains a single mesh made from all the objects in the .3ds file.

conv3ds -m File.3ds

Use the -T option to wrap all the objects and frame hierarchies in a single top-level frame. Using this option, all the frames and objects in the .3ds file can be loaded with a single call. The first top-level frame hierarchy in the .x file will be loaded. The frame containing all the other frames and meshes is called x3ds_filename, without the .3ds extension. The -T option will have no effect if it is used with the -m option.

The -s option enables you to specify a scale factor for all the objects converted in the .3ds file. For example, the following command makes all objects ten times bigger.

conv3ds -s10 File.3ds

The following command makes all objects ten times smaller:

conv3ds -s0.1 File.3ds

The -r option reverses the winding order of the faces when the .3ds file is converted. If, after converting the .3ds file and viewing it in Microsoft® Direct3D®, the object appears inside-out, try converting it with the -r option. All Lightwave models exported as .3ds files need this option. For details, see Producing 3DS Files from Lightwave Objects.

The -v option turns on verbose output mode. Specify an integer with it. The following table shows the currently supported integers.

Option | Meaning
-v0 | Default. Verbose mode off.
-v1 | Prints warnings about bad objects, and prints general information about what the converter is doing.
-v2 | Prints basic key frame information, the objects being included in the conversion process, and information about the objects being saved.
-v3 | Very verbose. Most useful for debugging information.

The -e option enables you to change the extension for texture map files, as shown in the following example.

conv3ds -e"ppm" File.3ds

If File.3ds contains objects that reference the texture map file Brick.gif, the .x file will reference the texture map file Brick.ppm. The converter does not convert the texture map file. The texture map files must be in the D3DPATH when the resulting .x file is loaded. The D3DPath is an environment variable that sets the default search path.

The -x option forces the Conv3ds.exe utility to produce a text .x file, instead of a binary .x file. Text files are larger but can be easily edited by hand.

The -X option forces the Conv3ds.exe utility to include the .x file templates in the file. By default, the templates are not included.

The -t option specifies that the .x file produced will not contain texture information.

The -N option specifies that the .x file produced will not contain normal vector information. All the load calls will generate normal vectors for objects with no normal vectors in the .x file.

The -c option specifies that the .x file produced should not contain texture coordinates. By default, if you use the -m option, the mesh that is output will contain (0,0) uv texture coordinates if the .3ds object had no texture coordinates.

The -f option specifies that the .x file produced should not contain a frame transformation matrix.

The -z and -Z options enable you to adjust the alpha face color value of all the materials referenced by objects in the .x file. For example, the following command causes Conv3ds.exe to add 0.1 to all alpha values under 0.2.

conv3ds -z0.1 -Z0.2 File.3ds

The following command causes Conv3ds.exe to subtract 0.2 from the alpha values for all alphas.

conv3ds-z"-0.2" -z1 File.3ds

The -o option enables you to specify the file name for the .x file produced.

The -h option tells the converter not to try to resolve any hierarchy information in the .3ds file, usually produced by the key framer. Instead, all the objects are output in top-level frames if the -m option is not used.


Producing 3DS Files from Lightwave Objects

There are several issues with .3ds files exported by the Trans3d plug-in for Lightwave. These are best handled using the following Conv3ds.exe command.

conv3ds -r -N -f -h -T|m trans3dfile.3ds

All the .3ds objects produced by Trans3d and the Lightwave object editor need their winding order reversed. Otherwise, they appear inside-out when displayed. They contain no surface normal vector information.


Hints and Tips

If you cannot see objects produced by Conv3ds.exe after loading them, use the scale option -s with a scale factor of approximately 100. This increases the scale of the objects in the .x file.

If, after loading the object into the viewer and switching from flat shading into Gouraud shading, the object turns dark gray, try converting with the -N option.

If the textures are not loaded after the object is converted, check whether the object is referencing either .ppm or .bmp files by using the -e option. Also check whether the texture widths and heights are a power of 2. Make sure the textures are stored in a directory in your D3DPATH.

Currently, Conv3ds.exe cannot handle dummy frames used in .3ds animations. It ignores them. However, it converts any child objects.


XSkinExp.dle

XSkinExp.dle is used as an exporter for 3D Studio Max and is located on the DirectX8 SDK CD.

The path for this file is: (CD Drive):\DXF\extras\direct3d\tools\3dsmax.

See the readme file provided with XSkinExp.dle for information on how to use the .dle.


Mesh View Help

Menu Descriptions

File

  • Open Mesh File

    • Opens a dialog to select a file in the .x or .m file format to be loaded and viewed.

  • Open PMesh File

    • Opens a dialog to select a file in the progressive mesh format to be loaded and viewed.

  • Create Shape

    • Opens a sub-dialog to create some basic shapes that are defined programmatically (text, polygon, box, cylinder, torus, teapot, sphere, cone).

  • Save Mesh As

    • Opens a dialog to save the selected mesh to a file. The file can be written as a text or binary file.

  • Close Selected

    • Closes and deletes the currently selected mesh.

  • Close Non Selected

    • Closes and deletes the meshes that are not currently selected.

View

  • Wireframe

    • View all content in wireframe mode.

  • Edges

    • View all content in solid-shaded mode with the edges drawn in black.

  • Creases

    • Highlight the creases on the visible meshes. A crease is an edge with a vertex that has a different piece of data on it for multiple faces that refer to it, that is, a different normal for the vertex per face.

  • Strips

    • Show the strips that are generated by this mesh in blue. The blue line goes from the center of each triangle to the next triangle in the triangle strip.

  • Adjacency

    • Show the adjacency of the polygons in a mesh by drawing a line from the center of a polygon to the center of the adjacent polygon.

  • Bounding Box

    • Draw the bounding boxes for the visible meshes.

  • Normals

    • Draw the normals of the vertices on the visible meshes in yellow.

  • Texture Coords

    • Show the texture coordinates for the viewed geometry as rays projecting from the vertices. Because a vertex in Microsoft® Direct3D® can have up to eight texture coordinates, users must specify which sets they would like to view. This viewing mode is especially useful when the texture coordinates are filled with tangents for use in pixel shaders for example.

  • Textures

    • Display the textures on the visible geometry.

  • Lighting

    • Show the geometry in the scene with lighting calculations still on.

  • Culling

    • Perform back face culling on the visible geometry when disabled polygons facing away from the camera are not drawn.

  • Hierarchy

    • Display the frame hierarchy of the meshes that are currently loaded. This is displayed in a separate floating window. To make the window disappear, on the View menu, clear the Hierarchy command.

  • Play Animation

    • Play the current animation for the currently loaded geometry if one exists.

  • Pause Animation

    • Stop the animation at the current frame when playing.

  • Normal Speed

    • Interpret the time value in the animation from an X file as 4800 units per second. Otherwise, the interpreted value is 30 units per second.

MeshOps

  • Optimize

    • Optimizes the currently selected mesh with the selected optimization method. See the Microsoft® Direct3DX reference pages to see the differences in methods.

  • Weld Vertices

    • Removes duplicate vertices and makes polygons that use these vertices use the nondeleted vertex.

  • Split Mesh

    • Splits the selected mesh into multiple meshes that are less than specified size in vertices and faces.

  • Collapse Meshes

    • Collapses the currently selected meshes into a single mesh.

  • Reset Matrices

    • Resets the matrices for the frames that are loaded to their initial position.

  • Mesh Properties

    • Shows the selected mesh's FVF render states and whether or not it is a 32 bit mesh.

  • Skinning Method

    • Allows the user to select the skinning method while animating a skinned mesh. The choices are nonindexed, indexed, and software skinning.

  • Face Selection

    • Enters a mode for the user to select an individual face on the current mesh.

  • Vertex Selection

    • Enters a mode for the user to select an individual vertex on the current mesh.

PMeshes

  • Convert Selected to PM

    • Convert the selected mesh to a progressive mesh. The conversion uses the error parameters that are entered in a dialog box. For more information on these parameters refer to the Direct3DX documentation of progressive meshes.

  • Snapshot to Mesh

    • Convert the current progressive mesh object to a static mesh object using the current settings of the progressive mesh.

  • Set number of Faces

    • Set the current number of faces in the progressive mesh to a specific number.

  • Set number of Vertices

    • Set the current number of vertices in the progressive mesh to a specific number.

  • Trim

    • Set the minimum and maximum number of faces for a progressive mesh. Once the user has set the trim values to the desired minimum and maximum, the progressive mesh can be trimmed to the selected values, thereby reducing the dynamic range of the progressive mesh.

N-Patches

  • N-Patch Selected

    • Draw the current object as an N-Patches object. The scroll bar in this mode selects the amount of N-Patch iterations for the current object.

  • SnapShot to mesh

    • Convert the selected object to a static mesh based on the current N-Patch settings to create a high-resolution static mesh.

Icons and Usage

Icons

  • Selection Modes

    • The first three icons are easy ways for the user to select the selection mode. They are Mesh Selection Mode (Arrow), Face Selection Mode (yellow outlined triangle), and Vertex Selection Mode (Red point highlighted triangle). These are the same modes that are available from the menus in MeshOps.

  • Display Modes

    • The next icons are easy ways to select the most common display modes for geometry. They are Shaded mode (nonoutlined tri-color cube), Wire frame mode (wire frame cube), and Edge mode (outlined tri-color cube). These are the same modes that are available from the menus in View.

  • Topology Display modes

    • The next icons display specific topological information about the geometry displayed. They are adjacency (A), Strips (S), Creases (C), and Normals (N). These are the same modes that are available from the menus in View.

  • Info

    • The next icon is the info button that will display information about the currently selected element.

  • Animation Controls

    • The last two icons are animation controls for playing and pausing the animation for the currently visible mesh.

Status Bar

The status bar in MView displays the current status of the visible geometry. The order from left to right of the displayed information is currently selected element (face or vertex only), Mesh mode (polygon, Pmesh, or pMesh), display frames per second, display triangles per second, number of displayed triangles, and number of displayed vertices.

Scroll Bar

The scroll bar will appear in two of the three mesh modes, pMesh and nPatch mode. In pMesh mode, the scroll bar indicates the range of displayed triangles for the progressive mesh. You can slide the scroll bar up or down to change the number of triangles displayed. In nPatch mode, the scroll bar indicates how many nPatch levels are being used. As the scroll bar is moved up or down, the number of nPatch interactions performed are adjusted accordingly.

More Information

For more information on any of the functions used by MView, refer to the Direct3DX documentation included in the Microsoft® DirectX® software development kit (SDK).


Reference

This section contains the reference pages for the Microsoft® Direct3D® application programming interface (API). Information is contained in the following sections.

  • Direct3D Visual Basic Reference

  • Direct3DX Visual Basic Reference

  • Vertex Shader Reference

  • Pixel Shader Reference

  • X File Visual Basic Reference


Direct3D Visual Basic Reference

This section contains reference information for the API elements provided by Microsoft® Direct3D®. Reference material is divided into the following categories.

  • Classes
  • Functions
  • Vertex Shader Declarator Functions
  • Types
  • Enumerations
  • Texture Argument Flags
  • Flexible Vertex Format Flags
  • Error Codes


Classes

This section contains reference information for the classes provided by Microsoft® Direct3D®. The following classes are used with Direct3D.

  • Direct3D8
  • Direct3DBaseTexture8
  • Direct3DCubeTexture8
  • Direct3DDevice8
  • Direct3DIndexBuffer8
  • Direct3DResource8
  • Direct3DSurface8
  • Direct3DSwapChain8
  • Direct3DTexture8
  • Direct3DVertexBuffer8
  • Direct3DVolume8
  • Direct3DVolumeTexture8


Direct3D8

Applications use the methods of the Direct3D8 class to create Microsoft® Direct3D® objects and set up the environment. This class includes methods for enumerating and retrieving capabilities of the device.

The Direct3D8 class is obtained by calling the DirectX8.Direct3DCreate method.

The methods of the Direct3D8 class can be organized into the following groups.

Creation | CreateDevice
Enumeration | EnumAdapterModes
Information | GetAdapterCount
 | GetAdapterDisplayMode
 | GetAdapterIdentifier
 | GetAdapterModeCount
 | GetAdapterMonitor
 | GetDeviceCaps
Registration | RegisterSoftwareDevice
Verification | CheckDepthStencilMatch
 | CheckDeviceFormat
 | CheckDeviceMultiSampleType
 | CheckDeviceType

See Also

DirectX8.Direct3DCreate


Direct3D8.CheckDepthStencilMatch

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.

object.CheckDepthStencilMatch( _
    Adapter As Long, _
    DeviceType As  CONST_D3DDEVTYPE, _
    AdapterFormat As CONST_D3DFORMAT, _
    RenderTargetFormat As CONST_D3DFORMAT, _
    DepthStencilFormat As CONST_D3DFORMAT) As Long

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
Member of the CONST_D3DDEVTYPE enumeration identifying the device type.
AdapterFormat
Member of the CONST_D3DFORMAT enumeration, identifying the format of the display mode into which the adapter will be placed.
RenderTargetFormat
Member of the CONST_D3DFORMAT enumeration, identifying the format of the render target surface to be tested.
DepthStencilFormat
Member of the CONST_D3DFORMAT enumeration, 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.

Error Codes

Err.Number is not set for this method.

Remarks

This method allows applications to work with hardware that requires certain depth formats for a given render target format. The following code fragment shows how to use CheckDeviceFormat to validate a depth stencil format.

Function IsDepthFormatOK( DepthFormat As CONST_D3DFORMAT, AdapterFormat As CONST_D3DFORMAT, _
                          BackBufferFormat As CONST_D3DFORMAT) as Boolean

      Dim check As Long

      check = d3d.CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, AdapterFormat, _
                                    D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, DepthFormat)
      If (check < 0) Then Exit Function   'Returns False

      check = d3d.CheckDepthStencilFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, AdapterFormat, _
                          RenderTargetFormat, DepthFormat)
      If (check < 0) Then
         IsDepthStencilFormatOK = 0
      Else
         IsDepthStencilFormatOK = 1
      End If

End function

The behavior of this method has been changed for Microsoft® DirectX® 8.1. This method now pays attention to the D24x8 and D32 depth-stencil formats. The previous version assumed that these format 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 preceding call returns 0 (False) if DepthFormat cannot be used in conjunction with AdapterFormat and BackBufferFormat.


Direct3D8.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.

object.CheckDeviceFormat( _
    Adapter As Long, _
    DeviceType As  CONST_D3DDEVTYPE, _
    AdapterFormat As CONST_D3DFORMAT, _
    Usage As Long, _
    RType As CONST_D3DRESOURCETYPE, _
    CheckFormat As CONST_D3DFORMAT) As Long

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
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
Member of the CONST_D3DDEVTYPE enumeration, identifying the device type.
AdapterFormat
Member of the CONST_D3DFORMAT enumeration, identifying the format of the display mode into which the adapter will be placed.
Usage
Requested usage for a surface of the CheckFormat. One or more of the following flags defined by the CONST_D3DUSAGEFLAGS enumeration can be specified.
D3DUSAGE_DEPTHSTENCIL
Set to indicate that the surface can be used as a depth-stencil surface.
D3DUSAGE_RENDERTARGET
Set to indicate that the surface can be used as a render target. In cases where the RType parameter value unambiguously implies a specific usage, the application can leave the Usage parameter as 0.
RType
A member of the CONST_D3DRESOURCETYPE enumeration, specifying the resource type requested for use with the queried format.
CheckFormat
Member of the CONST_D3DFORMAT enumeration. Indicates the format of the surfaces that may be used, as defined by Usage.

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. This method returns D3DERR_NOTAVAILABLE if the format is not acceptable to the device for this usage.

Error Codes

Err.Number is not set for this method.

Remarks

A typical use of CheckDeviceFormat is to verify the existence of a particular depth-stencil surface format. See Selecting a Device for more detail on the enumeration process. Another typical use of CheckDeviceFormat would be to verify if textures existing in particular surface formats can be rendered, given the current display mode.

Function DoesDepthFormatExist(DepthFormat As CONST_D3DFORMAT, AdapterFormat As CONST_D3DFORMAT) As Boolean

   Dim Check As Long
   Dim D3D As Direct3D8

   'we assume the D3D object has been created and initialized
   Check = D3D.CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, AdapterFormat, _
                                 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, DepthFormat)
   If (Check >= 0) Then
       DoesDepthFormatExist= 1
   Else
      DoesDepthFormatExist= 0
   End If

End Function

The preceding function call returns 0 (False) if DepthFormat does not exist on the system.

Another typical use of CheckDeviceFormat would be to verify if textures existing in particular surface formats can be rendered, given the current display mode. The following code fragment shows how you could use CheckDeviceFormat to verify that texture formats are compatible with specific back buffer formats.

Function IsTextureFormatOk(TextureFormat As D3DFORMAT ,AdapterFormat As D3DFORMAT ) As Boolean
   Dim Check As Long
   Dim D3D As Direct3D8

   Check = D3D.CheckDeviceFormat( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, AdapterFormat, _
                                  0, D3DRTYPE_TEXTURE, TextureFormat)

   If (Check >= 0) Then
      IsTextureFormatOk = 1
   Else
      IsTextureFormatOk = 0
   End If

End Function

The preceding call returns 0 (False) if TextureFormat cannot be used to render textures while the adapter surface format is AdapterFormat.


Direct3D8.CheckDeviceMultiSampleType

Determines if a multisampling technique is available on this device.

object.CheckDeviceMultiSampleType( _
    Adapter As Long, _
    DeviceType As CONST_D3DDEVTYPE, _
    Format As CONST_D3DFORMAT, _
    Windowed As Long, _
    MultiSampleType As CONST_D3DMULTISAMPLE_TYPE) As Long

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns 0 (False) when this value equals or exceeds the number of display adapters in the system.
DeviceType
Member of the CONST_D3DDEVTYPE enumeration, identifying the device type.
Format
Member of the CONST_D3DFORMAT enumeration that specifies the format of the surface to be multisampled. For more information, see "Remarks."
Windowed
Specify 1 to inquire about windowed multisampling, and specify 0 to inquire about full-screen multisampling.
MultiSampleType
Member of the CONST_D3DMULTISAMPLE_TYPE enumeration, identifying the multisampling technique to test.

Return Values

If the device can perform the specified multisampling method, this method returns D3D_OK.

If the method fails, one of the following values can be returned.

D3DERR_INVALIDCALL
D3DERR_INVALIDDEVICE
D3DERR_NOTAVAILABLE

Remarks

This method is intended for use with both render target and depth-stencil surfaces because you need to create both of them multisampled if you want to use them together.

The following code fragment shows how you could use CheckDeviceMultiSampleType to test for devices that support a specific multisampling method.

Dim Device As Direct3DDevice8
Dim Caps As D3DCAPS8
Dim Caps2 As CONST_D3DDEVTYPE
Dim FrontBuffer As CONST_D3DFORMAT
Dim BackBuffer As CONST_D3DFORMAT

If Device.CheckDeviceMultiSampleType(Caps.AdapterOrdinal, Caps2.DeviceType, _
                                     BackBuffer.Format, 0, D3DMULTISAMPLE_3_SAMPLES) And _
   Device.CheckDeviceMultiSampleType(Caps.AdapterOrdinal, Caps2.DeviceType, _
                                     FrontBuffer.Format, 0, D3DMULTISAMPLE_3_SAMPLES) Then
    ' things to do if D3DMULTISAMPLE_3_SAMPLES works in full screen mode
    ' with the specified surface format
End If

Error Codes

Err.Number is not set for this method.


Direct3D8.CheckDeviceType

Verifies whether or not a certain device type can be used on this adapter and expect hardware acceleration using the given formats.

object.CheckDeviceType( _
    Adapter As Long, _
    CheckType As CONST_D3DDEVTYPE, _
    DisplayFormat As CONST_D3DFORMAT, _
    BackBufferFormat As CONST_D3DFORMAT, _
    bWindowed As Long) As Long

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
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.
CheckType
Member of the CONST_D3DDEVTYPE enumeration, indicating the device type to check.
DisplayFormat
Member of the CONST_D3DFORMAT enumeration, indicating the format of the adapter display mode for which the device type is to be checked. For example, some devices operate only in 16-bits-per-pixel modes.
BackBufferFormat
Member of the CONST_D3DFORMAT enumeration, indicating the format of the adapter display mode for which the device type is to be checked. For example, some devices operate only in 16-bits-per-pixel modes.
bWindowed
Value indicating whether the device type will be used in full-screen or windowed mode. If set to 1, the query is performed for windowed applications; otherwise, this value should be set 0.

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. This method returns D3DERR_INVALIDDEVICE if CheckType specified a device that does not exist. D3DERR_NOTAVAILABLE is returned if either surface format is not supported, or if hardware acceleration is not available for the specified formats.

Error Codes

Err.Number is not set for this method.

Remarks

The most important device type that may not be present is D3DDEVTYPE_HAL. D3DDEVTYPE_HAL requires hardware acceleration. Applications should use CheckDeviceType to determine if the needed hardware and drivers are present on the system..

Applications should not specify a DisplayFormat that contains an alpha channel. This will result in a failed call. Note that an alpha channel may be present in the back buffer, but the two display formats must be identical in all other respects. For example, if DisplayFormat is D3DFMT_X1R5G5B5, valid values for BackBufferFormat include D3DFMT_X1R5G5B5 and D3DFMT_A1R5G5B5, but exclude D3DFMT_R5G6B5.

The following code fragment checks to see if the default adapter will handle RGB565 colors in windowed mode using hardware acceleration.

     Dim DisplayFormat As CONST_D3DFORMAT, BackBufferFormat As CONST_D3DFORMAT
     Dim IsWindowed As Long, bModeOK As Boolean, Check As Long

             DisplayFormat = D3DFMT_R5G6B5
             BackBufferFormat = D3DFMT_R5G6B5
     IsWindowed = 1     'True

     Check = d3d.CheckDeviceType(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, DisplayFormat, BackBufferFormat, IsWindowed)
     If (Check >= 0) Then
         bModeOK = 1
     Else
         bModeOK = 0
     End If


Direct3D8.CreateDevice

Creates a device to represent the display adapter.

object.CreateDevice( _
    Adapter As Long, _
    DeviceType As CONST_D3DDEVTYPE, _
    hFocusWindow As Long, _
    BehaviorFlags As Long, _
    PresentationParameters As D3DPRESENT_PARAMETERS) As Direct3DDevice8

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
Member of the CONST_D3DDEVTYPE enumeration. Denotes the desired device type. If the desired device type is not available, the method will fail.
hFocusWindow
Window handle to which focus belongs for this Direct3Ddevice. The window specified must be a top-level window for full-screen.
BehaviorFlags
A combination of one or more flags defined by the CONST_D3DCREATEFLAGS enumeration that control global behaviors of the Microsoft® Direct3D® device.
PresentationParameters
A D3DPRESENT_PARAMETERS type, describing the presentation parameters for the device to be created. Calling CreateDevice can change the value of the BackBufferCount member of D3DPRESENT_PARAMETERS; the back buffer count is changed to reflect a corrected number of back buffers.

Return Values

This method returns a Direct3DDevice8 object, representing the created device.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method returns a fully working device object, set to the required display mode (or windowed), and allocated with the appropriate back buffers. The application needs only to create and set a depth buffer, if desired, to begin rendering.

See Also

Direct3DDevice8.Reset, D3DDEVICE_CREATION_PARAMETERS


Direct3D8.EnumAdapterModes

Enumerates the display modes of an adapter.

object.EnumAdapterModes( _
    Adapter As Long, _
    Mode As Long, _
    DisplayMode As D3DDISPLAYMODE)

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
Ordinal number that denotes the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
Mode
Ordinal number that denotes the mode to enumerate. D3DCURRENT_DISPLAY_MODE is a special value denoting the current desktop display mode on this adapter and cannot be specified for this method.
DisplayMode
A D3DDISPLAYMODE type, to be filled with information describing this mode.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Some display drivers include refresh rate information that will greatly increase the number of modes. On older drivers, refresh rates of D3DADAPTER_DEFAULT are the only ones enumerated. Direct3D attempts to limit display modes and refresh rates based on the monitor capabilities. However, there is still some risk that an enumerated mode will not be supported by the system's monitor. You may want to implement a display mode testing facility similar to that used by the Microsoft® Windows® Display Control Panel utility.

Use Direct3D8.GetAdapterModeCount to determine the total number of modes supported by the system. Valid values for the Mode parameter range from 0 to the total number of modes minus 1.

See Also

Direct3D8.GetAdapterModeCount


Direct3D8.GetAdapterCount

Returns the number of adapters on the system.

object.GetAdapterCount() As Long

Parts

object
Object expression that resolves to a Direct3D8 object.

Return Values

A LONG value that denotes the number of adapters on the system at the time this Direct3D8 object was created.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3D8.GetAdapterIdentifier


Direct3D8.GetAdapterDisplayMode

Retrieves the current display mode of the adapter.

object.GetAdapterDisplayMode( _
    Adapter As Long, _
    Mode As D3DDISPLAYMODE)

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
Ordinal number that denotes the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
Mode
A D3DDISPLAYMODE type, to be filled with information describing the current adapter's mode.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Note that a device that represents an adapter may have been reset into a mode other than the adapter's mode. In this case, if the device is lost, it will not determine the adapter's current mode. This function returns the adapter mode, not any particular device's desired mode.


Direct3D8.GetAdapterIdentifier

Describes the physical display adapters present in the system when the Direct3D8 object was created.

object.GetAdapterIdentifier( _
    Adapter As Long, _
    Flags As Long, _
    Identifier As D3DADAPTER_IDENTIFIER8)

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
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 Direct3D8.GetAdapterCount.
Flags
Parameter that is typically set to 0 (zero). However, you can specify the following value defined by the CONST_D3DCONST enumeration.
D3DENUM_NO_WHQL_LEVEL
Forces the WHQLLevel member of the D3DADAPTER_IDENTIFIER8 type to be 0 (zero). In this case, no information is returned for the WHQL certification date. Setting this flag avoids the one- or two-second time penalty incurred to determine the WHQL certification date.
Identifier
A D3DADAPTER_IDENTIFIER8 type to be filled with information describing this adapter.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3D8.GetAdapterCount


Direct3D8.GetAdapterModeCount

Returns the number of display modes available on this adapter.

object.GetAdapterModeCount( _
    Adapter As Long) As Long

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.

Return Values

This method returns the number of display modes on this adapter, or 0 (zero) if Adapter is greater than or equal to the number of adapters on the system.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3D8.EnumAdapterModes


Direct3D8.GetAdapterMonitor

Returns the handle of the monitor associated with the Microsoft® Direct3D® object.

object.GetAdapterMonitor( _
    Adapter As Long) As Long

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

As shown in the following code fragment, which illustrates how to obtain a handle to the monitor associated with a given device, use Direct3DDevice8.GetDirect3D to return the Direct3D enumerator from the device, and use Direct3DDevice8.GetCreationParameters to retrieve the value for Adapter.

    Dim Device As Direct3DDevice8, D3D As Direct3DDevice8
    Dim Parameters As D3DDEVICE_CREATION_PARAMETERS
    Dim MonitorHandle As Long

    ' The following code fragment assumes that the above items have been properly created and initialized
    If ((Device.GetCreationParameters(Parameters) <= 0) And (Device.GetDirect3D(D3D) <= 0)) Then
        MonitorHandle = D3D.GetAdapterMonitor(Parameters.AdapterOrdinal)
    Else
        ' Error handling code here
    End If

See Also

Direct3DDevice8.GetCreationParameters, Direct3DDevice8.GetDirect3D


Direct3D8.GetDeviceCaps

Retrieves device-specific information about a device.

object.GetDeviceCaps( _
    Adapter As Long, _
    DeviceType As CONST_D3DDEVTYPE, _
    Caps As D3DCAPS8)

Parts

object
Object expression that resolves to a Direct3D8 object.
Adapter
Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
Member of the CONST_D3DDEVTYPE enumeration. Denotes the device type.
Caps
A D3DCAPS8 type to be filled with information describing the capabilities of the device.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_INVALIDDEVICE
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic Error Handling topic.

Remarks

The application should not assume the persistence of vertex processing capabilities across Microsoft® Direct3D® device objects. The particular capabilities that a physical device exposes may depend on parameters supplied to Direct3D8.CreateDevice. For example, the capabilities might yield different vertex processing capabilities before and after creating a Direct3D Device Object with hardware vertex processing enabled. For more information, see D3DCAPS8.


Direct3D8.RegisterSoftwareDevice

Registers a pluggable software device with Microsoft® Direct3D®.

object.RegisterSoftwareDevice( _
    InitializeFunction As Any)

Parts

object
Object expression that resolves to a Direct3D8 object.
InitializeFunction
Initialization function for the software device to be registered.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The current interface for pluggable software rasterizers is a depreciated feature so do not use this method for any rasterizer (other than using it with the Microsoft® DirectX® reference rasterizer for testing).


Direct3DBaseTexture8

Applications use the methods of the class to manipulate texture resources, including cube textures, textures and volume textures.

The Direct3DBaseTexture8 class assigned to a particular stage for a device is obtained by calling the Direct3DDevice8.GetTexture method.

The methods of the Direct3DBaseTexture8 class can be organized into the following groups.

Detail | GetLOD
 | SetLOD
Information | GetLevelCount

This class inherits additional functionality from the Direct3DResource8 class.


Direct3DBaseTexture8.GetLevelCount

Returns the number of texture levels in a multilevel texture.

object.GetLevelCount() As Long

Parts

object
Object expression that resolves to a Direct3DBaseTexture8 object.

Return Values

A Long value, indicating the number of texture levels in a multilevel texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DBaseTexture8.

  • Direct3DCubeTexture8
  • Direct3DTexture8
  • Direct3DVolumeTexture8


Direct3DBaseTexture8.GetLOD

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

object.GetLOD() As Long

Parts

object
Object expression that resolves to a Direct3DBaseTexture8 object.

Return Values

A Long value, clamped to the maximum LOD value (one less than the total number of levels).

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DBaseTexture8.

  • Direct3DCubeTexture8
  • Direct3DTexture8
  • Direct3DVolumeTexture8

Remarks

GetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

See Also

Direct3DBaseTexture8.SetLOD


Direct3DBaseTexture8.SetLOD

Sets the most detailed level of detail (LOD) for a managed texture.

object.SetLOD( _
    LODNew As Long) As Long

Parts

object
Object expression that resolves to a Direct3DBaseTexture8 object.
LODNew
Most detailed LOD value to set for the mipmap chain.

Return Values

A Long value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method return the clamped value, not the LOD value that was previously set.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DBaseTexture8.

  • Direct3DCubeTexture8
  • Direct3DTexture8
  • Direct3DVolumeTexture8

Remarks

SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

SetLOD communicates to the Microsoft® 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 256×256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

See Also

Direct3DBaseTexture8.GetLOD


Direct3DCubeTexture8

Applications use the methods of the Direct3DCubeTexture8 class to manipulate a cube map resource.

The Direct3DCubeTexture8 class is obtained by calling the Direct3DDevice8.CreateCubeTexture method.

The methods of the Direct3DCubeTexture8 class can be organized into the following groups.

Information | GetLevelDesc
Locking Surfaces | LockRect
 | UnlockRect
Miscellaneous | AddDirtyRect
 | GetCubeMapSurface

This class inherits additional functionality from the Direct3DBaseTexture8 class.

See Also

Direct3DDevice8.CreateCubeTexture


Direct3DCubeTexture8.AddDirtyRect

Adds a dirty region to a cube map resource.

object.AddDirtyRect( _
    FaceType  As CONST_D3DCUBEMAP_FACES, _
    DirtyRect As Any)

Parts

object
Object expression that resolves to a Direct3DCubeTexture8 object.
FaceType
Member of the CONST_D3DCUBEMAP_FACES enumeration, identifying the cube map face.
DirtyRect
A RECT type, specifying the dirty region. Specifying ByVal 0 expands the dirty region to cover the entire cube texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 LockRect or LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of a CopyRects call is marked dirty.

See Also

Direct3DCubeTexture8.GetLevelDesc, Direct3DCubeTexture8.LockRect, Direct3DCubeTexture8.UnlockRect


Direct3DCubeTexture8.GetCubeMapSurface

Retrieves a cube map surface.

object.GetCubeMapSurface( _
    FaceType As CONST_D3DCUBEMAP_FACES, _
    Level As Long) As Direct3DSurface8

Parts

object
Object expression that resolves to a Direct3DCubeTexture8 object.
FaceType
Member of the CONST_D3DCUBEMAP_FACES enumeration, identifying a cube map face.
Level
Specifies a level of a mipmapped cube texture.

Return Values

This method returns a Direct3DSurface8 object, representing the returned cube map surface.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DCubeTexture8.GetLevelDesc

Retrieves a description of one face of the specified cube texture level.

object.GetLevelDesc( _
    Level As Long, _
    Desc As D3DSURFACE_DESC)

Parts

object
Object expression that resolves to a Direct3DCubeTexture8 object.
Level
Specifies a level of a mipmapped cube texture.
Desc
A D3DSURFACE_DESC type, describing one face of the specified cube texture level.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if one or more of the parameters are invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DSURFACE_DESC structure contains a size member, which is the size of one face of the cube. To get the size of the entire cube, multiply the size data by six.

See Also

Direct3DCubeTexture8.AddDirtyRect, Direct3DCubeTexture8.LockRect, Direct3DCubeTexture8.UnlockRect


Direct3DCubeTexture8.LockRect

Locks a rectangle on a cube texture resource.

object.LockRect( _
    FaceType As CONST_D3DCUBEMAP_FACES, _
    Level As Long, _
    LockedRect As D3DLOCKED_RECT, _
    Rect As Any, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DCubeTexture8 object.
FaceType
Member of the CONST_D3DCUBEMAP_FACES enumeration, identifying a cube map face.
Level
Specifies a level of a mipmapped cube texture.
LockedRect
A D3DLOCKED_RECT type, describing the region to lock.
Rect
Rectangle to lock. Specified by a RECT type, or ByVal 0 to expand the dirty region to cover the entire texture.
Flags
A combination of zero or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See Direct3DDevice8.UpdateTexture for more information.

A multisample backbuffer cannot be locked.

See Also

Direct3DCubeTexture8.AddDirtyRect, Direct3DCubeTexture8.GetLevelDesc, Direct3DCubeTexture8.UnlockRect


Direct3DCubeTexture8.UnlockRect

Unlocks a rectangle on a cube texture resource.

object.UnlockRect( _
    FaceType As CONST_D3DCUBEMAP_FACES, _
    Level As Long)

Parts

object
Object expression that resolves to a Direct3DCubeTexture8 object.
FaceType
Member of the CONST_D3DCUBEMAP_FACES enumeration, identifying a cube map face.
Level
Specifies a level of a mipmapped cube texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DCubeTexture8.AddDirtyRect, Direct3DCubeTexture8.LockRect


Direct3DDevice8

Applications use the methods of the Direct3DDevice8 class to perform DrawPrimitive-based rendering, create resources, work with system-level variables, adjust gamma ramp levels, and work with palettes.

The Direct3DDevice8 class is obtained by calling the Direct3D8.CreateDevice method.

The methods of the Direct3DDevice8 class can be organized into the following groups.

Cursors | SetCursorPosition
 | SetCursorProperties
 | ShowCursor
Creation | CreateAdditionalSwapChain
 | CreateCubeTexture
 | CreateDepthStencilSurface
 | CreateImageSurface
 | CreateIndexBuffer
 | CreateRenderTarget
 | CreateTexture
 | CreateVertexBuffer
 | CreateVolumeTexture
Device States | ApplyStateBlock
 | BeginStateBlock
 | CaptureStateBlock
 | CreateStateBlock
 | DeleteStateBlock
 | EndStateBlock
 | GetClipStatus
 | GetRenderState
 | GetRenderTarget
 | GetTransform
 | SetClipStatus
 | SetRenderState
 | SetRenderTarget
 | SetTransform
Gamma Ramps | GetGammaRamp
 | SetGammaRamp
High-Order Primitives | DeletePatch
 | DrawRectPatch
 | DrawTriPatch
Index Data | GetIndices
 | SetIndices
Information | GetAvailableTextureMem
 | GetCreationParameters
 | GetDeviceCaps
 | GetDirect3D
 | GetDisplayMode
 | GetInfo
 | GetRasterStatus
Lighting and Materials | GetLight
 | GetLightEnable
 | GetMaterial
 | LightEnable
 | SetLight
 | SetMaterial
Miscellaneous | CopyRects
 | MultiplyTransform
 | ProcessVertices
 | ResourceManagerDiscardBytes
 | TestCooperativeLevel
Palettes | GetCurrentTexturePalette
 | GetPaletteEntries
 | SetCurrentTexturePalette
 | SetPaletteEntries
Pixel Shaders | CreatePixelShader
 | DeletePixelShader
 | GetPixelShader
 | GetPixelShaderConstant
 | GetPixelShaderFunction
 | SetPixelShader
 | SetPixelShaderConstant
Presentation | Present
 | Reset
Rendering | DrawIndexedPrimitive
 | DrawIndexedPrimitiveUP
 | DrawPrimitive
 | DrawPrimitiveUP
Scenes | BeginScene
 | EndScene
Stream Data | GetStreamSource
 | SetStreamSource
Surfaces | GetBackBuffer
 | GetDepthStencilSurface
 | GetFrontBuffer
Textures | GetTexture
 | GetTextureStageState
 | SetTexture
 | SetTextureStageState
 | UpdateTexture
 | ValidateDevice
User-Defined Clip Planes | GetClipPlane
 | SetClipPlane
Viewports | Clear
 | GetViewport
 | SetViewport
Vertex Shaders | CreateVertexShader
 | DeleteVertexShader
 | GetVertexShader
 | GetVertexShaderConstant
 | GetVertexShaderDeclaration
 | GetVertexShaderFunction
 | SetVertexShader
 | SetVertexShaderConstant

See Also

Direct3D8.CreateDevice


Direct3DDevice8.ApplyStateBlock

Applies an existing device-state block to the rendering device.

object.ApplyStateBlock( _
    Token As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Token
Handle to the device-state block to execute, as returned by a previous call to the Direct3DDevice8.EndStateBlock method.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

Err.Number may be set to D3DERR_INVALIDCALL to indicate that the Token parameter is invalid or a macro is currently being recorded.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The value &hFFFFFFFF& is an invalid state block handle.

Applications cannot apply a device-state block while recording another block.

As with all operations that affect the state of the rendering device, it is recommended that you apply state blocks during scene rendering—that is, after calling the Direct3DDevice8.BeginScene method and before calling Direct3DDevice8.EndScene.

See Also

Direct3DDevice8.BeginStateBlock, Direct3DDevice8.EndStateBlock, Direct3DDevice8.CaptureStateBlock, Direct3DDevice8.CreateStateBlock, Direct3DDevice8.DeleteStateBlock


Direct3DDevice8.BeginScene

Begins a scene.

object.BeginScene()

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Applications must call this method before performing any rendering and must call Direct3DDevice8.EndScene when rendering is complete and before calling BeginScene again.

If the BeginScene method fails, the device was unable to begin the scene, and there is no need to call the Direct3DDevice8.EndScene method. In fact, calls to EndScene fail if the previous call to BeginScene failed.

See Also

Direct3DDevice8.EndScene


Direct3DDevice8.BeginStateBlock

Signals Microsoft® Direct3D® to begin recording a device-state block.

object.BeginStateBlock()

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Applications can ensure that all recorded states are valid by calling the Direct3DDevice8.ValidateDevice method prior to calling this method.

The following methods can be recorded in a state block, after calling BeginStateBlock and before Direct3DDevice8.EndStateBlock.

  • Direct3DDevice8.LightEnable
  • Direct3DDevice8.SetClipPlane
  • Direct3DDevice8.SetIndices
  • Direct3DDevice8.SetLight
  • Direct3DDevice8.SetMaterial
  • Direct3DDevice8.SetPixelShader
  • Direct3DDevice8.SetPixelShaderConstant
  • Direct3DDevice8.SetRenderState
  • Direct3DDevice8.SetStreamSource
  • Direct3DDevice8.SetTexture
  • Direct3DDevice8.SetTextureStageState
  • Direct3DDevice8.SetTransform
  • Direct3DDevice8.SetViewport
  • Direct3DDevice8.SetVertexShader
  • Direct3DDevice8.SetVertexShaderConstant

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.

See Also

Direct3DDevice8.ApplyStateBlock, Direct3DDevice8.EndStateBlock, Direct3DDevice8.CaptureStateBlock, Direct3DDevice8.CreateStateBlock, Direct3DDevice8.DeleteStateBlock


Direct3DDevice8.CaptureStateBlock

Updates the values within an existing state block to the values set for the device.

object.CaptureStateBlock( _
    Token As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Token
Handle to the state block into which the device state is captured.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The value &hFFFFFFFF& is an invalid state block handle.

This method captures updated values for states within an existing state block. It does not capture the entire state of the device.

CaptureStateBlock does not capture information for lights that are explicitly or implicitly created after the stateblock is created. For example, capturing the current state into a stateblock of type D3DSBT_ALL does not store information for lights that are created post-capture.

See Also

Direct3DDevice8.ApplyStateBlock, Direct3DDevice8.BeginStateBlock, Direct3DDevice8.CreateStateBlock, Direct3DDevice8.EndStateBlock, Direct3DDevice8.DeleteStateBlock


Direct3DDevice8.Clear

Clears the viewport, or a set of rectangles in the viewport, to a specified RGBA color, clears the depth buffer, and erases the stencil buffer.

object.Clear( _
    Count As Long, _
    ClearD3DRect As Any,
    Flags As CONST_D3DCLEARFLAGS, _
    Color As Long, _
    Z As Single, _
    Stencil As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Count
Number of rectangles in the array at ClearD3DRect. If you set ClearD3DRect to ByVal 0, this parameter must be set to 0.
ClearD3DRect
First element of an array of D3DRECT types 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 surface. Coordinates are clipped to the bounds of the viewport rectangle. This parameter can be set to ByVal 0 to indicate that the entire viewport rectangle is to be cleared.
Flags
A combination of the flags defined by the CONST_D3DCLEARFLAGS enumeration that indicate which surfaces should be cleared. Note that at least one flag must be used.
Color
A 32-bit ARGB color value to which the render target surface is cleared.
Z
New z value that this method stores in the depth buffer. This parameter can be in the range from 0.0 through 1.0 (for z-based or w-based depth buffers). A value of 0.0 represents the nearest distance to the viewer, and 1.0 the farthest distance.
Stencil
Integer value to store in each stencil-buffer entry. This parameter can be in the range from 0 through 2n–1, where n is the bit depth of the stencil buffer.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method fails if you specify the D3DCLEAR_ZBUFFER or D3DCLEAR_STENCIL flags when the render target does not have an attached depth buffer. Similarly, if you specify the D3DCLEAR_STENCIL flag when the depth-buffer format does not contain stencil buffer information, this method fails.

The following code fragment shows how to call the default case for Clear.

Dim Device As Direct3DDevice8

' The following assumes that Flags, Color, Z, and Stencil
' have been set to valid values.
Device.Clear 0, ByVal 0, Flags, Color, Z, Stencil

The following code fragment show how to call Clear when specifying an array of rectangles to clear.

Dim clearD3dRects(10)
device.Clear 10, clearD3dRects(0), Flags, Color, Z, Stencil

Note that you pass in only the first element of the array of rectangles to clear.


Direct3DDevice8.CopyRects

Copies rectangular subsets of pixels from one surface to another.

object.CopyRects( _
    SourceSurface As Direct3DSurface8, _
    FirstElementOfSourceRectsArray As Any, _
    NumberOfRects As Long, _
    DestinationSurface As Direct3DSurface8, _
    FirstElementofDestPointArray As Any)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
SourceSurface
A Direct3DSurface8 object, representing the source surface. This parameter must be a different surface object than DestinationSurface.
FirstElementOfSourceRectsArray
First element of an array representing the rectangles to be transferred, or ByVal 0 to specify that the entire surface is copied. Each rectangle is transferred to the destination surface, with its top-left pixel at the position identified by the corresponding element of FirstElementofDestPointArray.
NumberOfRects
Number of rectangles contained in FirstElementOfSourceRectsArray.
DestinationSurface
A Direct3DSurface8 object, representing the destination surface. This parameter must be a different surface object than SourceSurface.
FirstElementofDestPointArray
First element of an array that defines a series of points, identifying the top-left pixel position of each rectangle contained in FirstElementOfSourceRectsArray. If this parameter is ByVal 0, the rectangles are copied to the same offset (same top/left location) as the source rectangle.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_DEVICELOST

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method does not support stretch, color key, alpha blend, format conversion or clipping of either source or destination rectangles. Note that this method will fail unless all the source rectangles and their corresponding destination rectangles are completely contained within the source and destination surfaces respectively. The format of the two surfaces must match, but they can have different dimensions.

If the destination surface is a level-zero of a texture, then it will be marked dirty. See Direct3DDevice8.UpdateTexture and Direct3DTexture8.AddDirtyRect for more details.

This method cannot be applied to surfaces whose formats are classified as depth stencil formats.

This method can return D3DERR_DEVICELOST when the source object is in volatile memory (D3DPOOL_DEFAULT) and the destination object is in nonvolatile memory (D3DPOOL_SYSTEMMEM or D3DPOOL_MANAGED). For more information, see Lost Devices.


Direct3DDevice8.CreateAdditionalSwapChain

Creates an additional swap chain for rendering multiple views.

object.CreateAdditionalSwapChain( _
    PresentationParameters As D3DPRESENT_PARAMETERS) As Direct3DSwapChain8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PresentationParameters
D3DPRESENT_PARAMETERS type, representing the presentation parameters for the new swap chain.

Return Values

An Direct3DSwapChain8 object, representing the additional swap chain.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

There is always at least one swap chain for each device because Microsoft® Direct3D® for Microsoft DirectX® 8.x has one swap chain as a property of the device.

Note that any given device can support only one full-screen swap chain.

See Also

Presenting Multiple Views in Windowed Mode


Direct3DDevice8.CreateCubeTexture

Creates a cube texture resource.

object.CreateCubeTexture( _
    EdgeLength As Long, _
    Levels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL) As Direct3DCubeTexture8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
EdgeLength
Size of the edges of all the top-level faces of the cube texture. The pixel dimensions of subsequent levels of each face are the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. If the division by 2 results in 0, 1 will be taken instead.
Levels
The number of levels in each face of the cube texture. If this is 0 (zero), Microsoft® Direct3D® will generate all cube texture sublevels down to 1×1 pixels for each face for hardware that supports mipmapped cube textures. Otherwise, it will create one level. Call Direct3DBaseTexture8.GetLevelCount to see the number of levels generated.
Usage
A combination of one or more of the following flags defined by the CONST_D3DUSAGEFLAGS enumeration, describing the usage for this resource.
D3DUSAGE_DEPTHSTENCIL
Set to indicate that the surface is to be used as a depth-stencil surface. The resource can be passed to the NewDepthStencil parameter of the Direct3DDevice8.SetRenderTarget method. See Remarks.
D3DUSAGE_RENDERTARGET
Set to indicate that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. See Remarks.
D3DUSAGE_DYNAMIC
Set to indicate that the usage for the surface is dynamic. See Using Dynamic Textures for more information.

If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DEPTHSTENCIL is specified, the application should check that the device supports these operations by calling Direct3D8.CheckDeviceFormat.

Format
Member of the CONST_D3DFORMAT enumeration, describing the format of all levels in all faces of the cube texture.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the cube texture should be placed.

Return Values

A Direct3DCubeTexture8 object, representing the created cube texture resource.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using Direct3DCubeTexture8.GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

A texture (mipmap) is a collection of successively downsampled (mipmapped) surfaces. On the other hand, a cube texture (created by 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).

In Microsoft® DirectX® 8.x, resource usage is enforced. An application that wishes to use a resource in a certain operation must specify that operation at resource creation time.


Direct3DDevice8.CreateDepthStencilSurface

Creates a depth-stencil resource.

object.CreateDepthStencilSurface( _
    Width As Long, _
    Height As Long, _
    Format As CONST_D3DFORMAT, _
    MultiSample As CONST_D3DMULTISAMPLE_TYPE, _
    Surface As Direct3DSurface8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Width
Width of the depth-stencil surface, in pixels.
Height
Height of the depth-stencil surface, in pixels.
Format
Member of the CONST_D3DFORMAT enumeration, describing the format of the depth-stencil surface. This value must be one of the enumerated depth-stencil formats for this device.
MultiSample
Member of the CONST_D3DMULTISAMPLE_TYPE enumeration, describing the multisampling buffer type. This value must be one of the allowed multisample types. When this surface is passed to SetRenderTarget, its multisample type must be the same as that of the render target.
Surface
A Direct3DSurface8 object, representing the created depth-stencil surface resource.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The memory class of the depth-stencil buffer is always D3DPOOL_DEFAULT.

See Also

Direct3DDevice8.CopyRects, Direct3DDevice8.SetRenderTarget


Direct3DDevice8.CreateImageSurface

Creates an image surface.

object.CreateImageSurface( _
    Width As Long, _
    Height As Long, _
    Format As CONST_D3DFORMAT) As Direct3DSurface8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Width
Width of the image surface, in pixels.
Height
Height of the image surface, in pixels.
Format
Member of the CONST_D3DFORMAT enumerated type, describing the format of the image surface.

Return Values

A Direct3DSurface8 object, representing the created image surface.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Image surfaces are place holders, they are surfaces that cannot be used in any Microsoft® Direct3D® operations except locking and Direct3DDevice8.CopyRects.

Image surfaces are placed in the D3DPOOL_SYSTEMMEM memory class.


Direct3DDevice8.CreateIndexBuffer

Creates an index buffer.

object.CreateIndexBuffer( _
    LengthInBytes As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL) As Direct3DIndexBuffer8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
LengthInBytes
Size of the index buffer, in bytes.
Usage
A combination of one or more of the following flags defined by the CONST_D3DUSAGEFLAGS enumeration, describing the usage controls for this resource.
D3DUSAGE_DONOTCLIP
Set to indicate that the index buffer content will never require clipping.
D3DUSAGE_DYNAMIC
Set to indicate when the vertex or index buffer requires dynamic memory usage. This usage is useful for drivers because it enables them to decide where to place the driver. 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 usage; 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 and index buffers created with D3DUSAGE_DYNAMIC; they are not valid flags on static vertex buffers.

Note that D3DUSAGE_DYNAMIC cannot be specified on managed vertex and index buffers. For more information, see Managing Resources.

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 select 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.
Format
Member of the CONST_D3DFORMAT enumeration, describing the format of the index buffer. The valid settings are the following:
D3DFMT_INDEX16
Indices are 16 bits each.
D3DFMT_INDEX32
Indices are 32 bits each. See Remarks.
Pool
Member of the CONST_D3DPOOL enumeration, describing a valid memory class into which to place the resource.

Return Values

A Direct3DIndexBuffer8 object, representing the created index buffer resource.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 Microsoft® 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 Direct3DDevice8.SetIndices, set up the vertices, set up the vertex shader, and call Direct3DDevice8.DrawIndexedPrimitive for rendering.

The MaxVertexIndex member of the D3DCAPS8 type indicates the types of index buffers that are valid for rendering.

See Also

Direct3DIndexBuffer8.GetDesc


Direct3DDevice8.CreatePixelShader

Creates a pixel shader.

object.CreatePixelShader( _
    FunctionTokenArray As Long) As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
FunctionTokenArray
First element of the pixel shader function token array, specifying the blending operations.

Return Values

Returned pixel shader handle.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.DeletePixelShader, D3DX8.AssembleShader, D3DX8.AssembleShaderFromFile


Direct3DDevice8.CreateRenderTarget

Creates a render target surface.

object.CreateRenderTarget( _
    Width As Long, _
    Height As Long, _
    Format As CONST_D3DFORMAT, _
    MultiSample As CONST_D3DMULTISAMPLE_TYPE, _
    Lockable As Long) As Direct3DSurface8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Width
Width of the render target surface, in pixels.
Height
Height of the render target surface, in pixels.
Format
Member of the CONST_D3DFORMAT enumeration, describing the format of the render target.
MultiSample
Member of the CONST_D3DMULTISAMPLE_TYPE enumeration, describing the multisampling buffer type. This parameter specifies the antialiasing type for this render target. The type must be the same as that of the depth stencil buffer when both surfaces are passed to SetRenderTarget.
Lockable
Value indicating whether the render target surface is lockable. If set to 1, the render target is lockable. If set to 0, it is unlockable. Note that lockable render targets incur a performance cost on some graphics hardware.

Return Values

A Direct3DSurface8 object, representing the render target surface.

Remarks

Render target surfaces are placed in the D3DPOOL_DEFAULT memory class.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DDevice8.CreateStateBlock

Creates a new state block that contains the values for all device states, vertex-related states, or pixel-related states.

object.CreateStateBlock( _
    BlockType As CONST_D3DSTATEBLOCKTYPE) As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
BlockType
Type of state data that the method should capture. This parameter can be set to a value defined in the CONST_D3DSTATEBLOCKTYPE enumeration.

Return Values

A Long value containing the state block handle if the method succeeds.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The value &hFFFFFFFF& is an invalid state block handle.

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.

See Also

Direct3DDevice8.ApplyStateBlock, Direct3DDevice8.BeginStateBlock, Direct3DDevice8.CaptureStateBlock, Direct3DDevice8.EndStateBlock, Direct3DDevice8.DeleteStateBlock


Direct3DDevice8.CreateTexture

Creates a texture resource.

object.CreateTexture( _
    Width As Long, _
    Height As Long, _
    Levels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL) As Direct3DTexture8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Width
Width of the top-level of the texture, in pixels. 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. If the division by 2 results in 0, 1 will be taken instead.
Height
Height of the top-level of the texture level, in pixels. 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. If the division by 2 results in 0, 1 will be taken instead.
Levels
The number of levels in the texture. If this is 0 (zero), Microsoft® Direct3D® will generate all texture sub-levels down to 1×1 pixels for hardware that supports MIP mapped textures. Otherwise, it will create one level. Call Direct3DBaseTexture8.GetLevelCount to see the number of levels generated.
Usage
A combination of one or more of the following flags defined by the CONST_D3DUSAGEFLAGS enumeration, describing the usage for this resource.
D3DUSAGE_DEPTHSTENCIL
Set to indicate that the surface is to be used as a depth-stencil surface. The resource can be passed to the NewDepthStencil parameter of the Direct3DDevice8.SetRenderTarget method.
D3DUSAGE_RENDERTARGET
Set to indicate that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method.
D3DUSAGE_DYNAMIC
Set to indicate that the usage for the surface is dynamic. See Using Dynamic Textures for more information.

If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DEPTHSTENCIL is specified, the application should check that the device supports these operations by calling Direct3D8.CheckDeviceFormat.

Format
Member of the CONST_D3DFORMAT enumeration, describing the format of all levels in the texture.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the texture should be placed.

Return Values

A Direct3DTexture8 object, representing the created texture resource.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

In order to call Direct3DDevice8.SetRenderTarget with a texture, you must select a level using Direct3DTexture8.GetSurfaceLevel and pass the resulting surface to SetRenderTarget.


Direct3DDevice8.CreateVertexBuffer

Creates a vertex buffer.

object.CreateVertexBuffer( _
    LengthInBytes As Long, _
    Usage As Long, _
    FVF As Long, _
    Pool As CONST_D3DPOOL) As Direct3DVertexBuffer8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
LengthInBytes
Size of the vertex buffer, in bytes. For Flexible Vertex Format (FVF) 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 validated only for FVF buffers.
Usage
A combination of one or more of the following flags defined by the CONST_D3DUSAGEFLAGS enumeration, describing the usage controls for this resource.
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 renderstate must be set to 0.
D3DUSAGE_DYNAMIC
Set to indicate when the vertex or index buffer requires dynamic memory usage. This usage is useful for drivers because it enables them to decide where to place the driver. In general, static vertex buffers will be placed in video memory and dynamic vertex buffers will be placed in AGP memory. Note that there is no separate static usage; 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 and index buffers created with D3DUSAGE_DYNAMIC; they are not valid flags on static vertex buffers.

For more information about using dynamic vertex buffers, see Using Dynamic Vertex and Index Buffers.

Note that D3DUSAGE_DYNAMIC cannot be specified on managed vertex and index buffers. For more information, see Managing Resources.

D3DUSAGE_RTPATCHES
Set to indicate when the vertex buffer is to be used for drawing high-order primitives.
D3DUSAGE_NPATCHES
Set to indicate when the vertex buffer is to be used for drawing N patches.
D3DUSAGE_POINTS
Set to indicate when the vertex buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the vertex buffer is to be used with software vertex processing.
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.
FVF
Combination of Flexible Vertex Format Flags, a usage specifier that describes the vertex format of the vertices in this buffer. When this parameter is set to a valid FVF code, the created vertex buffer is an FVF vertex buffer (see Remarks). Otherwise, when this parameter is set to 0 (zero), the vertex buffer is a non-FVF vertex buffer.
Pool
Member of the CONST_D3DPOOL enumeration, describing a valid memory class into which to place the resource.

Return Values

A Direct3DVertexBuffer8 object, representing the created vertex buffer resource.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The Direct3DDevice8 class supports rendering of primitives using vertex data stored in vertex buffer objects. Vertex buffers are created from the Direct3DDevice8 class, and are usable only with the Direct3DDevice8 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.

The D3DUSAGE_SOFTWAREPROCESSING flag specifies that the vertex buffer is to be used with software vertex processing. For more information, see Device Types and Vertex Processing Requirements.

Non-FVF buffers can be used to interleave data during multipass rendering or multitexture rendering in a single pass. To do this, put geometry data in one buffer and texture coordinate data for each texture to be rendered in separate buffers. 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 on texture coordinates, see Texture Coordinates.

See Also

Direct3DVertexBuffer8.GetDesc, Direct3DDevice8.ProcessVertices


Direct3DDevice8.CreateVertexShader

Creates a vertex shader and if created successfully sets that shader as the current shader.

object.CreateVertexShader( _
    DeclarationTokenArray As Long, _
    FunctionTokenArray As Any, _
    retHandle As Long, _
    Usage As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
DeclarationTokenArray
First element of the vertex shader declaration token array. This parameter defines the inputs to the shader, including how the vertex elements within the input data streams are used by the shader.
FunctionTokenArray
First element of the vertex shader function token array. This parameter defines the operations to apply to each vertex. If this parameter is set to ByVal 0, a shader is created for the fixed-function pipeline and the parameter declaration indicated by DeclarationTokenArray is made current and available to be set in a subsequent call to Direct3DDevice8.SetVertexShader.

If this parameter is not set to ByVal 0, the shader is programmable.

retHandle
Returned vertex shader handle.
Usage
Usage controls for the vertex shader. The following flag can be set.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the vertex shader is to be used with software vertex processing. The D3DUSAGE_SOFTWAREPROCESSING flag must be set for vertex shaders used when the D3DRS_SOFTWAREVERTEXPROCESSING member of the CONST_D3DRENDERSTATETYPE enumerated type is 1, and removed for vertex shaders used when D3DRS_SOFTWAREVERTEXPROCESSING is 0.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

A vertex shader is defined by two token arrays that specify the declaration and function of the shader. The token arrays are composed of single or multiple Long tokens terminated by a special &HFFFFFFFF token value.

The shader declaration defines the static external interface of the shader, including binding of stream data to vertex register inputs and values loaded into the shader constant memory. The shader function defines the operation of the shader as an array of instructions that are executed in order for each vertex processed during the time the shader is bound to a device. Shaders created without a function array apply the fixed function vertex processing when that shader is current.

See d3dshader.bas for a definition of the constants used to generate the declaration token array.

See Also

Direct3DDevice8.DeleteVertexShader, D3DX8.AssembleShader, D3DX8.AssembleShaderFromFile, D3DX8.DeclaratorFromFVF


Direct3DDevice8.CreateVolumeTexture

Creates a volume texture resource.

object.CreateVolumeTexture( _
    Width As Long, _
    Height As Long, _
    Depth As Long, _
    Levels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL) As Direct3DVolumeTexture8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Width
Width of the top-level of the volume texture, in pixels. This value must be a power of two. 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
Height of the top-level of the volume texture, in pixels. This value must be a power of two. 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.
Depth
Depth of the top-level of the volume texture, in pixels. This value must be a power of two. 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
The number of levels in the volume texture. If this is 0 (zero), Microsoft® Direct3D® will generate all texture sub-levels down to 1×1×1 pixels for hardware that supports mipmapped volume textures. Otherwise, it will create one level. Call Direct3DBaseTexture8.GetLevelCount to see the number of levels generated.
Usage
Currently not used, set to 0.
Format
Member of the CONST_D3DFORMAT enumeration, describing the format of all levels in the volume texture.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the volume texture should be placed.

Return Values

A Direct3DVolumeTexture8 object, representing the created volume texture resource.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DDevice8.DeletePatch

Frees a cached high-order patch.

object.DeletePatch( _
    Handle As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Handle
Handle of the cached high-order patch to delete.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL to indicate that the Handle parameter is invalid or a macro is currently being recorded.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.DrawRectPatch, Direct3DDevice8.DrawTriPatch, Drawing Patches


Direct3DDevice8.DeletePixelShader

Deletes the pixel shader referred to by the specified handle.

object.DeletePixelShader( _
    PixelShaderHandle As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PixelShaderHandle
Pixel shader handle, identifying the pixel shader to be deleted from its internal entry.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.CreatePixelShader


Direct3DDevice8.DeleteStateBlock

Deletes a previously recorded device-state block.

object.DeleteStateBlock( _
    Token As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Token
Handle to the device-state block to delete, as returned by a previous call to the Direct3DDevice8.EndStateBlock method.

Error Codes

If this method fails, an error is raised and Err.Number is set to one of the following:

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

Err.Number may be set to D3DERR_INVALIDCALL to indicate that the Token parameter is invalid or a macro is currently being recorded.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The value &hFFFFFFFF& is an invalid state block handle.

Applications cannot delete a device-state block while another is being recorded

See Also

Direct3DDevice8.ApplyStateBlock, Direct3DDevice8.BeginStateBlock, Direct3DDevice8.CaptureStateBlock, Direct3DDevice8.CreateStateBlock, Direct3DDevice8.EndStateBlock


Direct3DDevice8.DeleteVertexShader

Deletes the vertex shader referred to by the specified handle and frees up the associated resources.

object.DeleteVertexShader( _
    VertexShaderHandle As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
VertexShaderHandle
Vertex shader handle, identifying the vertex shader to be deleted.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.CreateVertexShader


Direct3DDevice8.DrawIndexedPrimitive

Renders the specified geometric primitive, based on indexing into an array of vertices.

object.DrawIndexedPrimitive( _
    PrimitiveType As CONST_D3DPRIMITIVETYPE, _
    MinIndex As Long, _
    NumIndices As Long, _
    StartIndex As Long, _
    PrimitiveCount As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PrimitiveType
Member of the CONST_D3DPRIMITIVETYPE enumeration, describing the type of primitive to render. See Remarks
MinIndex
Minimum vertex index for vertices used during this call.
NumIndices
The number of vertices indexed during this call starting from BaseVertexIndex + StartIndex.
StartIndex
Location in the index array to start reading indices.
PrimitiveCount
Number of primitives to render. The number of indices 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 D3DCAPS8 structure.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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, set during the Direct3DDevice8.SetIndices call.

The MinIndex and NumIndices parameters specify the range of vertex indices used for each 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.

DrawIndexedPrimitive fails if no index array is set.

The D3DPT_POINTLIST member of the CONST_D3DPRIMITIVETYPE enumeration is not supported and should not be specified for PrimitiveType.

See Also

Direct3DDevice8.DrawPrimitive, Direct3DDevice8.SetStreamSource, Rendering Primitives


Direct3DDevice8.DrawIndexedPrimitiveUP

Renders the specified geometric primitive with data specified by a user memory array.

object.DrawIndexedPrimitiveUP( _
    PrimitiveType As CONST_D3DPRIMITIVETYPE, _
    MinIndex As Long, _
    NumVertices As Long, _
    PrimitiveCount As Long, _
    IndexDataArray As Any, _
    IndexDataFormat As CONST_D3DFORMAT, _
    VertexStreamZeroDataArray As Any, _
    VertexStreamZeroStride As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PrimitiveType
Member of the CONST_D3DPRIMITIVETYPE enumeration, describing the type of primitive to render.
MinIndex
Minimum vertex index, relative to 0 (zero) (the start of VertexStreamZeroDataArray), for vertices used during this call.
NumVertices
The number of vertices used during this call, starting from MinIndex.
PrimitiveCount
Number of primitives to render. The number of indices 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 D3DCAPS8 structure.
IndexDataArray
First element of the user memory array containing the index data. This parameter should point to the start of the indices to use for drawing primitives.
IndexDataFormat
Member of the CONST_D3DFORMAT enumeration, describing the format of the index data. The valid settings are the following:
D3DFMT_INDEX16
Indices are 16 bits each.
D3DFMT_INDEX32
Indices are 32 bits each.
VertexStreamZeroDataArray
First element of the user memory array containing the vertex data to use for vertex stream zero.
VertexStreamZeroStride
Stride between data for each vertex, in bytes, as returned by the Len Microsoft® Visual Basic® function.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Visual Basic Error Handling topic.

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 zero. It is invalid to have the declaration of the current vertex shader refer to vertex streams other than stream zero.

Following any DrawIndexedPrimitiveUP call, the stream zero settings, referenced by Direct3DDevice8.GetStreamSource, are set to ByVal 0. Also, the index buffer setting for Direct3DDevice8.SetIndices is set to ByVal 0.

See Also

Direct3DDevice8.DrawPrimitiveUP, Direct3DDevice8.SetStreamSource, Rendering Primitives


Direct3DDevice8.DrawPrimitive

Renders nonindexed primitives from the current set of data input streams.

object.DrawPrimitive( _
    PrimitiveType As CONST_D3DPRIMITIVETYPE, _
    StartVertex As Long, _
    PrimitiveCount As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PrimitiveType
Member of the CONST_D3DPRIMITIVETYPE enumeration, describing the type of primitive to render.
StartVertex
Index of the first vertex to load. Beginning at StartVertex, the correct number of vertices will be read out of the vertex buffer.
PrimitiveCount
Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS8 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

DrawPrimitive should not be called with a single triangle at a time.

See Also

Direct3DDevice8.DrawIndexedPrimitive, Direct3DDevice8.SetStreamSource, Rendering Primitives


Direct3DDevice8.DrawPrimitiveUP

Renders data specified by a user memory pointer as a sequence of geometric primitives of the specified type.

object.DrawPrimitiveUP( _
    PrimitiveType As CONST_D3DPRIMITIVETYPE, _
    PrimitiveCount As Long, _
    VertexStreamZeroDataArray As Any, _
    VertexStreamZeroStride As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PrimitiveType
Member of the CONST_D3DPRIMITIVETYPE enumeration, describing the type of primitive to render.
PrimitiveCount
Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS8 structure.
VertexStreamZeroDataArray
First element of the user memory array containing the vertex data to use for vertex stream zero.
VertexStreamZeroStride
Stride between data for each vertex, in bytes. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 zero. It is invalid to have the declaration of the current vertex shader refer to vertex streams other than stream zero.

The following code fragment shows how to determine VertexStreamZeroStride, using the Visual Basic Len function.

Dim device As Direct3DDevice8
Dim verts(3) As D3DVERTEX

device.DrawPrimitiveUP D3DPT_TRIANGLELIST, 1, verts(0), Len(vert(0))

Note that you pass in only the first element of the array containing the vertex data.

Following any DrawPrimitiveUP call, the stream zero settings, referenced by Direct3DDevice8.GetStreamSource, are set to ByVal 0.

See Also

Direct3DDevice8.DrawIndexedPrimitiveUP, Direct3DDevice8.SetStreamSource, Rendering Primitives


Direct3DDevice8.DrawRectPatch

Draws a rectangular high-order patch using the currently set streams.

object.DrawRectPatch( _
    Handle As Long, _
    NumSegments As Single, _
    Surface As Any)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Handle
Handle to the rectangular high-order patch to draw.
NumSegments
Number of segments that each edge of the higher-order primitive should be divided into when tessellated.
Surface
D3DRECTPATCH_INFO type, describing the rectangular high-order patch to draw.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

For static patches, set the vertex shader and appropriate streams, supply patch information in the Surface parameter, and specify a handle so that Microsoft® Direct3D® can capture and cache information. Call DrawRectPatch subsequently with Surface set to NULL to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. Override the cached NumSegments by specifying a new value for NumSegments. When rendering a cached patch, you must set the same vertex shader that 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 NumSegments values, and does not cache any information. It is not valid to simultaneously set Handle to 0 and Surface to NULL.

See Also

Direct3DDevice8.DeletePatch, Drawing Patches

Using Higher-Order Primitives


Direct3DDevice8.DrawTriPatch

Draws a triangular high-order patch using the currently set streams.

object.DrawTriPatch( _
    Handle As Long, _
    NumSegments As Single, _
    Surface As Any)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Handle
Handle to the triangular high-order patch to draw.
NumSegments
Number of segments that each edge of the higher-order primitive should be divided into when tessellated.
Surface
D3DTRIPATCH_INFO type, describing the triangular high-order patch to draw.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

For static patches, set the vertex shader and appropriate streams, supply patch information in the Surface parameter, and specify a handle so that Microsoft® Direct3D® can capture and cache information. Call DrawRectPatch subsequently with Surface set to NULL to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. Override the cached NumSegments by specifying a new value for NumSegments. When rendering a cached patch, you must set the same vertex shader that 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 NumSegments values, and does not cache any information. It is not valid to simultaneously set Handle to 0 and Surface to NULL.

See Also

Direct3DDevice8.DeletePatch, Drawing Patches

Using Higher-Order Primitives


Direct3DDevice8.EndScene

Ends a scene that was begun by calling the Direct3DDevice8.BeginScene method.

object.EndScene()

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

When this method succeeds, the scene has been rendered and the device surface holds the rendered scene.

When scene rendering begins successfully, you must call this method before you can call the Direct3DDevice8.BeginScene method to start rendering another scene. If a prior call to BeginScene method fails, the scene did not begin and this method should not be called.

See Also

Direct3DDevice8.BeginScene


Direct3DDevice8.EndStateBlock

Signals Microsoft® Direct3D® to stop recording a device-state block and retrieve a handle to the state block.

object.EndStateBlock() As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

Variable to be filled with the handle to the completed device state block. This value is used with the Direct3DDevice8.ApplyStateBlock and Direct3DDevice8.DeleteStateBlock methods.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL to indicate that the return value is invalid or that the Direct3DDevice8.BeginStateBlock method has not been called.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.ApplyStateBlock, Direct3DDevice8.BeginStateBlock, Direct3DDevice8.CaptureStateBlock, Direct3DDevice8.CreateStateBlock, Direct3DDevice8.DeleteStateBlock


Direct3DDevice8.GetAvailableTextureMem

Returns an estimate of the amount of available texture memory.

object.GetAvailableTextureMem( _
    Pool As CONST_D3DPOOL) As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Pool
CONST_D3DPOOL type, specifying the pool type to check.

Return Values

The function returns an estimate of the available texture memory.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The returned value is rounded to the nearest megabyte (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. However, applications cannot use this value to make small-scale decisions such as if there is enough memory left to allocate another resource.


Direct3DDevice8.GetBackBuffer

Retrieves a back buffer from the device's swap chain.

object.GetBackBuffer( _
    BackBuffer As Long, _
    BufferType As CONST_D3DBACKBUFFERTYPE) As Direct3DSurface8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
BackBuffer
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.
BufferType
Stereo view is not supported in DirectX 8.0, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.

Return Values

A Direct3DSurface8 object, representing the returned back buffer surface.

Error Codes

If BackBuffer exceeds or equals the total number of back buffers, an error is raised and Err.Number may be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DDevice8.GetClipPlane

Retrieves the coefficients of a user-defined clipping plane for the device.

object.GetClipPlane( _
    Index As Long, _
    Plane As D3DPLANE)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Index
Index of the clipping plane for which the plane equation coefficients are retrieved.
Plane
A D3DPLANE type containing the clipping plane coefficients to be set, in the form of the general plane equation. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The coefficients that this method reports take the form of the general plane equation. The values in the D3DPLANE type Plane—a, b, c, and d—fit into the general plane equation so that ax + by + cz + d = 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.

The plane equation used by this method exists in world space and is set by a previous call to the Direct3DDevice8.SetClipPlane method.

See Also

Direct3DDevice8.SetClipPlane , D3DPLANE


Direct3DDevice8.GetClipStatus

Retrieves the clip status.

object.GetClipStatus( _
    ClipStatus As D3DCLIPSTATUS8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
ClipStatus
A D3DCLIPSTATUS8 type that describes the clip status.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if the parameter is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

When clipping is enabled during vertex processing (by ProcessVertices, DrawPrimitive, or other drawing functions), Microsoft® 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 D3DClipStatus8, 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 DrawRectPatch and DrawTriPatch because there is no software emulation for them.

See Also

Direct3DDevice8.SetClipStatus


Direct3DDevice8.GetCreationParameters

Retrieves the creation parameters of the device.

object.GetCreationParameters( _
    CreationParams As D3DDEVICE_CREATION_PARAMETERS)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
CreationParams
A D3DDEVICE_CREATION_PARAMETERS type, describing the creation parameters of the device.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if the parameter is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

You can query the AdapterOrdinal member of the returned D3DDEVICE_CREATION_PARAMETERS type to retrieve the ordinal of the adapter represented by this device.


Direct3DDevice8.GetCurrentTexturePalette

Retrieves the current texture palette.

object.GetCurrentTexturePalette() As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

Returns a value that identifies the current texture palette.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetCurrentTexturePalette, Texture Palettes


Direct3DDevice8.GetDepthStencilSurface

Retrieves the depth-stencil surface owned by the Direct3DDevice object.

object.GetDepthStencilSurface() As Direct3DSurface8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

A Direct3DSurface8 object, representing the returned depth-stencil surface.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetRenderTarget, Direct3DDevice8.CopyRects


Direct3DDevice8.GetDeviceCaps

Retrieves the capabilities of the rendering device.

object.GetDeviceCaps( _
    Caps As D3DCAPS8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Caps
A D3DCAPS8 type, describing the returned device.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

GetDeviceCaps retrieves the software vertex pipeline capabilities when the device is being used in software vertex processing mode. Software vertex processing mode is selected when a device has been created with D3DCREATE_SOFTWAREVERTEXPROCESSING, or when a device has been created with D3DCREATE_MIXEDVERTEXPROCESSING and D3DRS_SOFTWAREVERTEXPROCESSING is set to 1.


Direct3DDevice8.GetDirect3D

Returns a reference to the Microsoft® Direct3D® object that created the device.

object.GetDirect3D() As Direct3D8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

A Direct3D8 object, representing the Direct3D object that created the device.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DDevice8.GetDisplayMode

Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.

object.GetDisplayMode( _
    Mode As D3DDISPLAYMODE)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Mode
A D3DDISPLAYMODE type 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DDevice8.GetFrontBuffer

Generates a copy of the device's front buffer and places that copy in a system memory buffer provided by the application.

object.GetFrontBuffer( _
    DestSurface As Direct3DSurface8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
DestSurface
A Direct3DSurface8 object 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_DEVICELOST

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

For more information, see Lost Devices.

Remarks

The buffer returned in DestSurface will be filled with a representation of the front buffer, converted to the standard 32bpp format, D3DFMT_A8R8G8B8.

This method is the only way to capture an anti-aliased screen shot.


Direct3DDevice8.GetGammaRamp

Retrieves the gamma correction ramp for the swap chain.

object.GetGammaRamp( _
    Ramp As D3DGAMMARAMP)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Ramp
An application-supplied D3DGAMMARAMP type to fill with the gamma correction ramp.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetGammaRamp, Direct3D8.CreateDevice


Direct3DDevice8.GetIndices

Retrieves index data.

object.GetIndices( _
    RetIndexData As Direct3DIndexBuffer8, _
    RetBaseVertexIndex As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
RetIndexData
A Direct3DIndexBuffer8 object, representing the returned index data.
RetBaseVertexIndex
A variable 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The values in the index list are used to index into a vertex list when creating geometry to render.

The value returned in the RetBaseVertexIndex parameter specifies the base value for indices. This base value is added to all indices prior to referencing into the vertex data streams, which results in setting a starting position in the vertex data streams. The base vertex index enables multiple indexed primitives to be packed into a single set of vertex data without requiring the indices to be recomputed based on where the corresponding primitive is placed in the vertex data.

See Also

Direct3DDevice8.SetIndices


Direct3DDevice8.GetInfo

Retrieves information about the rendering device.

object.GetInfo( _
    DevInfoID As Long, _
    Info As Any, _
    Size As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
DevInfoID
Value used to identify what information will be returned in Info.
Info
A type that receives the specified device information if the call succeeds.
Size
Size of the type at Info, in bytes, as returned by the Len Microsoft® Visual Basic® function.

Error Codes

If this method fails, an error is raised and Err.Number is set to one of the following values.
D3DERR_INVALIDCALL | One or more parameters are invalid.
E_FAIL | All parameters are valid, but not supported. The type passed in the Info parameter is not filled.
S_FALSE | All parameters are valid, but an unknown error occurred. The type passed in the Info parameter is not filled.

For information on trapping errors, see the Visual Basic Error Handling topic.

Remarks

Information returned by this method can pertain to Microsoft® Direct3D® or the underlying device driver. This method makes it possible for drivers to declare specific information types and corresponding structures that are not documented in this software development kit (SDK).

This method executes synchronously and it can reduce your application's performance when it executes slowly. Do not call this method during scene rendering (between calls to Direct3DDevice8.BeginScene and Direct3DDevice8.EndScene).

This method is intended to be used for performance tracking and debugging during product development.

The following table shows a list of all the possible input values and the expected return value. ID is equivalent to the DevInfoID parameter, Type is equivalent to the Info parameter, and Size is equivalent to the Size parameter.

ID | Type | Size | Expected return value
- | NULL | - | D3DERR_INVALIDCALL
- | - | 0 | D3DERR_INVALIDCALL
0 | Type_5 | Size_5 | E_FAIL
ID_1 | Type_1 | Size_1 | E_FAIL
ID_2 | Type_2 | Size_2 | E_FAIL
ID_3 | Type_3 | Size_3 | E_FAIL
ID_4 | Type_4 | Size_4 | S_FALSE
ID_5 | Type_5 | Size_5 | E_FAIL

The table below shows the possible values for ID.
ID_1 | D3DDEVINFOID_TEXTUREMANAGER
ID_2 | D3DDEVINFOID_D3DTEXTUREMANAGER
ID_3 | D3DDEVINFOID_TEXTURING
ID_4 | D3DDEVINFOID_VCACHE
ID_5 | D3DDEVINFOID_RESOURCEMANAGER
ID_6 | D3DDEVINFOID_D3DVERTEXSTATS
ID_7 | D3DDEVINFOID_UNKNOWN

The table below shows the possible values for Type.
Type_1 | D3DDEVINFO_TEXTUREMANAGER
Type_2 | D3DDEVINFO_D3DTEXTUREMANAGER
Type_3 | D3DDEVINFO_TEXTUREMANAGER
Type_4 | D3DDEVINFO_VCACHE
Type_5 | D3DDEVINFO_RESOURCEMANAGER
Type_6 | D3DDEVINFO_D3DVERTEXSTATS
Type_7 | D3DDEVINFO_UNKNOWN

The table below shows the possible values for Size.
Size_1 | sizeof(D3DDEVINFO_TEXTUREMANAGER)
Size_2 | sizeof(D3DDEVINFO_D3DTEXTUREMANAGER)
Size_3 | sizeof(D3DDEVINFO_TEXTUREMANAGER)
Size_4 | sizeof(D3DDEVINFO_VCACHE)
Size_5 | sizeof(D3DDEVINFO_RESOURCEMANAGER)
Size_6 | sizeof(D3DDEVINFO_D3DVERTEXSTATS)
Size_7 | sizeof(D3DDEVINFO_UNKNOWN)


Direct3DDevice8.GetLight

Retrieves a set of lighting properties that this device uses.

object.GetLight( _
    Index As Long, _
    Light As D3DLIGHT8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Index
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 Direct3DDevice8.SetLight method.
Light
A D3DLIGHT8 type that is filled with the retrieved lighting-parameter set.

Error Codes

If the method fails, an error is raised and Err.Number may be set to D3DERR_INVALIDCALL if one of the parameters is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetLight, Direct3DDevice8.GetLightEnable, Direct3DDevice8.LightEnable


Direct3DDevice8.GetLightEnable

Retrieves the activity status—enabled or disabled—for a set of lighting parameters within a device.

object.GetLightEnable( _
    Index As Long) As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Index
Zero-based index of the set of lighting parameters that are the target of this method.

Return Values

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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.GetLight, Direct3DDevice8.LightEnable, Direct3DDevice8.SetLight


Direct3DDevice8.GetMaterial

Retrieves the current material properties for the device.

object.GetMaterial( _
    Material As D3DMATERIAL8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Material
A D3DMATERIAL8 type to fill with the currently set material properties.

Error Codes

If the method fails, an error is raised and Err.Number may be set to D3DERR_INVALIDCALL to indicate the Material parameter is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetMaterial


Direct3DDevice8.GetPaletteEntries

Retrieves palette entries.

object.GetPaletteEntries( _
    PaletteNumber As Long, _
    ArrayOfEntries As Any)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PaletteNumber
An ordinal value identifying the particular palette to retrieve.
ArrayOfEntries
A PALETTEENTRY type to be filled with the returned palette entries.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method assumes that the pEntries array has 256 PALETTEENTRY types.

See Also

Direct3DDevice8.GetCurrentTexturePalette, Direct3DDevice8.SetCurrentTexturePalette, Direct3DDevice8.SetPaletteEntries, Texture Palettes


Direct3DDevice8.GetPixelShader

Retrieves the currently set pixel shader.

object.GetPixelShader() As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

Pixel shader handle, representing the returned the pixel shader.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetPixelShader


Direct3DDevice8.GetPixelShaderConstant

Retrieves the values in the pixel constant array.

object.GetPixelShaderConstant( _
    Register As Long, _
    ConstantData As Any, _
    ConstantCount As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Register
Register address at which to start retrieving data from the pixel constant array.
ConstantData
First element of an array to hold the retrieved values from the pixel constant array.
ConstantCount
Number of constants to retrieve from the pixel constant array. Each constant is comprised of four Single values.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This is the method used to retrieve the values in the constant registers of the pixel shader assembler.

See Also

Direct3DDevice8.SetPixelShaderConstant


Direct3DDevice8.GetPixelShaderFunction

Retrieves the pixel shader function.

object.GetPixelShaderFunction( _
    Handle As Long, _
    Data As Any, _
    SizeOfData As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Handle
Handle to the referred to pixel shader.
Data
First element of an array to be filled with the code associated with the requested pixel shader handle, if the call succeeds.
SizeOfData
Size of the array at Data, in bytes. If this value is less than the actual size of the data (such as 0) the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA. If Data is ByVal 0, then this parameter is filled with the required size and D3D_OK is returned.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The pixel shader function specifies blending operations.

See Also

Direct3DDevice8.GetPixelShader


Direct3DDevice8.GetRasterStatus

Returns information describing the raster of the monitor on which the swap chain is presented.

object.GetRasterStatus() As D3DRASTER_STATUS

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

A D3DRASTER_STATUS type filled with information about the position or other status of the raster on the monitor driven by this adapter.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if pRasterStatus is invalid or if the device does not support reading the current scan line. You can determine whether or not the device supports reading the scan line by checking for the D3DCAPS_READ_SCANLINE flag in the Caps member of D3DCAPS8.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DRASTER_STATUS


Direct3DDevice8.GetRenderState

Retrieves a render-state value for a device.

object.GetRenderState( _
    State As CONST_D3DRENDERSTATETYPE) As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
State
Device state variable that is being queried. This parameter can be any member of the CONST_D3DRENDERSTATETYPE enumeration.

Return Values

A variable that receives the value of the queried render state variable when the method returns.

Error Codes

If the method fails, an error is raised and Err.Number may be set to D3DERR_INVALIDCALL if one of the parameters is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetRenderState


Direct3DDevice8.GetRenderTarget

Retrieves a pointer to the Microsoft® Direct3D® surface that is being used as a render target.

object.GetRenderTarget() As Direct3DSurface8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

A Direct3DSurface8 object, representing the returned render target surface for this device.

Error Codes

If the method fails, an error is raised and Err.Number may be set to D3DERR_INVALIDCALL if one of the parameters is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetRenderTarget


Direct3DDevice8.GetStreamSource

Retrieves a vertex buffer bound to the specified data stream.

object.GetStreamSource( _
    StreamNumber As Long, _
    RetStreamData As Direct3DVertexBuffer8, _
    RetStride As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
StreamNumber
Specifies the data stream, in the range from 0 to the maximum number of streams - 1.
RetStreamData
A Direct3DVertexBuffer8 object, representing the returned vertex buffer bound to the specified data stream.
RetStride
Returned stride of the component, in bytes. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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.

The following code fragment shows how to call GetStreamSource.

Dim device As Direct3DDevice8
Dim retVB As Direct3DVertexBuffer8
Dim retStride As Long

device.GetStreamSource 0, retVB, retStride

When GetStreamSource returns, retVB and retStride have been set to valid values.

See Also

Direct3DDevice8.SetStreamSource


Direct3DDevice8.GetTexture

Retrieves a texture assigned to a stage for a device.

object.GetTexture( _
    Stage As Long) As Direct3DBaseTexture8

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Stage
Stage identifier of the texture to retrieve. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum allowable value allowed for Stage is 7.

Return Values

A Direct3DBaseTexture8 object, representing the returned texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetTexture, Direct3DDevice8.GetTextureStageState, Direct3DDevice8.SetTextureStageState


Direct3DDevice8.GetTextureStageState

Retrieves a state value for an assigned texture.

object.GetTextureStageState( _
    Stage As Long, _
    State As CONST_D3DTEXTURESTAGESTATETYPE) As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Stage
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 allowable value allowed for Stage is 7.
State
Texture state to retrieve. This parameter can be any member of the CONST_D3DTEXTURESTAGESTATETYPE enumeration.

Return Values

Returns the state value.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetTextureStageState, Direct3DDevice8.GetTexture, Direct3DDevice8.SetTexture


Direct3DDevice8.GetTransform

Retrieves a matrix describing a transformation state.

object.GetTransform( _
    TransformType As CONST_D3DTRANSFORMSTATETYPE, _
    Matrix As D3DMATRIX)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
TransformType
Device state variable that is being modified. This parameter can be any member of the CONST_D3DTRANSFORMSTATETYPE enumeration.
Matrix
A D3DMATRIX type, describing the returned transformation state.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetTransform


Direct3DDevice8.GetVertexShader

Retrieves the currently set vertex shader.

object.GetVertexShader() As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

Vertex shader handle, representing the returned vertex shader.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if the Direct3DDevice object is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetVertexShader


Direct3DDevice8.GetVertexShaderConstant

Retrieves the values in the vertex constant array.

object.GetVertexShaderConstant( _
    Register As Long, _
    ConstantData As Any, _
    ConstantCount As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Register
Register address at which to start retrieving data from the vertex constant array.
ConstantData
First element of an array to hold the retrieved values from the vertex constant array.
ConstantCount
Number of constants to retrieve from the vertex constant array. Each constant is comprised of four Single values.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This is the method used to retrieve the values in the constant registers of the vertex shader assembler.

See Also

Direct3DDevice8.SetVertexShaderConstant


Direct3DDevice8.GetVertexShaderDeclaration

Retrieves the vertex shader declaration token array.

object.GetVertexShaderDeclaration( _
    Handle As Long, _
    Data As Any, _
    SizeOfData As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Handle
Handle to the referred to vertex shader.
Data
First element of an array to be filled with the declaration associated with the requested vertex shader handle, if the call succeeds.
SizeOfData
Size of the array at Data, in bytes. If this value is less than the actual size of the data (such as 0) the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA. If Data is ByVal 0, then this parameter is filled with the required size and D3D_OK is returned.

Error Codes

If Handle is an invalid handle to a vertex shader, D3DERR_INVALIDCALL is returned.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The vertex shader declaration token array defines the inputs to the shader, including how the vertex elements within the input data streams are used by the shader.

See Also

Direct3DDevice8.GetVertexShader


Direct3DDevice8.GetVertexShaderFunction

Retrieves the vertex shader function.

object.GetVertexShaderFunction( _
    Handle As Long, _
    Data As Any, _
    SizeOfData As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Handle
Handle to the referred to vertex shader.
Data
First element of an array to be filled with the code associated with the requested vertex shader handle, if the call succeeds.
SizeOfData
Size of the array at Data, in bytes. If this value is less than the actual size of the data (such as 0) the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA. If Data is ByVal 0, then this parameter is filled with the required size and D3D_OK is returned.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_MOREDATA

If Handle is an invalid handle to a vertex shader, D3DERR_INVALIDCALL is returned.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The vertex shader function defines the operation to apply to each vertex.

See Also

Direct3DDevice8.GetVertexShader


Direct3DDevice8.GetViewport

Retrieves the viewport parameters currently set for the device.

object.GetViewport( _
    Viewport As D3DVIEWPORT8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Viewport
A D3DVIEWPORT8 type, representing the returned viewport parameters.

Error Codes

An error is raised and Err.Number may be set to D3DERR_INVALIDCALL if the Viewport parameter is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.SetViewport


Direct3DDevice8.LightEnable

Enables or disables a set of lighting parameters within a device.

object.LightEnable( _
    Index As Long, _
    Enabled As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Index
Zero-based index of the set of lighting parameters that are the target of this method.
Enabled
Value that indicates if the set of lighting parameters are being enabled or disabled. Set this parameter 1 to enable lighting with the parameters at the specified index, or 0 to disable it.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If you supply a value for Index outside the range of the light property sets assigned within the device, the LightEnable method creates a light source represented by a D3DLIGHT8 type with the following properties, and it sets its enabled state to the value specified in Enabled.

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

See Also

Direct3DDevice8.GetLight, Direct3DDevice8.GetLightEnable, Direct3DDevice8.SetLight


Direct3DDevice8.MultiplyTransform

Multiplies a device's world, view, or projection matrices by a specified matrix.

object.MultiplyTransform( _
    TransformType As CONST_D3DTRANSFORMSTATETYPE, _
    Matrix As D3DMATRIX)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
TransformType
Member of the CONST_D3DTRANSFORMSTATETYPE enumeration that identifies which device matrix is to be modified. The most common setting, D3DTS_WORLD, modifies the world matrix, but you can specify that the method modify the view or projection matrices, if needed.
Matrix
A D3DMATRIX type that modifies the current transformation.

Error Codes

If the method fails, an error is raised and Err.Number will be set. The method returns D3DERR_INVALIDCALL if one of the parameters is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

An application might use the 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 of the parameters are shown in this pseudocode.)

Direct3DDevice8.SetTransform(D3DTS_WORLD,
    shoulder_transform)
Direct3DDevice8.DrawPrimitive(upper_arm)
Direct3DDevice8.MultiplyTransform(D3DTS_WORLD,
    elbow_transform)
Direct3DDevice8.DrawPrimitive(lower_arm)
Direct3DDevice8.MultiplyTransform(D3DTS_WORLD,
    wrist_transform)
Direct3DDevice8.DrawPrimitive(hand)

See Also

Direct3DDevice8.DrawPrimitive, Direct3DDevice8.SetTransform


Direct3DDevice8.Present

Presents the contents of the next in the sequence of back buffers owned by the device.

object.Present( _
    SourceRect As Any, _
    DestRect As Any, _
    DestWindowOverride As Long, _
    DirtyRegion As Any)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
SourceRect
Value that must be ByVal 0 unless the swap chain was created with D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC. SourceRect is a type containing the source rectangle. If ByVal 0, the entire source surface is presented. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
DestRect
Value that must be ByVal 0 unless the swap chain was created with D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC. DestRect is a type containing the destination rectangle, in window client coordinates. If ByVal 0, the entire client area is filled. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
DestWindowOverride
Destination window whose client area is taken as the target for this presentation. If this value is 0 (zero), then the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
DirtyRegion
This parameter is not used and should be set to ByVal 0.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_DEVICELOST

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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.

The following code fragment shows how to call the default case for Present.

Dim device As Direct3DDevice8
device.Present ByVal 0, ByVal 0, 0, ByVal 0

For the default case, note that you must specify ByVal 0 for the parameters that expect type Any. If you specify 0 (zero) for a parameter of type Any, an error will be generated and the method will fail.

See Also

Direct3DDevice8.Reset


Direct3DDevice8.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.

object.ProcessVertices( _
    SrcStartIndex As Long, _
    DestIndex As Long, _
    VertexCount As Long, _
    DestBuffer As Direct3DVertexBuffer8, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
SrcStartIndex
Index of first vertex to load.
DestIndex
Index of first vertex in the destination vertex buffer into which the results are placed.
VertexCount
Number of vertices to process.
DestBuffer
A Direct3DVertexBuffer8 object, the destination vertex buffer representing the stream of interleaved vertex data.
Flags
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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 usiong 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, it's 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, DestBuffer, must be created with a nonzero FVF parameter. The FVF code specified during the call to the Direct3DDevice8.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.

See Also

Device Types and Vertex Processing Requirements


Direct3DDevice8.Reset

Changes the type, size, and format of the swap chain.

object.Reset( _
    PresentationParameters As D3DPRESENT_PARAMETERS)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PresentationParameters
A D3DPRESENT_PARAMETERS type, describing the new presentation parameters.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If a call to Reset fails, the device will be placed in the "lost" state (as indicated by a return value of D3DERR_DEVICELOST from a call to TestCooperativeLevel) unless it is already in the "not reset" state (as indicated by a return value of D3DERR_DEVICENOTRESET from a call to TestCooperativeLevel). Refer to Direct3DDevice8.TestCooperativeLevel and Lost Devices for further information concerning the use of Reset in the context of lost devices.

Calling 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 Reset method for a device, an application should release any explicit render targets, depth stencil surfaces, additional swap chains and D3DPOOL_DEFAULT resources associated with the device.

The different types of swap chains are 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.

When Reset fails, the only valid methods you can call are Reset and Direct3DDevice8.TestCooperativeLevel. Calling any other method may result in an exception.

Pixel shaders and vertex shaders survive Reset calls for Microsoft® DirectX® 8.1. They do not need to be recreated explicitly by the application.

See Also

CONST_D3DSWAPEFFECT, D3DPRESENT_PARAMETERS, Direct3DDevice8.Present


Direct3DDevice8.ResourceManagerDiscardBytes

Invokes the resource manager to free memory.

object.ResourceManagerDiscardBytes( _
    NumberOfBytes As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
NumberOfBytes
The number of target bytes to discard. If 0 (zero), then the resource manager should discard all bytes.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The resource manager frees up memory allocations until the number of target bytes is reached. The resource manager follows a least-recently-used (LRU) priority technique.

Note that the number of bytes freed are not guaranteed to be contiguous, so you might not be able to create a resource that takes the number of bytes specified in Bytes after calling this method.


Direct3DDevice8.SetClipPlane

Sets the coefficients of a user-defined clipping plane for the device.

object.SetClipPlane( _
    Index As Long, _
    Plane As D3DPLANE)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Index
Index of the clipping plane for which the plane equation coefficients are to be set.
Plane
A D3DPLANE type containing the clipping plane coefficients to be set, in the form of the general plane equation. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The coefficients that this method sets take the form of the general plane equation. The values in the D3DPLANE type Plane—a, b, c, and d—fit into the general plane equation so that ax + by + cz + d = 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, use the D3DRS_CLIPPLANEENABLE render state constant of the CONST_D3DRENDERSTATETYPE enumeration.

See Also

Direct3DDevice8.GetClipPlane


Direct3DDevice8.SetClipStatus

Sets the clip status.

object.SetClipStatus( _
    ClipStatus As D3DCLIPSTATUS8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
ClipStatus
A D3DCLIPSTATUS8 type, describing the clip status settings to be set.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if the ClipStatus parameter is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

When clipping is enabled during vertex processing (by ProcessVertices, DrawPrimitive, or other drawing functions), Microsoft® 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 D3DClipStatus8, 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 DrawRectPatch and DrawTriPatch because there is no software emulation for them.

See Also

Direct3DDevice8.GetClipStatus


Direct3DDevice8.SetCurrentTexturePalette

Sets the current texture palette.

object.SetCurrentTexturePalette( _
    PaletteNumber As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PaletteNumber
Value that specifies the texture palette to set as the current texture palette.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

A single logical palette is associated with the device and is shared by all texture stages.

See Also

Direct3DDevice8.GetCurrentTexturePalette, Texture Palettes


Direct3DDevice8.SetCursorPosition

Sets the cursor position and update options.

object.SetCursorPosition( _
    XScreenSpace As Long, _
    YScreenSpace As Long
    Flags As CONST_D3DSCPFLAGS)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
XScreenSpace
The new X-position of the cursor in screen-space coordinates. See Remarks.
YScreenSpace
The new Y-position of the cursor in screen-space coordinates. See Remarks.
Flags
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 Direct3DDevice8.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 doesn't have an effect on these cards either.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 Direct3DDevice8.SetCursorProperties method.

If the cursor has been hidden by Direct3DDevice8.ShowCursor, then the cursor is not drawn.

See Also

Direct3DDevice8.SetCursorProperties, Direct3DDevice8.ShowCursor


Direct3DDevice8.SetCursorProperties

Sets properties for the cursor.

object.SetCursorProperties( _
    XHotSpot As Long, _
    YHotSpot As Long, _
    CursorSurface As Direct3DSurface8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
XHotSpot
X-coordinate offset into the cursor, in pixels from the top-left corner, that is considered the center. 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
Y-coordinate offset into the cursor, in pixels from the top-left corner, that is considered the center. 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.
CursorSurface
A Direct3DSurface8 object. This parameter must point to an 8888 ARGB surface (format D3DFORMAT_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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method is independent of the Microsoft® Win32® API ShowCursor and SetCursor functions. Applications should either use the Win32 cursor or the Microsoft Direct3D® cursor, not both.

The application can determine what hardware support is available for cursors by examining appropriate members of the D3DCAPS8 type. Typically, hardware supports only 32x32 cursors. Additionally, when windowed, the system might support only 32x32 cursors. In this case, SetCursorProperties still succeeds, but the cursor may be reduced to that size—the hot spot is scaled appropriately.

See Also

Direct3DDevice8.SetCursorPosition, Direct3DDevice8.ShowCursor , D3DCAPS8


Direct3DDevice8.SetGammaRamp

Sets the gamma correction ramp for the implicit swap chain.

object.SetGammaRamp( _
    Flags As Long, _
    Ramp As D3DGAMMARAMP)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Flags
Indicates whether correction should be applied. Gamma correction results in a more consistent display, but it 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 values defined by the CONST_D3DSGRFLAGS enumeration can be set.
Ramp
A D3DGAMMARAMP type, representing the gamma correction ramp to be set for the implicit swap chain.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

There is always at least one swap chain (the implicit swap chain) for each device because Microsoft® Direct3D® has one swap chain as a property of the device.

Because the gamma ramp is a property of the swap chain, the gamma ramp may be applied when the swap chain is windowed.

The gamma ramp takes effect immediately. No wait for VSYNC is performed.

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 D3DCAPS8 type to determine the capabilities of the device and whether a calibrator is installed.

See Also

Direct3D8.CreateDevice, Direct3DDevice8.GetGammaRamp


Direct3DDevice8.SetIndices

Sets index data.

object.SetIndices( _
    IndexData As Direct3DIndexBuffer8, _
    BaseVertexIndex As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
IndexData
A Direct3DIndexBuffer8 object, representing the index data to be set.
BaseVertexIndex
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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The SetIndices method sets the current index array to an index buffer. The single set of indices is used to index all streams.

The BaseVertexIndex parameter specifies the base value for indices. This base value is added to all indices prior to referencing into the vertex data streams, which results in setting a starting position in the vertex data streams. The base vertex index enables multiple indexed primitives to be packed into a single set of vertex data without requiring the indices to be recomputed based on where the corresponding primitive is placed in the vertex data.

See Also

Direct3DDevice8.GetIndices


Direct3DDevice8.SetLight

Assigns a set of lighting properties for this device.

object.SetLight( _
    Index As Long, _
    Light As D3DLIGHT8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Index
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 Light.
Light
A D3DLIGHT8 type, containing the lighting-parameters to set.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.GetLight, Direct3DDevice8.GetLightEnable, Direct3DDevice8.LightEnable


Direct3DDevice8.SetMaterial

Sets the material properties for the device.

object.SetMaterial( _
    Material As D3DMATERIAL8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Material
A D3DMATERIAL8 type, describing the material properties to set.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.GetMaterial


Direct3DDevice8.SetPaletteEntries

Sets palette entries.

object.SetPaletteEntries( _
    PaletteNumber As Long, _
    ArrayOfEntries As Any)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PaletteNumber
An ordinal value identifying the particular palette upon which the operation is to be performed.
ArrayOfEntries
First element of an array of PALETTEENTRY types, containing the palette entries to set. The number of PALETTEENTRY types in this array is assumed to be 256.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

For Microsoft® DirectX® 8.1 applications, any palette sent to this method must conform to the D3DPTEXTURECAPS_ALPHAPALETTE capability bit. 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 D3DPTEXTUECAPS_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.

The following code fragment shows how to call SetPaletteEntries.

Dim device As Direct3DDevice8
Dim pal(255) As PALETTEENTRY

'Pass the first element of the array of palette entries
device.SetPaletteEntries 255, pal(0)

Ensure that PaletteNumber matches the size of the passed array of palette entries.

See Also

Direct3DDevice8.GetCurrentTexturePalette, Direct3DDevice8.GetPaletteEntries, Direct3DDevice8.SetCurrentTexturePalette, Texture Palettes


Direct3DDevice8.SetPixelShader

Sets the current pixel shader to a previously created pixel shader.

object.SetPixelShader( _
    PixelShaderHandle As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
PixelShaderHandle
Handle to the pixel shader, specifying the pixel shader to set. The value for this parameter can be the handle returned by Direct3DDevice8.CreatePixelShader.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.GetPixelShader


Direct3DDevice8.SetPixelShaderConstant

Sets the values in the pixel constant array.

object.SetPixelShaderConstant( _
    Register As Long, _
    ConstantData As Any, _
    ConstantCount As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Register
Register address at which to start loading data into the pixel constant array.
ConstantData
First element of an array holding the values to load into the pixel constant array.
ConstantCount
Number of constants to load into the pixel constant array. Each constant is comprised of four Single values.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This is the method used to load the constant registers of the pixel shader assembler.

See Also

Direct3DDevice8.GetPixelShaderConstant


Direct3DDevice8.SetRenderState

Sets a single device render-state parameter.

object.SetRenderState( _
    State As CONST_D3DRENDERSTATETYPE, _
    Value As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
State
Device state variable that is being modified. This parameter can be any member of the CONST_D3DRENDERSTATETYPE enumeration.
Value
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 CONST_D3DSHADEMODE enumeration.

Error Codes

If the method fails, it sets Err.Number to an error code and raises an error. The error code is D3DERR_INVALIDCALL if one of the parameters is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.GetRenderState, Direct3DDevice8.SetTransform


Direct3DDevice8.SetRenderTarget

Sets a new color buffer, depth buffer, or both for the device.

object.SetRenderTarget( _
    NewRenderTarget As Direct3DSurface8, _
    NewDepthStencil As Direct3DSurface8, _
    Reserved )

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
NewRenderTarget
New color buffer. If Nothing, the existing color buffer is retained. If this parameter is not Nothing, the reference count on the new render target is incremented. Devices always have to be associated with a color buffer.

The new render target surface must have at least D3DUSAGE_RENDERTARGET specified.

NewDepthStencil
New depth-stencil buffer. If a depth-stencil buffer exists, it is released. If this parameter is not Nothing, the reference count on the new depth-stencil buffer surface is incremented. Applications can change the render target without changing the depth buffer by passing in the Direct3DSurface8 object returned by Direct3DDevice8.GetDepthStencilSurface.

The new depth-stencil surface must have at least D3DUSAGE_DEPTHSTENCIL and D3DPOOL_DEFAULT specified.

Reserved
Reserved. Must be set to 0.

Error Codes

If the method fails, an error is raised and Err.Number may be set to D3DERR_INVALIDCALL if NewRenderTarget or NewDepthStencil are not Nothing and invalid, or if the new depth buffer is smaller than the new or retained color buffer.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Once a color buffer and a depth-stencil surface have been associated with the same device by this method, they are said to be paired.

The previous depth-stencil surface's contents persist after a call to SetRenderTarget to disassociate the previous depth-stencil surface from the device. If the surface is re-associated with the device, then the contents of the surface will be unchanged, providing the color buffer to which the new depth-stencil surface is being paired is the same size and format as the color buffer to which the depth-stencil surface was most recently paired.

See Also

Direct3DDevice8.CreateDepthStencilSurface, Direct3DDevice8.GetDepthStencilSurface


Direct3DDevice8.SetStreamSource

Binds a vertex buffer to a device data stream.

object.SetStreamSource( _
    StreamNumber As Long, _
    StreamData As Direct3DVertexBuffer8, _
    Stride As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
StreamNumber
Specifies the data stream, in the range from 0 to the maximum number of streams - 1.
StreamData
A Direct3DVertexBuffer8 object, representing the vertex buffer to bind to the specified data stream.
Stride
Stride of the component, in bytes. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

When a flexible vertex format (FVF) vertex shader is used, the stream vertex stride in SetStreamSource must match the vertex size, computed from the FVF. When a declaration is used, the stream vertex stride in SetStreamSource should be greater than or equal to the stream size, computed from the declaration.

The SetStreamSource method binds a vertex buffer to a device data stream. For details, see Setting the Stream Source.

See Also

Direct3DDevice8.DrawIndexedPrimitive, Direct3DDevice8.DrawIndexedPrimitiveUP, Direct3DDevice8.DrawPrimitive, Direct3DDevice8.DrawPrimitiveUP, Direct3DDevice8.GetStreamSource


Direct3DDevice8.SetTexture

Assigns a texture to a stage for a device.

object.SetTexture( _
    Stage As Long, _
    Texture As Direct3DBaseTexture8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Stage
Stage identifier to which the texture is set. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum allowable value allowed for Stage is 7.
Texture
A Direct3DBaseTexture8 object, representing the texture being set. For complex textures, such as mipmaps and cube textures, this parameter must be the top-level surface.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method increments the reference count of the texture surface being assigned, and it decrements the reference count of the previously selected texture if there is one. When the texture is no longer needed, set the texture at the appropriate stage to Nothing. Failure to do this results in a memory leak.

See Also

Direct3DDevice8.GetTexture, Direct3DDevice8.GetTextureStageState, Direct3DDevice8.SetTextureStageState


Direct3DDevice8.SetTextureStageState

Sets the state value for the currently assigned texture.

object.SetTextureStageState( _
    Stage As Long, _
    Type As CONST_D3DTEXTURESTAGESTATETYPE, _
    Value As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Stage
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 allowable value allowed for Stage is 7.
Type
Texture state to set. This parameter can be any member of the CONST_D3DTEXTURESTAGESTATETYPE enumeration.
Value
State value to set. The meaning of this value is determined by the Type parameter.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.GetTextureStageState, Direct3DDevice8.GetTexture, Direct3DDevice8.SetTexture


Direct3DDevice8.SetTransform

Sets a single device transformation-related state.

object.SetTransform( _
    TransformType As CONST_D3DTRANSFORMSTATETYPE, _
    Matrix As D3DMATRIX)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
TransformType
Device-state variable that is being modified. This parameter can be any member of the CONST_D3DTRANSFORMSTATETYPE enumeration.
Matrix
A D3DMATRIX type that modifies the current transformation.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if one of the parameters is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DDevice8.GetTransform, Direct3DDevice8.SetRenderState


Direct3DDevice8.SetVertexShader

Sets the current vertex shader to a previously created vertex shader or to a flexible vertex format (FVF) fixed function shader.

object.SetVertexShader( _
    VertexShaderHandle As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
VertexShaderHandle
Handle to a vertex shader, specifying the vertex shader to set. The value for this parameter can be the handle returned by Direct3DDevice8.CreateVertexShader, or an FVF code. An FVF code is a combination of flexible vertex format flags.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The effect of using an FVF code in place of the handle is to enable a fixed-function vertex shader, with an implicit declaration that matches the FVF code contents read from stream zero. Only stream zero is referenced when an FVF-specified shader is bound to the device.

See Also

Direct3DDevice8.GetVertexShader


Direct3DDevice8.SetVertexShaderConstant

Sets values in the vertex constant array.

object.SetVertexShaderConstant( _
    Register As Long, _
    ConstantData As Any, _
    ConstantCount As Long)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Register
Register address at which to start loading data into the vertex constant array.
ConstantData
First element of an array holding the values to load into the vertex constant array.
ConstantCount
Number of constants to load into the vertex constant array. Each constant is comprised of four Single values.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This is the method used to load the constant registers of the vertex shader assembler. When loading transformation matrices, the application should transpose them row/column and load them into consecutive constant registers.

See Also

Direct3DDevice8.SetVertexShaderConstant


Direct3DDevice8.SetViewport

Sets the viewport parameters for the device.

object.SetViewport( _
    Viewport As D3DVIEWPORT8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
Viewport
A D3DVIEWPORT8 type, specifying the viewport parameters to set.

Error Codes

If the method fails, an error is raised and Err.Number may be set to D3DERR_INVALIDCALL to indicate that the Viewport parameter is invalid.

If the viewport parameters described by the D3DVIEWPORT8 type describe a region that cannot exist within the render target surface, the method fails, returning D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Any call to SetViewPort between a pair of calls to Direct3DDevice8.BeginScene and Direct3DDevice8.EndScene must be made before any geometry is drawn.

See Also

Direct3DDevice8.GetViewport


Direct3DDevice8.ShowCursor

Displays or hides the cursor.

object.ShowCursor( _
    bShow As Long) As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
bShow
If bShow is a nonzero value, the cursor is shown. If bShow is zero, the cursor is hidden.

Return Values

Value indicating whether the cursor was previously visible. This value is nonzero if the cursor was previously visible, or zero if the cursor was not previously visible.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method is independent of the Microsoft® Win32® API ShowCursor and SetCursor functions. Applications should either use the Win32 cursor or the Microsoft Direct3D® cursor, not both.

See Also

Direct3DDevice8.SetCursorPosition, Direct3DDevice8.SetCursorProperties


Direct3DDevice8.TestCooperativeLevel

Reports the current cooperative-level status of the Microsoft® Direct3D® device for a windowed or full-screen application.

object.TestCooperativeLevel() As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

If the method succeeds, it returns D3D_OK, indicating that the device is operational and the calling application can continue executing.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values (see Remarks).

D3DERR_DEVICELOST
D3DERR_DEVICENOTRESET

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If the device is lost but cannot be restored at the current time, this method 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 TestCooperativeLevel until it receives a return value of D3DERR_DEVICENOTRESET. The application may then attempt to reset the device by calling Direct3DDevice8.Reset and, if this succeeds, restore the necessary resources and resume normal operation. Note that Direct3DDevice8.Present will return D3DERR_DEVICELOST if the device is either "lost" or "not reset".


Direct3DDevice8.UpdateTexture

Updates the dirty portions of a texture.

object.UpdateTexture( _
    SourceTexture As Direct3DBaseTexture8, _
    DestinationTexture As Direct3DBaseTexture8)

Parts

object
Object expression that resolves to a Direct3DDevice8 object.
SourceTexture
A Direct3DBaseTexture8 object, representing the source texture. The source texture must be in system memory (D3DPOOL_SYSTEMMEM).
DestinationTexture
A Direct3DBaseTexture8 object, representing the destination texture. The destination texture must be in the D3DPOOL_DEFAULT memory pool.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

You can dirty a portion of a texture by locking it, or by calling one of the following methods.

  • Direct3DCubeTexture8.AddDirtyRect
  • Direct3DTexture8.AddDirtyRect
  • Direct3DVolumeTexture8.AddDirtyBox
  • Direct3DDevice8.CopyRects

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 LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of a CopyRects call is marked dirty.

This method fails if the textures are of different types, if their bottom-level buffers are of different sizes, and also if their matching levels do not match. For example, consider a six-level source texture with the following dimensions.

32×16, 16×8, 8×4, 4×2, 2×1, 1×1

This six-level source texture could be the source for the following one-level destination.

1×1

For the following two-level destination.

2×1, 1×1

Or, for the following three-level destination.

4×2, 2×1, 1×1

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 dirty regions, the copy may be optimized by restricting the copy to only those regions. It is not guaranteed that only those bytes marked dirty will be copied.


Direct3DDevice8.ValidateDevice

Reports the device's ability to render the current texture-blending operations and arguments in a single pass.

object.ValidateDevice() As Long

Parts

object
Object expression that resolves to a Direct3DDevice8 object.

Return Values

If the method succeeds, the return value is the number of rendering passes to complete the desired effect through multipass rendering.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_CONFLICTINGTEXTUREFILTER
D3DERR_CONFLICTINGTEXTUREPALETTE
D3DERR_DEVICELOST
D3DERR_TOOMANYOPERATIONS
D3DERR_UNSUPPORTEDALPHAARG
D3DERR_UNSUPPORTEDALPHAOPERATION
D3DERR_UNSUPPORTEDCOLORARG
D3DERR_UNSUPPORTEDCOLOROPERATION
D3DERR_UNSUPPORTEDFACTORVALUE
D3DERR_UNSUPPORTEDTEXTUREFILTER
D3DERR_WRONGTEXTUREFORMAT

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The ValidateDevice method should be used only to validate scenarios when other capabilities are deficient. For example, in a multistage texturing scenario, you could query the MaxTextureBlendStages and MaxSimultaneousTextures members of a D3DCAPS8 type 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 ValidateDevice method.

The 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.

Using diffuse iterated values, either as an argument or as an operation (D3DTA_DIFFUSE or D3DTOP_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.

See Also

Direct3DDevice8.GetTextureStageState, Direct3DDevice8.SetTextureStageState


Direct3DIndexBuffer8

Applications use the methods of the Direct3DIndexBuffer8 class to manipulate an index buffer resource.

The Direct3DIndexBuffer8 class is obtained by calling the Direct3DDevice8.CreateIndexBuffer method. The methods of the Direct3DIndexBuffer8 class can be organized into the following groups.

Information | GetDesc
Locking | Lock
 | Unlock

See Also

Direct3DDevice8.CreateIndexBuffer


Direct3DIndexBuffer8.GetDesc

Retrieves a description of the index buffer resource.

object.GetDesc( _
    Desc As D3DINDEXBUFFER_DESC)

Parts

object
Object expression that resolves to a Direct3DIndexBuffer8 object.
Desc
A D3DINDEXBUFFER_DESC type, describing the returned index buffer.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if the parameter is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DIndexBuffer8.Lock

Locks a range of index data and obtains access to the index buffer memory.

object.Lock( _
    OffsetToLock As Long, _
    SizeToLock As Long, _
    Data As Long, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DIndexBuffer8 object.
OffsetToLock
Offset into the index data to lock, in bytes. Lock the entire index buffer by specifying 0 for both parameters, SizeToLock and OffsetToLock.
SizeToLock
Size of the index data to lock, in bytes. Lock the entire index buffer by specifying 0 for both parameters, SizeToLock and OffsetToLock.
Data
First element of an array of Long values, filled with the returned index data
Flags
Combination of zero or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing how the index buffer memory should be locked.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

To lock, read, and unlock index data with a single function call, use D3DIndexBuffer8GetData.

To lock, fill, and unlock index data with a single function call, use D3DIndexBuffer8SetData.

When working with index buffers, you can 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.

See Using Dynamic Vertex and Index Buffers for information on using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

See Also

Direct3DIndexBuffer8.Unlock, D3DIndexBuffer8GetData, D3DIndexBuffer8SetData


Direct3DIndexBuffer8.Unlock

Unlocks index data.

object.Unlock()

Parts

object
Object expression that resolves to a Direct3DIndexBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

To lock, read, and unlock index data with a single function call, use D3DIndexBuffer8GetData.

To lock fill, and unlock index data with a single function call, use D3DIndexBuffer8SetData.

See Also

Direct3DIndexBuffer8.Lock, D3DIndexBuffer8GetData, D3DIndexBuffer8SetData


Direct3DResource8

Applications use the methods of the Direct3DResource8 class to query and prepare resources.

To create a texture resource, you can call one of the following methods.

  • Direct3DDevice8.CreateCubeTexture
  • Direct3DDevice8.CreateTexture
  • Direct3DDevice8.CreateVolumeTexture

To create a geometry-oriented resource, you can call one of the following methods.

  • Direct3DDevice8.CreateIndexBuffer
  • Direct3DDevice8.CreateVertexBuffer

The methods of the Direct3DResource8 class can be organized into the following groups.

Devices | GetDevice
Information | GetType
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData
Resource Management | GetPriority
 | PreLoad
 | SetPriority


Direct3DResource8.FreePrivateData

Frees the specified private data associated with this resource.

object.FreePrivateData( _
    RefGuid As DXGUID)

Parts

object
Object expression that resolves to a Direct3DResource8 object.
RefGuid
A DXGUID type, the globally unique identifier that identifies the private data to free.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DResource8.

  • Direct3DBaseTexture8
  • Direct3DCubeTexture8
  • Direct3DIndexBuffer8
  • Direct3DTexture8
  • Direct3DVertexBuffer8
  • Direct3DVolumeTexture8

See Also

Direct3DResource8.GetPrivateData, Direct3DResource8.SetPrivateData


Direct3DResource8.GetDevice

Retrieves the device associated with a resource.

object.GetDevice( _
    Riid As GUID) As Direct3DDevice8

Parts

object
Object expression that resolves to a Direct3DResource8 object.
Riid
A GUID type, the reference identifier of the device being requested.

Return Values

An Unknown object to fill with the device object, if the query succeeds.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DResource8.

  • Direct3DBaseTexture8
  • Direct3DCubeTexture8
  • Direct3DIndexBuffer8
  • Direct3DTexture8
  • Direct3DVertexBuffer8
  • Direct3DVolumeTexture8


Direct3DResource8.GetPriority

Retrieves the priority for this resource.

object.GetPriority() As Long

Parts

object
Object expression that resolves to a Direct3DResource8 object.

Return Values

Returns a Long value, indicating the priority of the resource.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DResource8.

  • Direct3DBaseTexture8
  • Direct3DCubeTexture8
  • Direct3DIndexBuffer8
  • Direct3DTexture8
  • Direct3DVertexBuffer8
  • Direct3DVolumeTexture8

Remarks

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.

See Also

Direct3DResource8.SetPriority


Direct3DResource8.GetPrivateData

Copies the private data associated with the resource to a provided buffer.

object.GetPrivateData( _
    RefGuid As DXGUID, _
    Data As Any, _
    SizeOfData As Long)

Parts

object
Object expression that resolves to a Direct3DResource8 object.
RefGuid
A DXGUID type, the globally unique identifier that identifies the private data to retrieve.
Data
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.
SizeOfData
Size of the buffer at Data, 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_MOREDATA
D3DERR_NOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DResource8.

  • Direct3DBaseTexture8
  • Direct3DCubeTexture8
  • Direct3DIndexBuffer8
  • Direct3DTexture8
  • Direct3DVertexBuffer8
  • Direct3DVolumeTexture8

See Also

Direct3DResource8.FreePrivateData, Direct3DResource8.SetPrivateData


Direct3DResource8.GetType

Returns the type of the resource.

object.GetType() As CONST_D3DRESOURCETYPE

Parts

object
Object expression that resolves to a Direct3DResource8 object.

Return Values

Returns a member of the CONST_D3DRESOURCETYPE enumeration, identifying the type of the resource.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DResource8.

  • Direct3DBaseTexture8
  • Direct3DCubeTexture8
  • Direct3DIndexBuffer8
  • Direct3DTexture8
  • Direct3DVertexBuffer8
  • Direct3DVolumeTexture8


Direct3DResource8.PreLoad

Preloads a managed resource.

object.PreLoad()

Parts

object
Object expression that resolves to a Direct3DResource8 object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DResource8.

  • Direct3DBaseTexture8
  • Direct3DCubeTexture8
  • Direct3DIndexBuffer8
  • Direct3DTexture8
  • Direct3DVertexBuffer8
  • Direct3DVolumeTexture8

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances Preload silently does nothing.


Direct3DResource8.SetPriority

Assigns the resource-management priority for this resource.

object.SetPriority( _
    PriorityNew As Long) As Long

Parts

object
Object expression that resolves to a Direct3DResource8 object.
PriorityNew
Long value that specifies the new resource-management priority for the resource.

Return Values

Returns the previous priority value for the resource.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DResource8.

  • Direct3DBaseTexture8
  • Direct3DCubeTexture8
  • Direct3DIndexBuffer8
  • Direct3DTexture8
  • Direct3DVertexBuffer8
  • Direct3DVolumeTexture8

Remarks

SetPriority 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.

See Also

Direct3DResource8.GetPriority


Direct3DResource8.SetPrivateData

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

object.SetPrivateData( _
    RefGuid As DXGUID, _
    Data As Any, _
    SizeOfData As Long, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DResource8 object.
RefGuid
A DXGUID type, the globally unique identifier that identifies the private data to set.
Data
A buffer that contains the data to be associated with the resource.
SizeOfData
Size of the buffer at Data, in bytes.
Flags
Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes. This parameter can be the value defined by the CONST_D3DSPDFLAGS enumeration, or 0. 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from Direct3DResource8.

  • Direct3DBaseTexture8
  • Direct3DCubeTexture8
  • Direct3DIndexBuffer8
  • Direct3DTexture8
  • Direct3DVertexBuffer8
  • Direct3DVolumeTexture8

Remarks

Direct3D does not manage the memory at Data. If this buffer was dynamically allocated, it is the caller's responsibility to free the memory.

See Also

Direct3DResource8.FreePrivateData, Direct3DResource8.GetPrivateData


Direct3DSurface8

Applications use the methods of the Direct3DSurface8 class to query and prepare surfaces.

The methods of the Direct3DSurface8 class can be organized into the following groups.

Devices | GetDevice
Information | GetContainer
 | GetDesc
Locking Surfaces | LockRect
 | UnlockRect
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData

See Also

Surfaces


Direct3DSurface8.FreePrivateData

Frees the specified private data associated with this surface.

object.FreePrivateData( _
    RefGuid As DXGUID)

Parts

object
Object expression that resolves to a Direct3DSurface8 object.
RefGuid
A DXGUID type, the globally unique identifier that identifies the private data to free.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DSurface8.GetPrivateData, Direct3DSurface8.SetPrivateData


Direct3DSurface8.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.

object.GetContainer( _
    Riid  As GUID) As Unknown

Parts

object
Object expression that resolves to a Direct3DSurface8 object.
Riid
Reference identifier of the container being requested.

Return Values

An Unknown object to fill with the container object, if the query succeeds. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If the surface is created using Direct3DDevice8.CreateImageSurface, Direct3DDevice8.CreateRenderTarget, or Direct3DDevice8.CreateDepthStencilSurface, the surface is considered stand alone. In this case, GetContainer will return the Direct3D device used to create the surface.


Direct3DSurface8.GetDesc

Retrieves a description of the surface.

object.GetDesc( _
    Desc As D3DSURFACE_DESC)

Parts

object
Object expression that resolves to a Direct3DSurface8 object.
Desc
A D3DSURFACE_DESC type, describing the surface.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DSurface8.GetDevice

Retrieves the device associated with a surface.

object.GetDevice() As Direct3DDevice8

Parts

object
Object expression that resolves to a Direct3DSurface8 object.

Return Values

The Direct3DDevice8 associated with the surface, if the query succeeds.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method enables navigation to the owning device object.


Direct3DSurface8.GetPrivateData

Copies the private data associated with the surface to a provided buffer.

object.GetPrivateData( _
    RefGuid As DXGUID, _
    Data As Any, _
    SizeOfData As Long)

Parts

object
Object expression that resolves to a Direct3DSurface8 object.
RefGuid
A DXGUID type, the globally unique identifier that identifies the private data to retrieve.
Data
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.
SizeOfData
Size of the buffer at Data, 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_MOREDATA
D3DERR_NOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DSurface8.FreePrivateData, Direct3DSurface8.SetPrivateData


Direct3DSurface8.LockRect

Locks a rectangle on a surface.

object.LockRect( _
    LockedRect As D3DLOCKED_RECT, _
    RECT As Any, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DSurface8 object.
LockedRect
A D3DLOCKED_RECT type, describing the locked region.
RECT
Rectangle to lock. Specified by a RECT type, or ByVal 0 to expand the dirty region to cover the entire surface.
Flags
A combination of zero or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

A multisample backbuffer cannot be locked.

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See Direct3DDevice8.UpdateTexture for more information.

See Also

Direct3DSurface8.UnlockRect


Direct3DSurface8.SetPrivateData

Associates data with the surface that is intended for use by the application, not by Microsoft® Direct3D®.

object.SetPrivateData( _
    RefGuid As DXGUID, _
    Data As Any, _
    SizeOfData As Long, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DSurface8 object.
RefGuid
A DXGUID type, the globally unique identifier that identifies the private data to set.
Data
A buffer that contains the data to associate with the surface.
SizeOfData
Size of the buffer at Data, in bytes.
Flags
Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes. This parameter can be the value defined by the CONST_D3DSPDFLAGS enumeration, or 0. 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Direct3D does not manage the memory at Data. If this buffer was dynamically allocated, it is the caller's responsibility to free the memory.

Data is passed by value, and multiple sets of data can be associated with a single surface.

See Also

Direct3DSurface8.FreePrivateData, Direct3DSurface8.GetPrivateData


Direct3DSurface8.UnlockRect

Unlocks a rectangle on a surface.

object.UnlockRect()

Parts

object
Object expression that resolves to a Direct3DSurface8 object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DSurface8.LockRect


Direct3DSwapChain8

Applications use the methods of the Direct3DSwapChain8 class to manipulate a swap chain.

There is always at least one swap chain, known as the implicit swap chain, for each device. However, an additional swap chain for rendering multiple views from the same device can be created by calling the Direct3DDevice8.CreateAdditionalSwapChain method.

The methods of the Direct3DSwapChain8 class can be organized into the following groups.

Presentation | Present
Surface Management | GetBackBuffer

See Also

Direct3DDevice8.CreateAdditionalSwapChain


Direct3DSwapChain8.GetBackBuffer

Retrieves a back buffers from the swap chain of the device.

object.GetBackBuffer( _
    BackBuffer As Long, _
    BufferType As CONST_D3DBACKBUFFERTYPE) As Direct3DSurface8

Parts

object
Object expression that resolves to a Direct3DSwapChain8 object.
BackBuffer
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.
BufferType
Stereo view is not supported in DirectX 8.0, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.

Return Values

A Direct3DSurface8 object, representing the returned back buffer surface.

Error Codes

If BackBuffer exceeds or equals the total number of back buffers, an error is raised and Err.Number may be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DSwapChain8.Present

Presents the contents of the next in the sequence of back buffers owned by the swap chain.

object.Present( _
    SourceRect As Any, _
    DestRect As Any, _
    DestWindowOverride As Long, _
    DirtyRegion As Any)

Parts

object
Object expression that resolves to a Direct3DSwapChain8 object.
SourceRect
Value that must be ByVal 0 unless the swap chain was created with D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC. SourceRect is a type containing the source rectangle. If ByVal 0, the entire source surface is presented. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
DestRect
Value that must be ByVal 0 unless the swap chain was created with D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC. DestRect is a type containing the destination rectangle, in window client coordinates. If ByVal 0, the entire client area is filled. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
DestWindowOverride
Destination window whose client area is taken as the target for this presentation.
DirtyRegion
This parameter is not used and should be set to ByVal 0.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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.

The following code fragment shows how to call the default case for Present.

Dim swapChain As Direct3DSwapChain8
swapChain.Present ByVal 0, ByVal 0, 0, ByVal 0

For the default case, note that you must specify ByVal 0 for the parameters that expect type Any. If you specify 0 (zero) for a parameter of type Any, an error will be generated and the method will fail.

See Also

Direct3DDevice8.Reset


Direct3DTexture8

Applications use the methods of the Direct3DTexture8 class to manipulate a texture resource.

The Direct3DTexture8 class is obtained by calling the Direct3DDevice8.CreateTexture method. The methods of the Direct3DTexture8 class can be organized into the following groups.

Information | GetLevelDesc
Locking Surfaces | LockRect
 | UnlockRect
Miscellaneous | AddDirtyRect
 | GetSurfaceLevel

This class inherits additional functionality from the Direct3DTexture8 class.

See Also

Direct3DDevice8.CreateTexture


Direct3DTexture8.AddDirtyRect

Adds a dirty region to a texture resource.

object.AddDirtyRect( _
    DirtyRect As Any)

Parts

object
Object expression that resolves to a Direct3DTexture8 object.
DirtyRect
A RECT type, specifying the dirty region to add. Specifying ByVal 0 expands the dirty region to cover the entire texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 LockRect or LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of a CopyRects call is marked dirty.

Applications can optimize what subset of a resource is copied by specifying dirty regions on the resource.


Direct3DTexture8.GetLevelDesc

Retrieves a level description of a texture resource.

object.GetLevelDesc( _
    Level As Long, _
    Desc As D3DSURFACE_DESC)

Parts

object
Object expression that resolves to a Direct3DTexture8 object.
Level
Identifies a level of the texture resource. This method returns a surface description for the level specified by this parameter.
Desc
A D3DSURFACE_DESC type, describing the returned mipmap.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if one or more of the parameters are invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DTexture8.GetSurfaceLevel

Retrieves the specified texture surface level.

object.GetSurfaceLevel( _
    Level As Long) As Direct3DSurface8

Parts

object
Object expression that resolves to a Direct3DTexture8 object.
Level
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.

Return Values

A Direct3DSurface8 object, representing the returned surface.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DTexture8.LockRect

Locks a rectangle on a texture resource.

object.LockRect( _
    Level As Long, _
    LockedRect As D3DLOCKED_RECT, _
    RECT As Any, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DTexture8 object.
Level
Specifies the level of the texture resource to lock.
LockedRect
A D3DLOCKED_RECT type, describing the locked region.
RECT
Rectangle to lock. Specified by a RECT type, or ByVal 0 to expand the dirty region to cover the entire texture.
Flags
A combination of zero or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Textures created in D3DPOOL_DEFAULT are not-lockable.

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See Direct3DDevice8.UpdateTexture for more information.

The only lockable format for a depth-stencil surface is D3DFMT_D16_LOCKABLE.

A multisample backbuffer cannot be locked. Video memory textures cannot be locked, but they must be modified by calling Direct3DDevice8.CopyRects or Direct3DDevice8.UpdateTexture. There are exceptions for some proprietary driver pixel formats that Microsoft® DirectX® 8.x does not recognize. These can be locked.

See Also

Direct3DTexture8.UnlockRect


Direct3DTexture8.UnlockRect

Unlocks a rectangle on a texture resource.

object.UnlockRect( _
    Level As Long)

Parts

object
Object expression that resolves to a Direct3DTexture8 object.
Level
Specifies the level of the texture resource to unlock.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DTexture8.LockRect


Direct3DVertexBuffer8

Applications use the methods of the Direct3DVertexBuffer8 class to manipulate an index buffer resource.

The Direct3DVertexBuffer8 class is obtained by calling the Direct3DDevice8.CreateVertexBuffer method. The methods of the Direct3DVertexBuffer8 class can be organized into the following groups.

Information | GetDesc
Locking | Lock
 | Unlock

See Also

Direct3DDevice8.CreateVertexBuffer


Direct3DVertexBuffer8.GetDesc

Retrieves a description of the vertex buffer resource.

object.GetDesc( _
    Desc As D3DVERTEXBUFFER_DESC)

Parts

object
Object expression that resolves to a Direct3DVertexBuffer8 object.
Desc
A D3DVERTEXBUFFER_DESC type, describing the returned vertex buffer.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if the parameter is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DVertexBuffer8.Lock

Locks a range of vertex data and obtains access to the vertex buffer memory.

object.Lock( _
    OffsetToLock As Long, _
    SizeToLock As Long, _
    Data As Long, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DVertexBuffer8 object.
OffsetToLock
Offset into the vertex data to lock, in bytes. To lock the entire vertex buffer, specify 0 for both parameters, SizeToLock and OffsetToLock.
SizeToLock
Size of the vertex data to lock, in bytes. To lock the entire vertex buffer, specify 0 for both parameters, SizeToLock and OffsetToLock.
Data
First element of an array of Long values, filled with the returned vertex data.
Flags
Combination of zero or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing how the vertex buffer memory should be locked.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

To lock, read, and unlock vertex data with a single function call, use D3DVertexBuffer8GetData.

To lock fill, and unlock vertex data with a single function call, use D3DVertexBuffer8SetData.

When working with vertex buffers, you can 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.

See Using Dynamic Vertex and Index Buffers for information on using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

See Also

Direct3DVertexBuffer8.Unlock, D3DVertexBuffer8GetData, D3DVertexBuffer8SetData


Direct3DVertexBuffer8.Unlock

Unlocks vertex data.

object.Unlock()

Parts

object
Object expression that resolves to a Direct3DVertexBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

To lock, read, and unlock vertex data with a single function call, use D3DVertexBuffer8GetData.

To lock fill, and unlock vertex data with a single function call, use D3DVertexBuffer8SetData.

See Also

Direct3DVertexBuffer8.Lock, D3DVertexBuffer8GetData, D3DVertexBuffer8SetData


Direct3DVolume8

Applications use the methods of the Direct3DVolume8 class to manipulate volume resources.

The Direct3DVolume8 class is obtained by calling the Direct3DVolumeTexture8.GetVolumeLevel method. The methods of the Direct3DVolume8 class can be organized into the following groups.

Devices | GetDevice
Information | GetContainer
 | GetDesc
Locking Volumes | LockBox
 | UnlockBox
Private Volume Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData


Direct3DVolume8.FreePrivateData

Frees the specified private data associated with this volume.

object.FreePrivateData( _
    RefGuid As DXGUID)

Parts

object
Object expression that resolves to a Direct3DVolume8 object.
RefGuid
A DXGUID type, the globally unique identifier that identifies the private data to free.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DVolume8.GetPrivateData, Direct3DVolume8.SetPrivateData


Direct3DVolume8.GetContainer

Provides access to the parent volume texture object, if this surface is a child level of a volume texture.

object.GetContainer( _
    Riid  As GUID) As Unknown

Parts

object
Object expression that resolves to a Direct3DVolume8 object.
Riid
Reference identifier of the volume being requested.

Return Values

An Unknown object to fill with the container object, if the query succeeds.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DVolume8.GetDesc

Retrieves a description of the volume.

object.GetDesc( _
    Desc As D3DVOLUME_DESC)

Parts

object
Object expression that resolves to a Direct3DVolume8 object.
Desc
A D3DVOLUME_DESC type, describing the volume.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if the parameter is invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DVolume8.GetDevice

Retrieves the device associated with a volume.

object.GetDevice() As Direct3DDevice8

Parts

object
Object expression that resolves to a Direct3DVolume8 object.

Return Values

The Direct3DDevice8 associated with the volume, if the query succeeds.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method enables navigation to the owning device object. For example, using IID_IDirect3DDevice8 returns the Microsoft® Direct3D® interface for the object that created this buffer.


Direct3DVolume8.GetPrivateData

Copies the private data associated with the volume to a provided buffer.

object.GetPrivateData( _
    RefGuid As DXGUID, _
    Data As Any, _
    SizeOfData As Long)

Parts

object
Object expression that resolves to a Direct3DVolume8 object.
RefGuid
A DXGUID type, the globally unique identifier that identifies the private data to retrieve.
Data
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.
SizeOfData
Size of the buffer at Data, 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_MOREDATA
D3DERR_NOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DVolume8.FreePrivateData, Direct3DVolume8.SetPrivateData


Direct3DVolume8.LockBox

Locks a box on a volume.

object.LockBox( _
    LockedBox As D3DLOCKED_BOX, _
    Box As D3DBOX, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DVolume8 object.
LockedBox
A D3DLOCKED_BOX type, describing the locked region.
Box
Box to lock. Specified by a D3DBOX type. Specifying ByVal 0 locks the entire volume.
Flags
A combination of zero or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See Direct3DDevice8.UpdateTexture for more information.

See Also

Direct3DVolume8.UnlockBox


Direct3DVolume8.SetPrivateData

Associates data with the volume that is intended for use by the application, not by Microsoft® Direct3D®.

object.SetPrivateData( _
    RefGuid As DXGUID, _
    Data As Any, _
    SizeOfData As Long, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DVolume8 object.
RefGuid
A DXGUID type, the globally unique identifier that identifies the private data to set.
Data
A buffer that contains the data to associate with the surface.
SizeOfData
Size of the buffer at Data, in bytes.
Flags
Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes. This parameter can be the value defined by the CONST_D3DSPDFLAGS enumeration, or 0. 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Direct3D does not manage the memory at Data. If this buffer was dynamically allocated, it is the caller's responsibility to free the memory.

Data is passed by value, and multiple sets of data can be associated with a single volume.

See Also

Direct3DVolume8.FreePrivateData, Direct3DVolume8.GetPrivateData


Direct3DVolume8.UnlockBox

Unlocks a box on a volume.

object.UnlockBox()

Parts

object
Object expression that resolves to a Direct3DVolume8 object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DVolume8.LockBox


Direct3DVolumeTexture8

Applications use the methods of the Direct3DVolumeTexture8 class to manipulate a volume texture resource.

The Direct3DVolumeTexture8 class is obtained by calling the Direct3DDevice8.CreateVolumeTexture method. The methods of the Direct3DVolumeTexture8 class can be organized into the following groups.

Information | GetLevelDesc
Locking Volumes | LockBox
 | UnlockBox
Miscellaneous | AddDirtyBox
 | GetVolumeLevel

This class inherits additional functionality from the Direct3DBaseTexture8 class.

See Also

Direct3DDevice8.CreateVolumeTexture


Direct3DVolumeTexture8.AddDirtyBox

Adds a dirty region to a volume texture resource.

object.AddDirtyBox( _
    DirtyBox As Any)

Parts

object
Object expression that resolves to a Direct3DVolumeTexture8 object.
DirtyBox
a D3DBOX type, specifying the dirty region to add. Specifying ByVal 0 locks the entire volume texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 LockRect or LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of a CopyRects call is marked dirty.

Applications can optimize what subset of a resource is copied by specifying boxes on the resource. However, the dirty regions may be expanded to optimize alignment.


Direct3DVolumeTexture8.GetLevelDesc

Retrieves a level description of a volume texture resource.

object.GetLevelDesc( _
    Level As Long, _
    pDesc As D3DVOLUME_DESC)

Parts

object
Object expression that resolves to a Direct3DVolumeTexture8 object.
Level
Identifies a level of the volume texture resource. This method returns a volume description for the level specified by this parameter.
pDesc
A D3DVOLUME_DESC type, describing the returned volume texture level.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL if one or more of the parameters are invalid.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DVolumeTexture8.GetVolumeLevel

Retrieves the specified volume texture level.

object.GetVolumeLevel( _
    Level As Long) As Direct3DVolume8

Parts

object
Object expression that resolves to a Direct3DVolumeTexture8 object.
Level
Identifies a level of the volume texture resource. This method returns a volume for the level specified by this parameter.

Return Values

A Direct3DVolume8 object, representing the returned volume level.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Direct3DVolumeTexture8.LockBox

Locks a box on a volume texture resource.

object.LockBox( _
    Level As Long, _
    LockedVolume As D3DLOCKED_BOX, _
    Box As Any, _
    Flags As Long)

Parts

object
Object expression that resolves to a Direct3DVolumeTexture8 object.
Level
Specifies the level of the volume texture resource to lock.
LockedVolume
A D3DLOCKED_BOX type, describing the locked region.
Box
Volume to lock. Specified by a D3DBOX type. Specifying ByVal 0 locks the entire volume level.
Flags
A combination of zero or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See Direct3DDevice8.UpdateTexture for more information.

See Also

Direct3DVolumeTexture8.UnlockBox


Direct3DVolumeTexture8.UnlockBox

Locks a box on a volume texture resource.

object.UnlockBox( _
    Level As Long)

Parts

object
Object expression that resolves to a Direct3DVolumeTexture8 object.
Level
Specifies the level of the volume texture resource to lock.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

Direct3DVolumeTexture8.LockBox


Functions

This section contains reference information for the functions that you need to implement when you work with Microsoft® Direct3D®. The following functions are implemented.

  • D3DColorARGB
  • D3DColorMake
  • D3DColorRGBA
  • D3DColorXRGB
  • D3DIndexBuffer8GetData
  • D3DVertexBuffer8GetData
  • D3DIndexBuffer8SetData
  • D3DVertexBuffer8SetData


D3DColorARGB

Initializes a color with the supplied alpha, red, green, and blue values.

D3DColorARGB( _
    a As Integer, _
    r As Integer, _
    g As Integer, _
    b As Integer) As Long

Parameters

a
Alpha value of the color. Values between 0 and 255.
r
Red value of the color. Values between 0 and 255.
g
Green value of the color. Values between 0 and 255.
b
Blue value of the color. Values between 0 and 255.

Return Values

Returns the Long value that corresponds to the supplied ARGB values.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Visual Basic Error Handling topic.


D3DColorMake

Initializes a color with the supplied red, green, blue, and alpha floating-point values.

D3DColorMake( _
    r As Single, _
    g As Single, _
    b As Single, _
    a As Single) As Long

Parameters

r
Red value of the color. Values between 0.0 and 1.0.
g
Green value of the color. Values between 0.0 and 1.0.
b
Blue value of the color. Values between 0.0 and 1.0.
a
Blue value of the color. Values between 0.0 and 1.0.

Return Values

Returns the Long value that corresponds to the supplied RGBA values.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Visual Basic Error Handling topic.


D3DColorRGBA

Initializes a color with the supplied red, green, blue, and alpha values.

D3DColorRGBA( _
    r As Integer, _
    g As Integer, _
    b As Integer, _
    a As Integer) As Long

Parameters

r
Red value of the color. Values between 0 and 255.
g
Green value of the color. Values between 0 and 255.
b
Blue value of the color. Values between 0 and 255.
a
Alpha value of the color. Values between 0 and 255.

Return Values

Returns the Long value that corresponds to the supplied RGBA values.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Visual Basic Error Handling topic.


D3DColorXRGB

Initializes a color with the supplied red, green, and blue values.

D3DColorXRGB( _
    r As Integer, _
    g As Integer, _
    b As Integer) As Long

Parameters

r
Red value of the color. Values between 0 and 255.
g
Green value of the color. Values between 0 and 255.
b
Blue value of the color. Values between 0 and 255.

Return Values

Returns the Long value that corresponds to the supplied RGB values.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Visual Basic Error Handling topic.


D3DIndexBuffer8GetData

Retrieves data from an index buffer.

D3DIndexBuffer8GetData( _
    IBuffer As Direct3DIndexBuffer8, _
    Offset As Long, _
    Size As Long, _
    Flags As Long, _
    Data As Any) As Long

Parameters

IBuffer
Direct3DIndexBuffer8 object, representing the index buffer from which to retrieve data.
Offset
Offset, in bytes, from the start of the buffer to where data retrieval begins.
Size
Size of the buffer, in bytes.
Flags
A combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.
Data
Buffer to be filled with the retrieved data.

Return Values

If the method fails, D3DERR_INVALIDCALL can be returned.

Error Codes

Err.Number is not set by this function.

See Also

D3DIndexBuffer8SetData


D3DIndexBuffer8SetData

Sets data in an index buffer.

D3DIndexBuffer8SetData( _
    IBuffer As Direct3DIndexBuffer8, _
    Offset As Long, _
    Size As Long, _
    Flags As Long, _
    Data As Any) As Long

Parameters

IBuffer
Direct3DIndexBuffer8 object, representing the index buffer into which to set data.
Offset
Offset, in bytes, from the start of the buffer to where data is set.
Size
Size of the buffer, in bytes.
Flags
A combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.
Data
Buffer containing data to set.

Return Values

If the method fails, D3DERR_INVALIDCALL can be returned.

Error Codes

Err.Number is not set by this function.

See Also

D3DIndexBuffer8GetData


D3DVertexBuffer8GetData

Retrieves data from a vertex buffer.

D3DVertexBuffer8GetData( _
    VBuffer As Direct3DVertexBuffer8, _
    Offset As Long, _
    Size As Long, _
    Flags As Long, _
    Data As Any) As Long

Parameters

VBuffer
Direct3DVertexBuffer8 object, representing the vertex buffer from which to retrieve data.
Offset
Offset, in bytes, from the start of the buffer to where data retrieval begins.
Size
Size of the buffer, in bytes.
Flags
A combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.
Data
Buffer to be filled with the retrieved data.

Return Values

If the method fails, D3DERR_INVALIDCALL can be returned.

Error Codes

Err.Number is not set by this function.

See Also

D3DVertexBuffer8SetData


D3DVertexBuffer8SetData

Sets data in a vertex buffer.

D3DVertexBuffer8SetData( _
    VBuffer As Direct3DVertexBuffer8, _
    Offset As Long, _
    Size As Long, _
    Flags As Long, _
    Data As Any) As Long

Parameters

VBuffer
Direct3DVertexBuffer8 object, representing the vertex buffer into which to set data.
Offset
Offset, in bytes, from the start of the buffer to where data is set.
Size
Size of the buffer, in bytes.
Flags
A combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.
Data
Buffer containing data to set.

Return Values

If the method fails, D3DERR_INVALIDCALL can be returned.

Error Codes

Err.Number is not set by this function.

See Also

D3DVertexBuffer8GetData


Vertex Shader Declarator Functions

This section covers the bit assembly functions used to compose the vertex shader declaration array.

  • D3DVSD_CONST
  • D3DVSD_END
  • D3DVSD_NOP
  • D3DVSD_REG
  • D3DVSD_SKIP
  • D3DVSD_STREAM
  • D3DVSD_STREAM_TESS
  • D3DVSD_TESSNORMAL
  • D3DVSD_TESSUV


D3DVSD_CONST

Loads data into the vertex shader constant memory.

Function D3DVSD_CONST(ConstantAddress As Long, Count As Long) As Long
     D3DVSD_CONST = (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_constMEM) Or _
     ((Count) * 2 ^ D3DVSD_CONSTCOUNTSHIFT) Or (ConstantAddress))
End Function

Parameters

ConstantAddress
Address of the constant array to begin filling data. Possible values range from 0 to 95.
Count
Number of constant vectors to load. See Remarks.

Remarks

D3DVSD_CONST and all the constants it uses are found in (SDK Root)\Samples\Multimedia\VBSamples\Common\D3DShaders.bas.

The following code example shows how this function might be used.

Dim Declarator(12) As Long

Declarator(0)  = D3DVSD_CONST(8, 1)
Declarator(1)  = FtoDW(1)
Declarator(2)  = FtoDW(1)
Declarator(3)  = FtoDW(1/255)
Declarator(4)  = FtoDW(1)
Declarator(5)  = D3DVSD_STREAM(0)
Declarator(6)  = D3DVSD_REG(0, D3DVSDT_FLOAT3)
Declarator(7)  = D3DVSD_REG(2, D3DVSDT_D3DCOLOR)
Declarator(8)  = D3DVSD_STREAM(1)
Declarator(9)  = D3DVSD_REG(1, D3DVSDT_FLOAT1)
Declarator(10) = D3DVSD_STREAM(2)
Declarator(11) = D3DVSD_REG(3, D3DVSDT_FLOAT2)
Declarator(12) = D3DVSD_END()

See Also

Direct3DDevice8.CreateVertexShader


D3DVSD_END

Generates an END token.

Function D3DVSD_END() As Long
        D3DVSD_END = &HFFFFFFFF
End Function

Parameters

None.

Remarks

D3DVSD_END and all the constants it uses are found in (SDK Root)\Samples\Multimedia\VBSamples\Common\D3DShaders.bas.

See Also

Direct3DDevice8.CreateVertexShader


D3DVSD_NOP

Generates an NOP token.

Function D3DVSD_NOP() As Long
    D3DVSD_NOP = 0
End Function

Parameters

None.

Remarks

D3DVSD_NOP and all the constants it uses are found in (SDK Root)\Samples\Multimedia\VBSamples\Common\D3DShaders.bas.

See Also

Direct3DDevice8.CreateVertexShader


D3DVSD_REG

Binds a single vertex register to a vertex element from the vertex stream.

Function D3DVSD_REG(VertexRegister As Long, dataType As Long) As Long
    D3DVSD_REG = (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAMDATA) Or _
     ((dataType) * 2 ^ D3DVSD_DATATYPESHIFT) Or (VertexRegister))
End Function

Parameters

VertexRegister
Address of the vertex register. Possible values range from 0 through 15. For the fixed function pipeline, the input registers have the following fixed mapping.
D3DVSDE_POSITION
Register 0.
D3DVSDE_BLENDWEIGHT
Register 1.
D3DVSDE_NORMAL
Register 2.
D3DVSDE_PSIZE
Register 3.
D3DVSDE_DIFFUSE
Register 4.
D3DVSDE_SPECULAR
Register 5.
D3DVSDE_TEXCOORD0
Register 6.
D3DVSDE_TEXCOORD1
Register 7.
D3DVSDE_TEXCOORD2
Register 8.
D3DVSDE_TEXCOORD3
Register 9.
D3DVSDE_TEXCOORD4
Register 10.
D3DVSDE_TEXCOORD5
Register 11.
D3DVSDE_TEXCOORD6
Register 12.
D3DVSDE_TEXCOORD7
Register 13.
dataType
Specifies the dimensionality and arithmetic data type. The following values are defined.
D3DVSDT_D3DCOLOR
4-D packed unsigned bytes mapped to 0.0 to 1.0 range. In double word format this is ARGB, or in byte ordering it would be B, G, R, A.
D3DVSDT_FLOAT1
1-D float expanded to (value, 0.0, 0.0, 1.0)
D3DVSDT_FLOAT2
2-D float expanded to (value, value, 0.0, 1.0)
D3DVSDT_FLOAT3
3-D float expanded to (value, value, value, 1.0)
D3DVSDT_FLOAT4
4-D float.
D3DVSDT_UBYTE4
4-D unsigned byte. In double word format this is ABGR, or in byte ordering it would be R, G, B, A.

Remarks

D3DVSD_REG and all the constants it uses are found in (SDK Root)\Samples\Multimedia\VBSamples\Common\D3DShaders.bas.

See Also

Direct3DDevice8.CreateVertexShader


D3DVSD_SKIP

Specifies how many Longs to skip in the vertex.

Function D3DVSD_SKIP(LongCount As Long) As Long
    D3DVSD_SKIP = (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAMDATA) Or _
                   &H10000000 Or _
                   ((LongCount) * 2 ^ D3DVSD_SKIPCOUNTSHIFT))
End Function

Parameters

LongCount
Number of Longs to skip in the vertex.

Remarks

D3DVSD_SKIP and all the constants it uses are found in (SDK Root)\Samples\Multimedia\VBSamples\Common\D3DShaders.bas.

See Also

Direct3DDevice8.CreateVertexShader


D3DVSD_STREAM

Sets the current stream.

Function D3DVSD_STREAM(StreamNumber As Long) As Long
    D3DVSD_STREAM = (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAM) Or _
                    (StreamNumber))
End Function

Parameters

StreamNumber
Specifies the stream from which to get data. Possible values range from 0 through MaxStreams - 1.

Remarks

D3DVSD_STREAM and all the constants it uses are found in (SDK Root)\Samples\Multimedia\VBSamples\Common\D3DShaders.bas.

See Also

Direct3DDevice8.CreateVertexShader


D3DVSD_STREAM_TESS

Sets the tessellator stream.

Function D3DVSD_STREAM_TESS() As Long
    D3DVSD_STREAM_TESS = (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAM) Or _
                         (D3DVSD_STREAMTESSMASK))
End Function

Parameters

None.

Remarks

D3DVSD_STREAM_TESS and all the constants it uses are found in (SDK Root)\Samples\Multimedia\VBSamples\Common\D3DShaders.bas.

See Also

Direct3DDevice8.CreateVertexShader


D3DVSD_TESSNORMAL

Enables tessellator-generated normals.

Function D3DVSD_TESSNORMAL(VertexRegisterIn As Long, VertexRegisterOut As Long) As Long
    D3DVSD_TESSNORMAL = (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_TESSELLATOR) Or _
     ((VertexRegisterIn) * 2 ^ D3DVSD_VERTEXREGINSHIFT) Or _
     ((&H2&) * 2 ^ D3DVSD_DATATYPESHIFT) Or (VertexRegisterOut))
End Function

Parameters

VertexRegisterIn
Address of the vertex register whose input stream will be used in normal computation. Possible values range from 0 to 15.
VertexRegisterOut
Address of the vertex register to output the normal to. Possible values range from 0 to 15.

Remarks

D3DVSD_TESSNORMAL and all the constants it uses are found in (SDK Root)\Samples\Multimedia\VBSamples\Common\D3DShaders.bas.

See Also

Direct3DDevice8.CreateVertexShader


D3DVSD_TESSUV

Enables tessellator-generated surface parameters.

Function D3DVSD_TESSUV(VertexRegister As Long) As Long
    D3DVSD_TESSUV = (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_TESSELLATOR) Or _
                     &H10000000 Or _
                     ((&H1&) * 2 ^ D3DVSD_DATATYPESHIFT) Or _
                     (VertexRegister))
End Function

Parameters

VertexRegister
Address of the vertex register to output parameters. Possible values range from 0 to 15.

Remarks

D3DVSD_TESSUV and all the constants it uses are found in (SDK Root)\Samples\Multimedia\VBSamples\Common\D3DShaders.bas.

See Also

Direct3DDevice8.CreateVertexShader


Types

This section contains information about the types used with Microsoft® Direct3D®.

  • D3DADAPTER_IDENTIFIER8
  • D3DBOX
  • D3DCAPS8
  • D3DCLIPSTATUS8
  • D3DCOLORVALUE
  • D3DDEVICE_CREATION_PARAMETERS
  • D3DDISPLAYMODE
  • D3DGAMMARAMP
  • D3DINDEXBUFFER_DESC
  • D3DLIGHT8
  • D3DLINEPATTERN
  • D3DLOCKED_BOX
  • D3DLOCKED_RECT
  • D3DLVERTEX
  • D3DLVERTEX2
  • D3DMATERIAL8
  • D3DMATRIX
  • D3DPLANE
  • D3DPRESENT_PARAMETERS
  • D3DQUATERNION
  • D3DRANGE
  • D3DRASTER_STATUS
  • D3DRECT
  • D3DRECTPATCH_INFO
  • D3DSURFACE_DESC
  • D3DTLVERTEX
  • D3DTLVERTEX2
  • D3DTRIPATCH_INFO
  • D3DVECTOR
  • D3DVECTOR2
  • D3DVECTOR4
  • D3DVERTEX
  • D3DVERTEX2
  • D3DVERTEXBUFFER_DESC
  • D3DVIEWPORT8
  • D3DVOLUME_DESC
  • PALETTEENTRY


D3DADAPTER_IDENTIFIER8

Contains information identifying the adapter.

Type D3DADAPTER_IDENTIFIER8
    Description(0 To 511) As Byte
    DeviceId As Long
    DeviceIdentifier As DXGUID
    Driver(0 To 511) As Byte
    DriverVersionHighPart As Long
    DriverVersionLowPart As Long
    Revision As Long
    SubSysId As Long
    VendorId As Long
    WHQLLevel As Long
End Type

Members

Description and Driver
For presentation to the user. These members should not be used to identify particular drivers because many different strings may be associated with the same device and driver from different vendors.
DeviceId
Identify the type of a particular chip set. The value may be zero if unknown.
DriverVersion, DriverVersionLowPart, and DriverVersionHighPart
Identify the version of the Microsoft® Direct3D® driver. It is legal to do < and > comparisons on the Long value. However, exercised caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier.
DeviceIdentifier
Track changes to the driver and chip set in order to generate a new profile for the graphics subsystem. This DXGUID is a unique identifier for the driver and chip set pair. You can also use DeviceIdentifier to identify particular problematic drivers.
Revision
Identify a particular chip set and its revision level. The value may be zero if unknown.
SubSysId
Identify a particular chip set and the subsystem. Typically this means the chip set's board. The value may be zero if unknown.
VendorId
Identify a particular chip set and its manufacturer. The value may be zero if unknown.
WHQLLevel
Determine the Windows Hardware Quality Lab (WHQL) certification level for this driver and device pair. The Long 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 certified, but no date information is available.

Remarks

You can use the VendorId, DeviceId, SubSysId, and Revision members in tandem to identify particular chip sets. However, use these members with caution.


D3DBOX

Defines a volume.

Type D3DBOX
    back As Long
    bottom As Long
    front As Long
    left As Long
    right As Long
    top As Long
End Type

Members

back, bottom, front, left, right, and top
The dimensions of the box.

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.


D3DCAPS8

Represents the capabilities of the hardware exposed through the Microsoft® Direct3D® object.

Type D3DCAPS8
    AdapterOrdinal As Long
    AlphaCmpCaps As Long
    caps As Long
    Caps2 As Long
    Caps3 As Long
    CubeTextureFilterCaps As Long
    CursorCaps As Long
    DestBlendCaps As Long
    DevCaps As Long
    DeviceType As Long
    ExtentsAdjust As Single
    FVFCaps As Long
    GuardBandBottom As Single
    GuardBandLeft As Single
    GuardBandRight As Single
    GuardBandTop As Single
    LineCaps As Long
    MaxActiveLights As Long
    MaxAnisotropy As Long
    MaxPixelShaderValue As Single
    MaxPointSize As Single
    MaxPrimitiveCount As Long
    MaxSimultaneousTextures As Long
    MaxStreams As Long
    MaxStreamStride As Long
    MaxTextureAspectRatio As Long
    MaxTextureBlendStages As Long
    MaxTextureHeight As Long
    MaxTextureRepeat As Long
    MaxTextureWidth As Long
    MaxUserClipPlanes As Long
    MaxVertexBlendMatrices As Long
    MaxVertexBlendMatrixIndex As Long
    MaxVertexIndex As Long
    MaxVertexShaderConst As Long
    MaxVertexW As Single
    MaxVolumeExtent As Long
    PixelShaderVersion As Long
    PresentationIntervals As Long
    PrimitiveMiscCaps As Long
    RasterCaps As Long
    ShadeCaps As Long
    SrcBlendCaps As Long
    StencilCaps As Long
    TextureAddressCaps As Long
    TextureCaps As Long
    TextureFilterCaps As Long
    TextureOpCaps As Long
    VertexProcessingCaps As Long
    VertexShaderVersion As Long
    VolumeTextureAddressCaps As Long
    VolumeTextureFilterCaps As Long
    ZCmpCaps As Long
End Type

Members

AdapterOrdinal
Adapter on which this Direct3DDevice object was created. This ordinal is valid only to pass to methods of the Direct3D8 class that created this Direct3DDevice object. The Direct3D8 class can always be retrieved by calling Direct3DDevice8.GetDirect3D.
AlphaCmpCaps
Alpha-test comparison capabilities. 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 defined by the CONST_D3DPCMPCAPSFLAGS enumeration identify the individual comparisons that are supported for alpha testing.
caps
Driver-specific capability, defined by the CONST_D3DCAPSFLAGS enumeration.
Caps2
Driver-specific capabilities. Possible values are defined by the CONST_D3DCAPS2FLAGS enumeration.
Caps3
Driver-specific capability.
D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD
The device will work as expected with the D3DRS_ALPHABLENDENABLE render state when a full-screen application uses D3DSWAPEFFECT_FLIP or D3DRS_SWAPEFFECT_DISCARD. D3DRS_ALPHABLENDENABLE works as expected when using D3DSWAPEFFECT_COPY and D3DSWAPEFFECT_COPYSYNC.
CubeTextureFilterCaps
Texture-filtering capabilities for a Direct3DCubeTexture object. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending with the Direct3DDevice8 class. This member can be any combination of the general and per-stage texture-filtering flags defined by the CONST_D3DPTFILTERCAPSFLAGS enumeration.
CursorCaps
Bit mask indicating what hardware support is available for cursors. Possible values are defined by the CONST_D3DCURSORCAPSFLAGS.
DestBlendCaps
Destination-blending capabilities. This member can be one or more of the flags defined by the CONST_D3DPBLENDCAPSFLAGS enumeration.
DevCaps
Flags identifying the capabilities of the device. Possible values are defined by the CONST_D3DDEVCAPSFLAGS enumeration.
DeviceType
Member of the CONST_D3DDEVTYPE enumeration. Denotes the amount of emulated functionality for this device. The value of this parameter mirrors the value passed to the Direct3D8.CreateDevice call that created this device.
ExtentsAdjust
Number of pixels to adjust the extents rectangle outward to accommodate antialiasing kernels.
FVFCaps
Flexible vertex format capabilities. Possible values are defined by the CONST_D3DFVFCAPSFLAGS enumeration.
GuardBandBottom, GuardBandLeft, GuardBandRight, and GuardBandTop
Screen-space coordinates of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
LineCaps
Defines the capabilities for line-drawing primitives. Possible values are defined by the CONST_D3DLINECAPS enumeration.
MaxActiveLights
Maximum number of lights that can be active simultaneously. For a given physical device, this capability might vary across Direct3D Device Objects depending on the parameters supplied to Direct3D8.CreateDevice.
MaxAnisotropy
Maximum valid value for the D3DTSS_MAXANISOTROPY texture-stage state.
MaxPixelShaderValue
Maximum value of pixel shader arithmetic component. This value indicates the internal range of values supported for pixel color blending operations. Implementations must allow data within the range that they report 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.Note that the value 0.0 indicates that no signed range is supported; therefore, the range is 0 to 1.0 as in Microsoft® DirectX® versions 6.0 and 7.0.
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.0.
MaxPrimitiveCount
Maximum number of primitives, or vertices for each DrawPrimitive call. Note that when Direct3D is working with a DirectX 6 or DirectX 7 driver, this field is set to 0xFFFF. This means that not only the number of primitives but also the number of vertices is limited by this value.
MaxSimultaneousTextures
Maximum number of textures that can be simultaneously bound to the texture blending stages. This value indicates the number of textures that can be used in a single pass. If the same texture is used in two blending stages, it counts as two when compared against the MaxSimultaneousTextures value. In the programmable pipeline, this indicates the number of texture registers supported by pixel shaders on this particular piece of hardware, and the number of texture declaration instructions that can be present.
MaxStreams
The maximum number of concurrent data streams for Direct3DDevice8.SetStreamSource. The valid range is 1 to 16. Note that if this value is 0, then the driver is not a DirectX 8.x driver.
MaxStreamStride
Maximum stride for Direct3DDevice8.SetStreamSource.
MaxTextureAspectRatio
Maximum texture aspect ratio supported by the hardware; this is typically a power of 2.
MaxTextureBlendStages
Maximum number of texture-blending stages supported. This value is the number of blenders available. In the DirectX 8.x programmable pixel pipeline, this should correspond to the number of instructions supported by pixel shaders on this particular implementation.
MaxTextureHeight and MaxTextureWidth
Maximum texture height and width for this device.
MaxTextureRepeat
Full range of the integer bits of the post-normalized texture indices. If the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE bit is set, the device defers scaling by the texture size until after the texture address mode is applied. If not set, the device scales the texture indices by the texture size (largest level of detail) prior to interpolation.

If D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is set, then the exact number of times a texture can be wrapped is MaxTextureRepeat. If D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set, then the exact number of times a texture can be wrapped is (MaxTextureRepeat * texture size). For example, the device has D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE set, MaxTextureRepeat is 32k, and the maximum texture size is 4k. The device uses 27 integer bits (plus 5 fraction bits in a 32 bit (signed) integer), and thus has enough to wrap a 4k texture 32k times (assuming the texture coordinates equally span the positive and negative texture coordinate range). Alternately, the device could not set D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE and set MaxTextureRepeat to 2**27.

MaxUserClipPlanes
Maximum number of user-defined clipping planes supported. This member can range from 0 through D3DMAXUSERCLIPPLANES. For a given physical device, this capability might vary across Direct3D Device Objects depending on the parameters supplied to Direct3D8.CreateDevice.
MaxVertexBlendMatrices
Maximum number of matrices that this device can apply when performing multimatrix vertex blending. For a given physical device, this capability might vary across Direct3D Device Objects depending on the parameters supplied to Direct3D8.CreateDevice.
MaxVertexBlendMatrixIndex
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 might vary across Direct3D Device Objects depending on the parameters supplied to Direct3D8.CreateDevice.

MaxVertexIndex
Maximum size of indices supported for hardware vertex processing. It is possible to create 32-bit index buffers by specifying D3DFMT_INDEX32; however, you will not be able to render with the index buffer unless this value is greater than &HFFFF.
MaxVertexW
Maximum W-based depth value that the device supports.
MaxVolumeExtent
The maximum volume extent.
MaxVertexShaderConst
Number of vertex shader constant registers.
PixelShaderVersion
The pixel shader version, indicating the level of pixel shader supported by the device. Only pixel shaders with version numbers equal to or less than this will succeed in calls to Direct3DDevice8.CreatePixelShader.
  • DirectX 8.x functionality is 01

The main version number is encoded in the second byte. The low byte contains a sub-version number.

PresentationIntervals
A bit mask of values representing what presentation swap intervals are available. Possible values are defined by the CONST_D3DPRESENT_INTERVAL_FLAGS enumeration.
PrimitiveMiscCaps
General capabilities for this primitive. Possible values are defined by the CONST_D3DPMISCCAPSFLAGS enumeration.
RasterCaps
Information on raster-drawing capabilities. This member can be one or more of the flags defined by the CONST_D3DPRASTERCAPSFLAGS enumeration.
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 CONST_D3DSHADEMODE enumeration). 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 flags defined by the CONST_D3DPSHADECAPSFLAGS enumeration.

SrcBlendCaps
Source-blending capabilities. This member can be one or more of the flags defined by the CONST_D3DPBLENDCAPSFLAGS enumeration.
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_STENCILFAILZFAIL). Possible values are defined by the CONST_D3DSTENCILCAPFLAGS enumeration.

For more information, see the CONST_D3DSTENCILOP enumeration.

TextureAddressCaps
Texture-addressing capabilities for a Direct3DTexture object. This member can be one or more of the flags defined by the CONST_D3DPTADDRESSCAPSFLAGS enumeration.
TextureCaps
Miscellaneous texture-mapping capabilities. This member can be one or more of the flags defined by the CONST_D3DPTEXTURECAPSFLAGS enumeration.
TextureFilterCaps
Texture-filtering capabilities for a Direct3DTexture object. General texture-filtering flags reflect which texture-filtering modes are supported and can be set for the D3DTSS_MAGFILTER, D3DTSS_MINFILTER, or D3DTSS_MIPFILTER texture-stage states. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending with the Direct3DDevice8 class. This member can be any combination of the general and per-stage texture-filtering flags defined by the CONST_D3DPTFILTERCAPSFLAGS enumeration.
TextureOpCaps
Combination of flags describing the texture operations supported by this device. Possible values are defined by the CONST_D3DTEXOPCAPSFLAGS enumeration.

For more information, see the CONST_D3DTEXTUREOP enumeration.

VertexProcessingCaps
Vertex processing capabilities. Possible values are defined by the CONST_D3DVTXPCAPSFLAGS enumeration. For a given physical device, this capability might vary across Direct3D Device Objects depending on the parameters supplied to Direct3D8.CreateDevice.
VertexShaderVersion
The vertex shader version, indicating the level of vertex shader supported by the device. Only vertex shaders with version numbers equal to or less than this will succeed in calls to Direct3DDevice8.CreateVertexShader. The level of shader is specified to CreateVertexShader as the first token in the vertex shader token stream.
  • DirectX 7.0 functionality is 0
  • DirectX 8.x functionality is 01

The main version number is encoded in the second byte. The low byte contains a sub-version number.

VolumeTextureAddressCaps
Texture-addressing capabilities for Direct3DVolumeTexture objects. This member can be one or more of the flags defined by the CONST_D3DPTADDRESSCAPSFLAGS enumeration.
VolumeTextureFilterCaps
Texture-filtering capabilities for a Direct3DVolumeTexture object. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending with the Direct3DDevice8 class. This member can be any combination of the per-stage texture-filtering flags defined for the TextureFilterCaps member. This member can be any combination of the general and per-stage texture-filtering flags defined by the CONST_D3DPTFILTERCAPSFLAGS enumeration.
ZCmpCaps
Z-buffer comparison capabilities. This member can include the same capability flags defined for the AlphaCmpCaps member. The flags for this member are defined by the CONST_D3DPCMPCAPSFLAGS enumeration.

Remarks

The MaxTextureBlendStages and MaxSimultaneousTextures members might seem very 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 Direct3DDevice8.SetTexture method.

When the driver fills this type, it can set values for execute-buffer capabilities, even when the class being used to retrieve the capabilities (such as Direct3DDevice8) does not support execute buffers.

The following flags concerning mipmapped textures are not supported in DirectX 8.x.

  • D3DPTFILTERCAPS_NEAREST
  • D3DPTFILTERCAPS_LINEAR
  • D3DPTFILTERCAPS_MIPNEAREST
  • D3DPTFILTERCAPS_MIPLINEAR
  • D3DPTFILTERCAPS_LINEARMIPNEAREST
  • D3DPTFILTERCAPS_LINEARMIPLINEAR

See Also

Direct3D8.GetDeviceCaps


D3DCLIPSTATUS8

Describes the current clip status.

Type D3DCLIPSTATUS8
    ClipUnion As Long
    ClipIntersection As Long
End Type

Members

ClipUnion
Clip union flags that describe the current clip status. This member can be one or more of the flags defined by the CONST_D3DCLIPFLAGS enumeration.
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 ProcessVertices, DrawPrimitive, or other drawing functions), Microsoft® 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 D3DClipStatus8, 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 DrawRectPatch and DrawTriPatch because there is no software emulation for them.

See Also

Direct3DDevice8.GetClipStatus, Direct3DDevice8.SetClipStatus


D3DCOLORVALUE

Describes color values.

Type D3DCOLORVALUE
    a As Single
    b As Single
    g As Single
    r As Single
End Type

Members

a, b, g, and r
Values specifying the red, green, blue, and alpha components of a color. These values generally are in the range from 0 through 1, with 0 being black.

Remarks

You can set the members of this type 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, which actually remove light from a scene.

See Also

Color Values for Lights and Materials


D3DDEVICE_CREATION_PARAMETERS

Describes the creation parameters for a device.

Type D3DDEVICE_CREATION_PARAMETERS
    AdapterOrdinal As Long
    BehaviorFlags As Long
    DeviceType As CONST_D3DDEVTYPE
    hFocusWindow As Long
End Type

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 Direct3D8 methods. Note that different Direct3D8 objects may use different ordinals. For example, adapters can enter and leave a system due to users adding or subtracting monitors from a multiple monitor system, or due to hot-swapping a laptop. Consequently, you should use this ordinal only in a Direct3D8 known to be valid. The only two valid Direct3D8 instances are the Direct3D8 that created this Direct3DDevice8 object and the Direct3D8 returned from Direct3DDevice8.GetDirect3D as called through this Direct3DDevice8 object.

BehaviorFlags
A combination of one or more of the flags that control global behaviors of the Microsoft® Direct3D® device. Possible values are defined by the CONST_D3DCREATEFLAGS enumeration.

The value of this parameter mirrors the value passed to the Direct3D8.CreateDevice call that created this device.

DeviceType
Member of the CONST_D3DDEVTYPE enumeration. Denotes the amount of emulated functionality for this device. The value of this parameter mirrors the value passed to the 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 CreateDevice call that created this device.

See Also

Direct3DDevice8.GetCreationParameters, Direct3D8.CreateDevice


D3DDISPLAYMODE

Describes the display mode.

Type D3DDISPLAYMODE
    Format As CONST_D3DFORMAT
    Height As Long
    RefreshRate As Long
    Width As Long
End Type

Members

Format
A member of the CONST_D3DFORMAT enumeration, describing the surface format of the display mode.
Height
The screen height, in pixels.
RefreshRate
The refresh rate. The value of 0 indicates an adapter default.
Width
The screen width, in pixels.

See Also

Direct3D8.EnumAdapterModes, Direct3D8.GetAdapterDisplayMode, Direct3DDevice8.GetDisplayMode


D3DGAMMARAMP

Contains red, green, and blue ramp data.

Type D3DGAMMARAMP
    blue(0 To 255) As Integer
    green(0 To 255) As Integer
    red(0 To 255) As Integer
End Type

Members

blue, green, and red
Array of 256 Integer elements that describe the red, green, and blue gamma ramps.

See Also

Direct3DDevice8.GetGammaRamp, Direct3DDevice8.SetGammaRamp


D3DINDEXBUFFER_DESC

Describes an index buffer.

Type D3DINDEXBUFFER_DESC
    Format As CONST_D3DFORMAT
    Pool As CONST_D3DPOOL
    Size As Long
    Type As CONST_D3DRESOURCETYPE
    Usage As Long
End Type

Members

Format
A member of the CONST_D3DFORMAT enumeration, describing the surface format of the index buffer data.
Pool
A member of the CONST_D3DPOOL enumeration, specifying the class of memory allocated for this index buffer.
Size
The size of the index buffer, in bytes.
Type
A member of the CONST_D3DRESOURCETYPE enumeration, identifying this resource as an index buffer.
Usage
A combination of one or more of the following flags defined by the CONST_D3DUSAGEFLAGS enumeration, 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 accelerated graphics port (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.

D3DUSAGE_HOSURFACES
Set to indicate when the index buffer is to be used for drawing high-order primitives.
D3DUSAGE_RTPATCHES
Set to indicate when the vertex 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.

See Also

Direct3DIndexBuffer8.GetDesc


D3DLIGHT8

Defines a set of lighting properties.

Type D3DLIGHT8
    ambient As D3DCOLORVALUE
    diffuse As D3DCOLORVALUE
    specular As D3DCOLORVALUE
    type As CONST_D3DLIGHTTYPE
    Attenuation0 As Single
    Attenuation1 As Single
    Attenuation2 As Single
    Direction As D3DVECTOR
    Falloff As Single
    Phi As Single
    position As D3DVECTOR
    Range As Single
    Theta As Single
End Type

Members

ambient
Ambient color emitted by the light. This member is a D3DCOLORVALUE type.
diffuse
Diffuse color emitted by the light. This member is a D3DCOLORVALUE type.
specular
Specular color emitted by the light. This member is a D3DCOLORVALUE type.
type
Type of the light source. This value is one of the members of the CONST_D3DLIGHTTYPE enumeration.
Attenuation0, Attenuation1, and Attenuation2
Values specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. These members represent attenuation constants. For information on attenuation, see Light Position, Range, and Attenuation. Valid values for these members range from 0.0 to infinity. For nondirectional lights, all three attenuation values should not be set to 0.0 at the same time.
Direction
Direction that the light is pointing in world space, specified by a D3DVECTOR type. This member has meaning only for directional and spotlights. This vector need not be normalized, but it should have a nonzero length.
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.

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.
position
Position of the light in world space, specified by a D3DVECTOR type. This member has no meaning for directional lights and is ignored in that case.
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.
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.

See Also

Direct3DDevice8.GetLight, Direct3DDevice8.SetLight


D3DLINEPATTERN

Describes a line pattern.

Type D3DLINEPATTERN
    LinePattern As Integer
    RepeatFactor As Integer
End Type

Members

LinePattern
Bits specifying the line pattern. For example, the following value would produce a dotted line: 1100110011001100.
RepeatFactor
Number of times to repeat each series of 1s and 0s specified in the LinePattern member. This enables an application to stretch the line pattern.

Remarks

These values are used by the D3DRS_LINEPATTERN render state in the CONST_D3DRENDERSTATETYPE enumeration.

A line pattern specifies how a line is drawn. The line pattern is always the same, no matter where it is started. (This differs from stippling, which affects how objects are rendered; that is, to imitate transparency.)

The line pattern specifies up to a 16-pixel pattern of on and off pixels along the line. The RepeatFactor member specifies how many pixels are repeated for each entry in LinePattern.


D3DLOCKED_BOX

Describes a locked box (volume).

Type D3DLOCKED_BOX
    pBits As Long
    RowPitch As Long
    SlicePitch As Long
End Type

Members

pBits
The locked bits. If a D3DBOX was provided to the LockRect call, pBits will be appropriately offset from the start of the volume.
RowPitch
The row pitch, in bytes.
SlicePitch
The slice pitch, in bytes.

Remarks

Volumes can be visualized as being organized into slices of width x height with 2-D surfaces stacked up to make a width x height x depth volume. For more information, see Volume Texture Resources.

See Also

Direct3DVolume8.LockBox, Direct3DVolumeTexture8.LockBox


D3DLOCKED_RECT

Describes a locked rectangular region.

Type D3DLOCKED_RECT
    pBits As Long
    Pitch As Long
End Type

Members

pBits
The locked bits. If a RECT was provided to the LockRect call, pBits will be appropriately offset from the start of the surface.
Pitch
Pitch of surface, in bytes.

See Also

Direct3DCubeTexture8.LockRect, Direct3DSurface8.LockRect, Direct3DTexture8.LockRect.


D3DLVERTEX

Defines an untransformed and lit vertex (model coordinates with color).

Type D3DLVERTEX
    color As Long
    specular As Long
    tu As Single
    tv As Single
    x As Single
    y As Single
    z As Single
End Type

Members

color and specular
Values describing the color and specular component of the vertex.
tu and tv
Values describing the texture coordinates of the vertex.
x, y, and z
Values describing the homogeneous coordinates of the vertex.

Remarks

An application should use this type when the vertex transformations will be handled by Microsoft® Direct3D®. This type contains only data and a color that would be filled by software lighting.

If D3DRS_SPECULARENABLE is 1, the specular component will be added to the base color after the texture cascade but before alpha blending. However, you can assign the specular component to be applied during texture color processing by setting the D3DTA_SPECULAR flag. For more information, see Texture Argument Flags.


D3DLVERTEX2

Defines an untransformed and lit vertex (model coordinates with color) with two sets of texture coordinates.

Type D3DLVERTEX2
    color As Long
    specular As Long
    tu1 As Single
    tu2 As Single
    tv1 As Single
    tv2 As Single
    x As Single
    y As Single
    z As Single
End Type

Members

color and specular
Values describing the color and specular component of the vertex.
tu1 and tv1
Values describing the first set of texture coordinates of the vertex.
tu2 and tv2
Values describing the second set of texture coordinates of the vertex.
x, y, and z
Values describing the homogeneous coordinates of the vertex.

Remarks

D3DLVERTEX2 is provided as a convenience, since many multitexture operations require two sets of texture coordinates.

An application should use this type when the vertex transformations will be handled by Microsoft® Direct3D®. This type contains only data and a color that would be filled by software lighting.

If D3DRS_SPECULARENABLE is 1, the specular component will be added to the base color after the texture cascade but before alpha blending. However, you can assign the specular component to be applied during texture color processing by setting the D3DTA_SPECULAR flag. For more information, see Texture Argument Flags.


D3DMATERIAL8

Specifies material properties.

Type D3DMATERIAL8
    ambient As D3DCOLORVALUE
    diffuse As D3DCOLORVALUE
    emissive As D3DCOLORVALUE
    power As Single
    specular As D3DCOLORVALUE
End Type

Members

ambient, diffuse, emissive, and specular
Values specifying the ambient color, diffuse color, emissive color, and specular color of the material, respectively. These values are D3DCOLORVALUE types.
power
Value specifying the sharpness of specular highlights. To turn off specular highlights for a material, set this member to 0; setting the specular color components to 0 is not enough.

See Also

Direct3DDevice8.GetMaterial, Direct3DDevice8.SetMaterial


D3DMATRIX

Describes a matrix.

Type D3DMATRIX
    m11 As Single
    m12 As Single
    m13 As Single
    m14 As Single
    m21 As Single
    m22 As Single
    m23 As Single
    m24 As Single
    m31 As Single
    m32 As Single
    m33 As Single
    m34 As Single
    m41 As Single
    m42 As Single
    m43 As Single
    m44 As Single
End Type

Remarks

In Microsoft® Direct3D®, the m34 element of a projection matrix cannot be a negative number. If an application needs to use a negative value in this location, it should scale the entire projection matrix by –1, instead.

See Also

Direct3DDevice8.GetTransform, Direct3DDevice8.MultiplyTransform, Direct3DDevice8.SetTransform


D3DPLANE

Describes a plane.

Type D3DPLANE
    a As Single
    b As Single
    c As Single
    d As Single
End Type

Members

a, b, c, and d
The a, b, c, and d coefficients, respectively, of the clipping plane in the general plane equation. See Remarks.

Remarks

The members of the D3DPLANE type take the form of the general plane equation. They fit into the general plane equation so that ax + by + cz + dw = 0.


D3DPRESENT_PARAMETERS

Describes the presentation parameters.

Type D3DPRESENT_PARAMETERS
    AutoDepthStencilFormat As CONST_D3DFORMAT
    BackBufferCount As Long
    BackBufferFormat As CONST_D3DFORMAT
    BackBufferHeight As Long
    BackBufferWidth As Long
    EnableAutoDepthStencil As Long
    Flags As Long
    FullScreen_PresentationInterval As Long
    FullScreen_RefreshRateInHz As Long
    hDeviceWindow As Long
    MultiSampleType As CONST_D3DMULTISAMPLE_TYPE
    SwapEffect As CONST_D3DSWAPEFFECT
    Windowed As Long
End Type

Members

AutoDepthStencilFormat
A member of the CONST_D3DFORMAT enumeration. The format of the automatic depth-stencil surface that the device will create. This member is ignored unless EnableAutoDepthStencil is a nonzero value (True).
BackBufferCount
This value can be 0, 1, 2 or 3. Note that 0 is treated as 1. If the number of back buffers cannot be created, Microsoft® Direct3D 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 type and expect it to work the second time.

One back buffer is considered the minimum number of back buffers. The method call fails if 1 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.

BackBufferFormat
A member of the CONST_D3DFORMAT enumeration. This value must be one of the render target formats as validated by Direct3D8.CheckDeviceType.

If Windowed is set to 1, then BackBufferFormat must be set to match the format of the current display mode. Use Direct3DDevice8.GetDisplayMode to obtain the current format.

BackBufferHeight and BackBufferWidth
The height and width of the new swap chain's back buffers, in pixels. If Windowed is zero (False) the presentation is full-screen, and these values must equal the height and width of one of the enumerated display modes found through Direct3D8.EnumAdapterModes. If Windowed is 1 and either of these values is zero, then the corresponding dimension of the client area of the hDeviceWindow (or the focus window, if hDeviceWindow is Nothing) is taken.
EnableAutoDepthStencil
If this value is 1, 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 1, then AutoDepthStencilFormat must be a valid depth-stencil format.

Flags
Currently this value is not used, it must be set to 0.
FullScreen_PresentationInterval
A bit mask of values representing what presentation swap intervals are available. For windowed mode, this value must be 0; otherwise, this value must be one of the values enumerated in the PresentationIntervals member of D3DCAPS8. Possible values are defined by the CONST_D3DPRESENT_INTERVAL_FLAGS enumeration.
FullScreen_RefreshRateInHz
The rate at which the display adapter refreshes the screen. For windowed mode, this value must be 0; otherwise, this value must be one of the refresh rates returned by Direct3D8.EnumAdapterModes, or one of the refresh rates defined by the CONST_D3DPRESENT_RATE_FLAGS enumeration.
hDeviceWindow
If full-screen, this is the cover window. If windowed, this will be the default target window for Direct3DDevice8.Present. If this value is Nothing, the focus window will be taken. For applications that use multiple full-screen devices, such as a multi-monitor system, exactly one device should use the focus window as the device window. All other devices should have unique device windows. Otherwise, behavior is undefined and applications will not work as expected.

Note that no attempt is made by Direct3D to reflect user changes in window size. The back buffer is not implicitly reset when this window is reset. However, the Present method does automatically track window position changes.

MultiSampleType
A member of the CONST_D3DMULTISAMPLE_TYPE enumeration. 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.
SwapEffect
A member of the CONST_D3DSWAPEFFECT enumeration. Direct3D will guarantee the implied semantics concerning buffer swap behavior. So if Windowed is 1 and D3DSWAPEFFECT_FLIP, then Direct3D will create one extra back buffer, and copy whichever becomes the front buffer at presentation time.

D3DSWAPEFFECT_COPY and D3DSWAPEFFECT_COPY_VSYNC require that BackBufferCount be set to 1.

D3DSWAPEFFECT_DISCARD will be enforced in the debug run time by filling any buffer with noise after it is presented.

Windowed
1 if the application runs windowed, 0 if the application runs full-screen.

See Also

Direct3D8.CreateDevice, Direct3DDevice8.CreateAdditionalSwapChain, Direct3DDevice8.Present, Direct3DDevice8.Reset


D3DQUATERNION

Describes a quaternion.

Type D3DQUATERNION
    w As Single
    x As Single
    y As Single
    z As Single
End Type

Members

w, x, y, and z
The w-, x-, y-, and z-components, respectively, of the quaternion.

Remarks

Quaternions add a fourth element to the [x, y, z] values that define a vector, resulting in arbitrary 4-D 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)


D3DRANGE

Defines a range.

Type D3DRANGE
    cbOffset As Long
    size As Long
End Type

Members

cbOffset
The offset, in bytes.
size
The size, in bytes.


D3DRASTER_STATUS

Describes the raster status.

Type D3DRASTER_STATUS
    InVBLANK As Long
    ScanLine As Long
End Type

Members

InVBLANK
1 if the raster is in the vertical blank period. 0 if the raster is not in the vertical blank period.
ScanLine
If InVBLANK is 0, 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 Microsoft® 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 1, then this value is set to zero and can be ignored.


D3DRECT

Defines a rectangle.

Type D3DRECT
    x1 As Long
    x2 As Long
    y1 As Long
    y2 As Long
End Type

Members

x1 and y1
Coordinates of the upper-left corner of the rectangle.
x2 and y2
Coordinates of the lower-right corner of the rectangle.

See Also

Direct3DDevice8.Clear


D3DRECTPATCH_INFO

Describes a rectangular high-order patch.

Type D3DRECTPATCH_INFO
    Basis As CONST_D3DBASISTYPE
    Height As Long
    Order As CONST_D3DORDERTYPE
    StartVertexOffsetHeight As Long
    StartVertexOffsetWidth As Long
    StrideBytes As Long
    Width As Long
End Type

Members

Basis
Member of the CONST_D3DBASISTYPE 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
Height
Height of each patch, in number of vertices.
Order
Member of the CONST_D3DORDERTYPE type, defining the order type for the rectangular high-order patch.
StartVertexOffsetHeight
Starting vertex offset height, in number of vertices.
StartVertexOffsetWidth
Starting vertex offset width, in number of vertices.
StrideBytes
The stride is a width of the imaginary 2-dimensional vertex array, which occupies the same space as the vertex buffer. See the diagram below for an example.
Width
Width of each patch, in number of vertices.

Remarks

To render a stream of individual rectangular patches (nonmosaic), you should interpret your geometry as a long narrow (1 × N) rectangular patch. The D3DRECTPATCH_INFO structure for such a strip (cubic Bézier) would be set up in the following manner.

Dim i As Integer
Dim RectInfo As D3DRECTPATCH_INFO

With D3DRECTPATCH_INFO
    .Width = 4
    .Height = 4
    .Stride = 4
    .Basis = D3DBASIS_BEZIER
    .Order = D3DORDER_CUBIC
    .StartVertexOffsetWidth = 0
    .StartVertexOffsetHeight = 4 * i  ' The variable i is the index of the patch you want to render.
End With

The following diagram identifies the parameters that specify a rectangle patch.

Parameters that specify a rectangle patch.

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 5. The "x" offset to the first vertex is called the StartIndexVertexWidth and is 1 in this case. The "y" offset to the first patch vertex is called the StartIndexVertexHeight and is 0 in this case.

See Also

Direct3DDevice8.DrawRectPatch


D3DSURFACE_DESC

Describes a surface.

Type D3DSURFACE_DESC
    format As CONST_D3DFORMAT
    Height As Long
    MultiSampleType As CONST_D3DMULTISAMPLE_TYPE
    Pool As CONST_D3DPOOL
    size As Long
    type As CONST_D3DRESOURCETYPE
    Usage As Long
    Width As Long
End Type

Members

format
A member of the CONST_D3DFORMAT enumeration, describing the surface format.
Height
The height of the surface, in pixels.
MultiSampleType
A member of the CONST_D3DMULTISAMPLE_TYPE enumeration, specifying the levels of full-scene multisampling supported by the surface.
Pool
A member of the CONST_D3DPOOL enumeration, specifying the class of memory allocated for this surface.
size
The size of the surface, in bytes.
type
A member of the CONST_D3DRESOURCETYPE enumerated type, identifying this resource as a surface.
Usage
A combination of one or more of the following flags defined by the CONST_D3DUSAGEFLAGS enumeration, specifying the usage for this resource.
D3DUSAGE_DEPTHSTENCIL
Set to indicate that the surface is to be used as a depth stencil surface.
D3DUSAGE_RENDERTARGET
Set to indicate that the surface is to be used as a render target.
Width
The width of the surface, in pixels.

See Also

Direct3DCubeTexture8.GetLevelDesc, Direct3DSurface8.GetDesc, Direct3DTexture8.GetLevelDesc.


D3DTLVERTEX

Defines a transformed and lit vertex (screen coordinates with color).

Type D3DTLVERTEX
    color As Long
    rhw As Single
    specular As Long
    sx As Single
    sy As Single
    sz As Single
    tu As Single
    tv As Single
End Type

Members

color and specular
Values describing the color and specular component of the vertex.
rhw
Value that is the reciprocal of homogeneous w from homogeneous coordinates (x,y,z,w). This value is often 1 divided by the distance from the origin to the object along the z-axis.
sx, sy, and sz
Values describing a vertex in screen coordinates. The largest allowable value for dvSZ is 1.0 if you want the vertex to be within the range of z-values that are displayed.
tu and tv
Values describing the texture coordinates of the vertex.

Remarks

Microsoft® Direct3D® uses the current viewport parameters (the x, y, Width, and Height members of the D3DVIEWPORT8 type) to clip D3DTLVERTEX vertices. The system always clips z-coordinates to [0, 1].

If D3DRS_SPECULARENABLE is 1, the specular component will be added to the base color after the texture cascade but before alpha blending. However, you can assign the specular component to be applied during texture color processing by setting the D3DTA_SPECULAR flag. For more information, see Texture Argument Flags.

See Also

D3DTLVERTEX2, D3DVERTEX, D3DVERTEX2


D3DTLVERTEX2

Defines a transformed and lit vertex (screen coordinates with color) with two sets of texture coordinates.

Type D3DTLVERTEX2
    color As Long
    rhw As Single
    specular As Long
    sx As Single
    sy As Single
    sz As Single
    tu1 As Single
    tu2 As Single
    tv1 As Single
    tv2 As Single
End Type

Members

color and specular
Values describing the color and specular component of the vertex.
rhw
Value that is the reciprocal of homogeneous w from homogeneous coordinates (x,y,z,w). This value is often 1 divided by the distance from the origin to the object along the z-axis.
sx, sy, and sz
Values describing a vertex in screen coordinates. The largest allowable value for dvSZ is 1.0 if you want the vertex to be within the range of z-values that are displayed.
tu1 and tv1
Values describing the first set of texture coordinates of the vertex.
tu2 and tv2
Values describing the second set of texture coordinates of the vertex.

Remarks

D3DTLVERTEX2 is provided as a convenience, since many multitexture operations require two sets of texture coordinates.

Microsoft® Direct3D® uses the current viewport parameters (the x, y, Width, and Height members of the D3DVIEWPORT8 type) to clip D3DTLVERTEX vertices. The system always clips z-coordinates to [0, 1].

If D3DRS_SPECULARENABLE is 1, the specular component will be added to the base color after the texture cascade but before alpha blending. However, you can assign the specular component to be applied during texture color processing by setting the D3DTA_SPECULAR flag. For more information, see Texture Argument Flags.

See Also

D3DVERTEX, D3DVERTEX2, D3DTLVERTEX


D3DTRIPATCH_INFO

Describes a triangular high-order patch.

Type D3DTRIPATCH_INFO
    Basis As CONST_D3DBASISTYPE
    NumVertices As Long
    Order As CONST_D3DORDERTYPE
    StartVertexOffsetWidth As Long
End Type

Members

Basis
Member of the CONST_D3DBASISTYPE type, defining the basis type for the triangular high-order patch.
NumVertices
The number of vertices in the triangular high-order patch.
Order
Member of the CONST_D3DORDERTYPE type, defining the order type for the triangular high-order patch.
Value | Number of Vertices
D3DORDER_BEZIER | N/A
D3DORDER_CUBIC | 10
D3DORDER_LINEAR | 3
D3DORDER_QUADRATIC | N/A
D3DORDER_QUINTIC | 21

N/A - Not available. Not supported.

StartVertexOffsetWidth
Starting vertex offset width, in number of vertices.

Remarks

The following diagram identifies the parameters that specify a triangle patch.

The integers values indicate how the patch vertex data is organized in the vertex buffer. In this case, the offset to the first vertex is zero because the first patch vertex is the first data point in the vertex buffer.

Currently works only with hardware vertex processing. Only D3DBASIS_BEZIER basis is supported D3DORDER_QUADRATIC is not supported

See Also

Direct3DDevice8.DrawTriPatch


D3DVECTOR

Defines a vector in three-dimensional space.

Type D3DVECTOR
    x As Single
    y As Single
    z As Single
End Type

Members

x, y, and z
Values describing the vector.

See Also

D3DVECTOR2, D3DVECTOR4


D3DVECTOR2

Describes a vector in two-dimensional (2-D) space.

Type D3DVECTOR2
    x As Single
    y As Single
End Type

Members

x and y
The x- and y-component, respectively, of the vector.

See Also

D3DVECTOR, D3DVECTOR4


D3DVECTOR4

Describes a vector in four-dimensional (4-D) space.

Type D3DVECTOR4
    w As Single
    x As Single
    y As Single
    z As Single
End Type

Members

w, x, y, and z
The w-, x-, y-, and z- component, respectively, of the vector.

See Also

D3DVECTOR, D3DVECTOR2


D3DVERTEX

Defines an untransformed and unlit vertex (model coordinates with normal direction vector).

Type D3DVERTEX
    nx As Single
    ny As Single
    nz As Single
    tu As Single
    tv As Single
    x As Single
    y As Single
    z As Single
End Type

Members

nx, ny, and nz
Values describing the normal coordinates of the vertex.
tu and tv
Values describing the texture coordinates of the vertex.
x, y, and z
Values describing the homogeneous coordinates of the vertex.

See Also

D3DTLVERTEX


D3DVERTEX2

Defines an untransformed and unlit vertex (model coordinates with normal direction vector) with two sets of texture coordinates.

Type D3DVERTEX2
    nx As Single
    ny As Single
    nz As Single
    tu1 As Single
    tu2 As Single
    tv1 As Single
    tv2 As Single
    x As Single
    y As Single
    z As Single
End Type

Members

nx, ny, and nz
Values describing the normal coordinates of the vertex.
tu1 and tv1
Values describing the first set of texture coordinates of the vertex.
tu2 and tv2
Values describing the second set of texture coordinates of the vertex.
x, y, and z
Values describing the homogeneous coordinates of the vertex.

Remarks

D3DVERTEX2 is provided as a convenience, since many multitexture operations require two sets of texture coordinates.

See Also

D3DVERTEX, D3DTLVERTEX, D3DTLVERTEX2


D3DVERTEXBUFFER_DESC

Describes a vertex buffer.

Type D3DVERTEXBUFFER_DESC
    format As CONST_D3DFORMAT
    FVF As Long
    Pool As CONST_D3DPOOL
    size As Long
    type As CONST_D3DRESOURCETYPE
    Usage As Long
End Type

Members

format
A member of the CONST_D3DFORMAT enumeration, describing the surface format of the vertex buffer data.
FVF
A combination of flexible vertex format flags that describes the vertex format of the vertices in this buffer.
Pool
A member of the CONST_D3DPOOL enumeration, specifying the class of memory allocated for this vertex buffer.
size
The size of the vertex buffer, in bytes
type
A member of the CONST_D3DRESOURCETYPE enumeration, identifying this resource as a vertex buffer.
Usage
A combination of one or more of the following flags defined by the CONST_D3DUSAGEFLAGS enumeration, specifying the usage for this resource.
D3DUSAGE_DONOTCLIP
Set to indicate that the vertex buffer content will never require clipping.
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 only valid on vertex buffers created with D3DUSAGE_DYNAMIC; they are not valid flags on static vertex buffers.

For more information about using dynamic vertex buffers, see Using Dynamic Vertex and Index Buffers.

Note that D3DUSAGE_DYNAMIC cannot be specified on managed vertex buffers. For more information, see Managing Resources.

D3DUSAGE_HOSURFACES
Set to indicate when the vertex buffer is to be used for drawing high-order primitives.
D3DUSAGE_RTPATCHES
Set to indicate when the vertex buffer is to be used for drawing high-order primitives.
D3DUSAGE_NPATCHES
Set to indicate when the vertex buffer is to be used for drawing N patches.
D3DUSAGE_POINTS
Set to indicate when the vertex buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the vertex buffer is to be used with software vertex processing.
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 can result in degraded performance.

See Also

Direct3DVertexBuffer8.GetDesc


D3DVIEWPORT8

Defines the window dimensions of a render target surface onto which a 3-D volume projects.

Type D3DVIEWPORT8
    MaxZ As Single
    MinZ As Single
    Height As Long
    Width As Long
    x As Long
    y As Long
End Type

Members

MaxZ and MinZ
Values 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 these values to 0.0 and 1.0, respectively. Clipping is performed after applying the projection matrix.
Height and Width
Dimensions of the viewport on the render target surface, in pixels. Unless you are rendering only to a subset of the surface, these members should be set to the dimensions of the render target surface.
x and y
Pixel coordinates of the upper-left corner of the viewport on the render target surface. Unless you want to render to a subset of the surface, these members can be set to 0.

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×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 (due to a call to the Direct3DDevice8.SetViewport method), the driver builds a new transformation matrix.

See Also

Direct3DDevice8.GetViewport, Direct3DDevice8.SetViewport


D3DVOLUME_DESC

Describes a volume.

Type D3DVOLUME_DESC
    Depth As Long
    format As CONST_D3DFORMAT
    Height As Long
    Pool As CONST_D3DPOOL
    size As Long
    type As CONST_D3DRESOURCETYPE
    Usage As Long
    Width As Long
End Type

Members

Depth
The depth of the volume, in pixels.
format
A member of the CONST_D3DFORMAT enumeration, describing the surface format of the volume.
Height
The height of the volume, in pixels.
Pool
A member of the CONST_D3DPOOL enumeration, specifying the class of memory allocated for this volume.
size
The size of the volume, in bytes.
type
A member of the CONST_D3DRESOURCETYPE enumeration, identifying this resource as a volume.
Usage
Currently not used. Will always be returned as 0.
Width
The width of the volume, in pixels.

See Also

Direct3DVolume8.GetDesc, Direct3DVolumeTexture8.GetLevelDesc


PALETTEENTRY

Specifies the color and usage of an entry in a logical palette.

Type PALETTEENTRY
    red As Byte
    green As Byte
    blue As Byte
    flags As Byte
End Type

Members

red
The red intensity value for the palette entry.
green
The green intensity value for the palette entry.
blue
The blue intensity value for the palette entry.
flags
The alpha intensity value for the palette entry. Note that as of Microsoft® DirectX® 8.0, this member is treated differently than documented in the Microsoft® Platform Software Development Kit (SDK).


Enumerations

This section contains information about the following enumerations used with Microsoft® Direct3D®.

  • CONST_D3DBACKBUFFERTYPE
  • CONST_D3DBASISTYPE
  • CONST_D3DBLEND
  • CONST_D3DBLENDOP
  • CONST_D3DCAPS2FLAGS
  • CONST_D3DCAPSFLAGS
  • CONST_D3DCLEARFLAGS
  • CONST_D3DCLIPFLAGS
  • CONST_D3DCLIPPLANEFLAGS
  • CONST_D3DCMPFUNC
  • CONST_D3DCOLORWRITEENABLEFLAGS
  • CONST_D3DCONST
  • CONST_D3DCREATEFLAGS
  • CONST_D3DCUBEMAP_FACES
  • CONST_D3DCULL
  • CONST_D3DCURSORCAPSFLAGS
  • CONST_D3DDEBUGMONITORTOKENS
  • CONST_D3DDEVCAPSFLAGS
  • CONST_D3DDEVTYPE
  • CONST_D3DERR
  • CONST_D3DFILLMODE
  • CONST_D3DFOGMODE
  • CONST_D3DFORMAT
  • CONST_D3DFVFCAPSFLAGS
  • CONST_D3DFVFFLAGS
  • CONST_D3DFVFTEXTUREFORMATS
  • CONST_D3DLIGHTTYPE
  • CONST_D3DLINECAPS
  • CONST_D3DLOCKFLAGS
  • CONST_D3DMATERIALCOLORSOURCE
  • CONST_D3DMULTISAMPLE_TYPE
  • CONST_D3DORDERTYPE
  • CONST_D3DPATCHEDGESTYLE
  • CONST_D3DPBLENDCAPSFLAGS
  • CONST_D3DPCMPCAPSFLAGS
  • CONST_D3DPMISCCAPSFLAGS
  • CONST_D3DPOOL
  • CONST_D3DPRASTERCAPSFLAGS
  • CONST_D3DPRESENT_INTERVAL_FLAGS
  • CONST_D3DPRESENT_RATE_FLAGS
  • CONST_D3DPRIMITIVETYPE
  • CONST_D3DPSHADECAPSFLAGS
  • CONST_D3DPTADDRESSCAPSFLAGS
  • CONST_D3DPTEXTURECAPSFLAGS
  • CONST_D3DPTFILTERCAPSFLAGS
  • CONST_D3DRENDERSTATETYPE
  • CONST_D3DRESOURCETYPE
  • CONST_D3DSCPFLAGS
  • CONST_D3DSGRFLAGS
  • CONST_D3DSHADEMODE
  • CONST_D3DSPDFLAGS
  • CONST_D3DSTATEBLOCKTYPE
  • CONST_D3DSTENCILCAPFLAGS
  • CONST_D3DSTENCILOP
  • CONST_D3DSWAPEFFECT
  • CONST_D3DTAFLAGS
  • CONST_D3DTEXOPCAPSFLAGS
  • CONST_D3DTEXTUREADDRESS
  • CONST_D3DTEXTUREFILTERTYPE
  • CONST_D3DTEXTUREOP
  • CONST_D3DTEXTURESTAGESTATETYPE
  • CONST_D3DTEXTURETRANSFORMFLAGS
  • CONST_D3DTRANSFORMSTATETYPE
  • CONST_D3DTSS_TCI_FLAGS
  • CONST_D3DUSAGEFLAGS
  • CONST_D3DVERTEXBLENDFLAGS
  • CONST_D3DVTXPCAPSFLAGS
  • CONST_D3DWRAPBIAS
  • CONST_D3DWRAPFLAGS
  • CONST_D3DZBUFFERTYPE


CONST_D3DBACKBUFFERTYPE

Defines constants that describe the type of back buffer.

Enum CONST_D3DBACKBUFFERTYPE
    D3DBACKBUFFER_TYPE_MONO  = 0
    D3DBACKBUFFER_TYPE_LEFT  = 1
    D3DBACKBUFFER_TYPE_RIGHT = 2
End Enum

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.

Remarks

Note that stereo view in not supported in DirectX 8.0, so the D3DBACKBUFFER_TYPE_LEFT and D3DBACKBUFFER_TYPE_RIGHT values of this enumeration are not used by Direct3D.

See Also

Direct3DDevice8.GetBackBuffer, Direct3DSwapChain8.GetBackBuffer


CONST_D3DBASISTYPE

Defines the basis type of a high-order surface.

Enum CONST_D3DBASISTYPE
    D3DBASIS_BEZIER      = 0
    D3DBASIS_BSPLINE     = 1
    D3DBASIS_INTERPOLATE = 2
End Enum

Constants

D3DBASIS_BEZIER
Input vertices are treated as a series of bézier patches. The number of vertices specified must be divisible by 3 + 1. 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 2 less than the number of apertures in that direction. In general, the generated surface does not contain the control vertices specified.
D3DBASIS_INTERPOLATE
An interpolating basis defines the surface so that the surface goes through all the input vertices specified.

Remarks

The members of D3DBASISTYPE specify the formulation to be used in evaluating the high-order surface primitive during tessellation.

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO


CONST_D3DBLEND

Defines the supported blend mode.

Enum CONST_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
End Enum

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); f = min(As, 1-Ad).
D3DBLEND_BOTHSRCALPHA
Not supported.
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.

Remarks

In the member descriptions above, the RGBA values of the source and destination are indicated by the subscripts s and d.

These flags are used to set the value of the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states for the CONST_D3DRENDERSTATETYPE enumeration.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DBLENDOP

Defines the supported blend operations.

Enum CONST_D3DBLENDOP
    D3DBLENDOP_ADD         = 1
    D3DBLENDOP_SUBTRACT    = 2
    D3DBLENDOP_REVSUBTRACT = 3
    D3DBLENDOP_MIN         = 4
    D3DBLENDOP_MAX         = 5
End Enum

Constants

D3DBLENDOP_ADD
Adds the destination to the source.

Result = Source + Destination

D3DBLENDOP_SUBTRACT
Subtract the destination subtracted from the source.

Result = Source - Destination

D3DBLENDOP_REVSUBTRACT
Subtract the source from the destination.

Result = Destination - Source

D3DBLENDOP_MIN
Return the minimum of the source and destination.

Result = MIN(Source, Destination)

D3DBLENDOP_MAX
Return the maximum of the source and destination.

Result = MAX(Source, Destination)

Remarks

This enumerated type defines values used by the D3DRS_BLENDOP render state.

See Also

D3DCAPS8, CONST_D3DRENDERSTATETYPE


CONST_D3DCAPS2FLAGS

Defines driver-specific capabilities.

Enum CONST_D3DCAPS2FLAGS
    D3DCAPS2_NO2DDURING3DSCENE =        2
    D3DCAPS2_FULLSCREENGAMMA   =   131072 (&H20000)
    D3DCAPS2_CANRENDERWINDOWED =   524288 (&H80000)
    D3DCAPS2_CANCALIBRATEGAMMA =  1048576 (&H100000)
    D3DCAPS2_RESERVED          = 33554432 (&H2000000)
End Enum

Constants

D3DCAPS2_NO2DDURING3DSCENE
When the D3DCAPS2_NO2DDURING3DSCENE capability is set by the driver, it means that 2-D operations cannot be performed in between calls to Direct3DDevice8.BeginScene and Direct3DDevice8.EndScene.

Typically, this capability is set by hardware that partitions the scene and then renders each partition in sequence. The partitioning is performed in the driver, and the hardware will contain a small color and depth buffer that corresponds to the size of the image partition. On this type of rendering hardware, it is typical that once each part of the image is rendered, the data in the color buffers are written to video memory and the contents of the depth-buffer are discarded. Also, note that 3-D rendering does not start until EndScene is encountered. Then, the scene is processed in regions. As such, the processing order cannot be guaranteed. For example, the first region, typically the upper left corner of the window, that is processed may include the last triangle in the frame. To contrast this with more traditional graphics systems, in the typical system each command is processed sequentially in the order that it was sent. The 2-D operations are implied to occur at some fixed point in the processing. In the systems that set D3DCAPS2_NO2DDURING3DSCENE the processing order is not guaranteed, so 2-D operations that are encountered during 3-D rendering may be discarded by the display adapter.

In general, it is recommended that 2-D operations be performed outside of a BeginScene and EndScene pair. If 2-D operations are to be performed between a BeginScene and EndScene pair, then it is necessary to check the D3DCAPS2_NO2DDURING3DSCENE capability. If it is set, the application must expect that any 2-D operation that occurs between BeginScene and EndScene will be discarded. For more information on writing applications for systems that set D3DCAPS2_NO2DDURING3DSCENE, see Remarks.

D3DCAPS2_FULLSCREENGAMMA
The driver supports dynamic gamma ramp adjustment in full-screen mode.
D3DCAPS2_CANRENDERWINDOWED
The driver is capable of rendering in windowed mode.
D3DCAPS2_CANCALIBRATEGAMMA
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 the Direct3DDevice8.SetGammaRamp method. Calibrating gamma ramps incurs some processing overhead and should not be used frequently.
D3DCAPS2_RESERVED
Reserved. Do not use.

Remarks

These flags may be combined and present in the Caps2 member of D3DCAPS8.

For systems that set the D3DCAPS2_NO2DDURING3DSCENE capability flag, performance problems may occur if you use a texture and then modify it during a scene. This is true on all hardware, but it is more severe on hardware that exposes the D3DCAPS2_NO2DDURING3DSCENE capability. If D3DCAPS2_NO2DDURING3DSCENE is present on the hardware, application-based texture management should ensure that no texture used in the current BeginScene and EndScene block is evicted unless absolutely necessary.

In the case of extremely high texture usage within a scene (that is, where you modify a texture that you have used in the scene and there is no spare texture memory available), the results are undefined. For such systems, the contents of the z buffer become invalid at EndScene. Applications should not call Direct3DDevice8.CopyRects to or from the back buffer on this type of hardware inside a BeginScene and 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 and EndScene pair.

See Also

D3DCAPS8


CONST_D3DCAPSFLAGS

Defines driver-specific capabilities.

Enum CONST_D3DCAPSFLAGS
    D3DCAPS_READ_SCANLINE = 131072 (&H20000)
End Enum

Constants

D3DCAPS_READ_SCANLINE
Display hardware is capable of returning the current scan line.

Remarks

This flag may be present in the Caps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DCLEARFLAGS

Defines constants that indicate which surface should be cleared.

Enum CONST_D3DCLEARFLAGS
    D3DCLEAR_TARGET  = 1
    D3DCLEAR_ZBUFFER = 2
    D3DCLEAR_STENCIL = 4
End Enum

Constants

D3DCLEAR_TARGET
Clear the render target.
D3DCLEAR_ZBUFFER
Clear the depth buffer.
D3DCLEAR_STENCIL
Clear the stencil buffer.

See Also

Direct3DDevice8.Clear


CONST_D3DCLIPFLAGS

Defines the clip status.

Enum CONST_D3DCLIPFLAGS
    D3DCS_LEFT   =    1
    D3DCS_RIGHT  =    2
    D3DCS_TOP    =    4
    D3DCS_BOTTOM =    8
    D3DCS_FRONT  =   16 (&H10)
    D3DCS_BACK   =   32 (&H20)
    D3DCS_PLANE0 =   64 (&H40)
    D3DCS_PLANE1 =  128 (&H80)
    D3DCS_PLANE2 =  256 (&H100)
    D3DCS_PLANE3 =  512 (&H200)
    D3DCS_PLANE4 = 1024 (&H400)
    D3DCS_PLANE5 = 2048 (&H800)
    D3DCS_ALL    = 4095 (&HFFF)
End Enum

Constants

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 through D3DCS_PLANE5
Application-defined clipping planes.
D3DCS_ALL
Combination of all clip flags.

Remarks

These flags may be combined and present in the ClipUnion and ClipIntersection member of D3DCLIPSTATUS8.

See Also

D3DCLIPSTATUS8


CONST_D3DCLIPPLANEFLAGS

Defines constants that enable user-defined clipping planes.

Enum CONST_D3DCLIPPLANEFLAGS
    D3DCLIPPLANE0 =  1
    D3DCLIPPLANE1 =  2
    D3DCLIPPLANE2 =  4
    D3DCLIPPLANE3 =  8
    D3DCLIPPLANE4 = 16 (&H10)
    D3DCLIPPLANE5 = 32 (&H20)
End Enum

Constants

D3DCLIPPLANE0 through D3DCLIPPLANE5
Enable the clipping plane, or planes, at the corresponding index ( 0 through 5). These values can be combined to simultaneously enable multiple clipping planes.

Remarks

These flags are used to set the value of the D3DRS_CLIPPLANEENABLE render state for the CONST_D3DRENDERSTATETYPE enumeration.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DCMPFUNC

Defines supported compare functions.

Enum CONST_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
End Enum

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.

Remarks

These flags are used to set the value of the D3DRS_ZFUNC, D3DRS_ALPHAFUNC, and D3DRS_STENCILFUNC render states for the CONST_D3DRENDERSTATETYPE enumeration.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DCOLORWRITEENABLEFLAGS

Defines color channels for updating during 3-D rendering.

Enum CONST_D3DCOLORWRITEENABLEFLAGS
    D3DCOLORWRITEENABLED_RED   = 1
    D3DCOLORWRITEENABLED_GREEN = 2
    D3DCOLORWRITEENABLED_BLUE  = 4
    D3DCOLORWRITEENABLED_ALPHA = 8
End Enum

Constants

D3DCOLORWRITEENABLED_RED
Specifies the red color channel.
D3DCOLORWRITEENABLED_GREEN
Specifies the green color channel.
D3DCOLORWRITEENABLED_BLUE
Specifies the blue color channel.
D3DCOLORWRITEENABLED_ALPHA
Specifies the alpha color channel.

Remarks

These flags are used to set the value of the D3DRS_COLORWRITEENABLE render state for the CONST_D3DRENDERSTATETYPE enumeration.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DCONST

Defines miscellaneous constants used by Microsoft® Direct3D®.

Enum CONST_D3DCONST
    D3D_OK                             =        0
    D3DADAPTER_DEFAULT                 =        0
    D3DCURSOR_IMMEDIATE_UPDATE         =        1
    D3DENUM_HOST_ADAPTER               =        1
    D3DPRESENTFLAG_LOCKABLE_BACKBUFFER =        1
    D3DPV_DONOTCOPYDATA                =        1
    D3DENUM_NO_WHQL_LEVEL              =        2
    D3DPRESENT_BACK_BUFFERS_MAX        =        3
    VALID_D3DENUM_FLAGS                =        3
    D3DMAXNUMPRIMITIVES                =    65535 (&HFFFF)
    D3DMAXNUMVERTICES                  =    65535 (&HFFFF)
    D3DCURRENT_DISPLAY_MODE            = 15728639 (&HEFFFFF)
End Enum

Constants

D3D_OK
Success code for compatibility with some methods that return error codes rather than setting Err.Number.
D3DADAPTER_DEFAULT
The primary display adapter.
D3DCURSOR_IMMEDIATE_UPDATE
Update cursor at the refresh rate.
D3DENUM_HOST_ADAPTER
Not documented for this release.
D3DPRESENTFLAG_LOCKABLE_BACKBUFFER
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 at Direct3D8.CreateDevice and Direct3DDevice8.Reset time. Lockable back buffers incur a performance cost on some graphics hardware configurations.

Performing a lock operation (or using Direct3DDevice8.CopyRects to read/write) on the lockable back-buffer will decrease performance on many cards. In this case, you should consider using textured triangles to move data to the back buffer.

D3DPV_DONOTCOPYDATA
Prevents the system from copying vertex data not affected by the vertex operation into the destination buffer.
D3DENUM_NO_WHQL_LEVEL
Forces the WHQLLevel member of the D3DADAPTER_IDENTIFIER8 type to be zero, meaning that no information is returned for the WHQL certification date. Setting this flag will avoid the one or two second time penalty incurred to determine the WHQL certification date.
D3DPRESENT_BACK_BUFFERS_MAX
Maximum number of back-buffers supported.
VALID_D3DENUM_FLAGS
Not documented for this release.
D3DMAXNUMPRIMITIVES
Maximum number of primitives a user can pass to any Direct3D drawing method.
D3DMAXNUMVERTICES
Maximum number of vertices user can pass to any Direct3D drawing function or vertex buffer creation method.
D3DCURRENT_DISPLAY_MODE
Denotes the current desktop display mode on an adapter.

See Also

Direct3DDevice8.SetCursorPosition


CONST_D3DCREATEFLAGS

Defines Microsoft® Direct3D® device creation flags.

Enum CONST_D3DCREATEFLAGS
    D3DCREATE_FPU_PRESERVE              = 2
    D3DCREATE_MULTITHREADED             = 4
    D3DCREATE_PUREDEVICE                = 16 (&H10)
    D3DCREATE_SOFTWARE_VERTEXPROCESSING = 32 (&H20)
    D3DCREATE_HARDWARE_VERTEXPROCESSING = 64 (&H40)
    D3DCREATE_MIXED_VERTEXPROCESSING    = 128 (&H80)
End Enum

Constants

D3DCREATE_FPU_PRESERVE
Indicates that the application needs either double precision FPU or FPU exceptions enabled. Direct3D sets the FPU state each time it is called. Setting the flag will reduce Direct3D performance.
D3DCREATE_MULTITHREADED
Indicates that the application requests Direct3D to be multithread safe. This makes Direct3D take its global critical section more frequently, which can degrade performance.
D3DCREATE_PUREDEVICE
Specifies hardware rasterization, transform, lighting, and shading. This flag should be specified only when D3DCREATE_HARDWARE_VERTEXPROCESSING is also specified.
D3DCREATE_SOFTWARE_VERTEXPROCESSING
Specifies software vertex processing. See Remarks.
D3DCREATE_HARDWARE_VERTEXPROCESSING
Specifies hardware vertex processing. See Remarks.
D3DCREATE_MIXED_VERTEXPROCESSING
Specifies mixed (both software and hardware) vertex processing. See Remarks.

Remarks

Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and that at least one of these vertex processing flags must be specified when calling Direct3D8.CreateDevice.

See Also

Direct3D8.CreateDevice


CONST_D3DCUBEMAP_FACES

Defines the faces of a cubemap.

Enum CONST_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
End Enum

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.

See Also

Direct3DCubeTexture8.AddDirtyRect, Direct3DCubeTexture8.GetCubeMapSurface, Direct3DCubeTexture8.LockRect, Direct3DCubeTexture8.UnlockRect


CONST_D3DCULL

Defines the supported culling modes.

Enum CONST_D3DCULL
    D3DCULL_NONE = 1
    D3DCULL_CW   = 2
    D3DCULL_CCW  = 3
End Enum

Constants

D3DCULL_NONE
Do not cull back faces.
D3DCULL_CW
Cull back faces with clockwise vertices.
D3DCULL_CCW
Cull back faces with counterclockwise vertices.

Remarks

The values in this enumerated type are used to set the value of the D3DRS_CULLMODE render state for the CONST_D3DRENDERSTATETYPE enumeration.

The culling modes define how back faces are culled when rendering a geometry.

See Also

D3DCAPS8, CONST_D3DRENDERSTATETYPE


CONST_D3DCURSORCAPSFLAGS

Defines cursor capabilities.

Enum CONST_D3DCURSORCAPSFLAGS
    D3DCURSORCAPS_COLOR   = 1
    D3DCURSORCAPS_LOWRES  = 2
End Enum

Constants

D3DCURSORCAPS_COLOR
A two-color black-and-white cursor is supported in hardware.
D3DCURSORCAPS_LOWRES
A full-color cursor is supported in hardware.

Remarks

Microsoft® Direct3D® does not define alpha-blending cursor capabilities.

See Also

D3DCAPS8


CONST_D3DDEBUGMONITORTOKENS

Defines the debug monitor tokens.

Enum CONST_D3DDEBUGMONITORTOKENS
    D3DDMT_ENABLE  = 0
    D3DDMT_DISABLE = 1
End Enum

Constants

D3DDMT_ENABLE
Enable the debug monitor.
D3DDMT_DISABLE
Disable the debug monitor.

Remarks

The values in this enumerated type are used by the D3DRS_DEBUGMONITORTOKEN render state and are relevant only for debug builds.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DDEVCAPSFLAGS

Defines the capabilities of the device.

Enum CONST_D3DDEVCAPSFLAGS
    D3DDEVCAPS_EXECUTESYSTEMMEMORY     =       16 (&H10)
    D3DDEVCAPS_EXECUTEVIDEOMEMORY      =       32 (&H20)
    D3DDEVCAPS_TLVERTEXSYSTEMMEMORY    =       64 (&H40)
    D3DDEVCAPS_TLVERTEXVIDEOMEMORY     =      128 (&H80)
    D3DDEVCAPS_TEXTURESYSTEMMEMORY     =      256 (&H100)
    D3DDEVCAPS_TEXTUREVIDEOMEMORY      =      512 (&H200)
    D3DDEVCAPS_DRAWPRIMITIVES2         =     8192 (&H2000)
    D3DDEVCAPS_DRAWPRIMTLVERTEX        =     1024 (&H400)
    D3DDEVCAPS_CANRENDERAFTERFLIP      =     2048 (&H800)
    D3DDEVCAPS_TEXTURENONLOCALVIDMEM   =     4096 (&H1000)
    D3DDEVCAPS_SEPARATETEXTUREMEMORIES =    16384 (&H4000)
    D3DDEVCAPS_DRAWPRIMITIVES2EX       =    32768 (&H8000)
    D3DDEVCAPS_HWTRANSFORMANDLIGHT     =    65536 (&H10000)
    D3DDEVCAPS_CANBLTSYSTONONLOCAL     =   131072 (&H20000)
    D3DDEVCAPS_HWRASTERIZATION         =   524288 (&H80000)
    D3DDEVCAPS_PUREDEVICE              =  1048576 (&H100000)
    D3DDEVCAPS_QUINTICRTPATCHES        =  2097152 (&H200000)
    D3DDEVCAPS_RTPATCHES               =  4194304 (&H400000)
    D3DDEVCAPS_RTPATCHHANDLEZERO       =  8388608 (&H800000)
    D3DDEVCAPS_NPATCHES                = 16777216 (&H1000000)
End Enum

Constants

D3DDEVCAPS_EXECUTESYSTEMMEMORY
Device can use execute buffers from system memory.
D3DDEVCAPS_EXECUTEVIDEOMEMORY
Device can use execute buffers from video 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.
D3DDEVCAPS_TEXTURESYSTEMMEMORY
Device can retrieve textures from system memory.
D3DDEVCAPS_TEXTUREVIDEOMEMORY
Device can retrieve textures from device memory.
D3DDEVCAPS_DRAWPRIMITIVES2
Not documented for this release.
D3DDEVCAPS_DRAWPRIMTLVERTEX
Device exports a DrawPrimitive-aware hardware abstraction layer (HAL).
D3DDEVCAPS_CANRENDERAFTERFLIP
Device can queue rendering commands after a page flip. Applications do not change their behavior if this flag is set; this capability simply means that the device is relatively fast.
D3DDEVCAPS_TEXTURENONLOCALVIDMEM
Device can retrieve textures from nonlocal video memory.
D3DDEVCAPS_SEPARATETEXTUREMEMORIES
Device is texturing from separate memory pools.
D3DDEVCAPS_DRAWPRIMITIVES2EX
Not documented for this release.
D3DDEVCAPS_HWTRANSFORMANDLIGHT
Device can support transformation and lighting in hardware.
D3DDEVCAPS_CANBLTSYSTONONLOCAL
Device supports blits from system-memory textures to nonlocal video-memory textures.
D3DDEVCAPS_HWRASTERIZATION
Device has hardware acceleration for scene rasterization.
D3DDEVCAPS_PUREDEVICE
Device can support rasterization, transform, lighting, and shading in hardware.
D3DDEVCAPS_QUINTICRTPATCHES
Device supports quintic béziers and B-splines.
D3DDEVCAPS_RTPATCHES
Device supports high-order surfaces.
D3DDEVCAPS_RTPATCHHANDLEZERO
Indicates that high-order surfaces can be drawn efficiently using a handle value of 0.
D3DDEVCAPS_NPATCHES
Device supports N patches.

Remarks

These flags may be combined and present in the DevCaps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DDEVTYPE

Defines device types.

Enum CONST_D3DDEVTYPE
    D3DDEVTYPE_HAL       = 1
    D3DDEVTYPE_REF       = 2
    D3DDEVTYPE_SW        = 3
End Enum

Constants

D3DDEVTYPE_HAL
Hardware rasterization and shading with software, hardware, or mixed transform and lighting.
D3DDEVTYPE_REF
Microsoft® Direct3D® features are implemented in software.
D3DDEVTYPE_SW
Not supported.

See Also

Direct3D8.CheckDeviceFormat, Direct3D8.CheckDeviceMultiSampleType, Direct3D8.CheckDeviceType, Direct3D8.CreateDevice, Direct3D8.GetDeviceCaps, D3DDEVICE_CREATION_PARAMETERS


CONST_D3DERR

Defines error codes raised by the system. For descriptions of these error codes, see Error Codes.


CONST_D3DFILLMODE

Defines constants that describe the fill mode.

Enum CONST_D3DFILLMODE
    D3DFILL_POINT     = 1
    D3DFILL_WIREFRAME = 2
    D3DFILL_SOLID     = 3
End Enum

Constants

D3DFILL_POINT
Fill points.
D3DFILL_WIREFRAME
Fill wireframes. This fill mode currently does not work for clipped primitives when you use the DrawPrimitive methods.
D3DFILL_SOLID
Fill solids.

Remarks

These flags are used to set the value of the D3DRS_FILLMODE render state for the CONST_D3DRENDERSTATETYPE enumeration.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DFOGMODE

Defines constants that describe the fog mode.

Enum CONST_D3DFOGMODE
    D3DFOG_NONE   = 0
    D3DFOG_EXP    = 1
    D3DFOG_EXP2   = 2
    D3DFOG_LINEAR = 3
End Enum

Constants

D3DFOG_NONE
No fog effect.
D3DFOG_EXP
Fog effect intensifies exponentially, according to the following formula.

D3DFOG_EXP2
Fog effect intensifies exponentially with the square of the distance, according to the following formula.

D3DFOG_LINEAR
Fog effect intensifies linearly between the start and end points, according to the following formula.

This is the only fog mode currently supported.

Remarks

These flags are used to set the value of the D3DRS_FOGTABLEMODE and D3DRS_FOGVERTEXMODE render states for the CONST_D3DRENDERSTATETYPE enumeration.

Fog can be considered a measure of visibility—the lower the fog value produced by a fog equation, the less visible an object is.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DFORMAT

Defines the various types of surface formats.

Enum CONST_D3DFORMAT
    D3DFMT_UNKNOWN       =   0
    D3DFMT_R8G8B8        =  20 (&H14)
    D3DFMT_A8R8G8B8      =  21 (&H15)
    D3DFMT_X8R8G8B8      =  22 (&H16)
    D3DFMT_R5G6B5        =  23 (&H17)
    D3DFMT_X1R5G5B5      =  24 (&H18)
    D3DFMT_A1R5G5B5      =  25 (&H19)
    D3DFMT_A4R4G4B4      =  26 (&H1A)
    D3DFMT_R3G3B2        =  27 (&H1B)
    D3DFMT_A8            =  28 (&H1C)
    D3DFMT_A8R3G3B2      =  29 (&H1D)
    D3DFMT_X4R4G4B4      =  30 (&H1E)
    D3DFMT_A8P8          =  40 (&H28)
    D3DFMT_P8            =  41 (&H29)
    D3DFMT_L8            =  50 (&H32)
    D3DFMT_A8L8          =  51 (&H33)
    D3DFMT_A4L4          =  52 (&H34)
    D3DFMT_V8U8          =  60 (&H3C)
    D3DFMT_L6V5U5        =  61 (&H3D)
    D3DFMT_X8L8V8U8      =  62 (&H3E)
    D3DFMT_Q8W8V8U8      =  63 (&H3F)
    D3DFMT_V16U16        =  64 (&H40)
    D3DFMT_W11V11U10     =  65 (&H41)
    D3DFMT_UYVY          = 1498831189 (&H59565955)
    D3DFMT_YUY2          =  844715353 (&H32595559)
    D3DFMT_DXT1          =  827611204 (&H31545844)
    D3DFMT_DXT2          =  844388420 (&H32545844)
    D3DFMT_DXT3          =  861165636 (&H33545844)
    D3DFMT_DXT4          =  877942852 (&H34545844)
    D3DFMT_DXT5          =  894720068 (&H35545844)
    D3DFMT_D16_LOCKABLE  =  70 (&H46)
    D3DFMT_D32           =  71 (&H47)
    D3DFMT_D15S1         =  73 (&H49)
    D3DFMT_D24S8         =  75 (&H4B)
    D3DFMT_D16           =  80 (&H50)
    D3DFMT_D24X8         =  77 (&H4D)
    D3DFMT_D24X4S4       =  79 (&H4F)
    D3DFMT_VERTEXDATA    = 100 (&H64)
    D3DFMT_INDEX16       = 101 (&H65)
    D3DFMT_INDEX32       = 102 (&H66)
End Enum

Constants

D3DFMT_UNKNOWN
Surface format is unknown.
D3DFMT_R8G8B8
24-bit RGB pixel format.
D3DFMT_A8R8G8B8
32-bit ARGB pixel format with alpha.
D3DFMT_X8R8G8B8
32-bit RGB pixel format where 8 bits are reserved for each color.
D3DFMT_R5G6B5
16-bit RGB pixel format.
D3DFMT_X1R5G5B5
16-bit pixel format where 5 bits are reserved for each color.
D3DFMT_A1R5G5B5
16-bit pixel format where 5 bits are reserved for each color and 1 bit is reserved for alpha (transparent texel).
D3DFMT_A4R4G4B4
16-bit ARGB pixel format.
D3DFMT_R3G3B2
8-bit RGB texture format.
D3DFMT_A8
8-bit alpha only.
D3DFMT_A8R3G3B2
16-bit ARGB texture format.
D3DFMT_X4R4G4B4
16-bit RGB pixel format where 4 bits are reserved for each color.
D3DFMT_A8P8
Surface is 8-bit color indexed with 8 bits of alpha.
D3DFMT_P8
Surface is 8-bit color indexed.
D3DFMT_L8
8-bit luminance only.
D3DFMT_A8L8
16-bit alpha luminance.
D3DFMT_A4L4
8-bit alpha luminance.
D3DFMT_V8U8
16-bit bump-map format.
D3DFMT_L6V5U5
16-bit bump-map format with luminance.
D3DFMT_X8L8V8U8
32-bit bump-map format with luminance where 8 bits are reserved for each element.
D3DFMT_Q8W8V8U8
32-bit bump-map format.
D3DFMT_V16U16
32-bit bump-map format.
D3DFMT_W11V11U10
32-bit bump-map format.
D3DFMT_UYVY
UYVY format (PC98 compliance).
D3DFMT_YUY2
YUY2 format (PC98 compliance).
D3DFMT_DXT1
DXT1 compression texture format.
D3DFMT_DXT2
DXT2 compression texture format.
D3DFMT_DXT3
DXT3 compression texture format.
D3DFMT_DXT4
DXT4 compression texture format.
D3DFMT_DXT5
DXT5 compression texture format.
D3DFMT_D16_LOCKABLE
16-bit z-buffer bit depth. This is an application-lockable surface format.
D3DFMT_D32
32-bit z-buffer bit depth.
D3DFMT_D15S1
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
32-bit z-buffer bit depth where 24 bits are reserved for the depth channel and 8 bits are reserved for the stencil channel.
D3DFMT_D16
16-bit z-buffer bit depth.
D3DFMT_D24X8
32-bit z-buffer bit depth where 24 bits are reserved for the depth channel.
D3DFMT_D24X4S4
32-bit z-buffer bit depth where 24 bits are reserved for the depth channel and 4 bits are reserved for the stencil channel.
D3DFMT_VERTEXDATA
Describes a vertex buffer surface.
D3DFMT_INDEX16
16-bit index buffer bit depth.
D3DFMT_INDEX32
32-bit index buffer bit depth.

Remarks

Note that render target formats are restricted to D3DFMT_X1R5G5B5, D3DFMT_R5G6B5, D3DFMT_X8R8G8B8, and D3DFMT_A8R8G8B8.

The order of the bits is from the most significant bit (MSB) first, so D3DFMT_A8L8 indicates that the high byte of this two-byte format is alpha.

All depth-stencil formats except D3DFMT_D16_LOCKABLE indicate no particular bit ordering per pixel. They are not application-lockable, and the driver is allowed to consume more than the indicated number of bits per depth channel (but not stencil channel).

Pixel formats are denoted by opaque Long identifiers. The format of these Longs has been chosen to enable the expression of IHV-defined extension formats, and also to include the well-established FOURCC method. The set of formats understood by the Microsoft® Direct3D® run time is defined by D3DFORMAT.

Note that IHV-supplied formats and many FOURCC codes are not listed in the D3DFORMAT enumeration. The formats in this enumeration are unique in that they are sanctioned by the run time, meaning that the reference rasterizer will operate on all these types. The IHV-supplied formats will be supported by the individual IHVs on a card-by-card basis.

See Also

Direct3D8.CheckDeviceFormat


CONST_D3DFVFCAPSFLAGS

Defines flexible vertex format capabilities.

Enum CONST_D3DFVFCAPSFLAGS
    D3DFVFCAPS_TEXCOORDCOUNTMASK  =   65535 (&HFFFF)
    D3DFVFCAPS_DONOTSTRIPELEMENTS =  524288 (&H80000)
    D3DFVFCAPS_PSIZE              = 1048576 (&H100000)
End Enum

Constants

D3DFVFCAPS_TEXCOORDCOUNTMASK
Masks the low 16 bits of the FVFCaps member of D3DCAPS8. Set the result to a variable of type Integer to calculate 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 only by using the specified number of texture coordinate sets.)
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
The absence of D3DFVFCAPS_PSIZE indicates that the device does not support D3DFVF_PSIZE for pre-transformed vertices. In this case the base point size always comes from D3DRS_POINTSIZE. This capability applies to fixed-function vertex processing in software only. D3DFVF_PSIZE is always supported when doing software vertex processing.

The output point size written by a vertex shader is always supported, and for vertex shaders any input can contribute to the output point size.

D3DFVF_PSIZE is always supported for post-transformed vertices. For more information on D3DFVF_PSIZE, see flexible vertex format flags.

Remarks

These flags may be combined and present in the FVFCaps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DFVFFLAGS

Defines flexible vertex format flags.

For details, see flexible vertex format flags.


CONST_D3DFVFTEXTUREFORMATS

Defines bit patterns that are used to identify texture coordinate formats within a flexible vertex format description. The members of this enumeration can be combined within a flexible vertex format description by using the OR operator.

Enum CONST_D3DFVFTEXTUREFORMATS
    D3DFVF_TEXTUREFORMAT1  =        3
    D3DFVF_TEXTUREFORMAT2  =        0
    D3DFVF_TEXTUREFORMAT3  =        1
    D3DFVF_TEXTUREFORMAT4  =        2
    D3DFVF_TEXCOORDSIZE1_0 =   196608 (&H30000)
    D3DFVF_TEXCOORDSIZE1_1 =   786432 (&HC0000)
    D3DFVF_TEXCOORDSIZE1_2 =  3145728 (&H300000)
    D3DFVF_TEXCOORDSIZE1_3 = 12582912 (&HC00000)
    D3DFVF_TEXCOORDSIZE2_0 =        0
    D3DFVF_TEXCOORDSIZE2_1 =        0
    D3DFVF_TEXCOORDSIZE2_2 =        0
    D3DFVF_TEXCOORDSIZE2_3 =        0
    D3DFVF_TEXCOORDSIZE3_0 =    65536 (&H10000)
    D3DFVF_TEXCOORDSIZE3_1 =   262144 (&H40000)
    D3DFVF_TEXCOORDSIZE3_2 =  1048576 (&H100000)
    D3DFVF_TEXCOORDSIZE3_3 =  4194304 (&H400000)
    D3DFVF_TEXCOORDSIZE4_0 =   131072 (&H20000)
    D3DFVF_TEXCOORDSIZE4_1 =   524288 (&H80000)
    D3DFVF_TEXCOORDSIZE4_2 =  2097152 (&H200000)
    D3DFVF_TEXCOORDSIZE4_3 =  8388608 (&H800000)
End Enum

Constants

D3DFVF_TEXTUREFORMAT1 to D3DFVF_TEXTUREFORMAT4
Values that can be used to calculate 1-, 2-, 3-, or 4-dimensional bit masks for identifying texture coordinate formats. See Remarks.
D3DFVF_TEXCOORDSIZE1_0 to D3DFVF_TEXCOORDSIZE4_3
These bit patterns specify texture coordinate formats of different sizes on specific vertices. TEXCOORDSIZEm_n specifies that m coordinates are to be associated with the (n+1)th position in the vertex format.

Remarks

D3DFVF_TEXTUREFORMAT1 to D3DFVF_TEXTUREFORMAT4 specify the number of values that define a texture coordinate set. The D3DFVF_TEXTUREFORMAT1 indicates one-dimensional texture coordinates, D3DFVF_TEXTUREFORMAT2 indicates two-dimensional texture coordinates, and so on. The following sample functions show you how to create bit patterns to describe the number of elements used by a particular set of texture coordinates.

'Equivalent to D3DFVF_TEXCOORDSIZE1_coordIndex, specifying that one
'texture coordinate is used for the vertex format specified by coordIndex
Function D3DFVF_TEXCOORDSIZE1(coordIndex As Long) As Long
    D3DFVF_TEXCOORDSIZE1 = D3DFVF_TEXTUREFORMAT1 * 2 ^ ((coordIndex * 2) + 16)
End Function

'Equivalent to D3DFVF_TEXCOORDSIZE1_coordIndex, specifying that two
'texture coordinates are used for the vertex format specified by coordIndex
Function D3DFVF_TEXCOORDSIZE2(coordIndex As Long) As Long
    D3DFVF_TEXCOORDSIZE2 = D3DFVF_TEXTUREFORMAT2
End Function

'Equivalent to D3DFVF_TEXCOORDSIZE1_coordIndex, specifying that three
'texture coordinates are used for the vertex format specified by coordIndex
Function D3DFVF_TEXCOORDSIZE3(coordIndex As Long) As Long
    D3DFVF_TEXCOORDSIZE3 = D3DFVF_TEXTUREFORMAT3 * 2 ^ ((coordIndex * 2) + 16)
End Function

'Equivalent to D3DFVF_TEXCOORDSIZE1_coordIndex, specifying that four
'texture coordinate are used for the vertex format specified by coordIndex
Function D3DFVF_TEXCOORDSIZE4(coordIndex As Long) As Long
    D3DFVF_TEXCOORDSIZE4 = D3DFVF_TEXTUREFORMAT4 * 2 ^ ((coordIndex * 2) + 16)
End Function

See Also

Flexible Vertex Format Flags


CONST_D3DLIGHTTYPE

Defines the light type.

Enum CONST_D3DLIGHTTYPE
    D3DLIGHT_POINT       = 1
    D3DLIGHT_SPOT        = 2
    D3DLIGHT_DIRECTIONAL = 3
End Enum

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 similar 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 D3DLIGHT8 type.
D3DLIGHT_DIRECTIONAL
Light is a directional source. This is equivalent to using a point light source at an infinite distance.

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 expensive.

See Also

D3DLIGHT8


CONST_D3DLINECAPS

Defines locking flags.

Enum CONST_D3DLINECAPS
    D3DLINECAPS_TEXTURE  =  1
    D3DLINECAPS_ZTEST    =  2
    D3DLINECAPS_BLEND=   =  4
    D3DLINECAPS_ALPHACMP =  8
    D3DLINECAPS_FOG      = 16 (&H10)
End Enum

Constants

D3DLINECAPS_TEXTURE
Supports texture-mapping.
D3DLINECAPS_ZTEST
Supports z-buffer comparisons.
D3DLINECAPS_BLEND
Supports source-blending.
D3DLINECAPS_ALPHACMP
Supports alpha-test comparisons.
D3DLINECAPS_FOG
Supports fog.


CONST_D3DLOCKFLAGS

Defines locking flags.

Enum CONST_D3DLOCKFLAGS
    D3DLOCK_READONLY        =    16 (&H10)
    D3DLOCK_NOSYSLOCK       =  2048 (&H800)
    D3DLOCK_NOOVERWRITE     =  4096 (&H1000)
    D3DLOCK_DISCARD         =  8192 (&H2000)
    D3DLOCK_NO_DIRTY_UPDATE = 32768 (&H8000)
End Enum

Constants

D3DLOCK_READONLY
The application will not write to the buffer. This enables some optimizations. D3DLOCK_READONLY cannot be specified with D3DLOCK_DISCARD; nor can it be specified on an index or vertex buffer created with D3DUSAGE_WRITEONLY.
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 flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system

D3DLOCK_NOOVERWRITE
Indicates that no indices or vertices that were referred to in drawing calls since the start of the frame or the last lock without this flag will be modified during the lock. This can enable optimizations only when the application is appending data to the index or vertex buffer. This flag is valid only on buffers created with D3DUSAGE_DYNAMIC.
D3DLOCK_DISCARD
The application overwrites, with a write-only operation, the entire buffer. This enables Direct3D to return a pointer to a new memory area so that dynamic memory access (DMA) and rendering from the old area do not stall. This flag is valid only for index and vertex buffers. This flag is valid only on buffers created with D3DUSAGE_DYNAMIC.
D3DLOCK_NO_DIRTY_UPDATE
By default, a lock on a resource adds a dirty region to that resource. This flag prevents any changes to the dirty state of the resource. Applications should use this flag when they have additional information about the actual set of regions changed during the lock operation. Note that this flag is not valid for vertex and index buffers.


CONST_D3DMATERIALCOLORSOURCE

Defines the location at which a color or color component must be accessed for lighting calculations.

Enum CONST_D3DMATERIALCOLORSOURCE
    D3DMCS_MATERIAL = 0
    D3DMCS_COLOR1   = 1
    D3DMCS_COLOR2   = 2
End Enum

Constants

D3DMCS_MATERIAL
Use the color from the current material.
D3DMCS_COLOR1
Use the diffuse vertex color.
D3DMCS_COLOR2
Use the specular vertex color.

Remarks

These flags are used to set the value of the following render states for the CONST_D3DRENDERSTATETYPE enumeration.

  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DMULTISAMPLE_TYPE

Defines levels of full-scene multisampling that the device can apply.

Enum CONST_D3DMULTISAMPLE_TYPE
    D3DMULTISAMPLE_NONE       =  0
    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 (&H10)
End Enum

Constants

D3DMULTISAMPLE_NONE
No level of full-scene multisampling is available.
D3DMULTISAMPLE_2_SAMPLES through D3DMULTISAMPLE_16_SAMPLES
The level of full-scene multisampling available.

Remarks

In addition to enabling full-scene multisampling at Direct3DDevice8.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.

See Also

Direct3D8.CheckDeviceMultiSampleType, Direct3DDevice8.CreateDepthStencilSurface, Direct3DDevice8.CreateRenderTarget, D3DPRESENT_PARAMETERS, D3DSURFACE_DESC


CONST_D3DORDERTYPE

Defines the order type of a high-order surface.

Enum CONST_D3DORDERTYPE
    D3DORDER_LINEAR    = 1
    D3DORDER_CUBIC     = 3
    D3DORDER_QUINTIC   = 5
End Enum

Constants

D3DORDER_LINEAR
Linear order type.
D3DORDER_CUBIC
Cubic order type.
D3DORDER_QUINTIC
Quintic order type.

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO


CONST_D3DPATCHEDGESTYLE

Defines source-blending capabilities.

Enum CONST_D3DPATCHEDGESTYLE
    D3DPATCHEDGE_DISCRETE = 0,
    D3DPATCHEDGE_CONTINUOUS = 1
End Enum

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 which can be smoothly varied to reduce "popping" artifacts.

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 wire-frame mode). Thus, 4.0 continuous is not the same as 4 discrete.


CONST_D3DPBLENDCAPSFLAGS

Defines source-blending capabilities.

Enum CONST_D3DPBLENDCAPSFLAGS
    D3DPBLENDCAPS_ZERO            =    1
    D3DPBLENDCAPS_ONE             =    2
    D3DPBLENDCAPS_SRCCOLOR        =    4
    D3DPBLENDCAPS_INVSRCCOLOR     =    8
    D3DPBLENDCAPS_SRCALPHA        =   16 (&H10)
    D3DPBLENDCAPS_INVSRCALPHA     =   32 (&H20)
    D3DPBLENDCAPS_DESTALPHA       =   64 (&H40)
    D3DPBLENDCAPS_INVDESTALPHA    =  128 (&H80)
    D3DPBLENDCAPS_DESTCOLOR       =  256 (&H100)
    D3DPBLENDCAPS_INVDESTCOLOR    =  512 (&H200)
    D3DPBLENDCAPS_SRCALPHASAT     = 1024 (&H400)
    D3DPBLENDCAPS_BOTHSRCALPHA    = 2048 (&H800)
    D3DPBLENDCAPS_BOTHINVSRCALPHA = 4096 (&H1000)
End Enum

Constants

D3DPBLENDCAPS_ZERO
Blend factor is (0, 0, 0, 0).
D3DPBLENDCAPS_ONE
Blend factor is (1, 1, 1, 1).
D3DPBLENDCAPS_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DPBLENDCAPS_INVSRCCOLOR
Blend factor is (1–Rd, 1–Gd, 1–Bd, 1–Ad).
D3DPBLENDCAPS_SRCALPHA
Blend factor is (As, As, As, As).
D3DPBLENDCAPS_INVSRCALPHA
Blend factor is (1–As, 1–As, 1–As, 1–As).
D3DPBLENDCAPS_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DPBLENDCAPS_INVDESTALPHA
Blend factor is (1–Ad, 1–Ad, 1–Ad, 1–Ad).
D3DPBLENDCAPS_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DPBLENDCAPS_INVDESTCOLOR
Blend factor is (1–Rd, 1–Gd, 1–Bd, 1–Ad).
D3DPBLENDCAPS_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
D3DPBLENDCAPS_BOTHSRCALPHA
The driver supports the D3DBLEND_BOTHSRCALPHA blend mode. (This blend mode is obsolete. For more information, see CONST_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.

Remarks

The RGBA values of the source and destination are indicated by the subscripts s and d.

The values in this enumeration define the values for the SrcBlendCaps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DPCMPCAPSFLAGS

Defines comparison capabilities.

Enum CONST_D3DPCMPCAPSFLAGS
    D3DPCMPCAPS_NEVER        =   1
    D3DPCMPCAPS_LESS         =   2
    D3DPCMPCAPS_EQUAL        =   4
    D3DPCMPCAPS_LESSEQUAL    =   8
    D3DPCMPCAPS_GREATER      =  16 (&H10)
    D3DPCMPCAPS_NOTEQUAL     =  32 (&H20)
    D3DPCMPCAPS_GREATEREQUAL =  64 (&H40)
    D3DPCMPCAPS_ALWAYS       = 128 (&H80)
End Enum

Constants

D3DPCMPCAPS_NEVER
Always fail the test.
D3DPCMPCAPS_LESS
Pass the test if the new value is less than the current value.
D3DPCMPCAPS_EQUAL
Pass the test if the new value equals the current value.
D3DPCMPCAPS_LESSEQUAL
Pass the test if the new value is less than or equal to the current value.
D3DPCMPCAPS_GREATER
Pass the test if the new value is greater than the current value.
D3DPCMPCAPS_NOTEQUAL
Pass the test if the new value does not equal the current value.
D3DPCMPCAPS_GREATEREQUAL
Pass the test if the new value is greater than or equal to the current value.
D3DPCMPCAPS_ALWAYS
Always pass the test.

Remarks

The values in this enumeration define the supported compare functions for the AlphaCmpCaps and ZCmpCaps members of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DPMISCCAPSFLAGS

Defines general capabilities for a primitive.

Enum CONST_D3DPMISCCAPSFLAGS
    D3DPMISCCAPS_MASKZ                 =    2
    D3DPMISCCAPS_LINEPATTERNREP        =    4
    D3DPMISCCAPS_CULLNONE              =   16 (&H10)
    D3DPMISCCAPS_CULLCW                =   32 (&H20)
    D3DPMISCCAPS_CULLCCW               =   64 (&H40)
    D3DPMISCCAPS_COLORWRITEENABLE      =  128 (&H80)
    D3DPMISCCAPS_CLIPPLANESCALEDPOINTS =  256 (&H100)
    D3DPMISCCAPS_CLIPTLVERTS           =  512 (&H200)
    D3DPMISCCAPS_TSSARGTEMP            = 1024 (&H400)
    D3DPMISCCAPS_BLENDOP               = 2048 (&H800)
End Enum

Constants

D3DPMISCCAPS_MASKZ
The device can enable and disable modification of the depth buffer on pixel operations.
D3DPMISCCAPS_LINEPATTERNREP
The driver can handle values other than 1 in the RepeatFactor member of the D3DLINEPATTERN type. (This applies only to line-drawing primitives.)
D3DPMISCCAPS_CULLNONE
The driver does not perform triangle culling. This corresponds to the D3DCULL_NONE member of the CONST_D3DCULL enumeration.
D3DPMISCCAPS_CULLCW
The driver supports clockwise triangle culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This corresponds to the D3DCULL_CW member of the CONST_D3DCULL enumeration.
D3DPMISCCAPS_CULLCCW
The driver supports counterclockwise culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This corresponds to the D3DCULL_CCW member of the CONST_D3DCULL enumeration.
D3DPMISCCAPS_COLORWRITEENABLE
The device supports per-channel writes for the render target color buffer through the D3DRS_COLORWRITEENABLE state.
D3DPMISCCAPS_CLIPPLANESCALEDPOINTS
Device correctly clips scaled points of size greater than 1.0 to user-defined clipping planes.
D3DPMISCCAPS_CLIPTLVERTS
Device clips post-transformed vertex primitives.
D3DPMISCCAPS_TSSARGTEMP
Device supports D3DTA_TEMP for temporary register.
D3DPMISCCAPS_BLENDOP
Device supports the alpha blending operations defined in the CONST_D3DBLENDOP enumerated type.

Remarks

MiscCaps

The values in this enumeration define the values for the PrimitveMiscCaps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DPOOL

Defines the memory class that holds a resource's buffers.

Enum CONST_D3DPOOL
    D3DPOOL_DEFAULT        = 0
    D3DPOOL_MANAGED        = 1
    D3DPOOL_SYSTEMMEM      = 2
    D3DPOOL_SCRATCH        = 3
End Enum

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_SYTEMMEM and specifies that the resource will be 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 and are therefore not directly accessible. Instead you must use functions such as Direct3DDevice8.CopyRects and Direct3dDevice8.UpdateTexture. 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 Microsoft® Direct3D® runtime, can be locked. Also note that—unlike textures—swapchain back buffers, render targets, vertex buffers, and index buffers can be locked.

When a device becomes lost, resources created using D3DPOOL_DEFAULT must be released before calling Direct3DDevice8.Reset. See Lost Devices for more information.

D3DPOOL_MANAGED
Resources will be 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 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
Memory that is not typically accessible by the 3-D device. This flag 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 they can be used as the source for a Direct3DDevice8.CopyRects or Direct3DDevice8.UpdateTexture operation to a memory resource created with D3DPOOL_DEFAULT.
D3DPOOL_SCRATCH
Resources are placed in system RAM, so you do not need to re-create them 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.

Remarks

Pools cannot be mixed for different objects contained within one resource (mip levels in a mipmap), and once a pool is chosen it cannot be changed.

Applications should use D3DPOOL_MANAGED for most static resources, as this isolates the application from dealing with lost device situations. (Managed resources are restored by the runtime.) This is especially beneficial for UMA systems. Dynamic texture resources can also be a good match for D3DPOOL_MANAGED, in spite of the high frequency at which they change. 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 Direct3DDevice8.UpdateTexture.

See Also

Direct3DDevice8.CreateCubeTexture, Direct3DDevice8.CreateIndexBuffer, Direct3DDevice8.CreateTexture, Direct3DDevice8.CreateVertexBuffer, Direct3DDevice8.CreateVolumeTexture, D3DINDEXBUFFER_DESC, D3DSURFACE_DESC, D3DVERTEXBUFFER_DESC, D3DVOLUME_DESC


CONST_D3DPRASTERCAPSFLAGS

Defines constants that provide information on raster-drawing capabilities.

Enum CONST_D3DPRASTERCAPSFLAGS
    D3DPRASTERCAPS_DITHER                     =       1
    D3DPRASTERCAPS_PAT                        =       8
    D3DPRASTERCAPS_ZTEST                      =      16 (&H10)
    D3DPRASTERCAPS_FOGVERTEX                  =     128 (&H80)
    D3DPRASTERCAPS_FOGTABLE                   =     256 (&H100)
    D3DPRASTERCAPS_ANTIALIASEDGES             =    4096 (&H1000)
    D3DPRASTERCAPS_MIPMAPLODBIAS              =    8192 (&H2000)
    D3DPRASTERCAPS_ZBIAS                      =   16384 (&H4000)
    D3DPRASTERCAPS_ZBUFFERLESSHSR             =   32768 (&H8000)
    D3DPRASTERCAPS_FOGRANGE                   =   65536 (&H10000)
    D3DPRASTERCAPS_ANISOTROPY                 =  131072 (&H20000)
    D3DPRASTERCAPS_WBUFFER                    =  262144 (&H40000)
    D3DPRASTERCAPS_WFOG                       = 1048576 (&H100000)
    D3DPRASTERCAPS_ZFOG                       = 2097152 (&H200000)
    D3DPRASTERCAPS_COLORPERSPECTIVE           = 4194304 (&H400000)
    D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE      = 8388608 (&H800000)
End Enum

Constants

D3DPRASTERCAPS_DITHER
The device can dither to improve color resolution.
D3DPRASTERCAPS_PAT
The driver can perform patterned drawing lines or fills with D3DRS_LINEPATTERN for the primitive being queried.
D3DPRASTERCAPS_ZTEST
The device can perform z-test operations. This effectively renders a primitive and indicates whether any z pixels have been rendered.
D3DPRASTERCAPS_FOGVERTEX
The device calculates the fog value during the lighting operation, places the value into the alpha component of the specular member of the D3DTLVERTEX type and interpolates the fog value during rasterization.
D3DPRASTERCAPS_FOGTABLE
The 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_ANTIALIASEDGES
The device can antialias lines forming the convex outline of objects. For more information, see D3DRS_EDGEANTIALIAS in the CONST_D3DRENDERSTATETYPE enumeration.
D3DPRASTERCAPS_MIPMAPLODBIAS
The device supports level-of-detail (LOD) 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 LOD bias in mipmaps, see D3DTSS_MIPMAPLODBIAS.
D3DPRASTERCAPS_ZBIAS
The device supports z-bias values. These are integer values assigned to polygons that enable physically coplanar polygons to appear separate. For more information, see D3DRS_ZBIAS in the CONST_D3DRENDERSTATETYPE enumeration.
D3DPRASTERCAPS_ZBUFFERLESSHSR
The 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 1).

D3DPRASTERCAPS_FOGRANGE
The 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. For more information, see Range-Based Fog.
D3DPRASTERCAPS_ANISOTROPY
The device supports anisotropic filtering.
D3DPRASTERCAPS_WBUFFER
The device supports depth buffering using w. For more information, see Depth Buffers.
D3DPRASTERCAPS_WFOG
The 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_ZFOG
The device supports z-based fog.
D3DPRASTERCAPS_COLORPERSPECTIVE
The device iterates colors perspective correct.
D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE
The device provides limited multisample support through a stretch-blt implementation. When this capability is set, D3DRS_MULTISAMPLEANTIALIAS cannot be turned on and off in the middle of a scene. Multisample masking cannot be performed if this flag is set.

Remarks

These flags may be combined and present in the RasterCaps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DPRESENT_INTERVAL_FLAGS

Maximum rate at which the swap chain's back buffers may be presented.

Enum CONST_D3DPRESENT_INTERVAL_FLAGS
    D3DPRESENT_INTERVAL_DEFAULT   =            0
    D3DPRESENT_INTERVAL_ONE       =            1
    D3DPRESENT_INTERVAL_TWO       =            2
    D3DPRESENT_INTERVAL_THREE     =            4
    D3DPRESENT_INTERVAL_FOUR      =            8
    D3DPRESENT_INTERVAL_IMMEDIATE =  -2147483648 (&H80000000)
End Enum

Constants

D3DPRESENT_INTERVAL_DEFAULT
The driver supports the default presentation interval.
D3DPRESENT_INTERVAL_ONE
The driver will wait for the vertical retrace period. Present operations will not be affected more frequently than the screen refresh.
D3DPRESENT_INTERVAL_TWO
The driver will wait for the vertical retrace period. Present operations will not be affected more frequently than every second screen refresh.
D3DPRESENT_INTERVAL_THREE
The driver will wait for the vertical retrace period. Present operations will not be affected more frequently than every third screen refresh.
D3DPRESENT_INTERVAL_FOUR
The driver will wait for the vertical retrace period. Present operations will not be affected more frequently than every fourth screen refresh.
D3DPRESENT_INTERVAL_IMMEDIATE
Present operations may be affected immediately. The driver will not wait for the vertical retrace period.

Remarks

For a windowed swap chain, this value must be D3DPRESENT_INTERVAL_DEFAULT (0). For a full-screen swap chain it may be D3DPRESENT_INTERVAL_DEFAULT or the value corresponding to exactly one of the flags enumerated in the PresentationIntervals member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DPRESENT_RATE_FLAGS

Defines the maximal rate at which frames can be presented to the output.

Enum CONST_D3DPRESENT_RATE_FLAGS
    D3DPRESENT_RATE_DEFAULT   =          0
    D3DPRESENT_RATE_UNLIMITED = 2147483647 (&H7FFFFFFF)
End Enum

Constants

D3DPRESENT_RATE_UNLIMITED
The presentation rate runs as quickly as the hardware can deliver frames.
D3DPRESENT_RATE_DEFAULT
Microsoft® Direct3D® will choose the presentation rate, or adopt the current rate if windowed.

Remarks

One of these flags may be specified in the FullScreen_RefreshRateInHz member of D3DPRESENT_PARAMETERS.

See Also

D3DPRESENT_PARAMETERS


CONST_D3DPRIMITIVETYPE

Defines the primitives supported by Microsoft® Direct3D®.

Enum CONST_D3DPRIMITIVETYPE
    D3DPT_POINTLIST     = 1
    D3DPT_LINELIST      = 2
    D3DPT_LINESTRIP     = 3
    D3DPT_TRIANGLELIST  = 4
    D3DPT_TRIANGLESTRIP = 5
    D3DPT_TRIANGLEFAN   = 6
End Enum

Constants

D3DPT_POINTLIST
Renders the vertices as a collection of isolated points.
D3DPT_LINELIST
Renders the vertices as a list of isolated straight line segments. Calls using this primitive type fail if the count is less than 2 or is odd.
D3DPT_LINESTRIP
Renders the vertices as a single polyline. Calls using this primitive type fail if the count is less than 2.
D3DPT_TRIANGLELIST
Renders the specified vertices as a sequence of isolated triangles. Each group of three vertices defines a separate triangle.

Backface 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.

Remarks

Using triangle strips or fans is often more efficient than using triangle lists because fewer vertices are duplicated. For more information see Triangle Strips and Triangle Fans.

See Also

Direct3DDevice8.DrawIndexedPrimitive, Direct3DDevice8.DrawIndexedPrimitiveUP, Direct3DDevice8.DrawPrimitive, Direct3DDevice8.DrawPrimitiveUP


CONST_D3DPSHADECAPSFLAGS

Defines shading operations capabilities.

Enum CONST_D3DPSHADECAPSFLAGS
    D3DPSHADECAPS_COLORGOURAUDRGB      =       8
    D3DPSHADECAPS_SPECULARGOURAUDRGB   =     512 (&H200)
    D3DPSHADECAPS_ALPHAGOURAUDBLEND    =   16384 (&H4000)
    D3DPSHADECAPS_FOGGOURAUD           =  524288 (&H80000)
End Enum

Constants

D3DPSHADECAPS_COLORGOURAUDRGB
Device can support colored Gouraud shading in the RGB color model. In this mode, the color component for a primitive is provided at vertices and interpolated across a face along with the other color components. In the RGB lighting model, the red, green, and blue components are interpolated.
D3DPSHADECAPS_SPECULARGOURAUDRGB
Device can support specular highlights in Gouraud shading in the RGB color model.
D3DPSHADECAPS_ALPHAGOURAUDBLEND
Device can support an alpha component for Gouraud-blended transparency (the D3DSHADE_GOURAUD state for the CONST_D3DSHADEMODE enumeration). 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_FOGGOURAUD
Device can support fog in the Gouraud shading mode.

Remarks

These flags may be combined and present in the ShadeCaps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DPTADDRESSCAPSFLAGS

Defines texture-addressing capabilities.

Enum CONST_D3DPTADDRESSCAPSFLAGS
    D3DPTADDRESSCAPS_WRAP          =  1
    D3DPTADDRESSCAPS_MIRROR        =  2
    D3DPTADDRESSCAPS_CLAMP         =  4
    D3DPTADDRESSCAPS_BORDER        =  8
    D3DPTADDRESSCAPS_INDEPENDENTUV = 16 (&H10)
    D3DPTADDRESSCAPS_MIRRORONCE    = 32 (&H20)
End Enum

Constants

D3DPTADDRESSCAPS_WRAP
Device can wrap textures to addresses.
D3DPTADDRESSCAPS_MIRROR
Device can mirror textures to addresses.
D3DPTADDRESSCAPS_CLAMP
Device can clamp textures to addresses.
D3DPTADDRESSCAPS_BORDER
Device supports setting coordinates outside the range [0.0, 1.0] to the border color, as specified by the D3DTSS_BORDERCOLOR texture-stage state.
D3DPTADDRESSCAPS_INDEPENDENTUV
Device can separate the texture-addressing modes of the u and v coordinates of the texture. This ability corresponds to the D3DTSS_ADDRESSU and D3DTSS_ADDRESSV render-state values.
D3DPTADDRESSCAPS_MIRRORONCE
Device can take the absolute value of the texture coordinate (thus, mirroring around 0), and then clamp to the maximum value.

Remarks

These flags may be combined and present in the TextureAddressCaps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DPTEXTURECAPSFLAGS

Defines miscellaneous texture-mapping capabilities.

Enum CONST_D3DPTEXTURECAPSFLAGS
    D3DPTEXTURECAPS_PERSPECTIVE              =      1
    D3DPTEXTURECAPS_POW2                     =      2
    D3DPTEXTURECAPS_ALPHA                    =      4
    D3DPTEXTURECAPS_SQUAREONLY               =     32 (&H20)
    D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE =     64 (&H40)
    D3DPTEXTURECAPS_ALPHAPALETTE             =    128 (&H80)
    D3DPTEXTURECAPS_NONPOW2CONDITIONAL       =    256 (&H100)
    D3DPTEXTURECAPS_PROJECTED                =   1024 (&H400)
    D3DPTEXTURECAPS_CUBEMAP                  =   2048 (&H800)
    D3DPTEXTURECAPS_VOLUMEMAP                =   8192 (&H2000)
    D3DPTEXTURECAPS_MIPMAP                   =  16384 (&H4000)
    D3DPTEXTURECAPS_MIPVOLUMEMAP             =  32768 (&H8000)
    D3DPTEXTURECAPS_MIPCUBEMAP               =  65536 (&H10000)
    D3DPTEXTURECAPS_CUBEMAP_POW2             = 131072 (&H20000)
    D3DPTEXTURECAPS_VOLUMEMAP_POW2           = 262144 (&H40000)
End Enum

Constants

D3DPTEXTURECAPS_PERSPECTIVE
Perspective correction texturing is supported.
D3DPTEXTURECAPS_POW2
All textures must have widths and heights specified as powers of 2. This requirement does not apply to either cube textures or volume textures.
D3DPTEXTURECAPS_ALPHA
Alpha in texture pixels is supported.
D3DPTEXTURECAPS_SQUAREONLY
All textures must be square.
D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE
Texture indices are not scaled by the texture size prior to interpolation.
D3DPTEXTURECAPS_ALPHAPALETTE
Device can draw alpha from texture palettes.
D3DPTEXTURECAPS_NONPOW2CONDITIONAL
Conditionally supports the use of textures with dimensions that are not powers of 2. 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_WRAPn set to 0).
  • Mipmapping is not in use (use magnification filter only).
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 supported then the projective divide happens on a per pixel basis. If this capability is not set and the application still wants the projective divide to happen, then it happens on a per-vertex basis by the Direct3D runtime.
D3DPTEXTURECAPS_CUBEMAP
Supports cube textures.
D3DPTEXTURECAPS_VOLUMEMAP
Device supports volume textures.
D3DPTEXTURECAPS_MIPMAP
Device supports mipmapped textures.
D3DPTEXTURECAPS_MIPVOLUMEMAP
Device supports mipmapped volume textures.
D3DPTEXTURECAPS_MIPCUBEMAP
Device supports mipmapped cube textures.
D3DPTEXTURECAPS_CUBEMAP_POW2
Device requires that cube texture maps have dimensions specified as powers of 2.
D3DPTEXTURECAPS_VOLUMEMAP_POW2
Device requires that volume texture maps have dimensions specified as powers of 2.

Remarks

These flags may be combined and present in the TextureCaps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DPTFILTERCAPSFLAGS

Defines texture-filtering capabilities.

Enum CONST_D3DPTFILTERCAPSFLAGS
    D3DPTFILTERCAPS_MINFPOINT         =       256 (&H100)
    D3DPTFILTERCAPS_MINFLINEAR        =       512 (&H200)
    D3DPTFILTERCAPS_MINFANISOTROPIC   =      1024 (&H400)
    D3DPTFILTERCAPS_MIPFPOINT         =     65536 (&H10000)
    D3DPTFILTERCAPS_MIPFLINEAR        =    131072 (&H20000)
    D3DPTFILTERCAPS_MAGFPOINT         =  16777216 (&H1000000)
    D3DPTFILTERCAPS_MAGFLINEAR        =  33554432 (&H2000000)
    D3DPTFILTERCAPS_MAGFANISOTROPIC   =  67108864 (&H4000000)
    D3DPTFILTERCAPS_MAGFAFLATCUBIC    = 134217728 (&H8000000)
    D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC = 268435456 (&H10000000)
End Enum

Constants

D3DPTFILTERCAPS_MINFPOINT
The device supports per-stage point-sample filtering for minifying textures. The point-sample minification filter is represented by the D3DTEXF_POINT member of the CONST_D3DTEXTUREFILTERTYPE enumeration.
D3DPTFILTERCAPS_MINFLINEAR
The device supports per-stage bilinear interpolation filtering for minifying textures. The bilinear minification filter is represented by the D3DTEXF_LINEAR member of the CONST_D3DTEXTUREFILTERTYPE enumeration.
D3DPTFILTERCAPS_MINFANISOTROPIC
The device supports per-stage anisotropic filtering for minifying textures. The anisotropic minification filter is represented by the D3DTEXF_ANISOTROPIC member of the CONST_D3DTEXTUREFILTERTYPE enumeration.
D3DPTFILTERCAPS_MIPFPOINT
The device supports per-stage point-sample filtering for mipmaps. The point-sample mipmapping filter is represented by the D3DTEXF_POINT member of the CONST_D3DTEXTUREFILTERTYPE enumeration.
D3DPTFILTERCAPS_MIPFLINEAR
The device supports per-stage trilinear interpolation filtering for mipmaps. The trilinear interpolation mipmapping filter is represented by the D3DTEXF_LINEAR member of the CONST_D3DTEXTUREFILTERTYPE enumeration.
D3DPTFILTERCAPS_MAGFPOINT
The device supports per-stage point-sample filtering for magnifying textures. The point-sample magnification filter is represented by the D3DTEXF_POINT member of the CONST_D3DTEXTUREFILTERTYPE enumeration.
D3DPTFILTERCAPS_MAGFLINEAR
The device supports per-stage bilinear interpolation filtering for magnifying textures. The bilinear interpolation magnification filter is represented by the D3DTEXF_LINEAR member of the CONST_D3DTEXTUREFILTERTYPE enumeration.
D3DPTFILTERCAPS_MAGFANISOTROPIC
The device supports per-stage anisotropic filtering for magnifying textures. The anisotropic magnification filter is represented by the D3DTEXF_ANISOTROPIC member of the CONST_D3DTEXTUREFILTERTYPE enumeration.
D3DPTFILTERCAPS_MAGFAFLATCUBIC
The device supports per-stage flat cubic filtering for magnifying textures. The flat cubic magnification filter is represented by the D3DTEXF_FLATCUBIC member of the CONST_D3DTEXTUREFILTERTYPE enumeration.
D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC
The device supports the per-stage Gaussian cubic filtering for magnifying textures. The Gaussian cubic magnification filter is represented by the D3DTEXF_GAUSSIANCUBIC member of the CONST_D3DTEXTUREFILTERTYPE enumeration.

Remarks

These flags may be combined and present in the TextureFilterCaps member of D3DCAPS8.

The following flags concerning mipmapped textures are not supported in DirectX 8:

  • D3DPTFILTERCAPS_NEAREST
  • D3DPTFILTERCAPS_LINEAR
  • D3DPTFILTERCAPS_MIPNEAREST
  • D3DPTFILTERCAPS_MIPLINEAR
  • D3DPTFILTERCAPS_LINEARMIPNEAREST

• D3DPTFILTERCAPS_LINEARMIPLINEAR

See Also

D3DCAPS8


CONST_D3DRENDERSTATETYPE

Defines device render states

Enum CONST_D3DRENDERSTATETYPE
    D3DRS_ZENABLE                  =   7
    D3DRS_FILLMODE                 =   8
    D3DRS_SHADEMODE                =   9
    D3DRS_LINEPATTERN              =  10
    D3DRS_ZWRITEENABLE             =  14
    D3DRS_ALPHATESTENABLE          =  15
    D3DRS_LASTPIXEL                =  16 (&H10)
    D3DRS_SRCBLEND                 =  19 (&H13)
    D3DRS_DESTBLEND                =  20 (&H14)
    D3DRS_CULLMODE                 =  22 (&H16)
    D3DRS_ZFUNC                    =  23 (&H17)
    D3DRS_ALPHAREF                 =  24 (&H18)
    D3DRS_ALPHAFUNC                =  25 (&H19)
    D3DRS_DITHERENABLE             =  26 (&H1A)
    D3DRS_ALPHABLENDENABLE         =  27 (&H1B)
    D3DRS_FOGENABLE                =  28 (&H1C)
    D3DRS_SPECULARENABLE           =  29 (&H1D)
    D3DRS_ZVISIBLE                 =  30 (&H1E)
    D3DRS_FOGCOLOR                 =  34 (&H22)
    D3DRS_FOGTABLEMODE             =  35 (&H23)
    D3DRS_FOGSTART                 =  36 (&H24)
    D3DRS_FOGEND                   =  37 (&H25)
    D3DRS_FOGDENSITY               =  38 (&H26)
    D3DRS_EDGEANTIALIAS            =  40 (&H28)
    D3DRS_ZBIAS                    =  47 (&H2F)
    D3DRS_RANGEFOGENABLE           =  48 (&H30)
    D3DRS_STENCILENABLE            =  52 (&H34)
    D3DRS_STENCILFAIL              =  53 (&H35)
    D3DRS_STENCILZFAIL             =  54 (&H36)
    D3DRS_STENCILPASS              =  55 (&H37)
    D3DRS_STENCILFUNC              =  56 (&H38)
    D3DRS_STENCILREF               =  57 (&H39)
    D3DRS_STENCILMASK              =  58 (&H3A)
    D3DRS_STENCILWRITEMASK         =  59 (&H3B)
    D3DRS_TEXTUREFACTOR            =  60 (&H3C)
    D3DRS_WRAP0                    = 128 (&H80)
    D3DRS_WRAP1                    = 129 (&H81)
    D3DRS_WRAP2                    = 130 (&H82)
    D3DRS_WRAP3                    = 131 (&H83)
    D3DRS_WRAP4                    = 132 (&H84)
    D3DRS_WRAP5                    = 133 (&H85)
    D3DRS_WRAP6                    = 134 (&H86)
    D3DRS_WRAP7                    = 135 (&H87)
    D3DRS_CLIPPING                 = 136 (&H88)
    D3DRS_LIGHTING                 = 137 (&H89)
    D3DRS_AMBIENT                  = 139 (&H8B)
    D3DRS_FOGVERTEXMODE            = 140 (&H8C)
    D3DRS_COLORVERTEX              = 141 (&H8D)
    D3DRS_LOCALVIEWER              = 142 (&H8E)
    D3DRS_NORMALIZENORMALS         = 143 (&H8F)
    D3DRS_DIFFUSEMATERIALSOURCE    = 145 (&H91)
    D3DRS_SPECULARMATERIALSOURCE   = 146 (&H92)
    D3DRS_AMBIENTMATERIALSOURCE    = 147 (&H93)
    D3DRS_EMISSIVEMATERIALSOURCE   = 148 (&H94)
    D3DRS_VERTEXBLEND              = 151 (&H97)
    D3DRS_CLIPPLANEENABLE          = 152 (&H98)
    D3DRS_SOFTWAREVERTEXPROCESSING = 153 (&H99)
    D3DRS_POINTSIZE                = 154 (&H9A)
    D3DRS_POINTSIZE_MIN            = 155 (&H9B)
    D3DRS_POINTSPRITEENABLE        = 156 (&H9C)
    D3DRS_POINTSCALEENABLE         = 157 (&H9D)
    D3DRS_POINTSCALE_A             = 158 (&H9E)
    D3DRS_POINTSCALE_B             = 159 (&H9F)
    D3DRS_POINTSCALE_C             = 160 (&HA0)
    D3DRS_MULTISAMPLEANTIALIAS     = 161 (&HA1)
    D3DRS_MULTISAMPLEMASK          = 162 (&HA2)
    D3DRS_PATCHEDGESTYLE           = 163 (&HA3)
    D3DRS_PATCHSEGMENTS            = 164 (&HA4)
    D3DRS_DEBUGMONITORTOKEN        = 165 (&HA5)
    D3DRS_POINTSIZE_MAX            = 166 (&HA6)
    D3DRS_INDEXVERTEXBLENDENABLE   = 167 (&HA7)
    D3DRS_COLORWRITEENABLE         = 168 (&HA8)
    D3DRS_TWEENFACTOR              = 170 (&HAA)
    D3DRS_BLENDOP                  = 171 (&HAB)
End Enum

Constants

D3DRS_ZENABLE
Depth-buffering state as one member of the CONST_D3DZBUFFERTYPE enumeration. 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 1, and D3DZB_FALSE otherwise.

D3DRS_FILLMODE
One or more members of the CONST_D3DFILLMODE enumeration. The default value is D3DFILL_SOLID.
D3DRS_SHADEMODE
One or more members of the CONST_D3DSHADEMODE enumeration. The default value is D3DSHADE_GOURAUD.
D3DRS_LINEPATTERN
D3DLINEPATTERN type. The default values are 0 for wRepeatPattern, and 0 for wLinePattern.
D3DRS_ZWRITEENABLE
1 to enable the application to write to the depth buffer. The default value is 1. This member enables an application to prevent the system from updating the depth buffer with new depth values. If 0, 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
1 to enable alpha tests. The default value is 0. This member enables applications to turn off the tests that accept or reject a pixel, based on its alpha value.

The incoming alpha value is compared with the reference alpha value, using the comparison function provided by the D3DRS_ALPHAFUNC render state. When this mode is enabled, alpha blending occurs only if the test succeeds.

D3DRS_LASTPIXEL
0 to enable drawing the last pixel in a line or triangle. The default value is 1.
D3DRS_SRCBLEND
One member of the CONST_D3DBLEND enumeration. The default value is D3DBLEND_ONE.
D3DRS_DESTBLEND
One member of the CONST_D3DBLEND enumeration. 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 CONST_D3DCULL enumerated type. The default value is D3DCULL_CCW.
D3DRS_ZFUNC
One member of the CONST_D3DCMPFUNC enumeration. 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 1.

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 specifying a reference alpha value against which pixels are tested when alpha testing is enabled. This can be a 16:16 fixed point value (D3DFIXED) ranging from 0 to 1, inclusive, where 1.0 is represented as &H00010000. The default value is 0.0.
D3DRS_ALPHAFUNC
One member of the CONST_D3DCMPFUNC enumeration. The default value is D3DCMP_ALWAYS. This member enables an application to accept or reject a pixel, based on its alpha value.
D3DRS_DITHERENABLE
1 to enable dithering. The default value is 0.
D3DRS_ALPHABLENDENABLE
1 to enable alpha-blended transparency. The default value is 0.

The type of alpha blending is determined by the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states.

D3DRS_FOGENABLE
1 to enable fog blending. The default value is 0.
D3DRS_SPECULARENABLE
1 to enable specular highlights. The default value is 0.

Specular highlights are calculated as though every vertex in the object being lit were 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.

When this member is set to 1, the specular color is added to the base color after the texture cascade but before alpha blending.

D3DRS_ZVISIBLE
Not supported.
D3DRS_FOGCOLOR
Value of type Long indicating RGB color. The default value is 0.
D3DRS_FOGTABLEMODE
The fog formula to be used for pixel fog. Set to one of the members of the CONST_D3DFOGMODE enumeration. The default value is D3DFOG_NONE.
D3DRS_FOGSTART
Depth at which pixel or vertex fog effects begin for linear fog mode. The default value is 0. 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 space when the system is using eye-relative fog (w-fog).
D3DRS_FOGEND
Depth at which pixel or vertex fog effects end for linear fog mode. The default value is 1. 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 space when the system is using eye-relative fog (w-fog).
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.
D3DRS_EDGEANTIALIAS
1 to antialias lines forming the convex outline of objects. The default value is 0. If 1, applications should render only lines, and only to the exterior edges of polygons in a scene. The behavior is undefined if triangles or points are drawn when this render state is set. Antialiasing is performed by averaging the values of neighboring pixels. Although this is not the best way to perform antialiasing, it can be very efficient; hardware that supports this kind of operation is becoming more common.

You can enable edge antialiasing only on devices that expose the D3DPRASTERCAPS_ANTIALIASEDGES capability.

D3DRS_ZBIAS
An integer value in the range 0 to 16 that causes polygons that are physically coplanar to appear separate. Polygons with a high z-bias value will appear in front of polygons with a low value, without requiring sorting for drawing order. Polygons with a value of 1 appear in front of polygons with a value of 0, and so on. The default value is zero.
D3DRS_RANGEFOGENABLE
1 to enable range-based vertex fog. The default value is 0, 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 expensive 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.

D3DRS_STENCILENABLE
1 to enable stenciling, or 0 to disable stenciling. The default value is 0.
D3DRS_STENCILFAIL
Stencil operation to perform if the stencil test fails. This can be one member of the CONST_D3DSTENCILOP enumeration. The default value is D3DSTENCILOP_KEEP.
D3DRS_STENCILZFAIL
Stencil operation to perform if the stencil test passes and the depth test (z-test) fails. This can be one of the members of the CONST_D3DSTENCILOP enumeration. The default value is D3DSTENCILOP_KEEP.
D3DRS_STENCILPASS
Stencil operation to perform if both the stencil and the depth (z) tests pass. This can be one member of the CONST_D3DSTENCILOP enumeration. The default value is D3DSTENCILOP_KEEP.
D3DRS_STENCILFUNC
Comparison function for the stencil test. This can be one member of the CONST_D3DCMPFUNC enumeration. 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 1, the stencil test passes.

D3DRS_STENCILREF
Integer 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 &HFFFFFFFF.
D3DRS_STENCILWRITEMASK
Mask applied to the reference value and each stencil buffer entry to determine the significant bits for the stencil test. The default mask is &HFFFFFFFF.
D3DRS_TEXTUREFACTOR
Color used for multiple-texture blending with the D3DTA_TFACTOR texture-blending argument or the D3DTOP_BLENDFACTORALPHA texture-blending operation. The default value is opaque white (&HFF000000).
D3DRS_WRAP0 through D3DRS_WRAP7
Texture-wrapping behavior for multiple sets of texture coordinates. Valid values for these render states 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 defined by the CONST_D3DWRAPFLAGS enumeration. These cause the system to wrap in the direction of the first, second, third, and fourth dimensions, sometimes referred to at the s, t, r, and q directions, for a given texture. The default value for these render states is 0 (wrapping disabled in all directions).
D3DRS_CLIPPING
1 to enable primitive clipping by Microsoft® Direct3D®, or 0 to disable it. The default value is 1.
D3DRS_LIGHTING
1 to enable Direct3D lighting, or 0 to disable it. The default value is 1. 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. The default value is 0.
D3DRS_FOGVERTEXMODE
Fog formula to be used for vertex fog. Set to one member of the CONST_D3DFOGMODE enumeration. The default value is D3DFOG_NONE. This render state is analogous to the legacy D3DLIGHTSTATE_FOGVERTEXMODE lighting state.
D3DRS_COLORVERTEX
1 to enable per-vertex color, or 0 to disable it. The default value is 1. 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
1 to enable camera-relative specular highlights, or 0 to use orthogonal specular highlights. The default value is 1. Applications that use orthogonal projection should specify 0.
D3DRS_NORMALIZENORMALS
1 to enable automatic normalization of vertex normals, or 0 to disable it. The default value is 1. Enabling this feature causes the system to normalize the vertex normals for vertices after transforming them to camera space, which can be computationally expensive.
D3DRS_DIFFUSEMATERIALSOURCE
Diffuse color source for lighting calculations. Valid values are members of the CONST_D3DMATERIALCOLORSOURCE enumeration. The default value is D3DMCS_COLOR1. The value for this render state is used only if the D3DRS_COLORVERTEX render state is set to 1.
D3DRS_SPECULARMATERIALSOURCE
Specular color source for lighting calculations. Valid values are members of the CONST_D3DMATERIALCOLORSOURCE enumeration. The default value is D3DMCS_COLOR2.
D3DRS_AMBIENTMATERIALSOURCE
Ambient color source for lighting calculations. Valid values are members of the CONST_D3DMATERIALCOLORSOURCE enumeration. The default value is D3DMCS_COLOR2.
D3DRS_EMISSIVEMATERIALSOURCE
Emissive color source for lighting calculations. Valid values are members of the CONST_D3DMATERIALCOLORSOURCE enumeration. 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 CONST_D3DVERTEXBLENDFLAGS enumeration. The default value is D3DVBF_DISABLE.
D3DRS_CLIPPLANEENABLE
Enables or disables user-defined clipping planes. Valid values are combinations of values from the CONST_D3DCLIPPLANEFLAGS enumeration. If you include a value from the enumeration, the corresponding clipping plane is enabled; if a value is not included, the clipping plane is disabled. The default value is D3DCPF_DISABLEALL.
D3DRS_SOFTWAREVERTEXPROCESSING
Value that enables applications to query and select hardware or software vertex processing. For a D3DDEVTYPE_SW device type this value is fixed to 1. This value can be set by the application for a D3DDEVTYPE_REF device type. For a D3DDEVTYPE_HAL device type, this value can be set only by the application when D3DDEVCAPS_HWTRANSFORMANDLIGHT is set; otherwise this flag is fixed to 1. When variable, the default value is 0.

Changing the vertex processing render state in mixed vertex processing mode will reset the current stream, indices, and vertex shader to their default values of ByVal 0 or 0

D3DRS_POINTSIZE
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 0; otherwise this value is in world space units. The default value is 1.0. The range for this value is greater than or equal to 0.0.
D3DRS_POINTSIZE_MIN
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 0.0. The range for this value is greater than or equal to 0.0.
D3DRS_POINTSPRITEENABLE
When 1, texture coordinates of point primitives are set so that full textures are mapped on each point. When 0, the vertex texture coordinates are used for the entire point. The default value is 0. You can achieve DirectX 7 style single-pixel points by setting D3DRS_POINTSCALEENABLE to 0 and D3DRS_POINTSIZE to 1.0, which are the default values.
D3DRS_POINTSCALEENABLE
Value that controls computation of size for point primitives. When 1, 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 0, the point size is interpreted as screen space and used directly. The default value is 0.
D3DRS_POINTSCALE_A
Value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is 1. The default value is 1.0. The range for this value is greater than or equal to 0.0.
D3DRS_POINTSCALE_B
Value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is 1. The default value is 0.0. The range for this value is greater than or equal to 0.0.
D3DRS_POINTSCALE_C
Value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is 1. The default value is 0.0. The range for this value is greater than or equal to 0.0.
D3DRS_MULTISAMPLEANTIALIAS
Value that determines how individual samples are computed when using a multisample render target buffer. When set to 1, 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 0, the multiple samples are all written with the same sample value (sampled at the pixel center), which enables non-antialiased rendering to a multisample buffer. This render state has no effect when rendering to a single sample buffer. The default value is 1.

Toggling this render state on and off in the same scene is not supported if D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE is enabled.

D3DRS_MULTISAMPLEMASK
Each bit in this mask, starting at the 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 8 write enables for each of the 8 samples. This render state has no effect when rendering to a single sample buffer. The default value is &HFFFFFFFF.

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.

This render state is not supported if D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE is enabled.

D3DRS_PATCHEDGESTYLE
Sets whether patch edges will use float-style tessellation. The default value is D3DPATCHEDGE_DISCRETE. Possible values are defined by the CONST_D3DPATCHEDGESTYLE enumerated type.
D3DRS_PATCHSEGMENTS
Number of segments per edge when drawing high-order primitives. The default value is 1.
D3DRS_DEBUGMONITORTOKEN
Set only for debugging the monitor.
D3DRS_POINTSIZE_MAX
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 D3DCAPS8 and greater than or equal to D3DRS_POINTSIZE_MIN. The default value is 64.
D3DRS_INDEXVERTEXBLENDENABLE
When 1, enables indexed vertex blending. When 0, disables indexed vertex blending. If this render state is enabled, the user must pass matrix indices as a packed LONG with 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
Value that enables a per-channel write for the render target color buffer. A set bit results in the color channel being updated during 3-D 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 D3DCAPS8 type for the device. This render state does not affect the clear operation. The default value is &H0000000F.

Valid values for this render state can be any combination of values defined by the CONST_D3DCOLORWRITEENABLEFLAGS enumeration.

D3DRS_TWEENFACTOR
Value that controls the tween factor. The default value is 0.
D3DRS_BLENDOP
Value used to select the arithmetic operation applied when the alpha blending render state, D3DRS_ALPHABLENDENABLE, is set to 1. Valid values are defined by the CONST_D3DBLENDOP enumerated type. The default value is D3DBLENDOP_ADD.

If the D3DPMISCCAPS_BLENDOP device capability is not supported, then D3DBLENDOP_ADD is performed.

Remarks

Direct3D defines the D3DRENDERSTATE_WRAPBIAS constant defined by the CONST_D3DWRAPBIAS enumeration 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_WRAPn state values). Add the D3DRENDERSTATE_WRAPBIAS value to the zero-based index of a texture coordinate set to calculate the D3DRS_WRAPn value that corresponds to that index, as shown in the following example:

    On Local Error Resume Next

    ' Enable U/V wrapping for textures that use the texture
    ' coordinate set at the index within the lIndex variable.
    Call d3dDevice8.SetRenderState( _
            lIndex + D3DRENDERSTATE_WRAPBIAS, _
            D3DWRAPCOORD_0 Or D3DWRAPCOORD_1)

    ' If lIndex is 3, the value that results from
    ' the addition equates to D3DRENDERSTATE_WRAP3 (131).
    If Err.Number <> DD_OK Then
       ' Code to handle error goes here.
    End If


CONST_D3DRESOURCETYPE

Defines resource types.

Enum CONST_D3DRESOURCETYPE
    D3DRTYPE_SURFACE       = 1
    D3DRTYPE_VOLUME        = 2
    D3DRTYPE_TEXTURE       = 3
    D3DRTYPE_VOLUMETEXTURE = 4
    D3DRTYPE_CUBETEXTURE   = 5
    D3DRTYPE_VERTEXBUFFER  = 6
    D3DRTYPE_INDEXBUFFER   = 7
End Enum

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.

See Also

Direct3DResource8.GetType


CONST_D3DSCPFLAGS

Defines update options for the cursor.

Enum CONST_D3DSCPFLAGS
     D3DCURSOR_IMMEDIATE_UPDATE = 1
End Enum

Constants

D3DCURSOR_IMMEDIATE_UPDATE
Update cursor at the refresh rate.

See Also

Direct3DDevice8.SetCursorPosition


CONST_D3DSGRFLAGS

Defines constants that indicate whether or not gamma correction should be applied.

Enum CONST_D3DSGRFLAGS
    D3DSGR_NO_CALIBRATION = 0
    D3DSGR_CALIBRATE      = 1
End Enum

Constants

D3DSGR_NO_CALIBRATION
No gamma correction is applied. The supplied gamma table is transferred directly to the device.
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.

See Also

Direct3DDevice8.SetGammaRamp


CONST_D3DSHADEMODE

Defines constants that describe the supported shade mode.

Enum CONST_D3DSHADEMODE
    D3DSHADE_FLAT    = 1
    D3DSHADE_GOURAUD = 2
    D3DSHADE_PHONG   = 3
End Enum

Constants

D3DSHADE_FLAT
Flat shade 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 shade 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
Phong shade mode is not currently supported.

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.

These flags are used to set the value of the D3DRS_SHADEMODE render state for the CONST_D3DRENDERSTATETYPE enumeration.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DSPDFLAGS

Defines how private data should be managed.

Enum CONST_D3DSPDFLAGS
    D3DSPD_IUNKNOWN = 1
End Enum

Constants

D3DSPD_IUNKNOWN
When the passed data is no longer needed, Microsoft® Direct3D® automatically releases the memory associated with the data.

See Also

Direct3DResource8.SetPrivateData, Direct3DSurface8.SetPrivateData, Direct3DVolume8.SetPrivateData


CONST_D3DSTATEBLOCKTYPE

Defines logical groups of device states.

Enum CONST_D3DSTATEBLOCKTYPE
    D3DSBT_ALL         = 1
    D3DSBT_PIXELSTATE  = 2
    D3DSBT_VERTEXSTATE = 3
End Enum

Constants

D3DSBT_ALL
Capture all device states.
All current render states. | All current clipplanes.
All current texture stage states. | The current material.
All current textures. | All current lights and enabled light parameters.
The current palette. | The current pixel shader.
All current streams. | The current pixel shader constants.
The current viewport. | The current vertex shader.
All current transforms. | The current vertex shader constants.

D3DSBT_PIXELSTATE
Capture all of the following pixel-related device states.

Render States
D3DRS_ALPHABLENDENABLE D3DRS_ALPHAFUNC
D3DRS_ALPHAREF D3DRS_ALPHATESTENABLE
D3DRS_BLENDOP D3DRS_COLORWRITEENABLE
D3DRS_DESTBLEND D3DRS_DITHERENABLE
D3DRS_EDGEANTIALIAS D3DRS_FILLMODE
D3DRS_FOGDENSITY D3DRS_FOGEND
D3DRS_FOGSTART D3DRS_LASTPIXEL
D3DRS_LINEPATTERN D3DRS_SHADEMODE
D3DRS_SRCBLEND D3DRS_STENCILENABLE
D3DRS_STENCILFAIL D3DRS_STENCILFUNC
D3DRS_STENCILMASK D3DRS_STENCILPASS
D3DRS_STENCILREF D3DRS_STENCILWRITEMASK
D3DRS_STENCILZFAIL D3DRS_TEXTUREFACTOR
D3DRS_WRAP0 through D3DRS_WRAP7 D3DRS_ZBIAS
D3DRS_ZENABLE D3DRS_ZFUNC
D3DRS_ZWRITEENABLE

Texture Stage States
D3DTSS_ADDRESSU D3DTSS_ADDRESSV
D3DTSS_ADDRESSW D3DTSS_ALPHAARG0
D3DTSS_ALPHAARG1 D3DTSS_ALPHAARG2
D3DTSS_ALPHAOP D3DTSS_BORDERCOLOR
D3DTSS_BUMPENVLOFFSET D3DTSS_BUMPENVLSCALE
D3DTSS_BUMPENVMAT00 D3DTSS_BUMPENVMAT01
D3DTSS_BUMPENVMAT10 D3DTSS_BUMPENVMAT11
D3DTSS_COLORARG0 D3DTSS_COLORARG1
D3DTSS_COLORARG2 D3DTSS_COLOROP
D3DTSS_MAGFILTER D3DTSS_MAXANISOTROPY
D3DTSS_MAXMIPLEVEL D3DTSS_MINFILTER
D3DTSS_MIPFILTER D3DTSS_MIPMAPLODBIAS
D3DTSS_RESULTARG D3DTSS_TEXCOORDINDEX
D3DTSS_TEXTURETRANSFORMFLAGS

D3DSBT_VERTEXSTATE
Capture all the current lights, the current vertex shader and vertex shader constants, and the texture stage states specified by D3DTSS_TEXCOORDINDEX and D3DTSS_TEXTURETRANSFORMFLAGS. In addition, D3DSBT_VERTEXSTATE captures all of the following vertex-related device states.

Render States
D3DRS_AMBIENT D3DRS_AMBIENTMATERIALSOURCE
D3DRS_CLIPPING D3DRS_CLIPPLANEENABLE
D3DRS_COLORVERTEX D3DRS_DIFFUSEMATERIALSOURCE
D3DRS_EMISSIVEMATERIALSOURCE D3DRS_FOGDENSITY
D3DRS_FOGEND D3DRS_FOGSTART
D3DRS_FOGTABLEMODE D3DRS_FOGVERTEXMODE
D3DRS_INDEXVERTEXBLENDENABLE D3DRS_LIGHTING
D3DRS_LOCALVIEWER D3DRS_MULTISAMPLEANTIALIAS
D3DRS_MULTISAMPLEMASK D3DRS_NORMALIZENORMALS
D3DRS_PATCHEDGESTYLE D3DRS_PATCHSEGMENTS
D3DRS_POINTSCALE_A D3DRS_POINTSCALE_B
D3DRS_POINTSCALE_C D3DRS_POINTSCALEENABLE
D3DRS_POINTSIZE D3DRS_POINTSIZE_MAX
D3DRS_POINTSIZE_MIN D3DRS_POINTSPRITEENABLE
D3DRS_RANGEFOGENABLE D3DRS_SOFTWAREVERTEXPROCESSING
D3DRS_SPECULARMATERIALSOURCE D3DRS_TWEENFACTOR
D3DRS_VERTEXBLEND

Remarks

The D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE values identify different logical groups of device states, though some states are common to both groups. The union of D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE is not equal to D3DSBT_ALL. The D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE values enable the capture of these frequently modified states between calls to Direct3DDevice8.DrawPrimitive without incurring the performance penalty of capturing the entire state. For information about the states defined by each group, see Creating Predefined State Blocks.

See Also

Direct3DDevice8.CreateStateBlock


CONST_D3DSTENCILCAPFLAGS

Defines stencil buffer capability flags

Enum CONST_D3DSTENCILCAPFLAGS
    D3DSTENCILCAPS_KEEP    =   1
    D3DSTENCILCAPS_ZERO    =   2
    D3DSTENCILCAPS_REPLACE =   4
    D3DSTENCILCAPS_INCRSAT =   8
    D3DSTENCILCAPS_DECRSAT =  16 (&H10)
    D3DSTENCILCAPS_INVERT  =  32 (&H20)
    D3DSTENCILCAPS_INCR    =  64 (&H40)
    D3DSTENCILCAPS_DECR    = 128 (&H80)
End Enum

Constants

D3DSTENCILCAPS_KEEP
The D3DSTENCILOP_KEEP operation is supported.
D3DSTENCILCAPS_ZERO
The D3DSTENCILOP_ZERO operation is supported.
D3DSTENCILCAPS_REPLACE
The D3DSTENCILOP_REPLACE operation is supported.
D3DSTENCILCAPS_INCRSAT
The D3DSTENCILOP_INCRSAT operation is supported.
D3DSTENCILCAPS_DECRSAT
The D3DSTENCILOP_DECRSAT operation is supported.
D3DSTENCILCAPS_INVERT
The D3DSTENCILOP_INVERT operation is supported.
D3DSTENCILCAPS_INCR
The D3DSTENCILOP_INCR operation is supported.
D3DSTENCILCAPS_DECR
The D3DSTENCILOP_DECR operation is supported.

Remarks

These flags may be combined and present in the StencilCaps member of D3DCAPS8.

For a definition of stencil operations, see CONST_D3DSTENCILOP.

See Also

D3DCAPS8, CONST_D3DSTENCILOP


CONST_D3DSTENCILOP

Defines constants that define stencil operations.

Enum CONST_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
End Enum

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 zero.
D3DSTENCILOP_REPLACE
Replace the stencil-buffer entry with reference value.
D3DSTENCILOP_INCRSAT
Increment the stencil-buffer entry, clamping to the maximum value. See Remarks for information on the maximum stencil-buffer values.
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. See Remarks for information on the maximum stencil-buffer values.
D3DSTENCILOP_DECR
Decrement the stencil-buffer entry, wrapping to the maximum value if the new value is less than zero.

Remarks

Stencil-buffer entries are integer values ranging inclusively from 0 to 2n -1, where n is the bit depth of the stencil buffer.

These flags are used to set the value of the D3DRS_STENCILFAIL, D3DRS_STENCILZFAIL, and D3DRS_STENCILPASS render states for the CONST_D3DRENDERSTATETYPE enumeration.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DSWAPEFFECT

Defines swap effects.

Enum CONST_D3DSWAPEFFECT
    D3DSWAPEFFECT_DISCARD    = 1
    D3DSWAPEFFECT_FLIP       = 2
    D3DSWAPEFFECT_COPY       = 3
    D3DSWAPEFFECT_COPY_VSYNC = 4
End Enum

Constants

D3DSWAPEFFECT_DISCARD
When a swap chain is created with a swap effect of D3DSWAPEFFECT_FLIP, D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC, the runtime will guarantee that a Direct3DDevice8.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.

As with 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 Direct3DDevice8.GetBackBuffer or Direct3DSwapChain8.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 once 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.

For a full-screen swap chain, the presentation rate is determined by the value assigned to the FullScreen_PresentationInterval member of the D3DPRESENT_PARAMETERS structure when the device or swap chain is created. Unless this value is D3DPRESENT_INTERVAL_IMMEDIATE, the presentation will be synchronized with the vertical sync of the monitor. For a windowed swap chain, the presentation is implemented by means of copy operations and always occurs immediately.

D3DSWAPEFFECT_FLIP
The swap chain may comprise 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 back buffer 0 becomes the new front buffer.

For a full-screen swap chain, the presentation rate is determined by the value assigned to the FullScreen_PresentationInterval field of the D3DPRESENT_PARAMETERS structure when the device or swap chain is created. Unless this value is D3DPRESENT_INTERVAL_IMMEDIATE, the presentation will be synchronized with the vertical sync of the monitor. For a windowed swap chain, the flipping is implemented by means of copy operations and the presentation always occurs immediately.

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 windowed swap chain, a Present operation causes the back buffer content to be copied to the client area of the target window immediately. No attempt is made to synchronize the copy with the vertical retrace period of the display adapter, so "tearing" effects may be observed. Windowed applications may wish to use D3DSWAPEFFECT_COPY_VSYNC instead to eliminate, or at least minimize, such tearing effects.

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 FullScreen_PresentationInterval 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_COPY_VSYNC
Like D3DSWAPEFFECT_COPY, this swap effect may only be used with a swap chain comprising a single back buffer and guarantees that a Present operation applied to the swap chain will exhibit copy semantics, as described above for D3DSWAPEFFECT_COPY.

For a windowed swap chain, a Present operation causes the back buffer content to be copied to the client area of the target window. The runtime will attempt to eliminate tearing effects by avoiding the copy operation while the adapter is scanning within the destination rectangle on the display. It will also perform at most one such copy operation during the adapter's refresh period and thus limit the presentation frequency. Note, however, that if the adapter does not support the ability to report the raster status, the swap chain will behave as though it had been created with the D3DSWAPEFFECT_COPY swap effect. (Refer to the description of the D3DCAPS_READ_SCANLINE flag value for the Caps member of D3DCAPS8.)

For a full-screen swap chain, D3DSWAPEFFECT_COPY_VSYNC is identical to D3DSWAPEFFECT_COPY, except that the D3DPRESENT_INTERVAL_IMMEDIATE flag is meaningless when used in conjunction with D3DSWAPEFFECT_COPY_VSYNC. (Refer to the description of the FullScreen_PresentationInterval member of the D3DPRESENT_PARAMETERS structure.)

Remarks

The state of the back buffer after a call to Present is well-defined by each of these swap effects, and whether the Microsoft® 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 run time 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 fullscreen 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. Take the following steps to work around this.

  • Use D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPYVSYNC.
  • Check the D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD flag in the Caps3 member of the D3DCAPS8 type. This flag indicates whether the driver can do alpha blending when D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_DISCARD are used.

See Also

Direct3DDevice8.Reset, D3DPRESENT_PARAMETERS


CONST_D3DTAFLAGS

Defines texture argument flags used to define texture blending stages.

For details, see Texture Argument Flags.


CONST_D3DTEXOPCAPSFLAGS

Defines texture-blending operation capabilities

Enum CONST_D3DTEXOPCAPSFLAGS
    D3DTEXOPCAPS_DISABLE                   =        1
    D3DTEXOPCAPS_SELECTARG1                =        2
    D3DTEXOPCAPS_SELECTARG2                =        4
    D3DTEXOPCAPS_MODULATE                  =        8
    D3DTEXOPCAPS_MODULATE2X                =       16 (&H10)
    D3DTEXOPCAPS_MODULATE4X                =       32 (&H20)
    D3DTEXOPCAPS_ADD                       =       64 (&H40)
    D3DTEXOPCAPS_ADDSIGNED                 =      128 (&H80)
    D3DTEXOPCAPS_ADDSIGNED2X               =      256 (&H100)
    D3DTEXOPCAPS_SUBTRACT                  =      512 (&H200)
    D3DTEXOPCAPS_ADDSMOOTH                 =     1024 (&H400)
    D3DTEXOPCAPS_BLENDDIFFUSEALPHA         =     2048 (&H800)
    D3DTEXOPCAPS_BLENDTEXTUREALPHA         =     4096 (&H1000)
    D3DTEXOPCAPS_BLENDFACTORALPHA          =     8192 (&H2000)
    D3DTEXOPCAPS_BLENDTEXTUREALPHAPM       =    16384 (&H4000)
    D3DTEXOPCAPS_BLENDCURRENTALPHA         =    32768 (&H8000)
    D3DTEXOPCAPS_PREMODULATE               =    65536 (&H10000)
    D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR    =   131072 (&H20000)
    D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA    =   262144 (&H40000)
    D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR =   524288 (&H80000)
    D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA =  1048576 (&H100000)
    D3DTEXOPCAPS_BUMPENVMAP                =  2097152 (&H200000)
    D3DTEXOPCAPS_BUMPENVMAPLUMINANCE       =  4194304 (&H400000)
    D3DTEXOPCAPS_DOTPRODUCT3               =  8388608 (&H800000)
    D3DTEXOPCAPS_MULTIPLYADD               = 16777216 (&H1000000)
    D3DTEXOPCAPS_LERP                      = 33554432 (&H2000000)
End Enum

Constants

D3DTEXOPCAPS_DISABLE
The D3DTOP_DISABLE 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_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_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_SUBTRACT
The D3DTOP_SUBTRACT texture-blending operation is supported.
D3DTEXOPCAPS_ADDSMOOTH
The D3DTOP_ADDSMOOTH texture-blending operation is supported.
D3DTEXOPCAPS_BLENDDIFFUSEALPHA
The D3DTOP_BLENDDIFFUSEALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHA
The D3DTOP_BLENDTEXTUREALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDFACTORALPHA
The D3DTOP_BLENDFACTORALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHAPM
The D3DTOP_BLENDTEXTUREALPHAPM texture-blending operation is supported.
D3DTEXOPCAPS_BLENDCURRENTALPHA
The D3DTOP_BLENDCURRENTALPHA texture-blending operation is supported.
D3DTEXOPCAPS_PREMODULATE
The D3DTOP_PREMODULATE 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_BUMPENVMAP
The D3DTOP_BUMPENVMAP texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAPLUMINANCE
The D3DTOP_BUMPENVMAPLUMINANCE texture-blending operation is supported.
D3DTEXOPCAPS_DOTPRODUCT3
The D3DTOP_DOTPRODUCT3 texture-blending operation is supported.
D3DTEXOPCAPS_MULTIPLYADD
The D3DTOP_MULTIPLYADD texture-blending operation is supported.
D3DTEXOPCAPS_LERP
The D3DTOP_LERP texture-blending operation is supported.

Remarks

These flags may be combined and present in the TextureOpCaps member of D3DCAPS8.

For a definition of texture operations, see CONST_D3DTEXTUREOP.

See Also

D3DCAPS8, CONST_D3DTEXTUREOP


CONST_D3DTEXTUREADDRESS

Defines constants that describe the supported texture-addressing modes.

Enum CONST_D3DTEXTUREADDRESS
    D3DTADDRESS_WRAP       = 1
    D3DTADDRESS_MIRROR     = 2
    D3DTADDRESS_CLAMP      = 3
    D3DTADDRESS_BORDER     = 4
    D3DTADDRESS_MIRRORONCE = 5
End Enum

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.

Remarks

These flags are used to set the value of the D3DTSS_ADDRESSU, D3DTSS_ADDRESSV, and D3DTSS_ADDRESSW texture stage states for the CONST_D3DTEXTURESTAGESTATETYPE enumeration.

See Also

CONST_D3DTEXTURESTAGESTATETYPE


CONST_D3DTEXTUREFILTERTYPE

Defines texture filtering modes for a texture stage.

Enum CONST_D3DTEXTUREFILTERTYPE
    D3DTEXF_NONE          = 0
    D3DTEXF_POINT         = 1
    D3DTEXF_LINEAR        = 2
    D3DTEXF_ANISOTROPIC   = 3
    D3DTEXF_FLATCUBIC     = 4
    D3DTEXF_GAUSSIANCUBIC = 5
End Enum

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×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_FLATCUBIC
Flat-cubic filtering used as a texture magnification filter.
D3DTEXF_GAUSSIANCUBIC
Gaussian-cubic filtering used as a texture magnification filter.

Remarks

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. DirectX 8.0 devices that support anisotropic filtering for 2-D 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.

Set a texture stage's magnification filter by calling the Direct3DDevice8.SetTextureStageState method with the D3DTSS_MAGFILTER render state value as the second parameter and one member of this enumeration as the third parameter.

Set a texture stage's minification filter by calling SetTextureStageState with the D3DTSS_MINFILTER render state 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 SetTextureStageState with the D3DTSS_MIPFILTER render state value as the second parameter and one member of this enumeration as the third parameter.

See Also

D3DCAPS8, CONST_D3DTEXTURESTAGESTATETYPE


CONST_D3DTEXTUREOP

Defines per-stage texture-blending operations.

Enum CONST_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 (&H10)
    D3DTOP_PREMODULATE               = 17 (&H11)
    D3DTOP_MODULATEALPHA_ADDCOLOR    = 18 (&H12)
    D3DTOP_MODULATECOLOR_ADDALPHA    = 19 (&H13)
    D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20 (&H14)
    D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21 (&H15)
    D3DTOP_BUMPENVMAP                = 22 (&H16)
    D3DTOP_BUMPENVMAPLUMINANCE       = 23 (&H17)
    D3DTOP_DOTPRODUCT3               = 24 (&H18)
    D3DTOP_MULTIPLYADD               = 25 (&H19)
    D3DTOP_LERP                      = 26 (&H1A)
End Enum

Constants

Control members
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.

Modulation members
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.

Addition and subtraction members
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.

Linear alpha blending members
D3DTOP_BLENDDIFFUSEALPHA, D3DTOP_BLENDTEXTUREALPHA, D3DTOP_BLENDFACTORALPHA, and D3DTOP_BLENDCURRENTALPHA
Linearly blend this texture stage, using the interpolated alpha from each vertex (D3DTOP_BLENDDIFFUSEALPHA), alpha from this stage's texture (D3DTOP_BLENDTEXTUREALPHA), a scalar alpha (D3DTOP_BLENDFACTORALPHA) set with the D3DRS_TEXTUREFACTOR render state, or the alpha taken from the previous texture stage (D3DTOP_BLENDCURRENTALPHA).

D3DTOP_BLENDTEXTUREALPHAPM
Linearly blend a texture stage that uses a premultiplied alpha.

Specular mapping members
D3DTOP_PREMODULATE
Modulate this texture stage with the next texture stage.
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).

Bump-mapping members
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.0 and 7.0 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.x 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.

Triadic texture blending members
D3DTOP_MULTIPLYADD
Performs a multiply-accumulate operation. It takes the last two arguments, multiplies them, adds them to the remaining input/source argument, and then places this sum into the result.

SRGBA = Arg1 + Arg2 * Arg3

D3DTOP_LERP
Linearly interpolates between the 2nd and 3rd source arguments by a proportion specified in the 1st source argument.

SRGBA = (Arg1) * Arg2 + (1-Arg1) * Arg3

Remarks

The members of this type are used when setting color or alpha operations by using the D3DTSS_COLOROP or D3DTSS_ALPHAOP texture stage state values with the Direct3DDevice8.SetTextureStageState method.

In the above formulas, SRGBA is the RGBA color produced by a texture operation, and Arg1 and Arg2 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

CONST_D3DTEXTURESTAGESTATETYPE


CONST_D3DTEXTURESTAGESTATETYPE

Defines texture stage states.

Enum CONST_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_ADDRESSU              = 13
    D3DTSS_ADDRESSV              = 14
    D3DTSS_BORDERCOLOR           = 15
    D3DTSS_MAGFILTER             = 16 (&H10)
    D3DTSS_MINFILTER             = 17 (&H11)
    D3DTSS_MIPFILTER             = 18 (&H12)
    D3DTSS_MIPMAPLODBIAS         = 19 (&H13)
    D3DTSS_MAXMIPLEVEL           = 20 (&H14)
    D3DTSS_MAXANISOTROPY         = 21 (&H15)
    D3DTSS_BUMPENVLSCALE         = 22 (&H16)
    D3DTSS_BUMPENVLOFFSET        = 23 (&H17)
    D3DTSS_TEXTURETRANSFORMFLAGS = 24 (&H18)
    D3DTSS_ADDRESSW              = 25 (&H19)
    D3DTSS_COLORARG0             = 26 (&H1A)
    D3DTSS_ALPHAARG0             = 27 (&H1B)
    D3DTSS_RESULTARG             = 28 (&H1C)
End Enum

Constants

D3DTSS_COLOROP
The texture-stage state is a texture color blending operation identified by one member of the CONST_D3DTEXTUREOP enumeration. The default value for the first texture stage (stage 0) is D3DTOP_MODULATE, and for all other stages the default is D3DTOP_DISABLE.
D3DTSS_COLORARG1
The texture-stage state is the first color argument for the stage, identified by one of the texture argument flags. The default argument is D3DTA_TEXTURE.
D3DTSS_COLORARG2
The texture-stage state is the second color argument for the stage, identified by one of the texture argument flags. The default argument is D3DTA_CURRENT.
D3DTSS_ALPHAOP
The texture-stage state is a texture alpha blending operation identified by one member of the CONST_D3DTEXTUREOP enumeration. 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
The texture-stage state is the first alpha argument for the stage, identified by one of the texture argument flags. The default argument is D3DTA_TEXTURE. If no texture is set for this stage, the default argument is D3DTA_DIFFUSE.
D3DTSS_ALPHAARG2
The texture-stage state is the second alpha argument for the stage, identified by one of the texture argument flags. The default argument is D3DTA_CURRENT.
D3DTSS_BUMPENVMAT00
The texture-stage state is a value for the [0][0] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_BUMPENVMAT01
The texture-stage state is a value for the [0][1] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_BUMPENVMAT10
The texture-stage state is a value for the [1][0] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_BUMPENVMAT11
The texture-stage state is a 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. Set this state to the zero-based index of the coordinate set for each vertex that this texture stage uses. 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).

This flag is used only for fixed-function vertex processing. For example, it should not be used with vertex shaders. 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.

Additionally, applications can include, as logical Or with the index being set, one of the following flags to request that Microsoft® Direct3D® automatically generate the input texture coordinates for a texture transformation. 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 defined by the CONST_D3DTSS_TCI_FLAGS enumeration are most useful when performing environment mapping.

D3DTSS_TCI_PASSTHRU
Use the specified texture coordinates contained within the vertex format. This value resolves to zero.
D3DTSS_TCI_CAMERASPACENORMAL
Use the vertex normal, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEPOSITION
Use the vertex position, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR
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_ADDRESSU
Member of the CONST_D3DTEXTUREADDRESS enumeration. Selects the texture-addressing method for the u coordinate. The default is D3DTADDRESS_WRAP.
D3DTSS_ADDRESSV
Member of the CONST_D3DTEXTUREADDRESS enumeration. Selects the texture-addressing method for the v coordinate. The default value is D3DTADDRESS_WRAP.
D3DTSS_BORDERCOLOR
Value that describes the color to use for rasterizing texture coordinates outside the [0.0,1.0] range. The default color is &H00000000.
D3DTSS_MAGFILTER
Member of the CONST_D3DTEXTUREFILTERTYPE enumeration that indicates the texture magnification filter to use when rendering the texture onto primitives. The default value is D3DTEXF_POINT.
D3DTSS_MINFILTER
Member of the CONST_D3DTEXTUREFILTERTYPE enumeration that indicates the texture minification filter to use when rendering the texture onto primitives. The default value is D3DTEXF_POINT.
D3DTSS_MIPFILTER
Member of the CONST_D3DTEXTUREFILTERTYPE enumeration that indicates the texture filter to use between mipmap levels. The default value is D3DTEXF_NONE.
D3DTSS_MIPMAPLODBIAS
Level of detail bias for mipmaps. Can be used to make textures appear more chunky or more blurred. The default value is 0.0.

Each unit of bias (+/-1.0) alters the selection by exactly one mipmap level. A negative bias causes the use of larger mipmap levels; the result is a sharper but more aliased image. A positive bias causes the use of smaller mipmap levels; the result is a more blurred image. A positive bias also causes less texture data to be referenced, which can boost performance on some systems.

D3DTSS_MAXMIPLEVEL
Maximum mipmap level of detail that the application allows, expressed as an index from the top of the mipmap chain. Lower values identify higher levels of detail within the mipmap chain. Zero, which is the default, indicates that all levels can be used. Nonzero values indicate that the application cannot display mipmaps that have a higher level of detail than the mipmap at the specified index.
D3DTSS_MAXANISOTROPY
Maximum level of anisotropy. The default value is 1.
D3DTSS_BUMPENVLSCALE
Scale for bump-map luminance. The default value is 0.0.
D3DTSS_BUMPENVLOFFSET
Offset for bump-map luminance. The default value is 0.0.
D3DTSS_TEXTURETRANSFORMFLAGS
Member of the CONST_D3DTEXTURETRANSFORMFLAGS enumeration that controls the transformation of texture coordinates for this texture stage. The default value is D3DTTFF_DISABLE.
D3DTSS_ADDRESSW
Member of the CONST_D3DTEXTUREADDRESS enumeration. Selects the texture-addressing method for the w coordinate. The default value is D3DTADDRESS_WRAP.
D3DTSS_COLORARG0
Settings for the third color operand for triadic operations (multiply, add, and linear interpolation), identified by one of the texture argument flags. 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 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 linear interpolation), identified by one of the texture argument flags. 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_RESULTARG
Setting to select destination register for the result of this stage, identified by one of the texture argument flags. 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.

Remarks

Members of this enumeration are used with the Direct3DDevice8.GetTextureStageState and Direct3DDevice8.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

Direct3DDevice8.GetTextureStageState, Direct3DDevice8.SetTextureStageState


CONST_D3DTEXTURETRANSFORMFLAGS

Defines texture-stage state values.

Enum CONST_D3DTEXTURETRANSFORMFLAGS
    D3DTTFF_DISABLE   =   0
    D3DTTFF_COUNT1    =   1
    D3DTTFF_COUNT2    =   2
    D3DTTFF_COUNT3    =   3
    D3DTTFF_COUNT4    =   4
    D3DTTFF_PROJECTED = 256 (&H100)
End Enum

Constants

D3DTTFF_DISABLE
Texture coordinates are passed directly to the rasterizer.
D3DTTFF_COUNT1
The rasterizer should expect 1-D texture coordinates.
D3DTTFF_COUNT2
The rasterizer should expect 2-D texture coordinates.
D3DTTFF_COUNT3
The rasterizer should expect 3-D texture coordinates.
D3DTTFF_COUNT4
The rasterizer should expect 4-D texture coordinates.
D3DTTFF_PROJECTED
The texture coordinates are all 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 is divided by the third coordinate before being passed to the rasterizer.

Remarks

These flags are used to set the value of the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state for the CONST_D3DTEXTURESTAGESTATETYPE enumeration.

See Also

CONST_D3DTEXTURESTAGESTATETYPE


CONST_D3DTRANSFORMSTATETYPE

Defines constants that identify the contents of a transformation matrix.

Enum CONST_D3DTRANSFORMSTATETYPE
    D3DTS_WORLD      =  1
    D3DTS_VIEW       =  2
    D3DTS_PROJECTION =  3
    D3DTS_WORLD1     =  4
    D3DTS_WORLD2     =  5
    D3DTS_WORLD3     =  6
    D3DTS_TEXTURE0   = 16 (&H10)
    D3DTS_TEXTURE1   = 17 (&H11)
    D3DTS_TEXTURE2   = 18 (&H12)
    D3DTS_TEXTURE3   = 19 (&H13)
    D3DTS_TEXTURE4   = 20 (&H14)
    D3DTS_TEXTURE5   = 21 (&H15)
    D3DTS_TEXTURE6   = 22 (&H16)
    D3DTS_TEXTURE7   = 23 (&H17)
End Enum

Constants

D3DTS_WORLD
Matrix contains a world transform.
D3DTS_VIEW
Matrix contains a view transform.
D3DTS_PROJECTION
Matrix contains a projection transform.
D3DTS_WORLD1 through D3DTS_WORLD3
Matrix contains values that can be used to blend vertices. The values are blending (beta) weight values specified in the vertex format.
D3DTS_TEXTURE0 through D3DTS_TEXTURE7
Matrix contains a transform matrix for a texture stage.

See Also

Direct3DDevice8.GetTransform, Direct3DDevice8.MultiplyTransform, Direct3DDevice8.SetTransform


CONST_D3DTSS_TCI_FLAGS

Defines constants specifying that Microsoft® Direct3D® automatically generate the input texture coordinates for a texture transformation.

Enum CONST_D3DTSS_TCI_FLAGS
    D3DTSS_TCI_PASSTHRU                    =      0
    D3DTSS_TCI_CAMERASPACENORMAL           =  65536 (&H10000)
    D3DTSS_TCI_CAMERASPACEPOSITION         = 131072 (&H20000)
    D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR = 196608 (&H30000)
End Enum

Constants

D3DTSS_TCI_PASSTHRU
Use the specified texture coordinates contained within the vertex format. This value resolves to zero.
D3DTSS_TCI_CAMERASPACENORMAL
Use the vertex normal, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEPOSITION
Use the vertex position, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR
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.

Remarks

These flags are used to set the value of the D3DTSS_TEXCOORDINDEX member for the CONST_D3DTEXTURESTAGESTATETYPE enumeration.

See Also

CONST_D3DTEXTURESTAGESTATETYPE


CONST_D3DUSAGEFLAGS

Defines constants that define usages for resources.

Enum CONST_D3DUSAGEFLAGS
    D3DUSAGE_RENDERTARGET       =   1
    D3DUSAGE_DEPTHSTENCIL       =   2
    D3DUSAGE_WRITEONLY          =   8
    D3DUSAGE_SOFTWAREPROCESSING =  16 (&H10)
    D3DUSAGE_DONOTCLIP          =  32 (&H20)
    D3DUSAGE_POINTS             =  64 (&H40)
    D3DUSAGE_RTPATCHES          = 128 (&H80)
    D3DUSAGE_NPATCHES           = 256 (&H100)
    D3DUSAGE_DYNAMIC            = 512 (&H200)
End Enum

Constants

D3DUSAGE_RENDERTARGET
Set to indicate that the surface is to be used as a render target. The resource can be passed to the RenderTarget parameter of the Direct3DDevice8.SetRenderTarget method.

This usage is automatically applied for a render target resource.

D3DUSAGE_DEPTHSTENCIL
Set to indicate that the surface is to be used as a depth-stencil surface. The resource can be passed to the NewZStencil parameter of SetRenderTarget.

This usage is automatically applied for a depth-stencil resource.

D3DUSAGE_WRITEONLY
Informs the system that the application writes only to the buffer. Using this flag enables the driver to select the best memory location for efficient write operations and rendering. Attempts to read from a buffer that is created with this capability can result in degraded performance.

This flag is valid only for index and vertex buffer resources.

D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the buffer is to be used with software processing.

This flag is valid only for index and vertex buffer resources.

D3DUSAGE_DONOTCLIP
Set to indicate that the vertex buffer content will never require clipping.

This flag is valid only for vertex buffer resources.

D3DUSAGE_POINTS
Set to indicate when a vertex or index buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_RTPATCHES
Set to indicate when a vertex or index buffer is to be used for drawing high-order surfaces.
D3DUSAGE_NPATCHES
Set to indicate when the vertex or index buffer is to be used for drawing N patches.
D3DUSAGE_DYNAMIC
Set to indicate when the vertex or index buffer requires dynamic memory usage. This usage is useful for drivers since it enables them to decide where to place the driver. 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 usage. 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 and index buffers created with D3DUSAGE_DYNAMIC. They are not valid flags on static vertex buffers.

Note that D3DUSAGE_DYNAMIC cannot be specified on managed vertex and index buffers. For more information, see Managing Resources.

This flag is valid only for index and vertex buffer resources.

See Also

Direct3DDevice8.CreateCubeTexture, Direct3DDevice8.CreateIndexBuffer, Direct3DDevice8.CreateTexture, Direct3DDevice8.CreateVertexBuffer, Direct3DDevice8.CreateVolumeTexture


CONST_D3DVERTEXBLENDFLAGS

Defines flags used to control the number or matrices that the system applies when performing multimatrix vertex blending.

Enum CONST_D3DVERTEXBLENDFLAGS
    D3DVBF_DISABLE     =   0
    D3DVBF_1WEIGHTS    =   1
    D3DVBF_2WEIGHTS    =   2
    D3DVBF_3WEIGHTS    =   3
    D3DVBF_TWEENING    = 255 (&HFF)
    D3DVBF_0WEIGHTS    = 256 (&H100)
End Enum

Constants

D3DVBF_DISABLE
Disable vertex blending; apply only the world matrix specified by the D3DTS_WORLD transformation state.
D3DVBF_1WEIGHTS
Enable vertex blending between the two matrices set by the D3DTS_WORLD and D3DTS_WORLD1 transformation states.
D3DVBF_2WEIGHTS
Enable vertex blending between the three matrices set by the D3DTS_WORLD, D3DTS_WORLD1, and D3DTS_WORLD2 transformation states.
D3DVBF_3WEIGHTS
Enable vertex blending between the four matrices set by the D3DTS_WORLD, D3DTS_WORLD1, D3DTS_WORLD2, and D3DTS_WORLD3 transformation states.
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

These flags are used to set the value of the D3DRS_VERTEXBLEND render state for the CONST_D3DRENDERSTATETYPE enumeration.

Geometry blending (multimatrix vertex blending) requires that your application use a vertex format that has blending (beta) weights for each vertex.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DVTXPCAPSFLAGS

Defines vertex processing capabilities.

Enum CONST_D3DVTXPCAPSFLAGS
    D3DVTXPCAPS_TEXGEN            =  1
    D3DVTXPCAPS_MATERIALSOURCE7   =  2
    D3DVTXPCAPS_DIRECTIONALLIGHTS =  8
    D3DVTXPCAPS_POSITIONALLIGHTS  = 16 (&H10)
    D3DVTXPCAPS_LOCALVIEWER       = 32 (&H20)
    D3DVTXPCAPS_TWEENING          = 64 (&H40)
End Enum

Constants

D3DVTXPCAPS_TEXGEN
Device can generate texture coordinates.
D3DVTXPCAPS_MATERIALSOURCE7
Device supports selectable vertex color sources.
D3DVTXPCAPS_DIRECTIONALLIGHTS
Device supports directional lights.
D3DVTXPCAPS_POSITIONALLIGHTS
Device supports positional lights (including point lights and spotlights).
D3DVTXPCAPS_LOCALVIEWER
Device supports local viewer.
D3DVTXPCAPS_TWEENING
Device supports vertex tweening.

Remarks

These flags can be combined and present in the VertexProcessingCaps member of D3DCAPS8.

See Also

D3DCAPS8


CONST_D3DWRAPBIAS

Defined to enable or disable texture wrapping based on the zero-based integer of a texture coordinate set.

Enum CONST_D3DWRAPBIAS
    D3DRENDERSTATE_WRAPBIAS = 128 (&H80)
End Enum

Constants

D3DRENDERSTATE_WRAPBIAS
Wrap bias. For implementation details, see Remarks.

Remarks

Microsoft® 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_WRAPn state values). Add the D3DRENDERSTATE_WRAPBIAS value to the zero-based index of a texture coordinate set to calculate the D3DRS_WRAPn value that corresponds to that index, as shown in the following example:

    On Local Error Resume Next

    ' Enable U/V wrapping for textures that use the texture
    ' coordinate set at the index within the lIndex variable.
    Call d3dDevice8.SetRenderState( _
            lIndex + D3DRENDERSTATE_WRAPBIAS, _
            D3DWRAPCOORD_0 Or D3DWRAPCOORD_1)

    ' If lIndex is 3, the value that results from
    ' the addition equates to D3DRENDERSTATE_WRAP3 (131).
    If Err.Number <> DD_OK Then
       ' Code to handle error goes here.
    End If

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DWRAPFLAGS

Defines texture wrapping behavior for multiple sets of texture coordinates.

Enum CONST_D3DWRAPFLAGS
    D3DWRAP_U      = 1
    D3DWRAPCOORD_0 = 1
    D3DWRAP_V      = 2
    D3DWRAPCOORD_1 = 2
    D3DWRAP_W      = 4
    D3DWRAPCOORD_2 = 4
    D3DWRAPCOORD_3 = 8
End Enum

Constants

D3DWRAP_U and D3DWRAPCOORD_0
Wrap in the direction of the first dimension for a given texture.
D3DWRAP_V and D3DWRAPCOORD_1
Wrap in the direction of the second dimension for a given texture.
D3DWRAP_W and D3DWRAPCOORD_2
Wrap in the direction of the third dimension for a given texture.
D3DWRAPCOORD_3
Wrap in the direction of the fourth dimension for a given texture.

Remarks

These flags set the value of the D3DRS_WRAP0 through D3DRS_WRAP7 render states for the CONST_D3DRENDERSTATETYPE enumeration.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DZBUFFERTYPE

Defines constants that describe depth-buffer formats.

Enum CONST_D3DZBUFFERTYPE
    D3DZB_FALSE = 0
    D3DZB_TRUE  = 1
    D3DZB_USEW  = 2
End Enum

Constants

D3DZB_FALSE
Disable depth buffering.
D3DZB_TRUE
Enable z-buffering.
D3DZB_USEW
Enable w-buffering.

Remarks

These flags are used to set the value of the D3DRS_ZENABLE render state for the CONST_D3DRENDERSTATETYPE enumeration.

See Also

CONST_D3DRENDERSTATETYPE


Texture Argument Flags

Each texture stage for a device can have two texture arguments that affect the color or alpha channel of the texture.

Set and retrieve texture arguments by calling the Direct3DDevice8.SetTextureStageState and Direct3DDevice8.GetTextureStageState, and specifying the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAARG1 or D3DTSS_ALPHAARG2 constants of the CONST_D3DTEXTURESTAGESTATETYPE enumeration.

The following flags, organized as arguments and modifiers, can be used with color and alpha arguments for a texture stage. You can combine an argument flag with a modifier, but you cannot combine two argument flags.

Argument flags
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 &HFFFFFFFF. 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 &HFFFFFFFF. Permissions are read only.
D3DTA_TEMP
Select the temporary register color. Permissions are read/write.
D3DTA_TEXTURE
The texture argument is the texture color for this texture stage. If no texture is set for a stage that uses this blending argument, the system defaults to a color value of R: 1.0, G: 1.0, B: 1.0 for color, and 1.0 for alpha. Permissions are read-only.
D3DTA_TFACTOR
The texture argument is the texture factor set in a previous call to the Direct3DDevice8.SetRenderState with the D3DRS_TEXTUREFACTOR render state value.
Modifier flags
D3DTA_ALPHAREPLICATE
Replicate the alpha information to all color channels before the operation completes.
D3DTA_COMPLEMENT
Invert the argument so that, if the result of the argument were referred to by the variable x, the value would be 1.0 - x.


Flexible Vertex Format Flags

The flexible vertex format (FVF) is used to describe the contents of vertices stored interleaved in a single data stream. A FVF code is generally used to specify data to be processed by fixed function vertex processing.

The following flags defined by the CONST_D3DFVFFLAGS enumeration, describe a vertex format.

Flexible vertex format (FVF) flags
D3DFVF_DIFFUSE
Vertex format includes a diffuse color component.
D3DFVF_NORMAL
Vertex format includes a vertex normal vector. This flag cannot be used with the D3DFVF_XYZRHW flag.
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.
D3DFVF_SPECULAR
Vertex format includes a specular color component.
D3DFVF_VERTEX )
Same as specifying (D3DFVF_XYZ Or D3DFVF_NORMAL Or D3DFVF_TEX1).
D3DFVF_XYZ
Vertex format includes the position of an untransformed vertex. This flag cannot be used with the D3DFVF_XYZRHW flag.
D3DFVF_XYZRHW
Vertex format includes the position of a transformed vertex. This flag cannot be used with the D3DFVF_XYZ or D3DFVF_NORMAL flags.
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, Microsoft® Direct3D® can blend with up to three weighting values and four blending matrices.
Texture-related FVF flags
D3DFVF_TEX0 through D3DFVF_TEX8
Number of texture coordinate sets for this vertex. The actual values for these flags are not sequential. For information on additional texture-related FVF flags, see the CONST_D3DFVFTEXTUREFORMATS enumeration.
Mask values
D3DFVF_POSITION_MASK
Mask for position bits.
D3DFVF_RESERVED0 and D3DFVF_RESERVED2
Mask values for reserved bits in the flexible vertex format. Do not use.
D3DFVF_TEXCOUNT_MASK
Mask value for texture flag bits.
Miscellaneous
D3DFVF_TEXCOUNT_SHIFT
The number of bits by which to shift an integer value that identifies the number of a texture coordinates for a vertex.

See Also

Vertex Formats, Geometry Blending


Error Codes

Errors are represented by negative values and cannot be combined. The following is a list of the values that can be returned by Microsoft® Direct3D® methods. See the individual method descriptions for lists of the values that each can return.

D3D_OK
No error occurred.
D3DERR_CANNOTTATTRSORT
Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
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. This generally occurs when a multitexture device requires that all palletized textures simultaneously enabled also share the same palette.
D3DERR_DEVICELOST
The device is lost and cannot be restored at the current time, so rendering is not possible.
D3DERR_DEVICENOTRESET
The device cannot be reset.
D3DERR_DRIVERINTERNALERROR
Internal driver error.
D3DERR_INVALIDCALL
The method call is invalid. For example, a method's parameter may have an invalid value.
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
The queried technique is not supported by this device.
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 operations for the alpha channel.
D3DERR_UNSUPPORTEDCOLORARG
The device does not support a specified texture-blending arguments for color values.
D3DERR_UNSUPPORTEDCOLOROPERATION
The device does not support a specified texture-blending operation for color values.
D3DERR_UNSUPPORTEDFACTORVALUE
The specified texture factor value is not supported by the device.
D3DERR_UNSUPPORTEDTEXTUREFILTER
The specified texture filter is not supported by the device.
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_OUTOFMEMORY
Direct3D could not allocate sufficient memory to complete the call.


Direct3DX Visual Basic Reference

This section contains reference information for the API elements provided by the Direct3DX utility library. Reference material is divided into the following categories.

  • Classes
  • Functions
  • Types
  • Enumerations
  • Error Codes


Classes

This section contains reference information for the classes provided by the Direct3DX utility library. The following classes are used with the Direct3DX utility library.

  • D3DX8
  • D3DXBaseMesh
  • D3DXBuffer
  • D3DXFont
  • D3DXMesh
  • D3DXPMesh
  • D3DXRenderToSurface
  • D3DXSkinMesh
  • D3DXSPMesh
  • D3DXSprite


D3DX8

Applications use the methods of the D3DX8 class to simplify complicated tasks such as creating textures, manipulating meshes, drawing shapes, and assembling shaders.

An instance of the D3DX8 class is obtained by declaring an object variable and setting that variable to a new instance of D3DX8, as shown in the following code fragment.

Dim d3dx As D3DX8
Set d3dx = New D3DX8

The methods of the D3DX8 class can be organized into the following groups.

Meshes | BoxBoundProbe
 | CleanMesh
 | ComputeBoundingBox
 | ComputeBoundingBoxFromMesh
 | ComputeBoundingSphere
 | ComputeBoundingSphereFromMesh
 | ComputeNormals
 | CreateBuffer
 | CreateMesh
 | CreateMeshFVF
 | CreatePolygon
 | CreateSkinMesh
 | CreateSkinMeshFromMesh
 | CreateSkinMeshFVF
 | CreateSPMesh
 | DeclaratorFromFVF
 | FVFFromDeclarator
 | GeneratePMesh
 | Intersect
 | LoadPMeshFromFile
 | LoadSkinMeshFromXof
 | LoadMeshFromX
 | LoadMeshFromXof
 | SaveMeshToX
 | SavePMeshToFile
 | SimplifyMesh
 | SphereBoundProbe
 | TessellateNPatches
 | ValidMesh
Miscellaneous | BufferGetBoneCombo
 | BufferGetBoneComboBoneIds
 | BufferGetBoneName
 | BufferGetData
 | BufferGetMaterial
 | BufferGetTextureName
 | BufferSetData
 | CreateFont
 | CreateRenderToSurface
 | CreateSprite
 | GetErrorString
 | GetFVFVertexSize
Shaders | AssembleShader
 | AssembleShaderFromFile
Shapes | CreateBox
 | CreateCylinder
 | CreateSphere
 | CreateTeapot
 | CreateText
 | CreateTorus
Textures | CheckCubeTextureRequirements
 | CheckTextureRequirements
 | CheckVolumeTextureRequirements
 | CreateCubeTexture
 | CreateCubeTextureFromFile
 | CreateCubeTextureFromFileEx
 | CreateCubeTextureFromFileInMemory
 | CreateCubeTextureFromFileInMemoryEx
 | CreateTexture
 | CreateTextureFromFile
 | CreateTextureFromFileEx
 | CreateTextureFromFileInMemory
 | CreateTextureFromFileInMemoryEx
 | CreateTextureFromResource
 | CreateTextureFromResourceEx
 | CreateVolumeTexture
 | FilterCubeTexture
 | FilterTexture
 | FilterVolumeTexture
 | LoadSurfaceFromFile
 | LoadSurfaceFromFileInMemory
 | LoadSurfaceFromMemory
 | LoadSurfaceFromResource
 | LoadSurfaceFromSurface
 | LoadVolumeFromMemory
 | LoadVolumeFromVolume


D3DX8.AssembleShader

Assembles an ASCII description of a pixel or vertex shader into binary form, where the shader source is in memory.

object.AssembleShader( _
    SrcData As Any, _
    Flags As Long, _
    Constants As D3DXBuffer) As D3DXBuffer

Parts

object
Object expression that resolves to a D3DX8 object.
SrcData
Source code from which to assemble the shader.
Flags
A combination of the members of the CONST_D3DXASM type, specifying assembly options.
Constants
D3DXBuffer object, to be filled with the constant declarations. These constants are returned as a vertex shader declaration fragment. It is up to the application to insert the contents of this buffer into their declaration. For pixel shaders this parameter is meaningless because constant declarations are included in the assembled shader. This parameter is ignored if it is NULL.

Return Values

Returns a D3DXBuffer object, containing the compiled object code.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.AssembleShaderFromFile

Assembles an ASCII description of a pixel or vertex shader into binary form.

object.AssembleShaderFromFile( _
    SrcFile As String, _
    Flags As Long, _
    ErrLog As String, _
    Constants As D3DXBuffer) As D3DXBuffer

Parts

object
Object expression that resolves to a D3DX8 object.
SrcFile
Source file name.
Flags
A combination of the members of the CONST_D3DXASM type, specifying assembly options.
ErrLog
Contains ASCII error messages.
Constants
D3DXBuffer object, to be filled with the constant declarations. These constants are returned as a vertex shader declaration fragment. It is up to the application to insert the contents of this buffer into their declaration. For pixel shaders this parameter is meaningless because constant declarations are included in the assembled shader. This parameter is ignored if it is NULL.

Return Values

Returns a D3DXBuffer object, containing the compiled object code.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.BoxBoundProbe

Determines if a ray intersects the volume of a box's bounding box.

object.BoxBoundProbe( _
    MinVert As D3DVECTOR, _
    MaxVert As D3DVECTOR, _
    RayPosition As D3DVECTOR, _
    Raydirection As D3DVECTOR) As Boolean

Parts

object
Object expression that resolves to a D3DX8 object.
MinVert
A D3DVECTOR type, describing the lower-left corner of the bounding box. See Remarks.
MaxVert
A D3DXVECTOR type, describing the upper-right corner of the bounding box. See Remarks.
RayPosition
A D3DXVECTOR type, specifying the origin coordinate of the ray.
Raydirection
A D3DXVECTOR type, specifying the direction of the ray.

Return Values

Returns 1 if the ray intersects the volume of the box's bounding box. Otherwise, returns 0.

Remarks

D3DX8.BoxBoundProbe determines if the ray intersects the volume of the box's bounding box, not just the surface of the box.

The D3DXVECTOR values passed to D3DX8.BoxBoundProbe 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, -1

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.BufferGetBoneCombo

Retrieves a bone combination from a buffer.

object.BufferGetBoneCombo( _
    BoneComboBuffer As D3DXBuffer, _
    Index As Long, _
    BoneCombo As D3DXBONECOMBINATION)

Parts

object
Object expression that resolves to a D3DX8 object.
BoneComboBuffer
D3DXBuffer object, the buffer containing the bone combination data.
Index
Index value, specifying the index into the buffer.
BoneCombo
D3DXBONECOMBINATION type, to be filled with the bone combination data for the bone specified by Index.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.LoadSkinMeshFromXof, D3DXSkinMesh.ConvertToBlendedMesh


D3DX8.BufferGetBoneComboBoneIds

Retrieves the bone IDs from a bone combination buffer.

object.BufferGetBoneComboBoneIds( _

    BoneComboBuffer As D3DXBuffer, _
    Index As Long, _
    PaletteSize As Long, _
    BoneIds As Any)

Parts

object
Object expression that resolves to a D3DX8 object.
BoneComboBuffer
D3DXBuffer object, the buffer containing the bone data.
Index
Index value, specifying the index into the buffer.
PaletteSize
The maximum number of matrices that the bone combination can have.
BoneIds
First element of 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 D3DXSkinMesh.ConvertToIndexedBlendedMesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXSkinMesh.GetMaxVertexInfluences, D3DXSkinMesh.GetNumBoneInfluences


D3DX8.BufferGetBoneName

Retrieves the name of a bone from a buffer.

object.BufferGetBoneName( _
    BoneNameBuffer As D3DXBuffer, _
    Index As Long) As String

Parts

object
Object expression that resolves to a D3DX8 object.
BoneNameBuffer
D3DXBuffer object, the buffer containing the bone data.
Index
Index value, specifying the index into the buffer.

Return Values

String identifying the name of the bone.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.BufferGetData

Retrieves data from a buffer.

object.BufferGetData( _
    Buffer As D3DXBuffer, _
    Index As Long, _
    TypeSize As Long, _
    TypeCount As Long, _
    Data As Any)

Parts

object
Object expression that resolves to a D3DX8 object.
Buffer
D3DXBuffer object, the buffer containing the data to retrieve.
Index
Index value, specifying the index into the buffer.
TypeSize
Size of the data type to retrieve from the buffer, in bytes.
TypeCount
Count of elements to retrieve from the buffer.
Data
After the method returns, an object holding the retrieved buffer data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.BufferGetMaterial

Retrieves material from a buffer.

object.BufferGetMaterial( _
    MaterialBuffer As D3DXBuffer, _
    Index As Long, _
    Mat As D3DMATERIAL8)

Parts

object
Object expression that resolves to a D3DX8 object.
MaterialBuffer
D3DXBuffer object, the buffer containing the material to retrieve.
Index
Index value, specifying the buffer's index.
Mat
D3DMATERIAL8 object; the material retrieved from the queried buffer.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.BufferGetTextureName

Retrieves the name of a texture from a buffer.

object.BufferGetTextureName( _
    MaterialBuffer As D3DXBuffer, _
    Index As Long) As String

Parts

object
Object expression that resolves to a D3DX8 object.
MaterialBuffer
D3DXBuffer object, the buffer containing the material to retrieve.
Index
Index value, specifying the buffer's index.

Return Values

Returned String, identifying the name of the texture contained in the queried buffer.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.BufferSetData

Sets data in a buffer.

object.BufferSetData( _
    Buffer As D3DXBuffer, _
    Index As Long, _
    TypeSize As Long, _
    TypeCount As Long, _
    Data As Any)

Parts

object
Object expression that resolves to a D3DX8 object.
Buffer
D3DXBuffer object, the buffer to load with data.
Index
Index value, specifying the index into the buffer.
TypeSize
Size of the data type to load into the buffer, in bytes.
TypeCount
Count of elements to load into the buffer.
Data
An object holding the data to load into the buffer.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.CheckCubeTextureRequirements

Checks cube texture creation parameters.

object.CheckCubeTextureRequirements( _
    Device As Direct3DDevice8, _
    Size As Long, _
    NumMipLevels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL)

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device associated with the cube texture.
Size
Requested width and height in pixels, or ByVal 0. Returns the corrected size.
NumMipLevels
Number of requested mipmap levels, or ByVal 0. Returns the corrected number of mipmap levels.
Usage
0 or the D3DUSAGE_RENDERTARGET member of the CONST_D3DUSAGEFLAGS enumeration. Specifying D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling Direct3D8.CheckDeviceFormat.
Format
Member of the CONST_D3DFORMAT enumeration. Specifies the desired pixel format. Returns the corrected format.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the cube texture should be placed.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using Direct3DCubeTexture8.GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

If parameters to this method are invalid, this function returns corrected parameters.


D3DX8.CheckTextureRequirements

Checks texture creation parameters.

object.CheckTextureRequirements( _
    Device As Direct3DDevice8, _
    Width As Long, _
    Height As Long, _
    NumMipLevels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL)

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device associated with the cube texture.
Width
Requested width in pixels, or ByVal 0. Returns the corrected size.
Height
Requested height in pixels, or ByVal 0. Returns the corrected size.
NumMipLevels
Number of requested mipmap levels, or ByVal 0. Returns the corrected number of mipmap levels.
Usage
0 or the D3DUSAGE_RENDERTARGET member of the CONST_D3DUSAGEFLAGS enumeration. Specifying D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling Direct3D8.CheckDeviceFormat.
Format
Member of the CONST_D3DFORMAT enumeration. Specifies the desired pixel format. Returns the corrected format.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the texture should be placed.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If parameters to this method are invalid, this function returns corrected parameters.


D3DX8.CheckVolumeTextureRequirements

Checks volume texture creation parameters.

object.CheckVolumeTextureRequirements( _
    Device As Direct3DDevice8, _
    Width As Long, _
    Height As Long, _
    Depth As Long, _
    NumMipLevels As Long, _
    Usage As Long, _
    PixelFormat CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL)

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device associated with the volume texture.
Width
Requested width in pixels, or ByVal 0. Returns the corrected size.
Height
Requested height in pixels, or ByVal 0. Returns the corrected size.
Depth
Requested depth in pixels, or ByVal 0. Returns the corrected size.
NumMipLevels
Number of requested mipmap levels, or ByVal 0. Returns the corrected number of mipmap levels.
Usage
Currently not used, set to 0.
PixelFormat
Member of the CONST_D3DFORMAT enumeration. Specifies the desired pixel format. Returns the corrected format.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the volume texture should be placed.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If parameters to this function are invalid, this function returns corrected parameters.


D3DX8.CleanMesh

Cleans a mesh, preparing it for simplification.

object.CleanMesh( _
    MeshIn As D3DXMesh, _
    Adjacency As Any) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
MeshIn
D3DXMesh object, representing the mesh to be cleaned.
Adjacency
First element of an array of three Long values per face that specify the three neighbors for each face in the mesh to be cleaned. The same mesh is returned that was passed in if no cleaning was necessary.

Return Values

D3DXMesh object, representing the returned cleaned mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method cleans the mesh by adding another vertex where two fans of triangles share the same vertex.

The following code fragment shows how to use a D3DXBuffer object to pass adjacency information.

Dim d3dxbAdjacency As D3DXBuffer
Dim mesh As D3DXMesh

' This code fragment assumes that d3dxbAdjacency and mesh have been properly
' initialized.
Call D3DX8.CleanMesh(d3dxm, ByVal d3dxbAdjacency.GetBufferPointer)


D3DX8.ComputeBoundingBox

Computes a bounding box.

object.ComputeBoundingBox( _
    PointsFVF As Any, _
    NumVertices As Long, _
    FVF As Long, _
    MinArray As D3DVECTOR, _
    MaxArray As D3DVECTOR)

Parts

object
Object expression that resolves to a D3DX8 object.
PointsFVF
Buffer containing the vertex data around which to calculate the bounding box.
NumVertices
Number of vertices.
FVF
Combination of flexible vertex format flags that describes the vertex format.
MinArray
D3DVECTOR type, describing the returned lower-left corner of the bounding box. See Remarks.
MaxArray
D3DVECTOR type, describing the returned upper-right corner of the bounding box. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DVECTOR values returned by ComputeBoundingBox 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, -1

See Also

D3DX8.ComputeBoundingBoxFromMesh


D3DX8.ComputeBoundingBoxFromMesh

Computes a bounding box from a mesh.

object.ComputeBoundingBoxFromMesh( _
    MeshIn As D3DXMesh, _
    MinArray As D3DVECTOR, _
    MaxArray As D3DVECTOR)

Parts

object
Object expression that resolves to a D3DX8 object.
MeshIn
D3DXMesh object, representing the input mesh.
MinArray
D3DVECTOR type, describing the returned lower-left corner of the bounding box. See Remarks.
MaxArray
D3DVECTOR type, describing the returned upper-right corner of the bounding box. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DVECTOR values returned by ComputeBoundingBoxFromMesh 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, -1

See Also

D3DX8.ComputeBoundingBox


D3DX8.ComputeBoundingSphere

Computes a bounding sphere.

object.ComputeBoundingSphere( _
    PointsFVF As Any, _
    NumVertices As Long, _
    FVF As Long, _
    Center As D3DVECTOR, _
    RadiusArray As Single)

Parts

object
Object expression that resolves to a D3DX8 object.
PointsFVF
Buffer containing the vertex data around which to calculate the bounding sphere.
NumVertices
Number of vertices.
FVF
Combination of flexible vertex format flags that describes the vertex format.
Center
D3DVECTOR type, defining the coordinate center of the returned bounding sphere.
RadiusArray
Radius of the returned bounding sphere.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.ComputeBoundingSphereFromMesh

Computes a bounding sphere from a mesh.

object.ComputeBoundingSphereFromMesh( _
    MeshIn As D3DXMesh, _
    Center As D3DVECTOR, _
    RadiusArray As Single)

Parts

object
Object expression that resolves to a D3DX8 object.
MeshIn
D3DXMesh object, representing the input mesh.
Center
D3DVECTOR type, defining the coordinate center of the returned bounding sphere.
RadiusArray
Radius of the returned bounding sphere.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.ComputeNormals

Computes normals for each vertex in a mesh.

object.ComputeNormals( _
    Mesh As D3DXBaseMesh)

Parts

object
Object expression that resolves to a D3DX8 object.
Mesh
D3DXBaseMesh object representing the normalized mesh object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Note The input mesh must have the D3DFVF_NORMAL flag specified in its FVF.

A normal for a vertex is generated by averaging the normals of all faces that share that vertex.


D3DX8.CreateBox

Uses a left-handed coordinate system to create a mesh containing an axis-aligned box.

object.CreateBox( _
    D3DDevice As Direct3DDevice8, _
    Width As Single, _
    Height As Single, _
    Depth As Single, _
    RetAdjacency As D3DXBuffer)As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
D3DDevice
A Direct3DDevice8 object, representing the device associated with the created box mesh.
Width
Width of the box, along the x-axis.
Height
Height of the box, along the y-axis.
Depth
Depth of the box, along the z-axis.
RetAdjacency
D3DXBuffer object. When the method returns, this parameter is filled with an array of three Long values per face that specify the three neighbors for each face in the mesh.

Return Values

.D3DXMesh object, representing the output box.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.CreateBuffer

Creates a buffer object.

object.CreateBuffer( _
    NumBytes As Long) As D3DXBuffer

Parts

object
Object expression that resolves to a D3DX8 object.
NumBytes
Size of the buffer to create, in bytes.

Return Values

D3DXBuffer object representing the created buffer.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.CreateCubeTexture

Creates an empty cube texture, adjusting the calling parameters as necessary.

object.CreateCubeTexture( _
    Device As Direct3DDevice8, _
    Size As Long, _
    MipLevels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL) As Direct3DCubeTexture8

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the cube texture.
Size
Width and height of the cube texture, in pixels. So, if the cube texture is an 8 pixel by 8 pixel cube, the value for this parameter should be 8. Note that this value must be nonzero.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT as defined by the CONST_D3DXENUM enumeration, a complete mipmap chain is created.
Usage
0 or the D3DUSAGE_RENDERTARGET member of the CONST_D3DUSAGEFLAGS enumeration. Specifying D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling Direct3D8.CheckDeviceFormat.
Format
Member of the CONST_D3DFORMAT enumeration, describing the requested pixel format for the cube texture. The returned cube texture might have a format different from that specified by Format. Applications should check the format of the returned cube texture.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the cube texture should be placed.

Return Values

Direct3DCubeTexture8 object representing the created cube texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DXERR_INVALIDDATA
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using Direct3DCubeTexture8.GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

Internally, D3DX8.CreateCubeTexture uses D3DX8.CheckCubeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DX8.CreateCubeTexture often succeed where calls to Direct3DDevice8.CreateCubeTexture fail.


D3DX8.CreateCubeTextureFromFile

Creates a cube texture from a file.

object.CreateCubeTextureFromFile( _
    Device As Direct3DDevice8, _
    SrcFile As String) As Direct3DCubeTexture8

Parameters

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the cube texture.
SrcFile
String that specifies the file from which to create the cube texture. See Remarks.

Return Values

Direct3DCubeTexture8 object representing the created cube texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Note that a resource created with this function will be placed in the memory class denoted by the D3DPOOL_MANAGED member of the CONST_D3DPOOL enumerated type.

CreateCubeTextureFromFile uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.


D3DX8.CreateCubeTextureFromFileEx

Creates a cube texture from a file. This is a more advanced method than D3DX8.CreateCubeTextureFromFile.

object.CreateCubeTextureFromFileEx( _
    Device As Direct3DDevice8, _
    SrcFile As String, _
    TextureSize As Long, _
    MipLevels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL, _
    Filter As Long, _
    MipFilter As Long, _
    ColorKey As Long, _
    SrcInfo As Any, _
    Palette As Any) As Direct3DCubeTexture8

Parameters

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the cube texture.
SrcFile
String that specifies the file from which to create the cube texture. See Remarks
TextureSize
Width and height of the cube texture, in pixels. So, if the cube texture is an 8 pixel by 8 pixel cube, the value for this parameter should be 8. Note that this value must be nonzero. If this value is 0 or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT as defined by the CONST_D3DXENUM enumeration, a complete mipmap chain is created.
Usage
0 or the D3DUSAGE_RENDERTARGET member of the CONST_D3DUSAGEFLAGS enumeration. Specifying D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling Direct3D8.CheckDeviceFormat.
Format
Member of the CONST_D3DFORMAT enumeration, describing the requested pixel format for the cube texture. The returned cube texture might have a format different from that specified by Format. Applications should check the format of the returned cube texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the cube texture should be placed.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
MipFilter
A combination of one or more mip filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.
SrcInfo
A D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or ByVal 0.
Palette
Object representing a 256-color palette to fill in, or Nothing.

Return Values

Direct3DCubeTexture8 object representing the created cube texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using Direct3DCubeTexture8.GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

CreateCubeTextureFromFileEx uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.


D3DX8.CreateCubeTextureFromFileInMemory

Creates a cube texture from a file in memory.

object.CreateCubeTextureFromFileInMemory( _
    Device As Direct3DDevice8, _
    SrcData As Any, _
    LengthInBytes As Long) As Direct3DCubeTexture8

Parameters

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the cube texture.
SrcData
File in memory from which to create the cube texture. See Remarks.
LengthInBytes
Size of the file in memory, in bytes.

Return Values

Direct3DCubeTexture8 object representing the created cube texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Note that a resource created with this function will be placed in the memory class denoted by the D3DPOOL_MANAGED member of the CONST_D3DPOOL enumerated type.

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 fails.

CreateCubeTextureFromFileInMemory uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.


D3DX8.CreateCubeTextureFromFileInMemoryEx

Creates a cube texture from a file in memory. This is a more advanced method than D3DX8.CreateCubeTextureFromFileInMemory.

object.CreateCubeTextureFromFileInMemoryEx( _
    Device As Direct3DDevice8, _
    SrcData As Any, _
    LengthInBytes As Long, _
    TextureSize As Long, _
    MipLevels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL, _
    Filter As Long, _
    MipFilter As Long, _
    ColorKey As Long, _
    SrcInfo As Any, _
    Palette As Any) As Direct3DCubeTexture8

Parameters

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the cube texture.
SrcData
File in memory from which to create the cube texture. See Remarks.
LengthInBytes
Size of the file in memory, in bytes.
TextureSize
Size of the file, in bytes.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT as defined by the CONST_D3DXENUM enumeration, a complete mipmap chain is created.
Usage
0 or the D3DUSAGE_RENDERTARGET member of the CONST_D3DUSAGEFLAGS enumeration. Specifying D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling Direct3D8.CheckDeviceFormat.
Format
Member of the CONST_D3DFORMAT enumeration, describing the requested pixel format for the cube texture. The returned cube texture might have a format different from that specified by Format. Applications should check the format of the returned cube texture. If this value is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the cube texture should be placed.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
MipFilter
A combination of one or more mip filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.
SrcInfo
A D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or ByVal 0.
Palette
Object representing a 256-color palette to fill in, or Nothing.

Return Values

Direct3DCubeTexture8 object representing the created cube texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using Direct3DCubeTexture8.GetCubeMapSurface and pass the resulting surface to 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 fails.

CreateCubeTextureFromFileInMemoryEx uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.


D3DX8.CreateCylinder

Uses a left-handed coordinate system to create a mesh containing a cylinder.

object.CreateCylinder( _
    Device As Direct3DDevice8, _
    Radius1 As Single, _
    Radius2 As Single
    Length As Single, _
    Slices As Long, _
    Stacks As Long, _
    RetAdjacency As D3DXBuffer) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object, representing the device associated with the created cylinder mesh.
Radius1
Radius at the negative Z end. Value should be greater than or equal to 0.0f.
Radius2
Radius at the positive Z end. Value should be greater than or equal to 0.0f.
Length
Length of the cylinder along the z-axis.
Slices
Number of slices about the main axis.
Stacks
Number of stacks along the main axis.
RetAdjacency
D3DXBuffer object. When the method returns, this parameter is filled with an array of three Long values per face that specify the three neighbors for each face in the mesh.

Return Values

D3DXMesh object, representing the output box.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using Direct3DCubeTexture8.GetCubeMapSurface and pass the resulting surface to SetRenderTarget


D3DX8.CreateFont

Creates a font object for a device and font.

object.CreateFont( _
    Device As Direct3DDevice8, _
    hFont As Long) As D3DXFont

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the font object.
hFont
Handle to the font object.

Return Values

D3DXFont object representing the created font object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.CreateMesh

Creates a mesh object using a declarator.

object.CreateMesh( _
    NumFaces As Long, _
    NumVertices As Long, _
    Options As Long, _
    Declaration As Any, _
    Device As Direct3DDevice8) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
NumFaces
Number of faces for the mesh. This parameter must be greater than 0.
NumVertices
Number of vertices for the mesh. This parameter must be greater than 0.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying options for the mesh.
Declaration
A declarator that describes the vertex format for the returned mesh. This parameter must map directly to an FVF.
Device
Direct3DDevice8 object, the device to be associated with the mesh.

Return Values

D3DXMesh object representing the created mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.DeclaratorFromFVF


D3DX8.CreateMeshFVF

Creates a mesh object using a flexible vertex format (FVF) code.

object.CreateMeshFVF( _
    NumFaces As Long, _
    NumVertices As Long, _
    Options As Long, _
    FVF As Long, _
    Device As Direct3DDevice8) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
NumFaces
Number of faces for the mesh. This parameter must be greater than 0.
NumVertices
Number of vertices for the mesh. This parameter must be greater than 0.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying options for the mesh.
FVF
Combination of flexible vertex format flags that describes the vertex format for the returned mesh.
Device
Direct3DDevice8 object, the device to be associated with the mesh.

Return Values

D3DXMesh object representing the created mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.FVFFromDeclarator


D3DX8.CreatePolygon

Uses a left-handed coordinate system to create a mesh containing an n-sided polygon.

object.CreatePolygon( _
    D3DDevice As Direct3DDevice8, _
    Length As Single, _
    Sides As Long, _
    RetAdjacency As D3DXBuffer) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
D3DDevice
Direct3DDevice8 object, representing the device associated with the created polygon mesh.
Length
Length of each side
Sides
Number of sides for the polygon. Value must be greater than or equal to 3.
RetAdjacency
D3DXBuffer object. When the method returns, this parameter is filled with an array of three Long values per face that specify the three neighbors for each face in the mesh.

Return Values

D3DXMesh object, representing the created polygon mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The created polygon is centered at the origin.


D3DX8.CreateRenderToSurface

Creates a render surface.

object.CreateRenderToSurface( _
    D3DDevice As Direct3DDevice8, _
    Width As Long, _
    Height As Long, _
    Format As CONST_D3DFORMAT, _
    DepthStencil As Long, _
    DepthStencilFormat As CONST_D3DFORMAT) As D3DXRenderToSurface

Parts

object
Object expression that resolves to a D3DX8 object.
D3DDevice
Direct3DDevice8 object, to be associated with the render surface.
Width
Width of the render surface, in pixels
Height
Height of the render surface, in pixels
Format
Member of the CONST_D3DFORMAT enumeration, describing the format of the render target.
DepthStencil
If 1, the render surface supports a depth-stencil surface. Otherwise this member is set to 0.
DepthStencilFormat
If DepthStencil is set to 1, this parameter is a member of the CONST_D3DFORMAT enumeration describing the depth-stencil format of the render surface.

Return Values

D3DXRenderToSurface object, representing the created polygon mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The created polygon is centered at the origin.


D3DX8.CreateSkinMesh

Creates an empty skin mesh object using a declarator.

object.CreateSkinMesh( _
    NumFaces As Long, _
    NumVertices As Long, _
    NumBones As Long, _
    Options As Long, _
    Declaration As Any, _
    D3DDevice As Direct3DDevice8) As D3DXSkinMesh

Parts

object
Object expression that resolves to a D3DX8 object.
NumFaces
Number of faces for the skin mesh.
NumVertices
Number of vertices for the skin mesh.
NumBones
Number of bones for the skin mesh.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying options for the skin mesh.
Declaration
A Long value, representing the declarator that describes the vertex format for the returned skin mesh.
D3DDevice
A Direct3DDevice8 object, the device object to be associated with the skin mesh.

Return Values

D3DXSkinMesh object, representing the created skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Use D3DXSkinMesh.SetBoneInfluence to populate the empty skin mesh object returned by this method.


D3DX8.CreateSkinMeshFromMesh

Creates a skin mesh from another mesh.

object.CreateSkinMeshFromMesh( _
    Mesh As D3DXMesh, _
    NumBones As Long) As D3DXSkinMesh

Parts

object
Object expression that resolves to a D3DX8 object.
Mesh
A D3DXMesh object, the mesh from which to create the skin mesh.
NumBones
Number of bones for the skin mesh.

Return Values

D3DXSkinMesh object, representing the created skin mesh object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.CreateSkinMeshFVF

Creates an empty skin mesh object using a flexible vertex format (FVF) code.

object.CreateSkinMeshFVF( _
    NumFaces As Long, _
    NumVertices As Long, _
    NumBones As Long, _
    Options As Long, _
    FVF As Long, _
    D3DDevice As Direct3DDevice8) As D3DXSkinMesh

Parts

object
Object expression that resolves to a D3DX8 object.
NumFaces
Number of faces for the skin mesh.
NumVertices
Number of vertices for the skin mesh.
NumBones
Number of bones for the skin mesh.
Options
A combination of one or more members of the CONST_D3DXMESH enumerated type, specifying options for the skin mesh.
FVF
Combination of flexible vertex format flags that describes the vertex format for the returned skin mesh.
D3DDevice
A Direct3DDevice8 object, the device object to be associated with the skin mesh.

Return Values

D3DXSkinMesh object, representing the created skin mesh object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Use D3DXSkinMesh.SetBoneInfluence to populate the empty skin mesh object returned by this method.


D3DX8.CreateSphere

Uses a left-handed coordinate system to create a mesh containing a sphere.

object.CreateSphere( _
    D3DDevice As Direct3DDevice8, _
    Radius As Single, _
    Slices As Long, _
    Stacks As Long, _
    RetAdjacency As D3DXBuffer) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
D3DDevice
Direct3DDevice8 object, associated with the created sphere mesh.
Radius
Radius of the sphere. This value should be greater than or equal to 0.
Slices
Number of slices about the main axis.
Stacks
Number of stacks along the main axis.
RetAdjacency
D3DXBuffer object to be filled with an array of three Long values per face that specify the three neighbors for each face in the mesh.

Return Values

D3DXMesh object, representing the created sphere.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The created sphere is centered at the origin, and its axis is aligned with the z-axis.


D3DX8.CreateSPMesh

Creates a simplification mesh.

object.CreateSPMesh( _
    Mesh As D3DXMesh, _
    Adjacency As Any, _
    VertexAttributeWeights As Any, _
    VertexWeights As Any) As D3DXSPMesh

Parts

object
Object expression that resolves to a D3DX8 object.
Mesh
D3DXMesh object, representing the mesh to simplify.
Adjacency
First element of an array of three Long values per face that specify the three neighbors for each face in the created simplification mesh.
VertexAttributeWeights
A D3DXATTRIBUTEWEIGHTS type, containing the weight for each vertex component. If this parameter is set to ByVal 0, a default type is used.
VertexWeights
First element of an array of vertex weights. Note that the higher the vertex weight for a given vertex, the less likely it is to be simplified away.

Return Values

D3DXSPMesh object, representing the created simplification mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DXERR_CANNOTATTRSORT
D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

A simplification mesh is used to simplify a mesh to a lower number of triangles and faces.

If VertexAttributeWeights is set to ByVal 0, the values are assigned according to the default D3DXATTRIBUTEWEIGHTS type.

Dim AttribruteWeights As D3DXATTRIBUTEWEIGHTS
With _
.position = 1
.Boundary = 1
.Normal = 1
.diffuse = 0
.specular = 0
.Tex(7) = 0
End With

This default type 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.

The following code fragment shows how to use a D3DXBuffer object to pass adjacency information.

Dim Mesh As D3DXMesh
Dim D3DXbAdjacency As D3DXBuffer
Dim VAttWeights As Any
Dim VWeights As Any

' This code fragment assumes that all arguments
' have been properly initialized.
Call D3DX8.CreateSPMesh(Mesh, ByVal D3DXbAdjacency.GetBufferPointer, VAttWeights, Vweights )


D3DX8.CreateSprite

Creates a sprite.

object.CreateSprite( _
    D3DDevice As Direct3DDevice8) As D3DXSprite

Parts

object
Object expression that resolves to a D3DX8 object.
D3DDevice
Direct3DDevice8 object representing the device to be associated with the sprite.

Return Values

D3DXSprite object representing the created sprite.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.CreateTeapot

Creates a teapot.

object.CreateTeapot( _
    D3DDevice As Direct3DDevice8, _
    RetAdjacency As D3DXBuffer) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
D3DDevice
Direct3DDevice8 object representing the device to be associated with the texture.
RetAdjacency
D3DXBuffer object. When the method returns, this parameter is filled with an array of three Long values per face that specify the three neighbors for each face in the mesh.

Return Values

D3DXMesh object representing the created teapot.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.CreateText

Creates a mesh containing the specified text using the font associated with the device context.

object.CreateText( _
    D3DDevice As Direct3DDevice8, _
    HDC As Long, _
    Text As String, _
    Deviation As Single, _
    Extrusion As Single, _
    RetMesh As D3DXMesh, _
    GlyphMetrics As Any)

Parts

object
Object expression that resolves to a D3DX8 object.
D3DDevice
Direct3DDevice8 object to be associated with the created text.
HDC
Device context, containing the font for output. The font selected by the device context must be a TrueType font.
Text
A string, specifying the text to generate.
Deviation
Maximum chordal deviation from true font outlines.
Extrusion
Amount to extrude text in the negative Z direction.
RetMesh
The output shape, a D3DXMesh object.
GlyphMetrics
First element of an array of GLYPHMETRICSFLOAT types to receive the glyph metric data. Each GLYPHMETRICSFLOAT type in the array contains information about the placement 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 type 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, you can pass ByVal 0 to GlyphMetrics

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.CreateTexture

Creates an empty texture, adjusting the calling parameters as needed.

object.CreateTexture( _
    Device As Direct3DDevice8, _
    Width As Long, _
    Height As Long, _
    MipLevels As Long, _
    Usage As Long, _
    PixelFormat As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL) As Direct3DTexture8

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the texture.
Width
Width of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels are 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 is taken instead. If this value is set to 0, then a value of 1 is used. D3DX_DEFAULT can also be used, see Remarks.
Height
Height of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels are 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 is taken instead. If this value is set to 0, then a value of 1 is used. D3DX_DEFAULT can also be used, see Remarks.
MipLevels
The number of levels in the texture. If this is zero, Microsoft® Direct3D® generates all texture sub-levels down to 1×1 pixels.
Usage
0 or the D3DUSAGE_RENDERTARGET member of the CONST_D3DUSAGEFLAGS enumeration. Specifying D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling Direct3D8.CheckDeviceFormat.
PixelFormat
Member of the CONST_D3DFORMAT enumeration, describing the requested pixel format for the texture. The returned texture might have a format different from that specified by PixelFormat. Applications should check the format of the returned texture.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the texture should be placed.

Return Values

Direct3DTexture8 object representing the created texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If the Height and Width parameters are both set to D3DX_DEFAULT, a value of 256 is used for both. If only one of these are set to D3DX_DEFAULT, then the texture will be square with the other dimensional parameter specifying both the height and width.

Internally, D3DX8.CreateTexture uses D3DX8.CheckTextureRequirements to adjust the calling parameters. Therefore, calls to D3DX8.CreateTexture often succeed where calls to Direct3DDevice8.CreateTexture fail.


D3DX8.CreateTextureFromFile

Creates a texture from a file.

object.CreateTextureFromFile( _
    Device As Direct3DDevice8, _
    SrcFile As String) As Direct3DTexture8

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the texture.
SrcFile
String that specifies the file from which to create the texture.

Return Values

Direct3DTexture8 object representing the created texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Mipmapped textures will automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some video cards 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 the D3DPOOL_MANAGED member of the CONST_D3DPOOL enumerated type.


D3DX8.CreateTextureFromFileEx

Creates a texture from a file. This is a more advanced method than D3DX8.CreateTextureFromFile.

object.CreateTextureFromFileEx( _
    Device As Direct3DDevice8, _
    SrcFile As String, _
    Width As Long, _
    Height As Long, _
    MipLevels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL, _
    Filter As Long, _
    MipFilter As Long, _
    ColorKey As Long, _
    SrcInfo As Any _
    Palette As Any) As Direct3DTexture8

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the texture.
SrcFile
String that specifies the file from which to create the texture.
Width
Width in pixels. If this value is zero or D3DX_DEFAULT as defined by the CONST_D3DXENUM enumeration, the dimensions are taken from the file.
Height
Height, in pixels. If this value is zero or D3DX_DEFAULT as defined by the CONST_D3DXENUM enumeration, the dimensions are taken from the file.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT as defined by the CONST_D3DXENUM enumeration, a complete mipmap chain is created.
Usage
0 or the D3DUSAGE_RENDERTARGET member of the CONST_D3DUSAGEFLAGS enumeration. Specifying D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling Direct3D8.CheckDeviceFormat.
Format
Member of the CONST_D3DFORMAT enumeration, describing the requested pixel format for the texture. The returned texture might have a format different from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the texture should be placed.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
MipFilter
A combination of one or more mip filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.
SrcInfo
A D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or ByVal 0.
Palette
The first element of an array of 256 PALETTEENTRY types to fill in, or ByVal 0. See Remarks.

Return Values

Direct3DTexture8 object representing the created texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Mipmapped textures will automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some video cards are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.


D3DX8.CreateTextureFromFileInMemory

Creates a texture from a file in memory.

object.CreateTextureFromFileInMemory( _
    Device As Direct3DDevice8, _
    SrcData As Any, _
    LengthInBytes As Long) As Direct3DTexture8

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the texture.
SrcData
File in memory from which to create the texture.
LengthInBytes
Size of the file in memory, in bytes.

Return Values

Direct3DTexture8 object representing the created texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Note that a resource created with this function will be placed in the memory class denoted by the D3DPOOL_MANAGED member of the CONST_D3DPOOL enumerated type.

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 fails.


D3DX8.CreateTextureFromFileInMemoryEx

Creates a texture from a file in memory. This is a more advanced method than D3DX8.CreateTextureFromFileInMemory.

object.CreateTextureFromFileInMemoryEx( _
    Device As Direct3DDevice8, _
    SrcData As Any, _
    LengthInBytes As Long, _
    Width As Long, _
    Height As Long, _
    MipLevels As Long, _
    Usage As Long, _
    Format As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL, _
    Filter As Long, _
    MipFilter As Long, _
    ColorKey As Long, _
    SrcInfo As Any, _
    Palette As Any) As Direct3DTexture8

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the texture.
SrcData
File in memory from which to create the texture.
LengthInBytes
Size of the file in memory, in bytes.
Width
Width in pixels. If this value is zero or D3DX_DEFAULT as defined by the CONST_D3DXENUM enumeration, the dimensions are taken from the file.
Height
Height, in pixels. If this value is zero or D3DX_DEFAULT as defined by the CONST_D3DXENUM enumeration, the dimensions are taken from the file.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT as defined by the CONST_D3DXENUM enumeration, a complete mipmap chain is created.
Usage
0 or the D3DUSAGE_RENDERTARGET member of the CONST_D3DUSAGEFLAGS enumeration. Specifying D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling Direct3D8.CheckDeviceFormat.
Format
Member of the CONST_D3DFORMAT enumeration, describing the requested pixel format for the texture. The returned texture might have a format different from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the texture should be placed.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
MipFilter
A combination of one or more mip filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.
SrcInfo
A D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or ByVal 0.
Palette
The first element of an array of 256 PALETTEENTRY types to fill in, or ByVal 0.

Return Values

Direct3DTexture8 object representing the created texture.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

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 fails.


D3DX8.CreateTextureFromResource

Creates a texture from a resource.

object.CreateTextureFromResource( _
    Device As Direct3DDevice8, _
    hModule As Long, _
    SrcResource As String) As Direct3DTexture8

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the texture.
hModule
Handle to the module where the resource is located, or App.hInstance if the resource information is located in the current process.
SrcResource
String that specifies the resource from which to create the texture.

Return Values

Direct3DTexture8 object representing the created texture object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Note that a resource created with this function will be placed in the memory class denoted by the D3DPOOL_MANAGED member of the CONST_D3DPOOL enumerated type.

See Also

D3DX8.CreateTextureFromResourceEx


D3DX8.CreateTextureFromResourceEx

Creates a texture from a resource. This is a more advanced method than D3DX8.CreateTextureFromResource.

object.CreateTextureFromResourceEx( _
    Device As Direct3DDevice8, _
    hSrcModule As Long, _
    SrcResource As String, _
    Width As Long, _
    Height As Long, _
    MipLevels As Long, _
    Usage As Long, _
    PixelFormat As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL, _
    Filter As Long, _
    MipFilter As Long, _
    ColorKey As Long, _
    SrcInfo As Any, _
    Palette As Any) As Direct3DTexture8

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the texture.
hSrcModule
Handle to the module where the resource is located, or App.hInstance if the resource information is located in the current process.
SrcResource
String that specifies the resource from which to create the texture.
Width
Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
0 or the D3DUSAGE_RENDERTARGET member of the CONST_D3DUSAGEFLAGS enumeration. Specifying D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can be passed to the NewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling Direct3D8.CheckDeviceFormat.
PixelFormat
Member of the CONST_D3DFORMAT enumeration, describing the requested pixel format for the texture. The returned texture might have a format different from that specified by PixelFormat. Applications should check the format of the returned texture. If PixelFormat is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the texture should be placed.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
MipFilter
A combination of one or more mip filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.
SrcInfo
A D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or ByVal 0.
Palette
The first element of an array of 256 PALETTEENTRY types to fill in, or ByVal 0.

Return Values

Direct3DTexture8 object representing the created texture object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.CreateTextureFromResource


D3DX8.CreateTorus

Creates an empty texture.

object.CreateTorus( _
    D3DDevice As Direct3DDevice8, _
    InnerRadius As Single, _
    OuterRadius As Single, _
    Sides As Long, _
    Rings As Long, _
    RetAdjacency As D3DXBuffer) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
D3DDevice
Direct3DDevice8 object representing the device to be associated with the texture.
InnerRadius
Inner-radius of the torus. Value should be greater than or equal to 0.
OuterRadius
Outer-radius of the torus. Value should be greater than or equal to 0.
Sides
Number of sides in a cross-section. Value must be greater than or equal to 3.
Rings
Number of rings making up the torus. Value must be greater than or equal to 3.
RetAdjacency
D3DXBuffer object. When the method returns, this parameter is filled with an array of three Long values per face that specify the three neighbors for each face in the mesh.

Return Values

D3DXMesh object representing the created torus.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The CreateTorus method draws a doughnut, centered at (0, 0, 0) whose 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 method returns a mesh that can be used later for drawing or manipulation by the application.


D3DX8.CreateVolumeTexture

Creates an empty volume texture, adjusting the calling parameters as necessary.

object.CreateVolumeTexture( _
    Device As Direct3DDevice8, _
    Width As Long, _
    Height As Long, _
    Depth As Long, _
    MipLevels As Long, _
    Usage As Long, _
    PixelFormat As CONST_D3DFORMAT, _
    Pool As CONST_D3DPOOL) As Direct3DVolume8

Parts

object
Object expression that resolves to a D3DX8 object.
Device
Direct3DDevice8 object representing the device to be associated with the volume.
Width
Width in pixels. This value must be nonzero.
Height
Height in pixels. This value must be nonzero.
Depth
Depth in pixels. This value must be nonzero.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
Currently not used, set to 0.
PixelFormat
Member of the CONST_D3DFORMAT enumeration, describing the requested pixel format for the volume texture. The returned volume texture might have a format different from that specified by Format. Applications should check the format of the returned volume texture.
Pool
Member of the CONST_D3DPOOL enumeration, describing the memory class into which the volume texture should be placed.

Return Values

Direct3DVolume8 object representing the created volume texture object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Internally, D3DX8.CreateVolumeTexture uses D3DX8.CheckVolumeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DX8.CreateVolumeTexture often succeed where calls to Direct3DDevice8.CreateVolumeTexture fail.


D3DX8.DeclaratorFromFVF

Returns a declarator from a flexible vertex format (FVF) code.

object.DeclaratorFromFVF( _
    FVF As Long, _
    Declarator As D3DXDECLARATOR)

Parts

object
Object expression that resolves to a D3DX8 object.
FVF
Combination of flexible vertex format flags that describes the FVF from which to generate the returned declarator.
Declarator
A D3DXDECLARATOR type, describing the returned declarator.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.FVFFromDeclarator


D3DXFont.DrawText

Draws formatted text on a Microsoft® Direct3D® device.

object.DrawText( _
    Text As String, _
    Count As Long, _
    DestRECT As RECT, _
    Format As Long, _
    Color As Long) As Long

Parts

object
Object expression that resolves to a D3DXFont object.
Text
The string to draw.
Count
Specifies the number of characters in the string. If Count is –1, then DrawText will compute the character count automatically. –1 might not be specified if Format includes DT_MODIFYSTRING.
DestRECT
RECT type that contains the rectangle, in logical coordinates, in which the text is to be formatted.
Format
A combinations of values from the CONST_DTFLAGS enumeration, specifying the text formatting. If Format includes DT_MODIFYSTRING, the function could add up to four additional characters to this string. The buffer containing the string should be large enough to accommodate these extra characters.
Color
Long value that specifies the color of the text.

Error Codes

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 lpRect->top to the bottom of the drawn text.

If the function fails, the return value is zero.

Remarks

DrawText must be called inside a Direct3DDevice8.BeginScene/Direct3DDevice8.EndScene block.

This method uses the device context's selected font, text color, and background color to draw the 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.


D3DX8.FilterCubeTexture

Filters a cube texture.

object.FilterCubeTexture( _
    CubeTexture As Direct3DCubeTexture8, _
    Palette As Any, _
    SrcLevel As Long, _
    MipFilter As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
CubeTexture
Direct3DCubeTexture8 object representing the cube texture to filter.
Palette
The first element of an array of 256 PALETTEENTRY types to fill in, or ByVal 0. If a palette is not specified, the default Microsoft® Direct3D® palette (an all opaque white palette) is provided.
SrcLevel
The level whose image is used to generate the subsequent levels. Specifying D3DX_DEFAULT for this parameter is equivalent to specifying 0.
MipFilter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the mipmap is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the texture does not cause the dirty rectangle to be updated. If D3DX8.FilterCubeTexture is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DTexture8.AddDirtyRect on the texture.

For each side of the cube texture, a box-filter is recursively applied to each level to generate the next level.


D3DX8.FilterTexture

Filters mipmap levels of a texture.

object.FilterTexture( _
    Texture As Direct3DTexturep8, _
    Palette As Any, _
    SrcLevel As Long, _
    MipFilter As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
Texture
Direct3DTexture8 object representing the texture to filter.
Palette
The first element of an array of 256 PALETTEENTRY types to fill in, or ByVal 0 for nonpalletized formats. If a palette is not specified, the default Microsoft® Direct3D® palette (an all opaque white palette) is provided.
SrcLevel
The level whose image is used to generate the subsequent levels. Specifying D3DX_DEFAULT for this parameter is equivalent to specifying 0.
MipFilter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the mipmap is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the texture does not cause the dirty rectangle to be updated. If D3DX8.FilterTexture is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DTexture8.AddDirtyRect on the texture.

Box-filter is recursively applied to each texture level to generate the next texture level.


D3DX8.FilterVolumeTexture

Filters mipmap levels of a volume texture.

object.FilterVolumeTexture( _
    VolumeTexture As Direct3DVolume8, _
    Palette As Any, _
    SrcLevel As Long, _
    MipFilter As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
VolumeTexture
Direct3DVolume8 object representing the volume to filter.
Palette
The first element of an array of 256 PALETTEENTRY> types to fill in, or ByVal 0 for nonpalletized formats. If a palette is not specified, the default Microsoft® Direct3D® palette (an all opaque white palette) is provided.
SrcLevel
The level whose image is used to generate the subsequent levels. Specifying D3DX_DEFAULT for this parameter is equivalent to specifying 0.
MipFilter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the mipmap is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the texture does not cause the dirty rectangle to be updated. If D3DX8.FilterVolumeTexture is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DTexture8.AddDirtyRect on the texture.

Box-filter is recursively applied to each texture level to generate the next texture level.


D3DX8.FVFFromDeclarator

Returns a flexible vertex format (FVF) code from a declarator.

object.FVFFromDeclarator( _
    Declarator As D3DXDECLARATOR) As Long

Parts

object
Object expression that resolves to a D3DX8 object.
Declarator
A D3DXDECLARATOR type, describing the declarator from which to generate the FVF code.

Return Values

Long value, representing the returned combination of flexible vertex format flags that describes the vertex format returned from the declarator.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Note This function fails for any declarator that does not map directly to an FVF.

See Also

D3DX8.DeclaratorFromFVF


D3DX8.GeneratePMesh

Generates a progressive mesh.

object.GeneratePMesh( _
    Mesh As D3DXMesh, _
    Adjacency As Any, _
    VertexAttributeWeights As Any, _
    VertexWeights As Any, _
    MinValue As Long, _
    Options As Long) As D3DXPMesh

Parts

object
Object expression that resolves to a D3DX8 object.
Mesh
D3DXMesh object, representing the source mesh.
Adjacency
First element of an array of three Long values per face that specify the three neighbors for each face in the created progressive mesh.
VertexAttributeWeights
a D3DXATTRIBUTEWEIGHTS type, containing the weight for each vertex component. If this parameter is set to ByVal 0, a default type is used. See Remarks.
VertexWeights
First element of an array of vertex weights. If this parameter is set to ByVal 0, 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
Number of vertices or faces, depending on the which flag is set in the Options parameter, by which to simplify the source mesh.
Options
Specifies simplification options for the mesh. One of the following flags defined by the CONST_D3DXMESHSIMP enumeration can be set.

Return Values

D3DXPMesh object, representing the created progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_CANNOTATTRSORT
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method 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 VertexAttributeWeights is set to ByVal 0, the values are assigned according to the default D3DXATTRIBUTEWEIGHTS type.

Dim AttribruteWeights As D3DXATTRIBUTEWEIGHTS
With _
.position = 1
.Boundary = 1
.Normal = 1
.diffuse = 0
.specular = 0
.Tex(7) = 0
End With

This default type is what most applications should use because it considers only geometric and normal adjustment. Only in special cases do the other member fields need to be modified.

The following code fragment shows how to use a D3DXBuffer object to pass adjacency information.

Dim Mesh As D3DXMesh
Dim D3DXbAdjacency As D3DXBuffer
Dim VAttWeights As Any
Dim VWeights As Any
Dim MinV As Long
Dim Opts As Long

' This code fragment assumes that all arguments
' have been properly initialized.
Call D3DX8.GeneratePMesh(Mesh, ByVal D3DXbAdjacency.GetBufferPointer, VAttWeights, Vweights, MinV, Opts )


D3DX8.GetErrorString

Returns the error string for an error code.

object.GetErrorString( _
    ErrorCode As Long) As String

Parts

object
Object expression that resolves to a D3DX8 object.
ErrorCode
The specified error code to decipher.

Return Values

Returned error string.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft Visual Basic® Error Handling topic.

Remarks

This function interprets all Microsoft® Direct3D® error codes.


D3DX8.GetFVFVertexSize

Returns the size of a vertex for a flexible vertex format.

object.GetFVFVertexSize( _
    FVF As Long) As Long

Parts

object
Object expression that resolves to a D3DX8 object.
FVF
Flexible vertex format to be queried. A combination of flexible vertex format flags.

Return Values

The flexible vertex format vertex size, in bytes.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.Intersect

Determines if a ray intersects with a mesh.

object.Intersect( _
    MeshIn As D3DXMesh, _
    RayPos As D3DVECTOR, _
    RayDir As D3DVECTOR, _
    retHit As Long, _
    retFaceIndex As Long, _
    retU As Single, _
    retV As Single, _
    retDist As Single)

Parts

object
Object expression that resolves to a D3DX8 object.
MeshIn
D3DXMesh object, representing the mesh to be tested.
RayPos
D3DVECTOR type, specifying the origin coordinate of the ray.
RayDir
D3DVECTOR type, specifying the direction of the ray.
retHit
If the ray intersects a triangular face on the mesh, this value is set to 1. Otherwise, this value is set to 0.
retFaceIndex
Index value of the face closest to the ray origin, if retHit is 1.
retU
Barycentric hit coordinate.
retV
Barycentric hit coordinate.
retDist
Ray intersection parameter distance.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DX8.LoadMeshFromX

Loads a mesh from a Microsoft® DirectX® X file.

object.LoadMeshFromX( _
    FileName As String, _
    Options As Long, _
    Device As Direct3DDevice8, _
    RetAdjacency As D3DXBuffer, _
    RetMaterials As D3DXBuffer, _
    RetMaterialCount As Long) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
FileName
String that specifies the name of the DirectX file to load.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
Device
Direct3DDevice8 object, the device associated with the mesh.
RetAdjacency
D3DXBuffer object. When the method returns, this parameter is filled with an array of three Long values per face that specify the three neighbors for each face in the mesh.
RetMaterials
D3DXBuffer object. When this method returns, this parameter is filled with an array of D3DXMATERIAL types, containing information saved in the DirectX file.
RetMaterialCount
Number of D3DXMATERIAL types in the RetMaterials array, when the method returns.

Return Values

D3DXMesh object representing the loaded mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The following code fragment shows how to call LoadMeshFromX.

Dim g_device As Direct3DDevice8

Dim g_d3dx As D3DX8
Set g_d3dx = New D3DX8

Dim mesh As D3DXMesh
Dim matBuf As D3DXBuffer

' The following assumes that FileName, g_device, matBuf, and matCount have been set to valid values.
Set mesh = g_d3dx.LoadMeshFromX(FileName, D3DXMESH_MANAGED, g_device, Nothing, matBuf, matCount)

When LoadMeshFromX returns, matBuf and matCount have been set to valid values.

Note All the meshes in the file are collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations are applied to the mesh.

See Also

D3DX8.BufferGetMaterial, D3DX8.BufferGetTextureName


D3DX8.LoadMeshFromXof

Loads a mesh from a Microsoft® DirectX® X file data object.

object.LoadMeshFromXof( _
    ofObjMesh As Unknown, _
    Options As Long, _
    Device As Direct3DDevice8, _
    RetBufAdjacency As D3DXBuffer, _
    RetMaterials As D3DXBuffer, _
    RetMaterialCount As Long) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
ofObjMesh
DirectXFileData object representing the DirectX file data object to load.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
Device
Direct3DDevice8 object, the device object associated with the mesh.
RetBufAdjacency
D3DXBuffer object. When the method returns, this parameter is filled with an array of three Long values per face that specify the three neighbors for each face in the mesh.
RetMaterials
D3DXBuffer object. When this method returns, this parameter is filled with an array of D3DXMATERIAL types, containing information saved in the DirectX file.
RetMaterialCount
Number of D3DXMATERIAL types in the RetMaterials array, when the method returns.

Return Values

D3DXMesh object representing the loaded mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft Visual Basic® Error Handling topic.

See Also

DirectXFileData


D3DX8.LoadPMeshFromFile

Loads a progressive mesh from a file.

object.LoadPMeshFromFile( _
    Filename As String, _
    D3DDevice As Direct3DDevice8, _
    RetMaterials As D3DXBuffer, _
    RetNumMaterials As Long) As D3DXPMesh

Parts

object
Object expression that resolves to a D3DX8 object.
Filename
String the specifies the name of the file from which to load the progressive mesh.
D3DDevice
Direct3DDevice8 object, the device object associated with the progressive mesh.
RetMaterials
D3DXBuffer object. When this method returns, this parameter is filled with an array of D3DXMATERIAL types, containing information saved in the file.
RetNumMaterials
The number of D3DXMATERIAL types in the RetMaterials array, when the method returns.

Return Values

D3DXPMesh object representing the loaded progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DXERR_INVALIDMESH.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.SavePMeshToFile


D3DX8.LoadSkinMeshFromXof

Loads a mesh from a Microsoft® DirectX® X file data object.

object.LoadSkinMeshFromXof( _
    OfObjMesh As Unknown, _
    Options As Long, _
    D3DDevice As Direct3DDevice8, _
    RetAdjacency As D3DXBuffer, _
    RetMaterials As D3DXBuffer, _
    RetMatout As Long, _
    RetBoneNames As D3DXBuffer, _
    RetBoneTransforms As D3DXBuffer) As D3DXSkinMesh

Parts

object
Object expression that resolves to a D3DX8 object.
OfObjMesh
DirectXFileData object representing the DirectX file data object to load.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
D3DDevice
Direct3DDevice8 object, the device object associated with the mesh.
RetAdjacency
D3DXBuffer object. When the method returns, this parameter is filled with an array of three Long values per face that specify the three neighbors for each face in the mesh.
RetMaterials
D3DXBuffer object. When this method returns, this parameter is filled with an array of D3DXMATERIAL types, containing information saved in the DirectX file.
RetMatout
The number of D3DXMATERIAL types in the RetMaterials array, when the method returns.
RetBoneNames
A D3DXBuffer object, containing the bone names.
RetBoneTransforms
A D3DXBuffer object, containing the bone transforms.

Return Values

D3DXSkinMesh object representing the loaded mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft Visual Basic® Error Handling topic.


D3DX8.LoadSurfaceFromFile

Loads a surface from a file.

object.LoadSurfaceFromFile( _
    DestSurface As Direct3DSurface8, _
    DestPalette As Any, _
    DestRect As Any, _
    SrcFile As String, _
    SrcRect As Any, _
    Filter As Long, _
    ColorKey As Long, _
    SrcInfo)

Parts

object
Object expression that resolves to a D3DX8 object.
DestSurface
Direct3DSurface8 object. Specifies the destination surface, which receives the image.
DestPalette
The first element of an array of 256 PALETTEENTRY types, representing the destination palette, or ByVal 0.
DestRect
RECT type. Specifies the destination rectangle. Set this parameter to ByVal 0 to specify the entire surface.
SrcFile
String that specifies the file name of the source image.
SrcRect
A RECT type. Specifies the source rectangle. Set this parameter to ByVal 0 to specify the entire image.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.
SrcInfo
A D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or ByVal 0.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the texture does not cause the dirty rectangle to be updated. If D3DX8.LoadSurfaceFromFile is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DTexture8.AddDirtyRect on the texture.


D3DX8.LoadSurfaceFromFileInMemory

Loads a surface from a file in memory.

object.LoadSurfaceFromFileInMemory( _
    DestSurface As Direct3DSurface8, _
    DestPalette As Any, _
    DestRect As Any, _
    SrcData As Any, _
    LengthInBytes As Long, _
    SrcRect As Any, _
    Filter As Long, _
    ColorKey As Long, _
    SrcInfo As Any)

Parts

object
Object expression that resolves to a D3DX8 object.
DestSurface
Direct3DSurface8 object. Specifies the destination surface, which receives the image.
DestPalette
The first element of an array of 256 PALETTEENTRY types, representing the destination palette, or ByVal 0.
DestRect
RECT type. Specifies the destination rectangle. Set this parameter to ByVal 0 to specify the entire surface.
SrcData
File in memory from which to load the surface.
LengthInBytes
Size of the file in memory, in bytes.
SrcRect
A RECT type. Specifies the source rectangle. Set this parameter to ByVal 0 to specify the entire image.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.
SrcInfo
A D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or ByVal 0.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the texture does not cause the dirty rectangle to be updated. If D3DX8.LoadSurfaceFromFileInMemory is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DTexture8.AddDirtyRect on the texture.


D3DX8.LoadSurfaceFromMemory

Loads a surface from memory.

object.LoadSurfaceFromMemory( _
    DestSurface As Direct3DSurface8, _
    DestPalette As Any, _
    DestRect As Any, _
    SrcData As Any, _
    SrcFormat As CONST_D3DFORMAT, _
    SrcPitch As Long, _
    SrcPalette As Any, _
    SrcRect As Any, _
    Filter As Long, _
    ColorKey As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
DestSurface
Direct3DSurface8 object. Specifies the destination surface, which receives the image.
DestPalette
The first element of an array of 256 PALETTEENTRY types, representing the destination palette, or ByVal 0.
DestRect
RECT type. Specifies the destination rectangle.
SrcData
The top-left corner of the source image in memory.
SrcFormat
Member of the CONST_D3DFORMAT enumeration; the pixel format of the source image.
SrcPitch
Pitch of source image, in bytes. For DXT formats, this number should represent the width of one row of cells, in bytes.
SrcPalette
The first element of an array of 256 PALETTEENTRY types, representing the source palette, or ByVal 0.
SrcRect
RECT type, describing the dimensions of the source image in memory.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the texture does not cause the dirty rectangle to be updated. If D3DX8.LoadSurfaceFromMemory is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DTexture8.AddDirtyRect on the texture.


D3DX8.LoadSurfaceFromResource

Loads a surface from a resource.

object.LoadSurfaceFromResource( _
    DestSurface As Direct3DSurface8, _
    DestPalette As Any, _
    DestRect As Any, _
    hSrcModule As Long, _
    SrcResource As String, _
    SrcRect As Any, _
    Filter As Long, _
    ColorKey As Long, _
    SrcInfo As Any)

Parts

object
Object expression that resolves to a D3DX8 object.
DestSurface
Direct3DSurface8 object. Specifies the destination surface, which receives the image.
DestPalette
The first element of an array of 256 PALETTEENTRY types, representing the destination palette, or ByVal 0.
DestRect
RECT type. Specifies the destination rectangle. Set this parameter to ByVal 0 to specify the entire surface.
hSrcModule
Handle to the module where the resource is located, or App.hInstance if the resource information is located in the current process.
SrcResource
String that specifies the resource name of the source image.
SrcRect
RECT type, describing the dimensions of the source image in memory.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.
SrcInfo
A D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or ByVal 0.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the texture does not cause the dirty rectangle to be updated. If D3DX8.LoadSurfaceFromMemory is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DTexture8.AddDirtyRect on the texture.


D3DX8.LoadSurfaceFromSurface

Loads a surface from another surface with color conversion.

object.LoadSurfaceFromSurface( _
    DestSurface As Direct3DSurface8, _
    DestPalette As Any, _
    DestRect As Any, _
    SrcSurface As Direct3DSurface8, _
    SrcPalette As Any, _
    SrcRect As Any, _
    Filter As Long, _
    ColorKey As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
DestSurface
Direct3DSurface8 object. Specifies the destination surface, which receives the image.
DestPalette
The first element of an array of 256 PALETTEENTRY types, representing the destination palette, or ByVal 0.
DestRect
RECT type. Specifies the destination rectangle. Set this parameter to ByVal 0 to specify the entire surface.
SrcSurface
Direct3DSurface8 object, representing the source surface.
SrcPalette
The first element of an array of 256 PALETTEENTRY types, representing the source palette, or ByVal 0.
SrcRect
RECT type. Specifies the source rectangle. Set this parameter to ByVal 0 to specify the entire surface.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the texture does not cause the dirty rectangle to be updated. If D3DX8.LoadSurfaceFromSurface is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DTexture8.AddDirtyRect on the texture.


D3DX8.LoadVolumeFromMemory

Loads a volume from memory.

object.LoadVolumeFromMemory( _
    DestVolume As Direct3DVolume8, _
    DestPalette As Any, _
    DestBox As Any, _
    SrcMemory As Any, _
    SrcFormat As Long, _
    SrcRowPitch As Long, _
    SrcSlicePitch As Long, _
    SrcPalette As Any, _
    SrcBox As D3DBOX, _
    Filter As Long, _
    ColorKey As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
DestVolume
Direct3DVolume8 object. Specifies the destination volume, which receives the image.
DestPalette
The first element of an array of 256 PALETTEENTRY types, representing the destination palette, or ByVal 0.
DestBox
D3DBOX type. Specifies the destination box. Set this parameter to ByVal 0 to specify the entire volume.
SrcMemory
Value that indicates the top-left corner of the source volume in memory.
SrcFormat
Member of the CONST_D3DFORMAT enumeration; the pixel format of the source volume.
SrcRowPitch
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
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.
SrcPalette
The first element of an array of 256 PALETTEENTRY types, representing the source palette, or ByVal 0.
SrcBox
D3DBOX type. Specifies the source box. ByVal 0 is not a valid value for this parameter.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the volume texture does not cause the dirty rectangle to be updated. If D3DX8.LoadVolumeFromMemory is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DVolumeTexture8.AddDirtyBox on the texture.


D3DX8.LoadVolumeFromVolume

Loads a volume from another volume.

object.LoadVolumeFromVolume( _
    DestVolume As Direct3DVolume8, _
    DestPalette As Any, _
    DestBox As Any, _
    SrcVolume As Direct3DVolume8, _
    SrcPalette As Any, _
    SrcBox As Any, _
    Filter As Long, _
    ColorKey As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
DestVolume
Direct3DVolume8 object. Specifies the destination volume, which receives the image.
DestPalette
The first element of an array of 256 PALETTEENTRY types, representing the destination palette, or ByVal 0.
DestBox
D3DBOX type. Specifies the destination box. Set this parameter to ByVal 0 to specify the entire volume.
SrcVolume
Direct3DVolume8 object. Specifies the source volume.
SrcPalette
The first element of an array of 256 PALETTEENTRY types, representing the source palette, or ByVal 0.
SrcBox
D3DBOX type. Specifies the source box. Set this parameter to ByVal 0 to specify the entire volume.
Filter
A combination of one or more filter flags defined by the CONST_D3DXENUM enumeration, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_DITHER Or D3DX_FILTER_TRIANGLE.
ColorKey
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 colorkeys. Thus, for opaque black, the value would be equal to &HFF000000.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Writing to a non-level-zero surface of the volume texture does not cause the dirty rectangle to be updated. If D3DX8.LoadVolumeFromVolume is called and the surface was not already dirty—this is unlikely under normal use scenarios—the application must explicitly call Direct3DVolumeTexture8.AddDirtyBox on the texture.


D3DX8.SaveMeshToX

Saves a mesh to a Microsoft® DirectX® X file.

object.SaveMeshToX( _
    FileName As String, _
    Mesh As D3DXMesh, _
    AdjacencyArray As Any, _
    MaterialArray As D3DXMATERIAL, _
    MaterialCount As Long, _
    xFormat As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
FileName
String that specifies the name of the DirectX file identifying the saved mesh.
Mesh
D3DXMesh object representing the mesh to save to a DirectX file.
AdjacencyArray
First element of an array of three Long values per face that specify the three neighbors for each face in the mesh.
MaterialArray
First element of an array of D3DXMATERIAL types, containing material information to be saved in the DirectX file.
MaterialCount
Number of D3DXMATERIAL types in the MaterialArray array.
xFormat
A member of the CONST_DXFILEFORMATFLAGS enumeration indicating the format to use when saving the DirectX file.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The default value for the file format is DXFILEFORMAT_BINARY. The file format values can be combined together 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 is saved as a text file because the value is indistinguishable from the text file format value (0 + 1 = 1). If you indicate that the file format should be text and compressed, the file is first written out as text and then compressed. However, compressed text files are not as efficient as binary text files, so in most cases you indicate binary and compressed. Setting a file to be compressed without specifying a format results in a binary, compressed file.


D3DX8.SavePMeshToFile

Saves a progressive mesh to a file.

object.SavePMeshToFile( _
    Filename As String, _
    Mesh As D3DXPMesh, _
    MaterialArray As D3DXMATERIAL, _
    MaterialCount As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
Filename
String that specifies the name of the file to which to save the progressive mesh.
Mesh
D3DXPMesh object, representing the progressive mesh to be saved to a file.
MaterialArray
First element of an array of D3DXMATERIAL types, containing material information to be saved in the file.
MaterialCount
Number of D3DXMATERIAL types in MaterialArray.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DXERR_INVALIDMESH.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.LoadPMeshFromFile


D3DX8.SimplifyMesh

Simplifies a mesh.

object.SimplifyMesh( _
    Mesh As D3DXMesh, _
    Adjacency As Any, _
    VertexAttributeWeights As Any, _
    VertexWeights As Any, _
    MinValue As Long, _
    Options As Long) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
Mesh
D3DXMesh object, representing the source mesh.
Adjacency
First element of an array of three Long values per face that specify the three neighbors for each face in the mesh to be simplified.
VertexAttributeWeights
A D3DXATTRIBUTEWEIGHTS type, containing the weight for each vertex component. If this parameter is set to ByVal 0, a default type is used. See Remarks.
VertexWeights
First element of an array of vertex weights. If this parameter is set to ByVal 0, all vertex weights are set to 1.0.
MinValue
Number of vertices or faces, depending on the which flag is set in the Options parameter, by which to simplify the source mesh.
Options
Specifies simplification options for the mesh. One of the flags defined by the CONST_D3DXMESHSIMP enumeration can be set.

Return Values

D3DXMesh object, representing the returned simplification mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method 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 VertexAttributeWeights is set to ByVal 0, the values are assigned according to the default D3DXATTRIBUTEWEIGHTS type.

Dim AttribruteWeights As D3DXATTRIBUTEWEIGHTS
With _
.position = 1
.Boundary = 1
.Normal = 1
.diffuse = 0
.specular = 0
.Tex(7) = 0
End With

This default type is what most applications should use because it considers only geometric and normal adjustment. Only in special cases do the other member fields need to be modified.

The following code fragment shows how to use a D3DXBuffer object to pass adjacency information.

Dim Mesh As D3DXMesh
Dim D3DXbAdjacency As D3DXBuffer
Dim VAttWeights As Any
Dim VWeights As Any
Dim MinV As Long
Dim Opts As Long

' This code fragment assumes that all arguments
' have been properly initialized.
Call D3DX8.SimplifyMesh(Mesh, ByVal D3DXbAdjacency.GetBufferPointer, VAttWeights, Vweights, MinV, Opts )


D3DX8.SphereBoundProbe

Determines if a ray intersects the volume of a sphere's bounding box.

object.SphereBoundProbe( _
    Center As D3DVECTOR, _
    Radius As Single, _
    RayPosition As D3DVECTOR, _
    Raydirection As D3DVECTOR) As Boolean

Parts

object
Object expression that resolves to a D3DX8 object.
Center
D3DVECTOR type, specifying the center coordinate of the sphere.
Radius
Radius of the sphere.
RayPosition
D3DVECTOR type, specifying the origin coordinate of the ray.
Raydirection
D3DVECTOR type, specifying the direction of the ray.

Return Values

Returns 1 if the ray intersects the volume of the sphere's bounding box. Otherwise, returns 0.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DXERR_INVALIDMESH.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

D3DXSphereBoundProbe determines if the ray intersects the volume of the sphere's bounding box, not just the surface of the sphere.


D3DX8.TessellateNPatches

Tessellates a mesh.

object.TessellateNPatches( _
    MeshIn As D3DXMesh, _
    adjacencyOut As Any, _
    NumSegs As Single, _
    QuadraticInterpNormals As Boolean, _
    adjacencyIn As Any) As D3DXMesh

Parts

object
Object expression that resolves to a D3DX8 object.
MeshIn
D3DXMesh object representing the mesh to tessellate.
adjacencyIn
First element of an array of three Long values per face that specify the three neighbors for each face in the source mesh. This parameter may be set to ByVal 0.
NumSegs
Number of segments per edge to tessellate.
QuadraticInterpNormals
If set to True, use quadratic interpolation for normals. If set to False, use linear interpolation.
adjacencyOut
First element of an array of three Long values per face that specify the three neighbors for each face in the output mesh. This parameter may be set to ByVal 0.

Return Values

D3DXMesh object representing the returned tessellated mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Note This function tessellates by using the n-Patch algorithm.


D3DX8.ValidMesh

Validates a mesh.

object.ValidMesh( _
    MeshIn As D3DXMesh, _
    Adjacency As Long) As Boolean

Parts

object
Object expression that resolves to a D3DX8 object.
MeshIn
D3DXMesh object representing the mesh to tessellate.
Adjacency
First element of an array of three Long values per face that specify the three neighbors for each face in the source mesh.

Return Values

Returns 1 if the mesh is valid; otherwise returns 0.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
D3DXERR_INVALIDMESH
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The following code fragment shows how to use a D3DXBuffer object to pass adjacency information.

Dim Mesh As D3DXMesh
Dim D3DXbAdjacency As D3DXBuffer

' This code fragment assumes that all arguments
' have been properly initialized.
Call D3DX8.GeneratePMesh(Mesh, ByVal D3DXbAdjacency.GetBufferPointer)


D3DXBaseMesh

Applications use the methods of the D3DXBaseMesh class to manipulate and query mesh and progressive mesh objects.

The methods of the D3DXBaseMesh class can be organized into the following groups.

Buffers | GetIndexBuffer
 | GetVertexBuffer
 | LockIndexBuffer
 | LockVertexBuffer
 | UnlockIndexBuffer
 | UnlockVertexBuffer
Copying | CloneMesh
 | CloneMeshFVF
Faces | GetNumFaces
Information | GetDevice
 | GetOptions
Rendering | DrawSubset
 | GetAttributeTable
Vertices | GetDeclaration
 | GetFVF
 | GetNumVertices

See Also

D3DXMesh, D3DXPMesh


D3DXBaseMesh.CloneMesh

Clones a mesh using a declarator.

object.CloneMesh( _
    Options As Long, _
    Declaration As Any, _
    Device As Direct3DDevice8) As D3DXMesh

Parts

object
Object expression that resolves to a D3DXBaseMesh object.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
Declaration
First element of an array of Long values, representing the declarator to describe the vertex format of the vertices in the output mesh.
Device
Direct3DDevice8 object representing the device object associated with the mesh.

Return Values

D3DXMesh object, representing the cloned mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

See Also

D3DX8.DeclaratorFromFVF, D3DXBaseMesh.GetDeclaration


D3DXBaseMesh.CloneMeshFVF

Clones a mesh using a flexible vertex format (FVF) code.

object.CloneMeshFVF( _
    Options As Long, _
    FVF As Long, _
    Device As Direct3DDevice8) As D3DXMesh

Parts

object
Object expression that resolves to a D3DXBaseMesh object.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
FVF
Combination of flexible vertex format flags that specifies the vertex format for the vertices in the output mesh.
Device
Direct3DDevice8 object representing the device object associated with the mesh.

Return Values

D3DXMesh object, representing the cloned mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

Remarks

CloneMeshFVF can be used to convert a mesh from one FVF to another.

See Also

D3DX8.FVFFromDeclarator, D3DXBaseMesh.GetFVF


D3DXBaseMesh.ConvertAdjacencyToPointReps

Converts mesh adjacency information to an array of point representatives.

object.ConvertAdjacencyToPointReps( _
  Adjacency As Any, _
  PointReps As Any)

Parts

Adjacency
First element of an array of three Singles per triangle of the mesh that contains adjacency information.
PointReps
First element of an array of one Single per vertex of the mesh that will be filled with point representative data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

See Also

D3DXBaseMesh.ConvertPointRepsToAdjacency


D3DXBaseMesh.ConvertPointRepsToAdjacency

Converts point representive data to mesh adjacency information.

object.ConvertPointRepsToAdjacency( _
  PointReps As Any, _
  Adjacency As Any)

Parts

PointReps
First element of an array of one Single per vertex of the mesh that contains point representive data.
Adjacency
First element of an array of three Singles per triangle of the mesh that contains the returned adjacency information.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

See Also

D3DXBaseMesh.ConvertAdjacencyToPointReps


D3DXBaseMesh.DrawSubset

Draws a subset of a mesh.

object.DrawSubset( _
    attribId  As Long)

Parts

object
Object expression that resolves to a D3DXBaseMesh object.
attribId
A Long value 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

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.

See Also

D3DXBaseMesh.GetAttributeTable


D3DXBaseMesh.GenerateAdjacency

Generates adjacency information based on mesh indices.

object.GenerateAdjacency( _
  Epsilon As Single, _
  Adjacency As Any)

Parts

Epsilon
Specifies that vertices that differ in position by less than epsilon should be treated as coincident.
Adjacency
First element of an array of three Singles per face that specify the three neighbors for each face in the mesh to be cleaned. Make sure that the size of this array is at least 3 * GetNumFaces * Len(Single) bytes long.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh


D3DXBaseMesh.GetAttributeTable

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

object.GetAttributeTable( _
    AttribTable As Any, _
    AttribTabSize As Long)

Parts

object
Object expression that resolves to a D3DXBaseMesh object.
AttribTable
First element of an array of D3DXATTRIBUTERANGE types, representing the entries in the mesh's attribute table. Specify ByVal 0 to retrieve the value for AttribTabSize.
AttribTabSize
Either the number of entries stored in AttribTable, or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

Remarks

An attribute table is created by D3DXMesh.Optimize and by 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.


D3DXBaseMesh.GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

object.GetDeclaration( _
    Declaration As Long)

Parts

object
Object expression that resolves to a D3DXBaseMesh object.
Declaration
First element of an array describing the vertex format of the vertices in the queried mesh. The upper limit of this declarator array is MAX_FVF_DECL_SIZE, limiting the declarator to a maximum of 20 Long values. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

Remarks

This code fragment shows how to pass in a D3DXDECLARATOR to retrieve the declaration of a mesh. This assumes there is an existing D3DXMesh object (d3dxm) that contains a mesh.

Dim d3dxd As D3DXDECLARATOR

'This assumes that (d3dxm) has been properly initialized
Call d3dxd.GetDeclaration(d3dxd.Value(0))

See Also

D3DXBaseMesh.GetFVF


D3DXBaseMesh.GetDevice

Retrieves the device associated with the mesh.

object.GetDevice() As Direct3DDevice8

Parts

object
Object expression that resolves to a D3DXBaseMesh object.

Return Values

Direct3DDevice8 object, identifying the Microsoft® Direct3D® device associated with the mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh


D3DXBaseMesh.GetFVF

Retrieves the flexible vertex format of the vertices in the mesh.

object.GetFVF() As Long

Parts

object
Object expression that resolves to a D3DXBaseMesh object.

Return Values

Returns a combination of flexible vertex format flags that describes the vertex format of the vertices in the queried mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

See Also

D3DXBaseMesh.GetDeclaration


D3DXBaseMesh.GetIndexBuffer

Retrieves the data in an index buffer.

object.GetIndexBuffer() As Direct3DIndexBuffer8

Parts

object
Object expression that resolves to a D3DXBaseMesh object.

Return Values

Direct3DIndexBuffer8 object representing the index buffer object associated with the mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh


D3DXBaseMesh.GetNumFaces

Retrieves the number of faces in the mesh.

object.GetNumFaces() As Long

Parts

object
Object expression that resolves to a D3DXBaseMesh object.

Return Values

Returns the number of faces in the mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh


D3DXBaseMesh.GetNumVertices

Retrieves the number of vertices in the mesh.

object.GetNumVertices() As Long

Parts

object
Object expression that resolves to a D3DXBaseMesh object.

Return Values

Returns the number of vertices in the mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh


D3DXBaseMesh.GetOptions

Retrieves the mesh options enabled for this mesh at creation time.

object.GetOptions() As Long

Parts

object
Object expression that resolves to a D3DXBaseMesh object.

Return Values

Returns a combination of one or more of the flags defined by the CONST_D3DXMESH enumeration, indicating the options enabled for this mesh at creation time.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh


D3DXBaseMesh.GetVertexBuffer

Retrieves a vertex buffer.

object.GetVertexBuffer() As Direct3DVertexBuffer8

Parts

object
Object expression that resolves to a D3DXBaseMesh object.

Return Values

Direct3DVertexBuffer8 object representing the vertex buffer object associated with the mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh


D3DXBaseMesh.LockIndexBuffer

Locks an index buffer and obtains access to the index buffer memory.

object.LockIndexBuffer( _
    Flags As Long) As Long

Parts

object
Object expression that resolves to a D3DXBaseMesh object.
Flags
Combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing how the index buffer memory should be locked.

Return Values

Returns a Long value providing access to the locked index data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls matches the number of unlock calls. DrawPrimitive calls do not succeed with any outstanding lock count on any currently set index buffer.

See Also

D3DXBaseMesh.UnlockIndexBuffer


D3DXBaseMesh.LockVertexBuffer

Locks a vertex buffer and obtains access to the vertex buffer memory.

object.LockVertexBuffer( _
    Flags As Long) As Long

Parts

object
Object expression that resolves to a D3DXBaseMesh object.
Flags
Combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing how the vertex buffer memory should be locked.

Return Values

Returns a Long value providing access to the locked vertex data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

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 do not succeed with any outstanding lock count on any currently set vertex buffer.

See Also

D3DXBaseMesh.UnlockVertexBuffer


D3DXBaseMesh.UnlockIndexBuffer

Unlocks an index buffer.

object.UnlockIndexBuffer()

Parts

object
Object expression that resolves to a D3DXBaseMesh object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

See Also

D3DXBaseMesh.LockIndexBuffer


D3DXBaseMesh.UnlockVertexBuffer

Unlocks a vertex buffer.

object.UnlockVertexBuffer()

Parts

object
Object expression that resolves to a D3DXBaseMesh object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from D3DXBaseMesh.

  • D3DXMesh
  • D3DXPMesh

See Also

D3DXBaseMesh.LockVertexBuffer


D3DXBuffer

The D3DXBuffer class is used as a data buffer that stores 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.

The D3DXBuffer class is obtained by calling the D3DX8.CreateBuffer method.

The methods of the D3DXBuffer class can be organized into the following group.

Information | GetBufferPointer
 | GetBufferSize


D3DXBuffer.GetBufferPointer

Retrieves a handle to the data in the buffer.

object.GetBufferPointer() As Long

Parts

object
Object expression that resolves to a D3DXBuffer object.

Return Values

Returns a handle to the data in the buffer.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.BufferGetData, D3DX8.BufferGetMaterial, D3DX8.BufferGetTextureName, D3DX8.BufferSetData


D3DXBuffer.GetBufferSize

Retrieves the total size of the data in the buffer.

object.GetBufferSize() As Long

Parts

object
Object expression that resolves to a D3DXBuffer object.

Return Values

Returns the total size of the data in the buffer, in bytes.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXFont

The D3DXFont class is used to encapsulate the textures and resources needed to render a specific font on a specific device.

The D3DXFont class is obtained by calling the D3DX8.CreateFont method.

The methods of the D3DXFont class can be organized into the following groups.

Drawing | Begin
 | DrawText
 | End
Information | GetDevice
 | GetLogFont
Miscellaneous | OnLostDevice
 | OnResetDevice


D3DXFont.Begin

Prepares a device for drawing text.

object.Begin()

Parts

object
Object expression that resolves to a D3DXFont object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method is optional. If a DrawTextW method is called outside of a Begin and D3DXFont.End pair, then Microsoft® Direct3D® calls Begin and End.


D3DXFont.End

Restores the device state to how it was when D3DXFont.Begin was called.

object.End()

Parts

object
Object expression that resolves to a D3DXFont object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXFont.Begin


D3DXFont.GetDevice

Retrieves the Microsoft® Direct3D® device associated with the font object.

object.GetDevice() As Direct3DDevice8

Parts

object
Object expression that resolves to a D3DXFont object.

Return Values

A Direct3DDevice8 object, representing the Direct3D device object associated with the font object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXFont.GetLogFont

Retrieves the attributes of the font.

object.GetLogFont(LogFont As LOGFONT)

Parts

object
Object expression that resolves to a D3DXFont object.
LogFont
LOGFONT type, to be filled with the attributes of the font.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXFont.OnLostDevice

Releases all references to video memory resources and deletes all stateblocks.

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. Before this object can be used again, the device must be reset and the D3DXFont.OnResetDevice method called.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXFont.OnResetDevice

Should be called after the device has been reset.

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

This method should be called after the device has been reset, before any other methods are called.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXMesh

Applications use the methods of the D3DXMesh class to manipulate mesh objects.

To obtain the D3DXMesh class, call the D3DX8.CreateMesh or D3DX8.CreateMeshFVF method.

The methods of the D3DXMesh class can be organized into the following groups.

Locking | LockAttributeBuffer
 | UnlockAttributeBuffer
Optimization | Optimize
 | OptimizeInplace

Remarks

This class inherits additional functionality from the D3DXBaseMesh class.


D3DXMesh.LockAttributeBuffer

Locks an attribute buffer.

object.LockAttributeBuffer( _
    Flags As Long) As Long

Parts

object
Object expression that resolves to a D3DXMesh object.
Flags
Combination of one or more locking flags defined by the CONST_D3DLOCKFLAGS enumeration, indicating how the attribute buffer memory should be locked.

Return Values

First element of an array of Long values, filled with the returned attribute buffer data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMesh.UnlockAttributeBuffer, D3DXATTRIBUTERANGE


D3DXMesh.Optimize

Controls the reordering of mesh faces and vertices to optimize performance.

object.Optimize( _
    Flags As Any, _
    Adjacency As Any, _
    OptAdj As Any, _
    FaceRemap As Any, _
    BuffVertexRemap As D3DXBuffer, _
    OptMesh As D3DXMesh)

Parts

object
Object expression that resolves to a D3DXMesh object.
Flags
A combination of one or more flags defined by the CONST_D3DXMESHOPT enumeration, specifying the type of optimization to perform.

Note that the D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

Adjacency
First element of an array of three Long values per face that specify the three neighbors for each face in the source mesh.
OptAdj
First element of an array, representing the destination buffer for the face adjacency array of the optimized 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.
FaceRemap
First element of an array, representing the destination buffer containing the new index for each face.
BuffVertexRemap
D3DXBuffer object, containing the new index for each vertex.
OptMesh
D3DXMesh object, representing the optimized mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method is very similar to the D3DXBaseMesh.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.


D3DXMesh.OptimizeInplace

Controls the reordering of mesh faces and vertices to optimize performance.

object.OptimizeInplace( _
    Flags As Long, _
    AdjacencyIn As Any, _
    AdjacencyOut As Any, _
    FaceRemap As Any, _
    VertexRemapOut As D3DXBuffer)

Parts

object
Object expression that resolves to a D3DXMesh object.
Flags
A combination of one or more flags defined by the CONST_D3DXMESHOPT enumeration, specifying the type of optimization to perform.

Note that the D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

AdjacencyIn
First element of an array of three Long values per face that specify the three neighbors for each face in the source mesh.
AdjacencyOut
First element of an array, representing the destination buffer for the face adjacency array of the optimized 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.
FaceRemap
First element of an array, representing the destination buffer containing the new index for each face.
VertexRemapOut
D3DXBuffer object, containing the new index for each vertex.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_CANNOTATTRSORT
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The output mesh inherits all of the creation parameters of the input mesh.

The following code fragment shows how to use a D3DXBuffer object to pass adjacency information.

Dim Opts As Long
Dim D3DXbAdjacencyIn As D3DXBuffer
Dim D3DXbAdjacencyOut As Any
Dim FaceRemap As Any
Dim FaceRemap As D3DXBuffer

' This code fragment assumes that all arguments
' have been properly initialized.
Call D3DX8.OptimizeInPlace( Opts, ByVal D3DXbAdjacencyIn.GetBufferPointer, D3DXbAdjacencyOut, _
                                            FaceRemap, FaceRemap )

Note This method fails if the mesh is sharing its vertex buffer with another mesh, unless the D3DXMESHOPT_IGNOREVERTS flag is set in the Flags parameter.


D3DXMesh.UnlockAttributeBuffer

Unlocks an attribute buffer.

object.UnlockAttributeBuffer()

Parts

object
Object expression that resolves to a D3DXMesh object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMesh.LockAttributeBuffer


D3DXPMesh

Applications use the methods of the D3DXPMesh class to manipulate progressive mesh objects. A progressive mesh enables progressive refinement of the mesh object.

To obtain the D3DXPMesh class, call the D3DX8.GeneratePMesh method.

The methods of the D3DXPMesh class can be organized into the following groups.

Copying | ClonePMesh
 | ClonePMeshFVF
Faces | GetMaxFaces
 | GetMinFaces
 | SetNumFaces
Miscellaneous | GetAdjacency
 | Optimize
Vertices | GetMaxVertices
 | GetMinVertices
 | SetNumVertices

Remarks

This class inherits additional functionality from the D3DXBaseMesh class.


D3DXPMesh.ClonePMesh

Clones a progressive mesh using a declarator.

object.ClonePMesh( _
    Options As Long, _
    Declaration As Any, _
    Device As Direct3DDevice8) As D3DXPMesh

Parts

object
Object expression that resolves to a D3DXPMesh object.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
Declaration
First element of an array of Long values, representing the declarator to describe the vertex format of the vertices in the output mesh. This parameter must map directly to an FVF.
Device
Direct3DDevice8 object representing the device object associated with the mesh.

Return Values

D3DXPMesh object, representing the cloned progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.DeclaratorFromFVF, D3DXBaseMesh.GetDeclaration


D3DXPMesh.ClonePMeshFVF

Clones a progressive mesh using a flexible vertex format (FVF) code.

object.ClonePMeshFVF( _
    Options As Long, _
    FVF As Long, _
    Device As Direct3DDevice8) As D3DXPMesh

Parts

object
Object expression that resolves to a D3DXPMesh object.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
FVF
Combination of flexible vertex format flags that specifies the vertex format for the vertices in the output mesh.
Device
Direct3DDevice8 object representing the device object associated with the mesh.

Return Values

D3DXPMesh object, representing the cloned progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

See Also

D3DX8.FVFFromDeclarator, D3DXBaseMesh.GetFVF


D3DXPMesh.GetAdjacency

Returns the face adjacency array of the mesh.

object.GetAdjacency( _
    AdjacencyOut As Any

Parts

object
Object expression that resolves to a D3DXPMesh object.
AdjacencyOut
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. The size of the adjacency array is the maximum number of faces multiplied by 3.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXPMesh.GetMaxFaces


D3DXPMesh.GetMaxFaces

Retrieves the maximum number of faces that the progressive mesh supports.

object.GetMaxFaces() As Long

Parts

object
Object expression that resolves to a D3DXPMesh object.

Return Values

Returns the maximum number of faces supported by the progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXPMesh.GetMaxVertices

Retrieves the maximum number of vertices that the progressive mesh supports.

object.GetMaxVertices() As Long

Parts

object
Object expression that resolves to a D3DXPMesh object.

Return Values

Returns the maximum number of vertices supported by the progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXPMesh.GetMinFaces

Retrieves the minimum number of faces that the progressive mesh supports.

object.GetMinFaces() As Long

Parts

object
Object expression that resolves to a D3DXPMesh object.

Return Values

Returns the minimum number of faces supported by the progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXPMesh.GetMinVertices

Retrieves the minimum number of vertices that the progressive mesh supports.

object.GetMinVertices() As Long

Parts

object
Object expression that resolves to a D3DXPMesh object.

Return Values

Returns the minimum number of vertices supported by the progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXPMesh.Optimize

Controls the reordering of mesh faces and vertices to optimize performance, generating an output mesh.

object.Optimize( _
    Flags As Long, _
    AdjacencyOut As Any, _
    FaceRemap As Any, _
    VertexRemapOut As D3DXBuffer) As D3DXMesh

Parts

object
Object expression that resolves to a D3DXPMesh object.
Flags
A combination of one or more flags defined by the CONST_D3DXMESHOPT enumeration, specifying the type of optimization to perform.

Note that the D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

AdjacencyOut
A destination buffer for the face adjacency array of the optimized 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. The size of this array is the maximum number of faces multiplied by 3.
FaceRemap
Destination buffer containing the new index for each face.
VertexRemapOut
D3DXBuffer object; containing the new index for each vertex.

Return Values

D3DXMesh object, representing the optimized mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

See Also

D3DX8.FVFFromDeclarator, D3DXBaseMesh.GetFVF


D3DXPMesh.SetNumFaces

Sets the current level of detail to as close to the specified number of faces as possible.

object.SetNumFaces( _
    Faces As Long)

Parts

object
Object expression that resolves to a D3DXPMesh object.
Faces
Target number of faces. This value specifies the desired change in the level of detail (LOD).

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 D3DXPMesh.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 D3DXPMesh.GetMinFaces.

The number of faces after this call might be off by one because some edge collapse might 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 is always the result.


D3DXPMesh.SetNumVertices

Sets the current level of detail (LOD) to as close to the specified number of vertices as possible.

object.SetNumVertices( _
    Vertices As Long)

Parts

object
Object expression that resolves to a D3DXPMesh object.
Vertices
Target number of vertices. This value specifies the desired change in the LOD.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 D3DXPMesh.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 D3DXPMesh.GetMinVertices.

The number of vertices after this call might be off by one because some edge collapse might 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 is always the result.


D3DXRenderToSurface

The D3DXRenderToSurface class is used to generalize the process of rendering to surfaces. 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 D3DXRenderToSurface class is obtained by calling the D3DX8.CreateRenderToSurface method.

The methods of the D3DXRenderToSurface class can be organized into the following groups.

Information | GetDesc
 | GetDevice
Rendering | BeginScene
 | EndScene


D3DXRenderToSurface.BeginScene

Begins a scene.

object.BeginScene( _
    Surface As Direct3DSurface8, _
    Viewport As D3DVIEWPORT8)

Parts

object
Object expression that resolves to a D3DXRenderToSurface object.
Surface
A Direct3DSurface8 object, representing the render surface.
Viewport
D3DVIEWPORT8 type, describing the viewport for the scene.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXRenderToSurface.EndScene


D3DXRenderToSurface.EndScene

Ends a scene.

object.EndScene()

Parts

object
Object expression that resolves to a D3DXRenderToSurface object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXRenderToSurface.BeginScene


D3DXRenderToSurface.GetDesc

Retrieves the parameters of the render surface.

object.GetDesc( _
    Parameters As D3DXRTS_DESC)

Parts

object
Object expression that resolves to a D3DXRenderToSurface object.
Parameters
D3DXRTS_DESC type, describing the parameters of the render surface.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXRenderToSurface.GetDevice

Retrieves the Microsoft® Direct3D® device associated with the render surface.

object.GetDevice() As Direct3DDevice8

Parts

object
Object expression that resolves to a D3DXRenderToSurface object.

Return Values

A Direct3DDevice8 object, representing the Direct3D device object associated with the render surface.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh

Applications use the methods of the D3DXSkinMesh class to manipulate skin mesh objects.

The D3DXSkinMesh class is obtained by calling one of the following methods.

  • D3DX8.CreateSkinMesh
  • D3DX8.CreateSkinMeshFromMesh
  • D3DX8.CreateSkinMeshFVF

To load a skin mesh from a Microsoft® DirectX® X file data object, use the D3DX8.LoadSkinMeshFromXof method.

Skinning is the technique of having different vertices of a mesh be transformed by multiple transform matrices and the results of the vertex being transformed with each individual matrix blended together to obtain the final transformed vertex.

This process is commonly called skinning because it is used to deform a mesh defining a skin of some character based on the animation of a skeleton of bones. In the simplest case of rigid animation, different parts of the character mesh are associated with a unique skeleton bone and vertices are transformed using the transform of that bone.

When discussing skinning, it is useful to define the following terms.

  • Skin. The triangle mesh being rendered using deformations. Typically this is the model of the character in some convenient pose.
  • Bone. A transform matrix that affects one or more vertices of the skin.
  • Skeleton. A hierarchy of all the bones that affect a skin mesh.
  • Pose. A set of bone transforms that completely defines the transforms for all the bones that affect a given skin mesh.
  • Initial Pose. This is the pose in which the mesh was associated with the skeleton. When the skeleton is in this pose, the deformed mesh is identical to the original undeformed mesh.
  • Bone Space Transform. This transform transforms the mesh into the local space of a particular bone.
  • Bone Weight. The amount of influence a bone has on a given vertex. A weight of 1 means that the vertex is only affected by that bone and 0 means it is unaffected by the bone. The sum of weights of all the bones that affect a vertex should add up to 1 for all vertices.

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 that 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.

The methods of the D3DXSkinMesh class can be organized into the following groups.

Buffers | GetIndexBuffer
 | GetVertexBuffer
Conversion | ConvertToBlendedMesh
 | ConvertToIndexedBlendedMesh
Information | GetBoneInfluence
 | GetDevice
 | GetMaxFaceInfluences
 | GetMaxVertexInfluences
 | GetNumBoneInfluences
 | GetNumBones
 | GetOptions
Faces | GetNumFaces
Locking | LockAttributeBuffer
 | LockIndexBuffer
 | LockVertexBuffer
 | UnlockAttributeBuffer
 | UnlockIndexBuffer
 | UnlockVertexBuffer
Miscellaneous | GenerateSkinnedMesh
 | GetOriginalMesh
 | SetBoneInfluence
 | UpdateSkinnedMesh
Vertices | GetDeclaration
 | GetFVF
 | GetNumVertices


D3DXSkinMesh.ConvertToBlendedMesh

Returns a blended mesh.

object.ConvertToBlendedMesh( _
    Options As Long, _
    AdjacencyIn As Any, _
    AdjacencyOut As Any, _
    RetNumBoneCombinations As Long, _
    RetBoneCombinationTable As D3DXBuffer, _
    pFaceRemap As Any, _
    VertexRemap As D3DXBuffer) As D3DXMesh

Parts

object
Object expression that resolves to a D3DXSkinMesh object.
Options
Combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying options for the mesh.
AdjacencyIn
First element of an array of three Long values per face that specify the three neighbors for each face in the source mesh. See Remarks.
AdjacencyOut
First element in a destination buffer for the face adjacency array of the optimized 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. See Remarks.
RetNumBoneCombinations
Number of entries.
RetBoneCombinationTable
First element in an array of D3DXBONECOMBINATION types. The count of types is NumBoneCombinations. Each bone combination table defines the four bones that you can draw at a time.
pFaceRemap
First element of an array, representing the destination buffer containing the new index for each face.
VertexRemap
D3DXBuffer object containing the new index for each vertex.

Return Values

Returns a D3DXMesh object, representing the blended mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY or D3DXERR_INVALIDMESH.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method takes a skin mesh and converts it into a blended mesh (a mesh with bone influences) using the Microsoft® Direct3D® vertex blending functionality available in Microsoft® DirectX® 7.x. For more information, see Geometry Blending.

The following code fragment shows how to use a D3DXBuffer object to pass adjacency information.

Dim Opts As Long
Dim D3DXbAdjacencyIn As D3DXBuffer
Dim D3DXbAdjacencyOut As Any
Dim NumBC As Long
Dim RetTable As D3DXBuffer

' This code fragment assumes that all arguments
' have been properly initialized.
Call D3DX8.ConvertToBlendedMesh(Opts, ByVal D3DXbAdjacencyIn.GetBufferPointer, _
                                D3DXbAdjacencyOut, NumBC, RetTable )


D3DXSkinMesh.ConvertToIndexedBlendedMesh

Returns an indexed blended mesh.

object.ConvertToIndexedBlendedMesh( _
    Options As Long, _
    AdjacencyIn As Any, _
    PaletteSize As Long, _
    AdjacencyOut As Any, _
    RetNumBoneCombinations As Long, _
    RetBoneCombinationTable As D3DXBuffer, _
    pFaceRemap As Any, _
    VertexRemap As D3DXBuffer) As D3DXMesh

Parts

object
Object expression that resolves to a D3DXSkinMesh object.
Options
Combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying options for the mesh.
AdjacencyIn
First element of an array of three Long values per face that specify the three neighbors for each face in the source mesh.
PaletteSize
Palette size.
AdjacencyOut
Destination buffer for the face adjacency array of the optimized 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.
RetNumBoneCombinations
Number of entries.
RetBoneCombinationTable
First element in an array of D3DXBONECOMBINATION types. The count of types is NumBoneCombinations. Each bone combination table defines the four bones that you can draw at a time.
pFaceRemap
First element of an array, representing the destination buffer containing the new index for each face.
VertexRemap
D3DXBuffer object containing the new index for each vertex.

Return Values

Returns a D3DXMesh object, representing the blended mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY or D3DXERR_INVALIDMESH.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method takes a skin mesh and converts it into an indexed blended mesh using the Microsoft® Direct3D® indexed vertex blending functionality. Indexed vertex blending uses indices to index into a matrix palette. For more information, see Geometry Blending. Converting a skin mesh into an indexed blended mesh enables you to render the mesh in a single drawing call.

The following code fragment shows how to use a D3DXBuffer object to pass adjacency information.

Dim Opts As Long
Dim D3DXbAdjacencyIn As D3DXBuffer
Dim PalSize as Long
Dim D3DXbAdjacencyOut As Any
Dim NumBC As Long
Dim RetTable As D3DXBuffer

' This code fragment assumes that all arguments
' have been properly initialized.
Call D3DX8.ConvertToIndexedBlendedMesh(Opts, ByVal D3DXbAdjacencyIn.GetBufferPointer, _
                                       PalSize, D3DXbAdjacencyOut, NumBC, RetTable )


D3DXSkinMesh.GenerateSkinnedMesh

Generates a skinned mesh.

object.GenerateSkinnedMesh( _
    Options As Long, _
    MinWeight As Single, _
    AdjacencyIn As Any, _
    AdjacencyOut As Any) As D3DXMesh

Parts

object
Object expression that resolves to a D3DXSkinMesh object.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying options for the mesh.
MinWeight
Sets the minimum weight clamping value.
AdjacencyIn
First element of an array of three Long values per face that specify the three neighbors for each face in the source mesh. See Remarks.
AdjacencyOut
A destination buffer for the face adjacency array of the optimized 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.

Return Values

Returns a D3DXMesh object, representing the generated skinned mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method enables you to specify all matrices and apply them to each bone. GenerateSkinnedMesh does the geometry blending for you, so you do not need to used Direct3D to do the geometry blending. In particular, this method allows more that four bone influences per vertex.

The mesh generated by this method is the one that should be supplied to D3DXSkinMesh.UpdateSkinnedMesh each time the skeleton transforms are modified.

This method is useful for skin animations.

The following code fragment shows how to use a D3DXBuffer object to pass adjacency information.

Dim Opts As Long
Dim MinW As Single
Dim D3DXbAdjacencyIn As D3DXBuffer
Dim D3DXbAdjacencyOut As Any

' This code fragment assumes that all arguments
' have been properly initialized.
Call D3DX8.ConvertToIndexedBlendedMesh(Opts, MinW, ByVal D3DXbAdjacencyIn.GetBufferPointer, PalSize, D3DXbAdjacencyOut)


D3DXSkinMesh.GetBoneInfluence

Returns a list of values indicating how a bone effects the skin mesh.

object.GetBoneInfluence( _
    Bone As Long, _
    Vertices As Long, _
    Weights As Single,)

Parts

object
Object expression that resolves to a D3DXSkinMesh object.
Bone
Bone to query.
Vertices
The list of vertices affected by the bone.
Weights
List of weights associated with each vertex in the list of vertices affected by the bone.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

object.GetDeclaration( _
    Declaration As Long)

Parameters

object
Object expression that resolves to a D3DXSkinMesh object.
Declaration
A returned array describing the vertex format of the vertices in the queried mesh. The upper limit of this declarator array is MAX_FVF_DECL_SIZE, limiting the declarator to a maximum of 20 Longs.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXSkinMesh.GetFVF


D3DXSkinMesh.GetDevice

Retrieves the device associated with the skin mesh.

object.GetDevice() As Direct3DDevice8

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

Returns a Direct3DDevice8 object, identifying the Microsoft® Direct3D® device associated with the mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.GetFVF

Retrieves the flexible vertex format of the vertices in the skin mesh.

object.GetFVF() As Long

Parameters

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

Returns a combination of Flexible Vertex Format Flags that describe the vertex format of the vertices in the skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXSkinMesh.GetDeclaration


D3DXSkinMesh.GetIndexBuffer

Retrieves the data in an index buffer.

object.GetIndexBuffer() As Direct3DIndexBuffer8

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

A Direct3DIndexBuffer8 object, representing the index buffer object associated with the skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.GetMaxFaceInfluences

Return the maximum number of face influences.

object.GetMaxFaceInfluences() As Long

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

Maximum number of influences effecting any single face in the skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Each face can be affected by n bones. The following diagram shows a face affected by 6 bones (the union of bones effecting each vertex of the face).


D3DXSkinMesh.GetMaxVertexInfluences

Returns the maximum number of vertex influences.

object.GetMaxVertexInfluences() As Long

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

Maximum number of influences effecting any single vertex in the skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Each vertex can be affected by n bones. If this method returns a value of 17, up to 17 bones effect a single vertex of the skin mesh. So, there are 17 separate weights on that vertex which add up to 1.


D3DXSkinMesh.GetNumBoneInfluences

Returns the number of influences (weights) on a given bone.

object.GetNumBoneInfluences( _
    Bone As Long) As Long

Parts

object
Object expression that resolves to a D3DXSkinMesh object.
Bone
The bone to query.

Return Values

Returns the number of weights on the given bone. If Bone is an invalid bone number, GetNumBoneInfluences returns 0.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.GetNumBones

Returns the number of bones in the skin mesh.

object.GetNumBones() As Long

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

Number of bones in the skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.GetNumFaces

Retrieves the number of faces in the skin mesh.

object.GetNumFaces() As Long

Parameters

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

Returns the number of faces in the skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.GetNumVertices

Retrieves the number of vertices in the skin mesh.

object.GetNumVertices() As Long

Parameters

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

Returns the number of vertices in the skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.GetOriginalMesh

Returns the skin mesh in its original (default) pose.

object.GetOriginalMesh() As D3DXMesh

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

A D3DXMesh object, representing the skin mesh in its default pose.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.GetOptions

Retrieves the mesh options enabled for this skin mesh at creation time.

object.GetOptions() As Long

Parameters

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
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 the D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered with N-patch enhancement using Microsoft® Direct3D®.
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_USEHWONLY
Use hardware processing only. This flag should be specified only for a hardware processing device. On a mixed mode device, this flag will cause the system to either use hardware only, or—if the hardware is not capable—it will approximate using the software capabilities.
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_SHARE
Forces the cloned meshes to share 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.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.GetVertexBuffer

Retrieves the data in a vertex buffer.

object.GetVertexBuffer() As Direct3DVertexBuffer8

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Return Values

Direct3DVertexBuffer8 object, representing the vertex buffer object associated with the skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.LockAttributeBuffer

Locks an attribute buffer.

object.LockAttributeBuffer( _
    Flags As Long) As Long

Parts

object
Object expression that resolves to a D3DXSkinMesh object.
Flags
A combination of one or more locking flags, indicating how the attribute buffer memory should be locked. Possible values are defined by the CONST_D3DLOCKFLAGS enumeration.

Return Values

First element of an array of Long values, filled with the returned attribute buffer data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSkinMesh.LockIndexBuffer

Locks an index buffer.

object.LockIndexBuffer( _
    Flags As Long) As Long

Parts

object
Object expression that resolves to a D3DXSkinMesh object.
Flags
A combination of one or more locking flags, describing how the index buffer memory should be locked. Possible values are defined by the CONST_D3DLOCKFLAGS enumeration.

Return Values

First element of an array of BYTE values, filled with the returned index data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls matches the number of unlock calls. DrawPrimitive calls do not succeed with any outstanding lock count on any currently set index buffer.

See Also

D3DXSkinMesh.UnlockIndexBuffer


D3DXSkinMesh.LockVertexBuffer

Locks a vertex buffer.

object.LockVertexBuffer( _
    Flags As Long) As Long

Parts

object
Object expression that resolves to a D3DXSkinMesh object.
Flags
A combination of one or more locking flags, indicating how the vertex buffer memory should be locked. Possible values are defined by the CONST_D3DLOCKFLAGS enumeration.

Return Values

First element of an array of BYTE values, filled with the returned vertex data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 do not succeed with any outstanding lock count on any currently set vertex buffer.

See Also

D3DXSkinMesh.UnlockVertexBuffer


D3DXSkinMesh.SetBoneInfluence

Sets the bone influence for a bone in the skin mesh.

object.SetBoneInfluence( _
    Bone As Long, _
    NumInfluences As Long, _
    Vertices As Long, _
    Weights As Single)

Parts

object
Object expression that resolves to a D3DXSkinMesh object.
Bone
Bone for which to set the influences.
NumInfluences
Number of influences to set for the bone.
Vertices
The list of vertices used to set the influences (weights).
Weights
The list of weights to set for the provided vertices. These values are used to programmatically fill in the skinning information for the skin mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to E_OUTOFMEMORY.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Using this method provides a mechanism to indicate how the given bone effects the given vertices. This method should be called for each bone that effects the mesh.


D3DXSkinMesh.UnlockAttributeBuffer

Unlocks an attribute buffer.

object.UnlockAttributeBuffer()

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXSkinMesh.LockAttributeBuffer


D3DXSkinMesh.UnlockIndexBuffer

Unlocks an index buffer.

object.UnlockIndexBuffer()

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXSkinMesh.LockIndexBuffer


D3DXSkinMesh.UnlockVertexBuffer

Unlocks a vertex buffer.

object.UnlockVertexBuffer()

Parts

object
Object expression that resolves to a D3DXSkinMesh object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXSkinMesh.LockVertexBuffer


D3DXSkinMesh.UpdateSkinnedMesh

Updates a skinned mesh.

object.UpdateSkinnedMesh( _
    BoneTransformsIn As Any, _
    RetMesh As D3DXMesh)

Parts

object
Object expression that resolves to a D3DXSkinMesh object
BoneTransformsIn
First element of an array of D3DMATRIX types, representing the bone transforms. The length of this array is the count of all the bones in the skin mesh
RetMesh
A D3DXMesh object, to be filled with the generated skinned mesh.

Remarks

This method updates the vertices blended with the new bone transforms.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXSkinMesh.GenerateSkinnedMesh


D3DXSPMesh

Applications use the methods of the D3DXSPMesh class to manipulate simplification mesh objects. A simplification mesh is used to simplify a given mesh to a lower number of faces.

The D3DXSPMesh class is obtained by calling the D3DX8.CreateSPMesh method.

The methods of the D3DXSPMesh class can be organized into the following groups.

Copying | CloneMesh
 | CloneMeshFVF
 | ClonePMesh
 | ClonePMeshFVF
Faces | GetMaxFaces
 | GetNumFaces
 | ReduceFaces
Information | GetDevice
 | GetOptions
Vertices | GetDeclaration
 | GetFVF
 | GetMaxVertices
 | GetNumVertices
 | ReduceVertices


D3DXSPMesh.CloneMesh

Clones a mesh using a declarator.

object.CloneMesh( _
    Options As Long, _
    Declaration As Any, _
    Device As Direct3DDevice8, _
    AdjacencyOut As Any, _
    VertexRemapOut As Any) As D3DXPMesh

Parts

object
Object expression that resolves to a D3DXSPMesh object.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
Declaration
First element of an array of Long values, representing the declarator to describe the vertex format of the vertices in the output mesh. This parameter must map directly to an FVF.
Device
Direct3DDevice8 object representing the device object associated with the mesh.
AdjacencyOut
First element of an array of three Long values per face that specify the three neighbors for each face in the source mesh
VertexRemapOut
First element of an array containing the index for each vertex.

Return Values

D3DXPMesh object, representing the cloned mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.DeclaratorFromFVF, D3DXSPMesh.GetDeclaration


D3DXSPMesh.CloneMeshFVF

Clones a mesh using a flexible vertex format (FVF) code.

object.CloneMeshFVF( _
    Options As Long, _
    FVF As Long, _
    Device As Direct3DDevice8, _
    AdjacencyOut As Any, _
    VertexRemapOut As Any) As D3DXPMesh

Parts

object
Object expression that resolves to a D3DXSPMesh object.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
FVF
Combination of flexible vertex format flags that specifies the vertex format for the vertices in the output mesh.
Device
Direct3DDevice8 object representing the device object associated with the mesh.
AdjacencyOut
First element of an array of three Long values per face that specify the three neighbors for each face in the source mesh.
VertexRemapOut
First element of an array containing the index for each vertex.

Return Values

D3DXPMesh object, representing the cloned mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

CloneMeshFVF can be used to convert a mesh from one FVF to another.

See Also

D3DX8.FVFFromDeclarator, D3DXSPMesh.GetFVF


D3DXSPMesh.ClonePMesh

Clones a progressive mesh using a declarator.

object.ClonePMesh( _
    Options As Long, _
    Declaration As Any, _
    Device As Direct3DDevice8, _
    VertexRemapOut As Any) As D3DXPMesh

Parts

object
Object expression that resolves to a D3DXSPMesh object.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
Declaration
First element of an array of Long values, representing the declarator to describe the vertex format of the vertices in the output mesh. This parameter must map directly to an FVF.
Device
Direct3DDevice8 object representing the device object associated with the mesh.
VertexRemapOut
First element of an array containing the index for each vertex.

Return Values

D3DXPMesh object, representing the cloned progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_CANNOTATTRSORT
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DX8.DeclaratorFromFVF, D3DXSPMesh.GetDeclaration


D3DXSPMesh.ClonePMeshFVF

Clones a progressive mesh using a flexible vertex format (FVF) code.

object.ClonePMeshFVF( _
    Options As Long, _
    FVF As Long, _
    Device As Direct3DDevice8, _
    VertexRemapOut As Any) As D3DXPMesh

Parts

object
Object expression that resolves to a D3DXSPMesh object.
Options
A combination of one or more flags defined by the CONST_D3DXMESH enumeration, specifying creation options for the mesh.
FVF
Combination of flexible vertex format flags that specifies the vertex format for the vertices in the output mesh.
Device
Direct3DDevice8 object representing the device object associated with the mesh.
VertexRemapOut
First element of an array containing the index for each vertex.

Return Values

D3DXPMesh object, representing the cloned progressive mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

See Also

D3DX8.FVFFromDeclarator, D3DXSPMesh.GetFVF


D3DXSPMesh.GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

object.GetDeclaration( _
    Declaration As Long)

Parts

object
Object expression that resolves to a D3DXSPMesh object.
Declaration
First element of an array describing the vertex format of the vertices in the queried mesh. The upper limit of this declarator array is MAX_FVF_DECL_SIZE, limiting the declarator to a maximum of 20 Long values.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXSPMesh.GetFVF


D3DXSPMesh.GetDevice

Retrieves the device object associated with the simplification mesh.

object.GetDevice() As Direct3DDevice8

Parts

object
Object expression that resolves to a D3DXSPMesh object.

Return Values

Direct3DDevice8 object, identifying the Microsoft® Direct3D® device associated with the simplification mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSPMesh.GetFVF

Retrieves the flexible vertex format of the vertices in the simplification mesh.

object.GetFVF() As Long

Parts

object
Object expression that resolves to a D3DXSPMesh object.

Return Values

Combination of flexible vertex format flags that describe the vertex format of the vertices in the simplification mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXSPMesh.GetDeclaration


D3DXSPMesh.GetMaxFaces

Retrieves the maximum number of faces that the simplification mesh supports.

object.GetMaxFaces() As Long

Parts

object
Object expression that resolves to a D3DXSPMesh object.

Return Values

Returns the maximum number of faces in the original mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSPMesh.GetMaxVertices

Retrieves the maximum number of vertices that the simplification mesh supports.

object.GetMaxVertices() As Long

Parts

object
Object expression that resolves to a D3DXSPMesh object.

Return Values

Returns the maximum number of vertices in the original mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSPMesh.GetNumFaces

Retrieves the number of faces in the simplification mesh.

object.GetNumFaces() As Long

Parts

object
Object expression that resolves to a D3DXSPMesh object.

Return Values

Returns the number of faces in the simplification mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSPMesh.GetNumVertices

Retrieves the number of vertices in the simplification mesh.

object.GetNumVertices() As Long

Parts

object
Object expression that resolves to a D3DXSPMesh object.

Return Values

Returns the number of vertices in the simplification mesh.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSPMesh.GetOptions

Retrieves the mesh options enabled for this simplification mesh at creation time.

object.GetOptions() As Long

Parts

object
Object expression that resolves to a D3DXSPMesh object.

Return Values

Returns a combination of one or more of the flags defined by the CONST_D3DXMESH enumeration, indicating the options enabled for this mesh at creation time.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXSPMesh.ReduceFaces

Reduces the number of faces in a simplification mesh.

object.ReduceFaces( _
    Faces As Long)

Parts

object
Object expression that resolves to a D3DXSPMesh object.
Faces
Number of faces to which to reduce the primitive count.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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.


D3DXSPMesh.ReduceVertices

Reduces the number of vertices in a simplification mesh.

object.ReduceVertices( _
    Vertices As Long)

Parts

object
Object expression that resolves to a D3DXSPMesh object.
Vertices
Number of vertices to which to reduce the primitive count.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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.


D3DXSprite

The D3DXSprite class provides a set of methods that simplify the process of drawing sprites using Microsoft® Direct3D®.

The D3DXSprite class is obtained by calling the D3DX8.CreateSprite method.

The methods of the D3DXSprite class can be organized into the following groups.

Drawing | Begin
 | Draw
 | DrawTransform
 | End
Information | GetDevice
Miscellaneous | OnLostDevice
 | OnResetDevice


D3DXSprite.Begin

Prepares a device for drawing sprites.

object.Begin()

Parts

object
Object expression that resolves to a D3DXSprite object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Calling Begin is optional. If called outside of a Begin/End sequence, the draw functions internally call Begin and End. To avoid extra overhead, this method should be used if more than one draw function is called successively.

This method must be called from inside a Direct3DDevice8.BeginScene and Direct3DDevice8.EndScene sequence.

D3DXSprite.Begin cannot be used as a substitute for either Direct3DDevice8.BeginScene or D3DXRenderToSurface.BeginScene.

See Also

D3DXSprite.End


D3DXSprite.Draw

Draws a simple sprite in screen-space.

object.Draw( _
    SrcTexture As Direct3DTexture8, _
    SrcRect As Any, _
    Scaling As D3DVECTOR2, _
    RotationCenter As D3DVECTOR2, _
    Rotation As Single, _
    Translation As D3DVECTOR2, _
    Color As Long)

Parts

object
Object expression that resolves to a D3DXSprite object.
SrcTexture
A Direct3DTexture8 object, representing the source image used for the sprite.
SrcRect
A RECT type that indicates what portion of the source texture to use for the sprite. If this parameter is ByVal 0, then the entire source image is used for the sprite. However, you can specify a sub-rectangle of the source image instead.

Before transformation, the size of the sprite is defined by SrcRect with the top-left corner at the origin (0,0).

Scaling
A D3DVECTOR2 type, containing the scaling vector. If this argument is ByVal 0, the value (1.0, 1.0) is used. Since Scaling is a vector, a multiplier of 1.0 would preserve the source size.
RotationCenter
A D3DVECTOR2 type, containing the point that in screen pixels that identifies the center of rotation. If this argument is ByVal 0, the point (0,0) is used, which is the upper-left corner of the texture.
Rotation
Value that specifies the rotation in radians, counter-clockwise.
Translation
[in] Pointer to a D3DVECTOR2 type, containing the translation in screen pixels. If this argument is ByVal 0, the point (0,0) is used.
Color
The color and alpha channels are modulated by this value. A value of &HFFFFFFFF& maintains the original source color and alpha data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method must be called between an Direct3DDevice8.BeginScene and Direct3DDevice8.EndScene pair.

If D3DXSprite.Begin has not been called, this method internally calls Begin and D3DXSprite.End. When making successive calls to D3DXSprite.Draw and/or D3DXSprite.DrawTransform, make sure to call Begin to avoid the extra overhead of Draw and DrawTransform internally calling Begin and End each time.

The image can be mirrored by specifying a negative vector in the appropriate direction (x, y, or both) for the Scaling parameter and adding the width and/or height of the source rectangle, specified in the SrcRect parameter, to the values specified in the Translation parameter. Note that this will change the point of origin for rotations.

See Also

D3DXSprite.DrawTransform


D3DXSprite.DrawTransform

Provides a mechanism for drawing a sprite that is transformed by a specified matrix.

object.DrawTransform( _
    SrcTexture As Direct3DTexture8, _
    SrcRect As Any, _
    TransformMatrix As D3DMATRIX, _
    Color As Long)

Parts

object
Object expression that resolves to a D3DXSprite object.
SrcTexture
Direct3DTexture8 object, representing the source image used for the sprite.
SrcRect
A RECT type that indicates what portion of the source texture to use for the sprite. If this parameter is ByVal 0, then the entire source image is used for the sprite. However, you can specify a sub-rectangle of the source image instead.

Before transformation, the size of the sprite is defined by SrcRect with the top-left corner at the origin (0,0).

TransformMatrix
A D3DMATRIX type, specifying the transformation that is applied.
Color
Value representing the color. The color and alpha channels are modulated by this value. A value of &HFFFFFFFF& maintains the original source color and alpha data.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method must be called between an Direct3DDevice8.BeginScene and Direct3DDevice8.EndScene pair.

If D3DXSprite.Begin has not been called, this method internally calls Begin and D3DXSprite.End. When making successive calls to D3DXSprite.Draw and/or D3DXSprite.DrawTransform, be sure to call Begin to avoid the extra overhead of Draw and DrawTransform internally calling Begin and End each time.

See Also

D3DXSprite.Draw


D3DXSprite.End

Restores the device state to how it was when D3DXSprite.Begin was called.

object.End()

Parts

object
Object expression that resolves to a D3DXSprite object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

D3DXSprite.End cannot be used as a substitute for either Direct3DDevice8.EndScene or D3DXRenderToSurface.EndScene.

See Also

D3DXSprite.Begin


D3DXSprite.GetDevice

Retrieves the Microsoft® Direct3D® device associated with the sprite object.

object.GetDevice() As Direct3DDevice8

Parts

object
Object expression that resolves to a D3DXSprite object.

Return Values

Direct3DDevice8 object representing the device object associated with the sprite object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Functions

This section contains reference information for the functions that you need to implement when you work with Direct3DX. The following functions are implemented.

  • Copy Functions
  • Math Functions


Copy Functions

The copying library provided by the Microsoft Direct3DX utility library supplies functions that enable you to easily copy data between vertex arrays, index arrays, and vertex and index buffers associated with mesh objects.

Mesh Buffer | D3DXMeshIndexBuffer8GetData
 | D3DXMeshIndexBuffer8SetData
 | D3DXMeshVertexBuffer8GetData
 | D3DXMeshVertexBuffer8SetData
Memory | DXCopyMemory


D3DXMeshIndexBuffer8GetData

Copies indices from a vertex buffer attached to a mesh object to an index array.

D3DXMeshIndexBuffer8GetData( _
    D3DXMeshobj As Unknown, _
    Offset As Long, _
    Size As Long, _
    Flags As Long, _
    Data As Any) As Long

Parameters

D3DXMeshobj
Object that resolves to a D3DXMesh object that contains the vertex buffer to retrieve.
Offset
Offset, in bytes, from the start of the buffer to where data retrieval begins.
Size
Size of the buffer, in bytes.
Flags
Combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.
Data
Memory to be filled with the retrieved data. 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
E_INVALIDARG

Error Codes

Err.Number is not set for this function.

Remarks

The following code fragment demonstrates a typical use for this function.

Dim IndexArray(9) As Long
Dim Mesh As D3DXMesh
Dim hr As Long

'The following code assumes that Mesh has been properly initialized
hr = D3DXMeshIndexBuffer8GetData(Mesh, 0, (Len(IndexArray(0)) * 10), _
                                  0, IndexArray(0))

See Also

D3DXMeshIndexBuffer8SetData


D3DXMeshIndexBuffer8SetData

Copies indices from an array of indices into an index buffer attached to a mesh object.

D3DXMeshIndexBuffer8SetData( _
    D3DXMeshobj As Unknown, _
    Offset As Long, _
    Size As Long, _
    Flags As Long, _
    Data As Any) As Long

Parameters

D3DXMeshobj
Object that resolves to a D3DXMesh object which contains the index buffer to set.
Offset
Offset, in bytes, from the start of the index buffer to where data is set.
Size
Size of the buffer, in bytes.
Flags
A combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.
Data
The first element of an index array to be used to set the index buffer. 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
E_INVALIDARG

Error Codes

Err.Number is not set for this function.

Remarks

The following code fragment demonstrates a typical use for this function.

Dim IndexArray(9) As Long
Dim Mesh As D3DXMesh
Dim hr As Long

'The following code assumes that Mesh has been properly initialized
hr = D3DXMeshIndexBuffer8SetData(Mesh, 0, (Len(IndexArray(0)) * 10), _
                                  0, IndexArray(0))

See Also

D3DXMeshIndexBuffer8GetData


D3DXMeshVertexBuffer8GetData

Copies vertices from a vertex buffer attached to a mesh object into an vertex array.

D3DXMeshVertexBuffer8GetData( _
    D3DXMeshobj As Unknown, _
    Offset As Long, _
    Size As Long, _
    Flags As Long, _
    Data As Any) As Long

Parameters

D3DXMeshobj
Object that resolves to a D3DXMesh object that contains the vertex buffer to retrieve.
Offset
Offset, in bytes, from the start of the buffer to where data retrieval begins.
Size
Size of the buffer, in bytes.
Flags
A combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.
Data
First element of an array of vertices to be filled with the retrieved data. 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
E_INVALIDARG

Error Codes

Err.Number is not set for this function.

Remarks

The following code fragment demonstrates a typical use for this function.

Dim VertArray(9) As D3DVERTEX
Dim Mesh As D3DXMesh
Dim hr As Long

'The following code assumes that Mesh has been properly initialized
hr = D3DXMeshVertexBuffer8GetData(Mesh, 0, (Len(VertArray(0)) * 10), _
                                  0, VertArray(0))

See Also

D3DXMeshVertexBuffer8SetData


D3DXMeshVertexBuffer8SetData

Copies vertices from a vertex array into a vertex buffer attached to a mesh object.

D3DXMeshVertexBuffer8SetData( _
    D3DXMeshobj As Unknown, _
    Offset As Long, _
    Size As Long, _
    Flags As Long, _
    Data As Any) As Long

Parameters

D3DXMeshobj
Object that resolves to a D3DXMesh object that contains the vertex buffer to set.
Offset
Offset, in bytes, from the start of the buffer to where data is set.
Size
Size of the buffer, in bytes.
Flags
A combination of one or more valid locking flags defined by the CONST_D3DLOCKFLAGS enumeration, describing the type of lock to perform.
Data
The first element of an array of vertices used to set the vertex buffer. 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
E_INVALIDARG

Error Codes

Err.Number is not set for this function.

Remarks

The following code fragment demonstrates a typical use for this function.

Dim VertArray(9) As D3DVERTEX
Dim Mesh As D3DXMesh
Dim hr As Long

'The following code assumes that Mesh has been properly initialized
hr = D3DXMeshVertexBuffer8SetData(Mesh, 0, (Len(VertArray(0)) * 10), _
                                  0, VertArray(0))

See Also

D3DXMeshVertexBuffer8GetData


DXCopyMemory

DXCopyMemory( _
    Dest As Any, _
    Src As Any, _
    Size As Long) As Long

Parameters

Dest
The memory into which to copy data. See Remarks.
Src
The memory from which to copy data. See Remarks
Size
Size, in bytes, of the data to copy.

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_INVALIDARG

Error Codes

Err.Number is not set for this function.

Remarks

Both Dest and Src may be any of the following: a type, the first element of an array, a pointer returned by D3DXBuffer.GetBufferPointer, or a pointer returned from either Direct3DIndexBuffer8.Lock or Direct3DVertexBuffer8.Lock.


Math Functions

The math library provided by the Direct3DX utility library supplies functions to compute both basic and complicated 3-D mathematical operations.

The 3-D math application functions can be organized into the following groups:

Color | D3DXColorAdd
 | D3DXColorAdjustContrast
 | D3DXColorAdjustSaturation
 | D3DXColorLerp
 | D3DXColorModulate
 | D3DXColorNegative
 | D3DXColorScale
 | D3DXColorSubtract
Plane | D3DXPlaneDot
 | D3DXPlaneDotCoord
 | D3DXPlaneDotNormal
 | D3DXPlaneFromPointNormal
 | D3DXPlaneFromPoints
 | D3DXPlaneIntersectLine
 | D3DXPlaneNormalize
 | D3DXPlaneTransform
Quaternion | D3DXQuaternionBaryCentric
 | D3DXQuaternionConjugate
 | D3DXQuaternionDot
 | D3DXQuaternionExp
 | D3DXQuaternionIdentity
 | D3DXQuaternionInverse
 | D3DXQuaternionIsIdentity
 | D3DXQuaternionLength
 | D3DXQuaternionLengthSq
 | D3DXQuaternionLn
 | D3DXQuaternionMultiply
 | D3DXQuaternionNormalize
 | D3DXQuaternionRotationAxis
 | D3DXQuaternionRotationMatrix
 | D3DXQuaternionRotationYawPitchRoll
 | D3DXQuaternionSlerp
 | D3DXQuaternionSquad
 | D3DXQuaternionToAxisAngle
2-D Vector | D3DXVec2Add
 | D3DXVec2BaryCentric
 | D3DXVec2CatmullRom
 | D3DXVec2CCW
 | D3DXVec2Dot
 | D3DXVec2Hermite
 | D3DXVec2Length
 | D3DXVec2LengthSq
 | D3DXVec2Lerp
 | D3DXVec2Maximize
 | D3DXVec2Minimize
 | D3DXVec2Normalize
 | D3DXVec2Scale
 | D3DXVec2Subtract
 | D3DXVec2Transform
 | D3DXVec2TransformCoord
 | D3DXVec2TransformNormal
3-D Vector | D3DXVec3Add
 | D3DXVec3BaryCentric
 | D3DXVec3CatmullRom
 | D3DXVec3Cross
 | D3DXVec3Dot
 | D3DXVec3Hermite
 | D3DXVec3Length
 | D3DXVec3LengthSq
 | D3DXVec3Lerp
 | D3DXVec3Maximize
 | D3DXVec3Minimize
 | D3DXVec3Normalize
 | D3DXVec3Project
 | D3DXVec3Scale
 | D3DXVec3Subtract
 | D3DXVec3Transform
 | D3DXVec3TransformCoord
 | D3DXVec3TransformNormal
 | D3DXVec3Unproject
4-D Matrix | D3DXMatrixAffineTransformation
 | D3DXMatrixfDeterminant
 | D3DXMatrixIdentity
 | D3DXMatrixInverse
 | D3DXMatrixIsIdentity
 | D3DXMatrixLookAtLH
 | D3DXMatrixLookAtRH
 | D3DXMatrixMultiply
 | D3DXMatrixOrthoLH
 | D3DXMatrixOrthoRH
 | D3DXMatrixOrthoOffCenterLH
 | D3DXMatrixOrthoOffCenterRH
 | D3DXMatrixPerspectiveFovLH
 | D3DXMatrixPerspectiveFovRH
 | D3DXMatrixPerspectiveLH
 | D3DXMatrixPerspectiveRH
 | D3DXMatrixPerspectiveOffCenterLH
 | D3DXMatrixPerspectiveOffCenterRH
 | D3DXMatrixReflect
 | D3DXMatrixRotationAxis
 | D3DXMatrixRotationQuaternion
 | D3DXMatrixRotationX
 | D3DXMatrixRotationY
 | D3DXMatrixRotationYawPitchRoll
 | D3DXMatrixRotationZ
 | D3DXMatrixScaling
 | D3DXMatrixShadow
 | D3DXMatrixTransformation
 | D3DXMatrixTranslation
 | D3DXMatrixTranspose
4-D Vector | D3DXVec4Add
 | D3DXVec4BaryCentric
 | D3DXVec4CatmullRom
 | D3DXVec4Cross
 | D3DXVec4Dot
 | D3DXVec4Hermite
 | D3DXVec4Length
 | D3DXVec4LengthSq
 | D3DXVec4Lerp
 | D3DXVec4Maximize
 | D3DXVec4Minimize
 | D3DXVec4Normalize
 | D3DXVec4Scale
 | D3DXVec4Subtract
 | D3DXVec4Transform


D3DXColorAdd

Adds two color values together to create a new color value.

D3DXColorAdd( _
    COut As D3DCOLORVALUE, _
    C1 As D3DCOLORVALUE, _
    C2 As D3DCOLORVALUE)

Parameters

COut
A D3DCOLORVALUE type that is the result of the operation, the sum of two color values.
C1
A source D3DCOLORVALUE type.
C2
A source D3DCOLORVALUE type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXColorModulate, D3DXColorSubtract


D3DXColorAdjustContrast

Adjusts the contrast value of a color.

D3DXColorAdjustContrast( _
    COut As D3DCOLORVALUE, _
    C1 As D3DCOLORVALUE, _
    c As Single)

Parameters

COut
A D3DCOLORVALUE type that is the result of the operation, the result of the contrast adjustment.
C1
A source D3DCOLORVALUE type.
c
Contrast value. This parameter linearly interpolates between 50 percent gray and the color C1. There are not limits on the value of c. If this parameter is zero, then the returned color is 50 percent gray. If this parameter is 1, then the returned color is the original color.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function interpolates the red, green, and blue color components of a D3DCOLORVALUE type between 50 percent gray and a specified contrast value, as shown in the following example.

    Cout.r = 0.5 + c * (C1.r - 0.5)

If c is greater than 0 and less than 1, the contrast is decreased. If c is greater than 1, then the contrast is increased.

See Also

D3DXColorAdjustSaturation


D3DXColorAdjustSaturation

Adjusts the saturation value of a color.

D3DXColorAdjustSaturation( _
    COut As D3DCOLORVALUE, _
    C1 As D3DCOLORVALUE, _
    s As Single)

Parameters

COut
A D3DCOLORVALUE type that is the result of the operation, the result of the saturation adjustment.
C1
A source D3DCOLORVALUE type.
s
Saturation value. This parameter linearly interpolates between the color converted to gray-scale and the original color, C1. There are no limits on the value of s. If s is 0, then the returned color is the gray-scale color. If s is 1, the returned color is the original color.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function interpolates the red, green, and blue color components of a D3DCOLORVALUE type between an unsaturated color and a color, as shown in the following example.

    ' Approximate values for each component's contribution to luminance.
    ' Based up the NTSC standard described in ITU-R Recommendation BT.709.
    Dim Grey As Long
    Grey = C1.r * 0.2125 + C1.g * 0.7154 + C1.b * 0.0721

    COut.r = Grey + s * (C1.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 gray-scale color is computed as: r = g = b = 0.2125*r + 0.7154*g + 0.0721*b.

See Also

D3DXColorAdjustContrast


D3DXColorLerp

Uses linear interpolation to create a color value.

D3DXColorLerp( _
    COut As D3DCOLORVALUE, _
    C1 As D3DCOLORVALUE, _
    C2 As D3DCOLORVALUE, _
    s As Single)

Parameters

COut
A D3DCOLORVALUE type that is the result of the operation, the result of the linear interpolation.
C1
A source D3DCOLORVALUE type.
C2
A source D3DCOLORVALUE type.
s
Parameter that linearly interpolates between the colors, C1 and C2, treating them both as 4-D vectors. There are no limits on the value of s.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function interpolates the red, green, blue, and alpha components of a D3DCOLORVALUE type between two colors, as shown in the following example.

    COut.r = .C1.r + s * (C2.r - C1.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 B.

See Also

D3DXColorModulate, D3DXColorNegative, D3DXColorScale


D3DXColorModulate

Blends two colors.

D3DXColorModulate( _
    COut As D3DCOLORVALUE, _
    C1 As D3DCOLORVALUE, _
    C2 As D3DCOLORVALUE)

Parameters

COut
A D3DCOLORVALUE type that is the result of the operation, the result of the blending operation.
C1
A source D3DCOLORVALUE type.
C2
A source D3DCOLORVALUE type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function blends together two colors by multiplying matching color components, as shown in the following example.

    Cout.r = C1.r * C2.r

See Also

D3DXColorLerp, D3DXColorNegative, D3DXColorScale


D3DXColorNegative

Creates the negative color value of a color value.

D3DXColorNegative( _
    COut As D3DCOLORVALUE, _
    C As D3DCOLORVALUE)

Parameters

COut
A D3DCOLORVALUE type that is the result of the operation, the negative color value of the color value.
C
A source D3DCOLORVALUE type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function returns the negative color value by subtracting 1.0 from the color components of the D3DCOLORVALUE type, as shown in the following example.

    COut.r = 1.0 - C.r

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorScale


D3DXColorScale

Scales a color value.

D3DXColorScale( _
    COut As D3DCOLORVALUE, _
    C1 As D3DCOLORVALUE, _
    s As Single)

Parameters

COut
A D3DCOLORVALUE type that is the result of the operation, the scaled color value.
C1
A source D3DCOLORVALUE type.
s
Scale factor. It scales the color, treating it like a 4-D vector. There are no limits on the value of s. If s is 1, the resulting color is the original color.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function computes the scaled color value by multiplying the color components of the D3DCOLORVALUE type by the specified scale factor, as shown in the following example.

    Cout.r = C1.r * s

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorNegative


D3DXColorSubtract

Subtracts two color values to create a new color value.

D3DXColorSubtract( _
    COut As D3DCOLORVALUE, _
    C1 As D3DCOLORVALUE, _
    C2 As D3DCOLORVALUE)

Parameters

COut
A D3DCOLORVALUE type that is the result of the operation, the difference between two color values.
C1
A source D3DCOLORVALUE type.
C2
A source D3DCOLORVALUE type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXColorAdd


D3DXMatrixAffineTransformation

Builds an affine transformation matrix.

D3DXMatrixAffineTransformation( _
    MOut As D3DMATRIX, _
    Scaling As Single, _
    VRotationCenter As D3DVECTOR, _
    QRotation As D3DQUATERNION, _
    VTranslation As D3DVECTOR)

Parameters

MOut
D3DMATRIX type that is the result of the operation, an affine transformation matrix.
Scaling
Scaling factor.
VRotationCenter
D3DVECTOR type, a point identifying the center of rotation. If this argument is an empty D3DVECTOR type, it is treated as identity.
QRotation
D3DQUATERNION type that specifies the rotation. If this argument is an empty D3DQUATERNION type, it is treated as identity.
VTranslation
D3DVECTOR type, representing the translation. If this argument is an empty D3DVECTOR type, it is treated as identity.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DXMatrixAffineTransformation function calculates the affine transformation matrix with the following formula: Ms * Mrc-1 * Mr * Mrc * Mt, where Ms is the scaling matrix, Mrc is the center of rotation matrix, Mr is the rotation matrix, and Mt is the translation matrix.


D3DXMatrixfDeterminant

Returns the determinant of a matrix.

D3DXMatrixfDeterminant( _
    M As D3DMATRIX) As Single

Parameters

M
The source D3DMATRIX type.

Return Values

The value of the matrix, the determinant.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXMatrixIdentity

Creates an identity matrix.

D3DXMatrixIdentity( _
    MOut As D3DMATRIX)

Parameters

MOut
D3DMATRIX type that is the result of the operation, the identity matrix.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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×4 matrix.

See Also

D3DXMatrixIsIdentity


D3DXMatrixInverse

Calculates the inverse of a matrix.

D3DXMatrixInverse( _
    MOut As D3DMATRIX, _
    Determinant As Single, _
    M As D3DMATRIX)

Parameters

MOut
D3DMATRIX type that is the result of the operation, the inverse of the matrix.
Determinant
After this function returns, a Single value that is the determinant of the matrix, M.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If matrix inversion fails, an empty D3DMATRIX type is returned by the D3DXMatrixInverse function. The determinant of M is returned if the Determinant parameter is not 0.


D3DXMatrixIsIdentity

Determines if a matrix is an identity matrix.

D3DXMatrixIsIdentity( _
    M As D3DMATRIX) As Long

Parameters

M
D3DMATRIX type that will be tested for identity.

Return Values

If the matrix is an identity matrix, this function returns a nonzero value (True); otherwise, this function returns zero (False).

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixIdentity


D3DXMatrixLookAtLH

Builds a left-handed, look-at matrix.

D3DXMatrixLookAtLH( _
    MOut As D3DMATRIX, _
    VEye As D3DVECTOR, _
    VAt As D3DVECTOR, _
    VUp As D3DVECTOR)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a left-handed, look-at matrix.
VEye
D3DVECTOR type that defines the eye point. This value is used in translation.
VAt
D3DVECTOR type that defines the camera look-at target.
VUp
D3DVECTOR type that defines the current world's up, usually [0, 1, 0].

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixLookAtRH


D3DXMatrixLookAtRH

Builds a right-handed, look-at matrix.

D3DXMatrixLookAtRH( _
    MOut As D3DMATRIX, _
    VEye As D3DVECTOR, _
    VAt As D3DVECTOR, _
    VUp As D3DVECTOR)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a right-handed, look-at matrix.
VEye
D3DVECTOR type that defines the eye point. This value is used in translation.
VAt
D3DVECTOR type that defines the camera look-at target.
VUp
D3DVECTOR type that defines the current world's up, usually [0, 1, 0].

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixLookAtLH


D3DXMatrixMultiply

Determines the product of two matrices.

D3DXMatrixMultiply( _
    MOut As D3DMATRIX, _
    M1 As D3DMATRIX, _
    M2 As D3DMATRIX)

Parameters

MOut
D3DMATRIX type that is the result of the operation, the product of two matrices.
M1
A source D3DMATRIX type.
M2
A source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The result represents the transformation M2 followed by the transformation M1 (Out = M1 * M2).

See Also

D3DXQuaternionMultiply


D3DXMatrixOrthoLH

Builds a left-handed orthogonal projection matrix.

D3DXMatrixOrthoLH( _
    MOut As D3DMATRIX, _
    w As Single, _
    h As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a left-handed orthogonal projection matrix.
w
Width of the view-volume.
h
Height of the view-volume.
zn
Minimum z-value of the view volume.
zf
Maximum z-value of the view volume.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All the parameters of the D3DXMatrixOrthoLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoOffCenterLH

Builds a customized, left-handed orthogonal projection matrix.

D3DXMatrixOrthoOffCenterLH( _
    MOut As D3DMATRIX, _
    l As Single, _
    r As Single, _
    b As Single, _
    t As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a customized, left-handed orthogonal projection matrix.
l
Minimum x-value of view-volume.
r
Maximum x-value of view-volume.
b
Maximum y-value of view-volume.
t
Minimum y-value of view-volume.
zn
Minimum z-value of the view volume.
zf
Maximum z-value of the view volume.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

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.

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH


D3DXMatrixOrthoOffCenterRH

Builds a customized, right-handed orthogonal projection matrix.

D3DXMatrixOrthoOffCenterRH( _
    MOut As D3DMATRIX, _
    l As Single, _
    r As Single, _
    b As Single, _
    t As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a customized, right-handed orthogonal projection matrix.
l
Minimum x-value of view-volume.
r
Maximum x-value of view-volume.
b
Maximum y-value of view-volume.
t
Minimum y-value of view-volume.
zn
Minimum z-value of the view volume.
zf
Maximum z-value of the view volume.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

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.

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoRH

Builds a right-handed orthogonal projection matrix.

D3DXMatrixOrthoRH( _
    MOut As D3DMATRIX, _
    w As Single, _
    h As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a right-handed orthogonal projection matrix.
w
Width of the view-volume.
h
Height of the view-volume.
zn
Minimum z-value of the view volume.
zf
Maximum z-value of the view volume.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All the parameters of the D3DXMatrixOrtho function are distances in camera-space. The parameters describe the dimensions of the view-volume.

See Also

D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixPerspectiveFovLH

Builds a left-handed perspective projection matrix based on a field of view (FOV).

D3DXMatrixPerspectiveFovLH( _
    MOut As D3DMATRIX, _
    fovy As Single, _
    aspect As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, left-handed perspective projection matrix.
fovy
Field of view, in radians.
aspect
Aspect ratio.
zn
Z-value of the near view-plane.
zf
Z-value of the far view-plane.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveFovRH

Builds a right-handed perspective projection matrix based on a field of view (FOV).

D3DXMatrixPerspectiveFovRH( _
    MOut As D3DMATRIX, _
    fovy As Single, _
    aspect As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, right-handed perspective projection matrix.
fovy
Field of view, in radians.
aspect
Aspect ratio.
zn
Z-value of the near view-plane.
zf
Z-value of the far view-plane.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveLH

Builds a left-handed perspective projection matrix

D3DXMatrixPerspectiveLH( _
    MOut As D3DMATRIX, _
    w As Single, _
    h As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a left-handed perspective projection matrix.
w
Width of the view-volume at the near view-plane.
h
Height of the view-volume at the near view-plane.
zn
Z-value of the near view-plane.
zf
Z-value of the far view-plane.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

All the parameters of the D3DXMatrixPerspectiveLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveOffCenterLH

Builds a customized, left-handed perspective projection matrix.

D3DXMatrixPerspectiveOffCenterLH( _
    MOut As D3DMATRIX, _
    l As Single, _
    r As Single, _
    b As Single, _
    t As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a customized, left-handed perspective projection matrix.
l
Minimum x-value of view-volume.
r
Maximum x-value of view-volume.
b
Maximum y-value of view-volume.
t
Minimum y-value of view-volume.
zn
Minimum z-value of the view volume.
zf
Maximum z-value of the view volume.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH


D3DXMatrixPerspectiveOffCenterRH

Builds a customized, right-handed perspective projection matrix.

D3DXMatrixPerspectiveOffCenterRH( _
    MOut As D3DMATRIX, _
    l As Single, _
    r As Single, _
    b As Single, _
    t As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a customized, right-handed perspective projection matrix.
l
Minimum x-value of view-volume.
r
Maximum x-value of view-volume.
b
Maximum y-value of view-volume.
t
Minimum y-value of view-volume.
zn
Minimum z-value of the view volume.
zf
Maximum z-value of the view volume.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterRH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveRH

Builds a right-handed perspective projection matrix.

D3DXMatrixPerspectiveRH( _
    MOut As D3DMATRIX, _
    w As Single, _
    h As Single, _
    zn As Single, _
    zf As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a right-handed perspective projection matrix.
w
Width of the view-volume at the near view-plane.
h
Height of the view-volume at the near view-plane.
zn
Z-value of the near view-plane.
zf
Z-value of the far view-plane.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

All the parameters of the D3DXMatrixPerspectiveRH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

See Also

D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixReflect

Builds a matrix that reflects the coordinate system about a plane.

D3DXMatrixReflect( _
    MOut As D3DMATRIX, _
    Plane As D3DPLANE)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a matrix that reflects the coordinate system about the source plane.
Plane
The source D3DPLANE type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXMatrixRotationAxis

Builds a matrix that rotates around an arbitrary axis.

D3DXMatrixRotationAxis( _
    MOut As D3DMATRIX, _
    VAxis As D3DVECTOR, _
    angle As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a matrix rotated around the specified axis.
VAxis
D3DVECTOR type that identifies the axis angle.
angle
Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationQuaternion

Builds a matrix from a quaternion.

D3DXMatrixRotationQuaternion( _
    MOut As D3DMATRIX, _
    Q As D3DQUATERNION)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a matrix built from the source quaternion.
Q
The source D3DQUATERNION type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationX

Builds a matrix that rotates around the x-axis.

D3DXMatrixRotationX( _
    MOut As D3DMATRIX, _
    angle As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a matrix rotated around the x-axis.
angle
Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationY

Builds a matrix that rotates around the y-axis.

D3DXMatrixRotationY( _
    MOut As D3DMATRIX, _
    angle As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a matrix rotated around the y-axis.
angle
Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationYawPitchRoll

Builds a matrix with a specified yaw, pitch, and roll.

D3DXMatrixRotationYawPitchRoll( _
    MOut As D3DMATRIX, _
    yaw As Single, _
    pitch As Single, _
    roll As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a matrix with the specified yaw, pitch, and roll.
yaw
Yaw around the y-axis, in radians.
pitch
Pitch around the x-axis, in radians.
roll
Roll around the z-axis, in radians.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ


D3DXMatrixRotationZ

Builds a matrix that rotates around the z-axis.

D3DXMatrixRotationZ( _
    MOut As D3DMATRIX, _
    angle As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a matrix rotated around the z-axis.
angle
Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll


D3DXMatrixScaling

Builds a matrix that scales along the x-, y-, and z-axes.

D3DXMatrixScaling( _
    MOut As D3DMATRIX, _
    x As Single, _
    y As Single, _
    z As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, the scaled matrix.
x
Scaling factor that is applied along the x-axis.
y
Scaling factor that is applied along the y-axis.
z
Scaling factor that is applied along the z-axis.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXMatrixShadow

Builds a matrix that projects geometry into a plane, as if casting a shadow from a light. See Remarks.

D3DXMatrixShadow( _
    MOut As D3DMATRIX, _
    VLight As D3DVECTOR4, _
    Plane As D3DPLANE)

Parameters

MOut
D3DMATRIX type that is the result of the operation, a matrix that projects geometry into a plane. See Remarks.
VLight
D3DVECTOR4 type describing the light's position.
Plane
The source D3DPLANE type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DXMatrixShadow function builds a matrix that projects geometry into a plane. If Vlight.w is 0, then the ray from the origin to Vlight represents a directional light. If it is 1, then Vlight represents a point light.


D3DXMatrixTransformation

Builds a transformation matrix.

D3DXMatrixTransformation( _
    MOut As D3DMATRIX, _
    VScaleCenter As D3DVECTOR, _
    QScaleRotation As D3DQUATERNION, _
    VScale As D3DVECTOR, _
    VRotationCenter As D3DVECTOR, _
    QRotation As D3DQUATERNION, _
    VTranslation As D3DVECTOR)

Parameters

MOut
D3DMATRIX type that is the result of the operation, the transformation matrix.
VScaleCenter
D3DVECTOR type, identifying the scaling center point. If this argument is an empty D3DVECTOR type, it is treated as identity.
QScaleRotation
D3DQUATERNION type that specifies the scaling rotation If this argument is an empty D3DQUATERNION type, it is treated as identity.
VScale
D3DVECTOR type, the scaling vector. If this argument is an empty D3DVECTOR type, it is treated as identity.
VRotationCenter
D3DVECTOR type, a point that identifies the center of rotation. If this argument is an empty D3DVECTOR type, it is treated as identity.
QRotation
D3DQUATERNION type that specifies the rotation. If this argument is an empty D3DQUATERNION type, it is treated as identity.
VTranslation
D3DVECTOR type, representing the translation. If this argument is an empty D3DVECTOR type, it is treated as identity.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DXMatrixTransformation function calculates the transformation matrix with the following formula: Msc-1 * Msr-1 * Ms * Msr * Msc * Mrc-1 * Mr * Mrc * Mt, where Msc is the center scaling matrix, Msr is the scaling rotation matrix, Ms is the scaling matrix, Mrc is the center of rotation matrix, Mr is the rotation matrix, and Mt is the translation matrix.

See Also

D3DXMatrixAffineTransformation


D3DXMatrixTranslation

Builds a matrix using the specified offsets.

D3DXMatrixTranslation( _
    MOut As D3DMATRIX, _
    x As Single, _
    y As Single, _
    z As Single)

Parameters

MOut
D3DMATRIX type that is the result of the operation, the translated matrix.
x
X-coordinate offset.
y
Y-coordinate offset.
z
Z-coordinate offset.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXMatrixTranspose

Returns the matrix transpose of a matrix.

D3DXMatrixTranspose( _
    MOut As D3DMATRIX, _
    M As D3DMATRIX)

Parameters

MOut
D3DMATRIX type that is the result of the operation, the matrix transpose of the matrix.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXPlaneDot

Computes the dot-product of a plane and a 4-D vector.

D3DXPlaneDot( _
    P1 As D3DPLANE, _
    P2 As D3DPLANE) As Single

Parameters

P1
A source D3DPLANE type.
P2
A source D3DPLANE type.

Return Values

The dot-product of the plane and 4-D vector.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Given a plane (a, b, c, d) and a 4-D 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.

See Also

D3DXPlaneDotCoord, D3DXPlaneDotNormal


D3DXPlaneDotCoord

Computes the dot-product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 1.

D3DXPlaneDotCoord( _
    P1 As D3DPLANE, _
    V As D3DVECTOR) As Single

Parameters

P1
A source D3DPLANE type.
V
A source D3DVECTOR type.

Return Values

The dot-product of the plane and 3-D vector.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Given a plane (a, b, c, d) and a 3-D 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 3-D space.

See Also

D3DXPlaneDot, D3DXPlaneDotNormal


D3DXPlaneDotNormal

Computes the dot-product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 0.

D3DXPlaneDotNormal( _
    P1 As D3DPLANE, _
    V As D3DVECTOR) As Single

Parameters

P1
A source D3DPLANE type.
V
A source D3DVECTOR type.

Return Values

The dot-product of the plane and 3-D vector.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Given a plane (a, b, c, d) and a 3-D 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 figuring out the angle between the normal of the plane, and another normal.

See Also

D3DXPlaneDot, D3DXPlaneDotCoord


D3DXPlaneFromPointNormal

Constructs a plane from a point and a normal.

D3DXPlaneFromPointNormal( _
    POut As D3DPLANE, _
    VPoint As D3DVECTOR, _
    vNormal As D3DVECTOR)

Parameters

POut
D3DPLANE type that is the result of the operation, a plane constructed from the point and the normal.
VPoint
D3DVECTOR type, defining the point used to construct the plane.
vNormal
D3DVECTOR type, defining the normal used to construct the plane.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXPlaneFromPoints


D3DXPlaneFromPoints

Constructs a plane from three points.

D3DXPlaneFromPoints( _
    POut As D3DPLANE, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR, _
    V3 As D3DVECTOR)

Parameters

POut
D3DPLANE type that is the result of the operation, a plane constructed from the given points.
V1
D3DVECTOR type, defining one of the points used to construct the plane.
V2
D3DVECTOR type, defining one of the points used to construct the plane.
V3
D3DVECTOR type, defining one of the points used to construct the plane.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXPlaneFromPointNormal


D3DXPlaneIntersectLine

Finds the intersection between a plane and a line.

D3DXPlaneIntersectLine( _
    POut As D3DPLANE, _
    P As D3DPLANE, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR)

Parameters

POut
D3DPLANE type that is the result of the operation, identifying the intersection between the specified plane and line.
P
The source D3DPLANE type.
V1
A source D3DVECTOR type, defining a line starting point.
V2
A source D3DVECTOR type, defining a line ending point.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If the line is parallel to the plane, an empty D3DPLANE type is returned.


D3DXPlaneNormalize

Returns the normal of a plane.

D3DXPlaneNormalize( _
    POut As D3DPLANE, _
    P As D3DPLANE)

Parameters

POut
D3DPLANE type that is the result of the operation, the normal of the plane.
P
The source D3DPLANE type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

D3DXPlaneNormalize normalizes a plane so that |a,b,c| == 1.


D3DXPlaneTransform

Transforms a plane by a given matrix.

D3DXPlaneTransform( _
    POut As D3DPLANE, _
    P As D3DPLANE, _
    M As D3DMATRIX)

Parameters

POut
D3DPLANE type that is the result of the operation, the transformed plane.
P
The source D3DPLANE type.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The matrix, M, must be an affine transform.


D3DXQuaternionBaryCentric

Returns a quaternion in Barycentric coordinates.

D3DXQuaternionBaryCentric( _
    QOut As D3DQUATERNION, _
    Q1 As D3DQUATERNION, _
    Q2 As D3DQUATERNION, _
    Q3 As D3DQUATERNION, _
    f As Single, _
    g As Single)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, a quaternion in Barycentric coordinates.
Q1
A source D3DQUATERNION type.
Q2
A source D3DQUATERNION type.
Q3
A source D3DQUATERNION type.
f
Weighting factor. See Remarks.
g
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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))


D3DXQuaternionConjugate

Returns the conjugate of a quaternion.

D3DXQuaternionConjugate( _
    QOut As D3DQUATERNION, _
    Q As D3DQUATERNION)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, the conjugate of the quaternion.
Q
The source D3DQUATERNION type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionConjugate function will return the quaternion (-x, -y, -z, w).

See Also

D3DXQuaternionInverse


D3DXQuaternionDot

Returns the conjugate of a quaternion.

D3DXQuaternionDot( _
    Q1 As D3DQUATERNION, _
    Q2 As D3DQUATERNION)

Parameters

Q1
A source D3DQUATERNION type.
Q2
A source D3DQUATERNION type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXQuaternionExp

Calculates the exponential.

D3DXQuaternionExp( _
    QOut As D3DQUATERNION, _
    Q As D3DQUATERNION)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, the exponential.
Q
The source D3DQUATERNION type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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)

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.

See Also

D3DXQuaternionLn, D3DXQuaternionSquad


D3DXQuaternionIdentity

Returns the identity quaternion.

D3DXQuaternionIdentity( _
    QOut As D3DQUATERNION)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, the identity quaternion.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionIdentity function will return the quaternion (0, 0, 0, 1).

See Also

D3DXQuaternionIsIdentity


D3DXQuaternionInverse

Conjugates and renormalizes a quaternion.

D3DXQuaternionInverse( _
    QOut As D3DQUATERNION, _
    Q As D3DQUATERNION)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, the inverse quaternion of the quaternion.
Q
The source D3DQUATERNION type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

For a unit quaternion, Q == (cos(theta), sin(theta) * v)
The inverse of Q is, Inv(Q) = Conjugate(Q)/LengthSq(Q)

See Also

D3DXQuaternionConjugate, D3DXQuaternionNormalize


D3DXQuaternionIsIdentity

Determines if a quaternion is an identity quaternion.

D3DXQuaternionIsIdentity( _
    Q As D3DQUATERNION) As Long

Parameters

Q
D3DQUATERNION type that will be tested for identity.

Return Values

If the quaternion is an identity quaternion, this function returns a nonzero value (True); otherwise, this function returns zero (False).

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXQuaternionIdentity


D3DXQuaternionLength

Returns the length of a quaternion.

D3DXQuaternionLength( _
    Q As D3DQUATERNION) As Single

Parameters

Q
The source D3DQUATERNION type.

Return Values

The quaternion's length.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXQuaternionLengthSq


D3DXQuaternionLengthSq

Returns the square of the length of a quaternion.

D3DXQuaternionLengthSq( _
    Q As D3DQUATERNION) As Single

Parameters

Q
The source D3DQUATERNION type.

Return Values

The quaternion's squared length.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXQuaternionLength


D3DXQuaternionLn

Calculates the natural logarithm.

D3DXQuaternionLn( _
    QOut As D3DQUATERNION, _
    Q As D3DQUATERNION)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, the natural logarithm.
Q
The source D3DQUATERNION type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function works only for unit quaternions.

For a unit quaternion, Q == (cos(theta), sin(theta) * v)
The natural logarithm of Q is, ln(Q) = (0, theta * v)

The D3DXQuaternionSquadSetup method can also be used to set up the control points of a quaternion.

See Also

D3DXQuaternionExp, D3DXQuaternionSquad


D3DXQuaternionMultiply

Multiplies two quaternions.

D3DXQuaternionMultiply( _
    QOut As D3DQUATERNION, _
    Q1 As D3DQUATERNION, _
    Q2 As D3DQUATERNION)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, the product of two quaternions.
Q1
A source D3DQUATERNION type.
Q2
A source D3DQUATERNION type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The result represents the rotation Q2 followed by the rotation Q1 (Out = Q2 * Q1). The output is actually Q2*Q1 (not 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.

See Also

D3DXMatrixMultiply


D3DXQuaternionNormalize

Returns the normal of a quaternion.

D3DXQuaternionNormalize( _
    QOut As D3DQUATERNION, _
    Q As D3DQUATERNION)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, the normal of the quaternion.
Q
The source D3DQUATERNION type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXQuaternionInverse


D3DXQuaternionRotationAxis

Rotates a quaternion about an arbitrary axis.

D3DXQuaternionRotationAxis( _
    QOut As D3DQUATERNION, _
    VAxis As D3DVECTOR, _
    angle As Single)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, a quaternion rotated around the specified axis.
VAxis
D3DVECTOR type that identifies the axis angle.
angle
Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXQuaternionRotationMatrix, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationMatrix

Builds a quaternion from a rotation matrix.

D3DXQuaternionRotationMatrix( _
    QOut As D3DQUATERNION, _
    M As D3DMATRIX)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, a quaternion built from a rotation matrix.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationYawPitchRoll

Builds a quaternion with the given yaw, pitch, and roll.

D3DXQuaternionRotationYawPitchRoll( _
    QOut As D3DQUATERNION, _
    yaw As Single, _
    pitch As Single, _
    roll As Single)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, a quaternion with the specified yaw, pitch, and roll.
yaw
Yaw around the y-axis, in radians.
pitch
Pitch around the x-axis, in radians.
roll
Roll around the z-axis, in radians.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationMatrix


D3DXQuaternionSlerp

Interpolates between two quaternions, using spherical linear interpolation.

D3DXQuaternionSlerp( _
    QOut As D3DQUATERNION, _
    Q1 As D3DQUATERNION, _
    Q2 As D3DQUATERNION, _
    t As Single)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, the result of the interpolation.
Q1
A source D3DQUATERNION type.
Q2
A source D3DQUATERNION type.
t
Parameter that indicates how far to interpolate between the quaternions.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXQuaternionSquad

Interpolates between quaternions, using spherical quadrangle interpolation.

D3DXQuaternionSquad( _
    QOut As D3DQUATERNION, _
    Q1 As D3DQUATERNION, _
    Q2 As D3DQUATERNION, _
    Q3 As D3DQUATERNION, _
    Q4 As D3DQUATERNION, _
    t As Single)

Parameters

QOut
D3DQUATERNION type that is the result of the operation, the result of the spherical quadrangle interpolation.
Q1
A source D3DQUATERNION type.
Q2
A source D3DQUATERNION type.
Q3
A source D3DQUATERNION type.
Q4
A source D3DQUATERNION type.
t
Parameter that indicates how far to interpolate between the quaternions.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function uses the following sequence of spherical linear interpolation operations: Slerp(Slerp(Q1, Q4, t), Slerp(Q2, Q3, 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.

See Also

D3DXQuaternionExp, D3DXQuaternionLn


D3DXQuaternionToAxisAngle

Computes a quaternion's axis and angle of rotation.

D3DXQuaternionToAxisAngle( _
    Q As D3DQUATERNION, _
    VAxis As D3DVECTOR, _
    angle As Single) As Long

Parameters

Q
The source D3DQUATERNION type.
VAxis
When this function returns, a D3DVECTOR type that identifies the quaternion's axis.
angle
When this function returns, a Single value that identifies the quaternion's angle of rotation, in radians.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function expects unit quaternions.


D3DXVec2Add

Adds two 2-D vectors.

D3DXVec2Add( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    V2 As D3DVECTOR2)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, the sum of the two vectors.
V1
A source D3DVECTOR2 type.
V2
A source D3DVECTOR2 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec2Subtract, D3DXVec2Scale


D3DXVec2BaryCentric

Returns a point in Barycentric coordinates, using the specified 2-D vectors.

D3DXVec2BaryCentric( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    V2 As D3DVECTOR2, _
    V3 As D3DVECTOR2, _
    f As Single, _
    g As Single)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, a vector in Barycentric coordinates
V1
A source D3DVECTOR2 type.
V2
A source D3DVECTOR2 type.
V3
A source D3DVECTOR2 type.
f
Weighting factor. See Remarks.
g
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 And g>=0 And 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 And g>=0 And 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 And g==0 And 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 And g>=0 And 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 simply represents a change in coordinate systems; what holds true for Cartesian coordinates holds true for Barycentric coordinates.


D3DXVec2CatmullRom

Performs a Catmull-Rom interpolation, using the specified 2-D vectors.

D3DXVec2CatmullRom( _
    VOut As D3DVECTOR2, _
    V0 As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    V2 As D3DVECTOR2, _
    V3 As D3DVECTOR2, _
    s As Single)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation.
V0
D3DVECTOR2 type, a position vector.
V1
D3DVECTOR2 type, a position vector.
V2
D3DVECTOR2 type, a position vector.
V3
D3DVECTOR2 type, a position vector.
s
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DXVec2CatmullRom function interpolates between the position V1 when s is equal to 0, and between the position V2 when s is equal to 1, using Catmull-Rom interpolation.


D3DXVec2CCW

Returns the z-component by taking the cross product of two 2-D vectors.

D3DXVec2CCW( _
    V1 As D3DVECTOR2, _
    V2 As D3DVECTOR2) As Single

Parameters

V1
A source D3DVECTOR2 type.
V2
A source D3DVECTOR2 type.

Return Values

The z-component.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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.

V1.x * V2.y - V1.y * V2.x

If the value of the z-component is positive, the vector V2 is counter-clockwise from the vector V1. This information is useful for back-face culling.

See Also

D3DXVec2Dot


D3DXVec2Dot

Determines the dot-product of two 2-D vectors.

D3DXVec2Dot( _
    V1 As D3DVECTOR2, _
    V2 As D3DVECTOR2) As Single

Parameters

V1
A source D3DVECTOR2 type.
V2
A source D3DVECTOR2 type.

Return Values

The dot-product.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec2CCW


D3DXVec2Hermite

Performs a Hermite spline interpolation, using the specified 2-D vectors.

D3DXVec2Hermite( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    T1 As D3DVECTOR2, _
    V2 As D3DVECTOR2, _
    T2 As D3DVECTOR2, _
    s As Single)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, the Hermite spline interpolation.
V1
A source D3DVECTOR2 type, a position vector.
T1
A source D3DVECTOR2 type, a tangent vector.
V2
A source D3DVECTOR2 type, a position vector.
T2
A source D3DVECTOR2 type, a tangent vector.
s
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DXVec2Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation. This function interpolates between the position V1 and the tangent T1, when s is equal to 0, and between the position V2 and the tangent T2, when s is equal to 1.

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.


D3DXVec2Length

Returns the length of a 2-D vector.

D3DXVec2Length( _
    v As D3DVECTOR2) As Single

Parameters

v
The source D3DVECTOR2 type.

Return Values

The vector's length.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec2LengthSq


D3DXVec2LengthSq

Returns the square of the length of a 2-D vector.

D3DXVec2LengthSq( _
    v As D3DVECTOR2) As Single

Parameters

v
The source D3DVECTOR2 type.

Return Values

The vector's squared length.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec2Length


D3DXVec2Lerp

Performs a linear interpolation between two 2-D vectors.

D3DXVec2Lerp( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    V2 As D3DVECTOR2, _
    s As Single)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, the linear interpolation.
V1
A source D3DVECTOR2 type.
V2
A source D3DVECTOR2 type.
s
Parameter that linearly interpolates between the vectors.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXVec2Maximize

Returns a 2-D vector that is made up of the largest components of two 2-D vectors.

D3DXVec2Maximize( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    V2 As D3DVECTOR2)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, a vector made up of the largest components of the two vectors.
V1
A source D3DVECTOR2 type.
V2
A source D3DVECTOR2 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec2Minimize


D3DXVec2Minimize

Returns a 2-D vector that is made up of the smallest components of two 2-D vectors.

D3DXVec2Minimize( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    V2 As D3DVECTOR2)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, a vector made up of the smallest components of the two vectors.
V1
A source D3DVECTOR2 type.
V2
A source D3DVECTOR2 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec2Maximize


D3DXVec2Normalize

Returns the normalized version of a 2-D vector.

D3DXVec2Normalize( _
    VOut As D3DVECTOR2, _
    v As D3DVECTOR2)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, the normalized version of the vector.
v
The source D3DVECTOR2 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXVec2Scale

Scales a 2-D vector.

D3DXVec2Scale( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    s As Single)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, the scaled vector.
V1
The source D3DVECTOR2 type.
s
Scaling value.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec2Add, D3DXVec2Subtract


D3DXVec2Subtract

Subtracts two 2-D vectors.

D3DXVec2Subtract( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    V2 As D3DVECTOR2)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, the difference of two vectors.
V1
A source D3DVECTOR2 type.
V2
A source D3DVECTOR2 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec2Add, D3DXVec2Scale


D3DXVec2Transform

Transforms a 2-D vector by a given matrix.

D3DXVec2Transform( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR2, _
    M As D3DMATRIX)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the transformed vector.
V1
The source D3DVECTOR2 type.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function transform the vector, V1 (x, y, 0, 1), by the matrix, M.

See Also

D3DXVec2TransformCoord, D3DXVec2TransformNormal


D3DXVec2TransformCoord

Transforms a 2-D vector by a given matrix, projecting the result back into w = 1.

D3DXVec2TransformCoord( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    M As D3DMATRIX)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, the transformed vector.
V1
The source D3DVECTOR2 type.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function transform the vector, V1 (x, y, 0, 1), by the matrix, M, projecting the result back into w=1.

See Also

D3DXVec2Transform, D3DXVec2TransformNormal


D3DXVec2TransformNormal

Transforms the 2-D vector normal by the given matrix.

D3DXVec2TransformNormal( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    M As D3DMATRIX)

Parameters

VOut
D3DVECTOR2 type that is the result of the operation, the transformed vector.
V1
The source D3DVECTOR2 type.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function transforms the vector normal (x, y, 0, 0) of the vector, V1, by the matrix, M.

See Also

D3DXVec2Transform, D3DXVec2TransformCoord


D3DXVec3Add

Adds two 3-D vectors.

D3DXVec3Add( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the sum of the two 3-D vectors.
V1
A source D3DVECTOR type.
V2
A source D3DVECTOR type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Subtract, D3DXVec3Scale


D3DXVec3BaryCentric

Returns a point in Barycentric coordinates, using the specified 3-D vectors.

D3DXVec3BaryCentric( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR, _
    V3 As D3DVECTOR, _
    f As Single, _
    g As Single)

Parameters

VOut
D3DVECTOR type that is the result of the operation, a vector in Barycentric coordinates.
V1
A source D3DVECTOR type.
V2
A source D3DVECTOR type.
V3
A source D3DVECTOR type.
f
Weighting factor. See Remarks.
g
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 And g>=0 And 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 And g>=0 And 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 And g==0 And 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 And g>=0 And 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 simply represents a change in coordinate systems; what holds true for Cartesian coordinates holds true for Barycentric coordinates.


D3DXVec3CatmullRom

Performs a Catmull-Rom interpolation, using the specified 3-D vectors.

D3DXVec3CatmullRom( _
    VOut As D3DVECTOR, _
    V0 As D3DVECTOR, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR, _
    V3 As D3DVECTOR, _
    s As Single)

Parameters

VOut
D3DVECTOR type that is the result of the operation.
V0
D3DVECTOR type, a position vector.
V1
D3DVECTOR type, a position vector.
V2
D3DVECTOR type, a position vector.
V3
D3DVECTOR type, a position vector.
s
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DXVec3CatmullRom function interpolates between the position V1 when s is equal to 0, and between the position V2 when s is equal to 1, using Catmull-Rom interpolation.


D3DXVec3Cross

Determines the cross-product of two 3-D vectors.

D3DXVec3Cross( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the cross product of two 3-D vectors.
V1
A source D3DVECTOR type.
V2
A source D3DVECTOR type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function determines the cross-product with the following code.

Dim VOut As D3DVECTOR

VOut.x = V1.y * V2.z - V1.z * V2.y
VOut.y = V1.z * V2.x - V1.x * V2.z
VOut.z = V1.x * V2.y - V1.y * V2.x

See Also

D3DXVec3Dot


D3DXVec3Dot

Determines the dot-product of two 3-D vectors.

D3DXVec3Dot( _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR) As Single

Parameters

V1
A source D3DVECTOR type.
V2
A source D3DVECTOR type.

Return Values

The dot-product.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Cross


D3DXVec3Hermite

Performs a Hermite spline interpolation, using the specified 3-D vectors.

D3DXVec3Hermite( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    T1 As D3DVECTOR, _
    V2 As D3DVECTOR, _
    T2 As D3DVECTOR, _
    s As Single)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the Hermite spline interpolation.
V1
A source D3DVECTOR type, a position vector.
T1
A source D3DVECTOR type, a tangent vector.
V2
A source D3DVECTOR type, a position vector.
T2
A source D3DVECTOR type, a tangent vector.
s
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DXVec3Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation. This function interpolates between the position V1 and the tangent T1, when s is equal to zero, and between the position V2 and the tangent T2, when s is equal to one.

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.


D3DXVec3Length

Returns the length of a 3-D vector.

D3DXVec3Length( _
    v As D3DVECTOR) As Single

Parameters

v
The source D3DVECTOR type.

Return Values

The vector's length.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3LengthSq


D3DXVec3LengthSq

Returns the square of the length of a 3-D vector.

D3DXVec3LengthSq( _
    v As D3DVECTOR) As Single

Parameters

v
The source D3DVECTOR type.

Return Values

The vector's squared length.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Length


D3DXVec3Lerp

Performs a linear interpolation between two 3-D vectors.

D3DXVec3Lerp( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR, _
    s As Single)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the linear interpolation.
V1
A source D3DVECTOR type.
V2
A source D3DVECTOR type.
s
Parameter that linearly interpolates between the vectors.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).


D3DXVec3Maximize

Returns a 3-D vector that is made up of the largest components of two 3-D vectors.

D3DXVec3Maximize( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR)

Parameters

VOut
D3DVECTOR type that is the result of the operation, a vector made up of the largest components of the two vectors.
V1
A source D3DVECTOR type.
V2
A source D3DVECTOR type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Minimize


D3DXVec3Minimize

Returns a 3-D vector that is made up of the smallest components of two 3-D vectors.

D3DXVec3Minimize( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR)

Parameters

VOut
D3DVECTOR type that is the result of the operation, a vector made up of the smallest components of the two vectors.
V1
A source D3DVECTOR type.
V2
A source D3DVECTOR type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Maximize


D3DXVec3Normalize

Returns the normalized version of a 3-D vector.

D3DXVec3Normalize( _
    VOut As D3DVECTOR, _
    v As D3DVECTOR)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the normalized version of the specified vector.
v
The source D3DVECTOR type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXVec3Project

Projects a vector from object space into screen space.

D3DXVec3Project( _
    VOut As D3DVECTOR, _
    V As D3DVECTOR, _
    Viewport As D3DVIEWPORT8, _
    Projection As D3DMATRIX, _
    View As D3DMATRIX, _
    World As D3DMATRIX)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the vector projected from object space to screen space.
V
The source D3DVECTOR type.
Viewport
D3DVIEWPORT8 type, representing the viewport.
Projection
D3DMATRIX type, representing the projection matrix.
View
D3DMATRIX type, representing the view matrix.
World
D3DMATRIX type, representing the world matrix.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Unproject


D3DXVec3Scale

Scales a 3-D vector.

D3DXVec3Scale( _
    VOut As D3DVECTOR2, _
    V1 As D3DVECTOR2, _
    s As Single)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the scaled vector.
V1
A source D3DVECTOR type.
s
Scaling value.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Add, D3DXVec3Subtract


D3DXVec3Subtract

Subtracts two 3-D vectors.

D3DXVec3Subtract( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    V2 As D3DVECTOR)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the difference of two vectors.
V1
A source D3DVECTOR type.
V2
A source D3DVECTOR type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec3Transform

Transforms a 3-D vector by a given matrix.

D3DXVec3Transform( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR, _
    M As D3DMATRIX)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the transformed vector.
V1
The source D3DVECTOR type.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function transform the vector, V1 (x, y, z, 1), by the matrix, M.

See Also

D3DXVec3TransformCoord, D3DXVec3TransformNormal


D3DXVec3TransformCoord

Transforms a 3-D vector by a given matrix, projecting the result back into w = 1.

D3DXVec3TransformCoord( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    M As D3DMATRIX)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the transformed vector.
V1
The source D3DVECTOR type.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function transform the vector, V1 (x, y, z, 1), by the matrix, M, projecting the result back into w=1.

See Also

D3DXVec3Transform, D3DXVec3TransformNormal


D3DXVec3TransformNormal

Transforms the 3-D vector normal by the given matrix.

D3DXVec3TransformNormal( _
    VOut As D3DVECTOR, _
    V1 As D3DVECTOR, _
    M As D3DMATRIX)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the transformed vector.
V1
The source D3DVECTOR type.
M
The source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function transforms the vector normal (x, y, z, 0) of the vector, V1, by the matrix, M.

If you transform a normal by a nonaffine matrix, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a coordinate.


D3DXVec3Unproject

Projects a vector from screen space into object space.

D3DXVec3Unproject( _
    VOut As D3DVECTOR, _
    V As D3DVECTOR, _
    Viewport As D3DVIEWPORT8, _
    Projection As D3DMATRIX, _
    View As D3DMATRIX, _
    World As D3DMATRIX)

Parameters

VOut
D3DVECTOR type that is the result of the operation, the vector projected from screen space to object space.
V
The source D3DVECTOR type.
Viewport
D3DVIEWPORT8 type, representing the viewport.
Projection
D3DMATRIX type, representing the projection matrix.
View
D3DMATRIX type, representing the view matrix.
World
D3DMATRIX type, representing the world matrix.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Project


D3DXVec4Add

Adds two 4-D vectors.

D3DXVec4Add( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    V2 As D3DVECTOR4)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the sum of the two vectors.
V1
A source D3DVECTOR4 type.
V2
A source D3DVECTOR4 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec4Subtract, D3DXVec4Scale


D3DXVec4BaryCentric

Returns a point in Barycentric coordinates, using the specified 4-D vectors.

D3DXVec4BaryCentric( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    V2 As D3DVECTOR4, _
    V3 As D3DVECTOR4, _
    f As Single, _
    g As Single)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, a vector in Barycentric coordinates.
V1
A source D3DVECTOR4 type.
V2
A source D3DVECTOR4 type.
V3
A source D3DVECTOR4 type.
f
Weighting factor. See Remarks.
g
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

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 And g>=0 And 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 And g>=0 And 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 And g==0 And 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 And g>=0 And 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 simply represents a change in coordinate systems; what holds true for Cartesian coordinates holds true for Barycentric coordinates.


D3DXVec4CatmullRom

Performs a Catmull-Rom interpolation, using the specified 4-D vectors.

D3DXVec4CatmullRom( _
    VOut As D3DVECTOR4, _
    V0 As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    V2 As D3DVECTOR4, _
    V3 As D3DVECTOR4, _
    s As Single)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation.
V0
D3DVECTOR4 type, a position vector.
V1
D3DVECTOR4 type, a position vector.
V2
D3DVECTOR4 type, a position vector.
V3
D3DVECTOR4 type, a position vector.
s
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DXVec4CatmullRom function interpolates between the position V1 when s is equal to 0, and between the position V2 when s is equal to 1, using Catmull-Rom interpolation.


D3DXVec4Cross

Determines the cross-product in 4 dimensions.

D3DXVec4Cross( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    V2 As D3DVECTOR4, _
    V3 As D3DVECTOR4)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the cross product.
V1
A source D3DVECTOR4 type.
V2
A source D3DVECTOR4 type.
V3
A source D3DVECTOR4 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec4Dot


D3DXVec4Dot

Determines the dot-product of two 4-D vectors.

D3DXVec4Dot( _
    V1 As D3DVECTOR4, _
    V2 As D3DVECTOR4) As Single

Parameters

V1
A source D3DVECTOR4 type.
V2
A source D3DVECTOR4 type.

Return Values

The dot-product.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec4Cross


D3DXVec4Hermite

Performs a Hermite spline interpolation, using the specified 4-D vectors.

D3DXVec4Hermite( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR, _
    T1 As D3DVECTOR, _
    V2 As D3DVECTOR, _
    T2 As D3DVECTOR, _
    s As Single)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the Hermite spline interpolation.
V1
A source D3DVECTOR type, a position vector.
T1
A source D3DVECTOR4 type, a tangent vector.
V2
A source D3DVECTOR type, a position vector.
T2
A source D3DVECTOR4 type, a tangent vector.
s
Weighting factor. See Remarks.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

The D3DXVec4Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation. This function interpolates between the position V1 and the tangent T1, when s is equal to zero, and between the position V2 and the tangent T2, when s is equal to one.

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.


D3DXVec4Length

Returns the length of a 4-D vector.

D3DXVec4Length( _
    v As D3DVECTOR4) As Single

Parameters

v
A source D3DVECTOR4 type.

Return Values

The vector's length.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec4LengthSq


D3DXVec4LengthSq

Returns the square of the length of a 4-D vector.

D3DXVec4LengthSq( _
    v As D3DVECTOR4) As Single

Parameters

v
A source D3DVECTOR4 type.

Return Values

The vector's squared length.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec4Length


D3DXVec4Lerp

Performs a linear interpolation between two 4-D vectors.

D3DXVec4Lerp( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    V2 As D3DVECTOR4, _
    s As Single)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the linear interpolation.
V1
A source D3DVECTOR4 type.
V2
A source D3DVECTOR4 type.
s
Parameter that linearly interpolates between the vectors.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).


D3DXVec4Maximize

Returns a 4-D vector that is made up of the largest components of two 4-D vectors.

D3DXVec4Maximize( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    V2 As D3DVECTOR4)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, a vector made up of the largest components of the two vectors.
V1
A source D3DVECTOR4 type.
V2
A source D3DVECTOR4 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec4Minimize


D3DXVec4Minimize

Returns a 4-D vector that is made up of the smallest components of two 4-D vectors.

D3DXVec4Minimize( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    V2 As D3DVECTOR4)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, a vector made up of the smallest components of the two vectors.
V1
A source D3DVECTOR4 type.
V2
A source D3DVECTOR4 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec4Maximize


D3DXVec4Normalize

Returns the normalized version of a 4-D vector.

D3DXVec4Normalize( _
    VOut As D3DVECTOR4, _
    v As D3DVECTOR4)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the normalized version of the vector.
v
The source D3DVECTOR4 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


D3DXVec4Scale

Scales a 4-D vector.

D3DXVec4Scale( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    s As Single)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the scaled vector.
V1
The source D3DVECTOR4 type.
s
Scaling value.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec4Add, D3DXVec4Subtract


D3DXVec4Subtract

Subtracts two 4-D vectors.

D3DXVec4Subtract( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    V2 As D3DVECTOR4)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the difference of two vectors.
V1
A source D3DVECTOR4 type.
V2
A source D3DVECTOR4 type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec4Transform

Transforms a 4-D vector by a given matrix.

D3DXVec4Transform( _
    VOut As D3DVECTOR4, _
    V1 As D3DVECTOR4, _
    M As D3DMATRIX)

Parameters

VOut
D3DVECTOR4 type that is the result of the operation, the transformed 4-D vector.
V1
A source D3DVECTOR4 type.
M
A source D3DMATRIX type.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


Types

This section contains information about the types included with the Direct3DX utility library.

  • D3DXATTRIBUTERANGE
  • D3DXATTRIBUTEWEIGHTS
  • D3DXBONECOMBINATION
  • D3DXDECLARATOR
  • D3DXIMAGE_INFO
  • D3DXMATERIAL
  • D3DXRTS_DESC


D3DXATTRIBUTERANGE

Stores an attribute table entry.

Type D3DXATTRIBUTERANGE
    AttribId As Long
    FaceCount As Long
    FaceStart As Long
    VertexCount As Long
    VertexStart As Long
End Type

Members

AttribId
Attribute table identifier.
FaceCount
Face count.
FaceStart
Starting face.
VertexCount
Vertex count.
VertexStart
Starting vertex.

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.

See Also

D3DXBaseMesh.DrawSubset


D3DXATTRIBUTEWEIGHTS

Specifies how to weigh vertex components.

Type D3DXATTRIBUTEWEIGHTS
    Boundary As Single
    diffuse As Single
    Normal As Single
    position As Single
    specular As Single
    Tex(0 To 7) As Single
End Type

Members

Boundary
Boundary component weight.
diffuse
Diffuse component weight.
Normal
Normal component weight.
position
Position component weight.
specular
Specular component weight.
Tex
Texture coordinate weights.

Remarks

This type 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, then the simplification operation will ignore the vertex normal component when calculating the error for the collapse. However, if the Normal field is 1.0, then the simplification operation will use the vertex normal component. if the Normal field is 2.0, then double the amount of errors; if the Normal field is 4.0, then quadruple the number of errors, and so on.

See Also

D3DX8.CreateSPMesh , D3DX8.GeneratePMesh, D3DX8.SimplifyMesh


D3DXBONECOMBINATION

Describes a subset of the mesh that has the same attribute and bone combination.

Type D3DXBONECOMBINATION
    AttribId As Long
    FaceCount As Long
    FaceStart As Long
    VertexCount As Long
    VertexStart As Long
End Type

Members

AttribId
Attribute table identifier.
FaceCount
Face count.
FaceStart
Starting face.
VertexCount
Vertex count.
VertexStart
Starting vertex.

Remarks

The subset of the mesh described by D3DXBONECOMBINATION can be rendered in a single drawing call.


D3DXDECLARATOR

Stores a declarator array.

Type D3DXDECLARATOR
    value(0 To 31) As Long
End Type

Members

value
A declarator array, describing the vertex format of vertices

See Also

D3DX8.DeclaratorFromFVF, D3DX8.FVFFromDeclarator


D3DXIMAGE_INFO

Use to return a description of what the original contents of an image file looked like.

Type D3DXIMAGE_INFO
    Depth As Long
    Height As Long
    MipLevels As Long
    Width As Long
    Format As Long
End Type

Members

Depth
Width of original image in pixels.
Height
Height of original image in pixels.
MipLevels
Depth of original image in pixels
Width
Number of mip levels in original image.
Format
A value from the CONST_D3DFORMAT enumerated type that most closely describes the data in the original image.

See Also

D3DX8.DeclaratorFromFVF, D3DX8.FVFFromDeclarator


D3DXMATERIAL

Returns material information saved in Microsoft® DirectX® X files.

Type D3DXMATERIAL
    Material As D3DMATERIAL8
    TextureFilename As String
End Type

Members

Material
D3DMATERIAL8 type that describes the material properties.
TextureFilename
String that specifies the file name of the texture.

Remarks

The D3DX8.LoadMeshFromX and D3DX8.LoadMeshFromXof methods return an array of D3DXMATERIAL types 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.

See Also

D3DX8.LoadMeshFromX, D3DX8.LoadMeshFromXof


D3DXRTS_DESC

Describes a render surface.

Type D3DXRTS_DESC
    Width As Long
    Height As Long
    format As Long
    DepthStencil As Long
    DepthStencilFormat As Long
End Type

Members

Width
Width of the render surface, in pixels
Height
Height of the render surface, in pixels.
format
Member of the CONST_D3DFORMAT enumerated type, describing the pixel format of the render surface.
DepthStencil
If 1, the render surface supports a depth-stencil surface; otherwise this member is set to 0.
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

D3DXRenderToSurface.GetDesc


Enumerations

This section contains information about the enumerations included with the Direct3DX utility library.

  • CONST_D3DXASM
  • CONST_D3DXENUM
  • CONST_D3DXERR
  • CONST_D3DXMESH
  • CONST_D3DXMESHMISC
  • CONST_D3DXMESHOPT
  • CONST_D3DXMESHSIMP
  • CONST_DTFLAGS


CONST_D3DXASM

Defines shader assembly flags.

Enum CONST_D3DXMESHMISC
    D3DXASM_DEBUG          = 1
    D3DXASM_SKIPVALIDATION = 2
End Enum

Constants

D3DXASM_DEBUG
Inserts debugging information as comments in the assembled shader.
D3DXASM_SKIPVALIDATION
Do not validate the generated code against known capabilities and constraints. This option is only recommended when assembling a shader you know will work (that is, the shader has been assembled before without this option.)

See Also

D3DX8.AssembleShader, D3DX8.AssembleShaderFromFile


CONST_D3DXENUM

Defines miscellaneous Direct3DX flags, including image filters.

Enum CONST_D3DXENUM
    D3DX_FILTER_NONE     =      0
    D3DX_FILTER_POINT    =      1
    D3DX_FILTER_LINEAR   =      2
    D3DX_FILTER_TRIANGLE =      3
    D3DX_FILTER_BOX      =      4
    D3DX_FILTER_MIRROR_U =  65536 (&H10000)
    D3DX_FILTER_MIRROR_V = 131072 (&H20000)
    D3DX_FILTER_MIRROR   = 196608 (&H30000)
    D3DX_FILTER_DITHER   = 524288 (&H80000)
    D3DX_DEFAULT         =     -1 (&HFFFFFFFF)
End Enum

Constants

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 linearly interpolating between the nearest pixels in the source image. This filter works best when the scale on each axis is less than 2.
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 2×2(×2) 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
Indicates that the pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Indicates that the pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying both the D3DX_FILTER_MIRROR_U and D3DX_FILTER_MIRROR_V flags.
D3DX_FILTER_DITHER
Dither the resulting image using a 4x4 ordered dither algorithm.D3DX_DEFAULT
Predefined value that can be used for a parameter that is an enumerated value or a handle. The documentation indicates wherever D3DX_DEFAULT may be used, and how it will be interpreted in each situation.

Remarks

Each valid filter must contain exactly one of the following flags.

  • D3DX_FILTER_BOX
  • D3DX_FILTER_LINEAR
  • D3DX_FILTER_NONE
  • D3DX_FILTER_POINT
  • D3DX_FILTER_TRIANGLE

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
  • D3DX_FILTER_MIRROR_U
  • D3DX_FILTER_MIRROR_V

See Also

D3DX8.FilterCubeTexture, D3DX8.FilterTexture, D3DX8.LoadSurfaceFromFile, D3DX8.LoadSurfaceFromFileInMemory, D3DX8.LoadSurfaceFromMemory, D3DX8.LoadSurfaceFromSurface


CONST_D3DXERR

Defines error codes raised by the system. For descriptions of these error codes, see Error Codes.


CONST_D3DXMESH

Defines creation options for a mesh.

Enum CONST_D3DXMESH
    D3DXMESH_32BIT        =        1
    D3DXMESH_DONOTCLIP    =        2
    D3DXMESH_POINTS       =        4
    D3DXMESH_RTPATCHES    =        8
    D3DXMESH_VB_SYSTEMMEM =       16 (&H10)
    D3DXMESH_VB_MANAGED   =       32 (&H20)
    D3DXMESH_VB_WRITEONLY =       64 (&H40)
    D3DXMESH_VB_DYNAMIC   =      128 (&H80)
    D3DXMESH_IB_SYSTEMMEM =      256 (&H100)
    D3DXMESH_SYSTEMMEM    =      272 (&H110)
    D3DXMESH_IB_MANAGED   =      512 (&H200)
    D3DXMESH_MANAGED      =      544 (&H220)
    D3DXMESH_WRITEONLY    =      816 (&H330)
    D3DXMESH_IB_WRITEONLY =     1024 (&H400)
    D3DXMESH_IB_DYNAMIC   =     2048 (&H800)
    D3DXMESH_DYNAMIC      =     2176 (&H880)
    D3DXMESH_VB_SHARE     =     4096 (&H1000)
    D3DXMESH_USEHWONLY    =     8192 (&H2000)
    D3DDEVCAPS_NPATCHES   = 16777216 (&H1000000)
End Enum

Constants

D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This constant is currently not supported and should not be used.
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_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class 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_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
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_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers. These meshes will have separate index buffers that index into the shared vertex buffer.
D3DXMESH_USEHWONLY
Use hardware processing only. This flag should only be specified for a hardware processing device. On a mixed mode device this flag will cause the system to either use hardware only, or if the hardware is not capable it will approximate using the software capabilities.

Note that this flag is only valid when specified as an option for the D3DXSkinMesh.ConvertToBlendedMesh method.

D3DDEVCAPS_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with the D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.

See Also

D3DX8.CreateMesh, D3DX8.CreateMeshFVF, D3DXBaseMesh.CloneMesh, D3DXBaseMesh.CloneMeshFVF, D3DXBaseMesh.GetOptions, D3DXPMesh.ClonePMesh, D3DXPMesh.ClonePMeshFVF , D3DXSPMesh.CloneMesh, D3DXSPMesh.CloneMeshFVF, D3DXSPMesh.ClonePMesh, D3DXSPMesh.ClonePMeshFVF, D3DXSPMesh.GetOptions


CONST_D3DXMESHMISC

Defines miscellaneous flags.

Enum CONST_D3DXMESHMISC
    UNUSED16          = 65535 (&HFFFF)
    UNUSED32          =    -1 (&HFFFFFFFF)
    MAX_FVF_DECL_SIZE =    20
End Enum

Constants

UNUSED16
This value is not used.
UNUSED32
This value is not used
MAX_FVF_DECL_SIZE
The upper limit of a declarator array.

See Also

D3DX8.LoadMeshFromX, D3DX8.LoadMeshFromXof, D3DXMesh.Optimize


CONST_D3DXMESHOPT

Defines the type of optimizations that can be performed on a mesh.

Enum CONST_D3DXMESHOPT
    D3DXMESHOPT_COMPACT      =  1
    D3DXMESHOPT_ATTRSORT     =  2
    D3DXMESHOPT_VERTEXCACHE  =  4
    D3DXMESHOPT_IGNOREVERTS  = 16
    D3DXMESHOPT_SHAREVB      = 32
End Enum

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 D3DXBaseMesh.DrawSubset performance.
D3DXMESHOPT_VERTEXCACHE
Reorders faces to increase the cache hit rate of vertex caches.
D3DXMESHOPT_IGNOREVERTS
Optimize the faces only; do not optimize the vertices.
D3DXMESHOPT_SHAREVB
Share vertex buffers.

See Also

D3DX8.LoadMeshFromX, D3DX8.LoadMeshFromXof, D3DXMesh.Optimize


CONST_D3DXMESHSIMP

Defines simplification options for a mesh.

Enum CONST_D3DXMESHSIMP
    D3DXMESHSIMP_VERTEX = 1
    D3DXMESHSIMP_FACE   = 2
End Enum

Constants

D3DXMESHSIMP_VERTEX
The mesh will be simplified by a specified number of vertices.
D3DXMESHSIMP_FACE
The mesh will be simplified by a specified number of faces.

See Also

D3DX8.GeneratePMesh, D3DX8.SimplifyMesh


CONST_DTFLAGS

Defines flags used for drawing text.

Enum CONST_DTFLAGS
    DT_LEFT                 =       0
    DT_TOP                  =       0
    DT_CENTER               =       1
    DT_RIGHT                =       2
    DT_VCENTER              =       4
    DT_BOTTOM               =       8
    DT_WORDBREAK            =      16 (&H10)
    DT_SINGLELINE           =      32 (&H20)
    DT_EXPANDTABS           =      64 (&H40)
    DT_TABSTOP              =     128 (&H80)
    DT_NOCLIP               =     256 (&H100)
    DT_EXTERNALLEADING      =     512 (&H200)
    DT_CALCRECT             =    1024 (&H400)
    DT_NOPREFIX             =    2048 (&H800)
    DT_INTERNAL             =    4096 (&H1000)
    DT_EDITCONTROL          =    8192 (&H2000)
    DT_PATH_ELLIPSIS        =   16384 (&H4000)
    DT_END_ELLIPSIS         =   32768 (&H8000)
    DT_MODIFYSTRING         =   65536 (&H10000)
    DT_RTLREADING           =  131072 (&H20000)
    DT_WORD_ELLIPSIS        =  262144 (&H40000)
    DT_NOFULLWIDTHCHARBREAK =  524288 (&H80000)
    DT_HIDEPREFIX           = 1048576 (&H100000)
    DT_PREFIXONLY           = 2097152 (&H200000)End Enum

Constants

DT_LEFT
Aligns text to the left.
DT_TOP
Top-justifies text (single line only).
DT_CENTER
Centers text horizontally in the rectangle.
DT_RIGHT
Aligns text to the right.
DT_VCENTER
Centers text vertically (single line only).
DT_BOTTOM
Justifies text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.
DT_WORDBREAK
Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the DestRect parameter. A carriage return/line feed sequence also breaks the line.
DT_SINGLELINE
Displays text on a single line only. Carriage returns and line feeds do not break the line.
DT_EXPANDTABS
Expands tab characters. The default number of characters per tab is eight. The DT_WORD_ELLIPSIS, DT_PATH_ELLIPSIS, and DT_END_ELLIPSIS values cannot be used with the DT_EXPANDTABS value.
DT_TABSTOP
Sets tab stops. Bits 15–8 (high-order byte of the low-order word) of the Format parameter specify the number of characters for each tab. The default number of characters per tab is eight. The DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX values cannot be used with the DT_TABSTOP value.
DT_NOCLIP
Draws without clipping. DrawTextW is somewhat faster when DT_NOCLIP is used.
DT_EXTERNALLEADING
Includes the font external leading in line height. Normally, external leading is not included in the height of a line of text.
DT_CALCRECT
Determines the width and height of the rectangle. If there are multiple lines of text, DrawTextW uses the width of the rectangle pointed to by the SrcRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawTextW modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawTextW returns the height of the formatted text but does not draw the text.
DT_NOPREFIX
Turns off processing of prefix characters. Normally, DrawTextW interprets the mnemonic-prefix character ampersand (&) as a directive to underscore the character that follows, and the mnemonic-prefix characters && as a directive to print a single &. By specifying DT_NOPREFIX, this processing is turned off. Compare with DT_HIDEPREFIX and DT_PREFIXONLY.
DT_INTERNAL
Uses the system font to calculate text metrics.
DT_EDITCONTROL
Duplicates the text-displaying characteristics of a multiline edit control. Specifically, the average character width is calculated in the same manner as for an edit control, and the function does not display a partially visible last line.
DT_END_ELLIPSIS or DT_PATH_ELLIPSIS
Truncates the string without adding ellipses so that the result fits in the specified rectangle. The string is not modified unless the DT_MODIFYSTRING flag is specified.

Specify DT_END_ELLIPSIS to truncate characters at the end of the string, or DT_PATH_ELLIPSIS to truncate characters in the middle of the string. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much of the text as possible after the last backslash.

DT_MODIFYSTRING
Modifies the string to match the displayed text. This flag has no effect unless the DT_END_ELLIPSIS or DT_PATH_ELLIPSIS flag is specified.
DT_RTLREADING
Displays text in right-to-left reading order for bi-directional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.
DT_WORD_ELLIPSIS
Truncates text that does not fit in the rectangle and adds ellipses.
DT_NOFULLWIDTHCHARBREAK
Microsoft® Windows® 98, Windows 2000: Prevents a line break at a DBCS (double-wide character string), so that the line breaking rule is equivalent to an SBCS (single-wide character string)strings. For example, this can be used in Korean windows to increase the readability of icon labels. This is only effective if DT_WORDBREAK is specified.
DT_HIDEPREFIX
Windows 2000: Ignores the ampersand (&) prefix character in the text. The letter that follows is not underlined, but other mnemonic-prefix characters are still processed.

Example:

input string: "A&bc&&d"

normal: "Abc&d"

HIDEPREFIX: "Abc&d"

Compare with DT_NOPREFIX and DT_PREFIXONLY.

DT_PREFIXONLY
Windows 2000: Draws only an underline at the position of the character following the ampersand (&) prefix character. Does not draw any character in the string.

Example:

input string: "A&bc&&d"

normal: "Abc&d"

PREFIXONLY: " "

Compare with DT_NOPREFIX and DT_HIDEPREFIX.

See Also

D3DX8.DrawText


Error Codes

Errors are represented by negative values and cannot be combined. This table lists the values that can be returned by methods included with the Direct3DX utility library. See the individual method descriptions for lists of the values that each can return.

D3DXERR_CANNOTATTRSORT
Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
D3DXERR_CANNOTMODIFYINDEXBUFFER
The index buffer cannot be modified.
D3DXERR_INVALIDDATA
The data is invalid.
D3DXERR_INVALIDMESH
The mesh is invalid.
D3DXERR_SKINNINGNOTSUPPORTED
Skinning is not supported.
D3DXERR_TOOMANYINFLUENCES
Too many influences specified.


Vertex Shader Assembler Reference

Microsoft DirectX 8.1 (vertex shader versions 1.0, 1.1)

Vertex Shader Reference

A programmable vertex shader is made up of a set of instructions that operate on vertex data. A shader uses registers to transfer data in and out of the pixel shader processor. Modifiers can be applied to data to modify the results of the current instruction.

Architecture

The Vertex Shader Block Diagram illustrates the relationship between shader registers and the vertex shader arithmetic logic unit (ALU).

Instructions

Instructions contains a list of the available instructions.

Registers

Registers lists the different types of registers used by the shader ALU.

Modifiers

Modifiers describes how to change the functionality of an instruction or the contents that are read from or written to a register.


Vertex Shader Architecture

A programmable vertex shader consists input registers, a processor and output registers. For a block diagram of a vertex shader, see Vertex Shader Block Diagram.


Instructions

This section contains reference information for the instructions implemented by the Direct3DX vertex shader assembler. Vertex shaders can be generated in an ascii file or even an ascii string. Each vertex shader can consist of up to 128 instructions. Each instruction can have up to three input arguments.

Version Instructions | Version
 | 1.0 | 1.1
vs | x | x
def | x | x
General Instructions | Version
 | 1.0 | 1.1
add | x | x
dp3 | x | x
dp4 | x | x
dst | x | x
expp | x | x
lit | x | x
logp | x | x
mad | x | x
max | x | x
min | x | x
mov | x | x
mul | x | x
rcp | x | x
rsq | x | x
sge | x | x
slt | x | x
sub | x | x
Macros | Version
 | 1.0 | 1.1
exp | x | x
frc | x | x
log | x | x
m3x2 | x | x
m3x3 | x | x
m3x4 | x | x
m4x3 | x | x
m4x4 | x | x

There are 4 types of vertex shader instructions.

  • A shader file must have a version instruction and it must be the first instruction in the file.

  • A shader file must write the vertex position to the output vertex position register. If the shader provides vertex color, the shader must write to the output vertex color register.

  • Macro instructions combine general instructions to provide higher level functionality.

  • Instruction modifiers can be applied to instruction arguments to mask, negate or swizzle the arguments. Modifiers are optional in a shader file. For more information see Modifiers


add

Adds sources.

add dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

The add instruction sums the components of the two source registers and stores the result in the destination register.

dest.x = src0.x + src1.x;
dest.y = src0.y + src1.y;
dest.z = src0.z + src1.z;
dest.w = src0.w + src1.w;

Example

// This example adds two constant colors. This combines the rgb components
// of each color to produce the final color

// shader file
vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c5  		; load pink
mov r1, c6	    	; load off white
add oD0, r0, r1		; add colors and output

// The resultant vertex color is a blend of pink and off white

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c5
float colorPink[] = {0.75,0,0,0};
m_pd3dDevice->SetVertexShaderConstant(5, &colorPink, 1);

// set register c6
float colorOffWhite[] = {0.9f,0.9f,0.9f,0.9f};
m_pd3dDevice->SetVertexShaderConstant(6, &colorOffWhite, 1);

// The c0 register is loaded with the view and projection matrix using the m4x4
// instruction (the m4x4 instruction also uses the c1, c2 and c3 registers).
// The last two methods set the constant color registers.


def

Defines vertex shader constants.

def dest, fVal0, fVal1, fVal2, fVal3

Registers

vDest
Destination register.
fVal0, fVal1, fVal2, fVal3
Four floating point values.

To learn more about registers, see Registers.

Remarks

There are three ways to define constants in a vertex shader.

  1. Define them directly within the declarator. In this case, there is no need to use the def instruction in the vertex shader.

This also applies to D3DXAssembleShaderFromFile and D3DXAssembleShaderFromResource


dp3

Computes the three-component dot product of the source registers.

dp3 dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the dp3 instruction.

dest.w = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.x = dest.y = dest.z = dest.w = the scalar result of dp3

Example

// This example adds two constant colors. This combines the rgb
// components of each color to produce the final color

// shader file
vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c5		    ; load pink
mov r1, c6	    	; load off-white
dp3 r2, r0, r1		; combine c5 and c6 using a dot product
mov oD0, r2		    ; output color

// The resultant vertex color is a shade of gray because the output scalar
// value is copied to all components

// Additional code is used to initialize the constant registers

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c5
float colorPink[] = {0.75,0,0,0};
m_pd3dDevice->SetVertexShaderConstant(5, &colorPink, 1);

// set register c6
float colorOffWhite[] = {0.9f,0.9f,0.9f,0.9f};
m_pd3dDevice->SetVertexShaderConstant(6, &colorOffWhite, 1);

// The c0 register is loaded with the view and projection matrix using
// the m4x4 instruction (the m4x4 instruction also uses the c1, c2 and
// c3 registers). The last two methods set the constant color registers


dp4

Computes the four-component dot product of the sources.

dp4 dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the dp4 instruction.

dest.w = (src0.x * src1.x) + (src0.y * src1.y) +
         (src0.z * src1.z) + (src0.w * src1.w);
dest.x = dest.y = dest.z = the scalar result of dp4

Example

// This example takes the dot product of two constant colors

// shader file
vs.1.0
dp4 r0.x, v0, c0	; transform vertices by view/projection matrix
dp4 r0.y, v0, c1
dp4 r0.z, v0, c2
dp4 r0.w, v0, c3
mov oPos, r0		; output position

mov oD0, c4 		; output green diffuse color

// The resultant vertex color is green

// Additional code is used to initialize the constant registers

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

float color[4] = {0,1,0,0};
m_pd3dDevice->SetVertexShaderConstant(4, &color, 1);

// The c0 register is loaded with the view and projection matrix using
// the m4x4 instruction (the m4x4 instruction also uses the c1, c2 and
// c3 registers). The last method sets the constant color register c4
// with the color green


dst

Calculates the distance vector.

dst dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the dst instruction.

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).

Example

// This example transforms vertices and outputs a constant color
// These steps are required in all vertex shaders. Once that is done,
// the sample shows how to set up the inputs to the dst instruction

// shader file
m4x4 oPos, v0, c0	    ; transform vertices by view/projection matrix
mov oD0, c4 	    	; output constant color

// find the distance
mov r0.xyz, v0.xyz		; load vertex position
dp3 r1.yz, r0.xyz, r0.xyz	; put d*d in r1.y and r1.z
rsq r2.y, r1.y			; 1/d
rcp r2.yw, r2.y			; put d in r2.y and r2.w
dst r3, r1, r2			; find the distance from v0 to origin
// The resultant vertex color is green and is shown below
// The dp3 instruction is used to load the src0 register with data
// in the form of (ignored, d*d, d*d, ignored). The rcp instruction
// finishes loading register src1 with data in the form of
// (ignored, d, ignored, d).

// Additional code is used to initialize the constant registers

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0,1,0,0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2,3,4 are
// bound to registers C2, C3, C4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register
// with the color green.


expp

Provides exponential 2x partial support.

expp dest, src

Registers

dest
Destination register.
src
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the expp instruction.

float w = src.w;
float v = (float)floor(src.w);

dest.x = (float)pow(2, v);
dest.y = w - v;

// Reduced precision exponent
float tmp = (float)pow(2, w);
DWORD tmpd = *(DWORD*)&tmp & 0xffffff00;
dest.z = *(float*)&tmpd;
dest.w = 1;

The expp instruction produces undefined results if fed a negative value for the exponent (src.w).

This instruction provides exponential base 2 partial precision. It allows for a more accurate determination of dest.x*function(dest.y), where function is a user approximation to 2*dest.y over the limited range where dest.y is between 0.0 and 1.0.

Reduced precision arithmetic is used to evaluate the destination z component (dest.z). However, the approximation error must be less than 1/(211) (the absolute error for 10-bit precision) and between 0.0 and 1.0.

Example

// This example changes the value of the vertex color.

// shader file
vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c5  		; load gray into register r0
mov r1, c4.y		; load 1's into register r1
expp r1.x, c6.y		; change r1.x only
                    ; c6.y = 0.5 so r1.x = 20.5 = 1.4
mul r2, r0, r1		; scale r0 by r1

mov oD0,  r2		; output

// The exp instruction causes the red component to increase about 40%.
// The resulting color is a dim red and is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0,1,0,0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register c5
float colorGray[] = {0.5f,0.5f,0.5f,0.5f};
m_pd3dDevice->SetVertexShaderConstant(5, &gray, 1);

// set register c6
float exp[] = {0.24f, 0.48f, 0.96f, 1.92f};
m_pd3dDevice->SetVertexShaderConstant(6, &exp, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2,3,4 are
// bound to registers C2, C3, c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register
// with the data for the color green. The next SetVertexShaderConstant
// method binds the C5 register with the data for the color gray. The
// last SetVertexShaderConstant method binds the C6 register with the
// data for the exponent values.


lit

Provides partial support for lighting by calculating lighting coefficients from two dot products and an exponent.

lit dest, src

Registers

dest
Destination register.
src
Input source register.

To learn more about registers, see Registers.

Remarks

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 8 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 and expp combination, or no more than approximately 1 least significant bit (LSB) for an 8-bit color component.


logp

Provides log2(x) partial support.

logp dest, src

Registers

dest
Destination register.
src
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the logp instruction.

float v = ABSF(src.w);
if (v != 0)
{
    int p = (int)(*(DWORD*)&v >> 23) - 127;
    dest.x = (float)p;    // exponent
    p = (*(DWORD*)&v & 0x7FFFFF) | 0x3f800000;
    dest.y =  *(float*)&p;// mantissa;
    float tmp = (float)(log(v)/log(2));
    DWORD tmpd = *(DWORD*)&tmp & 0xffffff00;
    dest.z = *(float*)&tmpd;
    dest.w = 1;
}
else
{
    dest.x = MINUS_MAX();
    dest.y = 1.0f;
    dest.z = MINUS_MAX();
    dest.w = 1.0f;
}

This instruction provides logarithm base 2 partial precision. It generates an approximate answer in the destination z component (dest.z). It also allows for a more accurate determination of dest.x + function(dest.y), where the function is a user approximation to log2(dest.y) for dest.y (1.0 <= dest.y < 2.0).

Reduced precision arithmetic is used to evaluate dest.z; however, the approximation error must be less than 1/(211) in absolute error (10-bit precision), and over the range (1.0 <= t.y < 2.0). A zero source argument generates the result vector (-infinity, 0.0, -infinity, 1.0).

Example

// This example changes the vertex color.

// shader file

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0.w, c4.w		; load constant color
logp r0,  r0.w		; take the logp and copy it to all four components
mov oD0, r0 		; output color

// The constant color loaded in r0 is (0, 0, 0, 1.5). The logp yields
// component values of (0, 1, 0.5) which is the pale green shade shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float log[] = {0,0,0,1.5f};
m_pd3dDevice->SetVertexShaderConstant(4, &log, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2, 3, 4 are
// bound to registers C2, C3, c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register with
// the data in the log array. Notice that only the w component is used.


mad

Multiplies and adds sources.

mad dest, src0, src1, src2

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.
src2
Input source register.

To learn more about registers, see Registers.

Remarks

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;

Example

// This example combines three colors.

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c4	    	; green
mov r1, c6		; off white
mov r2, c7	    	; gray
mad r3, r0, r1, r2	         ; combine all three colors
mov oD0, r3

// The resultant vertex color is a combination of all three colors.
// The mad instruction multiplies green and off-white to produce a
// slightly darker shade of green. Then gray is added to the result
// which yields a shade of green that has non-zero red and blue
// components. The resulting shade is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float color[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &color, 1);

// set register c6
float colorOffWhite[] = {0.9f, 0.9f, 0.9f, 0.9f};
m_pd3dDevice->SetVertexShaderConstant(6, &colorOffWhite, 1);

// set register c7
float colorGray[] = {0.5f, 0.5f, 0.5f, 0.5f};
m_pd3dDevice->SetVertexShaderConstant(7, &colorGray, 1);

// The c0 register is loaded with the view and projection matrix using the
// m4x4 instruction (the m4x4 instruction also uses the c1, c2 and c3
// registers). The last three methods set the constant color registers
// c4, c6 and c7.


max

Calculates the maximum of the sources.

max dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

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;

Example

This example compares two registers to find the maximum component values.

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c4  		; load green
mov r1, c5	    	; load pink
max r2, r0, r1		; pick max color values
mov oD0, r2		; output

// The resultant vertex color is part green and part pink and is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register c5
float colorPink[] = {0.75, 0, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(5, &colorPink, 1);

// The c0 register is loaded with the view and projection matrix
// using the m4x4 instruction (the m4x4 instruction also uses the
// c1, c2 and c3 registers). The last two methods set the constant
// color registers.


min

Calculates the minimum of the sources.

min dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

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;

Example

// This example adds two constant colors. This combines the rgb
// components of each color to produce the final color.

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c6  		; load off-white
mov r1, c7	    	; load gray
min r2, r1, r0		; pick min color values
mov oD0, r2                ; output

// The resultant vertex color is gray because the gray color components
// are less than the off-white color components.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c6
float colorOffWhite[] = {0.9f, 0.9f, 0.9f, 0.9f};
m_pd3dDevice->SetVertexShaderConstant(6, &colorOffWhite, 1);

// set register c7
float colorGray[] = {0.5f, 0.5f, 0.5f, 0.5f};
m_pd3dDevice->SetVertexShaderConstant(7, &colorGray, 1);

// The c0 register is loaded with the view and projection matrix using
// the m4x4 instruction (the m4x4 instruction also uses the c1, c2 and
// c3 registers). The last two methods set the constant color registers
// c6 and c7.


mov

Moves contents of the source into the destination.

mov dest, src

Registers

dest
Destination register.
src
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed.

if(dest == A0)
{
    float p = (float)floor(src.x);
    *(int*)&dest.x = FloatToInteger(p);
}
else
{
    dest = src;
}

Example

// This example outputs a constant diffuse color.

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix
mov oD0, c4 		; output constant color

// The resultant vertex color is green and is shown below.

// Additional code initializes the constant register c4 with the color green.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float color[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &color, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2, 3 and 4 are
// bound to registers C2, C3 and c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register
// with the color green.


mul

Multiplies sources into the destination.

mul dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
vSrc1
Input source register.

To learn more about registers, see Registers.

Remarks

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;

Example

This example combines two constant colors.

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c4  		; load green
mov r1, c7	    	; load gray
mul r2, r0, r1		; rgb component wise multiply
mov oD0, r2                ; output dark green

// The resultant vertex color is a a dark green and is shown below.

// Additional code is used to initialize the constant registers.
// The c0 register is loaded with the view and projection matrix
// using the m4x4 instruction (the m4x4 instruction also uses the
// c1, c2 and c3 registers). The last two methods set the constant
// color registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float color[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &color, 1);

// set register c7
float colorGray[] = {0.5f, 0.5f, 0.5f, 0.5f};
m_pd3dDevice->SetVertexShaderConstant(7, &colorGray, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2, 3 and 4 are
// bound to registers C2, C3 and c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register
// with the color green. The last SetVertexShaderConstant method
// binds the C7 register with the color gray.


rcp

Computes the reciprocal of the source scalar.

rcp dest, src

Registers

dest
Destination register.
src
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed.

if(src.w == 1.0f)
{
    dest.x = dest.y = dest.z = dest.w = 1.0f;
}
else if(src.w == 0)
{
    dest.x = dest.y = dest.z = dest.w = PLUS_INFINITY();
}
else
{
    dest.x = dest.y = dest.z = m_dest.w = 1.0f/src.w;
}

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.

Example

// This example changes the vertex color from green to white.
// The max instruction clamps the result to 1.0.

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

rcp r0, c5  		; take the reciprocal of 0.5
max r1, r0, c4.y	         ; clamp the output to max of 1
mov oD0, r2	    	; result is white

// The resultant vertex color is white and is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register c5
float colorGray[] = {0, 0, 0, 0.5f};
m_pd3dDevice->SetVertexShaderConstant(5, &colorGray, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2, 3 and 4 are
// bound to registers C2, C3 and c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register
// with the color green. The last SetVertexShaderConstant method
binds the C5 register with the color gray.


rsq

Computes the reciprocal square root of the source scalar.

rsq dest, src

Registers

dest
Destination register.
src
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed.

float v = ABSF(src.w);
if(v == 1.0f)
{
    dest.x = dest.y = dest.z = dest.w = 1.0f;
}
else if(v == 0)
{
    dest.x = dest.y = dest.z = dest.w = PLUS_INFINITY();
}
else
{
    v = (float)(1.0f / sqrt(v));
    dest.x = dest.y = dest.z = dest.w = v;
}

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.

Example

// This example changes the vertex color from dark red to white.
// The max instruction clamps the result to 1.0

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

rsq r0,  c5 		; take the reciprocal square root of 0.2
max r2, r0, c4.y	         ; clamp the output to max of 1
mov oD0, r2	    	; result is white

//The resultant vertex color is white and is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register c5
float colorDarkRed[] = {0.2f, 0.0f, 0.0f, 0.0f};
m_pd3dDevice->SetVertexShaderConstant(5, &colorDarkRed, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2, 3 and 4 are
// bound to registers C2, C3 and c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register
// with the color green. The last SetVertexShaderConstant method
// binds the C5 register with the color dark red.


sge

Compares the two sources to see if either is greater than the other. Sets the destination to 1.0 if the first source operand is greater than or equal to the second source operand; otherwise, the destination is set to 0.0.

sge dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the sge instruction.

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;

Example

// This example compares the component color values between two sources.

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c4  		; load pink
sge r1, c5, r0		; compare gray to pink, component to component
mov oD0, r1	    	; output result

// The resultant vertex color is cyan (0,1,1) and is shown below.
// The red component is 0 because src0.x < src1.x. The green component
// is 1 because src0.y > src1.y and the blue component is 1 because
// src0.z > src1.z.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register C4
float colorPink[] = {0.75, 0, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorPink, 1);

// set register C5
float colorGray[] = {0.5f, 0.5f, 0.5f, 0.5f};
m_pd3dDevice->SetVertexShaderConstant(5, &colorGray, 1);

// The first SetVertexShaderConstant method binds the C0 register with
// the first row of the view/projection matrix (rows 2, 3 and 4 are bound to
// registers C2, C3 and c4 also). The m4x4 instruction (in the shader file)
// loads the data.
// The second SetVertexShaderConstant method binds the C4 register with
// data for the color pink. The last SetVertexShaderConstant method binds
// the C5 register with data for the color gray.


slt

Compares sources to see which source is less. Sets the destination to 1.0 if the first source operand is less than the second source operand; otherwise, the destination is set to 0.0.

slt dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the slt instruction.

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;

Example

// The following example compares the component color values of the two sources.

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c5		    ; load pink
slt r2, c4, r0		    ; compare green to pink
mov oD0, r2		    ; output result

// The resultant vertex color is red (1, 0, 0) and is shown below. The red
// component is 1 because src0.x > src1.x. The green component is 0
// because src0.y < src1.y and the blue component is 0 because
// src0.z < src1.z.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register C4
float colorGreen[] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register C5
float colorPink[] = {0.75, 0, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(5, &colorPink, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2, 3 and 4 are
// bound to registers C2, C3 and c4 also). The m4x4 instruction
// (in the shader file) loads the data.

// The second SetVertexShaderConstant method binds the C4 register
// with data for the color green. The last SetVertexShaderConstant
// method binds the C5 register with data for the color pink.


sub

Subtracts sources.

sub dest, src0, src1

Registers

dest
Destination register, holding the result of the operation.
src0
Input source register, specifying the input argument.
src1
Input source register, specifying the input argument.

To learn more about registers, see Registers.

Remarks

This instruction performs the subtraction shown in this formula.

dest = src0 - src1

Example

The following example subtracts two colors.

// shader file
vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix
mov r0, c6		    ; load off-white
mov r1, c7		    ; load gray
sub r2, r0, r1		    ; subtract gray from off-white
mov oD0, r2		    ; output darker gray

The resultant vertex color is a darker gray and is shown below.

// additional code is required to initialize the constant registers.
// c0 is loaded with the view and projection matrix using the m4x4
// instruction (the m4x4 instruction also uses the c1, c2 and c3 registers).
// The last two methods set the constant color registers c6 and c7.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c6
float colorOffWhite[] = {0.9f, 0.9f, 0.9f, 0.9f};
m_pd3dDevice->SetVertexShaderConstant(6, &colorOffWhite, 1);

// set register c7
float colorGray[] = {0.5f, 0.5f, 0.5f, 0.5f};
m_pd3dDevice->SetVertexShaderConstant(7, &colorGray, 1);


vs

Provides a method to specify the type and version of the shader code.

vs.mainVer.subVer

Registers

mainVer
Main version number of the vertex shader.
subVer
Sub version number of the vertex shader.

Remarks

This instruction is required to be at the beginning of all vertex shaders.

Example

This example illustrates an example shader file.

// shader file
vs.1.0			    ; declare version number
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix
mov oD0, c4		    ; output constant color

The output vertex color is green and is shown below.

// Additional code is required to initialize the constant registers
// as shown below.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// The first SetVertexShaderConstant method binds the C0 register with the first
// row of the view/projection matrix (rows 2, 3 and 4 are bound to registers C2, C3 and
// c4 also). The m4x4 instruction (in the shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register with
// the color green.


exp

Provides exponential 2x with full precision to at least 1/220.

exp dest, src0

Registers

dest
Destination register.
src0
Input source register.

To learn more about registers, see Registers.

Remarks

float v = src0.w;
dest.x = dest.y = dest.z = dest.w = (float)pow(2, v);

Example

// This example changes the value of the vertex color

// shader file
vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c5   		; load gray into register r0
mov r1, c4.y		; load 1's into register r1
exp r1.x, c6.y		; change r1.x only
                    ; c6.y = 0.5 so r1.x = 20.5 = 1.4
mul r2, r0, r1		; scale r0 by r1

mov oD0,  r2		; output

// The exp instruction causes the red component to increase about 40%
// The resulting color is a dim red and is shown below

// Additional code is used to initialize the constant registers

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register c5
float colorGray[] = {0.5f, 0.5f, 0.5f, 0.5f};
m_pd3dDevice->SetVertexShaderConstant(5, &gray, 1);

// set register c6
float exp[] = {0.24f, 0.48f, 0.96f, 1.92f};
m_pd3dDevice->SetVertexShaderConstant(6, &exp, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2, 3, 4 are
// bound to registers C2, C3, c4 also). The m4x4 instruction (in the
// shader file) loads the data
// The second SetVertexShaderConstant method binds the C4 register
// with the data for the color green. The next SetVertexShaderConstant
// method binds the C5 register with the data for the color gray. The last
// SetVertexShaderConstant method binds the C6 register with the data for
// the exponent values.


frc

Returns the fractional portion of each input component.

frc dest, src

Registers

dest
Destination register.
src0
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the frc instruction.

dest.x = src.x - (float)floor(src.x);
dest.y = src.y - (float)floor(src.y);
dest.z = dest.w = ignored;

Each component of the result is in the range from 0.0 through 1.0.

Example

// This example changes the vertex color.

// shader file

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0, c5	    	; load white constant color in r0
frc r0.xy, r0.x		; remove fractional part, store result in (xy)
min r0, r0, c4.y           ; clamp max value at 1
mov oD0,   r0		; output result

// The frc instruction loads the fractional part in the x and y
// components of the destination register. This results in r0
// containing (0.2, 0.2, 6.2, 6.2). After the min instruction, r0
// contains (0.2, 0.2, 1,1). The resultant vertex color is blue
// and is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register C4
float color offWhite[] = {0.9f,0.9f,0.9f,0.9f};
m_pd3dDevice->SetVertexShaderConstant(4, &offWhite, 1);

// set register C5
float superWhite[] = {6.2f,6.2f,6.2f,6.2f};
m_pd3dDevice->SetVertexShaderConstant(5, &superWhite, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2, 3, 4 are
// bound to registers C2, C3, c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register with
// data for the color offWhite. The last SetVertexShaderConstant method
// binds the C5 register with the data for the color superWhite.


log

Provides log2(x) support with full float precision of at least 1/220.

log dest, src

Registers

dest
Destination register.
src
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed.

float v = ABSF(src.w);
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 = MINUS_MAX();
}

This instruction accepts a scalar source (src.w) of which the sign bit is ignored. The result is replicated to all four channels.

The input exponent must be in the range –128 to 128. The approximation error must be less than 1/220 in absolute error, and over the range (1.0 <= dest.y < 2.0).

A zero source generates (-infinity, -infinity, -infinity, -infinity).

Example

// This example changes the vertex color.

// shader file

vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix

mov r0.w, c4.w		; load constant color
log r0,  r0.w		; take the log and copy it to all four components
mov oD0, r0 		; output color

// The constant color loaded in r0 is (0, 0, 0, 1.5). The log of 1.5 is
// approx. 0.4 which yields a shade of gray since it is copied to all
// four components(x, y, z, w). The resulting color is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float log[] = {0, 0, 0, 1.5f};
m_pd3dDevice->SetVertexShaderConstant(4, &log, 1);

// The first SetVertexShaderConstant method binds the C0 register
// with the first row of the view/projection matrix (rows 2, 3, 4 are
// bound to registers C2, C3, c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the C4 register
// with the data in the log array. Notice that only the w component is used.


m3x2

Computes the product of the input vector and a 3x2 matrix.

m3x2 dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

// m3x2 operates as shown by the following equations
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 expansion below). A 2-D result is produced, leaving the other elements of the destination register (dest.z and dest.w) unaffected.

This operation is commonly used for 2-D transforms. This macro instruction is implemented as a pair of dot products as shown below.

m3x2   r5, v0, c3

which is performed as two dot products:
dp3   r5.x, v0, c3
dp3   r5.y, v0, c4

The swizzle and negate modifiers are not allowed on this instruction.

Example

// This example scales the object in both the x and y direction.

// shader file
vs.1.0
mov r0, v0	    	; load vertex position
m3x2 r1, r0, c5		; scale in x and y
m4x4 oPos, r1, c0	; transform vertices by view/projection matrix

mov oD0, c4		; output constant color

// The resultant green object is half the width and 1/4 the height
// and is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register c5 (also sets registers c6 and c7)
float scale[][4] = {{0.5f, 0, 0, 0}, {0, 0.25f, 0, 0}, {0, 0, 1, 0}};
m_pd3dDevice->SetVertexShaderConstant(5, &scale, 3);

// The first SetVertexShaderConstant method binds the c0 register
// with the first row of the view/projection matrix (rows 2, 3, 4 are
// bound to registers C2, C3, c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the c4 register with
// the data for the color green. The last SetVertexShaderConstant method
// binds the c5 register with the first row of the scale matrix (rows 2 and 3
// are bound to registers C6 and C7 also). The m3x3 instruction (in the shader
// file) loads the data.


m3x3

Computes the product of the input vector and a 3x3 matrix.

m3x3 dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

// m3x3 operates as shown in the following equation.
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 in the same register file--as shown in the expansion below). A 3-D 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 macro instruction is implemented as a pair of dot products as shown below.

m3x3 r5, v0, c[3]

which is performed as three dot products:
dp3   r5.x, v0, c[3]
dp3   r5.y, v0, c[4]
dp3   r5.z, v0, c[5]

The swizzle and negate modifiers are not allowed on this instruction.

Example

// This example scales the object in both the x and y direction.

// shader file

vs.1.0
mov r0, v0	    	; load vertex position
m3x3 r1, r0, c5		; scale in x and y
m4x4 oPos, r1, c0	; transform vertices by view/projection matrix

mov oD0, c4		; output constant color

// The resultant green object is half the width and 1/4 the height
// and is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register c5 (also sets registers c6 and c7)
float scale[][4] = {{0.5f, 0, 0, 0}, {0, 0.25f, 0, 0}, {0, 0, 1, 0}};
m_pd3dDevice->SetVertexShaderConstant(5, &scale, 3);

// The first SetVertexShaderConstant method binds the c0 register
// with the first row of the view/projection matrix (rows 2, 3, 4 are
// bound to registers C2, C3, c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the c4 register
// with the data for the color green. The last SetVertexShaderConstant
// method binds the c5 register with the first row of the scale matrix
// (rows 2 and 3 are bound to registers C6 and C7 also). The m3x3 instruction
// (in the shader file) loads the data.


m3x4

Computes the product of the input vector and a 3x4 matrix.

m3x4 dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

// m3x4 operates as shown in the following equation.
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 in the same register file--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 macro instruction is implemented as a pair of dot products as shown below.

m3x4   r5, v0, c3

which is performed as four dot products:
dp3 r5.x, v0, c3
dp3 r5.y, v0, c4
dp3 r5.z, v0, c5
dp3 r5.w, v0, c6

The swizzle and negate modifiers are not allowed on this instruction.

Example

// This example scales the object in the y direction.

// shader file

mov r0, v0	    	; load vertex position
m3x4 r1, r0, c5		; scale in y
mov r1.w, c4.y		; set w component to 1
m4x4 oPos, r1, c0	; transform vertices by view/projection matrix

mov oD0, c4		; output constant color

// The resultant green object is 3/4 the height and is shown below.

// Additional code is used to initialize the constant registers

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register c5 (also sets registers c6, c7, c8)
// 4 rows x 3 cols
float scaleY[][4] = {{1, 0, 0, 0},{0, 0.75, 0, 0},{0, 0, 1, 0},{0, 0, 0, 1}};
m_pd3dDevice->SetVertexShaderConstant(5, &scaleY, 4);

// The first SetVertexShaderConstant method binds the c0 register
// with the first row of the view/projection matrix (rows 2, 3 and 4 are
// bound to registers C2, C3 and C4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the c4 register
// with the data for the color green. The last SetVertexShaderConstant
// method binds the c5 register with the first row of the scale matrix
// (rows 2, 3 and 4 are bound to registers C6, C7 and C8). The m3x4 instruction
// (in the shader file) loads the data.


m4x3

Computes the product of the input vector and a 4x3 matrix.

m4x3 dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the m4x3 instruction.

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 3x4 matrix is in register src1 (and the next two higher registers in the same register file--as shown in the expansion below). A 3-D 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 macro instruction is implemented as a pair of dot products as shown below.

m4x3   r5, v0, c3

which is performed as three dot products:
dp4   r5.x, v0, c3
dp4   r5.y, v0, c4
dp4   r5.z, v0, c5

Note that the w-component in c3, c4, and c5 is ignored in this computation unless the input vector has a w-value of 1.0. If this w-value is 0.0, then no translation of the input vector will occur; that is, the translation elements of the matrix will not be applied.

The swizzle and negate modifiers are not allowed on this instruction.

Example

// This example scales the object in the y direction.

// shader file
vs.1.0
mov r0, v0	    	; load vertex position
m4x3 r1, r0, c5		; scale in y
m4x4 oPos, r1, c0	; transform vertices by view/projection matrix

mov oD0, c4	    	; output constant color

// The resultant green object is 3/4 the height and is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// set register c5 (also sets registers c6 and c7)
// 4 rows x 3 cols
float scale4x3[][4] = {{1, 0, 0, 0},{0, 0.75, 0, 0},{0, 0, 1, 0},{0, 0, 0, 1}};
m_pd3dDevice->SetVertexShaderConstant(5, &scale4x3, 4);

// The first SetVertexShaderConstant method binds the c0 register with
// the first row of the view/projection matrix (rows 2, 3 and 4 are bound to
// registers C2, C3 and c4 also). The m4x4 instruction (in the shader file)
// loads the data.
// The second SetVertexShaderConstant method binds the c4 register with
// the data for the color green. The last SetVertexShaderConstant method
// binds the c5 register with the first row of the scale matrix (rows 2, 3 and 4
// are bound to registers C6, C7 and c8 also). The m4x3 instruction (in the
// shader file) loads the data.


m4x4

Computes the product of the input vector and a 4x4 matrix.

m4x4 dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

To learn more about registers, see Registers.

Remarks

The following code fragment shows the operations performed by the m4x4 instruction.

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 in the same register file--as shown in the expansion below).

This operation is commonly used for transforming a position by a projection matrix. This macro instruction is implemented as a series of dot products as shown below.

m4x4   r5, v0, c3

which is performed as four dot products:
dp4   r5.x, v0, c3
dp4   r5.y, v0, c4
dp4   r5.z, v0, c5
dp4   r5.w, v0, c6

The swizzle and negate modifiers are not allowed on this instruction.

Example

// This example transforms the object with the view and projection matrix.

// shader file
vs.1.0
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix
mov oD0, c4 	; output constant color

// The resultant green object is shown below.

// Additional code is used to initialize the constant registers.

D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply(&mat, &matView, &matProj);
D3DXMatrixTranspose(&mat, &mat);
// set C0 with the view and projection matrix
m_pd3dDevice->SetVertexShaderConstant(0, &mat, 4);

// set register c4
float colorGreen[4] = {0, 1, 0, 0};
m_pd3dDevice->SetVertexShaderConstant(4, &colorGreen, 1);

// The first SetVertexShaderConstant method binds the c0 register
// with the first row of the view/projection matrix (rows 2, 3, and 4 are
// bound to registers C2, C3, and c4 also). The m4x4 instruction (in the
// shader file) loads the data.
// The second SetVertexShaderConstant method binds the c4 register
// with the data for the color green.


Registers

This section contains reference information for the input and output registers implemented by the Direct3DX vertex shader assembler. Information is divided into the following topics.

  • Input Registers
  • Output Registers

All registers are four-component floating-point vectors. Vector elements are designated as x, y, z and w in this documentation, but no semantics are implied.


Input Registers

The following table lists the minimum available input registers for use by a Microsoft® DirectX® 8.x vertex shader.

Name | Type | I/O Permissions | Count | Number allowed per instruction | Versions
a0 | address register | write/use only | 1 scalar | 0 in version 1.0; 1 in version 1.1 | 1.0 - 1.1
cn | constant register | read-only | 96 vectors | 1 | 1.0 - 1.1
rn | temporary register | read/write | 12 vectors | 3 | 1.0 - 1.1
vn | vertex register | read-only | 16 vectors | 1 | 1.0 - 1.1

Address Register - a0

a0 registers are the address registers. They are not available in vertex shader version 1.0 of DirectX 8.0, and only a single register is available in version 1.1. The address register, designated as a0.x, can be used as a signed integer offset for relative addressing into the constant register file.

c[a0.x + n]

Reads from out of the legal range will return (0.0, 0.0, 0.0, 0.0). Address registers may be a destination only for the mov instruction. Address registers cannot be read by the vertex shader, just used in relative addressing of the constant register file. Addresses read from outside the range of constant registers supported will return unpredictable results.

Version 1.0 vertex shaders that make any use of the address register will fail the Microsoft Direct3D® application programming interface (API) call to create the vertex shader. Version 1.1 vertex shaders that attempt to use the address register before setting it will also fail.

Constant Registers - cn

cn registers are the constant registers. There are at least 96 four-component floating-point vectors comprising the constant register file. The constant registers are 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, by using an absolute address, or addressed relative to an address register. Reads from out-of-range registers return (0.0, 0.0, 0.0, 0.0).

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 MaxVertexShaderConst member of D3DCAPS8 indicates the number of available constant registers. As shown in the table, vertex shaders support at least 96 constant registers.

The constant register file has its data loaded by calling the Direct3DDevice8::SetVertexShaderConstant. Alternatively, when creating a vertex shader, a user can declare constants in a vertex declaration. These constants are loaded every time Direct3DDevice8::SetVertexShader is called.

Temporary Registers - rn

rn registers are the temporary registers. The temporary registers are grouped into a file of 12 4-D floating point vectors. 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.

Vertex Registers - vn

vn registers are the input vertex registers. Each vertex from one or more input vertex streams is loaded into the vertex input registers before the vertex shader is executed. The vertex input registers are a register file consisting of 16 four-component floating-point vectors, designated as v0 through v15. These registers are read-only.

Any single instruction may access only one vertex input register. However, each source in the instruction may independently swizzle and negate that vector as it is read.

A programmable vertex shader can use up to 16 registers for vertex data.


Output Registers

Vertex shader output registers provide the inputs to the rasterizer. Output data from the vertex shader arithmetic logic unit (ALU) is written into the output registers, which have write-only access. The following table identifies the output register types.

Name | Type | I/O Permissions | Count | Versions
oD0, oD1 | Vertex color registers | write-only | 2 4-D vectors | 1.0, 1.1
oFog | Fog register | write-only | 1 scalar float | 1.0, 1.1
oPos | Position register | write-only | 1 4-D vector | 1.0, 1.1
oPts | Point size register | write-only | 1 scalar float | 1.0, 1.1
oT0 - oT7 | Texture coordinate registers | write-only | 8 4-D vectors | 1.0, 1.1

Register names are preceded by a lowercase o (oh), 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.

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.

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.

Point Size Register - oPts

The output point-size registers. Only the scalar x-component of the point size is used.

Texture Coordinate Register - oT0 - 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.

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 two-dimensional (2-D) 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.

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.


Modifiers

This section contains reference information for the component modifiers implemented by the Direct3DX vertex shader assembler.

As shown in the following table, component modifiers (where r is a valid input registers or any of the output registers) can be applied to the individual components of the vector data.

Component modifier | Description
r.{x}{y}{z}{w} | Destination mask
r.[xyzw][xyzw][xyzw][xywz] | Source swizzle
-r | Source negation

Exceptions

The swizzle and negate modifiers cannot be used on the following vertex shader (m3x2, m3x3, m4x3, m4x4) macro instructions.


Pixel Shader Assembler Reference

Microsoft DirectX 8.1 (pixel shader versions 1.0, 1.1, 1.2, 1.3, 1.4)

Pixel Shader Reference

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 arithmetic logic unit. Registers can also be used by some instructions to hold temporary results.

Architecture

Architecture contains a block diagram of the pixel shader arithmetic logic unit (ALU) and the shader registers.

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 executed 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.

Instructions contains a list of the available instructions.

When multisampling is enabled, pixel shaders only get executed once per pixel, not once for every sub pixel. Multisampling only increases the resolution of polygon edges, as well as depth and stencil tests. For example, if 3×3 multisampling is enabled, and a triangle being rasterized is found to cover 5 of the 9 subpixels for a particular pixel, the pixel shader gets executed once and the same color result is applied to all 5 sub pixels.

Registers

Registers lists the different registers used by the shader arithmetic logic unit.

Modifiers

Modifiers can be used to change the functionality of an instruction, or the data read from or written to a register.

Microsoft® DirectX® 8.x 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 minimize precision loss.


Architecture

The following topics illustrate the features of programmable pixel shaders.

  • Pixel Shader ALU

    • Contains a flow diagram showing what happens to register data as it is processed by the pixel shader processor.

  • Pixel Shader Texture Addressing

    • Contains block diagrams to help visualize how texture data is used by the pixel shader processor.

  • Counting Instructions

    • Details the limits on the number of instructions that can be used in a programmable shader.

  • Instruction Flow

    • Highlights the order of the different types of instructions in pixel shaders.

  • Instruction Pairing

    • Describes how some instructions can be paired to minimize execution time.

  • Order of Operations

    • Shows the order or operations for instructions that use source register modifiers, instruction modifiers, source register selectors, and destination register write masks.


Pixel Shader ALU

The diagram below shows the parallel pipeline structure of a pixel shader arithmetic logic unit (ALU). The left side is the vector pipeline, which operates on vector data. Vector data is also called color data and contains three channels (RGB) of data. The right side is the scalar pipeline, which operates on a single alpha data value. The pipeline is commonly referred to by the data type operated on, so the vector pipeline is commonly called the color pipe and the scalar pipeline is commonly called the alpha pipe.

Pixel shader arithmetic logic unit diagram

The blocks are identified below.

  • Input Registers - Pixel shader registers provide the RGBA input data for a pixel shader.
  • Component Copy - Source register selectors copy data from one channel into other channels. This is commonly called swizzling.
    • Modify Data - Source register modifiers modify data read from source registers before an instruction is executed.
    • Execute Instruction - Instructions are used to perform arithmetic and texture address operations on the pixel data. The color and alpha pipes do not have to execute the same instruction or have the same source registers. For pixel shader version 1.4, destination registers may also be different across the two pipes.
    • Modify Result - Instruction modifiers modify the result of the instruction before it is written to an output register.
  • Masking - Destination register write masks control which components of the destination register are written by the instruction.
  • Output Register - At the end of the shader, pixel shader register r0 contains the output color.


Pixel Shader Texture Addressing

Texture addressing is the mechanism by which texture coordinates are either retrieved directly or used to sample data from a texture.

Texture coordinates can be supplied as part of the vertex format or can be read from certain kinds of texture maps. Texture coordinates are commonly referred to as TCs. A two-dimensional (2-D) texture map is addressed (or looked up) using (UV) coordinates, a 3-D texture map (cube map or volume map) is addressed using (UVW) texture coordinates. Alternately, texture coordinates can be used directly (with no lookup).

Sampling occurs when a texture coordinate is used to address the texel data at a particular location. This is also commonly referred to as performing a texture lookup. In order to sample a texture, it must first be associated with a texture stage. The actual data sampled at the texture coordinate address is controlled by four things.

  1. The pixel shader texture addressing instruction.
  2. The texture coordinates.
  3. The texture set at a texture stage.
  4. The texture sampling attributes set in the texture stage states.

The following diagram shows ways that texture coordinates are used for texture addressing.

Pixel shader texture addressing diagram

For pixel shader version 1.0 to 1.3, texture coordinates are used in three ways:

  • Texture coordinates are used as texture coordinate data. No texture lookup is performed. No texture sampling is done. The texture register is simply loaded with the texture coordinate data.
  • The texture sampler samples a texture at the given texture coordinates. The texture is set at a texture stage. The texture is sampled according to the sampling attributes in the texture stage states. A texture coordinate set and the texture stage number to sample from always correspond to the instruction's destination register number in pixel shader version 1.0 to 1.3.
  • Certain texture addressing instructions in pixel shader version 1.0 to 1.3, such as texbem and texm3x3spec, perform various transformations on input texture coordinates to produce new texture coordinates for texture sampling. In two cases (texdp3 and texm3x3 instructions), a transformation is applied, but the result is passed directly to the destination register without doing any texture sampling.

For pixel shader version 1.4, the texture registers (t#) have a different meaning than previous pixel shader versions. They contain texture coordinates so they should be thought of as texture coordinate registers. These texture coordinate registers are read only (used as source parameters for texture addressing instructions) and are not available to arithmetic instructions.

Having texture coordinates in their own register means that the texture coordinate set and the texture stage number can be different in pixel shader version 1.4 texture addressing instructions. The texture stage number from which to sample is determined by the destination register number, but the texture coordinate set is determined by the new source (t#) register specified.

The "Modify TCs" box in the previous diagram does not apply to pixel shader version 1.4 because modification of texture coordinates before texture sampling is simply accomplished using standard arithmetic instructions, followed by a dependent read. Dependent reads are described in the following diagram and text.

Pixel shader dependent read diagram

Often, it is useful to perform some operation on texture coordinates before using them to sample a texture. This is referred to as a dependent read. The term "dependent" indicates that the texture data that gets sampled depends on some result computed in the pixel shader.

For pixel shader version 1.0 to 1.3, dependent reads are limited to a texture addressing instruction using the result of a previous texture addressing instruction as a source parameter. For pixel shader version 1.4, the dependent reads are much more flexible in that the texture coordinates for a texture sample may be derived from the result of previous texture addressing instructions and/or arbitrary pixel shader arithmetic instructions. Dependent reads in pixel shader version 1.4 always involve an (r#) register being used as the texture coordinates for a texture address instruction. This means that the dependent read only occurs in phase 2. For more information about ordering arithmetic and texture addressing instructions within a shader, see instruction flow.


Counting Instructions

Each shader has a maximum number of instructions allowed. Five types of instructions can be used in a shader: version, constant definition, phase, arithmetic, and texture address. Arithmetic and texture addressing instructions count toward the total number of instructions allowed. Phase, def, and version instructions do not count. These are summarized in the following table.

Instruction type | Version
 | 1.0 | 1.1 | 1.2 | 1.3 | 1.4 phase 1 | 1.4 phase 2
Version | * | * | * | * | * | N/A
Constant definition | * | * | * | * | * | N/A
Phase | N/A | N/A | N/A | N/A | * | *
Arithmetic | 8 | 8 | 8 | 8 | 8 | 8
Texture address | 4 | 4 | 4 | 4 | 6 | 6
Total | 8 | 12 | 12 | 12 | 14 | 14

*Version, constant definition, and phase instructions do not count toward instruction limits.

N/A Not applicable. The phase instruction applies only to pixel shader version 1.4. The version and constant definition instructions can be used only in phase 1.

Instruction count exceptions for pixel shader version 1.0, 1.1, 1.2, 1.3

  • For version 1.0 only, the tex instruction does not count toward the total number of instructions, although it does count toward the total number of texture address instructions.
  • In version 1.0, texbem counts as two texture address instructions. In versions 1.1, 1.2, and 1.3, texbem counts as one texture address instruction.
  • In version 1.0, texbeml counts as two texture address instructions plus one arithmetic instruction. In versions 1.1, 1.2, and 1.3, texbeml counts as one texture address instruction plus one arithmetic instruction.
  • For pixel shader version 1.2 and 1.3, both cmp and dp4 count as two instructions. Unfortunately, this was discovered too late in the development cycle and therefore is not validated properly when calling CreatePixelShader. They are incorrectly being counted as only consuming one instruction. Be sure to manually count each of these instructions as two instructions toward the maximum instruction count. For more information about instruction counts, see Counting Instructions.

Instruction count exceptions for pixel shader version 1.4

  • In version 1.4, only one phase instruction (also commonly called the phase marker) can be used per shader.
  • In version 1.4, bem counts as two arithmetic instructions.
  • Version 1.4 allows 14 instructions in both phase 1 and phase 2, for a total of 28 instructions. If no phase marker is specified, the default is phase 2 and the total instruction count is 14.


Instruction Flow

Pixel shader versions 1.0, 1.1, 1.2, and 1.3 allow four types of instructions. The instructions must appear in the order shown below.

Pixel shader instruction flow diagram for versions 1.0-1.3

Pixel shader version 1.4 adds a phase instruction that allows double the number of texture addressing and arithmetic instructions. The shader is separated into phase 1 and phase 2 by a phase marker. Each phase begins with up to six texture instructions, followed by up to eight arithmetic instructions. If a shader does not contain a phase marker, the shader behaves as if all the instructions are phase 2 instructions.

Pixel shader instruction flow diagram for version 1.4

The structure of a pixel shader version 1.4 shader is therefore:

  • Version instruction (ps.1.4)
  • Constant instructions
  • Up to six texture addressing instructions
  • Up to eight arithmetic instructions
  • Phase marker
  • Up to six texture addressing instructions
  • Up to eight arithmetic instructions

The unfortunate side-effect of the phase transition is that the alpha component of temporary registers are unset or uninitialized during the transition. For additional information, see the phase instruction.


Instruction Efficiency

Microsoft DirectX 8.1 (pixel shader versions 1.0, 1.1, 1.2, 1.3, 1.4)

Instruction Pairing

The pixel shader processor has two parallel pipelines: one for vector processing (RGB) and one for scalar processing (alpha). As a result, pixel shaders allow potentially different arithmetic operations to be performed concurrently in the RGB and alpha pipes.

A destination register write mask can affect how the two pipelines are allocated, but there can be ambiguities in the order of operations unless explicit pairing syntax is used. The following table illustrates the destination register write masks and their associated pipe.

Destination register write mask | Pipe
.a | The operation is in the scalar pipe.
.rgb | The operation is in the vector pipe.
.rgba | The operation is in both the scalar and vector pipes. It already counts as a pair.

Pairing, or co-issuing, is indicated by a plus sign (+) preceding the second instruction of the pair.

mul r0.rgb, t0, v0    // Component-wise multiply of the colors.
+ add r1.a, r1, c2    // Add an alpha component at the same time.

The dot product instructions are a special case. They are vector operations and are always executed in the vector pipeline. However, you still have the option to specify a different instruction in the scalar pipe and still get pairing.

dp3 r0.rgb, t0, v0
+ mul r0.a, r1, c2

For pixel shader version 1.0, the destination register for co-issued instruction pairs must be the same. However, for pixel shader version 1.1 to 1.4, the destination register for co-issued instruction pairs can be different.


Order of Operations

Pixel shaders instructions can be modified by a combination of source register modifiers, instruction modifiers, and destination register write masks. The result of the instruction is determined by the order in which they are executed. The sequence shown below identifies the order in which source register modifiers, instruction modifiers, and destination register write masks are executed.

  1. Execute source register selector(s) and source register modifier(s) .
  2. Execute instruction.
  3. Execute instruction modifier(s).
  4. Update destination register based on destination register write mask(s).

Note The saturate instruction modifier can be combined with any one of the other instruction modifiers. The source register selector(s) and source register modifier(s) may be combined.


Instructions

Pixel shaders contain the following types of instructions.

  • A Version instruction defines the shader version. There is only one version instruction in a shader and it is the first instruction in a shader.
  • Constant instructions define constants. These instructions must be after the version instruction and before any arithmetic or texture address instructions.
  • A Phase instruction splits a shader into two sections: phase 1 and phase 2. Each phase has separate arithmetic and texture address instruction limits. Version 1.4 is the only version that supports the phase instruction.
  • Arithmetic instructions include common mathematical operations such as add and subtract, multiply, and taking a dot product.
  • Texture Address instructions manipulate texture coordinate data that is associated with texture stages.

The instructions are listed below.

Version instructions | Version
 | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
ps | x | x | x | x | x
Constant instructions | Version
 | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
def | x | x | x | x | x
Phase instructions | Version
 | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
phase |  |  |  |  | x
Arithmetic instructions | Version
 | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
add | x | x | x | x | x
bem |  |  |  |  | x
cmp |  |  | x | x | x
cnd | x | x | x | x | x
dp3 | x | x | x | x | x
dp4 |  |  | x | x | x
lrp | x | x | x | x | x
mad | x | x | x | x | x
mov | x | x | x | x | x
mul | x | x | x | x | x
nop | x | x | x | x | x
sub | x | x | x | x | x
Texture address instructions | Version
 | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
tex | x | x | x | x |
texbem | x | x | x | x |
texbeml | x | x | x | x |
texcoord | x | x | x | x |
texcrd |  |  |  |  | x
texdepth |  |  |  |  | x
texdp3 |  |  | x | x |
texdp3tex |  |  | x | x |
texkill | x | x | x | x | x
texld |  |  |  |  | x
texm3x2depth |  |  |  | x |
texm3x2pad | x | x | x | x |
texm3x2tex | x | x | x | x |
texm3x3 |  |  | x | x |
texm3x3pad | x | x | x | x |
texm3x3tex | x | x | x | x |
texm3x3spec | x | x | x | x |
texm3x3vspec | x | x | x | x |
texreg2ar | x | x | x | x |
texreg2gb | x | x | x | x |
texreg2rgb |  |  | x | x |


add

Performs a component-wise add of two registers.

add dest, src0, src1

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.0
 |  |  |  | x | x | 1.1, 1.2, 1.3
 |  |  |  |  | x | 1.4
src0, src1 | Source register | x | x | x | x | 1.0, 1.1, 1.2, 1.3
 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

To learn more about registers, see Registers.

Remarks

This instruction performs a component-wise addition of two registers as shown below.

dest.r = src0.r + src1.r
dest.g = src0.g + src1.g
dest.b = src0.b + src1.b
dest.a = src0.a + src1.a

Example

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

// This example adds the vertex color to the texture color.

// The shader is shown below.
ps.1.0          // Version instruction.
tex t0          // Declare texture. This example requires the DX Logo texture
                // to be set on stage 0.
add r0, t0, t0  // r0 = t0 + t0. This doubles each color component.
                // The effect is to increase image brightness.

// The input texture is shown on the left. The rendered output from the
// pixel shader is shown on the right. In this example, it is brighter
// because the texture color values have been doubled.

// Additional code loads the texture in texture stage 0.
LPDIRECT3DDEVICE8   m_pd3dDevice;   // Init this device pointer in the application.
LPDIRECT3DTEXTURE8  m_pTexture0;    // Use this variable to hold a pointer to the texture.
TCHAR               strPath[512] = "textureFile.jpg";

// Use a helper function from the SDK to load the texture.
D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );


bem

Apply a fake bump environment-map transform.

bem dest.rg, src0, src1

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.4 phase 1
src0 | Source register |  | x |  | x | 1.4 phase 1
src1 |  |  |  |  | x | 1.4 phase 1

To learn more about registers, see Registers.

Remarks

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.


cmp

Conditionally chooses between src1 and src2, based on the comparison src0 >= 0.

cmp dest, src0, src1, src2

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x | x | 1.2, 1.3
 |  |  |  |  | x | 1.4
src0, src1, src2 | Source register | x | x | x | x | 1.2, 1.3
 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

To learn more about registers, see Registers.

Remarks

The comparison is done per channel.

For pixel shader version 1.2 and 1.3, cmp counts as two arithmetic instructions. Unfortunately, this was discovered too late in the development cycle, and therefore is not validated properly when calling CreatePixelShader. It is incorrectly being counted as consuming only one arithmetic instruction. Be sure to manually count this instruction as two arithmetic instructions toward the maximum instruction count. For more information about instruction counts, see Counting Instructions.

In addition, for pixel shader version 1.2 and 1.3, the destination register for cmp cannot be the same as any of the source registers. Validation does not catch this, so be sure to keep this in mind.

Example

This example does a four-channel comparison.

// Compares all four components.
ps.1.4
def c0, -0.6, 0.6, 0, 0.6
def c1  0,0,0,0
def c2  1,1,1,1

cmp r0, c0, c1, c2   // 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

Conditionally chooses between src1 and src2, based on the comparison src0 > 0.5.

cnd dest, src0, src1, src2

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.0
 |  |  |  | x | x | 1.1, 1.2, 1.3
 |  |  |  |  | x | 1.4
src0 | Source register |  |  |  | r0.a | 1.0, 1.1, 1.2, 1.3
src1, src2 |  | x | x | x | x | 1.0, 1.1, 1.2, 1.3
src0, src1, src2 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

To learn more about registers, see Registers.

Remarks

For versions 1.0 to 1.3, src0 must be r0.a. Version 1.4 has no such restriction.

// 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
}

Example

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.

// Version 1.4 compares all four components.
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, to each other.
// This 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.

// The shader is shown below.
ps.1.0                // version instruction
sub r0, v0, v1_bias   // r0 = A - (B - 0.5)
cnd r0, r0.a, c0, c1  // r0 = ( A > B ? c0 : c1 )

// The result in r0 is c0 if A > B. Otherwise, the result in r0 is c1.


def

Provides a method to define constants to be used within the pixel shader.

def dest, fVal0, fVal1, fVal2, fVal3

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  | x |  |  | 1.0, 1.1, 1.2, 1.3, 1.4
fVal0, fVal1, fVal2, fVal3 | Source floating point value | N/A | N/A | N/A | N/A | 1.0, 1.1, 1.2, 1.3, 1.4

N/A Not applicable. The float values do not use registers.

Each of the float values in fVal0, fVal1, fVal2, fVal3 is between -1.0 and 1.0. This is not necessarily the number specified in MAXPIXELSHADERVALUE.

To learn more about registers, see Registers.

Remarks

def instructions must be placed after the version instruction and before any arithmetic or texture address instructions.

The def instruction is an alternative to setting pixel shader constants by calling SetPixelShaderConstant. When SetPixelShader is called, the def instruction is effectively translated into a SetPixelShaderConstant call. Constant registers that are initialized by the def instruction during SetPixelShader, may be overwritten by calling SetPixelShaderConstant manually.

This instruction does not count against the instruction limit. It is stripped from the instruction stream prior to being sent to the driver.

For more information about MAXPIXELSHADERVALUE, see D3DCAPS8.

Example

// This example outputs a constant color.

// The shader is shown below.
ps.1.0                              // version instruction
def c0, 1.0f, 0.0f, 0.0f, 1.0f      // set c0 register
mov r0, c0                          // output constant color


dp3

Calculates a three-component dot product. The scalar result is replicated to all four channels.

dp3 dest, src0, src1

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.0
 |  |  |  | x | x | 1.1, 1.2, 1.3
 |  |  |  |  | x | 1.4
src0, src1 | Source register | x | x | x | x | 1.0, 1.1, 1.2, 1.3
 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

dp3 does not automatically clamp the output result between zero and one. If clamping is necessary, use the saturate modifiers.

dp3 can be co-issued as long as dp3 is writing the color channels and the other instruction is writing the alpha channel.

To learn more about registers, see Registers.

Remarks

This instruction executes 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.

dp3 r0.rgb, t0, v0            // Copy scalar result to RGB components.

An instruction with a destination register RGB 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 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    // Here t0 is a bump map, v0 contains the light direction.

Example

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

This example uses a dot product to square the vertex diffuse color components.

// The shader is shown below.
ps.1.0          // Version instruction.
tex t0          // Declare texture.
dp3 r0, v0, v0  // Dot product squares the vertex color values,
                // color(v0) * color(v0).
                // Bright colors max out at white.
                // Dimmer colors yield gray.

The results of this example are shown below. The input vertex colors are shown on the left. The rendered output from the pixel shader is shown on the right. The left, bottom, and right edges are white because the input color components reach the maximum color value when squared. The center color is gray because the squared color values are lower where the input colors blend together.

Additional code loads a texture in texture stage 0
LPDIRECT3DDEVICE8   m_pd3dDevice;     // Initialize the pointer before using.
LPDIRECT3DTEXTURE8  m_pTexture0;      // Use this variable to hold a pointer to the texture.
TCHAR               strPath[512] = "textureFile.jpg";

D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );


dp4

Calculates a four-component dot product. The scalar result is replicated to all channels.

dp4 dest, src0, src1

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.2, 1.3
 |  |  |  |  | x | 1.4
src0, src1 | Source register | x | x | x | x | 1.2, 1.3
 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

This instruction cannot be co-issued.

This instruction does not automatically clamp the output result between zero and one. If clamping is necessary, use the saturate modifier.

To learn more about registers, see Registers.

Remarks

This instruction executes in both the vector and alpha pipeline.

dp4 r0, t0, v0      // Copy scalar result to RGBA components.

For pixel shader version 1.2 and 1.3, dp4 counts as two arithmetic instructions. Unfortunately, this was discovered too late in the development cycle and therefore is not validated properly when calling CreatePixelShader. It is being incorrectly counted as consuming only one arithmetic instruction. Be sure to manually count this instruction as two arithmetic instructions toward the maximum instruction count. For more information about instruction counts, see Counting Instructions.

In addition, for pixel shader version 1.2 and 1.3, the destination register for dp4 cannot be the same as any of the source registers. Validation does not catch this, so be sure to keep this in mind.


lrp

Interpolates linearly between the second and third source registers by a proportion specified in the first source register.

lrp dest, src0, src1, src2

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.0
 |  |  |  | x | x | 1.1, 1.2, 1.3
 |  |  |  |  | x | 1.4
src0, src1, src2 | Source register | x | x | x | x | 1.0, 1.1, 1.2, 1.3
 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

To learn more about registers, see Registers.

Remarks

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)

Example

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

// This example combines a texture color with a diffuse color value.

// The shader is shown below.
ps.1.0              // Version instruction.
tex t0              // Declare texture.
lrp r0, t0, v0, t0  // Blend from v0 to t0 by t0 amount.

// The input colors and the output colors are shown below. The first image
// (src0) determines the amount of the second image (src1) and the third image
// (src2) that are blended to make the final image (dest). Where the first image
// is white, the second image appears in the output. Where the first image is
// black, the third images appears in the output. Where the first is gray, the
// final image contains color values from the second and third image.

// Additional code loads the texture in texture stage 0.
LPDIRECT3DDEVICE8   m_pd3dDevice;   // initialize the pointer
LPDIRECT3DTEXTURE8  m_pTexture0;    // a pointer to the texture.
TCHAR               strPath[512] = "textureFile.jpg";

D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );


mad

Multiply and add instruction. Sets the destination register to (src0 * src1) + src2.

mad dest, src0, src1, src2

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.0
 |  |  |  | x | x | 1.1, 1.2, 1.3
 |  |  |  |  | x | 1.4
src0, src1, src2 | Source register | x | x | x | x | 1.0, 1.1, 1.2, 1.3
 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

To learn more about registers, see Registers.

Remarks

This instruction performs a multiply accumulate operation based on the following formula.

dest = src0 * src1 + src2

Example

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

// This example blends a diffuse color, a texture color and a constant color.

// The shader is shown below.
ps.1.0              // Version instruction.
tex t0              // Declare texture.
mad r0, v0, t0, v0  // Mix diffuse color and texture color.

// The following four images show the contents of the three source registers
// and the resulting output register. The output register shows the result of
// the gradient in the center of the destination image, where the mid tones
// appear. This is a result of adding the pixels from the center of src2 with
// the pixel color created from the center of the product of src0*src1.

// Additional code loads a texture in texture stage 0.
LPDIRECT3DDEVICE8   m_pd3dDevice;   // initialize this pointer
LPDIRECT3DTEXTURE8  m_pTexture0;    // a pointer to the texture.
TCHAR               strPath[512] = "textureFile.jpg";

D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );


mov

Copies the contents of the source to the destination.

mov dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.0
 |  |  |  | x | x | 1.1, 1.2, 1.3
 |  |  |  |  | x | 1.4
src | Source register | x | x | x | x | 1.0, 1.1, 1.2, 1.3
 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

To learn more about registers, see Registers.

Example

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

// This example copies the texture color to the output.

// The shader is shown below.
ps.1.0          // Version instruction
tex t0          // Declare texture.
mov r0, t0      // Move texture to output.

// The following images show the contents of the source register and
// the resulting destination register. The images are identical because
// the mov instruction was used.

// Additional code loads the texture in texture stage 0.
LPDIRECT3DDEVICE8   m_pd3dDevice;   // Init this device pointer in the application.
LPDIRECT3DTEXTURE8  m_pTexture0;    // Use this variable to hold a pointer to the texture.
TCHAR               strPath[512] = "textureFile.jpg";

D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );


mul

Multiplies the components of two source registers. The result is dest = src0 * src1.

mul dest, src0, src1

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.0
 |  |  |  | x | x | 1.1, 1.2, 1.3
 |  |  |  |  | x | 1.4
src0, src1 | Source register | x | x | x | x | 1.0, 1.1, 1.2, 1.3
 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

To learn more about registers, see Registers.

Example

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

// This example combines the texture color and the diffuse color.

// The shader is shown below.
ps.1.0              // Version instruction
tex t0              // Declare texture.
mul r0, v0, t0      // Multiply diffuse color with gradient texture.

// The following images show the contents of the source registers the
// resulting output register.
// Where src1 is white, the destination pixel color is the same as the
// source pixel color since dest = src * 1.0.
// Where src1 is black, the destination is also black.
// The pixel colors in the middle of the destination image are a blend
// of src0 and src1.

// Additional code loads a texture in texture stage 0.
LPDIRECT3DDEVICE8   m_pd3dDevice;   // Init this device pointer in the application.
LPDIRECT3DTEXTURE8  m_pTexture0;    // Use this variable to hold a pointer to the texture.
TCHAR               strPath[512] = "textureFile.jpg";

D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );


nop

No operation is performed.

nop

Registers

None

Remarks

This instruction performs a no-op, or no operation. The syntax for calling it is as follows:

nop


phase

The phase instruction marks the transition between phase 1 and phase 2. If no phase instruction is present, the entire shader if executed as if it is a phase 2 shader.

phase

Remarks

This instruction applies to version 1.4 only.

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 are unset or uninitialized during the transition.

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 executed 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.


ps

Provides the method to specify the version of the shader code.

ps.mainVer.subVer

Registers

Argument | Description | Values
mainVer | main version number | 1
subVer | sub version number | 0, 1, 2, 3, 4

Remarks

This instruction must be the first instruction in a shader.

Example

// This example declares a version 1.0 shader.
ps.1.0

// This example declares a version 1.4 shader.
ps.1.4


sub

Performs subtraction. Subtracts the second source register from the first source register.

sub dest, src0, src1

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.0
 |  |  |  | x | x | 1.1, 1.2, 1.3
 |  |  |  |  | x | 1.4
src0, src1 | Source register | x | x | x | x | 1.0, 1.1, 1.2, 1.3
 |  |  | x |  | x | 1.4 phase 1
 |  | x | x |  | x | 1.4 phase 2

To learn more about registers, see Registers.

Remarks

This instruction performs the subtraction based on the following formula.

dest = src0 - src1

Example

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

// This example subtracts texture color from the diffuse color.

// The shader is shown below.
ps.1.0              // Version instruction
tex t0              // Declare texture.
sub r0, v0, t0      // Subtract texture color from diffuse color.

// The following images show the contents of the source registers and
// the resulting destination register. The colors in the second image (src1)
// are subtracted from the color in the first image (src0) to make the
// resulting image (dest).

// Additional code loads the texture in texture stage 0.
LPDIRECT3DDEVICE8   m_pd3dDevice;   // Init this device pointer in the application.
LPDIRECT3DTEXTURE8  m_pTexture0;    // Use this variable to hold a pointer to the texture.
TCHAR  			strPath[512] = "textureFile.jpg";

D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );


tex

Loads the destination register with color data (RGBA) sampled from a texture.

The texture must be bound to a particular texture stage (n) using SetTexture. Texture sampling is controlled by the texture stage state attributes, set with SetTextureStageState.

tex dest

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

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 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.

Example

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

// This example applies a texture to a quad.

// The shader is shown below.
ps.1.0        // version instruction
tex t0        // samples the texture at stage 0 using texture coordinates from stage 0
mov r0, t0    // copies the color in t0 to output register r0

// The rendered output from the pixel shader is shown below. It is
// simply a texture map applied to a quad object.

// Additional code is required to use this shader and an example
// scenario is shown below.

// Load the texture in texture stage 0.
LPDIRECT3DDEVICE8   m_pd3dDevice;	// Initialize the pointer before using
LPDIRECT3DTEXTURE8  m_pTexture0;	// a pointer for the texture
TCHAR               strPath[512] = "DX5_Logo.bmp";
// Helper function from the SDK
D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );

// This code creates the shader from a file. The contents of the shader
// file can also be supplied as a text string.
TCHAR               strPShaderPath[512];
LPD3DXBUFFER        pCode;
// Helper function from the SDK
DXUtil_FindMediaFile( strPShaderPath, _T("shaderFile.txt") );

// Assemble the vertex shader from the file.
D3DXAssembleShaderFromFile( strPShaderPath, 0, NULL, &pCode, NULL );
m_pd3dDevice->CreatePixelShader((DWORD*)pCode->GetBufferPointer(),
                   &m_hPixelShader );
pCode->Release();

// Define 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, 1.0f, },
    { +1.0f, -1.0f, 0.0f, 1.0f, 1.0f, },
    { +1.0f, +1.0f, 0.0f, 1.0f, 0.0f, },
    { -1.0f, +1.0f, 0.0f, 0.0f, 0.0f, },
    // v1 is flipped to meet the top down convention in Windows
    // the upper left texture coordinate is (0,0)
    // the lower right texture coordinate is (1,1).
};

// Create and fill the quad vertex buffer.
m_pd3dDevice->CreateVertexBuffer( 4*sizeof(CUSTOMVERTEX),
        D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX,
        D3DPOOL_MANAGED, &m_pQuadVB );

CUSTOMVERTEX* pVertices = NULL;
m_pQuadVB->Lock( 0, 4*sizeof(CUSTOMVERTEX), (BYTE**)&pVertices, 0 );
for( DWORD i=0; i<4; i++ )
    pVertices[i] = g_Vertices[i];

m_pQuadVB->Unlock();

// Check to see if the hardware supports pixel shaders.
if( D3DSHADER_VERSION_MAJOR( pCaps->PixelShaderVersion ) < 1 )
    return E_FAIL;

// Set up the transforms.
D3DXVECTOR3 from( 0, 0, -5.0f );
D3DXVECTOR3 at( 0.0f, 0.0f, 0.0f );
D3DXVECTOR3 up( 0.0f, 1.0f, 0.0f );

D3DXMATRIX matWorld;
D3DXMatrixIdentity( &matWorld );
m_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

D3DXMATRIX matView;
D3DXMatrixLookAtLH( &matView, &from, &at, &up );
m_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

D3DXMATRIX matProj;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 0.5f, 1000.0f );
m_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );

// Render the output.
// Clear the back buffer to black.
m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET, 0x00000000, 1.0f, 0L );

// Set device state.
m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
m_pd3dDevice->SetRenderState( D3DRS_CLIPPING, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_ZENABLE,  FALSE );

m_pd3dDevice->SetTexture( 0, m_pTexture0 );
m_pd3dDevice->SetStreamSource( 0, m_pQuadVB, sizeof(CUSTOMVERTEX) );
m_pd3dDevice->SetVertexShader( D3DFVF_CUSTOMVERTEX );
m_pd3dDevice->SetPixelShader( m_hPixelShader );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );
m_pd3dDevice->SetTexture( 0, NULL );


texbem

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 two-dimensional (2-D) bump environment matrix.

texbem dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

The red and green color data in the src register is interpreted as the perturbation data (du,dv).

To learn more about registers, see Registers.

Remarks

This instruction transforms red and green components in the source register using the 2-D 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 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 CONST_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.

Note When using texbem or texbeml, do not re-read the source register later in the shader because the data within the register might be corrupted. The shader validation allows this even though the result will be undefined.

Example

// Here is an example shader with the texture maps identified and
// the texture stages identified.
ps.1.0
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

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 two-dimensional (2-D) bump environment matrix, and luminance.

texbeml dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

The red and green color data in the src register is interpreted as the perturbation data (du,dv).

To learn more about registers, see Registers.

Remarks

This instruction transforms the red and green components in the source register using the 2-D 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 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 CONST_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))]

Note When using texbem or texbeml, do not re-read the source register later in the shader because the data within the register might be corrupted. The shader validation allows this even though the result will be undefined.

Example

// Here is an example shader with the texture maps identified and
// the texture stages identified.
ps.1.0
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

Interprets texture coordinate data (UVW1) as color data (RGBA).

texcoord dest

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

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, once 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 SetTexture and by specifying how the texture sampling is done using SetTextureStageState. If the fixed function pipeline is used, be sure to supply the TSS_TEXCOORDINDEX flag.

// This instruction is used as follows:
texcoord tn

// A texture register (tn) contains four color values (RGBA). The data can also be
// thought of as vector data (xyzw). Texcoord will retrieve 3 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.

Example

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.0        ; 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.

// 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.
TCHAR               strPShaderPath[512];
LPD3DXBUFFER        pCode;
DXUtil_FindMediaFile( strPShaderPath, _T("shaderFile.txt") );

// 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

Copies texture coordinate data from the source texture coordinate iterator register as color data in the destination register.

texcrd dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.4
src | Source register |  |  | x |  | 1.4 phase 1
 |  |  |  | x |  | 1.4 phase 2

To learn more about registers, see Registers.

Remarks

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 [-D3DCAPS8.MaxTextureRepeat, D3DCAPS8.MaxTextureRepeat], while the destination register (r#) can hold data only in the (likely smaller) range [-D3DCAPS8.MaxPixelShaderValue, D3DCAPS8.MaxPixelShaderValue]. Note that for pixel shader version 1.4, D3DCAPS8.MaxPixelShaderValue 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 CONST_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 simply 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.

Example

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.

texcrd  r(m).rgb, t(n).xyz
// 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)
// Produces the same result as the previous instruction.

texcrd  r(m).rgb, t(n).xyw
// Puts first, second, and fourth components of t(n) into first three channels
// of r(m). The fourth channel of r(m) is uninitialized.

// Here is a projective divide example using the _dw modifier.
texcrd  r(m).rg,  t(n)_dw.xyw

// 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.


texdepth

Calculate depth values to be used in the depth buffer comparison test for this pixel.

texdepth dest

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | r5 | 1.4 phase 2 only

To learn more about registers, see Registers.

Remarks

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 executes once per pixel, the single depth value output by texm3x2depth or texdepth will be used for each of the sub-pixel depth comparison tests.

Example

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

Performs a three-component dot product between data in the texture register number and the texture coordinate set corresponding to the destination register number.

texdp3 dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.2, 1.3
src | Source register |  |  | x |  | 1.2, 1.3

Remarks

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

Performs a three-component dot product and uses the result to do a 1-D texture lookup.

texdp3tex dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.2, 1.3
src | Source register |  |  | x |  | 1.2, 1.3

Remarks

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 1-D 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 1-D lookup.
t(m)RGBA = TextureSample(stage m)RGBA using (u',0,0) as coordinates.


texkill

texkill src

Cancels rendering of the current pixel if any of the first three components (UVW) of the texture coordinates is less than zero.

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
 |  |  |  | x | x | 1.4 phase 2 only

To learn more about registers, see Registers.

Remarks

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 ( any of the first 3 components of TextureCoordinates(stage n)UVWQ < 0 )
  cancel pixel render

For ps 1.0, 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 iterator 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.

Example

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.
// The shader is shown below.
ps.1.0       // 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. It shows
// vertex color data applied to a plane. 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, },

};

// 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 colored 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.


texld

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 dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.4
src | Source register |  |  | x |  | 1.4 phase 1
 |  |  |  | x | x | 1.4 phase 2

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 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 flags 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 read(s), this can be mixed with other read(s) 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.

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 1-D, 2-D, or 3-D texture.

texld  r(m), t(n)
// Same as previous.

texld  r(m), t(n).xyw
// Uses xyw (skipping z) from t(n) to sample 1-D, 2-D or 3-D texture.

texld  r(m), t(n)_dw.xyw
// Samples 1-D or 2-D 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 1-D, 2-D, or 3-D 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 1-D or 2-D 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.


texm3x2depth

Calculate the depth value to be used in depth testing for this pixel.

texm3x2depth dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.3
src | Source register |  |  | x |  | 1.3

To learn more about registers, see Registers.

Remarks

This instruction must be used with the texm3x2pad 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 executing 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 executes once per pixel, the single depth value output by texm3x2depth/texdepth will be used for each of the sub-pixel depth comparison tests.


texm3x2pad

Performs the first row multiplication of a two-row matrix multiply. This instruction must be combined with either texm3x2tex or texm3x2depth. Refer to either of these instructions for details on using texm3x2pad.

texm3x2pad dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

This instruction cannot be used by itself.


texm3x2tex

Performs the final row of a 3×2 matrix multiply and uses the result to do a texture lookup. texm3x2tex must be used in conjunction with the texm3x2pad instruction.

texm3x2tex dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

The instruction is used as one of two instructions representing a 3×2 matrix multiply operation. This instruction must be used with the texm3x2pad.

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 3×2 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.

Example

// Here is an example shader with the texture maps and
// the texture stages identified.
ps.1.0
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 2-D texture set at
// that texture stage.


texm3x3

Performs a 3×3 matrix multiply when used in conjunction with two texm3x3pad instructions.

texm3x3 dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.2, 1.3
src | Source register |  |  | x |  | 1.2, 1.3

Remarks

This instruction is the same as the texm3x3tex instruction, without the texture lookup.

This instruction is used as the final of three instructions representing a 3×3 matrix multiply operation. The 3×3 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 3×3 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

Performs the first or second row multiply of a three-row matrix multiply. This instruction must be used in combination with texm3x3, texm3x3spec, texm3x3vspec, or texm3x3tex.

texm3x3pad dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

This instruction cannot be used by itself.


texm3x3spec

Performs a 3×3 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 instructions.

texm3x3spec dest, src0, src1, src2

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src0, src1 | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src2 |  |  | x |  |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

This instruction performs the final row of a 3×3 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 3×3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

The 3×3 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.

Example

// Here is an example shader with the texture maps and
// the texture stages identified.
ps.1.0
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 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 3×3 matrix.
// Any texture assigned to stage m is ignored.
//
// Texture coordinate set m+1 is assigned to row 2 of the 3×3 matrix.
// Any texture assigned to stage m+1 is ignored.
//
// Texture coordinate set m+2 is assigned to row 3 of the 3×3 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

Performs a 3×3 matrix multiply and uses the result to do a texture lookup. texm3x3tex must be used with two texm3x3pad instructions.

texm3x3tex dest, src

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

This instruction is used as the final of three instructions representing a 3×3 matrix multiply operation, followed by a texture lookup. The 3×3 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 3×3 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 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.
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 3×3 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.

Example

// Here is an example shader with the texture maps identified and
// the texture stages identified.
ps.1.0
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 stage 3
mov r0, t3            // 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 3×3 matrix.
// Any texture assigned to stage 1 is ignored.
//
// Texture coordinate set 2 is assigned to row 2 of the 3×3 matrix.
// Any texture assigned to stage 2 is ignored.
//
// Texture coordinate set 3 is assigned to row 3 of the 3×3 matrix.
// A volume or cube texture should be set to stage 3  for lookup by the
// transformed 3-D vector.
//


texm3x3vspec

Performs a 3×3 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 instructions.

If the eye-ray vector is constant, the texm3x3spec instruction will perform the same matrix multiply and texture lookup.

texm3x3vspec dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

This instruction performs the final row of a 3×3 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, except that the eye-ray vector is taken from the fourth component of the texture coordinates. The 3×3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

The 3×3 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.

Example

// Here is an example shader with the texture maps identified and
// the texture stages identified.
ps.1.0
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 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 3×3 matrix.
// Any texture assigned to stage m is ignored.
//
// Texture coordinate set m+1 is assigned to row 2 of the 3×3 matrix.
// Any texture assigned to stage m+1 is ignored.
//
// Texture coordinate set m+2 is assigned to row 3 of the 3×3 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

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.

texreg2ar dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

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

// 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)RGBA = TextureSample(stage m)RGBA using t(n)AR as coordinates.

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 CONST_D3DFORMAT.


texreg2gb

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.

texreg2gb dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.0, 1.1, 1.2, 1.3
src | Source register |  |  | x |  | 1.0, 1.1, 1.2, 1.3

To learn more about registers, see Registers.

Remarks

This instruction is useful for color-space remapping operations.

// Here is an example of the sequence the instruction follows.
tex t(n)
texreg2gb 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)RGBA = TextureSample(stage m)RGBA using t(n)GB as coordinates.

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 CONST_D3DFORMAT.


texreg2rgb

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.

texreg2rgb dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  | x |  | 1.2, 1.3
src | Source register |  |  | x |  | 1.2, 1.3

Remarks

This instruction is useful for color-space remapping operations. It supports two-dimensional (2-D) and three-dimensional (3-D) coordinates. It can be used just like the texreg2ar or texreg2gb to remap 2-D data. However, this instruction also supports 3-D data so it can be used with cube maps and 3-D 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

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 Count. 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

Registers transfer data to the shader ALU and store temporary results. The table below identifies the four types of registers and the number available in each shader version.

Register name | Type | Versions
 |  | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
cn | Constant register | 8 | 8 | 8 | 8 | 8
rn | Temporary register | 2 | 2 | 2 | 2 | 6
tn | Texture register | 4 | 4 | 4 | 4 | 6
vn | Color register | 2 | 2 | 2 | 2 | 2 in phase 2

  • Constant registers contain constant data organized in four fixed-point values. Data can be loaded into a constant register using SetPixelShaderConstant or it can be defined using the def shader instruction. Constant registers are not usable by texture address instructions. The only exception is the texm3x3spec instruction, which uses a constant register to supply an eye-ray vector.
    •
  • Temporary registers are used to store intermediate results, as four fixed-point values. 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 pre-processing will fail CreatePixelShader on any shader that attempts to read from a temporary register that has not been written by a previous instruction.
  • Texture registers
    • Pixel shader version 1.1 to 1.3

      • For pixel shader version 1.1 to 1.3, texture registers contain texture data, organized in four fixed-point values. 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.0, texture registers are read-only to arithmetic instructions.

    • Pixel shader version 1.4

      • 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.

      For this pixel shader version, texture registers contain texture coordinate data and are also available to texture addressing instructions as source parameters.

  • 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. Color registers store data in four fixed-point values. 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 application 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 is 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.

Register name | Type | Versions
 |  | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
cn | Constant register | 2 | 2 | 2 | 2 | 2
rn | Temporary register | 2 | 2 | 2 | 2 | 3
tn | Texture register | 1 | 2 | 3 | 3 | 1
vn | Color register | 1 | 2 | 2 | 2 | 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. As shown in the table, two color registers can be used in every version except 1.0.

mad r0, v0, v1, v1  // This is valid for versions 1.1, 1.2, 1.3, 1.4.

Any valid destination register can be used in the same instruction because read port count restrictions do not affect destination registers.

Destination registers are independent of the read port count restrictions.

For co-issued instructions, the maximum number of different registers (of the same type) that can be used across two co-issued instructions is three. This is true for all shader versions.

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.

Register name | Type | Versions
 |  | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
cn | Constant register | RO | RO | RO | RO | RO
rn | Temporary register | RW | RW | RW | RW | RW
tn | Texture register | See following note | RW | RW | RW | RO
vn | Color register | RO | 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.0, texture registers are RW for texture addressing instructions, but RO for arithmetic instructions.
  • 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 GetDeviceCaps.

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.


Modifiers

Modifiers are used to modify instructions, source registers, and destination registers.

  • Instruction modifiers
  • Source register modifiers
  • Source register selectors
  • Destination register write masks

Texture Register Modifiers

Pixel shader version 1.4 includes two new instructions, texld and texcrd, which contain custom register modifier functionality. These instructions support different register modifiers, register selectors, and register write masks. For more information, see Texture Register Modifiers.


Instruction Modifiers

Use instruction modifiers to change the output of an instruction. 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 executes but before writing the result to the destination register.

A list of the modifiers is shown below.

Modifier | Description | Syntax | Version
 |  |  | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
_x2 | Multiply by 2 | register_x2 | X | X | X | X | X
_x4 | Multiply by 4 | register_x4 | X | X | X | X | X
_x8 | Multiply by 8 | register_x8 |  |  |  |  | X
_d2 | Divide by 2 | register_d2 | X | X | X | X | X
_d4 | Divide by 4 | register_d4 |  |  |  |  | X
_d8 | Divide by 8 | register_d8 |  |  |  |  | X
_sat | Saturate (clamp from 0 and 1) | register_sat | X | 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.

Examples

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 Microsoft® DirectX® 6.0 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


Register Modifiers

Microsoft Directx 8.1 (pixel shader versions 1.0, 1.1, 1.2, 1.3, 1.4)

Source Register Modifiers

Use source register modifiers to change the value read from a register before an instruction executes. 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.

Version 1.4 shaders have modifier functionality specific to shader instructions texld and texcrd. These modifiers affect version 1.4 texture registers and are detailed in Texture Register Modifiers.

Source register modifiers | Syntax | Version
 |  | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
Bias | register_bias | X | X | X | X | X
Invert | 1 - register | X | X | X | X | X
Negate | - register | X | X | X | X | X
Scale×2 | register_x2 |  |  |  |  | X
Signed Scaling | register_bx2 | X | 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 signed scale modifier (_bx2). For version 1.0 and 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 scale×2 modifier. When combined, negate is executed last.
  • Invert cannot be combined with any other modifier.
  • Invert, negate, bias, signed scaling, and scale×2 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.


Bias

source register_bias

Subtract 0.5 from all components.

Register

Source register. For more about register types, see 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 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 Microsoft® DirectX® 6.0 and 7.0 multiple texture syntax.

add r0, r0, t0_bias    ; Shift down by 0.5.


Invert

1 - source register

Performs a (1 - value) calculation for each channel of the specified register.

Register

Source register. For more about register types, see 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 source register modifiers.

Example

This example uses inversion to generate the complement of register r1.

mul r0, r0, 1-r1    ; Multiply by (1.0 – r1).


Negate

- source register

Performs a negate (y = -x), on all register components.

Register

Source register. For more about register types, see 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 Invert so it cannot be applied to the same register.

This modifier is for use with the arithmetic instructions.

Example

The following example shows how to use this modifier.

mul r0, r0, -v1    ; Multiply by specular color.


Scale x 2

source register_x2

Multiply the value by two before using it in the instruction.

Register

Source register. For more about register types, see 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 Invert, so it cannot be applied to the same register.

This modifier is only available to arithmetic instructions in version 1.4.


Signed Scaling

source register_bx2

Subtracts 0.5 from each channel and scales the result by 2.0. The name "bx2" comes from "bias times two," which is the operation it performs.

Register

Source register. For more about register types, see Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register.

The signed scaling operation is applied to the data read from the register before the next instruction is executed. The operation is applied to all four color channels (RGBA) as follows:

y = 2(x – 0.5)

This operation is commonly used to expand data from [0.0 to 1.0] to [-1.0 to 1.0]. Using _bx2 on data outside the range 0 to 1 may produce undefined results.

This modifier is designed for use with the arithmetic instructions. This modifier is commonly used on inputs to the dot product instruction (dp3).

This modifier is mutually exclusive with Invert so it cannot be applied to the same register.

For shader versions 1.0 and 1.1, input arguments to any of the texture address instructions of the form texm3x2* and texm3x3* can use the _bx2 modifier.

For shader versions 1.2 and 1.3, the source register to any tex* instruction can use the _bx2 modifier.

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.


Source Register Selectors

This modifier replicates a single channel of a source-register argument to all channels.

source register.channel

Source register selectors | Syntax | Version
 |  | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
Red replicate | source register.r |  |  |  |  | X
Green replicate | source register.g |  |  |  |  | X
Blue replicate | source register.b |  | X | X | X | X
Alpha replicate | source register.a | X | X | X | X | X

  • Red replicate. Replicates the red channel to all channels.
  • Green replicate. Replicates the green channel to all channels.
  • Blue replicate. Replicates the blue channel to all channels.
  • Alpha replicate. Replicates the alpha channel to to all channels.

Register

Source register. For more about register types, see Registers.

In version 1.1, 1.2, and 1.3, blue replicate is available only on the source register of arithmetic instruction, which uses an alpha destination register write mask.

Remarks

Source register selectors are applied before any source register modifiers and before the instruction executes.

Copying the contents of a channel into one or more other channels is commonly referred to as "swizzling."

These selectors are valid on source registers for arithmetic instructions. The four selectors operate on different channels.

An alternate syntax for the r,g,b,a channels is x,y,z,w.

Source selectors and source modifiers may be combined freely. In this example, register r0 uses the invert, bias, and signed scaling modifier, as well as the green selector. The contents of the source register are unaffected; the modifier modifies only the data read.

-r0_bx2.g

To understand the order of the execution of these modifiers and selectors, see Order of Operations.

This operator can be used in conjunction with the Invert or Negate operators.

Alpha replicate functionality is analogous to the D3DTA_ALPHAREPLICATE flag in the Microsoft® DirectX® 6.0 and 7.0 multitexture syntax.

Example

The examples below illustrate each of the four selectors.

// Replicate the red color channel to the all channels before
// doing the multiply.
mul r0, r0, r1.r    // the result is r1.rgba = r1.r

// Replicate the green color channel to the all channels before
// doing the multiply.
mul r0, r0, r1.g    // the result is r1.rgba = r1.g

// Replicate the blue color channel to the all channels before
// doing the multiply.
mul r0, r0, r1.b    // the result is r1.rgba = r1.b

// For ps 1.1, 1.2, 1.3, the blue replicate example
// would require a destination write mask.
mul r0.a, r0, r1.b

// alpha replicate
mul r0, r0, r1.a    ; Replicate the alpha color channel to all channels.


Register Write Masks

Microsoft DirectX 8.1 (pixel shader versions 1.0, 1.1, 1.2, 1.3, 1.4)

Destination Register Write Masks

destination register.writemask

Write masks control which channels (red, green, blue, alpha) are updated in the destination register.

Register

Destination register. For more about register types, see Registers.

Remarks

The following destination write masks are available.

Write Mask | Syntax | Version
 |  | 1.0 | 1.1 | 1.2 | 1.3 | 1.4
red, green, blue, alpha | destination register.rgba | X | X | X | X | X
none | destination register | X | X | X | X | X
color (red, green, blue) | destination register.rgb | X | X | X | X | X
alpha | destination register.a | X | X | X | X | X
red | destination register.r |  |  |  |  | X
green | destination register.g |  |  |  |  | X
blue | destination register.b |  |  |  |  | X
arbitrary | destination register.rgba |  |  |  |  | See note below.

Note 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 only in version 1.4.

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.

An alternate syntax for the r,g,b,a channels is x,y,z,w.

For versions 1.0 to 1.3, the 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 and texld.

Examples

default

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

alpha write mask

The alpha write mask is used to control writing to the alpha channel.

// 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.

color write mask

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

arbitrary write mask

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

co-issued instructions

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.

// For example, the default example shown above:
mul r0, t0, v0

// is also equivalent to the following co-issued instruction
  mul r0.rgb, t0, v0
+ mul r0.a,   t0, v0

The advantage of pairing instructions this way is that it allows different operations to be performed in the vector and scalar pipeline in parallel.


Texture Register Modifiers

Microsoft Directx 8.1 (pixel shader version 1.4)

Texture Register Modifiers for texld and texcrd

Two pixel shader version 1.4 texture address instructions, texld and texcrd, have custom syntax. These instructions support their own set of source register modifiers, source register selectors, and destination-register write masks, as shown below.

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 | Version
_dz | Divide x,y components by z | source register_dz | 1.4
_db |  | source register_db | 1.4
_dw | Divide x,y components by w | source register_dw | 1.4
_da |  | source register_da | 1.4

Register

Source register. For more about register types, see Registers.

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

Note For pixel shader version 1.4, the D3DTTFF_PROJECTED flag under D3DTSS_TEXTURETRANSFORMFLAGS is ignored because a projective divide is accomplished by the source register modifiers listed previously.

Source Register Selectors for texld and texcrd

Selectors replicate the contents of one channel into other channels. Replicating the contents of a channel to one or more other channels is commonly referred to as "swizzling."

Source register selectors | Description | Syntax | Version
xyz | Maps x,y,z data to channels x,y,z,z | source register.xyz | 1.4
rgb |  | source register.rgb | 1.4
xyw | Maps x,y,w data to channels x,y,w,w | source register.xyw | 1.4
rga |  | source register.rga | 1.4

Register

Source register. For more about register types, see Registers.

Remarks

The texld and texcrd instructions never read more than the first three components. So, these selectors provide the option of taking the third component from either the third or the fourth component of the source register.

Destination Register Write Masks for texld and texcrd

Write masks control which channels (red, green, blue, alpha) are updated in the destination register.

Destination register write masks | Description | Syntax | Used by | Version
xyzw | Updates the x,y,z,w channels | destination register.xyzw | texld only | 1.4
rgba |  | destination register.rgba | texld only | 1.4
none |  | destination register | texld only | 1.4
xyz | Updates the x,y,z channels | destination register.xyz | texcrd only | 1.4
rgb |  | destination register.rgb | texcrd only | 1.4
xy | Updates the x,y channels | destination register.xy | texcrd only | 1.4
rg |  | destination register.rg | texcrd only | 1.4

Register

Destination register. For more about register types, see Registers.


X File Visual Basic Reference

This section contains reference information for the API elements used to work with Microsoft® DirectX® X files.

  • Classes
  • Enumerations
  • Error Codes
  • X File Format Reference


Classes

This section contains reference information for the classes used to read to and write from X files in Microsoft® DirectX®.

  • DirectXFile
  • DirectXFileBinary
  • DirectXFileData
  • DirectXFileEnum
  • DirectXFileObject
  • DirectXFileReference
  • DirectXFileSave


DirectXFile

Applications use the methods of the DirectXFile class to create DirectXFileEnumObject and DirectXFileSaveObject objects, and to register templates.

The DirectXFile class is obtained by calling the DirectX8.DirectXFileCreate method.

The methods of the DirectXFile class can be organized into the following groups.

Creation | CreateEnumObject
 | CreateSaveObject
Templates | RegisterDefaultTemplates
 | RegisterTemplates

The globally unique identifier (GUID) for the DirectXFile class is IID_IDirectXFile.


DirectXFile.CreateEnumObject

Creates an enumerator object.

object.CreateEnumObject( _
    FileName As String) As DirectXFileEnum

Parts

object
Object expression that resolves to a DirectXFile object.
FileName
String value set to the file name.

Return Values

Returns a DirectXFileEnum object, representing the created enumerator object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADFILEFLOATSIZE
DXFILEERR_BADFILETYPE
DXFILEERR_BADFILEVERSION
DXFILEERR_BADRESOURCE
DXFILEERR_BADVALUE
DXFILEERR_FILENOTFOUND
DXFILEERR_RESOURCENOTFOUND
DXFILEERR_URLNOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

After using this method, use one of the DirectXFileEnum methods to retrieve a data object.

See Also

DirectXFileEnum


DirectXFile.CreateSaveObject

Creates a save object.

object.CreateSaveObject( _
    FileName As String, _
    Flags As Long) As DirectXFileSave

Parts

object
Object expression that resolves to a DirectXFile object.
FileName
String value, identifying the file to use for saving data.
Flags
A member of the CONST_DXFILEFORMATFLAGS enumeration indicating the format to use when saving the DirectX file.

Return Values

Returns a DirectXFileSave object, representing the created save object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADFILE
DXFILEERR_BADVALUE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

After using this method, use methods of the DirectXFileSave class 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.

See Also

DirectXFileSave


DirectXFile.RegisterDefaultTemplates

Registers the default templates.

object.RegisterDefaultTemplates()

Parts

object
Object expression that resolves to a DirectXFile object.

Error Codes

If the method fails, an error is raised and Err.Number is set.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFile.RegisterTemplates

Registers custom templates.

object.RegisterTemplates( _
    TemplateData As Any, _
    Size As Long)

Parts

object
Object expression that resolves to a DirectXFile object.
TemplateData
Buffer consisting of a Microsoft® DirectX® file in text or binary format that contains templates.
Size
Size of the TemplateData buffer, in bytes.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADFILEFLOATSIZE
DXFILEERR_BADFILETYPE
DXFILEERR_BADFILEVERSION
DXFILEERR_BADVALUE
DXFILEERR_PARSEERROR

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

All templates must specify a name and a Universally Unique Identifier (UUID).


DirectXFileBinary

Applications use the methods of the DirectXFileBinary class to read and retrieve information about binary data.

The methods of the IDirectXFileBinary object can be organized into the following groups.

Information | GetMimeType
 | GetSize
Reading Data | Read

This class inherits additional functionality from the DirectXFileObject class.

The globally unique identifier (GUID) for the DirectXFileBinary class is IID_IDirectXFileBinary.


DirectXFileBinary.GetMimeType

Retrieves the Multipurpose Internet Mail Extensions (MIME) type for the binary data.

object.GetMimeType() As String

Parts

object
Object expression that resolves to a DirectXFileBinary object.

Return Values

Returns a String value set to the file's MIME type.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DXFILEERR_BADVALUE.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

When there is no MIME type specified in a Microsoft® DirectX® file for a binary object, the function will return an empty string.


DirectXFileBinary.GetSize

Retrieves the size of the binary data.

object.GetSize() As Long

Parts

object
Object expression that resolves to a DirectXFileBinary object.

Return Values

Returns a Long value set to the size of the binary data, in bytes.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DXFILEERR_BADVALUE.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFileBinary.Read

Reads the binary data.

object.Read( _
    Data As Any, _
    Size As Long) As Long

Parts

object
Object expression that resolves to a DirectXFileBinary object.
Data
Buffer that receives the data that has been read.
Size
Long value containing the size of the Data buffer, in bytes.

Return Values

Returns a Long value set to the number of bytes actually read.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOMOREDATA

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFileData

Applications use the methods of the DirectXFileData class 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.

The methods of the DirectXFileData class can be organized into the following groups.

Add Data | AddBinaryObject
 | AddDataObject
 | AddDataReference
Information | GetDataSize
 | GetType
Retrieve Data | GetData
 | GetDataFromOffset
 | GetNextObject

This class inherits additional functionality from the DirectXFileObject class.

The globally unique identifier (GUID) for the DirectXFileData class is IID_IDirectXFileData.


DirectXFileData.AddBinaryObject

Creates a binary object and adds it as a child object.

object.AddBinaryObject( _
    Name As String, _
    GuidObject As String, _
    MimeType As String, _
    Data As Any, _
    Size As Long)

Parts

object
Object expression that resolves to a DirectXFileData object.
Name
String value containing the object's name. Specify an empty string if the object does not need a name.
GuidObject
String value containing the globally unique identifier (GUID) that represents the object. Specify an empty string if the object does not need a GUID.
MimeType
String value containing the object's MIME type.
Data
Buffer containing the object's data.
Size
Long value containing the size of the Data buffer, in bytes.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

DirectXFileBinary.GetMimeType


DirectXFileData.AddDataObject

Adds a data object as a child object.

object.AddDataObject( _
    Data As DirectXFileData)

Parts

object
Object expression that resolves to a DirectXFileData object.
Data
DirectXFileData object, representing the file data object to add as a child object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Use the DirectXFileSave.CreateDataObject method to create the DirectXFileData object before calling this method.

See Also

DirectXFileSave.CreateDataObject


DirectXFileData.AddDataReference

Creates and adds a data reference object as a child object.

object.AddDataReference( _
    Name As String, _
    Guid As String)

Parts

object
Object expression that resolves to a DirectXFileData object.
Name
String value containing the name of the referenced data object. This parameter can be an empty string if Guid provides a reference to the globally unique identifier (GUID).
Guid
String value containing the GUID that represents the data. This parameter can be an empty string if Name provides a reference to the name.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

For this method to succeed, either the Name or Guid parameter must be a non-empty string.


DirectXFileData.GetData

Retrieves the data for one of the object's members or the data for all members.

object.GetData( _
    Name As String, _
    Data As Any)

Parts

object
Object expression that resolves to a DirectXFileData object.
Name
String value containing the name of the member for which to retrieve data. Specify an empty string to retrieve all required members' data.
Data
Buffer to receive the data associated with Name. If Name is an empty string, Data is set to a buffer containing all required members' data in a contiguous block of memory.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADARRAYSIZE
DXFILEERR_BADDATAREFERENCE
DXFILEERR_BADVALUE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method retrieves the data for required members of a data object but no data for optional (child) members. Use DirectXFileData.GetNextObject to retrieve child objects.

See Also

DirectXFileData.GetNextObject


DirectXFileData.GetDataFromOffset

Retrieves data starting from a specified offset.

object.GetDataFromOffset( _
    Name As String, _
    Offset As Long, _
    ByteCount As Long, _
    Data As Any)

Parts

object
Object expression that resolves to a DirectXFileData object.
Name
String value containing the name of the member for which to retrieve data. Specify an empty string to retrieve all required members' data.
Offset
Long value containing the offset into the data buffer.
ByteCount
The size of the data to retrieve, in bytes.
Data
Buffer to receive the data associated with Name. If Name is an empty string, Data is set to a buffer containing all required members' data in a contiguous block of memory.

Error Codes

If the method fails, an error is raised and Err.Number is set.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

DirectXFileData.GetDataSize


DirectXFileData.GetDataSize

Retrieves the data size of the specified member.

object.GetDataSize( _
    Name As String) As Long

Parts

object
Object expression that resolves to a DirectXFileData object.
Name
String value containing the name of the member for which to retrieve the data size.

Return Values

Returns a Long value that is set to the data size, in bytes.

Error Codes

If the method fails, an error is raised and Err.Number is set.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFileData.GetNextObject

Retrieves the next child data object, data reference object, or binary object in the Microsoft® DirectX® file.

object.GetNextObject() As DirectXFileObject

Parts

object
Object expression that resolves to a DirectXFileData object.

Return Values

Returns a DirectXFileObject object, representing the returned child object's file object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOMOREOBJECTS

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFileData.GetType

Retrieves the globally unique identifier (GUID) of the object's template.

object.GetType() As String

Parts

object
Object expression that resolves to a DirectXFileData object.

Return Values

Returns a String value containing the GUID of the object's template.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DXFILEERR_BADVALUE.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFileEnum

Applications use the methods of the DirectXFileEnum class 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.

The methods of the DirectXFileEnum class can be organized into the following groups.

Object Retrieval | GetDataObjectById
 | GetDataObjectByName
Enumeration | GetNextDataObject

The globally unique identifier (GUID) for the DirectXFileEnum class is IID_IDirectXFileEnumObject.


DirectXFileEnum.GetDataObjectById

Retrieves a data object specified by its globally unique identifier (GUID).

object.GetDataObjectById( _
    ID As String, _
    RetVal As DirectXFileData)

Parts

object
Object expression that resolves to a DirectXFileEnum object.
ID
String value set to the object's GUID.
RetVal
DirectXFileData object, representing the returned file data object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFileEnum.GetDataObjectByName

Retrieves the data object that has the specified name.

object.GetDataObjectByName( _
    ID As String, _
    RetVal As DirectXFileData)

Parts

object
Object expression that resolves to a DirectXFileEnum object.
ID
String value containing the object's name.
RetVal
DirectXFileData object, representing the returned file data object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFileEnum.GetNextDataObject

Retrieves the next top-level object in the Microsoft® DirectX® file.

object.GetNextDataObject() As DirectXFileData

Parts

object
Object expression that resolves to a DirectXFileEnum object.

Return Values

Returns a DirectXFileData object, representing the returned file data object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOMOREOBJECTS

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

Top-level objects are always data objects. Data reference objects and binary objects can only be children of data objects.


DirectXFileObject

Applications use the methods of the DirectXFileObject class to retrieve information about Microsoft® DirectX® file objects.

The methods of the DirectXFileObject class can be organized into the following group.

Information | GetId
 | GetName

The globally unique identifier (GUID) for the DirectXFileObject class is IID_IDirectXFileObject.


DirectXFileObject.GetId

Retrieves the globally unique identifier (GUID) that identifies a Microsoft® DirectX® file object.

object.GetId() As String

Parts

object
Object expression that resolves to a DirectXFileObject object.

Return Values

Returns a String containing the object's GUID.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DXFILEERR_BADVALUE.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from DirectXFileObject.

  • DirectXFileBinary
  • DirectXFileData

Remarks

Returns a String value containing the file's GUID.


DirectXFileObject.GetName

Retrieves a Microsoft® DirectX® file object's name.

object.GetName() As String

Parts

object
Object expression that resolves to a DirectXFileObject object.

Return Values

Returns a String value containing the object's name.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Applies To

This method applies to the following classes, which implement methods from DirectXFileObject.

  • DirectXFileBinary
  • DirectXFileData


DirectXFileReference

Applications use the methods of the DirectXFileReference class 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.

This interface has the following method:
  • Resolve

This interface inherits additional functionality from the DirectXFileObject interface.

After you have determined that an object is a data reference object, use the DirectXFileReference.Resolve method to retrieve the referenced object defined earlier in the file.

For information on how to identify a data reference object, see the DirectXFileData class.

The globally unique identifier (GUID) for the DirectXFileReference class is IID_IDirectXFileDataReference.


DirectXFileReference.Resolve

Resolves data references.

object.Resolve() As DirectXFileData

Parts

object
Object expression that resolves to a DirectXFileReference object.

Return Values

DirectXFileData object, representing the returned file data object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOTFOUND

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFileSave

Applications use the methods of the DirectXFileSave class 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.

The DirectXFileSave class is obtained by calling the DirectXFile.CreateSaveObject method.

The methods of the DirectXFileSave class can be organized into the following group.

Creation | CreateDataObject
Saving | SaveData
 | SaveTemplates

The globally unique identifier (GUID) for the DirectXFileSave class is IID_IDirectXFileSaveObject.


DirectXFileSave.CreateDataObject

Creates a data object.

object.CreateDataObject( _
    TemplateGuid As String, _
    Name As String, _
    DataTypeGuid As String, _
    ByteCount As Long, _
    Data As Any) As DirectXFileData

Parts

object
Object expression that resolves to a DirectXFileSave object.
TemplateGuid
String value containing the data object's template globally unique identifier (GUID).
Name
String value containing the object's name. Specify an empty string if the object does not have a name.
DataTypeGuid
String value containing the data object's GUID. Specify an empty string if the object does not have a GUID.
ByteCount
Long value containing the size of the data object, in bytes.
Data
Buffer containing all required member's data.

Return Values

DirectXFileData object, representing the created file data object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

If a data reference object will reference the data object, either the Name or DataTypeGuid parameter must be a non-empty string.

Save any templates by using the DirectXFileSave.SaveTemplates method before saving the data created by this method. Save the created data by using the DirectXFileSave.SaveData method.

If you need to save optional data, use the DirectXFileData.AddDataObject method after using this method and before using SaveData. If the object has child objects, add them before calling SaveData.

See Also

DirectXFileData.AddDataObject, DirectXFileSave.SaveData, DirectXFileSave.SaveTemplates


DirectXFileSave.SaveData

Saves a data object and its children to a Microsoft® DirectX® file.

object.SaveData( _
    DataObj As DirectXFileData)

Parts

object
Object expression that resolves to a DirectXFileSave object.
DataObj
DirectXFileData object, representing the file data object to save.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

DXFILEERR_BADARRAYSIZE
DXFILEERR_BADVALUE

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.


DirectXFileSave.SaveTemplates

Saves templates to a Microsoft® DirectX® file.

object.SaveTemplates( _
    Count As Long, _
    TemplateGuids() As String)

Parts

object
Object expression that resolves to a DirectXFileSave object.
Count
Total number of templates to save.
TemplateGuids
Array of String values containing the GUIDs for all templates to save.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DXFILEERR_BADVALUE.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

See Also

DirectXFileSave.CreateDataObject


Enumerations

This section contains information about the enumerations used with DirectX® files.

  • CONST_DXFILEERR
  • CONST_DXFILEFORMATFLAGS


CONST_DXFILEERR

Defines file error codes raised by the system. For descriptions of these error codes, see Error Codes.


CONST_DXFILEFORMATFLAGS

Defines constants that describe the fill mode.

Enum CONST_DXFILEFORMATFLAGS
    DXFILEFORMAT_BINARY     = 0
    DXFILEFORMAT_TEXT       = 1
    DXFILEFORMAT_COMPRESSED = 2
End Enum

Constants

DXFILEFORMAT_BINARY
Indicates a binary file.
DXFILEFORMAT_COMPRESSED
Indicates a compressed file.
DXFILEFORMAT_TEXT
Indicates a text file.

See Also

D3DX8.SaveMeshToX , DirectXFile.CreateSaveObject


Error Codes

The methods used to work with Microsoft® DirectX® X (.x) files can return the following error codes in addition to standard error codes.

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_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 Microsoft® DirectX® .x file format.

  • X File Templates
  • Binary Format


X File Templates

This section lists and details the following .x file templates.

  • Animation
  • AnimationKey
  • AnimationOptions
  • AnimationSet
  • Boolean
  • Boolean2d
  • ColorRGB
  • ColorRGBA
  • Coords2d
  • FloatKeys
  • Frame
  • FrameTransformMatrix
  • Header
  • IndexedColor
  • Material
  • Matrix4x4
  • Mesh
  • MeshFace
  • MeshFaceWraps
  • MeshTextureCoords
  • MeshMaterialList
  • MeshNormals
  • MeshVertexColors
  • Patch
  • PatchMesh
  • Quaternion
  • SkinWeights
  • TextureFilename
  • TimedFloatKeys
  • Vector
  • VertexDuplicationIndices
  • XSkinMeshHeader


Header

The following definitions should be used when directly reading and writing the binary header. Note that 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))


Vector

Defines a vector.

UUID

<3D82AB5E-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
x | FLOAT |  | None
y | FLOAT |  |
z | FLOAT |  |


Coords2d

A two dimensional vector used to define a mesh's texture coordinates.

UUID

<F6F23F44-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
u | FLOAT |  | None
v | FLOAT |  |


Quaternion

Currently unused.

UUID

<10DD46A3-775B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
s | FLOAT |  | None
v | Vector |  |


Matrix4x4

Defines a 4×4 matrix. This is used as a frame transformation matrix.

UUID

<F6F23F45-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
matrix | array FLOAT | 16 | None


ColorRGBA

Defines a color object with an alpha component. This is used for the face color in the material template definition.

UUID

<35FF44E0-6C7C-11cf-8F52-0040333594A3>

Member name | Type | Optional array Size | Optional data objects
red | FLOAT |  | None
green | FLOAT |  |
blue | FLOAT |  |
alpha | FLOAT |  |


ColorRGB

Defines the basic RGB color object.

UUID

<D3E16E81-7835-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
red | FLOAT |  | None
green | FLOAT |  |
blue | FLOAT |  |


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.

UUID

<1630B820-7842-11cf-8F52-0040333594A3>

Member name | Type | Optional array size
index | DWORD |
indexColor | ColorRGBA |


Boolean

Defines a simple Boolean type. This template should be set to 0 or 1.

UUID

<4885AE61-78E8-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
truefalse | DWORD |  | None


Boolean2d

Defines a set of two Boolean values used in the MeshFaceWraps template to define the texture topology of an individual face.

UUID

<4885AE63-78E8-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
u | Boolean |  | None
v | Boolean |  |


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 that the ambient color requires an alpha component.

TextureFilename is an optional data object. If this object is not present, the face is untextured.

UUID

<3D82AB4D-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
faceColor | ColorRGBA |  | Any
power | FLOAT |  |
specularColor | ColorRGB |  |
emissiveColor | ColorRGB |  |


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.

UUID

<A42790E1-7810-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
filename | STRING |  | None


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.

UUID

<3D82AB5F-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
nFaceVertexIndices | DWORD |  | None
faceVertexIndices | array DWORD | nFaceVertexIndicies |


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.

UUID

<4885AE62-78E8-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nFaceWrapValues | DWORD |  | None
faceWrapValues | Boolean2d |  |


MeshTextureCoords

Defines a mesh's texture coordinates.

UUID

<F6F23F40-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nTextureCoords | DWORD |  | None
textureCoords | array Coords2d | nTextureCoords |


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.

UUID

<F6F23F43-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nNormals | DWORD |  | None
normals | array Vector | nNormals |
nFaceNormals | DWORD |  |
faceNormals | array MeshFace | nFaceNormals |


MeshVertexColors

Specifies vertex colors for a mesh, instead of applying a material per face or per mesh.

UUID

<1630B821-7842-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nVertexColors | DWORD |  | None
vertexColors | array IndexedColor | nVertexColors |


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.

UUID

<F6F23F42-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nMaterials | DWORD |  | Material
nFaceIndexes | DWORD |  |
FaceIndexes | array DWORD | nFaceIndexes |


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.

UUID

<3D82AB44-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
nVertices | DWORD |  | Any
vertices | array Vector | nVertices |
nFaces | DWORD |  |
faces | array MeshFace | nFaces |

Optional Data Elements

The following optional data elements can be used.

Data element | Description
MeshFaceWraps | If this is not present, wrapping for both u and v defaults to false.
MeshTextureCoords | If this is not present, there are no texture coordinates.
MeshNormals | If this is not present, normals are generated using the GenerateNormals method of the API.
MeshVertexColors | If this is not present, the colors default to white.
MeshMaterialList | If this is not present, the material defaults to white.


FrameTransformMatrix

Defines a local transform for a frame (and all its child objects).

UUID

<F6F23F41-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
frameMatrix | Matrix4x4 |  | None


Frame

Defines a frame. Currently, the frame can contain objects of the type Mesh and a FrameTransformMatrix.

UUID

<3D82AB46-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
None |  |  | Any

Optional Data Elements

The following optional elements can be used.

Data element | Description
FrameTransformMatrix | If this element is not present, no local transform is applied to the frame.
Mesh | Any number of mesh objects that become children of the frame. These objects can be specified inline or by reference.


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.

UUID

<10DD46A9-775B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nValues | DWORD |  | None
values | array FLOAT | nValues |


TimedFloatKeys

Defines a set of floats and a positive time used in animations.

UUID

<F406B180-7B3B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
time | DWORD |  | None
tfkeys | FloatKeys |  |


AnimationKey

Defines a set of animation keys. The keyType member specifies whether the keys are rotation, scale, position, or matrix keys (using the integers 0, 1, 2, or 4 respectively). A matrix key is useful for sets of animation data that need to be represented as transformation matrices.

UUID

<10DD46A8-775B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
keyType | DWORD |  | None
nKeys | DWORD |  |
keys | array TimedFloatKeys | nKeys |


AnimationOptions

Enables you to set the animation options. The openclosed member can be either 0 for a closed or 1 for an open animation. The positionquality member is used to set the position quality for any position keys specified and can either be 0 for spline positions or 1 for linear positions. By default, an animation is closed.

UUID

<E2BF56C0-840F-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
openclosed | DWORD |  | None
positionquality | DWORD |  |


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.

UUID

<3D82AB4F-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
None |  |  | Any

Optional Data Elements

The following optional data elements are used.

Data element | Description
AnimationKey | All animations require AnimationKeys.
AnimationOptions | If this element is not present, an animation is closed.


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.

UUID

<3D82AB50-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
None |  |  | Animation


Patch

Defines a bézier control patch. The array defines the control points for the patch.

UUID

<A3EB5D44-FC22-429D-9AFB-3221CB9719A6>

Member name | Type | Optional array size | Optional data objects
nControlIndices | DWORD |  | None
controlIndices | array DWORD | nControlIndices |

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 (Rectangular) 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.

UUID

<D02C95CC-EDBA-4305-9B5D-1820D7704BBF>

Member name | Type | Optional array size | Optional data objects
nVertices | DWORD |  | None
vertices | array Vector | nVertices |
nPatches | DWORD |  |
patches | array Patch | nPatches |

The patches use the vertices in the array of vertices as the control points for each patch.


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.

UUID

<B8D65549-D7C9-4995-89CF-53A9A8B031E3>

Member name | Type | Optional array size | Optional data objects
nIndices | DWORD |  | None
nOriginalVertices | DWORD |  |
indices | array DWORD | nIndices |

The number of vertices in the mesh before any duplication occurred is nOriginalVertices. 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. So any indices in this array that are the same indicate duplicate vertices.


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.

UUID

<3CF169CE-FF7C-44ab-93C0-F78F62D172E2>

Member name | Type | Optional array size | Optional data objects
nMaxSkinWeightsPerVertex | WORD |  | None
nMaxSkinWeightsPerFace | WORD |  |
nBones | WORD |  |

The maximum number of transforms that affect a vertex in the mesh is nMaxSkinWeightsPerVertex. The maximum number of unique transforms that affect the three vertices of any face is nMaxSkinWeightsPerFace. The number of bones that affect vertices in this mesh is nBones.


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.

UUID

<6F0D123B-BAD2-4167-A0D0-80224F25FABB>

Member name | Type | Optional array size | Optional data objects
transformNodeName | STRING |  | None
nWeights | DWORD |  |
vertexIndices | array DWORD | nWeights |
weights | array float | nWeights |
matrixOffset | Matrix4x4 |  |

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.


Binary Format

This section details the binary version of the Microsoft® DirectX® .x file format as introduced with the release of DirectX 3.0. The information presented in this section should be read in conjunction with the X File Architecture section.

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


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

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 × 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 size specified 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 × count | Float or double list


Examples

Two example binary template definitions and an example of a binary data object follow. Note that 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. Note that data is stored in little-endian format, which is not shown in this example.

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


DirectX Audio

This section provides information about using Microsoft® DirectX® to play and capture sounds in applications.

Like other components of DirectX, DirectX Audio can be used with C, C++, and Microsoft® Visual Basic®. This Help file is specific to Visual Basic.

For an overview of the organization of the DirectX Audio Help, see Roadmap.


Roadmap

Information on DirectX Audio is presented in the following sections:

  • What's New in DirectX Audio. New features and functionality of this component in Microsoft® DirectX® 8.0. If you've used Microsoft® DirectSound® or Microsoft® DirectMusic® before, read this section first, because much has changed since DirectX 7.0.
  • Introduction to DirectX Audio. An overview of what DirectX Audio is and what it can do for your application, together with a first look at some important objects and the steps involved in playing audio.
  • Understanding DirectX Audio. A deeper look at the underlying mechanisms. This section won't teach you how to implement audio playback or capture in your application, but it will help you understand the application programming interface (API).
  • Using DirectX Audio. A guide to using the 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. Use it in conjunction with the reference section.
  • Advanced Topics in DirectX Audio. Information of interest mostly for developing specialized applications or applications that need highly optimized performance.
  • Programming Tips and Tools. Miscellaneous information about compiling and debugging DirectX Audio applications.
  • DirectX Audio Visual Basic Tutorials. Step-by-step implementation of basic functionality. If you're the kind of person who learns best by doing, this is a good place to start.
  • DirectX Audio Visual Basic 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 DirectX Audio.
  • DirectMusic Visual Basic Reference. Detailed information on the DirectMusic API elements in the DirectX for Visual Basic® type library.
  • DirectSound Visual Basic Reference. Detailed information on the DirectSound API elements in the DirectX for Visual Basic type library.

DirectMusic Producer

Microsoft DirectMusic Producer is a powerful authoring application included with the DirectX SDK. It enables composers to create dynamic musical elements that can be incorporated in an application.

If your focus is more on sound design than on application development, you might want to start with DirectMusic Producer Help, which is installed with that application.

If you're an application developer and just want an overview of the material you'll be working with, see Compositional Music Elements.


What's New in DirectX Audio

The audio components of Microsoft® DirectX® have undergone a major revision. Microsoft® DirectMusic® and Microsoft® DirectSound® are now a more unified API for playing sounds of all kinds, and many new capabilities have been added.

The following list describes some of the new features:

Integration of waves and message-based sounds in a single playback mechanism

Wave files and resources can now be loaded by the DirectMusic loader and played by the DirectMusic performance. The application no longer needs to parse the wave and copy or stream it to a DirectSound buffer. The timing of wave playback is based on the DirectMusic master clock, and waves can be synchronized to musical events and processed by tools just like any other segment.

The DirectSound API continues to be supported, and you can still play waves directly through DirectSound buffers. DirectSound continues to be the API for wave capture and full duplex.

More flexible and powerful audiopath model

In previous versions of DirectMusic, performance channels were mapped to ports, and each port sent its output to a single DirectSound buffer. Under the new model, channels in a segment are mapped to audiopaths that control the data flow from the performance to the final output. Output from the synthesizer can be sent to multiple playback buffers, each with its own 3-D positioning and effects. Audiopaths can be created dynamically by the application or authored into segments.

DirectX for Microsoft® Visual Basic® applications using DirectMusic must employ the audiopath model. Direct access to ports is no longer supported.

Individual control over segment states

Each playing instance of a segment can have its own audiopath, so parameters such as volume, pan, and pitch bend can be modified for each segment state individually.

DLS2 Synthesis

The DirectMusic synthesizer is now based on the Downloadable Sounds (DLS) Level 2 standard, providing higher-quality sound synthesis. New features of the DLS2 synthesizer include six-stage envelopes, layering of voices, release waveforms, and additional low-frequency oscillators (LFOs). Each voice has an optional low-pass resonant filter.

Special effects

DirectX Media Objects can be attached to sound buffers to add effects. Standard effects such as musical reverb, I3DL2 (Interactive 3-D Audio Level 2) environmental reverb, distortion, and echo are provided by DirectX Audio, and third-party effects can be added.

Greater control over cueing

A composer can set points in a segment that specify where the segment can begin playback, so that the segment can maintain its relationship to the time signature. Primary segments can contain arbitrary points where other segments can be cued, allowing greater control than cueing to the nearest measure, beat, or grid. A new segment cue flag, DMUS_SEGF_SEGMENTEND, causes the segment to play when the current primary segment finishes playing.

Notification of impending silence

The performance notification event has a new notification type, DMUS_NOTIFICATION_MUSICALMOSTEND, which indicates that the last primary segment in the queue is about to end. This notification gives the application a chance to schedule a new segment.

Enhanced MIDI controller support

Curve messages now support RPN and NRPN controller changes.

Infinite repetition of segments

The new DMUS_SEG_REPEAT_INFINITE flag allows a segment to play for an indefinite time.

Simplified downloading and unloading of bands

Bands can be downloaded and unloaded with a simple method call on the segment object.

Dynamic track data generation

New track configuration and play flags allow tracks to be recomposed each time the segment is played or looped. For example, a chordmap track can be configured to establish a new chord progression each time the segment plays.


Introduction to DirectX Audio

  • The Power of DirectX Audio
  • Getting Started with DirectX Audio


The Power of DirectX Audio

DirectX Audio does much more than simply play sounds. It provides a complete system for implementing a dynamic soundtrack that takes advantage of hardware acceleration, Downloadable Sounds (DLS), DirectX Media Objects (DMOs), and advanced 3-D positioning effects.

By using the DirectMusic and DirectSound interfaces in your application, you can do the following:

  • Load and play sounds from files or resources in MIDI, wave, or DirectMusic Producer run time format.
  • Play from multiple sources simultaneously.
  • Schedule the timing of musical events with high precision.
  • Send tempo changes, patch changes, and other MIDI events programmatically.
  • Use Downloadable Sounds. By using the DLS synthesizer, an application can be sure that message-based music sounds the same on all computers. An application can also play an unlimited variety of instruments and even produce unique sounds for individual notes and velocities.
  • Locate sounds in a 3-D environment.
  • Easily apply pitch changes, reverb, and other effects to sounds.
  • Use more than 16 MIDI channels. DirectX Audio breaks through the 16-channel limitation and makes it possible for any number of voices to be played simultaneously, up to the limits of the synthesizer.
  • Play segments on different audiopaths, so that effects or spatialization can be applied individually to each sound.
  • Capture MIDI data or stream ("thru") it from one port to another.
  • Capture wave sounds from a microphone or other input.

If you use source files from DirectMusic Producer or a similar application, you can do much more:

  • Control many more aspects of playback at run time, for example by choosing a different set of musical variations or altering the chord progression.
  • Play music that varies subtly each time it repeats.
  • Play waves with variations.
  • Map performance channels to audiopaths, so that different parts within the same segment can have different effects.
  • Compose wholly new pieces of music at run time, not generated algorithmically but based on components supplied by a human composer.
  • Dynamically compose transitions between existing pieces of music.
  • Cue transitions, motifs, and sound effects to occur at specified rhythmic points in the performance.

Also part of DirectX Audio is DirectMusic Producer, an application that enables composers to create DLS collections, chordmaps, styles, and segments—the pieces that let you take full advantage of the power of DirectMusic. DirectMusic Producer also makes it possible to create playable segments that contain multiple time-stamped waves. These waves can be in compressed or uncompressed format and can be either streamed at run time or wholly contained in memory.

As an application developer, you might never use DirectMusic Producer yourself, but it is a good idea to have a broad understanding of what it does so that you can work effectively with your sound design team. For an introduction from the application designer's perspective, see Compositional Music Elements. For more detail, see the DirectMusic Producer documentation.

DirectX Audio delivers full functionality on Microsoft® Windows® 98 and Microsoft® Windows® 2000. However, support for hardware synthesizers is available only on Windows 2000 and Windows 98 Second Edition.


Getting Started with DirectX Audio

Creating your first DirectX Audio application does not require a lot of setup. Presumably you have already installed the current version of DirectX and have the paths to the header files set up in your development environment. You must also be able to link to the DirectX library files in the \lib folder. The necessary DLLs and the default DLS collection (used by the software synthesizer) were placed in your system directory as part of the SDK installation.

Apart from that, all you need are a sound card, speakers or headphones, and some sounds. Any of the following will do:

  • MIDI (.mid) files.
  • Wave (.wav) files.
  • Segment (.sgt) files from DirectMusic Producer. Sample files are installed along with that application, and others are included with the DirectX sample applications.

For now, you can ignore the other kinds of files you'll find with DirectMusic Producer. Chordmaps, styles, bands, and DLS files are building blocks for playable segments but aren't playable themselves. Segments can also be obtained from container files, but it requires a bit of extra work to extract them.

More information on getting started is included in the following topics:

  • Basic Concepts of DirectX Audio
  • Basic Steps in Playing Sounds
  • Building DirectX Audio Projects


Basic Concepts of DirectX Audio

This section is an introduction to some of the key concepts of DirectX Audio and the objects that implement them.

DirectX is based on the Component Object Model (COM), so all functionality is performed by objects. In addition, source data is encapsulated in objects.

The objects discussed in this section are exposed in every DirectX Audio application, other than those using only DirectSound. Many other objects are at work behind the scenes and can be accessed by more advanced applications, but they are not discussed here.

The following topics are discussed:

  • Loader
  • Segments and Segment States
  • Performance
  • Messages
  • Performance Channels
  • DLS Synthesizer
  • Instruments and Downloading
  • Audiopaths and Buffers


Loader

The loader (DirectMusicLoader8) is an object that gets other objects. It is usually one of the first objects created in a DirectX Audio application.

Data objects parse themselves, and the entire loading process is carried out automatically. All you need to do is call the appropriate method of DirectMusicLoader8.


Segments and Segment States

Segments are objects encapsulating sequenced sound data. The data might be a MIDI sequence, a wave, a collection of information originating in a segment file from DirectMusic Producer, or a piece of music composed at run time from different components. In general, a segment is a piece of music or other sound that is played as a unit.

A segment can be played as a primary segment or secondary segment. Only one primary segment can be played at a time. Secondary segments are typically short musical motifs or sound effects played over the primary segment.

Segments originating as MIDI or wave files sound the same each time they are played, unless the application performs some special processing on them. A segment authored in DirectMusic Producer, on the other hand, can contain different musical patterns and other information that allows variation each time the segment is played.

Segments can combine different kinds of data such as waves, patterns, chord changes, band changes, and tempo changes. Each type of data is encapsulated in a track object. Applications written in Visual Basic do not have access to track objects. Segments can also contain information about the audiopath on which they should be played, including special effects.

DirectMusic Producer segments can also contain references to other loadable musical components. For example, it is possible to obtain a band object from a segment authored with that band.

Each time a segment is played, a segment state object is created. The application can use this object to get information about the state of playback and the audiopath for that instance of the playing segment.


Performance

The performance object manages the flow of data from the source to the synthesizer. Typically an application has only a single performance.

The performance handles timing, the mapping of data channels to audiopaths, the routing of messages, tool management, notifications, and other important tasks.


Messages

Audio data flows through the performance in the form of messages. Performance messages are similar to MIDI messages but contain more information and a greater variety of information. A message could contain information about a musical note, a wave, or a controller change. It might even contain text for a display of lyrics.

Most applications don't deal directly with messages, which are generated by tracks when a segment is playing. However, it is possible for an application to insert messages into the performance.

Messages are also used for notifications. Applications can request that an event be signaled whenever certain points in the performance are reached—for example, on every beat of the music. Information about the event is contained in a performance message.


Performance Channels

Every playing sound consists of one or more parts. A part might be a MIDI channel, a part in a DirectMusic Producer segment, or a wave. Often a part corresponds to a single musical instrument.

A performance channel is the route between a part and an audiopath. Every message that contains information about a part also specifies the part's performance channel, so that it can be routed correctly.

Performance channels are similar to MIDI channels, but whereas traditional MIDI playback is limited to 16 channels, the number of performance channels is virtually unlimited.


DLS Synthesizer

Data that is not already in the form of a wave—a MIDI note, for example—has to be converted to a wave form before it can be played by the sound card. This conversion is done by a synthesizer.

Although DirectX Audio supports basic MIDI synthesis on some operating systems, most applications use a synthesizer that implements the Downloadable Sounds (DLS) Level 2 standard. In the absence of a suitable hardware synthesizer, the Microsoft software synthesizer is used.

The synthesizer produces sounds based on wave samples and is capable of producing highly sophisticated musical timbres as well as any other kind of sound.

Note The DLS Level 1 synthesizer used with the DirectX 7 interfaces contains reverbation capabilities, which are on by default. The Waves TrueVerb reverberation technology is licensed to Microsoft Corporation as the SimpleVerb implementation.

The DLS Level 2 synthesizer used with the DirectX 8.0 interfaces does not contain built-in reverberation capabilities. Reverberation is instead implemented as a DMO. Waves MaxxVerb is licenced to Microsoft Corporation for this purpose.


Instruments and Downloading

To play an instrument, the synthesizer needs information about how the instrument should sound. This information, consisting of wave samples and articulation data, is stored in DLS collections. Instrument data is made available to the synthesizer by being downloaded.

Typically a range of notes for one instrument is based on one sample that is appropriately pitched for each note. However, DLS Level 2 enables each note to be based on a different sample or combination of samples. Even the velocity of a note can trigger the use of different samples for that instrument.

By default, the Microsoft software synthesizer takes its DLS data from the Roland GM/GS collection. The default collection contains DLS data for the 128 instruments defined by the General MIDI standard. Custom collections can include instruments of any kind. The wave samples for an instrument do not have to be based on a musical instrument but can be any recorded sound such as a sound effect, a fragment of speech, or even a fully formed measure of music.

Most applications do not need to access collections directly, as the necessary data is either contained in the default collection or referenced by a band object associated with a segment. A band is a set of instruments and settings mapped to performance channels. Several techniques are available for ensuring that band instruments are downloaded before use.

Note The Roland GM/GS Sound Set cannot be modified, due to legal restrictions.

Wave files and resources also have to be downloaded to the synthesizer before they can be played.


Audiopaths and Buffers

Each DirectMusic segment plays on an audiopath that controls the flow of sounds from the performance to the synthesizer, then through DirectSound buffers where effects can be applied, and finally into the primary buffer, where the final output is mixed.

Applications can create standard audiopaths and then play segments on them. For example, an application could create one audiopath for playing MIDI files to a buffer with musical reverb and another for playing wave files to a buffer with 3-D control.

More sophisticated audiopath configurations can be authored into a segment in DirectMusic Producer. For example, a nonstandard configuration might direct parts in a segment through different DirectSound buffers in order to apply different effects to them.

An audiopath can be seen as a chain of objects through which data is streamed. An application can gain access to any of these objects. For example, you might retrieve a buffer object to set 3-D properties of a sound source, or an effect DMO to change the parameters of the effect.


Basic Steps in Playing Sounds

If you understand the fundamentals outlined in Basic Concepts of DirectX Audio, you're ready to implement a rudimentary soundtrack in an application. After learning these few simple steps, you can go on to explore other parts of the API that will give you as much control over the soundtrack as you need.

This topic gives an overview of the necessary steps, without getting into the coding details. For sample code, see Tutorial 1: Playing Audio Files.

To produce a sound, an application needs to do the following:

1. Create and initialize the performance

Most applications have a single performance object. You create it by calling DirectX8.DirectMusicPerformanceCreate. Then call DirectMusicPerformance8.InitAudio. This method can set up a default audiopath.

2. Create the loader

Call DirectX8.DirectMusicLoaderCreate to obtain a DirectMusicLoader8 object. You need to do this only once, and you should keep the same loader object for the life of the application.

3. Load a segment

Call DirectMusicLoader8.SetSearchDirectory so the loader can find the data files. Then call DirectMusicLoader8.LoadSegment or DirectMusicLoader8.LoadSegmentFromResource to obtain a DirectMusicSegment8 object from a file or resource.

4. Download the band

Download DLS data to the synthesizer so that instruments can play. Wave files also must be downloaded. The simplest way to do this is by calling DirectMusicSegment8.Download.

5. Play the segment

Pass the segment pointer to DirectMusicPerformance8.PlaySegmentEx.

For a more detailed look at this process, see the following topics:

  • Loading Audio Data
  • Playing Sounds

Note It is also possible to play wave sounds using only the DirectSound interfaces. However, doing so requires you to parse the data source yourself and handle the streaming of data to buffers. For more information, see Wave Playback in DirectSound.


Building DirectX Audio Projects

To use DirectX for Visual Basic in a project, you must first ensure that the project has access to the type library.

  1. In Visual Studio, on the Project menu, click References. The References dialog box appears.
  2. Select the check box next to DirectX 8 for Visual Basic Type Library, and then click OK.


Understanding DirectX Audio

This section describes the underlying workings of Microsoft® DirectX® Audio without going into the details of the Microsoft® DirectMusic® and Microsoft® DirectSound® APIs. It is intended to give you a deeper understanding of concepts than that presented in Basic Concepts of DirectX Audio. For information on how to use the APIs, see Using DirectX Audio.

The following topics are covered:

  • DirectSound and DirectMusic
  • Overview of Audio Data Flow
  • Compositional Music Elements
  • How Music Varies During Playback
  • Music Values and MIDI Notes
  • Downloadable Sounds
  • Audio Scripts


DirectSound and DirectMusic

Previous versions of DirectX presented audio features as two discrete components: DirectSound and DirectMusic. DirectSound was for playing and capturing prerecorded digital samples (waves), and DirectMusic was for playing message-based data ranging from simple MIDI files to musical segments authored in DirectMusic Producer. Although DirectMusic has always been capable of playing nonmusical sound effects through the use of DLS, the emphasis in the past was on its ability to play music.

With DirectX 8, the DirectMusic interfaces are the primary mechanism for loading and playing all sounds, whether they originate as files or resources in wave format, MIDI format, DirectMusic Producer format, or indeed any format for which an add-on loader and tools are available.

Applications can still use the DirectSound interfaces for wave playback, and DirectSoundCapture remains the API for wave capture. However, in most applications DirectSound does its work downstream from the DirectMusic synthesizer. It takes the output from the synthesizer, routes it through effects filters, applies 3-D effects, and does the final mixing before streaming the data to the output device.

If you've used DirectSound in the past, you'll find that switching to the DirectMusic interfaces for loading and playing waves offers the following advantages:

  • No need to parse the file or resource. The DirectMusic loader does it for you.
  • Automatic use of the Windows audio compression manager (ACM ) for wave formats other than those supported by DirectSound.
  • Automatic streaming of data. No more manual buffer creation and tracking of read and write pointers.
  • Better timing control. Not only can you schedule sounds more precisely using the DirectMusic master clock, but you can easily synchronize sound effects with music.
  • Easier management of multiple instances of a sound.

Waves incorporated in DirectMusic Producer files have additional advantages. MIDI controller effects such as pitch bend can be added to waves. Segments can contain wave variations, adding a random element to playback.

These advantages don't mean you have to lose the low-level control offered by DirectSound. The DirectMusic API enables you to access any object in the audiopath. If you want to get an interface for an existing buffer, you can easily do so. You can also take advantage of all the new features of the DirectSound API for adding filters and effects.


Overview of Audio Data Flow

Typically, a DirectX Audio application obtains musical data from one or more of the following sources:

  • MIDI files.
  • Wave files.
  • Segment files authored in DirectMusic Producer or a similar application.
  • Component files authored in an application such as DirectMusic Producer and turned into a complete composition by the composer object.

Note Any of these data sources can be stored in the application as a resource rather than in a separate file.

Data from these sources is encapsulated in segment objects. Each segment object represents data from a single source. At any given moment in a performance, one primary segment and any number of secondary segments can be playing. Source files can be mixed—for example, a secondary segment based on a wave file can be played along with a primary segment based on an authored segment file.

A segment comprises one or more tracks, each containing timed data of a particular kind—for example, notes or tempo changes. Most tracks generate time-stamped messages when the segment is played by the performance. Other kinds of tracks supply data only when queried by the performance.

The performance first dispatches the messages to any application-defined tools. Such tools are grouped in segment toolgraphs that process only messages from particular segments, audiopath toolsgraphs for messages from all segments playing on the path, and a performance toolgraph that accepts messages from all segments. A tool can modify a message and pass it on, delete it, or send a new message.

Note Add-on tools are not supported by DirectX for Visual Basic.

Finally, the messages are delivered to the output tool, which converts the data to MIDI format before passing it to the synthesizer. Channel-specific MIDI messages are directed to the appropriate channel group on the synthesizer. The synthesizer creates sound waves and streams them to a device called a sink, which manages the distribution of data through buses to DirectSound buffers.

There are three kinds of buffers:

  • Sink-in buffers are DirectSound secondary buffers into which the sink streams data. These buffers convert the data format to that of the primary buffer, if necessary, and enable the application to control pan, volume, 3-D spatialization, and other properties. They can also pass their data through effects modules to add effects such as reverberation and echo. The resulting waveform is passed either directly to the primary buffer or to one or more mix-in buffers.
  • Mix-in buffers receive data from other buffers, apply effects, and mix the resulting wave forms. These buffers can be used to apply global effects. An effect achieved by directing data to a mix-in buffer is called a send.
  • The primary buffer performs the final mixing on all data and passes it to the rendering device.

Note Applications are not responsible for streaming the data through secondary buffers that are part of a DirectMusic performance. Although an application can obtain a buffer object for the purpose of adding effects and changing properties, it cannot lock the buffer and write to it, as it must when using the DirectSound API to play wave sounds.

The following diagram is a simplified view of the flow of data from files to the speakers. A single segment is shown, though multiple segments can play at the same time. The segment gets its data from only one of the four possible sources shown: a wave file, a MIDI file, a segment file authored in DirectMusic Producer, or component files combined by the composer object.

Note In all cases, data can come from a resource rather than a file.

For a closer look at the flow of messages through the performance, see Using DirectMusic Messages.

For information on how to implement the process shown in the illustration, see Loading Audio Data and Playing Sounds.


Compositional Music Elements

If you want to take full advantage of DirectX Audio, you won't play just MIDI and wave files. You'll take musical elements authored in DirectMusic Producer or a similar application and use them to create performances that can be varied or manipulated in countless ways.

Note Throughout this documentation, the human composer of musical elements is referred to as the author, to avoid confusion with the composer object of DirectMusic. Similarly, musical elements are said to be authored rather than composed.

The following brief introduction to these elements and how they are authored is meant to give the application developer an understanding of the material being used in the performance. For a more detailed view, see the documentation for DirectMusic Producer. For information on how to incorporate these elements in an application, see Using Compositional Elements.

The following compositional elements are described:

  • Styles
  • Chordmaps
  • Style-based Segments
  • MIDI-based Segments
  • Templates
  • Bands


Styles

A style is a collection of musical patterns that can be used to create a dynamic score. It also contains a time signature and a tempo, and can contain one or more bands.

A pattern is a musical figure, one or more measures long, consisting of a basic sequence of notes for each instrument, or part. These notes are not fixed but are ultimately mapped to particular pitches according to the current key, chord, and play mode. Patterns also include variations.

A motif is a special type of pattern designed to be played dynamically over the basic score. Motifs are often used in interactive applications to mark an event.

In DirectMusic Producer, patterns are created by the author on a grid analogous to a piano roll. Each part has its own row, corresponding to a performance channel, on which notes are represented by bars of varying length (duration), thickness (velocity), position on a vertical scale (pitch), and position on a horizontal scale (time).

The author can create many variations for each pattern. Typically, this is done by copying the pattern and then making small changes to one or more parts. At run time, variations are chosen by the style playback mechanism. However, the author can disable any variation for any chord—that is, specify that the variation must never be chosen when a certain chord is being played.

The author also assigns a groove range to the pattern, specifying the groove levels at which the pattern can be played.

The pattern can also be designated as an embellishment. Embellishments are of five types—intro, fill, break, end, and custom—and a pattern can be assigned to one or more of these categories. When the music is played and a certain type of embellishment is called for, only patterns of that type are candidates for playback.


Chordmaps

Much modern music, especially music in the popular, rock, folk, and jazz idioms, is based on the concept of chord progression, meaning that all the notes played within a given span of time are associated with a certain chord, and the music moves harmoniously from one chord to another.

The notes within a pattern authored for DirectMusic are derived from or intended to harmonize with a single chord. At run time, however, the pattern is transposed according to the chord progression—that is, each time the underlying chord changes, DirectMusic modifies the pitch of the notes accordingly.

The chordmap is a road map of chord progressions. Within the chordmap designer, the author chooses chords that can express the desired musical feeling or personality. These chords are arranged in a flowchart along a time line. The time line is conceptually circular, so it keeps looping back to the beginning as long as that segment of music is being played.

Certain important chords are designated as signposts. These are chords that must be played at certain points. The music is always moving from one signpost to the next. Between the signposts, however, the chord progression can follow various routes from one chord to another, as mapped out by the author.

The route through the chord chart may be chosen at run time by the composition engine, providing variation in addition to that found in the patterns themselves. Or it may be chosen by the authoring tool when the author is creating a segment.

A chord in the chordmap can actually consist of several different chords, referred to as subchords. In order to achieve polytonality by playing different inversions of the same chord, the author can assign different parts to different subchords. Each subchord is valid for one or more levels, and these are matched up with levels assigned to parts in the style.


Style-based Segments

A style-based segment is a largely prebuilt piece of music that the author constructs from the following elements:

  • Style. A style consists of general information about the music (such as time signature and tempo), as well as patterns. See Styles.
  • Chord progression. This might be derived automatically by the authoring tool from a chordmap (by choosing a path through the chord chart), or entered manually by the author.
  • Command track. This track, known as the groove track in DirectMusic Producer, is a series of commands for selecting appropriate patterns at set times. A characteristic of the patterns in styles is that they can be designated as embellishments (intro, fill, break, and end) and can also be assigned a certain groove range by the author. The command track of the segment might instruct the style playback engine to select an intro pattern and play it for the first measure, then play only patterns with a groove level of 25 for the next four measures, then play a break, and so on.
  • Band. The author can assign instruments and performance channels to all the parts in the various patterns.


MIDI-based Segments

A MIDI-based segment is created in DirectMusic Producer, often by importing a MIDI file to which the author might add tempo, key, and band changes, as well as loop points. Unlike a style-based segment, a MIDI segment has no patterns and no command track. Instead, it has a sequence track that contains MIDI notes and other commands.


Templates

A template is a segment that contains a signpost track and, optionally, a command track. The signpost track can be used to create a new chord progression, either for the segment itself or for another segment that does not have a signpost track. The command track supplies groove level and embellishments. You can use templates at run time to compose new material.

Note Templates created in versions of DirectMusic Producer prior to DirectX 8.0 are not playable self-contained segments. They can be used only to compose other segments.

The signpost track contains a sequence of signpost markers, which mark the beginning and end of regions in which variations in the chord progression are possible. Each signpost marker is designated as valid for a particular group of signpost chords in a chordmap. The author of the content is responsible for assigning signpost markers and signpost chords to the appropriate groups.

DirectMusic composes a segment by applying the signpost track to a particular style and chordmap. Each time the composer encounters a pair of signpost markers along the time line in the template, it searches the chordmap for a pair of signpost chords that belong to that group. If it finds a pair and the interval between them fits into the time available, it follows the chord progression between those two signpost chords, as defined in the chordmap. If it is unable to find a path that works, or if there is no end signpost marker, the engine plays any chord from the group of the beginning signpost marker.

For information on composing segments from templates in an application, see Using Templates.


Bands

A band is a collection of performance channel settings that determine how parts in a sound file are played. For each channel, a band includes an instrument assignment as well as settings for volume, pan, and transposition. Every part in a performance is mapped to a performance channel, and each part plays with the instrument settings applied to its channel by the band.

Although a band can be thought of as a set of instruments, it is not the same as a DLS collection. A DLS collection is a set of instruments that can be downloaded to the synthesizer and thus made available to any application. The instruments themselves contain no information about assignment to performance channels, volume, pan, or transposition. This data must be supplied by bands for the channels used by a performance.

Note When bands are downloaded to the synthesizer, it is really the DLS instruments referenced by the band that are being downloaded.

Bands can be saved as separate files or included in styles or segments.


How Music Varies During Playback

As DirectMusic plays a style-based segment, changes are made to the basic harmony and rhythm so that the performance does not sound static. Changes are partly scripted and partly random.

  • Choice of pattern. A typical style contains multiple patterns, which are selected in response to commands from the command track. For example, if the command track calls for a break embellishment to be played, the style playback engine selects a break pattern that is compatible with the current groove level. (The author specifies which groove levels are appropriate for each pattern.) If there is more than one suitable pattern, one is chosen according to rules embedded in the segment by the author. The choice might be completely or partly random, or patterns might be selected in a certain sequence.
  • Variations within a pattern. Any part within a pattern can have multiple variations. Variations can play in an order specified by the author; otherwise the style playback engine makes a random choice of variations on each repetition of the pattern.
  • Groove level. The groove level of the segment determines which of the patterns in the style can be selected for playback. The current level is set by the command track, which is normally authored into a segment. The groove level of a segment can also be changed programmatically, and a modifier can be applied to all segments by setting the master groove level for the performance.
  • Transposition. As the segment plays, changes are made to the underlying chord according to the progression in the chord track. The notes in the current pattern are automatically transposed to harmonize with the new chord.
  • Variations in timing. The playback engine can introduce small random changes in the parameters of individual notes—when they begin and when they end.
  • Band. The choice of instruments and instrument settings (volume, pan, and transposition) can be changed as the segment is playing, either by the band track within an authored segment or dynamically by the application. The application can change the band by creating a secondary segment based on a band object and then playing that segment, or by setting a parameter on the band track of the playing segment.

In many cases, applications exert control over the music by playing different segments rather than by manipulating existing segments. For example, to have the music reflect a change in the intensity of a game, you can simply transition to a new segment authored for that intensity level. You can achieve a similar effect with a single style-based segment by having the author create patterns with different groove ranges, and then changing the groove level in response to game events.


Music Values and MIDI Notes

Notes in a pattern within a DirectMusic style are not fixed notes. Rather, they are music values that become actual notes only when they are transposed to the current chord according to the current play mode and subchord level.

A music value is a representation of the note's intended role. For example, a music value can specify that a note is intended to be played as the second position in the chord, up one in the scale. When that music value is applied to a particular chord, it is converted to the appropriate MIDI note—the one in the second position in the chord, up one in the scale.

The play mode determines how to interpret the note against the chord. For example, if the mode is DMUS_PLAYMODE_NORMALCHORD, the note is interpreted against the intervals of the chord and scale, based on the root of the chord. If the mode is DMUS_PLAYMODE_FIXEDTOKEY, the note is interpreted as a linear value.

To allow for complex harmonies with multiple parallel chord progressions, DirectMusic chords can comprise multiple subchords. The subchord level is a value in the range from 0 through 31 that determines which subchords of a chord can be used in establishing the music value. Each subchord is valid for one or more levels, as defined by the author of the music. DirectMusic Producer supports up to four subchords per chord.

For an explanation of the data format of music values, see DMUS_NOTE_PMSG. For more information on the various play modes, see CONST_DMUS_PLAYMODE_FLAGS.


Downloadable Sounds

In the past, most computer audio has been produced in one of two fundamentally different ways, each with its advantages and disadvantages:

  • Waveforms are reproduced from digital samples, typically stored in a .wav file or, in the case of Red Book audio, on a standard CD track. Digital samples can reproduce any sound, and the output is very similar on all sound cards. However, they require large amounts of storage and resources for streaming.
  • Musical instrument sounds are synthesized, usually in hardware, in response to messages, typically from a MIDI file. MIDI files are compact and require few streaming resources, but the output is limited to the number of instruments available in the General MIDI set and in the synthesizer, and may sound very different on different systems.

One way to combine the advantages of digital sampling with the compactness and flexibility of MIDI is wave-table synthesis—the synthesis of instrument sounds from digital samples. These samples are obtained from recordings of real instruments and then stored on the hardware. The samples are looped and adjusted in such a way as to produce sounds of any length at various pitches and volumes.

Wave-table synthesis produces more realistic timbres than algorithmic FM synthesis but is still limited to a fixed set of instruments. Moreover, a particular instrument might sound different on different pieces of hardware, depending on the manufacturer's implementation of that instrument.

Enter the Downloadable Sounds (DLS) standard, published by the MIDI Manufacturers Association. DLS is a way of allowing wave-table synthesis to be based on samples provided at run time rather than hard-wired into the system. The data describing an instrument is downloaded to the synthesizer, and then the instrument can be played like any other MIDI instrument. Because DLS data can be distributed as part of an application, developers can be sure that their soundtracks will be delivered uniformly on all systems. Moreover, they are not limited in their choice of instruments.

A DLS instrument is created from one or more digital samples, typically representing single pitches, which are then modified by the synthesizer to create other pitches. Multiple samples are used to make the instrument sound realistic over a wide range of pitches. When a DLS instrument is downloaded, each sample is assigned to a certain range of pitches, called a region.

DLS Level 2 allows every note to occupy its own region. Moreover, the timbre for each region can be made up of multiple samples, called layers, and different layers can be triggered depending on the velocity of the note. A single instrument can thus be used to produce thousands of different sounds.

In addition, samples can be given an articulation, which defines characteristics that make the sound more like that produced by a real instrument. Articulation includes envelopes (shapes) for the volume and pitch of the sound, and a low-frequency oscillator (LFO) to provide vibrato and tremolo.

Samples can be loopable or single-shot. A loopable sample plays repeatedly for the duration of the note. A single-shot sample plays only once.

DLS data is stored in instrument collections, from which it is downloaded to the synthesizer.

DLS instruments are assigned patch numbers and respond to MIDI messages just like other MIDI instruments. However, a DLS instrument does not have to belong to the General MIDI set. In fact, it doesn't have to represent a musical instrument at all. Any sound, even a fragment of speech or a fully composed measure of music, can be associated with a DLS instrument.

For more information on DLS collections and how instruments are created, see the documentation for DirectMusic Producer. To learn more about the DLS standard, consult the document "Downloadable Sounds Level 2", available from the MIDI Manufacturers Association.

Most applications don't have to deal directly with instruments or DLS data. The opening of collections and downloading of instrument data is handled by the band object. When you download a band, all the instrument data associated with that band is downloaded as well. For more information, see Using Bands.


Audio Scripts

An audio script is a file containing variables and routines that can be accessed from within an application. It is written in a subset of Microsoft® Visual Basic® Scripting Edition called AudioVBScript. DirectMusic Producer includes an authoring environment for scripts and saves them in a special format that includes binary parameters as well as the text of the script.

Scripts implement some of the key DirectX Audio objects and can perform basic functions such as the following:

  • Creating audiopaths
  • Setting audiopath volumes
  • Setting global parameters for the performance
  • Loading, playing, and stopping segments
  • Downloading bands

DirectX® for Visual Basic does not enable applications to load and call audio scripts through the API. However, a segment authored in DirectMusic Producer can contain a script track that triggers calls to routines in one or more scripts.


Using DirectX Audio

This section is a guide to using the Microsoft® DirectMusic® and Microsoft® DirectSound® APIs in application development.

Information is presented in the following topics:

  • Loading Audio Data
  • Playing Sounds
  • Performance Parameters
  • Using Audiopaths
  • 3-D Sound
  • Using Effects
  • Buffer Chains
  • Using Compositional Elements
  • Using Audio Scripts
  • Wave Playback in DirectSound
  • Sound Capture

For a more general overview, see Getting Started with DirectX Audio.

For an understanding of the underlying mechanisms of data flow, see Understanding DirectX Audio.

For information on advanced features used mainly by specialized applications, see Advanced Topics in DirectX Audio.


Loading Audio Data

Many DirectMusic objects have to be loaded from a file or resource before they can be incorporated into a performance. The DirectMusicLoader8 class is used to manage the loading of such objects.

In most cases, an application should have only one DirectMusicLoader8 object in existence at a time. You should create a single global loader object and not free it until there is no more loading to be done. This strategy ensures that objects are found and loaded efficiently.

However, if your application loads a segment more than once, you should be aware that because of the caching system used internally by DirectMusic, on subsequent loads you might get back the same segment object you were using before, and it will still have any settings you previously gave it, such as start and loop points or a connection to a DLS collection. To ensure that this does not happen, you should release the DirectMusicLoader8 object by setting it to Nothing, and then create a new one, before reloading the segment.

Loading of objects referenced by other objects is handled transparently. For example, suppose a style being loaded from a DirectMusic Producer file contains a reference to a band whose data is in another file. DirectMusic loads the band automatically, and the application retrieves it by using the DirectMusicStyle8.GetBand method.

More information on using the loader is contained in the following topics:

  • Setting the Loader's Search Directory
  • Loading an Object from a File
  • Loading an Object from a Resource


Setting the Loader's Search Directory

By default, the loader looks for file objects in the current directory unless a full path has been passed to the load method. Using the DirectMusicLoader8.SetSearchDirectory method, you can set a different default path for the DirectMusicLoader8.LoadBand, DirectMusicLoader8.LoadCollection, DirectMusicLoader8.LoadSegment, and DirectMusicLoader8.LoadStyle methods.


Loading an Object from a File

To load an object, first create a DirectMusicLoader8 object. Then call one of the following methods:

  • DirectMusicLoader8.LoadBand
  • DirectMusicLoader8.LoadChordMap
  • DirectMusicLoader8.LoadCollection
  • DirectMusicLoader8.LoadSegment
  • DirectMusicLoader8.LoadStyle

Pass in either a simple file name or a full path for the file that contains the desired object.

The following code example, in which objDX is a DirectX8 object, loads a segment from a file in the current directory:

Dim objDMLoader As DirectMusicLoader8
Dim objSeg As DirectMusicSegment8

Set objDMLoader = objDX.DirectMusicLoaderCreate
Set objSeg = objDMLoader.LoadSegment("Myseg.sgt")

See also Loading an Object from a Resource.


Loading an Object from a Resource

Objects stored as resources or at some other location in memory are loaded in much the same way as file objects. See Loading an Object from a File.

The following methods each take a module name and resource identifier as parameters and return an instance of the appropriate class:

  • DirectMusicLoader8.LoadBandFromResource
  • DirectMusicLoader8.LoadChordMapFromResource
  • DirectMusicLoader8.LoadCollectionFromResource
  • DirectMusicLoader8.LoadSegmentFromResource
  • DirectMusicLoader8.LoadStyleFromResource

The following resource types are recognized by the loader:

String Identifier | Method
DMBAND | LoadBandFromResource
DMCHORD | LoadChordmapFromResource
DMCOLL | LoadCollectionFromResource
DMSEG | LoadSegmentFromResource
DMSTYLE | LoadStyleFromResource

Objects referenced by other objects must be loaded first. For example, if you load a segment that contains a reference to a style, the style must be loaded first in order for the segment to play correctly.

The following code example, where loader is a DirectMusicLoader8 object and perf is a DirectMusicPerformance8 object, loads and plays a MIDI file stored as a DMSEG resource in the executable:

Dim seg As DirectMusicSegment8
Set seg = loader.LoadSegmentFromResource("listen.exe", "CANYON.MID")
Call seg.Download(perf)
Call perf.PlaySegmentEx(SEG, 0, 0)


Playing Sounds

This section introduces the basic elements of a DirectMusic performance and the key methods that you need to get data from source to output.

The following topics are discussed:

  • Creating the Performance
  • Using Segments
  • Using Bands
  • Timing
  • Notification and Event Handling
  • Troubleshooting Playback


Creating the Performance

The performance object is the overall manager of playback. Among the tasks it performs are the following:

  • Managing ports and audiopaths
  • Mapping channels to audiopaths
  • Playing and stopping segments
  • Dispatching messages
  • Managing the timing

Most applications have a single DirectMusicPerformance8 object, but it is possible to have more than one performance with different parameters, such as master tempo or volume.

After the performance is created, it must be initialized by a call to DirectMusicPerformance8.InitAudio.

InitAudio associates a DirectSound8 object with the performance so that DirectSound can manage the sound data after it leaves the synthesizer. If your application uses DirectSound independently, you can either pass an existing object to InitAudio or set a variable to the object created by the method. In most cases, however, you don't need access to the DirectSound8 object.

By setting values in the DMUS_AUDIOPARAMS type that must be passed to InitAudio, the application can request synthesizer capabilities or set a synthesizer other than the default one. Most applications don't need to do this, and can request the default synthesizer and capabilities by leaving DMUS_AUDIOPARAMS.lValidData at 0.

The follow code example, in which objDX is a DirectX8 object, creates a performance and initializes it. It creates a standard default audiopath with 16 performance channels and all available features on the port.

Dim objDMPerformance as DirectMusicPerformance8
Dim audParams As DMUS_AUDIOPARAMS

Set objDMPerformance = objDX.DirectMusicPerformanceCreate
objDMPerformance.InitAudio Me.hWnd, DMUS_AUDIOF_ALL, audParams, _
   Nothing, DMUS_APATH_SHARED_STEREOPLUSREVERB, 16


Using Segments

Segments are the basic units of playable data in the DirectMusic performance. A segment is represented by a DirectMusicSegment8 object.

You can create a segment object in any of the following ways:

  • Load a file or resource object that supports the DirectMusicSegment8 class by using the DirectMusicLoader8.LoadSegment or the DirectMusicLoader8.LoadSegmentFromResource method. For more information, see Loading Audio Data.
  • Get a motif from a style by using the DirectMusicStyle8.GetMotif method.
  • Use methods of the DirectMusicComposer8 class to create a composition or transition at run time. See Overview of Programming for Composition and Using Transitions.
  • Make a copy of an existing segment by using the DirectMusicSegment8.Clone method.
  • Use the DirectMusicBand8.CreateSegment method. This creates a special type of secondary segment that is used only for making band changes. See Making Band Changes Programmatically.

Segments can perform different roles in the performance. There must always be a primary segment, which provides the main content of the soundtrack and normally serves as the control segment. Secondary segments play along with the primary segment and might provide sound effects or short musical themes. A special type of secondary segment is the motif, which is always obtained from a DirectMusic style object.

In addition there are three kinds of segments with special roles:

  • Transition segment. A short musical transition created at run time by the DirectMusic composer object and normally played as a primary segment leading from one segment to another, or from a segment to silence.
  • Band segment. A set of instruments and instrument settings for the various channels in the performance. The application can play a band segment as a secondary segment to execute changes in the band performing the music.
  • Template segment. A guide to chord progressions, groove levels, and embellishments, used in conjunction with a style and chordmap to compose music at run time.

The playback of segments is controlled by the DirectMusicPerformance8 object and begins with a call to DirectMusicPerformance8.PlaySegmentEx.

Only one primary segment can play inside a performance. When you cue a primary segment for playback, you can specify that it is to be played after the currently playing segment is finished, or you can use it to replace the current primary segment.

Secondary segments, on the other hand, play over the current primary segment, and any number of secondary segments can be playing simultaneously.

Secondary segments do not normally alter the performance of the primary segment. For example, a secondary segment can be based on a different style without affecting the style of the primary segment. However, a secondary segment can be designated as the control segment, in which case it takes over certain tasks normally handled by the primary segment.

More information on segments is contained in the following topics:

  • Segment States
  • Control Segments
  • Self-Controlling Segments
  • Wave Segments

See also Segment Timing.


Segment States

When you play a segment, parameters for that segment such as the audiopath, repetitions, and start point are stored in a segment state object, represented by a DirectMusicSegmentState8 object. The parameters are valid only for that instance of the segment. Changes subsequently made to the segment by using methods of DirectMusicSegment8 are reflected in new segment states created by calls to DirectMusicPerformance8.PlaySegmentEx.


Control Segments

A secondary segment can be designated a control segment, in which case it takes over the task of responding to certain calls such as DirectMusicPerformance8.GetCommand and controls some aspects of playback, such as the current tempo, chord, and groove level.

By default, the primary segment is the control segment. However, a secondary segment can be designated the control segment by passing the DMUS_SEGF_CONTROL flag to DirectMusicPerformance8.PlaySegmentEx. For more information, see CONST_DMUS_SEGF_FLAGS.

When a secondary segment is the control segment, the primary segment continues to function as a fallback source of control data. For example, if a secondary control segment does not contain a tempo track but the primary segment does, the tempo comes from the primary segment.


Self-Controlling Segments

A self-controlling segment ignores any control information from the control segment that duplicates control information in the self-controlling segment. For example, if the segment has a command track, it can use its own groove levels rather than the groove levels set by the control segment.

Segments can define for each track where it gets its controlling information, as follows:

  • From tracks in the control segment. This is the default behavior.
  • From tracks in the primary segment, regardless of whether it is the control segment.
  • From tracks in the same segment.

Segments are configured to be self-controlling by the author. DirectX for Visual Basic does not support track configuration by applications.


Wave Segments

The DirectMusic loader can load compressed wave-form audio files in any format supported by the audio compression manager (ACM), as well as uncompressed wave files.

Segments based on wave files are played just like any other segment. They pass through the performance as messages and are always played on channel 0 of the audiopath. Although waves are not synthesized in the same sense as musical notes, they do pass through the synthesizer and can be manipulated by MIDI controllers.

The following example code, where dmp is a DirectMusicPerformance8 object, sends a pitch change MIDI message to channel 0 on the default audiopath. The change in pitch affects every wave played on that audiopath.

Private Sub sldrPitch_Change()

  Dim hi As Byte, lo As Byte

  ' Split value into 7-bit bytes. The value returned by the slider
  ' is in the range 0 to 16383.

  hi = Fix(sldrPitch.Value / 128)
  lo = CByte(sldrPitch.Value And 127)

  ' Send pitch bend message.

  Call dmp.SendMIDIPMSG(0, DMUS_PMSGF_REFTIME, 0, &HE0, _
    lo, hi)

End Sub

Note The technique shown in the example is not guaranteed to work if your application uses multiple audiopaths. In DirectX for Visual Basic, there is no way to direct an application-created message to a particular audiopath. Because performance channel 0 is mapped to different channels on the synthesizer by different audiopaths, a MIDI controller change on one path has no effect on other paths. For more information, see Application-Created Messages.

Waves can also be embedded in DirectMusic Producer files, where they can behave somewhat like styles with variations. For an example, see the AudioScripts C++ sample application, where the ScriptDemoBaseball.spt script plays variations on the vendor's cry each time a button is clicked.

Waves in segment (.sgt) files must be downloaded to the synthesizer before being played. They are downloaded when the segment's bands are downloaded. For more information, see Downloading and Unloading Bands.


Using Bands

A band is a colllection of settings for performance channels. Every part in a segment or style plays on a single performance channel, and the most recently applied band determines how sound is synthesized on that channel.

Bands can contain the following information for each channel:

  • Instrument, identified by a MIDI patch number and bank select. This setting does not affect wave parts playing on the channel.
  • DLS collection from which to load the instrument. By default, the DLS collection is the standard General MIDI collection.
  • Volume.
  • Pan.
  • Transposition. If this value is not zero, music notes on the channel are automatically transposed for the instrument.

A band does not necessarily contain settings for every performance channel in use, and it does not have to contain every possible setting for channels it does affect. Settings not explicitly changed by a band remain as they were before the band was played. For example, if the application plays a band that does not contain any settings for channel 1, any parts on that channel continue playing on the last instrument assigned to it, and with the same volume, pan, and transposition settings. The band could change a single setting, such as the volume, without affecting any of the other settings currently in effect.

Segments and styles always contain at least one band, called the default band. Styles can contain additional bands. When you load a segment or style, the default band and any other bands are automatically loaded as well. However, you must still download the DLS data for the instruments in any band that you intend to use.

You can retrieve an object representing the default band by using the DirectMusicStyle8.GetDefaultBand method. Other bands might be authored into the style and can be retrieved by using the DirectMusicStyle8.GetBand method. Bands can also be obtained from other style files or from band files. Once you have obtained a DirectMusicBand8 object, you have access to that band and can substitute it for the default band.

More information about bands is contained in the following topics:

  • Downloading and Unloading Bands
  • Making Band Changes Programmatically
  • Ensuring Timely Band Changes
  • Playing a MIDI File with Custom Instruments


Downloading and Unloading Bands

Before a band can be used, the instruments it references must be downloaded to the performance. This step maps the instruments to performance channels and downloads the DLS data to the synthesizer.

By default, the application is responsible for downloading any band it uses. However, you can turn on automatic downloading of bands.

Downloading a band makes the band available to the performance but does not perform any program changes. Program changes take place in response to messages generated by the segment's band track, which is typically authored into a segment file. For information on how to make program changes at run time, see Making Band Changes Programmatically.

Information about how to implement downloading and unloading of bands is contained in the following topics:

  • Automatically Downloading Bands
  • Manually Downloading Bands
  • Patch Collisions
  • Unloading Bands

Automatically Downloading Bands

When automatic downloading is on, the instruments in the band are downloaded when the segment containing the band is cued. The instruments are automatically unloaded when the segment is stopped, unless another segment using the same instruments is cued to play immediately or is currently playing.

Automatic downloading should be used only when the timing of segment starts is not critical. Repeated loading and unloading of instruments takes time and can cause serious degradation of performance in complex audio environments.

Automatic unloading, which is part of the automatic downloading mechanism, can also lead to undesired results. For example, suppose you play a short secondary segment that changes the instrument on a channel. The instrument is automatically downloaded when the secondary segment starts, replacing the existing instrument. When the secondary segment ends, the instrument is automatically unloaded, with the result that there is no instrument on that channel, and the channel plays silence.

You can turn on automatic downloading of bands for the entire performance by using the DirectMusicPerformance8.SetMasterAutoDownload method, or for an individual segment by using the DirectMusicSegment8.SetAutoDownloadEnable method.

Manually Downloading Bands

You can manually download a band in one of the following ways:

  • Call DirectMusicSegment8.Download to download the bands in a segment to either an audiopath or a performance.
  • Retrieve a DirectMusicBand8 object from a file, a resource, or a DirectMusicStyle8 object and then call its DirectMusicBand8.Download method.

Patch Collisions

When bands from different segments are downloaded to the same port, instruments in band can overwrite data from a previously downloaded band.

For example, suppose segment A uses a band that assigns a piano to patch number 1, and segment B uses a band that assigns a banjo to the same patch. The application calls DirectMusicSegment8.Download first for segment A and then for segment B. Even though the bands might be downloaded to different audiopaths, the instrument data is downloaded to the same synthesizer, so any note on a performance channel mapped to patch number 1 will be played by the banjo.

This potential for patch collisions must be taken into account when the content is authored. Different segments should not use different instruments with the same patch number.

Unloading Bands

Bands take up memory, so they should be unloaded when they are no longer in use. If you have enabled automatic downloading of bands, the bands associated with a segment are unloaded automatically when the segment stops. Otherwise, you can manually unload a band by calling the DirectMusicSegment8.Unload or DirectMusicBand8.Unload method for instruments downloaded by the corresponding Download method.

The DirectMusicPerformance8.CloseDown method also unloads any remaining downloaded instruments.


Making Band Changes Programmatically

Usually, the band track in a loaded segment will perform program changes. However, you can also do so manually.

First create a segment by using DirectMusicBand8.CreateSegment, and then play that segment by calling DirectMusicPerformance8.PlaySegmentEx. Typically, you would use DMUS_SEGF_MEASURE or DMUS_SEGF_GRID in the lFlags parameter to ensure that the band change takes effect on an appropriate boundary.

A performance can be playing instruments from more than one band at a time. For example, suppose your application is playing a primary segment using one band, and then plays a motif from a style that has a different band. As long as the instruments in the two bands are mapped to different performance channels, no conflict arises. Note, though, that motif segments don't always have their own band tracks, so you might get silence from the motif's channels unless you first create a band segment and play it.


Ensuring Timely Band Changes

A consideration in playing band segments is the randomness in the timing of notes played by a style track. For instance, a note that is on measure 1, beat 1 might actually play somewhat earlier or later than the actual beat boundary. The band segment isn't aware of this, with the result that some of the notes might play with the incorrect instrument.

To prevent this problem, an application should cue the band segment early. Suppose, for example, that you have a style-based segment styleSeg and a band segment bandSeg. You want to play both the style segment and the band segment on the next measure boundary of the performance (perf). You know that the style contains notes that could go out up to 30 ticks earlier (in music time) than the start time of the segment. The following code example ensures that the band segment is played 31 ticks before the style segment, so all instruments are in place before any note is played:

'First get the time of the next measure
' and convert it to music time.

Dim ctResolved As Long
Dim mtResolved As Long

ctResolved = perf.GetResolvedTime(ctResolved, DMUS_SEGF_MEASURE)
mtResolved = perf.ClockToMusicTime(ctResolved)

' Now play the band segment 31 ticks before the measure boundary.

mtResolved = mtResolved - 31
Call perf.PlaySegmentEx(bandSeg, 0, mtResolved)

' Play the style segment on the measure boundary.

Call perf.PlaySegmentEx(styleSeg, DMUS_SEGF_MEASURE, 0 )

Note If there is no randomness in the notes played by a segment (for example, one loaded from a MIDI file), you don't need to worry about the timeliness of a band segment played at the same time. By default, all band segments start 1 tick early.


Playing a MIDI File with Custom Instruments

By default, when you play a MIDI file the instruments used are those in the Roland GM/GS Sound Set, contained in the Gm.dls file. However, you can use instruments from any DLS collection when playing a MIDI file.

To do so, load the collection, associate it with the segment based on the MIDI file, and download the collection as you would with any other segment.

The following example code, where dmLoader is a DirectMusicLoader8 object, loads a DLS collection, connects it to the DirectMusicSegment8 object represented by dmSeg, and downloads it to the default audiopath of the DirectMusicPerformance8 object dmPerf:

Dim dmColl As DirectMusicCollection8

Set dmColl = dmLoader.LoadCollection("boids.dls")
dmSeg.ConnectToCollection dmColl
dmSeg.Download dmPerf.GetDefaultAudioPath

When a custom collection is attached to a MIDI segment, the connection to the GM collection is not broken. For example, suppose you load a collection containing a single instrument that has a patch number of 12 and connect this to the segment. MIDI channels with any patch number other than 12 continue to be played by the appropriate instruments in the GM collection.

For more information on collections, see Using Instrument Collections.


Timing

This section is an overview of various timing issues in DirectMusic. The following topics are discussed:

  • Clock Time vs. Music Time
  • Changing the Tempo
  • Prepare Time
  • Latency and Bumper Time
  • Segment Timing


Clock Time vs. Music Time

In DirectX for Visual Basic, the time returned by the master clock is a Long representing units of approximately one millisecond. The value returned by DirectMusicPerformance8.GetClockTime is relative to an arbitrary start point.

Music time is also a Long. It is not an absolute measure of time but is relative to the tempo. The clock is started when the performance is initialized and ticks 768 times for each quarter-note. You can retrieve the current music time by using DirectMusicPerformance8.GetMusicTime.

To convert between the two kinds of time in a performance, you can use the DirectMusicPerformance8.MusicToClockTime and DirectMusicPerformance8.ClockToMusicTime methods.

When a segment is cued to play by a call to DirectMusicPerformance8.PlaySegmentEx and the start time is given in clock time, DirectMusic must convert the start time to music time. If no primary segment is currently playing, the conversion is made immediately, based on the current tempo. Otherwise, if another segment is playing, the start time of the cued segment isn't converted to music time until the start time has been reached.

If the tempo is changed before the segment starts playing, the start time can be affected, or the segment might not start on the desired boundary. In the first case, in which the conversion to music time is made immediately, the start time (in reference time) is advanced if the tempo speeds up and delayed if the tempo slows down. In the second case, in which conversion is made at start time, a change in tempo can mean that the segment does not start at correct resolution boundaries. For example, if the segment is supposed to start on a measure boundary (as indicated in the lFlags parameter of PlaySegmentEx), the actual start time (in clock time) is calculated when the segment is cued. However, if the tempo then changes, a measure boundary might not fall at that time.

When a primary segment is passed to PlaySegmentEx with the DMUS_SEGF_QUEUE flag (see CONST_DMUS_SEGF_FLAGS), the startTime parameter is ignored and the segment is cued to play after any primary segments whose start times have already been converted. If a previously cued segment is still stamped in reference time, that segment plays at its designated time, perhaps interrupting another segment.

For example, say you have three segments, each 10 seconds in length. You cue segment A to play 5 seconds from now. Because no primary segment is currently playing, the start time is immediately converted to music time. At 6 seconds, you cue segment B to play at 20 seconds. In this case, because music is already playing and the tempo might change, the conversion to music time is not made immediately. Then you cue segment C with the DMUS_SEGF_QUEUE flag so that it starts immediately after segment A finishes, at 15 seconds. At 20 seconds, segment B starts playing and interrupts segment C.


Changing the Tempo

The tempo of a performance dictates the conversion between the two types of time used in DirectMusic, which in turn controls the resolution of events to musical boundaries. (See Clock Time vs. Music Time.) The tempo track of the control segment usually manages the tempo, but it is also possible for an application to set the tempo dynamically.

There are two ways to do so: by setting the master tempo and by sending a tempo message.

The master tempo is a factor by which all tempos in the performance are multiplied. For example, if you set the master tempo by calling DirectMusicPerformance8.SetMasterTempo with a parameter of 0.75, and then play a segment that has a tempo of 120 beats per minute, the segment plays with a tempo of 90.

Sending a tempo by using the DirectMusicPerformance8.SendTempoPMSG method changes the tempo at the time for which the message is stamped. The new tempo is valid until another tempo message is sent or the tempo is changed by a control segment. The tempo value can be modified by the master tempo.

The following call, where perf is a DirectMusicPerformance8 object, immediately sets the tempo to 100 beats per minute. Note that if you pass 0 as the lTime parameter to signify that the message is to go out immediately, you must also set the DMUS_PMSGF_REFTIME flag.

Call perf.SendTempoPMSG(0, DMUS_PMSGF_REFTIME, 100)


Prepare Time

As a segment is played, the performance makes repeated calls to the segment's tracks, causing them to generate messages for the supplied time range, which is some fraction of a second. These messages are then placed in the queue behind those that were generated in previous calls. By default, about a second's worth of messages are in the queue at any given time.

Each time the performance calls on a track to play messages, it calculates the end time for that call by adding the prepare time to the current time. If the current time is 10,000 milliseconds (or the equivalent in REFERENCE_TIME units) and the prepare time is the default 1000 ms, the end time is 11,000—that is, all new messages that are to play up to time 11,000 must be prepared and placed in the queue.

The size of the queue can be changed by calling the DirectMusicPerformance8.SetPrepareTime method, and the current size can be retrieved by using DirectMusicPerformance8.GetPrepareTime.

Most applications don't need to change the default prepare time, and the process just described is not visible to the application. However, it is helpful to understand the concept of prepare time because of the DMUS_SEGF_AFTERPREPARETIME flag, which the application can pass to DirectMusicPerformance8.PlaySegmentEx.

Without this flag, if you set a start time of "now" for the segment, the performance invalidates any messages currently in the queue. Any tracks that are still valid at this point—for example, tracks of secondary segments that continue to play despite the introduction of a new primary segment—then have to resend their messages, taking into account any changes made to the environment by the new segment. This causes extra processing and might also lead to undesired results.

You can use the DMUS_SEGF_AFTERPREPARETIME flag to specify that the segment isn't to start playing until all messages currently in the queue have been processed and passed to the port buffer. If messages up to time 10,000 milliseconds (ms) are in the queue and the current time is 9,000 ms, a segment cued to play immediately, but flagged DMUS_SEGF_AFTERPREPARETIME, starts playing just after the 10,000 ms mark.

For more information, see Segment Timing. For an illustration, see Latency and Bumper Time.


Latency and Bumper Time

Latency is the delay between the time at which the port receives a message and the time at which it has synthesized enough of a wave to play. The DirectMusicPerformance8.GetLatencyTime method retrieves the current time plus the latency for the performance as a whole. This is the largest value returned by any of the ports' latency clocks.

The bumper is an extra amount of time allotted for code to run between the time that an event is put into the port buffer and the time that the port starts to process it. By default, the bumper length is 50 milliseconds (ms). An application can change this value by using the DirectMusicPerformance8.SetBumperLength method, and retrieve the current value by calling DirectMusicPerformance8.GetBumperLength.

Here's an example of how latency time and bumper time are combined. Suppose an event is supposed to play at 10,000 ms. The latency of the port is known to be 100 ms, and the bumper length is at its default value of 50 ms. The performance therefore places the message into the port buffer at 9,850 ms.

Once a message has been placed in the port buffer, it no longer belongs to the performance and cannot be stopped from playing by using the DirectMusicPerformance8.Invalidate or the DirectMusicPerformance8.StopEx method. The first message that can be invalidated has a time stamp equal to or greater than the current time plus the latency and bumper time. This value can be retrieved by using the DirectMusicPerformance8.GetQueueTime method.

The following diagram, not to scale, illustrates the relationship of the times and durations retrieved by various methods. The current time is at the left, and the last time for which messages have been prepared is at the right. Remember that prepare time is only an approximation of the total timespan of messages in the queue at any given moment.

The methods in the illustration are from the C++ API, but most have similar names in DirectX for Visual Basic. The GetTime method in the illustration is equivalent to DirectMusicPerformance8.GetClockTime.


Segment Timing

This section covers various aspects of timing in the playing of segments.

To clarify the relationship between times within segments and times within the performance, the following terms are used throughout this section:

Start point

The first point in the segment that can be a segment start time. By default this value is 0, indicating the beginning of the segment. However, it can be changed by the application.

Segment start time

The point in a segment where it begins producing sounds. This time is usually the same as the start point, but can be later if the start point is deliberately aligned to a play time that is in the past.

Play time

The point in the performance where a new segment's start point is cued. In the DirectMusic API, this time is sometimes called start time.

Start marker

A marker indicating a valid start time in a segment. This can be an enter switch point in the marker track, or a variation switch point in a pattern.

Play marker

A marker in the marker track of a control segment indicating where another segment's start point can be cued.

Note Start markers and play markers are placed in the segment by the author and cannot be changed by the application.

Segments normally play from the beginning. You can make a segment start from another point by using the DirectMusicSegment8.SetStartPoint method. This start point is used whenever the segment is played.

If a repeat count is set by using DirectMusicSegment8.SetRepeats, the entire segment repeats that number of times, unless a loop has been defined by a call to DirectMusicSegment8.SetLoopPoints, in which case only the part of the segment between the loop points repeats.

The play time is determined by two parameters of DirectMusicPerformance8.PlaySegmentEx:

  • The startTime parameter sets the earliest time at which the segment can start playing. If startTime is 0, this time is as soon as possible. The actual time at which the segment will play depends on the type of segment. If it is a primary segment or a secondary control segment, the earliest play time is at queue (or flush) time. If it is a noncontrol secondary segment, the earliest play time is at latency time. For more information on queue time and latency time, see Latency and Bumper Time.
  • The lFlags parameter specifies how soon after the earliest possible play time the segment will actually start playing. Most often you will want to wait for an appropriate point in the rhythm before introducing a new primary segment, transition, or motif. You control the delay by setting oneor more flags from the CONST_DMUS_SEGF_FLAGS enumeration.

Aligning a Segment to a Past Time

Rather than forcing the segment start time to the next grid, beat, or measure in the control segment, you might want the segment to start playing sooner, yet still match the rhythm of the current segment. You can make the segment do so by cuing its start point to a rhythmic boundary that has already passed. The rhythm in the cued segment is thus aligned with that in the current segment, and the new segment can start playing immediately.

To cue the segment in the past, use the DMUS_SEGF_ALIGN flag. Add one of DMUS_SEGF_GRID, DMUS_SEGF_BEAT, DMUS_SEGF_MEASURE, or DMUS_SEGF_SEGMENTEND to cue the start point of the segment at the appropriate rhythmic boundary. Alternatively, you can use DMUS_SEGF_MARKER to align the start point to the most recently played play marker in the control segment.

Note Combining DMUS_SEGF_ALIGN with DMUS_SEGF_SEGMENTEND causes the beginning of the cued segment to be aligned with the beginning of the current segment.

Of course, when the start point is in the past, the segment start time has to be adjusted to fall in the present or the future. The performance uses the following rules to determine the segment start time. In all cases, "next" means "next possible"—that is, within the part of the segment that does not fall in the past.

  • If a start marker appears in the cued segment before the next resolution boundary of the specified type, the segment start time falls at that point.
  • If there is no valid start marker, the segment start time is at the next start resolution boundary of the cued segment, as specified by one of the following flags:
    Flag | Purpose
    DMUS_SEGF_VALID_START_BEAT | Put the segment start time on the next beat.
    DMUS_SEGF_VALID_START_GRID | Put the segment start time on the next grid.
    DMUS_SEGF_VALID_START_MEASURE | Put the segment start time on the next bar line.
    DMUS_SEGF_VALID_START_TICK | Put the segment start time at the earliest possible point.

  • If there is no valid start marker and no start resolution flag is supplied, the segment start time is at the next play resolution boundary as specified by the DMUS_SEGF_GRID, DMUS_SEGF_BEAT, or DMUS_SEGF_MEASURE flag. If none of these flags is present, the segment start time is immediate.

Play markers and start markers allow greater flexibility in the cuing of segments, especially motifs. Suppose a motif is designed to sound best when it starts playing at the beginning of a measure in the primary segment. If the motif is cued with the DMUS_SEGF_MEASURE flag, there might be a significant delay before the next measure boundary is reached and the motif plays. But if the DMUS_SEGF_ALIGN flag is added, the motif can start playing sooner without violating the rhythm. Adding the DMUS_SEGF_MARKER flag ensures that the motif plays at an appropriate boundary within the control segment, rather than on just any measure, beat, or grid.

For information on how tempo changes can affect segment start times, see Clock Time vs. Music Time.

The following diagram shows how the timing is determined for a segment cued with the DMUS_SEGF_MEASURE, DMUS_SEGF_ALIGN, and DMUS_SEGF_VALID_START_BEAT flags. The solid vertical lines are measure boundaries, and the dotted lines are beat boundaries. The start point of the segment is aligned with the previous measure boundary in the current primary segment. The segment start time falls at the first beat in the cued segment after the unresolved play time.

Logical Time vs. Actual Time

Some events have both a logical time and an actual time. The actual time is when the event will take place, and the logical time represents the musical position where it belongs.

For example, a segment might contain a program change that belongs to the start of a beat. The logical time is the start of the beat. However, you want to make sure the program change takes place before the note on the beat is played, so you assign it a physical time that's a little earlier.

If the segment loops to the logical time (the start of that same beat), the program change will still go out.


Notification and Event Handling

From time to time, your application may need to respond to a performance event. For example, you might need to know when the end of a segment has been reached, or you might want to synchronize graphics with the beat of the music. You get the desired information by asking DirectMusic to notify you when a certain type of event has taken place.

Note Performance notifications are not to be confused with DirectSound buffer notifications, which are used only by applications that are streaming wave data directly to or from buffers. See Play Buffer Notification and Capture Buffer Notification.

Specify what types of events you want to be notified of by calling the DirectMusicPerformance8.AddNotificationType method once for each desired type of event. The following code example, in which perf is a DirectMusicPerformance8 object, requests notifications for segment events. The type of event (such as a segment start or a segment end) will be derived later from the notification message.

Call perf.AddNotificationType(DMUS_NOTIFY_ON_SEGMENT)

Notifications are sent in the form of a DMUS_NOTIFICATION_PMSG message type. You can poll for any pending notification messages by calling the DirectMusicPerformance8.GetNotificationPMSG method in Sub Main, or you can have DirectMusic signal an event when a message is pending.

To have DirectMusic signal events, use DirectX8.CreateEvent to obtain an event handle, and then pass this handle to DirectMusicPerformance8.SetNotificationHandle. The module that you pass to CreateEvent must implement the DirectXEvent8 class and must also provide an implementation of the DirectXEvent8.DXCallback method, which is called by DirectMusic whenever an event is signaled.

The following code example sets up notifications for a form module called frmMain:

' DX is a DirectX8 object; perf is a DirectMusicPerformance8 object.

Dim hEvent As Long
hEvent = DX.CreateEvent(frmMain)
Call perf.SetNotificationHandle(hEvent)

The form module contains code to intercept any message indicating that the segment has finished playing:

Implements DirectXEvent8

Private Sub DirectXEvent8_DXCallback(ByVal eventid As Long)

  Dim GotMSG As Boolean
  Dim PMsg As DMUS_NOTIFICATION_PMSG

  Do
  GotMSG = gobjDMPerformance.GetNotificationPMSG(PMsg)
  If GotMSG Then
  If PMsg.lNotificationOption = DMUS_NOTIFICATION_SEGEND Then

    ' Segment has finished playing, so do something.
    .
    .
    .
  End If
  End If
  Loop Until Not GotMSG

End Sub

It isn't necessary to create an event in order to retrieve notification messages in your application's main loop. As long as you have requested notifications by calling the DirectMusicPerformance8.AddNotificationType method, the performance sends messages that can be retrieved by calling DirectMusicPerformance8.GetNotificationPMSG.

More than one message might be waiting when an event is signaled or when you call GetNotificationPMSG in the loop. To be sure of catching all notifications, call GetNotificationPMSG repeatedly until it returns False.

Multiple messages with the same time stamp are not queued in any particular order.


Troubleshooting Playback

The following are common causes for sounds not playing correctly.

  • Instruments have not been downloaded. You must download all instruments and waves used by segments, even the default Gm.dls instrument collection. To ensure that all instruments and waves are downloaded, you can turn on automatic downloading; however, this is not recommended. A better way is to download each segment when it is loaded, by using DirectMusicSegment8.Download. For more information, see Downloading and Unloading Bands.

    There is one case in which automatic downloading might be required: when a segment trigger track cues other segments that use different instruments or waves. Because your application doesn't obtain an interface to the triggered segments, it cannot download them manually.

  • The loader cannot find needed files. Make sure the loader is looking in the correct folder by calling DirectMusicLoader8.SetSearchDirectory.


Performance Parameters

In DirectX for Visual Basic, performance parameters are set and retrieved by using various methods of DirectMusicPerformance8 and DirectMusicSegment8.

To have the performance respond immediately to a changed parameter, an application can flush messages from the queue by using the DirectMusicPerformance8.Invalidate method. This method causes all tracks to resend messages from the specified point forward.


Setting and Retrieving Track Parameters

Some methods of DirectMusicPerformance8 and DirectMusicSegment8 have the effect of setting or retrieving parameters on a particular track, usually in the control segment. However, applications using DirectX for Visual Basic don't need to be concerned about tracks as such, and these methods can be used without any knowledge of what is happening at a lower level.


Disabling and Enabling Track Parameters

By using the DirectMusicSegment8.SetTempoEnable and DirectMusicSegment8.SetTimeSigEnable methods, you can disable the setting of tempo and time signature by a control segment. You might want to do this, for example, when you have set the tempo dynamically and don't want the primary segment to change the tempo.

You can also use SetTempoEnable to force a segment to send tempo messages even though it isn't the control segment, and SetTimeSigEnable to cause a secondary segment to send time signature messages. For more information, see Control Segments.


Setting and Retrieving Global Parameters

The DirectMusicPerformance8 class has the following methods for setting and retrieving global parameters, which affect the entire performance.

GetMasterAutoDownload SetMasterAutoDownload | This parameter controls whether instruments are automatically downloaded when a segment is played. By default, it is off. See Downloading and Unloading Bands.
GetMasterGrooveLevel SetMasterGrooveLevel | The master groove level is a value that is always added to the groove level established by the command track. The resulting value is adjusted, if necessary, to fall within the range from 1 through 100.
GetMasterTempo SetMasterTempo | The master tempo is a scaling factor that is applied to the tempo by the final output tool. By default, it is 1. A value of 0.5 would halve the tempo, and a value of 2.0 would double it. This value can be set in the range from 0.01 through 100.0.
GetMasterVolume SetMasterVolume | The master volume is an amplification or attenuation factor, in hundredths of a decibel, applied to the default volume of the entire performance and any other performances using the same synthesizer. The range of permitted values is determined by the port. Hardware MIDI ports do not support changing master volume.


Using Audiopaths

A DirectMusic performance contains one or more audiopaths, which manage the flow of sound data through various objects. An audiopath might include the performance itself, a segment, toolgraphs, the synthesizer, DirectSound buffers, effects DMOs, and the primary buffer where the final mixing is done.

If your application does nothing more complicated than playing 2-D sound effects or MIDI files, you can set up a standard default audiopath and play everything on it. But to take advantage of the full power of DirectX Audio you must be able to take control of the audiopath.

This section is a guide to creating audiopaths, playing segments on them, and accessing objects within them. The following topics are covered:

  • Migrating from Ports to Audiopaths
  • Creating Audiopaths
  • Default Audiopath
  • Standard Audiopaths
  • Playing Sounds on Audiopaths
  • Retrieving Objects from an Audiopath


Migrating from Ports to Audiopaths

If you have written applications using versions of DirectMusic prior to DirectX 8.0, you will find that the way of creating a route for audio output has changed. DirectX for Visual Basic no longer requires you to set a port on the performance. Instead, ports are incorporated into audiopaths.


Creating Audiopaths

Applications can set up audiopaths in the following ways:

  • Create a default standard audiopath for the performance in the call to DirectMusicPerformance8.InitAudio. See Default Audiopath.
  • Create one or more standard audiopaths by using DirectMusicPerformance8.CreateStandardAudioPath. See Standard Audiopaths.
  • Obtain an audiopath configuration from a file authored in DirectMusic Producer and pass the configuration object to DirectMusicPerformance8.CreateAudioPath.
  • Have DirectMusic create an audiopath from the segment's audiopath configuration when the segment is played. Audiopaths created in this way are temporary and not visible to the application.

An audiopath configuration embedded in a segment can be retrieved by using DirectMusicSegment8.GetAudioPathConfig. The audiopath configuration object does not have a unique interface or methods, and your application cannot change the configuration in any way. All you can do with the object is pass it, as a variable of type IUnknown, to DirectMusicPerformance8.CreateAudioPath. For sample code, see Playing Sounds on Audiopaths.

Audiopath configurations are the only means of creating nonstandard audiopaths. For instance, if different performance channels are to be routed to different buffers, this mapping must be specified in the audiopath configuration of a segment.


Default Audiopath

The default audiopath is the one used when no audiopath is specified in the call to DirectMusicPerformance8.PlaySegmentEx.

You can create an audiopath and make it the default by specifying a standard type in the lDefaultPathType parameter of DirectMusicPerformance8.InitAudio.

Any existing audiopath can be made the default audiopath by passing it to DirectMusicPerformance8.SetDefaultAudioPath. Retrieve the default audiopath by using DirectMusicPerformance8.GetDefaultAudioPath.


Standard Audiopaths

If your application does not play exclusively on audiopaths created from audiopath configuration objects, you must create one or more standard audiopaths.

Standard audiopaths are identified by the values passed in the lType parameter of DirectMusicPerformance8.CreateStandardAudioPath or in the lDefaultPathType parameter of DirectMusicPerformance8.InitAudio.

The audiopaths defined by DirectMusic manage the flow of synthesizer output through combinations of standard buffers, some of which have effect DMOs attached to them. The following table shows the standard audiopaths and which standard buffers they contain. Shared buffers can be used by more than one audiopath.

Audiopath Type | Standard Buffers | Buffer Shared?
DMUS_APATH_DYNAMIC_3D | 3-D Dry | No
DMUS_APATH_DYNAMIC_MONO | Mono | No
DMUS_APATH_DYNAMIC_STEREO | Stereo | No
DMUS_APATH_SHARED_STEREOPLUSREVERB | Stereo Reverb | Yes Yes

Characteristics of the standard buffers are shown in the following table, where the Capabilities column lists values that would be returned in the lFlags member of the DSBCAPS type passed to DirectSoundSecondaryBuffer8.GetCaps. The last column shows objects that can always be obtained from the buffer object. In addition, applications can add effects to buffers by using DirectSoundSecondaryBuffer8.SetFX, in which case other objects will be available. A DirectSoundSecondaryBuffer8 object can be obtained for any buffer. For more information on obtaining objects, see Retrieving Objects from an Audiopath.

Standard Buffer | Description | Capabilities | Objects
3-D Dry | Mono 3-D buffer | DSBCAPS_CTRLFX DSBCAPS_CTRL3D DSBCAPS_CTRLFX DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS DSBCAPS_MUTE3DATMAXDISTANCE | DirectSound3DBuffer8
Mono | Mono buffer with no effects | DSBCAPS_CTRLFX DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | None.
Reverb | Stereo buffer with music reverberation effect | DSBCAPS_CTRLFX DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | DirectSoundFXWavesReverb8
Stereo | Stereo buffer with no effects | DSBCAPS_CTRLFX DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | None.

More information about the standard audiopaths is available in the following topics:

  • DMUS_APATH_DYNAMIC_3D
  • DMUS_APATH_DYNAMIC_MONO
  • DMUS_APATH_DYNAMIC_STEREO
  • DMUS_APATH_SHARED_STEREOPLUSREVERB


DMUS_APATH_DYNAMIC_3D

Sets up a nonshared buffer of type 3-D Dry.

Applications can obtain an object representing the 3-D Dry buffer by calling DirectMusicAudioPath8.GetObjectInPath with lStage set to DMUS_PATH_BUFFER and lBuffer set to 0.


DMUS_APATH_DYNAMIC_MONO

Sets up a nonshared buffer of type Mono that has no 3-D parameters or special effects.

Applications can obtain an object representing the buffer by calling DirectMusicAudioPath8.GetObjectInPath with lStage set to DMUS_PATH_BUFFER and lBuffer set to 0.


DMUS_APATH_DYNAMIC_STEREO

Sets up a nonshared buffer of type Stereo. This audiopath is intended for sound effects on stereo buffers. No reverberation is available.

Applications can obtain an object representing the buffer by calling DirectMusicAudioPath8.GetObjectInPath with lStage set to DMUS_PATH_BUFFER and lBuffer set to 0.


DMUS_APATH_SHARED_STEREOPLUSREVERB

Sets up buffers of type Reverb and Stereo.

The Stereo buffer is shared among multiple audiopaths. It is a sink-in buffer, meaning that it accepts data directly from the synthesizer, not from other buffers.

Applications can obtain an object representing the Stereo buffer by calling DirectMusicAudioPath8.GetObjectInPath with lStage set to DMUS_PATH_BUFFER and lBuffer set to 0.

The Reverb buffer is also a shared sink-in buffer. Unlike the Stereo buffer, it accepts a mono input from the synthesizer and converts the data to stereo format.

Applications can obtain an object representing the Reverb buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 1.


Playing Sounds on Audiopaths

If your application has created a default audiopath in the call to DirectMusicPerformance8.InitAudio, you can play a segment on this path by omitting the AudioPath parameter of DirectMusicPerformance8.PlaySegmentEx.

If there is no default audiopath, or if you want to play a segment on another path, specify the audiopath by using one of the following techniques:

  • Supply an DirectMusicAudioPath8 object in the AudioPath parameter. Usually this is the object you received when the audiopath was created.
  • Include DMUS_SEGF_USE_AUDIOPATH in lFlags. This flag causes the segment to create an audiopath from a configuration embedded in the segment object.

Note An audiopath created in response to the DMUS_SEGF_USE_AUDIOPATH flag is automatically released as soon as the segment has stopped playing. If the audiopath contains an effect such as reverberation, the effect is cut short prematurely. To prevent this from happening, the application should create the audiopath manually and release it only after a suitable delay.

Bands are not downloaded for segments played with the DMUS_SEGF_USE_AUDIOPATH flag unless automatic downloading is enabled. For more information, see Automatically Downloading Bands.

The following sample code, where dmp is a DirectMusicPerformance8 object and dmSeg is a DirectMusicSegment8 object representing any type of sound file, plays the segment on an embedded audiopath configuration if one is available. If an error occurs on the call to DirectMusicSegment8.GetAudioPathConfig, the value of path remains Nothing and the segment is played on the default audiopath.

Dim path As DirectMusicAudioPath8
Dim Config As IUnknown

If Not (dmSeg Is Nothing) Then

  On Error GoTo NOCONFIG
  Set path = Nothing
  Set Config = dmSeg.GetAudioPathConfig
  Set path = dmp.CreateAudioPath(Config, True)
NOCONFIG:
  On Error Resume Next
  dmp.PlaySegmentEx dmSeg, 0, 0, , path

End If

If you have an audiopath object, you can change the volume by using DirectMusicAudioPath8.SetVolume. Unlike the DirectMusicPerformance8.SetMasterVolume method, which affects all sounds playing on the synthesizer, this method sets the volume only on the performance channels playing on this audiopath.


Retrieving Objects from an Audiopath

It is often necessary to retrieve a particular object within the audiopath. Common reasons to do so include the following:

  • To manipulate the 3-D properties of sounds by obtaining a DirectSound3DBuffer8 object.
  • To set global 3-D sound properties by obtaining an DirectSound3DListener8 object from the primary buffer.
  • To set effects on a secondary buffer by obtaining a DirectSoundSecondaryBuffer8 object.
  • To set effect parameters by obtaining a DMO such as DirectSoundFXI3DL2Reverb8.

Objects can be retrieved from an audiopath by calling DirectMusicAudioPath8.GetObjectInPath. The following table gives information about the parameters to this method.

lStage | guidObject | lPChannel used? | lIndex used? | iidInterface (typical)
DMUS_PATH_AUDIOPATH | Not supported in DirectX for Visual Basic. The application already has the DirectMusicAudioPath8 object from which GetObjectInPath was called.
DMUS_PATH_AUDIOPATH_GRAPH | Not supported in DirectX for Visual Basic.
DMUS_PATH_AUDIOPATH_TOOL | Not supported in DirectX for Visual Basic.
DMUS_PATH_BUFFER | GUID_ALL | Yes | No, identify by dwBuffer. | IID_DirectSoundSecondaryBuffer8
DMUS_PATH_BUFFER_DMO | DMO class ID, such as GUID_DSFX_STANDARD_GARGLE, or GUID_ALL to enumerate | Yes | No, identify by dwBuffer. | IID for standard DMO, such as IID_DirectSoundGargle
DMUS_PATH_MIXIN_BUFFER | GUID_ALL | No | Yes | IID_DirectSoundSecondaryBuffer8
DMUS_PATH_MIXIN_BUFFER_DMO | DMO class GUID, or GUID_ALL to enumerate | No | Yes | IID for standard DMO, such as IID_DirectSoundFXI3DL2Reverb
DMUS_PATH_PERFORMANCE | Not supported in DirectX for Visual Basic.
DMUS_PATH_PERFORMANCE_GRAPH | Not supported in DirectX for Visual Basic.
DMUS_PATH_PERFORMANCE_TOOL | Not supported in DirectX for Visual Basic.
DMUS_PATH_PORT | Not supported in DirectX for Visual Basic.
DMUS_PATH_PRIMARY_BUFFER | GUID_ALL | No | No | IID_DirectSound3DListener8
DMUS_PATH_SEGMENT (*) | GUID_ALL | No | No | IID_DirectMusicSegment8
DMUS_PATH_SEGMENT_GRAPH (*) | Not supported in DirectX for Visual Basic.
DMUS_PATH_SEGMENT_TOOL (*) | Not supported in DirectX for Visual Basic.
DMUS_PATH_SEGMENT_TRACK (*) | Not supported in DirectX for Visual Basic.

For more information on the values for lIndex when retrieving standard buffers, see Standard Audiopaths.

If you already have an object for an effects buffer, it is also possible to retrieve a DMO by using DirectSoundSecondaryBuffer8.GetObjectInPath.

You can retrieve a DirectSoundSecondaryBuffer8 object for any buffer in the audiopath, but some methods are not valid. For more information, see DirectSoundSecondaryBuffer8.

If you set a global variable to a buffer object obtained from the audiopath, be sure to set the variable to Nothing before calling DirectMusicPerformance8.CloseDown. If you fail to do so, CloseDown will destroy the buffer and then a memory access violation can occur when the variable goes out of scope as the program exits.


3-D Sound

Using DirectX Audio, you can locate sounds in space and can apply Doppler shift to moving sounds.

3-D effects are applied to individual DirectSound buffers. Because you can direct different sounds along different audiopaths, each with its own buffer, it's easy to apply different parameters to different sounds.

The following topics cover some general aspects of 3-D sound:

  • Coordinates of 3-D Space
  • Perception of Sound Positions

Information on how to use 3-D sound in an application is found in the following sections:

  • DirectSound 3-D Buffers
  • DirectSound 3-D Listeners


Coordinates of 3-D Space

The position, velocity, and orientation of sound sources and listeners in 3-D 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.

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 3-D 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 3-D world is facing north, level to the ground, and the orientation of the listener is (1, 0, 0)—that is, positive on the x-axis and neutral on the other two axes—then the listener is facing due east. If the vector is (1, 0, 1), the listener's orientation is to the northeast. If it is (-1, 0, 1) the listener is facing northwest. Since the values within a vector are not in absolute units, the last example could equally well be expressed as (-5, 0, 5) or (-0.25, 0, 0.25).

You can see how vectors in 2-D 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. 3-D vectors work in just the same way, with an additional axis.


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.

Although these are not the only cues people use to discern the position of sound, they are the main ones, and they are the factors that have been implemented in the positioning system of DirectX Audio. Hardware optimized for 3-D sound can support other cues as well, such as the effect of the earlobes on the pitch and timing of sounds arriving from different directions. The mathematics behind this effect are known as the head-related transfer function (HRTF).

In most cases, DirectSound creates virtual 3-D effects on two speakers or a set of headphones. However, it will also take advantage of four-channel systems with WDM drivers if the user has selected the surround sound speaker configuration in Control Panel. For more information, see DSBUFFERDESC.


DirectSound 3-D Buffers

Each sound source in a 3-D environment is represented by a DirectSound3DBuffer8 object. This object controls the 3-D properties of the buffer from which it is obtained. This object is obtainable only from secondary sound buffers created with the DSBCAPS_CTRL3D flag. Methods of the object are used to set and retrieve parameters of a single sound source.

Applications must supply monaural sound sources when using the 3-D capabilities of DirectSound. If you attempt to create a buffer with the DSBCAPS_CTRL3D flag set and a wave format with more than one channel, an error results.

This section describes how your applications can obtain and manage 3-D buffer objects.The following topics are discussed:

  • Obtaining the 3-D Buffer Object
  • Batch Parameters for 3-D Buffers
  • Minimum and Maximum Distances
  • Processing Mode
  • Buffer Position and Velocity
  • Sound Cones


Obtaining the 3-D Buffer Object

The DirectSound3DBuffer8 object is obtained from a secondary DirectSound buffer that has been created with the DSBCAPS_CTRL3D flag in the lFlags member of the DSBUFFERDESC type.

If your application is using the DirectMusic performance and audiopaths, you can create an audiopath containing a 3-D buffer by passing DMUS_APATH_DYNAMIC_3D as the lType parameter to DirectMusicPerformance8.CreateStandardAudioPath.

You can also create a suitable audiopath from a configuration object. An audiopath configuration can specify 3-D parameters for a buffer. When the audiopath is created, the 3-D properties of the buffer are initialized with these parameters.

To obtain an object representing a 3-D buffer in an audiopath, call DirectMusicAudioPath8.GetObjectInPath, with lStage set to DMUS_PATH_BUFFER, as in the following example:

Dim dsb As DirectSound3dBuffer8

Set dsb = dmAudioPath.GetObjectinPath(DMUS_PCHANNEL_ALL, _
  DMUS_PATH_BUFFER, 0, GUID_ALL, 0, IID_DirectSound3DBuffer)

The following example, where m_ds is a DirectSound8 object, shows how to create a DirectSound3DBuffer8 object in an application that is not using the DirectMusic performance:

Dim dsbd As DSBUFFERDESC
Dim dsBuffer As DirectSoundSecondaryBuffer8
Dim ds3dBuffer As DirectSound3DBuffer8

' Create the secondary buffer.

dsbd.lFlags = DSBCAPS_CTRL3D
Set dsBuffer = m_ds.CreateSoundBufferFromFile("sound.wav", dsbd)

' Obtain the 3-D buffer object.

Set ds3dBuffer = dsBuffer.GetDirectSound3DBuffer


Batch Parameters for 3-D Buffers

Applications can retrieve or set a 3-D sound buffer's parameters individually or in batches. To set individual values, your application can use the applicable DirectSound3DBuffer8 method. However, applications often must set or retrieve all the values at once. You can do this with the DirectSound3DBuffer8.GetAllParameters and DirectSound3DBuffer8.SetAllParameters methods.

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.


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 is especially useful when an application must compensate for the difference in absolute volume levels of different sounds. Although a jet engine is much louder than a bee, for practical reasons these sounds must be recorded at similar absolute volumes. An application might use a minimum distance of 100 meters for the jet engine and 2 centimeters for the bee. With these settings, the jet engine would be at half volume when the listener was 200 meters away, but the bee would be at half volume when the listener was 4 centimeters away.

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, half as loud at 2 meters, a quarter as loud 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 sound does not get any quieter. The default maximum distance for a DirectSound 3-D 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, applications should set a reasonable maximum distance and include the DSBCAPS_MUTE3DATMAXDISTANCE flag when creating the buffer. This flag is automatically set on standard 3-D buffers created as part of an audiopath; see Standard Audiopaths.

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.

The following illustration shows how minimum and maximum distance affect the loudness of a jet and a bee at increasing distances.

Minimum and maximum distances

An application sets and retrieves the minimum distance value by using the DirectSound3DBuffer8.SetMinDistance and DirectSound3DBuffer8.GetMinDistance methods. Similarly, it can set and retrieve the maximum distance value by using the DirectSound3DBuffer8.SetMaxDistance and DirectSound3DBuffer8.GetMaxDistance methods.

By default, distance values are expressed in meters. See Distance Factor.

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, the sound source is positioned and oriented absolutely in world space. This is the default mode.

In head-relative mode, the buffer is automatically repositioned in world space as the listener moves and turns. Values set and retrieved through methods such as DirectSound3DBuffer8.SetPosition, DirectSound3DBuffer8.SetVelocity, and DirectSound3DBuffer8.GetConeOrientation are all relative to the current position, velocity, and orientation of the listener.

In disabled mode, 3-D sound processing is disabled and the sound seems to originate from the center of the listener's head.

An application sets the mode for a 3-D sound buffer by using the DirectSound3DBuffer8.SetMode method.


Buffer Position and Velocity

3-D sounds have position and velocity. It is entirely up to the application to specify values for both.

Position is expressed as a vector, relative to either world space or the listener, depending on the processing mode.

Velocity is measured in distance units per second—by default, meters per second. Velocity is used only in calculating the effects of Doppler shift and does not have to correspond to the actual rate of movement of the sound source.

An application can set and retrieve a sound source's position in 3-D space by using the DirectSound3DBuffer8.SetPosition and DirectSound3DBuffer8.GetPosition methods.

To set or retrieve the velocity, use the DirectSound3DBuffer8.SetVelocity and DirectSound3DBuffer8.GetVelocity methods. Velocity is measured in distance units per second—by default, meters per second.


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.

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.

Every 3-D 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.

An application sets or retrieves the angles that define sound cones by using the DirectSound3DBuffer8.SetConeAngles and DirectSound3DBuffer8.GetConeAngles methods. The outside cone angle must always be equal to or greater than the inside cone angle.

To set or retrieve the orientation of sound cones, an application can use the DirectSound3DBuffer8.SetConeOrientation and DirectSound3DBuffer8.GetConeOrientation methods.

An application sets and retrieves the outside cone volume by using the DirectSound3DBuffer8.SetConeOutsideVolume and DirectSound3DBuffer8.GetConeOutsideVolume methods.


DirectSound 3-D Listeners

In a virtual 3-D environment as in the real world, sounds exist only in relation to a point of reception. The 3-D sound effects in a DirectX Audio 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. By obtaining an object to represent the listener, 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 and manage global 3-D sound parameters. The following topics are discussed:

  • Obtaining the 3-D Listener
  • Batch Parameters for 3-D Listeners
  • Deferred Settings
  • Distance Factor
  • Listener Orientation
  • Listener Position and Velocity
  • Doppler Factor
  • Rolloff Factor


Obtaining the 3-D Listener

Global sound parameters are set and retrieved by using the DirectSound3DListener8 object, which is obtained from the primary buffer. There is only one primary buffer in an application, and only one listener.

If you are using the DirectMusic performance and audiopaths to play your 3-D sounds, you can obtain the listener from the audiopath by using DirectMusicAudioPath8.GetObjectInPath, setting the lStage parameter to DMUS_PATH_PRIMARY_BUFFER. In the following example, AudioPath is a DirectMusicAudioPath8 object:

Dim dx As New DirectX8

Dim perf As DirectMusicPerformance8
Dim audparams As DMUS_AUDIOPARAMS
Dim audiopath As DirectMusicAudioPath8
Dim listener As DirectSound3dListener8

Private Sub Form_Load()
  Set perf = dx.DirectMusicPerformanceCreate
  perf.InitAudio Me.hWnd, DMUS_AUDIOF_ALL, audparams, _
    Nothing, Nothing, DMUS_APATH_DYNAMIC_3D, 16
  Set audiopath = perf.GetDefaultAudioPath
  Set listener = audiopath.GetObjectinPath(0, _
    DMUS_PATH_PRIMARY_BUFFER, 0, vbNullString, 0, _
    IID_DirectSound3DListener)
End Sub

If your application is creating and managing its own sound buffers using only the DirectSound API, you must create a primary buffer object and then obtain the listener interface from that.

Create the primary buffer object by using the DirectSound8.CreatePrimarySoundBuffer method, specifying the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags in the lFlags member of the accompanying DSBUFFERDESC type. Call the DirectSoundPrimaryBuffer8.GetDirectSound3DListener method on the resulting buffer to obtain a DirectSound3DListener8 object. These steps are shown in the following example, where ds is a global DirectSound8 object:

Dim dsbd As DSBUFFERDESC
Dim dsbPrimary As DirectSoundPrimaryBuffer8
Dim waveFormat As WAVEFORMATEX
Dim ds3dListener As DirectSound3DListener8

' Create the primary buffer. The waveFormat parameter is ignored
' for primary buffers, so it doesn't have to be initialized.

dsbd.lFlags = DSBCAPS_CTRL3D Or DSBCAPS_PRIMARYBUFFER
Set dsbPrimary = ds.CreatePrimarySoundBuffer(dsbd, waveFormat)

' Create the DirectSound3DListener8 object.

Set ds3DListener = dsbPrimary.GetDirectSound3DListener

Once the listener has been obtained, the primary buffer object is not needed and can be allowed to go out of scope.


Batch Parameters for 3-D Listeners

Applications can retrieve or set a 3-D listener object's parameters individually or in batches. To set individual values, your application can use the applicable DirectSound3DListener8 object method. However, applications often must set or retrieve all the values that describe the listener at once. An application can perform these batch parameter manipulations in a single call by using the DirectSound3DListener8.GetAllParameters and DirectSound3DListener8.SetAllParameters methods.

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 3-D sound buffer and listener settings causes remixing, at the expense of CPU cycles. To minimize the performance impact of changing 3-D settings, use the DS3D_DEFERRED flag in the applyFlag parameter of any of the DirectSound3DListener8 or DirectSound3DBuffer8 methods that change 3-D settings. Then call the DirectSound3DListener8.CommitDeferredSettings method to execute all of the deferred commands at once.

Note Deferred settings are overridden 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.


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 3-D 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.3408 meters. You call the DirectSound3DListener8.SetDistanceFactor method, specifying 0.3048 as the distanceFactor parameter. From then on, you continue using feet in parameters to method calls, and they are automatically converted to meters.

You can retrieve the current distance factor set for a listener by using the DirectSound3DListener8.GetDistanceFactor method.

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 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, whether those units are in feet, meters, or any other measure. For more information, see Minimum and Maximum Distances.


Listener Orientation

Listener orientation 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.

An application can set and retrieve the listener's orientation by using the DirectSound3DListener8.SetOrientation and DirectSound3DListener8.GetOrientation methods.

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.


Listener Position and Velocity

An application can set and retrieve a listener's position in 3-D space by using the DirectSound3DListener8.SetPosition and DirectSound3DListener8.GetPosition methods.

To set or retrieve the velocity value that DirectSound uses to calculate Doppler-shift effects for a moving listener, use the DirectSound3DListener8.SetVelocity and DirectSound3DListener8.GetVelocity methods. Velocity is measured in distance units per second—by default, meters per second.

As with buffers, a listener's position and its velocity are completely independent. It is up to the application to set an appropriate velocity for the listener.


Doppler Factor

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. In other words, a value of 1 (or DS3D_DEFAULTDOPPLERFACTOR) means the Doppler shift that would be experienced in the real world is applied to the sound, a value of 2 means twice the real-world Doppler shift, and so on.

The Doppler factor can be set and retrieved by using the DirectSound3DListener8.SetDopplerFactor and DirectSound3DListener8.GetDopplerFactor methods.


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 variable 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 no rolloff is applied to a sound. Every other value represents a multiple of the real-world rolloff. In other words, a value of 1 (DS3D_DEFAULTROLLOFFFACTOR) means the rolloff that would be experienced in the real world is applied to the sound, a value of 2 means twice the real-world rolloff, and so on.

Set and retrieve the rolloff factor for all sounds by using the DirectSound3DListener8.SetRolloffFactor and DirectSound3DListener8.GetRolloffFactor methods.

To change the effect of distance for an individual sound buffer, you can set the minimum distance for the buffer. For more information, see Minimum and Maximum Distances.


Using Effects

DirectX Audio provides support for effects processing of sounds by DirectX Media Objects (DMOs). For general information on DMOs, see Introduction to DirectX Media Objects in the DirectShow documentation.

A standard set of effects is available to every DirectX application. Other DMOs can be registered on the system.

All the standard DMOs except Waves reverberation can process 8- or 16-bit PCM wave format data with one or two channels at any sample rate supported by DirectSound. Waves reverberation does not support 8-bit samples.

The following topics contain information on setting up and using effects:

  • Setting Effects on Buffers
  • Effect Parameters
  • Standard Effects

This section focuses on the use of effects in audiopaths, but much of the information is also relevant to applications that manage their own DirectSound buffers. See Using Effects in DirectSound.


Setting Effects on Buffers

If you are playing segments authored in DirectMusic Producer with audiopath configurations, any effects are set up when you create the audiopath from the configuration object. A standard audiopath might also contain effects. However, in some cases you may prefer to implement an effect on a custom audiopath at run time or add an effect to a standard audiopath. For example, you might want to add an effect to a standard audiopath so that you can apply the effect to wave or MIDI files.

To apply an effect to an audiopath, first obtain a DirectSoundSecondaryBuffer8 object for a buffer on the path. Then set one or more effects on that buffer by using DirectSoundSecondaryBuffer8.SetFX. The audiopath must be inactive.

To learn how to obtain a buffer object, see Retrieving Objects from an Audiopath. For information on how to identify standard audiopath buffers in the call to GetObjectInPath, see the audiopath types under Standard Audiopaths.

The following sample code, where dmPerformance is a DirectMusicPerformance8 object, sets a standard audiopath, retrieves a buffer from the path, and sets an echo effect on the buffer:

Dim dmAudioPath As DirectMusicAudioPath8
Dim dsBuffer As DirectSoundSecondaryBuffer8
Dim DSEffects(0) As DSEFFECTDESC
Dim lResults(0) As Long

' Create a standard audiopath with a source and
' environment reverb buffers. Don't activate the path;
' SetFX fails if the buffer is running.

Set dmAudioPath = dmPerformance.CreateStandardAudioPath( _
  DMUS_APATH_DYNAMIC_3D, 128, False)

' Get the buffer in the audiopath.

Set dsBuffer = dmAudioPath.GetObjectinPath(DMUS_PCHANNEL_ALL, _
  DMUS_PATH_BUFFER, 0, GUID_ALL, 0, IID_DirectSoundSecondaryBuffer)

' Describe the effect.

DSEffects(0).lFlags = 0
DSEffects(0).guidDSFXClass = DSFX_STANDARD_ECHO

' Set the effect on the buffer.

dsBuffer.SetFX 1, DSEffects, lResults

' You can check the value of lResults(0) here to see if and how
' the effect was allocated.

dmAudioPath.Activate (True)


Effect Parameters

To set or retrieve parameters of sound effects, you must first obtain the appropriate object from the buffer that contains the effect. The following classes give you access to parameters of the DMOs supplied with DirectX Audio:

  • DirectSoundFXChorus8
  • DirectSoundFXCompressor8
  • DirectSoundFXDistortion8
  • DirectSoundFXEcho8
  • DirectSoundFXFlanger8
  • DirectSoundFXGargle8
  • DirectSoundFXI3DL2Reverb8
  • DirectSoundFXParamEq8
  • DirectSoundFXWavesReverb8

To retrieve an effect object, pass DMUS_PATH_BUFFER_DMO as the lStage parameter to DirectMusicAudioPath8.GetObjectInPath. If the audiopath contains more than one buffer, lBuffer must be the index of the buffer. For information on the index numbers of buffers in standard audiopaths, see the audiopath types under Standard Audiopaths.

The following sample code retrieves an interface for the gargle effect on a buffer. It then uses this interface to change a parameter of the effect. Assume that the DirectMusicAudioPath8 object dmAudioPath has been obtained by calling DirectMusicPerformance8.CreateAudioPath on an audiopath configuration object.

Dim gargleParams As DSFXI3DL2GARGLE
Dim gargleFX As DirectSoundFXGargle8

Set gargleFX = dmAudioPath.GetObjectinPath(DMUS_PCHANNEL_ALL, _
  DMUS_PATH_BUFFER_DMO, 0, DSFX_STANDARD_GARGLE, 0, _
  IID_DirectSoundFXGARGLE)

gargleParams = gargleFX.GetAllParameters
gargleParams.lRateHZ = DSFXGARGLE_RATEHZ_MIN
gargleFX.SetAllParameters gargleParams

If your application is managing its own DirectSound buffers, you might need to take steps to ensure that changes in effect parameters take place immediately. For efficiency, DirectSound processes 100 milliseconds of sound data in a buffer, starting at the play cursor, before DirectSoundSecondaryBuffer8.Play is called. This can happen after any of the following calls:

  • DirectSound8.CreateSoundBufferFromFile
  • DirectSoundSecondaryBuffer8.WriteBuffer
  • DirectSoundSecondaryBuffer8.Stop
  • DirectSoundSecondaryBuffer8.SetCurrentPosition
  • DirectSoundSecondaryBuffer8.SetFX

If you call any of these methods and then change effect parameters, the new parameters will not be heard until the preprocessed data has been played. To avoid this situation, do one of the following:

  • Write data to the buffer after effect parameters have been changed, not before. This technique doesn't apply to buffers created from file, which already contain data.
  • Call Stop or SetCurrentPosition on the buffer to force preprocessing after you have set the parameters.


Standard Effects

This topic is an introduction to the sound effects provided with DirectX Audio. 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 delayof the echo.

This effect is represented by the DirectSoundFXChorus8 object. Its parameters are contained in the DSFXCHORUS type.


Compression

Compression is a reduction in the fluctuation of a signal above a certain amplitude.

This effect is represented by the DirectSoundFXCompressor8 object. Its parameters are contained in the DSFXCOMPRESSOR type.


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 DirectSoundFXDistortion8 object. Its parameters are contained in the DSFXDISTORTION type.


Echo

An echo effect causes an entire sound to be repeated after a fixed delay.

This effect is represented by the DirectSoundFXEcho8 object. Its parameters are contained in the DSFXECHO type.


Environmental Reverberation

DirectX supports environmental reverberation in accordance with the Interactive 3-D 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 in this release.

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. There is therefore only one direct path signal.
  • 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.

Reverb 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 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 a DirectSoundFXI3DL2Reverb8 object, and the parameters of the environment are contained in a DSFXI3DL2REVERB type.

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 DirectSoundFXI3DL2Reverb8.SetPreset.

To set custom properties, use DirectSoundFXI3DL2Reverb8.SetAllParameters. You can retrieve the current properties by using DirectSoundFXI3DL2Reverb8.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 DirectSoundFXFlanger8 object. Its parameters are contained in the DSFXFLANGER type.


Gargle

The gargle effect modulates the amplitude of the signal.

This effect is represented by the DirectSoundFXGargle8 object. Its parameters are contained in the DSFXGARGLE type.


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 DirectSoundFXParamEq8 object. Its parameters are contained in the DSFXPARAMEQ type.


Waves Reverberation

The Waves reverberation effect is intended for use with music. The Waves reverberation DMO is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

This effect is represented by the DirectSoundFXWavesReverb8 object. Its parameters are contained in the DSFXWAVESREVERB type.


Buffer Chains

A sound does not necessarily go through only a single secondary sound buffer. It is possible for buffers in an audiopath to send data to other secondary buffers. The advantage in doing so is that sounds from multiple buffers can be directed to a shared buffer where common 3-D parameters or special effects can be applied. Shared buffers can also be more efficient.

Buffer chains are set up automatically when an audiopath is created from an audiopath configuration embedded in a DirectMusic Producer file. For more information, see Using Audiopaths.

DirectX 8.1 does not support the creation of buffer chains by using the DirectSound API.


Using Compositional Elements

This section is a guide to incorporating dynamic musical components into a DirectX Audio application. It is presumed that you have a basic understanding of elements such as chordmaps and styles. If not, you should first read Compositional Music Elements.

It's possible to incorporate files from DirectMusic Producer into applications without working with individual compositional elements. Many applications use only fully authored segments. However, using individual components gives greater control over the performance at run time.

The following topics are discussed in this section:

  • Music Files for Composition
  • Overview of Programming for Composition
  • Using Styles
  • Using Motifs
  • Using Chordmaps
  • Using Templates
  • Using Transitions


Music Files for Composition

When programming for DirectMusic composition, you will use a variety of files produced in a tool such as DirectMusic Producer. You load these elements into the application as COM objects and obtain objects for them. See Loading Audio Data.

The following table summarizes the types of file objects you will encounter. Any of these objects can also be obtained from a resource by the corresponding method, such as DirectMusicLoader8.LoadBandFromResource.

Element | DirectMusicLoader8 method | Class | File type
Band | LoadBand | DirectMusicBand8 | bnd
Chordmap | LoadChordMap | DirectMusicChordMap8 | cdm
DLS collection | LoadCollection | DirectMusicCollection | dls
Segment | LoadSegment | DirectMusicSegment8 | sgt
Style | LoadStyle | DirectMusicStyle8 | sty

Note Bands can be authored as part of a style, in which case they are automatically loaded when the style is loaded. Similarly, styles and bands can be authored into a segment, in which case you don't need separate files for those elements.

Files can also contain references to other files. If a style contains a reference to a band file, the band is automatically loaded when the style is, provided the loader can find the band file.


Overview of Programming for Composition

When you implement music composed at run time, you will use previously authored objects as building blocks. In consultation with the author or other content provider, you can choose to get the musical data in the form of small building blocks that offer you the greatest possible flexibility and variation at run time, or you can use larger prefabricated elements that define the form of the music more fully.

Using the largest building blocks, you load highly structured segments (either style-based or MIDI-based) that contain everything the performance needs to know about the music in order to play it. All you have to do is load the segment by using the DirectMusicLoader8.LoadSegment or the DirectMusicLoader8.LoadSegmentFromResource method. You then pass the returned DirectMusicSegment8 object to the DirectMusicPerformance8.PlaySegmentEx method. The style playback engine selects pattern variations from the style and plays them according to a fixed chord progression—or, in the case of a MIDI-based segment, simply plays the MIDI sequence. Band changes are usually contained in the segment as well.

If you want to use smaller building blocks, you obtain the following elements:

  • Chordmaps, which are road maps of chord progressions.
  • Styles, which define a basic melody and rhythm with variations, motifs, and embellishments.
  • Template segments, which are structural plans that control various aspects of playback, including the length of the segment, whether it loops, where groove level changes and embellishment patterns are to be placed, and what types of chords in the chordmap are to serve as signposts.

You can construct a segment by combining any chordmap, style, and template, using the DirectMusicComposer8.ComposeSegmentFromTemplate method.

To have even more flexibility in music composition at run time, you can create segments based on predefined shapes rather than templates, using the DirectMusicComposer8.ComposeSegmentFromShape method. The shape is used in creating the command and signpost tracks, which control the choice of embellishment patterns, the chord progression, and the frequency of chord changes.

When playing segments, you can also control the band used to play the parts. Bands are typically authored right into styles and templates, but they can also be supplied as separate files. To make band changes dynamically, create a secondary segment containing only the band, using the DirectMusicBand8.CreateSegment method, and play this segment when it is time to assign instruments and instrument settings to the primary segment. For more information, see Using Bands.


Using Styles

The DirectMusic style object represents a collection of musical patterns, usually including embellishments and motifs, with a time signature, tempo, and band. It defines the basic rhythm and the notes to be played in each instrument part.

For a conceptual overview, see Styles.

A style by itself does not contain enough information to create a segment of music at run time. For this you need two other components: a chordmap, which is a scheme of chord progressions, and a command track to set the groove level and embellishments as the music plays. The command track can come from a template or be generated at run time from a shape. The chordmap generally comes from a chordmap file or resource.

To create a segment with a command track based on a template, call the DirectMusicComposer8.ComposeSegmentFromTemplate method. (See Using Templates.)

To create a segment based on a shape, call the DirectMusicComposer8.ComposeSegmentFromShape method. You supply pointers to a style and a chordmap. You also supply a rate of harmonic motion, which controls the frequency of chord changes, and a shape constant, which determines the progression of groove levels and embellishments.


Using Motifs

A motif is a special kind of pattern in a style intended to be played over the basic style pattern, typically in response to an interactive event. Although a motif can be as complex as any other pattern, even containing variations and multiple instrument parts, usually it is a short, simple musical figure that sounds good against a variety of background patterns. It might also be a sound effect played by a custom DLS instrument or instruments.

All the motifs authored into a style become available to you as soon as you have loaded that style. To get a particular motif ready for playback, call the DirectMusicStyle8.GetMotif method, passing in the name of the motif. You might know this from the documentation for the style, or you can obtain it from an index value by using the DirectMusicStyle8.GetMotifName method.

The following code example obtains and plays the first motif in the style:

' style is a DirectMusicStyle8.
' perf is the DirectMusicPerformance8.

Dim MotifName As String
Dim segMotif As DirectMusicSegment8

MotifName = style.GetMotifName(1)
Set segMotif = style.GetMotif(MotifName)
Call perf.PlaySegmentEx(segMotif, DMUS_SEGF_SECONDARY, 0)

Note that segMotif is played as a secondary segment, because a motif is normally played over a primary segment. You cannot play a motif as a primary segment, because it does not have a chord track or band track. If you want to play a motif against silence, create a primary segment from a style that has only blank patterns, and keep that segment playing while you play the motif.


Using Chordmaps

A chordmap object represents a collection of chords that provides the foundation of the harmonic structure and the mood of the music. A chordmap contains several pathways with many interconnected chords, providing many possibilities for the composition engine to choose from in determining the chord progression in a piece of music.

For a conceptual overview, see Chordmaps.

For authored segments, applications don't normally need to concern themselves with chordmaps. The chordmap is used at the authoring stage to create a fixed chord progression. However, chordmaps can be used to compose segments at run time and to alter the chord progression of existing segments.

You set the chordmap for a composition when you create a segment by using either DirectMusicComposer8.ComposeSegmentFromTemplate or DirectMusicComposer8.ComposeSegmentFromShape. For more information, see Using Styles.

Once a segment has been created, you can change its chordmap by calling the DirectMusicComposer8.ChangeChordMap method. This has the effect of changing the mood of the music without altering its basic rhythm and melody.


Using Templates

A template is a segment that can be used in composing a playable segment of music at run time. The template sets the length of the segment and any loop points. It can provide the command track, which controls changes in the groove level and the choice of embellishment patterns. It also prescribes how the chordmap is used in composing the segment, by specifying from which signpost group each new chord must come.

For a conceptual overview, see Templates.

A template is represented by a DirectMusicSegment8 object.

There are two ways to obtain a template object:

  • Load it from a template file or resource by using DirectMusicLoader8.LoadSegment or DirectMusicLoader8.LoadSegmentFromResource.
  • Create it from a shape, using the DirectMusicComposer8.ComposeTemplateFromShape method. You choose the length, the overall shape, whether intro and end embellishment patterns are to be played, and how long the ending is to be.

Once you have obtained a template segment object, you can pass it to the DirectMusicComposer8.ComposeSegmentFromTemplate method, along with pointers to a style and a chordmap. You also supply a rate of harmonic motion, which sets the frequency of chord changes. The ComposeSegmentFromTemplate method creates a segment that can be passed to the DirectMusicPerformance8.PlaySegmentEx method.


Using Transitions

To avoid a sudden and perhaps discordant break when stopping one segment and beginning another, or when bringing the music to a close, you can have the composer object create an intermediate or closing segment that provides an appropriate transition.

You have your choice of three techniques for composing transitional segments:

  • The DirectMusicPerformance8.PlaySegmentEx method allows you to specify a segment in the Transition parameter. This segment is used as a template for a newly composed transition. The transition is played at startTime, and then the segment specified by Source is played.
  • The DirectMusicComposer8.AutoTransition method, given a DirectMusicPerformance8 object, creates a transition from the currently playing segment to a second segment of your choice, and then automatically cues the transitional segment and the second segment for playback. The transition begins playing immediately or on the next boundary, as specified in the lFlags parameter. Optionally, the second segment can be Nothing so that the transition is to silence.
  • The DirectMusicComposer8.ComposeTransition method composes a transition from any point in one segment to the beginning of a second segment, or to silence, and returns a DirectMusicSegment8 object so that the application can play the transition.

The AutoTransition and ComposeTransition methods both take a chordmap, a command, and a set of flags as parameters.

  • The chordmap, as usual, is used to create a chord track that defines the chord progression in the segment.
  • The command is one of the CONST_DMUS_COMMANDT_TYPES enumeration. It determines which type of pattern—either an ordinary groove pattern or one of the embellishments—is called for in the command track of the transitional segment. When the segment plays, an appropriate pattern is selected from the style.
  • The flags are from CONST_DMUS_COMPOSEF_FLAGS and further define the transition, principally its timing. The DMUS_COMPOSEF_MODULATE flag can be used to cause the transition to move smoothly from one tonality to another; it can't be used when there is no second segment, because there can be no modulation to silence.

Transitions created by AutoTransition and ComposeTransition are normally a single measure in length. However, they can be longer if the DMUS_COMPOSEF_LONG flag is included and the embellishment in the style is more than one measure long. They also contain at least two measures if they are of type DMUS_COMMANDT_ENDANDINTRO.


Track Composition

Most tracks in a segment are fixed and generate the same data each time the segment is played. However, tracks can generate their data dynamically each time they start playing or each time they loop, provided they are configured to do so.

One standard track, the signpost track, supports composition. The signpost track composes a new chord track from a chordmap.


Using Audio Scripts

Scripts are objects authored in an application that contains a script editor, such as DirectMusic Producer. Although they consist mainly of text, script objects also contain a few binary parameters.

DirectX for Visual Basic does not enable applications to load and call audio scripts through the API. However, a segment authored in DirectMusic Producer can contain a script track that triggers calls to routines in one or more scripts.


Wave Playback in DirectSound

This section is a guide to playing waves through DirectSound buffers without making use of the services provided by the DirectMusic loader and performance objects.

For most applications written for DirectX 8.0 and later, the best way to play wave sounds is to load them as segments and play them through the performance. Doing so requires less code, allows tighter integration of sound effects and music, and provides greater functionality such as the ability to mix sounds on an audiopath before they enter a 3-D buffer. However, you can still play wave sounds directly to buffers if you so choose.

Information in this section is contained in the following topics:

  • DirectSound Playback Overview
  • DirectSound Devices
  • DirectSound Buffers
  • Using Wave Data
  • Using Effects in DirectSound


DirectSound Playback Overview

The DirectSound object represents a device and is used to manage that device and create sound buffers.

Multiple applications can create DirectSound 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.

The DirectSound buffer object represents a buffer containing sound data. Buffer objects are used to start, stop, and pause sound playback, as well as to set attributes such as frequency and format.

The primary buffer holds the audio that the listener will hear. Secondary sound buffers each contain a single sound or stream of audio. DirectSound automatically creates a primary buffer, but it is the application's responsibility to create secondary buffers. When sounds in secondary buffers are played, DirectSound mixes them in the primary buffer and sends them to the output device. Only the available processing time limits the number of buffers that DirectSound can mix.

A short sound can be loaded into a 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.

DirectX for Visual Basic has methods for creating sound buffers that automatically load a complete sound from a wave file or resource. For longer sounds, the application must handle the parsing and streaming.


DirectSound Devices

The first step in implementing DirectSound in an application is to create a DirectSound object, which represents a sound device.

This section describes how your application can enumerate available sound devices, create the DirectSound object for a device, and use the methods of the object to set the cooperative level, retrieve the capabilities of the device, create sound buffers, and set the configuration of the system's speakers.

  • Enumeration of Sound Devices
  • Creating the DirectSound Object
  • Cooperative Levels
  • Device Capabilities
  • Speaker Configuration


Enumeration of Sound Devices

For an application that is simply going to play sounds through the user's preferred playback device, you don't need to enumerate the available devices. When you create the DirectSound8 object by calling the DirectX8.DirectSoundCreate function, you can specify a default device. For more information, see Creating the DirectSound Object.

If you are looking for a particular kind of device, wish to offer the user a choice of devices, or need to work with two or more devices, you must enumerate the devices available on the system.

Enumeration serves three purposes:

  • Reports what hardware is available.
  • Supplies a globally unique identifier (GUID) for each device.
  • Enables you to create a temporary DirectSound object for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, you must first call the DirectX8.GetDSEnum method. This method creates a DirectSoundEnum8 object containing a collection of DirectSound-capable devices. Call the DirectSoundEnum8.GetCount method to ascertain the number of available devices. Information on each device is returned by the DirectSoundEnum8.GetDescription, DirectSoundEnum8.GetGuid, and DirectSoundEnum8.GetName methods, each of which takes as a parameter the index of a device within the collection.

The following sample application prints the description of each sound device:

Dim dx As New DirectX8
Dim dsenum As DirectSoundEnum8

Private Sub Form_Load()
  Set dsenum = dx.GetDSEnum
  For x = 1 To dsenum.GetCount
  Debug.Print dsenum.GetDescription(x), " ",
  Next x
End Sub

Note The first device enumerated is always called "Primary Sound Driver", and its GUID is all zeros. 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 DirectSound Object

Create the DirectSound8 object by using the DirectX8.DirectSoundCreate method. The single parameter specifies the GUID of the device to be associated with the object. You can obtain this GUID by Enumeration of Sound Devices, or you can specify a default device by passing one of the following values:

DSDEVID_DEFAULTPLAYBACK

The default system audio device. You can also specify this device by passing vbNullString 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.

The creation method raises an error if there is no sound device or if the sound device is under the control of an application using the waveform audio (non-DirectSound) 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 example code creates a DirectSound8 object using the default system device:

Dim m_dx As New DirectX8
Dim m_ds As DirectSound8
Set m_ds = m_dx.DirectSoundCreate(vbNullString)


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 DirectSound8 object, you must set the cooperative level for the device with the DirectSound8.SetCooperativeLevel method before you can play sounds.

The following example code sets the cooperative level for the DirectSound8 object m_ds. The hwnd argument is the handle to the application window.

m_ds.SetCooperativeLevel Me.hWnd, DSSCL_PRIORITY

DirectSound defines three cooperative levels for sound devices, represented by the values DSSCL_NORMAL, DSSCL_PRIORITY, and DSSCL_WRITEPRIMARY.

Note

The DSSCL_EXCLUSIVE cooperative level available in versions earlier than DirectX 8.0 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, 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, 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

Visual Basic applications should not use the DSSCL_WRITEPRIMARY cooperative level. This level is for specialized applications that do not use the DirectSound mixer.


Device Capabilities

DirectSound enables your application to retrieve the hardware capabilities of the sound device. Most applications will 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 DirectX8.DirectSoundCreate method to create a DirectSound8 object, your application can retrieve the capabilities of the sound device by calling the DirectSound8.GetCaps method.

The following example retrieves the capabilities of the device represented by the DirectSound8 object m_ds:

Dim caps As DSCAPS
m_ds.GetCaps caps

The DSCAPS type 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.

If your application scales to hardware capabilities, you should call the DirectSound8.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 3-D effects for the user's sound system.

In Windows 98 and Windows 2000, the speaker configuration can be set by the user in Control Panel. An application can retrieve this value by using DirectSound8.GetSpeakerConfig and override it by calling DirectSound8.SetSpeakerConfig.

There is no guarantee that SetSpeakerConfig will have an immediate effect; it might simply change a registry setting that will not take effect until the computer is restarted. Instead of using this method, applications should advise the user to change the speaker configuration through Control Panel.


DirectSound Buffers

DirectSound buffer objects control the delivery of wave data from a source to a destination. The source might be a synthesizer, another buffer, a 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 PCM samples to sound waves.

The information in this section is of interest mainly for applications originally written for previous versions of DirectSound, or applications that need to have low-level control over buffers. If your application is playing sounds by using the DirectMusic performance object, buffer creation and management is done automatically. You can, however, obtain buffer objects in order to gain access to parameters for 3-D effects and effects in DMOs. For more information, see Using Effects and 3-D Sound.

Information about using DirectSound buffers is contained in the following topics:

  • Buffer Basics
  • Creating Secondary Buffers
  • Duplicating Buffers
  • Buffer Control Options
  • 3-D Algorithms for Buffers
  • Filling and Playing Static Buffers
  • Using Streaming Buffers
  • Playback Controls
  • Play and Write Cursors
  • Play Buffer Notification
  • Mixing Sounds
  • Buffer Management

For information about capture buffers, see Capturing Waves.


Buffer Basics

When DirectSound is initialized, it automatically creates and manages a primary buffer for mixing sounds and sending them to the output device.

Your application must create at least one secondary sound buffer for storing and playing individual sounds. For more information on how to do this, see Creating Secondary Buffers.

A secondary buffer can exist throughout the life of an application or it can be destroyed when no longer needed. It can contain a single sound that is to be played repeatedly, such as a sound effect in a game, or it can be filled with new data from time to time. The application can play a sound stored in a secondary buffer as a single event or as a looping sound that plays continuously. Secondary buffers can also be used to stream data, in cases where a sound file contains more data than can conveniently be stored in memory.

Buffers can be located either in hardware or in software. Hardware buffers are mixed by the sound card processor, and software buffers are mixed by the CPU. Software buffer data is always in system memory; hardware buffer data can be in system memory or, if the application requests it and resources are available, in on-board memory. For more information, see Dynamic Voice Management and Hardware Acceleration on ISA and PCI Cards.

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.


Creating Secondary Buffers

To create a secondary sound buffer, call the DirectSound8.CreateSoundBuffer, DirectSound8.CreateSoundBufferFromFile, or DirectSound8.CreateSoundBufferFromResource method. These methods create a DirectSoundSecondaryBuffer8 object, which can then be used to manipulate and play the buffer.

CreateSoundBufferFromFile and CreateSoundBufferFromResource are good methods to use when the sound is not very long. DirectSound creates a buffer just big enough to hold the entire sound, matches its wave format to the format of the data, and fills it with the data. CreateSoundBuffer is suitable for streaming buffers; however, you have to do your own parsing of the wave file or resource as well as handling the streaming of data to the buffer.

Always specify the DSBCAPS_GETCURRENTPOSITION2 flag in the DSBUFFERDESC type when creating a streaming buffer.

The following example shows how to create a streaming buffer able to hold 2 seconds of data. Assume that the m_ds variable has been set to a DirectSound8 object.

Dim m_dsb As DirectSoundSecondaryBuffer8

Public Sub CreateSoundBuffer()

  Dim buffdesc As DSBUFFERDESC

  ' Describe the sound buffer to be created.

  With buffdesc
  lFlags = DSBCAPS_CTRLPAN Or DSBCAPS_CTRLVOLUME _
    Or DSBCAPS_CTRLFREQUENCY

  With .fxFormat
  .nFormatTag = WAVE_FORMAT_PCM
  .nChannels = 2
  .lSamplesPerSec = 22050
  .nBitsPerSample = 16
  .nBlockAlign = (.nChannels * .nBitsPerSample) / 8
  .lAvgBytesPerSec = .lSamplesPerSec * .nBlockAlign
  .nSize = 0  ' Ignored for WAVE_FORMAT_PCM
  End With

  lBufferBytes = .fxFormat.lAvgBytesPerSec * 2

  End With

  Set m_dsb = ds.CreateSoundBuffer(buffdesc)

End Sub

Creating a buffer from a file or resource is much simpler, as the following example shows:

Dim m_dsb As DirectSoundSecondaryBuffer8
Dim buffdesc As DSBUFFERDESC

buffdesc.lFlags = DSBCAPS_CTRLPAN Or DSBCAPS_CTRLVOLUME _
  Or DSBCAPS_CTRLFREQUENCY
Set dsbuffer = ds.CreateSoundBufferFromFile( _
  "c:\media\ding.wav", dsbdesc)

In this case, the format of the buffer is based on that of the data, and the method places this information in dsbdesc.fxFormat.

DirectSound allocates hardware resources to the first buffer that can take advantage of them. 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 type. 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 DirectSoundSecondaryBuffer8.GetCaps method and checking the lFlags member of the DSBCAPS type for either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flags. One or the other is always specified.

Setting the DSBCAPS_STATIC flag lets DirectSound know that the buffer should be created in on-board hardware memory if possible. The buffer creation method does not fail if a hardware buffer is not available. This flag has no effect on most modern sound cards, which use system memory for their buffers. Hardware static buffers should be used only for short sounds that are to be played repeatedly. For more information, see Voice Management on ISA and PCI Cards.


Duplicating Buffers

You can create two or more secondary buffers containing the same data by using the DirectSound8.DuplicateSoundBuffer method. You cannot duplicate the primary buffer. There is no guarantee that the duplicate buffer actually shares memory with the original buffer, so it is unwise to make changes to one buffer in the expectation that these changes will be reflected in all 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 lFlags member of the DSBUFFERDESC type, which can contain one or more DSBCAPS_CTRL* flags.

The following controls are available:

  • 3-D properties
  • Effects
  • Frequency
  • Pan
  • Volume
  • Position notification

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.

Note that certain combinations of controls are not allowed. For example, pan and 3-D are mutually exclusive.

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 DirectSoundSecondaryBuffer8.SetVolume method, the method can succeed only if the DSBCAPS_CTRLVOLUME flag was specified when the buffer was created. Otherwise, the method fails and raises the DSERR_CONTROLUNAVAIL error.

See also Playback Controls.


3-D 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 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. For more information, see Voice Management on ISA and PCI Cards.

A static buffer can be created and filled with data by using a single method call, either DirectSound8.CreateSoundBufferFromFile or DirectSound8.CreateSoundBufferFromResource.

The following sample code creates a static buffer from the wave identified as "bounce" in the resource file. Assume that m_ds is a DirectSound8 object.

Dim dsbd As DSBUFFERDESC
Dim dsbBounce As DirectSoundSecondaryBuffer8

dsbd.lFlags = DSBCAPS_CTRLVOLUME
Set dsbBounce = m_ds.CreateSoundBufferFromResource( _
    vbNullString, "bounce", dsbd)

The resource file has been compiled into the executable file, so no module name needs to be provided. Nor does the value of the lBufferBytes member of the DSBUFFERDESC type need to be set, because the method determines the size of the buffer from the size of the data. The WAVEFORMATEX type receives information about the wave format from the header stored in the resource.

To play the buffer, call DirectSoundSecondaryBuffer8.Play, as in the following example:

dsbResource.SetCurrentPosition 0
dsbResource.Play 0

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 DirectSoundSecondaryBuffer8.Stop. When you stop a buffer prematurely, the play cursor remains where it is. Hence the call to DirectSoundSecondaryBuffer8.SetCurrentPosition in the example, which ensures that the buffer starts from the beginning.

You can also create an empty static buffer by using DirectSound8.CreateSoundBuffer and then fill it with data from another location in memory by using the DirectSoundSecondaryBuffer8.WriteBuffer method.

More information on writing to secondary buffers is given in the next topic, Using Streaming Buffers.


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 DirectSoundSecondaryBuffer8.Play method, specifying DSBPLAY_LOOPING in the flags parameter.

To halt playback, call the DirectSoundSecondaryBuffer8.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.

Stream data into a buffer by using the DirectSoundSecondaryBuffer8.WriteBuffer method. This method lets you write data to any portion of the buffer. Although it's possible to write to the entire buffer, you must not do so while it is playing. Refresh only a portion 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. For more information, see Play and Write Cursors.

The following sample code writes 1000 bytes of data from the byte array myBuffer to the beginning of the buffer represented by dsb:

dsb.WriteBuffer 0, 1000, myBuffer(0), DSBLOCK_DEFAULT

WriteBuffer handles wraparound transparently. Suppose the secondary buffer has been created with a size of 10,000 bytes, and the application writes 5000 bytes to an offset past the midpoint of the buffer, as follows:

dsb.WriteBuffer 8000, 5000, myBuffer(0), DSBLOCK_DEFAULT

This call writes the first 2000 bytes to the last part of the buffer and the next 3000 bytes to the beginning of the buffer.

It is the application's responsibility to track the offset for the next data write. The easiest way to do this is by setting notification positions and writing a fixed number of bytes each time an event is triggered.

For more information, see the following topics:

  • Play and Write Cursors
  • Play Buffer Notification
  • Reading Wave Files


Playback Controls

To retrieve and set the volume at which a buffer is played, your application can use the DirectSoundSecondaryBuffer8.GetVolume and DirectSoundSecondaryBuffer8.SetVolume methods. Equivalent methods are available on the DirectSoundPrimaryBuffer8 object. Setting the volume on the primary buffer changes the waveform-audio volume of the sound card.

By calling the DirectSoundSecondaryBuffer8.GetFrequency and DirectSoundSecondaryBuffer8.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 pan, use the DirectSoundSecondaryBuffer8.GetPan and DirectSoundSecondaryBuffer8.SetPan methods. Equivalent methods are available on the DirectSoundPrimaryBuffer8 object.

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 DirectSoundSecondaryBuffer8.Play method always starts playing at the buffer's play cursor. When a buffer is created, the cursor position is set to zero. As a sound is played, the cursor moves and always points to the next byte of data to be output. When the buffer is stopped, the cursor remains at the next byte of data.

The write cursor is the point after which it is safe to write data into the buffer. The block between the current play position and the current write position 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 position and the write position are like two hands sweeping around the face at the same speed, the write position always keeping a little ahead of the play position. If the play position points to the 1 and the write position 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 position moves with the play position, 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 DirectSoundSecondaryBuffer8.GetCurrentPosition method. The DirectSoundSecondaryBuffer8.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

When streaming audio, you may want your application to be notified when the play cursor reaches a certain point in the buffer, or when playback is stopped. By using the DirectSoundSecondaryBuffer8.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.

To set notification events on a buffer, you must first implement the DirectXEvent8 class in the form that contains the code for the buffer. Create a DirectXEvent8.DXCallback method by choosing DirectXEvent8 from the drop-down class list, and add the code you want to be executed when the event is signaled.

Create an event handle by calling the DirectX8.CreateEvent method and pass the event handle in the hEventNotify member of a DSBPOSITIONNOTIFY type. Pass the type to the DirectSoundSecondaryBuffer8.SetNotificationPositions method. The event handle will now be passed to DirectXEvent8.DXCallback whenever the play cursor reaches that position.

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.

The following example code shows how to set up a single notification position. The following are the relevant lines in the Declarations section of the module:

Implements DirectXEvent8

Dim gDX As New DirectX8
Dim gDSB As DirectSoundSecondaryBuffer8
Dim endEvent As Long
Dim dsbpn(0) As DSBPOSITIONNOTIFY

Note that dsbpn must be an array, even though it contains only a single notification position.

In the Form_Load subroutine, an event is created:

endEvent = gDX.CreateEvent(Me)

After the DirectSoundSecondaryBuffer8 object has been created, the notification position is set and associated with the event, as follows:

With dsbpbn(0)
  .hEventNotify = endEvent
  .lOffset = DSBPN_OFFSETSTOP
End With
gDSB.SetNotificationPositions 1, dsbpn()

The offset of the notification, DSBPN_OFFSETSTOP or -1, is a special value indicating that the event is to be set when the buffer stops playing, either because it was not looping and the end of the buffer has been reached, or because the application called the DirectSoundSecondaryBuffer8.Stop method. When this happens, the application-defined callback function is automatically called, with the event identifier endEvent being passed in as the parameter.

Private Sub DirectXEvent8_DXCallback(ByVal eventid As Long)
  If eventid = endEvent Then
  lblStatus.Caption = "Buffer stopped."
  End If
End Sub


Mixing Sounds

It is easy to mix multiple streams with DirectSound. You simply create secondary sound buffers, obtaining a DirectSoundSecondaryBuffer8 object for each sound. You then play the buffers simultaneously. DirectSound takes care of the mixing in the primary buffer and plays the result.

The DirectSound mixer produces the best sound quality if all your application's sounds use the same wave 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 and calling the DirectSoundPrimaryBuffer8.SetFormat method. You need a cooperative level of DSSCL_PRIORITY or higher in order to call the SetFormat method. DirectSound will restore the hardware format to the format specified in the last call every time the application gains the input focus.

You must set the format of the primary buffer before creating any secondary buffers.

Note With 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.


Buffer Management

The DirectSoundPrimaryBuffer8.GetCaps and DirectSoundSecondaryBuffer8.GetCaps methods retrieve the capabilities of a buffer.

Your application can use the DirectSoundPrimaryBuffer8.GetStatus or DirectSoundSecondaryBuffer8.GetStatus method to determine if the buffer is playing or if it has stopped.

You can use the DirectSoundPrimaryBuffer8.GetFormat or DirectSoundSecondaryBuffer8.GetFormat method to retrieve information about the format of the sound data in the buffer. You also can use the DirectSoundPrimaryBuffer8.SetFormat method to retrieve and set the format of the sound data in the primary buffer.

Note There is no SetFormat method for DirectSoundSecondaryBuffer8. After a secondary buffer is created, its format is fixed. If you need a secondary buffer that uses 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 is raised when the DirectSoundSecondaryBuffer8.WriteBuffer or DirectSoundSecondaryBuffer8.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 DirectSoundSecondaryBuffer8.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 Wave Data

DirectSound buffers play only waveform audio data, which consists of digital samples of the sound at a fixed sampling rate. The representation of an analog signal by a sequence of numbers is known as pulse code modulation (PCM).

Wave data is usually stored in files or resources in Resource Interchange File Format (RIFF). The data includes a description of the wave format, including parameters such as the sampling rate and number of output channels.

The particular format of a sound can be described by a WAVEFORMATEX type.

Note The WAVEFORMATEX type in the DirectX for Visual Basic type library is not identical to the WAVEFORMATEX structure declared in Mmreg.h and used in the format chunk of a wave file or resource. For information on how to read a format chunk and copy the relevant data into a DirectX WAVEFORMATEX type, see Reading Wave Files.

When you are creating a static buffer by using DirectSound8.CreateSoundBufferFromFile or DirectSound8.CreateSoundBufferFromResource, you do not specify a buffer format, because the format of the created buffer always matches the format of the data. You do, however, have to specify the format of any buffer created by using DirectSound8.CreateSoundBuffer, and this format must match the format of the data you intend to play in the buffer.

DirectSound does not support compressed wave formats. Applications should use the audio compression manager (ACM) functions, provided with the Win32 APIs in the Platform SDK, to convert compressed audio to PCM format before writing the data to a sound buffer. Alternatively, use the DirectMusic loader, which automatically enlists the help of ACM when loading compressed waves for playback through the DirectMusic performance.

More information on waves is included in the following topics:

  • Multichannel Wave Formats
  • Reading Wave Files
  • Reading Wave Data from a Resource


Multichannel Wave Formats

DirectX for Visual Basic does not support wave formats with more than two channels.


Reading Wave Files

This topic explains how to load data from wave files into DirectSound buffers without the help of the DirectMusic loader and performance. Most applications do not need to work directly with wave data and buffers. For the preferred method of loading and playing waves, see Loading Audio Data and Playing Sounds.

For short sounds, the easiest way to play a wave file using DirectSound alone is to load it into a static buffer by calling the DirectSound8.CreateSoundBufferFromFile method. See Creating Secondary Buffers.

For larger files that will not conveniently fit in memory, you need to create a streaming buffer and read the file in pieces.

Wave files are in the Resource Interchange File Format (RIFF), which consists of a file header followed by variable number of "chunks," each made up of a header and data. The chunk header consists of a four-character tag identifying the type of data and a Long giving the length of the data.

The wave file header is organized as follows:

  • The string "RIFF", which can also be read as the Long &H46464952.
  • A Long giving the size of the file.
  • The string "WAVE", which can also be read as the Long &H45564157.

The first chunk is always the format chunk, which looks like this:

  • The string "fmt" followed by a space.
  • A Long giving the size of the format data.
  • Data describing the wave format of the data. For files in PCM format, this is 16 bytes of data equivalent to that in the WAVEFORMATEX type.

The PCM sample data in a wave file is contained in a chunk beginning with the string "data", which can also be read as the Long &H61746164. Most often this chunk immediately follows the format chunk, but because RIFF is an extensible format, there is no guarantee that some other type of chunk will not precede it. Your file parser must be capable of ignoring chunks it cannot handle.

To parse a wave file, it is helpful to have three user-defined types. The first will receive all the information in the file header and in the header of the format chunk.

Private Type FileHeader
  lRiff As Long
  lFileSize As Long
  lWave As Long
  lFormat As Long
  lFormatLength As Long
End Type

The second type will receive the format data. You can't use the WAVEFORMATEX type for this, because the members are in a different order. Your user-defined type needs to retrieve only 16 bytes, because if WAVEFORMATEX.nSize is present, it is always zero in standard PCM files.

Private Type WaveFormat
  wFormatTag As Integer
  nChannels As Integer
  nSamplesPerSec As Long
  nAvgBytesPerSec As Long
  nBlockAlign As Integer
  wBitsPerSample As Integer
End Type

The third type can be used to retrieve the header of any chunk, including the data chunk.

Private Type ChunkHeader
  lType As Long
  lLen As Long
End Type

The following sample function verifies that a file is a RIFF wave file, seeks the beginning of the sample data, and returns a WAVEFORMATEX type containing information about the wave format:

Dim FileFree As Long     ' Global file handle.
Dim lDataLength As Long    ' Global data length.

Private Function FillFormat(FileName As String) As WAVEFORMATEX

  Dim Header As FileHeader
  Dim HdrFormat As WaveFormat
  Dim chunk As ChunkHeader
  Dim by As Byte
  Dim i As Long

  ' Open the file and read the header.

  Close #FileFree
  FileFree = FreeFile
  Open FileName For Binary Access Read As #FileFree
  Get #FileFree, , Header

  ' Check for "RIFF" tag and exit if not found.

  If Header.lRiff <> &H46464952 Then
    Exit Function
  End If

  ' Check for "WAVE" tag and exit if not found.

  If Header.lWave <> &H45564157 Then
    Exit Function
  End If

  ' Check format chunk length; if less than 16,
  ' it's not PCM data so we can't use it.

  If Header.lFormatLength < 16 Then
    Exit Function
  End If

  ' Retrieve format.

  Get #FileFree, , HdrFormat

  ' Seek to next chunk by discarding any extra WAVEFORMATEX bytes.

  For i = 1 To Header.lFormatLength - 16
    Get #FileFree, , by
  Next

  ' Ignore chunks until we get to the "data" chunk.

  Get #FileFree, , chunk
  Do While chunk.lType <> &H61746164
    For i = 1 To chunk.lLen
    Get #FileFree, , by
    Next
    Get #FileFree, , chunk
  Loop

  ' Retrieve the size of the data.

  lDataLength = chunk.lLen

 ' Fill the returned type with the format information.

  With FillFormat
    .lAvgBytesPerSec = HdrFormat.nAvgBytesPerSec
    .lExtra = 0
    .lSamplesPerSec = HdrFormat.nSamplesPerSec
    .nBitsPerSample = HdrFormat.wBitsPerSample
    .nBlockAlign = HdrFormat.nBlockAlign
    .nChannels = HdrFormat.nChannels
    .nFormatTag = HdrFormat.wFormatTag
    .nSize = 0
  End With

End Function

The application can now begin reading data from the file and streaming that data into the secondary sound buffer. It's impossible to read data directly from the file into the secondary buffer, so you must first read the data into a private buffer and then copy it to the secondary buffer by using DirectSoundSecondaryBuffer8.WriteBuffer.

For more information on streaming, see Using Streaming Buffers and Play Buffer Notification.


Reading Wave Data from a Resource

Because sounds stored as resources are likely to be short, it is recommended that they be played through static buffers. To create a static buffer and fill it with data from a resource, use the DirectSound8.CreateSoundBufferFromResource method. For an example, see Filling and Playing Static Buffers.

Longer sounds can be stored in wave files and played through streaming buffers. For more information, see the following topics:

  • Using Streaming Buffers
  • Reading Wave Files


Using Effects in DirectSound

Playback effects in a pure DirectSound application are handled in fundamentally the same way as in an application that uses the DirectMusic performance and audiopaths. For more information, see Using Effects. Because there are no audiopaths in a DirectSound application, you always work directly with buffers.

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.

Create a secondary buffer that is capable of holding a DMO by setting the DSBCAPS_CTRLFX flag in the DSBUFFERDESC type.

Implement effects on your secondary sound buffers by using DirectSoundSecondaryBuffer8.SetFX.

Obtain objects for effects by using DirectSoundSecondaryBuffer8.GetObjectInPath. Note that this method, unlike DirectMusicAudioPath8.GetObjectInPath, does not take an lStage parameter, because DMOs are the only objects that can be retrieved from buffers.


Sound Capture

This section is a guide to capturing sounds using DirectMusic and DirectSoundCapture objects. The following topic is discussed:

  • Capturing Waves

Note DirectX for Visual Basic does not support MIDI capture.


Capturing Waves

The DirectSoundCapture8 object is used to query the capabilities of sound capture devices and to create buffers for capturing audio from an input source. DirectSoundCapture8 allows capturing of data in PCM or compressed formats.

The DirectSoundCaptureBuffer8 object 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 the DirectSoundCaptureBuffer8 object allow 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 some other purpose.

More information about wave capture is found in the following topics:

  • Enumeration of Capture Devices
  • Creating the DirectSoundCapture Object
  • Capture Device Capabilities
  • Creating a Capture Buffer
  • Capture Buffer Information
  • Capture Buffer Notification
  • Using the Capture Buffer
  • Writing to a Wave File


Enumeration of Capture Devices

For an application that is simply going to capture sounds through the user's preferred capture device, you don't need to enumerate the available devices. By passing vbNullString or a predefined GUID to DirectX8.DirectSoundCaptureCreate, you can create a default device. For more information, see Creating the DirectSoundCapture Object.

If you are looking for a particular kind of device or wish to offer the user a choice of devices, you must enumerate the devices available on the system.

Enumeration serves three purposes:

  • Reports what hardware is available.
  • Supplies a GUID for each device.
  • Enables you to initialize each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, first call the DirectX8.GetDSCaptureEnum method to create a DirectSoundEnum8 object representing a collection of devices. You can then query each device by using the DirectSoundEnum8.GetDescription, DirectSoundEnum8.GetGuid, and DirectSoundEnum8.GetName methods.

For an example of the use of DirectSoundEnum8, see Enumeration of Sound Devices.


Creating the DirectSoundCapture Object

You create the DirectSoundCapture8 object by calling the DirectX8.DirectSoundCaptureCreate method.

The guid parameter to DirectSoundCaptureCreate can be a GUID obtained by enumeration, or it can be one of the following values:

DSDEVID_DefaultCapture

The default system capture device. You can also specify this device by passing vbNullString in the device GUID parameter.

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 raises an error.

If you want DirectSound8 and DirectSoundCapture8 objects to coexist, then you should create the DirectSound8 object before creating the DirectSoundCapture8 object.

Some audio devices aren't configured for full duplex audio by default. If your application has problems creating both a DirectSound8 object and a DirectSoundCapture8 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 DirectSoundCapture8.GetCaps method. The parameter to this method is a DSCCAPS type. On return, the type contains the number of channels the device supports as well as a combination of values for supported formats.

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

Create a capture buffer by calling the DirectSoundCapture8.CreateCaptureBuffer method.

One of the parameters to the method is a DSCBUFFERDESC type that describes the characteristics of the desired buffer. The fxFormat member is a WAVEFORMATEX type, which must be initialized with the details of the desired wave format.

Note that if your application is using DirectSound8 as well as DirectSoundCapture8, 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 sets up a capture buffer that will hold 1 second of data:

' dsc is a DirectSoundCapture8 object.

Dim dscbd As DSCBUFFERDESC
Dim dscb As DirectSoundCaptureBuffer8

' Set up the wave format.
With dscbd.fxFormat
  .nFormatTag = WAVE_FORMAT_PCM
  .nChannels = 2
  .lSamplesPerSec = 22050
  .nBitsPerSample = 16
  .nBlockAlign = _
    .nBitsPerSample / 8 * WaveFormat.nChannels
  .lAvgBytesPerSec = _
     waveFormat.lSamplesPerSec * waveFormat.nBlockAlign
  .nSize = 0  ' Ignored for WAVE_FORMAT_PCM.
End With

dscbd.lFlags = DSCBCAPS_DEFAULT
dscbd.lBufferBytes = dscbd.fxFormat.lAvgBytesPerSec

Set dscb = dsc.CreateCaptureBuffer (dscbd)


Capture Buffer Information

Use the DirectSoundCaptureBuffer8.GetCaps method to retrieve information about buffer capabilities. To get information about the data format of the buffer, set when the buffer was created, call the DirectSoundCaptureBuffer8.GetFormat method.

To find out what a capture buffer is doing, call the DirectSoundCaptureBuffer8.GetStatus method. This method returns 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 DirectSoundCaptureBuffer8.Start.

Finally, the DirectSoundCaptureBuffer8.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

You may want your application to be notified when the read cursor reaches a certain point in the buffer, or when it reaches the end. The read cursor is at the point up to which it is safe to read data from the buffer. With the DirectSoundCaptureBuffer8.SetNotificationPositions method, you can set any number of points within the buffer where events are to be signaled.

To set notification events on a buffer, you must first implement the DirectXEvent8 class in the form that contains the code for the buffer. Create a DirectXEvent8.DXCallback method by choosing DirectXEvent8 from the drop-down class list, and add the code you want to be executed when the event is signaled.

Create an event handle by calling the DirectX8.CreateEvent method and pass the event handle in the hEventNotify member of a DSBPOSITIONNOTIFY type. Pass the type to the DirectSoundCaptureBuffer8.SetNotificationPositions method. The event handle will now be passed to DirectXEvent8.DXCallback whenever the play cursor reaches that position.


Using the Capture Buffer

Capturing a sound consists of the following steps:

  1. Start the buffer by calling the DirectSoundCaptureBuffer8.Start method. 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, read a portion of the capture buffer by calling the DirectSoundCaptureBuffer8.ReadBuffer method.

    To make sure you are not attempting to read a portion of memory that is about to be used for capture, you can first obtain the position of the read cursor by calling DirectSoundCaptureBuffer8.GetCurrentPosition. For an explanation of the read cursor, see Capture Buffer Information.

  4. Repeat steps 2 and 3 until you are ready to stop capturing data. Then call the DirectSoundCaptureBuffer8.Stop method.

By default, the buffer stops capturing automatically when the capture cursor reaches the end of the buffer. However, if the DSCBSTART_LOOPING flag was set in the flags parameter to the DirectSoundCaptureBuffer8.Start method, the capture continues until the application calls the DirectSoundCaptureBuffer8.Stop method.

The following procedure in a form that implements DirectXEvent8 is called each time the capture cursor reaches a notification position. It calculates the amount of new data available, copies it to an intermediate buffer, and then writes it to a file.

Private Sub DirectXEvent8_DXCallback(ByVal eventid As Long)

' Global variables:
' lastPos As Long – initialized to 0 each time capture starts
' BytesWritten As Long – also initialized to 0
' dscb As DirectSoundCaptureBuffer8
' dscbDesc As DSCBUFFERDESC
' EventStop As Long

  Static curPos As Long
  Static curs As DSCURSORS
  Dim dataBuf() As Byte
  Dim dataSize As Long

  dscb.GetCurrentPosition curs
  curPos = curs.lWrite  ' Position up to which data is valid

  ' Create an intermediate, temporary data buffer.
  ' lastPos is a global Long that is initialized to 0 each time
  ' capture begins.

  dataSize = curPos - lastPos
  If dataSize < 0 Then   ' curPos wrapped around.
  dataSize = dscbDesc.lBufferBytes - lastPos + curPos
  End If

  ReDim dataBuf(dataSize - 1)
  dscb.ReadBuffer lastPos, dataSize, dataBuf(0), DSCBLOCK_DEFAULT

  Put #1, , dataBuf
  BytesWritten = BytesWritten + dataSize
  lastPos = curPos

  If (eventid = EventStop) Then
  CloseFile
  End If

End Sub

The EventStop event was associated with the offset DSBPN_OFFSETSTOP when notification positions were set. This event is signaled when the capture buffer stops. In response, the application calls a procedure that adds information to the file header and closes the file. For information on how to write file headers for wave files, see Writing to a Wave File.


Writing to a Wave File

Short sounds can be saved from a secondary buffer to a wave file by using DirectSoundSecondaryBuffer8.SaveToFile. This method copies the entire contents of the buffer to a file.

In most cases, the sound that you want to save starts out in a capture buffer. The following code shows how to move data from a capture buffer, dscb, to a secondary buffer and then to a file.

Dim ds As DirectSound8
Dim dscb As DirectSoundCaptureBuffer8
Dim dscd As DSCBUFFERDESC
Dim dsd As DSBUFFERDESC
Dim capCurs As DSCURSORS
Dim numBytes As Long
Dim ByteBuffer() As Integer
.
.
.
' Assume that ds has been created, dscb has been created and
' contains data, and dscd holds the format of the capture buffer.

' Create a secondary buffer with the same format, and large enough
' to contain all data so far written to the capture buffer.

dscb.GetCurrentPosition capCurs
numBytes = capCurs.lWrite + 1
dsd.lBufferBytes = numBytes
dsd.fxFormat = dscd.fxFormat
Set dsb = ds.CreateSoundBuffer(dsd)

' Make a private buffer large enough to hold the same data.

ReDim ByteBuffer(numBytes)

' Read the contents of the capture buffer into the private buffer.

dscb.ReadBuffer 0, numBytes, ByteBuffer(0), DSCBLOCK_DEFAULT

' Write the private buffer to the secondary buffer.

dsb.WriteBuffer 0, numBytes, ByteBuffer(0), DSBLOCK_DEFAULT

' Save the wave.

dsb.SaveToFile "captured.wav"

For sounds that might exceed the length of the capture buffer, you need to create the wave file yourself and stream data into it. Streaming captured data to a wave file is done in the following steps:

  1. Create the file and write the file header, the format chunk, and the header of the data chunk. The format chunk must describe the format of the capture buffer. Note, however, that the elements of the format are not in the same order as in the WAVEFORMATEX type. For information on the organization of headers and chunks, see Reading Wave Files.
  2. Stream data from a capture buffer to a private buffer and from there to the file, keeping track of how many bytes have been written. For more information, see Using the Capture Buffer.
  3. When capture stops and all data has been written, calculate the length of the data chunk and the total size of the file, and write these values to the appropriate locations in the data chunk header and file header respectively.

The following code creates a file and writes the RIFF header information:

Private Type FileHeader
  lRiff As Long
  lFileSize As Long
  lWave As Long
  lFormat As Long
  lFormatLength As Long
End Type

Private Type WaveFormat
  wFormatTag As Integer
  nChannels As Integer
  nSamplesPerSec As Long
  nAvgBytesPerSec As Long
  nBlockAlign As Integer
  wBitsPerSample As Integer
'  cbSize As Integer
End Type

Private Type ChunkHeader
  lType As Long
  lLen As Long
End Type

Dim fh As FileHeader
Dim wf As WaveFormat
Dim ch As ChunkHeader

Private Sub OpenFile(WaveFileName As String)

  Open WaveFileName For Binary Access Write As #1

  With fh
  .lRiff = &H46464952  ' <RIFF> chunk tag
  .lFileSize = 0   ' Will get later
  .lWave = &H45564157  ' <WAVE> chunk tag
  .lFormat = &H20746D66  ' <fmt > chunk tag
  .lFormatLength = Len(wf)
  End With

  Put #1, , fh

  With wf
  .wFormatTag = dscbDesc.fxFormat.nFormatTag
  .nChannels = dscbDesc.fxFormat.nChannels
  .nSamplesPerSec = dscbDesc.fxFormat.lSamplesPerSec
  .wBitsPerSample = dscbDesc.fxFormat.nBitsPerSample
  .nBlockAlign = dscbDesc.fxFormat.nBlockAlign
  .nAvgBytesPerSec = dscbDesc.fxFormat.lAvgBytesPerSec
  End With

  Put #1, , wf

  ch.lType = &H61746164  ' <data> chunk tag

  Put #1, , ch

End Sub

Captured data can now be appended to the file. Assuming that the number of data bytes written to the file is kept in a Long called BytesWritten, the file is closed by using the following procedure:

Private Sub CloseFile()

  Dim fsize As Long

  ' Write file size.

  fsize = Len(fh) + Len(wf) + Len(ch) + BytesWritten
  Put #1, 5, fsize

  ' Rewrite data chunk header with size.

  ch.lLen = BytesWritten
  Put #1, Len(fh) + Len(wf) + 1, ch

  Close #1

End Sub


Advanced Topics in DirectX Audio

This section contains information needed for specialized applications that need functionality beyond that covered under Using DirectX Audio.

Information is presented in the following topics:

  • Using DirectMusic Messages
  • Using Instrument Collections
  • Optimizing DirectSound Performance
  • Writing to the Primary Buffer


Using DirectMusic Messages

Sound data passes through the DirectMusic performance in the form of messages. For the most part, messages are created and processed behind the scenes, and your application might never have to work directly with them. However, a basic knowledge of messages can help you understand how DirectMusic works, and a more thorough understanding will enable you to use messages for greater control over the performance.

DirectMusic uses two different kinds of messages:

  • Performance messages. All sequenced data passes through the performance engine in this form. These messages contain detailed information about timing and routing of the data.
  • Standard MIDI messages. These can be read from a MIDI file or device and either passed directly (thrued) to another device or converted to performance message format when played by the performance.

Applications don't deal directly with MIDI messages. When a segment is played, all its data is in the form of performance messages and stays that way until it reaches the final output tool, which converts it to MIDI message format before sequencing it to the synthesizer. However, some performance messages contain information similar to that in standard MIDI messages. To help you understand such messages, this section describes some aspects of the MIDI message format.

Note The DirectMusicPerformance8.SendMIDIPMSG method sends data equivalent to that in any standard MIDI message. However, the data is in the form of a performance message.

Most performance messages are sent by a segment's tracks as the segment is playing. Applications can also send messages to do things like setting a MIDI controller, playing a single note, or changing the tempo.

Once a message has been sent, the application cannot retrieve or alter it. For example, a segment authored in DirectMusic Producer might contain a lyrics track that generates text messages. DirectX for Visual Basic does not enable an application to retrieve these messages and display the lyrics.

Notifications are an exception to the rule that messages cannot be retrieved by the application. The DirectMusicPerformance8.GetNotificationPMSG method enables the application to retrieve DMUS_NOTIFICATION_PMSG messages. For more information, see Notification and Event Handling.

The following topics discuss messages and how they are routed:

  • Channels
  • Message Creation and Delivery
  • Application-Created Messages
  • Curves
  • MIDI Messages


Channels

A channel is a destination for a message that is specific to one part in the performance. For example, a channel might receive a note-on message that causes the instrument on that channel to make a sound, or a program-change message that assigns a different instrument to that part. See MIDI Channel Messages.

Under the MIDI 1.0 standard, there are 16 MIDI channels, meaning that no more than 16 instruments can be playing at one time. To support this standard but at the same time make more channels available to applications, DirectMusic creates channel groups. Up to 65,536 channel groups can exist at one time, each containing 16 channels, for a total of over one million channels. A particular port can be assigned any number of channel groups, up to its capability to support them. MIDI hardware ports have only a single channel group.

System-exclusive messages address all 16 channels within a channel group, but not other channel groups.

Every part in a DirectMusic performance has a unique performance channel, sometimes called a PChannel. The performance channel represents a particular MIDI channel in a particular group on a particular port. When a band is selected by a performance, each instrument in that band is mapped to a performance channel, so the part on that channel will play on that instrument.

When audiopaths are being used, identical performance channels on different audiopaths are mapped to different output channels.

Channel Priority

The number of notes that can be played simultaneously is limited by the number of voices available on the port. A voice is a set of resources dedicated to the synthesis of a single note or wave being played on a channel. In the event that more notes are playing than there are available voices, one or more notes must be suppressed by the synthesizer. The choice is determined by the priority of the voice currently playing the note, which is based in turn on the priority of the channel. By default, channels are ranked according to their index value, except that channel 10, the MIDI percussion channel, is ranked highest.


Message Creation and Delivery

When a segment is played, most of its tracks generate messages containing information about events that are to take place during playback.

A few tracks send more than one kind of message. For example, a style track sends note messages and time signature messages. In such cases, an application can disable certain kinds of messages in the track. For more information, see Disabling and Enabling Track Parameters.

The performance engine determines when each message is to be processed in clock time. In the case of channel messages, the performance also determines which performance channel gets the message. This information, along with other data—including the message type, its source track, and pointers to the first toolgraph and tool that are to receive it—is stored in the message structure.

Certain messages, such as tempo and time signature changes, are immediately processed and freed by the performance. Other messages, such as notes and patch changes, are placed in a queue and processed in order of time stamp.

Note There is no guarantee that messages with the same time stamp will be processed in any particular order.

Time signature messages are purely informational. The time signature is built into the segment and cannot be changed.

Ultimately, unless a message has been discarded, it arrives at the DirectMusic output tool, which converts all the data it receives into standard MIDI messages and delivers these to the synthesizer through the port buffer.

For an illustration, see Overview of Audio Data Flow.


Application-Created Messages

Most messages are generated by tracks, but applications can place messages in the queue directly. You might do this, for example, to change the tempo or to play a sound effect as a note on a DLS instrument.

The following methods send a performance message.

DirectMusicPerformance8.SendCurvePMSG | Curve
DirectMusicPerformance8.SendNotePMSG | Musical note
DirectMusicPerformance8.SendPatchPMSG | Patch change
DirectMusicPerformance8.SendMIDIPMSG | Miscellaneous MIDI events
DirectMusicPerformance8.SendTempoPMSG | Tempo change
DirectMusicPerformance8.SendTimeSigPMSG | Time signature change
DirectMusicPerformance8.SendTransposePMSG | Transposition change

When a performance has multiple audiopaths, DirectMusic may not be able to route application-created messages correctly, because a new message contains no information about what audiopath it belongs to. In DirectX for Visual Basic, there is no way to direct an application-created message to a particular audiopath.


Curves

A curve is a series of MIDI controller changes bringing about a smooth transition from one value to another—for example, volume fade-out or fade-in.

You can execute a curve by sending a single performance message, using DirectMusicPerformance8.SendCurvePMSG. The DMUS_CURVE_PMSG type passed to this method enables you to set the start and end values, the duration of the curve, and its shape. Optionally, you can also set a reset value, which is the value to which the controller will return in case of an invalidation.

The measure, offset, beat, grid, and mtOriginalStart members of the message structure are used in messages sent by DirectMusic Producer segments. In messages sent by applications, these values should be 0.

The MergeIndex member is used to determine whether changes are cumulative or overriding. Two curve messages with different merge indexes are cumulative; otherwise, each message in turn overrides settings made by a previous message.

The ccData member contains the MIDI controller number for controller changes, and is otherwise ignored. For information on controller numbers, see the MIDI specification.

The following sample code fades out the current volume over a duration of 5 seconds:

Dim curveMsg As DMUS_CURVE_PMSG

curveMsg.curveShape = DMUS_CURVES_LINEAR
curveMsg.mtDuration = 5000
curveMsg.Type = DMUS_CURVET_CCCURVE
curveMsg.ccData = 7  ' MIDI channel volume controller
curveMsg.flags = DMUS_CURVE_START_FROM_CURRENT

dmPerf.SendCurvePMSG 0, _
  DMUS_PMSGF_REFTIME Or DMUS_PMSGF_LOCKTOREFTIME, _
  DMUS_PCHANNEL_BROADCAST_PERFORMANCE, curveMsg

Note A simpler way to implement volume fading is by using DirectMusicAudioPath8.SetVolume. This method always uses the linear shape for the curve.

The following code changes the pitch bend from the current value to the maximum value over a duration of 3 seconds. If an invalidation occurs during that period, which might happen if another segment replaces the currently playing segment, the pitch is reset to the value in g_Pitch.

curveMsg.curveShape = DMUS_CURVES_LINEAR
curveMsg.startValue = 0  ' Ignored, start from current.
curveMsg.endValue = 16383
curveMsg.mtDuration = 3000
curveMsg.Type = DMUS_CURVET_PBCURVE
curveMsg.ccData = 0
curveMsg.flags = DMUS_CURVE_RESET Or DMUS_CURVE_START_FROM_CURRENT
curveMsg.resetValue = g_Pitch
curveMsg.mtResetDuration = 0

dmPerf.SendCurvePMSG 0, _
  DMUS_PMSGF_REFTIME Or DMUS_PMSGF_LOCKTOREFTIME, _
  DMUS_PCHANNEL_BROADCAST_PERFORMANCE, curveMsg


MIDI Messages

Most applications don't deal directly with MIDI messages. However, an application can send a MIDI command as a performance message—for example, to make a control change.

MIDI messages consist of a status byte and usually one or two data bytes. System exclusive MIDI messages are of variable length.

The status byte indicates the type of message and, in some cases, the channel that is to receive the message. When several events of the same kind are in sequence in the file, the status byte can be omitted. Data bytes are recognizable because the high bit is always clear, whereas in status bytes it is always set.

The timing of MIDI events is controlled by a number before each message, indicating how many ticks separate this event from the last. The actual duration of a tick depends on the time format in the file header.

Note There is no guarantee that MIDI messages will be processed in the same order in which they occur in the source data. DirectMusic messages are delivered in order of time stamp, and two MIDI messages with identical times might not be delivered in the expected order. Care must be taken, in authoring MIDI content, to leave an interval between events if they must take place sequentially. For example, don't place a program change at the same time as a note that depends on the program change.

MIDI messages are divided into two main categories:

  • MIDI Channel Messages
  • MIDI System Messages


MIDI Channel Messages

A channel message is addressed to a particular MIDI channel, which corresponds to a single part in the music.

A channel message can be either a mode message or a voice message.

A mode message determines how a channel will deal with subsequent voice messages. For example, a mode message might instruct the channel to remain silent, ignoring all note-on messages until further notice.

Most channel messages are voice messages. They instruct the channel to begin or stop playing a note or to modify the note in some way, or they change the timbre by assigning a different MIDI patch number to the channel.

The following table describes types of voice messages.

Voice message | Purpose
Note-on | Play a note.
Note-off | Stop playing the note.
Control change | Modify the tone with data from a pedal, lever, or other device; also used for miscellaneous controls such as volume and bank select.
Program (patch) change | Select an instrument for the channel by assigning a patch number.
Aftertouch | Modify an individual note, or all notes on the channel, according to the aftertouch of a key.
Pitch bend change | Modify the pitch of all notes played on the channel.

Keep in mind that these descriptions apply to standard MIDI messages, not MIDI data that has been converted to performance message format. For example, two MIDI messages to start and stop a note are combined by DirectMusic into a single performance message giving the duration of the note. DirectMusic messages also contain much additional information about timing and routing.

MIDI Notes

The data bytes of a note-on message represent the pitch and velocity. In most cases, a pitch value of 0 represents C below subcontra C (called C0 in MIDI notation), 12 represents subcontra C (or C1), 60 is middle C (or C5), and so on. For drum kits, the data byte instead represents a particular drum sound. For example, as long as the General MIDI (GM) percussion key map is being adhered to, a value of 60 represents a high bongo sound. Channel 10 is reserved for drum kits, so the synthesizer knows that note-on messages on that channel are to be treated differently than on other channels.

For information on how DirectMusic converts to and from MIDI notes, see Music Values and MIDI Notes.

Program Changes

Program changes and patch numbers are a key concept in MIDI playback and in DirectMusic. A program change assigns a particular instrument (also called a program or timbre) to a channel so that the notes sent to that channel are played with the appropriate sound. Instruments are identified by patch numbers. If the GM instrument set is loaded, a program change specifying patch number 1 always causes the channel to play its notes as an acoustic grand piano. The actual sound produced at the speakers depends on how the instrument is synthesized.

Bank Selection

Because a single data byte is used to select the patch number in a program change, and only 7 bits in each data byte of a MIDI message are significant, a program change can select from a maximum of 128 instruments. To provide a greater choice, the MIDI specification allows for the use of up to 16,384 instrument banks, each containing up to 128 instruments.

To select an instrument from a different bank, the MIDI sequencer must first send a control change message called bank select. The 2 data bytes of this message are referred to as the most significant byte (MSB) and least significant byte (LSB), and they are combined to identify a bank. Once the bank has been selected, each subsequent program change selects an instrument from that bank.

DirectMusic Patch Numbers

This topic pertains only to applications written in C++. DirectX for Visual Basic does not enable applications to change patch numbers except by using the DirectMusicPerformance8.SendPatchPMSG method.


MIDI System Messages

System messages are not exclusive to any channel. There are three kinds, as shown in the following table.

Message type | Purpose
System common | Miscellaneous commands and data.
System exclusive | Equipment-specific commands and data.
System real-time | Synchronization of clock-based MIDI equipment.

Unlike other MIDI messages, system exclusive messages can contain any number of data bytes. After transmitting the data, the sequencer sends a system common message called an EOX, which signals the end of the system exclusive message.

DirectX for Visual Basic does not give applications direct access to system exclusive messages.


Using Instrument Collections

In most applications, DLS instrument data is associated with bands and is downloaded to the synthesizer when the band is downloaded. For more information, see Using Bands.

Information about working directly with instrument collections is presented in the following topic:

  • Loading and Downloading Collections


Loading and Downloading Collections

To load an instrument collection, call the DirectMusicLoader8.LoadCollection or the DirectMusicLoader8.LoadCollectionFromResource method. Each of these methods returns a DirectMusicCollection8 object. This object has no methods, and its only role is to be passed as a parameter to DirectMusicSegment8.ConnectToCollection. You call that method to associate the collection with a segment, and then download the instruments by calling DirectMusicSegment8.Download. For an example, see Playing a MIDI File with Custom Instruments.

These steps are necessary only when you want to use a collection other than the default one. Normally, when you call DirectMusicSegment8.Download, the instruments downloaded to the port are from the default collection authored into the segment, or from the General MIDI set if the segment does not reference a collection. When you download a band, all DLS data needed by the instruments in that band is downloaded. See Using Bands.


Optimizing DirectSound Performance

This section offers some miscellaneous tips for improving the performance of applications that play their audio data directly into DirectSound buffers. The following topics are covered:

  • Matching Buffer Formats
  • Using Hardware Mixing
  • Dynamic Voice Management
  • Hardware Acceleration on ISA and PCI Cards
  • Playing the Primary Buffer Continuously
  • Minimizing Control Changes
  • CPU Considerations for 3-D Buffers


Matching Buffer Formats

The DirectSound mixer converts the data from each secondary sound buffer into the format of the primary sound buffer. This conversion is done on the fly as data is mixed into the primary buffer, and costs CPU cycles. You can eliminate this overhead by ensuring that your secondary buffers and primary buffer have the same format. Normally, this means setting the primary buffer format to the format of the wave files used for data.

Because of the way DirectSound does format conversion, you only need to match the sample rate and number of channels. It doesn't matter if there is a difference in sample size (8-bit or 16-bit).


Using Hardware Mixing

Most sound cards support some level of hardware mixing if there is a DirectSound driver for the card. The following tips will enable you to make the most of hardware mixing:

  • At run time, use the DirectSound8.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 lFlags member of the DSBUFFERDESC type. If you do this and resources for hardware mixing are not available, the DirectSound8.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 3-D 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 3-D 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—that is, the number of hardware buffers is limited by the hardware voices available. DirectSound allocates a hardware voice when a buffer is created and releases it only when the buffer is destroyed; the voice is not free even when the buffer is not playing. If an application creates many buffers, chances are that some of them will end up being in software—that is, they will be managed and mixed by the CPU rather than the sound card.

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 so that their resources can be allocated to new sounds.

To defer the allocation of resources for hardware mixing and 3-D effects to the moment when the buffer is played, specify the DSBCAPS_LOCDEFER flag in the DSBUFFERDESC type passed to DirectSound8.CreateSoundBuffer, DirectSound8.CreateSoundBufferFromFile, or DirectSound8.CreateSoundBufferFromResource. When you call DirectSoundSecondaryBuffer8.Play or DirectSoundSecondaryBuffer8.AcquireResources on a buffer created with the DSBCAPS_LOCDEFER flag, 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 3-D 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 DirectSoundSecondaryBuffer8.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 for some PCI 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. For more information, see Voice Management on ISA and PCI Cards.


Hardware Acceleration on ISA and PCI Cards

In the past few years, sound cards have moved from the ISA bus to the PCI bus. This design change has fundamentally altered the way DirectSound-accelerated cards handle audio data. In addition, DirectSound has introduced voice management, which enables applications to make more efficient use of limited hardware acceleration resources.

This section discusses some considerations in allocating buffers and using voice management on the two kinds of sound cards. The following topics are discussed:

  • DirectSound Buffers on ISA Cards
  • DirectSound Buffers on PCI Cards
  • Voice Management on ISA and PCI Cards


DirectSound Buffers on ISA Cards

When DirectSound was first introduced, all audio devices operated on the ISA bus. The ISA bus was sufficient to stream 16-bit, 22 kHz stereo data from the CPU to the sound card without unduly affecting overall system performance, but attempting to send more data often placed an undue burden on the bus. This limitation had a strong influence on audio hardware design.

To mix DirectSound buffers, a chip on the sound card has two choices: it can reach across the ISA bus into system memory, or it can have dedicated memory on the card itself. Owing to the ISA bus's limited bandwidth, reading audio data from system memory is not practical. Therefore, ISA-based sound cards that do DirectSound acceleration almost always have dedicated on-card RAM.

When such a sound card is used to accelerate DirectSound, the sound data must first be copied from system memory, across the ISA bus, and into the dedicated memory on the card. This copying can take some time. However, once the data is on the card, there is almost no cost to the system for starting, stopping, and mixing sounds; all that is handled by the audio processor chip accessing its own dedicated memory.

ISA-based DirectSound accelerators support static buffers on the card, but not streaming buffers, because it is impractical to stream data across the slow ISA bus. DirectSound buffers created with the DSBCAPS_STATIC flag are located in card memory if it is available. Others are created in system memory.


DirectSound Buffers on PCI Cards

Most audio cards sold today, if not all, are designed to connect to the PCI bus. With the movement to this bus comes a large increase in the available bandwidth between the system and the audio card. It is now practical to have the audio chip reach directly into system memory to retrieve audio data for hardware mixing. As a result, it is no longer worthwhile to have on-board memory for buffers.

On PCI cards, static buffers and streaming buffers are effectively the same. The DSBCAPS_STATIC flag does not affect the location of the buffer, because all buffers are located in system memory.

Note Most sound cards report in DSCAPS that they have static buffers, even though they have no on-card RAM. The streaming and static buffers reported by these cards are often the same buffers.


Voice Management on ISA and PCI Cards

By using the DSBCAPS_LOCDEFER flag when creating a buffer, you can defer the allocation of buffers to hardware-mixed or software-mixed memory until the moment when they are played. For information, see Dynamic Voice Management.

The effect of deferred allocation on application performance depends on the type of DirectSound accelerator in the user's system.

Consider the case of a PCI accelerator. When a deferred buffer is played, DirectSound first determines if there is hardware available to play the sound. Assuming there is, DirectSound then ensures that the hardware has access to the sound data, which remains where it is. Finally, DirectSound tells the hardware to start playing. This process is both efficient and fast.

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.

If the user has an ISA-based accelerator, the situation is quite different. In this case, the act of getting audio data to a hardware-mixed buffer is very slow, because the data needs to cross the ISA bus and be loaded into memory on the sound card before it can be mixed. For deferred buffers, this can introduce an unacceptable delay between when the play call is made and when the sound starts. For this reason, using voice management is not recommended on ISA-based DirectSound accelerator cards.

It is easy to prevent your application from using voice management on ISA devices. A buffer won't be assigned to a on-card memory unless the DSBCAPS_STATIC flag is set. Therefore, as long as you do not combine DSBCAPS_STATIC and DSBCAPS_LOCDEFER, there is no danger that buffers will be assigned to on-card memory at play time.

Using DSBCAPS_STATIC by itself ensures that the buffer will take advantage of any existing memory on an ISA card, but has no effect on a PCI card, where in the absence of other flags, DirectSound will attempt to place the buffer under hardware control but still in system memory. Using DSBCAPS_LOCDEFER by itself has no effect on an ISA card, since the buffer is always placed in system memory and is not managed by the hardware.

The following table summarizes the effects of the DSBCAPS_STATIC and DSBCAPS_LOCDEFER flags on buffers created for ISA and PCI devices.

Card | Flags | Memory | HW acceleration
ISA | DSBCAPS_STATIC | Hardware if available. | Yes, if in hardware memory.
PCI | DSBCAPS_STATIC | System. | Yes, if hardware voice available; flag has no effect.
ISA | DSBCAPS_LOCDEFER | Hardware if available, if DSBCAPS_STATIC set. | Yes, if in hardware memory; but latency on first play.
PCI | DSBCAPS_LOCDEFER | System. | Yes, if hardware voice available.

To take advantage of acceleration on ISA cards without running into the dangers presented by deferred allocation, first check the capabilities of the device. If the card reports more than zero static buffers and no streaming buffers, it is probably an older ISA card with on-card memory. You can then use the DSBCAPS_STATIC flag, but do not use DSBCAPS_LOCDEFER. If the card reports more than zero streaming buffers, it is probably a newer PCI-based accelerator card. In this case, you'll want to use DSBCAPS_LOCDEFER, and not DSBCAPS_STATIC, to make maximum use of the hardware voices.


Playing the Primary Buffer Continuously

When there are no sounds playing, DirectSound stops the mixer engine and halts DMA (direct memory access) activity. If your application has frequent short intervals of silence, the overhead of starting and stopping the mixer each time a sound is played may be worse than the DMA overhead if you kept the mixer active. Also, some sound hardware or drivers may produce unwanted audible artifacts from frequent starting and stopping of playback.

If your application is playing audio almost continuously with only short breaks of silence, you can force the mixer engine to remain active by calling the DirectSoundPrimaryBuffer8.Play method.

To resume the default behavior of stopping the mixer engine when there are no sounds playing, call the DirectSoundPrimaryBuffer8.Stop method.

To obtain the primary buffer object, use the DirectSound8.CreatePrimarySoundBuffer method.


Minimizing Control Changes

Performance is affected when you change the pan, volume, or frequency on a secondary buffer. To prevent interruptions in sound output, the DirectSound mixer must mix ahead from 20 to 100 or more milliseconds. Whenever you make a control change, the mixer has to flush its mix-ahead buffer and remix with the changed sound.

It's a good idea to minimize the number of control changes you send. Try reducing the frequency of calls to routines that use the DirectSoundSecondaryBuffer8.SetVolume, DirectSoundSecondaryBuffer8.SetPan, and DirectSoundSecondaryBuffer8.SetFrequency methods. 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.

Note 3-D control changes (orientation, position, velocity, Doppler factor, and so on) also cause DirectSound to remix its mix-ahead buffer. However, you can group a number of 3-D control changes together and cause only a single remix. See Deferred Settings.


CPU Considerations for 3-D Buffers

Software-emulated 3-D buffers are computationally expensive. You should take this into consideration when deciding when and how to use 3-D buffers in your applications.

Use as few 3-D sounds as you can, and don't use 3-D on sounds that won't really benefit from the effect. Design your application so that it's easy to enable and disable 3-D effects on each sound. You can call the DirectSound3DBuffer8.SetMode method with the DS3DMODE_DISABLE flag to disable 3-D processing on any 3-D sound buffer.

You can also ensure that 3-D processing is suspended on buffers that are too far away from the listener to be heard. See Minimum and Maximum Distances.


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 talks to the kernel mixer, or Kmixer. Kmixer'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 only mixes DirectSound buffer data, but Kmixer 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 can't both be open at the same time is not true on systems with WDM drivers.

Of particular importance is Kmixer's relationship with the audio hardware. Kmixer 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 particular driver the user has installed. For that 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 Kmixer, and you should ensure your application's behavior and performance are acceptable on both.


Writing to the Primary Buffer

Applications can write directly to the primary buffer by using the DirectSoundPrimaryBuffer8.WriteBuffer method, provided that the cooperative level is set to DSSCL_WRITEPRIMARY. However, it is strongly recommended that DirectX for Visual Basic applications not do so.


Programming Tips and Tools

This section contains information to help you develop Microsoft® DirectX® Audio applications efficiently. The following topic is covered:

  • Adjusting DirectSound Acceleration for Testing


Adjusting DirectSound Acceleration for Testing

By using the Sounds and Multimedia Properties 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. Then 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. This is the default setting on Windows 98.

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.


DirectX Audio Visual Basic Tutorials

This section contains the following tutorials showing how to implement Microsoft® DirectMusic® and Microsoft® DirectSound® in a Microsoft® Visual Basic® application:

  • Tutorial 1: Playing Audio Files
  • Tutorial 2: Using Audiopaths

Other, more specialized uses of Microsoft® DirectX® Audio are demonstrated in the sample applications provided with the SDK. For a description of these samples, see DirectX Audio Visual Basic Samples.


Tutorial 1: Playing Audio Files

This tutorial is a guide to performing the most basic tasks in DirectX Audio: initializing a DirectMusic performance and playing an audio file. The tutorial is presented in the following steps:

  • Step 1: Set Up the Audio System
  • Step 2: Load a File
  • Step 3: Play the File
  • Step 4: Close Down

The complete sample code for the tutorial is available in the following folder:

(SDK root)\samples\Multimedia\VBSamples\DirectMusic\Tutorials\Tut1


Step 1: Set Up the Audio System

The sample application declares the following object variables:

Private dx As New DirectX8
Private dml As DirectMusicLoader8
Private dmp As DirectMusicPerformance8
Private seg As DirectMusicSegment8

The only one of these objects that can be initialized during declaration is the DirectX8 object. DirectMusicLoader8 and DirectMusicPerformance8 must be created by using methods of this object, as follows:

Set dml = dx.DirectMusicLoaderCreate
Set dmp = dx.DirectMusicPerformanceCreate

After the performance has been created, it must be initialized. The DirectMusicPerformance8.InitAudio method performs the following tasks:

  • Creates a DirectSound8 object. In most cases you don't need a variable for this object, and you can pass Nothing as the DirectSound parameter, or omit it.
  • Associates an application window with the DirectSound object. Normally, the handle of the main application window is passed as the hwnd parameter.
  • Sets up a default audiopath of a standard type. The tutorial requests a path of type DMUS_APATH_SHARED_STEREOPLUSREVERB, which is suitable for music.
  • Allocates a number of performance channels to the audiopath. Wave files require only a single performance channel, and MIDI files require up to 16. Segments created in DirectMusic Producer might need more. No harm is done by asking for extra channels.
  • Specifies capabilities and resources of the synthesizer. This can be done in one of two ways: by setting flags or by supplying more detailed information in the DMUS_AUDIOPARAMS type. Most applications set the DMUS_AUDIOF_ALL flag and let DirectMusic create the synthesizer with default parameters. A DMUS_AUDIOPARAMS type still has to be passed to the method, but it can be left blank, as in the DMUS_AUDIOPARAMS typesample.

In the sample application, the call to InitAudio is very simple:

dmp.InitAudio Me.hWnd, DMUS_AUDIOF_ALL, dmA, Nothing, _
   DMUS_APATH_SHARED_STEREOPLUSREVERB, 64

Next: Step 2: Load a File


Step 2: Load a File

The DirectMusicLoader8 object created in the preceding step can be used throughout the lifetime of the application to load sound data from files.

To get the data, the loader needs to know where to find it. Although a full path can be provided each time a file is loaded, it is more convenient to establish a default directory. Do this by using the DirectMusicLoader8.SetSearchDirectory method. The sample application uses the path returned by its FindMediaDir function. This function finds the directory where the sample file is located. The loader could subsequently load any file from this directory without being given more than the name.

dml.SetSearchDirectory FindMediaDir("sample.sgt", True)

The loader then loads the file and returns it as a DirectMusicSegment8 object:

Set seg = dml.LoadSegment("sample.sgt")

Next: Step 3: Play the File


Step 3: Play the File

The file loaded in the previous step is now available to the performance as a DirectMusicSegment8 object.

Before a segment loaded from a MIDI file or a DirectMusic Producer segment file can be played, its band must be downloaded to the synthesizer. As long as you don't unload the band, this step has to be taken only once for each segment that uses a unique band.

The following code from the sample application downloads the band to the default audiopath. Alternatively, it could be downloaded to the performance. As long as only a single synthesizer is in use, it doesn't matter which destination object you choose.

seg.Download dmp.GetDefaultAudioPath

To play the file, pass the segment object to DirectMusicPerformance8.PlaySegmentEx. This method offers many options for playback, but to play a segment immediately on the default audiopath, all the parameters except the first can be 0 or omitted, as in the following code from the sample application:

dmp.PlaySegmentEx seg, 0, 0

Next: Step 4: Close Down


Step 4: Close Down

To exit an audio application cleanly, you must perform three main steps:

  • Stop any playing segments by calling DirectMusicPerformance8.StopEx.
  • Close down the performance. The DirectMusicPerformance8.CloseDown method performs miscellaneous cleanup tasks and releases internal references to objects.
  • Release all objects by setting object variables to Nothing.

The following procedure from the sample application closes down DirectX Audio:

Private Sub Form_Unload(Cancel As Integer)
  If Not (seg Is Nothing) Then
    dmp.StopEx dmp.GetDefaultAudioPath, 0, 0
  End If
  Set seg = Nothing
  dmp.CloseDown
  Set dmp = Nothing
  Set dml = Nothing
  Set dx = Nothing
End Sub


Tutorial 2: Using Audiopaths

This tutorial shows how to set up a DirectX Audio application that uses an audiopath other than the default audiopath. It also demonstrates how to set the volume on the audiopath and obtain an object from the audiopath to set parameters. In this case, the object obtained is a DirectSound3DBuffer8 object, which can be used to locate the sound in space.

The tutorial is presented in the following steps:

  • Step 1: Create the DirectX Objects
  • Step 2: Initialize the Audio Environment
  • Step 3: Create the Audiopath
  • Step 4: Load a Segment
  • Step 5: Download the Band
  • Step 6: Play the Sound on the Audiopath
  • Step 7: Stop the Sound
  • Step 8: Set Audiopath Parameters
  • Step 9: Set 3-D Parameters

The complete sample code for the tutorial is available in the following folder:

(SDK root)\samples\Multimedia\VBSamples\DirectMusic\Tutorials\Tut2


Step 1: Create the DirectX Objects

The first step is to create the DirectX8 object, which is then used to create DirectMusicLoader8 and DirectMusicPerformance8.

The variables for these objects are declared as follows:

Private dx As DirectX8
Private dml As DirectMusicLoader8
Private dmp As DirectMusicPerformance8

In addition, the following global object variables are declared for later use:

Private dmSeg As DirectMusicSegment8
Private dmSegState As DirectMusicSegmentState8
Private dmPath As DirectMusicAudioPath8

The first three objects are created in the Form_Load procedure. If any errors occur, they are ignored until after each creation method has been tried. If any error occurred, a single message box is displayed and the application terminates.

Private Sub Form_Load()

  Dim dmA As DMUS_AUDIOPARAMS
  MediaPath = FindMediaDir("tuta.wav")

  On Local Error Resume Next

  Set dx = New DirectX8
  Set dml = dx.DirectMusicLoaderCreate
  Set dmp = dx.DirectMusicPerformanceCreate

The Form_Load procedure is continued in the next topic, Step 2: Initialize the Audio Environment


Step 2: Initialize the Audio Environment

Still in the Form_Load procedure, the sample application sets the search directory so the loader knows where to find the sound files:

  dml.SetSearchDirectory MediaPath

Next it initializes the performance. The DMUS_AUDIOPARAMS type is left blank, causing the performance to be initialized with default parameters. No default audiopath is requested.

  dmp.InitAudio Me.hWnd, DMUS_AUDIOF_ALL, dmA

If any errors have occurred in creating or initializing the objects, they are handled now:

  If Err.Number <> 0 Then
    MsgBox "Could not initialize DirectMusic." & vbCrLf & _
    "This sample will exit.", vbOKOnly Or vbInformation, _
    "Exiting..."
    Unload Me
    Exit Sub
  End If

The Form_Load procedure is concluded in the next topic, Step 3: Create the Audiopath


Step 3: Create the Audiopath

Recall that in the call to DirectMusicPerformance8.InitAudio, no default audiopath was specified. Instead, the sample creates a standard audiopath on which segments can be played. In a more complex application, multiple audiopaths might be created: one for music and one for 3-D sound effects, for example. This tutorial requires only a single audiopath, of type DMUS_APATH_DYNAMIC_3D. This type of audiopath does not contain any effects such as reverberation, but is adequate for simple sound effects.

  Set dmPath = dmp.CreateStandardAudioPath(DMUS_APATH_DYNAMIC_3D, _
               64, True)
End Sub  ' Form_Load

The audiopath contains support for up to 64 performance channels and is activated on creation.

Next: Step 4: Load a Segment


Step 4: Load a Segment

The application now has all the objects it needs for loading and playing sounds. In the sample, one of three sound files is always played in response to the Play button, depending on the user's choice of file type.

The LoadSound procedure is called in response to the first click of the Play button, and also in response to the selection of an option button. The first thing the procedure does is verify that the file exists, as follows:

  If Dir$(sFile) = vbNullString Then
    MsgBox "Unable to find " & sFile, vbOKOnly Or vbCritical, _
     "Not found."
    Unload Me
  End If

If a segment has already been loaded, its band or bands are unloaded from the synthesizer, and the segment is released:

  If Not (dmSeg Is Nothing) Then
    dmSeg.Unload dmPath
    Set dmSeg = Nothing
  End If

Then the new segment is loaded. If it is a MIDI file, the application calls DirectMusicSegment8.SetStandardMidiFile. A standard MIDI file behaves somewhat differently than one that has been saved as a DirectMusic Producer segment, and this call ensures that it is handled properly.

  Set dmSeg = dml.LoadSegment(sFile)
  If Right$(sFile, 4) = ".mid" Then dmSeg.SetStandardMidiFile

The LoadSound procedure is concluded in the next topic, Step 5: Download the Band


Step 5: Download the Band

An easily overlooked step in playing a segment is to download the band. This step is not needed for wave files, but does no harm. For MIDI files and DirectMusic Producer segments, it is essential, so that the synthesizer can play note messages with the correct timbres.

The DirectMusicSegment8.Download method takes either an audiopath or the performance as a parameter. Since most applications use only a single synthesizer, it doesn't matter which you use. In the sample, the segment's bands are downloaded to the audiopath created in Step 3: Create the Audiopath.

dmSeg.Download dmPath

The LoadSound procedure concludes by initializing the volume and 3-D positioning of the sound:

  scrlPan_Change
  scrlVol_Change
End Sub

Next: Step 6: Play the Sound on the Audiopath


Step 6: Play the Sound on the Audiopath

When the Play button is clicked, the following procedure checks the state of the option buttons, loads the appropriate segment if one has not already been loaded in response to an option button selection, and plays the segment as a primary segment on the audiopath created previously.

Private Sub cmdPlay_Click()

  If dmSeg Is Nothing Then
    If optWave.Value Then LoadSound MediaPath & "\tuta.wav"
    If optMid.Value Then LoadSound MediaPath & "\tut.mid"
    If optSeg.Value Then LoadSound MediaPath & "\sample.sgt"
  End If

  Set dmSegState = dmp.PlaySegmentEx(dmSeg, 0, 0, Nothing, dmPath)

End Sub

The procedure obtains a DirectMusicSegmentState8 object, which could be used to retrieve information about the state of the playback. The segment state can also be passed to DirectMusicPerformance8.StopEx to stop just one instance of the segment. This is useful for secondary segments, where multiple instances might be playing at the same time.

Next: Step 7: Stop the Sound


Step 7: Stop the Sound

The following procedure stops the sound in response to input. Because no repetitions are set for any of the sample segments, they also stop automatically when they reach the end.

Private Sub cmdStop_Click()
  If dmSeg Is Nothing Then Exit Sub
  dmp.StopEx dmSeg, 0, 0
  mlOffset = 0
End Sub

The call to DirectMusicPerformance8.StopEx takes the segment as an argument; it might also take the segment state obtained in the previous step, or the audiopath. The second parameter orders an immediate stop, and the third specifies no flags. The flags could request that the music not stop until an appropriate boundary occurs, such as the end of a measure, but such a request would be ignored for wave files.

Next: Step 8: Set Audiopath Parameters


Step 8: Set Audiopath Parameters

At any time, the user of the sample application can set the volume on the audiopath by moving the slider. In response, the application calls DirectMusicAudioPath8.SetVolume. The change affects all segments played on the audiopath. If the application had multiple audiopaths, segments played on other audiopaths would not be affected.

Private Sub scrlVol_Change()
  dmPath.SetVolume scrlVol.Value, 0
End Sub

The first parameter is the new volume, in hundredths of a decibel. The application allows the volume to be lowered by up to 50 decibels. The second value is the fade time, or the duration over which the change in volume takes place. In this case, the new volume is set immediately.

Next: Step 9: Set 3-D Parameters


Step 9: Set 3-D Parameters

In this step you learn how to obtain the DirectSound3DBuffer8 object from the audiopath and use it to locate the sound in space. Although the sample application only pans the sound from right to left, the same technique can be used to move the sound in three dimensions.

In Step 3: Create the Audiopath, when the performance was initialized, the application requested a default audiopath of type DMUS_APATH_DYNAMIC_3D. This standard audiopath sends its data through a 3-D buffer. When the user moves the pan slider, the application responds first by obtaining an object for this buffer.

Private Sub scrlPan_Change()
  If dmSeg Is Nothing Then Exit Sub

  Dim dsBuf As DirectSound3DBuffer8

  Set dsBuf = dmPath.GetObjectinPath(DMUS_PCHANNEL_ALL, _
    DMUS_PATH_BUFFER, 0, vbNullString, 0, _
    "IID_IDirectSound3DBuffer")

The parameters to DirectMusicAudioPath8.GetObjectInPath can be a little tricky to set up properly. For information on which parameters are relevant for objects at different stages in the path, see Retrieving Objects from an Audiopath.

In this case, you are retrieving a secondary buffer that is used by all performance channels on this audiopath. Set the lPChannel parameter to DMUS_PCHANNEL_ALL.

Because the buffer you want is the first of the two in the chain, you pass 0 as lBuffer. The DMUS_PATH_BUFFER stage contains only buffer objects, and not the DMOs attached to those buffers; therefore lIndex is ignored.

Now the application can use the buffer object to set the position of the sound source, as follows:

  dsBuf.SetPosition scrlPan.Value / 5, 0, 0, DS3D_IMMEDIATE
  Set dsBuf = Nothing

End Sub

The first three parameters specify the new position of the sound source in relation to the default listener. The default listener is at coordinates (0.0, 0.0, 0.0), facing toward the positive z-axis, with the top of the head toward the positive y-axis. Distance units are meters by default. For more information, see Coordinates of 3-D Space and Listener Orientation.

The last parameter of the DirectSound3DBuffer8.SetPosition method specifies whether the change is to be made immediately or deferred until all changes are committed. For more information, see Deferred Settings.


DirectX Audio Visual Basic Samples

The sample applications described in this section demonstrate the use and capabilities of the Microsoft® DirectMusic® and Microsoft® DirectSound® application programming interfaces (APIs) in Microsoft® DirectX® for Microsoft® Visual Basic®.

The samples are described under the following headings:

  • DirectMusic Visual Basic Samples. These samples use the DirectMusic API to load and play sounds. Some of them also use elements of the DirectSound API.
  • DirectSound Visual Basic Samples. These samples use only the DirectSound API. However, many of the techniques shown can also be used with buffers obtained from a DirectMusic audiopath.


DirectMusic Visual Basic Samples

The following executable applications using the DirectMusic API, or DirectSound and DirectMusic together, are found on the Start menu under Programs/Microsoft DirectX 8.1 SDK/Visual Basic Samples/DirectMusic Samples:

  • AudioEffects
  • AudioPath
  • DLSEffects
  • DMDrums
  • PlayAudio
  • PlayMotif
  • SimpleAudioPath

The source code is in the following folder:

\(SDK root)\samples\Multimedia\VBSamples\DirectMusic\

In addition to these samples, the source files for tutorial applications are contained in the following folder:

\(SDK root)\samples\Multimedia\VBSamples\DirectMusic\Tutorials

For more information, see DirectX Audio Visual Basic Tutorials.


AudioEffects

Description

The AudioEffects sample shows how to retrieve a buffer from an audiopath and apply effects to it. It also demonstrates the standard effects supplied with DirectX.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\AudioEffects

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\Bin

User's Guide

Load a sound file. Add one or more effects to the Effects in Use list by selecting an effect from the Available Effects list and clicking the right arrow. Remove an effect by selecting it in the Effects in Use list and clicking the left arrow. To update the effects on the buffer, click Apply Effects.

Programming Notes

The cmdApply_Click procedure contains the code for setting the effects, or removing them. Note the main steps:

  • Describe the effects in the DSEffects array of DSEFFECTDESC types.
  • Obtain the buffer from the audiopath by calling DirectMusicAudioPath8.GetObjectInPath.
  • Deactivate the audiopath.
  • Set the effects by calling DirectSoundSecondaryBuffer8.SetFX.
  • Reactivate the audiopath.


AudioPath

Description

The AudioPath sample shows how files can be played on separate audiopaths, each of which can be manipulated separately.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\AudioPath

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\Bin

User's Guide

Load one file on Audiopath 1 and one or more files on Audiopaths 2 and Audiopath 3. Click Play for any audiopath to play all files listed for that path. You can play more than one audiopath at the same time. Use the sliders to change the volume and 3-D spatialization on each audiopath.

Programming Notes

In the InitAudio procedure, the performance is initialized without a default audiopath, and three standard audiopaths are created. Each segment is played on a particular audiopath by passing that audiopath to DirectMusicPerformance8.PlaySegmentEx.

It is possible to play multiple instances of a segment on a single audiopath by loading the file more than once as a secondary segment. Because the instances play simultaneously in the sample, you only hear one instance. However, the sample does illustrate how each instance is represented by a DirectMusicSegmentState8 object, which is passed to DirectMusicPerformance8.IsPlaying to ascertain whether the instance is playing.


DLSEffects

Description

The DLSEffects sample shows how an application can use DLS instruments for sound effects, and how to send MIDI messages.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\DLSEffects

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\Bin

User's Guide

Click the buttons labeled C3 to C10 to play a vocal effect. Click On to play the heartbeat effect continuously, and vary the pitch by using the Note and Pitch Bend sliders. Set the velocity (volume) of notes by using the slider on the right. Changes in velocity apply only to sounds started after the change is made.

Programming Notes

The DLS instruments are taken from Boids.dls. That collection contains only a single instrument, called Vocals, which is based on different wave samples for different regions, or ranges of notes. For example, the first speech sound is used when any MIDI note between C3 and B3 is played. The speech sounds are played at the original pitch only when the note is the lowest one in the region.

One of the samples, called Heartbeat, is valid for the range B7-B8. Because this is not a speech sample, the pitch can reasonably be varied. This is done by playing various notes within the range, as determined by the slider setting.

Heartbeat is also the only sample in the DLS collection that is based on a looped wave, so that it can be played continuously as long as the note is on. The other samples play only once regardless of the duration of the note.


DMDrums

Description

The DMDrums sample application shows how an application can vary music by changing the band, volume, master groove level, and tempo. It also shows how to play motifs in response to user input.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\DMDrums

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\Bin

User's Guide

Start the music by clicking the Play button. Select different types of music from the Groove list and different bands from the Drum Sets list. Adjust tempo and volume with the UpDown controls. Play drum motifs by clicking on any of the drum buttons.

Programming Notes

The selection in the Groove list determines the master groove level, which causes different patterns to be selected from the style object associated with the segment.

Every drum button plays a different motif. The instrument associated with the button is assigned in the motif.


PlayAudio

Description

The PlayAudio sample plays a sound on an audiopath and enables the user to set the tempo and master volume.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\PlayAudio

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\Bin

User's Guide

Load a segment, MIDI file, or wave by clicking Audio File. Select playback options. The Tempo slider is not enabled for wave files.

Programming Notes

The application sets up a notification of type DMUS_NOTIFY_ON_SEGMENT, which triggers the DirectXEvent8_DXCallback procedure on various segment-related events. In the callback procedure, the subtype of the notification message is checked to see if the segment has stopped playing. If it has, the user interface is updated to enable play options.


PlayMotif

Description

The PlayMotif sample demonstrates how a motif played as a secondary segment can be aligned to the rhythm of the primary segment in various ways.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\PlayMotif

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\Bin

User's Guide

Play the default segment, or load another DirectMusic Producer segment that contains motifs. Select one of the patterns in the list box and one of the Align Option buttons, and then click Play Motif. Note how the motif does not begin playing until an appropriate boundary in the primary segment has been reached.

Programming Notes

Information about the motifs is contained in an array of user-defined types, which is initialized in the LoadSegment procedure. When a motif is played, it is aligned to the primary segment's rhythm by passing one of the CONST_DMUS_SEGF_FLAGS to DirectMusicPerformance8.PlaySegmentEx, in the cmdPlayMotif_Click procedure.

Notifications are used to keep the user interface up to date. Of particular interest is the way the segment state is retrieved from the User member of the DMUS_NOTIFICATION_PMSG type, so that the application can ascertain which motif started or stopped.


SimpleAudioPath

Description

The SimpleAudioPath sample demonstrates how different sounds can be played on an audiopath, and how the parameters of all sounds are affected by changes made on the audiopath.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\SimpleAudioPath

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectMusic\Bin

User's Guide

Click Lullaby, Snore, and Mumble to play different sounds. Adjust the 3-D position of the sounds by using the sliders. Click Rude Awakening to stop all other sounds.

Programming Notes

The lullaby music is played as the primary segment, which means that only one instance of it can be playing at one time. You can play multiple instances of the snore and mumble sounds.

The audiopath is of type DMUS_APATH_DYNAMIC_3D. The path contains a 3-D buffer into which the synthesizer mixes all the sounds. To change the position of the sound, the application retrieves a DirectSound3DBuffer8 object from the path and calls DirectSound3DBuffer8.SetPosition.

When Rude Awakening is clicked, the audiopath is passed to DirectMusicPerformance8.PlaySegmentEx as the From parameter. This causes all segment instances playing on the audiopath to stop before the new segment begins.


DirectSound Visual Basic Samples

The following executable applications using only DirectSound are found on the Start menu under Programs/Microsoft DirectX 8.1 SDK/Visual Basic Samples/DirectSound Samples:

  • AdjustSound
  • DeferredEffects
  • EffectsBuffers
  • EnumDevice
  • Play3DSound

The source code for these samples is in the following folder:

\(SDK root)\samples\Multimedia\VBSamples\DirectSound\

In addition to these samples, the source files for the tutorial applications are contained in the following folder:

\(SDK root)\samples\Multimedia\VBSamples\DirectSound\Tutorials

For more information, see DirectX Audio Visual Basic Tutorials.


AdjustSound

Description

The AdjustSound sample shows how to create a DirectSound secondary buffer to play a wave file, and how to change the parameters of the buffer.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\AdjustSound

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\Bin

User's Guide

Load a wave file by clicking Sound File. Select the 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

The application attempts to create a sound buffer when the file is loaded, and each time Play is clicked, using whatever options are selected at the time.


DeferredEffects

Description

The DefferedEffects sample demonstrates how to create deferred sound buffers with effects. Resources are not allocated to the buffers until the application requests them.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\DeferredEffects

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\Bin

User's Guide

Load a wave file by clicking the button beside the top text box. Select an effect in the top list and move it to the bottom list by clicking the down arrow, or by double-clicking the effect. Remove an effect by selecting it in the bottom list and clicking on the up arrow, or by double-clicking the effect. Update the effects on the buffer by clicking Apply Effects. Note that the status of each effect is given in the Effects in Use list. Play the sound.

Programming Notes

The sound buffer is created with the DSBCAPS_LOCDEFER flag, so that no resources are allocated to it until it is played, or until the application calls DirectSoundSecondaryBuffer8.AcquireResources.

The buffer is still deferred when DirectSoundSecondaryBuffer8.SetFX is called. The application then immediately calls AcquireResources to allocate resources to the buffer. It then ascertains whether the effects were successfully instantiated, and whether they are in hardware or software. (In DirectX 8.0, all effects are in software.)


EffectsBuffers

Description

The EffectsBuffers sample demonstrates the use of effects on DirectSound secondary buffers, and enables modification of effect parameters.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\EffectsBuffers

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\Bin

User's Guide

Load a wave file by clicking the button beside the top text box. Select an effect in the top list and move it to the bottom list by clicking the down arrow, or by double-clicking the effect. Remove an effect by selecting it in the bottom list and clicking on the up arrow, or by double-clicking the effect, or by right-clicking the effect and choosing Remove from the popup menu. Update the effects on the buffer by clicking Apply Effects. Note that the status of each effect is given in the Effects in Use list. Play the sound.

You can modify the parameters for an effect when the sound is not playing. Select the effect in the Effects In Use list and click Modify Effect, or right-click the effect and choose Change Settings from the popup menu.

Programming Notes

The ApplySettings function keeps track of what effects have already been applied by creating a unique value for each combination of effects. When the user clicks Apply Effects, the current combination is compared with the last one, stored in mlEffectKey, to see whether the effects have to be updated.


EnumDevice

Description

The EnumDevice sample shows how to enumerate and create playback and capture devices.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\EnumDevice

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\Bin

User's Guide

Select a playback and capture device from the dropdown lists. Click Create.

Programming Notes

The LoadEnum procedure populates the listboxes. The primary devices on the system are always enumerated twice, once under their proper names and once as "Primary Sound Driver" or "Primary Sound Capture Driver." The value returned by DirectSoundEnum8.GetGuid for the primary driver is all zeros.

The DirectSound8 object is released as soon as it has been created. On systems that do not support full duplex, the creation of DirectSoundCapture8 could fail if the DirectSound8 object exists.


Play3DSound

Description

The Play3DSound sample shows how to create a 3-D sound buffer and manipulate its properties.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\Play3DSound

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectSound\Bin

User's Guide

Load a mono wave file by clicking Sound. Choose a 3-D virtualization algorithm. Play the sound, and set the volume and direction of the sound source by using the sliders. The direction is the orientation of the sound cone; the sound cone is oriented toward the narrow point of the red triangle. Move the sound source by dragging the red triangle or by clicking on a destination. The listener is represented by the black triangle, which cannot be moved.

Programming Notes

Because of the limitations of a two-dimensional display, the sound source can move only along the x-axis (positive toward the right of the screen) and along the z-axis (positive toward the bottom of the screen). The application uses the default listener position (0, 0, 0) and orientation (0, 0, 1). This means that the listener is facing the top of the screen.

If the user attempts to load a stereo file, an error results, because a buffer in a stereo wave format cannot be created with the DSBCAPS_CTRL3D flag. The DSBUFFERDESC type passed to DirectSound8.CreateSoundBufferFromFile receives information about the format even though the method fails, making it possible for the application to warn the user after handling the error. Even if the method succeeds, the buffer is discarded because the application creates a new one after ascertaining the user's preferred virtualization algorithm. A DirectSound3DBuffer8 object is obtained from this buffer, and this object is used for controlling the 3-D parameters.


DirectMusic Visual Basic Reference

This section contains reference information for the API elements of Microsoft® DirectMusic® for Microsoft® Visual Basic®. Reference material is divided into the following categories:

  • DirectMusic Classes
  • DirectMusic Types
  • DirectMusic Enumerations
  • DirectMusic Error Codes


DirectMusic Classes

This section contains references for methods of the following DirectMusic classes.

Class | Description
DirectMusicAudioPath8 | Represents the stages of data flow from the performance to the DirectSound buffer.
DirectMusicBand8 | Represents a band, which is used to set the instrument choices and mixer settings for a set of performance channels.
DirectMusicChordMap8 | Represents a chordmap, which provides the DirectMusicComposer8 object with the information it needs to create chord progressions for segments it composes.
DirectMusicCollection8 | Manages an instance of a DLS file.
DirectMusicComposer8 | Composes segments and transitions from compositional elements, and to change the chordmap of an existing segment.
DirectMusicLoader8 | Finds and loads objects that represent musical and instrument data.
DirectMusicPerformance8 | Acts as overall manager of music playback.
DirectMusicSegment8 | Represents a single piece of music or a template.
DirectMusicSegmentState8 | Represents a playing instance of a segment.
DirectMusicStyle8 | Represents a style, which is a collection of musical data including patterns and instruments.


DirectMusicAudioPath8

The DirectMusicAudioPath8 class represents the stages of data flow from the performance to the DirectSound buffer. A standard audiopath can be created by using DirectMusicPerformance8.CreateStandardAudioPath. A standard default path can also be created by DirectMusicPerformance8.InitAudio and retrieved by using DirectMusicPerformance8.GetDefaultAudioPath. Finally, an audiopath can be created from an audiopath configuration in a segment by using the DirectMusicPerformance8.CreateAudioPath method.

A DirectMusicAudioPath8 object is passed to DirectMusicPerformance8.PlaySegmentEx to play the segment on that audiopath.

The DirectMusicAudioPath8 class has the following methods.

Method | Description
Activate | Activates or deactivates the audiopath.
GetObjectInPath | Retrieves an object in the audiopath.
SetVolume | Sets the audio volume on the path.


DirectMusicAudioPath8.Activate

The Activate method activates or deactivates the audiopath.

object.Activate(fActive As Boolean)

Parts

object

Resolves to a DirectMusicAudioPath8 object.

fActive

Boolean value that specifies the state of the path. A value of True activates the path, and False deactivates it.

Error Codes

If the method fails, an error is raised.


DirectMusicAudioPath8.GetObjectInPath

The GetObjectInPath method retrieves an object in the audiopath.

object.GetObjectInPath( _
  lPChannel As Long, _
  lStage As CONST_DMUSIC_PATH, _
  lBuffer As Long,
  guidObject As String, _
  lIndex As Long, _
  iidInterface As String _
) As Unknown

Parts

object

Resolves to a DirectMusicAudioPath8 object.

lPChannel

performance channel to search, or DMUS_PCHANNEL_ALL to search all channels. The first channel is numbered 0. See Remarks.

lStage

Stage in the path. One of the constants from the CONST_DMUSIC_PATH enumeration. See Remarks.

lBuffer

If lStage is DMUS_PATH_BUFFER_DMO or DMUS_PATH_MIXIN_BUFFER_DMO, specifies the index of the buffer in which that DMO resides. If lStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER, specifies the index of the buffer. Otherwise must be 0.

guidObject

Class identifier of the object, such as CLSID_DirectMusicPerformance, or GUID_ALL_OBJECTS to search for an object of any class. This parameter is ignored if only a single class of object can exist at the stage specified by lStage, and can be set to GUID_NULL.

lIndex

Index of the object within a list of matching objects. Set to 0 to find the first matching object. If lStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER, this parameter is ignored, and the buffer index is specified by lBuffer.

iidInterface

Identifier of the desired class. This can be a GUID in string form, or one of the identifiers in the AUDIOSTRINGCONSTANTS module, such as IID_DirectSoundPrimaryBuffer.

Return Values

Returns an object of the class specified in iidInterface.

Error Codes

If the method fails, an error is raised. Possible values of Err.Number include the following:

DMUS_E_NOT_FOUND
DMUS_E_NOINTERFACE

Remarks

The value in lPChannel must be 0 for any stage that is not channel-specific. Objects in the following stages are channel-specific and can be retrieved by setting a channel number or DMUS_PCHANNEL_ALL in lPChannel:

DMUS_PATH_AUDIOPATH_TOOL
DMUS_PATH_BUFFER
DMUS_PATH_BUFFER_DMO
DMUS_PATH_PERFORMANCE_TOOL
DMUS_PATH_PORT
DMUS_PATH_SEGMENT_TOOL

The precedence of the parameters in filtering out unwanted objects is as follows:

  1. lStage.
  2. guidObject. If this value is not GUID_All_Objects, only objects whose class identifier equals guidObject are searched. However, this parameter is ignored if only a single class of object can be found at the specified stage.
  3. lPChannel. If the stage is channel-specific and this value is not DMUS_PCHANNEL_ALL, only objects on the channel are searched.
  4. lBuffer. This is used only if lStage is DMUS_PATH_BUFFER, DMUS_PATH_MIXIN_BUFFER, DMUS_PATH_BUFFER_DMO, or DMUS_PATH_MIXIN_BUFFER_DMO.
  5. lIndex.

If a matching object is found but the class specified by iidInterface cannot be obtained, the method fails.

Not all types of objects that can be retrieved by this method are supported in DirectX for Visual Basic. For example, it would be meaningless to pass DMUS_PATH_PERFORMANCE_TOOL in lStage, because tools are not supported.

See Also

Retrieving Objects from an Audiopath


DirectMusicAudioPath8.SetVolume

The SetVolume method sets the audio volume on the path.

object.SetVolume(lVolume As Long, lDuration As Long)

Parts

object

Resolves to a DirectMusicAudioPath8 object.

lVolume

Value that specifies the attenuation, in hundredths of a decibel.

lDuration

Value that specifies the time, in milliseconds, over which the volume change takes place. A value of 0 ensures maximum efficiency.

Error Codes

If the method fails, an error is raised.

Remarks

This method works by sending a volume curve message. Any volume events occurring later, such as a band change, override the volume set by this method. DirectMusicAudioPath8.SetVolume is useful mainly for adjusting currently playing sounds; for example, to fade out before stopping a segment. If you want to make a global change that affects all playback, use one of the following techniques:

  • Obtain the buffer object from the audiopath and use DirectSoundSecondaryBuffer8.SetVolume.
  • Set the master volume for the performance by using DirectMusicPerformance8.SetMasterVolume.


DirectMusicBand8

The DirectMusicBand8 class represents a band, which is used to set the instrument choices and mixer settings for a set of performance channels.

Bands can be stored directly in their own files or embedded in a style. The DirectMusicBand8 object is obtained by using one of the following methods:

  • DirectMusicLoader8.LoadBand
  • DirectMusicLoader8.LoadBandFromResource
  • DirectMusicStyle8.GetDefaultBand
  • DirectMusicStyle8.GetBand

The DirectMusicBand8 class has the following methods:

Method | Description
CreateSegment | Creates a segment object.
Download | Downloads the DLS data for instruments in the band to a performance object.
Unload | Unloads the DLS data for instruments in the band previously downloaded by the Download method.


DirectMusicBand8.CreateSegment

The CreateSegment method creates a segment object that can be used to perform the volume, pan, transposition, and patch change commands in the band dynamically, using the DirectMusicPerformance8.PlaySegmentEx method.

object.CreateSegment() As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicBand8 object.

Return Values

Returns a DirectMusicSegment8 object.

Error Codes

If the method fails, Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_OUTOFMEMORY


DirectMusicBand8.Download

The Download method downloads the DLS data for instruments in the band to a performance object. Once a band has been downloaded, the instruments in the band can be selected, either individually with program change MIDI messages, or all at once by playing a band segment created through a call to the DirectMusicBand8.CreateSegment method.

object.Download(downloadpath As Unknown)

Parts

object

Resolves to a DirectMusicBand8 object.

downloadpath

DirectMusicAudioPath8 or DirectMusicPerformance8 object that specifies the path on which the band is to perform.

Error Codes

If the method fails, and Err.Number can be set to one of the following values:

DMUS_E_NOT_INIT
DMUS_E_OUTOFMEMORY

Remarks

Because a downloaded band uses synthesizer resources, it should be unloaded when no longer needed by using the DirectMusicBand8.Unload method.

If DMUS_E_NOT_INIT is raised, it usually means that the performance was not properly connected to an initialized port. Since this is a complete failure, there is no need to call DirectMusicBand8.Unload later.

If the download only partially succeeds, no error is raised but some instruments might not play. The following are some common causes of a partial download:

  • The band has instruments on performance channels not allocated on the port.
  • The band has instruments in a DLS format incompatible with the synthesizer they are being downloaded to.


DirectMusicBand8.Unload

The Unload method unloads the DLS data for instruments in the band previously downloaded by DirectMusicBand8.Download.

object.Unload(downloadpath As Unknown)

Parts

object

Resolves to a DirectMusicBand8 object.

downloadpath

DirectMusicAudioPath8 or DirectMusicPerformance8 object that specifies the path to which the band was downloaded.

Error Codes

If the method fails, it raises an error. Possible values of Err.Number include the following:

DMUS_E_NOT_INIT
DMUS_E_NOT_FOUND


DirectMusicChordMap8

The DirectMusicChordMap8 class represents a chordmap. Chordmaps provide the DirectMusicComposer8 object with the information it needs to create chord progressions for segments it composes. A chordmap can also be applied to an existing segment in order to change the chords.

The class has no public methods. An instance of it is obtained by using the DirectMusicPerformance8.GetChordmap method.

See Also

  • DirectMusicComposer8.AutoTransition
  • DirectMusicComposer8.ChangeChordMap
  • DirectMusicComposer8.ComposeSegmentFromShape
  • DirectMusicComposer8.ComposeSegmentFromTemplate
  • DirectMusicComposer8.ComposeTransition
  • DirectMusicPerformance8.GetChordmap


DirectMusicCollection8

The DirectMusicCollection8 class manages an instance of a DLS file.

The class has no public methods. An instance of it is obtained by using the DirectMusicLoader8.LoadCollection or the DirectMusicLoader8.LoadCollectionFromResource method, and is associated with a segment by a call to DirectMusicSegment8.ConnectToCollection.


DirectMusicComposer8

The DirectMusicComposer8 class is used to compose segments and transitions from compositional elements, and to change the chordmap of an existing segment.

A DirectMusicComposer8 object is obtained by using the DirectX8.DirectMusicComposerCreate method.

The DirectMusicComposer8 class has the following methods.

Method | Description
AutoTransition | Composes a transition between segments and cues the transition and the second segment to play.
ChangeChordMap | Modifies the chords and scale pattern of an existing segment to reflect a new chordmap.
ComposeSegmentFromShape | Creates an original segment from a style and a chordmap, based on a predefined shape.
ComposeSegmentFromTemplate | Creates an original segment from a style, a chordmap, and a template.
ComposeTemplateFromShape | Creates a new template segment based on a predefined shape.
ComposeTransition | Composes a transition from a measure inside one segment to another.


DirectMusicComposer8.AutoTransition

The AutoTransition method composes a transition from inside a performance's primary segment (or from silence) to another segment, and then cues the transition and the second segment to play.

object.AutoTransition( _
  performance As DirectMusicPerformance8, _
  toSeg As DirectMusicSegment8, _
  lCommand As Long, _
  lFlags As Long, _
  chordmap As DirectMusicChordMap8 _
) As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicComposer8 object.

performance

DirectMusicPerformance8 object in which to do the transition.

toSeg

Segment to which the transition should smoothly flow. See Remarks.

lCommand

Embellishment to use when composing the transition. See CONST_DMUS_COMMANDT_TYPES. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to the primary segment and an introduction to toSeg.

lFlags

Composition options. See CONST_DMUS_COMPOSEF_FLAGS.

chordmap

DirectMusicChordMap8 object representing the chordmapto be used when composing the transition.

Return Values

Returns a DirectMusicSegment8 object, unless no style is available for the composition of the transitional segment. See Remarks.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The value in toSeg can be Nothing, as long as lFlags does not include DMUS_COMPOSEF_MODULATE. If toSeg is Nothing or a segment that contains no style track, intro embellishments are not valid. If there is no currently playing segment or it contains no style track, then fill, break, end, and groove embellishments are not valid.

It is possible for both the currently playing segment and segment1 to be Nothing or segments that contain no style tracks (such as segments based on MIDI files). If so, all embellishments are invalid, and no transition occurs between the currently playing segment and segment1. The method returns Nothing, but it succeeds and cues the segment represented by segment1.

The value in chordmap can be Nothing. If so, an attempt is made to obtain a chordmap from a chordmap track, first from segment1 and then from the performance's primary segment. If neither of these segments contains a chordmap track, the chord occurring at the current time in the primary segment is used as the chord in the transition.


DirectMusicComposer8.ChangeChordMap

The DirectMusicComposer8.ChangeChordMap method modifies the chords and scale pattern of an existing segment to reflect a new chordmap.

object.ChangeChordMap(segment As DirectMusicSegment8, _
  trackScale As Boolean, _
  chordmap As DirectMusicChordMap8)

Parts

object

Resolves to a DirectMusicComposer8 object.

segment

DirectMusicSegment8 object that specifies the segment in which to change the chordmap.

trackScale

Value of type Boolean that specifies scale tracking. If True, the method transposes all the chords to be relative to the root of the new chordmap's scale. If False, roots are left as they were.

chordmap

DirectMusicChordMap8 object that specifies the new chordmap for the segment.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The method can be called while the segment is playing.


DirectMusicComposer8.ComposeSegmentFromShape

The ComposeSegmentFromShape method creates an original segment from a style and a chordmap, based on a predefined shape. The shape represents the way chords and embellishments occur over time across the segment.

object.ComposeSegmentFromShape(style As DirectMusicStyle8, _
  numberOfMeasures As Integer, _
  shape As Integer, _
  activity As Integer, _
  bIntro As Boolean, _
  bEnd As Boolean, _
  chordmap As DirectMusicChordMap8 _
) As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicComposer8 object.

style

DirectMusicStyle8 object that specifies the style from which to compose the segment.

numberOfMeasures

Length, in measures, of the segment to be composed.

shape

Shape of the segment to be composed, based on changes in the groove level. Possible values are of the CONST_DMUS_SHAPET_TYPES enumeration.

activity

Rate of harmonic motion. Valid values are from 0 through 3. Lower values mean more chord changes.

bIntro

True if an introduction is to be composed for the segment, False otherwise.

bEnd

True if an ending is to be composed for the segment, False otherwise.

chordmap

DirectMusicChordMap8 object from which to create the segment.

Return Values

Returns a DirectMusicSegment8 object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicComposer8.ComposeSegmentFromTemplate
  • DirectMusicComposer8.ComposeTemplateFromShape


DirectMusicComposer8.ComposeSegmentFromTemplate

The ComposeSegmentFromTemplate method creates an original segment from a style, a chordmap, and a template.

object.ComposeSegmentFromTemplate( _
  style As DirectMusicStyle8, _
  templateSeg As DirectMusicSegment8, _
  activity As Integer, _
  chordmap As DirectMusicChordMap8 _
) As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicComposer8 object.

style

DirectMusicStyle8 object from which to create the segment.

templateSeg

DirectMusicSegment8 object representing the template from which to create the segment.

activity

Rate of harmonic motion. Valid values are from 0 through 3. Lower values mean more chord changes.

chordmap

DirectMusicChordMap8 object representing the chordmap from which to create the segment.

Return Values

Returns a DirectMusicSegment8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_INVALIDARG.

Remarks

If style is not Nothing, it is used in composing the segment; if it is Nothing, a style is retrieved from the template specified in templateSeg. Similarly, if chordmap is not Nothing, it is used in composing the segment; if it is Nothing, a chordmap is retrieved from the template.

If style is Nothing and there is no style track in the template, or chordmap is Nothing and there is no chordmap track, the method returns DMUS_E_INVALIDARG.

The length of the segment is equal to the length of the template passed in.

See Also

  • DirectMusicComposer8.ComposeSegmentFromShape
  • DirectMusicComposer8.ComposeTemplateFromShape


DirectMusicComposer8.ComposeTemplateFromShape

The ComposeTemplateFromShape method creates a new template segment based on a predefined shape.

object.ComposeTemplateFromShape(numMeasures As Integer, _
  shape As Integer, _
  bIntro As Boolean, _
  bEnd As Boolean, _
  endLength As Integer _
) As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicComposer8 object.

numMeasures

Length, in measures, of the segment to be composed. This value must be greater than 0.

shape

Shape of the segment to be composed, based on groove levels. Possible values are of the CONST_DMUS_SHAPET_TYPES enumeration.

bIntro

True if an introduction is to be composed for the segment, False otherwise.

bEnd

True if an ending is to be composed for the segment, False otherwise.

endLength

Length in measures of the ending, if one is to be composed. If bEnd is True, this value must be greater than 0 and equal to or less than the number of measures available (that is, not used in the introduction). See also Remarks.

Return Values

Returns a DirectMusicSegment8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY

Remarks

The value of endLength should not be greater than the length of the longest ending available in any style likely to be associated with this template through the DirectMusicComposer8.ComposeSegmentFromTemplate method. The ending starts playing at endLength measures before the end of the segment. If the ending is less than endLength measures long, the music then reverts to the regular groove.

See Also

  • DirectMusicComposer8.ComposeSegmentFromShape
  • DirectMusicComposer8.ComposeSegmentFromTemplate


DirectMusicComposer8.ComposeTransition

The ComposeTransition method composes a transition from a measure inside one segment to another.

object.ComposeTransition(fromSeg As DirectMusicSegment8, _
  toSeg As DirectMusicSegment8, _
  mtTime As Long, _
  lCommand As Long, _
  lFlags As Long, _
  chordmap As DirectMusicChordMap8 _
) As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicComposer8 object.

fromSeg

DirectMusicSegment8 object representing the segment from which to compose the transition.

toSeg

Segment to which the transition should smoothly flow. Can be Nothing if lFlags does not include DMUS_COMPOSEF_MODULATE.

mtTime

Time in fromSeg from which to compose the transition.

lCommand

Embellishment to use when composing the transition. See CONST_DMUS_COMMANDT_TYPES. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to fromSeg and an introduction to toSeg.

lFlags

Composition options. This parameter can contain one or more of the CONST_DMUS_COMPOSEF_FLAGS enumeration.

chordmap

DirectMusicChordMap8 object representing the chordmap to be used when composing the transition. See Remarks.

Return Values

Returns a DirectMusicSegment8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY

Remarks

The value in chordmap can be Nothing. If so, an attempt is made to obtain a chordmap from a chordmap track, first from toSeg and then from fromSeg. If neither of these segments contains a chordmap track, the chord occurring at mtTime in fromSeg is used as the chord in the transition.

The composer looks for a tempo, first in fromSeg, and then in toSeg. If neither of those segments contains a tempo track, the tempo for the transition segment is taken from the style.

See Also

  • DirectMusicComposer8.AutoTransition


DirectMusicLoader8

The DirectMusicLoader8 class is used to find and load objects that represent musical and instrument data.

The object is obtained by using the DirectX8.DirectMusicLoaderCreate method.

Objects referred to by other objects are loaded automatically. For example, a style may contain references to bands and collections in other files, and these are loaded, if possible, when the DirectMusicLoader8.LoadStyle method is called.

The DirectMusicLoader8 interface has the following methods.

Method | Description
LoadBand | Loads a band from a file.
LoadBandFromResource | Loads a band from a resource.
LoadChordMap | Loads a chordmap from a file.
LoadChordMapFromResource | Loads a chordmap from a resource.
LoadCollection | Loads a collection from a file.
LoadCollectionFromResource | Loads a collection from a resource.
LoadSegment | Loads a segment from a file.
LoadSegmentFromResource | Loads a segment from a resource.
LoadStyle | Loads a style from a file.
LoadStyleFromResource | Loads a style from a resource.
SetSearchDirectory | Sets the directory to be searched by the methods that load objects from a file.


DirectMusicLoader8.LoadBand

The LoadBand method loads a band from a file.

object.LoadBand(filename As String) As DirectMusicBand8

Parts

object

Resolves to a DirectMusicLoader8 object.

filename

Name of the file containing the band. If the file is not in the current directory or in the directory set by DirectMusicLoader8.SetSearchDirectory, the full path must be given.

Return Values

Returns a DirectMusicBand8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_INVALID_BAND
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

  • DirectMusicLoader8.LoadBandFromResource


DirectMusicLoader8.LoadBandFromResource

The LoadBandFromResource method loads a band from a resource.

object.LoadBandFromResource( _
  moduleName As String, _
  resourceName As String _
) As DirectMusicBand8

Parts

object

Resolves to a DirectMusicLoader8 object.

moduleName

Name of the module containing the resource.

resourceName

Identifier of the resource containing the band. The resource must be of type "DMBAND".

Return Values

Returns a DirectMusicBand8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_INVALID_BAND
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

  • DirectMusicLoader8.LoadBand


DirectMusicLoader8.LoadChordMap

The LoadChordMap method loads a chordmap from a file.

object.LoadChordMap(filename As String _
) As DirectMusicChordMap8

Parts

object

Resolves to a DirectMusicLoader8 object.

filename

Name of the file containing the chordmap. If the file is not in the current directory or in the directory set by DirectMusicLoader8.SetSearchDirectory, the full path must be given.

Return Values

Returns a DirectMusicChordMap8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

  • DirectMusicLoader8.LoadChordMapFromResource


DirectMusicLoader8.LoadChordMapFromResource

The LoadChordMapFromResource method loads a chordmap from a resource.

object.LoadChordMapFromResource( _
  moduleName As String, _
  resourceName As String _
) As DirectMusicChordMap8

Parts

object

Resolves to a DirectMusicLoader8 object.

moduleName

Name of the module containing the resource.

resourceName

Identifier of the resource containing the chordmap. The resource must be of type "DMCHORD".

Return Values

Returns a DirectMusicChordMap8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

  • DirectMusicLoader8.LoadChordMap


DirectMusicLoader8.LoadCollection

The LoadCollection method loads a DLS collection from a file.

object.LoadCollection(filename As String _
) As DirectMusicCollection8

Parts

object

Resolves to a DirectMusicLoader8 object.

filename

Name of the file containing the DLS collection. If the file is not in the current directory or in the directory set by DirectMusicLoader8.SetSearchDirectory, the full path must be given.

Return Values

Returns a DirectMusicCollection8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
DMUS_E_NOTADLSCOL

See Also

  • DirectMusicLoader8.LoadCollectionFromResource


DirectMusicLoader8.LoadCollectionFromResource

The LoadCollectionFromResource method loads a DLS collection from a resource.

object.LoadCollectionFromResource( _
  moduleName As String, _
  resourceName As String _
) As DirectMusicCollection8

Parts

object

Resolves to a DirectMusicLoader8 object.

moduleName

Name of the module containing the resource.

resourceName

Identifier of the resource containing the collection. The resource must be of type "DMCOLL".

Return Values

Returns a DirectMusicCollection8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
DMUS_E_NOTADLSCOL

See Also

  • DirectMusicLoader8.LoadCollection


DirectMusicLoader8.LoadSegment

The LoadSegment method loads a segment from a MIDI file, a wave file, or a segment file authored in DirectMusic Producer.

object.LoadSegment(filename As String _
) As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicLoader8 object.

filename

Name of the file containing the segment. If the file is not in the current directory or in the directory set by DirectMusicLoader8.SetSearchDirectory, the full path must be given.

Return Values

Returns a DirectMusicSegment8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

  • DirectMusicLoader8.LoadSegmentFromResource


DirectMusicLoader8.LoadSegmentFromResource

The LoadSegmentFromResource method loads a segment from a resource. The segment can be in the format of a MIDI file, a wave file, or a segment authored in DirectMusic Producer.

object.LoadSegmentFromResource( _
  moduleName As String, _
  resourceName As String _
) As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicLoader8 object.

moduleName

Name of the module containing the resource. The resource must be of type "DMSEG".

resourceName

Identifier of the resource containing the segment.

Return Values

Returns a DirectMusicSegment8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
DMUS_E_UNSUPPORTED_STREAM

See Also

  • DirectMusicLoader8.LoadSegment


DirectMusicLoader8.LoadStyle

The LoadStyle method loads a style object from a file.

object.LoadStyle(filename As String) As DirectMusicStyle8

Parts

object

Resolves to a DirectMusicLoader8 object.

filename

Name of the file containing the style object. If the file is not in the current directory or in the directory set by DirectMusicLoader8.SetSearchDirectory, the full path must be given.

Return Values

Returns a DirectMusicStyle8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

  • DirectMusicLoader8.LoadStyleFromResource


DirectMusicLoader8.LoadStyleFromResource

The LoadStyleFromResource method loads a style object from a resource.

object.LoadStyleFromResource( _
  moduleName As String, _
  resourceName As String _
) As DirectMusicStyle8

Parts

object

Resolves to a DirectMusicLoader8 object.

moduleName

Name of the module containing the resource.

resourceName

Identifier of the resource containing the style object. The resource must be of type "DMSTYLE".

Return Values

Returns a DirectMusicStyle8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

  • DirectMusicLoader8.LoadStyle


DirectMusicLoader8.SetSearchDirectory

The SetSearchDirectory method sets the directory to be searched by the DirectMusicLoader8.LoadBand, DirectMusicLoader8.LoadChordMap, DirectMusicLoader8.LoadCollection, DirectMusicLoader8.LoadSegment, and DirectMusicLoader8.LoadStyle methods when a fully qualified path is not supplied.

object.SetSearchDirectory(dir As String)

Parts

object

Resolves to a DirectMusicLoader8 object.

dir

Directory to search.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_BADPATH

Remarks

Once a search path is set, the loader does not need a full path every time it is given an object to load by file name. This allows objects that refer to other objects to find them by file name without knowing the full path.


DirectMusicPerformance8

The DirectMusicPerformance8 class overall manager of music playback. The performance maps performance channels to audiopaths, plays segments, dispatches messages, requests and receives event notifications, and sets and retrieves music parameters. It also has several methods for getting information about timing and for converting time and music values from one system to another.

If an application wants to have two or more complete sets of music playing at the same time, it can do so by creating more than one performance object. Separate performances obey separate tempo maps and play completely asynchronously, whereas all segments within one performance play in lock step.

The DirectMusicPerformance8 object is obtained by using the DirectX8.DirectMusicPerformanceCreate method.

The DirectMusicPerformance8 class has the following methods.

Audiopaths

Method | Description
CreateAudioPath | Creates an audiopath object from a configuration.
CreateStandardAudioPath | Creates an audiopath object of a standard type.
GetDefaultAudioPath | Retrieves the default audiopath.
SetDefaultAudioPath | Sets and activates the default audiopath for the performance.

Initialization and Cleanup

Method | Description
InitAudio | Initializes the performance and optionally sets up a default audiopath.
CloseDown | Closes down the performance.

Messages

Method | Description
SendCurvePMSG | Sends a performance message containing information about a controller curve.
SendMIDIPMSG | Sends a performance message containing information about a MIDI channel message not covered by other methods.
SendNotePMSG | Sends a performance message containing information about a note.
SendPatchPMSG | Sends a performance message containing information about a MIDI patch change.
SendTempoPMSG | Sends a performance message containing information about a tempo change.
SendTimeSigPMSG | Sends a performance message containing information about a time signature.
SendTransposePMSG | Sends a performance message causing a transposition to begin.

Notification

Method | Description
AddNotificationType | Causes the performance to generate notification messages whenever events of the requested type occur.
GetNotificationPMSG | Retrieves a pending notification message.
RemoveNotificationType | Removes a previously added notification type from the performance.
SetNotificationHandle | Sets the event handle for notifications.

Parameters

Method | Description
GetChordmap | Retrieves the chordmap from the performance's control segment.
GetCommand | Retrieves a command from the performance's control segment.
GetGrooveLevel | Retrieves the groove level from the performance's control segment.
GetMasterAutoDownload | Retrieves the setting for automatic downloading of instruments.
GetMasterGrooveLevel | Retrieves the value added to all groove levels in the performance.
GetMasterTempo | Retrieves a scaling factor that is applied to the tempo.
GetMasterVolume | Retrieves the master volume.
GetStyle | Retrieves the style underlying the control segment at a given time.
GetTempo | Retrieves the tempo at a given time.
GetTimeSig | Retrieves the time signature at a given time.
SetMasterAutoDownload | Turns automatic downloading of instruments on or off.
SetMasterGrooveLevel | Sets a value to be added to all groove levels in the performance.
SetMasterTempo | Sets a scaling factor that is applied to the tempo.
SetMasterVolume | Adjusts the master volume of the performance.

Segments

Method | Description
GetSegmentState | Retrieves an object representing the play state of the primary segment.
IsPlaying | Ascertains whether a particular segment or segment state is currently playing at the speakers.
PlaySegmentEx | Begins playback of a segment.
StopEx | Stops playback of an object.

Timing

Method | Description
AdjustTime | Adjusts the internal performance time forward or backward.
ClockToMusicTime | Converts clock time to music time.
GetBumperLength | Retrieves the amount of time between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port.
GetClockTime | Retrieves the current time.
GetLatencyTime | Retrieves the current latency time.
GetMusicTime | Retrieves the current time of the performance, in music time.
GetPrepareTime | Retrieves the approximate interval between the time at which messages are prepared and the time at which they are processed and heard.
GetQueueTime | Retrieves the current queue (or flush) time.
GetResolvedTime | Adjusts a given time to a given boundary.
MusicToClockTime | Converts time in music time format to time in clock time format.
SetBumperLength | Sets the amount of time between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port.
SetPrepareTime | Sets the approximate interval between the time at which messages are prepared and the time at which they are processed and heard.

Miscellaneous

Method | Description
Invalidate | Flushes all queued messages whose time stamps are later than the supplied time and causes all tracks of all segments to resend their data from the given time forward.
Reset | Resets the port.


DirectMusicPerformance8.AddNotificationType

The AddNotificationType method causes the performance to generate notification messages whenever events of the requested type occur.

object.AddNotificationType( _
  type As CONST_DMUS_NOTIFICATION_TYPE)

Parts

object

Resolves to a DirectMusicPerformance8 object.

type

Type of event for which notification messages are to be sent. For possible values, see CONST_DMUS_NOTIFICATION_TYPE.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY

See Also

  • DirectMusicPerformance8.RemoveNotificationType


DirectMusicPerformance8.AdjustTime

The AdjustTime method adjusts the internal performance time forward or backward. This is mostly used to compensate for drift when synchronizing to another source.

object.AdjustTime(tAmount As Long)

Parts

object

Resolves to a DirectMusicPerformance8 object.

tAmount

Amount of time, in clock time units, to add or subtract. This can be a number in the range from –1000 through 1000 (–1 second through +1 second).

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_INVALIDARG.

Remarks

The adjusted time is used internally by DirectMusic. It is not reflected in the time retrieved by the DirectMusicPerformance8.GetClockTime method.


DirectMusicPerformance8.ClockToMusicTime

The ClockToMusicTime method converts clock time to music time.

object.ClockToMusicTime(ctTime As Long) As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

ctTime

Time to convert, in clock time units.

Return Values

Returns the equivalent music time.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

Remarks

This method converts a time offset from the start of the performance, not a duration. The ratio between music time and clock time units depends on the tempo, so in making the conversion, DirectMusic takes into account all tempo changes since the start of the performance. If a master tempo has been set for the performance, it is taken into account as well.

Because music time is less precise than clock time, rounding off occurs.

See Also

  • DirectMusicPerformance8.MusicToClockTime
  • Clock Time vs. Music Time


DirectMusicPerformance8.CloseDown

The CloseDown method closes down the performance. An application that created the performance object and called DirectMusicPerformance8.InitAudio on it must call CloseDown before the performance object is released.

object.CloseDown()

Parts

object

Resolves to a DirectMusicPerformance8 object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

Failure to call CloseDown can cause memory leaks or application failures.

If the DirectSound8 object was created in the call to DirectMusicPerformance8.InitAudio but no object was returned to the application, CloseDown also releases DirectSound and all DirectSound buffers. If your application has set any variables to DirectSound buffer objects, it should ensure that those variables go out of scope or are set to Nothing before calling Closedown.

If the application created DirectSound8 explicitly, or obtained the DirectSound8 object from InitAudio, it is responsible for releasing DirectSound.

CloseDown releases any downloaded instruments that have not been unloaded.


DirectMusicPerformance8.CreateAudioPath

The CreateAudioPath method creates an audiopath object that represents the stages in data flow from the performance to DirectSound buffers.

object.CreateAudioPath( _
  SourceConfig As Unknown _
) As DirectMusicAudioPath8

Parts

object

Resolves to a DirectMusicPerformance8 object.

SourceConfig

Object that represents the audiopath configuration. This object is typically obtained from a segment by using the DirectMusicSegment8.GetAudioPathConfig method.

Return Values

Returns a DirectMusicAudioPath8 object.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include the following:

DMUS_E_NOT_INIT
DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_OUTOFMEMORY


DirectMusicPerformance8.CreateStandardAudioPath

The CreateStandardAudioPath method creates an object that represents the stages in data flow from the performance to DirectSound buffers. This method can be used instead of DirectMusicPerformance8.CreateAudioPath to create a basic predefined audiopath rather than one defined in a source file.

object.CreateStandardAudioPath( _
  lType As CONST_DMUSIC_STANDARD_AUDIO_PATH, _
  lPChannelCount As Long, _
  fActive As Boolean _
) As DirectMusicAudioPath8

Parts

object

Resolves to a DirectMusicPerformance8 object.

lType

Type of the path, specified by one of the constants of the CONST_DMUSIC_STANDARD_AUDIO_PATH enumeration. For more information on these audiopath types, see Standard Audiopaths.

lPChannelCount

Value that specifies the number of performance channels in the path.

fActive

Boolean value that specifies whether to activate the path on creation.

Return Values

Returns a DirectMusicAudioPath8 object.

Error Codes

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY


DirectMusicPerformance8.GetBumperLength

The GetBumperLength method retrieves the amount of time between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port.

object.GetBumperLength() As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns the bumper length, in milliseconds.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default value is 50 milliseconds.

See Also

DirectMusicPerformance8.SetBumperLength


DirectMusicPerformance8.GetChordmap

The GetChordmap method retrieves the chordmap from the performance's control segment.

object.GetChordMap( _
  mtTime As Long, _
  mtUntil As Long _
) As DirectMusicChordMap8

Parts

object

Resolves to a DirectMusicPerformance8 object.

mtTime

Time for which the chordmap is to be retrieved, in music time.

mtUntil

Variable of type Long that receives the music time (relative to mtTime) until which the chordmap is valid. If this returns a value of 0, either the chordmap is always valid, or it is unknown when it might become invalid. See Remarks.

Return Values

Returns a DirectMusicChordMap8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND

Remarks

Normally the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. The object returned by the method can become invalid before the time returned in mtUntil if another control segment is cued.

See Also

  • CONST_DMUS_SEGF_FLAGS


DirectMusicPerformance8.GetClockTime

The GetClockTime method retrieves the current time.

object.GetClockTime() As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns the time in units of approximately 1 millisecond, relative to an arbitrary start time.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

See Also

  • DirectMusicPerformance8.GetMusicTime
  • Clock Time vs. Music Time


DirectMusicPerformance8.GetCommand

The GetCommand method retrieves a command from the performance's control segment. The command indicates what type of pattern is being played at the specified time.

object.GetCommand( _
  mtTime As Long, _
  mtUntil As Long _
) As Byte

Parts

object

Resolves to a DirectMusicPerformance8 object.

mtTime

Time for which the command is to be retrieved, in music time.

mtUntil

Variable to receive the music time (relative to mtTime) until which the command is valid. If this returns a value of 0, either the command is always valid, or it is unknown when it might become invalid. See Remarks.

Return Values

Returns a command type. See CONST_DMUS_COMMANDT_TYPES.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following error codes:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND

Remarks

Normally the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. The object returned by the method can become invalid before the time returned in mtUntil if another control segment is cued.

See Also

  • CONST_DMUS_SEGF_FLAGS


DirectMusicPerformance8.GetDefaultAudioPath

The GetDefaultAudioPath method retrieves the default audiopath set by DirectMusicPerformance8.InitAudio or DirectMusicPerformance8.SetDefaultAudioPath.

object.GetDefaultAudioPath() As DirectMusicAudioPath8

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns a DirectMusicAudioPath8 object.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include the following:

DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_NOT_INIT


DirectMusicPerformance8.GetGrooveLevel

The GetGrooveLevel method retrieves the groove level from the performance's control segment. The groove level determines which patterns can be played at the specified time.

object.GetGrooveLevel( _
  mtTime As Long, _
  mtUntil As Long _
) As Byte

Parts

object

Resolves to a DirectMusicPerformance8 object.

mtTime

Time for which the groove level is to be retrieved, in music time.

mtUntil

Variable of type Long that receives the music time (relative to mtTime) until which the groove level is valid. If this returns a value of 0, either the groove level is always valid, or it is unknown when it might become invalid. See Remarks.

Return Values

Returns a value in the range from 1 through 100.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following error codes:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND

Remarks

Normally the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. The object returned by the method can become invalid before the time returned in mtUntil if another control segment is cued.

See Also

  • DirectMusicPerformance8.GetMasterGrooveLevel
  • CONST_DMUS_SEGF_FLAGS


DirectMusicPerformance8.GetLatencyTime

The GetLatencyTime method retrieves the current latency time. Latency time is the time at which messages are sent to the port to be rendered.

object.GetLatencyTime() As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns the latency time, in clock time units.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK


DirectMusicPerformance8.GetMasterAutoDownload

The GetMasterAutoDownload method retrieves the current setting for automatic downloading of instruments.

object.GetMasterAutoDownload() As Boolean

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns True if autodownloading is on, and False otherwise. The default value is False.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicPerformance8.SetMasterAutoDownload
  • DirectMusicSegment8.SetAutoDownloadEnable


DirectMusicPerformance8.GetMasterGrooveLevel

The GetMasterGrooveLevel method retrieves the current master groove level, which is a value added to all groove levels in the performance. The resulting value is adjusted, if necessary, to fall within the range from 1 through 100.

object.GetMasterGrooveLevel() As Integer

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns the master groove level.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicPerformance8.GetGrooveLevel
  • DirectMusicPerformance8.SetMasterGrooveLevel


DirectMusicPerformance8.GetMasterTempo

The GetMasterTempo method retrieves the master tempo.

object.GetMasterTempo() As Single

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns a value in the range from 0.01 through 100.0.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The master tempo is a scaling factor that is applied to the tempo by the final output tool. By default it is 1. A value of 0.5 would halve the tempo, and a value of 2.0 would double it.

See Also

  • DirectMusicPerformance8.SetMasterTempo


DirectMusicPerformance8.GetMasterVolume

The GetMasterVolume method retrieves the master volume.

object.GetMasterVolume() As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns the current master volume, in hundredths of a decibel.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The master volume is an amplification or attenuation factor applied to the default volume of the entire performance. The range of permitted values is determined by the port.

See Also

  • DirectMusicPerformance8.SetMasterVolume


DirectMusicPerformance8.GetMusicTime

The GetMusicTime method retrieves the current time of the performance, in music time.

object.GetMusicTime() As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns the current time, in music time units.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

See Also

  • DirectMusicPerformance8.GetClockTime
  • Clock Time vs. Music Time


DirectMusicPerformance8.GetNotificationPMSG

The GetNotificationPMsg method retrieves a pending notification message.

object.GetNotificationPMSG( _
  message As DMUS_NOTIFICATION_PMSG _
) As Boolean

Parts

object

Resolves to a DirectMusicPerformance8 object.

message

DMUS_NOTIFICATION_PMSG type that receives the message.

Return Values

Returns True if a message was received, and False if no message was pending.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicPerformance8.GetPrepareTime

The GetPrepareTime method retrieves the approximate interval between the time at which messages are prepared and the time at which they are processed and heard.

object.GetPrepareTime() As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns the prepare time, in milliseconds.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default value is 1000 milliseconds.

See Also

  • DirectMusicPerformance8.SetPrepareTime
  • Prepare Time


DirectMusicPerformance8.GetQueueTime

The GetQueueTime method retrieves the queue (or flush) time. Messages that have time stamps earlier than this time have already been queued to the port and cannot be invalidated.

object.GetQueueTime() As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

Return Values

Returns the queue time, in clock time units.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

Remarks

Queue time is equal to the value returned by DirectMusicPerformance8.GetLatencyTime plus the value returned by DirectMusicPerformance8.GetBumperLength.

When a segment is stopped immediately, all messages that have been sent but not queued to the port buffer are flushed. If you want to resume playing the segment again at the last point heard, set the new start point to the offset of queue time within the segment when the segment was stopped.

See Also

  • DirectMusicPerformance8.Invalidate


DirectMusicPerformance8.GetResolvedTime

The GetResolvedTime method adjusts a given time to a given boundary.

object.GetResolvedTime( _
  ctTime As Long, _
  flags As Long _
) As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

ctTime

Time to resolve, in clock time units. If this is less than the current time, the current time is used.

flags

One or more of the following CONST_DMUS_SEGF_FLAGS describing the resolution desired:

Value | Description
DMUS_SEGF_AFTERLATENCYTIME | Resolve to a time after the latency time.
DMUS_SEGF_AFTERPREPARETIME | Resolve to a time after the Prepare Time.
DMUS_SEGF_AFTERQUEUETIME | Resolve to a time after the queue time.
DMUS_SEGF_BEAT | Resolve to a time on a beat boundary.
DMUS_SEGF_GRID | Resolve to a time on a grid boundary.
DMUS_SEGF_MARKER | Resolve to a marker.
DMUS_SEGF_MEASURE | Resolve to a time on a measure boundary.
DMUS_SEGF_SEGMENTEND | Resolve to the end of the segment.

Return Values

Returns the resolved time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The time returned is the soonest time after the supplied time that falls on the specified boundary.


DirectMusicPerformance8.GetSegmentState

The GetSegmentState method retrieves an object representing the play state of the primary segment.

object.GetSegmentState( _
  mtTime As Long _
) As DirectMusicSegmentState8

Parts

object

Resolves to a DirectMusicPerformance8 object.

mtTime

Time for which the segment state is to be retrieved, in music time.

Return Values

Returns a DirectMusicSegmentState8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NOT_FOUND.

Remarks

To get the currently playing segment state, pass the time retrieved by the DirectMusicPerformance8.GetMusicTime method. Currently playing in this context means that it is being called into to perform messages. Because of latency, the currently playing segment state is not necessarily the one actually being heard.

Also because of latency, it is a good idea to add 150 to mtTime if retrieving a segment state immediately after calling DirectMusicPerformance8.PlaySegmentEx.


DirectMusicPerformance8.GetStyle

The GetStyle method retrieves the style underlying the control segment at a given time.

object.GetStyle( _
  mtTime As Long, _
  mtUntil As Long _
) As DirectMusicStyle8

Parts

object

Resolves to a DirectMusicPerformance8 object.

mtTime

Time for which the style is to be retrieved, in music time.

mtUntil

Variable of type Long that receives the music time (relative to mtTime) until which the style is valid. If this returns a value of 0, either the style is always valid, or it is unknown when it might become invalid. See Remarks.

Return Values

Returns a DirectMusicStyle8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND

Remarks

Normally the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. The object returned by the method can become invalid before the time returned in mtUntil if another control segment is cued.


DirectMusicPerformance8.GetTempo

The GetTempo method retrieves the tempo at a given time.

object.GetTempo( _
  mtTime As Long, _
  mtUntil As Long _
) As Double

Parts

object

Resolves to a DirectMusicPerformance8 object.

mtTime

Time for which to retrieve the tempo, in music time. The last tempo change before or at this time is used to determine the tempo.

mtUntil

Variable of type Long that receives the music time (relative to mtTime) until which the tempo is valid. If this returns a value of 0, either the tempo is always valid, or it is unknown when it might become invalid.

Return Values

Returns the tempo, in beats per minute. This value is in the range from DMUS_TEMPO_MIN through DMUS_TEMPO_MAX (see CONST_DMUS).

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND


DirectMusicPerformance8.GetTimeSig

The GetTimeSig method retrieves the time signature at a given time.

object.GetTimeSig( _
  mtTime As Long, _
  mtUntil As Long, _
  timeSig As DMUS_TIMESIGNATURE)

Parts

object

Resolves to a DirectMusicPerformance8 object.

mtTime

Value that specifies the time for which to retrieve the time signature, in music time. The last time signature change before or at this time is used to determine the time signature.

mtUntil

Variable of type Long that receives the music time (relative to mtTime) until which the time signature is valid. If this returns a value of 0, either the time signature is always valid, or it is unknown when it might become invalid. See Remarks.

timeSig

DMUS_TIMESIGNATURE type that receives information about the time signature. The mtTime member receives the offset of the last time signature change from the requested time, and is always 0 or less.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND


DirectMusicPerformance8.InitAudio

The InitAudio method initializes the performance and optionally sets up a default audiopath. This method must be called before the performance can play using audiopaths.

object.InitAudio( _
  hwnd As Long, _
  lFlags As CONST_DMUS_AUDIO, _
  AudioParams As DMUS_AUDIOPARAMS, _
  [DirectSound As DirectSound8], _
  [lDefaultPathType As CONST_DMUSIC_STANDARD_AUDIO_PATH], _
  [lPChannelCount As Long] )

Parts

object

Resolves to a DirectMusicPerformance8 object.

hwnd

Window handle to use for the creation of DirectSound. If 0, the foreground window is used. See Remarks.

This parameter is ignored if a DirectSound8 object is passed to the method in DirectSound. In that case the application is responsible for setting the window handle by using DirectSound8.SetCooperativeLevel.

lFlags

Flags from the CONST_DMUS_AUDIO enumeration that specify requested features. If the lValidData member of the AudioParams type is not zero, this value is ignored and the requested features are specified in the lFeatures member of AudioParams.

AudioParams

DMUS_AUDIOPARAMS type that specifies parameters for the synthesizer and receives information about what parameters were set. If the lValidData member is zero, default parameters are set.

DirectSound

Optional DirectSound8 object to use by default for wave output.

If this parameter is a DirectSound8 variable set to Nothing, a DirectSound object is created and the variable is set to that object.

If this parameter is omitted, a private DirectSound8 object is created.

See Remarks.

lDefaultPathType

Value that specifies the default audiopath type. Can be zero or omitted if no default path type is wanted, or one of the constants of the CONST_DMUSIC_STANDARD_AUDIO_PATH enumeration.

lPChannelCount

Value that specifies the number of performance channels to allocate to the path, if lDefaultPathType is not zero or omitted.

Return Values

If the method fails, an error is raised. Possible values for Err.Number include the following:

DMUS_E_ALREADY_INITED
DMUS_E_OUTOFMEMORY

Remarks

This method can be called only once.

The performance must be terminated by using the DirectMusicPerformance8.CloseDown method before being released.

There should be only one DirectSound8 object per process. If your application uses DirectSound8 separately, it should pass that object in DirectSound. It must first set the cooperative level by passing DSSCL_PRIORITY to DirectSound8.SetCooperativeLevel.

You can pass 0 in the hwnd parameter to give the current foreground window handle to DirectSound. However, do not assume that the application window will be in the foreground during initialization. It is best to pass the top-level application window handle.

Parameters set in the lFlags and AudioParams parameters apply to the default audiopath and any audiopaths created subsequently.


DirectMusicPerformance8.Invalidate

The Invalidate method flushes all queued messages whose time stamps are later than the supplied time and causes all tracks of all segments to resend their data from the given time forward.

object.Invalidate( _
  mtTime As Long, _
  flags As Long)

Parts

object

Resolves to a DirectMusicPerformance8 object.

mtTime

Time from which to invalidate, adjusted by flags. Setting this value to 0 causes immediate invalidation.

flags

Value that causes mtTime to align to measures, beats, or grids. This value can be 0 or one of the following members of CONST_DMUS_SEGF_FLAGS:

DMUS_SEGF_MEASURE
DMUS_SEGF_BEAT
DMUS_SEGF_GRID

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

Remarks

If mtTime is so long ago that it is impossible to invalidate that time, the earliest possible time is used.

See Also

  • DirectMusicPerformance8.GetQueueTime


DirectMusicPerformance8.IsPlaying

The IsPlaying method ascertains whether a particular segment or segment state is currently playing at the speakers.

object.IsPlaying( _
  segment As DirectMusicSegment8, _
  SegmentState8 As DirectMusicSegmentState8 _
) As Boolean

Parts

object

Resolves to a DirectMusicPerformance8 object.

segment

DirectMusicSegment8 to check. If Nothing, check only SegmentState8.

SegmentState8

DirectMusicSegmentState8 to check. If Nothing, check only segment.

Return Values

If the method succeeds and the requested segment or segment state is playing, the return value is True. If neither is playing, or only one was requested and it is not playing, the return value is False.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK

Remarks

The method returns True only if the segment or segment state is actually playing at the speakers. Because of latency, this method might return False even though DirectMusicPerformance8.PlaySegmentEx has just been called on the segment. Similarly, the method returns True as long as the segment is being heard, even though all messages might already have been dispatched.


DirectMusicPerformance8.MusicToClockTime

The MusicToClockTime method converts time in music time format to time in clock time format.

object.MusicToClockTime(mtTime As Long) As Long

Parts

object

Resolves to a DirectMusicPerformance8 object.

mtTime

Time in music time format to convert.

Return Values

Returns the time in clock time units.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

Remarks

This method converts a time offset from the start of the performance, not a duration. The ratio between music time and clock time units depends on the tempo, so in making the conversion, DirectMusic takes into account all tempo changes since the start of the performance. If a master tempo has been set for the performance, it is taken into account as well.

Because clock time has a greater precision than music time, a time that has been converted from clock time to music time, and then back again, will probably not have its original value.

See Also

  • DirectMusicPerformance8.ClockToMusicTime
  • Clock Time vs. Music Time


DirectMusicPerformance8.PlaySegmentEx

The PlaySegmentEx method begins playback of a segment.

object.PlaySegmentEx( _
  Source As Unknown, _
  lFlags As CONST_DMUS_SEGF_FLAGS, _
  StartTime As Long, _
  [From As Unknown], _
  [AudioPath As Unknown], _
) As DirectMusicSegmentState8

Parts

object

Resolves to a DirectMusicPerformance8 object.

Source

DirectMusicSegment8 object to play.

lFlags

Flags that modify the method's behavior. Can be 0 or one or more constants from the CONST_DMUS_SEGF_FLAGS enumeration.

StartTime

Performance time at which to begin playing the segment, adjusted to any resolution boundary specified in lFlags. The time is in music time unless the DMUS_SEGF_REFTIME flag is set. A value of 0 causes the segment to start playing as soon as possible.

From

Optional DirectMusicSegmentState8 or DirectMusicAudioPath8 object to stop playing when the new segment begins. If it is an audiopath, all segment states playing on that audiopath are stopped. See also Remarks.

AudioPath

Optional DirectMusicAudioPath8 object that represents the audiopath on which to play the segment. If Nothing or omitted, the segment plays on the default path.

Return Values

Returns a DirectMusicSegmentState8 object that represents the playing instance of the segment.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include the following:

DMUS_E_AUDIOPATH_INACTIVE
DMUS_E_AUDIOPATH_NOPORT
DMUS_E_NO_MASTER_CLOCK
DMUS_E_SEGMENT_INIT_FAILED
DMUS_E_TIME_PAST
DMUS_E_OUTOFMEMORY

Remarks

Segments should be greater than 250 milliseconds in length.

The boundary resolutions in lFlags are relative to the primary segment.

If a primary segment is scheduled to play while another primary segment is playing, the first one stops unless you set the DMUS_SEGF_QUEUE flag for the second segment, in which case it plays as soon as the first one finishes.

For more information on the exact start time of segments, see Segment Timing. For information on how the start time of segments can be affected by tempo changes, see Clock Time vs. Music Time.

If DMUS_SEGF_AUTOTRANSITION is specified in lFlags and a segment is playing at StartTime and is being interrupted, the method composes a transition between the two segments and plays it before playing Source.

If Source is a segment, a transitional segment based on a template provided at Transition is composed and played.

When the segment is being cued as a secondary segment, the pFrom parameter can be used to specify another secondary segment against which to cue the new segment. For example, the following code cues SegmentA to play as soon as SegmentB finishes playing:

dmPerformance.PlaySegmentEx SegmentA, DMUS_SEGF_QUEUE Or DMUS_SEGF_SECONDARY, _
    0, SegmentB, Nothing

In the example, SegmentB plays to the end before stopping because the DMUS_SEGF_QUEUE flag has been set. If you set a different flag such as DMUS_SEGF_MEASURE, SegmentB stops as soon as the boundary is reached and the new secondary segment begins playing.

See Also

  • Using Segments
  • Using Transitions


DirectMusicPerformance8.RemoveNotificationType

The RemoveNotificationType method removes a previously added notification type from the performance so that notification messages of that type are no longer sent.

object.RemoveNotificationType( _
  type As CONST_DMUS_NOTIFICATION_TYPE)

Parts

object

Resolves to a DirectMusicPerformance8 object.

type

Type of event for which notification messages are no longer to be sent. For possible values, see CONST_DMUS_NOTIFICATION_TYPE.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_INVALIDARG.

See Also

  • DirectMusicPerformance8.AddNotificationType


DirectMusicPerformance8.Reset

The Reset method resets the port.

object.Reset(resetflags As Long)

Parts

object

Resolves to a DirectMusicPerformance8 object.

resetflags

Flags. If this value is 0, the method performs a GMReset. If this value is 1, the port is reset by being closed and reopened.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicPerformance8.SendCurvePMSG

The SendCurvePMSG method sends a performance message containing information about a curve.

object.SendCurvePMSG( _
  lTime As Long, _
  flags As Long, _
  channel As Long, _
  msg As DMUS_CURVE_PMSG)

Parts

object

Resolves to a DirectMusicPerformance8 object.

lTime

Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.

flags

Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.

channel

Performance channel that is the destination for the message. To send the message to more than one channel, use one of the members of the CONST_DMUS_PCHANNEL enumeration.

msg

DMUS_CURVE_PMSG type containing information about the curve.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, the message is cued to go out immediately.

See Also

  • Curves


DirectMusicPerformance8.SendMIDIPMSG

The SendMIDIPMSG method sends a performance message containing information about a MIDI channel message not covered by other methods.

object.SendMIDIPMSG( _
  lTime As Long, _
  flags As Long, _
  channel As Long, _
  status As Byte, _
  byte1 As Byte, _
  byte2 As Byte)

Parts

object

Resolves to a DirectMusicPerformance8 object.

lTime

Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.

flags

Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.

channel

Performance channel that is the destination for the message. To send the message to more than one channel, use one of the members of the CONST_DMUS_PCHANNEL enumeration.

status

Standard MIDI status byte. See Remarks.

byte1

First data byte. Ignored for MIDI messages that do not require it.

byte2

Second data byte. Ignored for MIDI messages that do not require it.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, the message is cued to go out immediately.

Because the channel is specified in another parameter, status does not contain the channel number in the 4 lower bits, as it would in a standard MIDI message. Thus status is &H80 for a note-off, &H90 for a note-on, and so on. See the MIDI specification for other status bytes.


DirectMusicPerformance8.SendNotePMSG

The SendNotePMSG method sends a performance message containing information about a note.

object.SendNotePMSG( _
  lTime As Long, _
  flags As Long, _
  channel As Long, _
  msg As DMUS_NOTE_PMSG)

Parts

object

Resolves to a DirectMusicPerformance8 object.

lTime

Time at which the message is to play. This value is in music time unless DMUS_PMSGF_REFTIME is in flags. If the value of lTime is 0 and flags contains DMUS_PMSGF_REFTIME, the message plays immediately.

flags

Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.

channel

Performance channel that is the destination for the message. To send the message to more than one channel, use one of the members of the CONST_DMUS_PCHANNEL enumeration.

msg

DMUS_NOTE_PMSG type containing information about the note.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

The following code example, where perf is a DirectMusicPerformance8 object, sends a message to play middle C immediately.

Dim note As DMUS_NOTE_PMSG

note.midiValue = 60
note.mtDuration = 500
note.flags = DMUS_NOTEF_NOTEON
note.velocity = 127
Call perf.SendNotePMSG(0, DMUS_PMSGF_REFTIME, 1, note)


DirectMusicPerformance8.SendPatchPMSG

The SendPatchPMSG method sends a performance message containing information about a MIDI patch change.

object.SendPatchPMSG( _
  lTime As Long, _
  flags As Long, _
  channel As Long, _
  instrument As Byte, _
  byte1 As Byte, _
  byte2 As Byte)

Parts

object

Resolves to a DirectMusicPerformance8 object.

lTime

Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.

flags

Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.

channel

Performance channel that is the destination for the message. To send the message to more than one channel, use one of the members of the CONST_DMUS_PCHANNEL enumeration.

instrument

Patch number to assign to the channel.

byte1

Most significant byte of the bank select.

byte2

Least significant byte of the bank select.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, the message is cued to go out immediately.


DirectMusicPerformance8.SendTempoPMSG

The SendTempoPMSG method sends a performance message containing information about a tempo change.

object.SendTempoPMSG( _
  lTime As Long, _
  flags As Long, _
  tempo As Double)

Parts

object

Resolves to a DirectMusicPerformance8 object.

lTime

Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.

flags

Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.

tempo

New tempo, in beats per minute.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, the message is cued to go out immediately.


DirectMusicPerformance8.SendTimeSigPMSG

The SendTimeSigPMSG method sends a performance message containing information about a time signature.

object.SendTimeSigPMSG( _
  lTime As Long, _
  flags As Long, _
  timeSig As DMUS_TIMESIGNATURE)

Parts

object

Resolves to a DirectMusicPerformance8 object.

lTime

Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.

flags

Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.

timeSig

DMUS_TIMESIGNATURE type containing information about the time signature.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, the message is cued to go out immediately.


DirectMusicPerformance8.SendTransposePMSG

The SendTransposePMSG method sends a performance message causing a transposition to begin.

object.SendTransposePMSG( _
  lTime As Long, _
  flags As Long, _
  channel As Long, _
  transpose As Integer)

Parts

object

Resolves to a DirectMusicPerformance8 object.

lTime

Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.

flags

Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.

channel

Performance channel on which the transposition is to take place. To send the message to more than one channel, use one of the members of the CONST_DMUS_PCHANNEL enumeration.

transpose

Number of semitones by which to transpose notes. This can be a negative value. If the transposition of a note puts it outside the standard MIDI range from 0 through 127, it does not play.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, the message is cued to go out immediately.


DirectMusicPerformance8.SetBumperLength

The SetBumperLength method sets the amount of time between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port.

object.SetBumperLength(lMilliSeconds As Long)

Parts

object

Resolves to a DirectMusicPerformance8 object.

lMilliSeconds

Desired bumper length, in milliseconds. The default value is 50.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicPerformance8.GetBumperLength
  • DirectMusicPerformance8.SetPrepareTime


DirectMusicPerformance8.SetDefaultAudioPath

The SetDefaultAudioPath method sets and activates the default audiopath for the performance.

object.SetDefaultAudioPath( _
  AudioPath As DirectMusicAudioPath8)

Parts

object

Resolves to a DirectMusicPerformance8 object.

AudioPath

DirectMusicAudioPath8 object that specifies the default audiopath.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include the following:

DMUS_E_INVALIDARG
DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_NOT_INIT


DirectMusicPerformance8.SetMasterAutoDownload

The SetMasterAutoDownload method turns automatic downloading of instruments on or off.

object.SetMasterAutoDownload(b As Boolean)

Parts

object

Resolves to a DirectMusicPerformance8 object.

b

True to turn autodownloading on, False to turn it off. The default value is False.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicPerformance8.GetMasterAutoDownload, DirectMusicSegment8.SetAutoDownloadEnable


DirectMusicPerformance8.SetMasterGrooveLevel

The SetMasterGrooveLevel method sets a value to be added to all groove levels in the performance.

object.SetMasterGrooveLevel(level As Integer)

Parts

object

Resolves to a DirectMusicPerformance8 object.

level

Value to add to the groove level, in the range from –99 through 99.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_OUTOFMEMORY

Remarks

The adjusted groove level is always in the range from 1 through 100.

See Also

  • DirectMusicPerformance8.GetMasterGrooveLevel


DirectMusicPerformance8.SetMasterTempo

The SetMasterTempo method sets a scaling factor that is applied to the tempo.

object.SetMasterTempo(tempo As Single)

Parts

object

Resolves to a DirectMusicPerformance8 object.

tempo

Desired master tempo, in the range from 0.01 through 100.0.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

By default, the master tempo is 1. A value of 0.5 would halve the tempo, and a value of 2.0 would double it.

See Also

  • DirectMusicPerformance8.GetMasterTempo


DirectMusicPerformance8.SetMasterVolume

The SetMasterVolume method adjusts the master volume of the performance.

object.SetMasterVolume(vol As Long)

Parts

object

Resolves to a DirectMusicPerformance8 object.

vol

Master volume adjustment, in hundredths of a decibel.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The master volume is an amplification or attenuation factor applied to the default volume of the entire performance. The range of permitted values is determined by the port. For the default software synthesizer, the allowed range is +20dB to –200dB, but the useful range is +10dB to –100dB.

See Also

  • DirectMusicPerformance8.GetMasterVolume


DirectMusicPerformance8.SetNotificationHandle

The SetNotificationHandle method sets the event handle for notifications. When signaled, the application should call the DirectMusicPerformance8.GetNotificationPMSG method to retrieve the notification event.

object.SetNotificationHandle(hnd As Long)

Parts

object

Resolves to a DirectMusicPerformance8 object.

hnd

Event handle, or 0 to clear an existing handle.


DirectMusicPerformance8.SetPrepareTime

The SetPrepareTime method sets the approximate interval between the time at which messages are prepared and the time at which they are processed and heard.

object.SetPrepareTime(lMilliSeconds As Long)

Parts

object

Resolves to a DirectMusicPerformance8 object.

lMilliSeconds

Prepare time, in milliseconds. The default value is 1000.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicPerformance8.GetPrepareTime
  • DirectMusicPerformance8.SetBumperLength
  • Prepare Time


DirectMusicPerformance8.StopEx

The StopEx method stops playback of an object.

object.StopEx( _
  ObjectToStop As Unknown, _
  lStopTime As Long, _
  lFlags As Long)

Parts

object

Resolves to a DirectMusicPerformance8 object.

ObjectToStop

DirectMusicSegment8, DirectMusicSegmentState8, or DirectMusicAudioPath8 object to stop.

lStopTime

Time at which to stop. If the time is in the past or 0 is passed in this parameter, the object stops playing immediately.

lFlags

Flags that indicate when the stop should occur. Boundaries are in relation to the current primary segment. If this parameter is 0, the stop occurs immediately. Can contain one of the following constants from the CONST_DMUS_SEGF_FLAGS enumeration, or DMUS_SEGF_REFTIME combined with one other flag.

Value | Description
DMUS_SEGF_BEAT | Stop on the next beat boundary at or after lStopTime.
DMUS_SEGF_DEFAULT | Stop on the default boundary.
DMUS_SEGF_GRID | Stop on the next grid boundary at or after lStopTime.
DMUS_SEGF_MEASURE | Stop on the next measure boundary at or after lStopTime.
DMUS_SEGF_REFTIME | The value in i64StopTime is in reference time.
DMUS_SEGF_SEGMENTEND | Stop at the end of the segment.
DMUS_SEGF_MARKER | Stop at the next marker.

Error Codes

If the method fails, an error is raised.

Remarks

Stopping a segment stops all instances that are playing.

See Also

  • DirectMusicPerformance8.PlaySegmentEx


DirectMusicSegment8

An object of the DirectMusicSegment8 class represents a single piece of music or a template.

Segments are usually loaded by calling DirectMusicLoader8.LoadSegment and DirectMusicLoader8.LoadSegmentFromResource. They can also be composed from musical elements by using methods of the DirectMusicComposer8 object, or created from existing segments by using the DirectMusicSegment8.Clone method.

The DirectMusicSegment8 class has the following methods.

Timing and looping

Method | Description
GetLength | Retrieves the length of the segment.
GetLoopPointStart | Retrieves the point in the segment at which a repeating section ends.
GetLoopPointEnd | Retrieves the point in the segment at which a repeating section starts.
GetRepeats | Retrieves the number of times that the looping portion of a segment is set to repeat.
GetStartPoint | Retrieves the point within the segment at which it starts playing.
SetLength | Sets the length of the segment.
SetLoopPoints | Sets the start and end points of a repeating section in the segment.
SetRepeats | Sets the number of times that the looping portion of the segment is to repeat.
SetStartPoint | Sets the point within the segment at which it starts playing.

Instruments

Method | Description
ConnectToCollection | Associates a segment with a DLS instrument collection.
Download | Downloads band and wave data to a performance or audiopath.
Unload | Unloads instruments that were downloaded to the port.

Parameters

Method | Description
SetAutoDownloadEnable | Enables or disables automatic downloading and unloading of instruments in the collection associated with the segment.
SetStandardMidiFile | Advises DirectMusic that the segment is based on a standard MIDI file, to ensure correct playback.
SetTempoEnable | Enables or disables tempo messages for the segment.
SetTimeSigEnable | Enables or disables time signature messages for the segment.

Miscellaneous

Method | Description
Clone | Ceates a copy of all or part of the segment.
GetAudioPathConfig | Retrieves an object that represents the audiopath configuration for the segment.
GetChordMap | Retrieves a chordmap.
GetName | Retrieves the internal name of the segment.
GetStyle | Retrieves a style.


DirectMusicSegment8.Clone

The Clone method creates a copy of all or part of the segment.

object.Clone( _
  mtStart As Long, _
  mtEnd As Long _
) As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicSegment8 object.

mtStart

Start of the part to clone, in music time. If less than 0 or greater than the length of the segment, 0 is used.

mtEnd

End of the part to clone, in music time. If this value is past the end of the segment, the segment is cloned to the end. A value of 0 or anything less than mtStart also clones to the end.

Return Values

Returns a DirectMusicSegment8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_OUTOFMEMORY.

Remarks

Properties of the original segment, including start and loop points, number of repeats, and any default audiopath, are copied to the clone.

For style-based segments, if mtStart is greater than 0, it should be on a measure boundary.


DirectMusicSegment8.ConnectToCollection

The ConnectToCollection method associates a segment with a DLS instrument collection. The collection will be downloaded when the DirectMusicSegment8.Download method is called.

object.ConnectToCollection(c As DirectMusicCollection8)

Parts

object

Resolves to a DirectMusicSegment8 object.

c

DirectMusicCollection8 object that represents instruments to be used by the segment.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND

Remarks

By default, the General MIDI collection in the Gm.dls file is connected to the segment. This method needs to be called only if the segment is to be played with custom instruments.


DirectMusicSegment8.Download

The Download method downloads band and wave data to a performance or audiopath.

object.Download(downloadpath As Unknown)

Parts

object

Resolves to a DirectMusicSegment8 object.

downloadpath

DirectMusicAudioPath8 or DirectMusicPerformance8 object to which the instruments are being downloaded.

Error Codes

If the method fails, it raises an error. Possible values for Err.Number include the following:

DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND

Remarks

All bands and wave data in the segment are downloaded.

Always call DirectMusicSegment8.Unload before the segment object goes out of scope or is otherwise destroyed.

See Also

  • DirectMusicSegment8.ConnectToCollection
  • DirectMusicSegment8.Unload
  • DirectMusicSegment8.SetAutoDownloadEnable


DirectMusicSegment8.GetAudioPathConfig

The GetAudioPathConfig method retrieves an object that represents the audiopath configuration for the segment.

object.GetAudioPathConfig() As Unknown

Parts

object

Resolves to a DirectMusicSegment8 object.

Return Values

Returns an object representing the audiopath configuration. This object can be retrieved in a variable of type IUnknown and passed to DirectMusicPerformance8.CreateAudioPath.

Error Codes

If the method fails, an error is raised.


DirectMusicSegment8.GetChordMap

The GetChordMap method retrieves a chordmap.

object.GetChordMap( _
  lTrack As Long, _
  mtTime As Long, _
  mtUntil As Long _
) As DirectMusicChordMap8

Parts

object

Resolves to a DirectMusicSegment8 object.

lTrack

Index of the chordmap track, or &H80000000 to find the track.

mtTime

Time at which to retrieve the chordmap.

mtUntil

Variable that receives the time, relative to mtTime, until which the chordmap is valid.

Return Values

Returns a DirectMusicChordMap8 object.

Error Codes

If the method fails, an error is raised.


DirectMusicSegment8.GetLength

The GetLength method retrieves the length of the segment.

object.GetLength() As Long

Parts

object

Resolves to a DirectMusicSegment8 object.

Return Values

Returns the length of the segment, in music time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The method always returns 1 for segments created from wave files.

See Also

  • DirectMusicSegment8.SetLength


DirectMusicSegment8.GetLoopPointEnd

The GetLoopPointEnd method retrieves the point in the segment at which a repeating section ends.

object.GetLoopPointEnd() As Long

Parts

object

Resolves to a DirectMusicSegment8 object.

Return Values

Returns the end point of the loop, in music time. If this value is 0, the entire segment loops.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The section does not repeat unless the number of repetitions has been set to 1 or more by using the DirectMusicSegment8.SetRepeats method. By default, the entire segment repeats.

See Also

  • DirectMusicSegment8.GetLoopPointStart
  • DirectMusicSegment8.SetLoopPoints
  • DirectMusicSegment8.GetRepeats


DirectMusicSegment8.GetLoopPointStart

The GetLoopPointStart method retrieves the point in the segment at which a repeating section starts.

object.GetLoopPointStart() As Long

Parts

object

Resolves to a DirectMusicSegment8 object.

Return Values

Returns the start point of the loop, in music time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The section does not repeat unless the number of repetitions has been set to 1 or more by using the DirectMusicSegment8.SetRepeats method. By default, the entire segment repeats.

See Also

  • DirectMusicSegment8.GetLoopPointEnd
  • DirectMusicSegment8.SetLoopPoints
  • DirectMusicSegment8.GetRepeats


DirectMusicSegment8.GetName

The GetName method retrieves the internal name of the segment.

object.GetName() As String

Parts

object

Resolves to a DirectMusicSegment8 object.

Return Values

Returns the internal name of the segment or, if it has no internal name, the filename.

Error Codes

If the method fails, an error is raised.


DirectMusicSegment8.GetRepeats

The GetRepeats method retrieves the number of times that the looping portion of a segment is set to repeat.

object.GetRepeats() As Long

Parts

object

Resolves to a DirectMusicSegment8 object.

Return Values

Returns the number of times that the looping portion repeats.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicSegment8.SetRepeats
  • DirectMusicSegment8.SetLoopPoints
  • DirectMusicSegment8.GetLoopPointStart
  • DirectMusicSegment8.GetLoopPointEnd
  • DirectMusicSegmentState8.GetRepeats


DirectMusicSegment8.GetStartPoint

The GetStartPoint method retrieves the point within the segment at which it starts playing in response to the DirectMusicPerformance8.PlaySegmentEx method.

object.GetStartPoint() As Long

Parts

object

Resolves to a DirectMusicSegment8 object.

Return Values

Returns the start point of the segment, in music time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicSegment8.SetStartPoint


DirectMusicSegment8.GetStyle

The GetStyle method retrieves a style.

object.GetStyle( _
  lTrack As Long, _
  mtTime As Long, _
  mtUntil As Long _
) As DirectMusicStyle8

Parts

object

Resolves to a DirectMusicSegment8 object.

lTrack

Index of the style track, or &H80000000 to find the track.

mtTime

Time at which to retrieve the style.

mtUntil

Variable that receives the time, relative to mtTime, until which the style is valid.

Return Values

Returns a DirectMusicStyle8 object.

Error Codes

If the method fails, an error is raised.


DirectMusicSegment8.SetAutoDownloadEnable

The SetAutoDownloadEnable method enables or disables automatic downloading and unloading of instruments in the collection associated with the segment.

object.SetAutoDownloadEnable(b As Boolean)

Parts

object

Resolves to a DirectMusicSegment8 object.

b

True to enable autodownloading, or False to disable it.

Remarks

Automatic downloading is disabled by default. When it is enabled, instruments are automatically downloaded when the segment is played, and unloaded when it is stopped.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND

See Also

  • DirectMusicSegment8.Download


DirectMusicSegment8.SetLength

The SetLength method sets the length of the segment.

object.SetLength(mtLength As Long)

Parts

object

Resolves to a DirectMusicSegment8 object.

mtLength

Desired length, in music time. Must be greater than 0.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_OUT_OF_RANGE.

Remarks

In most cases, applications do not need to set the length, which is automatically set when the segment is loaded. However, this method can be used to shorten a segment.

See Also

  • DirectMusicSegment8.GetLength


DirectMusicSegment8.SetLoopPoints

The SetLoopPoints method sets the start and end points inside the segment to repeat the number of times set by the DirectMusicSegment8.SetRepeats method.

object.SetLoopPoints(mtStart As Long, mtEnd As Long)

Parts

object

Resolves to a DirectMusicSegment8 object.

mtStart

Point at which to begin the loop, in music time.

mtEnd

Point at which to end the loop, in music time. A value of 0 loops the entire segment.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_OUT_OF_RANGE.

Remarks

When the segment is played, it plays from the segment start time until mtEnd, then loops to mtStart, plays the looped portion the number of times set by DirectMusicSegment8.SetRepeats, and then plays to the end.

The default values are set to loop the entire segment from beginning to end.

The method fails if mtStart is greater than or equal to the length of the segment, or if mtEnd is greater than the length of the segment. If mtEnd is 0, mtStart must be 0 as well.

This method does not affect any currently playing segment states created from this segment.

A segment that is reused might be loaded from an internal cache, in which case it will have the same loop points it had the last time this value was set. It is a good idea to reset the loop points to 0 before releasing a segment that might be played again.

See Also

  • DirectMusicSegment8.GetLoopPointStart
  • DirectMusicSegment8.GetLoopPointEnd
  • DirectMusicSegment8.SetRepeats


DirectMusicSegment8.SetRepeats

The SetRepeats method sets the number of times that the looping portion of the segment is to repeat.

object.SetRepeats(lRepeats As Long)

Parts

object

Resolves to a DirectMusicSegment8 object.

lRepeats

Number of repetitions.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicSegment8.GetRepeats
  • DirectMusicSegment8.SetLoopPoints


DirectMusicSegment8.SetStandardMidiFile

The SetStandardMidiFile method advises DirectMusic that the segment is based on a standard MIDI file, not one authored specifically for DirectMusic. Calling this method ensures that channels do not play silently if the file contains no patch changes, and that bank selects are ignored.

object.SetStandardMidiFile()

Parts

object

Resolves to a DirectMusicSegment8 object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The method should be called before instruments are downloaded.


DirectMusicSegment8.SetStartPoint

The SetStartPoint method sets the point within the segment at which it starts playing in response to a call to the DirectMusicPerformance8.PlaySegmentEx method.

object.SetStartPoint(mtStart As Long)

Parts

object

Resolves to a DirectMusicSegment8 object.

mtStart

Point within the segment at which it is to start playing, in music time. Must be greater than or equal to zero and less than the length of the segment.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_OUT_OF_RANGE.

Remarks

By default, the start point is 0, meaning that the segment starts from the beginning.

The method does not affect any currently playing segment states created from this segment.

A segment that is reused might be loaded from an internal cache, in which case it will have the same start point it had the last time this value was set. It is a good idea to reset the start point to 0 before releasing a segment that might be played again.

See Also

  • DirectMusicSegment8.GetStartPoint
  • DirectMusicSegmentState8.GetStartPoint
  • DirectMusicSegment8.SetLoopPoints


DirectMusicSegment8.SetTempoEnable

The SetTempoEnable method enables or disables tempo messages for the segment.

object.SetTempoEnable(b As Boolean)

Parts

object

Resolves to a DirectMusicSegment8 object.

b

True to enable tempo messages, or False to disable them.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND


DirectMusicSegment8.SetTimeSigEnable

The SetTimeSigEnable method enables or disables time signature messages for the segment.

object.SetTempoEnable(b As Boolean)

Parts

object

Resolves to a DirectMusicSegment8 object.

b

True to enable time signature messages, or False to disable them.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND


DirectMusicSegment8.Unload

The Unload method unloads instruments that were downloaded to the port by the DirectMusicSegment8.Download method.

object.Unload(downloadpath As Unknown)

Parts

object

Resolves to a DirectMusicSegment8 object.

downloadpath

DirectMusicAudioPath8 or DirectMusicPerformance8 object from which to unload instruments.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicSegment8.SetAutoDownloadEnable


DirectMusicSegmentState8

The DirectMusicSegmentState8 class represents a playing instance of a segment. When the DirectMusicPerformance8.PlaySegmentEx method is called, it creates a DirectMusicSegmentState8 object that enables the application to retrieve information about that instance. The object can also be passed to methods of DirectMusicPerformance8 to determine whether a segment instance is still playing, or to stop it.

The DirectMusicSegmentState8 class has the following methods.

Method | Description
GetRepeats | Retrieves the number of times that the looping portion of the segment is set to repeat.
GetSeek | Retrieves the seek pointer in the segment state.
GetSegment | Retrieves an object representing the segment that owns this segment state.
GetStartPoint | Retrieves the offset into the segment at which play began or will begin.
GetStartTime | Retrieves the performance time at which the segment started or will start playing.

See Also

  • DirectMusicPerformance8.GetSegmentState


DirectMusicSegmentState8.GetRepeats

The GetRepeats method retrieves the number of times that the looping portion of the segment is set to repeat.

object.GetRepeats() As Long

Parts

object

Resolves to a DirectMusicSegmentState8 object.

Return Values

Returns the repeat count. A value of 0 indicates that the segment is to play through only once, with no portion repeated.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicSegment8.SetRepeats


DirectMusicSegmentState8.GetSeek

The GetSeek method retrieves the seek pointer in the segment state. This is immediately after the last point in the segment for which messages have been generated.

object.GetSeek() As Long

Parts

object

Resolves to a DirectMusicSegmentState8 object.

Return Values

Returns the seek pointer, in music time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

When a segment is stopped, messages that have been sent but not yet queued to the port buffer are flushed. Therefore, if you stop a segment and then restart it at the last seek pointer, some notes are lost.


DirectMusicSegmentState8.GetSegment

The GetSegment method retrieves an object representing the segment that owns this segment state.

object.GetSegment() As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicSegmentState8 object.

Return Values

Returns a DirectMusicSegment8 object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicSegmentState8.GetStartPoint

The GetStartPoint method retrieves the offset into the segment at which play began or will begin.

object.GetStartPoint() As Long

Parts

object

Resolves to a DirectMusicSegmentState8 object.

Return Values

Returns the start point for this segment state, in music time. This is not the value returned by DirectMusicSegment8.GetStartPoint if the start point of the segment has been changed since this segment state was created. Different instances of a playing segment can have different start points.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicSegment8.SetStartPoint
  • DirectMusicSegmentState8.GetStartTime


DirectMusicSegmentState8.GetStartTime

The GetStartTime method retrieves the performance time at which the segment started or will start playing.

object.GetStartTime() As Long

Parts

object

Resolves to a DirectMusicSegmentState8 object.

Return Values

Returns the start time, in music time, of this instance of the segment.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_BUFFER_EMPTY.

Remarks

If the segment was started from some point other than the beginning, you can retrieve the time at which the beginning of the segment would have fallen by subtracting the time returned by DirectMusicSegmentState8.GetStartPoint from the value returned by this method.

See Also

  • DirectMusicSegment8.SetStartPoint
  • DirectMusicSegment8.GetStartPoint
  • DirectMusicSegmentState8.GetStartPoint


DirectMusicStyle8

The DirectMusicStyle8 class represents a style, which is a collection of musical data including patterns and instruments.

The object is generally obtained by using the DirectMusicLoader8.LoadStyle or the DirectMusicLoader8.LoadStyleFromResource method. It can also be obtained from the performance by using the DirectMusicPerformance8.GetStyle method, provided the current control segment is based on a style.

The DirectMusicStyle8 class has the following methods.

Bands

Method | Description
GetBand | Retrieves a band object by name.
GetBandCount | Retrieves the number of bands available in the style.
GetBandName | Retrieves the name of a band in the style.
GetDefaultBand | Retrieves the default band for the style.

Motifs

Method | Description
GetMotif | Creates a segment containing the named motif.
GetMotifCount | Retrieves the number of motifs available in the style.
GetMotifName | retrieves the name of a motif in the style.

Time

Method | Description
GetTempo | Retrieves the recommended tempo of the style.
GetTimeSignature | Retrieves the style's time signature.


DirectMusicStyle8.GetBand

The GetBand method retrieves a band object by name.

object.GetBand(name As String) As DirectMusicBand8

Parts

object

Resolves to a DirectMusicStyle8 object.

name

Name assigned to the band by the author of the style.

Return Values

Returns a DirectMusicBand8 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_FAIL.

See Also

  • DirectMusicStyle8.GetBandName
  • DirectMusicStyle8.GetDefaultBand


DirectMusicStyle8.GetBandCount

The GetBandCount method retrieves the number of bands available in the style.

object.GetBandCount() As Long

Parts

object

Resolves to a DirectMusicStyle8 object.

Return Values

Returns the number of bands.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicStyle8.GetBand
  • DirectMusicStyle8.GetBandName


DirectMusicStyle8.GetBandName

The GetBandName method retrieves the name of a band in the style.

object.GetBandName(index As Long) As String

Parts

object

Resolves to a DirectMusicStyle8 object.

index

Index of the band in the style, in the range from 1 through DirectMusicStyle8.GetBandCount.

Return Values

Returns the name assigned to the band by the author of the style.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicStyle8.GetBand


DirectMusicStyle8.GetDefaultBand

The GetDefaultBand method retrieves the default band for the style.

object.GetDefaultBand() As DirectMusicBand8

Parts

object

Resolves to a DirectMusicStyle8 object.

Return Values

Returns a DirectMusicBand8 object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicStyle8.GetBand


DirectMusicStyle8.GetMotif

The GetMotif method creates a segment containing the named motif.

object.GetMotif(name As String) As DirectMusicSegment8

Parts

object

Resolves to a DirectMusicStyle8 object.

name

Name assigned to the motif by the author of the style.

Return Values

Returns a DirectMusicSegment8 object representing the motif.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicStyle8.GetMotifCount
  • DirectMusicStyle8.GetMotifName


DirectMusicStyle8.GetMotifCount

The GetMotifCount method retrieves the number of motifs available in the style.

object.GetMotifCount() As Long

Parts

object

Resolves to a DirectMusicStyle8 object.

Return Values

Returns the number of motifs in the style.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicStyle8.GetMotifName

The GetMotifName method retrieves the name of a motif in the style.

object.GetMotifName(index As Long) As String

Parts

object

Resolves to a DirectMusicStyle8 object.

index

Index of the motif in the style, in the range from 1 through DirectMusicStyle8.GetMotifCount.

Return Values

Returns the name assigned to the motif by the author of the style.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

  • DirectMusicStyle8.GetMotif


DirectMusicStyle8.GetTempo

The GetTempo method retrieves the recommended tempo of the style.

object.GetTempo() As Double

Parts

object

Resolves to a DirectMusicStyle8 object.

Return Values

Returns the recommended tempo, in beats per minute.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicStyle8.GetTimeSignature

The GetTimeSignature method retrieves the style's time signature.

object.GetTimeSignature(pTimeSig As DMUS_TIMESIGNATURE)

Parts

object

Resolves to a DirectMusicStyle8 object.

pTimeSig

DMUS_TIMESIGNATURE type that receives information about the time signature.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusic Types

This section contains information on the following types used in DirectMusic for Visual Basic.

Type | Description
DMUS_AUDIOPARAMS | Describes required resources for the default synthesizer and buffers of a performance.
DMUS_CURVE_PMSG | Contains information about a curve message.
DMUS_NOTE_PMSG | Contains data for a music note event.
DMUS_NOTIFICATION_PMSG | Contains information about a notification message sent by the performance.
DMUS_TIMESIGNATURE | Contains information about a time signature.


DMUS_AUDIOPARAMS

The DMUS_AUDIOPARAMS type describes required resources for the default synthesizer and buffers of a performance. Passed to the DirectMusicPerformance8.InitAudio method to request desired features and to receive information about what requests were granted.

Syntax

Type DMUS_AUDIOPARAMS
  clsidDefaultSynth As String
  fInitNow As Boolean
  lFeatures As Long
  lSampleRate As Long
  lValidData As Long
  lVoices As Long
End Type

Members

clsidDefaultSynth

Class identifier of the default synthesizer. This is the synthesizer used by standard audiopaths and audiopaths created from configurations that request the default synthesizer. If this value is not supplied, the Microsoft software synthesizer is the default synthesizer.

fInitNow

Boolean value that specifies whether the sink and synthesizer are created immediately. If so, results are returned in this structure.

lFeatures

Flags that specify capabilities of the path. Can be 0, or one or more constants of the CONST_DMUS_AUDIO enumeration.

lSampleRate

Sample rate of sink and synthesizer, in the range from 11,025 to 96,000 kHz. The default value is 22,050.

lValidData

Flags that specify which members of this structure contain valid data. If fInitNow is True when the structure is passed, this member receives flags that specify what members received data. See CONST_DMUS_AUDIOPARAMS.

lVoices

Number of voices. The default value is 64.

See Also

  • DirectMusicPerformance8.InitAudio


DMUS_CURVE_PMSG

The DMUS_CURVE_PMSG type contains information about a curve message.

Syntax

Type DMUS_CURVE_PMSG
  beat As Byte
  ccData As Byte
  curveShape As Byte
  endValue As Integer
  flags As Byte
  grid As Byte
  measure As Integer
  MergeIndex As Integer
  mtDuration As Long
  mtOriginalStart As Long
  mtResetDuration As Long
  offset As Integer
  ParamType As Integer
  resetValue As Integer
  startValue As Integer
  type As Byte
End Type

Members

beat

Beat count (within a measure) at which this curve occurs.

ccData

Controller number, if type is DMUS_CURVET_CCCURVE.

curveShape

Shape of the curve. This can be one of the values from the CONST_DMUS_CURVES enumeration.

endValue

End value of the curve.

flags

Flags. Can be 0 or one or more constants from the CONST_DMUS_CURVE_FLAGS enumeration.

grid

Grid offset from a beat at which this curve occurs. In application-created messages, should be 0.

measure

Measure in which this curve occurs. In application-created messages, should be 0.

MergeIndex

Merge index. Supported for transpose, pitch bend, volume, expression, pan, filter, mod wheel, chorus, and reverb controllers. See Remarks.

mtDuration

How long the curve lasts. This value is in music time unless DMUS_PMSGF_LOCKTOREFTIME is present in the flags parameter of DirectMusicPerformance8.SendCurvePMSG, in which case it is in milliseconds and is unaffected by a change in tempo.

mtOriginalStart

Original start time, in music time. In application-created messages, must be 0.

mtResetDuration

Length of time after the end of the curve during which a reset can take place in response to an invalidation. Ignored if DMUS_CURVE_RESET is not in the flags member. This value is in music time unless DMUS_PMSGF_LOCKTOREFTIME is present in the flags parameter of DirectMusicPerformance8.SendCurvePMSG, in which case it is in milliseconds and is unaffected by a change in tempo.

offset

Offset from a grid at which this curve occurs, in music time.

ParamType

MIDI parameter number. See Remarks.

resetValue

Value to set after a flush or invalidation.

startValue

Start value of the curve.

type

Type of curve. This can be one of the values from the CONST_DMUS_CURVET enumeration.

Remarks

An RPN or NRPN curve type in ParamType is stored as two bytes with seven significant bits. For example, if the MSB is 0x23 and the LSB is 0x74, the value in ParamType is 0x2374.

Data in startValue, endValue, and resetValue is limited to 14 bits. For MIDI data consisting of two seven-bit bytes, the value is stored as a word with the upper two bits empty.

All curves with MergeIndex of 0 override each other. If the merge index is another value, the values generated by the curve are added to the values for merge index 0. For example, if an application uses curves with indexes of 0 and 3, the 0 curves always replace each other but add to the 3 curves, and the 3 curves also always replace each other and add to the 0 curves.

See Also

  • DirectMusicPerformance8.SendCurvePMSG


DMUS_NOTE_PMSG

ontains data for a music note event.

Syntax

Type DMUS_NOTE_PMSG
  beat as Byte
  durRange As Byte
  flags As Byte
  grid As Byte
  measure As Integer
  midiValue As Byte
  mtDuration As Long
  musicValue As Integer
  offset As Integer
  playModeFlags As Byte
  subChordLevel As Byte
  timeRange As Byte
  transpose As Integer
  velocity As Byte
  velRange As Byte
End Type

Members

beat

Beat count (within a measure) at which this note occurs.

durRange

Range to randomize duration.

flags

Should be set to DMUS_NOTEF_NOTEON. See Remarks.

grid

Grid offset from a beat at which this note occurs.

measure

Measure in which this note occurs.

midiValue

MIDI note value.

mtDuration

Duration of the note, in music time. There are 768 ticks in a quarter note.

musicValue

Description of the note. In most play modes, this is a packed array of four-bit values, as follows:

Octave, in the range from –2 through 14. The note is transposed up or down by the octave times 12.

Chord position, in the range from 0 through 15, though it should never be above 3. The first position in the chord is 0.

Scale position, in the range from 0 through 15. Typically, it is from 0 through 2, but it is possible to have a one-note chord and have everything above the chord be interpreted as a scale position.

Accidental, in the range from –8 through 7, but typically in the range from –2 through 2. This represents an offset that takes the note out of the scale.

In the fixed play modes, the music value is a MIDI note value in the range from 0 through 127.

offset

Offset from a grid at which this note occurs, in music time.

playModeFlags

Play mode determining how the music value is related to the chord and subchord. For a list of values, see CONST_DMUS_PLAYMODE_FLAGS.

subChordLevel

Subchord level that the note uses.

timeRange

Range by which to randomize time.

transpose

Transposition to add to midiValue after conversion from musicValue.

velocity

Note velocity.

velRange

Range by which to randomize velocity.

Remarks

Applications sending note messages must provide values only in the flags, midiValue, mtDuration, and velocity members. The other members are of interest only to tools, which are not supported in DirectX for Visual Basic.

Normally the application sets flags to DMUS_NOTEF_NOTEON. The application is not responsible for sending note-off messages. When the DirectMusic output tool receives a DMUS_NOTE_PMSG and sees that DMUS_NOTEF_NOTEON is set, it clears the flag, adds mtDuration to the time stamp, and requeues the message so that the note is turned off at the appropriate time.

It is possible, however, for the application to stop a note prematurely by sending the same note on the same channel with flags set to 0.

See Also

  • DirectMusicPerformance8.SendNotePMSG
  • Music Values and MIDI Notes


DMUS_NOTIFICATION_PMSG

The DMUS_NOTIFICATION_PMSG type contains information about a notification message sent by the performance.

Syntax

Type DMUS_NOTIFICATION_PMSG
  ctTime As Long
  lField1 As Long
  lField2 As Long
  lNotificationOption As Long
  lNotificationType As Long
  mtTime As Long
  User As Unknown
End Type

Members

ctTime

Time stamp of the message, in clock time.

lField1

Extra data specific to the type of notification. For DMUS_NOTIFY_ON_MEASUREANDBEAT notifications, this member returns the beat number within the measure.

lField2

Extra data specific to the type of notification. Reserved for future or application-defined use.

lNotificationOption

Identifier of the notification subtype, from the CONST_DMUS_NOTIFICATION_SUBTYPE enumeration.

The possible values in this member dpend on the notification type, as shown in the following tables.

If the notification type is DMUS_NOTIFY_ON_SEGMENT, this member can contain one of the following values:

Value | Description
DMUS_NOTIFICATION_SEGABORT | The segment was stopped prematurely or was removed from the primary segment queue.
DMUS_NOTIFICATION_SEGALMOSTEND | The segment has reached the end minus the Prepare Time.
DMUS_NOTIFICATION_SEGEND | The segment has ended.
DMUS_NOTIFICATION_SEGLOOP | The segment has looped.
DMUS_NOTIFICATION_SEGSTART | The segment has started.

If the notification type is DMUS_NOTIFY_ON_COMMAND, this member can contain one of the following values:

Value | Description
DMUS_NOTIFICATION_GROOVE | Groove change.
DMUS_NOTIFICATION_EMBELLISHMENT | Embellishment command (intro, fill, break, or end).

If the notification type is DMUS_NOTIFY_ON_PERFORMANCE, this member can contain one of the following values:

Value | Description
DMUS_NOTIFICATION_MUSICALMOSTEND | The currently playing primary segment has reached the end minus the prepare time, and no more primary segments are cued to play.
DMUS_NOTIFICATION_MUSICSTARTED | Playback has started.
DMUS_NOTIFICATION_MUSICSTOPPED | Playback has stopped.

If the notification type is DMUS_NOTIFY_ON_MEASUREANDBEAT, this member contains DMUS_NOTIFICATION_MEASUREBEAT. No other subtypes are defined.

If the notification type is DMUS_NOTIFY_ON_CHORD, this member contains DMUS_NOTIFICATION_CHORD. No other subtypes are defined.

If the notification type is DMUS_NOTIFY_ON_RECOMPOSE, this member contains DMUS_NOTIFICATION_RECOMPOSE. No other subtypes are defined.

lNotificationType

Identifier of the notification type, from the CONST_DMUS_NOTIFICATION_TYPE enumeration.

mtTime

Time stamp of the message, in music time.

User

Object associated with the event. See Remarks.

Remarks

For most notifications, the User member contains a DirectMusicSegmentState8 object. When an application is notified of a segment event, the relevant segment can be retrieved from this object by using DirectMusicSegmentState8.GetSegment.

For notifications of type GUID_NOTIFICATION_PERFORMANCE, the User member is always Nothing.

See Also

  • DirectMusicPerformance8.AddNotificationType
  • DirectMusicPerformance8.GetNotificationPMSG


DMUS_TIMESIGNATURE

The DMUS_TIMESIGNATURE type contains information about a time signature. It is passed to the DirectMusicPerformance8.GetTimeSig and DirectMusicStyle8.GetTimeSignature methods, and is also used in messages sent by the DirectMusicPerformance8.SendTimeSigPMSG method.

Syntax

Type DMUS_TIMESIGNATURE
  beat As Byte
  beatsPerMeasure As Byte
  gridsPerBeat As Integer
  mtTime As Long
End Type

Members

beat

Bottom of time signature.

beatsPerMeasure

Top of time signature.

gridsPerBeat

Grids (subdivisions) per beat. This value determines the timing resolution for certain music events—for example, segments cued with the DMUS_SEGF_GRID flag.

mtTime

Music time at which this time signature occurs.


DirectMusic Enumerations

DirectMusic for Visual Basic uses enumerations to group constants to take advantage of the statement completion feature of the Microsoft® Visual Studio® development environment.

This section contains reference information for the following enumerations:

  • CONST_DMUS
  • CONST_DMUS_AUDIO
  • CONST_DMUS_AUDIOPARAMS
  • CONST_DMUS_COMMANDT_TYPES
  • CONST_DMUS_COMPOSEF_FLAGS
  • CONST_DMUS_CURVE_FLAGS
  • CONST_DMUS_CURVES
  • CONST_DMUS_CURVET
  • CONST_DMUS_NOTEF_FLAGS
  • CONST_DMUS_NOTIFICATION_SUBTYPE
  • CONST_DMUS_NOTIFICATION_TYPE
  • CONST_DMUS_PCHANNEL
  • CONST_DMUS_PLAYMODE_FLAGS
  • CONST_DMUS_PMSGF_FLAGS
  • CONST_DMUS_SEGF_FLAGS
  • CONST_DMUS_SHAPET_TYPES
  • CONST_DMUSERR
  • CONST_DMUSIC_PATH
  • CONST_DMUSIC_STANDARD_AUDIO_PATH


CONST_DMUS

The CONST_DMUS enumeration contains miscellaneous constants used in DirectMusic.

Syntax

Enum CONST_DMUS
  DMUS_MAXSUBCHORD =    8
  DMUS_TEMPO_MAX   = 1000 (&H3E8)
  DMUS_TEMPO_MIN   =    1
End Enum

Constants

DMUS_MAXSUBCHORD

Maximum number of subchords allowed in a chord.

DMUS_TEMPO_MAX

Maximum tempo, in beats per minute.

DMUS_TEMPO_MIN

Minimum tempo, in beats per minute.


CONST_DMUS_AUDIOPARAMS

The CONST_DMUS_AUDIOPARAMS enumeration is used to specify valid members of the DMUS_AUDIOPARAMS type.

Syntax

Enum CONST_DMUS_AUDIOPARAMS
  DMUS_AUDIOPARAMS_DEFAULTSYNTH = 8
  DMUS_AUDIOPARAMS_FEATURES     = 1
  DMUS_AUDIOPARAMS_SAMPLERATE   = 4
  DMUS_AUDIOPARAMS_VOICES       = 2
End Enum

Constants

DMUS_AUDIOPARAMS_DEFAULTSYNTH

The clsidDefaultSynth member contains valid data.

DMUS_AUDIOPARAMS_FEATURES

The lFeatures member contains valid data.

DMUS_AUDIOPARAMS_SAMPLERATE

The lSampleRate member contains valid data.

DMUS_AUDIOPARAMS_VOICES

The lVoices member contains valid data.


CONST_DMUS_AUDIO

The CONST_DMUS_AUDIO enumeration is used to specify features in an audiopath.

Syntax

Enum CONST_DMUS_AUDIO
  DMUS_AUDIOF_3D        =  1
  DMUS_AUDIOF_ALL       = 31 (&H1F)
  DMUS_AUDIOF_BUFFERS   = 32 (&h20)
  DMUS_AUDIOF_DMOS      =  8
  DMUS_AUDIOF_EAX       =  4
  DMUS_AUDIOF_ENVIRON   =  2
  DMUS_AUDIOF_STREAMING = 16 (&H10)
End Enum

Constants

DMUS_AUDIOF_3D

3-D buffers.

DMUS_AUDIOF_ALL

Combination of all other flags.

DMUS_AUDIOF_BUFFERS

Multiple buffers. This flag should always be set to provide full support for audiopaths.

DMUS_AUDIOF_DMOS

Additional DMOs.

DMUS_AUDIOF_EAX

EAX effects.

DMUS_AUDIOF_ENVIRON

Environmental modeling.

DMUS_AUDIOF_STREAMING

Support for streaming waves.


CONST_DMUS_COMMANDT_TYPES

The CONST_DMUS_COMMANDT_TYPES enumeration is used to identify commands that establish musical patterns.

Syntax

Enum CONST_DMUS_COMMANDT_TYPES
  DMUS_COMMANDT_BREAK       = 3
  DMUS_COMMANDT_END         = 4
  DMUS_COMMANDT_ENDANDINTRO = 5
  DMUS_COMMANDT_FILL        = 1
  DMUS_COMMANDT_GROOVE      = 0
  DMUS_COMMANDT_INTRO       = 2
End Enum

Constants

DMUS_COMMANDT_BREAK

Break.

DMUS_COMMANDT_END

Ending.

DMUS_COMMANDT_ENDANDINTRO

Ending and intro.

DMUS_COMMANDT_FILL

Fill.

DMUS_COMMANDT_GROOVE

Normal groove pattern.

DMUS_COMMANDT_INTRO

Intro.

See Also

  • DirectMusicComposer8.AutoTransition
  • DirectMusicComposer8.ComposeTransition
  • DirectMusicPerformance8.GetCommand


CONST_DMUS_COMPOSEF_FLAGS

The CONST_DMUS_COMPOSEF_FLAGS enumeration is used as flags in the composition of transitions.

Syntax

Enum CONST_DMUS_COMPOSEF_FLAGS
  DMUS_COMPOSEF_1BAR_ADDITION       =  131072 (&H20000)
  DMUS_COMPOSEF_1BAR_TRANSITION     =   32768 (&H8000)
  DMUS_COMPOSEF_AFTERPREPARETIME    =      64 (&H40)
  DMUS_COMPOSEF_ALIGN               =       1
  DMUS_COMPOSEF_BEAT                =      16 (&H10)
  DMUS_COMPOSEF_DEFAULT             =  524288 (&H80000)
  DMUS_COMPOSEF_ENTIRE_ADDITION     =   65536 (&H10000)
  DMUS_COMPOSEF_ENTIRE_TRANSITION   =   16384 (&H4000)
  DMUS_COMPOSEF_GRID                =       8
  DMUS_COMPOSEF_IMMEDIATE           =       4
  DMUS_COMPOSEF_LONG                =    8192 (&H2000)
  DMUS_COMPOSEF_MARKER              =    2048 (&H800)
  DMUS_COMPOSEF_MEASURE             =      32 (&H20)
  DMUS_COMPOSEF_MODULATE            =    4096 (&H1000)
  DMUS_COMPOSEF_NOINVALIDATE        = 1048576 (&H100000)
  DMUS_COMPOSEF_NONE                =       0
  DMUS_COMPOSEF_OVERLAP             =       2
  DMUS_COMPOSEF_SEGMENTEND          =    1024 (&H400)
  DMUS_COMPOSEF_USE_AUDIOPATH       = 2097152 (&H200000)
  DMUS_COMPOSEF_VALID_START_BEAT    =     128 (&H80)
  DMUS_COMPOSEF_VALID_START_GRID    =     256 (&H100)
  DMUS_COMPOSEF_VALID_START_MEASURE =  262144 (&H40000)
  DMUS_COMPOSEF_VALID_START_TICK    =     512 (&H200)
End Enum

Constants

DMUS_COMPOSEF_1BAR_ADDITION

Include one bar of the additional transition pattern. This is the default behavior when DMUS_COMPOSEF_LONG is specified.

DMUS_COMPOSEF_1BAR_TRANSITION

Include one bar of the transition pattern.

DMUS_COMPOSEF_AFTERPREPARETIME

AutoTransition only. Use the DMUS_SEGF_AFTERPREPARETIME flag (see CONST_DMUS_SEGF_FLAGS) when cueing the transition.

DMUS_COMPOSEF_ALIGN

Align transition to the time signature of the currently playing segment.

DMUS_COMPOSEF_BEAT

AutoTransition only. Start transition on a beat boundary.

DMUS_COMPOSEF_DEFAULT

Use the segment's default boundary.

DMUS_COMPOSEF_ENTIRE_ADDITION

Include the additional transition pattern in its entirety. Used in combination with DMUS_COMPOSEF_LONG.

DMUS_COMPOSEF_ENTIRE_TRANSITION

Include the entire transition pattern.

DMUS_COMPOSEF_GRID

AutoTransition only. Start transition on a grid boundary.

DMUS_COMPOSEF_IMMEDIATE

AutoTransition only. Start transition on a music or clock time boundary.

DMUS_COMPOSEF_LONG

Composes a long transition. If this flag is not set, the length of the transition is at most one measure unless the lCommand parameter of ComposeTransition or AutoTransition specifies an ending and the style contains an ending of greater than one measure. If this flag is set, the length of the transition increases by one measure.

DMUS_COMPOSEF_MARKER

Play the transition at the next marker in the current segment.

DMUS_COMPOSEF_MEASURE

AutoTransition only. Start transition on a measure boundary.

DMUS_COMPOSEF_MODULATE

Compose a transition that modulates smoothly from fromSeg to toSeg, using the chord of toSeg.

DMUS_COMPOSEF_NOINVALIDATE

Do not invalidate segments that are playing.

DMUS_COMPOSEF_NONE

No flags. By default, the transition starts on a measure boundary.

DMUS_COMPOSEF_OVERLAP

Overlap the transition into toSeg. Not currently implemented.

DMUS_COMPOSEF_SEGMENTEND

Play the transition at the end of the current segment.

DMUS_COMPOSEF_USE_AUDIOPATH

Use audiopath embedded in the segments.

DMUS_COMPOSEF_VALID_START_BEAT

Allow the switch to occur on any beat. Used in conjunction with DMUS_COMPOSEF_ALIGN.

DMUS_COMPOSEF_VALID_START_GRID

Allow the switch to occur on any grid. Used in conjunction with DMUS_COMPOSEF_ALIGN.

DMUS_COMPOSEF_VALID_START_MEASURE

Allow the switch to occur on any bar. Used in combination with DMUS_COMPOSEF_ALIGN.

DMUS_COMPOSEF_VALID_START_TICK

Allow the switch to occur at any time. Used in conjunction with DMUS_COMPOSEF_ALIGN.

See Also

  • DirectMusicComposer8.AutoTransition
  • DirectMusicComposer8.ComposeTransition


CONST_DMUS_CURVE_FLAGS

The CONST_DMUS_CURVE_FLAGS enumeration is used in the flags member of the DMUS_CURVE_PMSG type.

Syntax

Enum CONST_DMUS_CURVE_FLAGS
  DMUS_CURVE_RESET              = 1
  DMUS_CURVE_START_FROM_CURRENT = 2
End Enum

Constants

DMUS_CURVE_RESET

The value in the resetValue member is to be set when the time is reached or an invalidation occurs because of a transition. If this flag is not set, the curve stays permanently at the new value.

DMUS_CURVE_START_FROM_CURRENT

Ignore nStartValue and start the curve at the current value. Implemented for volume, expression, pitch bend, filter cuttoff, pan, and mod wheel.


CONST_DMUS_CURVES

The CONST_DMUS_CURVES enumeration is used to define the shape of a curve in the DMUS_CURVE_PMSG type.

Syntax

Enum CONST_DMUS_CURVES
  DMUS_CURVES_EXP     = 2
  DMUS_CURVES_INSTANT = 1
  DMUS_CURVES_LINEAR  = 0
  DMUS_CURVES_LOG     = 3
  DMUS_CURVES_SINE    = 4
End Enum

Constants

DMUS_CURVES_EXP

Exponential curve shape.

DMUS_CURVES_INSTANT

Instant curve shape (beginning and end of curve happen at essentially the same time).

DMUS_CURVES_LINEAR

Linear curve shape.

DMUS_CURVES_LOG

Logarithmic curve shape.

DMUS_CURVES_SINE

Sine curve shape.


CONST_DMUS_CURVET

The CONST_DMUS_CURVET enumeration is used to describe the MIDI controller in the DMUS_CURVE_PMSG type.

Syntax

Enum CONST_DMUS_CURVET
  DMUS_CURVET_CCCURVE   = 4
  DMUS_CURVET_MATCURVE  = 5
  DMUS_CURVET_NRPNCURVE = 8
  DMUS_CURVET_PATCURVE  = 6
  DMUS_CURVET_PBCURVE   = 3
  DMUS_CURVET_RPNCURVE  = 7
End Enum

Constants

DMUS_CURVET_CCCURVE

Continuous controller curve (MIDI Control Change channel voice message; status byte &HBn, where n is the channel number).

DMUS_CURVET_MATCURVE

Monophonic aftertouch curve (MIDI Channel Pressure channel voice message; status byte &HDn).

DMUS_CURVET_NRPNCURVE

NRPN curve of type defined in the ParamType member.

DMUS_CURVET_PATCURVE

Polyphonic aftertouch curve (MIDI Poly Key Pressure channel voice message, status byte &HDn).

DMUS_CURVET_PBCURVE

Pitch-bend curve (MIDI Pitch Bend channel voice message; status byte &HEn).

DMUS_CURVET_RPNCURVE

RPN curve of type defined in ParamType.


CONST_DMUS_NOTEF_FLAGS

The CONST_DMUS_NOTEF_FLAGS enumeration is used in note messages.

Syntax

Enum CONST_DMUS_NOTEF_FLAGS
  DMUS_NOTEF_NOTEON = 1
End Enum

Constants

DMUS_NOTEF_NOTEON

See the Remarks for DMUS_NOTE_PMSG.


CONST_DMUS_NOTIFICATION_SUBTYPE

The CONST_DMUS_NOTIFICATION_SUBTYPE enumeration provides information about the musical events reported in notification messages.

Syntax

Enum CONST_DMUS_NOTIFICATION_SUBTYPE
  DMUS_NOTIFICATION_CHORD    = 0
  DMUS_NOTIFICATION_EMBELLISHMENT  = 1
  DMUS_NOTIFICATION_GROOVE         = 0
  DMUS_NOTIFICATION_MEASUREBEAT    = 0
  DMUS_NOTIFICATION_MUSICALMOSTEND = 2
  DMUS_NOTIFICATION_MUSICSTARTED   = 0
  DMUS_NOTIFICATION_MUSICSTOPPED   = 1
  DMUS_NOTIFICATION_RECOMPOSE      = 0
  DMUS_NOTIFICATION_SEGABORT       = 4
  DMUS_NOTIFICATION_SEGALMOSTEND   = 2
  DMUS_NOTIFICATION_SEGEND         = 1
  DMUS_NOTIFICATION_SEGLOOP        = 3
  DMUS_NOTIFICATION_SEGSTART       = 0
End Enum

Constants

For an explanation of the constants, see DMUS_NOTIFICATION_PMSG.


CONST_DMUS_NOTIFICATION_TYPE

The CONST_DMUS_NOTIFICATION_TYPE enumeration is used to identify a notification type. These constants are passed to the DirectMusicPerformance8.AddNotificationType and DirectMusicPerformance8.RemoveNotificationType methods and identify the notification type in messages retrieved by DirectMusicPerformance8.GetNotificationPMSG.

Syntax

Enum CONST_DMUS_NOTIFICATION_TYPE
  DMUS_NOTIFY_ON_CHORD          = 1
  DMUS_NOTIFY_ON_COMMAND        = 2
  DMUS_NOTIFY_ON_MEASUREANDBEAT = 3
  DMUS_NOTIFY_ON_PERFORMANCE    = 4
  DMUS_NOTIFY_ON_RECOMPOSE      = 0
  DMUS_NOTIFY_ON_SEGMENT        = 5
End Enum

Constants

DMUS_NOTIFY_ON_CHORD

Chord change.

DMUS_NOTIFY_ON_COMMAND

Command event.

DMUS_NOTIFY_ON_MEASUREANDBEAT

Measure and beat event.

DMUS_NOTIFY_ON_PERFORMANCE

Performance event. When this value is found in the lNotificationType member of a DMUS_NOTIFICATION_PMSG type, the event is further defined in the lNotificationOption member.

DMUS_NOTIFY_ON_RECOMPOSE

Recomposition event. When this value is found in the lNotificationType of a DMUS_NOTIFICATION_PMSG type, the event is further defined in the lNotificationOption member.

DMUS_NOTIFY_ON_SEGMENT

Segment event. When this value is found in the lNotificationType of a DMUS_NOTIFICATION_PMSG type, the event is further defined in the lNotificationOption member.

See Also

  • DMUS_NOTIFICATION_PMSG


CONST_DMUS_PCHANNEL

The CONST_DMUS_PCHANNEL enumeration is used to direct messages to multiple performance channels. DMUS_PCHANNEL_ALL is used to search multiple channels for objects in the audiopath.

Syntax

Enum CONST_DMUS_PCHANNEL
  DMUS_PCHANNEL_ALL                   = -5 (&HFFFFFFFB)
  DMUS_PCHANNEL_BROADCAST_AUDIOPATH   = -2 (&HFFFFFFFE)
  DMUS_PCHANNEL_BROADCAST_GROUPS      = -4 (&HFFFFFFFC)
  DMUS_PCHANNEL_BROADCAST_PERFORMANCE = -1 (&HFFFFFFFF)
  DMUS_PCHANNEL_BROADCAST_SEGMENT     = -3 (&HFFFFFFFD)
End Enum

Constants

DMUS_PCHANNEL_ALL

Search all channels.

DMUS_PCHANNEL_BROADCAST_AUDIOPATH

Send a copy of the message to all channels of the audiopath.

DMUS_PCHANNEL_BROADCAST_GROUPS

Send a copy of the message to each channel group in the performance. Used for messages that need to be sent only once per channel group, such as system exclusive messages.

DMUS_PCHANNEL_BROADCAST_PERFORMANCE

Send a copy of the message to all channels of the performance.

DMUS_PCHANNEL_BROADCAST_SEGMENT

Send a copy of the message to all channels of the segment.


CONST_DMUS_PLAYMODE_FLAGS

The CONST_DMUS_PLAYMODE_FLAGS enumeration is used to set the play mode in a DMUS_NOTE_PMSG message type. The play mode determines how the note is transposed to the current chord before it is converted to a MIDI note.

Syntax

Enum CONST_DMUS_PLAYMODE_FLAGS
  DMUS_PLAYMODE_ALWAYSPLAY      = 14
  DMUS_PLAYMODE_CHORD_INTERVALS =  8
  DMUS_PLAYMODE_CHORD_ROOT      =  2
  DMUS_PLAYMODE_FIXED           =  0
  DMUS_PLAYMODE_FIXEDTOCHORD    =  2
  DMUS_PLAYMODE_FIXEDTOKEY      =  1
  DMUS_PLAYMODE_KEY_ROOT        =  1
  DMUS_PLAYMODE_MELODIC          = 6
  DMUS_PLAYMODE_NONE            = 16 (&H10)
  DMUS_PLAYMODE_NORMALCHORD     = 10
  DMUS_PLAYMODE_PEDALPOINT      =  5
  DMUS_PLAYMODE_SCALE_INTERVALS =  4
End Enum

Constants

The following members are the basic flags:

DMUS_PLAYMODE_CHORD_INTERVALS

Use chord intervals from chord pattern.

DMUS_PLAYMODE_CHORD_ROOT

Transpose over the chord root.

DMUS_PLAYMODE_KEY_ROOT

Transpose over the key root.

DMUS_PLAYMODE_NONE

No mode. Indicates that the parent part's mode should be used.

DMUS_PLAYMODE_SCALE_INTERVALS

Use scale intervals from scale pattern.

The following members represent combinations of the basic flags:

DMUS_PLAYMODE_ALWAYSPLAY

Combination of DMUS_PLAYMODE_SCALE_INTERVALS, DMUS_PLAYMODE_CHORD_INTERVALS, and DMUS_PLAYMODE_CHORD_ROOT. If it is desirable to play a note that is above the top of the chord, this mode finds a position for the note by using intervals from the scale. Essentially, this mode is a combination of the normal and melodic playback modes, in which a failure in normal mode causes a second try in melodic mode.

DMUS_PLAYMODE_FIXED

Interpret the music value as a MIDI value. This is defined as 0 and signifies the absence of other flags. This flag is used for drums, sound effects, and sequenced notes that should not be transposed by the chord or scale.

DMUS_PLAYMODE_FIXEDTOCHORD

Same as DMUS_PLAYMODE_CHORD_ROOT. The music value is a fixed MIDI value, but it is transposed over the chord root.

DMUS_PLAYMODE_FIXEDTOKEY

Same as DMUS_PLAYMODE_KEY_ROOT. The music value is a fixed MIDI value, but it is transposed over the key root.

DMUS_PLAYMODE_MELODIC

Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The chord root is used, but the notes track only the intervals in the scale. The key root and chord intervals are ignored. This is useful for melodic lines that play relative to the chord root.

DMUS_PLAYMODE_NORMALCHORD

Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_CHORD_INTERVALS. This is the prevalent playback mode. The notes track the intervals in the chord, which is based on the chord root. If there is a scale component to the music value, the additional intervals are pulled from the scale and added. If the chord does not have an interval to match the chord component of the music value, the note is silent.

DMUS_PLAYMODE_PEDALPOINT

Combination of DMUS_PLAYMODE_KEY_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The key root is used, and the notes track only the intervals in the scale. The chord root and intervals are ignored. This is useful for melodic lines that play relative to the key root.


CONST_DMUS_PMSGF_FLAGS

The members of the CONST_DMUS_PMSGF_FLAGS enumeration are used in the various message-sending methods of DirectMusicPerformance8.

Syntax

Enum CONST_DMUS_PMSGF_FLAGS
  DMUS_PMSGF_DX8            = 128 (&H80)
  DMUS_PMSGF_LOCKTOREFTIME  =  64 (&H40)
  DMUS_PMSGF_MUSICTIME      =   2
  DMUS_PMSGF_REFTIME        =   1
  DMUS_PMSGF_TOOL_ATTIME    =  16 (&H10)
  DMUS_PMSGF_TOOL_FLUSH     =  32 (&H20)
  DMUS_PMSGF_TOOL_IMMEDIATE =   4
  DMUS_PMSGF_TOOL_QUEUE     =   8
End Enum

Constants

DMUS_PMSGF_DX8

Message has valid members not present in versions prior to DirectX 8.0. It is not necessary to set this flag in DirectX for Visual Basic.

DMUS_PMSGF_LOCKTOREFTIME

The clock time of the message cannot be altered by a tempo change.

DMUS_PMSGF_REFTIME

The time stamp is in clock time.

DMUS_PMSGF_MUSICTIME

The time stamp is in music time.

DMUS_PMSGF_TOOL_IMMEDIATE
DMUS_PMSGF_TOOL_QUEUE
DMUS_PMSGF_TOOL_ATTIME
DMUS_PMSGF_TOOL_FLUSH

See Remarks.

Remarks

Because DirectX for Visual Basic does not support DirectMusic tools, only DMUS_PMSGF_REFTIME and DMUS_PMSGF_MUSICTIME are currently valid. Because the time of messages is in music time by default, DMUS_PMSGF_REFTIME is the only flag that applications normally use.


CONST_DMUS_SEGF_FLAGS

The members of the CONST_DMUS_SEGF_FLAGS enumeration are used in various methods of the DirectMusicPerformance8 object to control the timing and other aspects of actions on a segment.

Syntax

Enum CONST_DMUS_SEGF_FLAGS
  DMUS_SEGF_AFTERLATENCYTIME    =   4194304 (&H400000)
  DMUS_SEGF_AFTERPREPARETIME    =      1024 (&H400)
  DMUS_SEGF_AFTERQUEUETIME      =   2097152 (&H200000)
  DMUS_SEGF_ALIGN               =     65536 (&H10000)
  DMUS_SEGF_AUTOTRANSITION      =   1048576 (&H100000)
  DMUS_SEGF_BEAT                =      4096 (&H1000)
  DMUS_SEGF_CONTROL             =       512 (&H200)
  DMUS_SEGF_DEFAULT             =     16384 (&H4000)
  DMUS_SEGF_GRID                =      2048 (&H800)
  DMUS_SEGF_MARKER              =  16777216 (&H1000000)
  DMUS_SEGF_MEASURE             =      8192 (&H2000)
  DMUS_SEGF_NOINVALIDATE        =     32768 (&H8000)
  DMUS_SEGF_QUEUE               =       256 (&H100)
  DMUS_SEGF_REFTIME             =        64 (&H40)
  DMUS_SEGF_SECONDARY           =       128 (&H80)
  DMUS_SEGF_SEGMENTEND          =   8388608 (&H800000)
  DMUS_SEGF_TIMESIG_ALWAYS      =  33554432 (&H2000000)
  DMUS_SEGF_USE_AUDIOPATH       =  67108864 (&H4000000)
  DMUS_SEGF_VALID_START_BEAT    =    131072 (&H20000)
  DMUS_SEGF_VALID_START_GRID    =    262144 (&H40000)
  DMUS_SEGF_VALID_START_MEASURE = 134217728 (&H8000000
  DMUS_SEGF_VALID_START_TICK    =    524288 (&H80000)
End Enum

Constants

DMUS_SEGF_AFTERLATENCYTIME

Play after the latency time. Because this is true for all segments, this flag currently has no effect.

DMUS_SEGF_AFTERPREPARETIME

Play after the Prepare Time.

DMUS_SEGF_AFTERQUEUETIME

Play after the queue time. This is the default for primary segments. Ignored if DMUS_SEGF_AFTERPREPARETIME is also set.

DMUS_SEGF_ALIGN

The beginning of the segment can be aligned with a boundary, such as measure or beat, that has already passed. For this to happen, the segment must have a valid start point that falls before the next boundary. Start points can be defined in the segment, or one of the DMUS_SEGF_VALID_START_xxx flags can be used to define the granularity of valid start points. Any DMUS_SEGF_VALID_START_xxx flag takes effect only if a valid start point is not defined in the segment.

DMUS_SEGF_AUTOTRANSITION

Compose and play a transition segment, using the transition template.

DMUS_SEGF_BEAT

Play on a beat boundary.

DMUS_SEGF_CONTROL

Play as a control segment (secondary segments only). See Remarks.

DMUS_SEGF_DEFAULT

Use segment's default boundary.

DMUS_SEGF_GRID

Play on a grid boundary.

DMUS_SEGF_MARKER

Play at next marker in the primary segment. If there are no markers, use other resolution flags.

DMUS_SEGF_MEASURE

Play on a measure boundary.

DMUS_SEGF_NOINVALIDATE

Setting this flag in DirectMusicPerformance8.PlaySegmentEx for a primary or control segment causes the new segment not to cause an invalidation. Without this flag, an invalidation occurs, cutting off and resetting any currently playing curve or note. This flag should be combined with DMUS_SEGF_AFTERPREPARETIME so that notes in the new segment do not play over notes played by the old segment.

DMUS_SEGF_QUEUE

For a primary segment, play at the end of the primary segment queue. For a secondary segment, play at the end of the secondary segment specified in the pFrom parameter of DirectMusicPerformance8.PlaySegmentEx.

DMUS_SEGF_REFTIME

Time parameter is in clock time.

DMUS_SEGF_SECONDARY

Secondary segment.

DMUS_SEGF_SEGMENTEND

Play at the end of the primary segment that is playing at the start time. If the new segment is being played as a primary segment, any primary segments already queued after the currently playing primary segment are flushed. If no primary segment is playing, use other resolution flags. When combined with DMUS_SEGF_ALIGN, this flag causes the beginning of the cued segment to be aligned with the beginning of the current primary segment.

DMUS_SEGF_TIMESIG_ALWAYS

Align start time with current time signature, even if there is no primary segment.

DMUS_SEGF_USE_AUDIOPATH

Use the audiopath embedded in the segment. Automatic downloading of bands must be enabled to ensure that the sounds play correctly.

DMUS_SEGF_VALID_START_BEAT

Allow the start to occur on any beat. Used in combination with DMUS_SEGF_ALIGN.

DMUS_SEGF_VALID_START_GRID

Allow the start to occur on any grid. Used in combination with DMUS_SEGF_ALIGN.

DMUS_SEGF_VALID_START_MEASURE

Allow the start to occur on any measure. Used in combination with DMUS_SEGF_ALIGN.

DMUS_SEGF_VALID_START_TICK

Allow the start to occur any time. Used in combination with DMUS_SEGF_ALIGN.

Remarks

Normally the primary segment is the control segment. The DMUS_SEGF_CONTROL flag can be used to make a secondary segment the control segment. There should be only one control segment at a time. (Although it is possible to create multiple control segments, there is no guarantee of which one will actually be used by DirectMusic as the control segment.) By default, only the control segment sends tempo messages.

If the DMUS_SEGF_CONTROL flag is set, DMUS_SEGF_SECONDARY is assumed.

No more than one flag from each of the following groups should be specified.

Boundary

This flag controls the point in the currently playing primary segment at which the start point of the cued segment falls. It can be combined with DMUS_SEGF_MARKER, in which case the boundary flag will be used only if no marker exists in the primary segment.

DMUS_SEGF_BEAT
DMUS_SEGF_DEFAULT
DMUS_SEGF_GRID
DMUS_SEGF_MEASURE
DMUS_SEGF_QUEUE
DMUS_SEGF_SEGMENTEND

Alignment

This flag controls the segment start time of the cued segment, when its play time falls in the past. It must be combined with DMUS_SEGF_ALIGN.

DMUS_SEGF_VALID_START_BEAT
DMUS_SEGF_VALID_START_GRID
DMUS_SEGF_VALID_START_MEASURE
DMUS_SEGF_VALID_START_TICK

It is possible to combine one flag from each group. For example, combining DMUS_SEGF_MEASURE with DMUS_SEGF_ALIGN and DMUS_SEGF_VALID_START_BEAT causes the start point of the cued segment to fall at a measure boundary in the current primary segment. If this boundary has already passed, the cued segment starts playing at the next beat boundary within itself that is not aligned to a past time. For more information, see Segment Timing.

See Also

  • DirectMusicPerformance8.GetResolvedTime
  • DirectMusicPerformance8.Invalidate
  • DirectMusicPerformance8.PlaySegmentEx
  • DirectMusicPerformance8.StopEx


CONST_DMUS_SHAPET_TYPES

The members of the CONST_DMUS_SHAPET_TYPES enumeration are used in the wShape parameter of the DirectMusicComposer8.ComposeSegmentFromShape and DirectMusicComposer8.ComposeTemplateFromShape methods to specify the desired pattern of the groove level.

Syntax

Enum CONST_DMUS_SHAPET_TYPES
  DMUS_SHAPET_FALLING  = 0
  DMUS_SHAPET_LEVEL    = 1
  DMUS_SHAPET_LOOPABLE = 2
  DMUS_SHAPET_LOUD     = 3
  DMUS_SHAPET_PEAKING  = 5
  DMUS_SHAPET_QUIET    = 4
  DMUS_SHAPET_RANDOM   = 6
  DMUS_SHAPET_RISING   = 7
  DMUS_SHAPET_SONG     = 8
End Enum

Constants

DMUS_SHAPET_FALLING

The groove level falls.

DMUS_SHAPET_LEVEL

The groove level remains even.

DMUS_SHAPET_LOOPABLE

The segment is arranged to loop back to the beginning.

DMUS_SHAPET_LOUD

The groove level is high.

DMUS_SHAPET_PEAKING

The groove level rises to a peak, and then falls.

DMUS_SHAPET_QUIET

The groove level is low.

DMUS_SHAPET_RANDOM

The groove level is random.

DMUS_SHAPET_RISING

The groove level rises.

DMUS_SHAPET_SONG

The segment is in a song form. Several phrases of 6 to 8 bars are composed and put together to give a verse-chorus effect, with variations in groove level.


CONST_DMUSERR

The CONST_DMUSERR enumeration represents DirectMusic error codes. For a list of values, see DirectMusic Error Codes.


CONST_DMUSIC_PATH

The CONST_DMUSIC_PATH enumeration is used to specify the stage in the audiopath from which to retrieve an object. Some of these flags are valid when using the DirectMusicAudioPath8.GetObjectInPath method.

Not all objects that can be retrieved are supported in DirectX for Visual Basic. For more information, see Retrieving Objects from an Audiopath.

Syntax

Enum CONST_DMUSIC_PATH
  DMUS_PATH_AUDIOPATH          =  8192 (&H2000)
  DMUS_PATH_AUDIOPATH_GRAPH    =  8704 (&H2200)
  DMUS_PATH_AUDIOPATH_TOOL     =  8960 (&H2300)
  DMUS_PATH_BUFFER             = 24576 (&H6000)
  DMUS_PATH_BUFFER_DMO         = 24832 (&H6100)
  DMUS_PATH_MIXIN_BUFFER       = 28672 (&H7000)
  DMUS_PATH_MIXIN_BUFFER_DMO   = 28928 (&H7100)
  DMUS_PATH_PERFORMANCE        = 12288 (&H3000)
  DMUS_PATH_PERFORMANCE_GRAPH  = 12800 (&H3200)
  DMUS_PATH_PERFORMANCE_TOOL   = 13056 (&H3300)
  DMUS_PATH_PORT               = 16384 (&H4000)
  DMUS_PATH_PRIMARY_BUFFER     = 32768 (&H8000)
  DMUS_PATH_SEGMENT            =  4096 (&H1000)
  DMUS_PATH_SEGMENT_GRAPH      =  4608 (&H1200)
  DMUS_PATH_SEGMENT_TOOL       =  4864 (&H1300)
  DMUS_PATH_SEGMENT_TRACK      =  4352 (&H1100)
End Enum

Constants

DMUS_PATH_AUDIOPATH

Get the audiopath from a segment state.

DMUS_PATH_AUDIOPATH_GRAPH

Get the audiopath tool graph. One is created if none exists.

DMUS_PATH_AUDIOPATH_TOOL

Get a tool from the audiopath tool graph.

DMUS_PATH_BUFFER

Get a DirectSound buffer.

DMUS_PATH_BUFFER_DMO

Get a DMO in the buffer.

DMUS_PATH_MIXIN_BUFFER

Get a global mix-in buffer.

DMUS_PATH_MIXIN_BUFFER_DMO

Get a DMO in a global mix-in buffer.

DMUS_PATH_PERFORMANCE

Get the performance.

DMUS_PATH_PERFORMANCE_GRAPH

Get the performance tool graph. One is created if none exists.

DMUS_PATH_PERFORMANCE_TOOL

Get a tool in the performance graph.

DMUS_PATH_PORT

Get the synthesizer.

DMUS_PATH_PRIMARY_BUFFER

Get the primary buffer.

DMUS_PATH_SEGMENT

Get the segment that owns this segment state.

DMUS_PATH_SEGMENT_GRAPH

Get the segment tool graph. One is created if none exists.

DMUS_PATH_SEGMENT_TOOL

Get a tool from the segment graph. See Remarks.

DMUS_PATH_SEGMENT_TRACK

Get a track from the segment.


CONST_DMUSIC_STANDARD_AUDIO_PATH

The CONST_DMUSIC_STANDARD_AUDIO_PATH enumeration is used to specify the audiopath to create by using DirectMusicPerformance8.CreateStandardAudioPath or DirectMusicPerformance8.InitAudio.

Syntax

Enum CONST_DMUSIC_STANDARD_AUDIO_PATH
  DMUS_APATH_DYNAMIC_3D              = 6
  DMUS_APATH_DYNAMIC_MONO            = 7
  DMUS_APATH_DYNAMIC_STEREO          = 8
  DMUS_APATH_SHARED_STEREOPLUSREVERB = 1
End Enum

Constants

DMUS_APATH_DYNAMIC_3D

An audiopath with one bus from the synthesizer feeding to a 3-D buffer.

DMUS_APATH_DYNAMIC_MONO

Audio environment with one mono buffer.

DMUS_APATH_DYNAMIC_STEREO

Audio environment with one stereo buffer.

DMUS_APATH_SHARED_STEREOPLUSREVERB

Audio environment with one stereo buffer and one buffer with environmental reverb.


DirectMusic Error Codes

This section provides a brief explanation of the various error codes that can be returned by DirectMusic methods. For a list of the specific codes that each method can return, see the individual method descriptions. These lists are not necessarily comprehensive.

Error codes are presented in the following sections:

  • DirectMusic Error Codes By Number
  • DirectMusic Error Codes By Name


DirectMusic Error Codes By Number

The following table lists DirectMusic error codes sorted by value. For a description, click on the constant.

Hexadecimal | Constant
&H00001AE | DMUS_E_NOINTERFACE
&H00001BD | DMUS_E_NOTIMPL
&H80070057 | DMUS_E_FAIL
&H88781101 | DMUS_E_DRIVER_FAILED
&H88781102 | DMUS_E_PORTS_OPEN
&H88781103 | DMUS_E_DEVICE_IN_USE
&H88781104 | DMUS_E_INSUFFICIENTBUFFER
&H88781105 | DMUS_E_BUFFERNOTSET
&H88781106 | DMUS_E_BUFFERNOTAVAILABLE
&H88781108 | DMUS_E_NOTADLSCOL
&H88781109 | DMUS_E_INVALIDOFFSET
&H88781111 | DMUS_E_ALREADY_LOADED
&H88781113 | DMUS_E_INVALIDPOS
&H88781114 | DMUS_E_INVALIDPATCH
&H88781115 | DMUS_E_CANNOTSEEK
&H88781116 | DMUS_E_CANNOTWRITE
&H88781117 | DMUS_E_CHUNKNOTFOUND
&H88781119 | DMUS_E_INVALID_DOWNLOADID
&H88781120 | DMUS_E_NOT_DOWNLOADED_TO_PORT
&H88781121 | DMUS_E_ALREADY_DOWNLOADED
&H88781122 | DMUS_E_UNKNOWNDOWNLOAD
&H88781123 | DMUS_E_SET_UNSUPPORTED
&H88781124 | DMUS_E_GET_UNSUPPORTED
&H88781125 | DMUS_E_NOTMONO
&H88781126 | DMUS_E_BADARTICULATION
&H88781127 | DMUS_E_BADINSTRUMENT
&H88781128 | DMUS_E_BADWAVELINK
&H88781128 | DMUS_E_BUFFER_EMPTY
&H8878112A | DMUS_E_NOTPCM
&H8878112B | DMUS_E_BADWAVE
&H8878112C | DMUS_E_BADOFFSETTABLE
&H8878112D | DMUS_E_UNKNOWN_PROPERTY
&H8878112E | DMUS_E_NOSYNTHSINK
&H8878112F | DMUS_E_ALREADYOPEN
&H88781129 | DMUS_E_NOARTICULATION
&H88781130 | DMUS_E_ALREADYCLOSED
&H88781131 | DMUS_E_SYNTHNOTCONFIGURED
&H88781132 | DMUS_E_SYNTHACTIVE
&H88781133 | DMUS_E_CANNOTREAD
&H88781134 | DMUS_E_DMUSIC_RELEASED
&H88781136 | DMUS_E_BUFFER_FULL
&H88781137 | DMUS_E_PORT_NOT_CAPTURE
&H88781138 | DMUS_E_PORT_NOT_RENDER
&H88781139 | DMUS_E_DSOUND_NOT_SET
&H8878113A | DMUS_E_ALREADY_ACTIVATED
&H8878113B | DMUS_E_INVALIDBUFFER
&H8878113C | DMUS_E_WAVEFORMATNOTSUPPORTED
&H8878113D | DMUS_E_SYNTHINACTIVE
&H8878113E | DMUS_E_DSOUND_ALREADY_SET
&H8878113F | DMUS_E_INVALID_EVENT
&H88781150 | DMUS_E_UNSUPPORTED_STREAM
&H88781151 | DMUS_E_ALREADY_INITED
&H88781152 | DMUS_E_INVALID_BAND
&H88781155 | DMUS_E_TRACK_HDR_NOT_FIRST_CK
&H88781156 | DMUS_E_TOOL_HDR_NOT_FIRST_CK
&H88781157 | DMUS_E_INVALID_TRACK_HDR
&H88781158 | DMUS_E_INVALID_TOOL_HDR
&H88781159 | DMUS_E_ALL_TOOLS_FAILED
&H88781160 | DMUS_E_ALL_TRACKS_FAILED
&H88781161 | DMUS_E_NOT_FOUND
&H88781162 | DMUS_E_NOT_INIT
&H88781163 | DMUS_E_TYPE_DISABLED
&H88781164 | DMUS_E_TYPE_UNSUPPORTED
&H88781165 | DMUS_E_TIME_PAST
&H88781166 | DMUS_E_TRACK_NOT_FOUND
&H88781170 | DMUS_E_NO_MASTER_CLOCK
&H88781180 | DMUS_E_LOADER_NOCLASSID
&H88781181 | DMUS_E_LOADER_BADPATH
&H88781182 | DMUS_E_LOADER_FAILEDOPEN
&H88781183 | DMUS_E_LOADER_FORMATNOTSUPPORTED
&H88781184 | DMUS_E_LOADER_FAILEDCREATE
&H88781185 | DMUS_E_LOADER_OBJECTNOTFOUND
&H88781186 | DMUS_E_LOADER_NOFILENAME
&H88781200 | DMUS_E_INVALIDFILE
&H88781201 | DMUS_E_ALREADY_EXISTS
&H88781202 | DMUS_E_OUT_OF_RANGE
&H88781203 | DMUS_E_SEGMENT_INIT_FAILED
&H88781204 | DMUS_E_ALREADY_SENT
&H88781205 | DMUS_E_CANNOT_FREE
&H88781206 | DMUS_E_CANNOT_OPEN_PORT
&H88781207 | DMUS_E_CANNOT_CONVERT
&H88781210 | DMUS_E_DESCEND_CHUNK_FAIL
&H88781211 | DMUS_E_NOT_LOADED
&H88781220 | DMUS_E_INVALID_SEGMENTTRIGGERTRACK
&H88781221 | DMUS_E_INVALID_LYRICSTRACK
&H88781222 | DMUS_E_INVALID_PARAMCONTROLTRACK
&H88781226 | DMUS_E_AUDIOPATHS_NOT_VALID
&H88781227 | DMUS_E_AUDIOPATHS_IN_USE
&H88781228 | DMUS_E_NO_AUDIOPATH_CONFIG
&H88781229 | DMUS_E_AUDIOPATH_INACTIVE
&H8878122A | DMUS_E_AUDIOPATH_NOBUFFER
&H8878122B | DMUS_E_AUDIOPATH_NOPORT
&H8878122C | DMUS_E_NO_AUDIOPATH


DirectMusic Error Codes By Name

The following list describes all DirectMusic error codes. To find a constant from its value, see DirectMusic Error Codes By Number.

DMUS_E_ALL_TOOLS_FAILED

The graph object was unable to load all tools, perhaps because of errors in the stream or because the tools are incorrectly registered on the client.

DMUS_E_ALL_TRACKS_FAILED

The segment object was unable to load all tracks from the IStream object data, perhaps because of errors in the stream or because the tracks are incorrectly registered on the client.

DMUS_E_ALREADY_ACTIVATED

The port has been activated, and the parameter cannot be changed.

DMUS_E_ALREADY_DOWNLOADED

Buffer has already been downloaded.

DMUS_E_ALREADY_EXISTS

The tool is already contained in the graph. You must create a new instance.

DMUS_E_ALREADY_INITED

The object has already been initialized.

DMUS_E_ALREADY_LOADED

The DLS collection is already open.

DMUS_E_ALREADY_SENT

The message has already been sent.

DMUS_E_ALREADYCLOSED

The port is not open.

DMUS_E_ALREADYOPEN

The port was already opened.

DMUS_E_AUDIOPATH_INACTIVE

An audiopath is inactive, perhaps because the performance has been closed down.

DMUS_E_AUDIOPATH_NOBUFFER

The audiopath could not be created because a requested buffer could not be created.

DMUS_E_AUDIOPATH_NOPORT

The audiopath could not be used for playback because it lacked port assignments.

DMUS_E_AUDIOPATHS_IN_USE

The performance has set up audiopaths, so performance channels cannot be allocated.

DMUS_E_AUDIOPATHS_NOT_VALID

The performance is not using audiopaths.

DMUS_E_BADARTICULATION

Invalid articulation chunk in DLS collection.

DMUS_E_BADINSTRUMENT

Invalid instrument chunk in DLS collection.

DMUS_E_BADOFFSETTABLE

Offset table has errors.

DMUS_E_BADWAVE

Corrupted wave header.

DMUS_E_BADWAVELINK

Wave-link chunk in DLS collection points to an invalid wave.

DMUS_E_BUFFER_EMPTY

There is no data in the buffer.

DMUS_E_BUFFER_FULL

The specified number of bytes exceeds the maximum buffer size.

DMUS_E_BUFFERNOTAVAILABLE

The buffer is not available for download.

DMUS_E_BUFFERNOTSET

No buffer was prepared for the data.

DMUS_E_CANNOT_CONVERT

The requested conversion between music and MIDI values could not be made.

DMUS_E_CANNOT_FREE

The message could not be freed, either because it was not allocated or because it has already been freed.

DMUS_E_CANNOT_OPEN_PORT

The default system port could not be opened.

DMUS_E_CANNOTREAD

An error occurred when trying to read from the IStream object.

DMUS_E_CANNOTSEEK

The stream object does not support seeking.

DMUS_E_CANNOTWRITE

The stream object does not support writing.

DMUS_E_CHUNKNOTFOUND

A chunk with the specified header could not be found.

DMUS_E_DESCEND_CHUNK_FAIL

An attempt to descend into a chunk failed.

DMUS_E_DEVICE_IN_USE

Device is already in use (possibly by a non-DirectMusic client) and cannot be opened again.

DMUS_E_DMUSIC_RELEASED

Operation cannot be performed because the final instance of the DirectMusic object was released. Ports cannot be used after final release of the DirectMusic object.

DMUS_E_DRIVER_FAILED

An unexpected error was returned from a device driver, indicating possible failure of the driver or hardware.

DMUS_E_DSOUND_ALREADY_SET

A DirectSound object has already been set.

DMUS_E_DSOUND_NOT_SET

Port could not be created because no DirectSound object has been specified.

DMUS_E_FAIL

The method did not succeed.

DMUS_E_GET_UNSUPPORTED

Getting the parameter is not supported.

DMUS_E_INSUFFICIENTBUFFER

Buffer is not large enough for the requested operation.

DMUS_E_INVALID_BAND

File does not contain a valid band.

DMUS_E_INVALID_DOWNLOADID

Invalid download identifier was used in the process of creating a download buffer.

DMUS_E_INVALID_EVENT

The event either is not a valid MIDI message or makes use of running status, and cannot be packed into the buffer.

DMUS_E_INVALID_LYRICSTRACK

The file contains an invalid lyrics track.

DMUS_E_INVALID_PARAMCONTROLTRACK

The file contains an invalid parameter control track.

DMUS_E_INVALID_SEGMENTTRIGGERTRACK

The file contains an invalid segment trigger track.

DMUS_E_INVALID_TOOL_HDR

The stream object's data contains an invalid tool header and cannot be read by the graph object.

DMUS_E_INVALID_TRACK_HDR

The stream object's data contains an invalid track header and cannot be read by the segment object.

DMUS_E_INVALIDARG

An invalid value has been passed in a parameter.

DMUS_E_INVALIDBUFFER

Invalid DirectSound buffer was handed to port.

DMUS_E_INVALIDFILE

Not a valid file.

DMUS_E_INVALIDOFFSET

Wave chunks in the DLS collection file are at incorrect offsets.

DMUS_E_INVALIDPATCH

No instrument in the collection matches the patch number.

DMUS_E_INVALIDPOS

Error reading wave data from a DLS collection. Indicates a bad file.

DMUS_E_LOADER_BADPATH

The file path is invalid.

DMUS_E_LOADER_FAILEDCREATE

Object could not be found or created.

DMUS_E_LOADER_FAILEDOPEN

File open failed because the file does not exist or is locked.

DMUS_E_LOADER_FORMATNOTSUPPORTED

The object cannot be loaded because the data format is not supported.

DMUS_E_LOADER_NOCLASSID

No class identifier was supplied in the object description.

DMUS_E_LOADER_NOFILENAME

No file name was supplied in the object description.

DMUS_E_LOADER_OBJECTNOTFOUND

The object was not found.

DMUS_E_NO_AUDIOPATH

An attempt was made to play on a nonexistent audiopath.

DMUS_E_NO_AUDIOPATH_CONFIG

The segment does not contain an embedded audiopath configuration.

DMUS_E_NO_MASTER_CLOCK

There is no master clock in the performance, perhaps because the DirectMusicPerformance8.InitAudio method was not called.

DMUS_E_NOARTICULATION

Articulation missing from an instrument in the DLS collection.

DMUS_E_NOINTERFACE

No object interface is available.

DMUS_E_NOSYNTHSINK

No sink is connected to the synthesizer.

DMUS_E_NOT_DOWNLOADED_TO_PORT

The object cannot be unloaded because it is not present on the port.

DMUS_E_NOT_FOUND

The requested item is not contained by the object.

DMUS_E_NOT_INIT

A required object is not initialized or failed to initialize.

DMUS_E_NOT_LOADED

An attempt to use this object failed because it was not loaded.

DMUS_E_NOTADLSCOL

The object being loaded is not a valid DLS collection.

DMUS_E_NOTIMPL

The method is not implemented. This value can be returned if a driver does not support a feature necessary for the operation.

DMUS_E_NOTMONO

The wave chunk has more than one interleaved channel. DLS format requires mono.

DMUS_E_NOTPCM

Wave data is not in PCM format.

DMUS_E_OUT_OF_RANGE

The requested time is outside the range of the segment.

DMUS_E_OUTOFMEMORY

Insufficient memory to complete task.

DMUS_E_PORT_NOT_CAPTURE

The port is not a capture port.

DMUS_E_PORT_NOT_RENDER

Not an output port.

DMUS_E_PORTS_OPEN

The requested operation cannot be performed while there are instantiated ports in any process in the system.

DMUS_E_SEGMENT_INIT_FAILED

Segment initialization failed, probably because of a critical memory situation.

DMUS_E_SET_UNSUPPORTED

Setting the parameter is not supported.

DMUS_E_SYNTHACTIVE

The synthesizer has been activated, and the parameter cannot be changed.

DMUS_E_SYNTHINACTIVE

The synthesizer has not been activated and cannot process data.

DMUS_E_SYNTHNOTCONFIGURED

The synthesizer is not properly configured or opened.

DMUS_E_TIME_PAST

The time requested is in the past.

DMUS_E_TOOL_HDR_NOT_FIRST_CK

The stream object's data does not have a tool header as the first chunk and, therefore, cannot be read by the graph object.

DMUS_E_TRACK_HDR_NOT_FIRST_CK

The stream object's data does not have a track header as the first chunk and, therefore, cannot be read by the segment object.

DMUS_E_TRACK_NOT_FOUND

There is no track of the requested type.

DMUS_E_TYPE_DISABLED

Parameter is unavailable because it has been disabled.

DMUS_E_TYPE_UNSUPPORTED

Parameter is unsupported on this track.

DMUS_E_UNKNOWN_PROPERTY

The property set or item is not implemented by this port.

DMUS_E_UNKNOWNDOWNLOAD

The synthesizer does not support this type of download.

DMUS_E_UNSUPPORTED_STREAM

The stream does not contain data supported by the loading object.

DMUS_E_WAVEFORMATNOTSUPPORTED

Invalid buffer format was handed to the synthesizer sink.


DirectSound Visual Basic Reference

This section contains reference information for the API elements of Microsoft® DirectSound® for Microsoft® Visual Basic®. Reference material is divided into the following categories:

  • DirectSound Classes
  • DirectSound Types
  • DirectSound Enumerations
  • DirectSound Error Codes


DirectSound Classes

This section contains references for the following DirectSound classes:

Class | Description
DirectSound3DBuffer8 | Sets and retrieves the position, orientation, and other parameters of a sound buffer in 3-D space.
DirectSound3DListener8 | Represents the position and orientation of the listener and controls global 3-D sound parameters.
DirectSound8 | Represents the DirectSound playback system.
DirectSoundCapture8 | Represents a sound capture device.
DirectSoundCaptureBuffer8 | Represents a buffer used to capture sounds.
DirectSoundEnum8 | An object of the DirectSoundEnum8 class represents a collection of DirectSound-capable devices.
DirectSoundFXChorus8 | Sets and retrieves effect parameters on a buffer that supports chorus.
DirectSoundFXCompressor8 | Sets and retrieves effect parameters on a buffer that supports compressor effects.
DirectSoundFXDistortion8 | Sets and retrieves effect parameters on a buffer that supports distortion effects.
DirectSoundFXEcho8 | Sets and retrieves effect parameters on a buffer that supports echo effects.
DirectSoundFXFlanger8 | Sets and retrieves effect parameters on a buffer that supports flanger effects.
DirectSoundFXGargle8 | Sets and retrieves effect parameters on a buffer that supports amplitude modulation.
DirectSoundFXI3DL2Reverb8 | Sets and retrieves effect parameters on a buffer that supports I3DL2 (Interactive 3D Audio Level 2) reverberation effects.
DirectSoundFXParamEq8 | Sets and retrieves effect parameters on a buffer that supports parametric equalizer effects.
DirectSoundFXWavesReverb8 | Sets and retrieves effect parameters on a buffer that that supports wave reverberation.
DirectSoundPrimaryBuffer8 | Represents the primary sound buffer.
DirectSoundSecondaryBuffer8 | An object of the DirectSoundSecondaryBuffer8 class represents a secondary play buffer.


DirectSound3DBuffer8

Methods of the DirectSound3DBuffer8 class are used to set and retrieve the position, orientation, and other parameters of a sound buffer in 3-D space.

A DirectSound3DBuffer8 object is obtained by using the DirectSoundSecondaryBuffer8.GetDirectSound3DBuffer method on a secondary buffer created with 3-D capabilities. The object can also be obtained from an audiopath.

The DirectSound3DBuffer8 class has the following methods.

3-D mode

Method | Description
GetMode | Retrieves the operation mode for 3-D sound processing.
SetMode | Sets the operation mode for 3-D sound processing.

Batch parameters

Method | Description
GetAllParameters | Retrieves information that describes the 3-D characteristics of a sound buffer at a given point in time.
SetAllParameters | Sets all 3-D sound buffer parameters.

Minimum and maximum distance

Method | Description
GetMaxDistance | Retrieves the maximum distance for this sound buffer.
GetMinDistance | Retrieves the minimum distance for this sound buffer.
SetMaxDistance | Sets the maximum distance value.
SetMinDistance | Sets the minimum distance value.

Position

Method | Description
GetPosition | Retrieves the sound buffer's position, in distance units.
SetPosition | Sets the sound buffer's position, in distance units.

Sound projection cone

Method | Description
GetConeAngles | Retrieves the inside and outside angles of the sound projection cone for this sound buffer.
GetConeOrientation | Retrieves the orientation of the sound projection cone for this sound buffer.
GetConeOutsideVolume | Retrieves the cone outside volume for this sound buffer.
SetConeAngles | Sets the inside and outside angles of the sound projection cone for this sound buffer.
SetConeOrientation | Sets the orientation of the sound projection cone for this sound buffer.
SetConeOutsideVolume | Sets the cone outside volume for this sound buffer.

Velocity

Method | Description
GetVelocity | Retrieves the velocity for this sound buffer.
SetVelocity | Sets the velocity of the sound source.

Miscellaneous

Method | Description
GetDirectSoundBuffer | Retrieves a DirectSoundSecondaryBuffer object from the 3-D buffer.

See Also

  • Obtaining the 3-D Buffer Object


DirectSound3DBuffer8.GetAllParameters

The GetAllParameters method retrieves information about the 3-D characteristics of a sound buffer.

Syntax

object.GetAllParameters(buffer As DS3DBUFFER)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

buffer

DS3DBUFFER type that receives the description of the 3-D characteristics of the sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DBuffer8.GetConeAngles

The GetConeAngles method retrieves the inside and outside angles of the sound projection cone for this sound buffer.

Syntax

object.GetConeAngles( _
  inCone As Long, _
  outCone As Long)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

inCone

Variable that receives the inside angle of the sound projection cone, in degrees.

outCone

Variable that receives the outside angle of the sound projection cone, in degrees.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE.

See Also

  • Sound Cones


DirectSound3DBuffer8.GetConeOrientation

The GetConeOrientation method retrieves the orientation of the sound projection cone for this sound buffer.

Syntax

object.GetConeOrientation(orientation As D3DVECTOR)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

orientation

D3DVECTOR type that receives the current orientation of the sound projection cone. The vector information represents the center of the sound cone.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The values returned are not necessarily the same as those set by using the DirectSound3DBuffer8.SetConeOrientation method. DirectSound adjusts orientation vectors so that they have a magnitude of less than or equal to 1.0.

See Also

  • Sound Cones


DirectSound3DBuffer8.GetConeOutsideVolume

The GetConeOutsideVolume method retrieves the current cone outside volume for this sound buffer.

Syntax

object.GetConeOutsideVolume() As Long

Parts

object

Resolves to a DirectSound3DBuffer8 object.

Return Values

Returns the current cone outside volume for this sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to 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). DirectSound does not support amplification.

See Also

  • Sound Cones


DirectSound3DBuffer8.GetDirectSoundBuffer

The GetDirectSoundBuffer method returns the secondary buffer from which the 3-D buffer was created.

Syntax

object.GetDirectSoundBuffer() As DirectSoundSecondaryBuffer8

Parts

object

Resolves to a DirectSound3DBuffer8 object.

Return Values

Returns a DirectSoundSecondaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

This method can be used to obtain a DirectSoundSecondaryBuffer8 object when the DirectSoundSecondaryBuffer8 object from which the DirectSound3DBuffer8 object was created is no longer available.


DirectSound3DBuffer8.GetMaxDistance

The GetMaxDistance method retrieves the current maximum distance for this sound buffer, which is the distance beyond which the volume is no longer attenuated.

Syntax

object.GetMaxDistance() As Single

Parts

object

Resolves to a DirectSound3DBuffer8 object.

Return Values

Returns the current maximum distance setting.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

See Also

  • DirectSound3DBuffer8.GetMinDistance
  • DirectSound3DBuffer8.SetMaxDistance
  • Minimum and Maximum Distances


DirectSound3DBuffer8.GetMinDistance

The GetMinDistance method retrieves the current minimum distance for this sound buffer, which is the distance at which the sound is at maximum volume.

Syntax

object.GetMinDistance() As Single

Parts

object

Resolves to a DirectSound3DBuffer8 object.

Return Values

Returns the minimum distance setting.

Error Codes

If the method fails, an error is raised and Err.Number may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, currently defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

See Also

  • DirectSound3DBuffer8.GetMaxDistance
  • DirectSound3DBuffer8.SetMinDistance
  • Minimum and Maximum Distances


DirectSound3DBuffer8.GetMode

The GetMode method retrieves the current operation mode for 3-D sound processing.

Syntax

object.GetMode() As CONST_DS3DMODEFLAGS

Parts

object

Resolves to a DirectSound3DBuffer8 object.

Return Values

Returns the mode setting. This value is one of the constants of the CONST_DS3DMODEFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DBuffer8.GetPosition

The GetPosition method retrieves the sound buffer's position, in distance units.

Syntax

object.GetPosition(position As D3DVECTOR)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

position

D3DVECTOR type that receives the position of the sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

By default, distance units are meters, but you can change the units by using the DirectSound3DListener8.SetDistanceFactor method.


DirectSound3DBuffer8.GetVelocity

The GetVelocity method retrieves the current velocity for this sound buffer.

Syntax

object.GetVelocity(velocity As D3DVECTOR)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

velocity

D3DVECTOR type that receives the sound buffer's current velocity.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not move the buffer.

The default unit of measurement is meters per second, but you can change this by using the DirectSound3DListener8.SetDistanceFactor method.

See Also

  • DirectSound3DBuffer8.SetPosition
  • DirectSound3DBuffer8.SetVelocity
  • Doppler Factor


DirectSound3DBuffer8.SetAllParameters

The SetAllParameters method sets all 3-D properties of a sound buffer.

Syntax

object.SetAllParameters( _
  buffer As DS3DBUFFER, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

buffer

DS3DBUFFER type containing the information that describes the 3-D characteristics of the sound buffer.

applyFlag

Value that specifies when the setting should be applied. This value must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration,

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DBuffer8.SetConeAngles

The SetConeAngles method sets the inside and outside angles of the sound projection cone for this sound buffer.

Syntax

object.SetConeAngles( _
  inCone As Long, _
  outCone As Long, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

inCone

Inside angle of the sound projection cone, in degrees.

outCone

Outside angle of the sound projection cone, in degrees.

applyFlag

Value that specifies when the setting should be applied. This value must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined 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.

See Also

  • Sound Cones


DirectSound3DBuffer8.SetConeOrientation

The SetConeOrientation method sets the orientation of the sound projection cone for this sound buffer. This method has no effect unless the cone angle and cone volume factor have also been set.

Syntax

object.SetConeOrientation( _
  x As Single, _
  y As Single, _
  z As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

x, y, z

Coordinates of the new sound cone orientation vector.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

  • Sound Cones


DirectSound3DBuffer8.SetConeOutsideVolume

The SetConeOutsideVolume method sets the cone outside volume for this sound buffer.

Syntax

object.SetConeOutsideVolume( _
  coneOutsideVolume As Long, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

coneOutsideVolume

Cone outside volume for this sound buffer, in hundredths of decibels.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to 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).

See Also

  • DirectSoundSecondaryBuffer8.SetVolume
  • Sound Cones


DirectSound3DBuffer8.SetMaxDistance

The SetMaxDistance method sets the maximum distance for the buffer, which is the distance beyond which the sound is no longer attenuated.

Syntax

object.SetMaxDistance( _
  maxDistance As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

maxDistance

Maximum distance value.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

See Also

  • DirectSound3DBuffer8.GetMaxDistance
  • DirectSound3DBuffer8.SetMinDistance
  • Minimum and Maximum Distances


DirectSound3DBuffer8.SetMinDistance

The SetMinDistance method sets the minimum distance for the buffer, which is the distance at which the sound is at maximum volume.

Syntax

object.SetMinDistance( _
  minDistance As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

minDistance

Minimum distance value.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to 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).

See Also

  • DirectSound3DBuffer8.SetMaxDistance
  • Minimum and Maximum Distances


DirectSound3DBuffer8.SetMode

The SetMode method sets the operation mode for 3-D sound processing.

Syntax

object.SetMode( _
  mode As CONST_DS3DMODEFLAGS, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

mode

One of the constants of the CONST_DS3DMODEFLAGS enumeration that specifies the 3-D sound processing mode to set.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DBuffer8.SetPosition

The SetPosition method sets the sound buffer's position, in distance units.

Syntax

object.SetPosition( _
  x As Single, _
  y As Single, _
  z As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

x, y, z

Values that specify the coordinates of the position vector. DirectSound may adjust these values to prevent floating-point overflow.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

By default, distance units are meters, but you can change the units by using the DirectSound3DListener8.SetDistanceFactor method.


DirectSound3DBuffer8.SetVelocity

The SetVelocity method sets the sound buffer's velocity.

Syntax

object.SetVelocity( _
  x As Single, _
  y As Single, _
  z As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DBuffer8 object.

x, y, z

Values that specify the coordinates of the velocity vector. DirectSound may adjust these values to prevent floating-point overflow.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not move the buffer.

The default unit of measurement is meters per second, but you can change this by using the DirectSound3DListener8.SetDistanceFactor method.

See Also

  • Buffer Position and Velocity
  • DirectSound3DBuffer8.GetVelocity
  • DirectSound3DBuffer8.SetPosition


DirectSound3DListener8

The DirectSound3DListener8 class represents the position and orientation of the listener and controls global 3-D sound parameters. For a conceptual overview, see DirectSound 3-D Listeners.

An object of the DirectSound3DListener8 class is obtained by using the DirectSoundPrimaryBuffer8.GetDirectSound3DListener method.

The methods of the DirectSound3DListener8 class can be organized into the following groups.

Batch parameters

Method | Description
CommitDeferredSettings | Commits any deferred settings made since the last call to this method.
GetAllParameters | Retrieves the state of the 3-D world and listener.
SetAllParameters | Sets all 3-D listener parameters.

Distance factor

Method | Description
GetDistanceFactor | Retrieves the distance factor, which is the number of meters in a vector unit.
SetDistanceFactor | Sets the distance factor, which is the number of meters in a vector unit.

Doppler factor

Method | Description
GetDopplerFactor | Retrieves the Doppler effect factor.
SetDopplerFactor | Sets the Doppler effect factor.

Orientation

Method | Description
GetOrientation | Retrieves the listener's orientation in vectors: a front vector and a top vector.
SetOrientation | Sets the listener's orientation in terms of two vectors: a front vector and a top vector.

Position

Method | Description
GetPosition | Retrieves the listener's position in distance units.
SetPosition | Sets the listener's position, in distance units.

Rolloff factor

Method | Description
GetRolloffFactor | Retrieves the rolloff factor, which determines the rate of attenuation over distance.
SetRolloffFactor | Sets the rolloff factor, which determines the rate of attenuation over distance.

Velocity

Method | Description
GetVelocity | Retrieves the listener's velocity.
SetVelocity | Sets the listener's velocity.

Miscellaneous

Method | Description
GetDirectSoundBuffer | Retrieves the primary buffer object.


DirectSound3DListener8.CommitDeferredSettings

The CommitDeferredSettings method commits all parameter changes made by passing the DS3D_DEFERRED flag to methods of DirectSound3DBuffer8 and DirectSound3DListener8.

Syntax

object.CommitDeferredSettings()

Parts

object

Resolves to a DirectSound3DListener8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

  • Deferred Settings


DirectSound3DListener8.GetAllParameters

The GetAllParameters method retrieves the state of the 3-D world and listener.

Syntax

object.GetAllParameters(listener As DS3DLISTENER)

Parts

object

Resolves to a DirectSound3DListener8 object.

listener

DS3DLISTENER type that receives parameters.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

  • DirectSound3DListener8.SetAllParameters


DirectSound3DListener8.GetDirectSoundBuffer

The GetDirectSoundBuffer method retrieves the primary buffer from which the listener was created.

Syntax

object.GetDirectSoundBuffer() As DirectSoundPrimaryBuffer8

Parts

object

Resolves to a DirectSound3DListener8 object.

Return Values

Returns a DirectSoundPrimaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_OUTOFMEMORY.


DirectSound3DListener8.GetDistanceFactor

The GetDistanceFactor method retrieves the distance factor, which is the number of meters in a vector unit.

Syntax

object.GetDistanceFactor() As Single

Parts

object

Resolves to a DirectSound3DListener8 object.

Return Values

Returns the distance factor.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

  • DirectSound3DListener8.SetDistanceFactor
  • Distance Factor


DirectSound3DListener8.GetDopplerFactor

The GetDopplerFactor method retrieves the Doppler effect factor.

Syntax

object.GetDopplerFactor() As Single

Parts

object

Resolves to a DirectSound3DListener8 object.

Return Values

Returns the Doppler factor.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

See Also

  • DirectSound3DListener8.SetDopplerFactor
  • Doppler Factor


DirectSound3DListener8.GetOrientation

The GetOrientation method retrieves the listener's orientation in 3-D space.

Syntax

object.GetOrientation( _
  orientFront As D3DVECTOR, _
  orientTop As D3DVECTOR)

Parts

object

Resolves to a DirectSound3DListener8 object.

orientFront

D3DVECTOR type that receives the listener's front orientation vector.

orientTop

D3DVECTOR type that receives the listener's top orientation vector.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points in the direction of 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 the DirectSound3DListener8.SetOrientation method. DirectSound adjusts orientation vectors so that they are at right angles and have a magnitude of less than or equal to 1.0.

See Also

  • Listener Orientation


DirectSound3DListener8.GetPosition

The GetPosition method retrieves the listener's position in 3-D space.

Syntax

object.GetPosition(position As D3DVECTOR)

Parts

object

Resolves to a DirectSound3DListener8 object.

position

D3DVECTOR type that receives the listener's position vector.

Error Codes

If the method fails, an error is raised and Err.Number may be set to the value of DSERR_INVALIDPARAM.

See Also

  • DirectSound3DListener8.SetPosition
  • Listener Position and Velocity


DirectSound3DListener8.GetRolloffFactor

The GetRolloffFactor method retrieves the rolloff factor, which controls the rate of attenuation over distance.

Syntax

object.GetRolloffFactor() As Single

Parts

object

Resolves to a DirectSound3DListener8 object.

Return Values

Returns the rolloff factor.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0).

See Also

  • DirectSound3DListener8.SetRolloffFactor
  • Rolloff Factor


DirectSound3DListener8.GetVelocity

The GetVelocity method retrieves the listener's velocity.

Syntax

object.GetVelocity() As D3DVECTOR

Parts

object

Resolves to a DirectSound3DListener8 object.

Return Values

Returns a D3DVECTOR type containing the listener's velocity.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The default velocity is (0,0,0).

Velocity is used only for Doppler effects. It does not move the listener.

See Also

  • DirectSound3DListener8.SetVelocity
  • Listener Position and Velocity


DirectSound3DListener8.SetAllParameters

The SetAllParameters method sets all the properties of a 3-D listener and global sound parameters.

Syntax

object.SetAllParameters( _
  listener As DS3DLISTENER, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DListener8 object.

listener

DS3DLISTENER type that contains information describing all 3-D listener parameters.

applyFlag

Value that specifies when the setting should be applied. This value must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

  • DirectSound3DListener8.GetAllParameters


DirectSound3DListener8.SetDistanceFactor

The SetDistanceFactor method sets the distance factor, which is the number of meters in a vector unit.

Syntax

object.SetDistanceFactor( _
  distanceFactor As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DListener8 object.

distanceFactor

Distance factor.

applyFlag

Value that specifies when the setting should be applied. This value must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

  • DirectSound3DListener8.GetDistanceFactor
  • Distance Factor


DirectSound3DListener8.SetDopplerFactor

The SetDopplerFactor method sets the Doppler effect factor.

Syntax

object.SetDopplerFactor( _
  dopplerFactor As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DListener8 object.

dopplerFactor

Doppler factor value.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to 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).

See Also

  • DirectSound3DListener8.GetDopplerFactor
  • Doppler Factor


DirectSound3DListener8.SetOrientation

The SetOrientation method sets the listener's orientation in terms of a front vector and a top vector.

Syntax

object.SetOrientation( _
  xFront As Single, _
  yFront As Single, _
  zFront As Single, _
  xTop As Single, _
  yTop As Single, _
  zTop As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DListener8 object.

xFront, yFront, zFront

Values that specify the coordinates of the front orientation vector.

xTop, yTop, zTop

Values that specify the coordinates of the top orientation vector.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points in the direction of 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.

See Also

  • DirectSound3DListener8.GetOrientation
  • Listener Orientation


DirectSound3DListener8.SetPosition

The SetPosition method sets the listener's position, in distance units.

Syntax

object.SetPosition( _
  x As Single, _
  y As Single, _
  z As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DListener8 object.

x, y, z

Values that specify the coordinates of the listener's position vector. DirectSound may adjust these values to prevent floating-point overflow.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

By default, these units are meters, but you can change this by calling the DirectSound3DListener8.SetDistanceFactor method.

See Also

  • DirectSound3DListener8.GetPosition
  • Listener Position and Velocity


DirectSound3DListener8.SetRolloffFactor

The SetRolloffFactor method sets the rolloff factor, which determines the rate of attenuation over distance.

Syntax

object.SetRolloffFactor( _
  rolloffFactor As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DListener8 object.

rolloffFactor

Rolloff factor.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to 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).

See Also

  • DirectSound3DListener8.GetRolloffFactor
  • Rolloff Factor


DirectSound3DListener8.SetVelocity

The SetVelocity method sets the listener's velocity.

Syntax

object.SetVelocity( _
  x As Single, _
  y As Single, _
  z As Single, _
  applyFlag As CONST_DS3DAPPLYFLAGS)

Parts

object

Resolves to a DirectSound3DListener8 object.

x, y, z

Values that specify the coordinates of the listener's velocity vector. DirectSound may adjust these values to prevent floating-point overflow.

applyFlag

Value that specifies when the setting should be applied. Must be one of the constants of the CONST_DS3DAPPLYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The default velocity is (0,0,0).

Velocity is used only for Doppler effects. It does not move the listener. To change the listener's position, use the DirectSound3DListener8.SetPosition method.

See Also

  • DirectSound3DListener8.GetVelocity
  • Listener Position and Velocity


DirectSound8

The DirectSound8 class represents the DirectSound playback system. Applications use the methods of the DirectSound8 class to create buffer objects and set up the audio environment.

An object of this class is obtained by using the DirectX8.DirectSoundCreate method.

The DirectSound8 class has the following methods.

Buffer creation

Method | Description
CreatePrimarySoundBuffer | Creates a primary buffer object.
CreateSoundBuffer | Creates a buffer to hold a sequence of audio samples.
CreateSoundBufferFromFile | Creates a buffer and fills it with data from a file.
CreateSoundBufferFromResource | Creates a buffer and fills it with data from a resource.
DuplicateSoundBuffer | Creates a new buffer that duplicates or shares the original buffer's memory.

Devices

Method | Description
GetCaps | Retrieves the capabilities of the hardware device.

Initialization

Method | Description
SetCooperativeLevel | Sets the cooperative level of the application for this sound device.

Speaker configuration

Method | Description
GetSpeakerConfig | Retrieves the speaker configuration.
SetSpeakerConfig | Specifies the speaker configuration of the DirectSound object.


DirectSound8.CreatePrimarySoundBuffer

The CreatePrimarySoundBuffer method creates a primary buffer object that can be used to change the format of the audio output and to obtain a DirectSound3DListener8 object.

Syntax

object.CreatePrimarySoundBuffer( _
  bufferDesc As DSBUFFERDESC _
) As DirectSoundPrimaryBuffer8

Parts

object

Resolves to a DirectSound8 object.

bufferDesc

DSBUFFERDESC type that specifies the description of the sound buffer to create. The lBufferBytes member must be 0, and lFlags must contain DSBCAPS_PRIMARYBUFFER.

Return Values

Returns a DirectSoundPrimaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values.

DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED


DirectSound8.CreateSoundBuffer

The CreateSoundBuffer method creates a secondary buffer to mix audio samples into the primary buffer.

Syntax

object.CreateSoundBuffer( _
  bufferDesc As DSBUFFERDESC _
) As DirectSoundSecondaryBuffer8

Parts

object

Resolves to a DirectSound8 object.

bufferDesc

DSBUFFERDESC type that specifies the description of the sound buffer to create.

Return Values

Returns a DirectSoundSecondaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values.

DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_BUFFERTOOSMALL
DSERR_CONTROLUNAVAIL
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
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.

See Also

  • DirectSound8.CreateSoundBufferFromFile
  • DirectSound8.CreateSoundBufferFromResource
  • DirectSound8.DuplicateSoundBuffer


DirectSound8.CreateSoundBufferFromFile

The CreateSoundBufferFromFile method creates a secondary buffer to mix audio samples into the primary buffer, and loads data from a file into the buffer.

Syntax

object.CreateSoundBufferFromFile( _
  filename As String, _
  bufferDesc As DSBUFFERDESC _
) As DirectSoundSecondaryBuffer8

Parts

object

Resolves to a DirectSound8 object.

filename

Name of the wave file to load into the created buffer.

bufferDesc

DSBUFFERDESC type that specifies the description of the sound buffer to create. The fxFormat and lBufferBytes members are ignored, as the method determines the format and size from the data itself.

Return Values

Returns a DirectSoundSecondaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values.

DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_BUFFERTOOSMALL
DSERR_CONTROLUNAVAIL
DSERR_INVALIDCALL
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

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 DSERR_CONTROLUNAVAIL on Windows 98. On Windows 2000, it returns DSERR_INVALIDCALL.

See Also

  • DirectSound8.CreateSoundBuffer
  • DirectSound8.CreateSoundBufferFromResource
  • DirectSound8.DuplicateSoundBuffer


DirectSound8.CreateSoundBufferFromResource

The CreateSoundBufferFromResource method creates a secondary buffer to mix audio samples into the primary buffer, and loads data from a resource into the buffer. The sound resource must be of type WAV or WAVE.

Syntax

object.CreateSoundBufferFromResource( _
  dll As String, _
  resourceName As String, _
  bufferDesc As DSBUFFERDESC _
) As DirectSoundSecondaryBuffer8

Parts

object

Resolves to a DirectSound8 object.

dll

Name of the DLL that contains the resource, or vbNullString if the resource is contained in the executable file.

resourceName

Name of the resource to load into the created sound buffer.

bufferDesc

DSBUFFERDESC type that specifies the description of the sound buffer to create. The fxFormat and lBufferBytes members are ignored, as the method determines the format and size from the data itself.

Return Values

Returns a DirectSoundSecondaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values.

DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_BUFFERTOOSMALL
DSERR_CONTROLUNAVAIL
DSERR_INVALIDCALL
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

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 DSERR_CONTROLUNAVAIL on Windows 98. On Windows 2000, it returns DSERR_INVALIDCALL.

See Also

  • DirectSound8.CreateSoundBuffer
  • DirectSound8.CreateSoundBufferFromFile
  • DirectSound8.DuplicateSoundBuffer


DirectSound8.DuplicateSoundBuffer

The DuplicateSoundBuffer method creates a new secondary buffer that duplicates or shares the original buffer's memory.

This method is deprecated. Duplicate buffers do not share memory on most systems, and effects set on the original buffer are not set on the duplicate.

Syntax

object.DuplicateSoundBuffer( _
  original As DirectSoundSecondaryBuffer8 _
) As DirectSoundSecondaryBuffer8

Parts

object

Resolves to a DirectSound8 object.

original

DirectSoundSecondaryBuffer8 object to duplicate.

Return Values

Returns a DirectSoundSecondaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values.

DSERR_ALLOCATED
DSERR_INVALIDCALL
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

This method is not valid for buffers created with the DSBCAPS_CTRLFX flag.

Initially, the duplicate buffer has 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.

Although duplicate buffers often share the same memory, this is not always the case. Changes in the data stored in one buffer are not necessarily reflected in its duplicates.

See Also

  • DirectSound8.CreateSoundBuffer
  • DirectSound8.CreateSoundBufferFromFile
  • DirectSound8.CreateSoundBufferFromResource


DirectSound8.GetCaps

The GetCaps method retrieves the capabilities of the hardware device represented by the DirectSound8 object.

Syntax

object.GetCaps(caps As DSCAPS)

Parts

object

Resolves to a DirectSound8 object.

caps

DSCAPS type that receives the capabilities of this sound device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values.

DSERR_GENERIC
DSERR_UNINITIALIZED

Remarks

Information retrieved in the DSCAPS type 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. For example, the maximum number of hardware-mixed streaming sound buffers might be available only if there are no hardware static sound buffers.


DirectSound8.GetSpeakerConfig

The GetSpeakerConfig method retrieves the speaker configuration for this DirectSound8 object.

Syntax

object.GetSpeakerConfig() As CONST_DSSPEAKERFLAGS

Parts

object

Resolves to a DirectSound8 object.

Return Values

Returns a Long value containing one or more of the constants of the CONST_DSSPEAKERFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values.

DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

The speaker geometry is set by default to zero, which states that the speaker geometry has not been defined. The geometry must be explicitly set by using the DirectSound8.SetSpeakerConfig method and passing one of the speaker geometry flags with the DSSPEAKER_STEREO flag.

See Also

  • DirectSound8.SetSpeakerConfig


DirectSound8.SetCooperativeLevel

The SetCooperativeLevel method sets the cooperative level of the application for this sound device.

Syntax

object.SetCooperativeLevel( _
  hwnd As Long, _
  level As CONST_DSSCLFLAGS)

Parts

object

Resolves to a DirectSound8 object.

hwnd

Window handle to the application. See Remarks.

level

Requested priority level. Must be a constant of the CONST_DSSCLFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values.

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.

The hwnd parameter should be the top-level application window handle.

See Also

  • Cooperative Levels


DirectSound8.SetSpeakerConfig

The SetSpeakerConfig method specifies the speaker configuration of the DirectSound8 object.

Syntax

object.SetSpeakerConfig( _
  speakerConfig As CONST_DSSPEAKERFLAGS)

Parts

object

Resolves to a DirectSound8 object.

speakerConfig

Speaker configuration of the DirectSound8 object. Must be one or more of the constants of the CONST_DSSPEAKERFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values.

DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

The speaker geometry is set by default to zero, which indicates that the speaker geometry has not been defined. The geometry must be explicitly set by passing one of the speaker geometry flags combined with the DSSPEAKER_STEREO flag.

See Also

  • DirectSound8.GetSpeakerConfig
  • Speaker Configuration


DirectSoundCapture8

An object of the DirectSoundCapture8 class represents a sound capture device. The methods of the class are used to create sound capture buffers and query the capabilities of the device.

A DirectSoundCapture8 object is obtained by using the DirectX8.DirectSoundCaptureCreate method.

The DirectSoundCapture8 class has the following methods

Method | Description
CreateCaptureBuffer | Creates a capture buffer.
GetCaps | Retrieves the capabilities of the capture device.

See Also

  • Capturing Waves


DirectSoundCapture8.CreateCaptureBuffer

The CreateCaptureBuffer method creates a capture buffer.

Syntax

object.CreateCaptureBuffer( _
  bufferDesc As DSCBUFFERDESC _
) As DirectSoundCaptureBuffer8

Parts

object

Resolves to a DirectSoundCapture8 object.

bufferDesc

DSCBUFFERDESC type that specifies values for the capture buffer being created.

Return Values

Returns a DirectSoundCaptureBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_INVALIDPARAM
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

On Microsoft Windows 98 and Windows 2000, each capture device supports a single buffer.


DirectSoundCapture8.GetCaps

The GetCaps method obtains the capabilities of the capture device.

Syntax

object.GetCaps(caps As DSCCAPS)

Parts

object

Resolves to a DirectSoundCapture8 object.

caps

DSCCAPS type that receives the capabilities of the capture device.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED


DirectSoundCaptureBuffer8

An object of the DirectSoundCaptureBuffer8 class represents a buffer used to capture sounds.

A DirectSoundCaptureBuffer8 object is obtained by calling the DirectSoundCapture8.CreateCaptureBuffer method.

The methods of the DirectSoundCaptureBuffer8 class may be grouped as follows:

Information

Method | Description
GetCaps | Retrieves the capabilities of the buffer.
GetCurrentPosition | Retrieves the capture and read cursors.
GetFormat | Retrieves the format of the capture buffer.
GetStatus | Retrieves the status of the capture buffer.

Buffer data

Method | Description
ReadBuffer | Reads a portion of the sound capture buffer and stores the data in an application buffer.
WriteBuffer | Writes data to the capture buffer.

Notification

Method | Description
SetNotificationPositions | Sets points in the buffer where notification events are to be signaled.

Capture management

Method | Description
Start | Begins capturing data into the buffer.
Stop | stops capturing data.

See Also

  • Capturing Waves


DirectSoundCaptureBuffer8.GetCaps

The GetCaps method retrieves the capabilities of the buffer.

Syntax

object.GetCaps(caps As DSCBCAPS)

Parts

object

Resolves to a DirectSoundCaptureBuffer8 object.

caps

DSCBCAPS type that receives the capabilities of the capture buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_OUTOFMEMORY


DirectSoundCaptureBuffer8.GetCurrentPosition

The GetCurrentPosition method retrieves the capture and read cursors.

Syntax

object.GetCurrentPosition(cursors As DSCURSORS)

Parts

object

Resolves to a DirectSoundCaptureBuffer8 object.

cursors

DSCURSORS type that receives the position of the capture cursor and the read cursor. Each value is an offset from the start of the buffer, in bytes. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Remarks

The capture cursor, DSCURSORS.lPlay indicates the point to which data is being captured. The read cursor, DSCURSORS.lWrite, is behind the capture cursor and indicates the point up to which data can safely be read. The data after lWrite, up to and including lPlay, is not necessarily valid data, because of buffering.

See Also

  • Capture Buffer Information


DirectSoundCaptureBuffer8.GetFormat

The GetFormat method retrieves the format of the capture buffer.

Syntax

object.GetFormat(waveformat As WAVEFORMATEX)

Parts

object

Resolves to a DirectSoundCaptureBuffer8 object.

waveformat

WAVEFORMATEX type that receives a description of the capture buffer format.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSoundCaptureBuffer8.GetStatus

The GetStatus method retrieves the status of the capture buffer.

Syntax

object.GetStatus() As CONST_DSCBSTATUSFLAGS

Parts

object

Resolves to a DirectSoundCaptureBuffer8 object.

Return Values

Returns a Long value containing one or more of the constants of the CONST_DSCBSTATUSFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSoundCaptureBuffer8.ReadBuffer

The ReadBuffer method reads a portion of the sound capture buffer and stores the data in an application buffer.

Syntax

object.ReadBuffer( _
  start As Long, _
  size As Long, _
  buffer As Any, _
  flags As CONST_DSCBLOCKFLAGS)

Parts

object

Resolves to a DirectSoundCaptureBuffer8 object.

start

Offset, in bytes, from the start of the buffer to where the read begins.

size

Size, in bytes, of the portion of the buffer to read. The sound buffer is conceptually circular, so this value can be greater than the number of bytes between start and the end of the buffer. This parameter is ignored if the DSCBLOCK_ENTIREBUFFER constant is set in the flags argument.

buffer

Variable to hold the data read. Typically this is an array of bytes, and you pass the first element of the array.

flags

One of the constants of the CONST_DSCBLOCKFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

See Also

  • DirectSoundCaptureBuffer8.GetCurrentPosition


DirectSoundCaptureBuffer8.SetNotificationPositions

The SetNotificationPositions method sets points in the buffer where notification events are to be signaled. An event is signaled when the read cursor reaches a notification position.

Syntax

object.SetNotificationPositions( _
  nElements As Long, _
  psa() As DSBPOSITIONNOTIFY)

Parts

object

Resolves to a DirectSoundCaptureBuffer8 object.

nElements

Number of elements in the psa array.

psa

Array of DSBPOSITIONNOTIFY types that specify the notification positions and associated events.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

See Also

  • DirectSoundCaptureBuffer8.GetCurrentPosition


DirectSoundCaptureBuffer8.Start

The Start method begins capturing data into the buffer. If the capture buffer is already capturing data, the method has no effect.

Syntax

object.Start(flags As CONST_DSCBSTARTFLAGS)

Parts

object

Resolves to a DirectSoundCaptureBuffer8 object.

flags

Flags that specify the behavior for the capture buffer when capturing sound data. Can be one of the constants of the CONST_DSCBSTARTFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY


DirectSoundCaptureBuffer8.Stop

The Stop method stops capturing data. If the capture buffer is already stopped, the method has no effect.

Syntax

object.Stop()

Parts

object

Resolves to a DirectSoundCaptureBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values

DSERR_NODRIVER
DSERR_OUTOFMEMORY


DirectSoundCaptureBuffer8.WriteBuffer

The WriteBuffer method writes data to the capture buffer. Most applications do not use this method, as data is written to the buffer in response to the DirectSoundCaptureBuffer8.Start method.

Syntax

object.WriteBuffer( _
  start As Long, _
  size As Long, _
  buffer As Any, _
  flags As CONST_DSCBLOCKFLAGS)

Parts

object

Resolves to a DirectSoundCaptureBuffer8 object.

start

Offset, in bytes, from the start of the buffer to where the write begins.

size

Size, in bytes, of the portion of the buffer to read. The sound buffer is conceptually circular, so this value can be greater than the number of bytes between start and the end of the buffer. This parameter is ignored if DSCBLOCK_ENTIREBUFFER is set in the flags parameter.

buffer

Variable containing the data to write to the capture buffer. Typically this is an array of bytes, and you pass the first element of the array.

flags

One of the constants from the CONST_DSCBLOCKFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

See Also

  • DirectSoundCaptureBuffer8.GetCurrentPosition


DirectSoundEnum8

An object of the DirectSoundEnum8 class represents a collection of DirectSound-capable devices. The object is obtained by using the DirectX8.GetDSEnum or DirectX8.GetDSCaptureEnum method.

This class has the following methods:

Method | Description
GetCount | retrieves the number of devices in the enumeration.
GetDescription | Retrieves the friendly name of a device in the enumeration.
GetGuid | Retrieves the unique identifier of a device in the enumeration.
GetName | Retrieves the name of a device driver in the enumeration.

See Also

  • Enumeration of Capture Devices
  • Enumeration of Sound Devices


DirectSoundEnum8.GetCount

The GetCount method retrieves the number of devices in the enumeration.

Syntax

object.GetCount() As Long

Parts

object

Resolves to a DirectSoundEnum8 object.

Return Values

Returns the number of entries in the enumeration.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectSoundEnum8.GetDescription

The GetDescription method retrieves the friendly name of a device in the enumeration.

Syntax

object.GetDescription(index As Long) As String

Parts

object

Resolves to a DirectSoundEnum8 object.

index

Index of the device in the enumeration.

Return Values

Returns the description of the device supplied by the driver.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectSoundEnum8.GetGuid

The GetGuid method retrieves the unique identifier of a device in the enumeration.

Syntax

object.GetGuid(index As Long) As String

Parts

object

Resolves to a DirectSoundEnum8 object.

index

Index of the device in the enumeration.

Return Values

The method returns the GUID of the device in string form.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectSoundEnum8.GetName

The GetName method retrieves the name of a device driver in the enumeration.

Syntax

object.GetName(index As Long) As String

object

Resolves to a DirectSoundEnum8 object.

index

Index of the device in the enumeration.

Return Values

Returns the name of the device driver. This is not the friendly name of the device, which is returned by DirectSoundEnum8.GetDescription.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSoundFXChorus8

The DirectSoundFXChorus8 class is used to set and retrieve effect parameters on a buffer that supports chorus.

An object of this class is obtained by calling DirectSoundSecondaryBuffer8.GetObjectInPath on the buffer that supports the effect.

The DirectSoundFXChorus8 class has the following methods.

Method | Description
GetAllParameters | Retrieves the chorus parameters of a buffer.
SetAllParameters | Sets the chorus parameters of a buffer.

See Also

  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundFXChorus8.GetAllParameters

The GetAllParameters method retrieves the chorus parameters of a buffer.

Syntax

object.GetAllParameters() As DSFXCHORUS

Parts

object

Resolves to a DirectSoundFXChorus8 object.

Return Values

Returns a DSFXCHORUS type that contains the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXChorus8.SetAllParameters

The SetAllParameters method sets the amplitude modulation parameters of a buffer.

Syntax

object.SetAllParameters(params As DSFXCHORUS)

Parts

object

Resolves to a DirectSoundFXChorus8 object.

params

DSFXCHORUS type that specifies the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXCompressor8

The DirectSoundFXCompressor8 class is used to set and retrieve effect parameters on a buffer that supports compressor effects.

An object of this class is obtained by calling DirectSoundSecondaryBuffer8.GetObjectInPath on the buffer that supports the effect.

The DirectSoundFXCompressor8 class has the following methods.

Method | Description
GetAllParameters | Retrieves the compressor parameters of a buffer.
SetAllParameters | Sets the compressor parameters of a buffer.

See Also

  • Compression
  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundFXCompressor8.GetAllParameters

The GetAllParameters method retrieves the compressor parameters of a buffer.

Syntax

object.GetAllParameters() As DSFXCOMPRESSOR

Parts

object

Resolves to a DirectSoundFXCompressor8 object.

Return Values

Returns a DSFXCOMPRESSOR type that contains the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXCompressor8.SetAllParameters

The SetAllParameters method sets the compression parameters of a buffer.

Syntax

object.SetAllParameters(params As DSFXCOMPRESSOR)

Parts

object

Resolves to a DirectSoundFXCompressor8 object.

params

DSFXCOMPRESSOR type that specifies the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXDistortion8

The DirectSoundFXDistortion8 class is used to set and retrieve effect parameters on a buffer that supports distortion effects.

An object of this class is obtained by calling DirectSoundSecondaryBuffer8.GetObjectInPath on the buffer that supports the effect.

The DirectSoundFXDistortion8 class has the following methods.

Method | Description
GetAllParameters | Retrieves the distortion parameters of a buffer.
SetAllParameters | Sets the distortion parameters of a buffer.

See Also

  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundFXDistortion8.GetAllParameters

The GetAllParameters method retrieves the distortion parameters of a buffer.

Syntax

object.GetAllParameters() As DSFXDISTORTION

Parts

object

Resolves to a DirectSoundFXDistortion8 object.

Return Values

Returns a DSFXDISTORTION type that contains the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXDistortion8.SetAllParameters

The SetAllParameters method sets the distortion parameters of a buffer.

Syntax

object.SetAllParameters(params As DSFXDISTORTION)

Parts

object

Resolves to a DirectSoundFXDistortion8 object.

params

DSFXDISTORTION type that specifies the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXEcho8

The DirectSoundFXEcho8 class is used to set and retrieve effect parameters on a buffer that supports echo effects.

An object of this class is obtained by calling DirectSoundSecondaryBuffer8.GetObjectInPath on the buffer that supports the effect.

The DirectSoundFXEcho8 class has the following methods.

Method | Description
GetAllParameters | Retrieves the echo parameters of a buffer.
SetAllParameters | Sets the echo parameters of a buffer.

See Also

  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundFXEcho8.GetAllParameters

The GetAllParameters method retrieves the echo parameters of a buffer.

Syntax

object.GetAllParameters() As DSFXECHO

Parts

object

Resolves to a DirectSoundFXEcho8 object.

Return Values

Returns a DSFXECHO type that contains the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXEcho8.SetAllParameters

The SetAllParameters method sets the echo parameters of a buffer.

Syntax

object.SetAllParameters(params As DSFXECHO)

Parts

object

Resolves to a DirectSoundFXEcho8 object.

params

DSFXECHO type that specifies the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXFlanger8

The DirectSoundFXFlanger8 class is used to set and retrieve effect parameters on a buffer that supports flanger effects.

An object of this class is obtained by calling DirectSoundSecondaryBuffer8.GetObjectInPath on the buffer that supports the effect.

The DirectSoundFXFlanger8 class has the following methods.

Method | Description
GetAllParameters | Retrieves the flanger parameters of a buffer.
SetAllParameters | Sets the flanger parameters of a buffer.

See Also

  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundFXFlanger8.GetAllParameters

The GetAllParameters method retrieves the flanger parameters of a buffer.

Syntax

object.GetAllParameters() As DSFXFLANGER

Parts

object

Resolves to a DirectSoundFXFlanger8 object.

Return Values

Returns a DSFXFLANGER type that contains the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXFlanger8.SetAllParameters

The SetAllParameters method sets the flanger parameters of a buffer.

Syntax

object.SetAllParameters(params As DSFXFLANGER)

Parts

object

Resolves to a DirectSoundFXFlanger8 object.

params

DSFXFLANGER type that specifies the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXGargle8

The DirectSoundFXGargle8 class is used to set and retrieve effect parameters on a buffer that supports amplitude modulation.

An object of this class is obtained by calling DirectSoundSecondaryBuffer8.GetObjectInPath on the buffer that supports the effect.

The DirectSoundFXGargle8 class has the following methods.

Method | Description
GetAllParameters | Retrieves the gargle parameters of a buffer.
SetAllParameters | Sets the gargle parameters of a buffer.

See Also

  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundFXGargle8.GetAllParameters

The GetAllParameters method retrieves the amplitude modulation parameters of a buffer.

Syntax

object.GetAllParameters() As DSFXGARGLE

Parts

object

Resolves to a DirectSoundFXGargle8 object.

Return Values

Returns a DSFXGARGLE type that contains the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXGargle8.SetAllParameters

The SetAllParameters method sets the amplitude modulation parameters of a buffer.

Syntax

object.SetAllParameters(params As DSFXGARGLE)

Parts

object

Resolves to a DirectSoundFXGargle8 object.

params

DSFXGARGLE type that specifies the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXI3DL2Reverb8

The DirectSoundFXI3DL2Reverb8 class is used to set and retrieve effect parameters on a buffer that supports I3DL2 (Interactive 3D Audio Level 2) reverberation effects.

An object of this class is obtained by calling DirectSoundSecondaryBuffer8.GetObjectInPath on the buffer that supports the effect.

The DirectSoundFXI3DL2Reverb8 class has the following methods.

Parameters

Method | Description
GetAllParameters | Retrieves the I3DL2 environmental reverberation parameters of a buffer.
GetQuality | Retrieves the quality of the environmental reverberation effect.
SetAllParameters | Sets the I3DL2 environmental reverberation parameters of a buffer.
SetQuality | Sets the quality of the environmental reverberation effect.

Presets

Method | Description
GetPreset | Retrieves an identifier for standard reverberation parameters of a buffer.
SetPreset | Sets standard reverberation parameters of a buffer.

See Also

  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundFXI3DL2Reverb8.GetAllParameters

The GetAllParameters method retrieves the I3DL2 (Interactive 3D Audio Level 2) reverberation parameters of a buffer.

Syntax

object.GetAllParameters() As DSFXI3DL2REVERB

Parts

object

Resolves to a DirectSoundFXI3DL2Reverb8 object.

Return Values

Returns a DSFXI3DL2REVERB type that contains the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXI3DL2Reverb8.GetPreset

The GetPreset method retrieves an identifier for standard reverberation parameters of a buffer.

Syntax

object.GetPreset() As Long

Parts

object

Resolves to a DirectSoundFXI3DL2Reverb8 object.

Return Values

Returns a preset identifier from the CONST_DSFX_I3DL2_ENVIRONMENT_PRESETS enumeration. See Dsound.h for the default parameters associated with each preset.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include the following:

DSERR_INVALIDPARAM
DSERR_INVALIDCALL


DirectSoundFXI3DL2Reverb8.GetQuality

The GetQuality method retrieves the quality of the environmental reverberation effect.

Syntax

object.GetQuality() As Long

Parts

object

Resolves to a DirectSoundFXI3DL2Reverb8 object.

Return Values

Returns the quality of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.

See Also

  • DirectSoundFXI3DL2Reverb8.SetQuality


DirectSoundFXI3DL2Reverb8.SetAllParameters

The SetAllParameters method sets the I3DL2 (Interactive 3D Audio Level 2) reverberation parameters of a buffer.

Syntax

object.SetAllParameters(params As DSFXI3DL2REVERB)

Parts

object

Resolves to a DirectSoundFXI3DL2Reverb8 object.

params

DSFXI3DL2REVERB type that specifies the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXI3DL2Reverb8.SetPreset

The SetPreset method sets standard reverberation parameters of a buffer.

Syntax

object.SetPreset(lPreset As Long)

Parts

object

Resolves to a DirectSoundFXI3DL2Reverb8 object.

lPreset

Constant from the CONST_DSFX_I3DL2_ENVIRONMENT_PRESETS enumeration that specifies a set of default parameters. See Dsound.h for the parameters associated with each constant.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXI3DL2Reverb8.SetQuality

The SetQuality method sets the quality of the environmental reverberation effect. Higher values produce better quality at the expense of processing time.

Syntax

object.SetQuality( _
  lQuality As CONST_DSFX_I3DL2REVERB_QUALITY)

Parts

object

Resolves to a DirectSoundFXI3DL2Reverb8 object.

lQuality

Value that specifies the quality of the effect. Minimum and maximum values are defined in the CONST_DSFX_I3DL2REVERB_QUALITY enumeration. The default value is 2.

Return Values

Returns the quality of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.

See Also

  • DirectSoundFXI3DL2Reverb8.GetQuality


DirectSoundFXParamEq8

The DirectSoundFXParamEq8 class is used to set and retrieve effect parameters on a buffer that supports parametric equalizer effects.

An object of this class is obtained by calling DirectSoundSecondaryBuffer8.GetObjectInPath on the buffer that supports the effect.

The DirectSoundFXParameq8 class has the following methods.

Method | Description
GetAllParameters | Retrieves the parametric equalizer parameters of a buffer.
SetAllParameters | Sets the parametric equalizer parameters of a buffer.

See Also

  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundFXParamEq8.GetAllParameters

The GetAllParameters method retrieves the parametric equalizer parameters of a buffer.

Syntax

object.GetAllParameters() As DSFXPARAMEQ

Parts

object

Resolves to a DirectSoundFXParamEq8 object.

Return Values

Returns a DSFXPARAMEQ type that contains the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXParamEq8.SetAllParameters

The SetAllParameters method sets the parametric equalizer parameters of a buffer.

Syntax

object.SetAllParameters(params As DSFXPARAMEQ)

Parts

object

Resolves to a DirectSoundFXParamEq8 object.

params

DSFXPARAMEQ type that specifies the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXWavesReverb8

The DirectSoundFXWavesReverb8 class is used to set and retrieve effect parameters on a buffer that that supports Waves reverberation.

An object of this class is obtained by calling DirectSoundSecondaryBuffer8.GetObjectInPath on the buffer that supports the effect.

The DirectSoundFXWavesReverb8 class has the following methods.

Method | Description
GetAllParameters | Retrieves the Waves reverb parameters of a buffer.
SetAllParameters | Sets the Waves reverb parameters of a buffer.

Remarks

The Waves reverberation DMO is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

See Also

  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundFXWavesReverb8.GetAllParameters

The GetAllParameters method retrieves the Waves reverberation parameters of a buffer.

Syntax

object.GetAllParameters() As DSFXWAVESREVERB

Parts

object

Resolves to a DirectSoundFXWavesReverb8 object.

Return Values

Returns a DSFXWAVESREVERB type that contains the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundFXWavesReverb8.SetAllParameters

The SetAllParameters method sets the Waves reverberation parameters of a buffer.

Syntax

object.SetAllParameters(params As DSFXWAVESREVERB)

Parts

object

Resolves to a DirectSoundFXWavesReverb8 object.

params

DSFXWAVESREVERB type that specifies the parameters of the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_INVALIDPARAM.


DirectSoundPrimaryBuffer8

The DirectSoundPrimaryBuffer8 class represents the primary sound buffer.

An object of the DirectSoundPrimaryBuffer8 class can be obtained by using the DirectSound8.CreatePrimarySoundBuffer method. Typically a primary buffer object is used to set the output format and to obtain a 3-D listener that controls global sound parameters. Specialized applications can handle the mixing of data into the primary buffer, but normally this is handled by DirectSound when secondary buffers are played.

The methods of this class can be organized into the following groups.

Data streaming

Method | Description
Play | Causes the primary buffer to play.
ReadBuffer | Reads a portion of the buffer and stores the data in an application buffer.
Stop | Causes the buffer to stop playing.
WriteBuffer | Writes audio data to the buffer.

Parameters

Method | Description
GetCurrentPosition | Retrieves the position of the play and write cursors.
GetDirectSound3DListener | Creates a listener object.
GetFormat | Retrieves a description of the wave format of the buffer.
GetPan | Retrieves the relative volume between the left and right audio channels.
GetStatus | Retrieves the status of the buffer.
GetVolume | Retrieves the sound volume of the buffer.
SetFormat | Sets the format of the buffer.
SetPan | Specifies the relative volume between the left and right channels.
SetVolume | Changes the sound volume of the buffer.

Miscellaneous

Method | Description
GetCaps | Retrieves the capabilities of the buffer.
Restore | Restores the memory allocation for a lost sound buffer.

See Also

  • DirectSoundSecondaryBuffer8


DirectSoundPrimaryBuffer8.GetCaps

The GetCaps method retrieves the capabilities of the buffer.

Syntax

object.GetCaps(caps As DSBCAPS)

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

caps

DSBCAPS type that receives the capabilities of the buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSoundPrimaryBuffer8.GetCurrentPosition

The GetCurrentPosition method retrieves the position of the play and write cursors.

Syntax

object.GetCurrentPosition(cursors As DSCURSORS)

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

cursors

DSCURSORS type that receives the offset of the play cursor and the write cursor, in bytes.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values.

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. For more information, see Play and Write Cursors.


DirectSoundPrimaryBuffer8.GetDirectSound3DListener

The GetDirectSound3DListener method creates a listener object, which represents the person listening to the sound. The listener object can be used to set global sound parameters.

Syntax

object.GetDirectSound3DListener() As DirectSound3DListener8

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

Return Values

Returns a DirectSound3DListener8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

The method succeeds only if the primary buffer was created with the DSBCAPS_CTRL3D flag.


DirectSoundPrimaryBuffer8.GetFormat

The GetFormat method retrieves a description of the wave format of the buffer.

Syntax

object.GetFormat(format As WAVEFORMATEX)

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

format

WAVEFORMATEX type that receives a description of the wave format of the buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

  • DirectSoundPrimaryBuffer8.SetFormat


DirectSoundPrimaryBuffer8.GetPan

The GetPan method retrieves the relative volume between the left and right audio channels.

Syntax

object.GetPan() As Long

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

Return Values

Returns the relative mix between the left and right speakers. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The return value is in hundredths of a decibel (dB), in the range of DSBPAN_LEFT (-10,000) to DSBPAN_RIGHT (10,000). The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER (0), meaning that both channels are at full volume (attenuated by 0 decibels).

At any setting other than DSBPAN_CENTER, one channel is at full volume and the other is attenuated. For example, a value of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume.

The pan control acts cumulatively with the volume control.

See Also

  • DirectSoundPrimaryBuffer8.GetVolume
  • DirectSoundPrimaryBuffer8.SetPan
  • DirectSoundPrimaryBuffer8.SetVolume


DirectSoundPrimaryBuffer8.GetStatus

The GetStatus method retrieves the status of the buffer.

Syntax

object.GetStatus() As CONST_DSBSTATUSFLAGS

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

Return Values

Returns the status of the sound buffer. The status can be zero, indicating that the buffer is neither lost nor playing, or a combination of the constants of the CONST_DSBSTATUSFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectSoundPrimaryBuffer8.GetVolume

The GetVolume method retrieves the volume of the buffer.

Syntax

object.GetVolume() As Long

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

Return Values

Returns the volume of the buffer. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The volume is specified in hundredths of decibels (dB) of attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). 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.

See Also

  • DirectSoundPrimaryBuffer8.GetPan
  • DirectSoundPrimaryBuffer8.SetVolume


DirectSoundPrimaryBuffer8.Play

The Play method causes the primary buffer to play.

Syntax

object.Play(flags As CONST_DSBPLAYFLAGS)

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

flags

Must be DSBPLAY_LOOPING.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

See Also

  • DirectSoundPrimaryBuffer8.Stop


DirectSoundPrimaryBuffer8.ReadBuffer

The ReadBuffer method reads a portion of the buffer and stores the data in an application buffer. Most applications do not use this method, as the primary buffer streams its own data to the sound device in response to the DirectSoundPrimaryBuffer8.Play method.

Syntax

object.ReadBuffer( _
  start As Long, _
  size As Long, _
  buffer As Any, _
  flags As CONST_DSBLOCKFLAGS)

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

start

Offset, in bytes, from the start of the buffer to where the read begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR is specified in the flags parameter.

size

Size, in bytes, of the portion of the buffer to read. The sound buffer is conceptually circular, so this value can be greater than the number of bytes between start and the end of the buffer. This member is ignored if DSBLOCK_ENTIREBUFFER is specified in the flags parameter.

buffer

Variable to hold the data read. Typically this is an array of bytes, and you pass the first element of the array.

flags

One of the constants of the CONST_DSBLOCKFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

See Also

  • DirectSoundPrimaryBuffer8.WriteBuffer


DirectSoundPrimaryBuffer8.Restore

The Restore method restores the memory allocation for a lost buffer.

Syntax

object.Restore()

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_PRIOLEVELNEEDED

Remarks

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 DirectSoundSecondaryBuffer8.Play method. This method raises the DSERR_BUFFERLOST error to indicate a lost buffer. The DirectSoundSecondaryBuffer8.GetStatus method can also be used to retrieve the status of the sound buffer and test for the DSBSTATUS_BUFFERLOST flag.

See Also

  • DirectSoundPrimaryBuffer8.GetStatus


DirectSoundPrimaryBuffer8.SetFormat

The SetFormat method sets the format of the buffer. Whenever this application gains the input focus, DirectSound sets the primary buffer to the specified format.

Syntax

object.SetFormat(format As WAVEFORMATEX)

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

format

WAVEFORMATEX type that specifies the new format for the primary sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_BADFORMAT
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_PRIOLEVELNEEDED

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, the buffer must be stopped before SetFormat is called. If 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 DirectSoundPrimaryBuffer8.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.

See Also

  • Matching Buffer Formats


DirectSoundPrimaryBuffer8.SetPan

The SetPan method specifies the relative volume between the left and right channels.

Syntax

object.SetPan(pan As Long)

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

pan

Relative volume between the left and right channels.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The return value is in hundredths of a decibel (dB), in the range of DSBPAN_LEFT (-10,000) to DSBPAN_RIGHT (10,000). The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER (0), meaning that both channels are at full volume (attenuated by 0 decibels).

At any setting other than DSBPAN_CENTER, one channel is at full volume and the other is attenuated. For example, a value of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume.

The pan control acts cumulatively with the volume control.

See Also

  • DirectSoundPrimaryBuffer8.GetPan
  • DirectSoundPrimaryBuffer8.SetVolume


DirectSoundPrimaryBuffer8.SetVolume

The SetVolume method changes the sound volume of the buffer.

Syntax

object.SetVolume(volume As Long)

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

volume

Volume requested for this sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The volume is specified in hundredths of decibels (dB) of attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). 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.

See Also

  • DirectSoundPrimaryBuffer8.GetVolume
  • DirectSoundPrimaryBuffer8.SetPan


DirectSoundPrimaryBuffer8.Stop

The Stop method causes the buffer to stop playing.

Syntax

object.Stop()

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

if an application has the DSSCL_WRITEPRIMARY level, this method stops the primary buffer and reset the play cursor to 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 DirectSoundPrimaryBuffer8.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 DirectSoundPrimaryBuffer8.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.


DirectSoundPrimaryBuffer8.WriteBuffer

The WriteBuffer method writes audio data to the buffer.

It is not recommended that applications write directly to the primary buffer. Calling DirectSoundSecondaryBuffer8.Play causes data from the secondary buffer to be mixed into the primary buffer.

Syntax

object.WriteBuffer( _
  start As Long, _
  size As Long, _
  buffer As Any, _
  flags As CONST_DSBLOCKFLAGS)

Parts

object

Resolves to a DirectSoundPrimaryBuffer8 object.

start

Offset, in bytes, from the start of the buffer to where the read begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR constant is specified in the flags parameter.

size

Size, in bytes, of the portion of the buffer to read. The sound buffer is conceptually circular, so this value can be greater than the number of bytes between start and the end of the buffer. This parameter is ignored if DSBLOCK_ENTIREBUFFER constant is specified in the flags parameter.

buffer

Variable that contains the data to write to the sound buffer. Typically this is an array of bytes, and you pass the first element of the array.

flags

One of the constants of the CONST_DSBLOCKFLAGS enumeration specifying how to write the data.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED


DirectSoundSecondaryBuffer8

An object of the DirectSoundSecondaryBuffer8 class represents a secondary play buffer. Sounds from secondary buffers are mixed into the primary buffer.

The object can be obtained by using the DirectSound8.CreateSoundBuffer, DirectSound8.CreateSoundBufferFromFile, or DirectSound8.CreateSoundBufferFromResource method. In applications that use audiopaths, a secondary buffer can be retrieved by using the DirectMusicAudioPath8.GetObjectInPath method.

The DirectSoundSecondaryBuffer8 class has the following methods.

Buffer information

Method | Description
GetCaps | Retrieves the capabilities of the buffer.
GetFormat | Retrieves a description of the wave format of the buffer.
GetStatus | Retrieves the status of the sound buffer.

Effects and 3-D

Method | Description
GetDirectSound3DBuffer | Retrieves an object that can be used to manipulate 3-D effects on the buffer.
GetObjectInPath | Retrieves an object, typically an effect DMO, in the audiopath of the buffer.
SetFX | Sets effects for sounds in the buffer.

Play management

Method | Description
GetCurrentPosition | Retrieves the position of the play and write cursors.
GetFrequency | Retrieves the sample frequency at which the buffer is playing.
GetPan | Retrieves the relative volume between the left and right audio channels.
GetVolume | Retrieves the sound volume of the sound buffer.
Play | Causes the sound buffer to play from the play cursor.
ReadBuffer | Reads a portion of the sound buffer and stores the data in an application buffer.
SetCurrentPosition | Sets the position of the play cursor.
SetFrequency | Sets the frequency at which the audio samples are played.
SetNotificationPositions | Sets positions where the play cursor signals events.
SetPan | Specifies the relative volume between the left and right channels.
SetVolume | Sets the sound volume.
Stop | Causes the sound buffer to stop playing.
WriteBuffer | Writes to a portion of the sound buffer from an application buffer holding audio data.

Resource management

Method | Description
AcquireResources | Allocates resources for a buffer created with the DSBCAPS_LOCDEFER flag.
Restore | Restores the memory allocation for a lost sound buffer.

Miscellaneous

Method | Description
SaveToFile | Saves the contents of the buffer to a wave file.

The following table shows which methods are supported for buffer objects obtained from an audiopath; that is, buffers created by a DirectMusic performance. Mix-in buffers accept sends from other buffers. All other buffers in the audiopath are sink-in buffers, which means that they accept data only from the synthesizer sink.

DirectSoundSecondaryBuffer8 method | Mix-in | Sink-in
AcquireResources |  |
GetCaps | Yes | Yes
GetCurrentPosition |  |
GetDirectSound3D Buffer | Yes | Yes
GetFormat | Yes | Yes
GetFrequency |  |
GetObjectInPath | Yes | Yes
GetPan | Yes | Yes
GetStatus | Yes | Yes
GetVolume | Yes | Yes
Play | Yes |
ReadBuffer |  |
Restore |  |
SaveToFile |  |
SetCurrentPosition |  |
SetFrequency |  |
SetFX | Yes | Yes
SetNotificationPositions |  |
SetPan | Yes | Yes
SetVolume | Yes | Yes
Stop | Yes |
WriteBuffer |  |

See Also

  • DirectSound Buffers
  • DirectSoundPrimaryBuffer8


DirectSoundSecondaryBuffer8.AcquireResources

The AcquireResources method allocates resources for a buffer created with the DSBCAPS_LOCDEFER flag.

Syntax

object.AcquireResources( _
  lFlags As Long, _
  lEffectsResults() As Long)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

lFlags

One or more flags from the CONST_DSBPLAYFLAGS enumeration, other than DSBPLAY_LOOPING, specifying how resources are to be allocated.

lEffectsResults

Array of variables of type Long that receives information about the effects associated with the buffer. The number of elements must be equal to the number of effects previously set on the buffer by using DirectSoundSecondaryBuffer8.SetFX. For each effect, one of the following constants from the CONST_DSOUNDFX enumeration is returned.

Value | Description
DSFXR_FAILED | No effect was created because resources weren't available.
DSFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSFXR_LOCSOFTWARE | Effect is instantiated in software.
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.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include the following:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDCALL
DSERR_INVALIDPARAM

Remarks

Normally, buffers created with DSBCAPS_LOCDEFER are not given resources until DirectSoundSecondaryBuffer8.Play is called. DirectSoundSecondaryBuffer8.AcquireResources can be used to allocate resources for deferred buffers. By doing so, the application can retrieve information about effects processing and set effect parameters before the buffer is played.

If the method fails, the value for each effect in lEffectsResults is either DSFXF_PRESENT or DSFXR_UNKNOWN. Check these values 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.

If AcquireResources 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.

Resources are released when playback is stopped.

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.


DirectSoundSecondaryBuffer8.GetCaps

The GetCaps method retrieves the capabilities of the buffer.

Syntax

object.GetCaps(caps As DSBCAPS)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

caps

DSBCAPS type that receives the capabilities of the buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The DSBCAPS type is similar to the DSBUFFERDESC type passed to the DirectSound8.CreateSoundBuffer method, with additional information. This information can include the buffer's location, either in hardware or software, and performance measures.

The flags in the lFlags member of the DSBCAPS type are the same flags used by the DSBUFFERDESC type. The only difference is that in the DSBCAPS type, either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE is specified according to the location of the buffer memory. In the DSBUFFERDESC type, these flags are optional and, depending on which flag is specified, force the buffer to be located in either hardware or software.


DirectSoundSecondaryBuffer8.GetCurrentPosition

The GetCurrentPosition method retrieves the position of the play and write cursors.

Syntax

object.GetCurrentPosition(cursors As DSCURSORS)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

cursors

DSCURSORS type that receives the offset of the play cursor and the write cursor, in bytes.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values.

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. For more information, see Play and Write Cursors.

See Also

  • DirectSoundSecondaryBuffer8.SetCurrentPosition


DirectSoundSecondaryBuffer8.GetDirectSound3DBuffer

The GetDirectSound3DBuffer method retrieves an object that can be used to manipulate 3-D effects on the buffer.

Syntax

object.GetDirectSound3DBuffer() As DirectSound3DBuffer8

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

Return Values

Returns a DirectSound3DBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to E_NOINTERFACE or DSERR_OUTOFMEMORY.

Remarks

The method succeeds only on buffers that have been created with the DSBCAPS_CTRL3D flag.


DirectSoundSecondaryBuffer8.GetFormat

The GetFormat method retrieves a description of the wave format of the buffer.

Syntax

object.GetFormat(format As WAVEFORMATEX)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

format

WAVEFORMATEX type that receives a description of the wave format of the buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSoundSecondaryBuffer8.GetFrequency

The GetFrequency method retrieves the sample frequency at which the buffer is playing.

Syntax

object.GetFrequency() As Long

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

Return Values

Returns the frequency in hertz, or samples per second.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The frequency value is in the range from DSBFREQUENCY_MIN (100) to DSBFREQUENCY_MAX (100,000).

See Also

  • DirectSoundSecondaryBuffer8.SetFrequency


DirectSoundSecondaryBuffer8.GetObjectInPath

The GetObjectInPath method retrieves an object in the audiopath of the buffer. Typically this method is used to retrieve an object representing a sound effect in a buffer or DMO.

Syntax

object.GetObjectinPath( _
  guidFX As String, _
  lIndex As Long, _
  iidInterface As String _
) As Unknown

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

guidFX

String that specifies the unique identifier for the effect class. See Remarks. Can be one of the members of the AUDIOSTRINGCONSTANTS module that begins with DSFX, or a GUID in string form. See Remarks.

lIndex

Value of type Long that specifies the index of the object within objects of that class in the path. This is the index of the object in the array of effects passed to DirectSoundSecondaryBuffer8.SetFX. This is not necessarily the actual position of the object in the effects chain, because some effects might not have been created.

iidInterface

String that specifies the unique identifier of the class of the returned object. Can be one of the members of the AUDIOSTRINGCONSTANTS module that begins with IID, or a GUID in string form. See Remarks.

Return Values

Returns an object representing the effect.

Error Codes

If the method fails, an error is raised. Possible values for Err.Number include DSERR_OBJECTNOTFOUND.

Remarks

The following table shows the standard effects objects that can be retrieved from a buffer on which the effects have been set.

guidFX | iidInterface | Returned object
DSFX_STANDARD_CHORUS | IID_DirectSoundFXChorus | DirectSoundFXChorus8
DSFX_STANDARD_COMPRESSOR | IID_DirectSoundFXCompressor | DirectSoundFXCompressor8
DSFX_STANDARD_DISTORTION | IID_DirectSoundFXDistortion | DirectSoundFXDistortion8
DSFX_STANDARD_ECHO | IID_DirectSoundFXEcho | DirectSoundFXEcho8
DSFX_STANDARD_FLANGER | IID_DirectSoundFXFlanger | DirectSoundFXFlanger8
DSFX_STANDARD_GARGLE | IID_DirectSoundFXGargle | DirectSoundFXGargle8
DSFX_STANDARD_I3DL2REVERB | IID_DirectSoundFXI3DL2REVERB | DirectSoundFXI3DL2Reverb8
DSFX_STANDARD_PARAMEQ | IID_DirectSoundFXParamEq | DirectSoundFXParamEq8
DSFX_STANDARD_WAVES_REVERB | IID_DirectSoundFXWavesReverb | DirectSoundFXWavesReverb8

Any DMO that has been set on a buffer by using DirectSoundSecondaryBuffer8.SetFX can be retrieved, even it has not been allocated resources.

See Also

  • DirectSoundSecondaryBuffer8.SetFX


DirectSoundSecondaryBuffer8.GetPan

The GetPan method retrieves the relative volume between the left and right audio channels.

Syntax

object.GetPan() As Long

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

Return Values

Returns the relative attenuation of the channels. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The return value is in hundredths of a decibel (dB), in the range of DSBPAN_LEFT (-10,000) to DSBPAN_RIGHT (10,000). The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER (0), meaning that both channels are at full volume (attenuated by 0 decibels).

At any setting other than DSBPAN_CENTER, one channel is at full volume and the other is attenuated. For example, a value of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume.

The pan control acts cumulatively with the volume control.

See Also

  • DirectSoundSecondaryBuffer8.GetVolume
  • DirectSoundSecondaryBuffer8.SetPan
  • DirectSoundSecondaryBuffer8.SetVolume


DirectSoundSecondaryBuffer8.GetStatus

The GetStatus method retrieves the status of the sound buffer.

Syntax

object.GetStatus() As CONST_DSBSTATUSFLAGS

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

Return Values

Returns the status of the sound buffer. The status can be zero or one or more of the constants of the CONST_DSBSTATUSFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectSoundSecondaryBuffer8.GetVolume

The GetVolume method retrieves the sound volume of the sound buffer.

Syntax

object.GetVolume() As Long

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

Return Values

Returns the attenuation of the buffer, in hundredths of a decibel. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The return value is in the range from DSBVOLUME_MAX through DSBVOLUME_MIN. These constants 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.

See Also

  • DirectSoundSecondaryBuffer8.GetPan
  • DirectSoundSecondaryBuffer8.SetVolume


DirectSoundSecondaryBuffer8.Play

The Play method causes the sound buffer to play from the play cursor.

Syntax

object.Play(flags As CONST_DSBPLAYFLAGS)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

flags

One or more of the constants of the CONST_DSBPLAYFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Before this method can be used the first time, the application must call the DirectSound8.SetCooperativeLevel method.

If the buffer specified in the method is already playing, the call succeeds and the buffer continues to play. However, the flags defined in the most recent call supersede the flags defined in previous calls.

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 can 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 | Nonlooping sound with least time left to play is terminated and the new sound plays on the released voice. | Nonlooping 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.

See Also

  • Dynamic Voice Management
  • Effect Parameters


DirectSoundSecondaryBuffer8.ReadBuffer

The ReadBuffer method reads a portion of the sound buffer and stores the data in an application buffer.

Most applications do not use this method, because secondary buffers automatically send their data to the primary buffer in response to the DirectSoundSecondaryBuffer8.Play method.

Syntax

object.ReadBuffer( _
  start As Long, _
  size As Long, _
  buffer As Any, _
  flags As CONST_DSBLOCKFLAGS)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

start

Offset, in bytes, from the start of the buffer to where the read begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR is specified in the flags parameter.

size

Size, in bytes, of the portion of the buffer to read. The sound buffer is conceptually circular, so this value can be greater than the number of bytes between start and the end of the buffer. This member is ignored if DSBLOCK_ENTIREBUFFER is specified in the flags parameter.

buffer

Variable that receives the data. Typically this is an array of bytes, and you pass the first element of the array.

flags

One of the constants of the CONST_DSBLOCKFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED


DirectSoundSecondaryBuffer8.Restore

The Restore method restores the memory allocation for a lost sound buffer.

Syntax

object.Restore()

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_PRIOLEVELNEEDED

Remarks

If the application does not have the input focus, DirectSoundSecondaryBuffer8.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.

Once 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 DirectSoundSecondaryBuffer8.WriteBuffer or DirectSoundSecondaryBuffer8.Play method. These methods return DSERR_BUFFERLOST to indicate a lost buffer. The DirectSoundSecondaryBuffer8.GetStatus method can also be used to retrieve the status of the sound buffer and test for the DSBSTATUS_BUFFERLOST flag.

See Also

  • Buffer Management
  • DirectSoundSecondaryBuffer8.GetStatus


DirectSoundSecondaryBuffer8.SaveToFile

The SaveToFile method saves the contents of the buffer to a wave file.

Syntax

object.SaveToFile(filename As String)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

filename

Name of the file where the sound buffer will be saved. If a file of that name exists, it is overwritten.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_INVALIDCALL
DSERR_INVALIDPARAM

See Also

  • Writing to a Wave File


DirectSoundSecondaryBuffer8.SetCurrentPosition

The SetCurrentPosition method sets the position of the play cursor.

Syntax

object.SetCurrentPosition(newPosition As Long)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

newPosition

Offset of the play cursor, in bytes, from the beginning of the buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values

DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

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 DirectSoundSecondaryBuffer8.Play method is called.

See Also

  • DirectSoundSecondaryBuffer8.GetCurrentPosition
  • Play and Write Cursors


DirectSoundSecondaryBuffer8.SetFrequency

The SetFrequency method sets the frequency at which the audio samples are played.

Syntax

object.SetFrequency(frequency As Long)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

frequency

New frequency, in hertz, at which to play the audio samples. The value must be in the range DSBFREQUENCY_MIN (100) to DSBFREQUENCY_MAX (100,000).

If the value is DSBFREQUENCY_ORIGINAL, the frequency is reset to the default value in the buffer format. This format is specified in the DirectSound8.CreateSoundBuffer method.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

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.

See Also

  • DirectSoundSecondaryBuffer8.GetFrequency


DirectSoundSecondaryBuffer8.SetFX

The SetFX method sets effects for sounds in the buffer. The buffer must not be playing.

Syntax

object.SetFX( _
  EffectsCount As Long, _
  Buffers() As DSEFFECTDESC, _
  lResultIDs() As Long)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

EffectsCount

Number of elements in Buffers and lResultIDs. Set to 0 to remove all effects from the buffer.

Buffers

Array of DSEFFECTDESC types that specify the effects to set.

lResultIDs

Array of Long variables, one for each effect in the Buffers array, that receive information about the result of the attempt to create the corresponding effect. Each element receives one of the following values from the CONST_DSOUNDFX enumeration.

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 nor 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.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_INVALIDCALL
DSERR_NOINTERFACE
DSERR_PRIOLEVELNEEDED

Remarks

For the method to succeed, the buffer must have been created with the DSBCAPS_CTRLFX flag and must not be playing.

If the method fails, the value for each effect in lEffectsResults is either DSFXF_PRESENT or DSFXR_UNKNOWN. Check these values to determine which effects caused the failure.

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 an audiopath, the audiopath must be inactive. See DirectMusicAudioPath8.Activate.

An effect must be set on a buffer before the effect object can be obtained. To obtain the effect object, use DirectSoundSecondaryBuffer8.GetObjectInPath.


DirectSoundSecondaryBuffer8.SetNotificationPositions

The SetNotificationPositions method sets the notification positions. During playback, whenever the play cursor reaches a specified offset, the associated event is signaled.

Syntax

object.SetNotificationPositions( _
  nElements As Long, _
  psa() As DSBPOSITIONNOTIFY)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

nElements

Number of elements in the psa array.

psa

Array of DSBPOSITIONNOTIFY types that specify the notification positions and associated events.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

See Also

  • Play Buffer Notification


DirectSoundSecondaryBuffer8.SetPan

The SetPan method specifies the relative volume between the left and right channels.

Syntax

object.SetPan(pan As Long)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

pan

Value that specifies the relative attenuation of the channels. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The value in pan is in hundredths of a decibel (dB), in the range of DSBPAN_LEFT (-10,000) to DSBPAN_RIGHT (10,000). The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER (0), meaning that both channels are at full volume (attenuated by 0 decibels).

At any setting other than DSBPAN_CENTER, one channel is at full volume and the other is attenuated. For example, a value of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume.

The pan control acts cumulatively with the volume control.

See Also

  • DirectSoundSecondaryBuffer8.GetPan
  • DirectSoundSecondaryBuffer8.SetVolume


DirectSoundSecondaryBuffer8.SetVolume

The SetVolume method sets the sound volume.

Syntax

object.SetVolume(volume As Long)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

volume

Attenuation of the volume, in hundredths of a decibel. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The value of volume must be in the range from DSBVOLUME_MAX through DSBVOLUME_MIN. These constants 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.

See Also

  • DirectSoundSecondaryBuffer8.GetVolume
  • DirectSoundSecondaryBuffer8.SetPan


DirectSoundSecondaryBuffer8.Stop

The Stop method causes the buffer to stop playing.

Syntax

object.Stop()

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values.

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The method sets the play cursor of the buffer to the sample that follows the last sample played. This means that when the DirectSoundSecondaryBuffer8.Play method is subsequently called on the buffer, it continues playing where it left off.


DirectSoundSecondaryBuffer8.WriteBuffer

The WriteBuffer method writes to a portion of the sound buffer from an application buffer holding audio data.

Syntax

object.WriteBuffer( _
  start As Long, _
  size As Long, _
  buffer As Any, _
  flags As CONST_DSBLOCKFLAGS)

Parts

object

Resolves to a DirectSoundSecondaryBuffer8 object.

start

Offset, in bytes, from the start of the buffer to where the read begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR constant is specified in the flags parameter.

size

Size, in bytes, of the portion of the buffer to write to. The sound buffer is conceptually circular, so this value can be greater than the number of bytes between start and the end of the buffer. This parameter is ignored if DSBLOCK_ENTIREBUFFER constant is specified in the flags parameter.

buffer

Variable that contains the data to write to the sound buffer. Typically this is an array of bytes, and you pass the first element of the array.

flags

One of the constants of the CONST_DSBLOCKFLAGS enumeration specifying how to write the data.

Error Codes

If the method Fails, an error is raised and Err.Number may be set to one of the following error codes.

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

See Also

  • Using Streaming Buffers


DirectSound Types

This section contains reference information for the following types used with DirectSound.

Structure | Description
D3DVECTOR | Defines a vector in three-dimensional space.
DS3DBUFFER | Describes the location, orientation, and motion of a 3-D sound buffer.
DS3DLISTENER | Describes 3-D global parameters and properties of the listener.
DSBCAPS | Describes the capabilities of a buffer object.
DSBPOSITIONNOTIFY | Describes a notification position.
DSBUFFERDESC | Describes the necessary characteristics of a new DirectSound buffer object.
DSCAPS | Describes the capabilities of a DirectSound device.
DSCBCAPS | Describes the capabilities of a capture buffer.
DSCBUFFERDESC | Describes a capture buffer.
DSCCAPS | Describes the capabilities of the capture device.
DSCURSORS | Returns the position of the play and write cursors
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 flanger effect.
DSFXGARGLE | Contains parameters for a gargle effect.
DSFXPARAMEQ | Contains parameters for a parametric equalizer effect.
DSFXWAVESREVERB | Contains parameters for a Waves reverb effect.
WAVEFORMATEX | Describes the format of waveform audio data.


D3DVECTOR

The D3DVECTOR type defines a vector in three-dimensional space.

Syntax

Type D3DVECTOR
    x As Single
    y As Single
    z As Single
End Type

Members

x, y, and z

Values describing the vector.


DS3DBUFFER

The DS3DBUFFER type describes the location, orientation, and motion of a 3-D sound buffer. This type is used with the DirectSound3DBuffer8.GetAllParameters and DirectSound3DBuffer8.SetAllParameters methods.

Syntax

Type DS3DBUFFER
  lConeOutsideVolume As Long
  lInsideConeAngle As Long
  lMode As CONST_DS3DMODEFLAGS
  lOutsideConeAngle As Long
  maxDistance As Single
  minDistance As Single
  vConeOrientation As D3DVECTOR
  vPosition As D3DVECTOR
  vVelocity As D3DVECTOR
End Type

Members

lConeOutsideVolume

Volume outside the sound cone.

lInsideConeAngle

Angle of the inner sound projection cone.

lMode

3-D sound processing mode to set. This is one of the constants of the CONST_DS3DMODEFLAGS enumeration.

lOutsideConeAngle

Angle of the outer sound projection cone.

maxDistance

Maximum distance.

minDistance

Minimum distance.

vConeOrientation

D3DVECTOR type that describes the orientation of the sound projection cone.

vPosition

D3DVECTOR type that describes the position of the buffer.

vVelocity

D3DVECTOR type that describes the velocity of the buffer.


DS3DLISTENER

The DS3DLISTENER type describes 3-D global parameters and properties of the listener. This type is used with the DirectSound3DListener8.GetAllParameters and DirectSound3DListener8.SetAllParameters methods.

Syntax

Type DS3DLISTENER
  distanceFactor As Single
  dopplerFactor As Single
  rolloffFactor As Single
  vOrientFront As D3DVECTOR
  vOrientTop As D3DVECTOR
  vPosition As D3DVECTOR
  vVelocity As D3DVECTOR
End Type

Members

distanceFactor

Number of meters in a unit of distance.

dopplerFactor

Factor applied to the Doppler shift for a buffer that has velocity.

rolloffFactor

Factor applied to the attenuation of sound over distance.

vOrientFront

D3DVECTOR type that describes the listener's front orientation.

vOrientTop

D3DVECTOR type that describes the listener's top orientation.

vPosition

D3DVECTOR type that describes the listener's position.

vVelocity

D3DVECTOR type that describes the listener's velocity.


DSBCAPS

The DSBCAPS type describes the capabilities of a buffer object. It is used in the DirectSoundPrimaryBuffer8.GetCaps and DirectSoundSecondaryBuffer8.GetCaps method.

Syntax

Type DSBCAPS
  lBufferBytes As Long
  lFlags As CONST_DSBCAPSFLAGS
  lPlayCpuOverhead As Long
  lUnlockTransferRate As Long
End Type

Members

lBufferBytes

Size of the buffer, in bytes.

lFlags

One of more of the constants of the CONST_DSBCAPSFLAGS enumeration.

lPlayCpuOverhead

Processing overhead, specified as a percentage of main processing cycles needed to mix this sound buffer. For hardware buffers, this value is zero, because the mixing is performed by the sound device. For software buffers, the value depends on the buffer format and the speed of the system processor.

lUnlockTransferRate

Rate, in kilobytes per second, at which data is transferred to the buffer memory.

Remarks

The DSBCAPS type contains information similar to that found in the DSBUFFERDESC type passed to the DirectSound8.CreateSoundBuffer method.

The lFlags member of the DSBCAPS type contains the same flags used by the DSBUFFERDESC type. The only difference is that in the DSBCAPS type, either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag is returned, according to the location of the buffer memory. In the DSBUFFERDESC type, these flags are optional and are used to force the buffer to be located in either hardware or software.


DSBPOSITIONNOTIFY

The DSBPOSITIONNOTIFY type describes a notification position. Used by the DirectSoundSecondaryBuffer8.SetNotificationPositions and DirectSoundCaptureBuffer8.SetNotificationPositions methods.

Syntax

Type DSBPOSITIONNOTIFY
  hEventNotify As Long
  lOffset As Long
End Type

Members

hEventNotify

Handle to the event to signal when the offset has been reached. Obtain this handle by using the DirectX8.CreateEvent method.

lOffset

Offset from the beginning of the buffer where the notify event is to be triggered, or DSBPN_OFFSETSTOP. See Remarks.

Remarks

The DSBPN_OFFSETSTOP value in the lOffset 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 DirectSoundSecondaryBuffer8.Stop or DirectSoundCaptureBuffer8.Stop method.

When you use DSBCAPS_LOCDEFER and DSBCAPS_NOTIFY along with a voice management flag, a sound that has notifications set, but not yet reached, may be terminated by the voice manager. In this event, the notification event will not occur.


DSBUFFERDESC

The DSBUFFERDESC type describes the necessary characteristics of a new DirectSound buffer object. This type is used by the DirectSound8.CreateSoundBuffer and DirectSound8.CreatePrimarySoundBuffer methods.

Syntax

Type DSBUFFERDESC
  fxFormat As WaveFormatEx
  guid3DAlgorithm As String
  lBufferBytes As Long
  lFlags As CONST_DSBCAPSFLAGS
End Type

Members

fxFormat

WAVEFORMATEX type that specifies the wave format of the buffer.

guid3DAlgorithm

Unique identifier of the two-speaker virtualization algorithm to be used by DirectSound when 3-D effects are not available in hardware. If the DSCAPS_CTRL3D flag is not set for the sound buffer, this value is ignored. If DSBCAPS_CTRL3D is not set in lFlags, this member must be GUID_DS3DALG_DEFAULT. See Remarks.

The following algorithm identifiers are defined in the AUDIOSTRINGCONSTANTS module.

Value | Description | Availability
GUID_DS3DALG_DEFAULT | DirectSound uses the default algorithm. The default algorithm may be based on a Control Panel setting. In most cases it is DS3DALG_NO_VIRTUALIZATION. On WDM drivers, if the user has selected surround sound in Control Panel, the sound is panned among the left, center, right, and surround channels. | Applies to software mixing only. Available on WDM or Vxd Drivers.
GUID_DS3DALG_NO_VIRTUALIZATION | 3-D effects are mapped onto normal 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 3-D filtering is not performed on this buffer. This is the most efficient software implementation, but provides no virtual 3-D audio effect. When the DS3DALG_NO_VIRTUALIZATION flag is specified, HRTF processing is not done. Because DS3DALG_NO_VIRTUALIZATION uses only normal stereo panning, a buffer created with this algorithm may be accelerated by a 2-D hardware voice if no free 3-D hardware voices are available. | Applies to software mixing only. Available on WDM or Vxd Drivers.
GUID_DS3DALG_HRTF_FULL | 3-D effects are processed with the high quality 3-D audio algorithm. This algorithm gives the highest quality 3-D 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.
GUID_DS3DALG_HRTF_LIGHT | 3-D effects are processed with the efficient 3-D audio algorithm. This algorithm gives a good 3-D audio effect, but uses fewer CPU cycles than DS3DALG_HRTF_FULL. See Remarks. | Applies to software mixing only. Available on Windows 98 Second Edition and later operating systems when using WDM drivers.

lBufferBytes

Size of the buffer, in bytes. This value must be 0 when creating a buffer with the DSBCAPS_PRIMARYBUFFER flag. For secondary buffers, the size must be in the range from 4 to &H0FFFFFFF (268,435,455).

lFlags

Flags specifying the capabilities of the buffer. Can be zero or one or more of the constants of the CONST_DSBCAPSFLAGS enumeration.

Remarks

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 returned in the lFlags member of the DSBCAPS type, where they indicate the actual location of the buffer.

The 3-D 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 3-D hardware voices are available, the buffer is then treated as a 2-D buffer, but with 3-D API 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:

  • If a free hardware 3-D voice is available, that 3-D hardware voice is used.
  • If no free hardware 3-D voices are available and a 2-D hardware voice is available, that 2-D hardware voice will be used. This is possible because the DS3DALG_NO_VIRTUALIZATION algorithm is a simple stereo pan algorithm
  • If no free 2-D or 3-D 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), the method succeeds but the sound buffer uses DS3DALG_NO_VIRTUALIZATION instead.


DSCAPS

The DSCAPS type describes the capabilities of a DirectSound device. Used by the DirectSound8.GetCaps method.

Syntax

Type DSCAPS
  lFlags As CONST_DSCAPSFLAGS
  lFreeHw3DAllBuffers As Long
  lFreeHw3DStaticBuffers As Long
  lFreeHw3DStreamingBuffers As Long
  lFreeHwMemBytes As Long
  lFreeHwMixingAllBuffers As Long
  lFreeHwMixingStaticBuffers As Long
  lFreeHwMixingStreamingBuffers As Long
  lMaxContigFreeHwMemBytes As Long
  lMaxHw3DAllBuffers As Long
  lMaxHw3DStaticBuffers As Long
  lMaxHw3DStreamingBuffers As Long
  lMaxHwMixingAllBuffers As Long
  lMaxHwMixingStaticBuffers As Long
  lMaxHwMixingStreamingBuffers As Long
  lMaxSecondarySampleRate As Long
  lMinSecondarySampleRate As Long
  lPlayCpuOverheadSwBuffers As Long
  lPrimaryBuffers As Long
  lReserved1 As Long
  lReserved2 As Long
  lTotalHwMemBytes As Long
  lUnlockTransferRateHwBuffers As Long
End Type

Members

lFlags

Device capabilities. Can be one or more of the constants from the CONST_DSCAPSFLAGS enumeration.

lFreeHw3DAllBuffers

Number of unallocated 3-D buffers.

lFreeHw3DStaticBuffers

Number of unallocated static 3-D buffers.

lFreeHw3DStreamingBuffers

Number of unallocated streaming 3-D buffers.

lFreeHwMemBytes

Size, in bytes, of the free memory on the sound card.

lFreeHwMixingAllBuffers

Number of unallocated buffers. On WDM drivers, this includes lFreeHw3DAllBuffers.

lFreeHwMixingStaticBuffers

Number of unallocated static buffers.

lFreeHwMixingStreamingBuffers

Number of unallocated streaming buffers.

lMaxContigFreeHwMemBytes

Size, in bytes, of the largest contiguous block of free memory on the sound card.

lMaxHw3DAllBuffers

Maximum number of 3-D buffers.

lMaxHw3DStaticBuffers

Maximum number of static 3-D buffers.

lMaxHw3DStreamingBuffers

Maximum number of streaming 3-D buffers.

lMaxHwMixingAllBuffers

Total number of buffers that can be mixed in hardware. This member can be less than the sum of lMaxHwMixingStaticBuffers and lMaxHwMixingStreamingBuffers. Resource tradeoffs frequently occur.

lMaxHwMixingStaticBuffers

Maximum number of static sound buffers.

lMaxHwMixingStreamingBuffers

Maximum number of streaming sound buffers.

lMaxSecondarySampleRate, lMinSecondarySampleRate

Maximum and minimum sample rate specifications that are supported by this device's hardware secondary sound buffers.

lPlayCpuOverheadSwBuffers

Description of the processing overhead, as a percentage of the central processing unit, needed to mix software buffers—those located in main system memory. This varies according to the bus type, the processor type, and the clock speed.

The unlock transfer rate for software buffers is zero because the data need not be transferred. Similarly, the play processing overhead for hardware buffers is 0 because the mixing is done by the sound device.

lPrimaryBuffers

Number of primary buffers supported. This value is always 1.

lReserved1, lReserved2

Reserved.

lTotalHwMemBytes

Size, in bytes, of the memory on the sound card that stores static sound buffers.

lUnlockTransferRateHwBuffers

Rate, in kilobytes per second, at which data can be transferred to hardware static sound buffers.

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.


DSCBCAPS

The DSCBCAPS type describes the capabilities of a capture buffer. Used by the DirectSoundCaptureBuffer8.GetCaps method.

Syntax

Type DSCBCAPS
  lBufferBytes As Long
  lFlags As CONST_DSCBCAPSFLAGS
  lReserved As Long
End Type

Members

lBufferBytes

Size, in bytes, of the capture buffer.

lFlags

Flag describing device capabilities. One of the constants of the CONST_DSCBCAPSFLAGS enumeration.

lReserved

Reserved.


DSCBUFFERDESC

The DSCBUFFERDESC type describes a capture buffer. Used by the DirectSoundCapture8.CreateCaptureBuffer method.

Syntax

Type DSCBUFFERDESC
  fxFormat As WAVEFORMATEX
  guid3DAlgorithm As String
  lBufferBytes As Long
  lFlags As CONST_DSCBCAPSFLAGS
End Type

Members

fxFormat

WAVEFORMATEX type containing the format in which to capture the data.

guid3DAlgorithm

Not used.

lBufferBytes

Size of capture buffer to create, in bytes.

lFlags

Flag specifying device capabilities. One of the constants of the CONST_DSCBCAPSFLAGS enumeration.


DSCCAPS

The DSCCAPS type describes the capabilities of the capture device. Used by the DirectSoundCapture8.GetCaps method.

Syntax

Type DSCCAPS
  lChannels As Long
  lFlags As CONST_DSCCAPSFLAGS
  lFormats As CONST_WAVEFORMATFLAGS
End Type

Members

lChannels

Number of channels supported by the device, where 1 is mono, 2 is stereo, and so on.

lFlags

Device capabilities. One of the members of the CONST_DSCCAPSFLAGS enumeration.

lFormats

Standard formats that are supported. One or more of the constants of the CONST_WAVEFORMATFLAGS enumeration.


DSCURSORS

The DSCURSORS type returns the position of the play and write cursors to the DirectSoundSecondaryBuffer8.GetCurrentPosition method. Also returns the position of the capture and read cursors to the DirectSoundCaptureBuffer8.GetCurrentPosition method.

Syntax

Type DSCURSORS
  lPlay As Long
  lWrite As Long
End Type

Members

lPlay

Play cursor in the play buffer or capture cursor in the capture buffer.

lWrite

Write cursor in the play buffer or read cursor in the capture buffer.

Remarks

Values are offsets from the start of the buffer, in bytes.

The cursor represented by lPlay is slightly ahead of the cursor represented by lWrite. The part of the buffer between the two is not ready for reading or writing. Applications can safely read data from a capture buffer or write data to a play buffer up to lWrite.

See Also

  • Capture Buffer Information
  • Play and Write Cursors


DSEFFECTDESC

The DSEFFECTDESC type describes an effect associated with a buffer.

Syntax

Type DSEFFECTDESC
  guidDSFXClass As String
  lFlags As Long
End Type

Members

guidDSFXClass

String that specifies the class identifier of the effect. You can use one of the following aliases for a standard effect, or a GUID.

DSFX_STANDARD_CHORUS
DSFX_STANDARD_COMPRESSOR
DSFX_STANDARD_DISTORTION
DSFX_STANDARD_ECHO
DSFX_STANDARD_FLANGER
DSFX_STANDARD_GARGLE
DSFX_STANDARD_I3DL2REVERB
DSFX_STANDARD_PARAMEQ
DSFX_STANDARD_WAVES_REVERB

lFlags

Flags that specify buffer creation options. Can be 0 or one of the following values from the CONST_DSOUNDFX enumeration.

Value | Description
DSFX_LOCHARDWARE | Effect must be in hardware. If the effect is not available in hardware, DirectSoundSecondaryBuffer8.SetFX raises an error. Because DirectX 8.1 does not support hardware acceleration of effects, 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. In DirectX 8.1, all effects are in software regardless of whether this flag is set.

Remarks

If lFlags is zero, the effect is placed in hardware if possible. If the hardware does not support the effect, software is used. If the effect is not available at all, the call to SetFX raises an error.

An effect of class DSFX_STANDARD_WAVES_REVERB can be set only on a buffer that has a 16-bit audio format.

See Also

  • Using Effects


DSFXI3DL2REVERB

The DSFXI3DL2REVERB type contains parameters for an I3DL2 (Interactive 3D Audio Level 2) reverberation effect.

Syntax

Type DSFXI3DL2REVERB
  fDecayHFRatio As Single
  fDecayTime As Single
  fDensity As Single
  fDiffusion As Single
  fHFReference As Single
  fReflectionsDelay As Single
  fReverbDelay As Single
  fRoomRolloffFactor As Single
  lReflections As Long
  lReverb As Long
  lRoom As Long
  lRoomHF As Long
End Type

Members

fDecayHFRatio

Ratio of the decay time at high frequencies to the decay time at low frequencies, in the range 0.1 to 2. The default value is 0.83.

fDecayTime

Decay time, in the range 0.1 to 20 seconds. The default value is 1.49 seconds.

fDensity

Modal density in the late reverberation decay. The default value is 100.0 percent. Minimum and maximum values are defined in the CONST_DSFX_I3DL2REVERB_DENSITY enumeration.

fDiffusion

Echo density in the late reverberation decay. The default value is 100.0 percent. Minimum and maximum values are defined in the CONST_DSFX_I3DL2REVERB_DIFFUSION enumeration.

fHFReference

Reference high frequency. The default value is 5000.0 Hz. Minimum and maximum values are defined in the CONST_DSFX_I3DL2REVERB_HFREFERENCE enumeration.

fReflectionsDelay

Delay time of the first reflection relative to the direct path, in the range 0 to 0.3 seconds. The default value is 0.007 seconds.

fReverbDelay

Time limit between the early reflections and the late reverberation relative to the time of the first reflection, in the range 0 to 0.1 seconds. The default value is 0.011 seconds.

fRoomRolloffFactor

Rolloff factor for the reflected signals. The default value is 0.0. Minimum and maximum values are defined in the CONST_DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR enumeration. The rolloff factor for the direct path is controlled by the DirectSound listener.

lReflections

Attenuation of early reflections relative to lRoom. The default value is -2602 mB. Minimum and maximum values are defined in the CONST_DSFX_I3DL2REVERB_REFLECTIONS enumeration.

lReverb

Attenuation of late reverberation relative to lRoom. The default value is -200 mB. Minimum and maximum values are defined in the CONST_DSFX_I3DL2REVERB_REVERB enumeration.

lRoom

Attenuation of the room effect. The default value is -1000 mB. Minimum and maximum values are defined in the CONST_DSFX_I3DL2REVERB_ROOM enumeration.

lRoomHF

Attenuation of the room high-frequency effect. The default value is -100 mB. Minimum and maximum values are defined in the CONST_DSFX_I3DL2REVERB_ROOMHF enumeration.


DSFXCHORUS

The DSFXCHORUS type contains parameters for a chorus effect.

Syntax

Type DSFXCHORUS
  fDelay As Single
  fDepth As Single
  fFeedback As Single
  fFrequency As Single
  fWetDryMix As Single
  lPhase As CONST_DSFX_PHASE
  lWaveform As CONST_DSFX_WAVE
End Type

Members

fDelay

Amount of time, in milliseconds, that the input is delayed before it is played back. The default value is 16. Maximum and minimum values are defined in the CONST_DSFX_DELAY enumeration.

fDepth

Percentage by which the delay time is modulated by the low-frequency oscillator, in percentage points. The default value is 10. Maximum and minimum values are defined in the CONST_DSFX_DEPTH enumeration.

fFeedback

Percentage of output signal to feed back into the effect's input. The default value is 25. Maximum and minimum values are defined in the CONST_DSFX_FEEDBACK enumeration.

fFrequency

Frequency of the LFO. The default value is 1.1. Maximum and minimum values are defined in the CONST_DSFX_FREQUENCY enumeration.

fWetDryMix

Ratio of wet (processed) signal to dry (unprocessed) signal. Minimum and maximum values are defined in the CONST_DSFX_WETDRY enumeration. The default value is 50.

lPhase

Phase differential between left and right LFOs. Allowable values are defined in the CONST_DSFX_PHASE enumeration. The default value is DSFX_PHASE_90.

lWaveform

Waveform of the LFO. By default, the waveform is a sine. Allowable values are defined in the CONST_DSFX_WAVE enumeration.

Remarks

Where the type of a member is an enumeration that defines minimum and maximum values, other Long values within this defined range are allowed. The enumeration is a convenience so that minimum and maximum values are easily accessible when writing code.

See Also

  • Chorus
  • DirectSoundFXChorus8


DSFXCOMPRESSOR

The DSFXCOMPRESSOR type contains parameters for a compression effect.

Syntax

Type DSFXCOMPRESSOR
  fAttack As Single
  fGain As Single
  fPreDelay As Single
  fRatio As Single
  fRelease As Single
  fThreshold As Single
End Type

Members

fAttack

Time before compression reaches its full value. The default value is 10 ms. Minimum and maximum values are defined in the CONST_DSFXCOMPRESSOR_ATTACK enumeration. See Remarks.

fGain

Output gain of signal after compression. The default value is 0 dB. Minimum and maximum values are defined in the CONST_DSFXCOMPRESSOR_GAIN enumeration.

fPreDelay

Time after lThreshold is reached before attack phase is started. The default value is 4 ms. Minimum and maximum values are defined in the CONST_DSFXCOMPRESSOR_PREDELAY enumeration.

fRatio

Compression ratio. The default value is 3, which means 3:1 compression. Minimum and maximum values are defined in the CONST_DSFXCOMPRESSOR_RATIO enumeration.

fRelease

Speed at which compression is stopped after input drops below lThreshold. The default value is 200 ms. Minimum and maximum values are defined in the CONST_DSFXCOMPRESSOR_RELEASE enumeration.

fThreshold

Point at which compression begins. The default value is -20 dB. Minimum and maximum values are defined in the CONST_DSFXCOMPRESSOR_THRESHOLD enumeration.

Remarks

For convenience, the minimum value for fAttack is defined as the integer 1 in the CONST_DSFXCOMPRESSOR_ATTACK enumeration. However, the actual minimum value, which is also the default, is 0.01.

See Also

  • Compression
  • DirectSoundFXCompressor8


DSFXDISTORTION

The DSFXDISTORTION type contains parameters for a distortion effect.

Syntax

Type DSFXDISTORTION
  fEdge As Single
  fGain As Single
  fPostEQBandwidth As Single
  fPostEQCenterFrequency As Single
  fPreLowpassCutoff As Single
End Type

Members

fEdge

Percentage of distortion intensity. The default value is 15. Minimum and maximum values are defined in the CONST_DSFXDISTORTION_EDGE enumeration.

fGain

Amount of signal change after distortion, in decibels. The default value is -18. Minimum and maximum values are defined in the CONST_DSFXDISTORTION_GAIN enumeration.

fPostEQBandwidth

Width of frequency band that determines range of harmonic content addition, in Hertz. The default value is 2400. Minimum and maximum values are defined in the CONST_DSFXDISTORTION_POSTEQBANDWIDTH enumeration.

fPostEQCenterFrequency

Center frequency of harmonic content addition, in Hertz. The default value is 2400. Minimum and maximum values are defined in the CONST_DSFXDISTORTION_POSTEQCENTERFREQUENCY enumeration.

fPreLowpassCUTOFF

Filter cutoff for high-frequency harmonics attenuation, in Hertz. The default value is 8000. Minimum and maximum values are defined in the CONST_DSFXDISTORTION_PRELOWPASSCUTOFF enumeration.

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 higher value, the parameter is set to the nearest supported value.

See Also

  • DirectSoundFXDistortion8
  • Distortion


DSFXECHO

The DSFXECHO type contains parameters for an echo effect.

Syntax

Type DSFXECHO
  fFeedback As Single
  fLeftDelay As Single
  fRightDelay As Single
  fWetDryMix as Single
  lPanDelay As CONST_DSFX_PANDELAY
End Type

Members

fFeedback

Percentage of output fed back into input. The default value is 50. Minimum and maximum values are defined in the CONST_DSFXECHO_FEEDBACK enumeration.

fLeftDelay

Delay for left channel. The default value is 500 ms. Minimum and maximum values are defined in the CONST_DSFX_LEFTRIGHTDELAY enumeration.

fRightDelay

Delay for right channel. The default value is 500 ms. Minimum and maximum values are defined in the CONST_DSFX_LEFTRIGHTDELAY enumeration.

fWetDryMix

Ratio of wet (processed) signal to dry (unprocessed) signal. Minimum and maximum values are defined in the CONST_DSFX_WETDRY enumeration. The default value is 50.

lPanDelay

Value that specifies whether to swap left and right delays with each successive echo. The default value is zero, meaning no swap. Allowable values are defined in the CONST_DSFX_PANDELAY enumeration.

Remarks

Where the type of a member is an enumeration that defines minimum and maximum values, other Long values within this defined range are allowed. The enumeration is a convenience so that minimum and maximum values are easily accessible when writing code.

See Also

  • DirectSoundFXEcho8
  • Echo


DSFXFLANGER

The DSFXFLANGER type contains parameters for a flanger effect.

Syntax

Type DSFXFLANGER
  fDelay As Single
  fDepth As Single
  fFeedback As Single
  fFrequency As Single
  fWetDryMix As Single
  lPhase As CONST_DSFX_PHASE
  lWaveform As CONST_DSFX_WAVE
End Type

Members

fDelay

Amount of time, in milliseconds, that the input is delayed before it is played back. The default value is 2. Maximum and minimum values are defined in the CONST_DSFX_FLANGER_DELAY enumeration.

fDepth

Percentage by which the delay time is modulated by the low-frequency oscillator, in percentage points. The default value is 100. Maximum and minimum values are defined in the CONST_DSFX_DEPTH enumeration.

fFeedback

Percentage of output signal to feed back into the effect's input. The default value is -50. Maximum and minimum values are defined in the CONST_DSFX_FEEDBACK enumeration.

fFrequency

Frequency of the LFO. The default value is 0.25. Maximum and minimum values are defined in the CONST_DSFX_FREQUENCY enumeration.

fWetDryMix

Ratio of wet (processed) signal to dry (unprocessed) signal. Minimum and maximum values are defined in the CONST_DSFX_WETDRY enumeration. The default value is 50.

lPhase

Phase differential between left and right LFOs. Allowable values are defined in the CONST_DSFX_PHASE enumeration. The default value is DSFX_PHASE_ZERO.

lWaveform

Waveform of the LFO. By default, the waveform is a sine. Allowable values are defined in the CONST_DSFX_WAVE enumeration.

Remarks

Where the type of a member is an enumeration that defines minimum and maximum values, other Long values within this defined range are allowed. The enumeration is a convenience so that minimum and maximum values are easily accessible when writing code.

See Also

  • DirectSoundFXFlanger8
  • Flange


DSFXGARGLE

The DSFXGARGLE type contains parameters for an amplitude modulation effect represented by a DirectSoundFXGargle8 object.

Syntax

Type DSFXGARGLE
  lRateHz As CONST_DSFXGARGLE_RATEHZ
  lWaveShape As CONST_DSFXGARGLE_WAVE
End Type

Members

lRateHz

Rate of modulation, in Hertz. Minimum and maximum values are defined in the CONST_DSFXGARGLE_RATEHZ enumeration. Any Long value within this range is valid. The default value is 20.

lWaveShape

Shape of the modulation wave. Allowable values are defined in the CONST_DSFXGARGLE_WAVE enumeration. The default value is DSFXGARGLE_WAVE_TRIANGLE

See Also

  • DirectSoundFXGargle8
  • Gargle


DSFXPARAMEQ

The DSFXPARAMEQ type contains parameters for a parametric equalizer effect.

Syntax

Type DSFXPARAMEQ
  fBandwidth As Single
  fCenter As Single
  fGain As Single
End Type

Members

fBandwidth

Bandwidth, in semitones. Minimum and maximum values are defined in the CONST_DSFXPARAMEQ_BANDWIDTH enumeration. The default value is 12.

fCenter

Center frequency, in hertz. Minimum and maximum values are defined in the CONST_DSFXPARAMEQ_CENTER enumeration. This value cannot exceed one-third of the frequency of the buffer. The default value is 8000.

fGain

Gain, in decibels. Minimum and maximum values are defined in the CONST_DSFXPARAMEQ_GAIN enumeration. The default value is 0.

Remarks

The value in fCenter cannot exceed one-third of the frequency of the buffer. If an attempt is made to set a higher value, the parameter is set to the nearest supported value.

See Also

  • DirectSoundFXParamEq8
  • Parametric Equalizer


DSFXWAVESREVERB

The DSFXWAVESREVERB type contains parameters for a Waves reverberation effect represented by a DirectSoundFXWavesReverb8 object.

Syntax

Type DSFXWavesReverb
  fHighFreqRTRatio As Long
  fInGain As Long
  fReverbMix As Long
  fReverbTime As Long
End Type

Members

fHighFreqRTRatio

In the range from 0.001 through 0.999. The default value is 0.001.

fInGain

Input gain of signal, in decibels (dB). The default value is 0.0. Maximum and minimum values are defined in the CONST_DSFX_WAVESREVERB_INGAIN enumeration.

fReverbMix

Reverb mix, in dB. The default value is 0. Maximum and minimum values are defined in the CONST_DSFX_WAVESREVERB_REVERBMIX enumeration.

fReverbTime

Reverb time, in milliseconds, in the range from 0.001 through 3000.0. The default value is 1000.0.


WAVEFORMATEX

The WAVEFORMATEX type describes the format of waveform audio data.

Syntax

Type WAVEFORMATEX
  lAvgBytesPerSec As Long
  lExtra As Long
  lSamplesPerSec As Long
  nBitsPerSample As Integer
  nBlockAlign As Integer
  nChannels As Integer
  nFormatTag As Integer
  nSize As Integer
End Type

Members

lAvgBytesPerSec

Required average data-transfer rate, in bytes per second, for the format. If nFormatTag is WAVE_FORMAT_PCM, nAvgBytesPerSec should be equal to the product of lSamplesPerSec and nBlockAlign.

lExtra

Not used; set to zero.

lSamplesPerSec

Sample rate, in samples per second (hertz), at which each channel should be played or recorded. If nFormatTag is WAVE_FORMAT_PCM, then common values for lSamplesPerSec are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz.

nBitsPerSample

Bits per sample. If nFormatTag is WAVE_FORMAT_PCM, nBitsPerSample should be 8 or 16.

nBlockAlign

Block alignment, in bytes. The block alignment is the minimum atomic unit of data for the nFormatTag format type. If nFormatTag is WAVE_FORMAT_PCM, nBlockAlign should be equal to the product of nChannels and nBitsPerSample divided by 8 (bits per byte).

Data written to and read from a buffer 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.

nChannels

Number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels.

nFormatTag

Waveform-audio format type. In DirectSound, this member must always be WAVE_FORMAT_PCM.

nSize

Size, in bytes, of extra format information. For WAVE_FORMAT_PCM formats, this member is ignored.


DirectSound Enumerations

DirectSound uses enumerations to group constants to take advantage of the statement completion feature of Visual Basic. The enumerations used in DirectSound are:

  • CONST_DS3DAPPLYFLAGS
  • CONST_DS3DMODEFLAGS
  • CONST_DSBCAPSFLAGS
  • CONST_DSBLOCKFLAGS
  • CONST_DSBPLAYFLAGS
  • CONST_DSBSTATUSFLAGS
  • CONST_DSCAPSFLAGS
  • CONST_DSCBCAPSFLAGS
  • CONST_DSCBLOCKFLAGS
  • CONST_DSCBSTARTFLAGS
  • CONST_DSCBSTATUSFLAGS
  • CONST_DSCCAPSFLAGS
  • CONST_DSFX_DELAY
  • CONST_DSFX_DEPTH
  • CONST_DSFXECHO_FEEDBACK
  • CONST_DSFX_FEEDBACK
  • CONST_DSFX_FLANGER_DELAY
  • CONST_DSFX_FREQUENCY
  • CONST_DSFX_I3DL2_ENVIRONMENT_PRESETS
  • CONST_DSFX_I3DL2REVERB_DENSITY
  • CONST_DSFX_I3DL2REVERB_DIFFUSION
  • CONST_DSFX_I3DL2REVERB_HFREFERENCE
  • CONST_DSFX_I3DL2REVERB_QUALITY
  • CONST_DSFX_I3DL2REVERB_REFLECTIONS
  • CONST_DSFX_I3DL2REVERB_REVERB
  • CONST_DSFX_I3DL2REVERB_ROOM
  • CONST_DSFX_I3DL2REVERB_ROOMHF
  • CONST_DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR
  • CONST_DSFX_LEFTRIGHTDELAY
  • CONST_DSFX_PANDELAY
  • CONST_DSFX_PHASE
  • CONST_DSFX_WAVE
  • CONST_DSFX_WAVESREVERB_INGAIN
  • CONST_DSFX_WAVESREVERB_REVERBMIX
  • CONST_DSFX_WETDRY
  • CONST_DSFXCOMPRESSOR_ATTACK
  • CONST_DSFXCOMPRESSOR_GAIN
  • CONST_DSFXCOMPRESSOR_PREDELAY
  • CONST_DSFXCOMPRESSOR_RATIO
  • CONST_DSFXCOMPRESSOR_RELEASE
  • CONST_DSFXCOMPRESSOR_THRESHOLD
  • CONST_DSFXDISTORTION_EDGE
  • CONST_DSFXDISTORTION_GAIN
  • CONST_DSFXDISTORTION_POSTEQBANDWIDTH
  • CONST_DSFXDISTORTION_POSTEQCENTERFREQUENCY
  • CONST_DSFXDISTORTION_PRELOWPASSCUTOFF
  • CONST_DSFXGARGLE_RATEHZ
  • CONST_DSFXGARGLE_WAVE
  • CONST_DSFXPARAMEQ_BANDWIDTH
  • CONST_DSFXPARAMEQ_CENTER
  • CONST_DSFXPARAMEQ_GAIN
  • CONST_DSOUND
  • CONST_DSOUNDERR
  • CONST_DSOUNDFX
  • CONST_DSSCLFLAGS
  • CONST_DSSPEAKERFLAGS
  • CONST_WAVEFORMATFLAGS


CONST_DS3DAPPLYFLAGS

The CONST_DS3DAPPLYFLAGS enumeration is used in parameters to various methods of the DirectSound3DBuffer8 and DirectSound3DListener8 classes. The members of this enumeration are used to specify when new settings should be applied.

Syntax

Enum CONST_DS3DAPPLYFLAGS
  DS3D_DEFERRED  = 1
  DS3D_IMMEDIATE = 0
End Enum

Constants

DS3D_DEFERRED

Settings are not applied until the application calls the DirectSound3DListener8.CommitDeferredSettings method.

DS3D_IMMEDIATE

Settings are applied immediately.

Remarks

When several parameter changes are made at once, it is more efficient to flag them as DS3D_DEFERRED and commit them with a single call.


CONST_DS3DMODEFLAGS

The CONST_DS3DMODEFLAGS enumeration is used by the DirectSound3DBuffer8.GetMode and DirectSound3DBuffer8.SetMode methods to set and retrieve the operation mode for 3-D sound processing.

Syntax

Enum CONST_DS3DMODEFLAGS
  DS3DMODE_DISABLE      = 2
  DS3DMODE_HEADRELATIVE = 1
  DS3DMODE_NORMAL       = 0
End Enum

Constants

DS3DMODE_DISABLE

Processing of 3-D 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 as the listener's parameters change, so that the relative parameters remain constant.

DS3DMODE_NORMAL

Sound parameters are relative to world space. This is the default mode.


CONST_DSBCAPSFLAGS

The CONST_DSBCAPSFLAGS enumeration is used in the DSBUFFERDESC types to specify desired capabilities of a new buffer and in DSBCAPS to describe capabilities of an existing buffer.

Syntax

Enum CONST_DSBCAPSFLAGS
  DSBCAPS_CTRL3D              =     16 (&H10)
  DSBCAPS_CTRLCHANNELVOLUME   =   1024 (&H400)
  DSBCAPS_CTRLFREQUENCY       =     32 (&H20)
  DSBCAPS_CTRLFX              =    512 (&H200)
  DSBCAPS_CTRLPAN             =     64 (&H40)
  DSBCAPS_CTRLPOSITIONNOTIFY  =    256
  DSBCAPS_CTRLVOLUME          =    128 (&H80)
  DSBCAPS_GETCURRENTPOSITION2 =  65536 (&H10000)
  DSBCAPS_GLOBALFOCUS         =  32768 (&H8000)
  DSBCAPS_LOCDEFER            = 262144 (&H40000)
  DSBCAPS_LOCHARDWARE         =      4
  DSBCAPS_LOCSOFTWARE         =      8
  DSBCAPS_MUTE3DATMAXDISTANCE = 131072 (&H20000)
  DSBCAPS_PRIMARYBUFFER       =      1
  DSBCAPS_STATIC              =      2
  DSBCAPS_STICKYFOCUS         =  16384 (&H4000)
End Enum

Constants

DSBCAPS_CTRL3D

The buffer supports 3-D control.

DSBCAPS_CTRLCHANNELVOLUME

The buffer supports setting channel volumes. This control is available only on mono buffers and cannot be combined with DSBCAPS_CTRL3D or DSBCAPS_CTRLPAN.

DSBCAPS_CTRLFREQUENCY

The buffer supports frequency control. Cannot be combined with DSBCAPS_CTRLFX.

DSBCAPS_CTRLFX

The buffer supports effects. Cannot be combined with DSBCAPS_CTRLFREQUENCY. The wave format must be an 8-bit or 16-bit PCM format with no more than two channels.

DSBCAPS_CTRLPAN

The buffer supports pan control.

DSBCAPS_CTRLPOSITIONNOTIFY

The buffer supports position notification. See Remarks.

DSBCAPS_CTRLVOLUME

The buffer supports volume control.

DSBCAPS_GETCURRENTPOSITION2

DirectSoundSecondaryBuffer8.GetCurrentPosition uses the new behavior of the play cursor. Always set this flag on secondary buffers.

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. However, if the focus is switched to a DirectSound application that uses the DSSCL_WRITEPRIMARY flag for its cooperative level, the global sounds from other applications are not audible.

DSBCAPS_LOCDEFER

The buffer is not assigned to hardware or software until it is played. This flag must be set for buffers that use voice management.

DSBCAPS_LOCHARDWARE

The buffer uses hardware mixing. If the device does not support hardware mixing or if the required hardware memory is not available, the call to the DirectSound8.CreateSoundBuffer method fails. The application must ensure that a mixing channel will be available for this buffer; this condition is not guaranteed.

DSBCAPS_LOCSOFTWARE

The buffer uses software mixing, even if DSBCAPS_STATIC is specified and hardware resources are available.

DSBCAPS_MUTE3DATMAXDISTANCE

The buffer stops playing when the maximum distance from the listener is exceeded, so that processor time is not wasted.

DSBCAPS_PRIMARYBUFFER

The buffer is a primary sound buffer. Cannot be combined with DSBCAPS_CTRLFX

DSBCAPS_STATIC

The buffer is placed in memory on the sound card, if available. This is not the same as DSBCAPS_LOCHARDWARE, which forces the buffer to be placed in memory, usually system memory, managed by the driver. Cannot be combined with DSBCAPS_CTRLFX.

DSBCAPS_STICKYFOCUS

The buffer has sticky focus. An application using DirectSound can continue to play such buffers if the user switches to an application that is not using DirectSound. In this situation, the application's normal buffers are muted, but the sticky focus buffers are still audible. This is useful for nongame applications when the user wants to hear the soundtrack while using another application. However, if the user switches to a DirectSound application, all sound buffers, both normal and sticky focus, in the previous application are muted.

Remarks

When a buffer is being created, 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. In the DSBCAPS type, the flag indicates the actual location of the buffer.

If you create a sound buffer with the DSBCAPS_CTRLPOSITIONNOTIFY flag but fail to set notifications, the behavior is undefined, and sounds may be played twice.

On VxD drivers, if a sound buffer is created with DSBCAPS_CTRLPOSITIONNOTIFY, the buffer is always a software buffer. Calling DirectSoundSecondaryBuffer8.Play with the DSBPLAY_LOCHARDWARE flag will fail when playing a buffer created with this flag set. With WDM drivers, a notification-enabled buffer can be in hardware, if hardware is available.


CONST_DSBLOCKFLAGS

The CONST_DSBLOCKFLAGS enumeration is used in the flags parameter of the DirectSoundSecondaryBuffer8.ReadBuffer and DirectSoundSecondaryBuffer8.WriteBuffer methods to specify what portion of the buffer is to be read or written to.

Syntax

Enum CONST_DSBLOCKFLAGS
  DSBLOCK_DEFAULT         = 0
  DSBLOCK_ENTIREBUFFER    = 2
  DSBLOCK_FROMWRITECURSOR = 1
End Enum

Constants

DSBLOCK_DEFAULT

Read from or write to the position specified in the start parameter.

DSBLOCK_ENTIREBUFFER

Read from or write to the entire buffer. The size parameter is ignored.

DSBLOCK_FROMWRITECURSOR

Read from or write to the write cursor. The start parameter is ignored.


CONST_DSBPLAYFLAGS

The CONST_DSBPLAYFLAGS enumeration is used in the flags parameter of the DirectSoundSecondaryBuffer8.Play method to specify how to play the buffer.

Syntax

Enum CONST_DSBPLAYFLAGS
  DSBPLAY_DEFAULT              =  0
  DSBPLAY_LOCHARDWARE          =  2
  DSBPLAY_LOCSOFTWARE          =  4
  DSBPLAY_LOOPING              =  1
  DSBPLAY_TERMINATEBY_DISTANCE = 16 (&H10)
  DSBPLAY_TERMINATEBY_PRIORITY = 32 (&H20)
  DSBPLAY_TERMINATEBY_TIME     =  8
End Enum

Constants

DSBPLAY_DEFAULT

Play from the play cursor to the end of the audio buffer.

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 DirectSoundsSecondaryBuffer8.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 DSBPLAY_TERMINATEBY flag.

DSBPLAY_LOOPING

Play from the play cursor to the end of the buffer, and restart at the beginning of the buffer. The buffer plays till explicitly stopped.

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.›

DSBPLAY_TERMINATEBY_TIME

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 is the one with the least time left to play.


CONST_DSBSTATUSFLAGS

The CONST_DSBSTATUSFLAGS enumeration describe the status of a buffer. Constants from this enumeration are returned by the DirectSoundSecondaryBuffer8.GetStatus method.

Syntax

Enum CONST_DSBSTATUSFLAGS
  DSBSTATUS_BUFFERLOST  =  2
  DSBSTATUS_LOCHARDWARE =  8
  DSBSTATUS_LOCSOFTWARE = 16 (&H10)
  DSBSTATUS_LOOPING     =  4
  DSBSTATUS_PLAYING     =  1
  DSBSTATUS_TERMINATED  = 32 (&H20)
End Enum

Constants

DSBSTATUS_BUFFERLOST

The buffer is lost and must be restored before it can be played or locked.

DSBSTATUS_LOCHARDWARE

The buffer is playing in hardware. Set only for buffers created with the DSBCAPS_LOCDEFER flag.

DSBSTATUS_LOCSOFTWARE

The buffer is playing in software. Set only for buffers created with the DSBCAPS_LOCDEFER flag.

DSBSTATUS_LOOPING

The buffer is being looped. If this value is not set, the buffer stops 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.

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.


CONST_DSCAPSFLAGS

The CONST_DSCAPSFLAGS enumeration is used in the lFlags member of the DSCAPS type to describe device capabilities.

Syntax

Enum CONST_DSCAPSFLAGS
  DSCAPS_CERTIFIED       =   64 (&H40)
  DSCAPS_CONTINUOUSRATE  =   16 (&H10)
  DSCAPS_EMULDRIVER      =   32 (&H20)
  DSCAPS_PRIMARY16BIT    =    8
  DSCAPS_PRIMARY8BIT     =    4
  DSCAPS_PRIMARYMONO     =    1
  DSCAPS_PRIMARYSTEREO   =    2
  DSCAPS_SECONDARY16BIT  = 2048 (&H800)
  DSCAPS_SECONDARY8BIT   = 1024 (&H400)
  DSCAPS_SECONDARYMONO   =  256 (&H100)
  DSCAPS_SECONDARYSTEREO =  512 (&H200)
End Enum

Constants

DSCAPS_CERTIFIED

This driver has been tested and certified by Microsoft. This flag is always set for WDM drivers, and should not be relied on.

DSCAPS_CONTINUOUSRATE

The device supports all sample rates between the lMinSecondarySampleRate and lMaxSecondarySampleRate member values. Typically, this means that the actual output rate is 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 primary sound buffers 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.


CONST_DSCBCAPSFLAGS

The CONST_DSCBCAPSFLAGS enumeration is used in the lFlags member of the DSCBCAPS type to specify device capabilities.

Syntax

Enum CONST_DSCBCAPSFLAGS
  DSCBCAPS_DEFAULT    =           0
  DSCBCAPS_WAVEMAPPED = -2147483648 (&H80000000)
End Enum

Constants

DSCBCAPS_WAVEMAPPED

The Win32 wave mapper is used for formats not supported by the device.


CONST_DSCBLOCKFLAGS

The CONST_DSCBLOCKFLAGS enumeration is used by the DirectSoundCaptureBuffer8.ReadBuffer and DirectSoundCaptureBuffer8.WriteBuffer methods to specify what is read from or written to the sound capture buffer.

Syntax

Enum CONST_DSCBLOCKFLAGS
  DSCBLOCK_DEFAULT      = 0
  DSCBLOCK_ENTIREBUFFER = 1
End Enum

Constants

DSCBLOCK_DEFAULT

Read from or write to the offset specified by the start parameter.

DSCBLOCK_ENTIREBUFFER

Read from or write to the entire buffer. The size parameter is ignored. If start is not zero, the data transfer begins at start and wraps around to the beginning of the buffer.


CONST_DSCBSTARTFLAGS

The CONST_DSCBSTARTFLAGS enumeration is used in the flags member of the DirectSoundCaptureBuffer8.Start method to specify the behavior of the capture buffer when capturing sound data.

Syntax

Enum CONST_DSCBSTARTFLAGS
  DSCBSTART_DEFAULT = 0
  DSCBSTART_LOOPING = 1
End Enum

Constants

DSCBSTART_DEFAULT

Capture stops when the end of the buffer is reached.

DSCBSTART_LOOPING

Once the end of the buffer is reached, capture restarts at the beginning and continues until explicitly stopped.


CONST_DSCBSTATUSFLAGS

The CONST_DSCBSTATUSFLAGS enumeration describes the status of a capture buffer and is returned by the DirectSoundCaptureBuffer8.GetStatus method.

Syntax

Enum CONST_DSCBSTATUSFLAGS
  DSCBSTATUS_CAPTURING = 1
  DSCBSTATUS_LOOPING   = 2
End Enum

Constants

DSCBSTATUS_CAPTURING

The capture buffer is capturing sound data.

DSCBSTATUS_LOOPING

The capture buffer is looping. This value is always returned in combination with DSCBSTATUS_CAPTURING.


CONST_DSCCAPSFLAGS

The CONST_DSCCAPSFLAGS enumeration is used in the lFlags member of the DSCCAPS type to describe capture device capabilities.

Syntax

Enum CONST_DSCCAPSFLAGS
  DSCCAPS_DEFAULT    =  0
  DSCCAPS_EMULDRIVER = 32 (&H20)
End Enum

Constants

DSCCAPS_DEFAULT

The device is capable of DirectSound capture.

DSCCAPS_EMULDRIVER

There is no capable driver for the device, so the standard wave audio functions are being used.


CONST_DSFX_DELAY

The CONST_DSFX_DELAY enumeration is used in the DSFXCHORUS type.

Syntax

Enum CONST_DSFX_DELAY
  DSFX_DELAY_MAX = 20 (&H14)
  DSFX_DELAY_MIN =  0
End Enum

Constants

DSFX_DELAY_MAX

Maximum value.

DSFX_DELAY_MIN

Minimum value.


CONST_DSFX_DEPTH

The CONST_DSFX_DEPTH enumeration is used in the DSFXCHORUS and DSFXFLANGER types.

Syntax

Enum CONST_DSFX_DEPTH
  DSFX_DEPTH_MAX  = 100 (&H64)
  DSFX_DEPTH_MIN  =   0
End Enum

Constants

DSFX_DEPTH_MAX

Maximum value.

DSFX_DEPTH_MIN

Minimum value.


CONST_DSFXECHO_FEEDBACK

The CONST_DSFXECHO_FEEDBACK enumeration is used in the DSFXECHO type.

Syntax

Enum CONST_DSFXECHO_FEEDBACK
  DSFXECHO_FEEDBACK_MAX = 100 (&H64)
  DSFXECHO_FEEDBACK_MIN =   0
End Enum

Constants

DSFXECHO_FEEDBACK_MAX

Maximum value.

DSFXECHO_FEEDBACK_MIN

Minimum value.


CONST_DSFX_FEEDBACK

The CONST_DSFX_FEEDBACK enumeration is used in the DSFXCHORUS and DSFXFLANGER types.

Syntax

Enum CONST_DSFX_FEEDBACK
  DSFX_FEEDBACK_MAX =  99 (&H63)
  DSFX_FEEDBACK_MIN = -99 (&HFFFFFF9D)
End Enum

Constants

DSFX_FEEDBACK_MAX

Maximum value.

DSFX_FEEDBACK_MIN

Minimum value.


CONST_DSFX_FLANGER_DELAY

The CONST_DSFX_FLANGER_DELAY enumeration is used in the DSFXFLANGER type.

Syntax

Enum CONST_DSFX_FLANGER_DELAY
  DSFX_FLANGER_DELAY_MAX =  4
  DSFX_FLANGER_DELAY_MIN =  0
End Enum

Constants

DSFX_FLANGER_DELAY_MAX

Maximum value.

DSFX_FLANGER_DELAY_MIN

Minimum value.


CONST_DSFX_FREQUENCY

The CONST_DSFX_FREQUENCY enumeration is used in the DSFXCHORUS and DSFXFLANGER types.

Syntax

Enum CONST_DSFX_FREQUENCY
  DSFX_FREQUENCY_MAX = 10
  DSFX_FREQUENCY_MIN = 0
End Enum

Constants

DSFX_FREQUENCY_MAX

Maximum value.

DSFX_FREQUENCY_MIN

Minimum value.


CONST_DSFX_I3DL2_ENVIRONMENT_PRESETS

The CONST_DSFX_I3DL2_ENVIRONMENT_PRESETS enumeration is used in methods of DirectSoundFXI3DL2Reverb8 to identify predefined sets of effect parameters.

Syntax

Enum CONST_DSFX_I3DL2_ENVIRONMENT_PRESETS
  DSFX_I3DL2_ENVIRONMENT_PRESET_ALLEY         = 15
  DSFX_I3DL2_ENVIRONMENT_PRESET_ARENA         = 10
  DSFX_I3DL2_ENVIRONMENT_PRESET_AUDITORIUM    =  7
  DSFX_I3DL2_ENVIRONMENT_PRESET_BATHROOM      =  4
  DSFX_I3DL2_ENVIRONMENT_PRESET_CARPETEDHALLWAY=12
  DSFX_I3DL2_ENVIRONMENT_PRESET_CAVE          =  9
  DSFX_I3DL2_ENVIRONMENT_PRESET_CITY          = 17 (&H11)
  DSFX_I3DL2_ENVIRONMENT_PRESET_CONCERTHALL   =  8
  DSFX_I3DL2_ENVIRONMENT_PRESET_DEFAULT       =  0
  DSFX_I3DL2_ENVIRONMENT_PRESET_FOREST        = 16 (&H10)
  DSFX_I3DL2_ENVIRONMENT_PRESET_GENERIC       =  1
  DSFX_I3DL2_ENVIRONMENT_PRESET_HALLWAY       = 13
  DSFX_I3DL2_ENVIRONMENT_PRESET_HANGAR        = 11
  DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEHALL     = 28 (&H1C)
  DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEROOM     = 26 (&H1A)
  DSFX_I3DL2_ENVIRONMENT_PRESET_LIVINGROOM    =  5
  DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMHALL    = 27 (&H1B)
  DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMROOM    = 25 (&H19)
  DSFX_I3DL2_ENVIRONMENT_PRESET_MOUNTAINS     = 18 (&H12)
  DSFX_I3DL2_ENVIRONMENT_PRESET_PADDEDCELL    =  2
  DSFX_I3DL2_ENVIRONMENT_PRESET_PARKINGLOT    = 21 (&H15)
  DSFX_I3DL2_ENVIRONMENT_PRESET_PLAIN         = 20 (&H14)
  DSFX_I3DL2_ENVIRONMENT_PRESET_PLATE         = 29 (&H1D)
  DSFX_I3DL2_ENVIRONMENT_PRESET_QUARRY        = 19 (&H13)
  DSFX_I3DL2_ENVIRONMENT_PRESET_ROOM          =  3
  DSFX_I3DL2_ENVIRONMENT_PRESET_SEWERPIPE     = 22 (&H16)
  DSFX_I3DL2_ENVIRONMENT_PRESET_SMALLROOM     = 24 (&H18)
  DSFX_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR = 14
  DSFX_I3DL2_ENVIRONMENT_PRESET_STONEROOM     =  6
  DSFX_I3DL2_ENVIRONMENT_PRESET_UNDERWATER    = 23 (&H17)
End Enum

Constants

See Dsound.h for a list of values associated with each preset constant.


CONST_DSFX_I3DL2REVERB_DENSITY

The CONST_DSFX_I3DL2REVERB_DENSITY enumeration is used in the fDensity member of the DSFXI3DL2REVERB type.

Syntax

Enum CONST_DSFX_I3DL2REVERB_DENSITY
  DSFX_I3DL2REVERB_DENSITY_DEFAULT = 100 (&H64)
  DSFX_I3DL2REVERB_DENSITY_MAX     = 100 (&H64)
  DSFX_I3DL2REVERB_DENSITY_MIN     =   0
End Enum

Constants

DSFX_I3DL2REVERB_DENSITY_DEFAULT

Default value.

DSFX_I3DL2REVERB_DENSITY_MAX

Maximum value.

DSFX_I3DL2REVERB_DENSITY_MIN

Minimum value.


CONST_DSFX_I3DL2REVERB_DIFFUSION

The CONST_DSFX_I3DL2REVERB_DIFFUSION enumeration is used in the fDiffusion member of the DSFXI3DL2REVERB type.

Syntax

Enum CONST_DSFX_I3DL2REVERB_DIFFUSION
  DSFX_I3DL2REVERB_DIFFUSION_DEFAULT = 100 (&H64)
  DSFX_I3DL2REVERB_DIFFUSION_MAX     = 100 (&H64)
  DSFX_I3DL2REVERB_DIFFUSION_MIN     =   0
End Enum

Constants

DSFX_I3DL2REVERB_DIFFUSION_DEFAULT

Default value.

DSFX_I3DL2REVERB_DIFFUSION_MAX

Maximum value.

DSFX_I3DL2REVERB_DIFFUSION_MIN

Minimum value.


CONST_DSFX_I3DL2REVERB_HFREFERENCE

The CONST_DSFX_I3DL2REVERB_HFREFERENCE enumeration is used in the fHFReference member of the DSFXI3DL2REVERB type.

Syntax

Enum CONST_DSFX_I3DL2REVERB_HFREFERENCE
  DSFX_I3DL2REVERB_HFREFERENCE_DEFAULT =  5000 (&H1388)
  DSFX_I3DL2REVERB_HFREFERENCE_MAX     = 20000 (&H4E20)
  DSFX_I3DL2REVERB_HFREFERENCE_MIN     =    20 (&H14)
End Enum

Constants

DSFX_I3DL2REVERB_HFREFERENCE_DEFAULT

Default value.

DSFX_I3DL2REVERB_HFREFERENCE_MAX

Maximum value.

DSFX_I3DL2REVERB_HFREFERENCE_MIN

Minimum value.


CONST_DSFX_I3DL2REVERB_QUALITY

The CONST_DSFX_I3DL2REVERB_QUALITY enumeration is used in the lQuality parameter of the DirectSoundFXI3DL2Reverb8.SetQuality method.

Syntax

Enum CONST_DSFX_I3DL2REVERB_REFLECTIONS
  DSFX_I3DL2REVERB_QUALITY_DEFAULT = 2
  DSFX_I3DL2REVERB_QUALITY_MAX     = 3
  DSFX_I3DL2REVERB_QUALITY_MIN     = 0
End Enum

Constants

DSFX_I3DL2REVERB_QUALITY_DEFAULT

Default value.

DSFX_I3DL2REVERB_QUALITY_MAX

Maximum value.

DSFX_I3DL2REVERB_QUALITY_MIN

Minimum value.


CONST_DSFX_I3DL2REVERB_REFLECTIONS

The CONST_DSFX_I3DL2REVERB_REFLECTIONS enumeration is used in the lReflectionsDelay member of the DSFXI3DL2REVERB type.

Syntax

Enum CONST_DSFX_I3DL2REVERB_REFLECTIONS
  DSFX_I3DL2REVERB_REFLECTIONS_DEFAULT = -10000 (&HFFFFD8F0)
  DSFX_I3DL2REVERB_REFLECTIONS_MAX     =   1000 (&H3E8)
  DSFX_I3DL2REVERB_REFLECTIONS_MIN     = -10000 (&HFFFFD8F0)
End Enum

Constants

DSFX_I3DL2REVERB_REFLECTIONS_DEFAULT

Default value.

DSFX_I3DL2REVERB_REFLECTIONS_MAX

Maximum value.

DSFX_I3DL2REVERB_REFLECTIONS_MIN

Minimum value.


CONST_DSFX_I3DL2REVERB_REVERB

The CONST_DSFX_I3DL2REVERB_REVERB enumeration is used in the lReverbDelay member of the DSFXI3DL2REVERB type.

Syntax

Enum CONST_DSFX_I3DL2REVERB_REVERB
  DSFX_I3DL2REVERB_REVERB_DEFAULT = -10000 (&HFFFFD8F0)
  DSFX_I3DL2REVERB_REVERB_MAX     =   2000 (&H7D0)
  DSFX_I3DL2REVERB_REVERB_MIN     = -10000 (&HFFFFD8F0)
End Enum

Constants

DSFX_I3DL2REVERB_REVERB_DEFAULT

Default value.

DSFX_I3DL2REVERB_REVERB_MAX

Maximum value.

DSFX_I3DL2REVERB_REVERB_MIN

Minimum value.


CONST_DSFX_I3DL2REVERB_ROOM

The CONST_DSFX_I3DL2REVERB_ROOM enumeration is used in the lRoom member of the DSFXI3DL2REVERB type.

Syntax

Enum CONST_DSFX_I3DL2REVERB_ROOM
  DSFX_I3DL2REVERB_ROOM_DEFAULT = -10000 (&HFFFFD8F0)
  DSFX_I3DL2REVERB_ROOM_MAX     =      0
  DSFX_I3DL2REVERB_ROOM_MIN     = -10000 (&HFFFFD8F0)
End Enum

Constants

DSFX_I3DL2REVERB_ROOM_DEFAULT

Default value.

DSFX_I3DL2REVERB_ROOM_MAX

Maximum value.

DSFX_I3DL2REVERB_ROOM_MIN

Minimum value.


CONST_DSFX_I3DL2REVERB_ROOMHF

The CONST_DSFX_I3DL2REVERB_ROOMHF enumeration is used in the lRoomHF member of the DSFXI3DL2REVERB type.

Syntax

Enum CONST_DSFX_I3DL2REVERB_ROOMHF
  DSFX_I3DL2REVERB_ROOMHF_DEFAULT =      0
  DSFX_I3DL2REVERB_ROOMHF_MAX     =      0
  DSFX_I3DL2REVERB_ROOMHF_MIN     = -10000 (&HFFFFD8F0)
End Enum

Constants

DSFX_I3DL2REVERB_ROOMHF_DEFAULT

Default value.

DSFX_I3DL2REVERB_ROOMHF_MAX

Maximum value.

DSFX_I3DL2REVERB_ROOMHF_MIN

Minimum value.


CONST_DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR

The CONST_DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR enumeration is used in the lRoomRolloffFactor member of the DSFXI3DL2REVERB type.

Syntax

Enum CONST_DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR
  DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_DEFAULT = 0
  DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MAX     = 1
  DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MIN     = 0
End Enum

Constants

DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_DEFAULT

Default value.

DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MAX

Maximum value.

DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MIN

Minimum value.


CONST_DSFX_LEFTRIGHTDELAY

The CONST_DSFX_LEFTRIGHTDELAY enumeration is used in the DSFXECHO type.

Syntax

Enum CONST_DSFX_LEFTRIGHTDELAY
  DSFX_LEFTRIGHTDELAY_MAX = 2000 (&H7D0)
  DSFX_LEFTRIGHTDELAY_MIN =    1
End Enum

Constants

DSFX_LEFTRIGHTDELAY_MAX

Maximum value.

DSFX_LEFTRIGHTDELAY_MIN

Minimum value.


CONST_DSFX_PANDELAY

The CONST_DSFX_PANDELAY enumeration is used in the DSFXECHO type.

Syntax

Enum CONST_DSFX_PANDELAY
  DSFX_PANDELAY_MAX = 1
  DSFX_PANDELAY_MIN = 0
End Enum

Constants

DSFX_PANDELAY_MAX

Maximum value; equivalent to True.

DSFX_PANDELAY_MIN

Minimum value; equivalent to False.


CONST_DSFX_PHASE

The CONST_DSFX_PHASE enumeration is used in the DSFXCHORUS and DSFXFLANGER types.

Syntax

Enum CONST_DSFX_PHASE
  DSFX_PHASE_180     = 4
  DSFX_PHASE_90      = 3
  DSFX_PHASE_MAX     = 4
  DSFX_PHASE_MIN     = 0
  DSFX_PHASE_NEG_180 = 0
  DSFX_PHASE_NEG_90  = 1
  DSFX_PHASE_ZERO    = 2
End Enum

Constants

DSFX_PHASE_180

Descending midpoint of the waveform.

DSFX_PHASE_90

Top of the waveform.

DSFX_PHASE_MAX

Maximum value.

DSFX_PHASE_MIN

Minimum value.

DSFX_PHASE_NEG_180

Ascending midpoint of the waveform.

DSFX_PHASE_NEG_90

Bottom of the waveform.

DSFX_PHASE_ZERO

Ascending midpoint of the waveform.


CONST_DSFX_WAVE

The CONST_DSFX_WAVE enumeration is used in the DSFXCHORUS and DSFXFLANGER types.

Syntax

Enum CONST_DSFX_WAVE
  DSFX_WAVE_SIN      = 1
  DSFX_WAVE_TRIANGLE = 0
End Enum

Constants

DSFX_WAVE_SIN

Sine wave.

DSFX_WAVE_TRIANGLE

Triangular wave.


CONST_DSFX_WAVESREVERB_INGAIN

The CONST_DSFX_WAVESREVERB_INGAIN enumeration is used in the fInGain member of the DSFXWAVESREVERB type.

Syntax

Enum CONST_DSFX_WAVESREVERB_INGAIN
  DSFX_WAVESREVERB_INGAIN_MAX =   0
  DSFX_WAVESREVERB_INGAIN_MIN = -96 (&HFFFFFFA0)
End Enum

Constants

DSFX_WAVESREVERB_INGAIN_MAX

Maximum value.

DSFX_WAVESREVERB_INGAIN_MIN

Minimum value.


CONST_DSFX_WAVESREVERB_REVERBMIX

The CONST_DSFX_WAVESREVERB_REVERBMIX enumeration is used in the fReverbMix member of the DSFXWAVESREVERB type.

Syntax

Enum CONST_DSFX_WAVESREVERB_REVERBMIX
  DSFX_WAVESREVERB_REVERBMIX_MAX =   0
  DSFX_WAVESREVERB_REVERBMIX_MIN = -96 (&HFFFFFFA0)
End Enum

Constants

DSFX_WAVESREVERB_REVERBMIX_MAX

Maximum value.

DSFX_WAVESREVERB_REVERBMIX_MIN

Minimum value.


CONST_DSFX_WETDRY

The CONST_DSFX_WETDRY enumeration is used in the DSFXCHORUS, DSFXECHO, and DSFXFLANGER types.

Syntax

Enum CONST_DSFX_WETDRY
  DSFX_WETDRYMIX_MAX = 100 (&H64)
  DSFX_WETDRYMIX_MIN =   0
End Enum

Constants

DSFX_WETDRYMIX_MAX

Maximum value.

DSFX_WETDRYMIX_MIN

Minimum value.


CONST_DSFXCOMPRESSOR_ATTACK

The CONST_DSFXCOMPRESSOR_ATTACK enumeration is used in the fAttack member of the DSFXCOMPRESSOR type.

Syntax

Enum CONST_DSFXCOMPRESSOR_ATTACK
  DSFXCOMPRESSOR_ATTACK_MAX = 500 (&H1F4)
  DSFXCOMPRESSOR_ATTACK_MIN =   1
End Enum

Constants

DSFXCOMPRESSOR_ATTACK_MAX

Maximum value.

DSFXCOMPRESSOR_ATTACK_MIN

Minimum value.


CONST_DSFXCOMPRESSOR_GAIN

The CONST_DSFXCOMPRESSOR_GAIN enumeration is used in the fGain member of the DSFXCOMPRESSOR type.

Syntax

Enum CONST_DSFXCOMPRESSOR_GAIN
  DSFXCOMPRESSOR_GAIN_MAX =  60 (&H3C)
  DSFXCOMPRESSOR_GAIN_MIN = -60 (&HFFFFFFC4)
End Enum

Constants

DSFXCOMPRESSOR_GAIN_MAX

Maximum value.

DSFXCOMPRESSOR_GAIN_MIN

Minimum value.


CONST_DSFXCOMPRESSOR_PREDELAY

The CONST_DSFXCOMPRESSOR_PREDELAY enumeration is used in the fPreDelay member of the DSFXCOMPRESSOR type.

Syntax

Enum CONST_DSFXCOMPRESSOR_PREDELAY
  DSFXCOMPRESSOR_PREDELAY_MAX = 4
  DSFXCOMPRESSOR_PREDELAY_MIN = 0
End Enum

Constants

DSFXCOMPRESSOR_PREDELAY_MAX

Maximum value.

DSFXCOMPRESSOR_PREDELAY_MIN

Minimum value.


CONST_DSFXCOMPRESSOR_RATIO

The CONST_DSFXCOMPRESSOR_RATIO enumeration is used in the fRatio member of the DSFXCOMPRESSOR type.

Syntax

Enum CONST_DSFXCOMPRESSOR_RATIO
  DSFXCOMPRESSOR_RATIO_MAX = 100 (&H64)
  DSFXCOMPRESSOR_RATIO_MIN =   1
End Enum

Constants

DSFXCOMPRESSOR_RATIO_MAX

Maximum value.

DSFXCOMPRESSOR_RATIO_MIN

Minimum value.


CONST_DSFXCOMPRESSOR_RELEASE

The CONST_DSFXCOMPRESSOR_RELEASE enumeration is used in the fRelease member of the DSFXCOMPRESSOR type.

Syntax

Enum CONST_DSFXCOMPRESSOR_RELEASE
  DSFXCOMPRESSOR_RELEASE_MAX = 3000 (&HBB8)
  DSFXCOMPRESSOR_RELEASE_MIN =   50 (&H32)
End Enum

Constants

DSFXCOMPRESSOR_RELEASE_MAX

Maximum value.

DSFXCOMPRESSOR_RELEASE_MIN

Minimum value.


CONST_DSFXCOMPRESSOR_THRESHOLD

The CONST_DSFXCOMPRESSOR_THRESHOLD enumeration is used in the fThreshold member of the DSFXCOMPRESSOR type.

Syntax

Enum CONST_DSFXCOMPRESSOR_THRESHOLD
  DSFXCOMPRESSOR_THRESHOLD_MAX =   0
  DSFXCOMPRESSOR_THRESHOLD_MIN = -60 (&HFFFFFFC4)
End Enum

Constants

DSFXCOMPRESSOR_THRESHOLD_MAX

Maximum value.

DSFXCOMPRESSOR_THRESHOLD_MIN

Minimum value.


CONST_DSFXDISTORTION_EDGE

The CONST_DSFXDISTORTION_EDGE enumeration is used in the DSFXDISTORTION type.

Syntax

Enum CONST_DSFXDISTORTION_EDGE
  DSFXDISTORTION_EDGE_MAX = 100 (&H64)
  DSFXDISTORTION_EDGE_MIN =   0
End Enum

Constants

DSFXDISTORTION_EDGE_MAX

Maximum value.

DSFXDISTORTION_EDGE_MIN

Minimum value.


CONST_DSFXDISTORTION_GAIN

The CONST_DSFXDISTORTION_GAIN enumeration is used in the DSFXDISTORTION type.

Syntax

Enum CONST_DSFXDISTORTION_GAIN
  DSFXDISTORTION_GAIN_MAX =   0
  DSFXDISTORTION_GAIN_MIN = -60 (&HFFFFFFC4)
End Enum

Constants

DSFXDISTORTION_GAIN_MAX

Maximum value.

DSFXDISTORTION_GAIN_MIN

Minimum value.


CONST_DSFXDISTORTION_POSTEQBANDWIDTH

The CONST_DSFXDISTORTION_POSTEQBANDWIDTH enumeration is used in the DSFXDISTORTION type.

Syntax

Enum CONST_DSFXDISTORTION_POSTEQBANDWIDTH
  DSFXDISTORTION_POSTEQBANDWIDTH_MAX = 8000 (&H1F40)
  DSFXDISTORTION_POSTEQBANDWIDTH_MIN =  100 (&H64)
End Enum

Constants

DSFXDISTORTION_POSTEQBANDWIDTH_MAX

Maximum value.

DSFXDISTORTION_POSTEQBANDWIDTH_MIN

Maximum value.


CONST_DSFXDISTORTION_POSTEQCENTERFREQUENCY

The CONST_DSFXDISTORTION_POSTEQCENTERFREQUENCY enumeration is used in the DSFXDISTORTION type.

Syntax

Enum CONST_DSFXDISTORTION_POSTEQCENTERFREQUENCY
  DSFXDISTORTION_POSTEQCENTERFREQUENCY_MAX = 8000 (&H1F40)
  DSFXDISTORTION_POSTEQCENTERFREQUENCY_MIN =  100 (&H64)
End Enum

Constants

DSFXDISTORTION_POSTEQCENTERFREQUENCY_MAX

Maximum value.

DSFXDISTORTION_POSTEQCENTERFREQUENCY_MIN

Minimum value.


CONST_DSFXDISTORTION_PRELOWPASSCUTOFF

The CONST_DSFXDISTORTION_PRELOWPASSCUTOFF enumeration is used in the DSFXDISTORTION type.

Syntax

Enum CONST_DSFXDISTORTION_PRELOWPASSCUTOFF
  DSFXDISTORTION_PRELOWPASSCUTOFF_MAX = 8000 (&H1F40)
  DSFXDISTORTION_PRELOWPASSCUTOFF_MIN =  100 (&H64)
End Enum

Constants

DSFXDISTORTION_PRELOWPASSCUTOFF_MAX

Maximum value.

DSFXDISTORTION_PRELOWPASSCUTOFF_MIN

Minimum value.


CONST_DSFXGARGLE_RATEHZ

The CONST_DSFXGARGLE_RATEHZ enumeration is used in the DSFXGARGLE type.

Syntax

Enum CONST_DSFXGARGLE_RATEHZ
  DSFXGARGLE_RATEHZ_MAX = 1000 (&H3E8)
  DSFXGARGLE_RATEHZ_MIN =    1
End Enum

Constants

DSFXGARGLE_RATEHZ_MAX

Maximum value.

DSFXGARGLE_RATEHZ_MIN

Minimum value.


CONST_DSFXGARGLE_WAVE

The CONST_DSFXGARGLE_WAVE enumeration is used in the DSFXGARGLE type.

Syntax

Enum CONST_DSFXGARGLE_WAVE
  DSFXGARGLE_WAVE_SQUARE   = 1
  DSFXGARGLE_WAVE_TRIANGLE = 0
End Enum

Constants

DSFXGARGLE_WAVE_TRIANGLE

Triangular wave.

DSFXGARGLE_WAVE_SQUARE

Square wave.


CONST_DSFXPARAMEQ_BANDWIDTH

The CONST_DSFXPARAMEQ_BANDWIDTH enumeration is used in the fBandwidth member of the DSFXPARAMEQ type.

Syntax

Enum CONST_DSFXPARAMEQ_BANDWIDTH
  DSFXPARAMEQ_BANDWIDTH_MAX = 36 (&H24)
  DSFXPARAMEQ_BANDWIDTH_MIN =  1
End Enum

Constants

DSFXPARAMEQ_BANDWIDTH_MAX

Maximum value.

DSFXPARAMEQ_BANDWIDTH_MIN

Minimum value.


CONST_DSFXPARAMEQ_CENTER

The CONST_DSFXPARAMEQ_CENTER enumeration is used in the fCenter member of the DSFXPARAMEQ type.

Syntax

Enum CONST_DSFXPARAMEQ_CENTER
  DSFXPARAMEQ_CENTER_MAX = 16000 (&H3E80)
  DSFXPARAMEQ_CENTER_MIN =    80 (&H50)
End Enum

Constants

DSFXPARAMEQ_CENTER_MAX

Maximum value.

DSFXPARAMEQ_CENTER_MIN

Minimum value.


CONST_DSFXPARAMEQ_GAIN

The CONST_DSFXPARAMEQ_GAIN enumeration is used in the fGain member of the DSFXPARAMEQ type.

Syntax

Enum CONST_DSFXPARAMEQ_GAIN
  DSFXPARAMEQ_GAIN_MAX =  15
  DSFXPARAMEQ_GAIN_MIN = -15 (&HFFFFFFF1)
End Enum

Constants

DSFXPARAMEQ_GAIN_MAX

Maximum value.

DSFXPARAMEQ_GAIN_MIN

Minimum value.


CONST_DSOUND

The CONST_DSOUND enumeration contains miscellaneous constants used throughout DirectSound.

Syntax

Enum
  DS3D_DEFAULTCONEANGLE         =        360 (&H168)
  DS3D_DEFAULTCONEOUTSIDEVOLUME =          0
  DS3D_DEFAULTDISTANCEFACTOR    =          1
  DS3D_DEFAULTDOPPLERFACTOR     =          1
  DS3D_DEFAULTMAXDISTANCE       = 1000000000 (&H3B9ACA00)
  DS3D_DEFAULTMINDISTANCE       =          1
  DS3D_DEFAULTROLLOFFFACTOR     =          1
  DS3D_MAXCONEANGLE             =        360 (&H168)
  DS3D_MAXDISTANCEFACTOR        =         10
  DS3D_MAXDOPPLERFACTOR         =         10
  DS3D_MAXROLLOFFFACTOR         =         10
  DS3D_MINCONEANGLE             =          0
  DS3D_MINDISTANCEFACTOR        =          0
  DS3D_MINDOPPLERFACTOR         =          0
  DS3D_MINROLLOFFFACTOR         =          0
  DSBFREQUENCY_MAX              =     100000 (&H186A0)
  DSBFREQUENCY_MIN              =        100 (&H64)
  DSBFREQUENCY_ORIGINAL         =          0
  DSBPAN_CENTER                 =          0
  DSBPAN_LEFT                   =     -10000 (&HFFFFD8F0)
  DSBPAN_RIGHT                  =      10000 (&H2710)
  DSBPN_OFFSETSTOP              =         -1 (&HFFFFFFFF)
  DSBSIZE_MAX                   =  268435455 (&HFFFFFFF)
  DSBSIZE_MIN                   =          4
  DSBVOLUME_MAX                 =          0
  DSBVOLUME_MIN                 =     -10000 (&HFFFFD8F0)
  WAVE_FORMAT_PCM               =          1
End Enum

Constants

DS3D_DEFAULTCONEANGLE = 360 (&H168)
DS3D_DEFAULTCONEOUTSIDEVOLUME
DS3D_DEFAULTDISTANCEFACTOR
DS3D_DEFAULTDOPPLERFACTOR
DS3D_DEFAULTMAXDISTANCE
DS3D_DEFAULTMINDISTANCE
DS3D_DEFAULTROLLOFFFACTOR
DS3D_MAXCONEANGLE
DS3D_MAXDISTANCEFACTOR
DS3D_MAXDOPPLERFACTOR
DS3D_MAXROLLOFFFACTOR
DS3D_MINCONEANGLE
DS3D_MINDISTANCEFACTOR
DS3D_MINDOPPLERFACTOR
DS3D_MINROLLOFFFACTOR

Allowable and default values for 3-D buffer parameters.

DSBFREQUENCY_MAX
DSBFREQUENCY_MIN
DSBFREQUENCY_ORIGINAL
DSBPAN_CENTER
DSBPAN_LEFT
DSBPAN_RIGHT
DSBPN_OFFSETSTOP
DSBSIZE_MAX
DSBSIZE_MIN
DSBVOLUME_MAX
DSBVOLUME_MIN

Allowable and default values for buffer parameters.

WAVE_FORMAT_PCM

Used in the nFormatTag member of the WAVEFORMATEX type.


CONST_DSOUNDERR

The CONST_DSOUNDERR enumeration represents DirectMusic error codes. For a list of values, see DirectSound Error Codes.


CONST_DSOUNDFX

The CONST_DSOUNDFX enumeration is used in specifying and retrieving parameters of effects buffer creation.

Syntax

Enum CONST_DSOUNDFX
  DSFX_LOCHARDWARE  = 1
  DSFX_LOCSOFTWARE  = 2
  DSFXR_FAILED      = 4
  DSFXR_LOCHARDWARE = 1
  DSFXR_LOCSOFTWARE = 2
  DSFXR_PRESENT     = 0
  DSFXR_UNALLOCATED = 3
  DSFXR_UNKNOWN     = 5
End Enum

Constants

DSFX_LOCHARDWARE
DSFX_LOCSOFTWARE

These flags control the creation of play buffer effects. See DSEFFECTDESC.

DSFXR_FAILED
DSFXR_LOCHARDWARE
DSFXR_LOCSOFTWARE
DSFXR_PRESENT
DSFXR_UNALLOCATED
DSFXR_UNKNOWN

These values describe the result of an attempt to create a play buffer effect. See DirectSoundSecondaryBuffer8.AcquireResources and DirectSoundSecondaryBuffer8.SetFX.


CONST_DSSCLFLAGS

The CONST_DSSCLFLAGS enumeration is used in the level parameter of the DirectSound8.SetCooperativeLevel method to specify the priority level.

Syntax

Enum CONST_DSSCLFLAGS
  DSSCL_NORMAL       = 1
  DSSCL_PRIORITY     = 2
  DSSCL_WRITEPRIMARY = 4
End Enum

Constants

DSSCL_NORMAL

Sets the application to a fully cooperative status. 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 application to the priority level. Applications with this cooperative level can call the DirectSoundPrimaryBuffer8.SetFormat method.

DSSCL_WRITEPRIMARY

Sets the application to the highest priority level. The application has write access to the primary sound buffer.

Remarks

The DSSCL_EXCLUSIVE cooperative level is no longer supported.


CONST_DSSPEAKERFLAGS

The CONST_DSSPEAKERFLAGS enumeration is used by the DirectSound8.GetSpeakerConfig and DirectSound8.SetSpeakerConfig method to specify the speaker configuration.

Syntax

Enum CONST_DSSPEAKERFLAGS
  DSSPEAKER_GEOMETRY_MAX    = 180 (&HB4)
  DSSPEAKER_GEOMETRY_MIN    =   5
  DSSPEAKER_GEOMETRY_NARROW =  10
  DSSPEAKER_GEOMETRY_WIDE   =  20 (&H14)
  DSSPEAKER_HEADPHONE       =   1
  DSSPEAKER_MONO            =   2
  DSSPEAKER_QUAD            =   3
  DSSPEAKER_STEREO          =   4
  DSSPEAKER_SURROUND        =   5
End Enum

Constants

DSSPEAKER_GEOMETRY_MAX

The speakers are directed over an arc of 180 degrees.

DSSPEAKER_GEOMETRY_MIN

The speakers are directed over an arc of 5 degrees.

DSSPEAKER_GEOMETRY_NARROW

The speakers are directed over an arc of 10 degrees.

DSSPEAKER_GEOMETRY_WIDE

The speakers are directed over an arc of 20 degrees.

DSSPEAKER_HEADPHONE

The speakers are headphones.

DSSPEAKER_MONO

The speakers are monaural.

DSSPEAKER_QUAD

The speakers are quadraphonic.

DSSPEAKER_STEREO

The speakers are stereo.

DSSPEAKER_SURROUND

The speakers are surround sound.


CONST_WAVEFORMATFLAGS

The CONST_WAVEFORMATFLAGS enumeration is used in the lFormats member of the DSCCAPS type to indicate what standard formats are supported.

Syntax

Enum CONST_WAVEFORMATFLAGS
  WAVE_FORMAT_1M08 =    1
  WAVE_FORMAT_1M16 =    4
  WAVE_FORMAT_1S08 =    2
  WAVE_FORMAT_1S16 =    8
  WAVE_FORMAT_2M08 =   16 (&H10)
  WAVE_FORMAT_2M16 =   64 (&H40)
  WAVE_FORMAT_2S08 =   32 (&H20)
  WAVE_FORMAT_2S16 =  128 (&H80)
  WAVE_FORMAT_4M08 =  256 (&H100)
  WAVE_FORMAT_4M16 = 1024 (&H400)
  WAVE_FORMAT_4S08 =  512 (&H200)
  WAVE_FORMAT_4S16 = 2048 (&H800)
End Enum

Constants

WAVE_FORMAT_1M08

11.025 kHz, mono, 8-bit.

WAVE_FORMAT_1M16

11.025 kHz, mono, 16-bit.

WAVE_FORMAT_1S08

11.025 kHz, stereo, 8-bit.

WAVE_FORMAT_1S16

11.025 kHz, stereo, 16-bit.

WAVE_FORMAT_2M08

22.05 kHz, mono, 8-bit.

WAVE_FORMAT_2M16

22.05 kHz, mono, 16-bit.

WAVE_FORMAT_2S08

22.05 kHz, stereo, 8-bit.

WAVE_FORMAT_2S16

22.05 kHz, stereo, 16-bit.

WAVE_FORMAT_4M08

44.1 kHz, mono, 8-bit.

WAVE_FORMAT_4M16

44.1 kHz, mono, 16-bit.

WAVE_FORMAT_4S08

44.1 kHz, stereo, 8-bit.

WAVE_FORMAT_4S16

44.1 kHz, stereo, 16-bit.


DirectSound Error Codes

This section lists values specific to DirectSound that can be returned in Err.Number when an error is raised on a method call. For a list of the specific codes that each method can return, see the individual method descriptions. These lists are not necessarily comprehensive.

Error codes are presented in the following sections:

  • DirectSound Error Codes By Number
  • DirectSound Error Codes By Name


DirectSound Error Codes By Number

The following table lists DirectSound error codes sorted by value. For a description, click on the constant.

Hexadecimal | Constant
&H00000007 | DSERR_OUTOFMEMORY
&H000001AE | DSERR_NOINTERFACE
&H80004001 | DSERR_UNSUPPORTED
&H80004005 | DSERR_GENERIC
&H80070057 | DSERR_INVALIDPARAM
&H8878000A | DSERR_ALLOCATED
&H8878001E | DSERR_CONTROLUNAVAIL
&H88780032 | DSERR_INVALIDCALL
&H88780046 | DSERR_PRIOLEVELNEEDED
&H88780064 | DSERR_BADFORMAT
&H88780078 | DSERR_NODRIVER
&H88780082 | DSERR_ALREADYINITIALIZED
&H88780096 | DSERR_BUFFERLOST
&H887800A0 | DSERR_OTHERAPPHASPRIO
&H887800AA | DSERR_UNINITIALIZED
&H887810B4 | DSERR_BUFFERTOOSMALL
&H887810BE | DSERR_DS8_REQUIRED
&H88781161 | DSERR_OBJECTNOTFOUND


DirectSound Error Codes By Name

The following list describes all DirectSound error codes. To find a constant from its value, see DirectSound Error Codes By Number.

DSERR_ALLOCATED

The request failed because resources, such as a priority level, were in use by another caller.

DSERR_ALREADYINITIALIZED

The object is already initialized.

DSERR_BADFORMAT

The specified wave format is not supported.

DSERR_BUFFERLOST

The buffer memory has been lost and must be restored.

DSERR_BUFFERTOOSMALL

The buffer is not large enough to support effects processing.

DSERR_CONTROLUNAVAIL

The control (volume, pan, and so forth) requested by the caller is not available.

DSERR_DS8_REQUIRED

A DirectSound object of class CLSID_DirectSound8 or later is required for the requested functionality.

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_NODRIVER

No sound driver is available for use.

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

The caller does not have the priority level required for the function to succeed.

DSERR_UNINITIALIZED

The DirectSound device has not been initialized.

DSERR_UNSUPPORTED

The function called is not supported at this time.


Glossary

To find a term in the glossary, click the letter of the alphabet that is the first letter in the term you want to look up.

You can also read glossary terms within the text of Help by clicking the underlined glossary term links. After you click a glossary link, the glossary term and definition appear in a pop-up window. To close the window, click anywhere on the screen.

A | B | C | D | E | F | G | H | I | J | K | L | M
N | O | P | Q | R | S | T | U | V | W | X | Y | Z

A

articulation

A series of adjustments applied by a synthesizer to the pitch, volume, and other parameters of an instrument sound to make it more realistic.

Back to Top

B

bank select

A MIDI controller that enables instruments to be chosen from different groups, or banks, each identified by a 2-byte code.

Back to Top

C

chordmap

A scheme of chord progressions, arranged in a flowchart along a time line.

curve

In DirectMusic, a continuous series of events with a start and end value, such as volume fade.

Back to Top

D

DirectX Media Object (DMO)

A COM object that processes multimedia data streams from buffers allocated by the client.

DLS

See definition for: Downloadable Sounds (DLS)

DMO

See definition for: DirectX media object (DMO)

Downloadable Sounds (DLS)

A standard for synthesizing wave sounds from digital samples stored in software. The DLS level 1 and level 2 standards are published by the MIDI Manufacturers Association.

Back to Top

G

groove level

A value given to music during style playback, determining which patterns can be selected at any given time. The author assigns a range of groove levels to each pattern.

Back to Top

L

latency

A delay in response. For example, in DirectSound, it is the interval between the time at which a sound buffer plays and the time that the speakers actually reproduce the sound. In DirectPlay, it is the time that it takes for a packet to reach a specified destination.

Back to Top

M

mix-in buffer

In DirectSound, a buffer that receives data from other DirectSound buffers rather than directly from the synthesizer.

See also: sink-in buffer

motif

In DirectMusic, a type of pattern played explicitly by an application to mark an event.

music value

In DirectMusic, a note in a pattern within a style whose pitch is defined only when it is transposed to the current chord according to the current play mode and subchord level.

Back to Top

N

nonregistered parameter number (NRPN)

Nonregistered parameters can be used for different functions by different manufacturers and are accessed through MIDI controllers. For more information, see the MIDI specification.

NRPN

See definition for: nonregistered parameter number (NRPN)

Back to Top

P

pan value

The relative volume, measured in hundredths of decibels, between the left and right audio channels.

pattern

In DirectMusic, a musical figure, one or more measures long, consisting of a basic sequence of music values for each instrument part.

PChannel

See definition for: performance channel (PChannel)

PCM

See definition for: pulse code modulation (PCM)

performance

In DirectMusic, an object that manages the flow of data from the source to the synthesizer, and controls global values, such as timing, tempo, and master volume.

performance channel (PChannel)

In DirectMusic, a set of parameters used to play one or more parts in a segment. Each performance channel has its own instrument, pan, volume, and transposition settings, and belongs to a single audiopath.

primary buffer

A buffer in which all data is mixed for the final time and then passed to the rendering device.

pulse code modulation (PCM)

An uncompressed wave data format in which each value represents the amplitude of the signal at the time of sampling.

Back to Top

R

registered parameter number (RPN)

An identification number for a registered parameter that has been assigned a function by the MIDI Manufacturers Association and can be accessed through controllers.

rolloff

The attenuation of sound over distance.

RPN

See definition for: registered parameter number (RPN)

Back to Top

S

script

In DirectMusic, a file containing variables and routines that can be accessed from within an application.

segment state

An object created each time a segment is played. It is used to get information about the state of playback and the audiopath for that instance of the segment being played.

send

A sound effect for a buffer that is applied by sending the sound data to a second buffer.

sink

In DirectX, an object that manages the distribution of data from the synthesizer through buses to DirectSound buffers.

sink-in buffer

A DirectSound buffer that receives data directly from the synthesizer rather than from other DirectSound buffers.

See also: mix-in buffer

static buffer

A secondary sound buffer that contains an entire sound; typically it is filled with data only once.

streaming buffer

A secondary sound buffer that contains only part of a sound. Its data must be refreshed as it is playing.

style

In DirectMusic, a collection of musical patterns and other data that can be used to create a dynamic score. A style defines a basic melody and rhythm with variations, motifs, and embellishments, contains a time signature and a tempo, and can contain one or more bands.

Back to Top

T

template

In DirectMusic, a segment that can be used in combination with a chordmap to compose a new segment at run time. A template must contain a signpost track.

track

In DirectMusic, a component of a segment that contains timed data of a particular kind.

Back to Top

V

velocity

In music, the speed at which a MIDI key is pressed, roughly equivalent to the dynamic level at which the note is played in some instrumental timbres.

Back to Top


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 about 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.

What's New in DirectInput. Summary of features new to this version of DirectX. Read this section if you have used DirectInput before but want to take advantage of the new capabilities.

Introduction to DirectInput. High-level overview of the capabilities of DirectInput and the steps you will take to implement it. Start with this section if you are new to DirectInput.

Understanding DirectInput. Introduction to the objects and classes of DirectInput and how they are related to the Microsoft Windows message system. Read this section if you are 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 will use for setting up devices, retrieving data, and implementing force-feedback effects. If you are 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 Visual Basic Reference.

Programming Tips and Tools. Advanced programming topics and a guide to the DirectInput tools provided with the DirectX Software Development Kit (SDK).

DirectInput Visual Basic 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 Visual Basic Samples. A guide to the DirectInput Visual Basic samples included in the SDK, illustrating the use and capabilities of DirectInput.

DirectInput Visual Basic Reference. Reference information for the API. Use this section when you need to know the details of a class, method, type, macro, or other element.


What's New in DirectInput

New Features for DirectInput 8.1

Microsoft® DirectX® 8.1 is a major release primarily for DirectX graphics. The improvements for Microsoft DirectInput® are primarily performance enhancements.

To find out more about the new features in DirectX, see What's New in DirectX 8.1.

New Features for DirectInput 8.0

The following are some of the new features in DirectInput.

Action mapping
DirectInput for DirectX 8.0 introduces a major new feature: action mapping. Action mapping enables you to establish a connection between input actions and input devices that does not depend on the existence of particular device objects (such as specific buttons or axes). Action mapping simplifies the input loop and reduces the need for custom game drivers, custom device profilers, and custom configuration user interfaces in games.

For more information, see Action Mapping.

New DirectInput object features
The DirectInput object is now represented by the DirectInput8 class, which is obtained by using the DirectX8.DirectInputCreate method.
New keyboard properties
Two keyboard properties have been added: DIPROP_KEYNAME, which retrieves a localized key name, and DIPROP_SCANCODE, which retrieves the scan code.
Joystick slider data in rglSlider array
Joystick slider data that was assigned to the z-axis of a DIJOYSTATE or DIJOYSTATE2 type under earlier DirectX versions will now be found in the slider array of those same types.
Improved support for pedal on wheels
In DirectX 7.0, pedal data was placed in several different locations, based on IHV preference. In DirectX 8.1, we attempt to place all combined wheel data on Y and all separate pedal data on Y (Accel) and Rz (Brake). This makes programming for wheels much simpler when using the DirectX 8 interfaces.


Introduction to DirectInput

Microsoft® 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. It includes the following:

  • The Power of DirectInput
  • Getting Started with DirectInput

For a more comprehensive view of how DirectInput works, see Understanding DirectInput.

For a step-by-step guide to using the DirectInput application programming interface (API), see the following topics.

  • Using DirectInput
  • DirectInput Visual Basic Tutorials

The Power of DirectInput

Apart from providing services for devices not supported by the Microsoft® Win32® API, Microsoft DirectInput® gives faster access to input data by communicating directly with the hardware drivers rather than relying on Microsoft Windows® messages.

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 Microsoft® DirectInput® in a simple application.

For details and examples of these steps, see Using DirectInput and DirectInput Visual Basic 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 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.

For more information, see Action Mapping.


Understanding DirectInput

This topic covers the underlying structure of Microsoft® DirectInput® and its relationship to the Microsoft Windows® message system.

  • DirectInput Objects
  • Interaction with Windows

For practical information on how to implement the elements of DirectInput introduced here, see Using DirectInput.

DirectInput Objects

An input-only Microsoft® DirectInput® implementation consists of a single DirectInput8 object along with DirectInputDevice8 objects for each input device that is being used by the application. The DirectInputDevice8 object is used for retrieving the input data.

Any available device, regardless of whether it is being used by DirectInput, can also be represented by a DirectInputDeviceInstance8 object, which can be used to retrieve miscellaneous information about that device.

Each DirectInputDevice8 object represents one input device, such as a mouse, keyboard, or joystick. (The DirectInput API uses the term joystick for all game controllers other than a mouse or a 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 DirectInputDevice8 objects. A force-feedback device is represented by a single joystick object that handles both input and output.

Each device in turn has device objects, which are individual controls or switches, such as keys, buttons, or axes. Each device object is represented by an instance of the DirectInputDeviceObjectInstance class, whose methods can be used to retrieve information about the device object. (The input data, however, is always retrieved by DirectInputDevice8.)

Devices and device objects can be enumerated, and the resulting collections are represented by DirectInput8.GetDIDevices and DirectInputDevice8.GetDeviceObjectsEnum objects.

Force-feedback effects are represented by the DirectInputEffect class. Methods of this interface are used to create, modify, start, and stop effects.

Interaction with Windows

Because Microsoft® DirectInput® works directly with the device drivers, it either suppresses or ignores Microsoft 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® DirectInput®. It includes information on the following:

  • Creating DirectInput
  • DirectInput Device Enumeration

For a broader overview, see Understanding DirectInput.

For related information, see the following:

  • DirectInput Devices
  • DirectInput Device Data
  • Action Mapping
  • Force Feedback

Creating DirectInput

The first step in any Microsoft® DirectInput® application is creating the DirectInput8 object. Do this by using the DirectX8.DirectInputCreate method.

You should create a single DirectInput8 object and not destroy it until the application terminates.

DirectInput Device Enumeration

Microsoft® 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. See Creating a DirectInput Device.

For all other input devices, and for systems with multiple keyboards or mouse devices, call DirectInput8.GetDIDevices to build a collection of available devices. This method returns a DirectInputEnumDevices8 object representing the collection. Each device in the collection can be retrieved as a DirectInputDeviceInstance8 object by using the DirectInputEnumDevices8.GetItem method. The following example shows how to build a collection of game controllers and display them in a list box named lstJoysticks.

Dim diDevEnum As DirectInputEnumDevices8

Set diDevEnum = di.GetDIDevices(DI8DEVCLASS_GAMECTRL, DIEDFL_ATTACHEDONLY)

Dim i As Integer
For i = 1 To diDevEnum.GetCount
    Call lstJoysticks.AddItem(diDevEnum.GetItem(i).GetInstanceName)
Next i

At the very least, you must retrieve the unique identifier for a nonstandard device from the enumeration by calling DirectInputDeviceInstance8.GetGuidInstance before you can create a DirectInputDevice8 object for that device. You might also want to enumerate devices in order to look for particular types and subtypes (by using DirectInputDeviceInstance8.GetDevType) or to populate a list box that enables the user to select a game controller.

You might even want to search for a device with particular capabilities. To do this, create a DirectInputDevice8 object for each candidate in order to examine it further by using the DirectInputDevice8.GetCapabilities method.


DirectInput Devices

This section contains information about the code objects that represent devices such as a mouse, keyboards, or joysticks. The following topics are covered:

  • Device Setup
  • Creating a DirectInput Device
  • Device Capabilities
  • Cooperative Levels
  • Device Object Enumeration
  • Device Data Formats
  • Device Properties
  • Acquiring Devices

For information on how to retrieve and interpret data from devices, see DirectInput Device Data.


Device Setup

Your application must obtain a Microsoft® 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.


Creating a DirectInput Device

To get input data from a device, you first have to create an object to represent that device.

The DirectInput8.CreateDevice method is used to obtain a DirectInputDevice8 object. Methods of this interface are then used to manipulate the device and obtain data.

The following code example, where di is the DirectInput8 object, creates a keyboard device:

Dim diDev As DirectInputDevice
Set diDev = di.CreateDevice("GUID_SysKeyboard")

The parameter is an alias for a GUID that identifies the instance of the device for which the interface is to be created. Microsoft® DirectInput® provides two predefined GUIDs, represented by the strings GUID_SysMouse and GUID_SysKeyboard, which stand for the system mouse and keyboard. You can pass either of these to the CreateDevice method.

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.

For devices other than the system mouse or keyboard, use the instance GUID for the device obtained from DirectInputDeviceInstance8.GetGuidInstance. 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.

In the following code example, it is presumed that the application has enumerated devices and found a suitable one, diDevInstance, which is to be created as a DirectInputDevice:

Dim guid As String
guid = diDevInstance.GetGuidInstance
Set diDev = di.CreateDevice(guid)

For more information on obtaining the DirectInputDeviceInstance8 object, see DirectInput Device Enumeration.


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?

Such questions are answered with a call to the DirectInputDevice8.GetCapabilities method, which returns the data in a DIDEVCAPS type.

The following code example checks whether the mouse is attached and whether it has a third axis (presumably a wheel):

'diMouse is a valid DirectInputDevice object.

Dim WheelAvailable As Boolean
Dim dicaps as DIDEVCAPS

Call diDev.GetCapabilities(dicaps)
WheelAvailable = ((dicaps.lFlags And DIDC_ATTACHED) _
        And (dicaps.lAxes > 2))

Another way to check for a certain button or axis is to call DirectInputDevice8.GetObjectInfo for that object. If the call raises the error DIERR_NOTFOUND, the object is not present. The following code determines whether there is a z-axis, even if it is not the third axis:

Dim didoi As DirectInputDeviceObjectInstance
On Error GoTo NOTFOUND
Set didoi = diDev.GetObjectInfo(DIMOFS_Z, DIPH_BYOFFSET)
On Error GoTo 0
.
.
.
NOTFOUND:
If Err.Number = DIERR_NOTFOUND Then
  MsgBox "No z-axis found."
End If


Cooperative Levels

The cooperative level of a device determines how the input is shared with other applications and with the Microsoft® Windows® system. You set it by using the DirectInputDevice8.SetCooperativeLevel method, as in the following code example:

'hwnd is the top-level window handle.
Call diDevice.SetCooperativeLevel(hWnd,
        DISCL_NONEXCLUSIVE Or 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.

Note The hWnd property of a form does not become valid until the form is shown. If you are initializing the Microsoft® DirectInput® device in the Load method of the application's main form, you must call Show before attempting to set the cooperative level.

Although DirectInput provides a default setting, you should still explicitly set the cooperative level because this is the only way to give DirectInput the window handle. Without this handle, DirectInput cannot react to situations that involve window messages, such as joystick recalibration.

The valid flag combinations are shown in the following table.

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

A foreground cooperative level means that the input device is available only when the application is in the foreground or, in other words, has the input focus. If the application moves to the background, the device is automatically unacquired, or made unavailable.

A background cooperative level really means foreground and background. A device with a background cooperative level can be acquired and used by an application at any time.

You will usually want to have foreground access only, since most applications are not designed to respond to input that takes place when another program is in the foreground.

While developing an application, it is useful to employ conditional compilation so that the background cooperative level is always set for debugging. This prevents your application from losing access to the device every time it moves to the background as you switch to the debugging environment.

Exclusive vs. Nonexclusive

In most cases, the fact that your application is using a device at the exclusive level does not mean that other applications cannot get data from the device. Also, an application that requests background exclusive mode may lose access if another application requests exclusive access. The application can regain access to the device by manually unacquiring the device and reaquiring it.

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 DirectInput8.CreateDevice, Windows is not allowed any access and no mouse messages are generated. A further side effect is that the cursor disappears.


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.

You enumerate device objects by calling DirectInputDevice8.GetDeviceObjectsEnum, which returns an instance of the DirectInputEnumDeviceObjects class representing the collection of available device objects that match the requested parameters.

The following code example enumerates axes on a device:

' diDev is a DirectInputDevice object.

Dim diEnumObjects As DirectInputEnumDeviceObjects
Set diEnumObjects = diDev.GetDeviceObjectsEnum(DIDFT_AXIS)

The parameter is a combination of flags (just one, in this case) to indicate which type or types of objects to include in the enumeration.

Note Some of the CONST_DIDFTFLAGS flags are combinations of others; for example, DIDFT_AXIS is equivalent to DIDFT_ABSAXIS Or DIDFT_RELAXIS.

To obtain information about a particular device object, call the methods of a DirectInputDeviceObjectInstance object obtained by calling DirectInputEnumDeviceObjects.GetItem. Information available for a device object includes its name, its type, and its offset in the data structure for the device.

The following code lists the names of the axes enumerated in the previous example:

Dim diDevObjInstance As DirectInputDeviceObjectInstance
Dim i As Integer
For i = 1 To diEnumObjects.GetCount
  Set diDevObjInstance = diEnumObjects.GetItem(i)
  Call List1.AddItem(diDevObjInstance.GetName)
Next i


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. Microsoft® DirectInput® uses the data format in many methods to identify particular device objects.

The DirectInputDevice8.SetCommonDataFormat and DirectInputDevice8.SetDataFormat methods tell Microsoft® DirectInput® what device objects will be used and how the data will be arranged.

For standard devices—the mouse, keyboard, and any game controller whose input data can be described in a DIJOYSTATE or DIJOYSTATE2 type—you can set the data format by calling the SetCommonDataFormat method, passing in a constant from the CONST_DICOMMONDATAFORMATS enumeration. The common data formats are adequate for most applications.

For specialized devices, you must pass a description of the data format to the SetDataFormat method. The following code example sets the data format for a device with two axes, both of which require a Long for their data, and no buttons:

Dim dx As New DirectX8
Dim di As DirectInput8
Dim did As DirectInputDevice8
Dim fD As DIDATAFORMAT
Dim fDA(1) As DIOBJECTDATAFORMAT

Private Sub Form_Load()
    Set di = dx.DirectInputCreate()

    Set did = di.CreateDevice("GUID_SysMouse")

    fDA(0).lFlags = DIDOI_POLLED
    fDA(0).lOfs = 0
    fDA(0).lType = DIDFT_RELAXIS
    fDA(0).strGuid = "GUID_XAxis"

    fDA(1).lFlags = DIDOI_POLLED
    fDA(1).lOfs = 4
    fDA(1).lType = DIDFT_RELAXIS
    fDA(1).strGuid = "GUID_YAxis"

    fD.dataSize = 8
    fD.lFlags = DIDF_RELAXIS
    fD.lObjSize = 4
    fD.numObjs = 2

    did.SetDataFormat fD, fDA()

End Sub


Device Properties

Properties of Microsoft® 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 DirectInputDevice8.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.

The DirectInputDevice8.SetProperty and DirectInputDevice8.GetProperty methods take two parameters: a GUID alias in string form that identifies the property being set, and data of type Any. The data is actually passed in one of the following types:

  • DIPROPLONG is for properties that require a single value, such as a buffer size. The property data consists of a single Long.
  • DIPROPRANGE is for range properties, which require two values (maximum and minimum). The property data consists of two Long data members.

For SetProperty, the data members of the property types are the values you want to set. For GetProperty, the current value is returned in these members.

In addition to the actual property data, both these types contain two other members: lHow and lObj.

The values in lHow and lObj work together, with lHow signifying the system that is used to identify the device object whose property is being set or retrieved, and lObj identifying the device object.

If lHow is DIPH_BYID, the device object is described by a unique numerical identifier in lObj. This ID can be extracted from the value returned by DirectInputDeviceObjectInstance.GetType after device objects have been enumerated.

For most applications, it is simpler to identify the device object by its offset within the data structure established by DirectInputDevice8.SetCommonDataFormat or DirectInputDevice8.SetDataFormat. In this case, lHow is DIPH_BYOFFSET, and lObj is the offset, in bytes. For the keyboard, mouse, and any game controller whose data can be returned in a DIJOYSTATE or DIJOYSTATE2 type, the device object can be identified by a predefined constant. See CONST_DIKEYFLAGS, CONST_DIMOUSEOFS, and CONST_DIJOYSTICKOFS.

The lHow member can also contain DIPH_DEVICE, which means that the property belongs to the entire device, rather than a single device object. Buffer size is an example of such a property. When lHow is DIPH_DEVICE, lObj is 0.

The following strings are used to identify the property passed to SetProperty and GetProperty. For more information, see DirectInputDevice8.GetProperty.

  • DIPROP_AXISMODE. See also Relative and Absolute Axis Coordinates.
  • DIPROP_BUFFERSIZE. See also Buffered and Immediate Data.
  • DIPROP_DEADZONE
  • DIPROP_GRANULARITY
  • DIPROP_RANGE
  • DIPROP_SATURATION

For more information about dead zone, range, and saturation, see also Interpreting Joystick Axis Data.

The following code example sets the buffer size for a device:

' diDev is a DirectInputDevice whose data format has been set.

Dim diProp As DIPROPLONG
diProp.lHow = DIPH_DEVICE
diProp.lObj = 0
diProp.lData = 10
Call diDev.SetProperty("DIPROP_BUFFERSIZE", diProp)


Acquiring Devices

Acquiring a Microsoft® 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 unacquire a device many times.

In certain cases, depending on the cooperative level, a device is unacquired automatically whenever the application moves to the background. The mouse is automatically unacquired when the user clicks a menu, because at this point Microsoft Windows® assumes control of the device.

You must unacquire 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:

First, DirectInput must be able to tell the application when the flow of data from the device has been interrupted by the system. For instance, 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. Or 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.

Second, because your application can alter the properties of the device, without safeguards DirectInput would have to check the properties each time you wanted to retrieve data. This would be very inefficient. Even worse, a potential disaster could happen such as a hardware interrupt accessing a data buffer just as you were changing the buffer size. Therefore DirectInput requires your application to unacquire the device before changing 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.

Because your application might unacquire a device unexpectedly, especially if you have set the exclusive cooperative level, you must ensure that the application tracks the state of acquisition. One technique is to check for the DIERR_INPUTLOST error after attempting to retrieve data. If this error is raised, you know the device has been unacquired. If your application is getting input in response to event notification, an event is signaled when acquisition is lost.

See the ScrawlB Sample for more information about how to manage device acquisition in exclusive mode.

Attempting to reacquire a device that is already acquired does no harm. Redundant calls to Acquire are ignored, and the device can always be unacquired with a single call to Unacquire.

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. The ScrawlB sample responds to a right-click button by unacquiring the mouse, putting the Windows cursor in the same spot as its own, displaying a shortcut menu, and letting Windows handle the input until a menu choice is made.


DirectInput Device Data

This section covers the following basic concepts of getting data from Microsoft® 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 Microsoft 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.

Most of the information in this section applies to both mechanisms. For more information on the newer way of identifying device data, see Action Mapping.


Buffered and Immediate Data

Microsoft® 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 If you are using Action Mapping, you will want to retrieve buffered data because the buffered data packets contain the application-defined data associated with the input. Doing so means that you are responsible for tracking the position of absolute axes, since events but not states are reported in buffered data packets.

An application retrieves immediate data by calling one of the following methods:

  • DirectInputDevice8.GetDeviceStateKeyboard. For devices that retrieve data in a DIKEYBOARDSTATE type. (For this and the following three methods, the data format must have been set by using DirectInputDevice8.SetCommonDataFormat.)
  • DirectInputDevice8.GetDeviceStateMouse. For devices that retrieve data in a DIMOUSESTATE type.
  • DirectInputDevice8.GetDeviceStateMouse2. For devices that retrieve data in a DIMOUSESTATE2 type.
  • DirectInputDevice8.GetDeviceStateJoystick. For devices that retrieve data in a DIJOYSTATE type.
  • DirectInputDevice8.GetDeviceStateJoystick2. For devices that retrieve data in a DIJOYSTATE2 type.
  • DirectInputDevice8.GetDeviceState. For devices that use custom data formats, as set by using DirectInputDevice8.SetDataFormat.

As the names imply, each of these methods returns the current state of the device—for example, whether each button is up or down. The method provides no data about what has happened with the device since the last call, apart from implicit information that you can derive by comparing the current state with the last one. For example if a user presses and releases a button between two calls to the method, your application will never be given this input. On the other hand, if the user is holding a button down, the method continues reporting that fact until the user releases it.

This way of reporting the device state is different from the way Microsoft Visual Basic® reports events with one-time events such as Click and Keydown. If you are polling a device with one of the GetDeviceState methods, you are responsible for determining what constitutes a button click, a double-click, a single keystroke, and so on, and for ensuring that your application does not keep responding to a button-down or key-down state when it is not appropriate to do so.

With buffered data, events are stored until you are ready to deal with them. Every time a button or key is pressed or an axis is moved, information about the event is placed in a DIDEVICEOBJECTDATA type in the buffer. Your application reads the buffer with a call to DirectInputDevice8.GetDeviceData. You can read any number of items at a time.

Reading an item normally deletes it from the buffer, but you also have the choice of retrieving without deleting by setting the DIGDD_PEEK flag.

To get buffered data, you must first set the buffer size by using the DirectInputDevice8.SetProperty or DirectInputDevice8.SetActionMap method. (See the example under Device Properties.) Set the buffer size before acquiring the device for the first time. For reasons of efficiency, the default size of the buffer is 0, and you cannot obtain buffered data unless you change this value. The size of the buffer is measured in items of data for that type of device, not in bytes.

The return value of GetDeviceData tells you the number of items retrieved from the buffer. If the buffer has overflowed, no data is returned, and GetDeviceData raises an error, which the application should trap.

Note For devices that do not generate interrupts, such as analog joysticks, DirectInput does not obtain any data until you call the DirectInputDevice8.Poll method. For more information, see Polling and Event Notification.

See also:

  • Time Stamps and Sequence Numbers
  • Mouse Data
  • Keyboard Data
  • Joystick Data


Time Stamps and Sequence Numbers

When Microsoft® DirectInput® input data is buffered (see Buffered and Immediate Data), each DIDEVICEOBJECTDATA type 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 lTimeStamp 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 lSequence 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.

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.


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 Microsoft® Visual Basic® application, polling would typically be done in the Sub Main procedure.

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 DirectInputDevice8.Poll method. (This behind-the-scenes polling is not to be confused with the kind of application polling just discussed. Poll does not retrieve any data, but merely makes data available.)

To find out whether it is necessary to call Poll each time you want to retrieve data, first set the data format for the device, then call the DirectInputDevice8.GetCapabilities method and check for the DIDC_POLLEDDATAFORMAT flag in the DIDEVCAPS type.

Do not confuse the DIDC_POLLEDDATAFORMAT flag with the DIDC_POLLEDDEVICE flag. The latter is set if any object on the device requires polling. You can then find out whether this is the case for a particular object by calling the DirectInputDevice8.GetObjectInfo method to get a DirectInputDeviceObjectInstance object, and then checking for the DIDOI_POLLED flag in the valued returned by DirectInputDeviceObjectInstance.GetFlags.

The DIDC_POLLEDDEVICE flag describes the worst case for the device, not the actual situation. For example, an 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 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 such as the ScrawlB Sample that wait for input before doing anything.

To use event notification, implement DirectXEvent8 in the form or module in which you want to retrieve data. Then create an event handle by using DirectX8.CreateEvent, and pass this handle to DirectInputDevice8.SetEventNotification. Now, whenever an input event occurs on the device, the DirectXEvent8.DXCallback method is called, and in your implementation of this method you can retrieve either the device state or buffered data just as you would if you were doing so in Sub Main.


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.


Mouse Data

To set up the mouse device for data retrieval, first call the DirectInputDevice8.SetCommonDataFormat method with DIFORMAT_MOUSE as the parameter value.

For maximum performance in a full-screen application, set the cooperative level to DISCL_EXCLUSIVE Or 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 the Microsoft Visual Basic® development environment. 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:

  • Immediate Mouse Data
  • Buffered Mouse Data
  • Interpreting Mouse Axis Data
  • Checking for Lost Mouse Input

See Also

Device Data Formats, Cooperative Levels


Immediate Mouse Data

To retrieve the current state of the mouse, call DirectInputDevice8.GetDeviceStateMouse or DirectInputDevice8.GetDeviceStateMouse2, passing in a DIMOUSESTATE or DIMOUSESTATE2 type. The mouse state returned in the type includes axis data and the state of each of the buttons.

The x, y, and z members of the DIMOUSESTATE and DIMOUSESTATE2 types hold the axis coordinates. (See Interpreting Mouse Axis Data.) The buttons member is an array of bytes, one for each button. The first element in the array is generally the left button, the second is the right button, 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


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 types. 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 by using the DirectInputDevice8.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 instance, if the user presses button 0 and moves the mouse diagonally, the array passed to GetDeviceData (if it has at least three elements) 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 return value of the method will be 3.

You can determine which object an element in the array refers to by checking the lOfs member of the DIDEVICEOBJECTDATA type against the constants in the CONST_DIMOUSEOFS enumeration. Each of these values is derived from the offset of the data for the object in a DIMOUSESTATE or DIMOUSESTATE2 type. For example, DIMOFS_BUTTON0 is equivalent to the offset of buttons(0) in the DIMOUSESTATE type. DIMOFS_BUTTON4 to DIMOFS_BUTTON7 are supported only for DIMOUSESTATE2.

The data for the change of state of the device object is located in the lData member of the DIDEVICEOBJECTDATA type. For axes, the coordinate value is returned in this member. For button objects, only the low byte of lData 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 (lData And &H80) is nonzero.

For more information on the other members of the DIDEVICEOBJECTDATA type, see Time Stamps and Sequence Numbers.

The following code example retrieves the entire contents of the buffer (which contains BufferSize elements) and responds to various events:

' objDIDev is a DirectInputDevice object.
Dim diDeviceData(1 To BufferSize) As DIDEVICEOBJECTDATA
Dim NumEvents As Integer
Dim i As Integer

NumEvents = objDIDev.GetDeviceData(diDeviceData, 0)
For i = 1 To NumEvents
    Select Case diDeviceData(i).lOfs
        Case DIMOFS_X
           ' Respond to x-axis movement.

         Case DIMOFS_Y
           ' Respond to y-axis movement.

         Case DIMOFS_BUTTON0
           If diDeviceData(i).lData And &H80 Then
             ' Respond to left button pressed.
           Else
             ' Respond to left button released.
           End If

    End Select
Next i


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 Microsoft® 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 DirectInputDevice8.SetProperty with "DIPROP_AXISMODE" in the guid parameter and with DIPROPAXISMODE_ABS in the lData member of the DIPROPLONG type.

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 simply 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.


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), Microsoft® Windows® might force your application to unacquire the mouse. For this reason, you should check for the DIERR_INPUTLOST return value from the DirectInputDevice8.GetDeviceData or the DirectInputDevice8.GetDeviceStateMouse 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.


Keyboard Data

When using Microsoft® 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 Microsoft 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 DirectInputDevice8.SetCommonDataFormat method with DIFORMAT_KEYBOARD as the parameter.

The following sections give more information about obtaining and interpreting keyboard data:

  • Immediate Keyboard Data
  • Buffered Keyboard Data
  • Interpreting Keyboard Data
  • Checking for Lost Keyboard Input


Immediate Keyboard Data

To retrieve the current state of the keyboard, call the DirectInputDevice8.GetDeviceStateKeyboard method, passing a DIKEYBOARDSTATE type.

The GetDeviceState method returns a snapshot of the current state of the keyboard. Each key is represented by an element in the array of 256 bytes that makes up the DIKEYBOARDSTATE type. If the high bit of the byte is set, the key is down. The array is most conveniently indexed with the members of the CONST_DIKEYFLAGS enumeration. (See also Interpreting Keyboard Data.)

The following code example determines whether the ESC key is currently being pressed. Assume that objDIDev is a DirectInputDevice8 object.

Dim KeyState As DIKEYBOARDSTATE

Call objDIDev.GetDeviceStateKeyboard(KeyState)
If (KeyState.Key(DIK_ESCAPE) And &H80) Then
    ' Key is down.
End If


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 types. 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 DirectInputDevice8.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 lOfs member of the DIDEVICEOBJECTDATA type against the constants in the CONST_DIKEYFLAGS enumeration. (See also Interpreting Keyboard Data.)

The data for the change of state of the key is located in the lData member of the DIDEVICEOBJECTDATA type. Only the low byte of lData 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 (lData And &H80) is nonzero.


Interpreting Keyboard Data

This topic covers the identification of keys for which data is reported by the DirectInputDevice8.GetDeviceState and DirectInputDevice8.GetDeviceData methods. For more information on interpreting the data from GetDeviceData, see Time Stamps and Sequence Numbers.

In one important respect, Microsoft® DirectInput® applications read the keyboard differently from the way Microsoft 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 numeric 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.


Checking for Lost Keyboard Input

Because Microsoft® Windows® might force your application to unacquire the keyboard when you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application, you should check for the DIERR_INPUTLOST return value from the DirectInputDevice8.GetDeviceData or the DirectInputDevice8.GetDeviceStateKeyboard method 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 fail, you would get another DIERR_NOTACQUIRED error, and so on.


Joystick Data

To set up the joystick device for data retrieval, first call the DirectInputDevice8.SetCommonDataFormat method with DIFORMAT_JOYSTICK or DIFORMAT_JOYSTICK2 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 DirectInputDevice8.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:

  • Immediate Joystick Data
  • Buffered Joystick Data
  • Interpreting Joystick Axis Data
  • Using CPOINTs
  • Checking for Lost Joystick Input


Immediate Joystick Data

To retrieve the current state of the joystick, call the DirectInputDevice8.GetDeviceStateJoystick or the DirectInputDevice8.GetDeviceStateJoystick2 method, depending on whether the data format was set with DIFORMAT_JOYSTICK or DIFORMAT_JOYSTICK2. (See Device Data Formats.) The joystick state returned in the state parameter includes the coordinates of the axes, the state of the buttons, and the state of the point-of-view controllers.

The POV member of the DIJOYSTATE or the DIJOYSTATE2 type contains the position of up to four point-of-view controllers in hundredths of a degree clockwise from north (or forward). The center position is reported as –1. For controllers that have only five positions, the position is one of the following values:

  • –1
  • 0
  • 9000
  • 18000
  • 27000

Some drivers report a value of 65,535, instead of –1, for the neutral position. You should check for a centered POV indicator as follows:

Dim POVCentered As Boolean
POVCentered = MyDijoystate.POV(0) And &HFFFF

The buttons member is an array of bytes, one for each of 32 or 128 buttons, depending on the data type. 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 type has additional members for information about the velocity, acceleration, force, and torque of the axes.

For more information, see Interpreting Joystick Axis Data.

See also

Buffered and Immediate Data


Buffered Joystick Data

To retrieve buffered data from the joystick, first set the buffer size (see Device Properties) and declare an array of DIDEVICEOBJECTDATA types. 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 DirectInputDevice8.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 GetDeviceData (if it has at least three elements) 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 return value of the method will be 3.

You can determine which object an element in the array refers to by checking the lOfs member of the DIDEVICEOBJECTDATA type against the constants of the CONST_DIJOYSTICKOFS enumeration. Each of these values is equivalent to the offset of the data for the object in a DIJOYSTATE type. For example, DIJOFS_BUTTON0 is equivalent to the offset of buttons(0) in the DIJOYSTATE type.

If the data format was set with DIFORMAT_JOYSTICK2, you can use the offset constants 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 internal organization of this type is the same as that of the equivalent C++ structure in the Dinput.h header file.

The data for the change of state of the device object is located in the lData member of the DIDEVICEOBJECTDATA type. For axes, the coordinate value is returned in this member. For button objects, only the low byte of lData 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.


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.

For more information on joystick properties, see the following:

  • DirectInputDevice8.GetProperty
  • DirectInputDevice8.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 DirectInputDevice8.SetProperty with "DIPROP_AXISMODE" in the guid parameter and with DIPROPAXISMODE_REL in the lData member of the DIPROPLONG type.


Using CPOINTs

The CPOINT type is used to calibrate segments of the response curve of a device axis. Up to eight CPOINTs can be set through the DIPROPCPOINTS type. Each CPOINT type 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 type, the response graph for the example axis would appear as shown below, including saturation and dead zones.

A DIPROPCPOINTS type is initialized as follows, assuming the physical range to be -500 to 500.

Dim dipcp as DIPROPCPOINTS

dipcp.lHow = DIPH_BYOFFSET
dipcp.lObj = DIJOFS_X
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

You do not need to know the actual maximum returned value as the values in the dwLog member of the CPOINT type 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 DirectInputDevice8.SetProperty, the curve responds as shown below.


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 DirectInputDevice8.GetDeviceData or the DirectInputDevice8.GetDeviceStateKeyboard method 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 fail, 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 Microsoft® Windows® system—an alternative method is to reacquire the device in response to a WM_ACTIVATE message.


Output Data

Some Human Interface Devices both generate input and accept output. The DirectInputDevice8.SendDeviceData method is used to send packets of data to such devices.

SendDeviceData can be viewed as DirectInputDevice8.GetDeviceData in reverse. As with that method, it uses the DIDEVICEOBJECTDATA type as the basic unit of data. In this case, however, the lOfs member contains the instance ID of the device object associated with the data, rather than its offset in the data format for the device. This ID can be extracted from the value returned by DirectInputDeviceObjectInstance.GetType after device objects have been enumerated. (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 lData member contains whatever data is appropriate for the object. The lTimeStamp and lSequence members are not used and must be set to 0.

To send data to the device, first set up an array of DIDEVICEOBJECTDATA types, fill the required number of elements with data, and then pass its address and the number of elements used to 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 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 after passing the HID usage page and usage code to DirectInputDevice8.GetObjectInfo.

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 device object instance identifiers NumLockID, CapsLockID, and ScrollLockID have all been previously obtained, and diDevKeyboard is a previously defined DirectInputDevice8 object.

Private Sub FlashLEDs()
    Const ARRAYSIZE = 4
    Static rgiBits(ARRAYSIZE-1) As Integer
       rgiBits(0) = 1
       rgiBits(1) = 2
       rgiBits(2) = 4
       rgiBits(3) = 2
    Static iLooper As Integer
       iLooper = 0
    Dim cdod As Long
       cdod = 3                  ' Number of items
    Dim rgdod(3) As DIDEVICEOBJECTDATA
    Dim i as Integer

    ' lTimeStamp and lSequence must be set to 0
    For i = 0 To 3
        rgdod(i).lTimeStamp = 0
        rgdod(i).lSequence = 0
    Next i

    rgdod(0).lOfs = NumLockID
    rgdod(1).lOfs = CapsLockID
    rgdod(2).lOfs = ScrollLockID

    Select Case (rgiBits(iLooper) And 1)
        Case Is = 0
            rgdod(0).lData = 0
        Case Is = 1
            rgdod(0).lData = &H80          ' NumLock light on/off
    End Select

    Select Case (rgiBits(iLooper) And 2)
        Case Is = 0
            rgdod(1).lData = 0
        Case Is = 1
            rgdod(1).lData = &H80          ' CapsLock light on/off
    End Select

    Select Case (rgiBits(iLooper) And 4)
        Case Is = 0
            rgdod(2).lData = 0
        Case Is = 1
            rgdod(2).lData = &H80          ' ScrollLock light on/off
    End Select

    iLooper = (iLooper + 1) Mod ARRAYSIZE  ' Loops from 0 to 3

    Call diDevKeyboard.SendDeviceData(cdod, rgdod, 0)

End Sub


Action Mapping

Traditionally, applications have done their own mapping of events to particular buttons and axes. A car-racing game, for example, might assume that the x-axis on the user's joystick or mouse was the most suitable control for steering the car. The only way to accommodate new or unusual devices was to provide configuration options so that the user could specify some other axis, such as a rotational axis, to use for steering. Moreover, the application had no way of knowing which installed device was the best fit for the game, so the user typically had to choose a device from a menu or make sure only the preferred device was attached.

Using action mapping, you no longer need to make assumptions about the best use of devices and device objects. Instead, your application binds actions to virtual controls wherever possible. Rather than getting data from the x-axis and steering the car to the left or the right accordingly, the application might get data from a virtual control called DIAXIS_DRIVINGR_STEER. Microsoft® DirectInput® assigns the virtual control to a physical control—that is, a device object. It does so by taking into account the application genre, user preferences, information from the device manufacturer, and the user's configuration of the device.

Action mapping also simplifies the input loop by returning data for all devices in a form independent of the particular device. A single action can be mapped to more than one device, and the input loop can respond to the action the same way regardless of which device is being read.

The following topics contain more information on the steps required to implement action mapping.

  • Preparing the Action Map
  • Finding Matching Devices
  • Configuring the Action Map
  • User Configuration of the Device
  • Retrieving Action Data
  • Maintaining Files During Development


Preparing the Action Map

The action map is a DIACTIONFORMAT type containing information about application actions and their mapping to virtual controls or device objects. The type is passed back and forth between the application and Microsoft® DirectInput® to establish the final mapping. This section explains how to initialize the map.

1. Define Application Actions

The first step in implementing DirectInput action mapping is to determine what input-driven actions in your application need to be mapped to device objects. For actions that can be performed either by an axis or by a button, you must define separate actions for both input types. It is recommended that you define button actions for all important functions, in case the device does not have the appropriate axes.

The following sample enumeration of action values might be defined by a car-racing game. Axis actions begin with "eA" and button actions with "eB".

Enum eGameActions
    eA_STEER        'Steering
    eB_STEER_LEFT   'Steer left
    eB_STEER_RIGHT  'Steer right
    eA_ACCELERATE   'Change speed
    eB_ACCELERATE   'Speed up
    eB_DECELERATE   'Slow down
    eA_BRAKE        'Brake
    eB_BRAKE        'Brake
    eB_UPSHIFT      'Shift to higher gear
    eB_DOWNSHIFT    'Shift to lower gear
    eB_CYCLEVIEW    'Cycle to next view
    eB_COURSEVIEW   'Toggle course view
    eB_DRIVERVIEW   'View from driver's seat
    eB_BRAKEBIAS    'Brake bias
    eA_VOLUME       'Sound volume
    eB_MUTE         'Toggle sound
End Enum

Const NUM_MY_ACTIONS = 16

In the example, actions are defined as enumerated values. However, they could be other 32-bit data types. When you retrieve device data, you get whatever action value you have defined, and you can handle it in any way you like.

2. Define the Genre

The next step is to decide what genre your application belongs to. A genre defines a set of virtual controls. By selecting the proper genre, you can obtain the best possible fit of virtual controls to application actions. Manufacturers who choose to supply default mappings for their devices must support one or more of the genres defined by DirectInput. See Action Mapping Constants for a list of these genres.

For the game in the example, the obvious choice is the DIVIRTUAL_DRIVING_RACE genre, which contains the following virtual controls.

Priority 1 Controls

DIAXIS_DRIVINGR_STEER
DIAXIS_DRIVINGR_ACCELERATE
DIAXIS_DRIVINGR_BRAKE
DIBUTTON_DRIVINGR_SHIFTUP
DIBUTTON_DRIVINGR_SHIFTDOWN
DIBUTTON_DRIVINGR_VIEW
DIBUTTON_DRIVINGR_MENU

Priority 2 Controls

DIAXIS_DRIVINGR_ACCEL_AND_BRAKE
DIHATSWITCH_DRIVINGR_GLANCE
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_PAUSE
DIBUTTON_DRIVINGR_PIT
DIBUTTON_DRIVINGR_STEER_LEFT_LINK
DIBUTTON_DRIVINGR_STEER_RIGHT_LINK

There is no difference in functionality between Priority 1 and Priority 2 controls. Priority 1 controls are those most likely to be supported by device manufacturers in their default mappings. However, there is no guarantee that any virtual control will be supported by a device.

3. Assign Actions to Controls or Device Objects

The next step in creating the action map is to associate each application action with one or more of the virtual controls defined for the genre. You do this by declaring and initializing an array of DIACTION types. Each type in the array specifies the action value, the virtual control to associate with it, and a friendly name that describes the action. Leave other members as zero; they will be filled in later by DirectInput.

You can also use elements of the DIACTION array to map actions to particular keys or buttons on the keyboard or mouse or to channels on a Microsoft DirectPlay® voice device. By doing so, you can take advantage of the simplified input loop for all input, not just that from virtual controls. For example, suppose you map the application-defined action eB_UPSHIFT to both the DIBUTTON_DRIVINGR_SHIFTUP virtual control and to the Page Up key. When retrieving data, you get back eB_UPSHIFT whether the input came from a joystick button or the keyboard.

The following example begins the declaration of an action map for the car-racing game.

Dim rgActions(20) As DIACTION

' Genre-defined virtual axes
With rgActions(0)
  .lAppData = eA_STEER
  .lSemantic = DIAXIS_DRIVINGR_STEER
  .lFlags = 0
  .ActionName = "Steer"
End With
With rgActions(1)
  .lAppData = eA_ACCELERATE
  .lSemantic = DIAXIS_DRIVINGR_ACCELERATE
  .lFlags = 0
  .ActionName = "Accelerate"
End With
With rgActions(2)
  .lAppData = eA_BRAKE
  .lSemantic = DIAXIS_DRIVINGR_BRAKE
  .lFlags = 0
  .ActionName = "Brake"
End With
'and so on.

It may be more efficient, however, to use a Sub procedure to assign the values to the DIACTION array in the DIACTIONFORMAT type directly as in the following example.

Dim m_diaf As DIACTIONFORMAT
Dim m_NumberofSemantics As Long

Private Sub Form_Load()

m_NumberofSemantics = 0

AddAction eA_STEER, DIAXIS_DRIVINGR_STEER, 0, "Steer"
AddAction eA_ACCELERATE, DIAXIS_DRIVINGR_ACCELERATE, 0, "Accelerate"
AddAction eA_BRAKE, DIAXIS_DRIVINGR_BRAKE, 0, "Brake"

' Genre-defined virtual buttons

AddAction eB_UPSHIFT, DIBUTTON_DRIVINGR_SHIFTUP, 0, "Upshift"
AddAction eB_DOWNSHIFT, DIBUTTON_DRIVINGR_SHIFTDOWN, 0, "DownShift"
AddAction eB_CYCLEVIEW, DIBUTTON_DRIVINGR_VIEW, 0, "Change View"

'  Actions not defined in the genre that can be assigned to any
'  button or axis

AddAction eA_VOLUME, DIAXIS_ANY_1, 0, "Volume"
AddAction eB_MUTE, DIBUTTON_ANY, 0, "Toggle Sound"

'  Actions not defined in the genre that must be assigned to
'  particular keys

AddAction eB_DRIVERVIEW, DIKEYBOARD_1, 0, "Driver View"
AddAction eB_COURSEVIEW, DIKEYBOARD_C, 0, "Course View"
AddAction eB_BRAKEBIAS, DIKEYBOARD_B, 0, "Brake Bias"

'  Actions mapped to keys as well as to virtual controls

AddAction eB_UPSHIFT, DIKEYBOARD_PRIOR, 0, "Upshift"
AddAction eB_DOWNSHIFT, DIKEYBOARD_NEXT, 0, "Downshift"
AddAction eB_STEER_LEFT, DIKEYBOARD_LEFT, 0, "Steer Left"
AddAction eB_STEER_RIGHT, DIKEYBOARD_RIGHT, 0, "Steer Right"
AddAction eB_ACCELERATE, DIKEYBOARD_UP, 0, "Accelerate"
AddAction eB_DECELERATE, DIKEYBOARD_DOWN, 0, "Decelerate"
AddAction eB_BRAKE, DIKEYBOARD_END, 0, "Brake"

'  Actions mapped to buttons as well as to virtual controls and keys

AddAction eB_UPSHIFT, DIMOUSE_BUTTON0, 0, "Upshift"
AddAction eB_DOWNSHIFT, DIMOUSE_BUTTON1, 0, "Downshift"

End Sub

Private Sub AddAction(user As Long, semantic As Long,_
                             flags As Long, strName As String)
ReDim Preserve m_diaf.ActionArray(m_NumberofSemantics)

With m_diaf.ActionArray(m_NumberofSemantics)
    .lAppData = user
    .lSemantic = semantic
    .lFlags = flags
    .ActionName = strName
End With
m_NumberofSemantics = m_NumberofSemantics + 1

End Sub

In the example, some actions are mapped to actual keys by using Keyboard Mapping Constants. Similar mappings to the mouse buttons and axes can be made by using Mouse Mapping Constants.

The DIACTION array is contained within the DIACTIONFORMAT type that also contains information about the genre, the application, and the desired scaling of axis data. Use the same instance of this type throughout the action mapping process. Some members will not be used immediately, but you can fill in the entire type before the next step, Finding Matching Devices.


Finding Matching Devices

After you define the application actions and the virtual controls or device objects to which these actions are to be mapped, the next step is to enumerate devices on the system to find those that best support the desired virtual controls.

To do so, pass the DIACTIONFORMAT type to DirectInput8.GetDevicesBySemantics. This method works in much the same way as DirectInput8.GetDIDevices.

Devices that have been configured by the user to match certain controls are always enumerated first. For example, if a user has configured a wheel as the primary steering device for driving games, then the wheel is enumerated first whenever devices that support DIAXIS_DRIVINGR_STEER are requested, taking precedence over other capable devices such as joysticks that have not been configured by the user. Otherwise, the order in which available devices are enumerated is determined by the degree to which they match the requested controls. However, the order in which devices are enumerated by Microsoft® DirectInput® is not guaranteed.

Once you have the enumeration, you can retrieve the default action mapping for each device, change any mappings you don't like, give the user an opportunity to reconfigure the device, and apply the action map. These steps are covered in Configuring the Action Map.


Configuring the Action Map

As each device is enumerated, you can retrieve the default action map, make changes in the default map, and apply the final mappings.

1. Obtaining the Device

Once the enumeration is complete, you can use the DirectInputEnumDevices8.GetItem method to obtain an instance of the DirectInputDeviceInstance8 class. DirectInputDeviceInstance8.GetGuidInstance enables the retrieval of the device GUID, which can in turn be passed to DirectInput8.CreateDevice. The resulting DirectInputDevice8 object can then be saved to a global variable for use in your application, and its methods can be used to get or set any properties of the device that you may wish to examine or change before building the action map.

2. Obtaining the Default Action Map

To obtain the default action map for the device, call DirectInputDevice8.BuildActionMap. Microsoft® DirectInput® takes the list of virtual controls specified in your DIACTIONFORMAT type and attempts to map these to physical device objects, returning the results in the same type. You should examine the lHow member of each DIACTION element to determine whether the control was successfully mapped. If it was, you can also ascertain what criterion was used in choosing the object—for example, configuration by the user or by the device manufacturer.

3. Making Changes to the Action Map

You now have the option of changing the default mappings, although it is not recommended that you do so. After examining the lSemantic member of the DIACTION type to determine which device object was mapped to an action, you can change that value. For example, if an action is mapped to DIJOFS_BUTTON9, but you want that action to be mapped to the trigger button instead, change the value to DIJOFS_BUTTON0 before applying the action map.

4. Applying the Action Map

When you are satisfied that the DIACTIONFORMAT type contains suitable mappings for the device, call DirectInputDevice8.SetActionMap. The value you assigned to the lAppData member of each DIACTION type now becomes bound to the control specified in the lSemantic member, which in turn is bound to a particular device object.

5. Mapping More than One Device

Repeat steps 1 through 4 for each device you want to use in your application. Suppose you want to map actions to both a joystick and the keyboard. In the racing-game example, the action defined in the game as eB_DRIVERVIEW was mapped to a keyboard key in the DIACTION array.

In that example, when BuildActionMap is called on any device that is not a keyboard, the lHow member of the DIACTION type for that element is set to DIAH_UNMAPPED. Continue examining the lHow member as each device in turn is enumerated, until a value other than DIAH_UNMAPPED is returned. This indicates that the device being currently mapped is a keyboard and the action has been successfully mapped to the requested key.

Even actions that have been successfully mapped can be mapped to another device. In the example, eB_UPSHIFT is given two DIACTION types.

As devices are successively enumerated, the eB_UPSHIFT action is mapped to a suitable button on one or more joysticks or other game controllers, and then again to the keyboard.

6. Displaying the Configuration

To show the user how actions have been mapped to devices, pass the DICD_DEFAULT flag to DirectInput8.ConfigureDevices. The property sheet for the device, containing a graphical representation of mappings, is displayed in view-only mode as in the following diagram. For more information on the mechanics of displaying the image, refer to the Using Action Mapping tutorial.

If the device manufacturer has not provided a device image, the mapping will be presented in text mode as in the following diagram.

Note Even if the cooperative level for the application is disabling the Microsoft® 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.

For more information about this property sheet, see User Configuration of the Device.


User Configuration of the Device

Microsoft® DirectInput® provides a property sheet that can be called from an application, enabling the user to configure devices for the application and view the current configuration. This property sheet can display various views of the device as provided by the manufacturer.

To enable user configuration, pass a DICONFIGUREDEVICESPARAMS type containing the DIACTIONFORMAT type describing the desired mapping, along with the DICD_EDIT flag, to the DirectInput8.ConfigureDevices method. Normally you would do this after calling DirectInputDevice8.BuildActionMap on all devices that will be used in the application.

The following illustration shows a typical property sheet in edit mode.

If the device manufacturer has not provided a device image, the mapping will be presented in text mode as in the following diagram.

Note Even if the cooperative level for the application is disabling the Microsoft® 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 property page for a device lists the friendly names that were provided by you in the ActionName member of each DIACTION type. If you have already called BuildActionMap for a device, the page also shows these names as callouts on the image of the device, with lines pointing to the device objects to which the actions have been mapped.

The user now has the opportunity to reassign game actions by first choosing a control then choosing an action from the menu. When the user closes the property sheet, the method returns and the modifications are stored in the DIACTIONFORMAT type that you passed in. You can now pass the same type to DirectInputDevice8.SetActionMap in order to implement the new mapping scheme.


Retrieving Action Data

You retrieve buffered data from action-mapped devices just as you would from unmapped devices: by calling DirectInputDevice8.GetDeviceData. However, instead of identifying device objects by examining the lOfs member of the DIDEVICEOBJECTDATA type, you obtain the action associated with the object from the lUserData member. This is the same value you passed to the device in the DIACTION type.

Remember that an action can be associated with more than one device. You still have to obtain data from both devices independently, but you can use the same routine to handle the data regardless of where it comes from.

The following sample code, which might be part of the game loop in a driving simulation, retrieves data from all devices in the m_Devices array. This array contains m_nDevices elements.

Dim iDevice As Integer
For iDevice = 1 To m_nDevices
    Dim didod(BUFFERSIZE) As DIDEVICEOBJECTDATA

    'Poll the device for data.
    m_Devices(iDevice).Poll

    'Determine how many pieces of data are available.
    m_nItems = m_Devices(iDevice).GetDeviceData(didod, 0)

    'Handle the actions regardless of what device returned them.
    For i = 0 To m_nItems
        Select Case didod(i).lUserData
            Case eA_STEER:
                Call SteerCar (didod(i).lData)
            Case eB_UPSHIFT:
                If (didod(i).lData & &H80) Then
                    Call ShiftGears (UPSHIFT)
            .
            .
            .
        End Select
    Next
Next

Note Axis constants for specific genres, such as DIAXIS_DRIVINGR_STEER or DIAXIS_SPACESIM_LATERAL, are used for absolute joystick data. The action mapper attempts to map this virtual control to a device object that returns absolute data. The data returned from that device should be processed accordingly in the application. Device constants such as DIMOUSE_XAXIS, however, are expected to return relative data.

When retrieving data, each potential source of data should be processed separately to keep one device object from possibly overwriting the data from another. For instance, the following DIACTION types are used in an action map to control direction.

With rgActions(0)
  .lAppData = INPUT_LEFTRIGHT_ABS_AXIS
  .lSemantic = DIAXIS_SPACESIM_LATERAL
  .lFlags = 0
  .ActionName = "Turn"
End With
With rgActions(1)
  .lAppData = INPUT_LEFTRIGHT_REL_AXIS
  .lSemantic = DIMOUSE_XAXIS
  .lFlags = 0
  .ActionName = "Turn"
End With
With rgActions(2)
  .lAppData = INPUT_TURNLEFT
  .lSemantic = DIKEYBOARD_LEFT
  .lFlags = 0
  .ActionName = "Turn left"
End With
With rgActions(3)
  .lAppData = INPUT_TURNRIGHT
  .lSemantic = DIKEYBOARD_RIGHT
  .lFlags = 0
  .ActionName = "Turn right"
End With

The application's input loop processes data from these actions in the following case statement.

Select Case adod(j).lUserData
    Case INPUT_LEFTRIGHT_ABS_AXIS:
        g_dwAbsLR = adod(j).lData
    Case INPUT_LEFTRIGHT_REL_AXIS:
        g_dwRelLR = adod(j).lData
    Case INPUT_TURNLEFT:
        g_bLeft = (adod(j).lData <> 0)
    case INPUT_TURNRIGHT:
        g_bRight = (adod(j).lData <> 0)
End Select

Note that each data source is assigned to a separate variable rather than all data sources being assigned a generic "turn" variable. If they to share a generic variable, holding down the LEFT ARROW key and then moving the joystick would cause the keyboard information to be lost. This is because the joystick data would overwrite the variable.

In addition to individual variables, there are many ways to process the data. Whatever method is used, care should be taken in the processing of data to avoid unexpectedly lost information.


Maintaining Files During Development

During a development cycle, unused and out of date .ini files may accumulate due to frequent action map changes, Microsoft® DirectX® reinstallations, multiple users, and other normal development situations. These files could possibly cause unexpected mappings or reports of "recent" (DIEDBS_RECENTDEVICE) for devices that would not be expected to return that value. For this reason, it is good practice to occasionally delete any unused .ini files. These files can be found in C:\Program Files\Common Files\DirectX\DirectInput\User Maps.

Note The procedure suggested above is meant to be performed only manually during a development cycle to ensure that the development environment is in a cleaner state. A shipping application should never delete user maps as this could result in the loss of a user's preferred settings.


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. Microsoft® 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
  • Effect Enumeration
  • Loading Effects from a File
  • Information About a Supported Effect
  • Creating an Effect
  • Effect Direction
  • Envelopes and Offsets
  • Effect Playback
  • Downloading and Unloading Effects
  • Changing an Effect
  • Gain
  • Force-Feedback State
  • 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 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.

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.

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.

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.


Effect Enumeration

The DirectInputDevice8.GetEffectsEnum method enumerates effects supported by the device. It returns a DirectInputEnumEffects object representing the collection of supported effects. Methods of DirectInputEnumEffects can be used to get information about a particular effect.

It is important to distinguish between supported effects and created effects, or effect objects. A supported effect might be a constant force that can be shaped by an envelope. However, this effect has no properties such as magnitude, direction, duration, attack, or fade. You set these properties when you create an effect object in your application. 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.

The following code example shows how an application could enumerate hardware-specific effects, looking for a particular effect supported by the Microsoft® SideWinder® joystick. If the desired effect is not found, the application substitutes one of the standard effects:

Const BasketballDribble = _
        "{E84CD1AC-81FA-11D0-94AB-0080C74C7E95}"
Dim diEnumEffects As DirectInputEnumEffects
Dim EffGuid As String
Dim i As Integer

' diDev is a DirectInputDevice object.
Set diEnumEffects = didev.GetEffectsEnum(DIEFT_HARDWARE)
For i = 1 To diEnumEffects.GetCount
  If diEnumEffects.GetEffectGuid(i) = BasketballDribble Then
    EffGuid = BasketballDribble
    Exit For
  End If
Next i
If EffGuid <> BasketballDribble Then
  EffGuid = "GUID_Sine"
  ' Set parameters for emulated dribble here
  .
  .
  .
End If

Ultimately, EffGuid is passed to DirectInputDevice8.CreateEffect.


Loading Effects from a File

Using the Force Editor supplied with the Microsoft® DirectX® SDK, or another application that uses the same file format, you can design effects and save them in a file. You can then use these effects in any application by loading them at run time.

To load effects, call the DirectInputDevice8.CreateEffectFromFile method. The resulting DirectInputEffect object may then be used normally.


Information About a Supported Effect

In Microsoft® DirectX® for Microsoft Visual Basic®, information about a supported effect must be obtained from the DirectInputEnumEffects enumeration object. See Effect Enumeration.

The following code example gets information about the first enumerated effect and determines whether the direction of the effect can be changed without stopping and restarting it. Assume that diEnumEffects is an initialized DirectInputEnumEffects object.

Dim params As Long
params = diEnumEffects.GetDynamicParams(1)
If params And DIEP_DIRECTION Then
  Debug.Print "Direction is dynamic."
End If


Creating an Effect

Create an effect object by using the DirectInputDevice8.CreateEffect method, as in the following code example, where didev is a DirectInputDevice8 object. This example creates a very simple effect that pulls the joystick away from the user at full force for half a second.

Dim effectInfo As DIEFFECT
Dim objDIEffect As DirectInputEffect

With effectInfo
  .constantForce.lMagnitude = 10000
  .lGain = 10000
  .lDuration = 500000
  .x = 18000
  .lTriggerButton = -1  ' No trigger button
End With

didev.Acquire
Set objDIEffect = didev.CreateEffect("GUID_ConstantForce", effectInfo)

The first parameter to CreateEffect can be one of the predefined GUID aliases, or an actual GUID in string form known from hardware documentation or retrieved for an enumerated effect by using the DirectInputEnumEffects.GetEffectGuid method.

The relevant members of the DIEFFECT type vary according to the kind of effect. Constant forces are the simplest kind, requiring only a single type-specific parameter. The lGain, lDuration, and lTriggerButton members should be set for all effects, since the default values of 0 are not usually suitable.

By default, the direction of the effect is expressed in polar coordinates, meaning that DIEFFECT.x holds the direction from which the force comes, in hundredths of a degree, and DIEFFECT.y must be 0.

Effects are automatically downloaded to the device when created, provided the device is not full and is acquired at the exclusive cooperative level.


Effect Direction

Microsoft® DirectX® for Microsoft Visual Basic® supports two-axis effects on the x-axis and y-axis.

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 in order 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 or Cartesian coordinates. By default, polar coordinates are used, and the direction is specified in the x member of the DIEFFECT type, with y always 0. To use Cartesian coordinates, you must specify DIEFF_CARTESIAN in the lFlags member and supply values in both x and y.

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.

Cartesian coordinates are similar to 3-D vectors and are most useful for matching a force to the user's orientation in a 3-D environment. 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.

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 was assigned as follows, where effectInfo is a valid DIEFFECT type.

effectInfo.x = 18000

The effectInfo.y member must be set to 0, which it is by default. For greater clarity, the assignment could also be expressed this way:

effectInfo.x = 180 * DI_DEGREES

How do you accomplish the same thing with Cartesian coordinates? Presuming that you have used the DIEFF_CARTESIAN flag in the lFlags member, you would specify the direction like this:

effectInfo.x = 0
effectInfo.y = 1

As long as the x value is 0, any number in the y value will give the same effect because only direction is indicated, not magnitude. The theory of effect directions can be difficult to grasp, but the practice is fairly straightforward.

The following code example reverses the direction of a force represented by the DirectInputEffect object dieff, which was created using the global DIEFFECT type effectInfo:

effectInfo.lFlags = DIEFF_CARTESIAN
effectInfo.X = effectInfo.X * -1
effectInfo.Y = effectInfo.Y * -1
Call dieff.SetParameters(effectInfo, DIEP_DIRECTION)

Examples of Setting Effect Direction

Single-Axis Effects with Cartesian Coordinates

Setting up the direction for a single-axis effect is easy because you need to specify only the direction of the axis. Put the DIEFF_CARTESIAN flag in the lFlags member of the DIEFFECT structure and set the x or y member to either 1 or -1, depending on the direction you want the effect to come from.

The following code example sets an x-axis effect with a right to left direction:

Dim eff As DIEFFECT

eff.lFlags = DIEFF_CARTESIAN Or DIEFF_OBJECTOFFSETS
eff.x = 1
eff.y = 0

Single-Axis Effects with Polar Coordinates

The same effect could be set up just as easily using polar coordinates. Put the DIEFF_POLAR flag in the lFlags member of the DIEFFECT structure and set the x member to either 0, 90, 180, or 270 degrees.

The following code example sets the same x-axis effect as in the previous example:

Dim eff As DIEFFECT

eff.lFlags = DIEFF_POLAR Or DIEFF_OBJECTOFFSETS
eff.x = 90 * DI_DEGREES
eff.y = 0

Two-Axis Effects with Polar Coordinates

Setting up the direction for a polar two-axis effect is no different than a polar one-axis effect. The only difference is that the range of degree values is not restricted to the four axis values.

The following code example sets an effect originating from the user's upper right:

Dim eff As DIEFFECT

eff.lFlags = DIEFF_POLAR Or DIEFF_OBJECTOFFSETS
eff.x = 45 * DI_DEGREES
eff.y = 0

Two-Axis Effects with Cartesian Coordinates

Setting up the direction for a Cartesian two-axis effect is straightforward as well. First, set the DIEFF_CARTESIAN flag in lFlags. The x and y members will be filled with the x and y coordinates of any point on a line of direction through that point and the origin (0,0).

The following code example sets the same effect as in the previous sample:

Dim eff As DIEFFECT

eff.lFlags = DIEFF_CARTESIAN Or DIEFF_OBJECTOFFSETS
eff.x = 1
eff.y = 2


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, set the bUseEnvelope member of the DIEFFECT type to True and initialize the envelope member, which is a DIENVELOPE type.

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 DirectInputEnumEffects.GetStaticParams method and check for the DIEP_ENVELOPE flag in the returned value.

To apply an offset, set the lOffset member of the DIPERIODICFORCE or DICONDITION type used in the periodicForce, conditionX or conditionY member of DIEFFECT. For periodic effects, the absolute value of the offset plus the magnitude of the effect must not exceed 10,000.

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.


Effect Playback

There are two principal ways to start playback of an effect: manually by a call to the DirectInputEffect.Start method, or automatically in response to a button press. Playback also starts when you change an effect by calling the DirectInputEffect.SetParameters method with the DIEP_START flag.

Passing –1 in the iterations parameter of the 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 iterations to 1 and set the lDuration member of the DIEFFECT type to –1. (This is the type passed to the DirectInputDevice8.CreateEffect method.)

Note Some devices do not support multiple iterations of an effect and accept only the value 1 in the iterations parameter to the Start method.

To associate an effect with a button press, set the lTriggerButton member of the DIEFFECT type. Also set the lTriggerRepeatInterval 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 DirectInputEffect.Unload method or set the parameters for the effect with lTriggerButton set to -1 or 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. This step is not necessary for effects not associated with a trigger because they are automatically downloaded if necessary whenever the Start method is called.

If an effect has a finite duration and is started by a call to the Start method, it stops playing when the time has elapsed. If an effect has been instructed to play continually, playback ends only when the DirectInputEffect.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.


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 DirectInputEffect.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 DirectInputEffect.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 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 DirectInputEffect.Unload method. You can also remove all effects by resetting the device through a call to the DirectInputDevice8.SendForceFeedbackCommand method.

When you create a force-feedback device, the hardware and driver are reset, so any existing effects are cleared.


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 DirectInputEffect.SetParameters method.

To find which effect parameters can be changed while an effect is playing, call the DirectInputEnumEffects.GetDynamicParams method.

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 to SetParameters.

The following code example changes the magnitude of a constant force represented by the DirectInputEffect object dieff, which was created using the global DIEFFECT type effectinfo:

effectinfo.constantForce.lMagnitude = 5000
Call dieff.SetParameters(effectinfo, DIEP_TYPESPECIFICPARAMS)

Note You must set the DIEP_TYPESPECIFICPARAMS flag if you are changing the condition, constantforce, periodicforce, or rampforce members of DIEFFECT.


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.

You can set the gain for the entire device by using the DirectInputDevice8.SetProperty method.

You must set the gain for individual effects when creating them by putting a value in the lGain member of the DIEFFECT type. (If lGain is 0, the effect will not be felt.) You can change this value later by using DirectInputEffect.SetParameters, passing DIEP_GAIN in the flags 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.


Force-Feedback State

The DirectInputDevice8.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 DirectInputDevice8.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 about whether the device is currently powered.


Effect Types

This section contains information specific to the following types of force-feedback effects:

  • Constant Forces
  • Ramp Forces
  • Periodic Effects
  • Conditions
  • Custom Forces
  • Device-Specific Effects


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 DirectInputDevice8.CreateEffect method. You can also pass any other GUID obtained by the DirectInputEnumEffects.GetEffectGuid method, provided the low byte of the value returned by DirectInputEnumEffects.GetType 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.

The magnitude of a constant force is contained in a DICONSTANTFORCE type in the constantForce member of DIEFFECT. A negative magnitude has the effect of reversing the direction of the force.


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 DirectInputDevice8.CreateEffect method. You can also pass any other GUID obtained by the DirectInputEnumEffects.GetEffectGuid method, provided the low byte of the value returned by DirectInputEnumEffects.GetType is equal to DIEFT_RAMPFORCE. In this way, you can use hardware-specific ramp forces designed by the manufacturer.

The starting and ending magnitude of the force are defined in a DIRAMPFORCE type in the rampForce member of DIEFFECT. The duration cannot be infinite, and therefore DIEFFECT.lDuration must be a positive value.


Periodic Effects

Periodic effects are waveform effects. Microsoft® 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.

To create a periodic force, pass one of the following values in the guid parameter of the DirectInputDevice8.CreateEffect method:

  • "GUID_Square"
  • "GUID_Sine"
  • "GUID_Triangle"
  • "GUID_SawtoothUp"
  • "GUID_SawtoothDown"

You can also pass any other GUID obtained by the DirectInputEnumEffects.GetEffectGuid method, provided the low byte of the value returned by DirectInputEnumEffects.GetType is equal to DIEFT_PERIODIC. In this way, you can use hardware-specific periodic forces designed by the manufacturer.

The type-specific parameters for periodic effects are contained in a DIPERIODICFORCE type in the periodicForce member of DIEFFECT.

Do not confuse the period of a periodic effect (DIEFFECT.periodic.lPeriod) with the sample period (DIEFFECT.lSamplePeriod). The period is the length of time 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.


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.

Microsoft® 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 DirectInputDevice8.CreateEffect method:

  • "GUID_Spring"
  • "GUID_Damper"
  • "GUID_Inertia"
  • "GUID_Friction"

You can also pass any other GUID obtained by the DirectInputEnumEffects.GetEffectGuid method, provided the low byte of the value returned by DirectInputEnumEffects.GetType is equal to DIEFT_CONDITION. In this way, you can use hardware-specific conditions designed by the manufacturer.

The type-specific parameters for a condition are described in a DICONDITION type in the conditionX and conditionY members of the DIEFFECT type.

An application should call the DirectInputEnumEffects.GetType method and examine the return value member 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 DICONDITION.lNegativeCoefficient, 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 lNegativeSaturation and the value in lPositiveSaturation is used as the negative saturation level. Finally, if the effect does not return the DIEFT_SATURATION flag, it ignores both the lPositiveSaturation and lNegativeSaturation values, and no saturation is applied.

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.

You should also check the value returned by GetType 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 type will be ignored.

To create a single-axis effect, set the coefficients for the unused axis to 0 in the conditionX or conditionY member of the DIEFFECT type.

DirectX® for Microsoft Visual Basic® does not support rotation of conditions.


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.

To create a custom force, first define an array of magnitudes, all in the range from –10,000 through 10,000. Then pass this array to the DirectInputDevice8.CreateCustomEffect method.

Set the samplePeriod parameter and the lSamplePeriod member of the DIEFFECT type to the same value. This is the length of 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 DIEFFECT.lDuration has elapsed.


Device-Specific Effects

Hardware drivers can support special effects that do not fit into the categories defined by Microsoft® DirectInput®. The type-specific parameters for these effects may be either hard-coded or modifiable by the application.

Microsoft® DirectX® for Microsoft Visual Basic® does not support hardware effects that require custom type-specific parameters.

The hardware vendor must provide a GUID identifying the device-specific effect. Your application then must initialize a DIEFFECT type, as with any other effect. You then pass this type, along with the GUID, to the DirectInputDevice8.CreateEffect method.

When you obtain information about a device-specific effect in a DirectInputEnumEffects enumeration, the low byte of the return value of DirectInputEnumEffects.GetType 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 DIEFFECT type must be initialized as it would be for a standard force of that category. For example, if the effect type is DIEFT_CONSTANTFORCE, the constantForce member must be initialized.

DirectInput passes the GUID and the DIEFFECT type 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.


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
  • Force Editor
  • GetDeviceData and an Unacquired Device

Designing for Previous Versions of DirectInput

If you want to design for DirectX 7 (the only previous version of DirectX that supports Microsoft Visual Basic®), you must include the DirectX 7 for Visual Basic type library. Refer to the DirectX 7 documentation for more information.

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)

Without changing how DirectInput returns data, this value invokes an emulation mode that is not susceptible to those delays. The Microsoft software development kit (SDK) includes two registry files—Mouse and Keyboard Emulation On.reg and Mouse and Keyboard Emulation Off.reg—to activate and deactivate this emulation mode. The files are located under (SDK root)\Samples\Multimedia\DirectInput\Bin.

Note The emulation value is supported only in debug mode when your device is using an Exclusive and Foreground cooperative level. You can switch to debug mode in the SDK Control Panel if you are using DirectX 8.0 or later. If you are using earlier versions of DirectX, you must do a debug SDK install in order to get the correct debug DLL onto your machine.

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, AppldFlag.

The following table lists the possible values for AppldFlag.

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 AppldFlag is set to 3, all builds of applications with the same file name will use the same key.

Note The AppldFlag value should be set only on test machines to avoid the possibility of two applications that ship with the same file name interfering with each other's input control mappings.

Force Editor

Description

The Force Editor application enables you to design force-feedback effects and test them singly or in combination. Effects can be saved to file and then loaded into DirectInput applications.

Path

Executable: (SDK root)\Bin\Dxutils\Fedit.exe

User's Guide

The Force Editor has its own documentation. Once you've launched Fedit.exe, press F1 for online Help. The Help file can also be launched directly.

(SDK root)\Bin\Dxutils\Fedit.chm

GetDeviceData and an Unacquired Device

When using the debug version of Microsoft DirectPlay®, you may notice some unusual behavior from the GetDeviceData method when a device is unacquired. If you call GetDeviceData and the device is not acquired, random bytes will be placed in the device data buffer and the value of the pdwInOut parameter will not be changed. Therefore, if your application does not check for the DPNERR_UNACQUIRED error code, your application will mistakenly determine that there is data in the buffer.


DirectInput Visual Basic Tutorials

This section contains the following tutorials, each providing step-by-step instructions for implementing Microsoft® DirectInput® in a Microsoft Visual Basic® application.

  • Tutorial 1: Using the Keyboard

    The first tutorial shows how to add DirectInput keyboard support to an existing application, using event polling.

  • Tutorial 2: Using the Mouse

    The next tutorial takes you through the steps of providing DirectInput mouse support in an application, using the exclusive cooperative level and event notification. The tutorial is based on the ScrawlB Sample, and focuses on buffered data.

  • Tutorial 3: Using the Joystick

    This tutorial shows how to enumerate all the joysticks connected to a system, how to create and initialize DirectInputDevice objects for each of them in a callback function, and how to retrieve immediate data.

  • Tutorial 4: Using Force Feedback

    This tutorial shows how to implement simple force-feedback effects in an application.

  • Tutorial 5: Using Action Mapping

    The final tutorial shows how to set up, apply, and use the new Action Mapping functionality of DirectInput.


Tutorial 1: Using the Keyboard

To prepare for keyboard input, you first create a DirectInput8 object. Then you create a DirectInputDevice8 object representing the keyboard. The DirectInputDevice8 class methods are used to set the behavior of the device and retrieve data.

The tutorial divides the required tasks into the following steps.

  • Step 1: Creating the DirectInput8 Object and the Keyboard Device
  • Step 2: Setting the Keyboard Parameters
  • Step 3: Gaining Access to the Keyboard
  • Step 4: Retrieving Immediate Data from the Keyboard
  • Step 5: Closing Down the DirectInput System


Step 1: Creating the DirectInput8 Object and the Keyboard Device

The first step in setting up the Microsoft® DirectInput® system is to create a single DirectInput8 object as overall manager. This is done with a call to the DirectX8.DirectInputCreate method, typically in the Load event handler for the main form or in Sub Main.

Dim dx As New DirectX8
Dim di As DirectInput8

Set di = dx.DirectInputCreate()

The keyboard is then created as a standard device by passing the keyboard GUID alias to DirectInput8.CreateDevice.

Dim didev As DirectInputDevice8
Set didev = di.CreateDevice("GUID_SysKeyboard")

Once the keyboard device is created, its methods will be used to set its data format and cooperative level in Step 2: Setting the Keyboard Parameters.


Step 2: Setting the Keyboard Parameters

After creating a DirectInputDevice8, your application must set the device's data format. For keyboards, as with other standard devices, this is a very simple task. Call the DirectInputDevice8.SetCommonDataFormat method, specifying the data format provided by Microsoft® DirectInput® by using the DIFORMAT_KEYBOARD constant as the parameter. You must set the data format even if you intend to retrieve buffered data.

Call didev.SetCommonDataFormat(DIFORMAT_KEYBOARD)

DirectInput identifies the device objects by their offset within the data format. In the case of the keyboard, keys are identified by their offsets within the DIKEYBOARDSTATE type.

Before your application can gain access to the keyboard, it must set the device's behavior using the DirectInputDevice8.SetCooperativeLevel method, as follows:

didev.SetCooperativeLevel Me.hWnd, _
        DISCL_NONEXCLUSIVE Or DISCL_BACKGROUND

This method accepts the handle to the window to be associated with the device, and exactly two flags (either DISCL_EXCLUSIVE or DISCL_NONEXCLUSIVE, plus either DISCL_FOREGROUND or DISCL_BACKGROUND), indicating the desired cooperative level. However, DirectInput does not support exclusive access to keyboard devices, so the DISCL_NONEXCLUSIVE flag must always be used in the case of keyboards as it is here.

The example also sets the background cooperative level, so input will be available regardless of whether the form is in the foreground. Note also that keystrokes continue to be passed through to whatever application has the focus. Most applications don't need input when they're in the background, and in such cases the DISCL_FOREGROUND flag should be set instead.

Now that the keyboard device has been created and set up, it must be acquired. This is shown in Step 3: Gaining Access to the Keyboard.


Step 3: Gaining Access to the Keyboard

After your application sets the keyboard's behavior, it can acquire access to the device by calling the DirectInputDevice8.Acquire method. The application must acquire the device before retrieving data from it. The Acquire method accepts no parameters.

Call didev.Acquire

In the sample, the application is unlikely to fail to acquire the keyboard, or to lose it later, because it is using the background, nonexclusive cooperative level. However, in general it is good practice to handle errors on calls to Acquire as well as when attempting to retrieve data.

You are now ready to begin receiving data from the keyboard. This is shown in Step 4: Retrieving Immediate Data from the Keyboard.


Step 4: Retrieving Immediate Data from the Keyboard

Once a device is acquired, your application can start retrieving data from it. The simplest way to do this is to call the DirectInputDevice8.GetDeviceStateKeyboard method, which takes a snapshot of the device's state at the time of the call.

The GetDeviceStateKeyboard method accepts as its single parameter a DIKEYBOARDSTATE type, which simply contains an array of 256 bytes.

The following sample code retrieves the state of the keyboard.

Dim state As DIKEYBOARDSTATE
Call didev.GetDeviceStateKeyboard(state)

After retrieving the keyboard's current state, your application may respond to specific keys that were pressed at the time of the call. Each element in the buffer represents a key. If an element's high bit is set equal to 1, the key was pressed at the moment of the call. Otherwise, the key was up. To check the state of a given key, use the constants of the CONST_DIKEYFLAGS enumeration to index the buffer for a given key.

The following sample code shows how an application might move a vehicle around in response to the arrow keys.

If state.Key(DIK_UP) And &H80 Then
  ' Move the vehicle up
End If
if state.Key(DIK_DOWN) And &H80 Then
  ' Move the vehicle down
End If
' And so on.

The following form could also be used.

If state.Key(DIK_UP) Then
  ' Move the vehicle up
End If

Keep in mind that DIK_UP is a single key, the dedicated up arrow key. DirectInput treats the 8 key on the numerical keypad as a distinct key, and gives it the same identifier regardless of whether NUM LOCK is on. In order to allow input from either of the arrow keys, you would have to write code as in the following sample.

If state.Key(DIK_UP) Or state.Key(DIK_NUMPAD8) Then
  ' Move the vehicle up
End If


Step 5: Closing Down the DirectInput System

When an application is about to close, it should release all Microsoft—> DirectInput—> devices. This is done using the DirectInputDevice8.Unacquire method, generally in the Unload event handler as shown in the following code sample.

Private Sub Form_Unload(Cancel As Integer)
    didev.Unacquire
End Sub


Tutorial 2: Using the Mouse

This tutorial focuses on using the mouse at the exclusive cooperative level and shows how to retrieve buffered data in response to notifications. The sample code is based on the ScrawlB Sample.

The tutorial is divided into the following steps.

  • Step 1: Setting Up the Mouse
  • Step 2: Setting Up Notifications
  • Step 3: Managing Exclusive Access to the Mouse
  • Step 4: Retrieving Buffered Data from the Mouse


Step 1: Setting Up the Mouse

First steps in setting up the mouse for use under Microsoft® DirectInput® are similar to those taken in Tutorial 1: Using the Keyboard. In the ScrawlB sample, initialization takes place in Sub Main after some global declarations.

Public objDX As New DirectX8
Public objDI As DirectInput8
.
.
Set objDIDev = objDI.CreateDevice("guid_SysMouse")
Call objDIDev.SetCommonDataFormat(DIFORMAT_MOUSE)
Call objDIDev.SetCooperativeLevel(frmCanvas.hwnd, _
        DISCL_FOREGROUND Or DISCL_EXCLUSIVE)

As opposed to the instance of the keyboard, DirectInput takes exclusive control of the mouse. The result is that as long as the application has the mouse in the acquired state, Microsoft Windows® does not generate mouse messages or display the system cursor. Note that DISCL_EXCLUSIVE must be combined with DISCL_FOREGROUND; it is not possible for an application to have exclusive access to the mouse and also receive input when it loses the focus.

Because the ScrawlB sample application is taking full responsibility for the mouse, it must also track the position of its private cursor, and it must scale movement of the cursor to movements of the mouse. The following global variables are used to store the cursor coordinates (in pixels relative to the upper left corner of the main form) and movement scaling.

Public g_cursorx As Long
Public g_cursory As Long
Public g_Sensitivity

In Sub Main, the application sets the buffer size so that it can receive buffered data, using the DirectInputDevice8.SetProperty method.

Dim diProp As DIPROPLONG
diProp.lHow = DIPH_DEVICE
diProp.lObj = 0
diProp.lData = BufferSize    ' BufferSize is a constant

Call objDIDev.SetProperty("DIPROP_BUFFERSIZE", diProp)

You are now ready to specify how mouse events will trigger data retrieval in Step 2: Setting Up Notifications


Step 2: Setting Up Notifications

Rather than polling for mouse input in Sub Main, the ScrawlB sample application relies on Microsoft® DirectInput® to notify it whenever a mouse event takes place. As part of initialization, the application gets an event handle and passes it to DirectInputDevice8.SetEventNotification.

Dim EventHandle As Long

EventHandle = objDX.CreateEvent(frmCanvas)
Call objDIDev.SetEventNotification(EventHandle)

DirectInput will now notify any object that implements the DirectXEvent8 class. In the case of ScrawlB, the implementing object is the frmCanvas form, whose declarations section contains the following line.

Implements DirectXEvent8

This line causes frmCanvas to inherit all the methods of the DirectXEvent8 class. The only method implemented by that class is DirectXEvent8.DXCallback, and the inheriting class must implement this method. DirectInput calls this method whenever an input event is signaled.

The implementation of DXCallback is covered under Step 4: Retrieving Buffered Data from the Mouse.

There are responsibilities involved in maintaining an exclusive access level. They are covered in Step 3: Managing Exclusive Access to the Mouse


Step 3: Managing Exclusive Access to the Mouse

The ScrawlB sample demonstrates using the mouse with the exclusive foreground cooperative level. At this level, Microsoft® Windows® does not track the mouse while it is acquired by the application. There are three major consequences for the application.

  • It is entirely responsible for displaying a cursor if one is needed, and for moving it at an appropriate speed in response to Microsoft DirectInput® data.
  • It loses acquisition when the user switches to another application by using the keyboard, and must reacquire the mouse when the user switches back.
  • It must provide a means for Windows to get the mouse back whenever the user needs to use the system cursor—for example, to navigate a menu within the application.

ScrawlB handles the first responsibility by keeping a private record of mouse movements, adjusted by a user-defined sensitivity value, and displaying an icon that serves as a cursor for drawing.

ScrawlB loses acquisition of the mouse involuntarily whenever the application window moves to the background. When it comes to the foreground again, the application automatically reacquires the mouse by calling DirectInputDevice8.Acquire in the MouseMove event handler, which is called whenever Windows sends a mouse message to the application. This happens as soon as the system cursor moves over the client window, or the client window gains the focus under the system cursor. Once ScrawlB reacquires the mouse, of course, no more Windows mouse messages are sent, so the Form_MouseMove method is not called in response to subsequent mouse events.

In order to let the user navigate the shortcut menu, or to display the system cursor for some other purpose such as resizing the window, ScrawlB calls the DirectInputDevice8.Unacquire method whenever the user opens the menu. When the menu is closed, Form_MouseMove is called and the mouse is reacquired, unless the user has chosen Suspend from the menu, in which case a flag is set. This flag prevents Form_MouseMove from reacquiring, so that the user can continue using the system cursor.

The sample application demonstrates one more technique for releasing the mouse. If the user opens the system menu by pressing ALT+SPACE, Windows sends a WM_ENTERMENULOOP message. This message is intercepted by a subclassed window procedure, which then unacquires the mouse. As long as Windows is using the system cursor for navigating the menu or allowing the user to move or resize the window, it sends no mouse messages to frmCanvas, so the application doesn't attempt to reacquire the mouse in Form_MouseMove. A similar technique could be used for intercepting other Windows messages such as WM_ACTIVATE or WM_ACTIVATEAPP, so that the application could fully control acquisition and unacquisition of the mouse in response to gaining and losing the focus.

You are now ready to receive data from the mouse in Step 4: Retrieving Buffered Data from the Mouse


Step 4: Retrieving Buffered Data from the Mouse

The ScrawlB sample retrieves buffered mouse data inside the DirectXEvent8.DXCallback method implemented by frmCanvas. This method is called each time an input event is signaled.

The method declares an array of the same size as the buffer Microsoft® DirectInput® is using to store the data. This is the size that was set previously by a call to DirectInputDevice8.SetProperty.

Dim diDeviceData(1 To BufferSize) As DIDEVICEOBJECTDATA

Also required are a variable to receive the number of items actually retrieved, a loop counter, and a variable to track the previous sequence number of an event.

Dim NumItems As Integer
Dim i As Integer
Static OldSequence As Long

The application now retrieves all the data available, in a single call to DirectInputDevice8.GetDeviceData.

On Error GoTo INPUTLOST
NumItems = objDIDev.GetDeviceData(diDeviceData, 0)
On Error GoTo 0

Note the error trap. One of the events that DirectInput will signal is loss of acquisition. If the user switches to another application, for instance, ScrawlB will no longer have the mouse in the acquired state. An event will be signaled and GetDeviceData will be called, but the method will fail because data can be retrieved only from a device that is in an acquired state.

The application next iterates through the retrieved items and examines the data in the DIDEVICEOBJECTDATA type, comparing the lOfs member against the constants for the various buttons and axes that are of interest. For the x-axis, for instance, the application extracts the change in axis position from the lData member and uses this to adjust the cursor position, taking into account the user-defined sensitivity, as in the following code sample.

For i = 1 To NumItems
    Select Case diDeviceData(i).lOfs
        Case DIMOFS_X
            g_cursorx = g_cursorx + diDeviceData(i).lData * _
                g_Sensitivity

The application also examines the sequence number and compares it with the previous one. If two axis events have the same sequence number, the mouse has been moved diagonally. To avoid a staircase effect, it is not desirable to update the cursor position or draw a line until both movements have been taken into account.

            If OldSequence <> diDeviceData(i).lSequence Then
                UpdateCursor
                OldSequence = diDeviceData(i).lSequence
            Else
                OldSequence = 0
            End If

For the buttons, the method determines the event type by checking the appropriate bit in lData. If the bit is set, the mouse button was pressed; otherwise, it was released. Remember, GetDeviceData does not return the current state of the device, so it is up to the application to keep a private record of whether a button is being held down. For the left button, ScrawlB keeps this information in the Drawing variable.

        Case DIMOFS_BUTTON0
            If diDeviceData(i).lData And &H80 Then
                Drawing = True

                ' Keep record for Line function
                CurrentX = g_cursorx
                CurrentY = g_cursory

                ' Draw point in case button-up follows immediately
                PSet (g_cursorx, g_cursory)
            Else
                Drawing = False
            End If
.
.
    End Select
Next i


Tutorial 3: Using the Joystick

This tutorial shows how to create a joystick device, set its properties, and retrieve immediate data. The example code is based on the Joystick Sample.

The tutorial divides the required tasks into the following steps.

  • Step 1: Enumerating Devices and Creating the Joystick
  • Step 2: Getting Joystick Capabilities
  • Step 3: Setting Joystick Properties
  • Step 4: Retrieving Immediate Data from the Joystick


Step 1: Enumerating Devices and Creating the Joystick

Because there is no such thing as a system joystick in the same sense that there can be a system keyboard or mouse, in order to create a DirectInputDevice8 object for a joystick you first need to obtain an instance GUID, or globally unique identifier. Generally, this is done by enumerating the available joysticks, presenting the user with a choice, and then obtaining the information for the selected device.

As with all devices, the DirectInput system must first be created.

Dim dx As New DirectX8
Dim di As DirectInput8

Set di = dx.DirectInputCreate()

The next step is enumeration of devices using the DirectInput8.GetDIDevices method. As a parameter to this method, flags are passed indicating that the application should enumerate only game controller devices that are physically attached to the system. The results of this enumeration are stored in an instance of the DirectInputEnumDevices8 class.

Dim diDev As DirectInputDevice8
Dim diDevEnum As DirectInputEnumDevices8

Set diDevEnum = di.GetDIDevices( _
            DI8DEVCLASS_GAMECTRL, DIEDFL_ATTACHEDONLY)

Once the enumeration is complete, assuming at least one joystick was found, that information can be manipulated. In the case of the Joystick Sample, the devices are added to a list box from which the user can make a choice. The DirectInputEnumDevices8.GetCount method specifies how many items are contained in the enumeration.

'Add attached joysticks to the list box
Dim i As Integer
For i = 1 To diDevEnum.GetCount
    Call lstJoySticks.AddItem( _
        diDevEnum.GetItem(i).GetInstanceName)
Next

GetInstanceName returns a friendly name for the device.

At this point, the Joystick Sample initializes an event handle to associate with the device. This is used at the end of Step 2: Getting Joystick Capabilities.

Dim EventHandle as Long
EventHandle = dx.CreateEvent(Me)

When the user selects a joystick from the list, the device is created and initialized in the lstJoySticks_Click procedure. Because there are no standard GUIDs to pass to DirectInput8.CreateDevice, as there are for the system keyboard and system mouse, the GUID of the device instance must be extracted by using the DirectInputDeviceInstance8.GetGuidInstance method. Note that as with all enumerated collections in Microsoft DirectX® for Microsoft Visual Basic®, the device enumeration is 1-based. Therefore, the index is one greater than the index of the selected item in the list box. The list box must also be unsorted.

Set diDev = di.CreateDevice(diDevEnum.GetItem( _
        lstJoySticks.ListIndex + 1).GetGuidInstance)

The joystick must also be initialized for cooperative level and format. In this case, the DIFORMAT_JOYSTICK format is used. Another format, DIFORMAT_JOYSTICK2 is also available for joysticks with a larger assortment of controls.

diDev.SetCommonDataFormat DIFORMAT_JOYSTICK
diDev.SetCooperativeLevel Me.hWnd, _
        DISCL_BACKGROUND Or DISCL_NONEXCLUSIVE

You must set the data format before attempting to enumerate objects on the device or manipulate its properties.

Once the joystick is in place, its capabilities are explored in Step 2: Getting Joystick Capabilities


Step 2: Getting Joystick Capabilities

Getting basic information about the buttons, axes, and point-of-view controllers on the device requires a simple call to DirectInputDevice8.GetCapabilities.

Dim joyCaps As DIDEVCAPS
diDev.GetCapabilities joyCaps

The Joystick Sample needs only the number of buttons and point-of-view controllers on the device. Although the DIDEVCAPS type also reports the number of axes on the device, it does not reveal anything about what those axes are. For this information, the sample calls its own IdentifyAxes procedure. It first declares its variables and initializes an array that will hold Boolean values indicating the presence or absence of each possible axis.

Sub IdentifyAxes(diDev As DirectInputDevice8)

    Dim didoEnum As DirectInputEnumDeviceObjects
    Dim dido As DirectInputDeviceObjectInstance
    Dim i As Integer

    For i = 1 To 8
        AxisPresent(i) = False
    Next

The procedure goes on to enumerate device objects on the device. The DIDFT_AXIS value will restrict the enumeration to axes.

    Set didoEnum = diDev.GetDeviceObjectsEnum(DIDFT_AXIS)

Each DirectInputDeviceObjectInstance is then queried for its offset within the data format that was established earlier by the call to DirectInputDevice8.SetCommonDataFormat. This offset identifies the conventional role or type of the axis; for instance, a GUID_RzAxis likely corresponds to a twisting motion on the main stick. Keep in mind, though, that device drivers are free to assign any designation to an axis. It is always a good idea to allow users to change the mapping of the axes to actions within your application.

    Dim sGuid as String
    For i = 1 To didoEnum.GetCount
        Set dido = didoEnum.GetItem(i)
        sGuid = didoEnum.GetItem(i)

        Select Case sGuid
            Case "GUID_Xaxis"
                AxisPresent(1) = True
            Case "GUID_Yaxis"
                AxisPresent(2) = True
' and so on
.
.
.
        End Select
    Next
End Sub

The application now passes the event handle created earlier to the device, so that notifications will be sent to the form when an input event takes place.

Call diDev.SetEventNotification(EventHandle)

Next, you set the joystick properties in Step 3: Setting Joystick Properties.


Step 3: Setting Joystick Properties

Property changes are made through the DirectInputDevice8.SetProperty method, and must be made after the data format of the device is established, but before it is acquired.

Because different devices might return different ranges of axis values, it is a good idea to set a range that will apply to all devices. The Joystick Sample requests that all axis values be within the range 0 to 10,000.

Properties are set using different types for different properties. For an axis value, use the DIPROPRANGE type. This property type structure is then applied by calling SetProperty.

Dim DiProp_Range As DIPROPRANGE

With DiProp_Range
    .lHow = DIPH_DEVICE
    .lMin = 0
    .lMax = 10000
End With
diDev.SetProperty "DIPROP_RANGE", DiProp_Range

The DIPH_DEVICE flag is used to indicate that the property applies to all axes on the device. The Joystick Sample also sets the dead zone and saturation zones for the joystick. In this case, it is not desirable to set these values for other axes such as a throttle or rudder. The lHow member of the property type is set to indicate that the property change applies to a device object identified by its offset within the data format, and the lObj member is set to that offset value. In this case, the DIPROPLONG type is used to send values of type Long through SetProperty. The following sample code demonstrates this for the dead zone property.

Dim DiProp_Dead As DIPROPLONG

With DiProp_Dead
    .lData = 1000
    .lHow = DIPH_BYOFFSET

' Set for x-axis
    .lObj = DIJOFS_X
    diDev.SetProperty "DIPROP_DEADZONE", DiProp_Dead

' Set for y-axis
    .lObj = DIJOFS_Y
    diDev.SetProperty "DIPROP_DEADZONE", DiProp_Dead
End With

The value in lData is the proportion of the range of travel, in units of 10,000, that is set up as a dead zone. Because 1000 is one-tenth of 10,000, it specifies that one-tenth of the range of travel of the x-axis and y-axis, balanced at the center, will be reported as still being in the center (in this case, a value of 5000).

Note Dead zone and saturation values are always calculated in units of 10,000, regardless of the actual range of values reported by the device.

The saturation zones for the device are set similarly. In this case, lData is 9500, because it represents the proportion of the range of travel that lies outside the saturation zones at the extremities. In other words, the top and bottom 5 percent of the raw values returned by the joystick is reported as the minimum or maximum range value set for the device (in this case, 0 or 10,000).

You are now ready to get data from the device in Step 4: Retrieving Immediate Data from the Joystick.


Step 4: Retrieving Immediate Data from the Joystick

Now that the necessary properties have been set, the device can be acquired and data can be collected from the joystick. In the Joystick Sample, the device is polled in a loop after its properties have been set. This uses the DirectInputDevice8.Poll method. In a real-world multimedia application, polling would take place in the main game loop or rendering loop.

diDev.Acquire

While DoEvents
    diDev.Poll
Wend

The sample application does not actually retrieve immediate data each time the device is polled. To avoid unnecessary screen updates, it relies on notification, and the call to Poll is only to ensure that notifications are issued by devices that do not generate interrupts. Polling is not necessary for some game devices (such as HIDs), but it is as efficient to make a redundant call to DirectInputDevice8.Poll as to check a flag for the device before calling Poll.

Notifications are handled, as usual, in the implementation of the DirectXEvent8.DXCallback method. Each time this procedure is called, the application knows that a joystick event has occurred. At this point the application could call DirectInputDevice8.GetDeviceData to retrieve any pending axis changes or button events. However, with a game controller it is more common to retrieve the state of the entire device. Therefore, the sample uses DirectInputDevice8.GetDeviceStateJoystick, called from within the callback function.

Dim js As DIJOYSTATE

diDev.GetDeviceStateJoystick js

The values in the DIJOYSTATE type contain the state of all the device objects on the joystick. Because Step 2: Getting Joystick Capabilities checked which buttons, axes, and point-of-view controllers are actually present, you know which members in the type to ignore.


Tutorial 4: Using Force Feedback

This tutorial shows how to test for the presence of a force-feedback device, how to create and play an effect, and how to change the parameters of an effect as it is playing.

The tutorial divides the tasks into the following steps.

  • Step 1: Initializing the Force-Feedback Device
  • Step 2: Setting Device Properties
  • Step 3: Creating an Effect
  • Step 4: Modifying an Effect


Step 1: Initializing the Force-Feedback Device

In order to implement force feedback, you must first determine whether an appropriate device is available, and if so, create a DirectInputDevice8 object for it. This tutorial presumes an application requiring a device that can play effects on both the x-axis and y-axis.

The following example starts, as usual, by creating a DirectInput8 object, then using that object to enumerate the available devices into a DirectInputEnumDevices8 object. The enumeration is restricted to attached devices of type DI8DEVTYPE_JOYSTICK.

Dim dx As DirectX8
Dim di As DirectInput8

Dim diDev As DirectInputDevice8
Dim diEnumDev As DirectInputEnumDevices8
Dim diDevInst As DirectInputDeviceInstance8
Dim diDevObjEnum As DirectInputEnumDeviceObjects
Dim devobj As DirectInputDeviceObjectInstance

Dim devcaps As DIDEVCAPS
Dim ForceX As Boolean, ForceY As Boolean
Dim FoundForce As Boolean
Dim efftype As Long
Dim strObjGuid As String

Dim i As Integer, iAxes As Integer

Set di = dx.DirectInputCreate
Set diEnumDev = di.GetDIDevices(DI8DEVTYPE_JOYSTICK, _
                                          DIEDFL_ATTACHEDONLY)

The example now iterates through the available devices until it finds one that has force-feedback capabilities.

For i = 1 To diEnumDev.GetCount
    Set diDevInst = diEnumDev.GetItem(i)
    Set diDev = di.CreateDevice(diDevInst.GetGuidInstance)
    Call diDev.GetCapabilities(devcaps)
    If devcaps.lFlags And DIDC_FORCEFEEDBACK Then
    'Process the force-feedback device

Next, because the example requires that both the X and Y axes must support force feedback, all axes on the device are enumerated in a DirectInputEnumDeviceObjects collection.

    Set diDevObjEnum = didev.GetDeviceObjectsEnum(DIDFT_AXIS)

The collection of axes present is then inspected, looking for the x-axis and y-axis, and checking to see whether they support force-feedback effects.

    ForceX = False
    ForceY = False
    For iAxes = 1 To diDevObjEnum.GetCount
        Set devobj = diDevObjEnum.GetItem(iAxes)
        strObjGuid = devobj.GetGuidType
        If strObjGuid = "GUID_XAxis" Then
            If devobj.GetFlags And DIDOI_FFACTUATOR Then
                ForceX = True
            End If
        ElseIf strObjGuid = "GUID_YAxis" Then
            If devobj.GetFlags And DIDOI_FFACTUATOR Then
                ForceY = True
            End If
        End If
        FoundForce = ForceX And ForceY
        If FoundForce Then Exit For
    Next iAxes

Next i    'Next device

If Not FoundForce Then
    MsgBox "Two force feedback axes required."
End If

Now that a suitable device is assured, its properties are set in Step 2: Setting Device Properties.


Step 2: Setting Device Properties

Presuming that you have found a suitable force-feedback device, the DirectInputDevice8 object created in the last step in order to check capabilities can be left in place. It requires some further normal initialization, as covered in Tutorial 3: Using the Joystick: setting the data format and cooperative level, and setting the range properties for input. Note that the cooperative level must include DISCL_EXCLUSIVE. Although an actual application probably does not require background access to the device, the DISCL_BACKGROUND flag makes debugging easier because you will not lose acquisition when you switch to the code window.

Call didev.SetCommonDataFormat(DIFORMAT_JOYSTICK2)
Call didev.SetCooperativeLevel(Me.hWnd, _
        DISCL_BACKGROUND Or DISCL_EXCLUSIVE)
' Set range properties...

For force feedback, it is often good practice to disable the autocenter property of the device, so that the default spring action will not interfere with effects you create. This is done by sending a DIPROPLONG type through the DirectInputDevice8.SetProperty method, setting the DIPROP_AUTOCENTER property to 0.

Dim prop As DIPROPLONG
prop.lData = 0
prop.lHow = DIPH_DEVICE
prop.lObj = 0
Call didev.SetProperty("DIPROP_AUTOCENTER", prop)

Once you have configured the device as desired, it can be acquired.

 didev.Acquire

Now that you have a force-feedback device ready, you need to create an effect to use with it. This is covered in Step 3: Creating an Effect.


Step 3: Creating an Effect

The effect created in this example simulates the pull of a stationary object, such as a magnet, on a movable object, such as an iron ball. The movable object is controlled by the joystick. At the beginning of the simulation, the iron ball is due south of the magnet and experiencing one-half the maximum pull.

The pull of the magnet is simulated by a constant force. The first step is to set up the DIEFFECT type that describes the force.

Dim EffectInfo as DIEFFECT
With EffectInfo
    .constantForce.lMagnitude = 5000
    .lDuration = -1       ' Infinite
    .x = 18000
    .lGain = 10000        ' Play at full magnitude
    .lTriggerButton = -1  ' No trigger button
End With

By setting the x parameter to 18,000, you specify a force originating from a spot 180 degrees from due north. In other words, a force moving from due south toward due north, away from the user. For an in-depth discussion of effect directions, see Effect Direction

All other members of DIEFFECT are either not relevant to a constant force or are valid with a value of 0.

Now that the effect has been defined, it can be created using the DirectInputDevice8.CreateEffect method.

Dim di_effect As DirectInputEffect
Set di_effect = didev.CreateEffect("GUID_ConstantForce", EffectInfo)

If the device is in an acquired state at this time, the effect is automatically downloaded. If not, the effect will be downloaded when it is started using the DirectInputEffect.Start method.

di_effect.Start(1, 0)

Only one iteration of the effect is needed because it has infinite duration and no flags are required.

While a constant unchanging effect can be useful, an effect might also change as it plays or in reaction to user input. This is discussed in Step 4: Modifying an Effect.


Step 4: Modifying an Effect

As the user moves the iron ball around using the joystick, the application adjusts the direction and magnitude of the effect. First, however, you should check whether the device enables changing the direction of the effect without stopping and restarting the effect. Microsoft® DirectInput® will stop and restart the effect automatically if necessary, but by doing this yourself, you might avoid unseemly breaks in continuity.

In order to examine the capabilities for any effect, you first enumerate supported effects. To do so, use the DirectInputDevice8.GetEffectsEnum method, which resolves to a DirectInputEnumEffects type. The DIEFT_CONSTANTFORCE flag enables you to restrict the enumeration to supported only constant force effects.

Dim diEnumEffects As DirectInputEnumEffects
Set diEnumEffects = didev.GetEffectsEnum(DIEFT_CONSTANTFORCE)

Next, examine the enumeration for the particular effect you are interested in. If the enumerated effect meets the criteria, call the DirectInputEnumEffects.GetDynamicParams method to examine the effect for parameters that can be changed without stopping and restarting. Examine the flags returned by GetDynamicParams, comparing them against known values from CONST_DIEPFLAGS. In the case of the following example, the params variable containing the result flags is compared against DIEP_DIRECTION to ensure that the direction of the effect can be changed while the effect is running.

Dim params As Long
Dim i As Long

For i = 1 To diEnumEffects.GetCount
    ' Look for the standard constant force. There could be others.

    If diEnumEffects.GetEffectGuid(i) = "GUID_ConstantForce" Then
        params = diEnumEffects.GetDynamicParams(i)
        Exit For
    End If

Next i

If Not (params And DIEP_DIRECTION) Then
    ' Cannot change direction dynamically. Take remedial action such
    ' as limiting points at which modifications will be made.
End If

Similarly, to learn whether you can change the magnitude of the effect dynamically, perform the following check.

If Not (params And DIEP_TYPESPECIFICPARAMS)
   ' Cannot change type-specific parameters dynamically.
End If

The application modifies the effect each time the device has been polled for input and the iron ball has moved. Assume that the new magnitude is stored in CurrentMag, and the new direction (in degrees) in CurrentBearing. To make the necessary changes, you need to initialize only those members of DIEFFECT that are relevant.

EffectInfo.constantForce.lMagnitude = CurrentMag
EffectInfo.x = CurrentBearing * DI_DEGREES

You now pass the DIEFFECT type with the new data to DirectInputEffect.SetParameters along with flags indicating which members contain valid data.

di_effect.SetParameters(EffectInfo, _
        DIEP_DIRECTION Or DIEP_TYPESPECIFICPARAMS)

The DIEP_TYPESPECIFICPARAMS flag indicates that any member containing information particular to that type of effect is valid. In the case of a constant force, this means the constantForce member.


Tutorial 5: Using Action Mapping

This tutorial guides you through the setup, modification, and application of an action map. Code samples are based on the ActionMapper Sample, which is designed as though it were a space combat game.

Preliminary steps of setting up the Microsoft—> DirectInput—> system are the same for any application and are covered in detail in the other tutorials. The keyboard, mouse, and a joystick (if present) are all used in the sample, so each of those devices needs to be set up.

The tutorial divides the 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 the ActionMapper Sample, 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, as in the Preparing the Action Map overview, or they could be defined as constants, as in the following code fragment from the ActionMapper sample.

Const INPUT_LEFTRIGHT_AXIS = 1
Const INPUT_UPDOWN_AXIS = 2
Const INPUT_TURNLEFT = 4
Const INPUT_TURNRIGHT = 5
Const INPUT_FORWARDTHRUST = 6
Const INPUT_REVERSETHRUST = 7
Const INPUT_FIREWEAPONS = 8
Const INPUT_ENABLESHIELD = 9
Const INPUT_DISPLAYGAMEMENU = 10
Const INPUT_QUITGAME = 11

Once these values are defined, they can be assigned to genre-specific action-mapping constants. This is shown 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 they are defined by genre and subgenre. In the case of the ActionMapper Sample, 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 types. Each DIACTION type contains at least one game action, its associated action-mapping constant, any necessary flags, and a friendly name for the action. The remaining DIACTION members are not used at this point. The following code sample shows the array of DIACTION types defined in the ActionMapper Sample. Note that CInputMapper is a class used and defined by the ActionMapper sample to contain many of the standard action-mapping procedures. In this case it uses its own AddAction function to add each new DIACTION type to an array of them contained in a DIACTIONFORMAT type.

Dim m_mapper As New CInputMapper

With m_mapper
.AddAction INPUT_LEFTRIGHT_AXIS, DIAXIS_SPACESIM_LATERAL, 0, "Turn"
.AddAction INPUT_UPDOWN_AXIS, DIAXIS_SPACESIM_MOVE, 0, "Move"
.AddAction INPUT_FIREWEAPONS, DIBUTTON_SPACESIM_FIRE, 0, "Shoot"
.AddAction INPUT_ENABLESHIELD, DIBUTTON_SPACESIM_GEAR, 0, "Shield"
.AddAction INPUT_DISPLAYGAMEMENU,DIBUTTON_SPACESIM_DISPLAY,0,"Display"
.AddAction INPUT_QUITGAME, DIBUTTON_SPACESIM_MENU, 0, "Quit Game"

' Keyboard input mappings
.AddAction INPUT_FORWARDTHRUST, DIKEYBOARD_UP, 0, "Forward thrust"
.AddAction INPUT_REVERSETHRUST, DIKEYBOARD_DOWN, 0, "Reverse thrust"
.AddAction INPUT_FIREWEAPONS, DIKEYBOARD_F, 0, "Fire weapons"
.AddAction INPUT_ENABLESHIELD, DIKEYBOARD_S, 0, "Enable shields"
.AddAction INPUT_DISPLAYGAMEMENU, DIKEYBOARD_D, 0, "Display game menu"
.AddAction INPUT_QUITGAME, DIKEYBOARD_ESCAPE, 0, "Quit game"
.AddAction INPUT_TURNRIGHT, DIKEYBOARD_RIGHT, 0, "Right Turn"
.AddAction INPUT_TURNLEFT, DIKEYBOARD_LEFT, 0, "Left Turn"

' Mouse input mappings
.AddAction INPUT_LEFTRIGHT_AXIS, DIMOUSE_XAXIS, 0, "Turn"
.AddAction INPUT_UPDOWN_AXIS, DIMOUSE_YAXIS, 0, "Move"
.AddAction INPUT_FIREWEAPONS, DIMOUSE_BUTTON0, 0, "Fire weapons"
.AddAction INPUT_ENABLESHIELD, DIMOUSE_BUTTON1, 0, "Enable shields"
End With

The DIACTIONFORMAT type containing the array of DIACTION types will be used to find a device that can best be used with it. This is shown in Step 3: Mapping Actions to Devices.


Step 3: Mapping Actions to Devices

The ActionMapper Sample uses its class function CreateDevicesFromMap to, among other things, measure the action map defined above against available devices. To do so, it first assigns values to the other members of the DIACTIONFORMAT type containing the array of DIACTION types. The values used in the sample have been passed as parameters to the CreateDevicesFromMap method. For clarity, the following code sample uses the actual values rather than the parameter names.

    m_diaf.guidActionMap = "{20CAA014-60BC-4399-BDD3-84AD65A38A1C}"
    m_diaf.lGenre = DIVIRTUAL_SPACESIM
    m_diaf.lBufferSize = 16
    m_diaf.lAxisMax = 100
    m_diaf.lAxisMin = -100
    m_diaf.ActionMapName = "Semantic Mapper VB Sample"
    m_diaf.lActionCount = 18

The guidActionMap value is defined by the program. For more information on creating GUIDs, see Using GUIDs.

Once the desired mapping has been defined, it must be applied to physical devices. DirectInput8.GetDevicesBySemantics begins this process in the following code fragment, where m_DI is a previously defined DirectInput8 object, m_DIEnum is a previously defined DirectInputEnumDevices8 object, and m_strUserName is a previously defined string containing a friendly identifier for the user.

Set m_DIEnum = m_DI.GetDevicesBySemantics(m_strUserName, m_diaf, 0)

Flags could be used to limit the enumeration to a more specific search, but in this case no flags are set.

The results of the enumeration are examined individually and devices are created for each keyboard, mouse, and joystick found. In the following code sample, devinst is a previously defined DirectInputDeviceInstance8 object, m_Devices is a previously defined array of DirectInputDevice8 objects, and m_DeviceTypes is a previously defined array of Long values.

    For i = 1 To m_DIEnum.GetCount

        Set devinst = m_DIEnum.GetItem(i)
        Set m_Devices(i) = m_DI.CreateDevice(devinst.GetGuidInstance)
        m_DeviceTypes(i) = devinst.GetDevType
        Set devinst = Nothing

The loop continues by checking whether the enumerated device currently under examination is a mouse. If so, the AXISMODE property is set to relative. Other properties could be set within this loop as well, but in the case of the ActionMapper Sample, this is all that will be done here.

        If m_DeviceTypes(i) = DI8DEVTYPE_MOUSE Then
            Dim dipl As DIPROPLONG
            dipl.lHow = DIPH_DEVICE
            dipl.lData = DIPROPAXISMODE_REL
            m_Devices(i).SetProperty "DIPROP_AXISMODE", dipl
        End If

DirectInputDevice8.BuildActionMap takes the list of control assignments specified in the DIACTIONFORMAT type and attempts to map them to specific device objects on the device being enumerated for the user specified in the m_strUserName parameter. The results of the mapping are returned in the same structure. Each pass maps different controls depending on the nature of the enumerated device currently being examined. A keyboard, for instance, maps controls that specify a mapping to a particular key, but it leaves controls that specify buttons, sliders, or axes unmapped. If a joystick is enumerated next, BuildActionMap ignores those controls mapped to keyboard keys, but it attempts to map the buttons, sliders, and axes to the joystick's device objects.

        m_Devices(i).BuildActionMap m_diaf, m_strUserName, 0

Once again, no flags are used in this instance.

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 type, it can be manipulated before being applied by DirectInputDevice8.SetActionMap.

The lHow member of each DIACTION type contained within the DIACTIONFORMAT type 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.

You can change the actual mapping itself by editing the lSemantic member of the appropriate DIACTION structure returned in the default mapping. However, making these changes is not recommended.

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 the DirectInputDevice8.SetActionMap method as follows.

        m_Devices(i).SetActionMap m_diaf, m_strUserName, 0

The parameters once again consist of the DIACTIONFORMAT type, the user name, and no flags.

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 preliminary setup is involved. A DICONFIGUREDEVICESPARAMS type is used to hold the property sheet information. DICONFIGUREDEVICESPARAMS contains an array of DIACTIONFORMAT types used for any mappings that have been defined, an array of user names to match to those action maps, and counts for both of the arrays. For this example, only one mapping and one user have been defined above. The initialization of the DICONFIGUREDEVICESPARAMS type is shown in the following sample code.

Dim m_cdParams As DICONFIGUREDEVICESPARAMS

    m_cdParams.ActionFormats(0) = m_diaf
    m_cdParams.FormatCount = 1
    m_cdParams.UserNames(0) = m_strUserName
    m_cdParams.UserCount = 1

Once that structure is initialized, call DirectInput8.ConfigureDevices to display the UI as shown in the following sample code.

    m_DI.ConfigureDevices 0, m_cdParams, DICD_EDIT

All that the sample is passing to ConfigureDevices is the DICONFIGUREDEVICESPARAMS type and a flag indicating that the UI 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.

Users can now reassign controllers to actions as they see fit. Any changes made will be reflected in the DIACTIONFORMAT type. Once the user interface is closed, the new action map must be sent to DirectInputDevice8.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 lOfs member of the DIDEVICEOBJECTDATA type to determine which device object reported a change. However, with action mapping, you look to the lUserData member. Data is found as usual in the lData member.


DirectInput Visual Basic Samples

The following sample programs demonstrate the use and capabilities of Microsoft® DirectInput®:

  • ActionMapper Sample
  • ForceFeedback Sample
  • Joystick Sample
  • Keyboard Sample
  • ScrawlB Sample


ActionMapper Sample

Description

The ActionMapper sample program demonstrates the retrieval of action-mapped data. It also enables reconfiguration of the keyboard, mouse, and other controller action mappings through the user interface.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectInput\ActionMapper

Executable: Source: (SDK root)\Samples\Multimedia\VBSamples\DirectInput\Bin\VB_ActionMapper.exe

User's Guide

The initial display gives a text feedback of axis movements and button or key presses from the mouse, keyboard, or other controller attached to the system. An EXCLUSIVE | FOREGROUND cooperative level is used so that the mouse cursor is hidden.

Pressing the D key displays the configuration user interface with tabs for the mouse, keyboard, and any other present controller device. If a graphic is available for the controller, it is displayed with callouts indicating which action is associated with which control. Double-clicking a callout label activates the menu of possible actions to apply to that control. To return to the initial screen with the new mappings, click OK.

To terminate the program, press the ESC key from the initial screen.

Programming Notes

You will need to modify ActionMap.cls. For the purpose of this sample, it queries for any and all input devices, and it does not distinguish the source of the input. However, you will usually modify the class to respond to only one given input, or to differentiate the input devices into different players or purposes.

This sample makes use of common DirectX code that is shared with other samples on the DirectX SDK. All common classes and modules can be found in the following directory:

(SDK root)\Samples\Multimedia\VBSamples\Common


ForceFeedback Sample

Description

The ForceFeedback sample program is a simple force-feedback editor that enables you to create an effect, set parameters, and play the effect.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectInput\Feedback

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectInput\Bin\VB_ForceFeedback.exe

User's Guide

Select an effect type from the list, and modify the parameters. Play the effect by pressing the primary button on the joystick.

Programming Notes

The ForceFeedback sample program shows how to turn off the autocenter property and how to create and modify effects. Changes in effect parameters are applied immediately.


Joystick Sample

Description

The Joystick sample program shows how to enumerate joysticks, set joystick properties, and get immediate data.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectInput\Joystick

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectInput\Bin\VB_Joystick.exe

User's Guide

Select a joystick from the list. The data from the axes and buttons is displayed. 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 list box is unsorted so that the selection can easily be retrieved from the DirectInputEnumDevices8 collection.


Keyboard Sample

Description

The Keyboard sample program shows how to create a keyboard device and retrieve immediate data from it.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Src\Keyboard

Executable: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Bin\Keyboard.exe

User's Guide

As you press one or more keys while the application has focus, the names of the keys (from CONST_DIKEYFLAGS) are displayed in the list box.

Programming Notes

The background cooperative level is used, so keys are read even when the application does not have the input focus.


ScrawlB Sample

Description

The ScrawlB sample program illustrates using Microsoft® DirectInput® to create a simple drawing program. It shows how to use the mouse in exclusive mode, how to use event notification for mouse events, how to retrieve and interpret buffered data, and how to use callback functions to receive mouse movement events.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectInput\Scrawl

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectInput\Bin\VB_Scrawlb.exe

User's Guide

Hold down the left button while dragging the mouse to draw. Click the right button to see a shortcut menu. Choosing Release Mouse (or pressing and releasing ALT) releases the system cursor so that you can move or resize the window or click on another application. Click on the client window again to resume drawing.

Programming Notes

The application subclasses the Display window to capture WM_ENTERMENULOOP messages. This is the best way to find out if the user has opened the system menu by pressing ALT+SPACEBAR, so that ScrawlB can release the mouse through a call to SetWindowLong. However, subclassing can lead to difficulties when debugging. Note that failure to comment out these lines while running the sample from within the Visual Basic environment will result in undefined behavior.

The frmCanvas module implements DirectXEvent8 in order to be able to process input events. The Microsoft® Visual Basic® MouseMove event is also used by this form for getting Microsoft Windows® mouse events when Microsoft DirectInput® does not have access to the mouse. When this event is triggered, the application knows that the cursor is back in the client window, so the mouse can be reacquired.


DirectInput Visual Basic Reference

Reference material for the Microsoft® DirectInput® Microsoft Visual Basic® application programming interface (API) is divided into the following categories.

  • Classes
  • Types
  • Enumerations
  • Keyboard Keys
  • Action Mapping Constants
  • Error Codes


Classes

This section contains references for methods of the following Microsoft® DirectInput® classes.

  • DirectInput8
  • DirectInputDevice8
  • DirectInputDeviceInstance8
  • DirectInputDeviceObjectInstance
  • DirectInputEffect
  • DirectInputEnumDeviceObjects
  • DirectInputEnumDevices8
  • DirectInputEnumEffects


DirectInput8

The DirectInput8 class represents the Microsoft® DirectInput® system. An application should have a single object of this class, which is used to enumerate available devices, create devices, and retrieve the status of devices, as well as to invoke an instance of the Microsoft Windows® Control Panel.

The DirectInput8 object is obtained by using the DirectX8.DirectInputCreate method.

The DirectInput8 class has the following methods:

Action Mapping | ConfigureDevices
 | GetDevicesBySemantics
Device Management | CreateDevice
 | GetDeviceStatus
 | GetDIDevices
Miscellaneous | RunControlPanel


DirectInput8.ConfigureDevices

Displays property pages for connected input devices and enables the user to map actions to device controls.

object.ConfigureDevices( _
  hEvent As Long, _
  CDParams As DICONFIGUREDEVICESPARAMS, _
  flags As Long)

Parts

object
Resolves to a DirectInput8 object.
hEvent
Handle to an event that is set each time a change is made to the display of the property sheet. Can be 0 or a value returned by DirectX8.CreateEvent.
CDParams
DICONFIGUREDEVICESPARAMS type that contains parameters for action mapping.
flags
Value that specifies the mode in which the control panel should be invoked. Must be one of the following values from the CONST_DICDFLAGS enumeration.
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 DirectInput8.GetDevicesBySemantics.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_INVALIDPARAM
DIERR_OUTOFMEMORY

Remarks

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 ActionName member of the DIACTION type.

Configuration is stored for each user of each device for each game. The information can be retrieved by the DirectInputDevice8.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 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 is active while the default action mapping UI is displayed.


DirectInput8.CreateDevice

Creates and initializes an instance of a device based on a given GUID.

object.CreateDevice(guid As String) As DirectInputDevice8

Parts

object
Resolves to a DirectInput8 object.
guid
The instance GUID for the desired input device. The GUID is retrieved from the DirectInputDeviceInstance8 object returned by the DirectInputEnumDevices8.GetItem method, or it can be one of the following strings:
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.

Return Values

Returns a DirectInputDevice8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOINTERFACE
DIERR_OUTOFMEMORY

See Also

DirectInput8, Using GUIDs


DirectInput8.GetDevicesBySemantics

Enumerates devices that most closely match the application-specified action map.

object.GetDevicesBySemantics( _
  str1 As String, _
  format As DIACTIONFORMAT, _
  flags As Long _
) As DirectInputEnumDevices8

Parts

object
Resolves to a DirectInput8 object.
str1
String identifying the current user, or vbNullString 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.
format
DIACTIONFORMAT type that specifies the action map for which suitable devices are enumerated.
flags
Flag value that specifies the scope of the enumeration. Can be one or more values from the CONST_DIEDBSFLFLAGS enumeration.

Return Values

Returns a DirectInputEnumDevices8 object that represents the collection of enumerated devices.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

The keyboard and mouse are enumerated last.

See Also

Action Mapping


DirectInput8.GetDeviceStatus

Determines whether a device is attached to the system.

object.GetDeviceStatus(guid As String) As Boolean

Parts

object
Resolves to a DirectInput8 object.
guid
The instance GUID for the desired input device. The GUID is retrieved by using the DirectInputDeviceInstance8.GetGuidInstance method on the object returned by DirectInputEnumDevices8.GetItem method, or it can be one of the following strings:
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.

Return Values

Returns True if the device is attached, and False otherwise.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_GENERIC
DIERR_INVALIDPARAM

See Also

DirectInput8, Using GUIDs


DirectInput8.GetDIDevices

Enumerates available devices.

object.GetDIDevices( _
  deviceType As CONST_DI8DEVICETYPE, _
  flags As CONST_DIENUMDEVICESFLAGS) _
  As DirectInputEnumDevices8

Parts

object
Resolves to a DirectInput8 object.
deviceType
Value that specifies the type of device to enumerate. If this parameter is 0, all types are enumerated. Otherwise, it is one of the constants of the CONST_DI8DEVICETYPE enumeration representing a class or type of device.
flags
Flag value that specifies the scope of the enumeration. This parameter contains one or more of the constants of the CONST_DIENUMDEVICESFLAGS enumeration.

Return Values

Returns a DirectInputEnumDevices8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

All installed devices can be enumerated, even if they are not present. For example, a joystick may be installed on the system but not currently plugged into the computer.

If a single piece of hardware can function as more than one Microsoft® DirectInput® device type, it will be returned for each device type it supports. For example, a keyboard with a built-in mouse will be enumerated as a keyboard and as a mouse. The product GUID would be the same for each device, however.

See Also

DirectInput8


DirectInput8.RunControlPanel

Runs the Microsoft® Windows® Control Panel to enable the user to install a new input device or modify configurations.

object.RunControlPanel(hwndOwner As Long)

Parts

object
Resolves to a DirectInput8 object.
hwndOwner
Handle to the window to be used as the parent window for the subsequent user interface. If this parameter is 0, no parent window is used.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInput8, DirectInputDevice8.RunControlPanel


DirectInputDevice8

Applications use the methods of the DirectInputDevice8 class to gain and release access to Microsoft® DirectInput® devices, manage device properties and information, set behavior, perform initialization, and invoke a device's property sheet.

The DirectInputDevice8 object is obtained by using the DirectInput8.CreateDevice method.

The methods of the DirectInputDevice8 class can be organized into the following groups.

Access | Acquire
 | SetCooperativeLevel
 | Unacquire
Action Mapping | BuildActionMap
 | GetImageInfo
 | GetImageInfoCount
 | SetActionMap
Data Retrieval | GetDeviceData
 | GetDeviceState
 | GetDeviceStateJoystick
 | GetDeviceStateJoystick2
 | GetDeviceStateKeyboard
 | GetDeviceStateMouse
 | GetDeviceStateMouse2
 | Poll
 | SetEventNotification
Force Feedback | CreateCustomEffect
 | CreateEffect
 | CreateEffectFromFile
 | GetEffectsEnum
 | GetForceFeedbackState
 | SendForceFeedbackCommand
 | WriteEffectToFile
Objects | GetDeviceObjectsEnum
 | GetObjectInfo
Properties | GetCapabilities
 | GetDeviceInfo
 | GetProperty
 | SetCommonDataFormat
 | SetDataFormat
 | SetProperty
Miscellaneous | RunControlPanel
 | SendDeviceData


DirectInputDevice8.Acquire

Obtains access to the input device.

object.Acquire()

Parts

object
Resolves to a DirectInputDevice8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.:

DIERR_INVALIDPARAM
DIERR_OTHERAPPHASPRIO

Remarks

Before a device can be acquired, a data format must be set by using the DirectInputDevice8.SetDataFormat or DirectInputDevice8.SetCommonDataFormat method.

A device must be acquired before input data can be retrieved from it.

See Also

DirectInputDevice8.Unacquire


DirectInputDevice8.BuildActionMap

Builds an action map for the device and retrieves information about it.

object.BuildActionMap( _
  format As DIACTIONFORMAT, _
  username As String, _
  flags As Long)

Parts

object
Resolves to a DirectInputDevice8 object.
format
DIACTIONFORMAT type that receives properties of the action map.
username
String that specifies the name of the user for whom mapping is requested. If an empty string, the current user is assumed.
flags
Flags used to control the mapping. Can be one of the constants of the CONST_DIDBAMFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INVALIDPARAM
DIERR_MAPFILEFAIL

Remarks

If DIERR_INVALIDPARAM is raised, one or more of the mappings was not valid. The lHow member of the DIACTION type is set to DIAH_ERROR. The application can iterate through the action map to find and correct errors.

See Also

DirectInputDevice8.SetActionMap, DirectInputDevice8.SetDataFormat


DirectInputDevice8.CreateCustomEffect

Creates a force-feedback effect consisting of a series of constant forces of fixed duration.

object.CreateCustomEffect(effectinfo As DIEFFECT, _
    channels As Long, samplePeriod As Long, _
    nSamples As Long, sampledata() As Long) _
    As DirectInputEffect

Parts

object
Resolves to a DirectInputDevice8 object.
effectinfo
DIEFFECT type containing general parameters of the effect.
channels
The number of channels (axes) affected by this force. Must be 1 or 2.

If there is only a single channel, then the effect will be rotated in the direction specified by the x member of the DIEFFECT type. Not all devices support rotation of custom effects.

If there is more than one channel, the first channel is applied to the x-axis and the second to the y-axis. Rotation is not allowed.

samplePeriod
The sample period in microseconds. See Remarks.
nSamples
Number of elements in the sampledata array.
sampledata
Array of magnitudes. If channels is greater than 1, then the values are interleaved. For example, if channels is 2, then the first element of the array is assigned to the x-axis, the second to the y-axis, the third to the x-axis, and so on.

Remarks

In theory, samplePeriod is the length of time for which each magnitude in sampledata is valid, whereas DIEFFECT.lSamplePeriod is the length of time between samplings of the data (and the minimum time between changes in magnitude). Since each element in the array needs to be sampled exactly once on each iteration through the array, and some drivers ignore samplePeriod in any case, it is best to make the values of lSamplePeriod and samplePeriod identical.

See Also

Custom Forces


DirectInputDevice8.CreateEffect

Creates a force-feedback effect. If the device is currently acquired at the exclusive cooperative level, the effect is also downloaded.

object.CreateEffect(effectGuid As String, _
  effectinfo As DIEFFECT) As DirectInputEffect

Parts

object
Resolves to a DirectInputDevice8 object.
effectGuid
String representation of a GUID for an effect recognized by the hardware driver, or one of the following aliases for standard effects:

GUID_ConstantForce
GUID_RampForce
GUID_Square
GUID_Sine
GUID_Triangle
GUID_SawtoothUp
GUID_SawtoothDown
GUID_Spring
GUID_Damper
GUID_Inertia
GUID_Friction

effectinfo
DIEFFECT type containing the parameters for the effect.

Return Values

Returns a DirectInputEffect object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_DEVICEFULL
DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

If no error is raised, the effect was created and the parameters of the effect were updated, but the effect was not necessarily downloaded. In order for it to be downloaded, the device must be acquired in exclusive mode.

See Also

DirectInputDevice8.CreateEffectFromFile

DirectInputEffect.Download

DirectInputEffect.Start


DirectInputDevice8.CreateEffectFromFile

Creates a force-feedback effect whose parameters are stored in a file. If the device is currently acquired at the exclusive cooperative level, the effect is also downloaded.

object.CreateEffectFromFile( _
  filename As String, _
  flags As Long, _
  effectName As String _
) As DirectInputEffect

Parts

object
Resolves to a DirectInputDevice8 object.
filename
String that specifies the file name.
flags
Flags that specify how to create the effect. Can be one or more values from the CONST_DIFEFFLAGS enumeration.
effectName
Friendly name of the effect, assigned by the author.

Return Values

Returns a DirectInputEffect object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_DEVICEFULL
DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

If no error is raised, the effect was created but not necessarily downloaded. In order for it to be downloaded, the device must be acquired in exclusive mode.

The file specified in the filename parameter must be in the format used by the Force Editor (Fedit.exe) application supplied with the Microsoft® DirectInput® SDK.

See Also

DirectInputEffect.Download, DirectInputDevice8.WriteEffectToFile


DirectInputDevice8.GetCapabilities

Retrieves the capabilities of the device.

object.GetCapabilities(caps As DIDEVCAPS)

Parts

object
Resolves to a DirectInputDevice8 object.
caps
A DIDEVCAPS type to be filled with the device capabilities.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputDevice8.GetDeviceData

Retrieves buffered data from the device.

object.GetDeviceData( _
  deviceObjectDataArray() As DIDEVICEOBJECTDATA, _
  flags As CONST_DIDGDDFLAGS) As Long

Parts

object
Resolves to a DirectInputDevice8 object.
deviceObjectDataArray()
Array of DIDEVICEOBJECTDATA types to receive the buffered data.
flags
Flags that control the manner in which data is obtained. This value can be 0 or one of the constants of the CONST_DIDGDDFLAGS enumeration.

Return Values

Returns the number of buffered data elements actually returned in deviceObjectDataArray.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
DIERR_NOTBUFFERED

Remarks

In the debug version of Microsoft® DirectInput®, if a call is made to DirectInputDevice8.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_NOTACQUIRED return code.

Before device data can be obtained, you must set the data format by using the DirectInputDevice8.SetDataFormat method, set the buffer size by using DirectInputDevice8.SetProperty method, and acquire the device by using the DirectInputDevice8.Acquire method. The maximum number of events that the buffer will hold is one less than the buffer size set with the DirectInputDevice8.SetProperty method.

You can use this method to retrieve one or more input events from the buffer you created by using SetProperty. You do not have to retrieve all pending events with a single call. You can, for example, pass in a deviceObjectDataArray() consisting of a single element and loop on GetDeviceData until no more data is returned.

If the buffer overflows, all pending data is lost and the DI_BUFFEROVERFLOW error is raised.

See Also

DirectInputDevice8.Poll, Polling and Event Notification


DirectInputDevice8.GetDeviceInfo

Retrieves information about the device's identity.

object.GetDeviceInfo() As DirectInputDeviceInstance8

Parts

object
Resolves to a DirectInputDevice8 object.

Return Values

Returns a DirectInputDeviceInstance8 object

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputDevice8.GetDeviceObjectsEnum

Enumerates the input and output objects available on a device.

object.GetDeviceObjectsEnum( _
  flags As CONST_DIDFTFLAGS) _
  As DirectInputEnumDeviceObjects

Parts

object
Resolves to a DirectInputDevice8 object.
flags
Flags specifying the type of object to be enumerated. Can be one or more of the members of the CONST_DIDFTFLAGS enumeration.

Return Values

If the method succeeds, the return value is a DirectInputEnumDeviceObjects object that represents the collection of enumerated devices.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

The DIDFT_FFACTUATOR and DIDFT_FFEFFECTTRIGGER flags 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 Or DIDFT_FFEFFECTTRIGGER) restricts enumeration to force-feedback trigger objects, and (DIDFT_FFEFFECTTRIGGER Or DIDFT_TGLBUTTON Or DIDFT_PSHBUTTON) restricts enumeration to buttons of any kind that can be used as effect triggers.

Applications should not rely on enumeration 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.


DirectInputDevice8.GetDeviceState

Retrieves immediate data for a device other than a standard keyboard, mouse, or joystick.

object.GetDeviceState(cb As Long, state As Any)

Parts

object
Resolves to a DirectInputDevice8 object.
cb
Size of the array whose first element is passed as state.
state
First element of an array to receive device state information.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice8.SetCooperativeLevel method, then set the data format by using DirectInputDevice8.SetDataFormat, and acquire the device by using the DirectInputDevice8.Acquire method.

See Also

DirectInputDevice8.GetDeviceStateJoystick, DirectInputDevice8.GetDeviceStateJoystick2, DirectInputDevice8.GetDeviceStateKeyboard , DirectInputDevice8.GetDeviceStateMouse, DirectInputDevice8.SetDataFormat, Buffered and Immediate Data


DirectInputDevice8.GetDeviceStateJoystick

Retrieves immediate data from a joystick device.

object.GetDeviceStateJoystick(state As DIJOYSTATE)

Parts

object
Resolves to a DirectInputDevice8 object.
state
A DIJOYSTATE type that receives the current state of the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice8.SetCooperativeLevel method, then set the data format by using DirectInputDevice8.SetCommonDataFormat, and acquire the device by using the DirectInputDevice8.Acquire method.

See Also

DirectInputDevice8.Poll Polling and Event Notification


DirectInputDevice8.GetDeviceStateJoystick2

Retrieves immediate data from a joystick device with extended capabilities.

object.GetDeviceStateJoystick2(state As DIJOYSTATE2)

Parts

object
Resolves to a DirectInputDevice8 object.
state
A DIJOYSTATE2 type that receives the current state of the device. The format of the data is established by a prior call to the DirectInputDevice8.SetDataFormat method.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice8.SetCooperativeLevel method, then set the data format by using DirectInputDevice8.SetCommonDataFormat, and acquire the device by using the DirectInputDevice8.Acquire method.

See Also

DirectInputDevice8.Poll, Polling and Event Notification


DirectInputDevice8.GetDeviceStateKeyboard

Retrieves immediate data from a keyboard device.

object.GetDeviceStateKeyboard(state As DIKEYBOARDSTATE)

Parts

object
Resolves to a DirectInputDevice8 object.
state
A DIKEYBOARDSTATE type that receives the current state of the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice8.SetCooperativeLevel method, then set the data format by using DirectInputDevice8.SetCommonDataFormat, and acquire the device by using the DirectInputDevice8.Acquire method.

See Also

DirectInputDevice8.Poll, Polling and Event Notification


DirectInputDevice8.GetDeviceStateMouse

Retrieves immediate data from a mouse device that has up to four buttons.

object.GetDeviceStateMouse(state As DIMOUSESTATE)

Parts

object
Resolves to a DirectInputDevice8 object.
state
A DIMOUSESTATE type that receives the state of the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice8.SetCooperativeLevel method, then set the data format by using DirectInputDevice8.SetCommonDataFormat, and acquire the device by using the DirectInputDevice8.Acquire method.

See Also

DirectInputDevice8.GetDeviceStateMouse2, DirectInputDevice8.Poll Polling and Event Notification


DirectInputDevice8.GetDeviceStateMouse2

Retrieves immediate data from a mouse device that has up to eight buttons.

object.GetDeviceStateMouse2(state As DIMOUSESTATE2)

Parts

object
Resolves to a DirectInputDevice8 object.
state
A DIMOUSESTATE2 type that receives the state of the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice8.SetCooperativeLevel method, then set the data format by using DirectInputDevice8.SetCommonDataFormat, and acquire the device by using the DirectInputDevice8.Acquire method.

See Also

DirectInputDevice8.GetDeviceStateMouse, DirectInputDevice8.Poll, Polling and Event Notification


DirectInputDevice8.GetEffectsEnum

Enumerates force-feedback effects supported by the device, including standard effects as well as effects designed by the device manufacturer.

object.GetEffectsEnum( _
  effType As CONST_DIEFTFLAGS _
) As DirectInputEnumEffects

Parts

object
Resolves to a DirectInputDevice8 object.
effType
One of the following flags from the CONST_DIEFTFLAGS enumeration specifying the type of effect to be enumerated:

DIEFT_ALL
DIEFT_CONDITION
DIEFT_CONSTANTFORCE
DIEFT_CUSTOMFORCE
DIEFT_HARDWARE
DIEFT_PERIODIC
DIEFT_RAMPFORCE

Return Values

Returns a DirectInputEnumEffects object whose methods can be used to retrieve information about the effects.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputDevice8.GetForceFeedbackState

Retrieves the state of the device's force-feedback system.

object.GetForceFeedbackState() As CONST_DIGFFSFLAGS

Parts

object
Resolves to a DirectInputDevice8 object.

Return Values

Returns flags from the CONST_DIGFFSFLAGS enumeration that describe the current state of the device's force-feedback system.

Applications should ignore any flags that are not currently defined.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

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.


DirectInputDevice8.GetImageInfo

Retrieves information about a device image for use in a configuration property sheet.

object.GetImageInfo(info As DIDEVICEIMAGEINFOHEADER)

Parts

object
Resolves to a DirectInputDevice8 object.
info
DIDEVICEIMAGEINFOHEADER type that receives information about the device image.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INVALIDPARAM
DIERR_MAPFILEFAIL
DIERR_MOREDATA
DIERR_NOTINITIALIZED
DIERR_OBJECTNOTFOUND

See Also

DirectInputDevice8.GetImageInfoCount


DirectInputDevice8.GetImageInfoCount

Retrieves the number of images available for the device. This method is used to ascertain how many array elements must be allocated in the Images member of the DIDEVICEIMAGEINFOHEADER type before the type is passed to the DirectInputDevice8.GetImageInfo.

object.GetImageInfoCount() As Long

Parts

object
Resolves to a DirectInputDevice8 object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputDevice8.GetObjectInfo

Retrieves information about a device object such as a button or axis.

object.GetObjectInfo( _
  obj As Long, _
  how As CONST_DIPHFLAGS) _
  As DirectInputDeviceObjectInstance

Parts

object
Resolves to a DirectInputDevice8 object.
obj
Value that identifies the object whose information will be retrieved. The interpretation of this parameter depends on the value specified in the how parameter.
how
Value specifying how the obj parameter should be interpreted. This value can be one of the constants of the CONST_DIPHFLAGS enumeration.

Return Values

Returns a DirectInputDeviceObjectInstance object whose methods can be used to retrieve information about the object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INVALIDPARAM
DIERR_OBJECTNOTFOUND


DirectInputDevice8.GetProperty

Retrieves information about the input device.

object.GetProperty( _
  guid As String, _
  propertyInfo As Any)

Parts

object
Resolves to a DirectInputDevice8 object.
guid
Identifier of the property to be retrieved. The following properties are defined for an input device and can be passed as strings:
DIPROP_APPDATA
Retrieves the application-defined value associated with an in-game action, as a DIPROPPOINTER.
DIPROP_AUTOCENTER
Specifies whether device objects are self-centering. See DirectInputDevice8.SetProperty for more information.
DIPROP_AXISMODE
Retrieves the axis mode. The retrieved value can be DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL. (See the CONST_DINPUT enumeration.)
DIPROP_BUFFERSIZE
Retrieves the input-buffer size. The buffer size determines the amount of data that the buffer can hold between calls to the DirectInputDevice8.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.
DIPROP_CPOINTS
Retrieves calibration points used to adjust incoming raw data as a DIPROPCPOINTS structure.
DIPROP_DEADZONE
Retrieves a value for the dead zone of a joystick, in the range 0 to 10,000, where 0 indicates 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 setting applies to the entire device, rather than to any particular object, so the lHow member of the associated DIPROPLONG type must be DIPH_DEVICE.

The lData 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 you should take all effect magnitudes at face value. A value of 9,000 indicates that you should reduce all effect magnitudes to 90% of their nominal magnitudes.

DIPROP_FFLOAD
Retrieves the memory load for the device. This setting applies to the entire device, rather than to any particular object, so the lHow member of the associated DIPROPLONG type must be DIPH_DEVICE. The device must be acquired in exclusive mode. If it is not, the method fails with a return value of DIERR_NOTEXCLUSIVEACQUIRED.

The lData member contains a value in the range 0 to 100, indicating the percentage of device memory in use.

DIPROP_GETPORTDISPLAYNAME
Retrieves the human-readable display name of the port to which this device is connected. Not generally used by applications. If no friendly name is returned, the method returns S_FALSE.
DIPROP_GRANULARITY
Retrieves the input granularity. Granularity represents the smallest distance in which the object reports movement. Most axis objects have a granularity of 1, whcih means that all values are possible. Some axes may have a larger granularity. For example, the wheel axis on a mouse might have a granularity of 20, meaning that all reported changes in position are multiples of 20. 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; you cannot set its value by calling the DirectInputDevice8.SetProperty method.

DIPROP_INSTANCENAME
Retrieves the friendly instance name of the device. For more information, see DirectInputDevice8.SetProperty.
DIPROP_JOYSTICKID
Retrieves the instance number of a joystick. This property is not implemented for the mouse or keyboard.
DIPROP_LOGICALRANGE
Retrieves the range of the raw data returned for axes on a HID. Devices can return negative values.
DIPROP_PHYSICALRANGE
Retrieves the range of data for axes as suggested by the manufacturer of a HID. 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 DirectInputDevice8.SetProperty.
DIPROP_RANGE
Retrieves the range of values an object can possibly report. The retrieved minimum and maximum values are set in the lMin and lMax members of the associated DIPROPRANGE type.

For some devices, this is a read-only property; you cannot set its value by calling the DirectInputDevice8.SetProperty method.

DIPROP_SATURATION
Retrieves a value for the saturation zones of a joystick, in the range 0 to 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, then 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 DIPROPLONG. If successful, DI_OK is returned. DIERR_GENERIC 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, DIERR_INVALIDPARAM is returned.
DIPROP_USERNAME
Retrieves the user name for a user currently assigned to a device, as a DIPROPSTRING. User names are set by calling DirectInputDevice8.SetActionMap. If no user name is set, the method returns S_FALSE.
propertyInfo
A DIPROPLONG type to receive a single value, a DIPROPRANGE type to receive a pair of values, or a DIPROPSTRING to receive a string for the property. The lObj, lHow, and lSize members of the type must be initialized before the method is called.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_OBJECTNOTFOUND
DIERR_UNSUPPORTED

See Also

DirectInputDevice8.SetProperty


DirectInputDevice8.Poll

Makes data available from polled objects on a Microsoft® DirectInput® device. If the device does not require polling, then calling this method has no effect. If a device that requires polling is not polled periodically, no new data will be received from the device. Calling this method causes Microsoft® DirectInput® to update the device state, generate input events (if buffered data is enabled), and set notification events (if notification is enabled).

object.Poll()

Parts

object
Resolves to a DirectInputDevice8 object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_NOTACQUIRED

Remarks

Before a device data can be polled, the data format must be set by using the DirectInputDevice8.SetDataFormat or DirectInputDevice8.SetCommonDataFormat method, and the device must be acquired by using the DirectInputDevice8.Acquire method.

See Also

Polling and Event Notification


DirectInputDevice8.RunControlPanel

Opens the Control Panel property sheet associated with this device. If the device does not have a property sheet associated with it, the default device property sheet is displayed.

object.RunControlPanel(hwnd As Long)

Parts

object
Resolves to a DirectInputDevice8 object.
hwnd
Handle to the parent window. If this parameter is 0, no parent window is used.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INVALIDPARAM


DirectInputDevice8.SendDeviceData

Sends data to a device that accepts output. The device must be in an acquired state.

object.SendDeviceData(count As Long, _
  data() As DIDEVICEOBJECTDATA, _
  flags As CONST_DESDDFLAGS) As Long

Parts

object
Resolves to a DirectInputDevice8 object.
count
Number of elements in data.
data
Array of DIDEVICEOBJECTDATA types containing the data to send to the device.

The lOfs field of each DIDEVICEOBJECTDATA type must contain the instance identifier (not the data offset) for the device object to which the data is directed. (See DirectInputDeviceObjectInstance.GetType.) The lTimeStamp and lSequence members must be 0.

flags
Flags controlling the manner in which data is sent. This may be 0 or the following value:
DISDD_CONTINUE
The device data sent will be overlaid on the previously sent device data. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_NOTACQUIRED
DIERR_REPORTFULL
DIERR_UNPLUGGED

Remarks

There is no guarantee that the individual data elements will be sent in a particular order. However, data sent by successive calls to SendDeviceData will not be interleaved. Furthermore, if multiple pieces of data are sent to the same object with a single call, it is unspecified which piece of data is sent.

Consider, for example, a device that can be sent data in packets, each packet describing two pieces of information, call them A and B. Suppose the application attempts to send three data elements: B = 2, A = 1, and B = 0.

The actual device will be sent a single packet. The A field of the packet will contain the value 1, and the B field of the packet will be either 2 or 0.

If the data must to be sent to the device exactly as specified, then three calls to SendDeviceData should be performed, each call sending one data element.

In response to the first call, the device will be sent a packet where the A field is blank and the B field contains the value 2.

In response to the second call, the device will be sent a packet where the A field contains the value 1, and the B field is blank.

Finally, in response to the third call, the device will be sent a packet where the A field is blank and the B field contains the value 0.

If the DISDD_CONTINUE flag is set, then the device data sent will be overlaid on the previously sent device data. Otherwise, the device data sent will start from scratch.

For example, suppose a device supports two button outputs, Button0 and Button1. If an application first calls SendDeviceData passing "Button0 pressed", then a packet of the form "Button0 pressed, Button1 not pressed" is sent to the device. If the application then makes another call, passing "Button1 pressed" and the DISDD_CONTINUE flag, then a packet of the form "Button0 pressed, Button1 pressed" is sent to the device. However, if the application had not passed the DISDD_CONTINUE flag, the packet sent to the device would have been "Button0 not pressed, Button1 pressed".


DirectInputDevice8.SendForceFeedbackCommand

Sends a command to the device's force-feedback system.

object.SendForceFeedbackCommand(flags As Long)

Parts

object
Resolves to a DirectInputDevice8 object.
flags
A single value indicating the desired change in state. The value may be one of the members of the CONST_DISFFCFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INPUTLOST
DIERR_NOTACQUIRED
DIERR_REPORTFULL
DIERR_UNPLUGGED


DirectInputDevice8.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.

Note

The device must be unacquired prior to calling this method.

object.SetActionMap(format As DIACTIONFORMAT, _
  userName As String, _
  flags As Long)

Parts

object
Resolves to a DirectInputDevice8 object.
format
DIACTIONFORMAT type that specifies information about the action map to be applied and about the buffer size for buffered device data.
userName
Value of type String that specifies the name of the user.
flags
Value of type Long that specifies how the action map is applied. Can be one of the constants of the CONST_DIDSAMFLAGS enumeration.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

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 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.

See Also

DirectInputDevice8.BuildActionMap


DirectInputDevice8.SetCommonDataFormat

Sets the input data format for standard devices.

object.SetCommonDataFormat( _
  format As CONST_DICOMMONDATAFORMATS)

Parts

object
Resolves to a DirectInputDevice8 object.
format
One of the CONST_DICOMMONDATAFORMATS enumeration, identifying the data format to use for the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_ACQUIRED
DIERR_INVALIDPARAM

Remarks

The data format must be set before the device can be acquired by using the DirectInputDevice8.Acquire method. It is necessary to set the data format only once. The data format cannot be changed while the device is acquired.

See Also

DirectInputDevice8.SetDataFormat


DirectInputDevice8.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.

object.SetCooperativeLevel(hwnd As Long, _
  flags As CONST_DISCLFLAGS)

Parts

object
Resolves to a DirectInputDevice8 object.
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 Microsoft® DirectInput® device.
flags
Flags that describe the cooperative level associated with the device. The flags are constants of the CONST_DISCLFLAGS enumeration.

The following combinations of flags are valid.
Flags | Meaning | Valid for
DISCL_NONEXCLUSIVE Or DISCL_BACKGROUND | Others can acquire device in exclusive or nonexclusive mode; your application has access to data at all times. | All.
DISCL_NONEXCLUSIVE Or DISCL_FOREGROUND | Others can acquire device in exclusive or nonexclusive mode; your application has access to data only when in the foreground. | All.
DISCL_EXCLUSIVE Or DISCL_BACKGROUND | Others can acquire device in nonexclusive mode; your application has access to data at all times. | Joystick.
DISCL_EXCLUSIVE Or DISC_FOREGROUND | Others can acquire device in nonexclusive mode; your application has access to data only when in the foreground. | All. Valid for mouse but prevents Microsoft® Windows® from displaying the cursor.

For keyboards, DISCL_NOWINKEY can be also be included with DISCL_NONEXCLUSIVE to disable the Windows logo key. the Windows logo key is always disabled when DISCL_EXCLUSIVE is specified. Note, however, that DISCL_NOWINKEY has no effect when the default action-mapping UI is displayed, and the Windows logo key operates normally as long as that UI is present.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INVALIDPARAM
DIERR_INVALIDHANDLE

Remarks

No two applications (or instances of the same application) can have a device acquired in exclusive mode at the same time. This is primarily a security feature; it prevents input intended for one application from going to another that may be running concurrently.

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 an 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.

If the system mouse is acquired in exclusive mode, then the pointer will be removed from the screen until the device is unacquired.

Applications must call this method before acquiring the device by using the DirectInputDevice8.Acquire method.

See Also

Cooperative Levels


DirectInputDevice8.SetDataFormat

Sets the data format for a Microsoft® DirectInput® device that is not a standard mouse, keyboard, or joystick.

object.SetDataFormat(format As DIDATAFORMAT, _
  formatArray() As DIOBJECTDATAFORMAT))

Parts

object
Resolves to a DirectInputDevice8 object.
format
A DIDATAFORMAT type that describes the format of the data the device should return.
formatArray
Array of DIOBJECTDATAFORMAT types describing data formats for objects on the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_ACQUIRED
DIERR_INVALIDPARAM

Remarks

The data format must be set before the device can be acquired by using the DirectInputDevice8.Acquire method. It is necessary to set the data format only once. The data format cannot be changed while the device is acquired.

See Also

DirectInputDevice8.SetActionMap, DirectInputDevice8.SetCommonDataFormat


DirectInputDevice8.SetEventNotification

Sets the event notification status. This method specifies an event that is to be set when the device state changes. It is also used to turn off event notification.

object.SetEventNotification(hEvent As Long)

Parts

object
Resolves to a DirectInputDevice8 object.
hEvent
Handle to the event that is to be set when the device state changes, or 0 to disable notification.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_ACQUIRED
DIERR_HANDLEEXISTS
DIERR_INVALIDPARAM

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

You must call this method with the hEvent parameter set to 0 before destroying the event.

The event notification handle cannot be changed while the device is acquired.

See Also

Polling and Event Notification, DirectXEvent8


DirectInputDevice8.SetProperty

Sets properties that define the device behavior.

object.SetProperty( _
  guid As String, _
  propertyInfo As Any)

Parts

object
Resolves to a DirectInputDevice8 object.
guid
Identifier of the property to be set. The following property values are predefined for an input device and can be passed as strings:
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 lHow member of the associated DIPROPLONG type must be DIPH_DEVICE.

The lData member can be one of the following values from the CONST_DINPUT enumeration.

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 (either DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL from the CONST_DINPUT enumeration) must be specified in the lData member of the associated DIPROPLONG type.

This setting applies to the entire device, so the lHow member of the DIPROPLONG type must be set to DIPH_DEVICE.

DIPROP_BUFFERSIZE
Sets the input-buffer size. See Remarks.

This setting applies to the entire device, so the lHow member of the associated DIPROPLONG type must be set to DIPH_DEVICE.

DIPROP_CALIBRATIONMODE
Enables the application to specify whether Microsoft® 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 lData member of the DIPROPLONG type may 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 Control Panel–type applications.

Note that setting a device into raw mode causes the dead zone, saturation, and range settings to be ignored.

DIPROP_CPOINTS
Retrieves calibration points used for the adjustment of incoming raw data as a DIPROPCPOINTS structure.
DIPROP_DEADZONE
Sets the value for the dead zone of a joystick, in the range 0 to 10,000, where 0 indicates 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 lHow member of the associated DIPROPLONG type must be DIPH_DEVICE.

The lData 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, and specifies the amount by which effect magnitudes are scaled for the device. For example, a value of 10,000 indicates that you should take all effect magnitudes at face value. A value of 9,000 indicates that you should reduce all effect magnitudes to 90% of their nominal magnitudes.

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 by GetInstanceName) to distinguish it from similar devices that are plugged in simultaneously. Most applications should not need to change the friendly name.

This setting applies to the entire device, so the lHow member of the associated DIPROPSTRING type must be set to DIPH_DEVICE.

The PropString member is a string that specifies the new friendly instance name for the device.

DIPROP_PRODUCTNAME
This property exists for advanced applications that want to change the friendly product name of a device (as returned by GetProductName) 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 lHow member of the associated DIPROPSTRING type must be set to DIPH_DEVICE.

The PropString member is a string that specifies the new friendly product name for the device.

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 type.

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 0 to 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, then 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 to a specific axis.

propertyInfo
A DIPROPLONG type containing data for properties that take a single value, a DIPROPRANGE type containing data for properties that take a pair of values, or a DIPROPSTRING type containing data for properties that take a string.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INVALIDPARAM
DIERR_OBJECTNOTFOUND
DIERR_UNSUPPORTED

Remarks

The buffer size determines the amount of data that the buffer can hold between calls to the DirectInputDevice8.GetDeviceData method before data is lost. This value may be set to 0 to indicate that the application will not be reading buffered data from the device. If the buffer size in the lData member of the DIPROPLONG type is too large to be supported by the device, the largest possible buffer size is set. To determine whether the requested buffer size was set, retrieve the buffer-size property and compare the result with the value you previously attempted to set.

See Also

DirectInputDevice8.GetProperty


DirectInputDevice8.Unacquire

Releases access to the device.

object.Unacquire()

Parts

object
Resolves to a DirectInputDevice8 object.

Error Codes

None.

See Also

DirectInputDevice8.Acquire


DirectInputDevice8.WriteEffectToFile

Writes a force-feedback effect to a file.

object.WriteEffectToFile( _
  filename As String, _
  flags As Long, _
  guid As String, _
  name As String, _
  CoverEffect As DIEFFECT)

Parts

object
Resolves to a DirectInputDevice8 object.
filename
Name of the RIFF file. If the file exists, it is overwritten.
flags
Flags which control how the effect should be written. Can be one of the following values from the CONST_DIFEFFLAGS enumeration.

DIFEF_DEFAULT

Do not write the effect if it is not a standard type.

DIFEF_INCLUDENONSTANDARD

Write the effect even if it is not a standard type.

guid
Identifier of the effect type, such as "GUID_RampForce". For a list of standard effects, see DirectInputDevice8.CreateEffect. For nonstandard effects, this parameter must be a string representation of the numerical GUID.
name
Friendly name of the effect.
CoverEffect
DIEFFECT type that specifies parameters of the effect.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes.

DIERR_INVALIDPARAM

Remarks

This method is chiefly of interest for force-authoring applications.

See Also

DirectInputDevice8.CreateEffectFromFile


DirectInputDeviceInstance8

The DirectInputDeviceInstance8 class is used to obtain information about an instance of a Microsoft® DirectInput® device.

An object of this class is returned by the DirectInputDevice8.GetDeviceInfo and DirectInputEnumDevices8.GetItem method.

The DirectInputDeviceInstance8 class has the following methods:

Information | GetDevType
 | GetGuidFFDriver
 | GetGuidInstance
 | GetGuidProduct
 | GetInstanceName
 | GetProductName
 | GetUsage
 | GetUsagePage


DirectInputDeviceInstance8.GetDevType

Retrieves the device type and subtype.

object.GetDevType() As Long

Parts

object
Resolves to a DirectInputDeviceInstance8 object.

Return Values

Returns a device type specifier. This value is a combination of a type (in the least significant byte) and subtype (in the next most significant byte), optionally combined using Or with DIDEVTYPE_HID, which specifies a Human Interface Device (HID). The following constants are from the CONST_DI8DEVICETYPE and CONST_DI8DEVICESUBTYPE enumerations.

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_HARDWIRED
Device which 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_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.
DI8DEVTYPEGAMEPAD_STANDARD
Standard gamepad that provides 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 only defined subtype is DI8DEVTYPEREMOTE_UNKNOWN.
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.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

To look for a particular subtype of device such as a wheel, check both the type and the subtype.


DirectInputDeviceInstance8.GetGuidFFDriver

Retrieves the unique identifier for the force-feedback driver.

object.GetGuidFFDriver() As String

Parts

object
Resolves to a DirectInputDeviceInstance8 object.

Return Values

Returns the GUID for the force feedback driver, in string form. This identifier is established by the manufacturer of the driver.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

Using GUIDs


DirectInputDeviceInstance8.GetGuidInstance

Retrieves the unique identifier for the instance of the device.

object.GetGuidInstance() As String

Parts

object
Resolves to a DirectInputDeviceInstance8 object.

Return Values

Returns the GUID for the device instance, in string form.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

An application can save the instance 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.

See Also

DirectInputDeviceInstance8.GetGuidProduct, Using GUIDs


DirectInputDeviceInstance8.GetGuidProduct

Retrieves the manufacturer's unique identifier for the device.

object.GetGuidProduct() As String

Parts

object
Resolves to a DirectInputDeviceInstance8 object.

Return Values

Returns the GUID for the product, in string form. This identifier is established by the manufacturer of the device.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDeviceInstance8.GetGuidInstance, Using GUIDs


DirectInputDeviceInstance8.GetInstanceName

Retrieves the name of the device instance.

object.GetInstanceName() As String

Parts

object
Resolves to a DirectInputDeviceInstance8 object.

Return Values

Returns the friendly name for the instance—for example, "Joystick 1".

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDeviceInstance8.GetProductName


DirectInputDeviceInstance8.GetProductName

Retrieves the product name of the device.

object.GetProductName() As String

Parts

object
Resolves to a DirectInputDeviceInstance8 object.

Return Values

Returns the friendly name for the product—for example, "Microsoft® SideWinder®".

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDeviceInstance8.GetInstanceName


DirectInputDeviceInstance8.GetUsage

Retrieves the usage code for Human Interface Devices (HIDs).

object.GetUsage() As Integer

Parts

object
Resolves to a DirectInputDeviceInstance8 object.

Return Values

Returns the HID usage code for HID devices, or 0.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDeviceInstance8.GetUsagePage


DirectInputDeviceInstance8.GetUsagePage

Retrieves the usage page for Human Interface Devices (HIDs).

object.GetUsagePage() As Integer

Parts

object
Resolves to a DirectInputDeviceInstance8 object.

Return Values

Returns the usage page or 0 for non-HIDs.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDeviceInstance8.GetUsage


DirectInputDeviceObjectInstance

The DirectInputDeviceObjectInstance class represents an object on a Microsoft® DirectInput® device, such as a button or axis.

A DirectInputDeviceObjectInstance object is returned by the DirectInputDevice8.GetObjectInfo and DirectInputEnumDeviceObjects.GetItem methods.

This class has the following methods:

Information | GetCollectionNumber
 | GetDesignatorIndex
 | GetDimension
 | GetExponent
 | GetFlags
 | GetGuidType
 | GetName
 | GetOfs
 | GetType
 | GetUsage
 | GetUsagePage


DirectInputDeviceObjectInstance.GetCollectionNumber

Retrieves the number of the HID link collection to which the device object belongs.

object.GetCollectionNumber() As Integer

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns the number of the collection or 0 if the object is not part of an HID.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputDeviceObjectInstance.GetDesignatorIndex

Retrieves the designator index for an object on a Human Interface Device (HID).

object.GetDesignatorIndex() As Integer

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns an index that refers to a designator in the HID physical descriptor.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputDeviceObjectInstance.GetDimension

Retrieves a Human Interface Device (HID)code for the dimensional units in which the object's value is reported.

object.GetDimension() As Long

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns a code for the dimensional units in which the object's value is reported, if known, or 0 if not known.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDeviceObjectInstance.GetExponent


DirectInputDeviceObjectInstance.GetExponent

Retrieves the exponent to associate with the dimensional units of the device object.

object.GetExponent() As Integer

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns the exponent to associate with the dimension, if known. Dimensional units are always integral, so an exponent may be needed to convert them to non-integral types.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDeviceObjectInstance.GetDimension


DirectInputDeviceObjectInstance.GetFlags

Retrieves the flags associated with the device object.

object.GetFlags() As CONST_DIDEVICEOBJINSTANCEFLAGS

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns one or more members of the CONST_DIDEVICEOBJINSTANCEFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputDeviceObjectInstance.GetGuidType

Retrieves the unique identifier of the object type.

object.GetGuidType() As String

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Can return one of the following string identifiers, representing the unique identifier for the object type. If the object type has a GUID not represented in the following list, a string representing the actual GUID is returned. If the object type does not have a GUID, an empty string is returned.

GUID_XAxis
The horizontal axis. For example, it may represent the left-right motion of a mouse.
GUID_YAxis
The vertical axis. For example, it may represent the forward-backward motion of a mouse.
GUID_ZAxis
The z-axis. For example, it may represent rotation of the wheel on a mouse, or movement of a throttle control on a joystick.
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 button on a mouse.
GUID_Key
A key on a keyboard.
GUID_POV
A point-of-view indicator or "hat".
GUID_Unknown
Unknown.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputDeviceObjectInstance.GetName

Retrieves the friendly name of the device object.

object.GetName() As String

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns the name of the object—for example, "X-Axis" or "Right Shift."

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputDeviceObjectInstance.GetOfs

Retrieves the offset of the device object's data within the data format for the device.

object.GetOfs() As Long

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns the offset within the data format at which data is reported for this object. This value can be used to identify the object in method calls and types that accept the DIPH_BYOFFSET flag.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDevice8.GetObjectInfo, DIPROPLONG, DIPROPRANGE


DirectInputDeviceObjectInstance.GetType

Retrieves the type and instance identifier of the object.

object.GetType() As Long

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns the device type that describes the object. This value is a combination of CONST_DIDFTFLAGS flags that describe the object type (axis, button, and so forth) and contains the object instance number in the middle 16 bits.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

To extract the object instance ID, use the following operation:

Dim ObjID as Long
ObjID = (diObj.GetType And &HFFFF00) \ 256


DirectInputDeviceObjectInstance.GetUsage

Retrieves the Human Interface Device (HID) usage code for the device object.

object.GetUsage() As Integer

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns the HID usage associated with the object, if known. HIDs always report a usage. Non-HID devices might report a usage; if they do not, the return value is zero.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDeviceObjectInstance.GetUsagePage


DirectInputDeviceObjectInstance.GetUsagePage

Retrieves the Human Interface Device (HID) usage page for the device object.

object.GetUsagePage() As Integer

Parts

object
Resolves to a DirectInputDeviceObjectInstance object.

Return Values

Returns the HID usage page associated with the object, if known. (HIDs) will always report a usage page. Non-HID devices might report a usage page; if they do not, the return value is zero.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectInputDeviceObjectInstance.GetUsage


DirectInputEffect

An object of the DirectInputEffect class represents a force-feedback effect created by an application. The object is created by using the DirectInputDevice8.CreateEffect method.

This class has the following methods:

Control | Download
 | SetParameters
 | Start
 | Stop
 | Unload
Information | GetEffectGuid
 | GetEffectStatus
 | GetParameters


DirectInputEffect.Download

Places the effect on the device. If the effect is already on the device, then the existing effect is updated to match the values set by the DirectInputEffect.SetParameters method.

object.Download()

Parts

object
Resolves to a DirectInputEffect object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_NOTINITIALIZED
DIERR_DEVICEFULL
DIERR_INCOMPLETEEFFECT
DIERR_INPUTLOST
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_INVALIDPARAM
DIERR_EFFECTPLAYING

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

It is valid to update an effect while it is playing. The semantics of such an operation are explained in the reference for DirectInputEffect.SetParameters.


DirectInputEffect.GetEffectGuid

Retrieves the GUID or GUID alias for the effect represented by the DirectInputEffect object.

object.GetEffectGuid() As String

Parts

object
Resolves to a DirectInputEffect object.

Return Values

Returns the GUID or alias that was passed to DirectInputDevice8.CreateEffect, such as "GUID_ConstantForce".

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

Using GUIDs


DirectInputEffect.GetEffectStatus

Retrieves the status of an effect.

object.GetEffectStatus() As Long

Parts

object
Resolves to a DirectInputEffect object.

Return Values

Returns status flags for the effect. The value may be zero, or one or more of the following constants of the CONST_DIEGESFLAGS enumeration.

DIEGES_PLAYING
The effect is playing.
DIEGES_EMULATED
The effect is emulated.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectInputEffect.GetParameters

Retrieves information about an effect.

object.GetParameters(effectinfo As DIEFFECT)

Parts

object
Resolves to a DirectInputEffect object.
effectinfo
DIEFFECT type to receive the effect parameters.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_INVALIDPARAM
DIERR_MOREDATA
DIERR_NOTINITIALIZED


DirectInputEffect.SetParameters

Sets the characteristics of an effect.

object.SetParameters(effectinfo As DIEFFECT, _
    flags As CONST_DIEPFLAGS)

Parts

object
Resolves to a DirectInputEffect object.
effectinfo
DIEFFECT type containing effect parameters.
flags
Flags from the CONST_DIEPFLAGS enumeration specifying which portions of the effect information are to be set and how the downloading of the parameters should be handled.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_NOTINITIALIZED
DIERR_INCOMPLETEEFFECT
DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_EFFECTPLAYING

Remarks

To determine which parameters can be dynamically updated while the effect is playing, use the DirectInputEnumEffects.GetDynamicParams method.

The DirectInputEffect.SetParameters method automatically downloads the effect, but this behavior can be suppressed by setting the DIEP_NODOWNLOAD flag. If automatic download has been suppressed, then you can manually download the effect by calling DirectInputEffect.Download.

If the effect is playing while the parameters are changed, then 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 will then continue 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 scenario, if after two seconds the duration of the effect were changed to 1.5 seconds, then 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 DirectInputEffect.Start method had been called with the iterations parameter set to 1 and with no flags. (Combining the update with DIEP_START is slightly faster than calling 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, then the parameters are updated and downloaded to the device.

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is playing, then 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.


DirectInputEffect.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, then it will be downloaded before being started. This default behavior can be suppressed by passing the DIES_NODOWNLOAD flag.

object.Start(iterations As Long, flags As Long)

Parts

object
Resolves to a DirectInputEffect object.
iterations
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 -1. To play the effect until explicitly stopped without re-articulating the envelope, modify the effect parameters with the DirectInputEffect.SetParameters method and change the lDuration member of DIEFFECT to -1.

flags
Flags from the CONST_DIESFLAGS enumeration that describe how the effect should be played by the device. The value can be zero or one or more flags.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_INVALIDPARAM
DIERR_INCOMPLETEEFFECT
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.


DirectInputEffect.Stop

Stops an effect that is playing.

object.Stop()

Parts

object
Resolves to a DirectInputEffect object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.


DirectInputEffect.Unload

Removes the effect from the device. If the effect is playing, it is automatically stopped before it is unloaded.

object.Unload()

Parts

object
Resolves to a DirectInputEffect object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.


DirectInputEnumDeviceObjects

The DirectInputEnumDeviceObjects class enumerates the Microsoft® DirectInputDevice8 objects installed on a system. This object is created and filled with data as a result of a call to DirectInputDevice8.GetDeviceObjectsEnum method.

This class has the following methods:

Information | GetCount
 | GetItem


DirectInputEnumDeviceObjects.GetCount

Returns the number of items in the DirectInputEnumDeviceObjects collection.

object.GetCount() As Long

Parts

object
Resolves to a DirectInputEnumDeviceObjects object.

Return Values

Returns the number of device objects enumerated for the device.

Error Codes

None.


DirectInputEnumDeviceObjects.GetItem

Retrieves an object describing the specified device object.

object.GetItem(index As Long) _
  As DirectInputDeviceObjectInstance

Parts

object
Resolves to a DirectInputEnumDeviceObjects object.
index
Index of the enumerated item to retrieve.

Return Values

Returns a DirectInputDeviceObjectInstance object whose methods can be used to retrieve information about the device object.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

To get the number of entries in the DirectInputEnumDeviceObjects first call the DirectInputEnumDeviceObjects.GetCount method.

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.


DirectInputEnumDevices8

The DirectInputEnumDevices8 class enumerates the Microsoft® DirectInput® devices installed on a system. This object is created and filled with data as a result of a call to the DirectInput8.GetDIDevices and DirectInput8.GetDevicesBySemantics methods.

This class has the following methods:

GetCount
GetItem


DirectInputEnumDevices8.GetCount

Returns the number of Microsoft® DirectInput® devices in the DirectInputEnumDevices8 collection.

object.GetCount() As Long

Parts

object
Resolves to a DirectInputEnumDevices8 object.

Return Values

Returns the number of DirectInput® devices in the DirectInputEnumDevices8 collection.

Error Codes

None.


DirectInputEnumDevices8.GetItem

Returns information about an enumerated device.

object.GetItem(index As Long) As DirectInputDeviceInstance8

Parts

object
Resolves to a DirectInputEnumDevices8 object.
index
Index of the device in the DirectInputEnumDevices8 collection.

Return Values

Returns a DirectInputDeviceInstance8 object whose methods can be used to retrieve information about the device.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

To get the number of entries in DirectInputEnumDevices8 first call the DirectInputEnumDevices8.GetCount method.


DirectInputEnumEffects

An object of the DirectInputEnumEffects class represents a collection of supported force-feedback effects on a device, and is used for retrieving information about the effects. The object is created by using the DirectInputDevice8.GetEffectsEnum method.

The class has the following methods:

Information | GetCount
 | GetDynamicParams
 | GetEffectGuid
 | GetName
 | GetStaticParams
 | GetType


DirectInputEnumEffects.GetCount

Returns the number of enumerated effects in the collection.

object.GetCount() As Long

Parts

object
Resolves to a DirectInputEnumEffects object.

Return Values

Returns the number of items in the collection.

Error Codes

If the method fails, it raises an error and Err.Number is set.


DirectInputEnumEffects.GetDynamicParams

Retrieves information about which effect parameters can be changed without stopping the effect, using the DirectInputEffect.SetParameters method.

object.GetDynamicParams(i As Long) As CONST_DIEPFLAGS

Parts

object
Resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

Returns flags from the CONST_DIEPFLAGS enumeration specifying which parameters can be dynamically updated while the effect is playing.

Error Codes

If the method fails, it raises an error and Err.Number is set.

See Also

DirectInputEffect.SetParameters


DirectInputEnumEffects.GetEffectGuid

Retrieves the GUID for the supported effect. This GUID can be passed to the DirectInputDevice8.CreateEffect method.

object.GetEffectGuid(i As Long) As String

Parts

object
Resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

Returns the GUID in string form. For standard effects, the return value is an alias such as "GUID_ConstantForce".

Error Codes

If the method fails, it raises an error and Err.Number is set.

See Also

Using GUIDs


DirectInputEnumEffects.GetName

Retrieves the name of the effect.

object.GetName(i As Long) As String

Parts

object
Resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

Returns the name of the effect, such as "Constant Force".

Error Codes

If the method fails, it raises an error and Err.Number is set.


DirectInputEnumEffects.GetStaticParams

Retrieves information about effect parameters supported on the device.

object.GetStaticParams(i As Long) As CONST_DIEPFLAGS

Parts

object
Resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

Returns flags from the CONST_DIEPFLAGS enumeration specifying which parameters are supported by the effect.

Error Codes

If the method fails, it raises an error and Err.Number is set.


DirectInputEnumEffects.GetType

Retrieves information about the type and capabilities of the effect.

object.GetType(i As Long) As CONST_DIEFTFLAGS

Parts

object
Resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

Returns flags from the CONST_DIEFTFLAGS enumeration giving information about the effect.

Error Codes

If the method fails, it raises an error and Err.Number is set.

Remarks

The effect type is stored in the low byte and can be retrieved by a bitwise And with &HFF.


Types

This section contains information on the following types used with Microsoft® DirectInput®.

  • CPOINT
  • DIACTION
  • DIACTIONFORMAT
  • DICOLORSET
  • DICONDITION
  • DICONFIGUREDEVICESPARAMS
  • DICONSTANTFORCE
  • DIDATAFORMAT
  • DIDEVCAPS
  • DIDEVICEIMAGEINFO
  • DIDEVICEIMAGEINFOHEADER
  • DIDEVICEOBJECTDATA
  • DIEFFECT
  • DIENVELOPE
  • DIJOYSTATE
  • DIJOYSTATE2
  • DIKEYBOARDSTATE
  • DIMOUSESTATE
  • DIMOUSESTATE2
  • DIOBJECTDATAFORMAT
  • DIPERIODICFORCE
  • DIPROPGUIDANDPATH
  • DIPROPLONG
  • DIPROPRANGE
  • DIPROPSTRING
  • DIRAMPFORCE


CPOINT

Describes a calibration point. An array of CPOINT types is contained by a DIPROPCPOINTS type.

Type CPOINT
     lp As Long
     dwLog As Long
End Type

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

Specifies and receives information about the mapping of a single application action to a device object or virtual control.

Type DIACTION
    ActionName As String
    lAppData As Long
    lFlags As Long
    lHow As Long
    lObjId As Long
    lSemantic As Long
End Type

Members

ActionName
Application-defined name of the action. This string is displayed by the device property sheet when DirectInput8.ConfigureDevices is called. If sResIDString is not an empty string, this member is ignored.
lAppData
Value to be returned to the application when the state of the control associated with the action changes. This value is returned in the lUserData member of the DIDEVICEOBJECTDATA type retrieved by DirectInputDevice8.GetDeviceData.
lFlags
Flags used to request specific attributes or processing. Can be zero or one or more of the values in the CONST_DIAFLAGS enumeration.
lHow
Mapping mechanism used by Microsoft® DirectInput® to configure the action. This member receives one of the members of the CONST_DIAHFLAGS enumeration when the type is returned by DirectInputDevice8.BuildActionMap.

This member is ignored when the action map is passed to DirectInputDevice8.SetActionMap.

lObjId
Control identifier.
lSemantic
For a joystick, a predefined action mapping constant for this application genre, representing a virtual control. See CONST_DIGENRE.

This value can also be one of the CONST_DIMAPFLAGS enumeration to map the action to a virtual control not defined in a genre.

For a keyboard, mouse, or Microsoft DirectPlay® voice device, this value is a constant that represents a particular device object.

See Also

CONST_DIKEYBOARDFLAGS, CONST_DIMOUSEFLAGS, CONST_DIVOICEFLAGS


DIACTIONFORMAT

Specifies and receives information about an action map.

Type DIACTIONFORMAT
    ActionArray() As DIACTION
    ActionMapName As String
    guidActionMap As String
    lActionCount As Long
    lAxisMax As Long
    lAxisMin As Long
    lBufferSize As Long
    lDataSize As Long
    lGenre As Long
End Type

Members

ActionArray
Array of DIACTION types, 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.
ActionMapName
Friendly name for the action map.
guidActionMap
GUID that identifies the action map. This value can be used by device manufacturers to tune mappings for a specific title.
lActionCount
Number of elements in ActionArray.
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 the DIACTION type for that action. See Remarks.
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 the DIACTION type for that action. See Remarks.
lBufferSize
Value that specifies the number of input data packets in the buffer for each device to which this action map is applied. See Remarks.
lDataSize
Value that specifies the size of immediate data to be returned by the device, in bytes. When this type is passed to DirectInputDevice8.SetActionMap, this value should be four times the number of elements in the array of DIACTION types passed to the method.
lGenre
Genre of the application. One of the members of the CONST_DIGENRE enumeration whose names begin with DIVIRTUAL.

Remarks

The lAxisMax and lAxisMin members are valid only for axis actions and should be set to zero for all other actions. Setting them before passing this type to DirectInputDevice8.SetActionMap is equivalent to setting the range properties by passing a DIPROPRANGE type to DirectInputDevice8.SetProperty.

The buffer size must be set to a value greater than zero if you want to retrieve data by using DirectInputDevice8.GetDeviceData. Applications that set the lBufferSize member to the desired buffer size before passing this type to DirectInputDevice8.SetActionMap do not need to set the DIPROP_BUFFERSIZE property by using DirectInputDevice8.SetProperty.


DICOLORSET

Describes a set of colors used to draw the device configuration user interface. It is part of the DICONFIGUREDEVICESPARAMS TYPE.

Type DICOLORSET
    cAreaFill As Long
    cBorder As Long
    cCalloutHighlight As Long
    cCalloutLine As Long
    cControlFill As Long
    cHighlightFill As Long
    cTextFore As Long
    cTextHighlight As Long
End Type

Members

cAreaFill
Fill color for areas outside controls such as tabs and buttons.
cBorder
Border color, used to display lines around controls such as tabs and buttons.
cCalloutHighlight
Color used to display callout lines.
cCalloutLine
Color used to display callout lines.
cControlFill
Fill color for controls such as tabs and buttons.
cHighlightFill
Fill color for highlighted controls.
cTextFore
Foreground text color.
cTextHighlight
Foreground color for highlighted text.

Remarks

Text background color is always transparent.


DICONDITION

Describes parameters for a force-feedback condition in the DIEFFECT type.

Type DICONDITION
    lDeadBand As Long
    lNegativeCoefficient As Long
    lNegativeSaturation As Long
    lOffset As Long
    lPositiveCoefficient As Long
    lPositiveSaturation As Long
End Type

Members

lDeadBand
The region around lOffset where the condition is not active, in the range 0 to 10,000. In other words, the condition is not active between lOffset - lDeadBand and lOffset + lDeadBand.
lNegativeCoefficient
The coefficient constant on the negative side of the offset, in the range -10,000 to +10,000.

If the device does not support separate positive and negative coefficients, then the value of lNegativeCoefficient is ignored and the value of lPositiveCoefficient is used as both the positive and negative coefficients.

lNegativeSaturation
The maximum force output on the negative side of the offset, in the range 0 to 10,000.

If the device does not support force saturations, then the value of this member is ignored.

If the device does not support separate positive and negative saturations, then the value of lNegativeSaturation is ignored and the value of lPositiveSaturation is used as both the positive and negative saturations.

lOffset
The offset for the condition, in the range -10,000 to +10,000.
lPositiveCoefficient
The coefficient constant on the positive side of the offset, in the range -10,000 to +10,000.
lPositiveSaturation
The maximum force output on the positive side of the offset, in the range 0 to 10,000.

If the device does not support force saturation, then the value of this member is ignored.

Remarks

Different types of conditions will 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 dead band is provided. If the metric is less than lOffset - lDeadBand, then the resulting force is given by the following formula:

force = lNegativeCoefficient * (q - (lOffset - lDeadBand))

Similarly, if the metric is greater than lOffset + lDeadBand, then 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.


DICONFIGUREDEVICESPARAMS

Contains information for the device configuration property sheet. It is used by the DirectInput8.ConfigureDevices method.

Type DICONFIGUREDEVICESPARAMS
    ActionFormats() As DIACTIONFORMAT
    DDSTarget As Unknown
    dics As DICOLORSET
    FormatCount As Long
    hwnd As Long
    UserCount As Long
    UserNames() As String
End Type

Members

ActionFormats
Array of DIACTIONFORMAT types 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.
DDSTarget
Direct3DSurface8 object for the configuration user interface. The device image is alpha-blended over the background surface onto the target surface.

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 Microsoft DirectInput® to use the Windows Graphics Device Interface (GDI) functions to draw the configuration user interface image.

dics
DICOLORSET type that describes the color scheme to apply to the configuration user interface.
FormatCount
Number of elements in the ActionFormats 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.
UserCount
Number of elements in the UserNames array. Zero is an invalid value. If the UserCount value exceeds the number of entries actually in the array at UserNames(), the method fails, returning DIERR_INVALIDPARAM. If the UserNames array is set to NULL, the value in UserCount is ignored.
UserNames
Array of user names. This parameter can be set to NULL to request default names, the number of which is determined by UserCount. If the application passes more than UserCount names, 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.


DICONSTANTFORCE

Describes parameters for a constant force in the DIEFFECT type.

Type DICONSTANTFORCE
    lMagnitude As Long
End Type

Members

lMagnitude
Magnitude of the effect, in the range -10,000 to +10,000. If an envelope is applied to this effect, then the value represents the magnitude of the sustain. If no envelope is applied, then the value represents the amplitude of the entire effect.


DIDATAFORMAT

Describes a device's data format. This type is used with the DirectInputDevice8.SetDataFormat method.

Type DIDATAFORMAT
    dataSize As Long
    lFlags As CONST_DIDATAFORMATFLAGS
    lObjSize As Long
    numObjs As Long
End Type

Members

dataSize
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.
lFlags
Flags describing other attributes of the data format. This value can be one of the CONST_DIDATAFORMATFLAGS enumeration.
lObjSize
Size of the DIOBJECTDATAFORMAT type, in bytes.
numObjs
Number of objects for which data is to be returned.

Remarks

Applications need to create a DIDATAFORMAT type only for nonstandard devices. For the mouse, keyboard, and joystick, you set the data format by using DirectInputDevice8.SetCommonDataFormat.


DIDEVCAPS

Describes capabilities of a Microsoft® DirectInput® device. This type is used with the DirectInputDevice8.GetCapabilities method.

Type DIDEVCAPS
    lAxes As Long
    lButtons As Long
    lDevType As Long
    lDriverVersion As Long
    lFFMinTimeResolution As Long
    lFFSamplePeriod As Long
    lFirmwareRevision As Long
    lFlags As CONST_DIDEVCAPSFLAGS
    lHardwareRevision As Long
    lPOVs As Long
End Type

Members

lAxes
Number of axes available on the device.
lButtons
Number of buttons available on the device.
lDevType
A packed value containing information about the type and subtype of the device. The value is identical to that returned by the DirectInputDeviceInstance8.GetDevType method.
lDriverVersion
The version number of the device driver.
lFFMinTimeResolution
The minimum amount of time, in microseconds, that the device can resolve when playing force-feedback effects. The device rounds any times to the nearest supported increment. For example, if the value of lFFMinTimeResolution is 1000, then the device would round any times to the nearest millisecond.
lFFSamplePeriod
The minimum time between playback of consecutive raw force commands.
lFirmwareRevision
Specifies the firmware revision of the device.
lFlags
Flags associated with the device. This value can be a combination of the constants of the CONST_DIDEVCAPSFLAGS enumeration.
lHardwareRevision
The hardware revision of the device.
lPOVs
Number of point-of-view controllers available on the device.

Remarks

The semantics of version numbers are left to the manufacturer of the device. The only guarantee is that newer versions will have larger numbers.


DIDEVICEIMAGEINFO

Carries information required to display a device image, or an overlay image with a callout. This type is passed to the DirectInputDevice8.GetImageInfo method as an array within a DIDEVICEIMAGEINFOHEADER type.

Type DIDEVICEIMAGEINFO
    CalloutLine(0 To 4) As POINT
    CalloutRect As RECT
    flags As Long
    ImagePath As String
    ObjId As Long
    ViewID As Long
    OverlayRect As RECT
    TextAlign As Long
    ValidPts As Long
End Type

Members

CalloutLine
Array of types 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 one to four segments. This member is valid only if the DIDIFT_OVERLAY flag is present in flags.
CalloutRect
Type that specifies coordinates of the rectangle in which the game action string is displayed. The application handles clipping. This member is valid only if the DIDIFT_OVERLAY flag is present in flags.
flags
Flag that describes the intended use of the image. This member can be one of the following values from the CONST_DIDIFTFLAGS enumeration.
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 particular control on the configuration image. The ViewID, OverlayRect, ObjID, CalloutLine, CalloutRect, and TextAlign 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 rdOverlay.
ImagePath
Fully qualified path to the file that contains an image of the device.
ObjId
Control identifier, combining object type flags and an instance value, to which an overlay image corresponds for this device. For more information on this identifier, see DirectInputDeviceObjectInstance.GetType. This member is valid only if the DIDIFT_OVERLAY flag is present in flags.
OverlayOffset
Offset of the device configuration image over which this overlay is to be displayed. This member is valid only if the DIDIFT_OVERLAY flag is present in flags.
OverlayRect
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 flags.
TextAlign
Value that specifies the alignment of the text in the rectangle described by the CalloutRect member. Must be one horizontal alignment flag combined with one vertical alignment flag from the CONST_DIDALFLAGS enumeration.

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.

This member is valid only if the DIDIFT_OVERLAY flag is present in flags.

ValidPts
Number of points in the CalloutLine array.
ViewID
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.


DIDEVICEIMAGEINFOHEADER

Contains information about device images. This type is passed to the DirectInputDevice8.GetImageInfo method. On return, it contains information about the device and the images that represent it in the device configuration property sheet.

Type DIDEVICEIMAGEINFOHEADER
    Axes As Long
    Buttons As Long
    ImageCount As Long
    Images() As DIDEVICEIMAGEINFO
    POVs As Long
    Views As Long
End Type

Members

Axes
Number of axes on the device.
Buttons
Number of buttons on the device.
ImageCount
Number of elements in the Images array.
Images
Array of DIDEVICEIMAGEINFO types describing device images and views, overlay images, and callout-string coordinates.
POVs
Number of point-of-view controllers on the device.
Views
Number of views of this device.

Remarks

Before passing this type to DirectInputDevice8.GetImageInfo, the application must initialize the ImageCount and Images members as follows:

' Assume that didev is a DirectInputDevice8 object

Dim count as Integer
Dim diImageInfoHdr

count = didev.GetImageInfoCount
With diImageInfoHdr
  ImageCount = count
  ReDim Images(count)
End With

Members of the type other than ImageCount are filled with data by the method call.

See Also

DirectInputDevice8.GetImageInfoCount


DIDEVICEOBJECTDATA

Contains raw buffered device information. This type is used with the DirectInputDevice8.GetDeviceData method.

Type DIDEVICEOBJECTDATA
    lData As Long
    lOfs As Long
    lSequence As Long
    lTimeStamp As Long
    lUserData As Long
End Type

Members

lData
Data obtained from the device.

For axis input, if the device is in relative axis mode, then the relative axis motion is reported. If the device is in absolute axis mode, then the absolute axis coordinate is reported.

For button input, only the low byte of lData is significant. The high bit of the low byte is set if the button went down; it is clear if the button went up.

lOfs
Offset into the current data format of the object whose data is being reported—that is, the location where the data would have been stored if it had been obtained by a call to the DirectInputDevice8.GetDeviceStateX method where X refers to the specific device, for instance GetDeviceStateMouse. If the device is accessed as a keyboard, you can determine which key generated the event by comparing this value with the members of the CONST_DIKEYFLAGS enumeration. For the mouse and joystick, the value in lOfs is equivalent to the byte offset of the button or axis within the DIMOUSESTATE, DIJOYSTATE, or DIJOYSTATE2 type (depending on the data format that was established by using DirectInputDevice8.SetCommonDataFormat.) Constants for these offsets are contained in the CONST_DIMOUSEOFS and CONST_DIJOYSTICKOFS enumerations. If a custom data format has been set by using DirectInputDevice8.SetDataFormat, then lOfs is the offset of the device object's place in the custom data format.
lSequence
Microsoft® DirectInput® sequence number for this event. All input events are assigned an increasing sequence number. This allows events from different devices to be sorted chronologically. Since this value can wrap around, care must be taken when comparing two sequence numbers.
lTimeStamp
System time at which the input event was generated, in milliseconds. This value wraps around approximately every 50 days.
lUserData
Application-defined action value assigned to this object in the last call to DirectInputDevice8.SetActionMap. This is the value in the lAppData member of the DIACTION type associated with the object. Ignore this value if you are not using action mapping.

When the typestructure is used with the SendDeviceData method, this member must be zero.


DIEFFECT

Describes a force-feedback effect. It is passed to the DirectInputDevice8.CreateEffect and DirectInputEffect.SetParameters methods in order to set parameters for an effect. Existing parameters are retrieved in this type through the DirectInputEffect.GetParameters method.

Type DIEFFECT
    bUseEnvelope As Long
    conditionFlags As CONST_DICONDITIONFLAGS
    conditionX As DICONDITION
    conditionY As DICONDITION
    constantForce As DICONSTANTFORCE
    envelope As DIENVELOPE
    lDuration As Long
    lFlags As Long
    lGain As Long
    lSamplePeriod As Long
    lStartDelay As Long
    lTriggerButton As Long
    lTriggerRepeatInterval As Long
    periodicForce As DIPERIODICFORCE
    rampForce As DIRAMPFORCE
    x As Long
    y As Long
End Type

Members

bUseEnvelope
True if the envelope described in the envelope member is to be applied to the effect.
conditionFlags
Flags from the CONST_DICONDITIONFLAGS enumeration that determine use of the conditionX and conditionY members.
conditionX
DICONDITION type describing parameters of the condition on the x-axis. Ignored for other types of effects.
conditionY
DICONDITION type describing parameters of the condition on the y-axis. Ignored for other types of effects.
constantForce
DICONSTANTFORCE type describing parameters of a constant force. Ignored for other types of effects.
envelope
DIENVELOPE type describing parameters of an envelope to be applied to the effect. Valid only if the bUseEnvelope member is True.
lDuration
Duration of the effect, in microseconds. A value of -1 indicates infinite duration. If an envelope is applied to an effect of infinite duration, then the attack will be applied, followed by an infinite sustain.
lFlags
Zero or more members of the CONST_DIEFFFLAGS enumeration specifying how other members are to be interpreted.
lGain
The gain to be applied to the effect, in the range 0 to 10,000. The gain is a scaling factor applied to all magnitudes of the effect and its envelope.
lSamplePeriod
The period, in microseconds, at which the device samples the effect—in other words, the granularity of changes in force. A value of 0 indicates that the default playback sample rate should be used.

If the device is not capable of sampling the effect at the specified rate, it will choose the supported rate that is closest to the requested value.

Setting a custom sample period can be used for special effects. For example, playing a sine wave with an artificially large sample period results in a rougher texture.

lStartDelay
Time, in microseconds, the device should wait after a DirectInputEffect.Start call before playing the effect. If this value is 0, then effect playback begins immediately.
lTriggerButton
Offset value of the button that will trigger the effect. This should be one of the members of the CONST_DIJOYSTICKOFS enumeration, or DIEP_NOTRIGGER to indicate that the effect does not have a trigger button.
lTriggerRepeatInterval
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 -1 suppresses repetition.

Not all devices support trigger repeat.

periodicForce
DIPERIODICFORCE type describing parameters of a periodic effect. Ignored for other types of effects.
rampForce
DIRAMPFORCE type describing parameters of a ramp force. Ignored for other types of effects.
x
Direction of the effect. Normally, this is the amount by which the direction is rotated from north (usually the negative y-axis), in hundredths of degrees. Thus a value of 0 indicates a force pushing toward the user, a value of 9000 indicates a force pushing from the user's right, and so on. In this case, y should be 0.

If lFlags contains DIEFF_CARTESIAN, this is a Cartesian value describing the relative amount of force on the x-axis. For example, if x = -1 and y = 1, the direction of the force is from the southwest. For more information, see Effect Direction.

y
If lFlags contains DIEFF_CARTESIAN, this is a Cartesian value describing the relative amount of force on the y-axis. Otherwise it should be 0.


DIENVELOPE

Describes parameters for an envelope in the DIEFFECT type.

Type DIENVELOPE
    lAttackLevel As Long
    lAttackTime As Long
    lFadeLevel As Long
    lFadeTime As Long
End Type

Members

lAttackLevel
Amplitude for the start of the envelope, relative to the baseline (offset), in the range 0 to 10,000. If the effect's type-specific data does not specify a baseline, then the amplitude is relative to zero.
lAttackTime
The time, in microseconds, to reach the sustain level.
lFadeLevel
Amplitude for the end of the envelope, relative to the baseline, in the range 0 to 10,000. If the effect's type-specific data does not specify a baseline, then the amplitude is relative to zero.
lFadeTime
The time, in microseconds, to reach the fade level.


DIJOYSTATE

Describes the state of a joystick device. (This term includes other controllers such as game pads and steering wheels). This type is used with the DirectInputDevice8.GetDeviceStateJoystick method.

Type DIJOYSTATE
    Buttons(0 To 31) As Byte
    POV(0 To 3) As Long
    rx As Long
    ry As Long
    rz As Long
    slider(0 To 1) As Long
    x As Long
    y As Long
    z As Long
End Type

Members

Buttons
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.
POV
Direction controllers (such as point-of-view hats). The position is indicated in hundredths of degrees 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 will be -1, 0, 9,000, 18,000, or 27,000.
rx
X-axis rotation. If the joystick does not have this, the value is 0.
ry
Y-axis rotation. If the joystick does not have this axis, the value is 0.
rz
Z-axis rotation. If the joystick does not have this axis, the value is 0.
slider
Two additional axes whose semantics depend on the joystick. Use the DirectInputDevice8.GetObjectInfo method to obtain semantic information about these values.
x
X-axis, usually the left-right movement of a stick.
y
Y-axis, usually the forward-backward movement of a stick.
z
Z-axis, often the throttle control. If the joystick does not have this axis, the value is zero.

Remarks

You must prepare the device for joystick-style access by calling the DirectInputDevice8.SetCommonDataFormat method, passing the DIFORMAT_JOYSTICK format constant.

If an axis is in relative mode, then the appropriate member contains the change in position. If it is in absolute mode, then the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. You can determine whether an indicator is centered as follows:

Dim POVCentered as Boolean
POVCentered = MyDijoystate.POV(0) And &HFFFF

Note Under Microsoft® DirectX® 7, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8, those same sliders will be assigned to the slider array. This should be taken into account when porting applications to DirectX 8. Make any necessary alterations to ensure that slider data is retrieved from the slider array.

See Also

DIJOYSTATE2


DIJOYSTATE2

Describes the state of a joystick device with extended capabilities. This type is used with the DirectInputDevice8.GetDeviceStateJoystick2 method.

Most applications do not need to use this type, which is for highly specialized controllers including force-feedback devices. For standard game controllers, use the DIJOYSTATE type and obtain data by calling DirectInputDevice8.GetDeviceStateJoystick.

Type DIJOYSTATE2
    arx As Long
    ary As Long
    arz As Long
    aslider (0 to 1) As Long
    ax As Long
    ay As Long
    az As Long
    Buttons(0 To 127) As Byte
    frx As Long
    fry As Long
    frz As Long
    fslider(0 To 1) As Long
    fx As Long
    fy As Long
    fz As Long
    POV(0 To 3) As Long
    rx As Long
    ry As Long
    rz As Long
    slider(0 To 1) As Long
    vrx As Long
    vry As Long
    vrz As Long
    vslider(0 To 1) As Long
    vx As Long
    vy As Long
    vz As Long
    x As Long
    y As Long
    z As Long
End Type

Members

arx
X-axis angular acceleration.
ary
Y-axis angular acceleration.
arz
Z-axis angular acceleration.
aslider
Extra axis accelerations.
ax
X-axis acceleration.
ay
Y-axis acceleration.
az
Z-axis acceleration.
Buttons
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.
frx
X-axis torque.
fry
Y-axis torque.
frz
Z-axis torque.
fslider
Extra axis forces.
fx
X-axis force.
fy
Y-axis force.
fz
Z-axis force.
POV
Array of direction controllers, such as point-of-view hats. The position is indicated in hundredths of degrees 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 will be -1, 0, 9,000, 18,000, or 27,000.
rx
X-axis rotation. If the joystick does not have this, the value is 0.
ry
Y-axis rotation. If the joystick does not have this axis, the value is 0.
rz
Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is zero.
slider
Two additional axes whose semantics depend on the joystick. Use the DirectInputDevice8.GetObjectInfo method to obtain semantic information about these values.
vrx
X-axis angular velocity.
vry
Y-axis angular velocity.
vrz
Z-axis angular velocity.
vslider
Array of extra axis velocities.
vx
X-axis velocity.
vy
Y-axis velocity.
vz
Z-axis velocity.
x
Information about the joystick x-axis (usually the left-right movement of a stick).
y
Information about the joystick y-axis (usually the forward-backward movement of a stick).
z
Information about the joystick z-axis (often the throttle control). If the joystick does not have this axis, the value is zero.

Remarks

You must prepare the device for access to a joystick with extended capabilities by calling the DirectInputDevice8.SetCommonDataFormat method, passing the DIFORMAT_JOYSTICK2 data format variable.

If an axis is in relative mode, then the appropriate member contains the change in position. If it is in absolute mode, then the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. You can determine whether an indicator is centered as follows:

Dim POVCentered as Boolean
POVCentered = MyDijoystate2.POV(0) And &HFFFF

Note Under Microsoft® DirectX® 7, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8, those same sliders will be assigned to the slider array. This should be taken into account when porting applications to DirectX 8. Make any necessary alterations to ensure that slider data is retrieved from the slider array.


DIKEYBOARDSTATE

Describes the state of keyboard keys. This type is used with the DirectInputDevice8.GetDeviceStateKeyboard method.

Type DIKEYBOARDSTATE
    key(0 To 255) As Byte
End Type

Members

key
Array of key states. The array can be indexed by using members of the CONST_DIKEYFLAGS enumeration. For each key, the high bit is set if the key is down, and clear if the key is up or does not exist.

Remarks

The following example checks to see if the ESC key is being pressed:

Dim keyState as DIKEYBOARDSTATE
' diDevice is a valid DirectInputDevice8 object.

Call diDevice.GetDeviceStateKeyboard(keyState)
If (keyState.key(DIK_ESCAPE) And &H80) Then
    ' Key is down
End If


DIMOUSESTATE

Describes the state of a mouse device with up to four buttons. This type is used with the DirectInputDevice8.GetDeviceStateMouse method.

Type DIMOUSESTATE
    Buttons(0 To 3) As Byte
    lX As Long
    lY As Long
    lZ As Long
End Type

Members

Buttons
Array of button states. The high-order bit of a byte is set if the corresponding button is down.
lX
X-axis.
lY
Y-axis.
lZ
Z-axis, typically a wheel. If the mouse does not have a z-axis, then the value is 0.

Remarks

Immediate data is returned in this type from a device that has been prepared by passing the DIFORMAT_MOUSE constant to the DirectInputDevice8.SetCommonDataFormat method.

If an axis is in relative mode, then the appropriate member contains the change in position since the last call to this method. If the axis is in absolute mode, then the member contains the accumulated relative motion in relation to an arbitrary start point. The absolute axis position is not meaningful except in comparison with other absolute axis positions.

See Also

DIMOUSESTATE2


DIMOUSESTATE2

Describes the state of a mouse device with up to 8 buttons. This type is used with the DirectInputDevice8.GetDeviceStateMouse2 method.

Type DIMOUSESTATE2
    Buttons(0 To 7) As Byte
    lX As Long
    lY As Long
    lZ As Long
End Type

Members

Buttons
Array of button states. The high-order bit of a byte is set if the corresponding button is down.
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.

Remarks

Immediate data is returned in this type from a device that has been prepared by passing the DIFORMAT_MOUSE2 constant to the DirectInputDevice8.SetCommonDataFormat method.

If an axis is in relative mode, then the appropriate member contains the change in position since the last call to this method. If the axis is in absolute mode, then the member contains the accumulated relative motion in relation to an arbitrary start point. The absolute axis position is not meaningful except in comparison with other absolute axis positions.

See Also

DIMOUSESTATE


DIOBJECTDATAFORMAT

Describes a device object's data format for use with the DirectInputDevice8.SetDataFormat method.

Type DIOBJECTDATAFORMAT {
    lFlags As CONST_DIDEVICEOBJINSTANCEFLAGS
    lOfs As Long
    lType As CONST_DIDFTFLAGS
    strGuid As String
End Type

Members

lFlags
Zero or more of the following values from the CONST_DIDEVICEOBJINSTANCEFLAGS enumeration.
DIDOI_ASPECTACCEL
The object selected by DirectInputDevice8.SetDataFormat must report acceleration information.
DIDOI_ASPECTFORCE
The object selected by DirectInputDevice8.SetDataFormat must report force information.
DIDOI_ASPECTPOSITION
The object selected by DirectInputDevice8.SetDataFormat must report position information.
DIDOI_ASPECTVELOCITY
The object selected by DirectInputDevice8.SetDataFormat must report velocity information.
lOfs
Byte offset within the data packet where the data for the input source will be stored. This value must be a multiple of four for Long size data, such as axes. It can be byte-aligned for buttons.
lType
Device type that describes the object. It is a combination of values from the CONST_DIDFTFLAGS enumeration describing the object type (axis, button, and so forth) and containing the object-instance number in the middle 16 bits.
strGuid
Unique identifier for the type of input source. An empty string indicates that any type of object is permissible.

The following strings can be used in place of actual GUID strings to identify the type of device object:

GUID_XAxis
GUID_YAxis
GUID_ZAxis
GUID_RxAxis
GUID_RyAxis
GUID_RzAxis
GUID_Slider
GUID_Button
GUID_Key
GUID_POV


DIPERIODICFORCE

Describes parameters for a periodic force in the DIEFFECT type.

Type DIPERIODICFORCE
    lOffset As Long
    lMagnitude As Long
    lPeriod As Long
    lPhase As Long
End Type

Members

lOffset
The offset of the effect. The range of forces generated by the effect will be lOffset - lMagnitude to lOffset + lMagnitude. The value of the lOffset member is also the baseline for any envelope that is applied to the effect.
lMagnitude
The magnitude of the effect, in the range 0 to 10,000. If an envelope is applied to this effect, then the value represents the magnitude of the sustain. If no envelope is applied, then the value represents the amplitude of the entire effect.
lPeriod
The period of the effect, in microseconds.
lPhase
The position in the cycle of the periodic effect at which playback begins, in the range 0 to 35,999. See Remarks.

Remarks

A device driver might not provide support for all values in the lPhase member. In this case the value will be rounded off to the nearest supported value.


DIPROPCPOINTS

Sets calibration points for the current instance.

Type DIPROPCPOINTS
    lObj As Long
    lHow As Long
    dwCPointsNum As Long
    cp(MAXCPOINTSNUM) As CPOINT
End Type

Members

lObj
If the lHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is set or retrieved.

If the lHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is set or retrieved.

If the lHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object is 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.

lHow
Specifies how the lObj member should be interpreted. See the description of the lObj member for details.
dwCPointsNum
Number of stored calibration points. You can use no more than 8 calibration points.
cp(MAXCPOINTSNUM)
Array of calibration points. See CPOINT for more information.


DIPROPGUIDANDPATH

Describes properties whose values represent a GUID and a path. Used with the DirectInputDevice8.GetProperty method.

Type DIPROPGUIDANDPATH
    GUID As String
    lHow As Long
    lObj As Long
    Path As String
End Type

Members

GUID
String that receives the GUID.
lHow
Value that specifies how the lObj parameter should be interpreted. This value may be one of the members of the CONST_DIPHFLAGS enumeration.

If the property pertains to the entire device, lHow should be DIPH_DEVICE.

lObj
Object for which the property is to be accessed.

If the lHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved. This value can be retrieved for the object by using the DirectInputDeviceObjectInstance.GetType method.

If the lHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. This value can be obtained by using the DirectInputDeviceObjectInstance.GetOfs method.

Path
String that receives the path.


DIPROPLONG

Contains property information that is set on or retrieved from the input device by using the DirectInputDevice8.SetProperty and DirectInputDevice8.GetProperty methods, where the property is a single value.

Type DIPROPLONG
    lData As Long
    lHow As Long
    lObj As Long
End Type

Members

lData
The property-specific value being set or retrieved.
lHow
Value specifying how the lObj parameter should be interpreted. This value may be one of the members of the CONST_DIPHFLAGS enumeration.

If lObj is DIPROP_AXISMODE or DIPROP_BUFFERSIZE, lHow should be DIPH_DEVICE, because these properties cannot be set for an individual object.

lObj
Object for which the property is to be accessed.

If the lHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved. This value can be retrieved for the object by using the DirectInputDeviceObjectInstance.GetType method.

If the lHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. This value can be obtained by using the DirectInputDeviceObjectInstance.GetOfs method.

If lHow is DIPH_DEVICE, this value should be 0.

Remarks

All members must be initialized with the proper values before the type is passed to the SetProperty method. All members except lData must be initialized with the proper values before the type is passed to GetProperty.

See Also

DIPROPRANGE


DIPROPPOINTER

Used in setting and retrieving data values associated with an application-specific action associated with a device object in an action map.

Type DIPROPPOINTER
    lObj As Long
    lHow As Long
    uData As Long
End Type

Members

lObj
If the lHow member is DIPH_DEVICE, this member must be 0.

If the lHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is set or retrieved.

If the lHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is set or retrieved.

If the lHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object is identified by the HID usage page and usage values in packed form.

lHow
Specifies how the lObj member is interpreted. See the description of the lObj member for details.
uData
Application-defined value which represents the lAppData value (from an action map) that is associated with a device control.


DIPROPRANGE

Contains property information that is set on or retrieved from the input device by using the DirectInputDevice8.SetProperty and DirectInputDevice8.GetProperty methods, where the property is a range of values.

Type DIPROPRANGE
    lHow As Long
    lMax As Long
    lMin As Long
    lObj As Long
End Type

Members

lHow
Value specifying how the lObj member should be interpreted. This value may be one of the members of the CONST_DIPHFLAGS enumeration.
lMax
Upper limit of the range. If the range of the device is unrestricted, this value will be DIPROPRANGE_NOMAX (from the CONST_DINPUT enumeration) when the DirectInputDevice8.GetProperty method returns.
lMin
Lower limit of the range. If the range of the device is unrestricted, this value will be DIPROPRANGE_NOMIN (from the CONST_DINPUT enumeration)when the DirectInput8Device.GetProperty method returns.
lObj
Object for which the property is to be accessed.

If the lHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved. This value can be retrieved for the object by using the DirectInputDeviceObjectInstance.GetType method.

If the lHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. This value can be obtained by using the DirectInputDeviceObjectInstance.GetOfs method.

If lHow is DIPH_DEVICE, this value should be 0.

See Also

DIPROPLONG


DIPROPSTRING

Describes string properties. Used with the DirectInputDevice8.GetProperty and DirectInputDevice8.SetProperty methods.

Type DIPROPSTRING
    lHow As Long
    lObj As Long
    PropString As String
End Type

Members

lHow
How the lObj member should be interpreted.
lObj
Identifier of the object whose property is being retrieved or set.
PropString
String that specifies or receives the property.


DIRAMPFORCE

Describes parameters for a ramp force in the DIEFFECT type.

Type DIRAMPFORCE
    lRangeEnd As Long
    lRangeStart As Long
End Type

Members

lRangeEnd
The magnitude at the end of the effect, in the range -10,000 to +10,000.
lRangeStart
The magnitude at the start of the effect, in the range -10,000 to +10,000.

Remarks

The duration of a ramp force effect must be finite.


Enumerations

Microsoft® DirectInput® uses enumerations to group constants in order to take advantage of the statement completion feature of Microsoft Visual Basic®. The enumerations used in DirectInput are as follows:

  • CONST_DI8DEVICESUBTYPE
  • CONST_DI8DEVICETYPE
  • CONST_DIAFLAGS
  • CONST_DIAHFLAGS
  • CONST_DICDFLAGS
  • CONST_DICOMMONDATAFORMATS
  • CONST_DICONDITIONFLAGS
  • CONST_DIDALFLAGS
  • CONST_DIDATAFORMATFLAGS
  • CONST_DIDBAMFLAGS
  • CONST_DIDEVCAPSFLAGS
  • CONST_DIDEVICEOBJINSTANCEFLAGS
  • CONST_DIDFTFLAGS
  • CONST_DIDGDDFLAGS
  • CONST_DIDIFTFLAGS
  • CONST_DIDSAMFLAGS
  • CONST_DIEDBSFLFLAGS
  • CONST_DIEFFFLAGS
  • CONST_DIEFTFLAGS
  • CONST_DIEGESFLAGS
  • CONST_DIENUMDEVICESFLAGS
  • CONST_DIEPFLAGS
  • CONST_DIESFLAGS
  • CONST_DIFEFFLAGS
  • CONST_DIGENRE
  • CONST_DIGFFSFLAGS
  • CONST_DIJOYSTICKOFS
  • CONST_DIKEYBOARDFLAGS
  • CONST_DIKEYFLAGS
  • CONST_DIMAPFLAGS
  • CONST_DIMOUSEFLAGS
  • CONST_DIMOUSEOFS
  • CONST_DINPUT
  • CONST_DINPUTERR
  • CONST_DIPHFLAGS
  • CONST_DISCLFLAGS
  • CONST_DISDDFLAGS
  • CONST_DISFFCFLAGS
  • CONST_DIVOICEFLAGS


CONST_DI8DEVICESUBTYPE

Used to identify device subtypes. A packed value representing the device type and subtype is returned by the DirectInputDeviceInstance8.GetDevType method and in the lDevType member of the DIDEVCAPS type returned by DirectInputDevice8.GetCapabilities.

Enum CONST_DI8DEVICESUBTYPE
    DI8DEVTYPE_LIMITEDGAMESUBTYPE       =      256 (&H100)
    DI8DEVTYPE1STPERSON_LIMITED         =      256 (&H100)
    DI8DEVTYPE1STPERSON_SHOOTER         =     1024 (&H400)
    DI8DEVTYPE1STPERSON_SIXDOF          =      768 (&H300)
    DI8DEVTYPE1STPERSON_UNKNOWN         =      512 (&H200)
    DI8DEVTYPEDEVICECTRL_COMMSSELECTION =      768 (&H300)
    DI8DEVTYPEDEVICECTRL_HARDWIRED      =     1024 (&H400)
    DI8DEVTYPEDEVICECTRL_UNKNOWN        =      512 (&H200)
    DI8DEVTYPEDRIVING_COMBINEDPEDALS    =      512 (&H200)
    DI8DEVTYPEDRIVING_DUALPEDALS        =      768 (&H300)
    DI8DEVTYPEDRIVING_HANDHELD          =     1280 (&H500)
    DI8DEVTYPEDRIVING_LIMITED           =      256 (&H100)
    DI8DEVTYPEDRIVING_THREEPEDALS       =     1024 (&H400)
    DI8DEVTYPEFLIGHT_LIMITED            =      256 (&H100)
    DI8DEVTYPEFLIGHT_RC                 =     1024 (&H400)
    DI8DEVTYPEFLIGHT_STICK              =      512 (&H200)
    DI8DEVTYPEFLIGHT_YOKE               =      768 (&H300)
    DI8DEVTYPEGAMEPAD_LIMITED           =      256 (&H100)
    DI8DEVTYPEGAMEPAD_STANDARD          =      512 (&H200)
    DI8DEVTYPEGAMEPAD_TILT              =      768 (&H300)
    DI8DEVTYPEJOYSTICK_LIMITED          =      256 (&H100)
    DI8DEVTYPEJOYSTICK_STANDARD         =      512 (&H200)
    DI8DEVTYPEKEYBOARD_J3100            =     3072 (&HC00)
    DI8DEVTYPEKEYBOARD_JAPAN106         =     2560 (&HA00)
    DI8DEVTYPEKEYBOARD_JAPANAX          =     2816 (&HB00)
    DI8DEVTYPEKEYBOARD_NEC98            =     1792 (&H700)
    DI8DEVTYPEKEYBOARD_NEC98106         =     2304 (&H900)
    DI8DEVTYPEKEYBOARD_NEC98LAPTOP      =     2048 (&H800)
    DI8DEVTYPEKEYBOARD_NOKIA1050        =     1280 (&H500)
    DI8DEVTYPEKEYBOARD_NOKIA9140        =     1536 (&H600)
    DI8DEVTYPEKEYBOARD_OLIVETTI         =      512 (&H200)
    DI8DEVTYPEKEYBOARD_PCAT             =      768 (&H300)
    DI8DEVTYPEKEYBOARD_PCENH            =     1024 (&H400)
    DI8DEVTYPEKEYBOARD_PCXT             =      256 (&H100)
    DI8DEVTYPEKEYBOARD_UNKNOWN          =        0 (&H000)
    DI8DEVTYPEMOUSE_ABSOLUTE            =     1536 (&H600)
    DI8DEVTYPEMOUSE_FINGERSTICK         =      768 (&H300)
    DI8DEVTYPEMOUSE_TOUCHPAD            =     1024 (&H400)
    DI8DEVTYPEMOUSE_TRACKBALL           =     1280 (&H500)
    DI8DEVTYPEMOUSE_TRADITIONAL         =      512 (&H200)
    DI8DEVTYPEMOUSE_UNKNOWN             =      256 (&H100)
    DI8DEVTYPEREMOTE_UNKNOWN            =      512 (&H200)
    DI8DEVTYPESCREENPTR_LIGHTGUN        =      768 (&H300)
    DI8DEVTYPESCREENPTR_LIGHTPEN        =     1024 (&H400)
    DI8DEVTYPESCREENPTR_TOUCH           =     1280 (&H500)
    DI8DEVTYPESCREENPTR_UNKNOWN         =      512 (&H200)
    DI8DEVTYPESUPPLEMENTAL_2NDHANDCONTROLLER = 768 (&H300)
    DI8DEVTYPESUPPLEMENTAL_COMBINEDPEDALS  =  2560 (&HA00)
    DI8DEVTYPESUPPLEMENTAL_DUALPEDALS      =  2816 (&HB00)
    DI8DEVTYPESUPPLEMENTAL_HANDTRACKER     =  1280 (&H500)
    DI8DEVTYPESUPPLEMENTAL_HEADTRACKER     =  1024 (&H400)
    DI8DEVTYPESUPPLEMENTAL_RUDDERPEDALS    =  3328 (&HD00)
    DI8DEVTYPESUPPLEMENTAL_SHIFTER         =  1792 (&H700)
    DI8DEVTYPESUPPLEMENTAL_SHIFTSTICKGATE  =  1536 (&H600)
    DI8DEVTYPESUPPLEMENTAL_SPLITTHROTTLE   =  2304 (&H900)
    DI8DEVTYPESUPPLEMENTAL_THREEPEDALS     =  3072 (&HC00)
    DI8DEVTYPESUPPLEMENTAL_THROTTLE        =  2048 (&H800)
    DI8DEVTYPESUPPLEMENTAL_UNKNOWN         =   512 (&H200)
    DIDEVTYPE_HID                          = 65536 (&H10000)
End Enum

Constants

DI8DEVTYPEJOYSTICK_ENHANCED
Joystick that has more axes or point-of-view controllers than a standard joystick.
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.
DI8DEVTYPEDEVICECTRL_COMMSSELECTION
Control used to make communications selections.
DI8DEVTYPEDEVICECTRL_HARDWIRED
Device that must use its default configuration and cannot be remapped.
DI8DEVTYPEDEVICECTRL_UNKNOWN
Unknown subtype.
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.
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.
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.
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.
DI8DEVTYPEKEYBOARD_J3100
Japanese J3100 keyboard.
DI8DEVTYPEKEYBOARD_JAPAN106
Japanese 106-key keyboard.
DI8DEVTYPEKEYBOARD_JAPANAX
Japanese AX keyboard.
DI8DEVTYPEKEYBOARD_NEC98
Japanese NEC PC98 keyboard.
DI8DEVTYPEKEYBOARD_NEC98106
Japanese NEC PC98 106-key keyboard.
DI8DEVTYPEKEYBOARD_NEC98LAPTOP
Japanese NEC PC98 laptop keyboard.
DI8DEVTYPEKEYBOARD_NOKIA1050
Nokia 1050 keyboard.
DI8DEVTYPEKEYBOARD_NOKIA9140
Nokia 9140 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_PCXT
IBM PC/XT 83-key keyboard.
DI8DEVTYPEKEYBOARD_UNKNOWN
Unknown subtype.
DI8DEVTYPEMOUSE_ABSOLUTE
Mouse that returns absolute axis data.
DI8DEVTYPEMOUSE_FINGERSTICK
Fingerstick.
DI8DEVTYPEMOUSE_TOUCHPAD
Touchpad.
DI8DEVTYPEMOUSE_TRACKBALL
Trackball.
DI8DEVTYPEMOUSE_TRADITIONAL
Traditional mouse.
DI8DEVTYPEMOUSE_UNKNOWN
Unknown subtype.
DI8DEVTYPEREMOTE_UNKNOWN
Remote-control device. This is the only defined remote-control device subtype.
DI8DEVTYPESCREENPTR_LIGHTGUN
Light gun.
DI8DEVTYPESCREENPTR_LIGHTPEN
Light pen.
DI8DEVTYPESCREENPTR_TOUCH
Touch screen.
DI8DEVTYPESCREENPTR_UNKNOWN
Unknown subtype.
DI8DEVTYPESUPPLEMENTAL_2NDHANDCONTROLLER
Secondary hand-held 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.
DIDEVTYPE_HID
Human Interface Device (HID).

See Also

CONST_DI8DEVICETYPE


CONST_DI8DEVICETYPE

Used to identify input device classes and types. One of these constants is passed as the deviceType parameter to the DirectInput8.GetDIDevices method to specify the class or type to enumerate. A packed value representing the device type and subtype is returned by the DirectInputDeviceInstance8.GetDevType method and in the lDevType member of the DIDEVCAPS type returned by DirectInputDevice8.GetCapabilities.

Enum CONST_DI8DEVICETYPE
    DI8DEVCLASS_ALL          =  0
    DI8DEVCLASS_DEVICE       =  1
    DI8DEVCLASS_GAMECTRL     =  4
    DI8DEVCLASS_KEYBOARD     =  3
    DI8DEVCLASS_POINTER      =  2
    DI8DEVTYPE_1STPERSON     = 24 (&H18)
    DI8DEVTYPE_DEVICE        = 17 (&H11)
    DI8DEVTYPE_DEVICECTRL    = 25 (&H19)
    DI8DEVTYPE_DRIVING       = 22 (&H16)
    DI8DEVTYPE_FLIGHT        = 23 (&H17)
    DI8DEVTYPE_GAMEPAD       = 21 (&H15)
    DI8DEVTYPE_JOYSTICK      = 20 (&H14)
    DI8DEVTYPE_KEYBOARD      = 19 (&H13)
    DI8DEVTYPE_MOUSE         = 18 (&H12)
    DI8DEVTYPE_REMOTE        = 27 (&H1B)
    DI8DEVTYPE_SCREENPOINTER = 26 (&H1A)
    DI8DEVTYPE_SUPPLEMENTAL  = 28 (&H1C)
End Enum

Constants

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.
DI8DEVTYPE_1STPERSON
First-person action game device.
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.
DI8DEVTYPE_DRIVING
Device for steering.
DI8DEVTYPE_FLIGHT
Controller for flight simulation.
DI8DEVTYPE_GAMEPAD
Gamepad.
DI8DEVTYPE_JOYSTICK
Joystick.
DI8DEVTYPE_KEYBOARD
Keyboard or keyboard-like device.
DI8DEVTYPE_MOUSE
A mouse or mouse-like device (such as a trackball).
DI8DEVTYPE_REMOTE
Remote-control device.
DI8DEVTYPE_SCREENPOINTER
Screen pointer.
DI8DEVTYPE_SUPPLEMENTAL
Specialized device with functionality unsuitable for the main control of an application, such as pedals used with a wheel.

See Also

CONST_DI8DEVICESUBTYPE


CONST_DIAFLAGS

Used in lFlags member of the DIACTION type to specify how actions are to be mapped.

Enum CONST_DIAFLAGS
    DIA_APPMAPPED     = 2
    DIA_APPNOMAP      = 4
    DIA_FORCEFEEDBACK = 1
    DIA_NORANGE       = 8
End Enum

Constants

DIA_APPMAPPED
The lObjID member of the DIACTION type is valid, and DirectInputDevice8.BuildActionMap should 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.


CONST_DIAHFLAGS

Used in lHow member of the DIACTION type to report how actions were mapped.

Enum CONST_DIAHFLAGS
    DIAH_APPREQUESTED =           2
    DIAH_DEFAULT      =          32 (&H20)
    DIAH_ERROR        = -2147483648 (&H80000000)
    DIAH_HWAPP        =           4
    DIAH_HWDEFAULT    =           8
    DIAH_UNMAPPED     =           0
    DIAH_USERCONFIG   =           1
End Enum

Constants

DIAH_APPREQUESTED
The mapping was configured by the application, which specified the device (guidInstance) and device object (lObjID) when calling DirectInputDevice8.BuildActionMap.
DIAH_DEFAULT
The mapping was determined by Microsoft® 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.


CONST_DICDFLAGS

Used in the flags parameter of DirectInput8.ConfigureDevices to specify the mode for the property sheet.

Enum CONST_DICDFLAGS
    DICD_DEFAULT = 0
    DICD_EDIT    = 1
End Enum

Constants

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 DirectInput8.GetDevicesBySemantics.


CONST_DICOMMONDATAFORMATS

Specify the data format in the format parameter of the DirectInputDevice8.SetCommonDataFormat method.

Enum CONST_DICOMMONDATAFORMATS
    DIFORMAT_JOYSTICK  =  3
    DIFORMAT_JOYSTICK2 =  4
    DIFORMAT_KEYBOARD  =  1
    DIFORMAT_MOUSE     =  2
    DIFORMAT_MOUSE2    =  5
End Enum

Constants

DIFORMAT_JOYSTICK
Joystick whose state data can be received in a DIJOYSTATE type.
DIFORMAT_JOYSTICK2
Joystick with extended capabilities whose state data can be received in a DIJOYSTATE2 type.
DIFORMAT_KEYBOARD
Keyboard whose state data can be received in a DIKEYBOARDSTATE type.
DIFORMAT_MOUSE
Mouse whose state data can be received in a DIMOUSESTATE type.
DIFORMAT_MOUSE2
Mouse whose state data can be received in a DIMOUSESTATE2 type.


CONST_DICONDITIONFLAGS

Used in the conditionFlags member of the DIEFFECT type to set the axes and direction of a force-feedback effect.

Enum CONST_DICONDITIONFLAGS
    DICONDITION_USE_BOTH_AXES = 1
    DICONDITION_USE_DIRECTION = 2
End Enum

Constants

DICONDITION_USE_BOTH_AXES
Use data from both the conditionX and conditionY members of the DIEFFECT type
DICONDITION_USE_DIRECTION
Use data from only the conditionX member of the DIEFFECT type.


CONST_DIDALFLAGS

Used to specify text alignment in the action-mapping property sheet.

Enum CONST_DIDALFLAGS
    DIDAL_BOTTOMALIGNED = 8
    DIDAL_CENTERED      = 0
    DIDAL_LEFTALIGNED   = 1
    DIDAL_MIDDLE        = 0
    DIDAL_RIGHTALIGNED  = 2
    DIDAL_TOPALIGNED    = 4
End Enum

Constants

DIDAL_BOTTOMALIGNED
The text is aligned on the bottom border.
DIDAL_CENTERED
The text is horizontally centered.
DIDAL_LEFTALIGNED
The text is aligned on the left border.
DIDAL_MIDDLE
The text is vertically centered.
DIDAL_RIGHTALIGNED
The text is aligned on the right border.
DIDAL_TOPALIGNED
The text is aligned on the top border.


CONST_DIDATAFORMATFLAGS

Used in the lFlags member of the DIDATAFORMAT type to describe additional attributes of the data format.

Enum CONST_DIDATAFORMATFLAGS
    DIDF_ABSAXIS = 1
    DIDF_RELAXIS = 2
End Enum

Constants

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 DirectInputDevice8.SetProperty method. This may not 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 DirectInputDevice8.SetProperty method. This may not be combined with the DIDF_ABSAXIS flag.


CONST_DIDBAMFLAGS

Used in the DirectInputDevice8.BuildActionMap method.

Enum CONST_DIDBAMFLAGS
    DIDBAM_DEFAULT    = 0
    DIDBAM_HWDEFAULTS = 4
    DIDBAM_INITIALIZE = 2
    DIDBAM_PRESERVE   = 1
End Enum

Constants

DIDBAM_DEFAULT
Overwrite all mappings except application-specified mappings; that is, mappings that have the DIA_APPMAPPED flag in the DIACTION type.
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 Microsoft® DirectInput®.
DIDBAM_INITIALIZE
Overwrite all mappings, including application-specified mappings.
DIDBAM_PRESERVE
Preserve current mappings assigned for this device or any other configured device.


CONST_DIDEVCAPSFLAGS

Used in the lFlags member of the DIDEVCAPS type to describe the Microsoft® DirectInput® device.

Enum CONST_DIDEVCAPSFLAGS
    DIDC_ALIAS              =  65536 (&H10000)
    DIDC_ATTACHED           =      1
    DIDC_DEADBAND           =  16384 (&H4000)
    DIDC_EMULATED           =      4
    DIDC_FFATTACK           =    512 (&H200)
    DIDC_FFFADE             =   1024 (&H400)
    DIDC_FORCEFEEDBACK      =    256 (&H100)
    DIDC_PHANTOM            = 131072 (&H20000)
    DIDC_POLLEDDATAFORMAT   =      8
    DIDC_POLLEDDEVICE       =      2
    DIDC_POSNEGCOEFFICIENTS =   4096 (&H1000)
    DIDC_POSNEGSATURATION   =   8192 (&H2000)
    DIDC_SATURATION         =   2048 (&H800)
End Enum

Constants

DIDC_ALIAS
The device is a duplicate of another DirectInput device. Alias devices are by default not enumerated by DirectInput8.GetDIDevices.
DIDC_ATTACHED
The device is physically attached.
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 (HID)—or by some other ring-3 means. If it is not set, the data is coming directly from a kernel mode driver.
DIDC_FFATTACK
The force-feedback system supports the attack parameter for at least one effect. If the device does not support attack then the lAttackLevel and lAttackTime members of the DIENVELOPE type will be ignored by the device.
DIDC_FFFADE
The force-feedback system supports the fade parameter for at least one effect. If the device does not support fade then the lFadeLevel and lFadeTime members of the DIENVELOPE type will be ignored by the device.
DIDC_FORCEFEEDBACK
The device supports force feedback.
DIDC_PHANTOM
The device does not exist. It is a placeholder for a device that might exist later. Phantom devices are by default not enumerated by DirectInput8.GetDIDevices.
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 DirectInputDevice8.Poll method in order 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 DirectInputDevice8.Poll method in order to obtain data. HID devices may contain a mixture of polled and non-polled 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, then the negative coefficient in the DICONDITION type will be ignored.
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, then the negative saturation in the DICONDITION type will be ignored.
DIDC_SATURATION
The force-feedback system supports the saturation of condition effects for at least one condition. If the device does not support saturation, then the force generated by a condition is limited only by the maximum force that the device can generate.

See Also

CONST_DIEFTFLAGS


CONST_DIDEVICEOBJINSTANCEFLAGS

Used to describe device object capabilities. Members of this enumeration are returned by the DirectInputDeviceObjectInstance.GetFlags method. They are also present in the DIOBJECTDATAFORMAT type passed to the DirectInputDevice8.SetDataFormat method

Enum CONST_DIDEVICEOBJINSTANCEFLAGS
    DIDOI_ASPECTACCEL     =   768 (&H300)
    DIDOI_ASPECTFORCE     =  1024 (&H400)
    DIDOI_ASPECTMASK      =  3840 (&HF00)
    DIDOI_ASPECTPOSITION  =   256 (&H100)
    DIDOI_ASPECTVELOCITY  =   512 (&H200)
    DIDOI_FFACTUATOR      =     1
    DIDOI_FFEFFECTTRIGGER =     2
    DIDOI_GUIDISUSAGE      =  4096 (&H1000)
    DIDOI_POLLED          = 32768 (&H8000)
End Enum

Constants

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
DIOBJECTDATAFORMAT.strGuid contains Human Interface Device (HID) usage and usage page in packed form.
DIDOI_POLLED
The object does not return data until the DirectInputDevice8.Poll method is called.


CONST_DIDFTFLAGS

Used in the flags parameter of the DirectInputDevice8.GetDeviceObjectsEnum method to specify the type of device object to enumerate. These values are also returned by the DirectInputDeviceObjectInstance.GetFlags method to describe capabilities of the device object.

Enum CONST_DIDFTFLAGS
    DIDFT_ABSAXIS         =         2
    DIDFT_ALL             =         0
    DIDFT_ANYINSTANCE     =  16776960 (&HFFFF00)
    DIDFT_AXIS            =         3
    DIDFT_BUTTON          =        12
    DIDFT_COLLECTION      =        64 (&H40)
    DIDFT_FFACTUATOR      =  16777216 (&H1000000)
    DIDFT_FFEFFECTTRIGGER =  33554432 (&H2000000)
    DIDFT_INSTANCEMASK    =  16776960 (&HFFFF00)
    DIDFT_NOCOLLECTION    =  16776960 (&HFFFF00)
    DIDFT_NODATA          =       128 (&H80)
    DIDFT_OUTPUT          = 268435456 (&H10000000)
    DIDFT_POV             =        16 (&H10)
    DIDFT_PSHBUTTON       =         4
    DIDFT_RELAXIS         =         1
    DIDFT_TGLBUTTON       =         8
End Enum

Constants

DIDFT_ABSAXIS
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_ANYINSTANCE
Use the first instance enumerated that meets other criteria such as DIDFT_AXIS or DIDFT_BUTTON.
DIDFT_AXIS
Axis, either absolute or relative.
DIDFT_BUTTON
Push button or a toggle button.
DIDFT_COLLECTION
Human Interface Device (HID) link collection. HID link collections do not generate data of their own.
DIDFT_FFACTUATOR
Object that contains a force-feedback actuator. In other words, forces can be applied to this object.
DIDFT_FFEFFECTTRIGGER
Object that can be used to trigger force-feedback effects.
DIDFT_INSTANCEMASK
Same as DIDFT_ANYINSTANCE.
DIDFT_NOCOLLECTION
Object that does not belong to any HID link collection; in other words, an object for which DirectInputDeviceObjectInstance.GetCollectionNumber returns 0.
DIDFT_NODATA
Object that does not generate data.
DIDFT_OUTPUT
Object to which data can be sent by using the DirectInputDevice8.SendDeviceData method.
DIDFT_POV
Point-of-view controller.
DIDFT_PSHBUTTON
Push button. A push button is reported as down when the user presses it and as up when the user releases it.
DIDFT_RELAXIS
Relative axis.
DIDFT_TGLBUTTON
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.


CONST_DIDGDDFLAGS

Used in the flags parameter of the DirectInputDevice8.GetDeviceData method to control the manner in which data is obtained.

Enum CONST_DIDGDDFLAGS
    DIGDD_DEFAULT = 0
    DIGDD_PEEK    = 1
End Enum

Constants

DIGDD_DEFAULT
Remove retrieved items from the buffer.
DIGDD_PEEK
Do not remove retrieved items from the buffer. A subsequent GetDeviceData call will read the same data.


CONST_DIDIFTFLAGS

Used in the flags member of the DIDEVICEIMAGEINFO type to specify the type of the file.

Enum CONST_DIDIFTFLAGS
    DIDIFT_CONFIGURATION =     1
    DIDIFT_OVERLAY       =     2
End Enum

Constants

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 is an overlay for a configuration image. The OverlayOffset, OverlayRect, ObjID, CalloutLine, CalloutRect, and TextAlign members are valid and contain data used to display the overlay and callout information for a single control on the device.


CONST_DIDSAMFLAGS

Used in the DirectInputDevice8.SetActionMap method.

Enum CONST_DIDSAMFLAGS
    DIDSAM_DEFAULT   = 0
    DIDSAM_NOUSER    = 1
    DIDSAM_FORCESAVE = 2
End Enum

Constants

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.


CONST_DIEDBSFLFLAGS

Used in the DirectInput8.GetDevicesBySemantics method to specify the scope of the enumeration.

Enum CONST_DIEDBSFLFLAGS
    DIEDBSFL_ATTACHEDONLY       =     0
    DIEDBSFL_AVAILABLEDEVICES   =  4096 (&H1000)
    DIEDBSFL_FORCEFEEDBACK      =   256 (&H100)
    DIEDBSFL_MULTIMICEKEYBOARDS =  8192 (&H2000)
    DIEDBSFL_NONGAMINGDEVICES   = 16384 (&H4000)
    DIEDBSFL_THISUSER           =    16 (&H10)
    DIEDBSFL_VALID              =  4368 (&H1110)
End Enum

Constants

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 str1, and all unowned devices, are enumerated.
DIEDBSFL_VALID
Not used by applications.


CONST_DIEFFFLAGS

Used in the lFlags member of the DIEFFECT type.

Enum CONST_DIEFFFLAGS
    DIEFF_CARTESIAN     = 16 (&H10)
    DIEFF_OBJECTOFFSETS =  2
    DIEFF_POLAR         = 32 (&H20)
End Enum

Constants

DIEFF_CARTESIAN
The direction of the effect is given in Cartesian coordinates. DIEFFECT.x and DIEFFECT.y contain valid values.
DIEFF_OBJECTOFFSETS
The value of the lTriggerButton member of DIEFFECT is the offset of the button in the data structure for the device.
DIEFF_POLAR
The direction of the effect is given in polar coordinates. DIEFFECT.x contains a valid value.

Remarks

The default behavior of DirectInputDevice8.CreateEffect and DirectInputDevice8.CreateCustomEffect is to create the effect as if DIEFFECT.lFlags contained (DIEFF_OBJECTOFFSETS Or DIEFF_POLAR). In other words, it is not necessary to specify these flags.


CONST_DIEFTFLAGS

Used to describe types and capabilities of force-feedback effects. These flags restrict effect enumeration in the DirectInputDevice8.GetEffectsEnum method to one or more of the primary types. They are also returned by the DirectInputEnumEffects.GetType method.

Enum CONST_DIEFTFLAGS
    DIEFT_ALL                =     0
    DIEFT_CONDITION          =     4
    DIEFT_CONSTANTFORCE      =     1
    DIEFT_CUSTOMFORCE        =     5
    DIEFT_DEADBAND           = 16384 (&H4000)
    DIEFT_FFATTACK           =   512 (&H200)
    DIEFT_FFFADE             =  1024 (&H400)
    DIEFT_HARDWARE           =   255 (&HFF)
    DIEFT_PERIODIC           =     3
    DIEFT_POSNEGCOEFFICIENTS =  4096 (&H1000)
    DIEFT_POSNEGSATURATION   =  8192 (&H2000)
    DIEFT_RAMPFORCE          =     2
    DIEFT_SATURATION         =  2048 (&H800)
End Enum

Constants

DIEFT_ALL
All effects are to be enumerated.
DIEFT_CONDITION
The effect is a condition, or conditions are to be enumerated.
DIEFT_CONSTANTFORCE
The effect is a constant force, or constant forces are to be enumerated.
DIEFT_CUSTOMFORCE
The effect is a custom force, or custom forces are to be enumerated.
DIEFT_DEADBAND
The effect supports deadband.
DIEFT_FFATTACK
The effect supports attack.
DIEFT_FFFADE
The effect supports fade.
DIEFT_HARDWARE
The effect is specific to the hardware, or hardware effects are to be enumerated.
DIEFT_PERIODIC
The effect is periodic, or periodic effects are to be enumerated.
DIEFT_POSNEGCOEFFICIENTS
The condition supports different positive and negative coefficients.
DIEFT_POSNEGSATURATION
The effect supports different positive and negative saturation.
DIEFT_RAMPFORCE
The effect is a ramp force, or ramp forces are to be enumerated.
DIEFT_SATURATION
The effect supports saturation.

See Also

CONST_DIDEVCAPSFLAGS


CONST_DIEGESFLAGS

Returned by the DirectInputEffect.GetEffectStatus method.

Enum CONST_DIEGESFLAGS
    DIEGES_EMULATED = 2
    DIEGES_PLAYING  = 1
End Enum

Constants

DIEGES_EMULATED
The effect is emulated.
DIEGES_PLAYING
The effect is playing.


CONST_DIENUMDEVICESFLAGS

Used in the flags parameter of the DirectInput8.GetDIDevices method to indicate whether all devices or only attached devices are to be enumerated.

Enum CONST_DIENUMDEVICESFLAGS
    DIEDFL_ALLDEVICES      =      0
    DIEDFL_ATTACHEDONLY    =      1
    DIEDFL_FORCEFEEDBACK   =    256 (&H100)
    DIEDFL_INCLUDEALIASES  =  65536 (&H10000)
    DIEDFL_INCLUDEHIDDEN   = 262144 (&H40000)
    DIEDFL_INCLUDEPHANTOMS = 131072 (&H20000)
End Enum

Constants

DIEDFL_ALLDEVICES
All installed devices. 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 CONST_DIDEVCAPSFLAGS.
DIEDFL_INCLUDEPHANTOMS
Include phantom (placeholder) devices.


CONST_DIEPFLAGS

Miscellaneous flags for effects. Some members are passed to the DirectInputEffect.SetParameters method to specify which parameters are being set and the subsequent behavior of the effect. Some members are returned by the DirectInputEnumEffects.GetStaticParams and DirectInputEnumEffects.GetDynamicParams methods to describe support for the parameter.

Enum CONST_DIEPFLAGS
    DIEP_ALLPARAMS             =        1023 (&H3FF)
    DIEP_AXES                  =          32 (&H20)
    DIEP_DIRECTION             =          64 (&H40)
    DIEP_DURATION              =           1
    DIEP_ENVELOPE              =         128 (&H80)
    DIEP_GAIN                  =           4
    DIEP_NODOWNLOAD            = -2147483648 (&H80000000)
    DIEP_NORESTART             =  1073741824 (&H40000000)
    DIEP_SAMPLEPERIOD          =           2
    DIEP_START                 =   536870912 (&H20000000)
    DIEP_STARTDELAY            =         512 (&H200)
    DIEP_TRIGGERBUTTON         =           8
    DIEP_TRIGGERREPEATINTERVAL =          16 (&H10)
    DIEP_TYPESPECIFICPARAMS    =         256 (&H100)
End Enum

Constants

DIEP_ALLPARAMS
Not used.
DIEP_AXES
Not used
DIEP_DIRECTION
The x and y members of DIEFFECT are valid, or a direction parameter is supported. If you are setting or requesting effect parameters, you can specify that the direction is supplied or is to be returned in either Cartesian or polar coordinates by specifying DIEFF_CARTESIAN or DIEFF_POLAR in DIEFFECT.lFlags.
DIEP_DURATION
The lDuration member of DIEFFECT is valid, or the effect supports changing of the duration.
DIEP_ENVELOPE
The envelope member of DIEFFECT is valid, or the effect supports the application of an envelope.
DIEP_GAIN
The lGain member of DIEFFECT is valid, or the effect supports the application of gain.
DIEP_NODOWNLOAD
After setting parameters, the effect is not to be downloaded.
DIEP_NORESTART
Suppress the stopping and restarting of the effect in order to change parameters.
DIEP_SAMPLEPERIOD
The lSamplePeriod member of DIEFFECT is valid.
DIEP_START
Start the effect immediately.
DIEP_STARTDELAY
The lStartDelay member of DIEFFECT is valid, or the effect supports delayed start.
DIEP_TRIGGERBUTTON
The lTriggerButton member of DIEFFECT is valid, or the effect supports a trigger button.
DIEP_TRIGGERREPEATINTERVAL
The lTriggerRepeatInterval member of DIEFFECT is valid, or the effect supports trigger repeat.
DIEP_TYPESPECIFICPARAMS
The effect has type-specific parameters that can be changed by the application. This value is returned by DirectInputEnumEffects.GetStaticParams for all standard effects and for hardware-specific effects with application-modifiable parameters. Microsoft® DirectX® for Microsoft Visual Basic® supports hardware effects only if they do not have this flag set.


CONST_DIESFLAGS

Used in the flags parameter of DirectInputEffect.Start to control behavior of force-feedback effect playback.

Enum CONST_DIESFLAGS
    DIES_NODOWNLOAD = -2147483648 (&H80000000)
    DIES_SOLO       =           1
End Enum

Constants

DIES_NODOWNLOAD
Do not automatically download the effect.
DIES_SOLO
Stop all other effects before playing this effect. If this flag is omitted, the effect is mixed with effects already playing on the device.


CONST_DIFEFFLAGS

Used in the flags member of the DirectInputDevice8.CreateEffectFromFile method.

Enum CONST_DIFEFFLAGS
    DIFEF_DEFAULT            =  0
    DIFEF_INCLUDENONSTANDARD =  1
    DIFEF_MODIFYIFNEEDED     = 16 (&H10)
End Enum

Constants

DIFEF_DEFAULT
Do not create a nonstandard effect or modify the effect parameters.
DIFEF_INCLUDENONSTANDARD
Create an effect type that is not predefined by Microsoft® DirectInput®. If this flag is not set, the method fails when called on such effects.
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.


CONST_DIGENRE

Used in the lSemantic member of the DIACTION type to specify virtual controls and in the lGenre member of DIACTIONFORMAT to specify the application genre for action mapping.

For further details on any of the constants in this enumeration, see the appropriate section of the Action Mapping Constants page.

Enum CONST_DIGENRE
  DIAXIS_2DCONTROL_INOUT            = 587301379 (&H23018203)
  DIAXIS_2DCONTROL_LATERAL          = 587235841 (&H23008201)
  DIAXIS_2DCONTROL_MOVE             = 587268610 (&H23010202)
  DIAXIS_2DCONTROL_ROTATEZ          = 587350532 (&H23024204)
  DIAXIS_3DCONTROL_INOUT            = 604078595 (&H24018203)
  DIAXIS_3DCONTROL_LATERAL          = 604013057 (&H24008201)
  DIAXIS_3DCONTROL_MOVE             = 604045826 (&H24010202)
  DIAXIS_3DCONTROL_ROTATEX          = 604193284 (&H24034204)
  DIAXIS_3DCONTROL_ROTATEY          = 604160517 (&H2402C205)
  DIAXIS_3DCONTROL_ROTATEZ          = 604127750 (&H24024206)
  DIAXIS_ARCADEP_LATERAL            = 570458625 (&H22008201)
  DIAXIS_ARCADEP_MOVE               = 570491394 (&H22010202)
  DIAXIS_ARCADES_LATERAL            = 553681409 (&H21008201)
  DIAXIS_ARCADES_MOVE               = 553714178 (&H21010202)
  DIAXIS_BASEBALLB_LATERAL          = 251691521 (&H0F008201)
  DIAXIS_BASEBALLB_MOVE             = 251724290 (&H0F010202)
  DIAXIS_BASEBALLF_LATERAL          = 285245953 (&H11008201)
  DIAXIS_BASEBALLF_MOVE             = 285278722 (&H11010202)
  DIAXIS_BASEBALLP_LATERAL          = 268468737 (&H10008201)
  DIAXIS_BASEBALLP_MOVE             = 268501506 (&H10010202)
  DIAXIS_BBALLD_LATERAL             = 318800385 (&H13008201)
  DIAXIS_BBALLD_MOVE                = 318833154 (&H13010202)
  DIAXIS_BBALLO_LATERAL             = 302023169 (&H12008201)
  DIAXIS_BBALLO_MOVE                = 302055938 (&H12010202)
  DIAXIS_BIKINGM_BRAKE              = 470041091 (&H1C044203)
  DIAXIS_BIKINGM_PEDAL              = 469828098 (&H1C010202)
  DIAXIS_BIKINGM_TURN               = 469795329 (&H1C008201)
  DIAXIS_BROWSER_LATERAL            = 671121921 (&H28008201)
  DIAXIS_BROWSER_MOVE               = 671154690 (&H28010202)
  DIAXIS_BROWSER_VIEW               = 671187459 (&H28018203)
  DIAXIS_CADF_INOUT                 = 620855811 (&H25018203)
  DIAXIS_CADF_LATERAL               = 620790273 (&H25008201)
  DIAXIS_CADF_MOVE                  = 620823042 (&H25010202)
  DIAXIS_CADF_ROTATEX               = 620970500 (&H25034204)
  DIAXIS_CADF_ROTATEY               = 620937733 (&H2502C205)
  DIAXIS_CADF_ROTATEZ               = 620904966 (&H25024206)
  DIAXIS_CADM_INOUT                 = 637633027 (&H26018203)
  DIAXIS_CADM_LATERAL               = 637567489 (&H26008201)
  DIAXIS_CADM_MOVE                  = 637600258 (&H26010202)
  DIAXIS_CADM_ROTATEX               = 637747716 (&H26034204)
  DIAXIS_CADM_ROTATEY               = 637714949 (&H2602C205)
  DIAXIS_CADM_ROTATEZ               = 637682182 (&H26024206)
  DIAXIS_DRIVINGC_ACCEL_AND_BRAKE   =  33638916 (&H02014A04)
  DIAXIS_DRIVINGC_ACCELERATE        =  33788418 (&H02039202)
  DIAXIS_DRIVINGC_BRAKE             =  33821187 (&H02041203)
  DIAXIS_DRIVINGC_STEER             =  33589761 (&H03008A01)
  DIAXIS_DRIVINGR_ACCEL_AND_BRAKE   =  16861700 (&H01014A04)
  DIAXIS_DRIVINGR_ACCELERATE        =  17011202 (&H01039202)
  DIAXIS_DRIVINGR_BRAKE             =  17043971 (&H01041203)
  DIAXIS_DRIVINGR_STEER             =  16812545 (&H01008A01)
  DIAXIS_DRIVINGT_ACCEL_AND_BRAKE   =  50416133 (&H03014A05)
  DIAXIS_DRIVINGT_ACCELERATE        =  50565635 (&H03039203)
  DIAXIS_DRIVINGT_BARREL            =  50397698 (&H03010202)
  DIAXIS_DRIVINGT_BRAKE             =  50614788 (&H03045204)
  DIAXIS_DRIVINGT_STEER             =  50366977 (&H03008A01)
  DIAXIS_FIGHTINGH_LATERAL          = 134251009 (&H08008201)
  DIAXIS_FIGHTINGH_MOVE             = 134283778 (&H08010202)
  DIAXIS_FIGHTINGH_ROTATE           = 134365699 (&H08024203)
  DIAXIS_FISHING_LATERAL            = 234914305 (&H0E008201)
  DIAXIS_FISHING_MOVE               = 234947074 (&H0E010202)
  DIAXIS_FISHING_ROTATE             = 235028995 (&H0E024203)
  DIAXIS_FLYINGC_BANK               =  67144193 (&H04008A01)
  DIAXIS_FLYINGC_BRAKE              =  67398148 (&H04046A04)
  DIAXIS_FLYINGC_FLAPS              =  67459590 (&H04055A06)
  DIAXIS_FLYINGC_PITCH              =  67176962 (&H04010A02)
  DIAXIS_FLYINGC_RUDDER             =  67260933 (&H04025205)
  DIAXIS_FLYINGC_THROTTLE           =  67342851 (&H04039203)
  DIAXIS_FLYINGH_BANK               = 100698625 (&H06008A01)
  DIAXIS_FLYINGH_COLLECTIVE         = 100764163 (&H06018A03)
  DIAXIS_FLYINGH_PITCH              = 100731394 (&H06010A02)
  DIAXIS_FLYINGH_THROTTLE           = 100915717 (&H0603DA05)
  DIAXIS_FLYINGH_TORQUE             = 100817412 (&H06025A04)
  DIAXIS_FLYINGM_BANK               =  83921409 (&H05008A01)
  DIAXIS_FLYINGM_BRAKE              =  84173317 (&H05046205)
  DIAXIS_FLYINGM_FLAPS              =  84234758 (&H05055206)
  DIAXIS_FLYINGM_PITCH              =  83954178 (&H05010A02)
  DIAXIS_FLYINGM_RUDDER             =  84036100 (&H05024A04)
  DIAXIS_FLYINGM_THROTTLE           =  84120067 (&H05039203)
  DIAXIS_FOOTBALLD_LATERAL          = 385909249 (&H17008201)
  DIAXIS_FOOTBALLD_MOVE             = 385942018 (&H17010202)
  DIAXIS_FOOTBALLO_LATERAL          = 369132033 (&H16008201)
  DIAXIS_FOOTBALLO_MOVE             = 369164802 (&H16010202)
  DIAXIS_FOOTBALLQ_LATERAL          = 352354817 (&H15008201)
  DIAXIS_FOOTBALLQ_MOVE             = 352387586 (&H15010202)
  DIAXIS_FPS_LOOKUPDOWN             = 151093763 (&H09018203)
  DIAXIS_FPS_MOVE                   = 151060994 (&H09010202)
  DIAXIS_FPS_ROTATE                 = 151028225 (&H09008201)
  DIAXIS_FPS_SIDESTEP               = 151142916 (&H09024204)
  DIAXIS_GOLF_LATERAL               = 402686465 (&H18008201)
  DIAXIS_GOLF_MOVE                  = 402719234 (&H18010202)
  DIAXIS_HOCKEYD_LATERAL            = 436240897 (&H1A008201)
  DIAXIS_HOCKEYD_MOVE               = 436273666 (&H1A010202)
  DIAXIS_HOCKEYG_LATERAL            = 453018113 (&H1B008201)
  DIAXIS_HOCKEYG_MOVE               = 453050882 (&H1B010202)
  DIAXIS_HOCKEYO_LATERAL            = 419463681 (&H19008201)
  DIAXIS_HOCKEYO_MOVE               = 419496450 (&H19010202)
  DIAXIS_HUNTING_LATERAL            = 218137089 (&H0D008201)
  DIAXIS_HUNTING_MOVE               = 218169858 (&H0D010202)
  DIAXIS_HUNTING_ROTATE             = 218251779 (&H0D024203)
  DIAXIS_MECHA_ROTATE               = 687997443 (&H29020203)
  DIAXIS_MECHA_STEER                = 687899137 (&H29008201)
  DIAXIS_MECHA_THROTTLE             = 688095748 (&H29038204)
  DIAXIS_MECHA_TORSO                = 687931906 (&H29010202)
  DIAXIS_RACQUET_LATERAL            = 536904193 (&H20008201)
  DIAXIS_RACQUET_MOVE               = 536936962 (&H20010202)
  DIAXIS_REMOTE_SLIDER              = 654639617 (&H27050201)
  DIAXIS_REMOTE_SLIDER2             = 654656002 (&H27054202)
  DIAXIS_SKIING_SPEED               = 486605314 (&H1D010202)
  DIAXIS_SKIING_TURN                = 486572545 (&H1D008201)
  DIAXIS_SOCCERD_LATERAL            = 520126977 (&H1F008201)
  DIAXIS_SOCCERD_MOVE               = 520159746 (&H1F010202)
  DIAXIS_SOCCERO_BEND               = 503415299 (&H1E018203)
  DIAXIS_SOCCERO_LATERAL            = 503349761 (&H1E008201)
  DIAXIS_SOCCERO_MOVE               = 503382530 (&H1E010202)
  DIAXIS_SPACESIM_CLIMB             = 117555716 (&H0701C204)
  DIAXIS_SPACESIM_LATERAL           = 117473793 (&H07008201)
  DIAXIS_SPACESIM_MOVE              = 117506562 (&H07010202)
  DIAXIS_SPACESIM_ROTATE            = 117588485 (&H07024205)
  DIAXIS_SPACESIM_THROTTLE          = 117670403 (&H07038203)
  DIAXIS_STRATEGYR_LATERAL          = 184582657 (&H0B008201)
  DIAXIS_STRATEGYR_MOVE             = 184615426 (&H0B010202)
  DIAXIS_STRATEGYR_ROTATE           = 184697347 (&H0B024203)
  DIAXIS_STRATEGYT_LATERAL          = 201359873 (&H0C008201)
  DIAXIS_STRATEGYT_MOVE             = 201392642 (&H0C010202)
  DIAXIS_TPS_MOVE                   = 167838210 (&H0A010202)
  DIAXIS_TPS_STEP                   = 167821827 (&H0A00C203)
  DIAXIS_TPS_TURN                   = 167903745 (&H0A020201)
  DIBUTTON_2DCONTROL_DEVICE         = 587220222 (&H230044FE)
  DIBUTTON_2DCONTROL_DISPLAY        = 587219973 (&H23004405)
  DIBUTTON_2DCONTROL_MENU           = 587203837 (&H230004FD)
  DIBUTTON_2DCONTROL_PAUSE          = 587220220 (&H230044FC)
  DIBUTTON_2DCONTROL_SELECT         = 587203585 (&H23000401)
  DIBUTTON_2DCONTROL_SPECIAL        = 587203587 (&H23000403)
  DIBUTTON_2DCONTROL_SPECIAL1       = 587203586 (&H23000402)
  DIBUTTON_2DCONTROL_SPECIAL2       = 587203588 (&H23000404)
  DIBUTTON_3DCONTROL_DEVICE         = 603997438 (&H240044FE)
  DIBUTTON_3DCONTROL_DISPLAY        = 603997189 (&H24004405)
  DIBUTTON_3DCONTROL_MENU           = 603981053 (&H240004FD)
  DIBUTTON_3DCONTROL_PAUSE          = 603997436 (&H240044FC)
  DIBUTTON_3DCONTROL_SELECT         = 603980801 (&H24000401)
  DIBUTTON_3DCONTROL_SPECIAL        = 603980803 (&H24000403)
  DIBUTTON_3DCONTROL_SPECIAL1       = 603980802 (&H24000402)
  DIBUTTON_3DCONTROL_SPECIAL2       = 603980804 (&H24000404)
  DIBUTTON_ARCADEP_BACK_LINK        = 570508520 (&H220144E8)
  DIBUTTON_ARCADEP_CROUCH           = 570426371 (&H22000403)
  DIBUTTON_ARCADEP_DEVICE           = 570443006 (&H220044FE)
  DIBUTTON_ARCADEP_FIRE             = 570426370 (&H22000402)
  DIBUTTON_ARCADEP_FIRESECONDARY    = 570442758 (&H22004406)
  DIBUTTON_ARCADEP_FORWARD_LINK     = 570508512 (&H220144E0)
  DIBUTTON_ARCADEP_JUMP             = 570426369 (&H22000401)
  DIBUTTON_ARCADEP_LEFT_LINK        = 570475748 (&H2200C4E4)
  DIBUTTON_ARCADEP_MENU             = 570426621 (&H220004FD)
  DIBUTTON_ARCADEP_PAUSE            = 570443004 (&H220044FC)
  DIBUTTON_ARCADEP_RIGHT_LINK       = 570475756 (&H2200C4EC)
  DIBUTTON_ARCADEP_SELECT           = 570426373 (&H22000405)
  DIBUTTON_ARCADEP_SPECIAL          = 570426372 (&H22000404)
  DIBUTTON_ARCADEP_VIEW_DOWN_LINK   = 570934504 (&H2207C4E8)
  DIBUTTON_ARCADEP_VIEW_LEFT_LINK   = 570934500 (&H2207C4E4)
  DIBUTTON_ARCADEP_VIEW_RIGHT_LINK  = 570934508 (&H2207C4EC)
  DIBUTTON_ARCADEP_VIEW_UP_LINK     = 570934496 (&H2207C4E0)
  DIBUTTON_ARCADES_ATTACK           = 553649155 (&H21000403)
  DIBUTTON_ARCADES_BACK_LINK        = 553731304 (&H210144E8)
  DIBUTTON_ARCADES_CARRY            = 553649154 (&H21000402)
  DIBUTTON_ARCADES_DEVICE           = 553665790 (&H210044FE)
  DIBUTTON_ARCADES_FORWARD_LINK     = 553731296 (&H210144E0)
  DIBUTTON_ARCADES_LEFT_LINK        = 553698532 (&H2100C4E4)
  DIBUTTON_ARCADES_MENU             = 553649405 (&H210004FD)
  DIBUTTON_ARCADES_PAUSE            = 553665788 (&H210044FC)
  DIBUTTON_ARCADES_RIGHT_LINK       = 553698540 (&H2100C4EC)
  DIBUTTON_ARCADES_SELECT           = 553649157 (&H21000405)
  DIBUTTON_ARCADES_SPECIAL          = 553649156 (&H21000404)
  DIBUTTON_ARCADES_THROW            = 553649153 (&H21000401)
  DIBUTTON_ARCADES_VIEW_DOWN_LINK   = 554157288 (&H2107C4E8)
  DIBUTTON_ARCADES_VIEW_LEFT_LINK   = 554157284 (&H2107C4E4)
  DIBUTTON_ARCADES_VIEW_RIGHT_LINK  = 554157292 (&H2107C4EC)
  DIBUTTON_ARCADES_VIEW_UP_LINK     = 554157280 (&H2107C4E0)
  DIBUTTON_BASEBALLB_BACK_LINK      = 251741416 (&H0F0144E8)
  DIBUTTON_BASEBALLB_BOX            = 251675658 (&H0F00440A)
  DIBUTTON_BASEBALLB_BUNT           = 251659268 (&H0F000404)
  DIBUTTON_BASEBALLB_BURST          = 251659270 (&H0F000406)
  DIBUTTON_BASEBALLB_CONTACT        = 251659272 (&H0F000408)
  DIBUTTON_BASEBALLB_DEVICE         = 251675902 (&H0F0044FE)
  DIBUTTON_BASEBALLB_FORWARD_LINK   = 251741408 (&H0F0144E0)
  DIBUTTON_BASEBALLB_LEFT_LINK      = 251708644 (&H0F00C4E4)
  DIBUTTON_BASEBALLB_MENU           = 251659517 (&H0F0004FD)
  DIBUTTON_BASEBALLB_NORMAL         = 251659266 (&H0F000402)
  DIBUTTON_BASEBALLB_NOSTEAL        = 251675657 (&H0F004409)
  DIBUTTON_BASEBALLB_PAUSE          = 251675900 (&H0F0044FC)
  DIBUTTON_BASEBALLB_POWER          = 251659267 (&H0F000403)
  DIBUTTON_BASEBALLB_RIGHT_LINK     = 251708652 (&H0F00C4EC)
  DIBUTTON_BASEBALLB_SELECT         = 251659265 (&H0F000401)
  DIBUTTON_BASEBALLB_SLIDE          = 251659271 (&H0F000407)
  DIBUTTON_BASEBALLB_STEAL          = 251659269 (&H0F000405)
  DIBUTTON_BASEBALLF_AIM_LEFT_LINK  = 285263076 (&H1100C4E4)
  DIBUTTON_BASEBALLF_AIM_RIGHT_LINK = 285263084 (&H1100C4EC)
  DIBUTTON_BASEBALLF_BACK_LINK      = 285295848 (&H110144E8)
  DIBUTTON_BASEBALLF_BURST          = 285213700 (&H11000404)
  DIBUTTON_BASEBALLF_DEVICE         = 285230334 (&H110044FE)
  DIBUTTON_BASEBALLF_DIVE           = 285213702 (&H11000406)
  DIBUTTON_BASEBALLF_FORWARD_LINK   = 285295840 (&H110144E0)
  DIBUTTON_BASEBALLF_JUMP           = 285213701 (&H11000405)
  DIBUTTON_BASEBALLF_MENU           = 285213949 (&H110004FD)
  DIBUTTON_BASEBALLF_NEAREST        = 285213697 (&H11000401)
  DIBUTTON_BASEBALLF_PAUSE          = 285230332 (&H110044FC)
  DIBUTTON_BASEBALLF_SHIFTIN        = 285230087 (&H11004407)
  DIBUTTON_BASEBALLF_SHIFTOUT       = 285230088 (&H11004408)
  DIBUTTON_BASEBALLF_THROW1         = 285213698 (&H11000402)
  DIBUTTON_BASEBALLF_THROW2         = 285213699 (&H11000403)
  DIBUTTON_BASEBALLP_BACK_LINK      = 268518632 (&H100144E8)
  DIBUTTON_BASEBALLP_BASE           = 268436483 (&H10000403)
  DIBUTTON_BASEBALLP_DEVICE         = 268453118 (&H100044FE)
  DIBUTTON_BASEBALLP_FAKE           = 268436485 (&H10000405)
  DIBUTTON_BASEBALLP_FORWARD_LINK   = 268518624 (&H100144E0)
  DIBUTTON_BASEBALLP_LEFT_LINK      = 268485860 (&H1000C4E4)
  DIBUTTON_BASEBALLP_LOOK           = 268452871 (&H10004407)
  DIBUTTON_BASEBALLP_MENU           = 268436733 (&H100004FD)
  DIBUTTON_BASEBALLP_PAUSE          = 268453116 (&H100044FC)
  DIBUTTON_BASEBALLP_PITCH          = 268436482 (&H10000402)
  DIBUTTON_BASEBALLP_RIGHT_LINK     = 268485868 (&H1000C4EC)
  DIBUTTON_BASEBALLP_SELECT         = 268436481 (&H10000401)
  DIBUTTON_BASEBALLP_THROW          = 268436484 (&H10000404)
  DIBUTTON_BASEBALLP_WALK           = 268452870 (&H10004406)
  DIBUTTON_BBALLD_BACK_LINK         = 318850280 (&H130144E8)
  DIBUTTON_BBALLD_BURST             = 318768134 (&H13000406)
  DIBUTTON_BBALLD_DEVICE            = 318784766 (&H130044FE)
  DIBUTTON_BBALLD_FAKE              = 318768131 (&H13000403)
  DIBUTTON_BBALLD_FORWARD_LINK      = 318850272 (&H130144E0)
  DIBUTTON_BBALLD_JUMP              = 318768129 (&H13000401)
  DIBUTTON_BBALLD_LEFT_LINK         = 318817508 (&H1300C4E4)
  DIBUTTON_BBALLD_MENU              = 318768381 (&H130004FD)
  DIBUTTON_BBALLD_PAUSE             = 318784764 (&H130044FC)
  DIBUTTON_BBALLD_PLAY              = 318768135 (&H13000407)
  DIBUTTON_BBALLD_PLAYER            = 318768133 (&H13000405)
  DIBUTTON_BBALLD_RIGHT_LINK        = 318817516 (&H1300C4EC)
  DIBUTTON_BBALLD_SPECIAL           = 318768132 (&H13000404)
  DIBUTTON_BBALLD_STEAL             = 318768130 (&H13000402)
  DIBUTTON_BBALLD_SUBSTITUTE        = 318784521 (&H13004409)
  DIBUTTON_BBALLD_TIMEOUT           = 318784520 (&H13004408)
  DIBUTTON_BBALLO_BACK_LINK         = 302073064 (&H120144E8)
  DIBUTTON_BBALLO_BURST             = 301990919 (&H12000407)
  DIBUTTON_BBALLO_CALL              = 301990920 (&H12000408)
  DIBUTTON_BBALLO_DEVICE            = 302007550 (&H120044FE)
  DIBUTTON_BBALLO_DUNK              = 301990914 (&H12000402)
  DIBUTTON_BBALLO_FAKE              = 301990916 (&H12000404)
  DIBUTTON_BBALLO_FORWARD_LINK      = 302073056 (&H120144E0)
  DIBUTTON_BBALLO_JAB               = 302007307 (&H1200440B)
  DIBUTTON_BBALLO_LEFT_LINK         = 302040292 (&H1200C4E4)
  DIBUTTON_BBALLO_MENU              = 301991165 (&H120004FD)
  DIBUTTON_BBALLO_PASS              = 301990915 (&H12000403)
  DIBUTTON_BBALLO_PAUSE             = 302007548 (&H120044FC)
  DIBUTTON_BBALLO_PLAY              = 302007306 (&H1200440A)
  DIBUTTON_BBALLO_PLAYER            = 301990918 (&H12000406)
  DIBUTTON_BBALLO_POST              = 302007308 (&H1200440C)
  DIBUTTON_BBALLO_RIGHT_LINK        = 302040300 (&H1200C4EC)
  DIBUTTON_BBALLO_SCREEN            = 302007305 (&H12004409)
  DIBUTTON_BBALLO_SHOOT             = 301990913 (&H12000401)
  DIBUTTON_BBALLO_SPECIAL           = 301990917 (&H12000405)
  DIBUTTON_BBALLO_SUBSTITUTE        = 302007310 (&H1200440E)
  DIBUTTON_BBALLO_TIMEOUT           = 302007309 (&H1200440D)
  DIBUTTON_BIKINGM_BRAKE_BUTTON_LINK= 470041832 (&H1C0444E8)
  DIBUTTON_BIKINGM_CAMERA           = 469763074 (&H1C000402)
  DIBUTTON_BIKINGM_DEVICE           = 469779710 (&H1C0044FE)
  DIBUTTON_BIKINGM_FASTER_LINK      = 469845216 (&H1C0144E0)
  DIBUTTON_BIKINGM_JUMP             = 469763073 (&H1C000401)
  DIBUTTON_BIKINGM_LEFT_LINK        = 469812452 (&H1C00C4E4)
  DIBUTTON_BIKINGM_MENU             = 469763325 (&H1C0004FD)
  DIBUTTON_BIKINGM_PAUSE            = 469779708 (&H1C0044FC)
  DIBUTTON_BIKINGM_RIGHT_LINK       = 469812460 (&H1C00C4EC)
  DIBUTTON_BIKINGM_SELECT           = 469763076 (&H1C000404)
  DIBUTTON_BIKINGM_SLOWER_LINK      = 469845224 (&H1C0144E8)
  DIBUTTON_BIKINGM_SPECIAL1         = 469763075 (&H1C000403)
  DIBUTTON_BIKINGM_SPECIAL2         = 469763077 (&H1C000405)
  DIBUTTON_BIKINGM_ZOOM             = 469779462 (&H1C004406)
  DIBUTTON_BROWSER_DEVICE           = 671106302 (&H280044FE)
  DIBUTTON_BROWSER_FAVORITES        = 671106054 (&H28004406)
  DIBUTTON_BROWSER_HISTORY          = 671106057 (&H28004409)
  DIBUTTON_BROWSER_HOME             = 671106053 (&H28004405)
  DIBUTTON_BROWSER_MENU             = 671089917 (&H280004FD)
  DIBUTTON_BROWSER_NEXT             = 671106055 (&H28004407)
  DIBUTTON_BROWSER_PAUSE            = 671106300 (&H280044FC)
  DIBUTTON_BROWSER_PREVIOUS         = 671106056 (&H28004408)
  DIBUTTON_BROWSER_PRINT            = 671106058 (&H2800440A)
  DIBUTTON_BROWSER_REFRESH          = 671089666 (&H28000402)
  DIBUTTON_BROWSER_SEARCH           = 671106051 (&H28004403)
  DIBUTTON_BROWSER_SELECT           = 671089665 (&H28000401)
  DIBUTTON_BROWSER_STOP             = 671106052 (&H28004404)
  DIBUTTON_CADF_DEVICE              = 620774654 (&H250044FE)
  DIBUTTON_CADF_DISPLAY             = 620774405 (&H25004405)
  DIBUTTON_CADF_MENU                = 620758269 (&H250004FD)
  DIBUTTON_CADF_PAUSE               = 620774652 (&H250044FC)
  DIBUTTON_CADF_SELECT              = 620758017 (&H25000401)
  DIBUTTON_CADF_SPECIAL             = 620758019 (&H25000403)
  DIBUTTON_CADF_SPECIAL1            = 620758018 (&H25000402)
  DIBUTTON_CADF_SPECIAL2            = 620758020 (&H25000404)
  DIBUTTON_CADM_DEVICE              = 637551870 (&H260044FE)
  DIBUTTON_CADM_DISPLAY             = 637551621 (&H26004405)
  DIBUTTON_CADM_MENU                = 637535485 (&H260004FD)
  DIBUTTON_CADM_PAUSE               = 637551868 (&H260044FC)
  DIBUTTON_CADM_SELECT              = 637535233 (&H26000401)
  DIBUTTON_CADM_SPECIAL             = 637535235 (&H26000403)
  DIBUTTON_CADM_SPECIAL1            = 637535234 (&H26000402)
  DIBUTTON_CADM_SPECIAL2            = 637535236 (&H26000404)
  DIBUTTON_DRIVINGC_ACCELERATE_LINK =  33805536 (&H0203D4E0)
  DIBUTTON_DRIVINGC_AIDS            =  33571847 (&H02004407)
  DIBUTTON_DRIVINGC_BRAKE           =  33573896 (&H02004C08)
  DIBUTTON_DRIVINGC_DASHBOARD       =  33571846 (&H02004406)
  DIBUTTON_DRIVINGC_DEVICE          =  33572094 (&H020044FE)
  DIBUTTON_DRIVINGC_FIRE            =  33557505 (&H02000C01)
  DIBUTTON_DRIVINGC_FIRESECONDARY   =  33573897 (&H02004C09)
  DIBUTTON_DRIVINGC_GLANCE_LEFT_LINK = 34063588 (&H0207C4E4)
  DIBUTTON_DRIVINGC_GLANCE_RIGHT_LINK= 34063596 (&H0207C4EC)
  DIBUTTON_DRIVINGC_MENU            =  33555709 (&H020004FD)
  DIBUTTON_DRIVINGC_PAUSE           =  33572092 (&H020044FC)
  DIBUTTON_DRIVINGC_SHIFTDOWN       =  33573893 (&H02004C05)
  DIBUTTON_DRIVINGC_SHIFTUP         =  33573892 (&H02004C04)
  DIBUTTON_DRIVINGC_STEER_LEFT_LINK =  33606884 (&H0200CCE4)
  DIBUTTON_DRIVINGC_STEER_RIGHT_LINK = 33606892 (&H0200CCEC)
  DIBUTTON_DRIVINGC_TARGET          =  33557507 (&H02000C03)
  DIBUTTON_DRIVINGC_WEAPONS         =  33557506 (&H02000C02)
  DIBUTTON_DRIVINGR_ACCELERATE_LINK =  17028320 (&H0103D4E0)
  DIBUTTON_DRIVINGR_AIDS            =  16794630 (&H01004406)
  DIBUTTON_DRIVINGR_BOOST           =  16794632 (&H01004408)
  DIBUTTON_DRIVINGR_BRAKE           =  16796676 (&H01004C04)
  DIBUTTON_DRIVINGR_DASHBOARD       =  16794629 (&H01004405)
  DIBUTTON_DRIVINGR_DEVICE          =  16794878 (&H010044FE)
  DIBUTTON_DRIVINGR_GLANCE_LEFT_LINK = 17286372 (&H0107C4E4)
  DIBUTTON_DRIVINGR_GLANCE_RIGHT_LINK= 17286380 (&H0107C4EC)
  DIBUTTON_DRIVINGR_MAP             =  16794631 (&H01004407)
  DIBUTTON_DRIVINGR_MENU            =  16778493 (&H010004FD)
  DIBUTTON_DRIVINGR_PAUSE           =  16794876 (&H010044FC)
  DIBUTTON_DRIVINGR_PIT             =  16794633 (&H01004409)
  DIBUTTON_DRIVINGR_SHIFTDOWN       =  16780290 (&H01000C02)
  DIBUTTON_DRIVINGR_SHIFTUP         =  16780289 (&H01000C01)
  DIBUTTON_DRIVINGR_STEER_LEFT_LINK =  16829668 (&H0100CCE4)
  DIBUTTON_DRIVINGR_STEER_RIGHT_LINK = 16829676 (&H0100CCEC)
  DIBUTTON_DRIVINGR_VIEW            =  16784387 (&H01001C03)
  DIBUTTON_DRIVINGT_ACCELERATE_LINK =  50582752 (&H0303D4E0)
  DIBUTTON_DRIVINGT_BARREL_DOWN_LINK = 50414824 (&H030144E8)
  DIBUTTON_DRIVINGT_BARREL_UP_LINK  =  50414816 (&H030144E0)
  DIBUTTON_DRIVINGT_BRAKE           =  50351110 (&H03004C06)
  DIBUTTON_DRIVINGT_DASHBOARD       =  50355205 (&H03005C05)
  DIBUTTON_DRIVINGT_DEVICE          =  50349310 (&H030044FE)
  DIBUTTON_DRIVINGT_FIRE            =  50334721 (&H03000C01)
  DIBUTTON_DRIVINGT_FIRESECONDARY   =  50351111 (&H03004C07)
  DIBUTTON_DRIVINGT_GLANCE_LEFT_LINK = 50840804 (&H0307C4E4)
  DIBUTTON_DRIVINGT_GLANCE_RIGHT_LINK= 50840812 (&H0307C4EC)
  DIBUTTON_DRIVINGT_MENU            =  50332925 (&H030004FD)
  DIBUTTON_DRIVINGT_PAUSE           =  50349308 (&H030044FC)
  DIBUTTON_DRIVINGT_STEER_LEFT_LINK =  50384100 (&H0300CCE4)
  DIBUTTON_DRIVINGT_STEER_RIGHT_LINK = 50384108 (&H0300CCEC)
  DIBUTTON_DRIVINGT_TARGET          =  50334723 (&H03000C03)
  DIBUTTON_DRIVINGT_VIEW            =  50355204 (&H03005C04)
  DIBUTTON_DRIVINGT_WEAPONS         =  50334722 (&H03000C02)
  DIBUTTON_FIGHTINGH_BACKWARD_LINK  = 134300904 (&H080144E8)
  DIBUTTON_FIGHTINGH_BLOCK          = 134218755 (&H08000403)
  DIBUTTON_FIGHTINGH_CROUCH         = 134218756 (&H08000404)
  DIBUTTON_FIGHTINGH_DEVICE         = 134235390 (&H080044FE)
  DIBUTTON_FIGHTINGH_DISPLAY        = 134235145 (&H08004409)
  DIBUTTON_FIGHTINGH_DODGE          = 134235146 (&H0800440A)
  DIBUTTON_FIGHTINGH_FORWARD_LINK   = 134300896 (&H080144E0)
  DIBUTTON_FIGHTINGH_JUMP           = 134218757 (&H08000405)
  DIBUTTON_FIGHTINGH_KICK           = 134218754 (&H08000402)
  DIBUTTON_FIGHTINGH_LEFT_LINK      = 134268132 (&H0800C4E4)
  DIBUTTON_FIGHTINGH_MENU           = 134219005 (&H080004FD)
  DIBUTTON_FIGHTINGH_PAUSE          = 134235388 (&H080044FC)
  DIBUTTON_FIGHTINGH_PUNCH          = 134218753 (&H08000401)
  DIBUTTON_FIGHTINGH_RIGHT_LINK     = 134268140 (&H0800C4EC)
  DIBUTTON_FIGHTINGH_SELECT         = 134235144 (&H08004408)
  DIBUTTON_FIGHTINGH_SPECIAL1       = 134218758 (&H08000406)
  DIBUTTON_FIGHTINGH_SPECIAL2       = 134218759 (&H08000407)
  DIBUTTON_FISHING_BACK_LINK        = 234964200 (&H0E0144E8)
  DIBUTTON_FISHING_BAIT             = 234882052 (&H0E000404)
  DIBUTTON_FISHING_BINOCULAR        = 234882051 (&H0E000403)
  DIBUTTON_FISHING_CAST             = 234882049 (&H0E000401)
  DIBUTTON_FISHING_CROUCH           = 234898439 (&H0E004407)
  DIBUTTON_FISHING_DEVICE           = 234898686 (&H0E0044FE)
  DIBUTTON_FISHING_DISPLAY          = 234898438 (&H0E004406)
  DIBUTTON_FISHING_FORWARD_LINK     = 234964192 (&H0E0144E0)
  DIBUTTON_FISHING_JUMP             = 234898440 (&H0E004408)
  DIBUTTON_FISHING_LEFT_LINK        = 234931428 (&H0E00C4E4)
  DIBUTTON_FISHING_MAP              = 234882053 (&H0E000405)
  DIBUTTON_FISHING_MENU             = 234882301 (&H0E0004FD)
  DIBUTTON_FISHING_PAUSE            = 234898684 (&H0E0044FC)
  DIBUTTON_FISHING_RIGHT_LINK       = 234931436 (&H0E00C4EC)
  DIBUTTON_FISHING_ROTATE_LEFT_LINK = 235029732 (&H0E0244E4)
  DIBUTTON_FISHING_ROTATE_RIGHT_LINK= 235029740 (&H0E0244EC)
  DIBUTTON_FISHING_TYPE             = 234882050 (&H0E000402)
  DIBUTTON_FLYINGC_BRAKE_LINK       =  67398880 (&H04046CE0)
  DIBUTTON_FLYINGC_DEVICE           =  67126526 (&H040044FE)
  DIBUTTON_FLYINGC_DISPLAY          =  67118082 (&H04002402)
  DIBUTTON_FLYINGC_FASTER_LINK      =  67359968 (&H0403D4E0)
  DIBUTTON_FLYINGC_FLAPSDOWN        =  67134469 (&H04006405)
  DIBUTTON_FLYINGC_FLAPSUP          =  67134468 (&H04006404)
  DIBUTTON_FLYINGC_GEAR             =  67120131 (&H04002C03)
  DIBUTTON_FLYINGC_GLANCE_DOWN_LINK =  67618024 (&H0407C4E8)
  DIBUTTON_FLYINGC_GLANCE_LEFT_LINK =  67618020 (&H0407C4E4)
  DIBUTTON_FLYINGC_GLANCE_RIGHT_LINK = 67618028 (&H0407C4EC)
  DIBUTTON_FLYINGC_GLANCE_UP_LINK   =  67618016 (&H0407C4E0)
  DIBUTTON_FLYINGC_MENU             =  67110141 (&H040004FD)
  DIBUTTON_FLYINGC_PAUSE            =  67126524 (&H040044FC)
  DIBUTTON_FLYINGC_SLOWER_LINK      =  67359976 (&H0403D4E8)
  DIBUTTON_FLYINGC_VIEW             =  67118081 (&H04002401)
  DIBUTTON_FLYINGH_COUNTER          = 100684804 (&H06005404)
  DIBUTTON_FLYINGH_DEVICE           = 100680958 (&H060044FE)
  DIBUTTON_FLYINGH_FASTER_LINK      = 100916448 (&H0603DCE0)
  DIBUTTON_FLYINGH_FIRE             = 100668417 (&H06001401)
  DIBUTTON_FLYINGH_FIRESECONDARY    = 100682759 (&H06004C07)
  DIBUTTON_FLYINGH_GEAR             = 100688902 (&H06006406)
  DIBUTTON_FLYINGH_GLANCE_DOWN_LINK = 101172456 (&H0607C4E8)
  DIBUTTON_FLYINGH_GLANCE_LEFT_LINK = 101172452 (&H0607C4E4)
  DIBUTTON_FLYINGH_GLANCE_RIGHT_LINK= 101172460 (&H0607C4EC)
  DIBUTTON_FLYINGH_GLANCE_UP_LINK   = 101172448 (&H0607C4E0)
  DIBUTTON_FLYINGH_MENU             = 100664573 (&H060004FD)
  DIBUTTON_FLYINGH_PAUSE            = 100680956 (&H060044FC)
  DIBUTTON_FLYINGH_SLOWER_LINK      = 100916456 (&H0603DCE8)
  DIBUTTON_FLYINGH_TARGET           = 100668419 (&H06001403)
  DIBUTTON_FLYINGH_VIEW             = 100688901 (&H06006405)
  DIBUTTON_FLYINGH_WEAPONS          = 100668418 (&H06001402)
  DIBUTTON_FLYINGM_BRAKE_LINK       =  84174048 (&H050464E0)
  DIBUTTON_FLYINGM_COUNTER          =  83909636 (&H05005C04)
  DIBUTTON_FLYINGM_DEVICE           =  83903742 (&H050044FE)
  DIBUTTON_FLYINGM_DISPLAY          =  83911686 (&H05006406)
  DIBUTTON_FLYINGM_FASTER_LINK      =  84137184 (&H0503D4E0)
  DIBUTTON_FLYINGM_FIRE             =  83889153 (&H05000C01)
  DIBUTTON_FLYINGM_FIRESECONDARY    =  83905546 (&H05004C09)
  DIBUTTON_FLYINGM_FLAPSDOWN        =  83907592 (&H05005408)
  DIBUTTON_FLYINGM_FLAPSUP          =  83907591 (&H05005407)
  DIBUTTON_FLYINGM_GEAR             =  83911689 (&H0500640A)
  DIBUTTON_FLYINGM_GLANCE_DOWN_LINK =  84395240 (&H0507C4E8)
  DIBUTTON_FLYINGM_GLANCE_LEFT_LINK =  84395236 (&H0507C4E4)
  DIBUTTON_FLYINGM_GLANCE_RIGHT_LINK = 84395244 (&H0507C4EC)
  DIBUTTON_FLYINGM_GLANCE_UP_LINK   =  84395232 (&H0507C4E0)
  DIBUTTON_FLYINGM_MENU             =  83887357 (&H050004FD)
  DIBUTTON_FLYINGM_PAUSE            =  83903740 (&H050044FC)
  DIBUTTON_FLYINGM_SLOWER_LINK      =  84137192 (&H0503D4E8)
  DIBUTTON_FLYINGM_TARGET           =  83889155 (&H05000C03)
  DIBUTTON_FLYINGM_VIEW             =  83911685 (&H05006405)
  DIBUTTON_FLYINGM_WEAPONS          =  83889154 (&H05000C02)
  DIBUTTON_FOOTBALLD_AUDIBLE        = 385893387 (&H1700440B)
  DIBUTTON_FOOTBALLD_BACK_LINK      = 385959144 (&H170144E8)
  DIBUTTON_FOOTBALLD_BULLRUSH       = 385893385 (&H17004409)
  DIBUTTON_FOOTBALLD_DEVICE         = 385893630 (&H170044FE)
  DIBUTTON_FOOTBALLD_FAKE           = 385876997 (&H17000405)
  DIBUTTON_FOOTBALLD_FORWARD_LINK   = 385959136 (&H170144E0)
  DIBUTTON_FOOTBALLD_JUMP           = 385876995 (&H17000403)
  DIBUTTON_FOOTBALLD_LEFT_LINK      = 385926372 (&H1700C4E4)
  DIBUTTON_FOOTBALLD_MENU           = 385877245 (&H170004FD)
  DIBUTTON_FOOTBALLD_PAUSE          = 385893628 (&H170044FC)
  DIBUTTON_FOOTBALLD_PLAY           = 385876993 (&H17000401)
  DIBUTTON_FOOTBALLD_RIGHT_LINK     = 385926380 (&H1700C4EC)
  DIBUTTON_FOOTBALLD_RIP            = 385893386 (&H1700440A)
  DIBUTTON_FOOTBALLD_SELECT         = 385876994 (&H17000402)
  DIBUTTON_FOOTBALLD_SPIN           = 385893383 (&H17004407)
  DIBUTTON_FOOTBALLD_SUBSTITUTE     = 385893389 (&H1700440D)
  DIBUTTON_FOOTBALLD_SUPERTACKLE    = 385876998 (&H17000406)
  DIBUTTON_FOOTBALLD_SWIM           = 385893384 (&H17004408)
  DIBUTTON_FOOTBALLD_TACKLE         = 385876996 (&H17000404)
  DIBUTTON_FOOTBALLD_ZOOM           = 385893388 (&H1700440C)
  DIBUTTON_FOOTBALLO_BACK_LINK      = 369181928 (&H160144E8)
  DIBUTTON_FOOTBALLO_DEVICE         = 369116414 (&H160044FE)
  DIBUTTON_FOOTBALLO_DIVE           = 369116169 (&H16004409)
  DIBUTTON_FOOTBALLO_FORWARD_LINK   = 369181920 (&H160144E0)
  DIBUTTON_FOOTBALLO_JUKE           = 369116166 (&H16004406)
  DIBUTTON_FOOTBALLO_JUMP           = 369099777 (&H16000401)
  DIBUTTON_FOOTBALLO_LEFT_LINK      = 369149156 (&H1600C4E4)
  DIBUTTON_FOOTBALLO_LEFTARM        = 369099778 (&H16000402)
  DIBUTTON_FOOTBALLO_MENU           = 369100029 (&H160004FD)
  DIBUTTON_FOOTBALLO_PAUSE          = 369116412 (&H160044FC)
  DIBUTTON_FOOTBALLO_RIGHT_LINK     = 369149164 (&H1600C4EC)
  DIBUTTON_FOOTBALLO_RIGHTARM       = 369099779 (&H16000403)
  DIBUTTON_FOOTBALLO_SHOULDER       = 369116167 (&H16004407)
  DIBUTTON_FOOTBALLO_SPIN           = 369099781 (&H16000405)
  DIBUTTON_FOOTBALLO_SUBSTITUTE     = 369116171 (&H1600440B)
  DIBUTTON_FOOTBALLO_THROW          = 369099780 (&H16000404)
  DIBUTTON_FOOTBALLO_TURBO          = 369116168 (&H16004408)
  DIBUTTON_FOOTBALLO_ZOOM           = 369116170 (&H1600440A)
  DIBUTTON_FOOTBALLP_DEVICE         = 335561982 (&H140044FE)
  DIBUTTON_FOOTBALLP_HELP           = 335545347 (&H14000403)
  DIBUTTON_FOOTBALLP_MENU           = 335545597 (&H140004FD)
  DIBUTTON_FOOTBALLP_PAUSE          = 335561980 (&H140044FC)
  DIBUTTON_FOOTBALLP_PLAY           = 335545345 (&H14000401)
  DIBUTTON_FOOTBALLP_SELECT         = 335545346 (&H14000402)
  DIBUTTON_FOOTBALLQ_AUDIBLE        = 352338953 (&H15004409)
  DIBUTTON_FOOTBALLQ_BACK_LINK      = 352404712 (&H150144E8)
  DIBUTTON_FOOTBALLQ_DEVICE         = 352339198 (&H150044FE)
  DIBUTTON_FOOTBALLQ_FAKE           = 352322566 (&H15000406)
  DIBUTTON_FOOTBALLQ_FAKESNAP       = 352338951 (&H15004407)
  DIBUTTON_FOOTBALLQ_FORWARD_LINK   = 352404704 (&H150144E0)
  DIBUTTON_FOOTBALLQ_JUMP           = 352322563 (&H15000403)
  DIBUTTON_FOOTBALLQ_LEFT_LINK      = 352371940 (&H1500C4E4)
  DIBUTTON_FOOTBALLQ_MENU           = 352322813 (&H150004FD)
  DIBUTTON_FOOTBALLQ_MOTION         = 352338952 (&H15004408)
  DIBUTTON_FOOTBALLQ_PASS           = 352322565 (&H15000405)
  DIBUTTON_FOOTBALLQ_PAUSE          = 352339196 (&H150044FC)
  DIBUTTON_FOOTBALLQ_RIGHT_LINK     = 352371948 (&H1500C4EC)
  DIBUTTON_FOOTBALLQ_SELECT         = 352322561 (&H15000401)
  DIBUTTON_FOOTBALLQ_SLIDE          = 352322564 (&H15000404)
  DIBUTTON_FOOTBALLQ_SNAP           = 352322562 (&H15000402)
  DIBUTTON_FPS_APPLY                = 150995971 (&H09000403)
  DIBUTTON_FPS_BACKWARD_LINK        = 151078120 (&H090144E8)
  DIBUTTON_FPS_CROUCH               = 150995973 (&H09000405)
  DIBUTTON_FPS_DEVICE               = 151012606 (&H090044FE)
  DIBUTTON_FPS_DISPLAY              = 151012360 (&H09004408)
  DIBUTTON_FPS_DODGE                = 151012361 (&H09004409)
  DIBUTTON_FPS_FIRE                 = 150995969 (&H09000401)
  DIBUTTON_FPS_FIRESECONDARY        = 151012364 (&H0900440C)
  DIBUTTON_FPS_FORWARD_LINK         = 151078112 (&H090144E0)
  DIBUTTON_FPS_GLANCE_DOWN_LINK     = 151110888 (&H0901C4E8)
  DIBUTTON_FPS_GLANCE_UP_LINK       = 151110880 (&H0901C4E0)
  DIBUTTON_FPS_GLANCEL              = 151012362 (&H0900440A)
  DIBUTTON_FPS_GLANCER              = 151012363 (&H0900440B)
  DIBUTTON_FPS_JUMP                 = 150995974 (&H09000406)
  DIBUTTON_FPS_MENU                 = 150996221 (&H090004FD)
  DIBUTTON_FPS_PAUSE                = 151012604 (&H090044FC)
  DIBUTTON_FPS_ROTATE_LEFT_LINK     = 151045348 (&H0900C4E4)
  DIBUTTON_FPS_ROTATE_RIGHT_LINK    = 151045356 (&H0900C4EC)
  DIBUTTON_FPS_SELECT               = 150995972 (&H09000404)
  DIBUTTON_FPS_STRAFE               = 150995975 (&H09000407)
  DIBUTTON_FPS_WEAPONS              = 150995970 (&H09000402)
  DIBUTTON_GOLF_BACK_LINK           = 402736360 (&H180144E8)
  DIBUTTON_GOLF_DEVICE              = 402670846 (&H180044FE)
  DIBUTTON_GOLF_DOWN                = 402654212 (&H18000404)
  DIBUTTON_GOLF_FLYBY               = 402654214 (&H18000406)
  DIBUTTON_GOLF_FORWARD_LINK        = 402736352 (&H180144E0)
  DIBUTTON_GOLF_LEFT_LINK           = 402703588 (&H1800C4E4)
  DIBUTTON_GOLF_MENU                = 402654461 (&H180004FD)
  DIBUTTON_GOLF_PAUSE               = 402670844 (&H180044FC)
  DIBUTTON_GOLF_RIGHT_LINK          = 402703596 (&H1800C4EC)
  DIBUTTON_GOLF_SELECT              = 402654210 (&H18000402)
  DIBUTTON_GOLF_SUBSTITUTE          = 402670601 (&H18004409)
  DIBUTTON_GOLF_SWING               = 402654209 (&H18000401)
  DIBUTTON_GOLF_TERRAIN             = 402654213 (&H18000405)
  DIBUTTON_GOLF_TIMEOUT             = 402670600 (&H18004408)
  DIBUTTON_GOLF_UP                  = 402654211 (&H18000403)
  DIBUTTON_GOLF_ZOOM                = 402670599 (&H18004407)
  DIBUTTON_HOCKEYD_BACK_LINK        = 436290792 (&H1A0144E8)
  DIBUTTON_HOCKEYD_BLOCK            = 436208644 (&H1A000404)
  DIBUTTON_HOCKEYD_BURST            = 436208643 (&H1A000403)
  DIBUTTON_HOCKEYD_DEVICE           = 436225278 (&H1A0044FE)
  DIBUTTON_HOCKEYD_FAKE             = 436208645 (&H1A000405)
  DIBUTTON_HOCKEYD_FORWARD_LINK     = 436290784 (&H1A0144E0)
  DIBUTTON_HOCKEYD_LEFT_LINK        = 436258020 (&H1A00C4E4)
  DIBUTTON_HOCKEYD_MENU             = 436208893 (&H1A0004FD)
  DIBUTTON_HOCKEYD_PAUSE            = 436225276 (&H1A0044FC)
  DIBUTTON_HOCKEYD_PLAYER           = 436208641 (&H1A000401)
  DIBUTTON_HOCKEYD_RIGHT_LINK       = 436258028 (&H1A00C4EC)
  DIBUTTON_HOCKEYD_STEAL            = 436208642 (&H1A000402)
  DIBUTTON_HOCKEYD_STRATEGY         = 436225031 (&H1A004407)
  DIBUTTON_HOCKEYD_SUBSTITUTE       = 436225033 (&H1A004409)
  DIBUTTON_HOCKEYD_TIMEOUT          = 436225032 (&H1A004408)
  DIBUTTON_HOCKEYD_ZOOM             = 436225030 (&H1A004406)
  DIBUTTON_HOCKEYG_BACK_LINK        = 453068008 (&H1B0144E8)
  DIBUTTON_HOCKEYG_BLOCK            = 452985860 (&H1B000404)
  DIBUTTON_HOCKEYG_DEVICE           = 453002494 (&H1B0044FE)
  DIBUTTON_HOCKEYG_FORWARD_LINK     = 453068000 (&H1B0144E0)
  DIBUTTON_HOCKEYG_LEFT_LINK        = 453035236 (&H1B00C4E4)
  DIBUTTON_HOCKEYG_MENU             = 452986109 (&H1B0004FD)
  DIBUTTON_HOCKEYG_PASS             = 452985857 (&H1B000401)
  DIBUTTON_HOCKEYG_PAUSE            = 453002492 (&H1B0044FC)
  DIBUTTON_HOCKEYG_POKE             = 452985858 (&H1B000402)
  DIBUTTON_HOCKEYG_RIGHT_LINK       = 453035244 (&H1B00C4EC)
  DIBUTTON_HOCKEYG_STEAL            = 452985859 (&H1B000403)
  DIBUTTON_HOCKEYG_STRATEGY         = 453002246 (&H1B004406)
  DIBUTTON_HOCKEYG_SUBSTITUTE       = 453002248 (&H1B004408)
  DIBUTTON_HOCKEYG_TIMEOUT          = 453002247 (&H1B004407)
  DIBUTTON_HOCKEYG_ZOOM             = 453002245 (&H1B004405)
  DIBUTTON_HOCKEYO_BACK_LINK        = 419513576 (&H190144E8)
  DIBUTTON_HOCKEYO_BURST            = 419431427 (&H19000403)
  DIBUTTON_HOCKEYO_DEVICE           = 419448062 (&H190044FE)
  DIBUTTON_HOCKEYO_FAKE             = 419431429 (&H19000405)
  DIBUTTON_HOCKEYO_FORWARD_LINK     = 419513568 (&H190144E0)
  DIBUTTON_HOCKEYO_LEFT_LINK        = 419480804 (&H1900C4E4)
  DIBUTTON_HOCKEYO_MENU             = 419431677 (&H190004FD)
  DIBUTTON_HOCKEYO_PASS             = 419431426 (&H19000402)
  DIBUTTON_HOCKEYO_PAUSE            = 419448060 (&H190044FC)
  DIBUTTON_HOCKEYO_RIGHT_LINK       = 419480812 (&H1900C4EC)
  DIBUTTON_HOCKEYO_SHOOT            = 419431425 (&H19000401)
  DIBUTTON_HOCKEYO_SPECIAL          = 419431428 (&H19000404)
  DIBUTTON_HOCKEYO_STRATEGY         = 419447815 (&H19004407)
  DIBUTTON_HOCKEYO_SUBSTITUTE       = 419447817 (&H19004409)
  DIBUTTON_HOCKEYO_TIMEOUT          = 419447816 (&H19004408)
  DIBUTTON_HOCKEYO_ZOOM             = 419447814 (&H19004406)
  DIBUTTON_HUNTING_AIM              = 218104834 (&H0D000402)
  DIBUTTON_HUNTING_BACK_LINK        = 218186984 (&H0D0144E8)
  DIBUTTON_HUNTING_BINOCULAR        = 218104836 (&H0D000404)
  DIBUTTON_HUNTING_CALL             = 218104837 (&H0D000405)
  DIBUTTON_HUNTING_CROUCH           = 218121225 (&H0D004409)
  DIBUTTON_HUNTING_DEVICE           = 218121470 (&H0D0044FE)
  DIBUTTON_HUNTING_DISPLAY          = 218121224 (&H0D004408)
  DIBUTTON_HUNTING_FIRE             = 218104833 (&H0D000401)
  DIBUTTON_HUNTING_FIRESECONDARY    = 218121227 (&H0D00440B)
  DIBUTTON_HUNTING_FORWARD_LINK     = 218186976 (&H0D0144E0)
  DIBUTTON_HUNTING_JUMP             = 218121226 (&H0D00440A)
  DIBUTTON_HUNTING_LEFT_LINK        = 218154212 (&H0D00C4E4)
  DIBUTTON_HUNTING_MAP              = 218104838 (&H0D000406)
  DIBUTTON_HUNTING_MENU             = 218105085 (&H0D0004FD)
  DIBUTTON_HUNTING_PAUSE            = 218121468 (&H0D0044FC)
  DIBUTTON_HUNTING_RIGHT_LINK       = 218154220 (&H0D00C4EC)
  DIBUTTON_HUNTING_ROTATE_LEFT_LINK = 218252516 (&H0D0244E4)
  DIBUTTON_HUNTING_ROTATE_RIGHT_LINK= 218252524 (&H0D0244EC)
  DIBUTTON_HUNTING_SPECIAL          = 218104839 (&H0D000407)
  DIBUTTON_HUNTING_WEAPON           = 218104835 (&H0D000403)
  DIBUTTON_MECHA_BACK_LINK          = 687949032 (&H290144E8)
  DIBUTTON_MECHA_CENTER             = 687883271 (&H29004407)
  DIBUTTON_MECHA_DEVICE             = 687883518 (&H290044FE)
  DIBUTTON_MECHA_FASTER_LINK        = 688112864 (&H2903C4E0)
  DIBUTTON_MECHA_FIRE               = 687866881 (&H29000401)
  DIBUTTON_MECHA_FIRESECONDARY      = 687883273 (&H29004409)
  DIBUTTON_MECHA_FORWARD_LINK       = 687949024 (&H290144E0)
  DIBUTTON_MECHA_JUMP               = 687866886 (&H29000406)
  DIBUTTON_MECHA_LEFT_LINK          = 687916260 (&H2900C4E4)
  DIBUTTON_MECHA_MENU               = 687867133 (&H290004FD)
  DIBUTTON_MECHA_PAUSE              = 687883516 (&H290044FC)
  DIBUTTON_MECHA_REVERSE            = 687866884 (&H29000404)
  DIBUTTON_MECHA_RIGHT_LINK         = 687916268 (&H2900C4EC)
  DIBUTTON_MECHA_ROTATE_LEFT_LINK   = 688014564 (&H290244E4)
  DIBUTTON_MECHA_ROTATE_RIGHT_LINK  = 688014572 (&H290244EC)
  DIBUTTON_MECHA_SLOWER_LINK        = 688112872 (&H2903C4E8)
  DIBUTTON_MECHA_TARGET             = 687866883 (&H29000403)
  DIBUTTON_MECHA_VIEW               = 687883272 (&H29004408)
  DIBUTTON_MECHA_WEAPONS            = 687866882 (&H29000402)
  DIBUTTON_MECHA_ZOOM               = 687866885 (&H29000405)
  DIBUTTON_RACQUET_BACK_LINK        = 536954088 (&H200144E8)
  DIBUTTON_RACQUET_BACKSWING        = 536871938 (&H20000402)
  DIBUTTON_RACQUET_DEVICE           = 536888574 (&H200044FE)
  DIBUTTON_RACQUET_FORWARD_LINK     = 536954080 (&H200144E0)
  DIBUTTON_RACQUET_LEFT_LINK        = 536921316 (&H2000C4E4)
  DIBUTTON_RACQUET_MENU             = 536872189 (&H200004FD)
  DIBUTTON_RACQUET_PAUSE            = 536888572 (&H200044FC)
  DIBUTTON_RACQUET_RIGHT_LINK       = 536921324 (&H2000C4EC)
  DIBUTTON_RACQUET_SELECT           = 536871941 (&H20000405)
  DIBUTTON_RACQUET_SMASH            = 536871939 (&H20000403)
  DIBUTTON_RACQUET_SPECIAL          = 536871940 (&H20000404)
  DIBUTTON_RACQUET_SUBSTITUTE       = 536888327 (&H20004407)
  DIBUTTON_RACQUET_SWING            = 536871937 (&H20000401)
  DIBUTTON_RACQUET_TIMEOUT          = 536888326 (&H20004406)
  DIBUTTON_REMOTE_ADJUST            = 654334990 (&H27005C0E)
  DIBUTTON_REMOTE_CABLE             = 654334985 (&H27005C09)
  DIBUTTON_REMOTE_CD                = 654334986 (&H27005C0A)
  DIBUTTON_REMOTE_CHANGE            = 654320646 (&H27002406)
  DIBUTTON_REMOTE_CUE               = 654320644 (&H27002404)
  DIBUTTON_REMOTE_DEVICE            = 654329086 (&H270044FE)
  DIBUTTON_REMOTE_DIGIT0            = 654332943 (&H2700540F)
  DIBUTTON_REMOTE_DIGIT1            = 654332944 (&H27005410)
  DIBUTTON_REMOTE_DIGIT2            = 654332945 (&H27005411)
  DIBUTTON_REMOTE_DIGIT3            = 654332946 (&H27005412)
  DIBUTTON_REMOTE_DIGIT4            = 654332947 (&H27005413)
  DIBUTTON_REMOTE_DIGIT5            = 654332948 (&H27005414)
  DIBUTTON_REMOTE_DIGIT6            = 654332949 (&H27005415)
  DIBUTTON_REMOTE_DIGIT7            = 654332950 (&H27005416)
  DIBUTTON_REMOTE_DIGIT8            = 654332951 (&H27005417)
  DIBUTTON_REMOTE_DIGIT9            = 654332952 (&H27005418)
  DIBUTTON_REMOTE_DVD               = 654334989 (&H27005C0D)
  DIBUTTON_REMOTE_MENU              = 654312701 (&H270004FD)
  DIBUTTON_REMOTE_MUTE              = 654312449 (&H27000401)
  DIBUTTON_REMOTE_PAUSE             = 654329084 (&H270044FC)
  DIBUTTON_REMOTE_PLAY              = 654320643 (&H27002403)
  DIBUTTON_REMOTE_RECORD            = 654320647 (&H27002407)
  DIBUTTON_REMOTE_REVIEW            = 654320645 (&H27002405)
  DIBUTTON_REMOTE_SELECT            = 654312450 (&H27000402)
  DIBUTTON_REMOTE_TUNER             = 654334988 (&H27005C0C)
  DIBUTTON_REMOTE_TV                = 654334984 (&H27005C08)
  DIBUTTON_REMOTE_VCR               = 654334987 (&H27005C0B)
  DIBUTTON_SKIING_CAMERA            = 486540291 (&H1D000403)
  DIBUTTON_SKIING_CROUCH            = 486540290 (&H1D000402)
  DIBUTTON_SKIING_DEVICE            = 486556926 (&H1D0044FE)
  DIBUTTON_SKIING_FASTER_LINK       = 486622432 (&H1D0144E0)
  DIBUTTON_SKIING_JUMP              = 486540289 (&H1D000401)
  DIBUTTON_SKIING_LEFT_LINK         = 486589668 (&H1D00C4E4)
  DIBUTTON_SKIING_MENU              = 486540541 (&H1D0004FD)
  DIBUTTON_SKIING_PAUSE             = 486556924 (&H1D0044FC)
  DIBUTTON_SKIING_RIGHT_LINK        = 486589676 (&H1D00C4EC)
  DIBUTTON_SKIING_SELECT            = 486540293 (&H1D000405)
  DIBUTTON_SKIING_SLOWER_LINK       = 486622440 (&H1D0144E8)
  DIBUTTON_SKIING_SPECIAL1          = 486540292 (&H1D000404)
  DIBUTTON_SKIING_SPECIAL2          = 486540294 (&H1D000406)
  DIBUTTON_SKIING_ZOOM              = 486556679 (&H1D004407)
  DIBUTTON_SOCCERD_BACK_LINK        = 520176872 (&H1F0144E8)
  DIBUTTON_SOCCERD_BLOCK            = 520094721 (&H1F000401)
  DIBUTTON_SOCCERD_CLEAR            = 520111114 (&H1F00440A)
  DIBUTTON_SOCCERD_DEVICE           = 520111358 (&H1F0044FE)
  DIBUTTON_SOCCERD_FAKE             = 520094723 (&H1F000403)
  DIBUTTON_SOCCERD_FORWARD_LINK     = 520176864 (&H1F0144E0)
  DIBUTTON_SOCCERD_FOUL             = 520111112 (&H1F004408)
  DIBUTTON_SOCCERD_GOALIECHARGE     = 520111115 (&H1F00440B)
  DIBUTTON_SOCCERD_HEAD             = 520111113 (&H1F004409)
  DIBUTTON_SOCCERD_LEFT_LINK        = 520144100 (&H1F00C4E4)
  DIBUTTON_SOCCERD_MENU             = 520094973 (&H1F0004FD)
  DIBUTTON_SOCCERD_PAUSE            = 520111356 (&H1F0044FC)
  DIBUTTON_SOCCERD_PLAYER           = 520094724 (&H1F000404)
  DIBUTTON_SOCCERD_RIGHT_LINK       = 520144108 (&H1F00C4EC)
  DIBUTTON_SOCCERD_SELECT           = 520094726 (&H1F000406)
  DIBUTTON_SOCCERD_SLIDE            = 520094727 (&H1F000407)
  DIBUTTON_SOCCERD_SPECIAL          = 520094725 (&H1F000405)
  DIBUTTON_SOCCERD_STEAL            = 520094722 (&H1F000402)
  DIBUTTON_SOCCERD_SUBSTITUTE       = 520111116 (&H1F00440C)
  DIBUTTON_SOCCERO_BACK_LINK        = 503399656 (&H1E0144E8)
  DIBUTTON_SOCCERO_CONTROL          = 503333900 (&H1E00440C)
  DIBUTTON_SOCCERO_DEVICE           = 503334142 (&H1E0044FE)
  DIBUTTON_SOCCERO_FAKE             = 503317507 (&H1E000403)
  DIBUTTON_SOCCERO_FORWARD_LINK     = 503399648 (&H1E0144E0)
  DIBUTTON_SOCCERO_HEAD             = 503333901 (&H1E00440D)
  DIBUTTON_SOCCERO_LEFT_LINK        = 503366884 (&H1E00C4E4)
  DIBUTTON_SOCCERO_MENU             = 503317757 (&H1E0004FD)
  DIBUTTON_SOCCERO_PASS             = 503317506 (&H1E000402)
  DIBUTTON_SOCCERO_PASSTHRU         = 503333898 (&H1E00440A)
  DIBUTTON_SOCCERO_PAUSE            = 503334140 (&H1E0044FC)
  DIBUTTON_SOCCERO_PLAYER           = 503317508 (&H1E000404)
  DIBUTTON_SOCCERO_RIGHT_LINK       = 503366892 (&H1E00C4EC)
  DIBUTTON_SOCCERO_SELECT           = 503317510 (&H1E000406)
  DIBUTTON_SOCCERO_SHOOT            = 503317505 (&H1E000401)
  DIBUTTON_SOCCERO_SHOOTHIGH        = 503333897 (&H1E004409)
  DIBUTTON_SOCCERO_SHOOTLOW         = 503333896 (&H1E004408)
  DIBUTTON_SOCCERO_SPECIAL1         = 503317509 (&H1E000405)
  DIBUTTON_SOCCERO_SPRINT           = 503333899 (&H1E00440B)
  DIBUTTON_SOCCERO_SUBSTITUTE       = 503333895 (&H1E004407)
  DIBUTTON_SPACESIM_BACKWARD_LINK   = 117523688 (&H070144E8)
  DIBUTTON_SPACESIM_DEVICE          = 117458174 (&H070044FE)
  DIBUTTON_SPACESIM_DISPLAY         = 117457925 (&H07004405)
  DIBUTTON_SPACESIM_FASTER_LINK     = 117687520 (&H0703C4E0)
  DIBUTTON_SPACESIM_FIRE            = 117441537 (&H07000401)
  DIBUTTON_SPACESIM_FIRESECONDARY   = 117457929 (&H07004409)
  DIBUTTON_SPACESIM_FORWARD_LINK    = 117523680 (&H070144E0)
  DIBUTTON_SPACESIM_GEAR            = 117457928 (&H07004408)
  DIBUTTON_SPACESIM_GLANCE_DOWN_LINK= 117949672 (&H0707C4E8)
  DIBUTTON_SPACESIM_GLANCE_LEFT_LINK= 117949668 (&H0707C4E4)
  DIBUTTON_SPACESIM_GLANCE_RIGHT_LINK=117949676 (&H0707C4EC)
  DIBUTTON_SPACESIM_GLANCE_UP_LINK  = 117949664 (&H0707C4E0)
  DIBUTTON_SPACESIM_LEFT_LINK       = 117490916 (&H0700C4E4)
  DIBUTTON_SPACESIM_LOWER           = 117457927 (&H07004407)
  DIBUTTON_SPACESIM_MENU            = 117441789 (&H070004FD)
  DIBUTTON_SPACESIM_PAUSE           = 117458172 (&H070044FC)
  DIBUTTON_SPACESIM_RAISE           = 117457926 (&H07004406)
  DIBUTTON_SPACESIM_RIGHT_LINK      = 117490924 (&H0700C4EC)
  DIBUTTON_SPACESIM_SLOWER_LINK     = 117687528 (&H0703C4E8)
  DIBUTTON_SPACESIM_TARGET          = 117441539 (&H07000403)
  DIBUTTON_SPACESIM_TURN_LEFT_LINK  = 117589220 (&H070244E4)
  DIBUTTON_SPACESIM_TURN_RIGHT_LINK = 117589228 (&H070244EC)
  DIBUTTON_SPACESIM_VIEW            = 117457924 (&H07004404)
  DIBUTTON_SPACESIM_WEAPONS         = 117441538 (&H07000402)
  DIBUTTON_STRATEGYR_APPLY          = 184550402 (&H0B000402)
  DIBUTTON_STRATEGYR_ATTACK         = 184550404 (&H0B000404)
  DIBUTTON_STRATEGYR_BACK_LINK      = 184632552 (&H0B0144E8)
  DIBUTTON_STRATEGYR_CAST           = 184550405 (&H0B000405)
  DIBUTTON_STRATEGYR_CROUCH         = 184550406 (&H0B000406)
  DIBUTTON_STRATEGYR_DEVICE         = 184567038 (&H0B0044FE)
  DIBUTTON_STRATEGYR_DISPLAY        = 184566793 (&H0B004409)
  DIBUTTON_STRATEGYR_FORWARD_LINK   = 184632544 (&H0B0144E0)
  DIBUTTON_STRATEGYR_GET            = 184550401 (&H0B000401)
  DIBUTTON_STRATEGYR_JUMP           = 184550407 (&H0B000407)
  DIBUTTON_STRATEGYR_LEFT_LINK      = 184599780 (&H0B00C4E4)
  DIBUTTON_STRATEGYR_MAP            = 184566792 (&H0B004408)
  DIBUTTON_STRATEGYR_MENU           = 184550653 (&H0B0004FD)
  DIBUTTON_STRATEGYR_PAUSE          = 184567036 (&H0B0044FC)
  DIBUTTON_STRATEGYR_RIGHT_LINK     = 184599788 (&H0B00C4EC)
  DIBUTTON_STRATEGYR_ROTATE_LEFT_LINK=184698084 (&H0B0244E4)
  DIBUTTON_STRATEGYR_ROTATE_RIGHT_LINK=184698092 (&HB0244EC)
  DIBUTTON_STRATEGYR_SELECT         = 184550403 (&H0B000403)
  DIBUTTON_STRATEGYT_APPLY          = 201327619 (&H0C000403)
  DIBUTTON_STRATEGYT_BACK_LINK      = 201409768 (&H0C0144E8)
  DIBUTTON_STRATEGYT_DEVICE         = 201344254 (&H0C0044FE)
  DIBUTTON_STRATEGYT_DISPLAY        = 201344008 (&H0C004408)
  DIBUTTON_STRATEGYT_FORWARD_LINK   = 201409760 (&H0C0144E0)
  DIBUTTON_STRATEGYT_INSTRUCT       = 201327618 (&H0C000402)
  DIBUTTON_STRATEGYT_LEFT_LINK      = 201376996 (&H0C00C4E4)
  DIBUTTON_STRATEGYT_MAP            = 201344007 (&H0C004407)
  DIBUTTON_STRATEGYT_MENU           = 201327869 (&H0C0004FD)
  DIBUTTON_STRATEGYT_PAUSE          = 201344252 (&H0C0044FC)
  DIBUTTON_STRATEGYT_RIGHT_LINK     = 201377004 (&H0C00C4EC)
  DIBUTTON_STRATEGYT_SELECT         = 201327617 (&H0C000401)
  DIBUTTON_STRATEGYT_TEAM           = 201327620 (&H0C000404)
  DIBUTTON_STRATEGYT_TURN           = 201327621 (&H0C000405)
  DIBUTTON_STRATEGYT_ZOOM           = 201344006 (&H0C004406)
  DIBUTTON_TPS_ACTION               = 167773186 (&H0A000402)
  DIBUTTON_TPS_BACKWARD_LINK        = 167855336 (&H0A0144E8)
  DIBUTTON_TPS_DEVICE               = 167789822 (&H0A0044FE)
  DIBUTTON_TPS_DODGE                = 167789577 (&H0A004409)
  DIBUTTON_TPS_FORWARD_LINK         = 167855328 (&H0A0144E0)
  DIBUTTON_TPS_GLANCE_DOWN_LINK     = 168281320 (&H0A07C4E8)
  DIBUTTON_TPS_GLANCE_LEFT_LINK     = 168281316 (&H0A07C4E4)
  DIBUTTON_TPS_GLANCE_RIGHT_LINK    = 168281324 (&H0A07C4EC)
  DIBUTTON_TPS_GLANCE_UP_LINK       = 168281312 (&H0A07C4E0)
  DIBUTTON_TPS_INVENTORY            = 167789578 (&H0A00440A)
  DIBUTTON_TPS_JUMP                 = 167773189 (&H0A000405)
  DIBUTTON_TPS_MENU                 = 167773437 (&H0A0004FD)
  DIBUTTON_TPS_PAUSE                = 167789820 (&H0A0044FC)
  DIBUTTON_TPS_RUN                  = 167773185 (&H0A000401)
  DIBUTTON_TPS_SELECT               = 167773187 (&H0A000403)
  DIBUTTON_TPS_STEPLEFT             = 167789575 (&H0A004407)
  DIBUTTON_TPS_STEPRIGHT            = 167789576 (&H0A004408)
  DIBUTTON_TPS_TURN_LEFT_LINK       = 167920868 (&H0A0244E4)
  DIBUTTON_TPS_TURN_RIGHT_LINK      = 167920876 (&H0A0244EC)
  DIBUTTON_TPS_USE                  = 167773188 (&H0A000404)
  DIBUTTON_TPS_VIEW                 = 167789574 (&H0A004406)
  DIHATSWITCH_2DCONTROL_HATSWITCH   = 587220481 (&H23004601)
  DIHATSWITCH_3DCONTROL_HATSWITCH   = 603997697 (&H24004601)
  DIHATSWITCH_ARCADEP_VIEW          = 570443265 (&H22004601)
  DIHATSWITCH_ARCADES_VIEW          = 553666049 (&H21004601)
  DIHATSWITCH_BBALLD_GLANCE         = 318785025 (&H13004601)
  DIHATSWITCH_BBALLO_GLANCE         = 302007809 (&H12004601)
  DIHATSWITCH_BIKINGM_SCROLL        = 469779969 (&H1C004601)
  DIHATSWITCH_CADF_HATSWITCH        = 620774913 (&H25004601)
  DIHATSWITCH_CADM_HATSWITCH        = 637552129 (&H26004601)
  DIHATSWITCH_DRIVINGC_GLANCE       =  33572353 (&H02004601)
  DIHATSWITCH_DRIVINGR_GLANCE       =  16795137 (&H01004601)
  DIHATSWITCH_DRIVINGT_GLANCE       =  50349569 (&H03004601)
  DIHATSWITCH_FIGHTINGH_SLIDE       = 134235649 (&H08004601)
  DIHATSWITCH_FISHING_GLANCE        = 234898945 (&H0E004601)
  DIHATSWITCH_FLYINGC_GLANCE        =  67126785 (&H04004601)
  DIHATSWITCH_FLYINGH_GLANCE        = 100681217 (&H06004601)
  DIHATSWITCH_FLYINGM_GLANCE        =  83904001 (&H05004601)
  DIHATSWITCH_FPS_GLANCE            = 151012865 (&H09004601)
  DIHATSWITCH_GOLF_SCROLL           = 402671105 (&H18004601)
  DIHATSWITCH_HOCKEYD_SCROLL        = 436225537 (&H1A004601)
  DIHATSWITCH_HOCKEYG_SCROLL        = 453002753 (&H1B004601)
  DIHATSWITCH_HOCKEYO_SCROLL        = 419448321 (&H19004601)
  DIHATSWITCH_HUNTING_GLANCE        = 218121729 (&H0D004601)
  DIHATSWITCH_MECHA_GLANCE          = 687883777 (&H29004601)
  DIHATSWITCH_RACQUET_GLANCE        = 536888833 (&H20004601)
  DIHATSWITCH_SKIING_GLANCE         = 486557185 (&H1D004601)
  DIHATSWITCH_SOCCERD_GLANCE        = 520111617 (&H1F004601)
  DIHATSWITCH_SOCCERO_GLANCE        = 503334401 (&H1E004601)
  DIHATSWITCH_SPACESIM_GLANCE       = 117458433 (&H07004601)
  DIHATSWITCH_STRATEGYR_GLANCE      = 184567297 (&H0B004601)
  DIHATSWITCH_TPS_GLANCE            = 167790081 (&H0A004601)
  DIVIRTUAL_ARCADE_PLATFORM         = 570425344 (&H22000000)
  DIVIRTUAL_ARCADE_SIDE2SIDE        = 553648128 (&H21000000)
  DIVIRTUAL_BROWSER_CONTROL         = 671088640 (&H28000000)
  DIVIRTUAL_CAD_2DCONTROL           = 587202560 (&H23000000)
  DIVIRTUAL_CAD_3DCONTROL           = 603979776 (&H24000000)
  DIVIRTUAL_CAD_FLYBY               = 620756992 (&H25000000)
  DIVIRTUAL_CAD_MODEL               = 637534208 (&H26000000)
  DIVIRTUAL_DRIVING_COMBAT          =  33554432 (&H02000000)
  DIVIRTUAL_DRIVING_MECHA           = 687865856 (&H29000000)
  DIVIRTUAL_DRIVING_RACE            =  16777216 (&H01000000)
  DIVIRTUAL_DRIVING_TANK            =  50331648 (&H03000000)
  DIVIRTUAL_FIGHTING_FPS            = 150994944 (&H09000000)
  DIVIRTUAL_FIGHTING_HAND2HAND      = 134217728 (&H08000000)
  DIVIRTUAL_FIGHTING_THIRDPERSON    = 167772160 (&H0A000000)
  DIVIRTUAL_FLYING_CIVILIAN         =  67108864 (&H04000000)
  DIVIRTUAL_FLYING_HELICOPTER       = 100663296 (&H06000000)
  DIVIRTUAL_FLYING_MILITARY         =  83886080 (&H05000000)
  DIVIRTUAL_REMOTE_CONTROL          = 654311424 (&H27000000)
  DIVIRTUAL_SPACESIM                = 117440512 (&H07000000)
  DIVIRTUAL_SPORTS_BASEBALL_BAT     = 251658240 (&H0F000000)
  DIVIRTUAL_SPORTS_BASEBALL_FIELD   = 285212672 (&H11000000)
  DIVIRTUAL_SPORTS_BASEBALL_PITCH   = 268435456 (&H10000000)
  DIVIRTUAL_SPORTS_BASKETBALL_DEFENSE=318767104 (&H13000000)
  DIVIRTUAL_SPORTS_BASKETBALL_OFFENSE=301989888 (&H12000000)
  DIVIRTUAL_SPORTS_BIKING_MOUNTAIN  = 469762048 (&H1C000000)
  DIVIRTUAL_SPORTS_FISHING          = 234881024 (&H0E000000)
  DIVIRTUAL_SPORTS_FOOTBALL_DEFENSE = 385875968 (&H17000000)
  DIVIRTUAL_SPORTS_FOOTBALL_FIELD   = 335544320 (&H14000000)
  DIVIRTUAL_SPORTS_FOOTBALL_OFFENSE = 369098752 (&H16000000)
  DIVIRTUAL_SPORTS_FOOTBALL_QBCK    = 352321536 (&H15000000)
  DIVIRTUAL_SPORTS_GOLF             = 402653184 (&H18000000)
  DIVIRTUAL_SPORTS_HOCKEY_DEFENSE   = 436207616 (&H1A000000)
  DIVIRTUAL_SPORTS_HOCKEY_GOALIE    = 452984832 (&H1B000000)
  DIVIRTUAL_SPORTS_HOCKEY_OFFENSE   = 419430400 (&H19000000)
  DIVIRTUAL_SPORTS_HUNTING          = 218103808 (&H0D000000)
  DIVIRTUAL_SPORTS_RACQUET          = 536870912 (&H20000000)
  DIVIRTUAL_SPORTS_SKIING           = 486539264 (&H1D000000)
  DIVIRTUAL_SPORTS_SOCCER_DEFENSE   = 520093696 (&H1F000000)
  DIVIRTUAL_SPORTS_SOCCER_OFFENSE   = 503316480 (&H1E000000)
  DIVIRTUAL_STRATEGY_ROLEPLAYING    = 184549376 (&H0B000000)
  DIVIRTUAL_STRATEGY_TURN           = 201326592 (&H0C000000)
End Enum


CONST_DIGFFSFLAGS

Members of this enumeration describe the state of a force-feedback device. They are returned by the DirectInputDevice8.GetForceFeedbackState method.

Enum CONST_DIGFFSFLAGS
    DIGFFS_ACTUATORSOFF    =          32 (&H20)
    DIGFFS_ACTUATORSON     =          16 (&H10)
    DIGFFS_DEVICELOST      = -2147483648 (&H80000000)
    DIGFFS_EMPTY           =           1
    DIGFFS_PAUSED          =           4
    DIGFFS_POWEROFF        =         128 (&H80)
    DIGFFS_POWERON         =          64 (&H40)
    DIGFFS_SAFETYSWITCHOFF =         512 (&H200)
    DIGFFS_SAFETYSWITCHON  =         256 (&H100)
    DIGFFS_STOPPED         =           2
    DIGFFS_USERFFSWITCHOFF =        2048 (&H800)
    DIGFFS_USERFFSWITCHON  =        1024 (&H400)
End Enum

Constants

DIGFFS_ACTUATORSOFF
The device's force-feedback actuators are disabled.
DIGFFS_ACTUATORSON
The device's force-feedback actuators are enabled.
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, then neither DIGFFS_POWERON nor DIGFFS_POWEROFF will be returned.
DIGFFS_POWERON
Power to the force-feedback system is currently available. If the device cannot report the power state, then neither DIGFFS_POWERON nor DIGFFS_POWEROFF will be returned.
DIGFFS_SAFETYSWITCHOFF
The safety switch is currently off, meaning that the device cannot operate. If the device cannot report the state of the safety switch, then neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF will be returned.
DIGFFS_SAFETYSWITCHON
The safety switch is currently on, meaning that the device can operate. If the device cannot report the state of the safety switch, then neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF will be returned.
DIGFFS_STOPPED
No effects are playing and the device is not paused.
DIGFFS_USERFFSWITCHOFF
The user force-feedback switch is currently off, meaning that the device cannot operate. If the device cannot report the state of the user force-feedback switch, then neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF will be returned.
DIGFFS_USERFFSWITCHON
The user force-feedback switch is currently on, meaning that the device can operate. If the device cannot report the state of the user force-feedback switch, then neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF will be returned.


CONST_DIJOYSTICKOFS

Used to identify device objects in joystick data. The values of the constants are the offset of the data within the data format for immediate data. The same identifiers are used in buffered data packets.

Enum CONST_DIJOYSTICKOFS
    DIJOFS_BUTTON0  = 48 (&H30)
    DIJOFS_BUTTON1  = 49 (&H31)
    DIJOFS_BUTTON2  = 50 (&H32)
    DIJOFS_BUTTON3  = 51 (&H33)
    DIJOFS_BUTTON4  = 52 (&H34)
    DIJOFS_BUTTON5  = 53 (&H35)
    DIJOFS_BUTTON6  = 54 (&H36)
    DIJOFS_BUTTON7  = 55 (&H37)
    DIJOFS_BUTTON8  = 56 (&H38)
    DIJOFS_BUTTON9  = 57 (&H39)
    DIJOFS_BUTTON10 = 58 (&H3A)
    DIJOFS_BUTTON11 = 59 (&H3B)
    DIJOFS_BUTTON12 = 60 (&H3C)
    DIJOFS_BUTTON13 = 61 (&H3D)
    DIJOFS_BUTTON14 = 62 (&H3E)
    DIJOFS_BUTTON15 = 63 (&H3F)
    DIJOFS_BUTTON16 = 64 (&H40)
    DIJOFS_BUTTON17 = 65 (&H41)
    DIJOFS_BUTTON18 = 66 (&H42)
    DIJOFS_BUTTON19 = 67 (&H43)
    DIJOFS_BUTTON20 = 68 (&H44)
    DIJOFS_BUTTON21 = 69 (&H45)
    DIJOFS_BUTTON22 = 70 (&H46)
    DIJOFS_BUTTON23 = 71 (&H47)
    DIJOFS_BUTTON24 = 72 (&H48)
    DIJOFS_BUTTON25 = 73 (&H49)
    DIJOFS_BUTTON26 = 74 (&H4A)
    DIJOFS_BUTTON27 = 75 (&H4B)
    DIJOFS_BUTTON28 = 76 (&H4C)
    DIJOFS_BUTTON29 = 77 (&H4D)
    DIJOFS_BUTTON30 = 78 (&H4E)
    DIJOFS_BUTTON31 = 79 (&H4F)
    DIJOFS_POV0     = 32 (&H20)
    DIJOFS_POV1     = 36 (&H24)
    DIJOFS_POV2     = 40 (&H28)
    DIJOFS_POV3     = 44 (&H2C)
    DIJOFS_RX       = 12
    DIJOFS_RY       = 16 (&H10)
    DIJOFS_RZ       = 20 (&H14)
    DIJOFS_SLIDER0  = 24 (&H18)
    DIJOFS_SLIDER1  = 28 (&H1C)
    DIJOFS_X        =  0
    DIJOFS_Y        =  4
    DIJOFS_Z        =  8
End Enum

Constants

DIJOFS_BUTTON(n)
Offset of the data for button n.
DIJOFS_POV0, DIJOFS_POV1, DIJOFS_POV2, DIJOFS_POV3
Offset of the data for the point-of-view controller.
DIJOFS_RX, DIJOFS_RY, DIJOFS_RZ
Offset of the data for the axis rotation.
DIJOFS_SLIDER0, DIJOFS_SLIDER1
Offset of the data for the slider.
DIJOFS_X, DIJOFS_Y, DIJOFS_Z
Offset of the data for the axis.


CONST_DIKEYBOARDFLAGS

Used to specify keys in the lSemantic member of the DIACTION type.

Enum CONST_DIKEYBOARDFLAGS
    DIKEYBOARD_0            = -2130705397 (&H8100040B)
    DIKEYBOARD_1            = -2130705406 (&H81000402)
    DIKEYBOARD_2            = -2130705405 (&H81000403)
    DIKEYBOARD_3            = -2130705404 (&H81000404)
    DIKEYBOARD_4            = -2130705403 (&H81000405)
    DIKEYBOARD_5            = -2130705402 (&H81000406)
    DIKEYBOARD_6            = -2130705401 (&H81000407)
    DIKEYBOARD_7            = -2130705400 (&H81000408)
    DIKEYBOARD_8            = -2130705399 (&H81000409)
    DIKEYBOARD_9            = -2130705398 (&H8100040A)
    DIKEYBOARD_A            = -2130705378 (&H8100041E)
    DIKEYBOARD_ABNT_C1      = -2130705293 (&H81000473)
    DIKEYBOARD_ABNT_C2      = -2130705282 (&H8100047E)
    DIKEYBOARD_ADD          = -2130705330 (&H8100044E)
    DIKEYBOARD_APOSTROPHE   = -2130705368 (&H81000428)
    DIKEYBOARD_APPS         = -2130705187 (&H810004DD)
    DIKEYBOARD_AT           = -2130705263 (&H81000491)
    DIKEYBOARD_AX           = -2130705258 (&H81000496)
    DIKEYBOARD_B            = -2130705360 (&H81000430)
    DIKEYBOARD_BACK         = -2130705394 (&H8100040E)
    DIKEYBOARD_BACKSLASH    = -2130705365 (&H8100042B)
    DIKEYBOARD_C            = -2130705362 (&H8100042E)
    DIKEYBOARD_CALCULATOR   = -2130705247 (&H810004A1)
    DIKEYBOARD_CAPITAL      = -2130705350 (&H8100043A)
    DIKEYBOARD_COLON        = -2130705262 (&H81000492)
    DIKEYBOARD_COMMA        = -2130705357 (&H81000433)
    DIKEYBOARD_CONVERT      = -2130705287 (&H81000479)
    DIKEYBOARD_D            = -2130705376 (&H81000420)
    DIKEYBOARD_DECIMAL      = -2130705325 (&H81000453)
    DIKEYBOARD_DELETE       = -2130705197 (&H810004D3)
    DIKEYBOARD_DIVIDE       = -2130705227 (&H810004B5)
    DIKEYBOARD_DOWN         = -2130705200 (&H810004D0)
    DIKEYBOARD_E            = -2130705390 (&H81000412)
    DIKEYBOARD_END          = -2130705201 (&H810004CF)
    DIKEYBOARD_EQUALS       = -2130705395 (&H8100040D)
    DIKEYBOARD_ESCAPE       = -2130705407 (&H81000401)
    DIKEYBOARD_F            = -2130705375 (&H81000421)
    DIKEYBOARD_F1           = -2130705349 (&H8100043B)
    DIKEYBOARD_F2           = -2130705348 (&H8100043C)
    DIKEYBOARD_F3           = -2130705347 (&H8100043D)
    DIKEYBOARD_F4           = -2130705346 (&H8100043E)
    DIKEYBOARD_F5           = -2130705345 (&H8100043F)
    DIKEYBOARD_F6           = -2130705344 (&H81000440)
    DIKEYBOARD_F7           = -2130705343 (&H81000441)
    DIKEYBOARD_F8           = -2130705342 (&H81000442)
    DIKEYBOARD_F9           = -2130705341 (&H81000443)
    DIKEYBOARD_F10          = -2130705340 (&H81000444)
    DIKEYBOARD_F11          = -2130705321 (&H81000457)
    DIKEYBOARD_F12          = -2130705320 (&H81000458)
    DIKEYBOARD_F13          = -2130705308 (&H81000464)
    DIKEYBOARD_F14          = -2130705307 (&H81000465)
    DIKEYBOARD_F15          = -2130705306 (&H81000466)
    DIKEYBOARD_G            = -2130705374 (&H81000422)
    DIKEYBOARD_GRAVE        = -2130705367 (&H81000429)
    DIKEYBOARD_H            = -2130705373 (&H81000423)
    DIKEYBOARD_HOME         = -2130705209 (&H810004C7)
    DIKEYBOARD_I            = -2130705385 (&H81000417)
    DIKEYBOARD_INSERT       = -2130705198 (&H810004D2)
    DIKEYBOARD_J            = -2130705372 (&H81000424)
    DIKEYBOARD_K            = -2130705371 (&H81000425)
    DIKEYBOARD_KANA         = -2130705296 (&H81000470)
    DIKEYBOARD_KANJI        = -2130705260 (&H81000494)
    DIKEYBOARD_L            = -2130705370 (&H81000426)
    DIKEYBOARD_LBRACKET     = -2130705382 (&H8100041A)
    DIKEYBOARD_LCONTROL     = -2130705379 (&H8100041D)
    DIKEYBOARD_LEFT         = -2130705205 (&H810004CB)
    DIKEYBOARD_LMENU        = -2130705352 (&H81000438)
    DIKEYBOARD_LSHIFT       = -2130705366 (&H8100042A)
    DIKEYBOARD_LWIN         = -2130705189 (&H810004DB)
    DIKEYBOARD_M            = -2130705358 (&H81000432)
    DIKEYBOARD_MAIL         = -2130705172 (&H810004EC)
    DIKEYBOARD_MEDIASELECT  = -2130705171 (&H810004ED)
    DIKEYBOARD_MEDIASTOP    = -2130705244 (&H810004A4)
    DIKEYBOARD_MINUS        = -2130705396 (&H8100040C)
    DIKEYBOARD_MULTIPLY     = -2130705353 (&H81000437)
    DIKEYBOARD_MUTE         = -2130705248 (&H810004A0)
    DIKEYBOARD_MYCOMPUTER   = -2130705173 (&H810004EB)
    DIKEYBOARD_N            = -2130705359 (&H81000431)
    DIKEYBOARD_NEXT         = -2130705199 (&H810004D1)
    DIKEYBOARD_NEXTTRACK    = -2130705255 (&H81000499)
    DIKEYBOARD_NOCONVERT    = -2130705285 (&H8100047B)
    DIKEYBOARD_NUMLOCK      = -2130705339 (&H81000445)
    DIKEYBOARD_NUMPAD0      = -2130705326 (&H81000452)
    DIKEYBOARD_NUMPAD1      = -2130705329 (&H8100044F)
    DIKEYBOARD_NUMPAD2      = -2130705328 (&H81000450)
    DIKEYBOARD_NUMPAD3      = -2130705327 (&H81000451)
    DIKEYBOARD_NUMPAD4      = -2130705333 (&H8100044B)
    DIKEYBOARD_NUMPAD5      = -2130705332 (&H8100044C)
    DIKEYBOARD_NUMPAD6      = -2130705331 (&H8100044D)
    DIKEYBOARD_NUMPAD7      = -2130705337 (&H81000447)
    DIKEYBOARD_NUMPAD8      = -2130705336 (&H81000448)
    DIKEYBOARD_NUMPAD9      = -2130705335 (&H81000449)
    DIKEYBOARD_NUMPADCOMMA  = -2130705229 (&H810004B3)
    DIKEYBOARD_NUMPADENTER  = -2130705252 (&H8100049C)
    DIKEYBOARD_NUMPADEQUALS = -2130705267 (&H8100048D)
    DIKEYBOARD_O            = -2130705384 (&H81000418)
    DIKEYBOARD_OEM_102      = -2130705322 (&H81000456)
    DIKEYBOARD_P            = -2130705383 (&H81000419)
    DIKEYBOARD_PAUSE        = -2130705211 (&H810004C5)
    DIKEYBOARD_PERIOD       = -2130705356 (&H81000434)
    DIKEYBOARD_PLAYPAUSE    = -2130705246 (&H810004A2)
    DIKEYBOARD_POWER        = -2130705186 (&H810004DE)
    DIKEYBOARD_PREVTRACK    = -2130705264 (&H81000490)
    DIKEYBOARD_PRIOR        = -2130705207 (&H810004C9)
    DIKEYBOARD_Q            = -2130705392 (&H81000410)
    DIKEYBOARD_R            = -2130705389 (&H81000413)
    DIKEYBOARD_RBRACKET     = -2130705381 (&H8100041B)
    DIKEYBOARD_RCONTROL     = -2130705251 (&H8100049D)
    DIKEYBOARD_RETURN       = -2130705380 (&H8100041C)
    DIKEYBOARD_RIGHT        = -2130705203 (&H810004CD)
    DIKEYBOARD_RMENU        = -2130705224 (&H810004B8)
    DIKEYBOARD_RSHIFT       = -2130705354 (&H81000436)
    DIKEYBOARD_RWIN         = -2130705188 (&H810004DC)
    DIKEYBOARD_S            = -2130705377 (&H8100041F)
    DIKEYBOARD_SCROLL       = -2130705338 (&H81000446)
    DIKEYBOARD_SEMICOLON    = -2130705369 (&H81000427)
    DIKEYBOARD_SLASH        = -2130705355 (&H81000435)
    DIKEYBOARD_SLEEP        = -2130705185 (&H810004DF)
    DIKEYBOARD_SPACE        = -2130705351 (&H81000439)
    DIKEYBOARD_STOP         = -2130705259 (&H81000495)
    DIKEYBOARD_SUBTRACT     = -2130705334 (&H8100044A)
    DIKEYBOARD_SYSRQ        = -2130705225 (&H810004B7)
    DIKEYBOARD_T            = -2130705388 (&H81000414)
    DIKEYBOARD_TAB          = -2130705393 (&H8100040F)
    DIKEYBOARD_U            = -2130705386 (&H81000416)
    DIKEYBOARD_UNDERLINE    = -2130705261 (&H81000493)
    DIKEYBOARD_UNLABELED    = -2130705257 (&H81000497)
    DIKEYBOARD_UP           = -2130705208 (&H810004C8)
    DIKEYBOARD_V            = -2130705361 (&H8100042F)
    DIKEYBOARD_VOLUMEDOWN   = -2130705234 (&H810004AE)
    DIKEYBOARD_VOLUMEUP     = -2130705232 (&H810004B0)
    DIKEYBOARD_W            = -2130705391 (&H81000411)
    DIKEYBOARD_WAKE         = -2130705181 (&H810004E3)
    DIKEYBOARD_WEBBACK      = -2130705174 (&H810004EA)
    DIKEYBOARD_WEBFAVORITES = -2130705178 (&H810004E6)
    DIKEYBOARD_WEBFORWARD   = -2130705175 (&H810004E9)
    DIKEYBOARD_WEBHOME      = -2130705230 (&H810004B2)
    DIKEYBOARD_WEBREFRESH   = -2130705177 (&H810004E7)
    DIKEYBOARD_WEBSEARCH    = -2130705179 (&H810004E5)
    DIKEYBOARD_WEBSTOP      = -2130705176 (&H810004E8)
    DIKEYBOARD_X            = -2130705363 (&H8100042D)
    DIKEYBOARD_Y            = -2130705387 (&H81000415)
    DIKEYBOARD_YEN          = -2130705283 (&H8100047D)
    DIKEYBOARD_Z            = -2130705364 (&H8100042C)
End Enum

Constants

DIKEYBOARD_(n)
Number keys 0 through 9 on the main keyboard
DIKEYBOARD_A…DIKEYBOARD_Z
Letter keys A through Z on the main keyboard
DIKEYBOARD_ABNT_C1, DIKEYBOARD_ABNT_C2
On numeric keypad of Brazilian keyboards
DIKEYBOARD_ADD
PLUS SIGN (+) on the numeric keypad
DIKEYBOARD_APOSTROPHE
APOSTROPHE (') key
DIKEYBOARD_APPS
Application key
DIKEYBOARD_AT
On Japanese keyboard
DIKEYBOARD_AX
On Japanese keyboard
DIKEYBOARD_BACK
BACKSPACE key
DIKEYBOARD_BACKSLASH
BACKSLASH (\) key
DIKEYBOARD_CALCULATOR
Dedicated key that launches a calculator
DIKEYBOARD_CAPITAL
CAPS LOCK key
DIKEYBOARD_COLON
On Japanese keyboard
DIKEYBOARD_COMMA
COMMA (,) key
DIKEYBOARD_CONVERT
On Japanese keyboard
DIKEYBOARD_DECIMAL
Decimal point (PERIOD) on the numeric keypad
DIKEYBOARD_DELETE
DELETE key on the main keyboard (not DEL on the numeric keypad)
DIKEYBOARD_DIVIDE
FORWARD SLASH (/) on the numeric keypad
DIKEYBOARD_DOWN, DIKEYBOARD_UP
DOWN ARROW, UP ARROW on the main keyboard (not the arrow keys on the numeric keypad)
DIKEYBOARD_END
END key on the main keyboard (not END on the numeric keypad)
DIKEYBOARD_EQUALS
EQUAL SIGN on the main keyboard
DIKEYBOARD_ESCAPE
ESC key
DIKEYBOARD_F(n)
Function keys F1 through F15
DIKEYBOARD_GRAVE
Grave accent (`)
DIKEYBOARD_HOME
HOME key on the main keyboard (not HOME on the numeric keypad)
DIKEYBOARD_INSERT
INSERT key on the main keyboard (not INS on the numeric keypad)
DIKEYBOARD_KANA
On Japanese keyboard
DIKEYBOARD_KANJI
On Japanese keyboard
DIKEYBOARD_LBRACKET, DIKEYBOARD_RBRACKET
Left ( [ )and right ( ] ) SQUARE BRACKET keys
DIKEYBOARD_LCONTROL, DIKEYBOARD_RCONTROL
Left and right CTRL keys
DIKEYBOARD_LEFT, DIKEYBOARD_RIGHT
LEFT ARROW, RIGHT ARROW on the main keyboard (not the arrow keys on the numeric keypad)
DIKEYBOARD_LMENU, DIKEYBOARD_RMENU
Left and right ALT keys
DIKEYBOARD_LSHIFT, DIKEYBOARD_RSHIFT
Left and right SHIFT keys
DIKEYBOARD_LWIN, DIKEYBOARD_RWIN
Left and right Microsoft® Windows® logo keys
DIKEYBOARD_MAIL
Dedicated key to launch an e-mail program
DIKEYBOARD_MEDIASELECT
Media Select key, which displays a selection of supported media players on the system
DIKEYBOARD_MEDIASTOP
Stops multimedia play
DIKEYBOARD_MINUS
(HYPHEN) (-) (MINUS SIGN) on the main keyboard
DIKEYBOARD_MULTIPLY
Asterisk (*) on the numeric keypad
DIKEYBOARD_MUTE
Mutes sound output
DIKEYBOARD_MYCOMPUTER
Launches My Computer on applicable Windows systems
DIKEYBOARD_NEXT
PAGE DOWN key on the main keyboard (not PGDN on the numeric keypad)
DIKEYBOARD_NEXTTRACK
Advances to the next CD/DVD track
DIKEYBOARD_NOCONVERT
On Japanese keyboard
DIKEYBOARD_NUMLOCK
NUM LOCK key
DIKEYBOARD_NUMPAD(n)
Number keys on the numeric keypad
DIKEYBOARD_NUMPADCOMMA
COMMA (,)on the NEC PC98 numeric keypad
DIKEYBOARD_NUMPADENTER
ENTER on the numeric keypad
DIKEYBOARD_NUMPADEQUALS
EQUAL SIGN on the numeric keypad of the NEC PC98 keyboard
DIKEYBOARD_OEM_102
On British and German keyboards
DIKEYBOARD_PAUSE
PAUSE key
DIKEYBOARD_PERIOD
PERIOD on the main keyboard
DIKEYBOARD_PLAYPAUSE
Pauses multimedia play
DIKEYBOARD_POWER
System power key
DIKEYBOARD_PREVTRACK
Play the previous CD/DVD track; CIRCUMFLEX on Japanese keyboard
DIKEYBOARD_PRIOR
PAGE UP key on the main keyboard (not PGUP on the numeric keypad)
DIKEYBOARD_RETURN
ENTER on the main keyboard
DIKEYBOARD_SCROLL
SCROLL LOCK key
DIKEYBOARD_SEMICOLON
SEMICOLON (;) key
DIKEYBOARD_SLASH
FORWARD SLASH (/) on the main keyboard (not FORWARD SLASH on the numeric keypad)
DIKEYBOARD_SLEEP
Sends the system into sleep mode
DIKEYBOARD_SPACE
The SPACEBAR
DIKEYBOARD_STOP
On Japanese keyboard
DIKEYBOARD_SUBTRACT
MINUS SIGN on the numeric keypad
DIKEYBOARD_SYSRQ
SYSRQ key
DIKEYBOARD_TAB
TAB key
DIKEYBOARD_UNDERLINE
On Japanese keyboard
DIKEYBOARD_UNLABELED
On Japanese keyboard
DIKEYBOARD_VOLUMEDOWN
Decreases sound output level
DIKEYBOARD_VOLUMEUP
Increases sound output level
DIKEYBOARD_WAKE
Wakes the system out of sleep mode
DIKEYBOARD_WEBBACK
Navigates a browser back one page in the history list
DIKEYBOARD_WEBFAVORITES
Displays the Microsoft Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list
DIKEYBOARD_WEBFORWARD
Instructs a browser to move to the next page in the history list
DIKEYBOARD_WEBHOME
Instructs a browser to load the user's home page
DIKEYBOARD_WEBREFRESH
Instructs a browser to reload the current page
DIKEYBOARD_WEBSEARCH
Instructs a browser to launch a search engine
DIKEYBOARD_WEBSTOP
Instructs a browser to stop loading the current page
DIKEYBOARD_YEN
On Japanese keyboard

The constants in this enumeration correspond to the members of CONST_DIKEYFLAGS, but their names begin with DIK rather than DIKEYBOARD and they have different values.


CONST_DIKEYFLAGS

Used to identify keys in keyboard data.

Enum CONST_DIKEYFLAGS
    DIK_0            =  11
    DIK_1            =   2
    DIK_2            =   3
    DIK_3            =   4
    DIK_4            =   5
    DIK_5            =   6
    DIK_6            =   7
    DIK_7            =   8
    DIK_8            =   9
    DIK_9            =  10
    DIK_A            =  30 (&H1E)
    DIK_ABNT_C1      = 115 (&H73)
    DIK_ABNT_C2      = 126 (&H7E)
    DIK_ADD          =  78 (&H4E)
    DIK_APOSTROPHE   =  40 (&H28)
    DIK_APPS         = 221 (&HDD)
    DIK_AT           = 145 (&H91)
    DIK_AX           = 150 (&H96)
    DIK_B            =  48 (&H30)
    DIK_BACK         =  14
    DIK_BACKSLASH    =  43 (&H2B)
    DIK_BACKSPACE    =  14
    DIK_C            =  46 (&H2E)
    DIK_CALCULATOR   = 161 (&HA1)
    DIK_CAPITAL      =  58 (&H3A)
    DIK_CAPSLOCK     =  58 (&H3A)
    DIK_CIRCUMFLEX   = 144 (&H90)
    DIK_COLON        = 146 (&H92)
    DIK_COMMA        =  51 (&H33)
    DIK_CONVERT      = 121 (&H79)
    DIK_D            =  32 (&H20)
    DIK_DECIMAL      =  83 (&H53)
    DIK_DELETE       = 211 (&HD3)
    DIK_DIVIDE       = 181 (&HB5)
    DIK_DOWN         = 208 (&HD0)
    DIK_DOWNARROW    = 208 (&HD0)
    DIK_E            =  18 (&H12)
    DIK_END          = 207 (&HCF)
    DIK_EQUALS       =  13
    DIK_ESCAPE       =   1
    DIK_F            =  33 (&H21)
    DIK_F1           =  59 (&H3B)
    DIK_F2           =  60 (&H3C)
    DIK_F3           =  61 (&H3D)
    DIK_F4           =  62 (&H3E)
    DIK_F5           =  63 (&H3F)
    DIK_F6           =  64 (&H40)
    DIK_F7           =  65 (&H41)
    DIK_F8           =  66 (&H42)
    DIK_F9           =  67 (&H43)
    DIK_F10          =  68 (&H44)
    DIK_F11          =  87 (&H57)
    DIK_F12          =  88 (&H58)
    DIK_F13          = 100 (&H64)
    DIK_F14          = 101 (&H65)
    DIK_F15          = 102 (&H66)
    DIK_G            =  34 (&H22)
    DIK_GRAVE        =  41 (&H29)
    DIK_H            =  35 (&H23)
    DIK_HOME         = 199 (&HC7)
    DIK_I            =  23 (&H17)
    DIK_INSERT       = 210 (&HD2)
    DIK_J            =  36 (&H24)
    DIK_K            =  37 (&H25)
    DIK_KANA         = 112 (&H70)
    DIK_KANJI        = 148 (&H94)
    DIK_L            =  38 (&H26)
    DIK_LALT         =  56 (&H38)
    DIK_LBRACKET     =  26 (&H1A)
    DIK_LCONTROL     =  29 (&H1D)
    DIK_LEFT         = 203 (&HCB)
    DIK_LEFTARROW    = 203 (&HCB)
    DIK_LMENU        =  56 (&H38)
    DIK_LSHIFT       =  42 (&H2A)
    DIK_LWIN         = 219 (&HDB)
    DIK_M            =  50 (&H32)
    DIK_MAIL         = 236 (&HEC)
    DIK_MEDIASELECT  = 237 (&HED)
    DIK_MEDIASTOP    = 164 (&HA4)
    DIK_MINUS        =  12
    DIK_MULTIPLY     =  55 (&H37)
    DIK_MUTE         = 160 (&HA0)
    DIK_MYCOMPUTER   = 235 (&HEB)
    DIK_N            =  49 (&H31)
    DIK_NEXT         = 209 (&HD1)
    DIK_NEXTTRACK    = 153 (&H99)
    DIK_NOCONVERT    = 123 (&H7B)
    DIK_NUMLOCK      =  69 (&H45)
    DIK_NUMPAD0      =  82 (&H52)
    DIK_NUMPAD1      =  79 (&H4F)
    DIK_NUMPAD2      =  80 (&H50)
    DIK_NUMPAD3      =  81 (&H51)
    DIK_NUMPAD4      =  75 (&H4B)
    DIK_NUMPAD5      =  76 (&H4C)
    DIK_NUMPAD6      =  77 (&H4D)
    DIK_NUMPAD7      =  71 (&H47)
    DIK_NUMPAD8      =  72 (&H48)
    DIK_NUMPAD9      =  73 (&H49)
    DIK_NUMPADCOMMA  = 179 (&HB3)
    DIK_NUMPADENTER  = 156 (&H9C)
    DIK_NUMPADEQUALS = 141 (&H8D)
    DIK_NUMPADMINUS  =  74 (&H4A)
    DIK_NUMPADPERIOD =  83 (&H53)
    DIK_NUMPADPLUS   =  78 (&H4E)
    DIK_NUMPADSLASH  = 181 (&HB5)
    DIK_NUMPADSTAR   =  55 (&H37)
    DIK_O            =  24 (&H18)
    DIK_OEM_102      =  86 (&H56)
    DIK_P            =  25 (&H19)
    DIK_PAUSE        = 197 (&HC5)
    DIK_PERIOD       =  52 (&H34)
    DIK_PGDN         = 209 (&HD1)
    DIK_PGUP         = 201 (&HC9)
    DIK_PLAYPAUSE    = 162 (&HA2)
    DIK_POWER        = 222 (&HDE)
    DIK_PREVTRACK    = 144 (&H90)
    DIK_PRIOR        = 201 (&HC9)
    DIK_Q            =  16 (&H10)
    DIK_R            =  19 (&H13)
    DIK_RALT         = 184 (&HB8)
    DIK_RBRACKET     =  27 (&H1B)
    DIK_RCONTROL     = 157 (&H9D)
    DIK_RETURN       =  28 (&H1C)
    DIK_RIGHT        = 205 (&HCD)
    DIK_RIGHTARROW   = 205 (&HCD)
    DIK_RMENU        = 184 (&HB8)
    DIK_RSHIFT       =  54 (&H36)
    DIK_RWIN         = 220 (&HDC)
    DIK_S            =  31 (&H1F)
    DIK_SCROLL       =  70 (&H46)
    DIK_SEMICOLON    =  39 (&H27)
    DIK_SLASH        =  53 (&H35)
    DIK_SLEEP        = 223 (&HDF)
    DIK_SPACE        =  57 (&H39)
    DIK_STOP         = 149 (&H95)
    DIK_SUBTRACT     =  74 (&H4A)
    DIK_SYSRQ        = 183 (&HB7)
    DIK_T            =  20 (&H14)
    DIK_TAB          =  15
    DIK_U            =  22 (&H16)
    DIK_UNDERLINE    = 147 (&H93)
    DIK_UNLABELED    = 151 (&H97)
    DIK_UP           = 200 (&HC8)
    DIK_UPARROW      = 200 (&HC8)
    DIK_V            =  47 (&H2F)
    DIK_VOLUMEDOWN   = 174 (&HAE)
    DIK_VOLUMEUP     = 176 (&HB0)
    DIK_W            =  17 (&H11)
    DIK_WAKE         = 227 (&HE3)
    DIK_WEBBACK      = 234 (&HEA)
    DIK_WEBFAVORITES = 230 (&HE6)
    DIK_WEBFORWARD   = 233 (&HE9)
    DIK_WEBHOME      = 178 (&HB2)
    DIK_WEBREFRESH   = 231 (&HE7)
    DIK_WEBSEARCH    = 229 (&HE5)
    DIK_WEBSTOP      = 232 (&HE8)
    DIK_X            =  45 (&H2D)
    DIK_Y            =  21 (&H15)
    DIK_YEN          = 125 (&H7D)
    DIK_Z            =  44 (&H2C)
End Enum

Constants

DIK_(n)
Number keys 0 through 9 on the main keyboard
DIK_A…DIK_Z
Letter keys A through Z on the main keyboard
DIK_ABNT_C1, DIK_ABNT_C2
On numeric keypad of Brazilian keyboards
DIK_ADD
PLUS SIGN (+) on the numeric keypad
DIK_APOSTROPHE
APOSTROPHE (') key
DIK_APPS
Application key
DIK_AT
On Japanese keyboard
DIK_AX
On Japanese keyboard
DIK_BACK
BACKSPACE key
DIK_BACKSLASH
BACKSLASH (\) key
DIK_BACKSPACE
BACKSPACE key (alias of DIK_BACKSLASH)
DIK_CALCULATOR
Dedicated key that launches a calculator
DIK_CAPITAL
CAPS LOCK key
DIK_CAPSLOCK
CAPS LOCK key (alias of DIK_CAPITAL)
DIK_CIRCUMFLEX
On Japanese keyboard
DIK_COLON
On Japanese keyboard
DIK_COMMA
COMMA (,) key
DIK_CONVERT
On Japanese keyboard
DIK_DECIMAL
Decimal point (PERIOD) on the numeric keypad
DIK_DELETE
DELETE key on the main keyboard (not DEL on the numeric keypad)
DIK_DIVIDE
FORWARDSLASH (/) on the numeric keypad
DIK_DOWN, DIK_UP
DOWN ARROW, UP ARROW on main keyboard (not the arrow keys on the numeric keypad)
DIK_DOWNARROW, UPARROW
DOWN ARROW, UP ARROW on main keyboard (not the arrow keys on the numeric keypad) (aliases of DIK_DOWN and DIK_UP)
DIK_END
END key on the main keyboard (not END on the numeric keypad)
DIK_EQUALS
EQUAL SIGN on the main keyboard
DIK_ESCAPE
ESC key
DIK_F(n)
Function keys F1 through F15
DIK_GRAVE
Grave accent (`)
DIK_HOME
HOME key on the main keyboard (not HOME on the numeric keypad)
DIK_INSERT
INSERT key on the main keyboard (not INS on the numeric keypad)
DIK_KANA
On Japanese keyboard
DIK_KANJI
On Japanese keyboard
DIK_LALT, DIK RALT
Left and right ALT keys (alias of DIK_LMENU and DIK_RMENU)
DIK_LBRACKET, DIK_RBRACKET
Left ( [ ) and right ( ] ) SQUAREBRACKET keys
DIK_LCONTROL, DIK_RCONTROL
Left and right CTRL keys
DIK_LEFT, DIK_RIGHT
LEFT ARROW, RIGHT ARROW on the main keyboard (not the arrow keys on the numeric keypad)
DIK LEFTARROW, DIK_RIGHTARROW
LEFT ARROW, RIGHT ARROW on the main keyboard (not the arrow keys on the numeric keypad) (aliases of DIK_LEFT and DIK_RIGHT)
DIK_LMENU, DIK_RMENU
Left and right ALT keys
DIK_LSHIFT, DIK_RSHIFT
Left and right SHIFT keys
DIK_LWIN, DIK_RWIN
Left and right Microsoft® Windows® logo keys
DIK_MAIL
Dedicated key to launch an e-mail program
DIK_MEDIASELECT
Media Select key, which displays a selection of supported media players on the system
DIK_MEDIASTOP
Stops multimedia play
DIK_MINUS
MINUS SIGN (hyphen) on the main keyboard
DIK_MULTIPLY
Asterisk (*) on the numeric keypad
DIK_MUTE
Mutes sound output
DIK_MYCOMPUTER
Launches My Computer on applicable Windows systems
DIK_NEXT
PAGE DOWN key on the main keyboard (not PGDN on the numeric keypad)
DIK_NEXTTRACK
Advances to the next CD/DVD track
DIK_NOCONVERT
On Japanese keyboard
DIK_NUMLOCK
NUM LOCK key
DIK_NUMPAD(n)
Number keys on the numeric keypad
DIK_NUMPADCOMMA
COMMA on the NEC PC98 numeric keypad
DIK_NUMPADENTER
ENTER on the numeric keypad
DIK_NUMPADEQUALS
EQUAL SIGN on the numeric keypad of the NEC PC98 keyboard
DIK_NUMPADMINUS
MINUS SIGN on the numeric keypad (alias of DIK_SUBTRACT)
DIK_NUMPADPERIOD
Decimal point (PERIOD) on the numeric keypad (alias of DIK_DECIMAL)
DIK_NUMPADPLUS
PLUS SIGN (+) on the numeric keypad (alias of DIK_ADD)
DIK_NUMPADSLASH
FORWARD SLASH (/) on the numeric keypad (alias of DIK_DIVIDE)
DIK_NUMPADSTAR
ASTERISK (*) on the numeric keypad (alias of DIK_MULTIPLY)
DIK_OEM_102
On British and German keyboards
DIK_PAUSE
PAUSE key
DIK_PERIOD
PERIOD on the main keyboard (not the decimal point on the numeric keypad)
DIK_PGDN, DIK_PGUP
PAGE DOWN, PAGE UP keys on the main keyboard (not PGDN and PGUP on the numeric keypad) (aliases of DIK_NEXT and DIK_PRIOR)
DIK_PLAYPAUSE
Pauses multimedia play
DIK_POWER
System power key
DIK_PREVTRACK
Play the previous CD/DVD track
DIK_PRIOR
PAGE UP key on the main keyboard (not PGUP on the numeric keypad)
DIK_RETURN
ENTER on the main keyboard
DIK_SCROLL
SCROLL LOCK key
DIK_SEMICOLON
SEMICOLON key
DIK_SLASH
FORWARD SLASH (/) on the main keyboard (not FORWARD SLASH on the numeric keypad)
DIK_SLEEP
Sends the system into sleep mode
DIK_SPACE
The SPACEBAR
DIK_STOP
On Japanese keyboard
DIK_SUBTRACT
MINUS SIGN on the numeric keypad
DIK_SYSRQ
SYSRQ key
DIK_TAB
TAB key
DIK_UNDERLINE
On Japanese keyboard
DIK_UNLABELED
On Japanese keyboard
DIK_VOLUMEDOWN
Decreases sound output level
DIK_VOLUMEUP
Increases sound output level
DIK_WAKE
Wakes the system out of sleep mode
DIK_WEBBACK
Navigates a browser back one page in the history list
DIK_WEBFAVORITES
Displays the Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list
DIK_WEBFORWARD
Instructs a browser to move to the next page in the history list
DIK_WEBHOME
Instructs a browser to load the user's home page
DIK_WEBREFRESH
Instructs a browser to reload the current page
DIK_WEBSEARCH
Instructs a browser to launch a search engine
DIK_WEBSTOP
Instructs a browser to stop loading the current page
DIK_YEN
On Japanese keyboard

Remarks

The constants in this enumeration that are not aliases correspond to the members of CONST_DIKEYBOARDFLAGS, begin with DIK rather than DIKEYBOARD, and have different values.


CONST_DIMAPFLAGS

Used in the lSemantic member of the DIACTION type to map an action to any matching control on the device.

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 action is left unmapped.

Actions mapped with these constants 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.

Enum CONST_DIMAPFLAGS
    DIAXIS_ANY_1   = -16760319 (&HFF004201)
    DIAXIS_ANY_2   = -16760318 (&HFF004202)
    DIAXIS_ANY_3   = -16760317 (&HFF004203)
    DIAXIS_ANY_4   = -16760316 (&HFF004204)
    DIAXIS_ANY_A_1 = -16530943 (&HFF03C201)
    DIAXIS_ANY_A_2 = -16530942 (&HFF03C202)
    DIAXIS_ANY_B_1 = -16498175 (&HFF044201)
    DIAXIS_ANY_B_2 = -16498174 (&HFF044202)
    DIAXIS_ANY_C_1 = -16465407 (&HFF04C201)
    DIAXIS_ANY_C_2 = -16465406 (&HFF04C202)
    DIAXIS_ANY_R_1 = -16629247 (&HFF024201)
    DIAXIS_ANY_R_2 = -16629246 (&HFF024202)
    DIAXIS_ANY_S_1 = -16432639 (&HFF054201)
    DIAXIS_ANY_S_2 = -16432638 (&HFF054202)
    DIAXIS_ANY_U_1 = -16596479 (&HFF02C201)
    DIAXIS_ANY_U_2 = -16596478 (&HFF02C202)
    DIAXIS_ANY_V_1 = -16563711 (&HFF034201)
    DIAXIS_ANY_V_2 = -16563710 (&HFF034202)
    DIAXIS_ANY_X_1 = -16727551 (&HFF00C201)
    DIAXIS_ANY_X_2 = -16727550 (&HFF00C202)
    DIAXIS_ANY_Y_1 = -16694783 (&HFF014201)
    DIAXIS_ANY_Y_2 = -16694782 (&HFF014202)
    DIAXIS_ANY_Z_1 = -16662015 (&HFF01C201)
    DIAXIS_ANY_Z_2 = -16662014 (&HFF01C202)
    DIBUTTON_ANY   = -16759808 (&HFF004400)
    DIPOV_ANY_1    = -16759295 (&HFF004601)
    DIPOV_ANY_2    = -16759294 (&HFF004602)
    DIPOV_ANY_3    = -16759293 (&HFF004603)
    DIPOV_ANY_4    = -16759292 (&HFF004604)
End Enum

Constants

DIAXIS_ANY_1
Any axis.
DIAXIS_ANY_2
Any axis.
DIAXIS_ANY_3
Any axis.
DIAXIS_ANY_4
Any axis.
DIAXIS_ANY_A_1
Any accelerator.
DIAXIS_ANY_A_2
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_1
Any x-axis.
DIAXIS_ANY_Y_1
Any y-axis.
DIAXIS_ANY_Y_1
Any y-axis.
DIAXIS_ANY_Z_1
Any z-axis.
DIAXIS_ANY_Z_1
Any z-axis.
DIBUTTON_ANY
Any button.
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.


CONST_DIMOUSEFLAGS

Used to specify mouse buttons and axes in the lSemantic member of the DIACTION type.

Enum CONST_DIMOUSEFLAGS
    DIMOUSE_BUTTON0 = -2113928180 (&H8200040C)
    DIMOUSE_BUTTON1 = -2113928179 (&H8200040D)
    DIMOUSE_BUTTON2 = -2113928178 (&H8200040E)
    DIMOUSE_BUTTON3 = -2113928177 (&H8200040F)
    DIMOUSE_BUTTON4 = -2113928176 (&H82000410)
    DIMOUSE_BUTTON5 = -2113928175 (&H82000411)
    DIMOUSE_BUTTON6 = -2113928174 (&H82000412
    DIMOUSE_BUTTON7 = -2113928173 (&H82000413)
    DIMOUSE_WHEEL   = -2113928440 (&H82000308)
    DIMOUSE_XAXIS   = -2113928448 (&H82000300)
    DIMOUSE_XAXISAB = -2113928704 (&H82000200)
    DIMOUSE_YAXIS   = -2113928444 (&H82000304)
    DIMOUSE_YAXISAB = -2113928700 (&H82000204)
End Enum

Constants

DIMOUSE_BUTTON(n)
Buttons 0 through 7.
DIMOUSE_WHEEL, DIMOUSE_XAXIS, DIMOUSE_YAXIS
Axes that return relative data.
DIMOUSE_XAXISAB, DIMOUSE_YAXISAB
Axes that return absolute data.


CONST_DIMOUSEOFS

Used to identify buttons and axes in mouse data. The values of the constants are the offset of the data within the data format for immediate data. The same identifiers are used in buffered data packets.

Enum CONST_DIMOUSEOFS
    DIMOFS_BUTTON0 = 12
    DIMOFS_BUTTON1 = 13
    DIMOFS_BUTTON2 = 14
    DIMOFS_BUTTON3 = 15
    DIMOFS_BUTTON4 = 16 (&H10)
    DIMOFS_BUTTON5 = 17 (&H11)
    DIMOFS_BUTTON6 = 18 (&H12)
    DIMOFS_BUTTON7 = 19 (&H13)
    DIMOFS_X       =  0
    DIMOFS_Y       =  4
    DIMOFS_Z       =  8
End Enum

Constants

DIMOFS_BUTTON(n)
Offset of the data for buttons 0 through 7.
DIMOFS_X, DIMOFS_Y, DIMOFS_Z
Offset of the data for the axis.


CONST_DINPUT

The CONST_DINPUT enumeration contains various constants that are used throughout Microsoft® DirectInput®.

Enum CONST_DINPUT
    DIEB_NOTRIGGER               =          -1 (&HFFFFFFFF)
    DIPROPAUTOCENTER_OFF         =           0
    DIPROPAUTOCENTER_ON          =           1
    DIPROPAXISMODE_ABS           =           0
    DIPROPAXISMODE_REL           =           1
    DIPROPCALIBRATIONMODE_COOKED =           0
    DIPROPCALIBRATIONMODE_RAW    =           1
    DIPROPRANGE_NOMAX            =  2147483647 (&H7FFFFFFF)
    DIPROPRANGE_NOMIN            = -2147483648 (&H80000000)
End Enum

Constants

DIEB_NOTRIGGER
Used in the lTriggerButton member of the DIEFFECT type to specify that the effect has no trigger button.
DIPROPAUTOCENTER_OFF
The device should not automatically center when the user releases it. See DirectInputDevice8.SetProperty.
DIPROPAUTOCENTER_ON
The device should automatically center when the user releases it. See DirectInputDevice8.SetProperty.
DIPROPAXISMODE_ABS
Used in DirectInputDevice8.GetProperty and DirectInputDevice8.SetProperty to represent absolute axis mode.
DIPROPAXISMODE_REL
Used in DirectInputDevice8.GetProperty and DirectInputDevice8.SetProperty to represent relative axis mode.
DIPROPCALIBRATIONMODE_COOKED
Used in DirectInputDevice8.SetProperty to set the DIPROP_CALIBRATIONMODE property.
DIPROPCALIBRATIONMODE_RAW
Used in DirectInputDevice8.SetProperty to set the DIPROP_CALIBRATIONMODE property.
DIPROPRANGE_NOMAX
Returned from DirectInputDevice8.GetProperty if the axis has no upper limit on its range.
DIPROPRANGE_NOMIN
Returned from DirectInputDevice8.GetProperty if the axis has no lower limit on its range.


CONST_DINPUTERR

The CONST_DINPUTERR enumeration contains the error codes for Microsoft® DirectInput®. All the error codes and definitions can be found in the Error Codes topic.

Enum CONST_DINPUTERR
    DI_OK                         =           0
    DIERR_ACQUIRED                = -2147024726 (&H800700AA)
    DIERR_ALREADYINITIALIZED      = -2147023649 (&H800704DF)
    DIERR_BADDRIVERVER            = -2147024777 (&H80070077)
    DIERR_BETADIRECTINPUTVERSION  = -2147023743 (&H80070481)
    DIERR_DEVICEFULL              = -2147220991 (&H80040201)
    DIERR_DEVICENOTREG            = -2147221164 (&H80040154)
    DIERR_EFFECTPLAYING           = -2147220984 (&H80040208)
    DIERR_GENERIC                 = -2147467259 (&H80004005)
    DIERR_HANDLEEXISTS            = -2147024891 (&H80070005)
    DIERR_HASEFFECTS              = -2147220988 (&H80040204)
    DIERR_INCOMPLETEEFFECT        = -2147220986 (&H80040206)
    DIERR_INPUTLOST               = -2147024866 (&H8007001E)
    DIERR_INVALIDHANDLE           = -2147024890 (&H80070006)
    DIERR_INVALIDPARAM            =           5
    DIERR_MOREDATA                = -2147220990 (&H80040202)
    DIERR_NOAGGREGATION           = -2147467262 (&H80004002)
    DIERR_NOINTERFACE             =         430 (&H1AE)
    DIERR_NOTACQUIRED             = -2147024884 (&H8007000C)
    DIERR_NOTBUFFERED             = -2147220985 (&H80040207)
    DIERR_NOTDOWNLOADED           = -2147220989 (&H80040203)
    DIERR_NOTEXCLUSIVEACQUIRED    = -2147220987 (&H80040205)
    DIERR_NOTFOUND                = -2147024894 (&H80070002)
    DIERR_NOTINITIALIZED          = -2147024875 (&H80070015)
    DIERR_OBJECTNOTFOUND          = -2147024894 (&H80070002)
    DIERR_OLDDIRECTINPUTVERSION   = -2147023746 (&H8007047E)
    DIERR_OTHERAPPHASPRIO         = -2147024891 (&H80070005)
    DIERR_OUTOFMEMORY             =           7
    DIERR_READONLY                = -2147024891 (&H80070005)
    DIERR_REPORTFULL              = -2147220982 (&H8004020A)
    DIERR_UNPLUGGED               = -2147220983 (&H80040209)
    DIERR_UNSUPPORTED             =         445 (&H1BD)
    E_PENDING                     = -2147024889 (&H80070007)
End Enum

Constants

DI_OK
Success.
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_INVALIDHANDLE
An invalid window handle was passed to the method.
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_MOREDATA
Not all the requested information fitted into the buffer.
DIERR_NOAGGREGATION
This object does not support aggregation.
DIERR_NOINTERFACE
The specified interface is not supported by the object. 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
The 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 COM 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 couldn't 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_PENDING
Data is not yet available.


CONST_DIPHFLAGS

Members of the CONST_DIPHFLAGS enumeration are used to specify how a device object is identified. They are used in the DirectInputDevice8.GetObjectInfo method as well as in the DIPROPLONG and DIPROPRANGE types.

Enum CONST_DIPHFLAGS
    DIPH_BYID     = 2
    DIPH_BYOFFSET = 1
    DIPH_BYUSAGE  = 3
    DIPH_DEVICE   = 0
End Enum

Constants

DIPH_BYID
The device object is identified by the instance identifier obtained from the return value of the DirectInputDeviceObjectInstance.GetType method.
DIPH_BYOFFSET
The device object is identified by the offset into the current data format of the object whose information is being accessed.
DIPH_BYUSAGE
The device object is identified by the HID usage page and usage values in packed form.
DIPH_DEVICE
The property applies to the entire device, not to a particular object.


CONST_DISCLFLAGS

The CONST_DISCLFLAGS enumeration is used in the flags parameter of the DirectInputDevice8.SetCooperativeLevel method to determine how the device interacts with other instances of the device and the rest of the system.

Enum CONST_DISCLFLAGS
    DISCL_BACKGROUND   =  8
    DISCL_EXCLUSIVE    =  1
    DISCL_FOREGROUND   =  4
    DISCL_NONEXCLUSIVE =  2
    DISCL_NOWINKEY     = 16 (&H10)
End Enum

Constants

DISCL_BACKGROUND
The application requires background access. If background access is granted, the device may 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 may obtain exclusive access to the device while it is acquired. Note, however, non-exclusive access to the device is always permitted, even if another application has obtained exclusive access.

If an application acquires the mouse or keyboard device in exclusive mode, the user will not be able to use the window 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 non-exclusive access. Access to the device will not interfere with other applications that are accessing the same device.
DISCL_NOWINKEY
The Microsoft® Windows® logo key is disabled so that users cannot inadvertently break out of the application. This value can be combined with DISCL_NONEXCLUSIVE. In exclusive mode, the Windows logo key is always disabled. Note, however, that DISCL_NOWINKEY has no effect when the default action mapping UI is displayed, and the Windows logo key operates normally as long as that UI is present.

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.


CONST_DISDDFLAGS

Members of the CONST_DISDDFLAGS enumeration are passed to the DirectInputDevice8.SendDeviceData method.

Enum CONST_DISDDFLAGS
    DISDD_CONTINUE = 1
    DISDD_DEFAULT  = 0
End Enum

Constants

DISDD_CONTINUE
Data will overlaid on existing data. For more information, see the Remarks section for DirectInputDevice8.SendDeviceData method.
DISDD_DEFAULT
Data will not be overlaid on existing data.


CONST_DISFFCFLAGS

Members of the CONST_DISFFCFLAGS enumeration are used by the DirectInputDevice8.SendForceFeedbackCommand method to specify the command.

Enum CONST_DISFFCFLAGS
    DISFFC_CONTINUE        =  8
    DISFFC_PAUSE           =  4
    DISFFC_RESET           =  1
    DISFFC_SETACTUATORSOFF = 32 (&H20)
    DISFFC_SETACTUATORSON  = 16 (&H10)
    DISFFC_STOPALL         =  2
End Enum

Constants

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 may not be started and existing ones may not be modified. Doing so may result in the subsequent DISFFC_CONTINUE command failing 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 recreated 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 will be 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 DirectInputEffect.Stop method for each effect playing.


CONST_DIVOICEFLAGS

Used to specify voice device objects in the lSemantic member of the DIACTION type.

Enum CONST_DIVOICEFLAGS
    DIVOICE_ALL          = -2097150966 (&H8300040A)
    DIVOICE_CHANNEL1     = -2097150975 (&H83000401)
    DIVOICE_CHANNEL2     = -2097150974 (&H83000402)
    DIVOICE_CHANNEL3     = -2097150973 (&H83000403)
    DIVOICE_CHANNEL4     = -2097150972 (&H83000404)
    DIVOICE_CHANNEL5     = -2097150971 (&H83000405)
    DIVOICE_CHANNEL6     = -2097150970 (&H83000406)
    DIVOICE_CHANNEL7     = -2097150969 (&H83000407)
    DIVOICE_CHANNEL8     = -2097150968 (&H83000408)
    DIVOICE_PLAYBACKMUTE = -2097150964 (&H8300040C)
    DIVOICE_RECORDMUTE   = -2097150965 (&H8300040B)
    DIVOICE_TEAM         = -2097150967 (&H83000409)
    DIVOICE_TRANSMIT     = -2097150963 (&H8300040D)
    DIVOICE_VOICECOMMAND = -2097150960 (&H83000410)
End Enum
DIVOICE_ALL
Broadcast voice input on all channels
DIVOICE_CHANNEL(n)
Individual broadcast channels 1 through 8
DIVOICE_PLAYBACKMUTE
Mute voice broadcast
DIVOICE_RECORDMUTE
Mute recording
DIVOICE_TEAM
Broadcast voice only to team members
DIVOICE_TRANSMIT
Send broadcast
DIVOICE_VOICECOMMAND
Accept voice input as voice command rather than broadcast data


Keyboard Keys

This section contains information on the following topics:

  • Keyboard Device Constants
  • DirectInput and Japanese Keyboards


Keyboard Device Constants

Members of the CONST_DIKEYFLAGS enumeration represent offsets within a keyboard device's data packet, a 256-byte array. The data at a given offset is associated with a keyboard key.

The standard keyboard device constants are listed in the following table in ascending order of data offset.

The CONST_DIKEYBOARDFLAGS enumeration, used in action mapping, also contains constants for each of the keys in the table. The names of these constants begin with DIKEYBOARD rather than DIK.

Constant | Note
DIK_ESCAPE |
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_0 | On main keyboard
DIK_MINUS | On main keyboard
DIK_EQUALS | On main keyboard
DIK_BACK | BACKSPACE
DIK_TAB |
DIK_Q |
DIK_W |
DIK_E |
DIK_R |
DIK_T |
DIK_Y |
DIK_U |
DIK_I |
DIK_O |
DIK_P |
DIK_LBRACKET | Left square bracket.
DIK_RBRACKET | Right square bracket
DIK_RETURN | ENTER on main keyboard
DIK_LCONTROL | Left CTRL
DIK_A |
DIK_S |
DIK_D |
DIK_F |
DIK_G |
DIK_H |
DIK_J |
DIK_K |
DIK_L |
DIK_SEMICOLON |
DIK_APOSTROPHE |
DIK_GRAVE | Grave accent (`)
DIK_LSHIFT | Left SHIFT
DIK_BACKSLASH |
DIK_Z |
DIK_X |
DIK_C |
DIK_V |
DIK_B |
DIK_N |
DIK_M |
DIK_COMMA |
DIK_PERIOD | On main keyboard
DIK_SLASH | Forward slash on main keyboard
DIK_RSHIFT | Right SHIFT key
DIK_MULTIPLY | Asterisk on numeric keypad
DIK_LMENU | Left ALT
DIK_SPACE | SPACEBAR
DIK_CAPITAL | CAPS LOCK
DIK_F1 |
DIK_F2 |
DIK_F3 |
DIK_F4 |
DIK_F5 |
DIK_F6 |
DIK_F7 |
DIK_F8 |
DIK_F9 |
DIK_F10 |
DIK_NUMLOCK |
DIK_SCROLL | SCROLL LOCK
DIK_NUMPAD7 |
DIK_NUMPAD8 |
DIK_NUMPAD9 |
DIK_SUBTRACT | MINUS SIGN on numeric keypad
DIK_NUMPAD4 |
DIK_NUMPAD5 |
DIK_NUMPAD6 |
DIK_ADD | PLUS SIGN on numeric keypad
DIK_NUMPAD1 |
DIK_NUMPAD2 |
DIK_NUMPAD3 |
DIK_NUMPAD0 |
DIK_DECIMAL | PERIOD (decimal point) on numeric keypad
DIK_OEM_102 | On British and German keyboards.
DIK_F11 |
DIK_F12 |
DIK_F13 |
DIK_F14 |
DIK_F15 |
DIK_KANA | On Japanese keyboard
DIK_ABNT_C1 | On numeric pad of Brazilian keyboards
DIK_CONVERT | On Japanese keyboard
DIK_NOCONVERT | On Japanese keyboard
DIK_YEN | On Japanese keyboard
DIK_ABNT_C2 | On numeric pad of Brazilian keyboards
DIK_NUMPADEQUALS | On numeric keypad (NEC PC98)
DIK_PREVTRACK | Previous track; circumflex on Japanese keyboard
DIK_AT | On Japanese keyboard
DIK_COLON | On Japanese keyboard
DIK_UNDERLINE | On Japanese keyboard
DIK_KANJI | On Japanese keyboard
DIK_STOP | On Japanese keyboard
DIK_AX | On Japanese keyboard
DIK_UNLABELED | On Japanese keyboard
DIK_NEXTTRACK | Next track
DIK_NUMPADENTER |
DIK_RCONTROL | Right CTRL
DIK_MUTE |
DIK_CALCULATOR |
DIK_PLAYPAUSE |
DIK_MEDIASTOP |
DIK_VOLUMEDOWN |
DIK_VOLUMEUP |
DIK_WEBHOME |
DIK_NUMPADCOMMA | COMMA on NEC PC98 numeric keypad
DIK_DIVIDE | Forward slash on numeric keypad
DIK_SYSRQ |
DIK_RMENU | Right ALT
DIK_PAUSE |
DIK_HOME |
DIK_UP | UP ARROW
DIK_PRIOR | PAGE UP
DIK_LEFT | LEFT ARROW
DIK_RIGHT | RIGHT ARROW
DIK_END |
DIK_DOWN | DOWN ARROW
DIK_NEXT | PAGE DOWN
DIK_INSERT |
DIK_DELETE |
DIK_LWIN | Left Microsoft® Windows® logo key
DIK_RWIN | Right Windows logo key
DIK_APPS | Application key
DIK_POWER |
DIK_SLEEP |
DIK_WAKE |
DIK_WEBSEARCH |
DIK_WEBFAVORITES |
DIK_WEBREFRESH |
DIK_WEBSTOP |
DIK_WEBFORWARD |
DIK_WEBBACK |
DIK_MYCOMPUTER |
DIK_MAIL |
DIK_MEDIASELECT |

For information on Japanese keyboards, see DirectInput and Japanese Keyboards.


DirectInput and Japanese Keyboards

The following chart 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


Action Mapping Constants

This section is a reference to the constants defined in the CONST_DIGENRE enumeration for application genres and controls mapped to actions within each genre.

The control constants, such as DIAXIS_FIGHTINGH_MOVE, are used in the ActionName 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 lGenre 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 ActionName 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.

  • Keyboard Mapping Constants
  • Mouse Mapping Constants
  • DirectPlay Voice Mapping Constants
  • Any-Control Constants


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_PAUSE
DIBUTTON_FIGHTINGH_RIGHT_LINK
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.

  • 2-D Object
  • 3-D Model
  • 3-D Navigation
  • 3-D Object


2-D Object

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


3-D Model

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


3-D Navigation

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


3-D Object

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 Web browsers and remote-control devices.

  • Browser
  • Remote Control


Browser

The DIVIRTUAL_BROWSER_CONTROL genre contains controls for a Web 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
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_PAUSE
DIBUTTON_DRIVINGR_PIT
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_STEER
DIBUTTON_DRIVINGT_FIRE
DIBUTTON_DRIVINGT_MENU
DIBUTTON_DRIVINGT_TARGET
DIBUTTON_DRIVINGT_WEAPONS

Priority 2 Controls
DIAXIS_DRIVINGT_ACCEL_AND_BRAKE
DIAXIS_DRIVINGT_BRAKE
DIAXIS_DRIVINGT_ACCELERATE_LINK
DIAXIS_DRIVINGT_STEER_LEFT_LINK
DIAXIS_DRIVINGT_STEER_RIGHT_LINK
DIAXIS_DRIVINGT_BARREL_UP_LINK
DIAXIS_DRIVINGT_BARREL_DOWN_LINK
DIAXIS_DRIVINGT_GLANCE_LEFT_LINK
DIAXIS_DRIVINGT_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGT_BRAKE
DIBUTTON_DRIVINGT_DASHBOARD
DIBUTTON_DRIVINGT_DEVICE
DIBUTTON_DRIVINGT_FIRESECONDARY
DIBUTTON_DRIVINGT_PAUSE
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.

  • 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_BACK_LINK
DIBUTTON_BASEBALLB_BOX
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_HOCKEYD_FORWARD_LINK
DIBUTTON_HOCKEYD_LEFT_LINK
DIBUTTON_HOCKEYD_PAUSE
DIBUTTON_HOCKEYD_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_SOCCERD_BACK_LINK
DIBUTTON_SOCCERD_FORWARD_LINK
DIBUTTON_SOCCERD_RIGHT_LINK
DIBUTTON_SOCCERO_CONTROL
DIBUTTON_SOCCERO_DEVICE
DIBUTTON_SOCCERO_HEAD
DIBUTTON_SOCCERO_LEFT_LINK
DIBUTTON_SOCCERO_PASSTHRU
DIBUTTON_SOCCERO_PAUSE
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_LIN
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


Keyboard Mapping Constants

The following constants are used in the ActionName member of the DIACTION type to map an action to a physical key.

Constant | Note
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 Microsoft® Windows® logo key
DIKEYBOARD_M |
DIKEYBOARD_MAIL |
DIKEYBOARD_MEDIASELECT |
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 |
DIKEYBOARD_WEBFORWARD |
DIKEYBOARD_WEBHOME |
DIKEYBOARD_WEBREFRESH |
DIKEYBOARD_WEBSEARCH |
DIKEYBOARD_WEBSTOP |
DIKEYBOARD_X |
DIKEYBOARD_Y |
DIKEYBOARD_YEN | On Japanese keyboard
DIKEYBOARD_Z |


Mouse Mapping Constants

The following constants are used in the ActionName member of the DIACTION type to map an action to a physical axis or button on a mouse.

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

Note DIMOUSE_XAXISAB and DIMOUSE_YAXISAB represent the x-axis and y-axis on a mouse that returns absolute rather than relative axis data.


DirectPlay Voice Mapping Constants

The following constants are used in the ActionName member of the DIACTION type to map an action to a channel on a Microsoft® DirectPlay® voice device.

DIVOICE_CHANNEL1
DIVOICE_CHANNEL2
DIVOICE_CHANNEL3
DIVOICE_CHANNEL4
DIVOICE_CHANNEL5
DIVOICE_CHANNEL6
DIVOICE_CHANNEL7
DIVOICE_CHANNEL8
DIVOICE_ALL
DIVOICE_TEAM
DIVOICE_PLAYBACKMUTE
DIVOICE_RECORDMUTE
DIVOICE_TRANSMIT
DIVOICE_VOICECOMMAND


Any-Control Constants

The following constants are used in the ActionName member of the DIACTION type to map an action to any matching control on the device.

Constant | Device object
DIAXIS_ANY_1 | Any axis
DIAXIS_ANY_2 | Any axis
DIAXIS_ANY_3 | Any axis
DIAXIS_ANY_4 | Any axis
DIAXIS_ANY_A_1 | Any accelerator
DIAXIS_ANY_A_2 | 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
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

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.


Error Codes

This table lists the error codes that can be returned by DirectInput methods and functions. Errors are represented by negative values and cannot be combined.

For a list of the errors each method or function can raise, 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.

DI_OK
The operation completed successfully. This value is equal to the S_OK standard COM return value.
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_INVALIDHANDLE
An invalid window handle was passed to the method.
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 reading either the vendor-supplied action-mapping file for the device or reading or writing the user configuration file for the device.
DIERR_MOREDATA
Not all the requested information fitted into the buffer.
DIERR_NOAGGREGATION
This object does not support aggregation.
DIERR_NOINTERFACE
The specified interface is not supported by the object. 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
The 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 COM 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 couldn't 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_PENDING
Data is not yet available.


DirectPlay

The Microsoft® DirectPlay® application programming interface (API) is the component of Microsoft DirectX® that enables you to write network applications such as multiplayer games.

Like other components of DirectX, DirectPlay can be used with C, C++, and Microsoft Visual Basic®.

Information about DirectPlay is presented in the following sections.

Roadmap

What's New in DirectPlay. New features and functionality of this component in DirectX 8.1. If you have used DirectPlay before, read this section first because the technology has been completely redesigned since DirectX 7.0.

Introduction to DirectPlay. An overview of what DirectPlay is and what it can do for your application, together with a first look at some key objects and the steps involved in creating a network application.

Understanding DirectPlay. A deeper look at the underlying mechanisms. This section will not teach you how to implement a DirectPlay session but it will help you understand the API when you get into the details.

Using DirectPlay. A guide to using the API. You will 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. Use it in conjunction with the reference section.

DirectPlay Visual Basic Samples. A guide to the Visual Basic sample applications in the software development kit (SDK).

DirectPlay Visual Basic Reference. Detailed information the DirectPlay Visual Basic API.


What's New in DirectPlay

New Features for DirectPlay 8.1

Microsoft® DirectX 8.1® is a major release primarily for DirectX graphics. The improvements for Microsoft DirectPlay® are primarily performance enhancements.

To find out more about the new features in DirectX, see What's New in DirectX 8.1.

New Features for DirectPlay 8.0

The networking component of DirectX has undergone a major revision. DirectPlay introduces a new set of interfaces that enable games to have more direct access to the hardware, providing better performance.

The following list describes some of the new DirectPlay features.

Objects have been completely rewritten.
The complexity of creating a networked application has been dramatically simplified by separating the interfaces for creating peer-to-peer and client/server sessions. The objects for creating DirectPlay transport sessions are now:
DirectPlay8Peer
Provides methods for creating peer-to-peer sessions.
DirectPlay8Client
Provides methods for creating the client-side portion of a client/server application.
DirectPlay8Server
Provides methods for creating the server-side portion of a client/server application.
Lobbying is now independent from the rest of DirectPlay.
DirectPlay has removed the requirement that a lobby client work only with a DirectPlay application. This will allow for either the lobby service provider or the application to implement DirectPlay without concern for the other. Lobby implementation is now separated into two simplified objects.
DirectPlay8LobbyClient
This object is used to manage a lobby client and for enumerating and launching lobby-aware applications.
DirectPlay8LobbiedApplication
This object is used to register a lobby launchable application with the system so it can be lobby launched. It also is used to get the connection information from the lobby to enable game launching without querying the user.
Voice transmission has been added.
DirectPlay Voice provides a set of objects to add real-time voice communication to an application. The following objects are defined in the Dvoice.h header file.
DirectPlayVoiceClient8
Provides methods to create and manage clients in a DirectPlay Voice session.
DirectPlayVoiceServer8
Provides methods to host and manage a DirectPlay Voice session.
DirectPlayVoiceTest8
Used to test DirectPlay Voice audio configurations.
Addressing information has moved from GUID-based data to URL-based data format.
Previous versions of DirectPlay used binary chunks of data with GUID addresses that were difficult to implement and that humans could not read. In DirectX 8.1, DirectPlay introduces the representation of addresses in URL format. DirectPlay provides an object that is used to create and manipulate the new addressing format.
DirectPlay8Address
Provides generic addressing methods used to create and manipulate DirectPlay addresses.
Higher scalability and better memory management have been added.
Increases in consumer bandwidth have dramatically affected network game design and implementation. Improved DirectPlay thread-pool management makes it easier to for the developer to design scalable, more robust applications that can support massive multiplayer online applications.
Better support for firewalls and network address translators has been added.
Writing network games that traverse network address translators (NATs), firewalls, and other Internet connection sharing (ICS) methods can be difficult, particularly for non-guaranteed (UDP) traffic. Because DirectPlay 8.1 has been developed with these issues in mind, it will support NAT solutions where possible. The DirectPlay 8 TCP/IP service provider uses a single, developer-selectable UDP port for game data, making it possible to configure firewalls and NATs appropriately. Additionally, DirectPlay makes use of UDP so that, for client/server games, clients behind some NATs will be able to connect to games without additional configuration.
Test your application under a variety of network conditions with DP8Sim
You can now use a network simulator tool, DP8Sim, to help you predict how your application will perform under network conditions such as high latency or packet loss. DP8Sim is a simulated TCP/IP service provider applied on top of your existing network characteristics. A simple user interface (UI) allows you to easily change the simulated network settings and monitor your application's performance.


Introduction to DirectPlay

The Microsoft® DirectPlay® API provides developers with the tools to develop multiplayer applications such as games or chat clients. For simplicity, this documentation will refer to all such applications as games. A multiplayer application has two basic characteristics.

  • Two or more individual users, each with a game client on their computer.
  • Network links that enable the users' computers to communicate with each other, perhaps through a centralized server.

DirectPlay provides a layer that largely isolates your application from the underlying network. For most purposes, your application can simply use the DirectPlay API, and enable DirectPlay to handle the details of network communication. DirectPlay provides many features that simplify the process of implementing many aspects of a multiplayer application, including:

  • Creating and managing both peer-to-peer and client/server sessions
  • Managing users and groups within a session
  • Managing messaging between the members of a session over different network links and varying network conditions
  • Enabling applications to interact with lobbies
  • Enabling users to communicate with each other by voice

This documentation provides a high-level overview of the capabilities of DirectPlay. Subsequent sections will take you into the details of how to use DirectPlay in your multiplayer game.

  • Creating and Managing Sessions
  • DirectPlay Network Communication
  • Communicating with DirectPlay Objects
  • DirectPlay Lobby Support
  • DirectPlay Voice Communication

Note: If you are manufacturing or developing a telecommunications device using the DirectPlay Voice API, it is recommended that you determine whether your product complies with Section 255 of the U.S. Communications Act (47 U.S.C. Sec. 255). That law and associated FCC rules are aimed at ensuring telecommunications devices are accessible to people with disabilities. More information about Section 255 is available from the Disabilities Rights Office at the FCC at www.fcc.gov/cib/dro/. You can also visit www.microsoft.com/enable for more information on accessibility and Microsoft products.


Creating and Managing Sessions

A game session is an instance of a particular multiplayer game. A session has two or more users playing simultaneously, each with the same game client on his or her computer. A player is an entity in the game itself, and is defined by the particular game. Each user may have more than one player in a game. However, the game application must manage these players itself, using separate Microsoft® DirectPlay® interfaces or objects for each player.

The first step in creating a session is to collect a group of users. There are two basic approaches.

  • Many game sessions are arranged by a lobby application running on a remote computer. This approach is used by most Internet-based games.
  • It is also possible to arrange games by having the individual users' computers communicate with each other. This approach is typically limited to such situations as a group of potential users that are all on the same LAN.

Once the session has been arranged, the game is launched and game play begins. As the session proceeds, players may be eliminated from the session, or new players added. The details depend on the individual game.

With a multiplayer game, each user's UI can be synchronized with that of all the other users in the session. Managing a multiplayer session thus requires a continual stream of messages to and from each user. For example, every time a player moves, a message must be sent to update that player's position on all the other game clients in the session. The core of DirectPlay is that part of the API that supports efficient and flexible messaging between all the computers in a session.

There are two basic ways to structure the messaging topology of a session: peer-to-peer and client/server. Both topologies have their advantages and limitations, so you will need to evaluate which is most appropriate for your game.

This section includes the following topics.

  • Peer-to-Peer Topology
  • Client/Server Topology


Peer-to-Peer Topology

A peer-to-peer game consists of the individual players' computers, connected by network links. Schematically, the topology of a four-player peer-to-peer game looks like:

Game play is handled by having each user's game client communicate directly with the other users' clients. For instance, when one user moves, the game client must send three update messages, one to each of the other users' computers.

A peer-to-peer game is normally arranged and launched through a lobby client application that resides on the user's computer. There are two basic ways the lobby client can arrange a session:

  • The lobby client communicates directly with other potential users' lobby clients. This approach can be used, for instance, to arrange a game among users on the same LAN subnet.
  • The lobby client acts as a link to lobby server application running on a remote computer. This is the way Internet-based games are normally arranged.

Once a session has been arranged and launched, most or all of the messaging will be user to user. If a lobby server is involved, it will only be handling such tasks as updating its list of session members when a player leaves the game, or enabling a new user to request entry to the session. Otherwise, the server stays in the background, and is typically not even aware of most of the messages that are being sent.

Because the server is either non-existent or at least not directly involved with the game play, one user is designated as the game host. They are responsible for handling logistical details such as bringing new players into an ongoing session.

Peer-to-peer games have the advantage of simplicity. All that is needed is a collection of players with game clients, and a way to organize a session. The primary drawback of the peer-to-peer topology is scalability. As the number of users increase, the number of messages needed to facilitate game play increases geometrically. The maximum number of users that can be accommodated depends on the game and the network bandwidth, but is typically no more than 20-30.


Client/Server Topology

A client/server game consists of the individual players' computers, connected to a central server computer. Schematically, the topology of a four-player peer-to-peer game looks like:

Game play is handled by having each user's game client communicate with the server. The server is responsible for passing information on to the other users. For instance, when one user moves, they send a message to the server. The server then sends messages to the other players to inform them of a change in game state. The server can have a number of responsibilities:

  • Act as the session's messaging hub. Each computer only needs to send messages to the server. The server handles the logistics of synchronizing all the other users. This arrangement can substantially reduce message traffic, especially for large games.
  • Host the game. The server normally takes care of the tasks that must be handled by the session host in a peer-to-peer game.
  • Support many aspects of the game. The server often does much more than support game logistics. With many games, especially large ones, much of the processing that maintains the "game universe" takes place on the server. The game clients are primarily responsible for handling the user's UI.

A client/server game is normally arranged and launched through a lobby client application that resides on the user's computer. The lobby client acts as a link to a lobby server application that is normally running on a the same remote computer that is hosting the game. Once the game has been launched, the game server application becomes the host, and handles tasks such as admitting new users to the game.

There are a number of advantages to client/server games:

  • They are more efficient, especially for large-scale games. In particular, they scale much better than peer-to-peer games, because additional players only cause a linear increase in the messaging traffic. The client/server topology is necessary for massively-multiplayer games.
  • You not limited by the processing power of your users' computers. You can locate much of the processing required to maintain a large complex "game universe" on a single powerful computer, and let the users' computers handle the UI.
  • You can control key aspects of your game at a central site. For instance, you can often update the game or fix bugs by simply modifying the server application, avoiding the need to update large numbers of game clients.

However, once you have developed and shipped a peer-to-peer game, you are essentially finished. The game clients are largely self-sufficient. With a client/server game, you have an ongoing commitment to your users that goes beyond providing normal support services. You must also provide and maintain a game server computer and the associated software, along with the network links to handle all the messaging, for the lifetime of the application. In the case of massively multiplayer games, you may need to operate your servers for extended periods with few or no breaks in service, or risk angering users by disrupting their game play.


DirectPlay Network Communication

The primary function of Microsoft® DirectPlay® is to provide you with efficient and flexible messaging support that largely isolates your application from the underlying network hardware and software. If you need to send a status update, you can simply call the relevant DirectPlay API, regardless of what kind of network link is involved. DirectPlay network service providers support communication over TCP/IP, IPX, modem, and serial links.

Notes

DirectPlay does not support secure communications.

To use modems on Microsoft Windows® 95 systems, you must install version 2.0 of the Telephony API (TAPI). You can download TAPI 2.0 from http://www.microsoft.com.

DirectPlay Transport Protocol

The core of the Microsoft® DirectPlay® networking capabilities is the DirectPlay protocol. This transport-layer protocol has been completely overhauled for DirectPlay 8, and is now used for all messaging. The DirectPlay protocol is focused on making it simple for you to send data from the sending application to the target application, without needing to worry about what happens in between. The protocol offers a number of features that are tailored to the needs of multiplayer games, including:

  • Reliable and unreliable delivery of messages. Reliable messages will be resent until the target application receives them. You can assign the delivery type on a message-by-message basis.
  • Sequential and non-sequential delivery of messages. Sequential messages will be passed to the target application in the order they were sent.
  • Message fragmentation and reassembly. If message size exceeds the capacity of a particular network, DirectPlay automatically fragments and reassembles the message.
  • Congestion control. DirectPlay automatically throttles your outgoing messages to a level that can be handled by the target. This feature prevents you from flooding the target with more messages than it can process.
  • Send prioritization. To ensure that the most important messages get sent first, DirectPlay enables you to designate messages as low, medium, or high priority. The high priority messages are sent to the front of the output queue, followed by medium and low priority messages.
  • Message timeouts. To prevent the outgoing message queue from being clogged with messages that have been superseded by more recent messages, DirectPlay enables you to assign a timeout value to all messages. When a message times out, it is removed from the outgoing message queue, regardless of whether it has been sent or not.

DirectPlay Addresses

In order to deliver messages, each participant in a multiplayer game must have a unique address. Addresses can refer either to the computer that your application is running on (device address), or a computer that your application needs to communicate with (host address).

Microsoft® DirectPlay® addresses are in the form of URL strings. These strings consist of a scheme, scheme separator, and data string in the following general format.

x-directplay:/[data string]

The data string contains several elements that specify everything that is needed to enable communication to take place between sender and target, over a variety of different types of network link.

In use, the URL strings are embedded in a DirectPlay address object which is passed to or from DirectPlay API methods. You have the option of either manipulating the URL string directly, or using the methods exposed by the address object to handle each element of the data string separately.


Communicating with DirectPlay Objects

Microsoft® DirectPlay® essentially consists of a collection of COM objects. Each object exposes one or more interfaces that enable you to control various aspects of DirectPlay. For instance, the DirectPlay peer object (CLSID_DirectPlay8Peer) is used to manage peer-to-peer games.

You communicate with a DirectPlay object by calling the methods exposed by its interfaces. For instance, to send some data to another user in a peer-to-peer game, you would send a message by calling the DirectPlay8Peer.SendTo method. DirectPlay then takes care of getting the message to its target.

DirectPlay communicates with your application through one or more message handlers. A message handler is an object that DirectPlay calls to notify your application of various events. The documentation describes the methods that are exposed by the object, but you must implement all of the objects methods in your application. You then register the object during startup, and DirectPlay will call the object's methods to notify you when an event has occurred. Additional information about the event is passed through the method's parameters.


DirectPlay Lobby Support

A lobby is an application whose primary purpose is to enable players to meet and arrange games. It is typically located on a remote computer, and accessed over the Internet. Lobby servers often also perform a variety of other functions, such as hosting chat rooms, posting news and information, and selling merchandise. While lobby servers are convenient and commonly used to arrange multiplayer games, they aren't required. Multiplayer games can also be arranged by direct communication between lobby clients.

There are normally three components that are needed to enable a game to interact with a lobby:

  • A lobby server
  • A lobby client
  • A lobbyable game.

Microsoft® DirectPlay® does not specify how you should implement a lobby server application. Instead, DirectPlay provides support for a lobby client. A lobby client is an application that is implemented by a lobby server vendor, and installed on each user's system. It serves as a link between the user and the lobby. While you could handle such communication directly, you would have to know the specific implementation details of every lobby that might launch your game.

The lobby client application handles the details of communicating with its associated lobby server, using whatever protocols are appropriate. The lobby client communicates with the user and their game applications through a DirectPlay interface. DirectPlay then passes messages to the application. The application can also use a DirectPlay interface to pass messages to the lobby client.

A lobby can launch virtually any application. However, the application must have some specific lobby-aware components to take full advantage of lobby-launching. In particular, a lobbyable application can communicate with the lobby client throughout the course of the session. If an application is registered as lobbyable, the lobby client also automatically receives updates for various changes in game status, such as host migration.


DirectPlay Voice Communication

The current trend toward team-based multiplayer games makes player-to-player communication an essential part of game play. Historically this has been confined to text-based communication, where players type out the messages to their teammates. Although suitable for slower, turn-based games, text-based communication is at best an inconvenience for real-time games. Not only does it put slow typists at a disadvantage during game play but also it is a significant break in the reality that games attempt to create for the player. An obvious solution to the problem is the use of speech as a means for communication. It requires no training and increases the immersion of the game itself.

The Microsoft® Windows® platform provides all the tools required to provide real-time voice conferencing to video game developers, but it requires a significant amount of effort on the part of the game developer. This, combined with the cost and difficulty of obtaining the rights to compression technology capable of handling extremely low bandwidth situations, has prevented the widespread use of voice in games.

Microsoft DirectPlay® 8.1 provides the game developer with a robust real-time voice conferencing system that requires minimal effort to use.


Understanding DirectPlay

This section of the Microsoft® DirectPlay® documentation provides the background you need to understand how to use the DirectPlay application programming interface (API) in your application.

  • Peer-to-Peer Sessions
  • Client/Server Sessions
  • DirectPlay Lobbies
  • Basic Networking
  • Understanding DirectPlay Voice


Peer-to-Peer Sessions

A peer-to-peer session consists of a collection of users connected by a network. While a lobby server may be used to arrange and launch the game, the messaging needed to run the game is sent directly from one user's to another. Any communication with the lobby server is for such limited purposes as updating the list of participants.

With a peer-to-peer game, everything that is needed to run the game is part of the client software. With no server involved, all the processing needed to create and maintain the game universe must be handled by the client applications. This document discusses the basic principles of a lobbyable Microsoft® DirectPlay® peer-to-peer game. For a simple working example of a peer-to-peer application, see the SimplePeer application included with the SDK.

  • Initiating a Peer-to-Peer Session
  • Selecting a Service Provider for a Peer-to-Peer Session
  • Selecting a Host for a Peer-to-Peer Session
  • Connecting to a Peer-to-Peer Session
  • Managing a Peer-to-Peer Session
  • Host Migration
  • Normal Peer-to-Peer Game Play
  • Leaving a Peer-to-Peer Session
  • Terminating a Peer-to-Peer Session


Initiating a Peer-to-Peer Session

A peer-to-peer game can be launched directly by the user, or lobby-launched by a lobby client application that resides on the user's computer. This documentation will assume that the game is lobbyable, and can communicate with the lobby client.

One of the first steps you should take is to determine whether your game was lobby-launched. To do so, create a DirectPlay8LobbiedApplication object and a DirectPlay8LobbyEvent object. Register the DirectPlay8LobbyEvent object with Microsoft® DirectPlay® by calling DirectPlay8LobbiedApplication.RegisterMessageHandler. The DirectPlay8LobbyEvent object is essentially an event handler that receives notifications directly from the lobbied application object, and indirectly from the lobby client and the lobby. It is not provided by DirectPlay and must be implemented by your application. See the reference documentation for details.

If the application was lobby-launched, DirectPlay will call your DirectPlay8LobbyEvent.Connect method. The dlNotify parameter will contain a DPL_MESSAGE_CONNECT type with connection information. such as address objects for the members of the session.

You should also create a DirectPlay8Peer object and register a DirectPlay8Event notification handler object by calling DirectPlay8Peer.RegisterMessageHandler. These objects will be your primary means of communicating with DirectPlay and the other users in the session. If you want to have multiple players in the session, you must create a separate instance of these objects for each player.


Selecting a Service Provider for a Peer-to-Peer Session

The service provider is your network connection. Most games use either the TCP/IP or modem service provider, but Microsoft® DirectPlay® also provides support for serial and IPX connections.

If your user was connected to the session by a lobby client, you can determine the appropriate service provider by examining the DPL_CONNECTION_SETTINGS type that you receive when DirectPlay calls your DirectPlay8LobbyEvent.Connect. Otherwise, you may need to determine which service provider to use, perhaps by querying the user. You can use the client object's DirectPlay8Client.GetServiceProvider method to enumerate the available service providers. See Using DirectPlay Enumerations for further discussion.

Once you have selected a service provider, you can then create a DirectPlay address object for your user (a device address). You will use this address to identify your device with a number of DirectPlay methods. See DirectPlay Addressing for a detailed discussion of DirectPlay addresses and address objects.


Selecting a Host for a Peer-to-Peer Session

Although most aspects of peer-to-peer games can be handled by the various users' communicating directly with each other, there are some tasks that must have a single owner. These tasks are handled by the game host. To join a session, you must know the address of the session's host. A common way to select a host is through a lobby server. In that case, when a user's application is connected to the session, the connection settings that you receive when Microsoft® DirectPlay® calls your DirectPlay8LobbyEvent.Connect method include the host's address object. To find out who the session host is:

  • Check the dwFlags member of the DPL_CONNECTION_SETTINGS structure that is contained in the DPL_MESSAGE_CONNECTION_SETTINGS passed as the dlNotify parameter. If that member is set to DPLCONNECTSETTINGS_HOST, your system is the host.
  • If the DPLCONNECTSETTINGS_HOST flag is not set, then you can get the address of the host from the pdp8HostAddress member.

You can also create a broadcast session, perhaps on a LAN subnet, by advertising yourself as a session host. To do so call DirectPlay8Peer.SetPeerInfo to set the player's name and then call DirectPlay8Peer.Host to advertise yourself as a potential host. You specify the configuration of the game by assigning values the DPN_APPLICATION_DESC type that is passed through the pdnAppDesc parameter of IDirectPlay8Peer.Host.

To allow your user to examine the available sessions and hosts, you can enumerate the available hosts by calling DirectPlay8Peer.EnumHosts. Once the user has selected a session, you can request a connection.


Connecting to a Peer-to-Peer Session

Unless you are the session host, you will need to connect your player to the session. To do so, you must have the address of the session host. If your application was connected by a lobby client, you can obtain the host's address by calling DirectPlay8LobbiedApplication.GetConnectionSettings. You can also obtain the address by enumerating the available hosts. The information returned by the enumeration includes each host's addresses, and a DPN_APPLICATION_DESC structure that describes the associated session.

To ask to join a session, call DirectPlay8Peer.SetPeerInfo to set your player's name, and then call DirectPlay8Peer.Connect with the selected host's address to connect to the session.

When a player attempts to join a session, the Microsoft® DirectPlay® calls the host's DirectPlay8Event.IndicateConnect method. To accept the player into the session, set the method's fRejectMsg parameter to False before returning. Setting fRejectMsg to True rejects the request. In either case, the player's DirectPlay8Event.ConnectComplete method will be called with the response. If the host accepted the connection, the hResultCode member of the DPNMSG_CONNECT_COMPLETE type will be set to 0. If the request was rejected or failed for some other reason, hResultCode will be set to an error code.

Once the new player is connected, DirectPlay announces the new player by calling DirectPlay8Event.CreatePlayer for each member of the session, including the host. The lPlayerID parameter contains the player ID that you will use to send messages to that player.


Managing a Peer-to-Peer Session

The session host is responsible for managing the session, including:

  • Managing the list of session members and their network addresses
  • Deciding whether a new user is allowed to join the session.
  • Notifying all members when a new user joins the session, and passing them the new user's address.
  • Providing new users with the current game state
  • Notifying all users when a user leaves the session

When players attempt to join a session, Microsoft® DirectPlay® will call the host's DirectPlay8Event.IndicateConnect method. To accept the player into the session set fRejectMsg to False. Setting fRejectMsg to any other value rejects the request. In either case, DirectPlay calls the player's DirectPlay8Event.ConnectComplete method with the response to the request.

The host can remove a player from the session by calling DirectPlay8Peer.DestroyPeer. Other members of the session cannot call this method successfully. If you want to allow players to request that another player be removed from the session, you must send the request to the host, and have the host handle the request.


Host Migration

While the host must be one of the initial members of the session, they may choose to leave before session is finished. When the host leaves the session, there are two possible outcomes:

  • The session terminates.
  • The host migrates, and another user becomes host.

Sessions may or may not permit host migration. To enable host migration, the session organizer must set the DPNSESSION_MIGRATE_HOST flag in the dwFlags member of the DPN_APPLICATION_DESC type when they set up the game. If this flag is not set, the session terminates when the host leaves or loses their connection.

If the DPNSESSION_MIGRATE_HOST flag is set, the host can still force the session to terminate by calling DirectPlay8Peer.TerminateSession.

If DPNSESSION_MIGRATE_HOST flag is set and the host leaves the session, Microsoft® DirectPlay® will select a new session host. DirectPlay will call the DirectPlay8Event.HostMigrate method of all remaining session members with the ID of the new host.


Normal Peer-to-Peer Game Play

In Microsoft® DirectPlay® , a message is essentially a block of game-related data that you send to one or more members of the session. DirectPlay does not specify the contents or format of the data block, it just provides a mechanism to transmit the data from one user to another. Once the game is underway, each session member will normally send a constant stream of messages to all other members of the session for the duration of the game. The primary purpose of these messages is to keep the game state synchronized, so that each user's application displays the same UI. However, messages can also be used for a variety of other game-specific purposes.

For many games, especially rapidly changing ones, you may have to manage your messaging carefully. DirectPlay throttles outgoing messages to a level that can be handled by the target. You will have be careful that you do not send messages too rapidly, and ensure that the most important messages get through. See Basic Networking for a discussion of how to effectively handle DirectPlay messaging.

To send a message to another session member, call DirectPlay8Peer.SendTo. DirectPlay will call that members DirectPlay8Event.Receive method with the data. To send a message to a specific player, set the idSend parameter to the player ID that you when your DirectPlay8Event.CreatePlayer method was called. You can also send a message to every player in the session by setting idSend to DPNID_ALL_PLAYERS_GROUP. You can also define groups of players, and use a single SendTo call to send a message to all members of a group.

Note You can also use the DirectPlay8Peer.SetPeerInfo method to send information to other users. DirectPlay will call their DirectPlay8Event.InfoNotify method with the information. However, this way of transmitting information is not very efficient, and should not be used for normal messaging.

Using Groups

Many games allow players to be organized into groups. For instance, strategy games typically allow individual players to be organized into groups that can then be directed as a single entity. Microsoft® DirectPlay® also allows the formation of groups of players. DirectPlay groups are essentially a way to simplify your messaging. Once you have defined a group, you can send a message to every group member with a single DirectPlay8Peer.SendTo . While DirectPlay groups normally correspond to the groups that are defined by the game, you are free to create a group for any reason.

To create a DirectPlay group, call DirectPlay8Peer.CreateGroup. DirectPlay will call all session members' DirectPlay8Event.CreateGroup method with the details. The method's lGroupID parameter will be set to the group ID that you can use to send messages to the group.

Once the group is created, you then add players by calling DirectPlay8Peer.AddPlayerToGroup. DirectPlay will then call all members' DirectPlay8Event.AddRemovePlayerGroup with the IDs of the group and the player that was just added.

Once the group is established, you can send data to the group by calling DirectPlay8Peer.SendTo, with the idSend parameter set to the group ID. DirectPlay will call all group members' DirectPlay8Event.Receive method with the data.

To remove a player from a group, call DirectPlay8Peer.RemovePlayerFromGroup. DirectPlay will call the session members' DirectPlay8Event.AddRemovePlayerGroup method with the player's ID.

Finally, when you no longer need the group, you can destroy it by calling DirectPlay8Peer.DestroyGroup. DirectPlay will call all session members' DirectPlay8Event.DestroyGroup method with the group ID.


Leaving a Peer-to-Peer Session

To leave a session, terminate the connection by calling DirectPlay8Peer.Close. Microsoft® DirectPlay® will call the session members DirectPlay8Event.DestroyPlayer method with the lPlayerID parameter set to the player's ID.

If you are the session host, leaving also terminates the session unless you configured the session to allow host migration. See Host Migration for details.


Terminating a Peer-to-Peer Session

When the session is over, the host should terminate the session by calling DirectPlay8Peer.TerminateSession. This method terminates the session even if host-migration is enabled. Microsoft® DirectPlay® will notify all session members by calling their DirectPlay8Event.TerminateSession method. You should then perform any necessary cleanup. To start another session, you must first call DirectPlay8Peer.Close, and then DirectPlay8Peer.RegisterMessageHandler.

If you registered your application as available for connection by calling DirectPlay8LobbiedApplication.SetAppAvailable a lobby client can offer to connect you to a new session by calling your DirectPlay8LobbyEvent.Connect method. You must have first called DirectPlay8Peer.Close and DirectPlay8.RegisterMessageHandler.


Client/Server Sessions

A client/server session consists of a collection of players, or clients, connected to a central server. As far as Microsoft® DirectPlay® is concerned, a client has no knowledge of any other clients, only the server. The messaging needed to run the game is between the individual clients and the server. DirectPlay does not provide direct client-to-client messaging, as it does for peer-to-peer sessions.

A client/server session requires two distinctly different applications.

  • The server application runs on a remote server. At a minimum, it serves as a central messaging hub and game host. The server must receive and handle all incoming messages from the clients, and send appropriate messages back out. Any transfer of data from one client to another must be handled by the server application.
  • A client application runs on each players' computer. The primary function of this application is to handle the UI, and keep the player's game state synchronized with the server.

There are certain aspects of the session that can be handled by only one of these applications. For instance, updating a player's video display can only be done by the client application. However, many aspects of the processing needed to maintain the game universe can, at least in principle, be done by either application. Writing an effective client/server game requires some careful consideration of how to divide the processing chores between the two applications.

This document describes the basic principles of client server games, and outlines how to implement client and server applications.

  • Initiating a Client/Server Session
  • Selecting a Service Provider for a Client
  • Selecting a Client/Server Host
  • Connecting to a Client/Server Session
  • Managing a Client/Server Session
  • Normal Client/Server Game Play
  • Leaving a Client/Server Session
  • Terminating a Client/Server Session


Initiating a Client/Server Session

A client/server game can be launched through a lobby, or directly by the server application.

The Server Application

Client/server games are often arranged through lobbies. The most straightforward way to launch the server is to implement it as a lobbyable application. This approach provides a way to launch the server, and supports communication between server and lobby during the course of the session. See DirectPlay Lobbies for further discussion.

A server can also be directly launched, and then advertise itself as available and wait for clients to connect. See Selecting a Client/Server Host for details.

Once the server application has been launched, it should register it's DirectPlay8Event notification handler object. The DirectPlay8Event object is essentially an event handler that receives notifications from Microsoft® DirectPlay® . It is not provided by DirectPlay and must be implemented by your application. See the reference documentation for details. You should also call DirectPlay8Server.SetServerInfo to describe the current game. Clients cannot connect to a server until this method has been called.

The Client Application

One of the first steps you should take is to determine whether your game was lobby-launched. To do so, create a DirectPlay8LobbiedApplication object and a DirectPlay8LobbyEvent object. Register the DirectPlay8LobbyEvent object with Microsoft® DirectPlay® by calling DirectPlay8LobbiedApplication.RegisterMessageHandler. The DirectPlay8LobbyEvent object is essentially an event handler that receives notifications directly from the lobbied application object, and indirectly from the lobby client and the lobby. It is not provided by DirectPlay and must be implemented by your application. See the reference documentation for details.

If the application was lobby-launched, DirectPlay will call your DirectPlay8LobbyEvent.Connect method. The dlNotify parameter will contain a DPL_MESSAGE_CONNECT type with connection information. such as address objects for the members of the session.

You should also create a DirectPlay8Client object and register a DirectPlay8Event notification handler object by calling DirectPlay8Client.RegisterMessageHandler. These objects will be your primary means of communicating with the server.


Selecting a Service Provider for a Client

The service provider is your network connection. Most games use either the TCP/IP or modem service provider, but Microsoft® DirectPlay® also provides support for serial and IPX connections.

If your user was connected to the session by a lobby client, you can determine the appropriate service provider by examining the DPL_CONNECTION_SETTINGS type that you receive when DirectPlay calls your DirectPlay8LobbyEvent.Connect. Otherwise, you may need to determine which service provider to use, perhaps by querying the user. You can use the client object's DirectPlay8Client.GetServiceProvider method to enumerate the available service providers. See Using DirectPlay Enumerations for further discussion.

Once you have selected a service provider, you can then create a DirectPlay address object for your user (a device address). You will use this address to identify your device with a number of DirectPlay methods. See DirectPlay Addressing for a detailed discussion of DirectPlay addresses and address objects.


Selecting a Client/Server Host

By definition, the server application hosts the session. To join a session, a client application must determine the host server's address. A common way to select a host is through a lobby server. In that case, when a user's application is connected to the session, the connection settings that you receive when your DirectPlay8LobbyEvent.Connect method is called include a connection ID and the host's address.

Servers using an IP or IPX service provider can also create a broadcast session, perhaps on a LAN subnet, by advertising themselves as session hosts. To create a broadcast session, call DirectPlay8Server.SetServerInfo to specify the server settings. Then call DirectPlay8Server.Host to advertise the server as a session host. You specify the configuration of the game by assigning values to the DPN_APPLICATION_DESC structure that is passed through the AppDesc parameter of DirectPlay8Server.Host.

To allow your user to look at the available sessions and hosts, a client application can query for available hosts by calling DirectPlay8Client.EnumHosts. Once the user has selected a host, you can request a connection.


Connecting to a Client/Server Session

All clients must explicitly join the session by connecting to the host, even if the session has been arranged through a lobby. A connection establishes the client as a member of the session, and provides the host with the information it needs to communicate with the client. The host has the option of accepting or rejecting a connection request.

The Server Application

When a client attempts to join a session, the Microsoft® DirectPlay® calls the server's DirectPlay8Event.IndicateConnect method. To accept the player into the session, set the method's fRejectMsg parameter to False before returning. Setting fRejectMsg to True rejects the request. In either case, the player's DirectPlay8Event.ConnectComplete method will be called with the response. If the host accepted the connection, hResultCode member of the DPNMSG_CONNECT_COMPLETE type will be set to 0. If the request was rejected or failed for some other reason, hResultCode will be set to an error code.

If the player is successfully added to the session, DirectPlay will call the DirectPlay8Event.CreatePlayer method for the server and all client's with the new player's ID (DPNID).

The Client Application

To connect to a session, you must have the address of the session host. If your application was connected by a lobby client, you can obtain the host's address by calling DirectPlay8LobbiedApplication.GetConnectionSettings.

If you not have the address of a session host and you are using either an IP or IPX service provider, you can look for broadcast sessions by calling DirectPlay8Client.EnumHosts and enumerating the available hosts. You can also obtain the address by enumerating the available hosts. The information returned by the enumeration includes each host's address, the device use to reach the host, and a DPN_APPLICATION_DESC type that describes the associated session.

To ask to join a session, call DirectPlay8Client.SetClientInfo to set your player's name, and then call DirectPlay8Client.Connect with the selected host's address to connect to the session.

Microsoft® DirectPlay® will call your DirectPlay8Event.ConnectComplete method with the host's response. If the host accepted the connection, the hResultCode member of the DPNMSG_CONNECT_COMPLETE type will be set to 0. If the request was rejected or failed for some other reason, hResultCode will be set to an error code.


Managing a Client/Server Session

As host, the server is responsible for managing the course of the session. The details will depend on how the application is designed, but a session host's duties include, at a minimum,:

  • Managing the list of session members and their network addresses. Microsoft® DirectPlay® handles some of this task, but server applications typically need to manage more player data than is provided by DirectPlay.
  • Deciding whether a new user is allowed to join the session.
  • Providing new users with the current game state.

When a player attempts to join a session, DirectPlay calls the host's DirectPlay8Event.IndicateConnectmethod. To accept the player into the session set fRejectMsg to False. Setting fRejectMsg to any other value rejects the request. In either case, DirectPlay calls the player's DirectPlay8Event.ConnectComplete method with the response to the request.

The host can remove a player from the session by calling DirectPlay8Server.DestroyClient.


Normal Client/Server Game Play

In Microsoft® DirectPlay® , a message is essentially a block of game-related data that is sent from client to server or vice versa. DirectPlay does not specify the contents or format of the data block, it just provides a mechanism to transmit the data. Once the game is underway, each client will normally send a constant stream of messages to the server, and vice versa, for the duration of the game. The primary purpose of these messages is to keep the game state synchronized, so that each user's application displays the same UI. However, messages can also be used for a variety of other game-specific purposes.

For many games, especially rapidly changing ones, you may have to manage your messaging carefully. DirectPlay throttles outgoing messages to a level that can be handled by the target. You will have be careful that you do not send messages too rapidly, and ensure that the most important messages get through. See Basic Networking for a discussion of how to effectively handle DirectPlay messaging.

The Server Application

To send a message to a client, call DirectPlay8Server.SendTo. DirectPlay will call the client's DirectPlay8Event.Receive method with the data.

The Client Application

To send a message to the server, call DirectPlay8Client.Send. DirectPlay will call the server's DirectPlay8Event.Receive method with the data.

Note DirectPlay does not provide a mechanism for clients to communicate with other clients, only with the server. Any client-client communication must be implemented by the server application.

Using Groups

Many games allow players to be organized into groups. For example, in a squad-based game, every player in the squad could be a member of a group. DirectPlay allows servers in a client/server game to create groups of players. While DirectPlay groups typically correspond to the groups that defined by the game, you are free to create a group for any reason. DirectPlay groups are essentially a way to simplify your messaging. Once you have defined a group, you can send a message to every group member with a single DirectPlay8Server.SendTo call.

To create a DirectPlay group, call DirectPlay8Server.CreateGroup. DirectPlay will call your DirectPlay8Event.CreateGroup method with the details. The notification will include a group ID that is used to send messages to the group. Once the group is created, you then add players by calling DirectPlay8Server.AddPlayerToGroup.

Once the group is established, you can send data to the group by calling DirectPlay8Server.SendTo, with the idSend parameter set to the group ID. DirectPlay will then call the group members' DirectPlay8Event.Receive method with the data.

To remove a player from a group, call DirectPlay8Server.RemovePlayerFromGroup. Finally, when you no longer need the group, you can destroy it by calling DirectPlay8Server.DestroyGroup.


Leaving a Client/Server Session

A client can leave a session by calling DirectPlay8Client.Close. Microsoft® DirectPlay® notifies the server by calling its DirectPlay8Event.DestroyPlayer method.


Terminating a Client/Server Session

To terminate a client/server session, the server calls DirectPlay8Server.Close. There is no host migration in a client/server session, so this method terminates all connections and closes the session. Microsoft® DirectPlay® notifies the clients by calling their DirectPlay8Event.TerminateSession method.

DirectPlay then calls the server's DirectPlay8Event.DestroyPlayer method for each player, including itself. DirectPlay8Server.Close is synchronous, and will not return until all the DirectPlay8Event.DestroyPlayer method calls have been processed. Once DirectPlay8Server.Close has returned, you can safely shut down the server application.


DirectPlay Lobbies

A lobby is an application whose primary purpose is to help users arrange multiplayer games. The lobby is usually an application that is hosted on a remote server. The user visits the lobby, typically through the Internet, and either sets up a game session or joins a session started by someone else. The lobby application then launches the group's individual game applications, and the game is underway.

Because many multiplayer games are arranged through lobbies, most games based on Microsoft® DirectPlay® must be able to interact with lobby applications. Conversely, because most lobbies will want to support DirectPlay-based games, the lobby application must be able to interact with the game application. This document discusses how to enable a Microsoft DirectX® game to interact with a lobby, and vice versa.

  • DirectPlay Lobby Architecture
  • Lobby Servers
  • Lobby Clients
  • Lobbyable Applications


DirectPlay Lobby Architecture

The process of arranging and managing a session of a multiplayer game based on Microsoft® DirectPlay® involves five separate components. The lobby server application is a third-party application that typically resides on a remote server and is accessed through the Internet. The remaining four components are installed on each player's computer.

  • Lobby client. The lobby client is a third-party application that communicates with the lobby server. It also communicates with the user's game application through the DirectPlay lobby client object.
  • Lobbyable game application. The lobbyable game application is a third-party application that uses the DirectPlay lobbied application object to communicate with the lobby client, and through the lobby client with the lobby server.
  • DirectPlay lobby client object.
  • DirectPlay lobbied application object.

The two DirectPlay objects act as links between the game application and the lobby client. They communicate with each other through private interfaces. The following graphic shows how these pieces are linked, and how they communicate.


Lobby Servers

The lobby server is an application whose primary purpose is to enable players to meet and arrange games. It is typically located on a remote computer, and accessed over the Internet. Lobby servers often perform a variety of other functions such as hosting chat rooms, posting news and information, and selling merchandise.

To manage multiplayer games, a lobby server typically handles a variety of tasks, including:

  • Managing the network addresses of the various game sessions and players.
  • Launching a session by launching the associated game applications on the players' computers.
  • Adding players to an ongoing session.
  • Connecting the various computers in a session to the correct network addresses.
  • Keeping track of changes in the session, such as players leaving the game or changes in the game's host.

The details of the lobby server application depend on what kind of services the vendor wants to offer. Microsoft® DirectPlay® does not specify how a lobby server should be implemented nor how it should communicate with its users' computers. However, lobby vendors must implement and distribute to their users a lobby client that is compatible with DirectPlay.


Lobby Clients

A lobby client is an application that is implemented by the lobby server vendor and installed on each player's computer. It handles communication between the players and their game applications, and the lobby server. A common way to install a lobby client is to have the user download it from the lobby server's Web site as part of the sign-up procedure.

The following is a typical scenario.

  1. A new player goes to the Web site and signs up.
  2. As part of the sign-up procedure, the lobby client is downloaded to the client's computer.
  3. The player determines which game to play and asks to join a session.
  4. The Web site launches the lobby client on the player's computer. A typical launch mechanism is a URL that points to the lobby client's executable file.
  5. The lobby client handles the mechanics of arranging the session, and then launches the user's game application.
  6. If the game is a lobbyable application, the lobby client enables the game application to communicate with the lobby server. This connection enables the lobby server to keep track of events such as players entering and leaving the game and host migration.

Lobby clients do not necessarily have to be linked to a remote server. In another scenario the user launches the lobby client directly. The lobby client then lists the available games and sessions, perhaps among the people connected to the user's LAN subnet. Once the user chooses a game and session, the lobby client launches the game.

This section discusses some of the general features of a lobby client. For more information on communicating between a lobby client and its associated lobby server, see Communicating with a Lobbied Application.

For more information on implementation details, see Implementing a Lobby Client or the LobbyClient sample application included in the SDK.

Communicating with a Lobby Client

Much of the lobbied application's interaction with an associated lobby client is indirect. The application does something that affects the lobby client, Microsoft® DirectPlay® sends an appropriate message, and vice versa. For instance, if the application changes the connection settings, DirectPlay notifies the lobby client, and provides the new settings. However, there are two methods that provide information directly to the lobby client: DirectPlay8LobbiedApplication.UpdateStatus and DirectPlay8LobbiedApplication.Send.

You must notify the lobby client when any of the following changes in the game status take place.

  • The session is connected.
  • The session could not connect.
  • The session has been disconnected.
  • The session has been terminated.
  • The session host has migrated.
  • This computer has become the session host.

To notify the lobby client of one of these status changes, call DirectPlay8LobbiedApplication.UpdateStatus, and set the lStatus parameter to the appropriate value. DirectPlay will call the lobby client message handler's DirectPlay8LobbyEvent.SessionStatus method to notify it of the status change.

The DirectPlay8LobbiedApplication.Send method enables the application to send a message directly to the lobby client. DirectPlay passes the data to the lobby client without modification. It is the responsibility of the lobby client to process that data.

The lobby client can also send data directly to the application. DirectPlay passes the data to the lobby client's message handler by calling its DirectPlay8LobbyEvent.Receive method. DirectPlay passes the data to the application without modification. The lobby client must process the data.


Lobbyable Applications

Lobbyable applications are designed to work with a lobby client based on Microsoft® DirectPlay® . While a lobby client can use DirectPlay to launch any application, lobbyable applications have a number of advantages.

  • The lobby client receives automatic updates when game status changes.
  • The lobby client can use a standard API to communicate with the application.
  • The application can use a standard API to communicate with the lobby client.

In short, DirectPlay virtually eliminates the need for game-specific or lobby client-specific communication code. You can use a standard API for everything with little or no modification for the particular game or lobby client.

For a discussion of implementation details, see Implementing a Lobbyable Application or SDK samples such as SimplePeer, or StagedPeer.

Launching a Lobbyable Application

One of the first things a lobbyable application should do after it is launched is create a DirectPlay8LobbiedApplication object. Among other things, this object enables your application to determine whether it was lobby-launched. A lobbied application must also implement a message-handler callback function to receive messages from the lobby client. The basic procedure is:

  1. Create a DirectPlay8LobbiedApplication object.
  2. Register a DirectPlay8LobbyEvent message handler object by calling DirectPlay8LobbiedApplication.RegisterMessageHandler. If the application was lobby-launched, DirectPlay will call your DirectPlay8LobbyEvent.Connect method. The dlNotify parameter will contain a DPL_MESSAGE_CONNECT type with connection information such as address objects for the members of the session.

Note The DirectPlay8LobbyEvent object is essentially an event handler that receives notifications directly from the lobbied application object, and indirectly from the lobby client and the lobby. It is not provided by DirectPlay and must be implemented by your application. See the reference documentation for details.

Once an application has been successfully lobby launched, Microsoft® DirectPlay® automatically sends status updates to the lobby client when events such as host migration occur. You can also use the lobbied application interface to send messages to the lobby client.

Be aware that your message handler object might be called by the lobby client before the initialization method returns. In addition to the connection message, the DirectPlay calls the object when the lobby client changes connection settings, or it breaks the connection. The lobby client can also send messages directly to your message handler that contain game-specific information.


Basic Networking

This section covers some basic networking technology topics that you need to understand to write Microsoft® DirectPlay® applications. For a general discussion of networking technology, see one of the standard texts on the subject, such as Computer Networks by Andrew Tannenbaum.

  • DirectPlay Service Providers
  • DirectPlay Addressing
  • DirectPlay Protocol
  • Optimizing Network Usage
  • Network Address Translation, Firewalls, and Proxies
  • Using the DirectX Protocol in an Application


DirectPlay Service Providers

Microsoft® DirectPlay® provides your application with a virtual network connection that enables you to communicate with other computers in the same way, regardless of type of network involved. To provide this level of abstraction, network connections are made through a service provider. Once you have selected a service provider, your application uses the appropriate DirectPlay methods to communicate with other computers in a session. The service provider handles the details of communicating over the selected network hardware.

DirectPlay includes service providers for four types of network connections: TCP/IP, IPX, modem, and serial. See DirectPlay Addressing for a discussion of how to select a service provider.

Note To use modems on Microsoft Windows® 95 systems, you must install version 2.0 of the Telephony API (TAPI). You can download TAPI 2.0 from http://www.microsoft.com.


DirectPlay Addressing

To deliver messages, each participant in a multiplayer game must have a unique address. Addresses can refer to either the computer on which your application is running (device address) or a computer with which your application needs to communicate (host address).

Microsoft® DirectPlay® 8.1 represents addresses in the form of a URL string. The address string is then encapsulated in a DirectPlay8Address object that is passed as a parameter in or out of methods such as DirectPlay8Peer.Connect.

This section describes two ways to handle DirectPlay addresses.

  • DirectPlay URLs discusses how to construct the address string directly.
  • Handling Addresses discusses how to pass address objects in the Host, EnumHosts, or Connect methods.
  • DirectPlay Address Objects discusses how to manipulate the address string using the methods exposed by the address object's DirectPlay8Address class.


DirectPlay URLs

Microsoft® DirectPlay® represents addresses as URLs. In general, URLs are strings that consist of three basic components in the following order: scheme, scheme separator, and data string.

All DirectPlay addresses use "x-directplay" as the scheme, and ":/" (a colon followed by a forward slash) as the scheme separator. Using ":/" as a separator implies that the data that follows is opaque. In other words, the data string does not conform to any Internet standard and should be passed to the receiving application without modification. All DirectPlay URLs thus have the following general form.

x-directplay:/[data string]

Note Do not use "://" (a colon followed by two forward slashes) as a scheme separator. That separator implies that the data that follows conforms to an Internet standard and can be interpreted as such. To prevent confusion, DirectPlay flags any URL containing"://" as invalid.

This section discusses the following topics.

  • Data Strings
  • Data Values
  • Data Value Summary
  • Sample URLs


Data Strings

The data string holds address information. The first part of a data string consists of a series of keyname=value elements separated by semicolons (;). You can include optional user data by putting a number sign (#) after the last value, followed by an application-defined string.

The key name is a lowercase string that identifies the data and implicitly indicates what type of data is contained in the value. For instance, the "provider" key name indicates that the value contains a Microsoft® DirectPlay® service provider GUID, in the form of a GUID string. The following characters are reserved and should not be used in value strings.

Ampersand (&) | Forward slash (/)
At sign (@) | Number sign (#)
Colon (:) | Question mark (?)
Equal sign (=) | Semicolon (;)

The first element in the data string must be the provider. Other elements can follow in any order. A generic URL looks something like this.

x-directplay:/provider=%provider GUID%;[keyname1=value1];[keyname2=value2][...]#[user defined string]


Data Values

The values that need to be included in the data string depend on the particular service provider. Modem providers, for instance, need a telephone number in their address, whereas LAN providers might need a port number. This section provides a detailed description of the standard data values. It also includes a key name that can be used in place of the literal string. These names are defined in Dpaddr.h.

  • Application Instance
  • Baud
  • Device
  • Flow Control
  • Host Name
  • Parity
  • Phone Number
  • Port
  • Program
  • Provider
  • Stop Bits

Application Instance

An optional GUID that identifies an application instance. This value is used when specifying the game that is to be connected to.

Key Name: DPNA_KEY_APPLICATION_INSTANCE

Key String: "applicationinstance"

Data Type: GUID

Providers: All

Valid Values: Any valid application instance GUID

Baud

The baud rate

Key Name: DPNA_KEY_BAUD

Key String: "baud"

Data Type: DWORD

Providers: Modem and serial

Valid Values: Any valid baud rate. You can set this value to the appropriate integer, or you can use one of the following predefined values from Dpaddr.h.

DPNA_BAUD_RATE_9600
DPNA_BAUD_RATE_14400
DPNA_BAUD_RATE_19200
DPNA_BAUD_RATE_38400
DPNA_BAUD_RATE_56000

Device

A GUID that identifies the device on the local computer that will be used. If the service provider supports all adapters, you do not need to specify a device.

Key Name: DPNA_KEY_DEVICE

Key String: "device"

Data Type: GUID

Providers: All, but for device addresses only, not host addresses

Valid Values: Any valid device GUID.

Flow Control

The type of flow control to be used

Key Name: DPNA_KEY_FLOWCONTROL

Key String: "flowcontrol"

Data Type: String

Providers: Serial and modem

Valid Values: Any of the following predefined values from Dpaddr.h.

DPNA_FLOW_CONTROL_NONE | DPNA_FLOW_CONTROL_DTR
DPNA_FLOW_CONTROL_XONXOFF | DPNA_FLOW_CONTROL_RTSDTR
DPNA_FLOW_CONTROL_RTS |

Host Name

The name of a remote host computer

Key Name: DPNA_KEY_HOSTNAME

Key String: "hostname"

Data Type: String

Providers: All, but for host addresses only, not device addresses

Valid Values: A fully-qualified host name, or a dotted address.

Parity

The parity of the connection

Key Name: DPNA_KEY_PARITY

Key String: "parity"

Data Type: String

Providers: Serial and modem

Valid Values: Any of the following predefined values from Dpaddr.h.

DPNA_PARITY_NONE | DPNA_PARITY_MARK
DPNA_PARITY_EVEN | DPNA_PARITY_SPACE
DPNA_PARITY_ODD |

Phone Number

A phone number

Key Name: DPNA_KEY_PHONENUMBER

Key String: "phonenumber"

Data Type: String

Providers: Modem

Valid Values: Any valid phone number

Port

An optional port number

Key Name: DPNA_KEY_PORT

Key String: "port"

Data Type: DWORD

Providers: IP and IPX

Valid Values: Any 16-bit integer. Only the lower 16 bits of the value are valid. If you do not specify a port, DirectPlay will choose one for you.

Program

An optional application GUID

Key Name: DPNA_KEY_PROGRAM

Key String: "program"

Data Type: GUID

Providers: All

Valid Values: Any valid application GUID

Provider

A GUID that identifies the Microsoft® DirectPlay® service provider that will be used

Key Name: DPNA_KEY_PROVIDER

Key String: "provider"

Data Type: GUID

Providers: All.

Valid Values: Any valid service provider GUID

Stop Bits

The number of stop bits

Key Name: DPNA_KEY_STOPBITS

Key String: "stopbits"

Data Type: String

Providers: Serial and modem

Valid Values: Any of the following predefined values from Dpaddr.h.

DPNA_STOP_BITS_ONE | DPNA_STOP_BITS_TWO
DPNA_STOP_BITS_ONE_FIVE |


Data Value Summary

The following two tables outline the standard data values, and they indicate which values are used by each type service provider for both host and device addresses.

Host Addresses

 | IP | IPX | Serial | Modem
Application Instance | Optional | Optional | Optional | Optional
Baud | Not used | Not used | Required |
Device | Not used | Optional | Required | Required
Flow Control | Not used | Not used | Required |
Host Name | Required | Required | Optional | Optional
Parity | Not used | Not used | Required |
Phone Number | Not used | Not used | Not used | Required
Port | Required | Required | Not used | Not used
Program | Optional | Optional | Optional | Optional
Provider | Required | Required | Required | Required
Stop Bits | Not used | Not used | Required |

Device Addresses

 | IP | IPX | Serial | Modem
Application Instance | Optional | Optional | Optional | Optional
Baud | Not used | Not used | Required | Not used
Flow Control | Not used | Not used | Required | Not used
Host Name | Optional | Optional | Optional | Optional
Device | Optional | Required | Required | Required
Parity | Not used | Not used | Required | Not used
Phone Number | Not used | Not used | Not used | Not used
Port | Optional | Required | Not used | Not used
Program | Optional | Optional | Optional | Optional
Provider | Required | Required | Required | Required
Stop Bits | Not used | Not used | Required | Not used


Sample URLs

The following sample URLs illustrate what a Microsoft® DirectPlay® URL might look like for the four standard service providers.

Local IP Address

x-directplay:/provider=%7BEBFE7BA0-628D-11D2-AE0F-006097B01411%7D;device=%7BIP ADAPTER GUID%7D;port=0000230034#IPUserData

Local IPX Address

x-directplay:/provider=%7B53934290-628D-11D2-AE0F-006097B01411%7D;device=%7BIPX ADAPTER GUID%7D;port=00230#IPXUserData

Local Serial Address

x-directplay:/provider=%7B743B5D60-628D-11D2-AE0F-006097B01411%7D;device=%7BCOM PORT GUID%7D;baud=57600;stopbits=1;parity=NONE;flowcontrol=RTSDTR#SerialUserData

Remote Modem Address

x-directplay:/provider=%7B6D4A3650-628D-11D2-AE0F-006097B01411%7D;device=%7BMODEM DEVICE GUID%7D;phonenumber=555-1212#ModemUserData


Handling Addresses

If you call the Host, EnumHosts, or Connect methods exposed by the DirectPlay8Peer, DirectPlay8Client, or DirectPlay8Server you must pass address objects as parameters. If Microsoft® DirectPlay® does not have sufficient address information, the method that you called will fail, and it will return DPNERR_ADDRESSING. However, it is not necessary to have all the information in the address object at the time you call the method.

All address objects must have the service provider GUID set. However, it is possible to omit other data values.

  • You can omit the device if the service provider supports all adapters.
  • You can omit the port number for IP and IPX service providers for the Host, EnumHosts, and Connect methods. DirectPlay will assign a port number. This number may vary.
  • If you set the OKTOQUERYFORADDRESSING flag, the service provider can display a dialog box asking the user for the information needed to complete the address. If the user does not supply sufficient information, the method will fail. If the OKTOQUERYFORADDRESSING flag is not set, no dialog box will be displayed. If the address you pass to the method is insufficient, the method will fail. In the last two cases, the error value that is returned will be DPNERR_ADDRESSING.

There are two important issues for IP and IPX service providers that you need to be aware of. Failing to handle them properly may cause your application to fail.

  • If you set the NOBROADCASTFALLBACK flag when you call an enumeration method, you must supply a hostname. If you do not do so, the method will fail and return DPNERR_ADDRESSING.
  • If you do not specify a port, do not assume that DirectPlay will always choose the same port number. The only way to be certain of the port number is to specify it in your address. If you do not specify a port number, you must retrieve the actual value later, after the command is in progress.

Note: Application developers who choose to override the default DirectPlay 8 dialog for TCP/IP are strongly urged to implement a solution that allows the user to override the port used for a connection or enumeration. One possible solution is to enable users to follow the host name with a colon and then the port, as implemented by the default DirectPlay 8 TCP/IP dialog, for example: host.domain.com:8090. Another possible solution is to add a field to the UI that enables the user to enter a port.


DirectPlay Address Objects

Microsoft® DirectPlay® does not handle URL strings directly. Instead, the string must be encapsulated in a DirectPlay8Address object. This object exposes a number of methods that enable you to insert URL information into, or extract it from, the object.

To create DirectPlay address, you must first create a DirectPlay8Address object. You can then define the address in one of two ways:

  • Create the URL string directly. Then use DirectPlay8Address.BuildFromURL to insert the complete string.
  • Use other DirectPlay8Address methods to insert the various pieces of data that make up the string directly into the object.

When you receive an address object, you have a similar pair of options.

  • Extract the entire URL string with DirectPlay8Address.GetURL. Then parse the string and extract the needed information
  • Use other DirectPlay8Address methods to extract the particular data you are interested in from the address object.


DirectPlay Protocol

Multiplayer games require efficient and flexible network messaging services for optimal performance. The Microsoft® DirectPlay® protocol is a transport-layer messaging protocol that is used for all DirectPlay messaging. The protocol has been substantially reworked for DirectPlay 8.1. It provides your application with the messaging support it needs to make everything run smoothly. The DirectPlay protocol includes the following messaging support.

  • Reliable and unreliable delivery of messages
  • Sequential and non-sequential delivery of messages
  • Message fragmentation and reassembly
  • Congestion control
  • Send prioritization
  • Message timeouts

Note With previous versions of DirectPlay, the DirectPlay protocol was optional, and had to be specified explicitly. With DirectPlay 8.1, this protocol is used for all DirectPlay messaging.

This document provides a general description of how the DirectX protocol works, and how you can use it in your application.

  • Basic Message Handling
  • Message Categories
  • Congestion Control
  • Send Prioritization
  • Monitoring Messaging Statistics
  • Monitoring the Pending Message Queues


Basic Message Handling

A message, as the term is used in this document, is a block of data that needs to be sent to another computer. A network protocol creates a packet by adding some bits to the data block that hold information such as the target's network address. This packet is the basic unit of network data. When the target receives the packet, the target's network protocol removes the extra bits and passes the data block to the receiving application.

Although similar in usage, the terms message and packet are not strictly interchangeable. This document uses the term message to refer to the unit of information that is passed to and received from the Microsoft® DirectPlay® API. Packet refers to the unit of information handled by the network. DirectPlay handles packets internally. With rare exceptions, DirectPlay applications need to deal only with messages.

The primary reason for the distinction between message and packet is that networks generally limit the maximum size of the packets they handle. This size is referred to as a Maximum Transmission Unit (MTR). If a message is small, it is sent in a single packet and the two terms are effectively synonymous. However, large messages might need to be fragmented into two or more packets and then be reassembled by the receiver. The DirectPlay protocol automatically handles fragmentation and reassembly of messages as needed. As far as your application is concerned, you send a message, and the target receives it.

Note DirectPlay delivers messages of any size. However, the more packets that are required for a single message, the greater the odds that one or more packets will be lost and have to be retransmitted. Messages that are large enough to require fragmentation and reassembly thus typically have more network latency than single-packet messages. If you need to keep network latency to a minimum, avoid sending large messages, especially on lossy networks. You can determine the maximum size that your connection can accommodate in a single packet by calling the GetSPCaps method exposed by the DirectPlay8Peer, DirectPlay8Client, and DirectPlay8Server interfaces.


Message Categories

The Microsoft® DirectPlay® protocol is designed to handle the following two basic types of network messaging.

  • Reliable versus unreliable messaging determines whether messages are guaranteed to be delivered to the target application.
  • Non-sequential versus sequential messaging determines whether messages are received by the target application in the same order they are sent.

Games use messaging for a variety of purposes, each with different demands. To support this range of messaging needs, the DirectPlay protocol enables you to designate a message as belonging to one of four categories:

  • Reliable and sequential
  • Unreliable and sequential
  • Reliable and non-sequential
  • Unreliable and non-sequential

The DirectPlay protocol enables you to optimize your messaging strategy by assigning categories on a message-by-message basis.

Reliable and Unreliable Messaging

Messages are sometimes lost in transit. Reliable messaging provides a guarantee that the target will receive every message. This type of messaging is required when data loss cannot be tolerated. Most reliable messaging schemes require the target to acknowledge receipt of each message. If the sender does not receive an acknowledgment within a specified timeout period, it resends the message. This process typically continues until the sender receives an acknowledgment, confirming that the message has arrived.

The DirectPlay protocol imposes a limit on the number of resend attempts. If no acknowledgment is received after a reasonable number of attempts, DirectPlay assumes that the connection has been lost, and closes it.

Unreliable messaging is the simplest form of network communication. It might be faster than reliable messaging because there is no guarantee that the message will be delivered to the target. The sender transmits the message. If the target does not receive the message, the sender will not transmit the message again, and the packet is lost.

Unreliable messaging is used primarily when speed or bandwidth is more important than an occasional lost message. For example, high-bandwidth streaming media applications often use unreliable messaging. They cannot afford to take up bandwidth with acknowledgments and retransmissions, nor can they wait for a lost message to be retransmitted. An occasional lost message normally has only a minor impact on quality, so it can be ignored.

Sequential and Non-Sequential Messaging

Messages leave the sender in a particular sequence. However, there is no guarantee that messages will arrive at the target's computer in the same order that they are sent. For example, if a message is lost and must be retransmitted, that message will typically arrive later than messages that followed it in the original sequence.

Sequential messaging uses sequencing information embedded in the message to ensure that the messages are presented to the target application in the correct order. This type of messaging is required when the target application must receive messages in the correct order. Out-of-order messages are buffered until the missing messages arrive.

Non-sequential messaging presents the received messages to the target as soon as they arrive at the target computer, regardless of the order in which they were sent. Because there is no need to wait for a missing packet, applications often use non-sequential messaging when speed is more important than an occasional out-of-order message. The out-of-order message is ignored.

Choosing the Best Message Category

Choosing the best category for messages is a core issue for multiplayer game developers. While DirectPlay provides the tools to manage your messaging, the choice of a message category ultimately depends on the semantic content of the message and the nature of the game.

The following are general guidelines for choosing the best message category.

  • Use non-guaranteed messaging whenever the content permits. For example, your game might send frequent player-location updates. Each update is independent, and it supersedes any previous updates. If an update is lost, the next update is sufficient to maintain the player's game state. A lost and retransmitted message might arrive later than the subsequent update message.
  • Use guaranteed messaging when data loss cannot be tolerated. For example, a text-based chat feature depends on every character being delivered to its target.
  • Use sequential messaging when the order of the messages is important. For example, streaming media typically uses sequential-unreliable messaging. An occasional dropped message can be tolerated, but an out-of-order message would cause problems.


Congestion Control

In an ideal world, your game can send messages as often as it needs to. They arrive at the target immediately and are processed instantaneously. If all of the computers in your game have ample processing power and are connected by a lightly used high-bandwidth network link, you might approach this ideal situation. You can then send messages as often as you like. However, a number of factors can create congestion and cause messaging to work more slowly than this ideal:

  • Network latency. Even under ideal conditions, messages take a finite time to traverse the network from sender to target, especially over the Internet. There might be further delays for acknowledgments, retransmission of lost packets, or reassembly of out-of-order packets.
  • Network bandwidth. The network bandwidth controls the rate at which a message can be sent or received by a computer. Network links have a wide range of bandwidths, and even high-bandwidth networks might be slowed by high traffic levels. If one or more of your players has a low-bandwidth connection, they will be able to send and receive messages only at a limited rate.
  • Processing speed. Even if network bandwidth is high and latency low, the target application still needs some time to process a received message. If one or more of the players in a session is using a relatively slow computer, the rate at which they can process received messages might be below the rate at which messages can be sent.

Message Throttling

If there is no control over the rate at which messages are sent, a target can be flooded by more messages than it can handle. To prevent this situation, the Microsoft® DirectPlay® protocol throttles the rate at which messages are sent. The net effect of throttling is that the rate at which messages are sent is controlled by the rate at which the target can handle them.

Throttling is implemented with a sliding window mechanism. The sliding window is basically a queue with a limited number of slots that holds messages that have been sent but not yet received. All outgoing messages are placed in this queue, regardless of their category. Once the sent-message queue is full, it accepts no more outgoing messages until one of the messages in the queue has been received.

For optimal performance, the size of the sliding window must be matched to current network conditions. The DirectPlay protocol automatically monitors such factors as the number of messages and the total number of bytes in the sent-message queue. This information is then used to dynamically adjust the size of the sliding window to optimize messaging for the current network conditions.

Connection Checking

If there is no activity on a link, the DirectPlay protocol periodically tests the connection by sending an empty reliable packet. If no acknowledgment is received from the target after a reasonable number of attempts, DirectPlay concludes that the link has been disconnected.


Send Prioritization

Messages often vary widely in importance. Some are time-critical and must be delivered as quickly as possible. Others can be delayed if necessary or, possibly, not sent at all. One issue with congestion control algorithms is that an application might create messages faster than they can be sent. Unsent messages must then be held in a queue until an outgoing slot opens up. If all unsent messages are held in a single pending-message queue, high priority messages might be blocked while waiting for lower priority messages to be sent first.

The Microsoft® DirectPlay® protocol solves this problem by having three pending message queues: low, medium, and high priority. When a slot opens up in the sent-message queue, the protocol selects the next message to be sent as follows:

  1. Send the oldest message in the high-priority queue.
  2. If there are no messages in the high-priority queue, send the oldest message in the medium-priority queue.
  3. If there are no messages in the medium-priority queue, send the oldest message in the low-priority queue.

This priority mechanism enables you to get your time-critical messages out as quickly as possible, even when less important messages have already been submitted.

Note All DirectPlay Voice messages are sent with medium priority and a timeout value of 1.5 seconds. Any messages that should not be preempted by voice traffic should sent with high priority.

Send Timeouts

One of the consequences of throttling is that messages might spend a relatively long time in a pending-message queue, especially if they are low priority. Some messages might stay long enough to have been superseded by subsequent messages. These messages are no longer relevant. For example, your application might periodically send player-location update messages. Each update is independent of the others and supersedes any previous updates. If you have two player-location updates in the pending message queue, only the most recent one needs to be sent.

The DirectPlay protocol enables you to handle the problem of outdated messages by adding an optional timeout value to the message. If the message is still in a pending-message queue when the timeout expires, the message will be canceled.

Disconnection

When an application sends a disconnect message, the message is placed at the end of the low-priority pending-message queue, and the protocol stops accepting outgoing messages. This practice guarantees that all pending messages are sent before the link is disconnected. The disconnect message is sent as a reliable sequential message to guarantee that it arrives, but not before all other messages in the queue have been delivered.


Monitoring Messaging Statistics

While the Microsoft® DirectPlay® protocol handles many aspects of messaging automatically, your application should still monitor messaging behavior. For example, if you are consistently sending messages faster than they can be delivered, you might need to modify your messaging scheme.

Because network conditions change continuously, your application should periodically check the behavior of the network and adjust its messaging scheme accordingly. To do so, call the GetConnectionInfo method that is exposed by every DirectPlay 8.1 object that supports messaging. GetConnectionInfo returns a type that contains a wide variety of statistical information that you can use to refine your messaging scheme, including the following:
  • Round trip latency
  • Throughput
  • Packets sent
  • Packets received
  • Packets resent
  • Packets dropped
  • Messages transmitted at different priority levels

Note The messaging statistics are obtained by monitoring the actual network traffic. If you call GetConnectionInfo immediately after you initialize the connection, there will have been little time to collect data and the statistics might be misleading.


Monitoring the Pending Message Queues

You should monitor your pending message queues to ensure that they do not become too large. The DirectPlay8Peer, DirectPlay8Client, and DirectPlay8Server objects all expose a GetSendQueueInfo method that can be used to check the number of messages and the number of bytes currently in the queue. By default, the method returns the total for all three queues, but you can also obtain values for each of the three priority levels.


Optimizing Network Usage

Providing the best gaming experience normally means sending updates and other information as rapidly as possible without flooding the target with more messages than it can handle. The Microsoft® DirectPlay® protocol combined with asynchronous messaging enables you to dynamically optimize your messaging strategy to provide your users with the best possible game experience.

The bulk of your messaging will use the DirectPlay8Peer.SendTo, DirectPlay8Client.Send, or DirectPlay8Server.SendTo methods. These methods normally work asynchronously for all message categories. They return immediately, and DirectPlay calls your message handler's DirectPlay8Event.SendComplete method when the message is actually sent.

You can choose to send messages synchronously by setting the DPNSEND_SYNC flag. If you do so, the Send/SendTo method will block until the message is actually sent.

The DirectPlay protocol's throttling mechanism guarantees that the client will not receive messages faster than they can be handled. However, the throttling protocol does not control how frequently you submit messages to the outgoing queue. You can easily end up with a large backlog of messages in your unsent message queues. You can avoid this situation by sending messages as infrequently as possible, but then you might unnecessarily degrade the user's experience. An optimal messaging strategy sends messages as fast as possible without exceeding the target's ability to handle them.

The following are tips for optimizing your messaging strategy.

  • Send most if not all of your messages asynchronously. If you send a message synchronously, the method will block until the throttling mechanism allows the message to be sent.
  • Monitor the pending message queues and the network statistics. If there are few or no messages in the queue, you can increase your transmission rate. If the queues are large or growing rapidly, decrease your transmission rate and perhaps cancel some messages. See the discussion of send timeouts in Send Prioritization for more information.
  • Analyze the pending message queues on a player-by-player basis. Some players might be able to receive messages at a much higher rate than others. The bulk statistics might be misleading. Consider using directed sends rather than group sends.
  • Choose the appropriate category for each message. Reserve the categories with the highest overhead for the most important messages.
  • Prioritize your messages, so that the most important are assured of being sent promptly and not delayed by relatively unimportant messages.
  • Do not let the pending message queues grow too large. In addition to delaying the transmission of your messages, a large number of pending messages might consume significant memory resources.
  • Use the timeout feature of the Send and SendTo methods to automatically clear outdated messages from the pending message queue.
  • Minimize the amount of data per message. It is usually better to send frequent small messages than a smaller number of large messages.
  • Do not loop tightly when checking the pending message queue. Doing so wastes CPU cycles. Instead, use a sleep period based on how long it typically takes the queue to get down to the level that it will be ready for another send.


Network Address Translators, Firewalls, and Proxies

Microsoft DirectX 8.1 (Visual Basic)

Network Address Translation, Firewalls, and Proxies

Network Address Translators (NATs), firewalls, and proxies pose similar challenges when designing a game that allows players on different computers to connect to each other. NATs are used to share a single Internet Protocol (IP) address between multiple machines. This means that a machine's internal IP address will be different from its external IP address, and can result in complications when using Microsoft® DirectPlay®. Firewalls and proxies are used to prevent unauthorized access to a network or machine and are usually designed to be transparent. This section describes how to properly configure your game to work with NATs, firewalls, and proxies.

Using NATs

NATs work best with applications where the server is not behind a NAT and the clients do not communicate directly with each other. If you want your application to run through any hardware or software NAT, you should follow these guidelines:

  • Create client/server applications using the DirectPlay8Client and DirectPlay8Server classes.
  • Do not put the game server behind a NAT.
  • Either program your clients to enumerate the game's port directly without using DPNSVR, or connect directly without enumeration.

You can create an application that does not follow these guidelines, but it is not recommended.

In order for clients to enumerate the game's port directly, the client needs to know the host server's port. The client can get this knowledge through a third party, such as a matchmaking system, or the game can be programmed to use a particular port. Of the two options, using the third party is more flexible and is the better solution. If the server is not using a particular port, it should call the GetLocalHostAddress method to determine on what port it is hosting and communicate that information to the third-party matchmaking service.

A client enumerates the game's port directly by explicitly specifying the port number in the DirectPlay8Address object passed as the AddrHost parameter in the DirectPlay8Client.EnumHosts call as shown in the following example.

' Add host port to the address.
dph.AddComponentLong DPN_KEY_PORT, glDefaultPort                     ' sComponent, lValue
.
.
.
' Enumerate host.
mlEnumAsync = moDPC.EnumHosts(Desc, dph,                             ' ApplicationDesc, AddrHost
                              moDPA,                                 ' DeviceInfo
                              INFINITE,                              ' lRetryCount
                              0, INFINITE,                           ' lRetryInterval, lTimeOut
                              DPNENUMHOSTS_OKTOQUERYFORADDRESSING,   ' lFlags
                              ByVal 0&, 0)                           ' UserData, UserDataSize

If you do use enumeration instead of connecting directly, you should keep the enumeration active and pass the host and device addresses indicated in the DPNMSG_ENUM_HOSTS_RESPONSE message without modification to the call to Connect. To do this, complete the following tasks.

  1. Specify INFINITE for the lRetryCount parameter in the call to the DirectPlay8Client.EnumHosts method.
  2. Use DirectPlay8Address.Duplicate when handling the DPNMSG_ENUM_HOSTS_RESPONSE message to get private references to the address strings.
  3. Store the address strings in a global location using threadsafe code.
  4. Retrieve the address strings using threadsafe code when the user selects the session to join.
  5. Pass the address strings into the call to Connect.
  6. Release the references to the address strings when you are done.

DirectPlay will cancel the enumeration when the Connect method completes successfully. Do not call CancelAsyncOperation to end the enumeration unless the Connect method completes with a failure. For an example of how to store, retrieve, and release addresses using threadsafe code, see the code for the DirectPlay Samples.

If you want to allow end users to run their own servers, advise them not to put their game servers behind a NAT, or to explicitly configure their NAT to forward the game host's specific ports to the host machine. End users can also use Microsoft® Windows® Millennium Edition (Windows Me) or Microsoft® Windows XP Internet Connection Sharing (ICS) as their NAT to achieve this same result.

If your game is not able to follow these rules, for example if it is a peer-to-peer game, that game will have problems with most NATs. There is no way to implement a true peer-to-peer networking session where arbitrary users are behind arbitrary NATs. The behavior in this case is much improved when the end users are using Windows Me or Windows XP ICS as their NAT.

Some NATs perform special processing for particular applications or protocols. Windows ICS performs some special processing for DirectPlay. Different versions of Windows ICS perform different processing, depending on what version of DirectPlay was current at the time the Windows ICS was released.

Compatibility for Client/Server Games with NATs

The following sections discuss compatibility issues for client/server games depending on the NAT being used.

Windows 98 Second Edition ICS, Windows 2000 ICS, and third-party non-Universal Plug and Play NATs

Multiple clients behind Windows 98 Second Edition ICS, Windows 2000 ICS, or third-party NATs that are not Universal Plug and Play (UPnP)-compliant can join a client/server game hosted by a server that is not behind a NAT, as long as the clients behind the NAT use direct host enumeration as described earlier. Clients behind non-UPnP NATs are more likely to be able to join a DirectPlay client/server game if the server is not behind a NAT and the clients use direct host enumeration.

DirectPlay might be able to support a server behind these NATs in some cases. However, the application will not work automatically. The end users will need to enable port forwarding. If you selected a port on which to host, they must manually configure their NAT to redirect traffic received externally to the internal host on that port. Be aware that you cannot have more than one server behind the NAT. If you do not select a port, they can attempt to enable port forwarding for the DPNSVR port 6073 and the game port. DirectPlay will usually select port 2302 for the game port, but if there are other DirectPlay applications running, it will select the next sequential port number available (for example, 2303). The user should consult the documentation for the NAT that they are using for information on setting up port forwarding.

Note Most NATs do not support enumeration through the DPNSVR port for client applications. This is because the client sends initial outbound traffic to the DPNSVR port, but the reply comes from the game port. Clients can attempt to enable port forwarding for the game port, but like servers, this design limits the user to only one client behind the NAT.

Windows Me ICS, Windows XP ICS, and UPnP-compliant NATs

Multiple clients behind a Windows Me ICS machine can join a client/server game hosted by a server not behind a NAT, even if the clients do not use direct host enumeration. However, the Windows Me ICS machine sometimes has problems joining games. The Windows Me ICS machine can usually join the game if it joins the session before any of the clients behind the ICS machine join the game. If the ICS machine does not join first, clients behind the ICS machine will be able to join but the client on the ICS machine might not be able to join.

Servers can be located inside the Windows Me ICS machine and still be seen from outside the NAT. No extra configuration is required in ICS or in the application.

Windows XP ICS and other UPnP-compliant NATs can also cooperate with DirectPlay and should not require extra configuration to support clients or servers behind the NAT. If you are having trouble hosting on a Windows XP ICS machine, be sure that the "Allow other network users to control or disable the shared Internet connection" box is checked.

No NAT can have multiple hosts using the same fixed port simultaneously. If you are using Windows Me ICS, Windows XP ICS, or UPnP-compliant third-party NATs and you specify a port already in use, you will receive the DPNERR_INVALIDDEVICEADDRESS return code when the Host method is called. You can allow DirectPlay to select a port and use DPNSVR enumeration or call the GetLocalHostAddress method to reach the session. Alternatively, you can allow your users to manually override the fixed port.

Note When hosting behind these NATs, the GetLocalHostAddress method returns the public address (the external interface on the NAT machine). Machines outside or inside the NAT can use this address to join the session. It does not return the address of the local network interface card (NIC).

Compatibility for Peer-to-Peer Games with NATs

The following sections discuss compatibility issues for peer-to-peer games depending on the NAT being used.

Windows 98 Second Edition ICS, Windows 2000 ICS, and third-party non-UPnP NATs

DirectPlay8Peer will not function properly through Windows 98 Second Edition ICS, Windows 2000 ICS, and third-party NATs that are not UPnP-compliant. However, you might be able to get some scenarios working, with the following considerations:

  • You might be able to join a peer-to-peer session from behind the NAT as long as you are the first player to connect to the session and the host does not migrate to you.
  • Explicitly configuring the NAT to forward ports may also allow hosting behind the NAT. If you selected a port on which to host, the end user must manually configure their NAT to redirect traffic received externally to the internal host on that port. If you do not select a port, they will need to enable port forwarding for the DPNSVR port 6073 and the game port. DirectPlay will usually select port 2302 for the game port, but if there are other DirectPlay applications running, it will select the next sequential port number available (for example, 2303). The user should consult their NAT's documentation for information on setting up port forwarding.

Note Most NATs do not support enumeration through the DPNSVR port for peer applications. This is because the peer sends initial outbound traffic to the DPNSVR port, but the reply comes from the game port. Peers can attempt to enable port forwarding for the game port, but like hosts, this design limits the user to only one peer behind the NAT.

Windows Me ICS, Windows XP ICS, and UPnP-compliant NATs

Windows Me ICS, Windows XP ICS, and UPnP-compliant NATs cooperate with DirectPlay to make it possible to run full-featured, peer-to-peer DirectPlay sessions through the NAT. Users can host or join DirectPlay sessions that are hosted inside or outside the NAT. No special configuration is required. Even host migration is fully functional.

However, the restriction for Windows Me ICS mentioned previously in the client/server case holds true—the client on the Windows Me ICS machine must join the session before any client behind the NAT joins the session or else the ICS machine will not be able to join.

As with client/server sessions, no NAT can have multiple hosts using the same fixed port simultaneously. The call to DirectPlay8Peer.Host will fail if the port is already in use on Windows Me ICS, Windows XP ICS, or UPnP-compliant NATs. See the client/server section for more information.

Note When hosting behind Windows Me ICS, Windows XP ICS, or UPnP-compliant NATs, the GetLocalHostAddress method returns the public address (the external interface on the NAT machine). Machines outside or inside the NAT can use this address to join the session. It does not return the address of the local NIC.

Using Firewalls and Proxies

Applications work best when the server is not behind a firewall or proxy and the clients do not communicate directly with each other. If you want your application to run through any hardware or software firewall, you should follow these guidelines.

  • Create client/server applications using the DirectPlay8Client and DirectPlay8Server interfaces.
  • Do not put servers behind a firewall or proxy.
  • Program your clients to either enumerate the game's port directly (not using DPNSVR) or to connect directly without enumeration.

You can create an application that does not follow these guidelines but it is not recommended.

Compatibility for Client/Server Games Using Firewalls and Proxies

The following sections discuss compatibility issues for client/server games, depending on the firewalls and proxies being used.

Windows XP Internet Connection Firewall

DirectPlay works with the Internet Connection Firewall (ICF) capabilities of Windows XP. When your application begins hosting, enumerating, or connecting, the appropriate ports will automatically open and when your application shuts down, these ports will automatically close. However, the user launching the application must be a member of the administrator group for the computer so that DirectPlay has the security permissions to open the ports.

Third-Party Firewalls

DirectPlay is unable to configure third-party firewalls automatically. Clients behind a third-party firewall should work if the firewall allows outbound UDP traffic.

To support servers behind a third-party firewall, end users will have to manually configure their firewall. If you select a port for the local device address, end users must configure their firewall to open that port. If you do not select a local port, end users need to attempt to open the DPNSVR port 6073 and the game port. DirectPlay usually selects port 2302 for the game port but, if there are other DirectPlay applications running, it will select the next sequential port number available (for example, 2303). Users should consult their firewall's documentation for information on opening ports.

Microsoft Internet Security and Acceleration Server and Third Party Proxies

DirectPlay works with the Microsoft Internet Security and Acceleration (ISA) Server and other proxies when running client applications. Clients that have the ISA Firewall Client software installed should not cancel the enumeration before connecting and should pass the address objects from the DPN_MSGID_ENUM_RESPONSE as described in the Using NATs section. If the enumeration is cancelled, the ISA Server can close the virtual connection established by the enumeration and the call to Connect will fail.

If you want to support a server application behind an ISA Server proxy, the end user must configure the ISA Server. If you have selected a port for the local device address, end users must configure the ISA Server to redirect traffic received externally to the internal host on that port. If you do not select a local port, end users can attempt to configure the ISA Server for the DPNSVR port 6073 as well as the game port. DirectPlay will usually select port 2302 for the game port, but if there are other DirectPlay applications running, it will select the next sequential port number available (for example, 2303). The user should consult the product documentation for how to configure their proxy.

Note Most proxies do not support enumeration through the DPNSVR port for client applications. This is because the client sends initial outbound traffic to the DPNSVR port, but the reply comes from the game port. Clients can attempt to enable port forwarding for the game port, but like servers, this design limits the user to only one client behind the proxy.

Compatibility for Peer-to-Peer Games Using Firewalls and Proxies

The following sections discuss compatibility issues for peer-to-peer games depending on the firewalls and proxies being used.

Windows XP Internet Connection Firewall

DirectPlay works with the Internet Connection Firewall (ICF) capabilities of Windows XP. When your application begins hosting, enumerating, or connecting, the appropriate ports will automatically open and when your application shuts down, these ports will automatically close. However, the user launching the application must be a member of the administrator group for their computer, so that DirectPlay has the security permissions to open the ports.

Third-Party Firewalls

DirectPlay is unable to configure third-party firewalls automatically.

To support a host behind a third-party firewall, the end user will have to manually configure their firewall. If you select a port for the local device address, end users must configure their firewall to open that port. If you do not select a local port, end users can attempt to open the DPNSVR port 6073 and the game port. DirectPlay usually selects port 2302 for the game port, but if there are other DirectPlay applications running, it will select the next sequential port number available (for example, 2303). The user should consult their firewall's documentation for information on opening ports.

Microsoft Internet Security and Acceleration Server and Third Party Proxies

DirectPlay works with the Microsoft Internet Security and Acceleration (ISA) Server and other proxies when running peer applications. Peers that have the ISA Firewall Client software installed should not cancel the enumeration before connecting and should pass the address objects from the DPN_MSGID_ENUM_RESPONSE as described in the Using NATs section. If the enumeration is cancelled, the ISA Server can close the virtual connection established by the enumeration and the call to Connect will fail.

If you want to support a server application behind an ISA Server proxy, the end user must configure the ISA Server. If you have selected a port for the local device address, end users must configure the ISA Server to redirect traffic received externally to the internal host on that port. If you do not select a local port, end users can attempt to configure the ISA Server for the DPNSVR port 6073 as well as the game port. DirectPlay will usually select port 2302 for the game port, but if there are other DirectPlay applications running, it will select the next sequential port number available (for example, 2303). The user should consult the product documentation for how to configure their proxy.

Note Most proxies do not support enumeration through the DPNSVR port for client applications. This is because the client sends initial outbound traffic to the DPNSVR port, but the reply comes from the game port. Clients can attempt to enable port forwarding for the game port, but like servers, this design limits the user to only one client behind the proxy.


Using the DirectX Protocol in an Application

This section covers how you can use the features of the Microsoft® DirectPlay® protocol in your application.

You can use five DirectPlay objects to send messages.

  • DirectPlay8Peer
  • DirectPlay8Client
  • DirectPlay8Server
  • DirectPlay8LobbyClient
  • DirectPlay8LobbiedApplication

Depending on which object your application is using to send messages, you send a message by calling a method named either Send, or SendTo. While the usage of these five methods is similar, they vary in detail. Refer to the appropriate reference pages for further discussion.

The Send/Sendto method's parameters might allow you to control many of the DirectPlay protocol's features. For example, the lFlags field of DirectPlay8Peer.SendTo allows you to specify:

  • The message's priority level.
  • Whether the message is reliable or unreliable.
  • Whether the message is sequential or non-sequential.

Refer to the appropriate method reference for further details.

When your application receives a message, DirectPlay will call your message handler's DirectPlay8Event.Receive method. The associated type contains a pointer to the data block, along with information such as the source of the message.


Understanding DirectPlay Voice

Microsoft® DirectPlay® Voice uses a DirectPlay session for media-independent network transport and player management. The DirectPlay Voice application programming interface (API) does not duplicate session control features from DirectPlay. A DirectPlay network transport session must also be created before DirectPlay Voice can transmit and receive voice communications. DirectPlay Voice can use either the IDirectPlay4 object or IDirectPlay8 object for network transport.

Note that if DirectPlay Voice is being used in-process with a multiplayer game, the game will most likely also use the transport session to exchange its game-specific data. This makes it possible to optimize the use of network resources between the game and voice data.

It is also acceptable to create and use a transport session specifically for the voice session, as would be the case for a standalone voice conferencing application.

Microsoft® DirectPlay® Voice is a full-voice communications API that is integrated with DirectPlay for network session management and network transport.

DirectPlay Voice is also integrated with DirectPlay Sound for voice recording and playback, and all DirectPlay Sound audio features are inherited, including the ability to target voice data to different playback buffers and the use of special audio effects such as three-dimensional sound positioning.

  • DirectPlay Voice Topologies
  • Voice Host Migration
  • Audio Device Testing
  • Voice Codecs
  • Automatic Gain Control
  • Transmission Control
  • Creating a 3-D Voice Session
  • Jitter Buffers
  • Working Set Guidelines


DirectPlay Voice Topologies

Microsoft® DirectPlay® Voice sessions require a DirectPlay network session to transport voice communication. Once the network session has been created, a DirectPlay Voice object can be created to use one of three topologies.

  • Peer-to-Peer Voice Topology
  • Forwarding Server Voice Topology
  • Mixing Server Sessions

The choice of topology is dependent on several factors, and these factors are discussed in the individual DirectPlay Voice topology topics. Note that not all voice topologies can be transported over all types of DirectPlay networking sessions.


Peer-to-Peer Voice Topology

In a Microsoft® DirectPlay® Voice session using a peer-to-peer topology, each voice-session client streams its voice audio data directly to every other voice-session client. Each client receives all individual incoming voice audio streams, mixes the received streams, and plays the resulting mixed signal on the client's computer.

The advantage of using a peer-to-peer topology is that no computer in the voice session requires high bandwidth or processor power. However, the bandwidth and processor usage on each client's computer varies according to the number of incoming and outgoing audio streams. The number of outgoing voice audio streams is equal to the number of targets participating in the voice session, unless the network provider is capable of true multicasting, as noted below. The number of incoming voice audio streams depends on how many other voice-session clients are targeting the client in question and also on how many of the other clients are speaking.

As a game design consideration, it is not useful for a voice-session client to be the target of more than about six to eight other clients. If all six to eight clients are speaking at once, the conversation can become confusing, and communication between clients can be difficult.

If the DirectPlay network session supports true multicasting, the number of outgoing voice audio streams can be reduced considerably. If all clients are part of a multicast network and the target of the voice stream is a DirectPlay group, there is only one outgoing stream.

A DirectPlay voice session using a peer-to-peer voice topology supports 3-D spatialization of the voice data using the DirectPlay8VoiceClient.Create3DSoundBuffer method.

It is important to note that a voice session using a peer-to-peer voice topology cannot be used if the network transport is a client/server session.


Forwarding Server Voice Topology

In a Microsoft® DirectPlay® voice session using a forwarding server topology, one computer in the session acts as a forwarding server. Each client in the voice session streams voice data to the forwarding server, which then forwards the voice data to all other clients in the session. Each client receives all incoming audio streams forwarded from the forwarding server. Each client's computer then mixes the incoming streams and plays them back.

The outgoing bandwidth requirement on each client in a voice session using a forwarding server topology is constant because there is only one outgoing voice audio stream. The incoming bandwidth and processor requirements are identical to the requirements of a voice session using a peer-to-peer topology, but they vary depending on the number of incoming voice audio streams.

The server has much higher bandwidth requirements than the individual clients in a forwarding server DirectPlay voice session. However, the processor requirements are not high because no compression or decompression of voice data occurs on the server. This reduced load on the computer's processor also means that an individual client's computer with a high bandwidth connection can host the forwarding server without adversely affecting the performance of the individual client's computer or the performance of a game server and/or client program running on the same computer.

Note that in a voice session using a peer-to-peer topology, the outgoing bandwidth requirements on the individual clients are usually much higher than the incoming bandwidth requirements. Therefore, reducing the outgoing bandwidth requirement to a single stream of audio can result in a significant reduction in total bandwidth usage. For example, if a client is taking part in an eight-person voice session in which all clients can hear one another, the client has seven outgoing voice streams each time voice data is captured and transmitted on his or her computer. However, it is rare that all clients talk at once, so there are most likely fewer than two or three incoming voice streams at any one time.


Mixing Server Sessions

In mixing server sessions, one computer in the session acts as a mixing server. Each client streams its voice data to the mixing server. The mixing server examines the targets of each voice stream, performs decompression, mixing, and recompression as appropriate to generate a mixed stream of audio data for each client. Each client receives this single stream of pre-mixed audio data and plays it back.

The outgoing bandwidth, incoming bandwidth, and CPU requirement on the client in a mixing server session is easily predictable because each client has only one outgoing stream of audio to compress and send, and one incoming stream of audio to decompress and play back.

The mixing server has much higher bandwidth and CPU requirements than do the clients. Typically, the mixing server is either a completely dedicated computer, or it shares a computer with a dedicated game server.

Mixing server voice sessions do not support 3-D spatialization of the voice data through the DirectPlayVoiceClient8.Create3DSoundBuffer method.

You can run mixing server voice sessions using either a peer-to-peer or a client/server transport session.


Voice Host Migration

In a peer-to-peer Microsoft® DirectPlay® network session, one client of the networking session acts as host. If that host exits the session or stops responding for any reason, another client in the session is elected as host.

In a DirectPlay voice session, a similar process of host migration occurs in peer-to-peer voice sessions, except that the voice host migrates independently of the DirectPlay network session. The voice host migrates when the server calls DirectPlayVoiceServer8.StopSession or if the voice host stops responding.

When the voice host migrates, the DirectPlayVoiceEvent8.HostMigrated method is called on each of the clients. If the local client has become the new voice session host, the NewServer parameter will point to the newly created DirectPlayVoiceServer8 object that can be used by the local client for providing host services. If the local client is not the new host, the NewServer parameter will be NULL.


Audio Device Testing

Microphone setup is supported by the Microsoft® DirectX® Voice Test Wizard. This wizard confirms that your system properly supports full duplex operation and ensures your microphone and playback settings are correct. You need to run the wizard only once for each combination of playback and capture device you select.

You can launch the Voice Test Wizard in two ways:

  • You can launch the wizard from your program by creating a DirectPlayVoiceTest8 object and calling its DirectPlayVoiceTest8.CheckAudioSetup method.
  • With Microsoft® Windows® Millennium Edition (Windows Me) or Microsoft® Windows XP you can launch the wizard from the Voice tab of the Sound and Audio Devices control panel application.

Calling DirectPlayVoiceTest8.CheckAudioSetup method invokes the Voice Test Wizard, which runs tests and confirms that the system supports full duplex operation properly, and ensures that microphone and playback settings are correct. You need to run the wizard only once for each combination of playback and capture device you select. Each time your application starts, you should test the configuration by calling DirectPlayVoiceTest8.CheckAudioSetup with the lFlags parameter set to DVFLAGS_QUERYONLY. This enables you to test quickly whether the device configuration has changed since your devices were last tested. If your devices have not been tested, you should run DirectPlayVoiceTest8.CheckAudioSetup again to invoke the wizard. If the configuration has changed since the last test and you have not run the wizard again, DirectPlayVoiceClient8.Connect will return DVERR_RUNSETUP and you will not be able to initialize Microsoft® DirectPlay® Voice.

Many older computer systems still in use do not have a full duplex sound card. Without full duplex, a sound card can receive—but not send—voice communications. Because games typically hold the sound card in playback mode, DirectX 8.1 prevents problems by not allowing dynamic switching between playback and capture. The Voice Test Wizard provides users with information about the duplexing abilities of their system.


Voice Codecs

The compression/decompression (codec) algorithms provided with Microsoft® DirectPlay® are optimized for low-bandwidth voice compression and decompression. These codecs all operate on 8 kHz, 16-bit mono-format based data. However, DirectPlay Voice handles all the details of converting voice data to and from this intermediate format. Third-party codecs are not supported, and you cannot write proprietary codecs for use with DirectPlay Voice.

It is important to note that as the bandwidth requirements drop, the audio quality of the voice data also drops. The following table lists the supported codecs, the bandwidth in kilobits per second (Kbps), and the compression GUID used to select them. The compression GUIDs are defined in dvoice.h.

Codec | Bandwidth | GUID
Voxware VR12 | variable (1.2 Kbps, avg.) | DPVCTGUID_VR12
Voxware SC03 | 3.2 Kbps | DPVCTGUID_SC03
Voxware SC06 | 6.4 Kbps | DPVCTGUID_SC06
TrueSpeech | 8 Kbps | DPVCTGUID_TRUESPEECH
Microsoft® GSM | 13 Kbps | DPVCTGUID_GSM
Microsoft® ADPCM | 32 Kbps | DPVCTGUID_ADPCM
Microsoft® PCM | 64 Kbps | DPVCTGUID_NONE

The first three codecs provide a high level of compression and have approximately the same resource demands. On a 500 MHz Pentium III class computer, these codecs use approximately 1.5 percent of the CPU capacity. The VR12 codec sounds tinny and robotic, but the SC03 and SC06 codecs provide reasonable fidelity. The PCM codec provides the highest sound quality and is essentially uncompressed 8 kHz 16-bit mono-format audio data.

Note The GSM, ADPCM, and PCM codecs are included with the Microsoft® Windows® installation but may not have been installed by the user. You may need to prompt the user to install them. You can determine which codecs are available on your system by calling DirectPlayVoiceServer8.GetCompressionType. If a codec is not listed, the corresponding ACM codec is not installed.

Selecting a Codec

As with all other game setup parameters, the host controls which codec is used for the voice session. All members of the voice session must use the same codec. Remember that in a peer-to-peer voice session, the voice-session host does not necessarily have to be the same as the game-data host. The host selects the codec when it calls DirectPlayVoiceServer8.StartSession. Set the guidCT member of the DVSESSIONDESC type to the compression GUID of the codec that you want to use. A client can retrieve this structure by calling DirectPlayVoiceClient8.GetSessionDesc.

The same codec might not be ideal for the entire duration of a game. For instance, you might want to use one codec for the lobby chat feature that players use to set up the game, and another to handle voice communication after the game is launched. You cannot dynamically change codecs during a voice session. To switch to another codec, you must terminate the current voice session and create a new voice session with the new codec. However, you can stop and restart a voice session without terminating the underlying DirectPlay core session.

As with any form of network communication, it is important to analyze the cost of the voice communication to ensure that adequate bandwidth is available to support communication of the game data and voice data. Analyzing the voice bandwidth consumption is straightforward: Estimate the number of simultaneous voice streams that you anticipate and multiply that number by the sum of the bandwidth required by the codec and the protocol overhead. CPU consumption is another factor to consider when choosing a codec. As with network bandwidth, CPU resource consumption is additive, per stream.


Automatic Gain Control

Microsoft® DirectPlay® Voice offers functionality to adjust the hardware input volume on the sound card automatically and provide the best recording input level possible. To enable Automatic Gain Control, set the DVCLIENTCONFIG_AUTORECORDVOLUME flag in the lFlags member of the DVCLIENTCONFIG structure when you set the client configuration. Automatic Gain Control can be activated or deactivated at any time during the voice session.

Most game applications should use automatic gain control because it requires a negligible amount of game resources and prevents the need for an in-game volume recording control. Users are not required to set the level themselves, yet they experience the highest quality of voice transmission and reception possible.


Transmission Control

To keep the performance requirements of Microsoft® DirectPlay® Voice low, transmit voice data only when the user is speaking. You can control voice data transmission in three ways.

  • Push-to-Talk
  • Manual Voice Activation
  • Automatic Voice Activation

You select which transmission control method to use when you call DirectPlayVoiceClient8.Connect to connect to a voice session. To specify the type of transmission control you want to use, set the appropriate flag in the DVCLIENTCONFIG type's dwFlags member. You can change the method during the session by calling DirectPlayVoiceClient8.SetClientConfig and changing the flag setting.

Push to Talk

Push-to-talk transmission control is analogous to pushing the Talk button on a two-way radio. It adds reality to certain game genres such as first-person shooters. Push-to-talk requires users to actively select when they want to transmit voice data. There is no danger that anything besides voice data will activate transmission. In addition, requiring users to actively select when they want to speak reduces the number of users speaking at once.

Push-to-talk transmission control requires more design and development than voice activation. In particular, you must have some way of detecting when the user has chosen to start transmitting, typically by pushing a controller button or a key on the keyboard. When you detect that the user wants to start talking, you must start transmission by calling DirectPlayVoiceClient8.SetTransmitTargets, and provide an array of target IDs that will receive the transmission. When you detect that the user is finished, stop transmission by calling DirectPlayVoiceClient8.SetTransmitTargets again, with the target array set to NULL .

Push-to-talk is the default transmission control method. It is enabled unless you explicitly select voice activation by setting the DVCLIENTCONFIG_AUTOVOICEACTIVATED or DVCLIENTCONFIG_MANUALVOICEACTIVATED flag in the DVCLIENTCONFIG type.

Voice Activation

With voice activated transmission control, the microphone input is constantly analyzed to determine if the user is speaking. When the input exceeds a threshhold level, voice activation is triggered, and the user begins transmitting. Ideally, transmission starts when the user begins speaking, and stops when the user finishes.

Voice activation is simpler for the user than push-to-talk, because the user must only speak into the microphone. It is also more easily coded because you do not need to detect when the user wants to start or stop transmitting. You specify voice activation when you connect, and transmission control is handled by the system from that point on. However, one drawback of voice activation is that it can result in unwanted transmissions. In addition to speech, transmission can be triggered by sounds such as the user breathing directly on the microphone, high levels of ambient sound in a noisy environment, or a set of external speakers playing the game's audio background. Low-quality microphones can increase the probability of unwanted transmission.

Voice activation can be either automatic or manual. To specify one of these modes, set the DVCLIENTCONFIG_AUTOVOICEACTIVATED or DVCLIENTCONFIG_MANUALVOICEACTIVATED flag, respectively, when you connect to the voice session.

Automatic voice activation is the preferred transmission control method for most applications. In this mode, the threshold for transmission is determined automatically by the system. The theshhold level is adaptive, adjusting itself automatically to the input signal.

With manual voice activation, you must explicitly set a threshhold when you connect to the voice session by assigning a value to the dwThreshhold member of DVCLIENTCONFIG. The system will not change this value for you. If conditions change, and the threshhold value is no longer adequate, you must call DirectPlayVoiceClient8.SetClientConfig and specify a new value for dwThreshold.


Creating a 3-D Voice Session

You can add extra realism to a Microsoft® DirectPlay® Voice session by making the sound three-dimensional. Your players can then use audio cues to perceive the positions and movement of the other players. The basis for a 3-D voice session is the 3-D capabilities of Microsoft® DirectSound®. This document discusses how to manage your voice buffers to create a 3-D voice session. For complete details about how to use the DirectSound 3-D application programming interface (API), see 3-D Sound.

Managing 3-D Voice Buffers

When you receive a voice transmission, it is streamed into a DirectSound buffer. By default, everything is streamed into the main buffer. To implement 3-D sound, you must have a separate buffer for each distinct source. You can then use the DirectSound 3-D API to manage the buffers to create 3-D sound.

You can specify separate 3-D buffers for individual players and for groups of players. To specify a 3-D buffer for a particular player or group, call DirectPlayVoiceClient8.Create3DSoundBuffer and pass the method either the player or group DVID. All transmissions from that player or group will then go into the specified 3-D buffer.

DirectPlay Voice 3-D buffers have the following characteristics.

  • If you do not specify a 3-D buffer for a player or group, those transmissions will be streamed into the main buffer.
  • If you specify a 3-D buffer for a player or group, those transmissions will not be streamed into the main buffer.
  • You can retrieve the 3-D buffer for the main buffer by calling DirectPlayVoiceClient.Create3DSoundBuffer with DVID_REMAINING as the DVID.
    •
  • A player's transmission can be streamed into multiple buffers that can be managed separately. For instance, if a player has a 3-D buffer and is also a member of a group with a 3-D buffer, the player's transmissions will be streamed into both buffers. For example, you might have the group's transmissions coming from a radio on a table. If the player runs by shouting, you can hear the player through the radio, with a fixed position, as well as from a moving sound source as the player runs by.
  • You can mute the main buffer by calling DirectPlayVoiceClient8.SetClientConfig and setting the DVCLIENTCONFIG_MUTEGLOBAL flag in the DVCLIENTCONFIG type. If the main buffer is muted, your player will hear only those voice streams that have a 3-D buffer.


Jitter Buffers

Microsoft® DirectPlay® Voice features a jitter buffer, an adaptive buffering algorithm that provides optimal voice quality with the least amount of latency.

On busy networks, individual packets of voice data information might arrive in a different sequence from that in which they were encoded on the host computer. Because voice data is sequential in nature, these incoming packets must be queued for a period of time so that delayed packets have an opportunity to arrive and be played back in order.

If the jitter buffer is set to maximize the quality of voice communication, it takes longer for the required number of voice packets to arrive and be queued for play. The result is voice latency, and the effect is that voice communication is not heard in real time. Instead, the voice data might be heard anywhere from a fraction of a second to several seconds after it was recorded. This can introduce problems during cooperative game play because events can occur in the game but players will not be able to communicate information based on those events in real time. For example, if a player in a first-person shooter is about to be attacked from behind and a teammate attempts to warn the player, the voice communication might not be heard until after the player has been attacked.

If the jitter buffer is set to a reduce latency, the number of packets required to fill the queue is reduced. However, it is possible that not all sequential packets will arrive in time and, as a result, voice data will be missing from the buffer when it is played. The voice communication will be heard much closer to the actual time it was recorded. However, it will have a "broken-up" quality.

The DirectPlay jitter buffer uses two methods to determine how to provide the best quality of voice communication with the least amount of latency. First, network conditions are monitored to determine the amount of lag or network congestion. The size of the jitter buffer, or queue, is then dynamically sized to keep latency as low as possible while providing the least amount of voice break up.

The default behavior of DirectPlay Voice jitter buffer is to automatically adjust to network conditions. You can manually adjust how closely the algorithm tracks network conditions using the lBufferAggressiveness and lBufferQuality members of the DVCLIENTCONFIG type. The higher the level of aggressiveness, the more closely the algorithm monitors network conditions. In general, the higher the quality value, the higher the quality of the voice, but the higher the latency as well. The lower the quality value, the lower the latency but the lower the quality of the voice.

It is important to choose an appropriate level of aggressiveness for network conditions when your game application is running because selecting a high level of aggressiveness during times of steady network performance can cause the algorithm to misinterpret a transitory problem and overcompensate for a problem that might not exist.


Working Set Guidelines

Determining the best configuration of transport topology, voice topology, transmission control, and codec depends on the type or genre of game you are creating, the number of players that will participate in a single game session, and the type of connection that will be targeted.

It's important to note that the number of players participating in the voice session is not necessarily the number of players actually participating in the game session. For example, if your game is a first-person shooter, voice communication can be represented in the game as a radio or communicator that is offered as a time-limited powerup. Also, the radio metaphor can be used to limit communication to radios in either vehicles or stationary command stations.

A second example to consider is an online bridge game, which involves four players at one time. Because this is a small working set, it is appropriate to choose a peer-to-peer voice topology transported over a peer-to-peer network topology. This small working set also allows for the use of voice activation as the mode of transmission control. The peer-to-peer voice topology is easily implemented and does not require any player to act as a server. If all four players use the Voxware SC6 codec, the maximum resulting bandwidth is 4.2 Kbps per speech stream, including the codec protocol overhead. Further assuming that game data requires negligible bandwidth, the outgoing maximum bandwidth requirement for an individual speaker is three independent streams to the other three players, or 12.6 Kbps. The incoming stream to any client ranges from 0 if no other players are talking, to 12.6 Kbps if all three other players speak simultaneously. The CPU requirement is 8 percent for encoding and 0 to 12 percent for decoding. This results in a worst-case requirement of 25.2 Kbps. Therefore each player must have a minimum of a 14,400-baud modem.

Another example is a squad combat game that can involve up to 32 players split between 2 teams. Assume that the game data requires a 28,800 baud modem. In this example, there is a larger number of players and it is appropriate to choose a forwarding server voice topology. Again, if all players use the Voxware SC6 codec, the bandwidth requirements are the same as the bridge game above: 4.2 Kbps. In this example we see that there is 4.2 Kbps outgoing when speaking, and a maximum of 12.6 Kbps incoming from the squad. The maximum CPU requirement is 8 percent of a Pentium 200 for encode and 12 percent receiving. Therefore, each player requires 28.8 Kbps for game data, and the greater incoming bandwidth of 12.6 Kbps requires a minimum 41,400 baud rate from each player's modem.

The worst-case scenario for the forwarding server itself is if all 32 players talk at once, requiring 134.4 Kbps. The server CPU use is minimal because the server is not encoding or decoding the streams. It is merely redirecting them. More typically, there might be 16 players talking simultaneously for 67.2 Kbps.

To illustrate the difference between choosing a mixing server voice topology and a forwarding server voice topology, consider the same 32-player squad combat game discussed above. If a mixing server voice topology is used, each client requires 4.2 Kbps to send and 4.2 Kbps to receive. The worst-case bandwidth requirements drop to 8.4 Kbps and 12 percent of the Pentium processor running at 200 MHz. This reduces the modem requirement to a 33,600 Kbps baud rate for the client.

For the server, the CPU burden changes. The server is now decoding and re-encoding all incoming streams and is also mixing the streams as required. The CPU burden mix the stream is relatively low and is considered negligible. The worst case is the decoding and encoding of 32 simultaneous streams. This results in a requirement of at least a Pentium II processor running at 400 MHz for the voice service alone.


Using DirectPlay

This section of the Microsoft® DirectPlay® documentation shows you how to use the DirectPlay application programming interface (API) to implement a number of important aspects of multiplayer applications.

  • Using the DirectPlay Core Visual Basic API
  • Using the DirectPlay Lobby Visual Basic API
  • Using the DirectPlay Voice Visual Basic API


Using the DirectPlay Core Visual Basic API

This documentation provides detailed information about how to use the Microsoft® DirectPlay® Visual Basic® core application programming interface (API). Some of this material is also relevant to DirectPlay Lobby.

  • Using DirectPlay Enumerations
  • Using the DirectPlay DPNSVR Application
  • Testing Network Performance with DP8Sim
  • Monitoring DirectPlay Network Traffic with Netmon


Using DirectPlay Enumerations

Enumeration is one of the ways that Microsoft® DirectPlay® provides information to applications. Enumerations are used to collect data associated with a number of similar elements. For instance, you can use an enumeration to obtain information about each player in a session. To perform an enumeration, an application queries DirectPlay for a particular type of information, and DirectPlay returns a data type for each related element, typically as an array of types.

Most applications will need to perform at least one and often several enumeration operations. Each DirectPlay object supports a different set of enumerations. Thus the details will vary from application to application. The following is a list of available enumerations, along with the objects that support each type of enumeration.

  • Session hosts (DirectPlay8Peer, DirectPlay8Client)
  • Service providers (DirectPlay8Peer, DirectPlay8Client, DirectPlay8Server)
  • Players (DirectPlay8Peer, DirectPlay8Server)
  • Groups (DirectPlay8Peer, DirectPlay8Server)
  • Group members (DirectPlay8Peer, DirectPlay8Server)
  • Local programs (DirectPlay8LobbyClient)

For more information, see Implementing a DirectPlay Enumeration.


Implementing a DirectPlay Enumeration

Most DirectPlay enumerations follow a standard pattern: determine how many items are to be enumerated and call the appropriate enumeration method. The exception to this pattern is host enumerations, which are discussed separately.

The following procedure outlines how to enumerate the members of a group in a peer-to-peer game. The same general procedure is followed by all other types of enumeration, except for host enumerations.

  1. Call DirectPlay8Peer.GetCountGroupMembers. This method returns the number of members in the group.
    1. Call DirectPlay8Peer.GetGroupMember once for each member in the group. The method returns the ID of the specified player.

For more information, see Enumerating Hosts.


Enumerating Hosts

One way to arrange a session is to have session hosts advertise themselves as available. This type of session is referred to as a broadcast session. Peers or clients can look for a game to join by enumerating the available hosts, selecting one, and then join the game by sending a connection request. See Peer-to-Peer Sessions or Client/Server Sessions for a detailed discussion.

Unlike other enumerations, the information needed to respond to a request for available hosts is not stored on the local computer. Instead, a client or peer must broadcast a request, for instance on their local subnet, and wait for available hosts to respond. Hosts, on the other hand, must wait for these requests, and then respond appropriately. There are thus two slightly different procedures, depending on whether you are a potential session member, or a session host.

The following procedure illustrates how enumerate the available hosts for a peer-to-peer session. The procedure for a client/server session is essentially the same. DirectPlay8Peer.EnumHosts is the method that starts the enumeration. The key parameters to set are ApplicationDesc, Deviceinfo, and AddrHost.

  1. Assign the GUID of the game you are interested in playing to the guidApplication member of the DPN_APPLICATION_DESC type and assign assign it to the ApplicationDesc parameter.
  2. Create a DirectPlay8Address object for your device and assign it to Deviceinfo. This object contains the information needed to make a network connection.
  3. To query a specific computer for available hosts, create a DirectPlay8Address object for the host computer and assign it to pdpaddrHost. If you set leave the object empty, DirectPlay will create an address from the information contained in pdpaddrDeviceinfo. See DirectPlay Addressing for further discussion of address objects. If you are using an IP or IPX service provider, the query will then normally be broadcast to your local subnet.
  4. Call DirectPlay8Peer.EnumHosts.
  5. DirectPlay will then make a series of calls to your message handler's DirectPlay8Event.EnumHostsResponse method, once for each host that responds.

    Examine the information returned to your message handler, select a session, and ask to join it by calling DirectPlay8Peer.Connect.

If you want to be the host of a broadcast session, advertise yourself as available, and wait for queries or connection requests. The following procedure applies to peer-to-peer hosts, but is essentially similar to the procedure for client/server hosts.

  1. Call DirectPlay8Peer.SetPeerInfo to specify the static settings for your player.
  2. Specify the configuration of the game by assigning values in the DPN_APPLICATION_DESC type.
  3. Call DirectPlay8Peer.Host to advertise yourself as a potential host. Set the AppDesc parameter to the DPN_APPLICATION_DESC type defined in the previous step.
  4. Wait for enumeration requests. They will take the form of a call to your message handlers DirectPlay8Peer.EnumHostsQuery method. If you wish to respond to the enumeration request, fill in the DPN_APPLICATION_DESC type and set fRejectMsg to False.
  5. If the peer decides that they would like to join your session, DirectPlay will call your message handler's DirectPlay8Event.IndicateConnect method.

See the Peer-to-Peer Sessions and Client/Server Sessions sections for further discussion of how to arrange and launch a game.


Using the DirectPlay DPNSVR Application

Microsoft® Windows® allows one process per IP or IPX port. Windows does not allow multiple processes to share a single port. To act as a communication host, each application must use a separate port. This restriction creates several issues, especially with such tasks as enumerating running games:

  • Avoiding port conflicts. You must choose a port that does not conflict with other applications.
  • Managing multiple communications hosts on a single system. Each instance of a host must use a different port. Client applications must then determine which port a particular host is using.
  • Avoiding ports that are already in use. If your preferred port is in use, your application must be able to use another port.

The DPNSVR application addresses these issues by acting as a forwarding service for enumeration requests. When an application begins hosting, it notifies DPNSVR on which port it is running. DPNSVR monitors a well-known port and forwards any enumeration requests to all Microsoft® DirectPlay® hosts on the system. Responses to enumeration requests contain the port number to which the host is actually connected.

The following diagram illustrates how DPNSVR—on a computer with two active host applications—handles an enumeration query from a remote client.

DPNSVR offers developers the following advantages.

  • You can write generic enumeration routines that enumerate all the games running on a particular system.
  • You can use DirectPlay to select the host's port. Client applications can use the services of DPNSVR to enumerate the running games on a well-known port, and the responses will contain the port number to which the host is actually connected.
  • You need not allow for the situation where your application does not get the port it requests.
  • You need not be concerned about conflicts with other applications on the system.

While most applications will benefit from the services of DPNSVR, in some circumstances you may want to disable it. Two examples are:

  • You know what port you want to use, and only one instance of your application will be running on the computer.
  • You want to restrict the ability of players to enumerate your session. If you disable DPNSVR, only those players who know which port your host is connected to will be able to enumerate your host.

How to Use DPNSVR

To determine if DPNSVR is supported by your service provider, call the GetSPCaps methods supported by the DirectPlay8Peer, DirectPlay8Client, or DirectPlay8Server objects. If the service provider supports DPNSVR, the DPNSPCAPS_SUPPORTSDPNSRV flag will be set in the dwFlags member or the returned DPN_SP_CAPS type. Only IP and IPX service providers currently support DPNSVR.

Note Applications can always enumerate your host if they know the port on which it is running, even if the DPNSESSION_NODPNSVR flag is set.

Using DPNSVR requires no special effort, because it is selected by default. If you do not want enumeration requests forwarded to your host, you must explicitly disable DPNSVR by setting the DPNSESSION_NODPNSVR flag in the dwFlags member of the DPN_APPLICATION_DESC type. Some additional characteristics of DPNSVR are:
  • DPNSVR does not have a window but it does appear in the user's task list.
  • If no applications are using DPNSVR, it shuts down after ten minutes of inactivity. DPNSVR is automatically started up when an application begins hosting.
  • You can shut down DPNSVR by running "DPNSVR /K" from the command line and it will shut down immediately. However, if you have any host applications open when you shut down DPNSVR, they will no longer be able to receive enumerations on the DPNSVR port.


Using the DirectPlay Lobby Visual Basic API

This set of documents provides detailed information about how to use the Microsoft® DirectPlay® Visual Basic® Lobby application programming interface (API). For general information about using DirectPlay, see Using the DirectPlay Core API.

  • Implementing a Lobby Client
  • Implementing a Lobbyable Application


Implementing a Lobby Client

A lobby client is an application that resides on a user's computer. It typically serves as a link between a game application on the user's computer and a lobby server on a remote computer. However, lobby clients can also function as stand-alone applications. For instance, they can be used to arrange a game session among the users of a particular LAN subnet.

Lobby clients typically consist of three primary components that handle the following tasks:

  • Communicating with the outside world, either a lobby server or other lobby clients.
  • Communicating with the user, typically through a graphical user interface (GUI).
  • Communicating with Microsoft® DirectPlay® .

DirectPlay does not specify how the first two items should be implemented. Lobby client vendors should use whatever approach is suitable to their product. What DirectPlay provides is a standard API that a lobby client can use to communicate with DirectPlay, and through DirectPlay with the user's lobbyable game applications.

This section discusses the following essential details of lobby client implementation.

  • Initializing a Lobby Client
  • Launching a Lobbied Application
  • Implementing a Lobby Client Message Handler
  • Communicating with a Lobbied Application
  • Closing Down a Lobby Client

See the LobbyClient sample application for a fully implemented example of a simple lobby client.


Initializing a Lobby Client

Lobby clients are either launched by a lobby server or directly by a user. Once a lobby client is launched, it must be initialized before it can launch an application. Initialization involves the following tasks.

  • Create a DirectPlay8LobbyClient object.
  • Create a DirectPlay8LobbyEvent object. The DirectPlay8LobbyEvent object is essentially a message handler that receives messages directly from the lobby client object, and indirectly from the application. It is not provided by Microsoft® DirectPlay® and must be implemented by your application.
  • You must register this object with DirectPlay by calling DirectPlay8LobbyClient.RegisterMessageHandler.
  • Use the DirectPlay8LobbyClient.GetLocalProgram method to enumerate the lobbyable applications on the user's system.

The first two steps create the lobby client object, and set up a communication link between that object and your lobby client. The final step determines what lobbyable applications are available on the user's system. You need this information in order to launch the selected application.

You should store the application GUIDs of the registered applications because you need them to launch the application.

Depending on the design of your lobby client, you may also want to do one or more of the following tasks.

  • Perform any initialization that is not related to Microsoft® DirectPlay® , such as establishing a link with the lobby server.
  • Create a DirectPlay8Peer or DirectPlay8Client object.
    •
  • Use the peer or client object's enumeration methods to enumerate available service providers, adapters, and so on.


Launching a Lobbied Application

When the user has selected an application and your lobby client has verified that it has been registered on the user's system, you can launch the application. To do so, call DirectPlay8LobbyClient.ConnectApplication. The first parameter is a DPL_CONNECT_INFO structure that contains a variety of information needed to launch the application including the following:

  • The GUID that identifies the application.
  • The connection settings, including the user's Microsoft® DirectPlay® address. See DirectPlay Addressing for a discussion of DirectPlay addresses.
  • Whether the application will be a host.

The DirectPlay8LobbyClient.ConnectApplication method returns an application handle that is used to identify the application in all further communication. Once the application has launched and the connection successfully established, DirectPlay will call your message handlers DirectPlay8LobbyEvent.Connect method.

Note Your message handler's DirectPlay8LobbyEvent.Connect method may be called before the DirectPlay8LobbyClient.ConnectApplication method has confirmed the connection by returning a success code. Your message handler should be prepared to handle the message even if the method has not yet returned.


Implementing a Lobby Client Message Handler

The message handler is a DirectPlay8LobbyEvent object, that receives messages directly from the lobby client object, and indirectly from the application. It is not provided by DirectPlay and must be implemented by your application.

Your message handler must implement all of the following methods:

  • DirectPlay8LobbyEvent.Connect
  • DirectPlay8LobbyEvent.ConnectionSettings
  • DirectPlay8LobbyEvent.Disconnect
  • DirectPlay8LobbyEvent.Receive
  • DirectPlay8LobbyEvent.SessionStatus

Most of these methods are called by DirectPlay in response to changes in the game status, or when the lobby client requests information. The exception is DirectPlay8LobbyEvent.Receive. This method is called to pass data directly from the game application to the lobby client.

DirectPlay8LobbyEvent.Connect

This method is called by DirectPlay following the launch of a lobbyable application. The message indicates that the application has been successfully connected. The associated DPL_MESSAGE_CONNECT type holds a variety of information, including:

  • A connection ID. Use this ID when your lobby client needs to send data to the application with DirectPlay8LobbyClient.Send, or release the connection with DirectPlay8LobbyClient.ReleaseApplication.
  • Lobby connection data.
  • An optional connection context value.

DirectPlay8LobbyEvent.ConnectionSettings

This message is called by DirectPlay whenever an associated lobbyable application calls its DirectPlay8LobbiedApplication.SetConnectionSettings method to modify the session connections. The associated DPL_MESSAGE_CONNECTION_SETTINGS type contains the updated connection information.

DirectPlay8LobbyEvent.Disconnect

This message is sent when the lobbyable application disconnects from the session by calling DirectPlay8LobbiedApplication.Close. Your lobby client application should delete the connection from its list and free any data that is associated with the application.

DirectPlay8LobbyEvent.Receive

This message enables an application to pass data to the lobby client by calling DirectPlay8LobbiedApplication.Send. DirectPlay passes the data block from the application to the lobby client in a DPL_MESSAGE_RECEIVE type. It is up to the lobby client to process the data.

DirectPlay8LobbyEvent.SessionStatus

This message is sent by DirectPlay whenever one of the following six changes in the session's status occurs.

  • The session is connected.
  • The session could not connect.
  • The session has been disconnected.
  • The session has been terminated.
  • The session host has migrated.
  • This computer has become the session host.

The type of status change is indicated by the value of the method's status parameter.

For more information, see A Sample Lobby Client Message Handler.


Communicating with a Lobbied Application

Much of the lobby client's interaction with an associated application is indirect. The lobby client does something that affects the application, and Microsoft® DirectPlay® sends an appropriate message, and vice versa. For instance, if the lobby client changes the connection settings, DirectPlay notifies the application and provides the new settings. However, the DirectPlay8LobbyClient.Send method enables the lobby client to send a message directly to the application. DirectPlay passes the data to the application without modification. It is the responsibility of the application to process that data.

The lobbied application can also send data directly to the lobby client. DirectPlay transmits the data by calling the lobby client message handler's DirectPlay8LobbyEvent.Receive method. DirectPlay passes the data to the lobby client without modification. It is up to the lobby client to process the data.


Closing Down a Lobby Client

When you are ready to close the session, disconnect the application by calling DirectPlay8LobbyClient.ReleaseApplication. Microsoft® DirectPlay® will call notification by calling its message handler's DirectPlay8LobbyEvent.Disconnect method.

After releasing the application, perform any cleanup that is necessary, and close the session by calling DirectPlay8LobbyClient.Close.


Implementing a Lobbyable Application

A lobbyable application must be designed to work properly with a lobby client. While a lobby client can launch any application, only lobby-launched applications can receive messages from Microsoft® DirectPlay® and from the lobby client. To be lobby launched, an application must be appropriately registered, and it must be able to use a DirectPlay lobbied application object to communicate with DirectPlay and the lobby client.

This section discusses how to implement lobbyable applications.

  • Registering a Lobbyable Application
  • Handling Lobby Launching
  • Implementing a Lobbied Application Callback Message Handler
  • Communicating with a Lobby Client
  • Closing Down a Lobbied Application


Registering a Lobbyable Application

A lobbyable application must be registered before it can be lobby launched. This registration needs to be done only once and is typically handled by the application's setup procedure. Do not attempt to modify the registry directly to register an application as lobbyable. Instead, do the following:

  • Create a DirectPlay8LobbiedApplication object.
  • Call DirectPlay8LobbiedApplication.RegisterProgram.This method takes the information and creates appropriate registry keys and values.

You must provide DirectPlay8LobbiedApplication.RegisterProgram with a variety of information, including the following:
  • A GUID that is used to identify the application.
  • A friendly name for the application.
  • The location and name of the application's executable file.
  • The location and name of an optional launcher application.
  • Any command-line arguments that need to be passed to the executable file when it is launched.

Instead of launching the game application, Microsoft® DirectPlay® launches a launcher application. The launcher application then launches the game. Launcher applications can be used, for example, as an anti-piracy measure.

To unregister a registered program, call DirectPlay8LobbiedApplication.UnRegisterProgram. This method removes the registry entries created by DirectPlay8LobbiedApplication.RegisterProgram.


Handling Lobby Launching

The first thing your lobbyable application should do when it is launched is to create and initialize a Microsoft® DirectPlay® lobbied application object. To do this, perform the following tasks.

  • Create a DirectPlay8LobbiedApplication object.
  • Create a DirectPlay8LobbyEvent message handler object
  • Register the message handler object by calling DirectPlay8LobbiedApplication.RegisterMessageHandler.

If the application was lobby-launched, DirectPlay will call your DirectPlay8LobbyEvent.Connect method. The dlNotify parameter will contain a DPL_MESSAGE_CONNECT type with connection information. such as address objects for the members of the session.

If your application was not lobby launched, you can indicate that your application is available to lobby clients for connection by calling DirectPlay8LobbiedApplication.SetAppAvailable. This method is typically called when the application has been launched by the user. However, it can also be used if the user has closed one session but the application is still running and available for another session. In either case, DirectPlay will call your message handler's DirectPlay8LobbyEvent.Connect method when the lobby client connects your application to a session.


Implementing a Lobbied Application Callback Message Handler

The message handler is a DirectPlay8LobbyEvent object, that receives messages directly from the lobby client object, and indirectly from the application. It is not provided by Microsoft® DirectPlay® and must be implemented by your application.

Your message handler must implement all of the following methods:

  • DirectPlay8LobbyEvent.Connect
  • DirectPlay8LobbyEvent.ConnectionSettings
  • DirectPlay8LobbyEvent.Disconnect
  • DirectPlay8LobbyEvent.Receive
  • DirectPlay8LobbyEvent.SessionStatus

Most of these methods are called by DirectPlay in response to changes in the game status, or when the lobbied application requests information. The exception is DirectPlay8LobbyEvent.Receive. This method is called to pass data directly from the lobby client to the game application.

DirectPlay8LobbyEvent.Connect

This method is called when the lobby client calls DirectPlay8LobbyClient.ConnectApplication to connect an application to a session. The associated DPL_MESSAGE_CONNECT type holds a variety of information, including:

  • A connection ID. Use this ID when your lobby client needs to send data to the application with DirectPlay8LobbyClient.Send, or release the connection with DirectPlay8LobbyClient.ReleaseApplication.
  • Lobby connection data.
  • An optional connection context value.

DirectPlay8LobbyEvent.ConnectionSettings

DirectPlay calls this method whenever an associated lobby client calls its DirectPlay8LobbyClient.SetConnectionSettings method to modify the session connections. The associated DPL_MESSAGE_CONNECTION_SETTINGS type contains the updated connection information.

DirectPlay8LobbyEvent.Disconnect

This message is sent when the lobby client disconnects the application from the session by calling DirectPlay8LobbyClient.ReleaseApplication. Your application should delete the connection from its list, and free any data that is associated with the session.

DirectPlay8LobbyEvent.Receive

This message enables a lobby client to pass data to an application. When the lobby client calls DirectPlay8LobbyClient.Send, DirectPlay passes the data to the application by calling DirectPlay8LobbyEvent.Receive. It is up to the application to process the data.

DirectPlay8LobbyEvent.SessionStatus

DirectPlay does not call this method for lobbyable application message handlers. You must implement this method, but it can simply return 0.


Communicating with a Lobby Client

Much of the lobbied application's interaction with an associated lobby client is indirect. The application does something that affects the lobby client, Microsoft® DirectPlay® sends an appropriate message, and vice versa. For instance, if the application changes the connection settings, DirectPlay notifies the lobby client, and provides the new settings. However, there are two methods that provide information directly to the lobby client: DirectPlay8LobbiedApplication.UpdateStatus and DirectPlay8LobbiedApplication.Send.

You must notify the lobby client when any of the following changes in the game status take place.

  • The session is connected.
  • The session could not connect.
  • The session has been disconnected.
  • The session has been terminated.
  • The session host has migrated.
  • This computer has become the session host.

To notify the lobby client of one of these status changes, call DirectPlay8LobbiedApplication.UpdateStatus, and set the lStatus parameter to the appropriate value. DirectPlay will call the lobby client message handler's DirectPlay8LobbyEvent.SessionStatus method to notify it of the status change.

The DirectPlay8LobbiedApplication.Send method enables the application to send a message directly to the lobby client. DirectPlay passes the data to the lobby client without modification. It is the responsibility of the lobby client to process that data.

The lobby client can also send data directly to the application. DirectPlay passes the data to the lobby client's message handler by calling its DirectPlay8LobbyEvent.Receive method. DirectPlay passes the data to the application without modification. The lobby client must process the data.


Closing Down a Lobbied Application

To close a session, call DirectPlay8LobbiedApplication.Close. Microsoft® DirectPlay® calls the lobby client message handler's DirectPlay8LobbyEvent.Disconnect method to notify it of the disconnection. If you want to keep the application running and connect to another session, indicate that your application is available by calling DirectPlay8LobbiedApplication.SetAppAvailable.


Using the DirectPlay Voice Visual Basic API

This documentation provides detailed information about how to use the Microsoft® DirectPlay® Visual Basic® Voice application programming interface (API). For general information about using DirectPlay, see Using the DirectPlay Core Visual Basic API.

  • Configuring the Windows Sound Mixer


Configuring the Windows Sound Mixer

The Microsoft® Windows® audio mixer must be correctly set up for Microsoft® DirectPlay® Voice to function properly. This article contains the following sections, which describe how to set up the sound mixer to support a DirectPlay Voice session.

  • Selecting a DirectPlay Voice Device
  • Configuring the Windows Sound Mixer for Playback
  • Configuring the Windows Sound Mixer for Recording
  • Microphone Boost
  • Autoconfiguration

Selecting a DirectPlay Voice Device

On Microsoft® Windows XP and Microsoft® Windows Millennium Edition (Windows Me) systems, the Sound and Audio Devices Control Panel application has a Voice tab. You can use this tab to select playback and recording devices for DirectPlay Voice. If you have multiple sound cards on your system, you can select a different sound card for DirectPlay Voice transmissions than the sound card you use for normal audio.

Configuring the Windows Sound Mixer for Playback

To set up your sound system for DirectPlay Voice playback, you might have to configure the Windows audio playback mixer. You can launch the playback mixer in several ways, including:

  • Double-click the speaker icon in the status area of the taskbar.
  • Launch the Voice Test Wizard and click the Volume button below the Playback box on the microphone or speaker test pages.
  • Launch the Sound and Audio Devices Control Panel application, select the Audio Devices tab, and click the playback section's Volume button.

The following screen shot shows the Windows 2000 playback mixer.

Windows Audio Playback Mixer

To configure the playback mixer

  1. From the Options menu, choose Properties.
  2. In the Properties dialog box that appears, click Playback.
  3. At the bottom of the dialog box, make sure all available output lines are selected, as shown.
  4. Click OK to display the playback mixer again.
The following screen shot shows the mixer's Properties dialog box.

Audio Mixer Properties

The microphone has separate playback and recording lines. You must disable microphone playback line or your microphone input will be routed to your speakers and DirectPlay Voice will not be able to record your input.

To disable the microphone playback line

  1. Click OK on the Properties dialog box to display the playback mixer again.
  2. Make sure that the microphone section's Mute check box is selected.
  3. If the microphone section has a check box labeled Select, clear the check box.

Configuring the Windows Sound Mixer for Recording

You may also need to manually configure the recording mixer. There are three ways to launch the recording mixer.

  • Launch the Sound and Audio Devices Control Panel application, select the Audio Devices tab, and click the playback section's Volume button.
  • Launch the Voice Test Wizard and click the Volume button below the Recording box on either the microphone or speaker test pages.
  • Launch the playback mixer, choose the Properties command on the Options menu, select the Recording radio button, and click OK.

To configure the recording settings

  1. From the Options menu, choose Properties.
  2. Select Recording. The check boxes at the bottom of the dialog box will show all the available audio input sources for your selected devices.
  3. Make sure that all sources are selected, and click OK.
    The recording mixer will then display a volume control for the microphone and all other selected sources.
  4. Make sure that the microphone's Select check box is selected, and all other Select boxes are clear. In particular, do not select CD Audio. If CD Audio is selected and your user is listening to a CD while playing the game, DirectPlay Voice will transmit the output from the CD.
The following screen shot shows the Windows 2000 recording mixer.

Recording Mixer

Microphone Boost

Many sound cards have an option called "Microphone Boost" or "Mic Boost." This feature boosts the input volume so that weak input devices can produce stronger input. If you determine that the input level from a system is too low for your voice session, you can enable microphone boost.

To enable microphone boost

  1. Display the recording mixer, as described in the previous section.
  2. Enable the Advanced buttons on the mixer by choosing the Advanced command from the Options menu.
  3. Click the microphone line's Advanced button to display the microphone's Advanced Controls dialog box.
  4. Select the Microphone Boost check box.
If microphone boost makes your input too loud, you can use the same procedure to disable microphone boost. If your sound card does not support microphone boost, one or more of the following will be true.

  • The Advanced command on the recording mixer's Options menu will be unavailable.
  • The Advanced button in the recording mixer's microphone section will be unavailable.
  • The Microphone Boost check box on the Advanced Control dialog box will be unavailable.

Autoconfiguration

If you set the DVSOUNDCONFIG_AUTOSELECT flag in the dwFlags member of the DVSOUNDDEVICECONFIG structure, DirectPlay Voice will attempt to configure the recording portion of the audio mixer for you. However, the attempt might fail. For example, DirectPlay Voice always chooses microphone 0 as the input source. If your user's system has more than one microphone, autoselection works only if the user has the microphone connected to the microphone 0 input. To use another microphone channel, the user must configure the mixer manually.

Note To ensure that your application works on all systems, you should allow your users to disable autoselection if necessary and configure the mixer manually.


DirectPlay Visual Basic Samples

The following sample applications demonstrate the use and capabilities of the Microsoft® DirectPlay® application programming interface for the Microsoft® Visual Basic® programming language. Refer to the Readme.txt file in each sample folder for details. All sample folders can be found under the SDK root directory, typically C:\Dxsdk.

  • Chat
  • Conferencer
  • DataRelay
  • DXVB Messenger
  • Memory
  • SimpleClient
  • SimplePeer
  • SimpleServer
  • SimpleVoice
  • StagedPeer
  • VoiceGroup


Chat

The Chat sample enables the host and players connected to a session to chat with each other by passing text strings.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Chat

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

Refer to the User's Guide section of the SimplePeer sample.

Programming Notes

The ChatPeer sample is very similar in form to the SimplePeer. ChatPeer differs by enabling clients to send text strings instead of funny faces to all players connected to the session.

When a player types a text string and presses ENTER, the txtSend_KeyPress function does the following:

  1. Retrieves the text string from the dialog box.
  2. Fills out a byte array using the string.
  3. Calls the DirectPlay8Peer.SendTo method and passes the byte array. It sets the DPNID_ALL_PLAYERS_GROUP flag so that this message goes to all of the players.

When a player types a text string and presses Whisper, the cmdWhisper_Click function does the following:

  1. Retrieves the text string from the dialog box.
  2. Fills out a byte array using the string.
  3. Calls the DirectPlay8Peer.SendTo method and passes the byte array. It sets the DPNID of the player so that the message goes only to the person to whom the player is whispering.

The Chat sample handles the DPNMSG_RECEIVE message. On receipt of the message, the DirectPlay8Event_Recieve function:

  1. Checks if this is a Chat message or a Whisper message.
  2. Retrieves the string from the byte array.
  3. Updates the user interface accordingly.

See the DirectPlay8Event objects in the source code for more messages that the Chat sample handles.


Conferencer

The Conferencer sample is similar in form to Microsoft® NetMeeting®.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Conferencer

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

You may "call" friends in this application, and then share files, share a whiteboard, use voice chat, and text chat.

Programming Notes

The following table lists the messages that the Conferencer sample handles.

MsgChat | This message is received when someone is chatting (text) in the chat window.
MsgWhisper | This message is received when someone is whispering (text) in the chat window.
MsgAskToJoin | When a user attempts to contact you, this message is sent, which will pop up a dialog that enables the person receiving the event the opportunity to deny this person from joining.
MsgAcceptJoin | You will to allow this person to join your session.
MsgRejectJoin | You will not allow this person to join your session.
MsgCancelCall | You no longer want to wait for the session you are attempting to join to either accept or deny you.
MsgShowChat | Someone has opened the text chat window, and wants this session to do the same.
MsgSendFileRequest | Request a file transfer.
MsgSendFileAccept | Accept the file transfer.
MsgSendFileDeny | Deny the file transfer.
MsgSendFileInfo | Send file size information.
MsgSendFilePart | Send a part of the file.
MsgAckFilePart | Acknowledge the file part.
MsgSendDrawPixel | Send a drawn pixel in the whiteboard window, including color.
MsgSendDrawLine | Send a drawn line in the whiteboard window, including color.
MsgShowWhiteBoard | Show the whiteboard window.
MsgClearWhiteBoard | Clear the contents of the whiteboard.


DataRelay

The DataRelay sample is similar to SimplePeer but differs by sending a packet of data to a single target (or everyone) with options specified in the dialog box's user interface (UI).

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\DataRelay

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

You can host or connect to a session in the same manner as explained in the SimplePeer sample. When the main dialog appears select the target, size, rate, and timeout values. Then click the Push to Send button. This will send a packet of data with the specified size to the target at intervals specified by the rate.

Programming Notes

The DataRelay sample is very similar in form to the SimplePeer sample. The DataRelay sample differs by sending to a single target (or everyone) a packet of data with the options specified in the dialog box's UI.

When the Push to Send button is clicked, a timer goes off at intervals depending on the number of milliseconds selected in the Rate box. When the timer goes off, the application sends the user defined data packet in the following steps.

  1. A byte array is created with the options specified in the vbDataRelay box.
  2. DirectPlay8Peer.SendTo is called and the byte array is passed. The DataRelay sample sets the flag DPNSEND_NOLOOPBACK which tells Microsoft® DirectPlay® not to send the buffer back to the sender.

The DataRelay sample handles the following messages.

  • DPNMSG_RECEIVE. Upon receipt, the DataRelay sample:
    1. Gets the message type from the received byte array.
    2. Selects the data packet with the correct message type.
    3. Adds the data to a collection if the message type is MSG_GamePacket. A timer will notice the data in the collection and process it. This is important for keeping the DirectPlay threads working at full speed.
  • DPNMSG_SEND_COMPLETE. Upon receipt, the DataRelay sample:
    1. Checks the dpnotify.hResultCode for DPNERR_TIMEDOUT flag.
    2. Updates the UI if this flag exists.

See the DirectPlay8Event objects in the source code for more messages that the DataRelay sample handles.


DXVB Messenger

The DXVBMessenger sample is a simple client/server instant messaging application.

DXVB Messenger Server is the server portion of a client/server instant messaging application. This sample requires the use of XML to maintain the data needed. You must have at least Internet Explorer 4 installed on your machine to compile or run this sample.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\DXVBMessenger

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

Log on to a server, add friends, and send instant messages.

Programming Notes

The DXVBMessenger handles DirectPlay system messages. See implemented DirectPlay8Event objects in the source code for details.

DXVBMessenger client handles the DPNMSG_RECEIVE message and upon receipt will process the following message types.

Msg_LoginSuccess | Logged in successfully, update the UI
Msg_InvalidPassword | The password for this account is invalid
Msg_InvalidUser | This user doesn't exist
Msg_UserAlreadyExists | This user already exists
Msg_FriendAdded | A user was added to my list of friends
Msg_FriendDoesNotExist | Tried to add a friend that doesn't exist
Msg_BlockUserDoesNotExist | Tried to block a user that doesn't exist
Msg_FriendBlocked | A user was added to my list of blocked users
Msg_SendClientFriends | Get the list of my friends from the server
Msg_UserBlocked | Can't send a message to this person; they've blocked you
Msg_ReceiveMessage | Received a message; show the message UI and display the message
Msg_FriendLogon | A friend has just logged on, update UI
Msg_FriendLogoff | A friend has just logged off, update UI

DXVBMessenger server handles the DPNMSG_RECEIVE message and upon receipt will process the following message types.

Msg_Login | Get log on information, verify against the database
Msg_CreateNewAccount | A new account needs to be created; try to create in database
Msg_AddFriend | Add a friend to this users list
Msg_BlockFriend | Block someone in this users list
Msg_SendMessage | User is sending a message to someone, pass it on


Memory

Memory is a simple game in which you match tiles and try to score the most points.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Memory

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

Double-click the Memory icon to start the game. The application opens a small window and you can choose Multiplayer or Solitaire. When the Memory board opens, begin selecting tiles and try to match the images. Score one point for every match. In multiplayer mode, try to get more matches than your opponent(s). In solitaire mode, try to clear the board in as few attempts as possible.

Programming Notes

The Memory sample is very similar in form to the SimplePeer sample. For more information, see the Programming Notes section of the SimplePeer sample.

When a tile is clicked, the application will take the following steps.

  1. If it's the local player's turn, show the picture.
  2. Fill out a byte array telling everyone else to show the picture.
  3. Call DirectPlay8Peer.SendTo with the buffer() parameter set to the byte array. It also passes the DPNID_ALL_PLAYERS_GROUP flag in the idSend parameter so that this message goes to everyone.

When the Memory sample receives the DPNMSG_RECEIVE message, the DirectPlay8Event_Recieve function:

  • Checks the type of this message.
  • Selects the data packet with the correct message type.

The application will the process the following message types.

MSG_SETUPBOARD | Retrieve board information and update the local state.
MSG_SHOWPIECE | Show the image behind the indicated tile.
MSG_HIDEPIECES | Hide all tiles that aren't currently matched.
MSG_TURNEND | Advance to the next players turn.
MSG_CHAT | Receive a text string and update the user interface (UI).
MSG_MATCHED | Set the state so these two pictures are marked as matched.
See the DirectPlay8Event interfaces in the source code for more messages that the Memory sample handles.


SimpleClient

The SimpleClient sample is a simple application that can connect to a server and make funny faces to other players on that server.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\SimpleClient

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

Double-click the SimpleClient icon to start the game. First, you must enter your name and choose your service provider, then click OK. When the Create or Join Session dialog box opens, click the Start Search button to find a session. A window will open where you may enter a remote host address. If you do not enter an address, SimpleClient will search the local network. Choose a session in the Create or Join Session dialog box and click Join. When the game window opens, click the Make Faces button to make faces at other players.

Note The SimpleServer must be running to play this game.

Programming Notes

When the Make Faces button is pressed, the cmdFace_Click function:

  1. Creates an empty byte array, since all we can do is make faces.
  2. Calls DirectPlay8Client.Send with the buffer() parameter set to the byte array. The server will receive this message and handle it.

When a message is received from the server, the DirectPlay8Event_Receive function checks for the following message types.

Msg_NumPlayers | Change the number of current and max players in this session, update user interface (UI).
Msg_NoOtherPlayers | Notify the client there are no other players in the session.
Msg_SendWave | Notify the client that someone made a funny face at them.


SimplePeer

The SimplePeer sample allows players to make funny faces. Players can be either peers or the session host.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\SimplePeer

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

Double click the SimplePeer icon to start the application. Before you can start the game, you must select the protocol to use and enter your name. When the Create or Join Session dialog box opens, you have three choices.

  • Click Create to create a new session where you are the host.
  • Click Start Search to find a session to join.
  • Wait for a lobby session.

Once you are connected to a session, click Make Face to make funny faces at other players.

Programming Notes

When the Make Face button is pressed, the cmdMakeFace_Click function:

  1. Fills out a byte array using 1 since this is the only message to send.
  2. Calls DirectPlay8Peer.SendTo with the buffer() parameter set to the byte array. It passes the DPNID_ALL_PLAYERS_GROUP flag in the idSend parameter so that this message goes to everyone.

When the Chat sample receives the DPNMSG_RECEIVE message, the DirectPlay8Event_Receive function gets the name of the person sending the event and updates the user interface (UI). See the DirectPlay8Event objects in the source code for more messages that the SimplePeer sample handles.


SimpleServer

The SimpleServer sample is a simple server application that can connect and route client messages.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\SimpleServer

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

Double-click the SimpleServer icon to start the application. Choose a service provider, enter a session name, and choose the maximum number of players, then click Start Server.

Programming Notes

When the SimpleServer sample receives the DPNMSG_RECEIVE message, the DirectPlay8Event_Recieve function checks to see if more than one player is in the session. If so, SimpleServer notifies everyone that a funny face was made. Otherwise, SimpleServer notifies the client that it is the only player in the session. See the DirectPlay8Event interfaces in the source code for more messages that the SimpleServer sample handles.


SimpleVoice

The SimpleVoice sample is similar in form to SimplePeer. Once a player hosts or connects to a session, the players can chat with either other.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\SimpleVoice

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

Refer to the User's Guide section of the SimplePeer sample.

Programming Notes

The SimpleVoice sample differs from the SimplePeer sample by letting clients send audio data instead of funny faces to all players connected to the session.


StagedPeer

The StagedPeer sample connects players together with two dialog boxes that prompt users on the connection settings needed to join or create a session. After the user connects to a session, the sample displays a multiplayer stage that allows all players connected to the same session to chat. Players can start a new game when everyone is ready and the host decides to begin. The host may reject players or close player slots.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\StagedPeer

Executable: (SDK root)\Samples\Multimedia\DirectPlay\Bin


VoiceGroup

The VoiceGroup sample is similar in form to SimpleVoice. Once a player hosts or connects to a session, the players can chat with either other.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\VoiceGroup

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectPlay\Bin

User's Guide

Refer to User's Guide section of the SimplePeer sample.

Programming Notes

The VoiceGroup sample differs from the SimpleVoice sample by letting clients send audio data to all players connected to the session, or to specify a group to send to.


DirectPlay Visual Basic Reference

This section contains reference information for the API elements of Microsoft® DirectPlay® for Microsoft® Visual Basic® . Reference material is divided into the following categories.

  • Classes
  • Functions
  • Types
  • Enumerations
  • Error Codes


Classes

This section contains references for methods of the following Microsoft® DirectPlay® classes.

  • DirectPlay8Address
  • DirectPlay8Client
  • DirectPlay8Event
  • DirectPlay8LobbiedApplication
  • DirectPlay8LobbyClient
  • DirectPlay8LobbyEvent
  • DirectPlay8Peer
  • DirectPlay8Server
  • DirectPlayVoiceClient8
  • DirectPlayVoiceEvent8
  • DirectPlayVoiceServer8
  • DirectPlayVoiceTest8


DirectPlay8Address

The DirectPlay8Address class provides methods for creating and managing DirectPlay addresses.

The methods of the DirectPlay8Address class are:

DirectPlay8Address Methods | AddComponentLong
 | AddComponentString
 | BuildFromURL
 | Clear
 | Duplicate
 | GetComponentLong
 | GetComponentString
 | GetDevice
 | GetNumComponents
 | GetSP
 | GetURL
 | GetUserData
 | SetDevice
 | SetEqual
 | SetSP
 | SetUserData


DirectPlay8Address.AddComponentLong

Adds a component of type Long to the address. If the component is part of the address, then it is replaced by the new value in this call.

AddComponentLong(sComponent As String, lValue As Long)

Parts

sComponent
String that contains the key for the component.
lValue
Long value to be added to the component.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDPARAM
DPNERR_NOTALLOWED


DirectPlay8Address.AddComponentString

Adds a component of type String to the address. If the component is part of the address, then it is replaced by the new value in this call.

AddComponentString(sComponent As String, sValue As String)

Parts

sComponent
String that contains the key for the component.
sValue
String value to be added to the component.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDPARAM
DPNERR_NOTALLOWED


DirectPlay8Address.BuildFromURL

Sets the object equal to the address of a DirectPlay URL. It erases the contents of the object.

BuildFromURL(SourceURL As String)

Parts

SourceURL
String that contains a properly formatted DirectPlay address.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDURL
DPNERR_NOTALLOWED


DirectPlay8Address.Clear

Resets the address object to an empty address.

Clear()

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_NOTALLOWED


DirectPlay8Address.Duplicate

Creates a DirectPlay8Address object that duplicates the address in this object.

Duplicate() As DirectPlay8Address

Return Values

Returns a DirectPlay8Address object.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_GENERIC


DirectPlay8Address.GetComponentLong

Retrieves one of the integer components in the address URL string.

GetComponentLong(sComponent As String) As Long

Parts

sComponent
Name of the component to retrieve.

Return Values

Returns the value of the requested component.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_DOESNOTEXIST
DPNERR_INVALIDPARAM
DPNERR_BUFFERTOOSMALL

Remarks

For a discussion of the URL string, see DirectPlay Addressing.


DirectPlay8Address.GetComponentString

Retrieves one of the integer components in the address URL string.

GetComponentString(sComponent As String) As String

Parts

sComponent
Name of the component to retrieve.

Return Values

Returns the requested string.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_DOESNOTEXIST
DPNERR_INVALIDPARAM
DPNERR_BUFFERTOOSMALL

Remarks

For a discussion of the URL string, see DirectPlay Addressing.


DirectPlay8Address.GetDevice

Retrieves the local device GUID in the address object. If no device is specified, this method raises DPNERR_DOESNOTEXIST.

GetDevice() As String

Return Values

Returns a String value representing the device in the address object.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_DOESNOTEXIST


DirectPlay8Address.GetNumComponents

Retrieves the number of components in the address.

GetNumComponents() As Long

Return Values

Returns the number of components in this address object.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Address.GetSP

Retrieves the service provider GUID in the address object. If no service provider is specified, this method raises DPNERR_DOESNOTEXIST.

GetSP() As String

Return Values

Returns the service provider in the address object.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_DOESNOTEXIST


DirectPlay8Address.GetURL

Retrieves the DirectPlay address URL represented by this object.

GetURL() As String

Return Values

Returns the URL represented by this object.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_OUTOFMEMORY
DPNERR_INVALIDURL
DPNERR_GENERIC


DirectPlay8Address.GetUserData

Retrieves the user data in the address object. If no user data exists in this address object, DPNERR_DOESNOTEXIST is raised.

GetUserData(UserData As Long)

Parts

UserData
User data from this address.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_DOESNOTEXIST


DirectPlay8Address.SetDevice

Sets the local device GUID in the address object. If a local device is specified for this address, it is overwritten by this call.

SetDevice(guidDevice As String)

Parts

guidDevice
GUID of the local device.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_NOTALLOWED


DirectPlay8Address.SetEqual

Sets this DirectPlay8Address object to the address specified.

SetEqual(Address As DirectPlay8Address)

Parts

Address
DirectPlay8Address object that this object will be set to.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_NOTALLOWED


DirectPlay8Address.SetSP

Sets the service provider GUID in the address object. If a service provider is specified for this address, it is overwritten by this call.

SetSP(guidSP As String)

Parts

guidSP
Service provider GUID to set.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_NOTALLOWED


DirectPlay8Address.SetUserData

Sets the user data in the address object. If there is user data in this address, it is overwritten by this call.

SetUserData(UserData As Long, lDataSize As Long)

Parts

UserData
Data to place in the user data section of the address. Set to 0 to clear the user data.
lDataSize
Size, in bytes, of the data in UserData. If UserData is 0, this must be 0.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_NOTALLOWED


DirectPlay8Client

Applications use the methods of the DirectPlay8Client class to create and manage client applications for client/server sessions.

The methods of the DirectPlay8Client class can be organized into the following groups.

Session Management | Close
 | Connect
 | EnumHosts
 | GetApplicationDesc
 | GetCaps
 | GetCountServiceProviders
 | GetServiceProvider
 | GetSPCaps
 | SetCaps
 | SetSPCaps
Message Management | GetSendQueueInfo
 | RegisterMessageHandler
 | UnRegisterMessageHandler
 | Send
Client Information | SetClientInfo
Server Information | GetServerAddress
 | GetServerInfo
Miscellaneous | CancelAsyncOperation
 | GetConnectionInfo
 | RegisterLobby


DirectPlay8Client.CancelAsyncOperation

Cancels asynchronous requests. Many methods of the DirectPlay8Client class run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this class that can be run asynchronously return an lAsyncHandle parameter.

Specific requests are canceled by passing the lAsyncHandle of the request in this method's lAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, passing 0 in the lAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the lFlags parameter. If a specific handle is provided to this method, you must pass 0 in the lFlags parameter.

CancelAsyncOperation(lAsyncHandle As Long, _
    [lFlags As CONST_DPNCANCELFLAGS])

Parts

lAsyncHandle
Handle of the asynchronous operation to stop. This value can be 0 to stop all requests or a particular type of asynchronous request. If a specific handle for the request to cancel is specified, the lFlags parameter must be 0.
lFlags
Flag that specifies which asynchronous request to cancel. You can set this parameter to one of the flags of the CONST_DPNCANCELFLAGS enumeration.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_PENDING
DPNERR_INVALIDFLAGS
DPNERR_CANNOTCANCEL
DPNERR_INVALIDHANDLE

Remarks

You can cancel a send by providing the handle returned from DirectPlay8Client.Send method. The DirectPlay8Event.SendComplete method will still be called unless the message was sent with the DPNSEND_NOCOMPLETE flag set. If you cancel a send operation by calling DirectPlay8Peer.CancelAsyncOperation the hResultCode member of the DPNMSG_SEND_COMPLETE type that is passed to the DirectPlay8Event.SendComplete method will be set to DPNERR_CANCELLED.


DirectPlay8Client.Close

Closes the open connection to a session.

Close([lFlags As Long]);

Parts

lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_UNINITIALIZED

Remarks

Calling Close will cancel all outstanding operations, including data sent as guaranteed. To make sure all messages are sent, wait for all outstanding Send calls to complete before calling Close.


DirectPlay8Client.Connect

Establishes the connection to the server. Once a connection is established, the communication channel on the interface is open and active and the application should expect messages to arrive immediately. No messages can be sent by means of the DirectPlay8Client.Send method until the connection has completed.

Before this method is called, you can obtain an application description by calling DirectPlay8Client.EnumHosts. The EnumHosts method returns a DPN_APPLICATION_DESC type for each hosted application. The type describes the application, including the GUID of the application.

When the connection to the host is requested, the DirectPlay8Event.IndicateConnect method is called in the host's message handler. The host may either accept or reject the connection. In either case, once the host has acted, the client message handler's DirectPlay8Event.ConnectComplete method will be called to convey the response.

Connect(AppDesc As DPN_APPLICATION_DESC, _
    Address As DirectPlay8Address, _
    DeviceInfo As DirectPlay8Address, _
    lFlags As CONST_DPNOPERATIONS, _
    UserData As Any, _
    UserDataSize As Long) As Long

Parts

AppDesc
DPN_APPLICATION_DESC type that describes the application. The only member of this type that you must set is the guidApplication member. Only some of the members of this type are used by this method. The only member that you must set is guidApplication. You can also set guidInstance, pwszPassword, dwFlags, and dwSize.
Address
Optional DirectPlay8Address object that specifies the addressing information to use to connect to the computer that is hosting.
DeviceInfo
DirectPlay8Address object that specifies the network adapter (that is, NIC, modem, and so on) to use to connect to the server.
lFlags
Flag from the CONST_DPNOPERATIONS enumeration that describes the connection mode. You can set the following flag.
DPNOP_SYNC

Process the connection request synchronously. Setting this flag does not generate a DirectPlay8Event.ConnectComplete method call.

UserData
Application-specific user data.
UserDataSize
Size of the data contained in the UserData parameter.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Client.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOCONNECTION
DPNERR_INVALIDPASSWORD
DPNERR_INVALIDFLAGS
DPNERR_INVALIDINTERFACE
DPNERR_INVALIDAPPLICATION
DPNERR_NOTHOST
DPNERR_SESSIONFULL
DPNERR_HOSTREJECTEDCONNECTION
DPNERR_INVALIDINSTANCE

Remarks

Although multiple enumerations can be run concurrently, and can be run across the duration of a connection, only one connection is allowed per object. To establish a connection to more than one application, you must create another object. That is, only one running application per object is allowed. If DirectPlay8Client.Connect is called while another connection is in progress, the method raises an error.

After a call to DirectPlay8Client.Connect succeeds, all outstanding enumerations are canceled with the DPNERR_USERCANCEL error value set.


DirectPlay8Client.EnumHosts

Enumerates applications that host Microsoft® DirectPlay® games. When an application is found meeting the enumeration criteria, the DirectPlay8Event.EnumHostsResponse method is called in the application's message handler. This method contains a DPNMSG_ENUM_HOSTS_RESPONSE message type that contains a DPN_APPLICATION_DESC type that describes the applications found.

EnumHosts(ApplicationDesc As DPN_APPLICATION_DESC, _
    AddrHost As DirectPlay8Address, _
    DeviceInfo As DirectPlay8Address, _
    lRetryCount As Long, _
    lRetryInterval As Long, _
    lTimeOut As Long, _
    lFlags As  CONST_DPNOPERATIONS, _
    UserData As Any, _
    UserDataSize As Long) As Long

Parts

ApplicationDesc
DPN_APPLICATION_DESC structure that specifies which application hosts to enumerate. You can specify the following fields to reduce the number of responses to the enumeration.
guidApplication
GUID of the application to find; if not specified, all are searched for.
Password
Password to provide; secure sessions will not respond without a password.
AddrHost
DirectPlay8Address object that specifies the address of the computer that is hosting the application.
DeviceInfo
DirectPlay8Address object that specifies the service provider and settings to enumerate.
lRetryCount
Value that specifies how many times the enumeration data will be sent. You can set this parameter to zero to specify the default value. If you set this value to INFINITE, the enumeration will continue until canceled.
lRetryInterval
Value that specifies the time, in milliseconds, between successive enumeration attempts. Set this parameter to 0 to use the default value.
lTimeOut
Number of milliseconds for the enumeration to run. If 0 is specified, a default value is used. If INFINITE is specified, the enumeration continues until it is canceled.
lEnumPeriod
Value specifying how often to re-enumerate. If 0 is specified, a default value is used.
lFlags
Flag from the CONST_DPNOPERATIONS enumeration that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.
UserData
Block of data that is sent in the enumeration request to the host. The size of the data can be limited depending on the network type, but 512 bytes is supported at a minimum.
UserDataSize
Size of the data in the UserData parameter.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Client.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_TIMEDOUT
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

Because of the variety of ways enumeration can happen, it is not recommended that an application specify lEnumPeriod unless the application has some specific media knowledge.


DirectPlay8Client.GetApplicationDesc

Retrieves the full application description for the connected application.

GetApplicationDesc([lFlags As Long]) _
    As DPN_APPLICATION_DESC

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns a DPN_APPLICATION_DESC type describing the application.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOCONNECTION
DPNERR_INVALIDFLAGS
DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM


DirectPlay8Client.GetCaps

Retrieves the DPN_CAPS type for the current object.

GetCaps([lFlags As Long]) As DPN_CAPS

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns a DPN_CAPS type filled with session parameters.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Client.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Client.GetConnectionInfo

Retrieves statistical information about the connection between the local endpoint and the server.

GetConnectionInfo([lFlags As Long]) As DPN_CONNECTION_INFO

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns a DPN_CONNECTION_INFO type to retrieve information about the specified connection.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

This method can be called only after a successful Connect call has completed.


DirectPlay8Client.GetCountServiceProviders

Retrieves the number of registered service providers available to the application.

GetCountServiceProviders([lFlags As Long]) As Long

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns the number of registered service providers available to the application.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDOBJECT


DirectPlay8Client.GetSendQueueInfo

Used by the application to monitor the size of the send queue. Microsoft® DirectPlay® does not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should decrease the rate at which messages are sent.

GetSendQueueInfo(lNumMsgs As Long, _
    lNumBytes As Long, _
    [lFlags As CONST_DPNGETSENDQUEUEINFO])

Parts

lNumMsgs
Number of messages currently queued.
lNumBytes
Amount of data, in bytes, of the messages currently queued.
lFlags
Set this parameter to one of the CONST_DPNGETSENDQUEUEINFO values to get the send-queue information for a particular priority level. Set this flag to zero to get the combined send-queue information.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Client.GetServerAddress

Retrieves the address for the server for the session.

GetServerAddress([lFlags As Long]) As DirectPlay8Address

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns a DirectPlay8Address object specifying the address of the server.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED


DirectPlay8Client.GetServerInfo

Retrieves the data set for the server set by the call to the DirectPlay8Server.SetServerInfo method.

GetServerInfo([lFlags As Long]) As DPN_PLAYER_INFO

Parts

lFlags
Set this parameter to one of the CONST_DPNINFO flags to indicate whether the method should return the name or the data set.

Return Values

Returns a DPN_PLAYER_INFO type containing the name or the data set for the server.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_UNINITIALIZED


DirectPlay8Client.GetServiceProvider

Retrieves information for the specified service provider. Before calling this method, call the DirectPlay8Client.GetCountServiceProviders method to obtain the number of registered service providers available to the application.

GetServiceProvider(lIndex As Long) As DPN_SERVICE_PROVIDER_INFO

Parts

lIndex
Index value specifying the specific server provider.

Return Values

Returns a DPN_SERVICE_PROVIDER_INFO type that describes the service provider.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Client.GetSPCaps

Retrieves the DPN_SP_CAPS structure for the specified service provider.

GetSPCaps(guidSP As String, _
    [lFlags As Long]) As DPN_SP_CAPS

Parts

guidSP
String specifying the GUID of the service provider you want to get information about.
lFlags
Reserved. Must be 0.

Return Values

Returns a DPN_SP_CAPS type to receive the information about the specified service provider.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Client.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Client.RegisterLobby

Registers or unregisters an application with a lobby.

RegisterLobby(dpnHandle As Long, _
    LobbyApp As DirectPlay8LobbiedApplication, _
    [lFlags As Long])

Parts

dpnHandle
Connection handle to be used when making the calls to DirectPlay8LobbiedApplication.UpdateStatus.
LobbyApp
DirectPlay8LobbiedApplication object that specifies the application.
lFlags
Set this parameter to one of the two CONST_DPNLOBBY enumeration values to indicate whether the application is to be registered or unregistered.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM

Remarks

When an application is registered with a lobby, the lobby client automatically receives notifications of changes in game status.


DirectPlay8Client.RegisterMessageHandler

Registers an entry point in the client's code that receives the messages from the DirectPlay8Client object and from the server. This method must be called before calling any other methods of this class.

RegisterMessageHandler(event As DirectPlay8Event)

Parts

event
DirectPlay8Event object that will receive the messages generated by the client and server.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_ALREADYREGISTERED

Remarks

If you want to register a new message handler, you must first call DirectPlay8Client.UnRegisterMessageHandler to unregister the current message handler.


DirectPlay8Client.Send

Transmits data to the server. The message can be sent synchronously or asynchronously.

Send(buffer() As BYTE, _
    lTimeOut As Long, _
    [lFlags As CONST_DPNSENDFLAGS]) As Long

Parts

buffer()
Array of type BYTE that describes the data to send.
lTimeOut
Number of milliseconds to wait for the message to be sent. If the message has not been sent by the lTimeOut value, the message is not sent. If you do not want a time out for message sends, set this parameter to 0.
lFlags
Flags that describe send behavior. You can set one or more of the following flags defined in the CONST_DPNSENDFLAGS enumeration.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Client.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDFLAGS
DPNERR_TIMEDOUT

Remarks

This method will call the DirectPlay8Event.Receive method in the server's message handler. When the Send request is completed, the DirectPlay8Event.SendComplete method is called in the client's message handler. The SendComplete method contains a DPNMSG_SEND_COMPLETE message type. The success or failure of the request is contained in the hResultCode member of this message type.


DirectPlay8Client.SetCaps

Sets the capabilities for the session.

SetCaps(caps As DPN_CAPS, _
    [lFlags As Long])

Parts

caps
DPN_CAPS type used to set the information about the current session.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Client.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Client.SetClientInfo

Sets the static settings of a client with an application. Call this method before connecting to relay basic player information with the application. After the client successfully connects with the application, information obtained through this method can be retrieved by the server by calling the DirectPlay8Server.GetClientInfo method.

SetClientInfo(PlayerInfo As DPN_PLAYER_INFO, _
    [lFlags As CONST_DPNOPERATIONS]) As Long

Parts

PlayerInfo
DPN_PLAYER_INFO type that contains the peer information to set.
lFlags
Set the DPNSETCLIENTINFO_SYNC flag from the CONST_DPNOPERATIONS enumeration to have the method process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Client.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOCONNECTION
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

Transmission of nonstatic information should be handled with the DirectPlay8Client.Send method because of the high cost of using the DirectPlay8Client.SetClientInfo method.

You can modify the client information with this method after connecting to the application. Calling this method after connection will call the DirectPlay8Event.InfoNotify method in the server's message handler.


DirectPlay8Client.SetSPCaps

Sets the capabilities for the specified service provider.

SetSPCaps(guidSP As String, _
    spCaps As DPN_SP_CAPS, _
    [lFlags As Long])

Parts

guidSP
String specifying the GUID of the service provider you want to set information about.
spCaps
DPN_SP_CAPS type to set the information about the specified service provider.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Client.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Client.UnRegisterMessageHandler

Unregisters the current DirectPlay8Client message handler.

UnRegisterMessageHandler()

Remarks

You must call this method before registering a new message handler.


DirectPlay8Event

Applications use the methods of the DirectPlay8Event class to capture Microsoft® DirectPlay® events generated by the DirectPlay8Peer, DirectPlay8Client, and DirectPlay8Server classes.

DirectPlay8Event is associated with the DirectPlay8Peer, DirectPlay8Client, and DirectPlay8Server objects when calling RegisterMessageHandler for each object.

Note When implementing the DirectPlay8Event object, Microsoft® Visual Basic® requires that every method of this object is implemented in your form.

The methods of the DirectPlay8Event class are:

DirectPlay8Event Methods | AddRemovePlayerGroup
 | AppDesc
 | AsyncOpComplete
 | ConnectComplete
 | CreateGroup
 | CreatePlayer
 | DestroyGroup
 | DestroyPlayer
 | EnumHostsQuery
 | EnumHostsResponse
 | HostMigrate
 | IndicateConnect
 | IndicateConnectAborted
 | InfoNotify
 | Receive
 | SendComplete
 | TerminateSession


DirectPlay8Event.AddRemovePlayerGroup

Called by the associated DirectPlay8Peer, DirectPlay8Client, or DirectPlay8Server object when a player or group has been added to or removed from a group.

AddRemovePlayerGroup( _
    lMsgID As Long, _
    lPlayerID As Long, _
    lGroupID As Long, _
    fRejectMsg As Boolean)

Parts

lMsgID
One of the following flags, which indicate whether a player or group has joined or has left the session:
DPN_MSGID_ADD_PLAYER_TO_GROUP
A player has joined the group.
DPN_MSGID_REMOVE_PLAYER_FROM_GROUP
A player has left the group.
lPlayerID
Long value set to the ID of the player or group being added or removed.
lGroupID
Long value set to the ID of the group this player or group is being added to or removed from.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.AppDesc

Called when the application description has been changed by a call to the DirectPlay8Peer.SetApplicationDesc or DirectPlay8Server.SetApplicationDesc method.

AppDesc(fRejectMsg As Boolean)

Parts

fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.AsyncOpComplete

Called when an asynchronous operation has completed.

AsyncOpComplete( _
    dpnotify As DPNMSG_ASYNC_OP_COMPLETE, _
    fRejectMsg As Boolean)

Parts

dpnotify
DPNMSG_ASYNC_OP_COMPLETE message type containing the handle and the result of the asynchronous operation.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.ConnectComplete

Called when the attempt to connect to the host or server has completed.

ConnectComplete( _
    dpnotify As DPNMSG_CONNECT_COMPLETE,
    fRejectMsg As Boolean)

Parts

dpnotify
DPNMSG_CONNECT_COMPLETE message type containing the async handle and the result of the connection attempt.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.CreateGroup

Called when a group is created.

CreateGroup ( _
    lGroupID As Long, _
    lOwnerID As Long, _
    fRejectMsg As Boolean)

Parts

lGroupID
Long value set to the group's ID.
lOwnerID
Long value set to the owner's ID.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.CreatePlayer

Called when a player is created.

CreatePlayer ( _
    lPlayerID As Long, _
    fRejectMsg As Boolean)

Parts

lPlayerID
Long value set to the player's ID.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.DestroyGroup

Called when a group is destroyed.

DestroyGroup( _
    lGroupID As Long, _
    lReason As Long, _
    fRejectMsg As Boolean)

Parts

lGroupID
Long value set to the group's ID.
lReason
Long value that indicates the reason that the group was destroyed.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.DestroyPlayer

Called when a player is destroyed.

DestroyPlayer( _
    lPlayerID As Long, _
    lReason As Long, _
    fRejectMsg As Boolean)

Parts

lPlayerID
Long value set to the player's ID.
lReason
Long value that is set to one of the values from the CONST_DPNDESTROYPLAYERREASON enumeration to indicate the reason that the group was destroyed.
fRejectMsg
Parameter is not supported in this release.

Remarks

When the server closes a session, its DirectPlay8Event.DestroyPlayer method is called once for all connected players. Because the server knows that it is disconnecting, this is normal behavior, and the lReason parameter is set to DPNDESTROYPLAYERREASON_NORMAL. The DPNDESTROYPLAYERREASON_SESSIONTERMINATED value is only set for unexpected disconnections.


DirectPlay8Event.EnumHostsQuery

Called when host enumeration is requested through the DirectPlay8Peer.EnumHosts or DirectPlay8Client.EnumHosts method.

EnumHostsQuery( _
    dpnotify As DPNMSG_ENUM_HOSTS_QUERY, _
    fRejectMsg As Boolean)

Parts

dpnotify
DPNMSG_ENUM_HOSTS_QUERY message type containing received data.
fRejectMsg
Boolean value that is set to True to reject the enumeration request. However, if you reject the query, Microsoft® DirectPlay® will not call the client's DirectPlay8Event.EnumHostsResponse, so they will not be aware that you are hosting a session.


DirectPlay8Event.EnumHostsResponse

Contains the host information resulting from a call to the DirectPlay8Peer.EnumHosts or DirectPlay8Client.EnumHosts method.

EnumHostsResponse( _
    dpnotify As DPNMSG_ENUM_HOSTS_RESPONSE, _
    fRejectMsg As Boolean)

Parts

dpnotify
DPNMSG_ENUM_HOSTS_RESPONSE message type containing host information.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.HostMigrate

Called when the host has changed in a session by a call to the DirectPlay8Peer.Host or DirectPlay8Server.Host method.

HostMigrate(NewHostID As Long, _
    fRejectMsg As Boolean)

Parts

NewHostID
Long value set to the ID of the new host.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.IndicateConnect

Called on the host's message handler when a player has requested a connection to the session.

IndicateConnect( _
    dpnotify As DPNMSG_INDICATE_CONNECT, _
    fRejectMsg As Boolean)

Parts

dpnotify
DPNMSG_INDICATE_CONNECT message type.
fRejectMsg
Boolean value that is set to False to enable the player to join the session and True to reject the player's request.

Remarks

After this method returns, the player's DirectPlay8Event.ConnectComplete method will be called with the response to their request to join the session. If the connection request was successful, the hResultCode member of the DPNMSG_CONNECT_COMPLETE type will be set to 0. If the request was rejected or failed, hResultCode will be set to an error code.


DirectPlay8Event.IndicateConnectAborted

Called if a player's connection is lost after it was indicated on the host, but prior to being added to the session.

IndicateConnectAborted( _
    fRejectMsg As Boolean)

Parts

fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.InfoNotify

Called when the information for a client, server, peer, or group has been updated.

InfoNotify(lMsgID As Long, _
    lNotifyID As Long, _
    fRejectMsg As Boolean)

Parts

lMsgID
This will be set to one of the following constants.
DPN_MSGID_CLIENT_INFO
The client information has changed.
DPN_MSGID_GROUP_INFO
The group information has changed.
DPN_MSGID_PEER_INFO
The peer information has changed.
DPN_MSGID_SERVER_INFO
The server information has changed.
lNotifyID
Notification ID.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.Receive

Called in the receiver's message handler when a message is received from a player or host.

Receive( _
    dpnotify As DPNMSG_RECEIVE,
    fRejectMsg As Boolean)

Parts

dpnotify
DPNMSG_RECEIVE message type containing the data sent.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.SendComplete

Called in the sender's message handler when the message is received by the recipient.

SendComplete( _
    dpnotify As DPNMSG_SEND_COMPLETE, _
    fRejectMsg As Boolean)

Parts

dpnotify
DPNMSG_SEND_COMPLETE message type containing the result of the message send and the time it took to send the message.
fRejectMsg
Parameter is not supported in this release.


DirectPlay8Event.TerminateSession

Called in the message handler for each session player after a call to DirectPlay8Peer.TerminateSession.

TerminateSession( _
dpnotify As DPNMSG_TERMINATE_SESSION, _
fRejectMsg As Boolean)

Parts

dpnotify
DPNMSG_TERMINATE_SESSION message type containing the result of the message send.
fRejectMsg
Parameter is not supported in this release.

Remarks

In a peer-peer session that permits host-migration, the host migrates if the current host calls DirectPlay8Peer.Close or stops responding. When this event occurs:

  • Microsoft® DirectPlay® notifies all the other players that the host has left the session by calling their DirectPlay8Event.DestroyPlayer method.
  • DirectPlay then notifies the remaining players of the new host by calling their DirectPlay8Event.HostMigrate method

To prevent host-migration, the current host must terminate the session by calling DirectPlay8Peer.TerminateSession. When the host terminates a session this way:

  • DirectPlay calls each players' DirectPlay8Event.TerminateSession method. The hResultCode of the associated DPNMSG_TERMINATE_SESSION type will be set to DPNERR_HOSTTERMINATEDSESSION.
  • DirectPlay will then generate DirectPlay8Event.DestroyPlayer calls for each player.

In a peer-peer game that does not permit host-migration, the session is terminated if the host calls DirectPlay8Peer.Close, or stops responding. When this event occurs:

  • DirectPlay calls each player's DirectPlay8Event.TerminateSession method. The hResultCode of the associated DPNMSG_TERMINATE_SESSION type will be set to set to DPNERR_HOSTTERMINATEDSESSION.
  • DirectPlay will then generate DirectPlay8Event.DestroyPlayer calls for each player.

In a client/server game, the session is terminated if the host calls DirectPlay8Server.Close or stops responding. When this event occurs:

  • DirectPlay calls each player's DirectPlay8Event.TerminateSession method. The hResultCode of the associated DPNMSG_TERMINATE_SESSION type will be set to DPNERR_CONNECTIONLOST.
  • If the server disconnected itself from the session by calling DirectPlay8Server.Close, its DirectPlay8Event.DestroyPlayer method will be called once for each player in the session, including its own player.
  • Otherwise, the server's DirectPlay8Event.DestroyPlayer method is called for each client's player, but not for the server's player.


DirectPlay8LobbiedApplication

The DirectPlay8LobbiedApplication class is used by an application that supports lobbying. This class enables the application to register with the system so that it can be lobby launched. Additionally, it also enables the application to get the connection information necessary to launch a game without querying the user. Lastly, this class enables the lobbied application to send messages and notifications to the lobby client that launched the application.

The methods of the DirectPlay8LobbiedApplication class are:

DirectPlay8LobbiedApplication Methods | Close
 | GetConnectionSettings
 | RegisterMessageHandler
 | RegisterProgram
 | Send
 | SetAppAvailable
 | SetConnectionSettings
 | UnRegisterMessageHandler
 | UnRegisterProgram
 | UpdateStatus


DirectPlay8LobbiedApplication.Close

Deletes the lobbied application.

Close()

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDOBJECT


DirectPlay8LobbiedApplication.GetConnectionSettings

Retrieves the settings for the specified connection.

GetConnectionSettings(LobbyClient As Long, lFlags As Long)

Parts

LobbyClient
Handle to the connection to retrieve the settings for.
lFlags
Reserved, must be 0.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM
DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDOBJECT
DPNERR_INVALIDFLAGS


DirectPlay8LobbiedApplication.RegisterMessageHandler

Registers a message handler function that receives notifications about changes in the state of the lobbied application and receives messages from the lobby client.

RegisterMessageHandler(lobbyEvent As DirectPlay8LobbyEvent)

Parts

lobbyEvent
DirectPlay8LobbyEvent object that is used to receive notifications.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_ALREADYREGISTERED
DPNERR_INVALIDPARAM

Remarks

If you want to register a new message handler, you must first call DirectPlay8LobbiedApplication.UnRegisterMessageHandler to unregister the current message handler.


DirectPlay8LobbiedApplication.RegisterProgram

Registers a lobby-aware application with Microsoft® DirectPlay® . Applications must be registered to enable lobby launching.

RegisterProgram( _
    ProgramDesc As DPL_PROGRAM_DESC, _
    lFlags As Long)

Parts

ProgramDesc
DPL_PROGRAM_DESC type that describes the lobby-aware application to register.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

The application needs to register only once. It should be unregistered with a call to the DirectPlay8LobbiedApplication.UnRegisterProgram method when it is uninstalled. If a lobby client tries to launch an application that no longer exists on the system, DirectPlay automatically unregisters the application.

In DirectX® 8.1, RegisterProgram must be used. You cannot manually place application information into the registry. Failure to use this class makes your application nonportable and incompatible with later versions of DirectPlay.


DirectPlay8LobbiedApplication.Send

Sends a message from the lobbied application to the lobby client.

Send(Target As Long, _
    buffer() As Byte, _
    lBufferSize As Long, _
    lTimeOut As Long, _
    lFlags As Long)

Parts

Target
Long value specifying the handle of the lobby client to receive the message.
buffer()
Variable of type BYTE that contains the message buffer.
lBufferSize
Long value that specifies the size of the message buffer in the buffer() parameter, in bytes. This value must be at least 1 byte and no more than 64 KB.
lTimeOut
Long value that specifies the number of milliseconds to wait for the Send request to process.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_SENDTOOLARGE

Remarks

If the buffer size is larger than 64 KB, Err.Number is set to DPNERR_SENDTOOLARGE. If the buffer size is set to 0, Err.Number is set to DPNERR_INVALIDPARAM.


DirectPlay8LobbiedApplication.SetAppAvailable

Makes an application available or unavailable for a lobby client to connect to. This method is typically called if a lobbied application is independently launched, that is, not launched by a lobby client. Additionally, this method should be called if a game has ended and the lobbied application needs to be available to connect to a lobby client at the start of another game.

SetAppAvailable(fAvailable As Boolean)

Parts

fAvailable
Boolean value to set to TRUE if the application is available, or FALSE to make it unavailable.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDOBJECT


DirectPlay8LobbiedApplication.SetConnectionSettings

Specifies the settings for the connection.

SetConnectionSettings(hTarget As Long, _
    lFlags As Long, _
    ConnectionSettings As DPL_CONNECTION_SETTINGS, _
    HostAddress As DirectPlay8Address, _
    Device As DirectPlay8Address)

Parts

hTarget
Long value that is set to the connection handle.
lFlags
Reserved, must be 0.
ConnectionSettings
DPL_CONNECTION_SETTINGS type with the connection settings.
HostAddress
DirectPlay8Address object with the host address.
Device
DirectPlay8Address object with the device address.


DirectPlay8LobbiedApplication.UnRegisterMessageHandler

Unregisters the current DirectPlay8LobbiedApplication message handler.

UnRegisterMessageHandler()

Remarks

You must call this method before registering a new message handler.


DirectPlay8LobbiedApplication.UnRegisterProgram

Unregisters a lobby-aware application that was registered through the DirectPlay8LobbiedApplication.RegisterProgram method.

UnRegisterProgram(guidApplication As String, lFlags As Long)

Parts

guidApplication
GUID of the application to unregister.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8LobbiedApplication.UpdateStatus

Updates the status of a connected lobby client.

UpdateStatus(LobbyClient As Long, _
    lStatus As CONST_DPLSESSION)

Parts

LobbyClient
Long value that specifies the connection handle for the lobby client.
lStatus
One of the constants of the CONST_DPLSESSION enumeration that specifies the status between the lobby client and the lobbied application.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM

Remarks

You define the connection handle when you register the application with the lobby by calling DirectPlay8Client.RegisterLobby or DirectPlay8Peer.RegisterLobby.


DirectPlay8LobbyClient

The DirectPlay8LobbyClient class is used by a lobby client application and is responsible for enumerating and launching lobby-enabled game applications on the local computer, and communicating with them after they are running. The lobby client must register a message handler routine to process messages from the lobby and the lobbied game application.

The methods of the DirectPlay8LobbyClient class are:

DirectPlay8LobbyClient Methods | Close
 | ConnectApplication
 | GetCountLocalPrograms
 | GetLocalProgram
 | RegisterMessageHandler
 | ReleaseApplication
 | Send
 | SetConnectionSettings
 | UnRegisterMessageHandler


DirectPlay8LobbyClient.Close

Deletes the lobby client.

Close()

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDOBJECT


DirectPlay8LobbyClient.ConnectApplication

Connects a lobby-enabled application to the session specified in the DPL_CONNECT_INFO type. If the application is not running, this method can be used to launch the application.

When the connection is successfully established, Microsoft® DirectPlay® calls the message handler's DirectPlay8LobbyEvent.Connect method.

ConnectApplication( _
    ConnectionInfo As DPL_CONNECT_INFO,
    lTimeOut As Long, _
    lFlags As CONST_DPLCONNECT) As Long

Parts

ConnectionInfo
DPL_CONNECT_INFO type that describes the connection parameters, including the GUID of the application to connect to.
lTimeOut
Long value that specifies the number of milliseconds to wait for the connection to process.
lFlags
One of the constants of the CONST_DPLCONNECT enumeration that determines connection behavior.

Return Values

Returns a Long value that is set to the application connection handle . This handle is used for further communication with the application. Additionally, this handle is used in the Application parameter in the DirectPlay8LobbyClient.ReleaseApplication method.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_CANTLAUNCHAPPLICATION
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_TIMEDOUT


DirectPlay8LobbyClient.GetCountLocalPrograms

Retrieves the number of lobbied applications that are registered on the system.

GetCountLocalPrograms(guidApplication As String) As Long

Parts

guidApplication
String value specifying the GUID of the lobbied application to enumerate.

Return Values

Returns the number of lobbied applications that are registered.


DirectPlay8LobbyClient.GetLocalProgram

Enumerates the specified lobbied application that is registered on the system. Before calling this method, call DirectPlay8LobbyClient.GetCountLocalPrograms to see how many lobbied applications are registered.

GetLocalProgram(lProgID As Long) As DPL_APPLICATION_INFO

Parts

lProgID
Long value specifying the ID of the lobbied application to enumerate.

Return Values

Returns a DPL_APPLICATION_INFO type that describes the lobbied application.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

This method is generally called twice—once to obtain the size of the required buffer, and then with the correct buffer size.


DirectPlay8LobbyClient.RegisterMessageHandler

Registers a message handler function that receives notifications about changes in the state of the lobby client and receives messages from the lobbied application.

RegisterMessageHandler(lobbyEvent As DirectPlay8LobbyEvent)

Parts

lobbyEvent
DirectPlay8LobbyEvent object that is used to receive notifications.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_ALREADYREGISTERED
DPNERR_INVALIDPARAM

Remarks

If you want to register a new message handler, you must first call DirectPlay8LobbyClient.UnRegisterMessageHandler to unregister the current message handler.


DirectPlay8LobbyClient.ReleaseApplication

Releases a lobbied application and closes the connection between the lobby client and the application. This method should be called whenever a lobby client has finished its session with an application.

ReleaseApplication(Application As Long)

Parts

Application
Long value specifying the GUID of the lobbied application to release. This value is returned by the DirectPlay8LobbyClient.ConnectApplication method.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDHANDLE
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM


DirectPlay8LobbyClient.Send

Sends a message to a lobbied application that was launched by this lobby client or was connected by this lobby client.

Microsoft® DirectPlay® transmits the data to the target by calling the target message handler's DirectPlay8LobbyEvent.Receive method.

Send(Target As Long, _
    buffer() As Byte, _
    lBufferSize As Long, _
    lFlags As Long)

Parts

Target
Long value that specifies the target for the message transmission.
buffer()
Buffer that contains the message.
lBufferSize
Size of the message buffer in the buffer() parameter, in bytes. This value must be at least 1 byte and no more than 64 KB.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDHANDLE
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_SENDTOOLARGE

Remarks

If the buffer size is larger than 64 KB, Err.Number is set to DPNERR_SENDTOOLARGE. If the buffer size is set to 0, Err.Number is set to DPNERR_INVALIDPARAM.


DirectPlay8LobbyClient.SetConnectionSettings

Sets the connection settings to be associated with the specified connection.

SetConnectionSettings(hTarget As Long, _
    lFlags As Long, _
    ConnectionSettings As DPL_CONNECTION_SETTINGS), _
    HostAddress As DirectPlay8Address, _
    Device As DirectPlay8Address)

Parts

hTarget
Long value that is set to the connection handle.
lFlags
Reserved. Set to 0.
ConnectionSettings
DPL_CONNECTION_SETTINGS type that contains the connections.
HostAddress
DirectPlay8Address object containing the host address.
Device
DirectPlay8Address object containing the device address.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDOBJECT
DPNERR_INVALIDFLAGS


DirectPlay8LobbyClient.UnRegisterMessageHandler

Unregisters the current DirectPlay8LobbyClient message handler.

UnRegisterMessageHandler()

Remarks

You must call this method before registering a new message handler.


DirectPlay8LobbyEvent

The DirectPlay8LobbyEvent class is used to capture Microsoft® DirectPlay® events generated when using the DirectPlay8LobbiedApplication and DirectPlay8LobbyClient classes.

Note When implementing the DirectPlay8LobbyEvent object, Microsoft® Visual Basic® requires that every method of this object is implemented in your form.

The methods of the DirectPlay8LobbyEvent class are:

DirectPlay8LobbyEvent Methods | Connect
 | ConnectionSettings
 | Disconnect
 | Receive
 | SessionStatus


DirectPlay8LobbyEvent.Connect

Called when the DirectPlay8LobbyClient.ConnectApplication method has been called by the lobby client.

Connect( _
    dlNotify As DPL_MESSAGE_CONNECT, _
    fRejectMsg As Boolean)

Parts

dlNotify
DPL_MESSAGE_CONNECT message type with the connection information.
fRejectMsg
Boolean value indicating whether to connect the application.


DirectPlay8LobbyEvent.ConnectionSettings

Called when the DirectPlay8LobbyClient.SetConnectionSettings or DirectPlay8LobbiedApplication.SetConnectionSettings method is called.

ConnectionSettings( _ConnectionSettings As DPL_MESSAGE_CONNECTION_SETTINGS)

Parts

ConnectionSettings
DPL_MESSAGE_CONNECTION_SETTINGS message type with the connection settings.


DirectPlay8LobbyEvent.Disconnect

Called when the DirectPlay8LobbyClient.ReleaseApplication method has been called by the lobby client.

Disconnect(DisconnectID As Long, _
    lReason As Long)

Parts

DisconnectID
Long value specifying the identifier of the lobby application that requested to disconnect.
lReason
Long value that is set to the reason for the disconnection.


DirectPlay8LobbyEvent.Receive

Called when the DirectPlay8LobbyClient.Send or DirectPlay8LobbiedApplication.Send method has been called.

Receive(dlNotify As DPL_MESSAGE_RECEIVE, _
     fRejectMsg As Boolean)

Parts

dlNotify
DPL_MESSAGE_RECEIVE message type containing the message sent.
fRejectMsg
Boolean value indicating whether to accept or reject the message.


DirectPlay8LobbyEvent.SessionStatus

Called when the DirectPlay8LobbiedApplication.UpdateStatus method has been called by the lobbied application.

LobbySessionStatus(status As Long, _
     lHandle As Long)

Parts

status
Long value specifying the updated status of the lobby session. It will be set to one of the constants of the CONST_DPLSESSION enumeration that specifies the status between the lobby client and the lobbied application.
lHandle
Long value set to the handle of the application that sent the status update message.


DirectPlay8Peer

Applications use the methods of the DirectPlay8Peer class to create a peer-to-peer Microsoft® DirectPlay® session.

The methods of the DirectPlay8Peer class can be organized into the following groups.

Session Management | Close
 | Connect
 | EnumHosts
 | GetApplicationDesc
 | GetCaps
 | GetConnectionInfo
 | GetCountServiceProviders
 | GetEnumHostResponseAddress
 | GetServiceProvider
 | GetSPCaps
 | Host
 | SetApplicationDesc
 | SetCaps
 | SetSPCaps
 | TerminateSession
Message Management | GetSendQueueInfo
 | RegisterMessageHandler
 | SendTo
 | UnregisterMessageHandler
Player Management | DestroyPeer
 | GetPlayerOrGroup
 | GetCountClientsAndGroups
 | GetPeerAddress
 | GetPeerInfo
 | RemovePlayerFromGroup
 | SetPeerInfo
Group Management | AddPlayerToGroup
 | CreateGroup
 | DestroyGroup
 | GetCountGroupMembers
 | GetGroupInfo
 | GetGroupMember
 | SetGroupInfo
Miscellaneous | CancelAsyncOperation
 | RegisterLobby


DirectPlay8Peer.AddPlayerToGroup

Adds a peer to a group.

When this method is called, DirectPlay calls each player's DirectPlay8Event.AddRemovePlayerGroup method to notify him or her of the new group member.

AddPlayerToGroup(idGroup As Long, _
    idClient As Long,
    lFlags As Long) As Long

Parts

idGroup
Long value that specifies the identifier of the group to add the peer to.
idClient
Long value that specifies the identifier of the peer that is added to the group.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Peer.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS

Remarks

Any peer can add itself or another peer to an existing group. After the peer is successfully added to the group, all messages sent to the group are also sent to the peer.

For a peer to add itself to the group, pass DPNID_ME in the idClient parameter.


DirectPlay8Peer.CancelAsyncOperation

Cancels asynchronous requests. Many methods of the DirectPlay8Peer class run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this class that can be run asynchronously return an lAsyncHandle parameter.

Specific requests are canceled by passing the lAsyncHandle of the request in this method's lAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, passing 0 in the lAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the lFlags parameter. If a specific handle is provided to this method, you must pass 0 in the lFlags parameter.

CancelAsyncOperation(lAsyncHandle As Long, _
    lFlags As CONST_DPNCANCELFLAGS)

Parts

lAsyncHandle
Handle of the asynchronous operation to stop. This value can be 0 to stop all requests or a particular type of asynchronous request. If a specific handle for the request to cancel is specified, the lFlags parameter must be 0.
lFlags
Flag that specifies which asynchronous request to canceled. You can set this parameter to one of the flags of the CONST_DPNCANCELFLAGS enumeration.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_PENDING
DPNERR_INVALIDFLAGS
DPNERR_CANNOTCANCEL
DPNERR_INVALIDHANDLE

Remarks

You can cancel a send by providing the handle returned from DirectPlay8Peer.SendTo method. The DirectPlay8Event.SendComplete method will still be called unless the message was sent with the DPNSEND_NOCOMPLETE flag set. If you cancel a send operation by calling DirectPlay8Peer.CancelAsyncOperation the hResultCode member of the DPNMSG_SEND_COMPLETE type that is passed to the DirectPlay8Event.SendComplete method will be set to DPNERR_CANCELLED.


DirectPlay8Peer.Close

Closes the open connection to a session.

Close();

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_UNINITIALIZED

Remarks

Calling Close will cancel all outstanding operations, including data sent as guaranteed. To make sure all messages are sent, wait for all outstanding SendTo calls to complete before calling Close.


DirectPlay8Peer.Connect

Establishes the connection to the server. After a connection is established, the communication channel on the object is open and active and the application should expect messages to arrive immediately. No messages can be sent by means of the DirectPlay8Peer.SendTo method until the connection has completed.

Before this method is called, it must obtain an application description by calling DirectPlay8Peer.EnumHosts. The EnumHosts method returns a DPN_APPLICATION_DESC type for each hosted application. The type describes the application, including the GUID of the application.

Although the application GUID is not required, Microsoft® DirectPlay® performs verification if one is specified.

When the connection to the host is requested, the DirectPlay8Event.IndicateConnect method is called in the host's message handler. The host may either accept or reject the connection. In either case, after the host has acted, the client message handler's DirectPlay8Event.ConnectComplete method will be called to convey the response.

Connect(AppDesc As DPN_APPLICATION_DESC, _
    Address As DirectPlay8Address, _
    DeviceInfo As DirectPlay8Address, _
    lFlags As Long, _
    UserData As Any, _
    UserDataSize As Long) As Long

Parts

AppDesc
DPN_APPLICATION_DESC type that describes the application. Only some of the members of this type are used by this method. The only member of this type that you must set is the guidApplication member. You can also set guidInstance, Password, and lFlags.
Address
Optional DirectPlay8Address object that specifies the addressing information to use to connect to the computer that is hosting.
DeviceInfo
DirectPlay8Address object that specifies what service provider to enumerate and what settings to use.
lFlags
Flag that describes the connection mode. You can set the following flag.
DPNOP_SYNC
Process the connection request synchronously. If this flag is set, DirectPlay will not call the DirectPlay8Event.ConnectComplete method.
UserData
Application-specific user data.
UserDataSize
Size of the data contained in the UserData parameter.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Peer.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOCONNECTION
DPNERR_INVALIDPASSWORD
DPNERR_INVALIDFLAGS
DPNERR_INVALIDINTERFACE
DPNERR_INVALIDAPPLICATION
DPNERR_NOTHOST
DPNERR_SESSIONFULL
DPNERR_HOSTREJECTEDCONNECTION
DPNERR_INVALIDINSTANCE

Remarks

Although multiple enumerations can be run concurrently, and can be run across the duration of a connection, only one connection is allowed per object. To establish a connection to more than one application, you must create another object. That is, only one running application per object is allowed. If DirectPlay8Peer.Connect is called while another connection is in progress, the function raises an error.

After a call to DirectPlay8Peer.Connect succeeds, all outstanding enumerations are canceled with the DPNERR_USERCANCEL error value set.


DirectPlay8Peer.CreateGroup

Creates a group in the current session. A group is a logical collection of players.

When this method is called, DirectPlay calls each player's DirectPlay8Event.CreateGroup method to notify him or her of the new group.

CreateGroup(GroupInfo As DPN_GROUP_INFO, _
    lFlags As Long) As Long

Parts

GroupInfo
DPN_GROUP_INFO type that contains the group description.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Peer.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDFLAGS

Remarks

Microsoft® DirectPlay® does not maintain hierarchical groups because they can easily be implemented with flat groups and expeditious use of the group data.


DirectPlay8Peer.DestroyPeer

Deletes a peer from the session.

DestroyPeer(idClient As Long, _
    lFlags As Long, _
    UserData As Any, _
    UserDataSize As Long)

Parts

idClient
Long value that specifies the identifier of the peer to delete.
lFlags
Reserved. Must be 0.
UserData
Pointer that describes additional delete data information that is sent to the peer.
UserDataSize
Long value that specifies the size of the data contained in the UserData parameter.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOTHOST
DPNERR_INVALIDPLAYER
DPNERR_INVALIDPARAM

Remarks

This method calls the DirectPlay8Event.DestroyPlayer method in the destroyed player's message handler.


DirectPlay8Peer.DestroyGroup

Deletes a group created by the DirectPlay8Peer.CreateGroup method. This method can be called by any peer in the group.

This method will call the DirectPlay8Event.AddRemovePlayerGroup method for each peer in the group.

DestroyGroup(idGroup As Long, lFlags As Long) As Long

Parts

idGroup
Long value that specifies of the identifier of the group to delete.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Peer.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP


DirectPlay8Peer.EnumHosts

Enumerates applications that host Microsoft® DirectPlay® games. When an application is found meeting the enumeration criteria, the DirectPlay8Event.EnumHostsResponse method is called in the application's message handler. This method contains a DPNMSG_ENUM_HOSTS_RESPONSE message type that contains a DPN_APPLICATION_DESC type that describes the applications found.

EnumHosts(ApplicationDesc As DPN_APPLICATION_DESC, _
    AddrHost As DirectPlay8Address, _
    DeviceInfo As DirectPlay8Address, _
    lRetryCount As Long, _
    lRetryInterval As Long, _
    lTimeOut As Long, _
    lFlags As Long, _
    lFlags As CONST_DPNOPERATIONS, _
    UserData As Any, _
    UserDataSize As Long) As Long

Parts

ApplicationDesc
DPN_APPLICATION_DESC type that specifies which application hosts to enumerate. You can specify the following fields to reduce the number of responses to the enumeration.
guidApplication
GUID of the application to find; if not specified, all are searched for.
Password
Password to provide; secure sessions will not respond without a password.
AddrHost
DirectPlay8Address object that specifies the address of the computer that is hosting the application.
DeviceInfo
DirectPlay8Address object that specifies the service provider and settings to enumerate.
lRetryCount
Value that specifies how many times the enumeration data will be sent. You can set this parameter to zero to specify the default value. If you set this value to INFINITE, the enumeration will continue until canceled.
lRetryInterval
Value that specifies the time, in milliseconds, between successive enumeration attempts. Set this parameter to 0 to use the default value.
lTimeOut
Number of milliseconds for the enumeration to run. If 0 is specified, a default value is used. If INFINITE is specified, the enumeration continues until it is canceled.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.
UserData
Block of data that is sent in the enumeration request to the host. The size of the data can be limited depending on the network type, but 512 bytes is supported at a minimum.
UserDataSize
Size of the data in the UserData parameter.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Peer.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_TIMEDOUT
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

Because of the variety of ways enumeration can happen, it is not recommended that an application specify lRetryInterval, lRetryCount, or lTimeOut unless the application has some specific media knowledge. The only exception is if you want to have the enumeration continue until explicitly cancelled, then set lRetryCount to INFINITE.


DirectPlay8Peer.GetApplicationDesc

Retrieves the full application description for the connected application.

GetApplicationDesc(lFlags As Long) _
    As DPN_APPLICATION_DESC

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns a DPN_APPLICATION_DESC type describing the application.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOCONNECTION
DPNERR_INVALIDFLAGS
DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM


DirectPlay8Peer.GetCaps

Retrieves the DPN_CAPS type for the current object.

GetCaps() As DPN_CAPS

Return Values

Returns a DPN_SP_CAPS type to receive the information about the specified service provider.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Peer.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Peer.GetPlayerOrGroup

Retrieves the client or group identifier for the specified client or group. The number of clients or groups for the application can be determined by calling DirectPlay8Peer.GetCountPlayersAndGroups.

GetPlayerOrGroup(lIndex As Long) As Long

Parts

lIndex
Index of the client or group.

Return Values

Returns the identification of the client or group.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM


DirectPlay8Peer.GetConnectionInfo

Retrieves statistical information about the connection between the local endpoint and the host.

GetConnectionInfo(idPlayer As Long, [lFlags As Long]) As DPN_CONNECTION_INFO

Parts

idPlayer
Long value specifying the identifier of the player.
lFlags
Reserved. Must be 0.

Return Values

Returns a DPN_CONNECTION_INFO type to retrieve information about the specified connection.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

This method can be called only after a successful Connect call has completed.


DirectPlay8Peer.GetCountPlayersAndGroups

Retrieves the number of peers or groups for the session.

GetCountPlayersAndGroups( _
    lFlags As CONST_DPNENUMCLIENTGROUPFLAGS) As Long

Parts

lFlags
Flag that describes enumeration behavior. You can set one of the following flags of the CONST_DPNENUMCLIENTGROUPFLAGS enumeration.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDFLAGS


DirectPlay8Peer.GetCountGroupMembers

Retrieves the number of players in a group.

GetCountGroupMembers(dpid As Long) As Long

Parts

dpid
Long value that specifies the identification of the group.

Return Values

Returns the number of players in the group.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS

Remarks

Because player information changes frequently, the required buffer size returned may change between subsequent calls. Check and reallocate the buffer until the method succeeds.


DirectPlay8Peer.GetCountServiceProviders

Retrieves the number of registered service providers available to the application.

GetCountServiceProviders() As Long

Return Values

Returns the number of registered service providers available to the application.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDOBJECT


DirectPlay8Peer.GetEnumHostResponseAddress

Retrieves the address of the host.

GetEnumHostResponseAddress( _
    AppDesc As DPN_APPLICATION_DESC) _
    As DirectPlay8Address

Parts

AppDesc
DPN_APPLICATION_DESC type describing the application.

Return Values

Returns a DirectPlay8Address object specifying the address of the host.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Peer.GetGroupInfo

Retrieves a block of data associated with a group, including the group name.

This method is typically called after DirectPlay calls the DirectPlay8Event.InfoNotify method, indicating that the group data has been modified.

GetGroupInfo(idGroup As Long) As DPN_GROUP_INFO

Parts

idGroup
Long value that specifies the identifier of the group whose data block will be retrieved.

Return Values

Returns a DPN_GROUP_INFO type that describes the group data.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS


DirectPlay8Peer.GetGroupMember

Retrieves the identifier of the specified member of a group. The number of players in a group is determined by calling DirectPlay8Peer.GetCountGroupMembers.

GetGroupMember(lIndex As Long, dpid As Long) As Long

Parts

lIndex
Index value of the player in a group.
dpid
Long value that specifies the identification of the group.

Return Values

Returns a Long value that specifies the identification of the player.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDPARAM


DirectPlay8Peer.GetPeerAddress

Retrieves the address for the specified remote player in the session.

GetPeerAddress(idPlayer As Long) As DirectPlay8Address

Parts

idPlayer
Long value specifying the identification of the player.

Return Values

Returns a DirectPlay8Address object that specifies the address of the player.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_UNINITIALIZED

Remarks

This method cannot be used to retrieve the address of the local player. If the player calls this method on his or her own ID, it returns a DPNERR_INVALIDPLAYER error message.


DirectPlay8Peer.GetLocalHostAddress

Retrieves the local addresses used to host the session.

GetLocalHostAddress(lFlags As Long) As DirectPlay8Address

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns the DirectPlay8Address object that specifies the local host addresses.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED
DPNERR_NOTHOST

Remarks

If the caller is not the session host, the error code is DPNERR_NOTHOST. Use DirectPlay8Peer.GetPeerAddress to retrieve the address of a remote player.


DirectPlay8Peer.GetPeerInfo

Retrieves player information set for the specified peer.

GetPeerInfo(idPeer As Long) As DPN_PLAYER_INFO

Parts

idPeer
Long value that specifies the identifier of the peer whose information will be retrieved.

Return Values

Returns a DPN_PLAYER_INFO type describing player information.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDPLAYER
DPNERR_INVALIDPARAM

Remarks

Call this method after DirectPlay calls the DirectPlay8Event.InfoNotify method, indicating that the group data has been modified.


DirectPlay8Peer.GetSendQueueInfo

Used by the application to monitor the size of the send queue. Microsoft® DirectPlay® does not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should decrease the rate that messages are sent.

GetSendQueueInfo(lNumMsgs As Long, lNumBytes As Long)

Parts

lNumMsgs
Number of messages currently queued.
lNumBytes
Amount of data, in bytes, of the messages currently queued.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Peer.GetServiceProvider

Retrieves information for the specified service provider. Before calling this method, call the DirectPlay8Peer.GetCountServiceProviders method to obtain the number of registered service providers available to the application.

GetServiceProvider(lIndex As Long) As DPN_SERVICE_PROVIDER_INFO

Parts

lIndex
Index value specifying the specific server provider.

Return Values

Returns a DPN_SERVICE_PROVIDER_INFO type that describes the service provider.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Peer.GetSPCaps

Retrieves the DPN_SP_CAPS type for the specified service provider.

GetSPCaps(guidSP As String) As DPN_SP_CAPS

Parts

guidSP
String specifying the GUID of the service provider you want to get information about.

Return Values

Returns a DPN_SP_CAPS type to receive the information about the specified service provider.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Peer.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Peer.Host

Specifies the host for the peer-to-peer session.

Host(AppDesc As DPN_APPLICATION_DESC, _
    Address As DirectPlay8Address)

Parts

AppDesc
DPN_APPLICATION_DESC type that describes the application.
Address
DirectPlay8Address object that specifies an addresses of a service-provider device or a service provider to host the application on.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Peer.RegisterLobby

Registers or unregisters an application with a lobby.

RegisterLobby(dpnHandle As Long, _
    LobbyApp As DirectPlay8LobbiedApplication, _
    lFlags As Long)

Parts

dpnHandle
Connection handle to be used when making the calls to DirectPlay8LobbiedApplication.UpdateStatus.
LobbyApp
DirectPlay8LobbiedApplication object that specifies the application.
lFlags
Set this parameter to one of the two CONST_DPNLOBBY enumeration values to indicate whether the application is to be registered or unregistered.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM

Remarks

When an application is registered with a lobby, the lobby client automatically receives notifications of changes in game status.


DirectPlay8Peer.RegisterMessageHandler

Registers an entry point in the client's code that receives the messages from the DirectPlay8Peer class. Call this method before calling any other methods of this class.

RegisterMessageHandler(event As DirectPlay8Event)

Parts

event
DirectPlay8Event object that will receive the messages generated by the client and server.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_ALREADYREGISTERED

Remarks

If you want to register a new message handler, you must first call DirectPlay8Peer.UnRegisterMessageHandler to unregister the current message handler.


DirectPlay8Peer.RemovePlayerFromGroup

Removes a peer from a group.

When this method is called, DirectPlay calls each player's DirectPlay8Event.AddRemovePlayerGroup method to notify him or her that a member has been removed from the group.

RemovePlayerFromGroup(idGroup As Long, _
    idClient As Long, _
    lFlags As Long) As Long

Parts

idGroup
Long value that specifies the identifier of the group that the peer will be removed from.
idClient
Long value that specifies the identifier of the peer that will be removed from the group.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Peer.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPLAYER


DirectPlay8Peer.SendTo

Transmits data to the specified player. The message can be sent synchronously or asynchronously.

SendTo(idSend As Long, _
    buffer() As BYTE, _
    lPriority As Long, _
    lTimeOut As Long, _
    lFlags As CONST_DPNSENDFLAGS) As Long

Parts

idSend
Long value specifying the identifier of the player to receive data. Set this parameter to DPNID_ALL_PLAYERS_GROUP value from the CONST_DPNPLAYERGROUPFLAGS enumeration to send a message to all players in the session.
buffer()
Array of type BYTE that describes the data to send.
lPriority
Priority of the message.
lTimeOut
Number of milliseconds to wait for the message to be sent. If the message has not been sent by the lTimeOut value, the message is not sent. If you do not want a time-out for message sends, set this parameter to 0.
lFlags
Flags that describe send behavior. You can set one or more of the following flags defined in the CONST_DPNSENDFLAGS enumeration.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Peer.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDFLAGS
DPNERR_TIMEDOUT

Remarks

This method will call the DirectPlay8Event.Receive method in the recipient's message handler. When the SendTo request is completed, the DirectPlay8Event.SendComplete method is called in the sender's message handler. The SendComplete method contains a DPNMSG_SEND_COMPLETE message type. The success or failure of the request is contained in the hResultCode member of this message type.


DirectPlay8Peer.SetApplicationDesc

Changes the settings for the application that is being hosted. Only some settings can be changed.

SetApplicationDesc(AppDesc As DPN_APPLICATION_DESC, _
    lFlags As Long)

Parts

AppDesc
DPN_APPLICATION_DESC type that describes the application settings to modify.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDFLAGS

Remarks

You can use this method to modify only the following members of the DPN_APPLICATION_DESC type.

  • lMaxPlayers
  • SessionName
  • Password

You cannot set the lMaxPlayers member to a smaller value than the current number of players in the session.


DirectPlay8Peer.SetCaps

Sets the capabilities for the session.

SetCaps(caps As DPN_CAPS, lFlags As Long)

Parts

caps
DPN_CAPS type used to set the information about the current session.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Peer.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Peer.SetGroupInfo

Sets a block of data associated with a group, including the name of the group.

DirectPlay calls each player's DirectPlay8Event.InfoNotify method to notify him or her that the group information has changed.

SetGroupInfo(idGroup As Long, _
    PlayerInfo As DPN_GROUP_INFO, _
    lFlags As Long) As Long

Parts

idGroup
Long value that specifies the identifier of the group whose data block will be modified.
PlayerInfo
DPN_GROUP_INFO type that describes the group data to set.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method:
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Peer.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS


DirectPlay8Peer.SetPeerInfo

Sets the static settings of a peer with an application. Call this method before connecting to relay basic player information with the application. After the peer successfully connects with the application, information obtained through this method can be retrieved by other players by calling the DirectPlay8Peer.GetPeerInfo method.

SetPeerInfo(PlayerInfo As DPN_PLAYER_INFO) As Long

Parts

PlayerInfo
DPN_PLAYER_INFO type that contains the player information to set.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in the lAsyncHandle parameter of the DirectPlay8Peer.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOCONNECTION
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

Transmission of nonstatic information should be handled with the DirectPlay8Peer.SendTo method because of the high cost of using the DirectPlay8Peer.SetPeerInfo method.

You can modify the peer information with this method after connecting to the application. If this method is called after a connection, DirectPlay will call each player's DirectPlay8Event.InfoNotify method to notify him or her that the data has been updated.


DirectPlay8Peer.SetSPCaps

Sets the capabilities for the specified service provider.

SetSPCaps(guidSP As String, spCaps As DPN_SP_CAPS)

Parts

guidSP
String specifying the GUID of the service provider you want to set information about.
spCaps
DPN_SP_CAPS type to set the information about the specified service provider.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Peer.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Peer.TerminateSession

Terminates the current Microsoft® DirectPlay® session.

TerminateSession(lFlags As Long, _
    UserData As Any, _
    UserDataSize As Long)

Parts

lFlags
Reserved. Must be 0.
UserData
Pointer to termination data.
UserDataSize
Size of data contained in the UserData parameter.

Remarks

This method may be called only by the host player.

When this method is called, the DirectPlay8Event.TerminateSession method is called in the message handler of all players connected to the session.


DirectPlay8Peer.UnRegisterMessageHandler

Unregisters the current message handler.

UnRegisterMessageHandler()

Remarks

You must call this method before registering a new message handler.


DirectPlay8Server

Applications use the methods of the DirectPlay8Server class to create and manage the server for a Microsoft® DirectPlay® client/server transport session

The methods of the DirectPlay8Server class can be organized into the following groups.

Session Management | Close
 | GetApplicationDesc
 | GetCaps
 | GetConnectionInfo
 | GetCountServiceProviders
 | GetServiceProvider
 | GetSPCaps
 | Host
 | SetApplicationDesc
 | SetCaps
 | SetSPCaps
Message Management | GetSendQueueInfo
 | RegisterMessageHandler
 | SendTo
 | UnregisterMessageHandler
Player Management | DestroyClient
 | GetClientAddress
 | GetClientInfo
 | GetPlayerOrGroup
 | GetCountPlayersAndGroups
 | RemovePlayerFromGroup
 | SetServerInfo
Group Management | AddPlayerToGroup
 | CreateGroup
 | DestroyGroup
 | GetCountGroupMembers
 | GetGroupInfo
 | GetGroupMember
 | SetGroupInfo
Miscellaneous | CancelAsyncOperation
 | RegisterLobby


DirectPlay8Server.AddPlayerToGroup

Adds a client to a group.

AddPlayerToGroup(idGroup As Long, _
    idClient As Long,
    lFlags As Long) As Long

Parts

idGroup
Long value that specifies the identifier of the group to add the client to.
idClient
Long value that specifies the identifier of the client that is added to the group.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Server.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS

Remarks

Any client can add itself or another client to an existing group. After the client is successfully added to the group, all messages sent to the group are also sent to the client.

For a client to add itself to the group, pass DPNID_ME in the idClient parameter.


DirectPlay8Server.CancelAsyncOperation

Cancels asynchronous requests. Many methods of the DirectPlay8Server class run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this class that can be run asynchronously return a lAsyncHandle parameter.

Specific requests are canceled by passing the lAsyncHandle of the request in this method's lAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, passing 0 in the lAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the lFlags parameter. If a specific handle is provided to this method, you must pass 0 in the lFlags parameter.

CancelAsyncOperation(lAsyncHandle As Long, _
    lFlags As CONST_DPNCANCELFLAGS)

Parts

lAsyncHandle
Handle of the asynchronous operation to stop. This value can be 0 to stop all requests or a particular type of asynchronous request. If a specific handle for the request to cancel is specified, the lFlags parameter must be 0.
lFlags
Flag that specifies which asynchronous request to canceled. You can set this parameter to one of the flags of the CONST_DPNCANCELFLAGS enumeration.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_PENDING
DPNERR_INVALIDFLAGS
DPNERR_CANNOTCANCEL
DPNERR_INVALIDHANDLE

Remarks

You can cancel a send by providing the handle returned from DirectPlay8Server.SendTo method. The DirectPlay8Event.SendComplete method will still be called unless the message was sent with the DPNSEND_NOCOMPLETE flag set. If you cancel a send operation by calling DirectPlay8Peer.CancelAsyncOperation the hResultCode member of the DPNMSG_SEND_COMPLETE type that is passed to the DirectPlay8Event.SendComplete method will be set to DPNERR_CANCELLED.


DirectPlay8Server.Close

Closes the open connection to a session.

Close();

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_UNINITIALIZED

Remarks

Calling Close will cancel all outstanding operations, including data sent as guaranteed. To make sure all messages are sent, wait for all outstanding SendTo calls to complete before calling Close.


DirectPlay8Server.CreateGroup

Creates a group in the current session. A group is a logical collection of players.

CreateGroup(GroupInfo As DPN_GROUP_INFO, _
    lFlags As Long) As Long

Parts

GroupInfo
DPN_GROUP_INFO type that contains the group description.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Server.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDFLAGS

Remarks

Microsoft® DirectPlay® does not maintain hierarchical groups because they can easily be implemented with flat groups and expeditious use of the group data.


DirectPlay8Server.DestroyClient

Deletes a client from the session.

DestroyClient(idClient As Long, _
    lFlags As Long, _
    UserData As Any, _
    UserDataSize As Long)

Parts

idClient
Long value that specifies the identifier of the client to delete.
lFlags
Reserved. Must be 0.
UserData
Application-specific user data.
UserDataSize
Long value that specifies the size of the data contained in the UserData parameter.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOTHOST
DPNERR_INVALIDPLAYER
DPNERR_INVALIDPARAM

Remarks

This method calls the DirectPlay8Event.DestroyPlayer method in the destroyed player's message handler.


DirectPlay8Server.DestroyGroup

Deletes a group created by the DirectPlay8Server.CreateGroup method.

DestroyGroup(idGroup As Long, lFlags As Long) As Long

Parts

idGroup
Long value that specifies the identifier of the group to delete.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in the lAsyncHandle parameter of the DirectPlay8Server.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP


DirectPlay8Server.GetApplicationDesc

Retrieves the full application description for the connected application.

GetApplicationDesc(lFlags As Long) _
    As DPN_APPLICATION_DESC

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns a DPN_APPLICATION_DESC type describing the application.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOCONNECTION
DPNERR_INVALIDFLAGS
DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM


DirectPlay8Server.GetCaps

Retrieves the DPN_CAPS type for the current object.

GetCaps() As DPN_CAPS

Return Values

Returns a DPN_CAPS type filled with caps information.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Server.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Server.GetClientAddress

Retrieves the address for the specified player in the session.

GetClientAddress(idPlayer As Long) As DirectPlay8Address

Parts

idPlayer
Long value specifying the identification of the player.

Return Values

Returns a DirectPlay8Address object that specifies the address of the player.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_UNINITIALIZED


DirectPlay8Server.GetClientInfo

Retrieves player information set for the specified client.

GetClientInfo(idClient As Long) As DPN_PLAYER_INFO

Parts

idClient
Long value that specifies the identifier of the client whose information will be retrieved.

Return Values

Returns a DPN_PLAYER_INFO type describing player information.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDPLAYER
DPNERR_INVALIDPARAM

Remarks

Call this method after DirectPlay calls the DirectPlay8Event.InfoNotify method, indicating that the player data has been modified.


DirectPlay8Server.GetConnectionInfo

Retrieves statistical information about the connection between the specified player and the server.

GetConnectionInfo(idPlayer As Long, [lFlags As Long]) As DPN_CONNECTION_INFO

Parts

idPlayer
Long value specifying the identifier of the player.
lFlags
Reserved. Must be 0.

Return Values

Returns a DPN_CONNECTION_INFO type to retrieve information about the specified connection.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

This method can be called only after a successful Connect call has completed.


DirectPlay8Server.GetCountGroupMembers

Retrieves the number of players in a group.

GetCountGroupMembers(dpid As Long) As Long

Parts

dpid
Long value that specifies the identification of the group.

Return Values

Returns the number of players in the group.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS

Remarks

Because player information changes frequently, the required buffer size returned may change between subsequent calls. Check and reallocate the buffer until the method succeeds.


DirectPlay8Server.GetCountPlayersAndGroups

Retrieves the number of clients or groups for the session.

GetCountPlayersAndGroups( _
    lFlags As CONST_DPNENUMCLIENTGROUPFLAGS) As Long

Parts

lFlags
Flag that describes enumeration behavior. You can set one of the flags from the CONST_DPNENUMCLIENTGROUPFLAGS enumeration.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDFLAGS


DirectPlay8Server.GetCountServiceProviders

Retrieves the number of registered service providers available to the application.

GetCountServiceProviders() As Long

Return Values

Returns the number of registered service providers available to the application.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDOBJECT


DirectPlay8Server.GetGroupInfo

Retrieves a block of data associated with a group, including the group name.

Call this method after DirectPlay calls the DirectPlay8Event.InfoNotify method, indicating that the group data has been modified.

GetGroupInfo(idGroup As Long) As DPN_GROUP_INFO

Parts

idGroup
Long value that specifies the identifier of the group whose data block will be retrieved.

Return Values

Returns a DPN_GROUP_INFO type that describes the group data.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS


DirectPlay8Server.GetGroupMember

Retrieves the identifier of the specified member of a group. The number of players in a group is determined by calling DirectPlay8Server.GetCountGroupMembers.

GetGroupMember(lIndex As Long, dpid As Long) As Long

Parts

lIndex
Index value of the player in a group.
dpid
Long value that specifies the identification of the group.

Return Values

Long value that specifies the identification of the player.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDPARAM


DirectPlay8server.GetLocalHostAddress

Retrieves the local addresses used to host the session.

GetLocalHostAddress(lFlags As Long) As DirectPlay8Address

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns the DirectPlay8Address object that specifies the local host addresses.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED
DPNERR_NOTHOST

Remarks

If the caller is not the session host, the error code is DPNERR_NOTHOST. Use DirectPlay8Peer.GetPeerAddress to retrieve the address of a remote player.


DirectPlay8Server.GetPlayerOrGroup

Retrieves the client or group identifier for the specified client or group. The number of clients or groups for the application can be determined by calling DirectPlay8Server.GetCountPlayersAndGroups.

GetPlayerOrGroup(lIndex As Long) As Long

Parts

lIndex
Index of the client or group.

Return Values

Returns the identification of the client or group.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM


DirectPlay8Server.GetSendQueueInfo

Used by the application to monitor the size of the send queue. Microsoft® DirectPlay® does not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should decrease the rate at which messages are sent.

GetSendQueueInfo(idPlayer As Long, _
    lNumMsgs As Long, _
    lNumBytes As Long)

Parts

idPlayer
Long value specifying the identifier of the player.
lNumMsgs
Number of messages currently queued.
lNumBytes
Amount of data, in bytes, of the messages currently queued.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Server.GetServiceProvider

Retrieves information for the specified service provider. Before you call this method, call the DirectPlay8Server.GetCountServiceProviders method to obtain the number of registered service providers available to the application.

GetServiceProvider(lIndex As Long) As DPN_SERVICE_PROVIDER_INFO

Parts

lIndex
Index value specifying the specific server provider.

Return Values

Returns a DPN_SERVICE_PROVIDER_INFO type that describes the service provider.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Server.GetSPCaps

Retrieves the DPN_SP_CAPS structure for the specified service provider.

GetSPCaps(guidSP As String) As DPN_SP_CAPS

Parts

guidSP
String specifying the GUID of the service provider you want to get information about.

Return Values

Returns a DPN_SP_CAPS type to receive the information about the specified service provider.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Server.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Server.Host

Specifies the host for the client/server session.

Host(AppDesc As DPN_APPLICATION_DESC, _
    Address As DirectPlay8Address)

Parts

AppDesc
DPN_APPLICATION_DESC type that describes the application.
Address
DirectPlay8Address object that specifies the address of a service-provider device or a service provider on which to host the application.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Server.RegisterLobby

Enables launched applications to automatically propagate game status to the lobby.

RegisterLobby(LobbyApp As DirectPlay8LobbiedApplication)

Parts

LobbyApp
DirectPlay8LobbiedApplication object that specifies the application.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDPARAM


DirectPlay8Server.RegisterMessageHandler

Registers an entry point in the server's code that receives the messages from the DirectPlay8Server class and from connected clients.

RegisterMessageHandler(event As DirectPlay8Event)

Parts

event
DirectPlay8Event object that will receive the messages generated by the client and server.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_ALREADYREGISTERED

Remarks

If you want to register a new message handler, you must first call DirectPlay8Server.UnRegisterMessageHandler to unregister the current message handler.


DirectPlay8Server.RemovePlayerFromGroup

Removes a client from a group.

RemovePlayerFromGroup(idGroup As Long, _
    idClient As Long, _
    lFlags As Long) As Long

Parts

idGroup
Long value that specifies the identifier of the group from which the client will be removed.
idClient
Long value that specifies the identifier of the client that will be removed from the group.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Server.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPLAYER


DirectPlay8Server.SendTo

Transmits data to the specified player. The message can be sent synchronously or asynchronously.

SendTo(idSend As Long, _
     buffer() As BYTE, _
    lPriority As Long, _
    lTimeOut As Long, _
    lFlags As CONST_DPNSENDFLAGS) As Long

Parts

idSend
Long value specifying the identifier of the player to receive data.
buffer()
Array of type BYTE that describes the data to send.
lPriority
Priority of the message.
lTimeOut
Number of milliseconds to wait for the message to be sent. If the message has not been sent by the lTimeOut value, the message is not sent. If you do not want a time-out for message sends, set this parameter to 0.
lFlags
Flags that describe send behavior. You can set one or more of the flags defined in the CONST_DPNSENDFLAGS enumeration.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Server.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDFLAGS
DPNERR_TIMEDOUT

Remarks

This method will call the DirectPlay8Event.Receive method in the recipient's message handler. When the SendTo request is completed, the DirectPlay8Event.SendComplete method is called in the sender's message handler. The SendComplete method contains a DPNMSG_SEND_COMPLETE message type. The success or failure of the request is contained in the hResultCode member of this message type.


DirectPlay8Server.SetApplicationDesc

Changes the settings for the application that is being hosted. Only some settings can be changed.

SetApplicationDesc(AppDesc As DPN_APPLICATION_DESC, _
    lFlags As Long)

Parts

AppDesc
DPN_APPLICATION_DESC type that describes the application settings to modify.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to the following value.

DPNERR_INVALIDFLAGS

Remarks

You can use this method to modify only the following members of the DPN_APPLICATION_DESC type:

  • lMaxPlayers
  • SessionName
  • Password

You cannot set the lMaxPlayers member to a smaller value than the current number of players in the session.


DirectPlay8Server.SetCaps

Sets the capabilities for the session.

SetCaps(caps As DPN_CAPS, lFlags As Long)

Parts

caps
DPN_CAPS type used to set the information about the current session.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Server.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Server.SetGroupInfo

Sets a block of data associated with a group, including the name of the group.

SetGroupInfo(idGroup As Long, _
    PlayerInfo As DPN_GROUP_INFO, _
    lFlags As Long) As Long

Parts

idGroup
Long value that specifies the identifier of the group whose data block will be modified.
PlayerInfo
DPN_GROUP_INFO type that describes the group data to set.
lFlags
Flag that controls how this method is processed. The following flag can be set for this method:
DPNOP_SYNC
Causes the method to process synchronously.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Server.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDFLAGS


DirectPlay8Server.SetServerInfo

Sets the static settings of a client with an application. Call this method before connecting to relay basic player information with the application. After the client successfully connects with the application, other players can retrieve information obtained through this method by calling the DirectPlay8Client.GetServerInfo method.

SetServerInfo(PlayerInfo As DPN_PLAYER_INFO) As Long

Parts

PlayerInfo
DPN_PLAYER_INFO type that contains the player information to set.

Return Values

Returns the asynchronous handle for this operation. This is the handle that is used in lAsyncHandle parameter of the DirectPlay8Server.CancelAsyncOperation method to cancel the request, if the request is processed asynchronously.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_NOCONNECTION
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

Transmission of nonstatic information should be handled with the DirectPlay8Server.SendTo method because of the high cost of using the DirectPlay8Server.SetClientInfo method.

You can modify the client information with this method after connecting to the application. If this method is called after a connection, DirectPlay will call each player's DirectPlay8Event.InfoNotify method to notify him or her that the data has been updated.


DirectPlay8Server.SetSPCaps

Sets the capabilities for the specified service provider.

SetSPCaps(guidSP As String, spCaps As DPN_SP_CAPS)

Parts

guidSP
String specifying the GUID of the service provider you want to set information about.
spCaps
DPN_SP_CAPS type to set the information about the specified service provider.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

A successful call to DirectPlay8Server.RegisterMessageHandler must be made before this method can be called.


DirectPlay8Server.UnRegisterMessageHandler

Unregisters the current message handler.

UnRegisterMessageHandler()

Remarks

You must call this method before registering a new message handler.


DirectPlayVoiceClient8

Applications use the methods of the DirectPlayVoiceClient8 class to manage clients in a voice session.

The methods of the DirectPlayVoiceClient8 class can be organized into the following groups.

Buffer management | Create3DSoundBuffer
 | Delete3DSoundBuffer
Miscellaneous | GetCaps
 | GetCompressionType
 | GetCompressionTypeCount
 | GetSoundDeviceConfig
 | GetSoundDevices
 | StartClientNotification
Session management | Connect
 | Disconnect
 | GetClientConfig
 | GetSessionDesc
 | GetTransmitTargets
 | Initialize
 | SetClientConfig
 | SetCurrentSoundDevices
 | SetTransmitTargets
 | UnRegisterMessageHandler


DirectPlayVoiceClient8.Connect

Connects the client to a Microsoft® DirectPlay® Voice session.

Connect( _
    SoundDeviceConfig As DVSOUNDDEVICECONFIG, _
    ClientConfig As DVCLIENTCONFIG, _
    lFlags As Long)

Parts

SoundDeviceConfig
DVSOUNDDEVICECONFIG type that describes the sound device configuration.
ClientConfig
DVCLIENTCONFIG type that describes the general configuration of the client.
lFlags
You can specify the following flag.
DVFLAGS_SYNC
The method does not return until the operation is completed.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_ALREADYPENDING
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_INVALIDOBJECT
DVERR_SOUNDINITFAILURE
DVERR_INVALIDFLAGS
DVERR_OUTOFMEMORY
DVERR_NOTINITIALIZED
DVERR_COMPRESSIONNOTSUPPORTED
DVERR_TIMEOUT
DVERR_INVALIDDEVICE
DVERR_SENDERROR
DVERR_INCOMPATIBLEVERSION
DVERR_TRANSPORTNOPLAYER
DVERR_TRANSPORTNOSESSION
DVERR_RUNSETUP

Remarks

You must test the sound devices selected for playback and capture by invoking the Setup Wizard before connecting the client to the DirectPlay Voice session. On application startup, check the audio configuration by using DirectPlayVoiceTest8.CheckAudioSetup. If this method returns DVERR_RUNSETUP, the sound configuration specified has not been tested. The Setup Wizard needs to be run only once for any configuration.

Any calls to DirectPlayVoiceClient8.Connect while a connection is pending return DVERR_ALREADYPENDING. Additionally, only one connection can be pending at a time.

A transport session must be started on the specified DirectPlay object before calling this method. A successful call to DirectPlayVoiceClient8.Initialize must be made before calling the Connect method.


DirectPlayVoiceClient8.Create3DSoundBuffer

Retrieves a 3-D sound buffer for a player or group. You can use the methods of the 3-D sound buffer object to change the virtual 3-D position of incoming voice transmissions from the specified group or player.

Create3DSoundBuffer(playerID As Long) _
    As DirectSound3dBuffer8

Parts

playerID
Long value that specifies the identification of the player or group for which the user wants to reserve a buffer. You can also specify DVID_REMAINING to create a 3-D user buffer for all players or groups that do not have a user buffer.

Return Values

Returns a DirectSound3dBuffer8 type used for the Microsoft® DirectPlay® Voice main buffer.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_NOTCONNECTED
DVERR_SESSIONLOST
DVERR_ALREADYBUFFERED
DVERR_INVALIDPOINTER
DVERR_INVALIDOBJECT
DVERR_NOTINITIALIZED
DVERR_OUTOFMEMORY
DVERR_NOTALLOWED

Remarks

If the DirectPlay Voice session is a mixing server session, this method fails and returns DVERR_NOTALLOWED.

Because the DirectPlay Voice client uses the buffer to stream incoming audio, you can access all the member functions of the 3-D sound buffer object. However, you should not use the Lock, UnLock, or Play methods of the DirectSound3DBuffer object.

When the buffer for the individual user is no longer required or when a player leaves the voice session, it is important to call DirectPlayVoiceClient8.Delete3DSoundBuffer to free up resources.


DirectPlayVoiceClient8.Delete3DSoundBuffer

Returns exclusive control of the 3-D sound buffer object back to the Microsoft® DirectPlay® Voice client object.

Delete3DSoundBuffer(playerID As Long, _
    UserBuffer As DirectSound3dBuffer8)

Parts

playerID
Long value specifying the DVID of the player or group that the user wants to delete a buffer for.
UserBuffer
User buffer to delete. This must be a user buffer obtained through the DirectPlayVoiceClient8.Create3DSoundBuffer method.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_NOTCONNECTED
DVERR_SESSIONLOST
DVERR_ALREADYBUFFERED
DVERR_INVALIDPOINTER
DVERR_NOTBUFFERED
DVERR_INVALIDOBJECT
DVERR_NOTINITIALIZED
DVERR_NOTALLOWED

Remarks

If the DirectPlay Voice session is a mixing server session, this method fails and returns DVERR_NOTALLOWED.


DirectPlayVoiceClient8.Disconnect

Disconnects the Microsoft® DirectPlay® Voice client from the existing DirectPlay Voice session.

Disconnect(lFlags As Long)

Parts

lFlags
You can specify the following flag.
DVFLAGS_SYNC
Do not return until the operation is completed.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_PENDING
DVERR_ALREADYPENDING
DVERR_INVALIDPARAM
DVERR_NOTCONNECTED
DVERR_INVALIDFLAGS
DVERR_CONNECTABORTING
DVERR_NOTINITIALIZED
DVERR_TIMEOUT
DVERR_SESSIONLOST

Remarks

On calling this method, all recording and playback is stopped. If a connection is being processed, it is canceled by this call.

If this method is called synchronously by setting the DVFLAGS_SYNC flag, the method does not return until the Disconnect completes.


DirectPlayVoiceClient8.GetCaps

Retrieves the Microsoft® DirectPlay® Voice capabilities.

GetCaps() As DVCAPS

Return Values

Returns a DVCAPS type that contains the capabilities of the DirectPlayVoiceClient8 object.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER


DirectPlayVoiceClient8.GetClientConfig

Retrieves the client configuration.

GetClientConfig() As DVCLIENTCONFIG

Return Values

Returns a DVCLIENTCONFIG type that contains the configuration of the local client.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_NOTCONNECTED
DVERR_SESSIONLOST
DVERR_INVALIDPOINTER
DVERR_NOTINITIALIZED

Remarks

You can call this method only after a connection is successfully established with a Microsoft® DirectPlay® Voice session.


DirectPlayVoiceClient8.GetCompressionType

Retrieves the compression type.

GetCompressionType(lIndex As Long, _
    Data As DVCOMPRESSIONINFO, _
   lFlags As Long)

Parts

lIndex
Specific compression type. The number of supported compression types can be determined with a call to DirectPlayVoiceClient8.GetCompressionTypeCount.
Data
DVCOMPRESSIONINFO type describing compression information.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_BUFFERTOOSMALL
DVERR_INVALIDPOINTER
DVERR_INVALIDFLAGS


DirectPlayVoiceClient8.GetCompressionTypeCount

Retrieves the number of supported compression types.

GetCompressionTypeCount() As Long

Return Values

Returns the number of supported compression types.

Error Codes

If the method fails, Err.Number can be set to the following value.

DVERR_INVALIDOBJECT


DirectPlayVoiceClient8.GetSessionDesc

Retrieves the session properties.

GetSessionDesc() As DVSESSIONDESC

Return Values

Returns a DVSESSIONDESC type to receive the session description.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTCONNECTED
DVERR_SESSIONLOST
DVERR_NOTINITIALIZED

Remarks

This method may be called only after a connection is successfully established with a Microsoft® DirectPlay® Voice session.


DirectPlayVoiceClient8.GetSoundDeviceConfig

Retrieves the sound device configuration of the session.

GetSoundDeviceConfig() As DVSOUNDDEVICECONFIG

Return Values

Returns a DVSOUNDDEVICECONFIG type that is filled with the configuration of the sound device.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_NOTCONNECTED
DVERR_SESSIONLOST
DVERR_INVALIDPOINTER
DVERR_NOTINITIALIZED

Remarks

You can call this method only after a connection is successfully established with a Microsoft® DirectPlay® Voice session.


DirectPlayVoiceClient8.GetSoundDevices

Retrieves the current Microsoft® DirectSound® capture and playback objects.

GetSoundDevices( _
    DirectSoundObj As DirectSound8, _
    DirectCaptureObj As DirectSoundCapture8)

Parts

DirectSoundObj
Current DirectSound8 object being used for playback.
DirectCaptureObj
Current DirectSoundCapture8 object being using for capture.

Error Codes

If the method fails, Err.Number can be set to the following value.

DVERR_INVALIDPARAM


DirectPlayVoiceClient8.GetTransmitTargets

Retrieves the transmit targets, if any, of the voice stream from this client.

GetTransmitTargets(lFlags As Long) As Long()

Parts

lFlags
Reserved. Must be 0.

Return Values

Returns an array of Long values containing the DVIDs of the of the transmit targets, if any, of the client's voice stream.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_NOTALLOWED
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_BUFfERTOOSMALL
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_INVALIDFLAGS

Remarks

The DVIDs returned can be player or group DVIDs.


DirectPlayVoiceClient8.Initialize

Initializes the DirectPlayVoiceClient8 object by associating the DirectPlayVoiceClient8 object with a DirectPlay object.

This method must be called successfully before DirectPlayVoiceClient8.Connect method is called.

Initialize(DplayObj As Unknown, lFlags As Long)

Parts

DplayObj
Pointer to the IUnknown interface for the DirectPlay object that this DirectPlayVoiceClient8 object should use.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_ALREADYINITIALIZED
DVERR_INVALIDPOINTER
DVERR_TRANSPORTNOTINIT
DVERR_NOCALLBACK
DVERR_GENERIC


DirectPlayVoiceClient8.SetClientConfig

Sets the client configuration.

SetClientConfig(ClientConfig As DVCLIENTCONFIG)

Parts

ClientConfig
DVCLIENTCONFIG type that contains the configuration description to set.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_INVALIDFLAGS
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_SESSIONLOST

Remarks

You can call this method only after a connection is successfully established with a Microsoft® DirectPlay® Voice session.

Calling this method sets all the parameters in the DVCLIENTCONFIG type. Therefore, to leave a setting unmodified, you must retrieve the current configuration with DirectPlayVoiceClient8.GetClientConfig. Then, modify the parameters to change and call DirectPlayVoiceClient8.SetClientConfig.

If the session is running in half duplex, the members of the GetClientConfig method related to recording are ignored.


DirectPlayVoiceClient8.SetCurrentSoundDevices

Sets the current Microsoft® DirectSound® capture and playback objects.

SetCurrentSoundDevices( _
    DirectSoundObj As DirectSound8, _
    DirectCaptureObj As DirectSoundCapture8)

Parts

DirectSoundObj
DirectSound8 object to be used for playback.
DirectCaptureObj
DirectSoundCapture8 object to be used for capture.

Error Codes

If the method fails, Err.Number can be set to the following value.

DVERR_INVALIDPARAM


DirectPlayVoiceClient8.SetTransmitTargets

Specifies which players or groups receive audio transmissions from the local client.

SetTransmitTargets(playerIDs() As Long, lFlags As Long)

Parts

playerIDs()
Array of Long values specifying the DVIDs of the players or groups that are to receive the voice transmission.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_INVALIDFLAGS
DVERR_INVALIDPOINTER
DVERR_NOTINITIALIZED
DVERR_INVALIDTARGET

Remarks

If the session was created with the DVSESSION_SERVERCONTROLTARGET flag, only the server can set the target for this local client. A call to this method returns DVERR_NOTALLOWED.


DirectPlayVoiceClient8.StartClientNotification

Registers a DirectPlayVoiceEvent8 object with the client to receive all messages generated by the client and server.

StartClientNotification(event As DirectPlayVoiceEvent8)

Parts

event
DirectPlayVoiceEvent8 object that will receive messages from this client and from the server.

Error Codes

If the method fails, Err.Number can be set to the following value.

DVERR_INVALIDPARAM


DirectPlayVoiceClient8.UnRegisterMessageHandler

Unregisters the current DirectPlayVoiceClient8 message handler.

UnRegisterMessageHandler()

Remarks

You must call this method before registering a new message handler.


DirectPlayVoiceEvent8

Applications use the methods of the DirectPlayVoiceEvent8 class to capture Microsoft® DirectPlay® events generated by the DirectPlayVoiceClient8 and DirectPlayVoiceServer8 classes.

Note When implementing the DirectPlayVoiceEvent8 object, Microsoft® Visual Basic® requires that every method of this object is implemented in your form.

The methods of the DirectPlayVoiceEvent8 class are:

DirectPlayVoiceEvent8 Methods | ConnectResult
 | CreateVoicePlayer
 | DeleteVoicePlayer
 | DisconnectResult
 | HostMigrated
 | InputLevel
 | OutputLevel
 | PlayerOutputLevel
 | PlayerVoiceStart
 | PlayerVoiceStop
 | RecordStart
 | RecordStop
 | SessionLost


DirectPlayVoiceEvent8.ConnectResult

Called when the connect request generated through a call to the DirectPlayVoiceClient8.Connect method has completed.

ConnectResult(ResultCode As Long)

Parts

ResultCode
Long value set to the result code.


DirectPlayVoiceEvent8.CreateVoicePlayer

Called when a new player joins the voice session.

CreateVoicePlayer(playerID As Long, _
     flags As Long)

Parts

playerID
Long value set to the player's ID.
flags
Flags with information about the player.


DirectPlayVoiceEvent8.DeleteVoicePlayer

Called when a player quits the voice session.

DeleteVoicePlayer(playerID As Long)

Parts

playerID
Long value set to the player's ID.


DirectPlayVoiceEvent8.DisconnectResult

Called when the disconnect request generated through a call to the DirectPlayVoiceClient8.Disconnect method has completed.

DisconnectResult(ResultCode As Long)

Parts

ResultCode
Long value set to the result code.


DirectPlayVoiceEvent8.HostMigrated

Called when the voice host has changed.

HostMigrated(NewHostID As Long, _
     NewServer As DirectPlayVoiceServer8)

Parts

NewHostID
Long value set to the ID of the new voice host.
NewServer
If the local client has become the new voice session host, this member will point to a newly created DirectPlayVoiceServer8 object that can be used by the local client for providing host services. If the local client is not the new host, then this member will be NULL.


DirectPlayVoiceEvent8.InputLevel

Called periodically to notify the user of the input level from the microphone.

InputLevel(PeakLevel As Long, _
    RecordVolume As Long)

Parts

PeakLevel
Long value representing peak level across the current frame, which corresponds to approximately 1/10 second of audio stream. The current frame typically lags 50-200 milliseconds (ms) behind real-time. This value can range from 0 through 99, with 0 being completely silent and 99 being the highest possible input level.
RecordVolume
Current recording volume for the client. The value can range from -10,000 through 0. This member is available even when automatic gain control is active.


DirectPlayVoiceEvent8.OutputLevel

Called periodically to notify the user of the output level from the microphone.

OutputLevel(PeakLevel As Long, _
    OutputVolume As Long)

Parts

PeakLevel
Long value representing peak level across the current frame, that corresponds to approximately 1/10 second of audio stream. The current frame typically lags 50-200 ms behind real-time. This value can range from 0 through 99, with 0 being completely silent and 99 being the highest possible output level.
OutputVolume
Current playback volume for the client.


DirectPlayVoiceEvent8.PlayerOutputLevel

Called periodically to notify the user of the output level of an individual player's voice stream. It is generated while voice is being played back for an individual player. If multiple player voices are being played, one message for each player speaking will be sent each notification period.

PlayerOutputLevel(SourcePlayerID As Long, _
    PeakLevel As Long)

Parts

SourcePlayerID
Long value set to the ID of the player whose voice is being played back.
PeakLevel
Integer representing the peak output level of the player's voice stream. This value is in the range from 0 through 99, with 0 being completely silent and 99 being the highest possible output level


DirectPlayVoiceEvent8.PlayerVoiceStart

Called when an incoming audio stream begins playing back.

PlayerVoiceStart(SourcePlayerID As Long)

Parts

SourcePlayerID
Long value set to the ID of the player where the voice transmission originated.


DirectPlayVoiceEvent8.PlayerVoiceStop

Called when an incoming audio stream stops.

PlayerVoiceStop(SourcePlayerID As Long)

Parts

SourcePlayerID
Long value set to the ID of the player where the voice transmission stopped.


DirectPlayVoiceEvent8.RecordStart

Called when audio input on the local client begins. This can be caused by the voice activation sensitivity level being exceeded or when a valid target is specified in push-to-talk mode.

RecordStart(PeakVolume As Long)

Parts

PeakVolume
Long value set to the voice activation level that caused the transmission to begin. In push-to-talk mode, this value is 0.


DirectPlayVoiceEvent8.RecordStop

Called when audio input on the local client stops. This can be caused by the voice activation sensitivity level not being reached or when a target is deselected in push-to-talk mode.

RecordStop(PeakVolume As Long)

Parts

PeakVolume
Long value set to the voice activation level that caused the transmission to stop. In push-to-talk mode, this value is 0.


DirectPlayVoiceEvent8.SessionLost

Called when the voice session terminates.

SessionLost(ResultCode As Long)

Parts

ResultCode
Long value set to a result code that indicates why the session terminated.


DirectPlayVoiceServer8

Applications use the methods of the DirectPlayVoiceServer8 class to manage the host of the voice session.

The methods of the DirectPlayVoiceServer8 class can be organized into the following groups.

Miscellaneous | GetCaps
 | GetCompressionType
 | GetCompressionTypeCount
Session Management | GetSessionDesc
 | GetTransmitTargets
 | Initialize
 | SetSessionDesc
 | SetTransmitTargets
 | StartServerNotification
 | StartSession
 | StopSession
 | UnregisterMessageHandler


DirectPlayVoiceServer8.GetCaps

Retrieves the Microsoft® DirectPlay® Voice capabilities.

GetCaps() As DVCAPS

Return Values

Returns a DVCAPS type that contains the capabilities of the DirectPlayVoiceClient8 object.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER


DirectPlayVoiceServer8.GetCompressionType

Retrieves the compression type.

GetCompressionType(lIndex As Long, _
    Data As DVCOMPRESSIONINFO, _
   lFlags As Long)

Parts

lIndex
Specific compression type. The number of supported compression types can be determined with a call to DirectPlayVoiceServer8.GetCompressionTypeCount.
Data
DVCOMPRESSIONINFO type describing compression information.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_BUFFERTOOSMALL
DVERR_INVALIDPOINTER
DVERR_INVALIDFLAGS


DirectPlayVoiceServer8.GetCompressionTypeCount

Retrieves the number of supported compression types.

GetCompressionTypeCount() As Long

Return Values

Returns the number of supported compression types.

Error Codes

If the method fails, Err.Number can be set to the following value.

DVERR_INVALIDOBJECT


DirectPlayVoiceServer8.GetSessionDesc

Retrieves the session properties.

GetSessionDesc() As DVSESSIONDESC

Return Values

Returns a DVSESSIONDESC type to receive the session description.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTCONNECTED
DVERR_SESSIONLOST
DVERR_NOTINITIALIZED

Remarks

This method may be called only after a connection is successfully established with a Microsoft® DirectPlay® Voice session.


DirectPlayVoiceServer8.GetTransmitTargets

Retrieves the transmit targets, if any, of the voice stream for a player in a session.

GetTransmitTargets(playerSourceID As Long, _
    lFlags As Long) As Long()

Parts

playerSourceID
Long value specifying the DVID of the user or group whose target is returned.
lFlags
Reserved. Must be 0.

Return Values

Returns an array of Long values containing the DVIDs of the of the transmit targets, if any, of the server's voice stream.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_NOTALLOWED
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_BUFFERTOOSMALL
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_INVALIDFLAGS

Remarks

This method can be used only if the DVSESSION_SERVERCONTROLTARGET flag is specified on creation of the DirectPlay Voice session. If the flag is not specified, this method returns DVERR_NOTALLOWED.


DirectPlayVoiceServer8.Initialize

Initializes the DirectPlayVoiceClient8 object by associating the DirectPlayVoiceServer8 object with a Microsoft® DirectPlay® object.

Initialize(DplayObj As Unknown, lFlags As Long)

Parts

DplayObj
Pointer to the IUnknown interface for the DirectPlay object that this DirectPlayVoiceServer8 object should use.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_ALREADYINITIALIZED
DVERR_INVALIDPOINTER
DVERR_TRANSPORTNOTINIT
DVERR_NOCALLBACK
DVERR_GENERIC


DirectPlayVoiceServer8.SetSessionDesc

Sets the session settings.

SetSessionDesc(ClientConfig As DVSESSIONDESC)

Parts

ClientConfig
DVSESSIONDESC type that contains the session description.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_NOTHOSTING
DVERR_NOTINITIALIZED
DVERR_INVALIDPOINTER
DVERR_SESSIONLOST
DVERR_INVALIDOBJECT

Remarks

After the Microsoft® DirectPlay® Voice session has started, not all the session properties of the DVSESSIONDESC type can be changed. For more information, see DVSESSIONDESC.


DirectPlayVoiceServer8.SetTransmitTargets

Controls the transmission of audio from the client to the specified members of the session.

SetTransmitTargets(playerSourceID As Long, _
    playerTargetIDs As Long(), _
    lFlags As Long)

Parts

playerSourceID
DVID of the user whose targets are set.
playerTargetIDs
Array of long values specifying the DVIDs of the players or groups that are to receive the voice transmission. To specify no targets, pass an empty array for this parameter. To specify all players, create a single-item array containing DVID_ALLPLAYERS.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_NOTALLOWED
DVERR_INVALIDFLAGS
DVERR_INVALIDPOINTER
DVERR_NOTINITIALIZED
DVERR_INVALIDTARGET

Remarks

This method can be used only if the DVSESSION_SERVERCONTROLTARGET flag is specified on creation of the DirectPlay Voice session. If the flag is not specified, this method returns DVERR_NOTALLOWED.


DirectPlayVoiceServer8.StartServerNotification

Registers a DirectPlayVoiceEvent8 object that is used to capture messages generated by this Microsoft® DirectPlay® Voice session.

StartServerNotification(event As DirectPlayVoiceEvent8)

Parts

event
DirectPlayVoiceEvent8 object that will receive messages from this client and from the server.

Error Codes

If the method fails, Err.Number can be set to the following value.

DVERR_INVALIDPARAM


DirectPlayVoiceServer8.StartSession

Starts an initialized Microsoft® DirectPlay® Voice session within a running DirectPlay transport session. This method must be successfully called before the clients can complete a connection to the voice session.

StartSession(SessionDesc As DVSESSIONDESC, lFlags As Long)

Parts

SessionDesc
DVSESSIONDESC type that contains the session description.
lFlags
Reserved. Must be 0.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_ALREADYPENDING
DVERR_NOTINITIALIZED
DVERR_INVALIDOBJECT
DVERR_INVALIDPOINTER
DVERR_INVALIDFLAGS
DVERR_HOSTING

Remarks

The DirectPlayVoiceServer8.Initialize method must be called before this method is called. The voice session can be hosted on any client in the session if the voice session is peer-to-peer. If the voice session is not peer-to-peer, it must be hosted on the transport client, which is the host of an active transport session.

The DVSESSIONDESC structure contains the type of voice session to start. The type of voice session can have a dramatic effect on the CPU and bandwidth usage for both the client and the server.


DirectPlayVoiceServer8.StopSession

Stops the Microsoft® DirectPlay® Voice session.

StopSession(lFlags As Long)

Parts

lFlags
The following flag can be set.
DVFLAGS_NOHOSTMIGRATE
The host will not migrate regardless of session and transport settings. Use this flag to shut down the voice session completely.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_ALREADYPENDING
DVERR_SESSIONLOST
DVERR_NOTINITIALIZED
DVERR_NOTHOSTING
DVERR_INVALIDFLAGS
DVERR_INVALIDOBJECT

Remarks

This method returns the DVERR_ALREADYPENDING error value if it is called while another thread is processing a StopSession request.


DirectPlayVoiceServer8.UnRegisterMessageHandler

Unregisters the current DirectPlayVoiceServer8 message handler.

UnRegisterMessageHandler()

Remarks

You must call this method before registering a new message handler.


DirectPlayVoiceTest8

Applications use the method of the DirectPlayVoiceTest8 class to test the Microsoft® DirectPlay® Voice audio configuration.

The CheckAudioSetup method of the DirectPlayVoiceTest8 class is used to check the audio configuration.


DirectPlayVoiceTest8.CheckAudioSetup

Runs the Audio Setup Wizard on the specified devices. This wizard runs a series of tests on the devices to determine if they are capable of full duplex audio and to ensure that the microphone is plugged in and working correctly on the capture device.

CheckAudioSetup( _
    guidPlaybackDevice As String, _
    guidCaptureDevice As String, _
    hwndOwner As Long, _
    lFlags As Long) As Long

Parts

guidPlaybackDevice
GUID that identifies the playback device to test. If an empty string is passed for this parameter, Microsoft® DirectPlay® Voice tests the default voice playback device defined by Microsoft® DirectSound® .
guidCaptureDevice
GUID that identifies the capture device to test. If an empty string is passed for this parameter, DirectPlay Voice tests the default voice capture device defined by DirectSound.
hwndOwner
The test wizard invoked by this method is modal. If the calling application has a window that should be the parent window of the wizard, it should pass a handle to that window in this parameter. If the calling application does not have a window, it can pass 0. If the DVFLAGS_QUERYONLY flag is specified, this parameter is not used and the application can pass 0.
lFlags
Flags. The following flags can be set.
DVFLAGS_QUERYONLY
Audio setup is not run. Instead, the method checks the registry to see if the devices have been tested. If the devices have not been tested, the method returns DVERR_RUNSETUP. If the devices have been tested, the method returns DV_FULLDUPLEX if the devices support full duplex audio, or DV_HALFDUPLEX if the devices do not support full duplex audio.
DVFLAGS_ALLOWBACK
Enable the Back button on the Welcome page of the wizard. If the user clicks the Back button on the Welcome page, the wizard exits, and CheckAudioSetup returns DVERR_USERBACK.

Error Codes

If the method fails, Err.Number can be set to one of the following values.

DVERR_INVALIDPARAM
DVERR_RUNSETUP

Remarks

This method contains user interface (UI) elements and raises dialog boxes. If the DVFLAGS_QUERYONLY flag is specified, the tests are not actually run and no UI is raised. Instead the registry is checked to determine the results of a previous test of these devices.


Functions

This section contains references for the following Microsoft® DirectPlay® functions. They are designed to simplify the process of handling byte arrays.

  • AddDataToBuffer
  • AddStringToBuffer
  • GetDataFromBuffer
  • GetStringFromBuffer
  • NewBuffer


AddDataToBuffer

Adds nonstring data to a byte array.

AddDataToBuffer( _
    Buffer() As Byte, _
    lData As Any, _
    lSize As Long, _
    lOffset As Long)

Parameters

Buffer
Byte array to which the data is to be added.
lData
Data that is to be added to Buffer.
lSize
Size, in bytes, of the data in lData. The simplest way to determine this value is to use the Microsoft® Visual Basic® LenB function. You can also use one of the values from the CONST_DPLAYBUFSIZE enumeration.
lOffset
Long value containing the offset, in bytes, to the location in the byte array where the data is to be added. When the function returns, this parameter will be set to the offset of the first byte following the data that has just been added.

Remarks

If the byte array passed to Buffer is not large enough to hold the added data, the array will be enlarged without data loss to a sufficient size.


AddStringToBuffer

Adds a string to a byte array.

AddStringToBuffer( _
    Buffer() As Byte, _
    StringData As String, _
    lOffset As Long)

Parameters

Buffer
Byte array that the data is to be added to.
StringData
String value that is to be added to Buffer.
lOffset
Long value containing the offset, in bytes, to the location in the byte array where the data is to be added. When the function returns, this parameter will be set to the offset of the first byte following the data that has just been added.

Remarks

If the byte array passed to Buffer is not large enough to hold the added string, the array will be enlarged without data loss to a sufficient size.


GetDataFromBuffer

Retrieves nonstring data from a byte array.

GetDataFromBuffer( _
    Buffer() As Byte, _
    lData As Any, _
    lSize As Long, _
    lOffset As Long)

Parameters

Buffer
Byte array from which the data is to be retrieved.
lData
Variable to receive the data that is retrieved from Buffer.
lSize
Size of the data in lData, in bytes. The simplest way to determine this value is to use the Visual Basic LenB function. You can also use one of the values from the CONST_DPLAYBUFSIZE enumeration.
lOffset
Offset, in bytes, to the location in the byte array from which the data is to be retrieved. When the function returns, this parameter will be set to the offset of the first byte following the data that has just been retrieved.


GetStringFromBuffer

Retrieves string data from a byte array.

GetStringFromBuffer( _
    Buffer() As Byte, _
    lOffset As Long) As String

Parameters

Buffer
Byte array that the data is to be retrieved from.
lOffset
Long value containing the offset, in bytes, to the location in the byte array from which the data is to retrieved. When the function returns, this parameter will be set to the offset of the first byte following the data that has just been retrieved.

Return Values

Returns a String value containing the retrieved string.


NewBuffer

Creates a byte array.

NewBuffer( Buffer() As Byte ) As Long

Parameters

Buffer
Byte array that will be initialized to a default number of members.

Return Values

Returns a Long value containing the offset to the start of the array. This value will always be zero.

Remarks

The default number of members in the returned array is 20.


Types

This section contains information on the following types used with Microsoft® DirectPlay® .

  • DPL_APPLICATION_INFO
  • DPL_CONNECT_INFO
  • DPL_CONNECTION_SETTINGS
  • DPL_MESSAGE_CONNECT
  • DPL_MESSAGE_CONNECTION_SETTINGS
  • DPL_MESSAGE_RECEIVE
  • DPL_PROGRAM_DESC
  • DPN_APPLICATION_DESC
  • DPN_CAPS
  • DPN_CONNECTION_INFO
  • DPN_GROUP_INFO
  • DPN_PLAYER_INFO
  • DPN_SERVICE_PROVIDER_INFO
  • DPN_SP_CAPS
  • DPNMSG_ASYNC_OP_COMPLETE
  • DPNMSG_CONNECT_COMPLETE
  • DPNMSG_ENUM_HOSTS_QUERY
  • DPNMSG_ENUM_HOSTS_RESPONSE
  • DPNMSG_INDICATE_CONNECT
  • DPNMSG_RECEIVE
  • DPNMSG_SEND_COMPLETE
  • DVCAPS
  • DVCLIENTCONFIG
  • DVCOMPRESSIONINFO
  • DVSESSIONDESC
  • DVSOUNDDEVICECONFIG


DPL_APPLICATION_INFO

Returned in the DirectPlay8LobbyClient.GetLocalProgram method to describe the lobbied application.

Type DPL_APPLICATION_INFO
    ApplicationName As String
    guidApplication As String
    lFlags As CONST_DPLSESSION
    lNumRunning As Long
    lNumWaiting As Long
End Type

Members

ApplicationName
Name of the lobbied application.
guidApplication
String that specifies the GUID of the lobbied application.
lFlags
One of the constants of CONST_DPLSESSION enumeration that describes the current status of the lobbied application.
lNumRunning
Number of instances of the application.
lNumWaiting
Number of clients waiting to connect to the lobbied application.


DPL_CONNECT_INFO

Used to specify connection information for a lobby client when connecting to the lobby application in the DirectPlay8LobbyClient.ConnectApplication method.

Type DPL_CONNECT_INFO
    ConnectionSettings As DPL_CONNECTION_SETTINGS
    guidApplication As String
    lFlags As CONST_DPLCONNECT
End Type

Members

ConnectionSettings
DPL_CONNECTION_SETTINGS type with the settings for this connection.
guidApplication
String that specifies the GUID of the application.
lFlags
One of the constants of the CONST_DPLCONNECT enumeration that determine connection behavior.


DPL_CONNECTION_SETTINGS

Holds connection information for lobbied connections.

Type DPL_CONNECTION_SETTINGS
    AddressDeviceUrl As String
    AddressSenderUrl As String
    ApplicationDescription As DPN_APPLICATION_DESC
    lFlags As CONST_DPLCONNECTSETTINGS
    PlayerName As String
End Type

Members

AddressDeviceUrl
String set to the device URL.
AddressSenderUrl
String set to the sender URL.
ApplicationDescription
DPN_APPLICATION_DESC type containing the application description.
lFlags
Value from the CONST_CONNECTSETTINGS enumeration. This member is set to DPLCONNECTSETTINGS_HOST if your player is the session host, and 0 otherwise.
PlayerName
String value set to the player's name.


DPL_MESSAGE_CONNECT

This type is generated by Microsoft® DirectPlay® when a lobby client connects to the lobbied application through the DirectPlay8LobbyClient.ConnectApplication method.

Type DPL_MESSAGE_CONNECT
    ConnectId As Long
    dplMsgCon As DPL_CONNECTION_SETTINGS
    LobbyConnectData() As Byte
End Type

Members

ConnectId
Handle used to identify the connection. This handle is used to in subsequent calls to DirectPlay8LobbyClient.Send and DirectPlay8LobbyClient.ReleaseApplication.
dplMsgCon
DPL_CONNECTION_SETTINGS type with the connection settings.
LobbyConnectData
Lobby connection data.


DPL_MESSAGE_CONNECTION_SETTINGS

Used with the DirectPlay8LobbyEvent.ConnectionSettings method.

Type DPL_MESSAGE_CONNECTION_SETTINGS
    dplConnectionSettings
    hSender As Long
End Type

Members

dplConnectionSettings
DPL_CONNECTION_SETTINGS type that describes the connection settings.
hSender
Long value that contains the handle for the connection that sent this message.


DPL_MESSAGE_RECEIVE

Microsoft® DirectPlay® generates this type when the target receives a message sent by the DirectPlay8LobbyClient.Send or DirectPlay8LobbiedApplication.Send method.

Type DPL_MESSAGE_RECEIVE
    buffer() As Byte
    lBufferSize As Long
    Sender As Long
End Type

Members

buffer
BYTE array with the message data.
lBufferSize
Size of the message data contained in the buffer member.
Sender
Handle of the client that sent the message.


DPL_PROGRAM_DESC

Describes a Microsoft® DirectPlay® lobby-aware application.

Type DPL_PROGRAM_DESC
    ApplicationName As String
    CommandLine As String
    CurrentDirectory As String
    Description As String
    ExecutableFilename As String
    ExecutablePath As String
    guidApplication As String
    LauncherFilename As String
    LauncherPath As String
    lFlags As Long
End Type

Members

ApplicationName
Application name.
CommandLine
Command line arguments.
CurrentDirectory
Current directory.
Description
Application description.
ExecutableFilename
File name of the application executable.
ExecutablePath
Path of the application executable.
guidApplication
String that specifies the GUID of the application.
LauncherFilename
File name of the launcher executable.
LauncherPath
Path of the launcher executable.
lFlags
Reserved. Must be 0.


DPN_APPLICATION_DESC

Describes the settings for a Microsoft® DirectPlay® application.

Type DPN_APPLICATION_DESC
    guidApplication As String
    guidInstance As String
    lCurrentPlayers As Long
    lFlags As Long
    lMaxPlayers As Long
    Password As String
    SessionName As String
End Type

Members

guidApplication
Application globally unique identifier (GUID).
guidInstance
GUID that is generated at startup representing the instance of this application. This member is an [out] parameter when calling the GetApplicationDesc method exposed by the DirectPlay8Peer, DirectPlay8Client, and DirectPlay8Server objects. It is an optional [in] parameter when calling the Connect method exposed by the DirectPlay8Peer and DirectPlay8Client objects. It must be set to GUID NULL when you call the SetApplicationDesc method exposed by the DirectPlay8Server and DirectPlay8Peer objects. You cannot obtain this GUID by calling the DirectPlay8Server.Host or DirectPlay8Peer.Host methods. You must obtain the GUID by calling a GetApplicationDesc method.
lCurrentPlayers
Number of clients currently connected to the session.
lFlags
One of the following flags describing application behavior.
DPNSESSION_CLIENT_SERVER
Specifies that this type of session is client/server. This flag cannot be combined with DPNSESSION_MIGRATE_HOST.
DPNSESSION_NODPNSVR
Specifies that you do not want enumerations forwarded to your host from DPNSVR. See Using the DirectPlay DPNSVR Application for a further discussion of DPNSVR.
DPNSESSION_REQUIREPASSWORD
Specifies that the session is password protected. If this flag is set, Password must be a valid string.
DPNSESSION_MIGRATE_HOST
Used in peer-to-peer sessions, setting this flag will enable host migration. This flag cannot be combined with DPNSESSION_CLIENT_SERVER.
lMaxPlayers
Maximum number of clients allowed in the session. Set this member to 0 to indicate an unlimited number of players.
Password
String specifying the Unicode password that is required to connect to the session. This must be an empty string if the DPNSESSION_REQUIREPASSWORD is not set in the lFlags member.
SessionName
String specifying the Unicode name of the session.

Remarks

Multiple instances of the application can run simultaneously. "Application" refers to a specific instance of an application.

The lMaxPlayers, Password, and SessionName members can be set when calling the Host or SetApplicationDesc methods exposed by the DirectPlay8Server and DirectPlay8Peer objects.

When connecting to a password-protected session, the data in the Password member is transmitted in clear text to the host.


DPN_CAPS

Used to set and retrieve general parameters for Microsoft® DirectPlay® sessions.

Type DPN_CAPS
    lConnectRetries As Long
    lConnectTimeout As Long
    lFlags As Long
    lTimeoutUntilKeepAlive As Long
End Type

Members

lConnectRetries
Number of connection retries DirectPlay should make during the connection process.
lConnectTimeout
Number of milliseconds DirectPlay should wait before it retries a connection request.
lFlags
Reserved, must be 0.
lTimeoutUntilKeepAlive
Number of milliseconds DirectPlay should wait, since the last time it received a packet from an endpoint, before it sends a keep-alive message. You can catch the KeepAlive up to 2 times of what you specify.


DPN_CONNECTION_INFO

Used to retrieve statistics for the connection between you and a particular endpoint.

Type DPN_CONNECTION_INFO
    lSize As Long
    lRoundTripLatencyMS As Long
    lThroughPutBPS As Long
    lPeakThroughPutBPS As Long
    lBytesSentGuaranteed As Long
    lPacketsSentGuaranteed As Long
    lBytesSentNonGuaranteed As Long
    lPacketsSentNonGuaranteed As Long
    lBytesRetried As Long
    lPacketsRetried As Long
    lBytesDropped As Long
    lPacketsDropped As Long
    lBandwidthBPS As Long
    lMessagesTransmittedHighPriority As Long
    lMessagesTimedOutHighPriority As Long
    lMessagesTransmittedNormalPriority As Long
    lMessagesTimedOutNormalPriority As Long
    lMessagesTransmittedLowPriority As Long
    lMessagesTimedOutLowPriority As Long
    lBytesReceivedGuaranteed As Long
    lPacketsReceivedGuaranteed As Long
    lBytesReceivedNonGuaranteed As Long
    lPacketsReceivedNonGuaranteed As Long
    lMessagesReceived As Long
End Type

Members

lSize
Long value set to the size of the type.
lRoundTripLatencyMS
Long value set to the approximate time, in milliseconds, for a packet to reach the endpoint and return to the local computer. This number will fluctuate throughout the session, as network conditions change.
lThroughPutBPS
Long value set to the approximate throughput, in bytes per second (BPS). This number will fluctuate throughout the session, as link conditions change.
lPeakThroughPutBPS
Long value set to the peak throughput, in bytes per second. This number will fluctuate throughout the session, as link conditions change.
lBytesSentGuaranteed
Long value set to the amount, in bytes, of guaranteed messages that have been sent.
lPacketsSentGuaranteed
Long value set to the number of guaranteed packets that have been sent.
lBytesSentNonGuaranteed
Long value set to the amount, in bytes, of nonguaranteed messages that have been sent.
lPacketsSentNonGuaranteed
Long value set to the number of nonguaranteed packets that have been sent.
lBytesRetried
Long value set to the amount, in bytes, of messages that have been retried.
lPacketsRetried
Long value set to the number of packets that have been retried.
lBytesDropped
Long value set to the amount, in bytes, of messages that have been dropped.
lPacketsDropped
Long value set to the number of packets that have been dropped.
lBandwidthBPS
Long value set to the bandwidth, in bytes per second.
lMessagesTransmittedHighPriority
Long value set to the number of high-priority messages that have been transmitted.
lMessagesTimedOutHighPriority
Long value set to the number of high-priority messages that have timed out.
lMessagesTransmittedNormalPriority
Long value set to the number of normal-priority messages that have been transmitted.
lMessagesTimedOutNormalPriority
Long value set to the number of normal-priority messages that have timed out.
lMessagesTransmittedLowPriority
Long value set to the number of low-priority messages that have been transmitted.
lMessagesTimedOutLowPriority
Long value set to the number of low-priority messages that have timed out.
lBytesReceivedGuaranteed
Long value set to the amount, in bytes, of guaranteed messages that have been received.
lPacketsReceivedGuaranteed
Long value set to the number of guaranteed packets that have been received.
lBytesReceivedNonGuaranteed
Long value set to the amount, in bytes, of nonguaranteed messages that have been received.
lPacketsReceivedNonGuaranteed
Long value set to the number of nonguaranteed packets that have been received.
lMessagesReceived
Long value set to the number of messages that have been received.


DPN_GROUP_INFO

Describes static group information.

Type DPN_GROUP_INFO
    lGroupFlags As CONST_DPNGROUPINFOFLAGS
    lInfoFlags As CONST_DPNINFO
    name As String
End Type

Members

lGroupFlags
One of the constants of the CONST_DPNGROUPINFOFLAGS enumeration that describe the flags set for the player.
lInfoFlags
One of the constants of the CONST_DPNINFO enumeration that describe the type of data contained in this type.
Name
Name of the group.

Remarks

When using this type in the DirectPlay8Peer.GetGroupInfo and DirectPlay8Server.GetGroupInfo methods, lInfoFlags must be set to 0.


DPN_PLAYER_INFO

Describes static player information.

Type DPN_PLAYER_INFO
    lInfoFlags As CONST_DPNINFO
    lPlayerFlags As CONST_DPNPLAYINFOFLAGS
    name As String
End Type

Members

lInfoFlags
One of the constants in the CONST_DPNINFO enumeration that specify the type of information contained in this type.
lPlayerFlags
One of the constants in the CONST_DPNPLAYINFOFLAGS enumeration describing the flags set for the player.
name
Name of the player.

Remarks

When using this type in the DirectPlay8Peer.GetPeerInfo and DirectPlay8Server.GetClientInfo methods, lInfoFlags must be set to 0.


DPN_SERVICE_PROVIDER_INFO

Used when enumerating information for a specific service provider.

Type DPN_SERVICE_PROVIDER_INFO
    GUID As String
    lFlags As Long
    name As String
End Type

Members

GUID
GUID for the service provider.
lFlags
Reserved. Must be 0.
name
Name of the service provider.


DPN_SP_CAPS

Used to set and retrieve parameters for service providers.

Type DPN_SP_CAPS
    lBuffersPerThread As Long
    lDefaultEnumCount As Long
    lDefaultEnumRetryInterval As Long
    lDefaultEnumTimeout As Long
    lFlags As Long
    lMaxEnumPayloadSize As Long
    lNumThreads As Long
    lSystemBufferSizeAs Long
End Type

Members

lBuffersPerThread
The number of outstanding receive buffers allocated for each DirectPlay thread. If you increase the number of receive buffers, DirectPlay can pull more data out of the operating system buffers. However, you may also increase latency if data is arriving faster than your application can process it.
lDefaultEnumCount
Long value that specifies the default enumeration count.
lDefaultEnumRetryInterval
Long value that specifies the default retry interval, in milliseconds.
lDefaultEnumTimeout
Long value that specifies the default enumeration timeout value, in milliseconds.
lFlags
Long value that can be a combination of the following flags.
DPNSPCAPS_SUPPORTSALLADAPTERS
The service provider is supported on all the adapters that are present on the system.
DPNSPCAPS_SUPPORTSBROADCAST
For IP and IPX applications, the service provider has the ability to find games by broadcasting, if sufficient addressing information is not provided.
DPNSPCAPS_SUPPORTSDPNSRV
Dpnsvr.exe will provide port sharing for the given SP. Currently, this flag is available on IP and IPX only. See Using the DirectPlay DPNSVR Application for a further discussion of DPNSVR.
lMaxEnumPayloadSize
Long that specifies the maximum size of the payload information that can be sent in the ResponseData member of the types that accompany the DirectPlay8Event.EnumHostQuery and DirectPlay8Event.EnumHostQuery methods.
lNumThreads
Number of threads the service provider will use for servicing network requests. The default value is based on an algorithm that takes into account the number of processors on the system. Most applications will not need to modify this value.

After a service provider is active in your process you may only increase this value. Decreasing the value will have no effect. The setting is process wide, meaning it will effect your current Microsoft® DirectPlay® object and any other DirectPlay objects in your process.

lSystemBufferSizeAs
The size of the operating system buffer. This buffer holds data from the communications device when your application cannot process data as fast as it arrives. The purpose of this buffer is to prevent data loss if you receive a sudden burst of data, or if the receive threads are momentarily stalled. Increasing lSystemBufferSize may increase latency if your application cannot process the received data fast enough. You can eliminate the operating system buffer by setting lSystemBufferSize to 0. However, if you do so, you run the risk of losing data if you cannot process the received data as fast as it arrives.


DPNMSG_ASYNC_OP_COMPLETE

Used in the dpnotify parameter of the DirectPlay8Event.AsyncOpComplete method. This type is generated by Microsoft® DirectPlay® when an asynchronous operation has completed.

Type DPNMSG_ASYNC_OP_COMPLETE
    AsyncOpHandle As Long
    hResultCode As Long
End Type

Members

AsyncOpHandle
Long value specifying the handle of the asynchronous operation.
hResultCode
Long value specifying the result of the asynchronous operation.


DPNMSG_CONNECT_COMPLETE

Used in the dpnotify parameter of the DirectPlay8Event.ConnectComplete method. This type is generated by Microsoft® DirectPlay® when a connection request has been completed.

Type DPNMSG_CONNECT_COMPLETE
    AsyncOpHandle As Long
    hResultCode As Long
    ReplyData() as Byte
End Type

Members

AsyncOpHandle
Long value specifying the handle of the asynchronous operation.
hResultCode
Long value specifying result of the connection request.
ReplyData
Byte array containing the connection data returned by the host or server.


DPNMSG_ENUM_HOSTS_QUERY

Used in the dpnotify parameter of the DirectPlay8Event.EnumHostsQuery method. This type is generated by Microsoft® DirectPlay® when a player has requested a host enumeration.

Type DPNMSG_ENUM_HOSTS_QUERY
    AddressDeviceUrl As String
    AddressSenderUrl As String
    lMaxResponseDataSize As Long
    ReceivedData() As Byte
    ResponseData() As Byte
End Type

Members

AddressDeviceUrl
String value containing the device's URL.
AddressSenderUrl
String value containing the sender's URL.
lMaxResponseDataSize
Long value specifying the size of the response data block.
ReceivedData
Data received from the enumeration.
ResponseData
Data block containing the response to the enumeration request.


DPNMSG_ENUM_HOSTS_RESPONSE

Used in the dpnotify parameter of the DirectPlay8Event.EnumHostsResponse method. This type is generated by Microsoft® DirectPlay® when the host responds with information to an enumeration request.

Type DPNMSG_ENUM_HOSTS_RESPONSE
    AddressDeviceUrl As String
    AddressSenderUrl As String
    ApplicationDescription As DPN_APPLICATION_DESC
    lRoundTripLatencyMS As Long
    ResponseData As Byte
End Type

Members

AddressDeviceUrl
String specifying the device's address URL
AddressSenderUrl
String specifying the sender's address URL.
ApplicationDescription
DPN_APPLICATION_DESC type that describes the application.
lRoundTripLatencyMS
Round-trip latency, in milliseconds.
ResponseData
Response data from the enumeration.


DPNMSG_INDICATE_CONNECT

Used in the dpnotify parameter of the DirectPlay8Event.IndicateConnect method. This type is generated by Microsoft® DirectPlay® when a player has requested a connection to the session.

Type DPNMSG_INDICATE_CONNECT
    AddressDeviceUrl As String
    AddressPlayerUrl As String
    UserData() As Byte
End Type

Members

AddressDeviceUrl
String specifying the device's address URL
AddressSenderUrl
String specifying the sender's address URL.
UserData
Data of the connecting player.


DPNMSG_RECEIVE

Used in the dpnotify parameter of the DirectPlay8Event.Receive method. This type is generated by Microsoft® DirectPlay® when a message has been received.

Type DPNMSG_RECEIVE
    idSender As Long
    iDataSize As Long
    ReceivedData() As Byte
End Type

Members

idSender
Long value specifying the identifier of the message sender.
iDataSize
Long value specifying the number of bytes in the ReceivedData member. Because the byte array is zero-based, the upper limit of the array will be IDataSize-1.
ReceivedData
Byte array containing the message data that was sent.


DPNMSG_SEND_COMPLETE

Used in the dpnotify parameter of the DirectPlay8Event.SendComplete method. This type is generated by Microsoft® DirectPlay® when a message has been received by the recipient.

Type DPNMSG_SEND_COMPLETE
    AsyncOpHandle As Long
    hResultCode As Long
    lSendTime As Long
End Type

Members

AsyncOpHandle
Long value specifying the handle of the asynchronous operation.
hResultCode
Long value specifying the success or failure of the message send.
lSendTime
Time, in milliseconds, between send call and completion.


DPNMSG_TERMINATE_SESSION

Used in the DirectPlay8Event.TerminateSession method.

Type DPNMSG_TERMINATE_SESSION
    hResultCode As Long
    TerminateData() As Byte
End Type

Members

hResultCode
Long value specifying why the session was terminated. This member is set to DPNERR_HOSTTERMINATEDSESSION if the session was peer-to-peer, and the host called DirectPlay8Peer.TerminateSession. If the session was ended by the host calling Close, or if the host stops responding, hResultCode is set to DPNERR_CONNECTIONLOST.
TerminateData
Termination data. If hResultCode is set to DPNERR_HOSTTERMINATEDSESSION, TerminateData points to the data block that the host passed through the UserData parameter of DirectPlay8Peer.TerminateSession. If hResultCode is set to DPNERR_CONNECTIONLOST, TerminateData will be empty


DVCAPS

Describes the capabilities of the Microsoft® DirectPlay® Voice client object.

Type DVCAPS
    lFlags As Long
End Type

Members

lFlags
Reserved. Must be 0.


DVCLIENTCONFIG

Controls the run-time parameters for the client. This type is first used in the call to DirectPlayVoiceClient8.Connect, where it sets the initial state of these parameters. The type can be retrieved after a connection has been made by calling DirectPlayVoiceClient8.GetClientConfig, and set using DirectPlayVoiceClient8.SetClientConfig.

Type DVCLIENTCONFIG
    lBufferAggressiveness As CONST_DVBUFFERAGGRESSIVENESS
    lBufferQuality As CONST_DVBUFFERQUALITY
    lFlags As CONST_DVCLIENTCONFIGENUM
    lNotifyPeriod As Long
    lPlaybackVolume As Long
    lRecordVolume As Long
    lThreshold As CONST_DVTHRESHOLD
End Type

Members

lBufferAggressiveness
One of the constants of the CONST_DVBUFFERAGGRESSIVENESS enumeration that specifies the buffer aggressiveness setting for the adaptive buffer algorithm.
lBufferQuality
One of the constants of the CONST_DVBUFFERQUALITY enumeration that specifies the buffer quality setting for the adaptive buffering algorithm. For most applications, this should be set to DVBUFFERQUALITY_DEFAULT. It can be set to anything in the range of DVBUFFERQUALITY_MIN to DVBUFFERQUALITY_MAX. In general, the higher the value, the higher the quality of the voice but the higher the latency. The lower the value, the lower the latency but the lower the quality.
lFlags
Combination of flags from the CONST_DVCLIENTCONFIGENUM enumeration.
lNotifyPeriod
Specifies how often you want to receive DVMSGID_OUTPUTLEVEL and DVMSGID_INPUTLEVEL (if session is full duplex) messages. If this value is set to 0, these messages are disabled. The value specifies the number of milliseconds between these messages. DVNOTIFYPERIOD_MINPERIOD specifies the minimum period between messages that is allowed.
lPlaybackVolume
Specifies what the volume of the playback should be set to. Adjusting this volume adjusts both the main buffer and all 3-D sound buffers. See the DirectSoundPrimaryBuffer8.SetVolume method for the valid values for this member. You can specify DVPLAYBACKVOLUME_DEFAULT to use a default value that is appropriate for most situations (full volume).
lRecordVolume
Specifies what the volume of the recording should be set to. See the DirectSoundPrimaryBuffer8.SetVolume method for the valid values for this member.

If automatic gain control is enabled, this value can be set to DVRECORDVOLUME_LAST, which tells the system to use the current volume as determined by the automatic gain control algorithm. If a value other then DVRECORDVOLUME_LAST is specified in combination with automatic gain control, this value will be used to restart the algorithm at the specified value.

On return from a call to DirectPlayVoiceClient8.GetClientConfig, this value will contain the current recording volume. When adjusting the recording volume, Microsoft® DirectPlay® Voice will adjust the volume for the microphone (if a microphone volume is present for the card) and the master recording volume (if one is present on the card). If neither a microphone volume nor a master record volume is present, DirectPlay Voice will be unable to adjust the recording volume.

lThreshold
One of the constants of the CONST_DVTHRESHOLD enumeration that specifies the input level used to trigger voice transmission if the DVCLIENTCONFIG_MANUALVOICEACTIVATED flag is specified in the lFlags member. When the flag is specified, this value can be set to anywhere in the range of DVTHRESHOLD_MIN to DVTHRESHOLD_MAX. Additionally, DVTHRESHOLD_DEFAULT can be set to use a default value.

If DVCLIENTCONFIG_MANUALVOICEACTIVATED or DVCLIENTCONFIG_AUTOVOICEACTIVATED is not specified in the lFlags member of this type (indicating push-to-talk mode) this value must be set to DVTHRESHOLD_UNUSED.


DVCOMPRESSIONINFO

Describes the attributes of a specific Microsoft® DirectPlay® Voice compression type.

Type DVCOMPRESSIONINFO
    guidType As String
    lFlags As Long
    lMaxBitsPerSecond As Long
    strDescription As String
    strName As String
End Type

Members

guidType
String value specifying the GUID used to identify this compression type by DirectPlay Voice.
lFlags
Reserved; must be 0.
lMaxBitsPerSecond
Maximum number of bits per second claimed by the codec.
strDescription
Description of the codec.
strName
Name describing the codec.


DVSESSIONDESC

Describes the desired or current session settings for the Microsoft® DirectPlay® Voice server. This structure is used by the voice session host to configure the session, and by the session host and the clients to retrieve information about the current session. The lFlags, lSessionType, and guidCT members can only be set when the host starts the voice session. The host can change the buffer settings at any time.

Type DVSESSIONDESC
    guidCT As String
    lBufferAggressiveness As CONST_DVBUFFERAGGRESSIVENESS
    lBufferQuality As CONST_DVBUFFERQUALITY
    lFlags As CONST_DVSESSION
    lSessionType As CONST_DVSESSIONTYPE
End Type

Members

guidCT
String value specifying the GUID of the compression type of the session.
lBufferAggressiveness
One of the constants of the CONST_DVBUFFERAGGRESSIVENESS enumeration that specifies the buffer aggressiveness setting. This member is unused for all session types except mixing sessions. For all sessions except mixing sessions, set this member to DVBUFFERAGGRESSIVENESS_DEFAULT.

Allowable values are between DVBUFFERAGGRESSIVENESS _MIN and DVBUFFERAGGRESSIVENESS _MAX. Additionally, this member can be set to the following value.

DVBUFFERAGGRESSIVENESS_DEFAULT
Specifying this value tells DirectPlay Voice to use the system default for this value, which is adjustable through a registry entry that can also be set through Control Panel.
lBufferQuality
One of the constants of the CONST_DVBUFFERQUALITY enumeration that specifies the buffer quality setting. This member is unused for all session types except mixing sessions. For all sessions except mixing sessions, set this member to DVBUFFERQUALITY_DEFAULT.

Allowable values are between DVBUFFERQUALITY_MIN and DVBUFFERQUALITY_MAX. Additionally, this member can be set to the following value.

DVBUFFERQUALITY_DEFAULT
Specifying this value tells DirectPlay Voice to use the system default for this value, which is adjustable through a registry entry that can also be set through Sounds and Multimedia in Control Panel.
lFlags
Combination of the flags of the CONST_DVSESSION enumeration.
lSessionType
One of the flags of the CONST_DVSESSIONTYPE enumeration to specify the type of DirectPlay Voice session to run. The DVSESSIONTYPE_PEER flag is not available in client/server sessions; all other flags are valid for all session types.


DVSOUNDDEVICECONFIG

Used to set and retrieve information about the sound device configuration and cannot be changed once a connection has been made. After a connection is made, you can retrieve the current sound device configuration by calling DirectPlayVoiceClient8.GetSoundDeviceConfig.

Type DVSOUNDDEVICECONFIG
    guidCaptureDevice As String
    guidPlaybackDevice As String
    hwndAppWindow As Long
    lFlags As CONST_DVSOUNDEFFECT
    lMainBufferFlags As CONST_DSBPLAYFLAGS
    lMainBufferPriority As Long
    MainSoundBuffer As DirectSoundSecondaryBuffer8
End Type

Members

guidCaptureDevice
When this type is used in DirectPlayVoiceClient8.Connect method, this member specifies the GUID of the device used for capture.

When this type is used in the DirectPlayVoiceClient8.GetSoundDeviceConfig method, this member will contain the actual device GUID used for capture.

guidPlaybackDevice
When this type is used in the DirectPlayVoiceClient8.Connect method, this member specifies the GUID of the device used for playback.

When this type is used in the DirectPlayVoiceClient8.GetSoundDeviceConfig method, this member contains the actual device GUID used for playback.

hwndAppWindow
Must be set to the handle of the window that will be used to determine focus for sound playback. See DirectSound8.SetCooperativeLevel for information on Microsoft® DirectSound® focus. If you do not have a window to use for focus, use GetDesktopWindowHandle to use the desktop window.
lFlags
Combination of the flags from the CONST_DVSOUNDEFFECT enumeration.
lMainBufferFlags
Flags values taken from the CONST_DSBPLAYFLAGS enumeration that specify how to play the buffer.
lMainBufferPriority
Passed directly to the dwPriority parameter of the DirectSoundSecondaryBuffer8.Play method when Play is called on the main buffer.
MainSoundBuffer
DirectSoundSecondaryBuffer8 object, which is used to create the Microsoft DirectPlay® Voice main buffer. This parameter can be either NULL or a user-created DirectSound buffer. If this member is set to NULL, DirectPlay Voice will create a buffer for the main voice buffer. If users specify a buffer here, DirectPlay Voice will use their buffer for the main voice buffer.
  • The buffer must be 22 kilohertz, 16-bit, Mono format.
  • The buffer must be at least 1 second in length.
  • The buffer must have been created with the DSBCAPS_GETCURRENTPOSITION2 and DSBCAPS_CTRL3D flags.
  • The buffer must not be a primary buffer.
  • The buffer must not be playing when it is passed to DirectPlay.
  • The buffer must not be locked when it is passed to DirectPlay.


Enumerations

Microsoft® DirectPlay® uses enumerations to group constants in order to take advantage of the statement completion feature of Microsoft® Visual Basic® . The enumerations used in DirectPlay are:

  • CONST_DPLAYBUFSIZE
  • CONST_DPLCONNECT
  • CONST_DPLSESSION
  • CONST_DPNCANCELFLAGS
  • CONST_DPNENUMCLIENTGROUPFLAGS
  • CONST_DPNERR
  • CONST_DPNGROUPINFOFLAGS
  • CONST_DPNINFO
  • CONST_DPNLOBBY
  • CONST_DPNMESSAGEID
  • CONST_DPNOPERATIONS
  • CONST_DPNPLAYERGROUPFLAGS
  • CONST_DPNPLAYINFOFLAGS
  • CONST_DPNSENDFLAGS
  • CONST_DPNSESSIONFLAGS
  • CONST_DPNSPCAPS
  • CONST_DPNWAITTIME
  • CONST_DVBUFFERAGGRESSIVENESS
  • CONST_DVBUFFERQUALITY
  • CONST_DVCLIENTCONFIGENUM
  • CONST_DVERR
  • CONST_DVFLAGS
  • CONST_DVMESSAGE
  • CONST_DVNOTIFY
  • CONST_DVPLAYBACKVOLUME
  • CONST_DVSESSION
  • CONST_DVSESSIONTYPE
  • CONST_DVSOUNDEFFECT
  • CONST_DVTHRESHOLD


CONST_DPLAYBUFSIZE

Used to specify the data type used in buffers.

Enum CONST_DPLAYBUFSIZE
    SIZE_BOOLEAN = 2
    SIZE_BYTE = 1
    SIZE_CURRENCY = 8
    SIZE_DATE = 8
    SIZE_DECIMAL = 14
    SIZE_DOUBLE = 8
    SIZE_INTEGER = 2
    SIZE_LONG = 4
    SIZE_SINGLE = 4
End Enum

Constants

SIZE_BOOLEAN
Size of a BOOLEAN variable, in bytes.
SIZE_BYTE
Size of a BYTE variable, in bytes.
SIZE_CURRENCY
Size of a CURRENCY variable, in bytes.
SIZE_DATE
Size of a DATE variable, in bytes.
SIZE_DECIMAL
Size of a DECIMAL variable, in bytes.
SIZE_DOUBLE
Size of a DOUBLE variable, in bytes.
SIZE_INTEGER
Size of an INTEGER variable, in bytes.
SIZE_LONG
Size of a LONG variable, in bytes.
SIZE_SINGLE
Size of a SINGLE variable, in bytes.


CONST_DPLCONNECT

Used in the lFlags parameter of the DirectPlay8LobbyClient.ConnectApplication method to determine connection behavior.

Enum CONST_DPLCONNECT
    DPLCONNECT_LAUNCHNEW = 1
    DPLCONNECT_LAUNCHNOTFOUND = 2
End Enum

Constants

DPLCONNECT_LAUNCHNEW
Launch a new instance of the application.
DPLCONNECT_LAUNCHNOTFOUND
Launch a new instance of the application if there is no application running that can supply launch settings.


CONST_CONNECTSETTINGS

Used in the DPL_CONNECTION_SETTINGS type.

Enum CONST_CONNECTSETTINGS
    DPLCONNECTSETTINGS_HOST = 1
End Enum

Constants

DPLCONNECTSETTINGS_HOST
Your player is the session host.


CONST_DPLSESSION

Used in the lStatus parameter of the DirectPlay8LobbiedApplication.UpdateStatus method to set the current state of the connection between the lobby client and the lobbied application.

Enum CONST_DPLSESSION
    DPLSESSION_CONNECTED = 1
    DPLSESSION_COULDNOTCONNECT = 2
    DPLSESSION_DISCONNECTED = 3
    DPLSESSION_HOSTMIGRATED = 5
    DPLSESSION_HOSTMIGRATEDHERE = 6
    DPLSESSION_TERMINATED = 4
End Enum

Constants

DPLSESSION_CONNECTED
The lobbied application is currently connected to a session.
DPLSESSION_COULDNOTCONNECT
The lobbied application could not connect to the session.
DPLSESSION_DISCONNECTED
The lobbied application is currently disconnected from the session.
DPLSESSION_HOSTMIGRATED
The host of a peer-to-peer session has migrated. The local client is not the new host.
DPLSESSION_HOSTMIGRATEDHERE
The host of a peer-to-peer session has migrated. The local client is the new host.
DPLSESSION_TERMINATED
The connection between session host and the lobbied application has been terminated.


CONST_DPNCANCELFLAGS

Used in the lFlags parameter of the DirectPlay8Client.CancelAsyncOperation, DirectPlay8Server.CancelAsyncOperation and DirectPlay8Peer.CancelAsyncOperation methods to specify which type of asynchronous operation to cancel.

Enum CONST_DPNCANCELFLAGS
    DPNCANCEL_ALL_OPERATIONS = 32768 (&H8000)
    DPNCANCEL_CONNECT = 1
    DPNCANCEL_ENUM = 2
    DPNCANCEL_SEND = 4
End Enum

Constants

DPNCANCEL_ALL_OPERATIONS
Cancel all asynchronous requests.
DPNCANCEL_CONNECT
Cancel an asynchronous Connect request.
DPNCANCEL_ENUM
Cancel all asynchronous EnumHosts requests. A single EnumHosts request can be canceled by specifying the handle returned from the EnumHosts method.
DPNCANCEL_SEND
Cancel an asynchronous Send request.


CONST_DPNENUMCLIENTGROUPFLAGS

Used in the lFlags parameter of the DirectPlay8Peer.GetCountPlayersAndGroups and the DirectPlay8Server.GetCountPlayersAndGroups methods to determine which type of enumeration to return.

Enum CONST_DPNENUMCLIENTGROUPFLAGS
    DPNENUM_ALL = 17 (&H11)
    DPNENUM_GROUP_MULTICAST = 32 (&H20)
    DPNENUM_GROUPS = 16 (&H10)
    DPNENUM_PLAYERS = 1
End Enum

Constants

DPNENUM_ALL
Return the number of all groups and players.
DPNENUM_GROUP_MULTICAST
Return the number of multicast groups.
DPNENUM_GROUPS
Return the number of groups.
DPNENUM_PLAYERS
Return the number of players.


CONST_DPNERR

Contains the error values for Microsoft® DirectPlay® . For more information, see Error Codes.


CONST_DPNGROUPINFOFLAGS

Describes the settings for a group. This enumeration is used in the lGroupFlags member or the DPN_GROUP_INFO type.

Enum CONST_DPNGROUPINFOFLAGS
    DPNGROUP_AUTODESTRUCT = 1
End Enum

Constants

DPNGROUP_AUTODESTRUCT
Automatically destroy the group when the group creator leaves the group.


CONST_DPNINFO

Used to specify the type of information you set or retrieve from group and player information methods. This enumeration is used in the lInfoFlags member of both the DPN_GROUP_INFO and DPN_PLAYER_INFO types.

Enum CONST_DPNINFO
    DPNINFO_DATA = 2
    DPNINFO_NAME = 1
End Enum

Constants

DPNINFO_DATA
The information is data set for the player or group.
DPNINFO_NAME
The information is the name of the player or group.


CONST_DPNLOBBY

Used with the lFlags parameter of the DirectPlay8Client.RegisterLobby method. Set one of the two values to indicate whether the application is to be registered or unregistered.

Enum CONST_DPNLOBBY
    DPNLOBBY_REGISTER = 1
    DPNLOBBY_UNREGISTER = 2
End Enum

Constants

DPNLOBBY_REGISTER
Register the application with the lobby.
DPNLOBBY_UNREGISTER
Unregister the application with the lobby.


CONST_DPNMESSAGEID

Contains message identification flags that are used by some of the methods of the DirectPlay8Event class. For more information, see the DirectPlay8Event.AddRemovePlayerGroup, and DirectPlay8Event.InfoNotify methods.

Enum CONST_DPNMESSAGEID
    DPN_MSGID_ADD_PLAYER_TO_GROUP = -65528 (&HFFFF0008)
    DPN_MSGID_APPLICATION_DESC = -65526 (&HFFFF000A)
    DPN_MSGID_ASYNC_OP_COMPLETE = -65533 (&HFFFF0003)
    DPN_MSGID_CLIENT_INFO = -65524 (&HFFFF000C)
    DPN_MSGID_CONNECT_COMPLETE = -65520 (&HFFFF0010)
    DPN_MSGID_CREATE_GROUP = -65530 (&HFFFF0006)
    DPN_MSGID_CREATE_PLAYER = -65529 (&HFFFF0007)
    DPN_MSGID_DESTROY_GROUP = -65528 (&HFFFF0007)
    DPN_MSGID_DESTROY_PLAYER = -65527 (&HFFFF0005)
    DPN_MSGID_ENUM_HOSTS_QUERY = -65516 (&HFFFF0014)
    DPN_MSGID_ENUM_HOSTS_RESPONSE = -65515 (&HFFFF0015)
    DPN_MSGID_GROUP_INFO = -65522 (&HFFFF000E)
    DPN_MSGID_HOST_MIGRATE =  -65523 (&HFFFF000D)
    DPN_MSGID_INDICATE_CONNECT = -65521 (&HFFFF000F)
    DPN_MSGID_INDICATED_CONNECT_ABORTED = -65521 (&HFFFF000F)
    DPN_MSGID_PEER_INFO = -65525 (&HFFFF000B)
    DPN_MSGID_RECEIVE = -65535 (&HFFFF0001)
    DPN_MSGID_REMOVE_PLAYER_FROM_GROUP = -65518 (&HFFFF0012)
    DPN_MSGID_RETURN_BUFFER = -65517 (&HFFFF0013)
    DPN_MSGID_SEND_COMPLETE = -65534 (&HFFFF0002)
    DPN_MSGID_SERVER_INFO = -65523 (&HFFFF000D)
    DPN_MSGID_TERMINATE_SESSION = -65514 (&HFFFF0016)
End Enum


CONST_DPNOPERATIONS

Contains a set of flags that are used by the methods of the DirectPlay8Client class. See the individual method references for details.

Enum CONST_DPNOPERATIONS
    DPNADDPLAYERTOGROUP_SYNC =  -2147483648 (&H80000000)
    DPNCONNECT_SYNC = -2147483648 (&H80000000)
    DPNCREATEGROUP_SYNC = -2147483648 (&H80000000)
    DPNDESTROYGROUP_SYNC =  -2147483648 (&H80000000)
    DPNENUMHOSTS_SYNC =  -2147483648 (&H80000000)
    DPNHOST_OKTOQUERYFORADDRESSING = 1
    DPNOP_SYNC =  -2147483648 (&H80000000)
    DPNREMOVEPLAYERFROMGROUP_SYNC =  -2147483648 (&H80000000)
    DPNSETCLIENTINFO_SYNC =  -2147483648 (&H80000000)
    DPNSETGROUPINFO_SYNC =  -2147483648 (&H80000000)
    DPNSETPEERINFO_SYNC =  -2147483648 (&H80000000)
    DPNSETSERVERINFO_SYNC =  -2147483648 (&H80000000)
End Enum


CONST_DPNPLAYERGROUPFLAGS

Used by the DirectPlay8Server.SendTo and DirectPlay8Peer.SendTo methods.

Enum CONST_DPNPLAYERGROUPFLAGS
    DPNID_ALL_PLAYERS_GROUP = 0
End Enum

Constants

DPNID_ALL_PLAYERS_GROUP
Send a message to all players in the session.


CONST_DPNPLAYINFOFLAGS

Used in the lPlayerFlags member of the DPN_PLAYER_INFO structure to determine whether the player is a host player or local player.

Enum CONST_DPNPLAYINFOFLAGS
    DPNPLAYER_HOST = 4
    DPNPLAYER_LOCAL = 2
End Enum

Constants

DPNPLAYER_HOST
This information is for the local player.
DPNPLAYER_LOCAL
This player is the host for the application.


CONST_DPNSENDFLAGS

Contains flags that can be set in the DirectPlay8Client.Send, DirectPlay8Server.SendTo, and DirectPlay8Peer.SendTo methods to control how messages are sent.

Enum CONST_DPNSENDFLAGS
    DPNSEND_COMPLETEONPROCESS = 4
    DPNSEND_GUARANTEED = 8
    DPNSEND_NOCOMPLETE = 1
    DPNSEND_NOCOPY = 2
    DPNSEND_NOLOOPBACK = 32 (&H20)
    DPNSEND_NONSEQUENTIAL = 16 (&H10)
    DPNSEND_PRIORITY_HIGH = 128 (&H80)
    DPNSEND_PRIORITY_LOW = 64 (&H40)
    DPNSEND_SYNC = -2147483648 (&H80000000)
End Enum

Constants

DPNSEND_COMPLETEONPROCESS
Call the DirectPlay8Event.SendComplete method in the message handler when this message has been delivered to the target and the target's message handler returns from indicating its reception. There is additional internal message overhead when this flag is set, and the message transmission process may become significantly slower. If you set this flag, DPNSEND_GUARANTEED must also be set.
DPNSEND_GUARANTEED
Send the message by a guaranteed method of delivery.
DPNSEND_NOCOMPLETE
Do not call the DirectPlay8Event.SendComplete method in the sender's message handler. There is additional internal message overhead when this flag is set, and the message sends process is significantly slower. This flag cannot be combined with DPNSEND_NOCOPY.
DPNSEND_NOCOPY
Use the data in the buffer() parameter type and do not make an internal copy. This might be a more efficient method of sending data. However, it is less robust because the sender might be able to modify the message before the receiver has processed it. This flag cannot be combined with DPNSEND_NOCOMPLETE or DPNSEND_GUARANTEED.
DPNSEND_NOLOOPBACK
Do not call the DirectPlay8Event.Receive method in your message handler when you are sending to yourself. This flag is useful if you are broadcasting to the entire session, or you are sending a message to a group that you are a member of.
DPNSEND_NONSEQUENTIAL
Messages are delivered to the target application in the order that they are received. If the flag is not set, messages are delivered to the target application in the order that they are sent, which may necessitate buffering out-of-sequence messages until the missing messages arrive.
DPNSEND_PRIORITY_HIGH
Sets the priority of the message to high.
DPNSEND_PRIORITY_LOW
Sets the priority of the message to low.
DPNSEND_SYNC
Process the SendTo request synchronously.


CONST_DPNGETSENDQUEUEINFO

Used with the lFlags parameter of DirectPlay8Client.GetSendQueueInfo. Setting one of these flags instructs the method to only return send-queue information on the associated send queue instead of the total for all queues.

Enum CONST_DPNGETSENDQUEUEINFO
    DPNGETSENDQUEUEINFO_PRIORITY_HIGH = 2
    DPNGETSENDQUEUEINFO_PRIORITY_LOW = 4
    DPNGETSENDQUEUEINFO_PRIORITY_NORMAL = 1
End Enum

Constants

DPNGETSENDQUEUEINFO_PRIORITY_HIGH
Return information for the high-priority queue.
DPNGETSENDQUEUEINFO_PRIORITY_LOW
Return information for the low-priority queue.
DPNGETSENDQUEUEINFO_PRIORITY_NORMAL
Return information for the normal-priority queue.


CONST_DPNSESSIONFLAGS

Used in the lFlags member of the DPN_APPLICATION_DESC type to specify the type of session.

Enum CONST_DPNSESSIONFLAGS
    DPNSESSION_CLIENT_SERVER = 1
    DPNSESSION_MIGRATE_HOST = 4
    DPNSESSION_NODPNSVR = 64 (&H40)
    DPNSESSION_REQUIREPASSWORD = 128 (&H80)
End Enum

Constants

DPNSESSION_CLIENT_SERVER
Specify that this type of session is client/server. This flag cannot be combined with DPNSESSION_MIGRATE_HOST.
DPNSESSION_MIGRATE_HOST
Enable host migration. This flag is used in peer-to-peer sessions. This flag cannot be combined with DPNSESSION_CLIENT_SERVER.
DPNSESSION_NODPNSVR
Specify that you do not want enumerations forwarded to your host from DPNSVR.
DPNSESSION_REQUIREPASSWORD
Specify that the session is password protected. If this flag is set, the Password member of the DPN_APPLICATION_DESC type must be a valid string.


CONST_DPNSPCAPS

Used by the DPN_SP_CAPS type.

Enum CONST_DPNSPCAPS
    DPNSPCAPS_SUPPORTSALLADAPTERS = 4
    DPNSPCAPS_SUPPORTSBROADCAST = 2
    DPNSPCAPS_SUPPORTSDPNSRV = 1
End Enum

Constants

DPNSPCAPS_SUPPORTSALLADAPTERS
The service provider is supported on all the adapters present on the system.
DPNSPCAPS_SUPPORTSBROADCAST
On IP and IPX applications, the service provider has the ability to broadcast to find games if not enough addressing information is passed.
DPNSPCAPS_SUPPORTSDPNSRV
DPNSVR.EXE will provide port sharing for the given SP. Currently this flag is available on IP and IPX only.


CONST_DPNWAITTIME

Used by the DirectPlay8Client.EnumHosts, and DirectPlay8Peer.EnumHosts methods.

Enum CONST_DPNWAITTIME
    INFINITE = -1 (&HFFFFFFFF)
End Enum

Constants

INFINITE
Wait until the enumeration is canceled.


CONST_DVBUFFERAGGRESSIVENESS

Contains flags used in the lBufferAggressiveness member of the DVCLIENTCONFIG type. For most applications, this can be set to DVBUFFERAGGRESSIVENESS_DEFAULT. It can also be set to anything in the range of DVBUFFERAGGRESSIVENESS_MIN and DVBUFFERAGGRESSIVENESS_MAX. In general, the higher the value, the quicker the adaptive buffering adjusts to changing conditions. The lower the value, the slower the adaptive buffering adjusts to changing conditions.

Enum CONST_DVBUFFERAGGRESSIVENESS
    DVBUFFERAGGRESSIVENESS_DEFAULT = 0
    DVBUFFERAGGRESSIVENESS_MAX = 100 (&H64)
    DVBUFFERAGGRESSIVENESS_MIN = 1
End Enum

Constants

DVBUFFERAGGRESSIVENESS_DEFAULT
The default buffer aggressiveness value.
DVBUFFERAGGRESSIVENESS_MAX
The maximum buffer aggressiveness value.
DVBUFFERAGGRESSIVENESS_MIN
The minimum buffer aggressiveness value.


CONST_DVBUFFERQUALITY

Contains flags used in the lBufferQuality member of the DVCLIENTCONFIG type. For most applications, this should be set to DVBUFFERQUALITY_DEFAULT. It can be set to anything in the range of DVBUFFERQUALITY_MIN to DVBUFFERQUALITY_MAX. In general, the higher the value, the higher the quality of the voice but the also higher the latency. The lower the value, the lower the latency but also the lower the quality.

Enum CONST_DVBUFFERQUALITY
    DVBUFFERQUALITY_DEFAULT = 0
    DVBUFFERQUALITY_MAX = 100 (&H64)
    DVBUFFERQUALITY_MIN = 1
End Enum

Constants

DVBUFFERQUALITY_DEFAULT
The default buffer quality value.
DVBUFFERQUALITY_MAX
The maximum buffer quality value.
DVBUFFERQUALITY_MIN
The minimum buffer quality value.


CONST_DVCLIENTCONFIGENUM

Used in the lFlags member of the DVCLIENTCONFIG type to control voice transmission behavior.

Enum CONST_DVCLIENTCONFIGENUM
    DVCLIENTCONFIG_AUTORECORDVOLUME = 8
    DVCLIENTCONFIG_AUTOVOICEACTIVATED = 32 (&H20)
    DVCLIENTCONFIG_ECHOSUPPRESSION = 134217728 (&H8000000)
    DVCLIENTCONFIG_MANUALVOICEACTIVATED = 4
    DVCLIENTCONFIG_MUTEGLOBAL = 16 (&H10)
    DVCLIENTCONFIG_PLAYBACKMUTE = 2
    DVCLIENTCONFIG_RECORDMUTE = 1
End Enum

Constants

DVCLIENTCONFIG_AUTORECORDVOLUME
Activate automatic gain control. With automatic gain control, Microsoft® DirectPlay® Voice adjusts the hardware input volume on your sound card automatically to get the best input level possible. You can determine the current input volume by looking at the lRecordVolume member after a call to DirectPlayVoiceClient8.GetClientConfig.
DVCLIENTCONFIG_AUTOVOICEACTIVATED
Place the transmission control system into automatic voice activation mode. In this mode, the sensitivity of voice activation is determined automatically by the system. The input level is adaptive, adjusting itself automatically to the input signal. For most applications this should be the setting used. This flag and the DVCLIENTCONFIG_MANUALVOICEACTIVATED flag are mutually exclusive.
DVCLIENTCONFIG_ECHOSUPPRESSION
Activate the echo suppression mode. This mode reduces echo introduced by configurations with external speakers and extremely sensitive microphones. While remote player's voices are being played back on the local speaker, the microphone is automatically muted. If the local player is transmitting, then the playback of remote player voices is buffered until local input stops. After local input stops, playback resumes.
DVCLIENTCONFIG_MANUALVOICEACTIVATED
Place the transmission control system into manual voice activation mode. In this mode, transmission of voice begins when the input level passes the level specified by the lThreshold member of the DVCLIENTCONFIG type. When input levels drop below the specified level, transmission stops. This flag is mutually exclusive with the DVCLIENTCONFIG_AUTOVOICEACTIVATED flag.
DVCLIENTCONFIG_MUTEGLOBAL
Mute playback of the main sound buffer. Only sound buffers created through calls to DirectPlayVoiceClient8.Create3DSoundBuffer will be heard.
DVCLIENTCONFIG_PLAYBACKMUTE
Mute the playback of all DirectPlay Voice output and stop playback. This also stops decompression of incoming packets so CPU usage is reduced. Packets are effectively discarded while this flag is specified.
DVCLIENTCONFIG_RECORDMUTE
Mute the input from the microphone and stop recording. This also stops compression so CPU usage is reduced.

In addition to the preceding flags, the method of transmission is controlled by setting only one of the following flags or by not specifying either flag.

If you do not specify either DVCLIENTCONFIG_MANUALVOICEACTIVATED or DVCLIENTCONFIG_AUTOVOICEACTIVATED, the system will operate in push-to-talk mode. In push-to-talk mode, as long as there is a valid target specified the input from the microphone will be transmitted. Voice transmission stops when a NULL target is set or the current target leaves the session or is destroyed.


CONST_DVERR

Contains the error values for Microsoft® DirectPlay® Voice. For more information, see Error Codes.


CONST_DVFLAGS

Used by various Microsoft® DirectPlay® voice methods.

Enum CONST_DVFLAGS
    DVFLAGS_ALLOWBACK = 16 (&H10)
    DVFLAGS_NOHOSTMIGRATE = 8
    DVFLAGS_QUERYONLY = 2
    DVFLAGS_SYNC = 1
End Enum

Constants

DVFLAGS_ALLOWBACK
Enable the Back button on the wizard's Welcome page. If the user clicks the Back button on the Welcome page, the wizard exits, and CheckAudioSetup returns DVERR_USERBACK.
DVFLAGS_NOHOSTMIGRATE
The voice host will not migrate regardless of session and transport settings. Use this flag when you want to shut down the voice session completely.
DVFLAGS_QUERYONLY
Audio setup is not run. Instead, the method checks the registry to see if the devices have been tested. If the devices have not been tested, the method returns DVERR_RUNSETUP. If the devices have been tested, the method returns DV_FULLDUPLEX if the devices support full duplex audio, or DV_HALFDUPLEX if the devices do not support full duplex audio.
DVFLAGS_SYNC
Do not return until the operation is completed.


CONST_DVMESSAGE

Not used.

Enum CONST_DVMESSAGE
    DVID_ALLPLAYERS = 0
    DVID_NOTARGET = -1 (&HFFFFFFFF)
    DVID_REMAINING = -1 (&HFFFFFFFF)
    DVID_SERVERPLAYER = 1
    DVID_SYS = 0
    DVMSGID_BASE = 0
    DVMSGID_CONNECTRESULT = 8
    DVMSGID_CREATEVOICEPLAYER = 1
    DVMSGID_DELETEVOICEPLAYER = 2
    DVMSGID_DISCONNECTRESULT = 9
    DVMSGID_HOSTMIGRATED = 14
    DVMSGID_INPUTLEVEL = 12
    DVMSGID_MAXBASE = 16 (&H10)
    DVMSGID_MINBASE = 1
    DVMSGID_OUTPUTLEVEL = 13
    DVMSGID_PLAYEROUTPUTLEVEL = 16 (&H10)
    DVMSGID_PLAYERVOICESTART = 4
    DVMSGID_PLAYERVOICESTOP = 5
    DVMSGID_RECORDSTART = 6
    DVMSGID_RECORDSTOP = 7
    DVMSGID_SESSIONLOST = 3
    DVMSGID_SETTARGET = 15
    DVMSGID_STARTSESSIONRESULT = 10
    DVMSGID_STOPSESSIONRESULT = 11
End Enum


CONST_DVNOTIFY

Used by the DVCLIENTCONFIG type.

Enum CONST_DVNOTIFY
    DVNOTIFYPERIOD_MINPERIOD = 20 (&H14)
End Enum

Constants

DVNOTIFYPERIOD_MINPERIOD
Specifies the minimum period between messages that is allowed.


CONST_DVPLAYBACKVOLUME

Used by the DVCLIENTCONFIG type.

Enum CONST_DVPLAYBACKVOLUME
    DVPLAYBACKVOLUME_DEFAULT = 0
End Enum

Constants

CONST_DVPLAYBACKVOLUME
Use a default value that is appropriate for most situations.


CONST_DVSESSION

Used in the lFlags member of the DVSESSIONDESC type to control session behavior.

Enum CONST_DVSESSION
    DVSESSION_NOHOSTMIGRATION = 1
    DVSESSION_SERVERCONTROLTARGET = 2
End Enum

Constants

DVSESSION_NOHOSTMIGRATION
The voice host will not migrate regardless of the transport settings. If this flag is not specified, the voice host will migrate if the transport supports it.
DVSESSION_SERVERCONTROLTARGET
Only the server player can control the clients' speech target. If the server player does not specify this flag, only the clients can control their speech target. This flag can be specified only in multicast and mixing sessions.


CONST_DVSESSIONTYPE

Used in the lSessionType member of the DVSESSIONDESC type to specify the type of Microsoft® DirectPlay® Voice session to run. The DVSESSIONTYPE_PEER flag is not available in client/server sessions; all other flags are valid for all session types.

Type CONST_DVSESSIONTYPE
    DVSESSIONTYPE_ECHO = 4
    DVSESSIONTYPE_MIXING = 2
    DVSESSIONTYPE_FORWARDING = 3
    DVSESSIONTYPE_PEER = 1
End Type

Constants

DVSESSIONTYPE_ECHO
Voice messages will be echoed back to the player.
DVSESSIONTYPE_MIXING
The voice session will use a mixing server. In this mode of operation, all voice messages are sent to the server, which mixes them and forwards a single, premixed stream to each client. This reduces the bandwidth and CPU usage on clients significantly at the cost of increased bandwidth and CPU usage on the server.
DVSESSIONTYPE_FORWARDING
Voice messages will be routed through the session host. This saves bandwidth on the clients at the expense of bandwidth usage on the server. This option is useful only if the session host has a high-speed connection.
DVSESSIONTYPE_PEER
Voice messages will be sent directly between players.


CONST_DVSOUNDEFFECT

Used in the lFlags member of the DVSOUNDDEVICECONFIG type to control sound behavior.

Enum CONST_DVSOUNDEFFECT
    DVSOUNDCONFIG_AUTOSELECT = 2
    DVSOUNDCONFIG_HALFDUPLEX = 4
    DVSOUNDCONFIG_NOFOCUS = 536870912 (&H20000000)
    DVSOUNDCONFIG_NORECVOLAVAILABLE = 16 (&H10)
    DVSOUNDCONFIG_NORMALMODE = 1
    DVSOUNDCONFIG_SETCONVERSIONQUALITY = 8
    DVSOUNDCONFIG_STRICTFOCUS = 1073741824 (&H40000000)
End Enum

Constants

DVSOUNDCONFIG_AUTOSELECT
Tell Microsoft® DirectPlay® Voice to attempt to automatically select (or unmute) the microphone line in the mixer for the specified recording device.
DVSOUNDCONFIG_HALFDUPLEX
Tell DirectPlay Voice to initialize itself in half-duplex mode. In half-duplex mode no recording takes place. If the initialization of the sound system fails in full-duplex mode, this flag will be set by the system.
DVSOUNDCONFIG_NOFOCUS
Not enabled for this release.
DVSOUNDCONFIG_NORECVOLAVAILABLE
Indicate that the recording volume cannot be modified.
DVSOUNDCONFIG_NORMALMODE
Tell DirectPlay Voice to use Microsoft DirectSound® Normal Mode when initializing the DirectSound object. If this flag is not specified the DirectSound object is initialized with DirectSound Priority Mode. See documentation for DirectSound8.SetCooperativeLevel for more information.
DVSOUNDCONFIG_SETCONVERSIONQUALITY
Enable better quality audio at the expense of higher CPU usage.
DVSOUNDCONFIG_STRICTFOCUS
Not enabled for this release.


CONST_DVTHRESHOLD

Used in the lThreshold member of the DVCLIENTCONFIG type to specify the input level used to trigger voice transmission if the DVCLIENTCONFIG_MANUALVOICEACTIVATED flag is specified in the lFlags member. When the flag is specified, this value can be set to anywhere in the range of DVTHRESHOLD_MIN to DVTHRESHOLD_MAX. Additionally, DVTHRESHOLD_DEFAULT can be set to use a default value.

If DVCLIENTCONFIG_MANUALVOICEACTIVATED or DVCLIENTCONFIG_AUTOVOICEACTIVATED is not specified in the lFlags member of this structure (indicating push-to-talk mode), this value must be set to DVTHRESHOLD_UNUSED.

Enum CONST_DVTHRESHOLD
    DVTHRESHOLD_DEFAULT = -1 (&HFFFFFFFF)
    DVTHRESHOLD_MAX = 99 (&H63)
    DVTHRESHOLD_MIN = 0
    DVTHRESHOLD_UNUSED = -2 (&HFFFFFFFE)
End Enum

Constants

DVTHRESHOLD_DEFAULT
Default threshold value.
DVTHRESHOLD_MAX
Maximum threshold value.
DVTHRESHOLD_MIN
Minimum threshold value.
DVTHRESHOLD_UNUSED
Must be set for push-to-talk mode.


Error Codes

This table lists the error codes that can be returned by Microsoft® DirectPlay® methods and functions. Errors are represented by negative values and cannot be combined.

For a list of the errors each method or function can raise, see the individual descriptions. Lists of error codes in the documentation are necessarily incomplete. For example, any DirectPlay method can return DPERR_OUTOFMEMORY even though the error code is not explicitly listed as a possible return value in the documentation for that method.

DPNERR_ABORTED
The operation was canceled before it could be completed.
DPNERR_ADDRESSING
The address specified is invalid.
DPNERR_ALREADYCONNECTED
The object is already connected to the session.
DPNERR_ALREADYCLOSING
An attempt to call Close on a session has been made more than once.
DPNERR_ALREADYDISCONNECTING
The client is already disconnecting from the session.
DPNERR_ALREADYINITIALIZED
The object has already been initialized.
DPNERR_ALREADYREGISTERED
A message handler has already been registered. You must unregister the current handler before registering a new one.
DPNERR_BUFFERTOOSMALL
The supplied buffer is not large enough to contain the requested data.
DPNERR_CANNOTCANCEL
The operation could not be canceled.
DPNERR_CANTCREATEGROUP
A new group cannot be created.
DPNERR_CANTCREATEPLAYER
A new player cannot be created.
DPNERR_CANTLAUNCHAPPLICATION
The lobby cannot launch the specified application.
DPNERR_CONNECTING
The method is in the process of connecting to the network.
DPNERR_CONNECTIONLOST
The service provider connection was reset while data was being sent.
DPNERR_DOESNOTEXIST
Requested element is not part of the address.
DPNERR_EXCEPTION
An exception occurred when processing the request.
DPNERR_GENERIC
An undefined error condition occurred.
DPNERR_GROUPNOTEMPTY
The specified group is not empty.
DPNERR_HOSTING
DPNERR_HOSTREJECTEDCONNECTION
The connection request was rejected. Check the ReplyData member of the DPNMSG_CONNECT_COMPLETE type for details.
DPNERR_HOSTTERMINATEDSESSION
The host terminated the session.
DPNERR_INCOMPLETEADDRESS
The address specified is not complete.
DPNERR_INVALIDADDRESSFORMAT
The address format is invalid.
DPNERR_INVALIDAPPLICATION
The GUID supplied for the application is invalid.
DPNERR_INVALIDCOMMAND
The command specified is invalid.
DPNERR_INVALIDFLAGS
The flags passed to this method are invalid.
DPNERR_INVALIDGROUP
The group ID is not recognized as a valid group ID for this game session.
DPNERR_INVALIDHANDLE
The handle specified is invalid.
DPNERR_INVALIDINSTANCE
The GUID for the application instance is invalid.
DPNERR_INVALIDINTERFACE
The interface parameter is invalid. This value will be returned in a connect request if the connecting player was not a client in a client/server game or a peer in a peer-to-peer game.
DPNERR_INVALIDLOCALADDRESS
The address for the local computer or adapter is invalid.
DPNERR_INVALIDOBJECT
The DirectPlay object pointer is invalid.
DPNERR_INVALIDPARAM
One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPASSWORD
An invalid password was supplied when attempting to join a session that requires a password.
DPNERR_INVALIDPLAYER
The player ID is not recognized as a valid player ID for this game session.
DPNERR_INVALIDPOINTER
Pointer specified as a parameter is invalid.
DPNERR_INVALIDPRIORITY
The specified priority is not within the range of allowed priorities, which is inclusively from 0 through 65535.
DPNERR_INVALIDSTRING
String specified as a parameter is invalid.
DPNERR_INVALIDREMOTEADDRESS
The specified remote address is invalid.
DPNERR_INVALIDURL
Specified string is not a valid DirectPlay URL.
DPNERR_INVALIDVERSION
There was an attempt to connect to an invalid version of DirectPlay.
DPNERR_NOCAPS
The communication link that DirectPlay is attempting to use is not capable of this function.
DPNERR_NOCONNECTION
No communication link was established.
DPNERR_NOHOSTPLAYER
There is currently no player acting as the host of the session.
DPNERR_NOINTERFACE
The interface is not supported.
DPNERR_NORESPONSE
There was no response from the specified target.
DPNERR_NOTALLOWED
The object is read-only; this function is not allowed on this object.
DPNERR_NOTHOST
The client attempted to connect to a nonhost computer. Additionally, this error value may be returned by a nonhost that tried to set the application description.
DPNERR_OUTOFMEMORY
There is insufficient memory to perform the requested operation.
DPNERR_PENDING
Not an error, this return indicates that an asynchronous operation has reached the point where it is successfully queued.
DPNERR_PLAYERLOST
A player has lost the connection to the session.
DPNERR_SENDTOOLARGE
The buffer was too large.
DPNERR_SESSIONFULL
The request to connect to the host or server failed because the maximum number of players allotted for the session has been reached.
DPNERR_TIMEDOUT
The operation could not complete because it has timed out.
DPNERR_UNINITIALIZED
The requested object has not been initialized.
DPNERR_UNSUPPORTED
The function or feature is not available in this implementation or on this service provider.
DPNERR_USERCANCEL
The user canceled the operation.
DV_OK
The request completed successfully.
DV_FULLDUPLEX
The sound card is capable of full-duplex operation.
DV_HALFDUPLEX
The sound card can be run only in half-duplex mode.
DVERR_BUFFERTOOSMALL
The supplied buffer is not large enough to contain the requested data.
DVERR_EXCEPTION
An exception occurred when processing the request.
DVERR_GENERIC
An undefined error condition occurred.
DVERR_INVALIDFLAGS
The flags passed to this method are invalid.
DVERR_INVALIDOBJECT
The DirectPlay object pointer is invalid.
DVERR_INVALIDPARAM
One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPLAYER
The player ID is not recognized as a valid player ID for this game session.
DVERR_INVALIDGROUP
The group ID is not recognized as a valid group ID for this game session.
DVERR_INVALIDHANDLE
The handle specified is invalid.
DVERR_OUTOFMEMORY
There is insufficient memory to perform the requested operation.
DVERR_PENDING
Not an error, this return indicates that an asynchronous operation has reached the point where it is successfully queued.
DVERR_NOTSUPPORTED
The operation is not supported.
DVERR_NOINTERFACE
The specified interface is not supported. This error could indicate that you are using an earlier version of DirectX that does not expose the interface.
DVERR_SESSIONLOST
The transport has lost the connection to the session.
DVERR_NOVOICESESSION
The session specified is not a voice session.
DVERR_CONNECTIONLOST
The connection to the voice session has been lost.
DVERR_NOTINITIALIZED
The DirectPlayVoiceClient8.Initialize or DirectPlayVoiceServer8.Initialize method must be called before calling this method.
DVERR_CONNECTED
The DirectPlay Voice object is connected.
DVERR_NOTCONNECTED
The DirectPlay Voice object is not connected.
DVERR_CONNECTABORTING
The connection is being disconnected.
DVERR_NOTALLOWED
The object does not have the permission to perform this operation.
DVERR_INVALIDTARGET
The specified target is not a valid player ID or group ID for this voice session.
DVERR_TRANSPORTNOTHOST
The object is not the host of the voice session.
DVERR_COMPRESSIONNOTSUPPORTED
The specified compression type is not supported on the local computer.
DVERR_ALREADYPENDING
An asynchronous call of this type is already pending.
DVERR_ALREADYINITIALIZED
The object has already been initialized.
DVERR_SOUNDINITFAILURE
A failure was encountered initializing the sound card.
DVERR_TIMEOUT
The operation could not be performed in the specified time.
DVERR_CONNECTABORTED
The connect operation was canceled before it could be completed.
DVERR_NO3DSOUND
The local computer does not support 3-D sound.
DVERR_ALREADYBUFFERED
There is already a user buffer for the specified ID.
DVERR_NOTBUFFERED
There is no user buffer for the specified ID.
DVERR_HOSTING
The object is the host of the session.
DVERR_NOTHOSTING
The object is not the host of the session.
DVERR_INVALIDDEVICE
The specified device is invalid.
DVERR_RECORDSYSTEMERROR
An error in the recording system occurred.
DVERR_PLAYBACKSYSTEMERROR
An error in the playback system occurred.
DVERR_SENDERROR
An error occurred while sending data.
DVERR_USERCANCEL
The user canceled the operation.
DVERR_UNKNOWN
An unknown error occurred.
DVERR_RUNSETUP
The specified audio configuration has not been tested. Call the DirectPlayVoiceTest8.CheckAudioSetup method.
DVERR_INCOMPATIBLEVERSION
The client connected to a voice session that is incompatible with the host.
DVERR_INITIALIZED
The Initialize method failed because the object has already been initialized.
DVERR_INVALIDPOINTER
The pointer specified is invalid.
DVERR_NOTRANSPORT
The specified object is not a valid transport.
DVERR_NOCALLBACK
This operation cannot be performed because no callback function was specified.
DVERR_TRANSPORTNOTINIT
The specified transport is not yet initialized.
DVERR_TRANSPORTNOSESSION
The specified transport is valid but is not connected/hosting.
DVERR_TRANSPORTNOPLAYER
The specified transport is connected/hosting but no local player exists.


DirectSetup

This section provides information about the Microsoft® DirectSetup component of the Microsoft® DirectX® application programming interface (API) in the Platform Software Development Kit (SDK) or the stand-alone DirectX SDK. Most of this section is oriented towards C++ developers. For information on Microsoft® Visual Basic® setup, see Installing DirectX for Visual Basic Applications.

This section includes the following topics:

  • DirectSetup Essentials
  • Installing DirectX for Visual Basic Applications
    •
  • DXVBSetup Sample
    •

About DirectSetup

DirectSetup is a simple API that provides one-call installation of the DirectX components. This is more than a convenience—DirectX is a complex product and installing it is an involved task. You should not attempt to install DirectX manually.

DirectSetup includes several API functions and structures. It also includes a prototype DirectXSetupCallbackFunction that can be defined by an application to customize the user interface during the installation process. The DirectX SDK includes a sample application that demonstrates the use of this callback function.


DirectSetup Essentials

This section contains general information about the Microsoft® DirectSetup component. The following topics are discussed:

  • Setup Overview for DirectSetup
  • Preparing the Setup Folder
  • Customizing Setup
  • Testing the Setup Program
  • Enabling AutoPlay


Setup Overview for DirectSetup

Applications and games that depend on Microsoft® DirectX® use the DirectXSetup function to install the necessary system components into an existing Microsoft Windows® installation. The function optionally updates the display and audio drivers for optimal support of DirectX. Typically, you would call DirectXSetup from the program that you are using to install your own application files.

Note The DirectXSetup function overwrites system components from previous versions of DirectX. For example, if you install DirectX 8.1 on a system that already has DirectX 7.0 components, all DirectX 7.0 components are overwritten. Because all DirectX components comply with Component Object Model (COM) backward-compatibility rules, software written for DirectX 7.0 continues to function properly.

The DirectXSetup function can tell when DirectX components, display drivers, and audio drivers need to be upgraded. It can also distinguish whether or not these components can be upgraded without adversely affecting the Windows operating system. This is said to be a safe upgrade. The upgrade is safe for the operating system, not necessarily for the applications running on the computer. Some hardware-dependent applications can be negatively affected by an upgrade that is safe for Windows.

By default, the DirectXSetup function performs only safe upgrades. If the upgrade of a device driver might adversely affect the operation of Windows, the upgrade is not performed.

During the setup process, DirectSetup creates a backup copy of the system components and drivers that are replaced. These can be restored if problems occur.

When display or audio drivers are upgraded, the DirectXSetup function uses a database created by Microsoft to manage the process. The database contains information on existing drivers that are provided by Microsoft, the manufacturers of the hardware, or the vendors of the hardware. This database describes the upgrade status of each driver, based on testing done at Microsoft and other sites.

Check the value returned by DirectXSetup. If it is DSETUPERR_SUCCESS_RESTART, notify the user that changes do not take effect without a restart, and offer the choice of restarting immediately. See Dinstall.c in the Dinstall Sample sample application for an example of how to do this.


Preparing the Setup Folder

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—that is, the directory where your setup program resides.

The root directory must contain Dsetup.dll and Dsetup32.dll. It must also have a folder named "DirectX" (this name is not case sensitive), containing all the redistributable files and drivers. To create the proper structure on your application setup disk, copy the entire contents of the Dxf\Redist\DirectX8 folder on the Microsoft® DirectX® SDK disk into the root path of your setup program. This folder was not copied to your development computer when you installed the SDK, so you have to get it from the original disk.


Customizing Setup

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

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 Microsoft® Win32® 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 and device driver that can be installed or upgraded.

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 MessageBox or standard Microsoft® Windows® 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.


Testing the Setup Program

To test the Microsoft® DirectSetup component of your setup program, compile a version in which the DSETUP_TESTINSTALL flag is passed to the DirectXSetup function. Set up the installation directory, as described in Preparing the Setup Folder.

When you run your setup program, DirectSetup goes through the motions of installing Microsoft® DirectX®, including calls to a callback function if you have provided one, without actually installing any components.


Enabling AutoPlay

If you are building an AutoPlay compact disc title, copy the Autorun.inf file in the root directory of the Microsoft® DirectX® 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.


Installing DirectX for Visual Basic Applications

Although you can use the Microsoft® DirectSetup functions in your Microsoft® Visual Basic® application by declaring references to the functions in your module, the recommended method is to use the Distribution Wizard. To distribute your application through a compact disc, follow these steps.

Distributing your Visual Basic application

  1. Start the Distribution Wizard.
  2. Remove DX8VB.dll from the dependency list.
  3. Add all the DirectX 8 redistributable files. They are located in the \DXF\Redist\DirectX8 folder on the Microsoft® DirectX® 8 SDK CD.
  4. Click Finish to exit the Distribution Wizard.
  5. Overwrite the Setup1.exe file created by the Distribution Wizard with Setup1.exe from the \DXF\Samples\Multimedia\VBSamples\Misc\bin folder on the DirectX 8 SDK CD.
  6. If you are using Visual Basic 5.0, use the compress utility to compress Setup1.exe to Setup1.ex_. If you are developing on Visual Basic 6.0, run the batch file created by the Distribution Wizard.

The files are now ready to be distributed through a compact disc.


DXVBSetup Sample

Description

The DXVBSetup sample shows how Microsoft® DirectSetup can be used by a Microsoft® Visual Basic® application.

Path

(SDK root)\Samples\Multimedia\VBSamples\Misc\DXSetup

User's Guide

The setup application directory should have a subfolder called Setup containing Dsetup.dll and Dsetup32.dll. It must also have a folder named "DirectX" (this name is not case sensitive) containing all the redistributable files and drivers. To create the proper structure on your application setup disc, copy the entire contents of the \Redist\DirectX8 folder on the Microsoft® DirectX® SDK disc into the root path of your setup program. Note that because this folder was not copied to your development computer when you installed the SDK, you have to get it from the original disc.


Glossary

This section provides a glossary of technical terms used in the Microsoft® DirectX® software development kit (SDK) documentation.

A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z


A

alpha channel
The opacity of an image defined by an alpha value per pixel interleaved with the color components (for example, ARGB), an alpha value per pixel stored in a separate alpha surface, or a constant alpha value for the entire surface.
alpha color component
The portion of a 32-bit color that determines its opacity. In this case, the alpha value per pixel is interleaved with the color components (for example, ARGB). Less commonly, this term can also refer to an image with an alpha value per pixel stored in a separate alpha surface.
alpha constant
A level of opacity (alpha value) applied to an entire surface.
alpha edge blend
A particular use of alpha blending (and alpha channel information) to reduce aliasing by blending edges, based on pixel coverage information.
ambient
Description of a light source that illuminates everything in a scene, regardless of the orientation, position, and surface characteristics of the objects in the scene. Because it illuminates a scene with equal strength everywhere, the position and orientation of the frame that an ambient light source is attached to are inconsequential. Multiple ambient light sources are combined within a scene.
anisotropic filtering
A mipmap filtering mode that compensates for anisotropic distortion.
anisotropy
The distortion visible in the image of a 3-D object whose surface is oriented at an angle with respect to the viewing plane. The anisotropy is measured as the elongation (length divided by width) of a screen pixel that is inverse-mapped into texture space.
array object
A group of objects organized into an array. Array objects make it simpler to apply operations to the entire group. The COM interfaces that enable you to work with array objects contain the GetElement and GetSize methods. These methods retrieve a pointer to an element in the array and the size of the array, respectively.
attach
To connect multiple DirectDrawSurface objects into complex structures, such as those needed to support 3-D page flipping with z-buffers. Attachment is not bidirectional, and a surface cannot be attached to itself. Emulated surfaces (in system memory) cannot be attached to nonemulated surfaces. Unless one surface is a texture map, the two attached surfaces must be the same size.
attached
Physically connected to the system. A device may be installed but not currently attached.
attack
The period at the beginning of a force-feedback effect when the magnitude is reaching its basic or sustain level.


B

back buffer
A nonvisible surface to which bitmaps and other images can be drawn while the front buffer displays the currently visible image.
back clipping plane
The far boundary of a viewing frustum beyond which objects are not rendered. See also front clipping plane.
bank select
A MIDI controller that enables instruments to be chosen from different groups or banks, each identified by a 2-byte code.
billboard
A primitive inserted into a 3-D scene that is oriented so that one face is toward the viewer. A texture, usually an animated sprite, is applied to the billboard to give the appearance of a 3-D object in the scene.
billboarding
A 2-D technique of simulating the appearance of a 3-D object in a scene. An application inserts a primitive, typically rectangular, into the scene, orients it so that one face is toward the viewer, and applies a texture or a set of textures. The texture or set of textures gives the appearance of an animated 3-D object.
blend factor
The description of how each color component is blended in texture blending.
blend mode
The algorithm used to determine how a texture is blended with the colors of the surface to which the texture is applied.
blending stage
One step in a texture cascade. A blending stage includes one texture and a set of texture-blending operations that are used when blending multiple textures.
blit
A bit block transfer.
bounds checking
The process of checking that an on-screen image is displayed within the bounds of the screen.
bump mapping
A technique for simulating the appearance of rough surfaces in 3-D scenes. Variations in depth are stored in a texture and applied to a primitive, using standard texture-blending techniques.


C

camera
A Direct3DRMFrame object used by the viewport to define the viewing position and direction. The viewport renders only what is visible along the positive z-axis of the camera frame, with the up direction in the direction of the positive y-axis.
camera space
The frame of reference in which the viewer is at the origin, looking in the direction of the positive z-axis. Objects are transformed from world space to camera space by using the view transformation.
client/server session
A Microsoft® DirectPlay® session in which only the server stores the session's complete state, and each client has only a subset of the session's state. Each client receives only the information that is relevant to that computer from the server. When one computer changes something, it propagates the change to the server. The server then determines which clients it must inform of the change. See also peer-to-peer session.
clip list
A series of rectangles that describes the visible areas of the surface. The clip list cannot be set if a window handle is already associated with the DirectDrawClipper object.
clipper
A DirectDrawClipper object.
codec
Represents the phrase "compressor and decompressor."
collision detection
The process of determining if any pixels for two images share the same location on the screen. See also hit detection.
color key
A value indicating the color to be used for transparent or translucent effects. For example, when using a hardware blitter, all the pixels of a rectangular area are blitted, except the value that was set as the color key; this creates nonrectangular sprites on a surface.
color space
A model for representing color as three or more coordinates. Color-space models map color components onto a Cartesian coordinate system in three or more dimensions. A color space may use any of several types of color encoding and visualizing. The two most common types of color space models are RGB and YUV.
color-space conversion
A technique for converting a color in one color space to another color space. Typically, this conversion is from YUV colors from a video source to RGB for display.
color table
An array of n color values (normally RGB triples).
complex surface
The collective term for several DirectDrawSurface objects, all of which are attached to a root surface. The complex-surface structure can be destroyed only by destroying the root.
control segment
Musical segment that controls certain aspects of playback. Normally it is the primary segment, but a secondary segment can be designated as the control segment.
culling
Skipping a back face of a 3-D primitive during the rendering process.
curve
In Microsoft® DirectMusic®, a continuous series of events with a start and end value, such as volume fade.


D

dark light
A light source that removes illumination from a scene. Dark light is created by specifying negative values for the colors of the light.
DCI
Display Control Interface. Defined by the Intel and Microsoft® corporations, DCI is an interface that offers improved graphics performance as a result of direct video memory access.
deadband
A zone around the offset of a force-feedback axis at which a condition is not active.
dead zone
An area within the physical range of an axis where the axis is considered to be at the center.
decal
A texture that is rendered directly, as a visual. Decals are rendered into a viewport-aligned rectangle.
destination color key
The color that (in the case of blitting) is replaced or (in the case of overlays) is covered on the destination surface.
device window
A visible application window that Microsoft® DirectDraw® uses for display. Applications can have a device window for each display device attached to a given computer. See also focus window.
directional
Description of a light source that is attached to a frame but appears to illuminate all objects with equal intensity, as if it were at an infinite distance from the objects. Directional light has orientation but no position, and it is commonly used to simulate distant light sources, such as the sun.
DirectPlay address
A data format that Microsoft® DirectPlay® uses to pass addressing information between lobby servers, applications, DirectPlay, and service providers. A DirectPlay address is a sequence of variable-length data chunks tagged with a globally unique identifier (GUID) that supplies all the address information needed by DirectPlay. Examples of address information are: the network address of a server, the network address of a player, the e-mail name of a player, and the network address of a session.
DLS
Downloadable Sounds. A standard for synthesizing wave sounds from digital samples stored in software. The DLS level 1 and level 2 standards are published by the MIDI Manufacturers Association.
DMO
Microsoft® DirectX® Media Object. A COM object that processes multimedia data streams from buffers allocated by the client.


E

emissive property
The material property that determines whether a material emits light. The emissive property of a material is one of two properties that determines how the material reflects light. See also specular property.
emissive setting
See emissive property.
enable frame
The frame to which a light applies.
envelope
In force feedback, a set of values that defines the shape of an effect by modifying the magnitude at the beginning (attack) and end (fade).

In audio, a set of values that defines the shape of the amplitude or pitch of a sound. DLS level 1 defines a four-segment envelope: attack, decay, sustain, and release (ADSR). DLS level 2 defines six segments: delay, attack, hold, decay, sustain, and release (DAHDSR).

even field
The second field comprising a video frame in an odd/even field set. Also known as field 2.
execute buffer
A fully self-contained, independent packet of information that describes a 3-D scene. An execute buffer contains a vertex list followed by an instruction stream. The instruction stream consists of operation codes, or opcodes, and the data that is operated on by those opcodes.


F

face
A single polygon in a mesh.
fade
The period between the central, or sustain, portion of a force-feedback effect and its end.
falloff
Light attenuation between a spotlight's inner and outer cones.
field
Data for one-half of a single video frame within a video stream. Each field contains data for every other scan line. Fields are sent and received in odd field, even field order.
field polarity
Quality determining whether a field is an even field or an odd field. In odd fields the trailing edge of the VREF does not occur during a scan line. In even fields the trailing edge of the VREF occurs during a scan line.
flimmering
A shimmering appearance on 3-D primitives that results from a poor separation of z values when doing decaling. Some pixels from the back texture are rendered onto the front texture and vice versa.
flip
The process of swapping the addresses associated with the back and front buffers. This effectively swaps the image in the back buffer to the front buffer, thus displaying the image.
flipping chain
A series of surfaces attached to each other that can be flipped. See also flip.
flipping surface
Any piece of memory that can be flipped. See also flip.
focus window
An application window, visible or not visible, that Microsoft® DirectDraw® uses to hook window messages. The focus window's message handler receives input messages forwarded by DirectDraw. Applications can have only one focus window. See also device window.
frame
An invisible box that provides a frame of reference for objects in a scene. Objects can be placed in a scene by specifying their spatial relationship to a relevant reference frame. Visual objects take their positions and orientations from frames.

In a movie or animation, a single image.

front buffer
A rectangle of memory that is translated by the graphics adapter and displayed on the monitor or other output device.
front clipping plane
The near boundary of a viewing frustum. Any object closer to the camera than the front clipping plane is not rendered. The height of the front clipping plane defines the field of view. See also back clipping plane.


G

genlocking
The process of synchronizing one video signal with another. Because they are synchronized, the genlocked signal can be mixed with the original signal, enabling dissolves, wipes, and other transition effects.
grid
Subdivision of a beat. The number of grids per beat is part of the Microsoft® DirectMusic® time signature.
groove level
A value given to music during style playback. The groove level determines which patterns can be selected at any given time. The author assigns a range of groove levels to each pattern.
group
A logical collection of players. Microsoft® DirectPlay® supports groups within a session. By creating a group of players, an application can send a single message to the group, and all players in the group receive the message. A group is the means by which a network's multicast capabilities are exposed to the application.

Groups can be used to organize players in a session. A player can belong to more than one group. DirectPlay provides methods for administering groups and their membership.


H

HAL
Hardware abstraction layer. The HAL consists of hardware and device driver mechanisms that insulate applications from device-specific implementation details. If a capability requested by an application is not implemented by the current hardware, the capability is emulated by the software.
hardware blitter
A hardware component, built into the display adapter, that performs efficient blit operations.
HEL
Hardware emulation layer. The HEL provides software-based emulation of features that are not present in hardware.
HID
Human Interface Device. A USB class representing devices that enable a human to control a computer.
hit detection
See collision detection.
host
In Microsoft® DirectPlay®, a virtual player whose ID is DPID_SYSMSG. The host manages system messages and messages sent to all players in a session.
HREF
Horizontal refresh. In a video stream, the HREF is active to signal that the display is to begin a new scan line. See also VREF.
HRTF
Head-related transfer function. A mathematical representation of the effect of the listener's physiology on the pitch and timing of sounds arriving from different directions.


I, J, K

index palette
A DirectDrawPalette object whose entries are indexes into another palette object.
IPX service provider
A service provider that uses Windows Sockets to communicate over a local area network (LAN) using the Internetwork Packet Exchange (IPX) protocol. The service provider supports only nonguaranteed messaging. A single computer can host only one Microsoft® DirectPlay® session using IPX.
IRE scale
International Radio Engineers scale. A scale of values ranging from 0 to 100 that defines the brightness level of a broadcast video signal. The spectrum of low-to-high IRE values describes increasing brightness levels of a video signal. At 7.5 IRE brightness—the black cut-off threshold for a National Television System Committee (NTSC) signal—the electron guns of an NTSC display device are cut off and do not display images.


L

latency
A delay in response. For example, in Microsoft® DirectSound®, it is the interval between the time that a sound buffer plays and the time that the speakers actually reproduce the sound. In Microsoft DirectPlay®, it is the time that it takes for a packet to reach a given destination.
light map
A texture or group of textures that contain lighting information for a 3-D scene.
lobby-aware application
An application that, at a minimum, supports being launched from a lobby.
lobby client
Lobby management routines associated with the user's computer, including launching applications, updating the user interface, and communicating with the lobby server.
lobby provider
A client component (dynamic-link library) supplied by the developer of a lobby server. It implements communication functions with the lobby server, as requested by Microsoft® DirectPlay®.
lobby server
Lobby management routines associated with a remote server. The lobby server coordinates all the information about the users who are connected to a specific application.
lobby session
A connection to a lobby server on which clients and the server have not been specifically written to interoperate.


M

Mach bands
Bands of color that are not smoothly blended across a 3-D primitive.
material
A property that determines how a surface reflects light. A material has two components: an emissive property (whether it emits light) and a specular property, whose brightness is determined by a power setting.
mesh
A set of faces, each of which is described by a simple polygon.
mipmap
Also known as MIP map (Latin: multum in parvo, translated as "much in little"). A sequence of textures, each of which is a progressively lower-resolution, prefiltered representation of the same image. A higher-resolution image is used when a visible object is close to the viewer; as the object moves farther away (and gets smaller), lower-resolution images are used.
mixing
In Microsoft® DirectSound®, the process of combining sound buffers that are playing, and writing the result to the primary sound buffer, which supplies audio data to the sound hardware. There is no limit to the number of buffers that can be mixed, except the available processing time.
Mode X
A hybrid display mode derived from the standard VGA Mode 13. This mode allows the use of up to 256 KB of display memory (rather than the 64 KB allowed by Mode 13) by using the VGA display adapter's EGA multiple video plane system.
model coordinates
Coordinates that are relative to a local origin. See also model space and world coordinates.
model space
The frame of reference (used by model coordinates) that uses vertices relative to a single 3-D model's local origin.
multipass texture blending
The repeated rendering of a 3-D primitive while blending on a texture with each pass. This technique is widely used to achieve a variety of special effects.


N

nagling
An algorithm that causes the TCP/IP service provider to buffer small data packets into larger ones before sending. Nagling prevents a TCP/IP server from transmitting many very small packets by requiring the server to wait either until it has accumulated enough small data packets to combine them into a single large packet or until it has received an acknowledgment of the prior packet. Nagling can reduce message overhead (and decrease required bandwidth), but also causes a delay before small data packets are sent (increasing latency).
normal vector
An imaginary ray extending perpendicularly from a surface that defines the face's orientation.
NRPN
Nonregistered parameter number. Nonregistered parameters can be used for different functions by different manufacturers and are accessed through MIDI controllers. For more information, see the MIDI specification.


O

odd field
The first field comprising a video frame in an odd/even field set.
off-screen surface
A conceptually rectangular area in memory that is generally used to store bitmaps to be blitted to a back buffer before being displayed. Commonly used to store sprites.
opcode
Operation code that defines how to interpret the vertices in an execute buffer or how to change the state of the system.
overdraw
The average number of times to which a screen pixel is written.
overlay surface
A conceptually rectangular area in memory whose stored image information covers the image information of the primary surface to which it is applied. Overlays are assumed to be on top of all other screen components.
overlay z-order
Determines the order in which overlays clip each other, enabling a hardware sprite system to be implemented under Microsoft® DirectDraw®.


P

page flipping
See flip.
palette
The set of colors used by an object or application. In Microsoft® DirectX®, a DirectDrawPalette object.
palette index
An integer index into the palette table array that is used to select a particular color.
palettized surface
A DirectDrawSurface object that uses an attached palette to contain color information.
pan value
The relative volume, measured in hundredths of decibels, between the left and right audio channels.
parallel point
Description of a light source that illuminates objects with parallel light, but the orientation of the light is taken from the position of the parallel point light source. For example, two meshes on either side of a parallel point light source are lit on the side that faces the position of the source.
PChannel
Performance channel. A PChannel is a MIDI channel in a particular channel group on a particular port.
PCM
Pulse code modulation. An uncompressed wave data format in which each value represents the amplitude of the signal at the time of sampling.
peer-to-peer session
A Microsoft® DirectPlay® session in which the session's complete state is replicated on all the computers in the session. The session description data—the list of players and groups and the names and remote data associated with each session—are duplicated on every computer. When one computer changes something, it is immediately propagated to all the other computers. This is the default mode of communication for DirectPlay. See also client/server session.
perspective correction
The technique of applying a texture map to a polygon that is angled away from the camera, interpolating so that the texture is stretched onto the polygon appropriately for the apparent depth of the polygon. Microsoft® Direct3D® supplies perspective correction automatically.
pick
To search for visuals in a scene, given a 2-D coordinate in a viewport.
PID
Physical interface device. A USB class that enables humans to feel force feedback from a computer.
pitch
The distance, in bytes, between an address that represents the beginning of a bitmap line and the beginning of the next line. Do not confuse memory pitch and memory width because not all display memory is laid out as one linear block. For example, with rectangular memory, the pitch of the display memory could include the width of the bitmap plus part of a cache. See also width and stride.
player
A single participant in a Microsoft® DirectPlay® session. Each player is associated with a player ID that enables messages to be exchanged among players.
player ID
A unique number that is assigned to each participant in a Microsoft® DirectPlay® session when the participant is created. The application can exchange messages among players by using player IDs. The host is always assigned the DPID_SYSMSG player ID.
PNG
Portable Network Graphics. A nonproprietary bitmap format using lossless compression.
point light
A light source that radiates equally in all directions from its origin.
point list
The simplest 3-D primitive. A collection of unconnected points in 3-D space.
power
In the specular property of a material, the value that determines the sharpness of specular highlights. A value of 5 gives a metallic appearance, and higher values give a more plastic appearance.
primary sound buffer
An object that mixes and plays the final audio output. The primary buffer is generally used to mix sound from secondary buffers, but it can be accessed directly for custom mixing or other specialized activities.
primary surface
The area in memory containing the image being displayed on the monitor.
projection space
Frame of reference containing vertices after they are modified from their world space locations by the projection transformation. Projection space is a homogeneous cuboid space in which all vertices in a scene have x- and y-coordinates that range from –1.0 to 1.0, and a z-coordinate that ranges from 0.0 to 1.0. Projection space is sometimes referred to as post-perspective homogeneous space.
projection transformation
The application of a matrix to vertices to change them from camera space to projection space.


Q

quaternion
A fourth element added to the [x, y, z] values that define a vector. Quaternions define a 3-D axis and a rotation around that axis.


R

reference count
A control for a Component Object Model (COM) object. When an object is created, its reference count is set to 1. Every time an interface is bound to the object, its reference count is incremented; when the interface connection is destroyed, the reference count is decremented. The object is destroyed when the reference count reaches 0. All interfaces to that object are then invalid.
region
In DLS, a range of notes for which a particular digital sample is used in synthesizing an instrument's timbre.
root frame
A frame in Microsoft® Direct3D® that has no parent frame; it is at the top of a hierarchy of frames. The root frame contains the entire set of objects that make up a scene. See also scene.
RPN
Registered parameter number. Registered parameters have been assigned a function by the MIDI Manufacturers Association and can be accessed through controllers. For more information, see the MIDI specification.


S

saturation
In input and force feedback, adjustment to an axis range so that minimum or maximum values are retrieved or set before the physical extremities are reached. If the maximum value in a range is 1,000 and the maximum saturation point is set to 900, the maximum value is reached after 90 percent of the travel in that direction.
scene
The entire set of objects that make up a virtual environment, including visible objects, sounds, lights, and frames. In Microsoft® Direct3D®, the entire set of objects is contained in a root frame.
screen space
Frame of reference in which coordinates are related directly to 2-D locations in the frame buffer, to be displayed on a monitor or other viewing device. The origin, or (0,0), is defined to be the upper left corner. Y increases in the downward direction; X increases to the right. Projection space coordinates are converted to screen space coordinates, using a transformation matrix created from the viewport parameters.
secondary sound buffer
An object that manages a single sound or audio stream and plays it to the primary sound buffer.
secure session
A session in which all users have been authenticated against a database of known users before being allowed to join a session. In a secure session, all Microsoft® DirectPlay® system messages are digitally signed to verify the identity of the sender. Certain system messages that carry sensitive information are encrypted. System messages that originate from one player and need to be broadcast to all the other players in the session are first sent to the server. The server then puts its signature on the message and forwards the message to all the other computers in the session. Player-to-player messages are not signed by default and are not routed through the server.
send
(n.) A sound effect for a buffer that is applied by sending the sound data to a second buffer.
service provider
A dynamic-link library used by Microsoft® DirectPlay® to communicate over a network. The service provider contains all the network-specific code required to send and receive messages. Online services and network operators can supply service providers to use specialized hardware, protocols, communications media, and network resources.
session
In Microsoft® DirectPlay®, an instance of several applications on remote computers communicating with each other. Before an application can start communicating with other computers, it must be part of a session. An application can enumerate all the existing sessions on a network and join one of them, or it can create a new session and wait for other computers to join it. Once the application is part of a session, it can create a player and exchange messages with all the other players in the session.
sound buffer
An object that manages Microsoft® DirectSound® audio data.
source color key
A color that (in the case of blitting) is not copied to, or (in the case of overlays) not visible on, the destination.
specular property
The material property that determines how a point of light on a shiny object corresponds to the reflected light source. The specular property of a material is one of two properties that determines how a material reflects light. See also emissive property.
spotlight
A light source that emits a cone of light. Only objects within the cone are illuminated. The cone produces light of two degrees of intensity, with a central brightly lit section that acts as a point source, and a surrounding dimly lit section that merges with the surrounding deep shadow.
static buffer
A secondary sound buffer that contains an entire sound. Typically it is filled with data only once. Compare streaming buffer.
sticky focus
In Microsoft® DirectSound®, the ability to play sound buffers when the owning application does not have the input focus. For example, a DirectSound application could continue to play a sound buffer while the user is working in another application.
streaming buffer
A secondary sound buffer that contains only part of a sound. Its data must be refreshed as it is playing. Compare static buffer.
stretching
Blitting an image into a destination with different dimensions. This operation is supported directly by some hardware.
stride
Synonymous with pitch. See also width.
surface
Memory that represents visual images. This is often display memory, but it can also be system memory. See also complex surface, off-screen surface, overlay surface, and primary surface.
sustain
The period during which the basic magnitude of a force-feedback effect is attained, after the attack and before the fade.
system message
In Microsoft® DirectPlay®, a message from the player ID DPID_SYSMSG. All system messages begin with a DWORD value.


T

TCP/IP service provider
A service provider that uses Windows Sockets to communicate over the Internet or local area network (LAN), using the TCP/IP protocol. It uses User Datagram Protocol (UDP) packets for nonguaranteed messaging and TCP for guaranteed messaging. Using TCP/IP, a single computer can host multiple Microsoft® DirectPlay® sessions.
tearing
A visual artifact produced when the screen refresh rate is out of sync with an application's frame rate. The top portion of one frame is displayed at the same time as the bottom portion of another frame, with a discernible tear between the two partial images.
tessellating
Breaking an image into small square regions for processing or output.
texel
A single element in a texture. When a texture has been applied to an object, the texels rarely correspond to pixels on the screen. Applications can use texture filtering to control how the system interpolates between texels to create pixels in a scene.
texture
A rectangular array of pixels that is applied to a visual object in Microsoft® Direct3D®.
texture blending
The technique of combining the colors of a texture with the colors of the surface to which the texture is applied.
texture coordinates
The coordinates that determine which texel in each texture is assigned to each vertex in an object.
texture filtering
The process of mapping texel colors from one or more textures onto the pixels that comprise the image of a 3-D primitive.
texture mapping
The application of a texture to an object. Because a texture is a flat image and the object is often not, the texture must be mapped to the surface of the object, using texture coordinates and wrapping flags. See also texture coordinates and wrap.
thrashing
Removing textures used in the current frame to reclaim texture memory for subsequent frames.
throttling
Restricting the number of messages to avoid sending them faster than the underlying transport can deliver them.


U

unit vector
A vector with a magnitude (length) of 1.0.
USB
Universal serial bus.


V

VBI
Vertical blanking interval. In broadcast video, a small period of time that elapses between video frames during which a display device refreshes its display for the next frame.
velocity
In music, the speed at which a MIDI key is pressed. This is roughly equivalent to the dynamic level at which the note is played in some instrumental timbres.

In 3-D sound, for purposes of calculating Doppler shift, velocity is the speed at which a sound source or listener is considered to be moving.

vertex
A point in 3-D space.
video frame
A single image in a video stream, comprised of one odd field and one even field. See also field.
view space
See camera space.
view transformation
The application of a matrix to a model's vertices to change its orientation from world space to view space.
viewing frustum
A 3-D volume in a scene positioned relative to the viewport's camera. Objects within the frustum are visible. For perspective viewing, the viewing frustum is the volume of an imaginary pyramid that is between the front clipping plane and the back clipping plane. For orthographic viewing, the viewing frustum is cubic.
viewport
A rectangle that defines how a 3-D scene is rendered into a 2-D window. A viewport also defines an area on a device into which objects are rendered.
VREF
Vertical refresh. In a video stream, the VREF is active to signal that the display is to begin a new screen. See also HREF.


W

width
The distance between two addresses in memory that represent the beginning of a line and the end of the line of a stored bitmap. This distance represents only the width of the bitmap in memory. It does not include any extra memory required to reach the beginning of the next line of the bitmap, such as a cache in rectangular memory.
world coordinates
Coordinates that are relative to the origin of a scene. See also model coordinates and world space.
world space
The frame of reference, used by world coordinates, which declares vertices relative to a single origin within a 3-D scene.
world transformation
The application of a matrix to a model's vertices to change its orientation from model space to world space.
wrap
The procedure used to calculate texture coordinates for a face or mesh. The basic wrapping types are flat, cylindrical, spherical, and chrome.


X, Y, Z

z-buffer
A buffer that stores a depth value for each pixel in a scene. Pixels with a small z-value overwrite pixels with a large z-value.
z fighting
See flimmering.


Microsoft DirectX 8.1 (Visual Basic)

Multithreading Issues


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. See Templates for more information.

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";


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 universally unique identifiers (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
}


What's New in DirectX Graphics

This section describes Microsoft® DirectX® graphics features that are new in DirectX 8.x.

To see what's new in all of DirectX, see What's new in DirectX 8.1.

New Features in DirectX 8.1

Pixel Shaders

  • Added pixel shader versions 1.2, 1.3, and 1.4. These new versions expand existing functionality through a more powerful set of instructions, registers, and modifiers for programming pixel shaders.

New D3DX Functionality

Mesh API

Bump Mapping

MeshView Tool

Effect Framework

  • Effects. Added string support, added comments, and removed FourCC constraints.

    • Texture Library

    • Implemented a higher quality DXTn encoding algorithm.
    • Use D3DXGetImageInfoFrom to get image information before loading it.
    • Includes support for dynamic textures.
    • D3DPOOL_SCRATCH allows creation of resources that are not limited by device capabilities. They can be created and destroyed, locked and unlocked. These resources can be set to a device and used in rendering. Use with D3DX to convert to something useable such as loading a high-precision height field and converting to a normal map.

      • Math Library

      • Math library. Added CPU specific optimizations for most important functions for 3DNow, SSE, and SSE2.
      • Support for 16-byte aligned matrices using D3DXMATRIXA16.

      New DirectX Tools

      • DirectX tools. Helpful tools include KillHelp for terminating DirectX processes, DP8Sim for testing network performance, and Netmon for monitoring network performance.

      Samples

      Documentation Upgrades

      • DXGraphics SDK Docs. The graphics SDK documentation has been reorganized into two sections: a Reference section and a Programmers Guide.
      • The global illumination equations and the Mathematics of Lighting section have been rewritten and examples included.

      New Features in DirectX 8.0

      This version maintains backward compatibility by exposing and supporting objects and interfaces offered by previous releases of DirectX. However, many new features and performance enhancements have also been added to the Microsoft Direct3D® API interfaces.

      Pixel and Vertex Shaders

      • The two programmable sections of the Direct3D architecture are vertex shaders and pixel shaders. Vertex shaders are invoked prior to vertex assembly and operate on vertices. Pixel shaders are invoked after any DrawPrimitive or DrawIndexedPrimitive calls and generate the pixels that are written to the render target. The addition of programmable shaders for vertex and pixel operations provides the framework for real-time programmable effects that rival movie quality. The innovative freedom that this programmability gives back to game developers—by allowing them to implement whatever effect they see fit with the programmable pipeline—has the potential to unlock a new round of incredible games. Pixel and vertex shaders can be written using ASCII files, thus the shader files can be updated at runtime without recompiling the source application.

      Complete Integration of DirectDraw and Direct3D

      • Simplifies application initialization and improves data allocation and management performance, which reduces the memory footprint. Also, the integration of the graphics APIs enable parallel vertex input streams for more flexible rendering.

      Multisampling Rendering Support

      • Enables full-scene antialiasing and multisampling effects, such as motion blur and depth-of-field.

      Point Sprites

      • Enables high-performance rendering of particle systems for sparks, explosions, rain, snow, and so on.

      3-D Volumetric Textures

      • Enables range-attenuation in per-pixel lighting and volumetric atmospheric effects, and can be applied to more intricate geometry.

      Higher-Order Primitive Support

      • Enhances the appearance of three-dimensional (3-D) content and facilitates the mapping of content from major 3-D authoring tools.

      Higher-Level Technologies

      • Includes 3-D content-creation tool plug-ins (for export to Direct3D) for skinned meshes that use a variety of Direct3D techniques, multiresolution level-of-detail (LOD) geometry, and higher-order surface data.

      Indexed Vertex Blending

      • Extends geometry blending support to allow the matrices used for vertex blending to be referred to using a matrix index.

      Expansion of the Direct3DX Utility Library

      • Contains a wealth of new functionality. The Direct3DX utility library is a helper layer that sits on top of Direct3D to simplify common tasks encountered by 3-D graphics developers. Includes a skinning library, support for working with meshes, and functions to assemble vertex and pixel shaders. About 20 new functions have been added for DirectX 8.1. Note that the functionality supplied by D3D_OVERLOADS, first introduced with DirectX 5.0, has been moved to the Direct3DX utility library.


Create a Pixel Shader

This example uses a pixel shader to apply a Gouraud interpolated diffuse color to a geometric plane. The example will show the contents of the shader file as well as the code required in the application to set up the Microsoft® Direct3D® pipeline for the shader data.

To create a pixel shader
  1. Check for pixel shader support.
  2. Declare the vertex data.
  3. Design the pixel shader.
  4. Create the pixel shader.
  5. Render the output pixels.

If you already know how to build and run Direct3D samples, you should be able to cut and paste code from this example into your existing application.

Step 1: Check for pixel shader support

To check for pixel shader support, use the following code. This example checks for pixel shader version 1.1.

D3DCAPS8 caps;
m_pd3dDevice->GetDeviceCaps(&caps);        // init m_pd3dDevice before using
if( D3DPS_VERSION(1,1) != caps.PixelShaderVersion )
    return E_FAIL;

The caps structure returns the functional capabilities of the pipeline. Use the D3DPS_VERSION macro to test for the supported shader version number. If the version number is less than 1.1, this call will fail. If the hardware does not support the shader version that is tested, the application will have to fall back to another rendering approach (perhaps a lower shader version is available).

Step 2: Declare the vertex data

This example uses a plane, which is made up of two triangles. The data structure for each vertex will contain position and diffuse color data. The D3DFVF_CUSTOMVERTEX macro defines a data structure to match the vertex data. The actual vertex data is declared in a global array of vertices called g_Vertices[]. The four vertices are centered about the origin, and each vertex is given a different diffuse color.

// Declare vertex data structure.
struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD diffuseColor;
};
// Declare custom FVF macro.
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)

// Declare the vertex position and diffuse color data.
CUSTOMVERTEX g_Vertices[]=
{
//      x      y      z   diffuse color
    { -1.0f, -1.0f, 0.0f, 0xffff0000 },  // red   - bottom left
    { +1.0f, -1.0f, 0.0f, 0xff00ff00 },  // green - bottom right
    { +1.0f, +1.0f, 0.0f, 0xff0000ff },  // blue  - top right
    { -1.0f, +1.0f, 0.0f, 0xffffffff },  // white - top left
};

Step 3: Design the pixel shader

This shader moves the Gouraud interpolated diffuse color data to the output pixels. The shader file PixelShader.txt follows:

ps.1.0        // version instruction
mov r0,v0     // Move the diffuse vertex color to the output register.

The first instruction in a pixel shader file declares the pixel shader version, which is 1.0.

The second instruction moves the contents of the color register (v0) into the output register (r0). The color register contains the vertex diffuse color because the vertex data is declared to contain the interpolated diffuse color in step 1. The output register determines the pixel color used by the render target (because there is no additional processing, such as fog, in this case).

Step 4: Create the pixel shader

The pixel shader is created from the pixel shader instructions. In this example, the instructions are contained in a separate file. The instructions could also be used in a text string.

TCHAR        strPath[512];           // used to locate the shader file
LPD3DXBUFFER pCode;                  // points to the assembled shader code
DXUtil_FindMediaFile( strPath, _T("PixelShader.txt") );

D3DXAssembleShaderFromFile( strPath, 0, NULL, &pCode, NULL );    // assemble shader code
m_pd3dDevice->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(), &m_hPixelShader );

Once the shader is created, the handle m_hPixelShader is used to refer to it.

Step 5: Render the output pixels

Rendering the output pixels is very similar to using the fixed function pipeline sequence of calls except that the pixel shader handle is now used to set the shader.

// Turn lighting off for this example. It will not contribute to the final pixel color.
// The pixel color will be determined solely by interpolating the vertex colors.
m_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );

m_pd3dDevice->SetStreamSource( 0, m_pQuadVB, sizeof(CUSTOMVERTEX) );
m_pd3dDevice->SetVertexShader( D3DFVF_CUSTOMVERTEX );
m_pd3dDevice->SetPixelShader( m_hPixelShader );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

The gouraud shaded pixels are shown in the following image.

Pixel Shader Examples contains examples that show how to apply texture maps and blend between textures and vertex colors.


Pixel Shader Examples

The topic Create a Pixel Shader provides an example of how to use a pixel shader to apply a single diffuse color. The following are examples of other pixel shader functions. Each example builds on the previous example by adding a piece of additional pixel shader functionality.

  • Apply a Texture Map
  • Blend a Diffuse Vertex Color with a Texture
  • Blend Two Textures Using a Constant Color

    • Apply a Texture Map

    This example applies a texture map to a plane. The differences between this example and the previous example are as follows:

    • The vertex data structure and the Flexible Vertex Format (FVF) macro include texture coordinates. The vertex data includes u,v data. The vertex data no longer needs diffuse color because the pixel colors will come from the texture map.
    • The texture is linked to texture stage 0 with SetTexture. Because the previous example did not use a texture, there was no SetTexture method used.
    • The shader uses the t0 texture register instead of the v0 diffuse color register.

    The sample code follows:

    // Define vertex data structure.
struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    FLOAT u1, v1;
};

// Define corresponding FVF macro.
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_TEX|D3DFVF_TEXCOORDSIZE2(0))

// Create vertex data with position and texture coordinates.
static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z     u1    v1
    { -1.0f, -1.0f, 0.0f,  0, 1, },
    {  1.0f, -1.0f, 0.0f,  1, 1, },
    {  1.0f,  1.0f, 0.0f,  1, 0, },
    { -1.0f,  1.0f, 0.0f,  0, 0, },
    // v1 is flipped to meet the top down convention in Windows
    // the upper left texture coordinate is (0,0)
    // the lower right texture coordinate is (1,1).
};

// Create a texture. This file is in the DirectX 8.1 media from the SDK download.
TCHAR  strPath[512];
DXUtil_FindMediaFile( strPath, _T("DX5_Logo.bmp"));
LPDIRECT3DTEXTURE8      m_pTexture0;
D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );

// Create the pixel shader.
DXUtil_FindMediaFile( strPShaderPath, _T("PixelShader2.txt") );

D3DXAssembleShaderFromFile( strPShaderPath, 0, NULL, &pCode, NULL );
m_pd3dDevice->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(),&m_hPixelShader );

// Load the texture and render the output pixels.
m_pd3dDevice->SetTexture( 0, m_pTexture0 );		// load TSS0 from the texture
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

Contents of the file "PixelShader2.txt"
// Applies a texture map to object vertices.
ps.1.0                 // Version instruction must be first in the file.
tex t0                 // Declare texture register t0, which will be loaded from Texture Stage 0.
mov r0, t0             // Move the contents of the texture register (t0) to the output register (r0).

    The resulting image is shown in the following example.

    Blend a Diffuse Vertex Color with a Texture

    This example blends or modulates the colors in a texture map with the vertex colors. The differences between this example and the previous example are as follows:

    • The vertex data structure, the FVF macro, and the vertex data include diffuse color.
    • The shader file uses the multiply instruction (mul) to blend or modulate the texture colors with the vertex diffuse color.

    The texture create and load code is the same. It is included here for completeness.

    struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD color1;
    FLOAT tu1, tv1;
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1|D3DFVF_TEXCOORDSIZE2(0))

static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z     diffuse     u1    v1
    { -1.0f, -1.0f, 0.0f, 0xffff0000, 0, 1, }, // red
    {  1.0f, -1.0f, 0.0f, 0xff00ff00, 1, 1, }, // green
    {  1.0f,  1.0f, 0.0f, 0xff0000ff, 1, 0, }, // blue
    { -1.0f,  1.0f, 0.0f, 0xffffffff, 0, 0, }, // white
    // v1 is flipped to meet the top down convention in Windows
    // the upper left texture coordinate is (0,0)
    // the lower right texture coordinate is (1,1).
};

// Create a texture. This file is in the DirectX 8.1 media from the SDK download.
TCHAR  strPath[512];
DXUtil_FindMediaFile( strPath, _T("DX5_Logo.bmp"));
LPDIRECT3DTEXTURE8      m_pTexture0;
D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );

// Create the pixel shader.
DXUtil_FindMediaFile( strPShaderPath, _T("PixelShader3.txt") );
D3DXAssembleShaderFromFile( strPShaderPath, 0, NULL, &pCode, NULL );
m_pd3dDevice->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(),&m_hPixelShader );

// Load the texture and render the output pixels.
m_pd3dDevice->SetTexture( 0, m_pTexture0 );		// load TSS0 from the texture
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

Contents of the file "PixelShader3.txt"
ps.1.0          // version instruction
tex t0          // declare texture register t0 which will be loaded from Texture Stage 0
mul r0, v0, t0  // v0*t0, then move to r0

    The inputs to the shader are shown in the following example. The first image shows the vertex colors. The second image shows the texture map.

    The resulting image is shown in the following example. It shows the output, which is a blend of the vertex color and the texture image.

    Blend Two Textures Using a Constant Color

    This example blends two texture maps, using the vertex color, to determine how much of each texture map color to use. The differences between this example and the previous example are as follows:

    • The vertex data structure, the FVF macro, and the vertex data include a second set of texture coordinates because there is a second texture. SetTexture is also called twice, using two texture stage states.
    • The shader file declares two texture registers and uses the linear interpolate (lrp) instruction to blend the two textures. The values of the diffuse colors determine the ratio of texture0 to texture1 in the output color.

    Here is the sample code.

    struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD color;
    FLOAT tu1, tv1;
    FLOAT tu2, tv2;             // a second set of texture coordinates
};
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3D_FVF_DIFFUSE|D3DFVF_TEX2|D3DFVF_TEXCOORDSIZE4(0))

static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z     color       u1    v1    u2    v2
    { -1.0f, -1.0f, 0.0f, 0xff0000ff, 1.0f, 1.0f, 1.0f, 1.0f },
    { +1.0f, -1.0f, 0.0f, 0xffff0000, 0.0f, 1.0f, 0.0f, 1.0f },
    { +1.0f, +1.0f, 0.0f, 0xffffff00, 0.0f, 0.0f, 0.0f, 0.0f },
    { -1.0f, +1.0f, 0.0f, 0xffffffff, 1.0f, 0.0f, 1.0f, 0.0f },
};

// Create a texture. This file is in the DirectX 8.1 media from the SDK download.
TCHAR  strPath[512];
LPDIRECT3DTEXTURE8      m_pTexture0, m_pTexture1;
DXUtil_FindMediaFile( strPath, _T("DX5_Logo.bmp"));
D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture0, D3DFMT_R5G6B5 );
DXUtil_FindMediaFile( strPath, _T("snow2.jpg"));
D3DUtil_CreateTexture( m_pd3dDevice, strPath, &m_pTexture1, D3DFMT_R5G6B5 );

// Load the textures stages.
m_pd3dDevice->SetTexture( 0, m_pTexture0 );
m_pd3dDevice->SetTexture( 1, m_pTexture1 );        // Use a second texture stage.

m_pd3dDevice->SetStreamSource( 0, m_pQuadVB, sizeof(CUSTOMVERTEX) );
m_pd3dDevice->SetVertexShader( D3DFVF_CUSTOMVERTEX );
m_pd3dDevice->SetPixelShader( m_hPixelShader );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

Contents of the file "PixelShader5.txt"
ps.1.0              // pixel shader version
tex t0              // texture register t0 is loaded from texture stage 0
tex t1              // texture register t1 is loaded from texture stage 1
mov r1, t1          // move texture register1 into output register r1
lrp r0, v0, t0, r1  // linearly interpolate between t0 and r1 by a proportion
                    // specified in v0

    The resulting output is as follows:


Create a Vertex Shader

This example creates a vertex shader that applies a constant color to an object. The example will show the contents of the shader file as well as the code required in the application to set up the Microsoft® Direct3D® pipeline for the shader data.

To create a vertex shader

  • Step 1: Declare the vertex data
  • Step 2: Design the shader functionality
  • Step 3: Check for vertex shader support
  • Step 4: Declare the shader registers
  • Step 5: Create the shader
  • Step 6: Render the output pixels

If you already know how to build and run Direct3D samples, you can cut and paste code from this example into your existing application.

Step 1: Declare the vertex data

This example uses a quadrilateral that is made up of two triangles. The vertex data will contain (x,y,z) position and a diffuse color. The D3DFVF_CUSTOMVERTEX macro is defined to match the vertex data. The vertex data is declared in a global array of vertices (g_Vertices). The four vertices are centered about the origin, and each vertex is given a different diffuse color.

// Declare vertex data structure.
struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD diffuseColor;
};
// Declare custom FVF macro.
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)

// Declare the vertex position and diffuse color data.
CUSTOMVERTEX g_Vertices[]=
{
    //  x        y      z     diffuse color
    { -1.0f, -1.0f, 0.0f, 0xffff0000 },   // red   - bottom right
    { +1.0f, -1.0f, 0.0f, 0xff00ff00 },   // green - bottom left
    { +1.0f, +1.0f, 0.0f, 0xff0000ff },   // blue  - top left
    { -1.0f, +1.0f, 0.0f, 0xffffff00 },   // red and green = yellow - top right
};

Step 2: Design the shader functionality

This shader applies a constant color to each vertex. The shader file VertexShader.vsh follows:

vs.1.0              // version instruction
m4x4 oPos, v0, c0   // transform vertices by view/projection matrix
mov oD0, c4         // load constant color

This file contains three instructions.

The first instruction in a shader file must be the shader version declaration. This instruction (vs) declares the vertex shader version, which is 1.0 in this case.

The second instruction (m4x4) transforms the object vertices using the view/projection matrix. The matrix is loaded into four constant registers c0, c1, c2, c3 (as shown below).

The third instruction (mov) copies the constant color in register c4 to the output diffuse color register oD0. This results in coloring the output vertices.

Step 3: Check for vertex shader support

The device capability can be queried for vertex shader support before using a vertex shader.

D3DCAPS8 caps;
m_pd3dDevice->GetDeviceCaps(&caps);       // initialize m_pd3dDevice before using
if( D3DSHADER_VERSION_MAJOR( caps.VertexShaderVersion ) < 1 )
    return E_FAIL;

The caps structure returns the functional capabilities of the hardware after GetDeviceCaps is called. Use the D3DSHADER_VERSION_MAJOR macro to test the supported version number. If the version number is less than 1.0, this call will fail. The result of this method should be used to control whether or not vertex shaders are invoked by an application.

Step 4: Declare the shader registers

The shader is created by declaring the shader registers and compiling the shader file. Once created, Direct3D returns a shader handle, which is an integer number that is used to identify the shader.

// Create the shader declaration.
DWORD dwDecl[] =
{
    D3DVSD_STREAM(0),
    D3DVSD_REG(D3DVSDE_POSITION,  D3DVSDT_FLOAT3),
    D3DVSD_REG( D3DVSDE_DIFFUSE, D3DVSDT_D3DCOLOR ),
    D3DVSD_END()
};

The vertex declaration declares the mapping between input data streams and vertex buffers. Multiple streams can be declared in the shader declaration, up to the number specified in the MaxStreams cap. Vertex buffers are associated with input streams using SetStreamSource as illustrated in step 5.

Step 5: Create the shader

The shader is assembled and created next.

// Create the vertex shader.
TCHAR        strPath[512];                      // location of the shader file
LPD3DXBUFFER pCode;                             // assembled shader code
DXUtil_FindMediaFile( strPath, _T("VertexShader.vsh") );
D3DXAssembleShaderFromFile( strPath, 0, NULL, &pCode, NULL );  // assemble shader code
m_pd3dDevice->CreateVertexShader( dwDecl, (DWORD*)pCode->GetBufferPointer(), &m_hVertexShader, 0 )))
pCode->Release();

Once the shader file is located, D3DX8.AssembleShaderFromFile reads and validates the shader instructions. CreateVertexShader takes the shader declaration and the assembled instructions and creates the shader. It returns the shader handle, which is used to render the output.

CreateVertexShader can be used to create programmable or fixed function shaders. Programmable shaders are generated if a pointer to a shader declaration is passed as the second parameter. Otherwise, a fixed function vertex shader is generated if NULL is passed as the second parameter.

Step 6: Render the output pixels

Here is an example of the code that could be used in the render loop to render the object, using the vertex shader. The render loop updates the vertex shader constants as a result of changes in the 3-D scene and draws the output vertices with a call to DrawPrimitive.

// Turn lighting off. This is included for clarity but is not required.
m_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );

// Update vertex shader constants from view projection matrix data.
D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply( &mat, &matView, &matProj );
D3DXMatrixTranspose( &mat, &mat );
m_pd3dDevice->SetVertexShaderConstant( 0, &mat, 4 );

// Declare and define the constant vertex color.
float color[4] = {0,1,0,0};
m_pd3dDevice->SetVertexShaderConstant( 4, &color, 1 );

// Render the output.
m_pd3dDevice->SetStreamSource( 0, m_pQuadVB, sizeof(CUSTOMVERTEX) );
m_pd3dDevice->SetVertexShader( m_hVertexShader );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

Lighting is turned off just to make it clear that the vertex color is from the shader only. This statement is optional in this example.

The view and projection matrixes contain camera position and orientation data. Getting updated data and updating the shader constant registers is included in the render loop because the scene might change between rendered frames.

As usual, DrawPrimitive renders the output data using the vertex data provided from SetStreamSource. SetVertexShader is called to tell Direct3D to use the vertex shader. The result of the vertex shader is shown in the following image. It shows the constant color on the plane object.


Shader2 - Apply vertex colors

This example applies the vertex color from the vertex data to the object. The vertex data contains position data as well as diffuse color data. This is reflected in the vertex declaration and the fixed vertex function macro. These are shown below.

struct CUSTOMVERTEX_POS_COLOR
{
    float       x, y, z;
    DWORD       diffuseColor;
};
#define D3DFVF_CUSTOMVERTEX_POS_COLOR (D3DFVF_XYZ|D3DFVF_DIFFUSE)

// Create vertex data with position and texture coordinates.
CUSTOMVERTEX_POS_COLOR g_Vertices[]=
{
    //  x      y     z     diffuse
    { -1.0f, 0.25f, 0.0f, 0xffff0000,  },	//  - bottom right - red
    {  0.0f, 0.25f, 0.0f, 0xff00ff00,  },	//  - bottom left - green
    {  0.0f, 1.25f, 0.0f, 0xff0000ff,  },	//  - top left - blue
    { -1.0f, 1.25f, 0.0f, 0xffffffff,  },	//  - top right - white
};

The vertex shader declaration needs to reflect the position and color data also.

DWORD dwDecl2[] =
{
    D3DVSD_STREAM(0),
    D3DVSD_REG(0, D3DVSDT_FLOAT3),      // Register 0 will contain the position data.
    D3DVSD_REG(1, D3DVSDT_D3DCOLOR ),   // Register 1 will contain the color data.
    D3DVSD_END()
};

One way for the shader to get the transformation matrix is from a constant register. This is done by calling SetVertexShaderConstant.

    D3DXMATRIX mat;
    D3DXMatrixMultiply( &mat, &m_matView, &m_matProj );
    D3DXMatrixTranspose( &mat, &mat );
    hr = m_pd3dDevice->SetVertexShaderConstant( 1, &mat, 4 );
    if(FAILED(hr)) return hr;

This declaration declares one stream of data, which contains the position and the color data. The color data is assigned to vertex register 7.

Lastly, here is the shader file.

vs.1.0              ; version instruction
m4x4 oPos, v0, c0   ; transform vertices by view/projection matrix
mov oD0, v1         ; load color from register 7 to diffuse color

It contains three instructions. The first is always the version instruction. The second instruction transforms the vertices. The third instruction moves the color in the vertex register to the output diffuse color register. The result is output vertices using the vertex color data.

The resulting output looks like the following:

// Here is an example of the class used to produce this vertex shader.
// This example is for illustration only. It has not been optimized for performance.

// CVShader.h

// Use vertex color to color the object.

CUSTOMVERTEX_POS_COLOR g_VerticesVS[]=
{
    //  x      y     z     diffuse
    { -1.0f, 0.25f, 0.0f, 0xffff0000,  },	//  - bottom right - red
    {  0.0f, 0.25f, 0.0f, 0xff00ff00,  },	//  - bottom left - green
    {  0.0f, 1.25f, 0.0f, 0xff0000ff,  },	//  - top left - blue
    { -1.0f, 1.25f, 0.0f, 0xffffffff,  },	//  - top right - red
};

class CVShader
{
public:
    CVShader();

    HRESULT ConfirmDevice( D3DCAPS8* pCaps, DWORD dwBehavior, D3DFORMAT Format );
    HRESULT DeleteDeviceObjects();
    HRESULT Render();
    HRESULT RestoreDeviceObjects(LPDIRECT3DDEVICE8 l_pd3dDevice);
    HRESULT InitMatrices();
    HRESULT UpdateVertexShaderConstants();

private:

    LPDIRECT3DVERTEXBUFFER8	m_pQuadVB;
    LPDIRECT3DDEVICE8		m_pd3dDevice;
    DWORD					m_hVertexShader;
    D3DXMATRIX				m_matView;
    D3DXMATRIX				m_matProj;
};

CVShader::CVShader()
{
    m_pQuadVB			= NULL;
    m_pd3dDevice		= NULL;
    m_hVertexShader		= 0;
}

HRESULT CVShader::ConfirmDevice( D3DCAPS8* pCaps, DWORD dwBehavior,
                                          D3DFORMAT Format )
{
    if( D3DSHADER_VERSION_MAJOR( pCaps->VertexShaderVersion ) < 1 )
        return E_FAIL;

    return S_OK;
}

HRESULT CVShader::DeleteDeviceObjects()
{
    SAFE_RELEASE(m_pQuadVB);

    HRESULT hr;
    if(m_hVertexShader > 0)
    {
        hr = m_pd3dDevice->DeleteVertexShader(m_hVertexShader);
        if(FAILED(hr))
        {
            ::MessageBox(NULL,"","DeleteVertexShader failed",MB_OK);
            return E_FAIL;
        }

        m_hVertexShader = 0;
    }

    // local to this class
    m_pd3dDevice = NULL;

    return S_OK;
}

HRESULT CVShader::InitMatrices()
{
    HRESULT hr;

    D3DXVECTOR3 from( 0.0f, 0.0f, 3.0f );
    D3DXVECTOR3 at( 0.0f, 0.0f, 0.0f );
    D3DXVECTOR3 up( 0.0f, 1.0f, 0.0f );

    D3DXMATRIX matWorld;
    D3DXMatrixIdentity( &matWorld );
    hr = m_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

    D3DXMatrixIdentity( &m_matView );
    D3DXMatrixLookAtLH( &m_matView, &from, &at, &up );
    m_pd3dDevice->SetTransform( D3DTS_VIEW, &m_matView );

    D3DXMatrixIdentity( &m_matProj );
    D3DXMatrixPerspectiveFovLH( &m_matProj, D3DX_PI/4, 1.0f, 0.5f, 1000.0f );
    m_pd3dDevice->SetTransform( D3DTS_PROJECTION, &m_matProj );

    return S_OK;
}

HRESULT CVShader::Render()
{
    if(m_pQuadVB)
    {
        HRESULT hr;
        hr = m_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );

        UpdateVertexShaderConstants();

        hr = m_pd3dDevice->SetStreamSource( 0, m_pQuadVB,
            sizeof(CUSTOMVERTEX_POS_COLOR) );
        hr = m_pd3dDevice->SetVertexShader( m_hVertexShader );
        hr = m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );
    }

    return S_OK;
}

HRESULT CVShader::RestoreDeviceObjects(LPDIRECT3DDEVICE8 l_pd3dDevice)
{
    HRESULT hr;

    if(l_pd3dDevice == NULL)
    {
        ::MessageBox(NULL,"","Invalid D3D8 Device ptr",MB_OK);
        return E_FAIL;
    }
    else
        m_pd3dDevice = l_pd3dDevice;

    InitMatrices();

    // Create quad Vertex Buffer.
    hr = m_pd3dDevice->CreateVertexBuffer( 4*sizeof(CUSTOMVERTEX_POS_COLOR),
                    D3DUSAGE_WRITEONLY,
                    D3DFVF_CUSTOMVERTEX_POS_COLOR,
                    D3DPOOL_DEFAULT,
                    &m_pQuadVB );
    if( FAILED(hr) ) return hr;

    // Fill the quad VB.
    CUSTOMVERTEX_POS_COLOR1* pVertices = NULL;
    hr = m_pQuadVB->Lock( 0, 4*sizeof(CUSTOMVERTEX_POS_COLOR), (BYTE**)&pVertices, 0 );
    if(FAILED(hr)) return hr;

    for( DWORD i=0; i<4; i++ )
        pVertices[i] = g_VerticesVS2[i];

    m_pQuadVB->Unlock();

    // Create the vertex shader.
    TCHAR        strVertexShaderPath[512];
    LPD3DXBUFFER pCode;

    DWORD dwDecl2[] =
    {
        D3DVSD_STREAM(0),
        D3DVSD_REG(0, D3DVSDT_FLOAT3),
        D3DVSD_REG(1, D3DVSDT_D3DCOLOR ),
        D3DVSD_END()
    };

    // Find the vertex shader file.
    DXUtil_FindMediaFile( strVertexShaderPath, _T("VShader.vsh") );

    // Assemble the vertex shader from the file.
    if( FAILED( hr = D3DXAssembleShaderFromFile( strVertexShaderPath,
                                                 0, NULL, &pCode, NULL ) ) )
        return hr;

    // Create the vertex shader.
    if(SUCCEEDED(hr = m_pd3dDevice->CreateVertexShader( dwDecl2,
                    (DWORD*)pCode->GetBufferPointer(), &m_hVertexShader, 0 )))
        pCode->Release();

    return hr;
}

HRESULT CVShader::UpdateVertexShaderConstants()
{
    HRESULT hr;
    D3DXMATRIX mat;
    D3DXMatrixMultiply( &mat, &m_matView, &m_matProj );
    D3DXMatrixTranspose( &mat, &mat );
    hr = m_pd3dDevice->SetVertexShaderConstant( 1, &mat, 4 );
    return hr;
}


Shader3 - Apply a texture map

This example applies a texture map to the object.

The vertex data contains object position data as well as texture position or uv data. This causes changes to the vertex declaration structure and the fixed vertex function macro. The vertex data is also shown below.

struct CUSTOMVERTEX_POS_TEX1
{
    float       x, y, z;		// object position data
    float       tu1, tv1;		// texture position data
};
#define D3DFVF_CUSTOMVERTEX_POS_TEX1 (D3DFVF_XYZ|D3DFVF_TEX1)

CUSTOMVERTEX_POS_TEX1 g_Vertices[]=
{
    //  x      y     z      u1    v1
    { -0.75f, -0.5f, 0.0f, 0.0f, 0.0f },	//  - bottom right
    {  0.25f, -0.5f, 0.0f, 1.0f, 0.0f },	//  - bottom left
    {  0.25f,  0.5f, 0.0f, 1.0f, -1.0f },	//  - top left
    { -0.75f,  0.5f, 0.0f, 0.0f, -1.0f },	//  - top right
};

D3DUtil_CreateTexture( m_pd3dDevice, _T("earth.bmp"), &m_pTexture0, D3DFMT_R5G6B5 );

The texture image must be loaded. In this case, the file "earth.bmp" contains a 2-D texture map of the earth and will be used to color the object.

The vertex shader declaration needs to reflect the object position and texture position data.

DWORD dwDecl2[] =
{
    D3DVSD_STREAM(0),
    D3DVSD_REG(D3DVSDE_POSITION,  D3DVSDT_FLOAT3),
    D3DVSD_REG(8, D3DVSDT_FLOAT2 ),
    D3DVSD_END()
};

This declaration declares one stream of data that contains the object position and the texture position data. The texture position data is assigned to vertex register 8.

The rendering code tells Microsoft® Direct3D® where to find the data stream and the shader, and sets up texture stages because a texture map is being applied.

m_pd3dDevice->SetStreamSource( 0, m_pQuadVB, sizeof(CUSTOMVERTEX_POS_TEX1) );
m_pd3dDevice->SetVertexShader( m_hVertexShader );

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->SetTexture( 0, m_pTexture0 );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );
m_pd3dDevice->SetTexture( 0, NULL );

Because there is a single texture, the texture stage states need to be set for texture state 0. These methods tell Direct3D that the texel values will be used to provide diffuse color for the object vertices. In other words, a 2-D texture map will be applied like a decal.

Here is the shader file.

vs.1.0				; version instruction
m4x4 oPos, v0, c0	; transform vertices by view/projection matrix
mov oT0, v8			; move texture color to output texture register

The shader file contains three instructions. The first is always the version instruction. The second instruction transforms the vertices. The third instruction moves the texture colors from register v8 to the output diffuse color register. That results in a texture mapped object, which is shown below.


Shader4 - Apply a texture map with lighting

This example uses a vertex shader to apply a texture map and add lighting to the scene. The object used is a sphere. The sample code applies a texture map of the earth to the sphere and applies diffuse lighting to simulate night and day.

The code sample adds to the Shader3 example by adding lighting to a texture mapped object. Refer to Shader3 for information about loading the texture map and setting up the texture stage states.

Create Vertex Shader

The vertex data has been modified from the Shader3 sample to include vertex normals. For lighting to appear, the object must have vertex normals. The data structure for the vertex data and the flexible vertex format (FVF) macro used to declare the data type are shown below.

struct CUSTOMVERTEX_POS_NORM_COLOR1_TEX1
{
    float       x, y, z;        // position
    float       nx, ny, nz;     // normal
    DWORD       color1;         // diffuse color
    float       tu1, tv1;       // texture coordinates
};
#define D3DFVF_CUSTOMVERTEX_POS_NORM_COLOR1_TEX1 (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_DIFFUSE|D3DFVF_TEX1)

A shader declaration defines the input vertex registers and the data associated with them. This matches the FVF macro used to create the vertex buffer data later.

DWORD dwDecl[] =
{
    D3DVSD_STREAM(0),
    D3DVSD_REG(0,  D3DVSDT_FLOAT3),      // position
    D3DVSD_REG(4,  D3DVSDT_FLOAT3),      // normal
    D3DVSD_REG(7,  D3DVSDT_D3DCOLOR),    // diffuse color
    D3DVSD_REG(8,  D3DVSDT_FLOAT2),      // texture coordinate
    D3DVSD_END()
};

This declares one stream of data, which contains the vertex position, normal, diffuse color, and texture coordinates. The integer in each line is the register number that will contain the data. So, the texture coordinate data will be in register v8, for instance.

Next, create the shader file. You can create a shader from an ASCII text string or load it from a shader file that contains the same instructions. This example uses a shader file.

// Shader file
// v7  vertex diffuse color used for the light color
// v8  texture
// c4  view projection matrix
// c12 light direction
vs.1.0                       // version instruction
m4x4 oPos,    v0,    c4      // transform vertices using view projection transform
dp3  r0     , v4   , c12     // perform lighting N dot L calculation in world space
mul  oD0    , r0.x , v7      // calculate final pixel color from light intensity and
                             // interpolated diffuse vertex color
mov  oT0.xy , v8             // copy texture coordinates to output

You always enter the version instruction first. The last instruction moves the texture data to the output register oT0. After you write the shader instructions, you can use them to create the shader.

// Now that the file exists, use it to create a shader.
TCHAR        strVertexShaderPath[512];
LPD3DXBUFFER pCode;
DXUtil_FindMediaFile( strVertexShaderPath, _T("VShader3.vsh") );
D3DXAssembleShaderFromFile( strVertexShaderPath, 0, NULL, &pCode, NULL );
m_pd3dDevice->CreateVertexShader( dwDecl, (DWORD*)pCode->GetBufferPointer(), &m_hVertexShader, 0 );
pCode->Release();

After the file is located, Direct3D creates the vertex shader and returns a shader handle and the assembled shader code. This sample uses a shader file, which is one method for creating a shader. The other method is to create an ASCII text string with the shader instructions in it. For an example, see Programmable Shaders for DirectX 8.0.

Vertex Shader Constants

You can define vertex shader constants outside of the shader file as shown in the following example. Here, you use constants to provide the shader with a view/projection matrix, a diffuse light color, RGBA, and the light direction vector.

float constants[4] = {0, 0.5f, 1.0f, 2.0f};
m_pd3dDevice->SetVertexShaderConstant( 0, &constants, 1 );

D3DXMATRIX mat;
D3DXMatrixMultiply( &mat, &m_matView, &m_matProj );
D3DXMatrixTranspose( &mat, &mat );
m_pd3dDevice->SetVertexShaderConstant( 4, &mat, 4 );

float color[4] = {1,1,1,1};
m_pd3dDevice->SetVertexShaderConstant( 8, &color, 1 );

float lightDir[4] = {-1,0,1,0}; // fatter slice
m_pd3dDevice->SetVertexShaderConstant( 12, &lightDir, 1 );

You can also define constants inside a shader using the def instruction

Render

After you write the shader instructions, connect the vertex data to the correct vertex registers and initialize the constants, you should render the output. Rendering code tells Direct3D where to find the vertex buffer data stream and provides Direct3D with the shader handle. Because you use a texture, you must set texture stages to tell Direct3D how to use the texture data.

// Identify the vertex buffer data source.
m_pd3dDevice->SetStreamSource(0, m_pVB, sizeof(CUSTOMVERTEX_POS_NORM_COLOR1_TEX1));
// Identify the shader.
m_pd3dDevice->SetVertexShader( m_hVertexShader );

// Define the texture stage(s) and set the texture(s) used
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->SetTexture( 0, m_pTexture0 );

// Draw the object.
DWORD dwNumSphereVerts = 2 * m_dwNumSphereRings*(m_dwNumSphereSegments + 1);
m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, dwNumSphereVerts - 2);

// Set the texture stage to NULL after the render commands. Leaving this
// out will cause a memory leak.
m_pd3dDevice->SetTexture( 0, NULL );

The output image follows:

With the texture map applied, the sphere looks like the planet Earth. The lighting creates a bright to dark gradient on the face of the globe.

Additional Code

There is additional code required to support this example. Shown below are a few of the other methods for creating the sphere object, loading the texture, and checking for the correct version of pixel shader support.

// Confirm that the hardware supports version 1 shader instructions.
if( D3DSHADER_VERSION_MAJOR( pCaps->VertexShaderVersion ) < 1 )
    return E_FAIL;

// Load texture map for the sphere object.
LPDIRECT3DTEXTURE8 m_pTexture0;
D3DUtil_CreateTexture( m_pd3dDevice, _T("earth.bmp"), &m_pTexture0, D3DFMT_R5G6B5 );

// Create the sphere object.
DWORD dwNumSphereVerts = 2*m_dwNumSphereRings*(m_dwNumSphereSegments+1);
// once for the top, once for the bottom vertices

// Get the World-View(WV) matrix set.
D3DXMATRIX matWorld, matView, matWorldView;
m_pd3dDevice->GetTransform( D3DTS_WORLD, &matWorld );
m_pd3dDevice->GetTransform( D3DTS_VIEW,  &matView );
D3DXMatrixMultiply( &matWorldView, &matWorld, &matView );
m_pd3dDevice->CreateVertexBuffer(
    dwNumSphereVerts*sizeof(CUSTOMVERTEX_POS_NORM_COLOR1_TEX1),
    D3DUSAGE_WRITEONLY,
    D3DFVF_CUSTOMVERTEX_POS_NORM_COLOR1_TEX1,
    D3DPOOL_DEFAULT,
    &m_pVB)	);

CUSTOMVERTEX_POS_NORM_COLOR1_TEX1* pVertices;
HRESULT hr;
hr = m_pVB->Lock(0, dwNumSphereVerts*sizeof(pVertices),
                    (BYTE**)&pVertices, 0);
if(SUCCEEDED(hr))
{
    FLOAT fDeltaRingAngle = ( D3DX_PI / m_dwNumSphereRings );
    FLOAT fDeltaSegAngle  = ( 2.0f * D3DX_PI / m_dwNumSphereSegments );

    // Generate the group of rings for the sphere.
    for( DWORD ring = 0; ring < m_dwNumSphereRings; ring++ )
    {
        FLOAT r0 = sinf( (ring+0) * fDeltaRingAngle );
        FLOAT r1 = sinf( (ring+1) * fDeltaRingAngle );
        FLOAT y0 = cosf( (ring+0) * fDeltaRingAngle );
        FLOAT y1 = cosf( (ring+1) * fDeltaRingAngle );

        // Generate the group of segments for the current ring.
        for( DWORD seg = 0; seg < (m_dwNumSphereSegments+1); seg++ )
        {
            FLOAT x0 =  r0 * sinf( seg * fDeltaSegAngle );
            FLOAT z0 =  r0 * cosf( seg * fDeltaSegAngle );
            FLOAT x1 =  r1 * sinf( seg * fDeltaSegAngle );
            FLOAT z1 =  r1 * cosf( seg * fDeltaSegAngle );

            // Add two vertices to the strip, which makes up the sphere
            // (using the transformed normal to generate texture coords).
            pVertices->x = x0;
            pVertices->y = y0;
            pVertices->z = z0;
            pVertices->nx = x0;
            pVertices->ny = y0;
            pVertices->nz = z0;
            pVertices->color = HIGH_WHITE_COLOR;
            pVertices->tu = -((FLOAT)seg)/m_dwNumSphereSegments;
            pVertices->tv = (ring+0)/(FLOAT)m_dwNumSphereRings;
            pVertices++;

            pVertices->x = x1;
            pVertices->y = y1;
            pVertices->z = z1;
            pVertices->nx = x1;
            pVertices->ny = y1;
            pVertices->nz = z1;
            pVertices->color = HIGH_WHITE_COLOR;
            pVertices->tu = -((FLOAT)seg)/m_dwNumSphereSegments;
            pVertices->tv = (ring+1)/(FLOAT)m_dwNumSphereRings;
            pVertices++;
        }

        hr = m_pVB->Unlock();
    }
}


Common Framework

This source code is furnished to help you get up and running with DirectX more quickly. It is intended to illustrate how Direct3D works, and reduce the time it takes to build simple applications that allow you to experiment. It is used by the samples in the SDK. All of this source code lives in the Samples\Multimedia\Common\Src directory which can be installed during the SDK install.

This code is not intended to be cut and paste into a production application. This is not because it is poorly written, but rather that it is not designed for production. No attempt has been made to optimize it for performance. Very little error checking has been added as it obscures the functionality. Use to code to experiment with Direct3D to understand how it works.

Classes | Names
 | CD3DApplication
 | CD3DArcBall
 | CD3DCamera
 | CD3DFrame
 | CD3DFile
 | CD3DFont
 | CD3DMesh
 | CD3DScreenSaver

Functions | Names
 | D3DUtil_CreateTexture
 | D3DUtil_CreateVertexShader
 | D3DUtil_GetCubeMapVertex
 | D3DUtil_GetRotationFromCursor
 | D3DUtil_InitMaterial
 | D3DUtil_InitLight
 | D3DUtil_SetColorKey
 | D3DUtil_SetDeviceCursor

Structures | Names
 | D3DModeInfo
 | D3DWindowedModeInfo
 | D3DDeviceInfo
 | D3DAdapterInfo
 | MonitorInfo
 | RenderUnit

Macros | Names

Error Codes | Names


Header

Defines the application-specific header.

UUID

<3D82AB43-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
major | WORD |  | None
minor | WORD |  |
flags | DWORD |  |


Direct3DX Shader Assemblers Reference

This section contains reference information for the vertex and pixel shader assemblers provided by the Direct3DX utility library.

  • Vertex Shader Assembler Reference
  • Pixel Shader Assembler Reference

All of the example syntax used in this documentation is intended to demonstrate how to write shaders when using the Direct3DX vertex and pixel shader assemblers.


Microsoft DirectX 8.1 (vertex shader versions 1.0, 1.1)

Vertex Shader Block Diagram


Direct3DBaseTexture8.FreePrivateData

Redirecting to Direct3DResource8.FreePrivateData.


Direct3DBaseTexture8.GetDevice

Redirecting to Direct3DResource8.GetDevice.


Direct3DBaseTexture8.GetPriority

Redirecting to Direct3DResource8.GetPriority.


Direct3DBaseTexture8.GetPrivateData

Redirecting to Direct3DResource8.GetPrivateData.


Direct3DBaseTexture8.GetType

Redirecting to Direct3DResource8.GetType.


Direct3DBaseTexture8.PreLoad

Redirecting to Direct3DResource8.PreLoad.


Direct3DBaseTexture8.SetPriority

Redirecting to Direct3DResource8.SetPriority.


Direct3DBaseTexture8.SetPrivateData

Redirecting to Direct3DResource8.SetPrivateData.


Direct3DCubeTexture8.FreePrivateData

Redirecting to Direct3DResource8.FreePrivateData.


Direct3DCubeTexture8.GetDevice

Redirecting to Direct3DResource8.GetDevice.


Direct3DCubeTexture8.GetLevelCount

Redirecting to Direct3DBaseTexture8.GetLevelCount.


Direct3DCubeTexture8.GetLOD

Redirecting to Direct3DBaseTexture8.GetLOD.


Direct3DCubeTexture8.GetPriority

Redirecting to Direct3DResource8.GetPriority.


Direct3DCubeTexture8.GetPrivateData

Redirecting to Direct3DResource8.GetPrivateData.


Direct3DCubeTexture8.GetType

Redirecting to Direct3DResource8.GetType.


Direct3DCubeTexture8.PreLoad

Redirecting to Direct3DResource8.PreLoad.


Direct3DCubeTexture8.SetLOD

Redirecting to Direct3DBaseTexture8.SetLOD.


Direct3DCubeTexture8.SetPriority

Redirecting to Direct3DResource8.SetPriority.


Direct3DCubeTexture8.SetPrivateData

Redirecting to Direct3DResource8.SetPrivateData.


Direct3DIndexBuffer8.FreePrivateData

Redirecting to Direct3DResource8.FreePrivateData.


Direct3DIndexBuffer8.GetDevice

Redirecting to Direct3DResource8.GetDevice.


Direct3DIndexBuffer8.GetPriority

Redirecting to Direct3DResource8.GetPriority.


Direct3DIndexBuffer8.GetPrivateData

Redirecting to Direct3DResource8.GetPrivateData.


Direct3DIndexBuffer8.GetType

Redirecting to Direct3DResource8.GetType.


Direct3DIndexBuffer8.PreLoad

Redirecting to Direct3DResource8.PreLoad.


Direct3DIndexBuffer8.SetPriority

Redirecting to Direct3DResource8.SetPriority.


Direct3DIndexBuffer8.SetPrivateData

Redirecting to Direct3DResource8.SetPrivateData.


Direct3DTexture8.FreePrivateData

Redirecting to Direct3DResource8.FreePrivateData.


Direct3DTexture8.GetDevice

Redirecting to Direct3DResource8.GetDevice.


Direct3DTexture8.GetLevelCound

Direct3DyTexture8.GetLevelCount

Redirecting to Direct3Dbasetexture8.GetLevelCount.


Direct3DTexture8.GetLOD

Redirecting to Direct3DBaseTexture8.GetLOD.


Direct3DTexture8.GetPriority

Redirecting to Direct3DResource8.GetPriority.


Direct3DTexture8.GetPrivateData

Redirecting to Direct3DResource8.GetPrivateData.


Direct3DTexture8.GetType

Redirecting to Direct3DResource8.GetType.


Direct3DTexture8.PreLoad

Redirecting to Direct3DResource8.PreLoad.


Direct3DTexture8.SetLOD

Redirecting to Direct3DBaseTexture8.SetLOD.


Direct3DTexture8.SetPriority

Redirecting to Direct3DResource8.SetPriority.


Direct3DTexture8.SetPrivateData

Redirecting to Direct3DResource8.SetPrivateData.


Direct3DVertexBuffer8.FreePrivateData

Redirecting to Direct3DResource8.FreePrivateData.


Direct3DVertexBuffer8.GetDevice

Redirecting to Direct3DResource8.GetDevice.


Direct3DVertexBuffer8.GetPriority

Redirecting to Direct3DResource8.GetPriority.


Direct3DVertexBuffer8.GetPrivateData

Redirecting to Direct3DResource8.GetPrivateData.


Direct3DVertexBuffer8.GetType

Redirecting to Direct3DResource8.GetType.


Direct3DVertexBuffer8.PreLoad

Redirecting to Direct3DResource8.PreLoad.


Direct3DVertexBuffer8.SetPriority

Redirecting to Direct3DResource8.SetPriority.


Direct3DVertexBuffer8.SetPrivateData

Redirecting to Direct3DResource8.SetPrivateData.


Direct3DVolumeTexture8.FreePrivateData

Redirecting to Direct3DResource8.FreePrivateData.


Direct3DVolumeTexture8.GetDevice

Redirecting to Direct3DResource8.GetDevice.


Direct3DVolumeTexture8.GetLevelCount

Redirecting to Direct3Dbasetexture8.GetLevelCount.


Direct3DVolumeTexture8.GetLOD

Redirecting to Direct3DBaseTexture8.GetLOD.


Direct3DVolumeTexture8.GetPriority

Redirecting to Direct3DResource8.GetPriority.


Direct3DVolumeTexture8.GetPrivateData

Redirecting to Direct3DResource8.GetPrivateData.


Direct3DVolumeTexture8.GetType

Redirecting to Direct3DResource8.GetType.


Direct3DVolumeTexture8.PreLoad

Redirecting to Direct3DResource8.PreLoad.


Direct3DVolumeTexture8.SetLOD

Redirecting to Direct3DBaseTexture8.SetLOD.


Direct3DVolumeTexture8.SetPriority

Redirecting to Direct3DResource8.SetPriority.


Direct3DVolumeTexture8.SetPrivateData

Redirecting to Direct3DResource8.SetPrivateData.


D3DX8.DrawText

Draws formatted text on a Microsoft® Direct3D® device.

object.DrawText( _
    D3dFont As D3DXFont, _
    Color As Long, _
    TextString As String, _
    RECT As RECT, _
    Format As Long)

Parts

object
Object expression that resolves to a D3DX8 object.
D3dFont
A D3DXFont object specifying the font to use.
Color
Long value specifying the color of the text.
TextString
The string to draw.
RECT
RECT type that contains the rectangle, in logical coordinates, in which the text is to be formatted.
Format
A combination of values from the CONST_DTFLAGS enumeration, specifying the text formatting.

Error Codes

If the method fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

For information on trapping errors, see the Microsoft Visual Basic® Error Handling topic.

See Also

CONST_DTFLAGS, D3DXFont.DrawText


D3DXMesh.CloneMesh

Redirecting to D3DXBaseMesh.CloneMesh.


D3DXMesh.CloneMeshFVF

Redirecting to D3DXBaseMesh.CloneMeshFVF.


D3DXMesh.ConvertAdjacencyToPointReps

Redirecting to D3DXBaseMesh.ConvertAdjacencyToPointReps.


D3DXMesh.ConvertPointRepsToAdjacency

Redirecting to D3DXBaseMesh.ConvertPointRepsToAdjacency.


D3DXMesh.DrawSubset

Redirecting to D3DXBaseMesh.DrawSubset.


D3DXMesh.GenerateAdjacency

Redirecting to D3DXBaseMesh.GenerateAdjacency.


D3DXMesh.GetAttributeTable

Redirecting to D3DXBaseMesh.GetAttributeTable.


D3DXMesh.GetDeclaration

Redirecting to D3DXBaseMesh.GetDeclaration.


D3DXMesh.GetDevice

Redirecting to D3DXBaseMesh.GetDevice.


D3DXMesh.GetFVF

Redirecting to D3DXBaseMesh.GetFVF.


D3DXMesh.GetIndexBuffer

Redirecting to D3DXBaseMesh.GetIndexBuffer.


D3DXMesh.GetNumFaces

Redirecting to D3DXBaseMesh.GetNumFaces.


D3DXMesh.GetNumVertices

Redirecting to D3DXBaseMesh.GetNumVertices.


D3DXMesh.GetOptions

Redirecting to D3DXBaseMesh.GetOptions.


D3DXMesh.GetVertexBuffer

Redirecting to D3DXBaseMesh.GetVertexBuffer.


D3DXMesh.LockIndexBuffer

Redirecting to D3DXBaseMesh.LockIndexBuffer.


D3DXMesh.LockVertexBuffer

Redirecting to D3DXBaseMesh.LockVertexBuffer.


D3DXMesh.UnlockIndexBuffer

Redirecting to D3DXBaseMesh.UnlockIndexBuffer.


D3DXMesh.UnlockVertexBuffer

Redirecting to D3DXBaseMesh.UnlockVertexBuffer.


D3DXPMesh.CloneMesh

Redirecting to D3DXBaseMesh.CloneMesh.


D3DXPMesh.CloneMeshFVF

Redirecting to D3DXBaseMesh.CloneMeshFVF.


D3DXPMesh.ConvertAdjacencyToPointReps

Redirecting to D3DXBaseMesh.ConvertAdjacencyToPointReps.


D3DXPMesh.ConvertPointRepsToAdjacency

Redirecting to D3DXBaseMesh.ConvertPointRepsToAdjacency.


D3DXPMesh.DrawSubset

Redirecting to D3DXBaseMesh.DrawSubset.


D3DXPMesh.GenerateAdjacency

Redirecting to D3DXBaseMesh.GenerateAdjacency.


D3DXPMesh.GetAttributeTable

Redirecting to D3DXBaseMesh.GetAttributeTable.


D3DXPMesh.GetDeclaration

Redirecting to D3DXBaseMesh.GetDeclaration.


D3DXPMesh.GetDevice

Redirecting to D3DXBaseMesh.GetDevice.


D3DXPMesh.GetFVF

Redirecting to D3DXBaseMesh.GetFVF.


D3DXPMesh.GetIndexBuffer

Redirecting to D3DXBaseMesh.GetIndexBuffer.


D3DXPMesh.GetNumFaces

Redirecting to D3DXBaseMesh.GetNumFaces.


D3DXPMesh.GetNumVertices

Redirecting to D3DXBaseMesh.GetNumVertices.


D3DXPMesh.GetOptions

Redirecting to D3DXBaseMesh.GetOptions.


D3DXPMesh.GetVertexBuffer

Redirecting to D3DXBaseMesh.GetVertexBuffer.


D3DXPMesh.LockIndexBuffer

Redirecting to D3DXBaseMesh.LockIndexBuffer.


D3DXPMesh.LockVertexBuffer

Redirecting to D3DXBaseMesh.LockVertexBuffer.


D3DXPMesh.UnlockIndexBuffer

Redirecting to D3DXBaseMesh.UnlockIndexBuffer.


D3DXPMesh.UnlockVertexBuffer

Redirecting to D3DXBaseMesh.UnlockVertexBuffer.


D3DXRenderToSurface.OnLostDevice

Releases all references to video memory resources and deletes all stateblocks.

object.OnLostDevice()

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value is be D3DERR_INVALIDCALL.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the D3DXRenderToSurface.OnResetDevice method called.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXRenderToSurface.OnResetDevice

Should be called after the device has been reset.

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

This method should be called after the device has been reset, before any other methods are called.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXSprite.OnLostDevice

Releases all references to video memory resources and deletes all stateblocks.

object.OnResetDevice()

Parameters

object
Object expression that resolves to a D3DXSprite object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXFont::OnResetDevice method called.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXSprite.OnResetDevice

Should be called after the device has been reset.

object.OnResetDevice()

Parameters

object
Object expression that resolves to a D3DXSprite object.

Error Codes

If the method fails, an error is raised and Err.Number can be set to D3DERR_INVALIDCALL.

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This method should be called after the device has been reset, before any other methods are called.


D3DXQuaternionSquadSetup

Setup control points for spherical quadrangle interpolation.

D3DXQuaternionSquadSetup( _
AOut As D3DXQUATERNION*, _
    BOut As D3DXQUATERNION*, _
    COut As D3DXQUATERNION*, _
    Q0   As CONST D3DXQUATERNION*, _
    Q1   As CONST D3DXQUATERNION*, _
    Q2   As CONST D3DXQUATERNION*, _
    Q3   As CONST D3DXQUATERNION*)

Parameters

AOut
D3DQUATERNION type that is the result of the operation, the result of the spherical quadrangle interpolation.
BOut
D3DQUATERNION type that is the result of the operation, the result of the spherical quadrangle interpolation.
COut
D3DQUATERNION type that is the result of the operation, the result of the spherical quadrangle interpolation.
Q0
A source D3DQUATERNION type, containing a control point.
Q1
A source D3DQUATERNION type, containing a control point.
Q2
A source D3DQUATERNIONtype, containing a control point.
Q3
A source D3DQUATERNION type, containing a control point.
t
Parameter that indicates how far to interpolate between the quaternions.

Error Codes

If the function fails, an error is raised and Err.Number can be set to one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

For information on trapping errors, see the Microsoft® Visual Basic® Error Handling topic.

Remarks

This function takes the four control points supplied by Q0, Q1, Q2, and Q3. 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 shown below.

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

where:
Ln is the API method D3DXQuaternionLn
Exp is the API method D3DXQuaternionExp

Use a set of quaternion keys (q0, q1, q2, ..., qn) to compute the inner quadrangle points (a1, a2, a3, ..., an-1) as shown in the following example. This will ensure that the tangents are continuous across adjacent segments.

        a1    a2    a3
  q0    q1    q2    q3    q4

a[i] = q[i] * exp( -(ln(inv(q[i])*q[i+1]) + ln(inv(q[i])*q[i-1])) / 4 )

Once the values for a (a1, a2, a3 in this case) are computed, the results are used to interpolate along the curve.

qt = Squad(t, q[i], a[i], a[i+1], q[i+1])

See Also

D3DXQuaternionSquad


Microsoft DirectX 8.1 (Visual Basic)

Capture Focus


Microsoft DirectX 8.1 (Visual Basic)

Fast User Switching


Using the DirectPlay Core API

This documentation provides detailed information about how to use the Microsoft® DirectPlay® core application programming interface (API). Some of this material is also relevant to DirectPlay Lobby and DirectPlay Voice.

  • Using DirectPlay Enumerations
  • Using Player Context Values
  • Using the DirectPlay DPNSVR Application
  • Testing Network Performance with DP8Sim
  • Monitoring DirectPlay Network Traffic with Netmon
  • Implementing a Callback Function in DirectPlay and DirectPlay Voice


Implementing a Callback Function in DirectPlay and DirectPlay Voice


Implementing a DirectPlay Networking Callback Using Critical Section Objects

Multithreaded callbacks are not used in Visual Basic.


Using the DirectPlay Lobby API

This documentation provides detailed information about how to use the Microsoft® DirectPlay® Lobby application programming interface (API). For general information about using DirectPlay, see Using the DirectPlay Core API.

  • Implementing a Lobby Client
  • Implementing a Lobbyable Application


Microsoft DirectX 8.1 (Visual Basic)

Sharing the Audio Capture Device


Microsoft DirectX 8.1 (Visual Basic)

Using Player Context Values


A Sample Lobbied Application Message Handler


A Sample Lobby Client Message Handler


Creating a DirectSetup Callback Function

To customize the setup process, first 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 this example, adapted from the Dinstall Sample application, the name of the function is the same as that of the prototype, but this is optional. The parameter names differ slightly from those in the prototype declared in the Dsetup.h header file and are used throughout the following discussion.

Parameters

The dwReason parameter indicates why the callback function has been called. The possible values are listed and explained in the reference for DirectXSetupCallbackFunction.

The dwMsgType parameter receives flags equivalent to those that Microsoft® DirectSetup would, by default, pass to MessageBox, such as those controlling which buttons and icons are displayed. Of special interest are the button flags, which you use to determine what return values are expected. If this value is 0, the event never requires user input, and DirectSetup normally displays a status message.

The szMessage parameter receives the same text that DirectSetup would otherwise pass to the status dialog box or to MessageBox.

When a driver is a candidate for upgrading, its name is passed in the szName parameter, and pInfo points to information about how the upgrade is to be handled—for example, whether DirectSetup recommends that the old driver be kept or upgraded. For more information, see Creating a DirectSetup Callback Function.

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.

Return Value

The value returned by your callback function must conform to the following rules:

  • When dwMsgType is 0, the return value must be IDOK. In this case, there are no choices to be made by the user. (Your application, of course, is free to display a status message, even though no input is required.)
  • If dwMsgType is nonzero, the return value must be the same as would have been returned by MessageBox, given the equivalent choice by the user.

To determine the appropriate return value in the second case, test dwMsgType for the buttons that would normally have been put in a message box. The following example, from the GetReply function in Dinstall, shows how this is done:

/* The global g_wReply identifies the custom dialog button
   that has been selected by the user. */

switch (dwMsgType & 0x0000000F)
{
   / * There would normally have been an OK and a Cancel button.
       IDBUT1 is equivalent to the OK button. If the user did not
       choose that, it was a Cancel. */
    case MB_OKCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDOK : IDCANCEL;
        break;

    / * And so on with the other button combinations. */
    case MB_OK:
        wDefaultButton = IDOK;
        break;
    case MB_RETRYCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDRETRY : IDCANCEL;
        break;
    case MB_ABORTRETRYIGNORE:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDABORT;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDRETRY;
        else
            wDefaultButton = IDIGNORE;
        break;
    case MB_YESNOCANCEL:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDYES;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDNO;
        else
            wDefaultButton = IDCANCEL;
        break;
    case MB_YESNO:
        wDefaultButton = (g_wReply == IDBUT1) ? IDYES : IDNO;
        break;
    default:
        wDefaultButton = IDOK;
}

This routine translates button clicks from the custom interface into the equivalent button identifiers in the standard dialog box that DirectSetup would otherwise create. The wDefaultButton variable is set to the identifier of the equivalent standard dialog box button, and this value is ultimately returned from the callback function.

You do not necessarily have to give the user a choice, even when dwMsgType is nonzero. You might decide, for example, to upgrade drivers automatically even if DirectSetup would normally ask for confirmation from the user. The Dinstall sample does this when the user has asked to see only problem messages and the driver upgrade is considered safe, as follows:

case DSETUP_CB_UPGRADE_SAFE:
    switch (dwMsgType & 0x0000000F)
    {
        case MB_YESNO:
        case MB_YESNOCANCEL:
            return IDYES;
        case MB_OKCANCEL:
        case MB_OK:
        default:
            return IDOK;
    }
    break;

The callback function returns either IDYES or IDOK, depending on which button would have represented a positive choice in a dialog box asking the user whether or not the upgrade should proceed.

Setting the Callback Function

Before calling DirectXSetup, notify DirectSetup that you want to use a callback by calling the DirectXSetupSetCallback function, passing a pointer to the callback as a parameter. The following example shows how this is done:

DirectXSetupSetCallback(
        (DSETUP_CALLBACK) DirectXSetupCallbackFunction);

Using Upgrade Flags in the Callback Function

When the application-defined callback function DirectXSetupCallbackFunction is called by the DirectXSetup function, it is passed a parameter that contains the reason that the callback function was invoked. If the reason is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE, the pInfo parameter points to a DSETUP_CB_UPGRADEINFO structure containing flags that summarize the DirectXSetup function recommendations on how to perform the upgrade of Microsoft® DirectX® components and drivers. The structure member containing the flags is called UpgradeFlags.

The flags fall into the following categories:

Primary Upgrade Flags
These flags are mutually exclusive. One of them is always present in the UpgradeFlags structure member. You can extract it by performing a bitwise AND operation with DSETUP_CB_UPGRADE_TYPE_MASK.

DSETUP_CB_UPGRADE_FORCE

DSETUP_CB_UPGRADE_KEEP

DSETUP_CB_UPGRADE_SAFE

DSETUP_CB_UPGRADE_UNKNOWN

Secondary Upgrade Flags
Either one or both of these flags can be present.

DSETUP_CB_UPGRADE_CANTBACKUP

DSETUP_CB_UPGRADE_HASWARNINGS

Device Active Flag
This flag is present if the device whose driver is being upgraded is active. It can be combined with any of the others.

DSETUP_CB_UPGRADE_DEVICE_ACTIVE

Device Class Flags
These flags are mutually exclusive. One of them is always present.

DSETUP_CB_UPGRADE_DISPLAY

DSETUP_CB_UPGRADE_MEDIA

In summary: every time the Reason parameter has the value DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE, the UpgradeFlags member of the structure pointed to by pInfo contains one Primary Upgrade Flag, zero or more Secondary Upgrade Flags, zero or one Device Active Flag, and one Device Class Flag.

If the UpgradeFlags member is set to DSETUP_CB_UPGRADE_KEEP, the DirectX component or device driver cannot be upgraded without causing Microsoft® Windows® to cease functioning properly. The DirectXSetup function does not perform an upgrade on the component or driver.

A value of DSETUP_CB_UPGRADE_FORCE in UpgradeFlags means that the component or driver must be upgraded for Windows to function properly. The DirectXSetup function upgrades the driver or component. It is possible that the upgrade might adversely affect some programs on the system. When the DirectXSetup function detects this condition, the UpgradeFlags member is set to (DSETUP_CB_UPGRADE_FORCE | DSETUP_CB_UPGRADE_HAS_WARNINGS). When this occurs, the DirectXSetup function performs the upgrade but issues a warning to the user.

Components and drivers are considered safe for upgrade if they do not adversely affect the operation of Windows when they are installed. In this case, the UpgradeFlags member is set to DSETUP_CB_UPGRADE_SAFE. It is possible that the upgrade can be safe for Windows but still cause problems for programs installed on the system. When DirectXSetup detects this condition, the UpgradeFlags member contains the value (DSETUP_CB_UPGRADE_SAFE | DSETUP_CB_UPGRADE_HAS_WARNINGS). If this condition occurs, the default action for the DirectXSetup function is not to perform the upgrade.

Overriding Defaults in the Callback Function

The application-defined function DirectXSetupCallbackFunction can override some of the default behaviors of the DirectXSetup function through its return value.

For example, the default behavior for DirectXSetup is not to install a component if the upgrade type in the structure pointed to by the pInfo parameter is set to (DSETUP_CB_UPGRADE_SAFE | DSETUP_CB_UPGRADE_HAS_WARNINGS). In this case, the MsgType parameter of the callback function is set to (MB_YESNO | MB_DEFBUTTON2). Without a callback function, DirectSetup would present the user with a dialog box whose default button was No. If the callback function does not seek user input but accepts the default, it returns IDNO. To override the default, the callback function returns IDYES. If it does override the default, the DirectXSetup function notifies the user.


DirectSetup Reference

This section contains reference information for the Microsoft® DirectSetup API elements. Reference material is divided into the following categories.

  • Functions
  • Structures
  • Return Values


Return Values

The DirectXSetup function can return the following values. It can also return a standard COM error.

DSETUPERR_SUCCESS
Setup was successful and no restart is required.
DSETUPERR_SUCCESS_RESTART
Setup was successful and a restart is required.
DSETUPERR_BADSOURCESIZE
A file's size could not be verified or was incorrect.
DSETUPERR_BADSOURCETIME
A file's date and time could not be verified or were incorrect.
DSETUPERR_BADWINDOWSVERSION
Microsoft® DirectX® does not support the Microsoft® Windows® version on the system.
DSETUPERR_CANTFINDDIR
The setup program could not find the working directory.
DSETUPERR_CANTFINDINF
A required .inf file could not be found.
DSETUPERR_INTERNAL
An internal error occurred.
DSETUPERR_NEWERVERSION
A later version of DirectX has already been installed. Applications can safely ignore this error because the newer version is not overwritten and is fully compatible with applications written for earlier versions.
DSETUPERR_NOTADMIN
The current user does not have administrative privileges. On Windows 2000 systems, the user may need administrative privileges for some setup operations.
DSETUPERR_NOCOPY
A file's version could not be verified or was incorrect.
DSETUPERR_NOTPREINSTALLEDONNT
The version of Microsoft® Windows NT® or Windows 2000 on the system does not contain the current version of DirectX. An older version of DirectX might be present or DirectX might be absent altogether.
DSETUPERR_OUTOFDISKSPACE
The setup program ran out of disk space during installation.
DSETUPERR_SOURCEFILENOTFOUND
One of the required source files could not be found.
DSETUPERR_UNKNOWNOS
The operating system on your system is not currently supported.
DSETUPERR_UNSUPPORTEDPROCESSOR
The processor type is unsupported. DirectX 8 supports only Pentium or K6-compatible or higher processors.
DSETUPERR_USERHITCANCEL
The Cancel button was pressed before the application was fully installed.


DirectXRegisterApplication

Registers an application as one designed to work with DirectPlayLobby.

int WINAPI DirectXRegisterApplication(
  HWND hWnd,
  LPDIRECTXREGISTERAPP lpDXRegApp
);

Parameters

hWnd
Handle of the parent window. If this parameter is set to NULL, the desktop is the parent window.
lpDXRegApp
Address of the DIRECTXREGISTERAPP structure that contains the registry entries that are required for the application to function properly with DirectPlayLobby.

Return Values

If this function succeeds, it returns TRUE.

If it fails, it returns FALSE. Call the GetLastError function to get extended error information.

Remarks

The DirectXRegisterApplication function has to have both Dsetup.dll and Dsetup32.dll. These files are not installed on the system, but they are included in the SDK.

Requirements

Windows NT/2000/XP: Requires Windows 2000.
Windows 98/Me: Requires Windows 98 or later. Available as a redistributable for Windows 98.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXUnRegisterApplication


DirectXSetup

Installs one or more Microsoft® DirectX® components.

int WINAPI 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
One or more flags indicating which DirectX components should be installed. A full installation (DSETUP_DIRECTX) is recommended.
DSETUP_D3D | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DDRAW | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DDRAWDRV | Not used in DirectX 8.1.
DSETUP_DINPUT | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DIRECTX | Installs DirectX run-time components, as well as display and audio drivers compatible with DirectX.
DSETUP_DIRECTXSETUP | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DPLAY | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DPLAYSP | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DSOUND | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DSOUNDDRV | Not used in DirectX 8.1.
DSETUP_DXCORE | Installs DirectX run-time components. Does not install DirectX-compatible display and audio drivers.
DSETUP_TESTINSTALL | Performs a test installation. Does not install new components.
DSETUP_USEROLDERFLAG | Enables the return of –14, which means that the installed version of DirectX is newer than the version being installed.

Return Values

If this function succeeds, it returns one of the following success codes:

DSETUPERR_SUCCESS | Success.
DSETUPERR_SUCCESS_RESTART | Success, but the user must restart the system for the changes to take effect.

If it fails, it returns an error value. For a list of possible return values, see Return Values.

Remarks

Before using the DirectXSetup function in your setup program, you should first ensure that the system has enough available disk space. The maximum amount of space that you need to set up DirectX 8.1 is 20 MB for Microsoft® Windows® 95, Windows 98, and Windows Millennium Edition (Windows Me) systems, and 25 MB for Windows 2000.

Requirements

Windows NT/2000/XP: Requires Windows NT 4.0 SP3 or later.
Windows 98/Me: Requires Windows 98 or later. Available as a redistributable for Windows 98.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.


DirectXSetupCallbackFunction

A placeholder name for an optional callback function supplied by the setup program. If present, it is called once for each step in the setup process.

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 Microsoft® DirectX® components and device drivers.
DSETUP_CB_MSG_BEGIN_INSTALL_DRIVERS
DirectXSetup is about to begin installing device drivers.
DSETUP_CB_MSG_BEGIN_INSTALL_RUNTIME
DirectXSetup is about to begin installing DirectX components.
DSETUP_CB_MSG_BEGIN_RESTORE_DRIVERS
DirectXSetup is about to begin restoring previous drivers.
DSETUP_CB_MSG_CANTINSTALL_BETA
A prerelease beta version of the Microsoft® Windows® 95 operating system was detected. The DirectX component or device driver cannot be installed.
DSETUP_CB_MSG_CANTINSTALL_NOTWIN32
The operating system detected is not a Windows 32-bit operating system. DirectX is not compatible with Windows 3.x.
DSETUP_CB_MSG_CANTINSTALL_NT
The DirectX component or device driver cannot be installed on versions of the Microsoft® Windows NT® operating system prior to version 4.0.
DSETUP_CB_MSG_CANTINSTALL_UNKNOWNOS
The operating system is unknown. The DirectX component or device driver cannot be installed.
DSETUP_CB_MSG_CANTINSTALL_WRONGLANGUAGE
The DirectX component or device driver is not localized to the language being used by Windows.
DSETUP_CB_MSG_CANTINSTALL_WRONGPLATFORM
The DirectX component or device driver is for another type of computer.
DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE
Driver is being considered for upgrade. Verification from user is recommended.
DSETUP_CB_MSG_FILECOPYERROR
Setup of the DirectX component or device driver file has failed during the copy process.
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_NOTPREINSTALLEDONNT
The DirectX component or device driver cannot be installed on the version of Microsoft Windows NT or Microsoft Windows 2000 in use.
DSETUP_CB_MSG_OUTOFDISKSPACE
Setup of the DirectX component has failed due to lack of disk space.
DSETUP_CB_MSG_PREINSTALL_NT
DirectX is already installed on the version of Windows NT or Windows 2000 in use.
DSETUP_CB_MSG_SETUP_INIT_FAILED
Setup of the DirectX component or device driver has failed.
MsgType
Flags that control the display of a message box. These flags can be passed to the MessageBox function. An exception is when MsgType is 0. In that case, the setup program can display status information but 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 unless the Reason parameter is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE. In that case, szName contains a pointer to the name of the driver to be upgraded.
pInfo
Pointer to the address of a structure containing upgrade information. When Reason is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE, the setup program is upgrading a driver and asking the user whether the upgrade should take place. In this case, pInfo points to a DSETUP_CB_UPGRADEINFO structure containing information about the upgrade.

Return Values

The return value should be the same as the value that would be returned by the MessageBox function, with one exception. If this function returns 0, the DirectXSetup function performs the default action for upgrade of the DirectX component or driver.

Remarks

The name of DirectXSetupCallbackFunction 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.

Requirements

Windows NT/2000/XP: Requires Windows 2000.
Windows 98/Me: Requires Windows 98 or later. Available as a redistributable for Windows 98.
Header: Declared in Dsetup.h.
Import Library: User-defined.

See Also

MessageBox, DirectXSetupSetCallback, Customizing Setup


DirectXSetupGetVersion

Retrieves the version number of the Microsoft® DirectX® components that are currently installed.

INT WINAPI 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 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 1.0 | 0x00000000
DirectX 2.0 | 0x00000000
DirectX 3.0 | 0x00000000
DirectX 5.0 | 0x00040005
DirectX 6.0 | 0x00040006
DirectX 7.0 | 0x00040007
DirectX 8.1 | 0x00040008

There is no version 4 of DirectX.

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.

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

Windows NT/2000/XP: Requires Windows NT 4.0 SP3 or later.
Windows 98/Me: Requires Windows 98 or later. Available as a redistributable for Windows 98.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

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, see DirectXSetupCallbackFunction. If a setup program does not provide a callback function, DirectXSetupSetCallback is not invoked.

INT WINAPI 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

Windows NT/2000/XP: Requires Windows NT 4.0 SP3 or later.
Windows 98/Me: Requires Windows 98 or later. Available as a redistributable for Windows 98.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXSetupCallbackFunction, DirectXSetup


DirectXUnRegisterApplication

Deletes the registration of an application designed to work with DirectPlayLobby.

int WINAPI DirectXUnRegisterApplication(
  HWND   hWnd,
  LPGUID lpGUID
);

Parameters

hWnd
Handle of the parent window. Set this to NULL if the desktop is the parent window.
lpGUID
Address of a GUID that represents the Microsoft® DirectPlay® application to be unregistered.

Return Values

If the function succeeds, the return value is TRUE. This means that the registration is successfully deleted.

If the function fails, the return value is FALSE.

Remarks

The DirectXUnRegisterApplication function has to have both Dsetup.dll and Dsetup32.dll. These two files are not installed on the system, but they are included in the SDK.

Requirements

Windows NT/2000/XP: Requires Windows 2000.
Windows 98/Me: Requires Windows 98 or later. Available as a redistributable for Windows 98.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXRegisterApplication


Functions

This section contains information on the following global functions used with Microsoft® DirectSetup.

  • DirectXRegisterApplication
  • DirectXSetup
  • DirectXSetupCallbackFunction
  • DirectXSetupGetVersion
  • DirectXSetupSetCallback
  • DirectXUnRegisterApplication


DIRECTXREGISTERAPP

Contains the registry entries needed for applications designed to work with DirectPlayLobby.

typedef struct _DIRECTXREGISTERAPP {
    DWORD  dwSize;
    DWORD  dwFlags;
    LPSTR  lpszApplicationName;
    LPGUID lpGUID;
    LPSTR  lpszFilename;
    LPSTR  lpszCommandLine;
    LPSTR  lpszPath;
    LPSTR  lpszCurrentDirectory;
} DIRECTXREGISTERAPP, *PDIRECTXREGISTERAPP, *LPDIRECTXREGISTERAPP;

Members

dwSize
Size of the structure. This member must be initialized to the size of the DIRECTXREGISTERAPP structure.
dwFlags
Reserved.
lpszApplicationName
Name of the application.
lpGUID
Globally unique identifier (GUID) of the application.
lpszFilename
Name of the executable file to be called.
lpszCommandLine
Command-line arguments for the executable file.
lpszPath
Path of the executable file.
lpszCurrentDirectory
Current directory. This is typically the same as lpszPath.

Requirements

Windows NT/2000/XP: Requires Windows 2000.
Windows 98/Me: Requires Windows 98 or later. Available as a redistributable for Windows 98.
Header: Declared in Dsetup.h.


DSETUP_CB_UPGRADEINFO

Passed as a parameter to the application-defined DirectXSetupCallbackFunction. It contains valid information only when the Reason parameter is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE. Callback functions can use it to get status information on the upgrade that is about to be done.

typedef struct _DSETUP_CB_UPGRADEINFO {
    DWORD UpgradeFlags;
} DSETUP_CB_UPGRADEINFO;

Members

UpgradeFlags
One or more flags indicating the status of the upgrade. The following values are defined.
DSETUP_CB_UPGRADE_CANTBACKUP
The old system components cannot be backed up. Upgrade can be performed, but the components or drivers cannot be restored later.
DSETUP_CB_UPGRADE_DEVICE_ACTIVE
The device is currently in use.
DSETUP_CB_UPGRADE_DEVICE_DISPLAY
The device driver being upgraded is for a display device.
DSETUP_CB_UPGRADE_DEVICE_MEDIA
The device driver being upgraded is for a media device.
DSETUP_CB_UPGRADE_FORCE
Microsoft® Windows® might not function correctly if the component is not upgraded. The upgrade will be performed.
DSETUP_CB_UPGRADE_HASWARNINGS
Microsoft DirectSetup can upgrade the driver for this device, but doing so might affect one or more programs on the system. The szMessage parameter contains the names of the programs that might be affected. Upgrade not recommended.
DSETUP_CB_UPGRADE_KEEP
The system might fail if this device driver is upgraded. Upgrade not allowed.
DSETUP_CB_UPGRADE_SAFE
DirectSetup can safely upgrade this device driver. Upgrade recommended. A safe upgrade will not adversely affect the operation of Windows. Some hardware-dependent programs might be adversely affected.
DSETUP_CB_UPGRADE_UNKNOWN
DirectSetup does not recognize the existing driver for this device. This value occurs frequently. Upgrading might adversely affect the use of the device. It is strongly recommended that the upgrade not be performed.

Remarks

Use the DSETUP_CB_UPGRADE_TYPE_MASK value to extract the upgrade type (FORCE, KEEP, SAFE, or UNKNOWN) from UpgradeFlags.

Requirements

Windows NT/2000/XP: Requires Windows 2000.
Windows 98/Me: Requires Windows 98 or later. Available as a redistributable for Windows 98.
Header: Declared in Dsetup.h.

See Also

DirectXSetupCallbackFunction


Structures

This section contains information about the following structures used with Microsoft® DirectSetup.

  • DIRECTXREGISTERAPP
  • DSETUP_CB_UPGRADEINFO

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.


Dinstall Sample

Microsoft DirectX 8.1 (Visual Basic)