DirectX5.0 Latest Game Programming Guide
Review
For numerous game makers, the launch of Microsoft's DirectX 5 is not an excellent news. It contains the preparation of next-generation computer games and multimedia applications
The latest technologies and tools provide a wide range of application interface APIs to make programmers to design high-performance real-time applications. DirectX makes running in Microsoft
The game under the Windows operating system is better interactive than the game running under the MS-DOS operating system, even more than the dedicated gaming machine.
The primary purpose of Microsoft Development DirectX is to improve the easiness of game development in the Windows environment. Prior to this, most of the games on your computer are based on MS-DOS.
The game developers must prepare different programs for different hardware interface cards, although the code is similar, but it is inevitably there are many repetitive labor. Use DirectX, game development
Personnel can get the advantages of DirectX hardware independence, while also accessing hardware directly. The most important goal of DirectX is to provide direct hardware access directly in MS-DOS.
Sex, simultaneously remove the hardware identification issues brought by adding new hardware in your computer.
Because the hardware upgrade is inevitable, DirectX actually provides another method for plugging. Therefore, using DirectX can develop high performance real-time
Using the program, you can directly access hardware in the computer and the hardware devices in the future system. DirectX provides a consistent interface between hardware and applications to reduce installation and configuration
Complexity and the utilization of hardware reaches optimal. With interface provided by DirectX, programmers can take advantage of hardware features without considering their specific details. An excellent basis
Windows's high-performance games should be able to use the system as follows:
Accelerated acceleration card for improved performance
Plug and play PNP (PLUG AND PLAY)
Communication service embedded in Windows, including Directplay
DirectX 5 includes seven parts, which are described below with a brief description.
(1) .directDraw By supporting the hardware and hardware acceleration technology of the memory in the middle of the memory, it is quickly accessed, and the bit block transmission and buffer flip function of the hardware is quickly directly accessed by supporting the access screen.
(2) .directSound provides a hardware and software sound mixing and recording and reproducing.
(3) .directPlay makes the game more simple and convenient to the connection between the modem and the network.
(4) .direct3D provides a high-level retention mode interface and aimediate-mode interface. The former allows the program to be easily completed
The full 3D graphics system, the latter makes the program fully controlled the colored pipe.
.DirectInput provides an API and driver based on Windows game-based input, not only supports current keyboard, mouse, and joystick, but also supports future Windows-based
input device.
.DirectSetup provides a disposable installation process for DirectX.
(7) .autoplay It is the feature of Windows 95, when you put the disc in the optical drive, it automatically runs the installer or game. In fact, AutoPlay is also Microsoft Win32
Part of the API, not only in DirectX SDK. .
By querying various DirectX object interfaces, you can detect which version of DirectX is installed in the system, in the DirectX SDK in GetDxversion.cpp
The getDxversion function can complete this task. This function creates some key DirectX objects - a DirectDraw object, a DirectDrawSurface object and one
DirectInput object - to detect the version of DirectX installed in the system. If the old version of DirectX SDK is installed in the system, you must make sure not to include its Include and Lib path, using the DirectX 5 header compiled code with the DirectX 3 library link will appear unpredictable errors.
Because C languages are more directly accessible to computer hardware, DirectX uses C languages as the development of the main language. And DirectX is also specifically for Visual C
Designed, write DirectX programs can be made under Visual C . Of course, Borland C 5.0 is no problem, just configuring some differences, the following will mention this question.
question. In order to reduce the difficulty of programming, some companies also develop controls running in different programming environments for DirectX, such as Arakelian Soft's ActiveX control Directstudio98
For Visual Basic 5.0, Tegosoft's Tegosoft ActiveX for Visual Basic, and John Pullen, PAUL Bearne and Jeff Kurtz development running under Delphi
Delphi Games Creator et al. Considering compatibility issues, it is best to use Visual C .
First, DirectX and Parts Object Model COM
1.1, component object model COM (Component Object Model)
Most of the APIs in DirectX consists of COM-based objects and interfaces. COM is the foundation based on object-based system, which is the core model of COM programming.
It is also an interface specification. At the operating system level, it is another object model.
Many DirectX APIs are created as an instance of a COM object. You can see an object as a black box, the object communicate with the object through the interface, send it to the pair through the COM interface.
A command received from an object is called a method. For example, the iDirectdraw2 :: getDisplayMode method is to get the current display from the DirectDraw object via the iDirectDraw2 interface.
formula. Objects can be bundled with other objects at runtime and can use the interfaces of these objects. If you already know an object is a COM object, and you know the object support
The interface, your application or other objects can determine the service that the first object can perform. One way to inherit all COM objects is the query interface method, which makes you indeed
Set an interface supported by an object and create a pointer to these interfaces.
1.2, iUnknown interface
All COM interfaces are derived from a interface called IUNKNOWN, which provides DirectX's control and operational multi-interface capabilities for object survival. Iunknown
Contains three methods:
.AddRef When an interface or another application is bundled up to an object, use the AddRef method to add the index value of the object to 1.
.QueryInterface is queried by the characteristics supported by pointer to a specific interface.
.Release reduces the index value of the object, which is released from memory when the index value is 0.
The addRef and the release method are responsible for maintaining the index value of the object. For example, if you create a DirectDrawSurface object, the index value of the object is set to 1, each
When there is a function returns a pointer to the object, the function must be added to the index value of the object by returning a pin. Every addRef is called
A Release call corresponds to it. When the index value of the object reaches 0, the object is revoked, and all interfaces of the object are not reused.
QueryInterface method Determines whether an object supports the specified interface, if support, QueryInterface returns a pointer to the interface. Then you can use the method to communicate with the object. If QueryInterface successfully returns a pointer to the interface, it automatically invokes the AddRef method to increase the index value of the object. Before the interpuls of the interface pointer
Call the Release to reduce the index value of the object.
1.3, DirectX COM interface
The interface in DirectX is created with considerable basic COM programming. Each interface characterized by the object of the device is derived from the IUNKNOWN COM interface, such as IDirectDraw2,
IdirectSound and IDirectPlay are like this. The creation of the basic object is handled by the special function in the dynamic link library DLL.
Typically, the DirectX object model provides a primary object for each device. Other support services are derived from the primary object. For example, DirectDraw objects
The display adapter is displayed. You can use DirectDraw to create DirectDrawSurface objects that represent memory and behave the DirectDrawPalette object that characterizes the hardware palette. same
The truth, the DirectSound object characterizes the audio card and uses it creates the DirectSoundBuffer object that represents the sound source.
In addition to enabling sub-objects, the main object of the device can also determine the performance of the device it characterizes, such as the size of the screen and the number of colors, whether the sound card supports wave form synthesis.
1.4, C and COM interface
For C programmers, the COM interface is like an abstract base class. In the base class of C , all methods are defined as pure, which means no code is the same.
Related together. The purely virtual C function and the COM interface use a device called a virtual table (VTABLE). A virtual table contains a declaration for all functions applied to the interface. in case
You want programs or objects to use these functions, you can check the interface where the object exists with the queryinterface method, get the pointer of the interface, call QueryInterface, apply or
The pointer to the virtual table is actually received from the object, and all interface methods applied to the object can be invoked by the pointer.
Another similarity of COM objects and C is the first parameter of the method is the name of the interface or class, and C is called this parameter. Because COM objects and C objects are complete
Binary compatibility, the compiler is equipped with the COM interface as the C abstraction class, and has the same syntax, which makes the code simple.
1.5, get a new interface
The component object model is not a function of updating the object by changing a new interface containing new features by changing the existing interface. Situation in the existing interface status
Next, the COM object is free to expand the service and maintains the same old application compatibility. DirectX components follow this principle, for example, DirectDraw parts support iDirectdrawsurface interface
Three versions: iDirectdrawsurface, IDirectdrawsurface2 and iDirectdrawsurface3. To use the features provided by the new interface, you must call the object
IUNKNOWN :: QueryInterface method, specify the global unified identity of the interface to get to get the GUID (Global Unique Identifier). The GUID of the interface is declared in the relevant header file.
The following example shows how to query a new interface:
LPDIRECTDRAW LPDD1;
LPDIRECTDRAW2 LPDD2;
DDRVAL = DirectDrawCreate (NULL, & LPDD1, NULL);
IF (Failed (DDRVAL)) Goto Errorout;
// query for the iDirectdraw2 interface
DDRVAL = LPDD1-> query interface (IID_IDIRECTDRAW2, (Void **) & lpdd2);
IF (Failed (DDRVAL))
Goto errorout;
// now That We Have An IDirectDraw2, Release The Original Interface
LPDD1-> Release ();
The new interface does not support the method provided by the previous version of the interface, and the IDirect3ddevice2 interface is just such an interface. If your application requires an earlier version
The features provided by the interface you can use the GUID of the old interface, use the above-described routine to query the interface.
1.6, access COM object with C
Any COM interface method can also be called using the C language. Calling an interface method with C language requires main two things:
The first parameter of the method is always the object (ie this) that has been created.
Each method in the interface is referenced by a pointer to the object.
The following example uses the C language to create a surface that is associated with the same DirectDraw object using CreateSurFace method:
RET = LPDD-> LPVTBL-> CreateSurface (LPDD, & DDSD, & LPDDS,
NULL);
Where the LPDD parameter is the DirectDraw object associated with the new surface, and the method fills a structure & DDSD that describes the surface (SURFACE), returning to the new interface & lpdds
Pointer. Call the IDirectDraw2 :: createSurFace method, first point to the virtual table of the DirectDRAW object, then get the method in the virtual table. The first parameter provided in the method
It is an index of the DirectDraw object that has been created. The following code illustrates the differences between C and C to COM object method calls:
Ret = LPDD-> CreateSurface (& DDSD, & LPDDS, NULL)
Second, the new content in DirectX 5
Everyone knows that DirectX 5 is the latest version of DirectX. Before this, Microsoft has released DirectX, DirectX2, DirectX3 (without DirectX4). Obviously, DirectX
5 provides more features and services than DirectX3, but the programs written by DirectX3 API can be successfully compiled and running without modification. Below is DirectX5 and DirectX3
The main difference:
2.1, DirectDraw
DirectDraw extends new video port capabilities, allowing applications to control data streams from the hardware video port to the DirectDRAW surface in memory. In addition, DirectDraw
Hardware Simulation Layer Hel (Hardware Emulation Layer) can use the acceleration performance provided by the Pentium MMX processor. DirectDraw detects when you first create a surface
The processor is the MMX processor, on the non-Pepsc processor's computer, the test will cause the debugger to report an event, which does not affect the performance and stability of the program.
DirectDraw supports a wide-screen surface (OFF-Screen Surface) than the primary surface, as long as the hardware allows, you can create a sufficiently wide surface.
DirectDRAW supports the Advanced Graphics Port feature. In an AGP device system, you can create a surface in a non-local display memory. DDSCAPS Structure Support Standard (Local) Display Memory and AGP (Non-Local) Display Memory Different Signs. DirectDRAW can transmit DDCAPS structures to non-local display block blocks
Member information.
2.2, DirectPlay
DirectPlay contains a new interface IDirectPlay3, other than iDirectPlay2 except for new methods. Similarly, IDirectPlayLobby2 is also
The upgrade version of IDirectPlayLobby. Directplay's new features include the ability to hide the service provider (Service Provider) by creating connection shortcuts,
Hold the list of updates available sessions, apply the setSessionDesc method to better support password protection sessions, support confidential service connections and use CoCreateInstance to create multiple
DirectPlay object.
2.3, DirectSound
DirectSound contains a new interface IKSPROPERTYSET that supports extended services provided by the sound card and related drivers. COM-based function DirectSOUNDCAPTURE
Also new, it can access the driver directly.
2.4, Direct3D
Direct3D instant mode (IMMEDIATE MODE) now supports Drawing Primitive without having to work directly in the buffer. Direct3D Reserved Mode (Retained Mode)
Support interpolation allows you to adjust colors, smoothly moving objects, deformed grids, and perform many other transformations. The retention mode also supports progressive grid, that is, allow you to start starting with a thickness.
Rough grid and then refine it.
5, DirectInput
DirectInput provides a COM interface of the joystick, and also provides a COM interface of a keyboard and a mouse equivalent feedback device.
6, DirectSetup
DirectSetup now contains more user interface customization capabilities, which is provided by a callback function. This backup function passes the current installation status to the installer, you can
Use this information by customized user interface to display the installation status. In addition, DirectSetup provides a number of players' games, in the game, players can use
DirectPlayLobby removes registration information from the registry.
6. AutoPlay AutoPlay is the same as DirectX3, not changed.
DirectX5.0 Latest Game Programming Guide
DirectDraw articles
DirectDraw is one of the main parts of the DirectX SDK, which allows you to display memory operations directly, support hardware bit block transfer, hardware coverage, surface flipping, and maintain a look
The front Windows-based application and driver are compatible.
DirectDraw is a software interface that keeps also compatible with Windows Graphics Device Interface in addition to the display device access.
For graphics, it is not an advanced application interface. DirectDRAW provides a method-free approilt that makes Windows-based applications and games (for example
3D graphics software package and digital video games) can directly obtain the characteristics of the display device.
DirectDraw can work in a wide variety of display devices, from simple SVGA displays to advanced display devices that provide shear, stretching, and non-RGB formats. DirectDraw
The interface allows your application to simulate the performance of basic hardware and use hardware acceleration features; hardware does not provide features will be simulated by DirectX. DirectDraw provides access to devices that display memory that makes you easily manage display memory. Your application only needs to identify some basic device properties, they are all standard hardware applications, such as RGB
And the color of the YUV format. You don't need to call special procedures to use bit blocks to transfer or manipulate palette registers. With DirectDraw, you can easily display memory, charge
Dividing the bit block transmission and color decompression function of different types of display devices without the need to rely on specific hardware. DirectDraw can run in Windows95 / NT4.0 and later versions
in.
DirectDraw's hardware abstraction layer HAL (Hardware Abstract Layer) provides a unified interface, through which program can be directly displayed memory or video memory
Work, get the best performance of hardware.
DirectDraw estimates the performance of video hardware, as long as you may use the specific performance provided by the hardware. For example, if the video card supports bit block transmission, DirectDraw will put
The bit block transmission is delegated to the video card, the CPU does not participate in the processing of bit block transmission, which greatly improves the performance of the program. In addition, DirectDraw provides hardware simulation layer HEL (Hardware
Emulation Layer allows software simulation to support the characteristics that should be provided by these hardware when some hardware does not exist.
DirectDraw runs on Windows 95, which can utilize 32-bit memory superiority and "flat" memory models provided by the operating system. DirectDraw will system memory and video
It is used as a large block storage rather than a small segment. In addition, DirectDraw also brought a lot of power for Windows graphics:
.DirectDraw makes the page turnover of multiple background buffers in full screen mode easy
Support window mode and cutting function in full screen mode
. Support 3D Z buffer
Hardware auxiliary coverage in support Z direction
. Access to hardware for image stretching
Access standard and enhanced display device memory area
Dynamic palette, exclusive hardware access, resolution switch, etc.
Combine these features together, you can easily prepare a game that exceeds GDI-based standard Windows games or even MS-DOS.
First, DirectDraw's basic image concept
DirectDraw offers a set of graphical terms that are different from GDI, so it is necessary to use DirectDraw, first you should understand the concepts. Here are the medium of DirectDraw
An introduction to the concept.
1.1 Device independent bitmap DIB (device-independent bitmap)
DirectX uses device-independent bitmap Dib as the primary graphic file format. A DIB file mainly protects the following information: the dimension of the image, the number of colors used, described
Color value and data describing each pixel. The DIB file also protects less use parameters, like information about file compression, and physical dimension of the image. DIB file extension is general
Yes ".bmp", sometimes it may be ".dib".
Because DIB is extremely widely used in Windows programming, DirectX SDK already contains many related functions. For example, DDUTIL.CPP files provided by DirectX SDK
There is a function that combines the Win32 and DirectX functions, the concept is to load a DIB file into the DirectX surface, the code is as follows:
Extern "C" iDirectdrawsurface * DDLoadBitmap (iDirectdraw * PDD,
LPCSTR SZBITMAP, INT DX, INT DY
{
Hbitmap HBM;
Bitmap BM; DDSURFACEDESC DDSD;
IDirectdrawsurface * pdds;
// this is the win32 part.
// Try to load the bitmap as a resource, if That Fails, TRY IT as a file.
HBM = (hbitmap) loading (getModuleHandle (NULL), SZBITMAP, Image_bitmap, DX, DY, LR_CREATEDIBSECTION;
IF (hbm == null)
HBM = (Hbitmap) loadImage (NULL, SZBITMAP, Image_bitmap, DX, DY, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
IF (hbm == null)
Return NULL;
// Get the size of the bitmap.
GetObject (HBM, SIZEOF (BM), & BM);
// Now, return to DirectX Function Calls.
// Create a DirectDrawSurface for this bitmap.
ZeromeMory (& DDSD, SIZEOF (DDSD));
Ddsd.dwsize = sizeof (ddsd);
DDSD.DWFLAGS = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
DDSD.DDSCAPS.DWCAPS = DDSCAPS_OFFSCREENPLAIN
Ddsd.dwwidth = bm.bmwidth;
DDSD.DWHEIGHT = BM.BMHEIGHT;
IF (PDD-> CreateSurface (& DDSD, & PDDS, NULL)! = DD_OK)
Return NULL;
DDCopyBitmap (PDDS, HBM, 0, 0, 0, 0);
DeleteObject (HBM);
Return PDDS;
}
1.2, drawing surface (Drawing Surface)
The drawing surface accepts video data and displays it as an image. In most Windows applications, you can use the Win32 function such as getDC to access the drawing table.
surface. GETDC Getting the Device Context DC (Device Context), after obtaining the device, you can redraw the surface. However, the image function of Win32 is provided by GDI.
GDI is part of the system that provides an abstract layer that allows the standard Windows program to draw surfaces.
The disadvantage of GDI is that it is not designed for high-performance multimedia software, which is mainly used for commercial software such as word processing and spreadsheet software. GDI provides videos in system memory
Access to the buffer, but do not provide access to video memory. Although GDI is very suitable for most commercial software, it is too slow to multimedia applications and game software.
On the other hand, DirectDraw provides a drawing surface that characterizes real video memory, which means that when you use DirectDraw, you can write data directly to the video, so that
The display speed of the image is fast enough. These surfaces are characterized as a continuous memory block that makes it easier to address addresses.
1.3, bit block transmission blit
Blit is a story of "Bit Block Transfer", indicating bit block transmission. It is a way to transmit a data of one address in memory to another address. Block transmission is often used
In the elf animation. You can use the iDirectdrawsurface3 :: BLT method and the iDirectdrawsurface3 :: Bltfast method to perform bit block transmission. 1.4, Page Flipping and Back Buffering
Page flips is the key to multimedia, animation, game software. The software page flip is an simulation of cartoon painters to motion image motion. For example, the painter draws a character on a piece of paper.
Then placed it in the working state of the next frame, and only the character image is changed for each frame. When you quickly flip the sheet of paper, the continuous character image seems to have an animation.
The page flips in the software is similar to the above process. First, you have established a series of DirectDraw surfaces, which are ready to "flip" to the screen. The first surface is seen
It is the primary surface, which is called a background buffer after all surfaces behind the main surface. The application writes data to the background buffer, then flip the main surface, so the background is slow
The punch is displayed on the side. When the system is displaying an image, the program can write data to the background buffer, which has continued until the end of the animation, which makes you fast and efficiently
Change the discrete image into an animation. DirectDRAW can utilize relatively simple double buffers (a main surface and a background buffer), you can also use more complex technologies.
Other background buffers. Make you can easily create a program that flipped.
1.5, rectangle
One of the most important concepts that run through DirectDraw and Windows is the object on the surface - a bounded rectangle. A bounded rectangle is determined by two points, namely the upper left corner and the right
angle. When writing data in a block transmission, most applications use the RECT structure to transmit information about the boundary rectangle. The RECT structure is defined as follows:
Typedef struct tagRect {
LONG LEFT; // this is the top-left corner's x-coordinate.
Long Top; // The top-left corner's y-coordinate.
Long Right; // The Bottom-Right Corner's X-Coordinate.
Long bottom; // the bottom-right corner's y-coordinate.
} Rect, * Prect, Near * nPRECT, FAR * LPRECT
Where the LEFT and TOP member variables are the value of the X, Y coordinate of the upper left corner of the rectangle, and Right and Bottom are the coordinate values of X, Y in the lower right corner.
1.6, Elf (Sprite)
Many video games use the elves. In the most basic sense, a wizy is an image that moves on the screen. The elves draw on a surface and covered on an existing background.
The synthetic image is sent to the screen.
1.6.1, Transparent Blitting and Color Key
The difficulty in the elf animation is the treatment of the elves of non-standard rectangles. Because the bit block transport function is working in a rectangular mode, your elf must be placed in a rectangle, not
Tube it is rectangular on the screen.
The elf image itself is not a rectangular, but it is included in the rectangular area. When the image is transferred to the destination when using the bit block to the destination, the pixels that do not belong to the elves are "transparent".
deal with. The programmer selects any color to create a wizard, which is used as a transparency "color key". It is an uncommon color, and the programmer is only used to indicate
Brightness or specific color range.
With the idirectdrawsurface3 :: setColorKey method, you can set the Color Key for a surface. After setting the Color Key, call the idirectdrawsurface3 :: bltfast method to use the set of Color Key, regardless of whether the pixel matches the color key. This type of Color Key is the source Color Key. Source Color Key prohibits "transparent"
The pixel is written to the destination, so that the original background pixel is retained, making the elf look up and the wizard can also move on the background.
In addition, you can also use a Color Key to influence the surface of the target (the purpose of the purpose of the purpose). Destination Color Key is also a color on the surface, which is used to indicate whether pixels are
Can be covered by the elves.
1.6.2, Sprite and Patch Rectangle (SPRITE AND PATCHLE)
In order to produce the effect of the elf movement, you must erase the elf image from the old position from the background before drawing the elf to the new location. Of course, you can also re-transfer the entire background
Heavy attention to the elves, but this will greatly reduce the quality of animation. In fact, you can keep the last trajectory of the elongated rectangle, and then redraw only the location. This method is called "patching".
In order to fix the outstanding position, you can use the original background image (already transferred to a screen outside the surface) to redraw this location. Block transmission is used in this process
Methods, in the cycle of the entire surface, it is necessary to consume very small processing time. Below is a simple step of this process:
(1). Setting the repair rectangle of the first position of the elf
(2). Use the bit block to transfer the primary copy of the background image in the outer surface of the screen to this position
(3). Update wizard is a rectangle of destination, which reflects the new position of the elf
(4). Transfer the wizard block to the latest updated rectangular position on the background
(5). Repeat
Combine the powerful image features provided by DirectDraw with a linear C / C program, using the above steps, you can create a simple elf animation.
1.6.3, boundary check and collision detection (Bounds Checking and Hit Detection)
In the elf animation, boundary inspection and collision detection is two very workshop and a very important task. The boundary is the scope of the restrictions, and the boundary check is through the RECT structure.
To check the location of the elves, determine if the wizel exceeds a defined range.
Collision detection is to check if multiple elves take up the same location. Most collision detection is to check if there is a coverage between the rectangles of each elf.
Second, the system of DirectDraw
Multimedia software requires high performance image. Through DirectDraw, Microsoft makes programs that are sensitive to image sensitivity are greatly improved in GDI,
At the same time, it maintains the device-independent, and the tools provided by DirectDraw can complete the following key tasks:
. Operation multiple display surfaces
Direct access to video memory
Page flip
Background buffer
Palette management
Shear
In addition, DirectDraw allows you to query the performance of the display of the hardware and then provide the optimal performance that the display device can support.
DirectDraw provides a COM-based service interface, using the most used iDirectdraw2, idirectdrawsurface3, idirectdrawpalette, idirectddrawclipper, and
IdirectDrawvideOport. In addition to these interfaces, DirectDraw continues to support previous versions of interfaces.
The DirectDRAW object is characterized to display the adapter, reveal its method through the iDirectdraw and the iDirectDraw2 interface. In most cases, you can use DirectDrawCreate
Function to create a DirectDraw object or use COM functions CocreateInstance.
Once you have created a DirectDraw object, you can call the IDirectDraw2 :: createSurface method to create a surface for that object. The surface characterizes the memory of the display hardware, which can be a video
Memory can also be system memory. DirectDraw expands support for palette, shear, and video ports through other interfaces.
1, DirectDraw object type
DirectDraw objects can be either a separate object or a combination of several objects. The latest version of DirectDRAW has the following types of objects:
1.1, DirectDRAW object
The DirectDraw object is the core of the DirectDraw application, which is the first object you created. Once you have created a DirectDraw object, you can create other sites on it.
Have related objects. Creating a DirectDraw object is DirectDrawCreate.
1.2, DirectDrawSurface object
The DirectDrawSurface object characterizes a memory area where data is displayed as an image on the screen or moves to other surfaces. Create DirectDrawSurface
The object's approach is iDirectdraw2 :: createSurface, other related methods can pass interface IDirectdrawsurface, IDirectdrawsurface2 and iDirectdrawsurface3
.
1.3, DirectDrawPalette object
DirectDrawPalette object (sometimes "Palette") characterizes a 16-color or 256 colored index palette that is surface, which contains a series of descriptions of the same surface.
Off RGB color index value. The method for creating a DirectDrawPalette object is iDirectdraw2 :: CreatePalette. Other methods can be obtained from the interface IDirectDrawPalette.
1.4, DirectDrawClipper object
DirectDrawClipper objects (sometimes "clipper") helps you write data to a location or exceeding the surface, create DirectDrawClipper
The method is iDirectdraw2 :: CreateClipper, and other related methods can be obtained from Interface IdirectDrawClipper.
1.5, DirectDrawVideoPort object
The DirectDrawVideoPort object characterizes some of the video port hardware with only one system, which allows you to access the frame buffer without accessing the CPU or using the PCI bus.
You can first specify the IDDVIDEOPORTCONTAINER flag, then call the QueryInterface method to create a DirectDrawVideoPort object. Other related methods can be from interface
IddvideoPortContainer is available in IdirectDrawVideoPort.
2, hardware abstraction layer HAL (Hardware Abstract Layer)
DirectDraw provides devices independence through hardware abstraction layer HAL. HAL is a special equipment interface and is provided by equipment manufacturers. DirectDraw uses HAL direct
Work on the display device. Applications and different HAL interactions. Equipment manufacturer provides HAL in the form of 16 or 32-bit code under Windows95, under WindowsNT,
HAL is 32-bit code. HAL can be part of the display driver, or a dynamic link DLL that displays the driver communication with the private interface defined by the manufacturer.
DirectDraw HAL is provided by a chip, a board or OEM (Original Equipment Manufacture). HAL only provides device-related code, not simulated when executed. If one is
The function is not supported by hardware, and HAL will not treat this function as part of hardware performance. In addition, HAL does not confirm the parameters, and DirectDRAW will work in the call to complete the parameters prior to calling HAL.
3. Software emulation
When hardware HAL does not support a feature, DirectDraw is trying to simulate this feature with software. The simulation function is Hardware-Emulation Layer by hardware simulation layer.
which provided. Obviously, software simulation is not equivalent to the characteristics of hardware itself. You can use the iDirectdraw2 :: getCaps method to query the features supported by the hardware.
Sometimes, the inherent characteristics of hardware and the combination of both software simulation are slower than the software simulation alone. For example, if the display device driver supports DirectDraw but not
Write the way to write the block, when stretched from the video memory surface or the bit block transmission, it will produce a loss of performance. Because video memory is usually slower than the speed of the system memory, in the access video memory
The CPU must wait. Therefore, if your application uses hardware unable to provide features, it is best to create a surface in system memory to avoid CPU access video memory.
Performance loss.
4, system composition (System Integration)
The following figure shows the relationship between DirectDraw, graphics device interface GDI, hardware abstraction layer HAL, hardware simulation layer HEL, and hardware.
As shown in the figure, a DirectDRAW object is a parallel relationship with GDI, both through the device-related abstract layer access hardware. Different from GDI, DirectDraw as long as it is possible
It will make full use of the unique features provided by hardware. If the hardware does not support a feature, DirectDraw will try to simulate it with HEL. DirectDraw can also use the device context (Device
The Context is available in the form of surface memory, which you can use the GDI function to process surface objects.
Third, DirectDraw elements
The most basic elements in DirectDraw include collaboration level, display mode, DirectDraw object, surface, palette, cutting board, etc., the following is introduced one by one.
1, collaborative level (Cooperative Level)
Collaboration Level describes how DirectDRAW is interactive and the events that may affect the display. You can use the iDirectdraw2 :: setCoopeRarativeElevel method
Set collaboration level. In most cases, you can use the collaboration level to determine if the application runs in exclusive full screen mode or window mode. DirectDraw collaboration also has
The following role:
Make DirectDRAW to use X mode (Mode X) resolution.
If the user presses Ctrl Alt Del, the DirectDraw is prohibited from release the exclusive control and restart of the display (only in exclusive mode).
Make DirectDRAW to maximize and minimize events to respond to activated events.
The standard collaboration level indicates that the DirectDRAW program is a window application. In this case, you cannot change the palette and execution page of the main surface. In addition, you are still not
You can call those methods that have high degree of impact on display or video memory, such as IDirectDraw2 :: Compact.
Under the full-screen exclusive collaboration, you can use all of the hardware, set the usual palette and dynamic palette, change the display resolution, compact memory, and page flip. Full screen
The model does not prohibit other application allocation surfaces, nor does it prohibit them from using DirectDraw and GDI, but prohibiting other development applications changing display resolution and palette.
Because the application can use DirectDraw at multi-window, when the application requires work in DDSCL_NORMAL mode, the iDirectDraw2 :: setCoopeRATIVELEVELEVELEVELEVELEVELEVELE Way does not require a specified window handle. Pass NULL to the window handle, all of which work simultaneously in standard window mode.
2, display mode (Display Modes)
The display mode is a description of the size and bit-depth of the image that the display hardware is transmitted from the main surface to the display. The display mode can be combined to: width, high and bit depth. example
For example, most display adapters can display a wide range of 640 pixels, 480 pixels, and a data image of 8 bits per pixel, which is 640x480x256.
To get a larger resolution or bit depth, you need more display memory.
There are two types of display mode: color mode and non-torch mode. For toning display modes, each pixel is a pointing value pointing to the correlation palette. Display mode depth
The number of colors that can have in the palette is determined. For example, for an 8-bit color display mode, each pixel is a value from 0 to 255. In this display mode, the palette
Can contain 256 colors. The non-toning display mode does not use a palette, the bit depth in this mode indicates the total number of bits used to describe a pixel.
Any surfaces in the main surface and the main flush chain should be matched with the size, bit depth of the display mode, the bit depth, and pixel format.
2.1, detect the supported display mode
Because the display hardware is displayed, not all devices support all display modes. To detect the display mode supported by the system, you need to call
IDirectdraw2 :: EnumdisplayModes method. By setting the appropriate value and flag, the IDirectdraw2 :: EnumDisplayModes method can list all supported display mode,
Can also determine if a specified display mode is supported.
The first parameter DWFLAGS control method of the method controls the other options, usually set DWFLAGS to 0 to ignore other options; the second parameter LPDDSurfaceDesc is used
To describe the address of the structure DDSurfaceDesc to which the display mode is given, all modes can be set to NULL. The third parameter lpContext is a pointer.
DirectDRAW needs to pass the pointer to the callback function, if there is no additional data in the callback function, it can be set to NULL. The last parameter is
LpenumModesCallback, it is the address of the callback function called for each supported display mode call.
The callback function provided when calling the IDirectDraw2 :: EnumDisplayModes method must match the prototype of the EnumModesCallback function. For each of the hardware
The display mode, DirectDRAW calls your callback function to pass two parameters, the first is the address of the DDSurfaceDesc structure, which describes a supported display mode;
The second parameter is the address of the application defined when calling idirectdraw2 :: enumdisplayModes.
By checking the value of the DDSurfaceDesc structure to get the display mode it described, where the key members are dwwidth, dwheight, and DDPFPixElFormat. DWWIDTH
And dwheight describes the size of the display mode; DDPFPixElFormat is a DDPixElFormat structure that contains information about the depth of bit.
The DDPixelformat structure includes information describing the display mode bit depth and indicates whether the display mode uses a palette. If the dwflags member contains
DDPF_PALETTEINDEXED1, DDPF_PALETTEINDEXED2, DDPF_PALETTEINDEXED4 or DDPF_PALETTEINDEXED4 or DDPF_PALETTEINDEXED8 logo, the bit depth of the display mode is 1, 2, 4 or 8, and each pixel is an index of a phased palette. If dwflags contains a DDPF_RGB flag, the display mode is non-toner.
Display mode, and its bit depth is provided by DwrGbbitCount members in the DDPixelformat structure.
2.2, set display mode
You can call the iDirectdraw2 :: setDisplayMode method to set the display mode. This method accepts four parameters to set the size, bit depth and refresh of the resolution of the display mode.
rate. It uses the fifth parameters to specify a special option for a given mode, which is currently only used in 13 mode and X mode 320x200x8.
You can specify the bit depth of the desired display mode, but you cannot specify a pixel format that displays the hardware for the depth of the bit. To detect the RGB bit for display hardware for the current position depth
Shield, you can call the IDirectDraw2 :: getDisplayMode method after setting the display mode. If the current display mode is non-toning mode, you can check DWRbitmask,
DwGbitmask and the value in dwbbitmask get the positive red, green, and blue color position.
You can also change the display mode through multiple applications, as long as they share the same display card. You can also change the depth of the position, as long as the application can discuss DirectDraw exclusive
Objects, all DirectDrawSurface objects release surface memory after the display mode changes, so after changing the display mode, you must use iDirectdrawsurface3 :: Restore
The method is re-assigned to the object.
2.3, recovery display mode
If the display mode is done by calling the IDirectDraw2 :: SetDisplayMode method (not the iDirectdraw :: setDisplayMode method), you can call
IDirectdraw2 :: RestoredISplayMode method to restore to its original display mode. If the application is a single collaborative level, when you set the application's collaboration level
When the display mode is automatically restored to the original mode. If you use the DirectDraw interface, you must explicitly recover the display mode.
2.4, x mode and 13 mode
DirectDraw supports x mode and 13 mode two types of display modes. 13 mode is 320x200, each pixel is 8-bit color mode, and its 16-encycloped BIOS mode number is 13. mode
X is a mixed mode derived from a standard VGA 13 mode that allows the use of 256 KB display memory (13 mode only allows the use of the display memory).
Under Windows95, DirectDraw provides two X modes for all display cards (320x200x8 and 320x240x8). Some display cards also support linear low resolution mode,
Linear low resolution is silently up and down, the main surface can be locked or directly accessed, which is not allowed in x mode.
Just use DDSCL_AllowModex, DDSCL_FULLSCREEN, and DDSCL_FULLSCREEN and
DDSCL_EXCLUSIVE flags, X mode is available. If you do not specify a DDSCL_AllowModex flag, iDirectdraw2 :: EnumdisplayModes method is not
List the X mode, when requesting the x mode, the call to the idirectdraw2 :: setDisplayMode method will fail.
When the application does not use the idirectdrawsurface3 :: locksurface3 :: locksurface3 :: lock or idirectdrawsurface3 :: bLT method, write data to the main surface block, or you cannot use the idirectdrawsurface3 :: getDC method in the main surface or screen DC. X mode is specified by the DDSCAPS_MODEX flag in the DDSCAPS scapula, DDSCAPS
The structure is part of the DDSurfaceDesc structure returned by idirectdrawsurface3 :: getCaps and iDirectdraw2 :: EnumdisplayModes method.
2.5, high resolution and true color
DirectDraw supports all screen resolutions and bit depths supported by the display device driver. DirectDraw allows applications to change display mode to any computer display
The driver supported display mode, including 24-bit and 32-bit (true color) mode.
DirectDraw also supports the HEL block transmission of true color surfaces. If the display device driver supports bit block transmission at these resolutions, the memory - display memory bit block
Transfer will use hardware blocks, otherwise heel will use HEL to increase the performance of bit block transmission.
Windows95 and NT allow you to specify the type of display that is being used. DirectDraw checks a list of known display modes, if DirectDRAW detects the required mode
This monitor is not compatible, and the call to the idirectdraw2 :: setDisplayMode method will fail. When you call Method Idirectdraw2 :: EnumdisplayModes, only the display
The supported mode will be listed.
3, DirectDRAW object
The DirectDraw object is the core of all DirectDraw applications, as well as an organic component of the Direct3D application. DirectDraw object is the first one you created
Objects, create other related objects by this object. Generally create a DirectDraw object by calling the DirectDrawCreate function, the function returns an IDirectDraw connection
mouth.
DirectDraw objects characterize the display device. If the display device supports hardware acceleration, the DirectDRAW object can also utilize hardware acceleration. Every DirectDraw
Objects can process display devices and create surface objects, palette objects, palette objects, and clipboard objects that depend on the DirectDRAW object. For example, create a surface that needs to be called
IDirectDraw2 :: CreateSurface method, to attach a palette object on the surface, you need to call the IDirectDraw2 :: CreatePalette method. In addition, iDirectDraw2 is connected
The mouth also contains a similar method for creating a shear board object.
You can create multiple instances of a DirectDRAW object at the same time. The easiest example is the use of dual displays in a Windows95 system. Although Windows95 does not support more
The display is possible to write a DirectDraw hardware abstraction layer for each display device. Windows95 and GDI can identify display devices in creating default DirectDraw objects
The instance will be used. The display devices that Windows95 and GDI cannot be identified can be characterized by another independent DirectDRAW object. The object must use the second display device.
The Unified Identifier is created, and this GUID can be obtained by the function DirectDrawenumeRate.
DirectDRAW objects manages all other objects it created. It controls the default palette, Color Key, and hardware display mode, which also has allocated resources and retained resources
Make a marker.
The new version of DirectDraw adds new content in previous versions. The IDIRECTDRAW2 interface is increasing the IDIRECTDRAW2 :: GetAvailableVidmem method
The iDirectDRAW interface is expanded. This method allows you to query the display device's total available video memory and how much memory is used for one specified surface. IdirectDraw2 :: SetCoopeLevel method The interaction between IDirectdraw2 :: SetDisplayMode is different from these methods in the iDirectDRAW interface. If you should
Use the program
The iDirectDRAW interface sets the collaboration level of full-screen exclusive way and changing the display mode. When the standard collaboration level is returned, the display mode will not be automatically recovered, you must call
The iDirectdraw :: RestoredISplayMode method is explicitly recovered. If you use the IDirectDraw2 interface, the call to RestoreMode is not required. however
The iDirectdraw2 :: RestoredISplayMode method does not support explicitly recover the original display mode.
COM-based COM specifies that an object can provide new features by adding new interfaces without affecting its backward compatibility. So IdirectDraw2 interface can
Instead of the IDirectDRAW interface. The new interface can be obtained by iDirectdraw :: queryInterface method, as shown in the C code below:
// CREATE An IDirectDraw2 interface.
LPDIRECTDRAW LPDD;
LPDIRECTDRAW2 LPDD2;
DDRVAL = DirectDrawCreate (NULL, & LPDD, NULL);
IF (DDRVAL! = DD_OK)
Return;
DDRVAL = LPDD-> SetCooperativeElevel (hwnd,
DDSCL_NORMAL);
IF (DDRVAL! = DD_OK)
Return;
DDRVAL = LPDD-> QueryInterface (IID_IDIRECTDRAW2,
(Lpvoid *) & lpdd2);
IF (DDRVAL! = DD_OK)
Return;
A DirectDraw object is created in the example, then call the iUnknown :: queryinterface method for the iDirectDraw interface to create an IDirectDraw2 interface.
After getting an IDirectDraw2 interface, you can call its method to utilize the advantages of its new features. Because some methods may vary in the new version of the interface, so
Mixing using different versions of interfaces (such as IDirectDraw and iDirectDraw2) may result in unpredictable errors.
3.1, multiple DirectDRAW objects in each process
DirectDraw allows multiple DirectDrawCreate functions to be called multiple times in a process. Returns a unique independent independence every unique independent DirectDraw object after each call
Interface. Each DirectDRAW object can be used for the required relationship between the objects. Each object is like being created in the process alone.
DirectDrawSurface objects created by each DirectDraw object, DirectDrawPaletTe objects cannot be used by other DirectDraw pairs
Like use, because these objects are automatically undo when their parent target DirectDRAW objects are canceled.
The DirectDrawClipper object created using the DirectDrawCreateClipper function is an exception, and the DirectDrawClipper object in this case is independent of other arbitrary
DirectDRAW objects and can be used for one or more DirectDraw objects.
3.2, create a DirectDraw object with CoCreateInstance
You can also create a DirectDraw object using the CocreateInstance function and the iDirectDraw2 :: initialize method without using the DirectDrawCreate function. Below is the step of creating a DirectDraw object with a CoCreateInstance function:
i. Call Coinitialize initialization COM:
Failed (Coinitialize (NULL)))
Return False;
II. Create a DirectDraw object using the CocreateInstance function and iDirectdraw2 :: initialize method:
DDRVAL = CoCreateInstance (& clsid_directdraw,
NULL, CLSCTX_ALL, & IID_IDIRECTDRAW2, & LPDD);
IF (! failed (ddrval))
DDRVAL = iDirectdraw2_initialize (lpdd, null);
In the call to COCREATEINSTANCE, the first parameter CLSID_DIRECTDRAW is the class flag of the DirectDraw driver object class, and the IID_IDIRECTDRAW2 parameter is indicated.
The DirectDraw interface to create, the LPDD parameter points to the acquired DirectDraw object. If the call is successful, the function will return the DirectDRAW object that has been initially initialized.
Before using the DirectDraw object, you must also call the iDirectdraw2 :: initialize method, which does not use the GUID parameter (DirectDrawCreate function requires only as long as it is).
After the DirectDraw object is initialized, you can use it or release the object, just that the object is created by the DirectDrawCreate function. If you are calling
The approach to the IDirectdraw2 :: Initialize method will cause a DderR_notinitialized error.
Before closing the application, you should use the CounInitialize function to close the COM, the form is as follows:
Counitialize ();
4, surface (SURFACE)
A surface or DirectDrawSurface object characterizes a linear memory area. The surface usually resides in the display memory, and of course, it can also exist in system memory. Unless clear
Specify, DirectDraw places the DirectDrawSurface object where you can get the best performance when you create a DirectDrawSurface object. DirectDrawSurface object
It is also possible to use the special processor on the display card, which can not only speed up the execution speed of the task, but also to handle some tasks with the system CPU parallel.
With the iDirectdraw2 :: CreateSurface method, you can create a single surface object, a complex surface flip strand and a three-dimensional surface. Create your you want to use the CreateSurface method
Survey surface or flip chain and get a pointer to the IDirectdrawSurface interface of the main surface.
The IDirectDrawSurface3 interface allows you to access memory directly with bit block transmission methods, such as IDirectDrawSurface3 :: BLTFAST methods, etc. Surface object can improve a device
Here, it allows you to use the GDI function. In addition, you can access the display memory between the iDirectDrawSurface3 method. For example, you can use iDirectdrawsurface3 :: LOCK
Method locks the display memory and obtains the address of the relevant surface. The address of the display memory may point to the visible buffer memory (main surface) or invisible buffer (exterior surface or overlay surface).
Inasoless buffers typically reside in the display memory, but can be created in system memory, if the hardware allows or DirectDRAW uses software simulation functions. In addition, the IDirectdrawSurface3 interface extends some ways. With these methods, you can place or get the palette to work in the specified type surface.
4.1, surface interface (Surface Interface)
The DirectDrawSurface object expresses its function via IDirectdrawSurface, IDirectDrawSurface2, and iDirectDrawSurface3 interface. Each new version of the connection
The mouth has improved the same functionality as previous versions, and the features that have not been have emerged in the old version through new methods.
The oldest version in this class interface on the IDirectdrawSurface interface, when you use the idirectdraw2 :: createSurface method to create a surface, the default is this interface.
To use the new features provided by another version, you must also query the new version of the interface with the queryinterface method. The following code shows how to complete this:
LPDIRECTDRAWSURFACE LPSURF;
LPDIRECTDRAWSURFACE2 LPSURF2;
// CREATE SURFCES.
MEMSET (& DDSD, 0, SIZEOF (DDSD));
Ddsd.dwsize = sizeof (ddsd);
DDSD.DWFLAGS = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
DDSD.DDSCAPS.DWCAPS = DDSCAPS_OFFSCREENPLAIN |
DDSCAPS_SYSTEMMORY;
DDSD.dwwidth = 10;
DDSD.DWHEIGHT = 10;
DDRVAL = LPDD2-> CreateSurface (& DDSD, & lPSURF, NULL);
IF (DDRVAL! = DD_OK)
Return;
DDRVAL = LPSURF-> QueryInterface
IID_IDirectDrawSurface2, (lpvoid *) & lpsurf2);
IF (DDRVAL! = DD_OK)
Return;
DDRVAL = LPSURF2-> PageLock (0);
IF (DDRVAL! = DD_OK)
Return;
DDRVAL = LPSURF2-> PageUnlock (0);
IF (DDRVAL! = DD_OK)
Return;
The above example got the IDirectDrawSurface2 interface of the DirectDrawSurface object by specifying the IID_IDIRECTDRAW2 flag when calling the queryinterface method. want
Want to get the IDirectdrawSurface3 interface, use the IID_IDIRECTDRAWSURFACE3 flag instead of IID_IDirectDraw2.
4.2, Color Key
DirectDraw supports bit block transmission and overriding Source Color Key and destination Color Key. Set the table by calling the IDirectdrawSurface3 :: SetColorKey method
Color Key of the face. When using the bit block transmission, the source color key indicates the color or color range that is not copied, and the destination Color Key indicates the replaced color or color range.
Some hardware only support the color range of YUV pixel format. YUV data is usually video data, and the transparent background may not be a single color due to the quantization error in the conversion.
Color Key is specified with the pixel format of the surface. If the surface is a color format, the Color Key is specified as the range of indexes or indexes. If the surface of the pixel format is described by describing YUV
Fourcc code specified in the format, YUV Color Key is two members in three DDColorKey DWColorspacelowValue and DWColorspacehighValue
The three bytes are specified, and the three bytes are V, U, Y data, respectively. The dwflags parameter in the IDirectdrawSurface3 :: setColorKey method indicates whether the Color Key is overwritten or
The bit block transfer operation is whether it is a source color key or a destination color key. The following code is some examples of valid Color Key:
// 8-digit tone mode
// The palette entity 26 is a Color Key.
DWCOLORSPA PartLOWVALUE = 26;
DWCOLORSPACEHIGHVALUE = 26;
// 24 true color mode
// Color 255, 128, 128 is Color Key.
DWCOLORSPACLOWVALUE = RGBQUAD (255, 128, 128);
DWCOLORSPACEHIGHVALUE = RGBQUAD (255, 128, 128);
// Fourcc YUV mode
// any yuv color where y is between 100 and 110
// and u or v is Between 50 and 55 is transparent.
DWCOLORSPA PartLOWVALUE = YUVQUAD (100, 50, 50);
DWCOLORSPACEHIGHVALUE = YUVQUAD (110, 55, 55);
4.3, Pixel Format
The pixel format points out any explanation of each pixel data in surface memory. DirectDRAW describes various pixel information using the DDPixElFormat structure.
Members of the DDPixelformat structure describe the following characteristics of the pixel format:
Pinjet or non-torched pixel format
If it is a non-toner format, the pixel format is RGB or YUV format
Position depth
Position shielding of pixel format components
You can call the iDirectdrawsurface3 :: getpixelformat method to get the pixel format of the existing surface.
4.4, create a surface
The DirectDrawSurface object characterizes a surface that resides in the display memory. If the memory is displayed or explicitly created, the surface can also exist in system memory.
You can create one or more surfaces using the iDirectdraw2 :: CreateSurface method. When you call createSurface, you must specify the size of the surface, the surface type (is a single surface
It is a complex surface), pixel format (if the surface does not use the indexed palette). All of these features are included in the DDSurFacesc structure, which needs to be used when calling
The address is transmitted. If the hardware does not support request, the call will fail if those resources have been assigned to another DirectDrawSurface object.
Creating a single surface or multi-surface requires only a few lines of simple code. There are four main steps to create a surface. Every step needs more preparations than the previous step, but
Not too difficult, they are:
(1). Creating the main surface
(2) Create a screen outside the surface
(3). Create complex surfaces and flip chains
(4). Create a wide surface
In the default, DirectDraw creates a surface in the local video memory. If enough local video memory saves the surface, DirectDraw tries to use non-local videos.
Memory (only in some AGP device systems). You can explicitly specify the surface in which type memory is explicitly indicated to the DDSCAPS structure with the appropriate flag when calling createSurface.
4.4.1, create a main surface
The main surface is the surface currently visible on the monitor and indicated by the DDSCAPS_PRIMARYSURFACE flag, and each DirectDRAW object can only have a main surface. When you create a home surface, its size should match the current display mode. Therefore, in this case you don't need to indicate the size of the surface. In fact, if you indicate the surface
Size, even with the current display mode, it will also result in failure of the creation process.
The following example shows how relevant members of the DDSurfaceDesc structure are set to create the main surface:
DDSURFACEDESC DDSD;
Ddsd.dwsize = sizeof (ddsd);
// Tell DirectDraw Which Members Are Valid.
DDSD.DWFLAGS = DDSD_CAPS;
// Request a primary surface.
DDSD.DDSCAPS.DWCAPS = DDSCAPS_PRIMARYSURFACE;
4.4.2, create a screen outer surface
The exterior surface of the screen is usually used for the cache of bitmaps, which will be transferred by bit blocks into the main surface or background buffer. You must set the containing DDSC_WIDTH and DDSD_HEIGHT standard
Logging and setting dwwidth and dwheight members as the appropriate value to illustrate the size of the screen outside. In addition, DDSCAPS_OFFSCREENPLAIN must also be included in the DDSCAPS structure.
Sign.
DirectDraw uses system memory to create a surface when there is not enough display memory usage. You can include DWCAPS members in the DDSCAPS structure
DDSCAPS_SYSTEMEMORY or DDSCAPS_VIDEMEMORY flags explicitly indicate whether to create a surface in display memory or in system memory. The following example shows
Prepare the preparation before creating an exterior surface:
DDSURFACEDESC DDSD;
Ddsd.dwsize = sizeof (ddsd);
// Tell DirectDraw Which Members Are Valid.
DDSD.DWFLAGS = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
// Request a Simple Off-Screen Surface, Sized
// 100 by 100 pixels.
DDSD.DDSCAPS.DWCAPS = DDSCAPS_OFFSCREENPLAIN
Dwheight = 100;
DWWIDTH = 100;
In the previous version of DirectX, the maximum width of the exterior surface cannot exceed the width of the main surface. In DirectX 5, you can create an exterior surface of any width, as long as the display is displayed
Prepare it. It should be noted that when the width of the exterior surface is declared, if the width of the surface of the requested surface is displayed, the surface will be created in the system memory. If
The use of video memory, while the video memory is not enough, the job created will fail.
4.4.3, create complex surfaces (Complex Surface) and flipping chain (FLIPPING CHAIN)
A complex surface is a combination of a set of single surfaces created with the iDirectdraw2 :: CreateSurface method. Set it when CreateSurface is called
DDSCAPS_COMPLEX flags, in addition to explicitly specified surfaces, DirectDRAW will also implicate one or more surfaces. You can manage complex tables as manageing a single surface
surface. Call iDirectDraw :: Release method Releases all surfaces, call IDirectdrawSurface3 :: Restore to recover these surfaces.
The most commonly used complex surface is a flip chain. Typically, a flip chain consists of a major surface and one or more background buffers. The DDSCAPS_FLIP flag shows that a surface is part of a flip chain. Creating a flip chain with this way also requires the DDSCAPS_COMPLEX flag. The following example creates a preparation required for a main surface flip chain:
DDSURFACEDESC DDSD;
Ddsd.dwsize = sizeof (ddsd);
// Tell DirectDraw Which Members Are Valid.
DDSD.DWFLAGS = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
// Request a primary Surface with a single
// Back Buffer
DDSD.DDSCAPS.DWCAPS = DDSCAPS_COMPLEX | DDSCAPS_FLIP |
DDSCAPS_PRIMARYSURFACE;
DDSD.DWBACKBUFFERCOUNT = 1;
This example constructs a double buffer overwhelming environment. Call the IDirectdrawSurface3 :: Flip method to swap the surface memory of the main surface and the background buffer. If DDSURFACEDESC
The member DwBackBufferCount in the structure is 2, and two back buffers will be created. The surface is turned around each time the FLIP will be looped and the three buffer overwhelming environments are provided.
4.4.4, create a wide surface (Wide Surface)
DirectDraw allows you to create an exterior surface that is wide than the main surface, of course, this needs to display hardware support. To determine if the display device supports the wide surface, you need to call
IDirectDraw2 :: getCaps method, see if DWCAPS2 members in the first DDCAPS structure include DDCaps2_WIDesurface flags. If the logo exists,
It is indicated that the outer surface of the exterior surface that is wider than the main surface can be created in the video memory. If the flag does not exist, create a wide surface in the video memory will fail, and return one
DDERR_INVALIDPARAMS error.
The system memory surface, the video port surface, and the buffer are supported by the wide surface.
4.4.5, flipping surface (Flipping Surface)
Any surfaces in DirectDraw can be constructed as a flip surface. A flip surface is capable of visiting the Front Buffer and Back Buffer
Arbitrary memory between mutual exchange. Typically, the front buffer is the main surface, but this is not required.
When using the IDirectDrawSurface3 :: FLIP method to perform surface flip operation, pointing to the surface memory of the main surface and a pointer to the surface memory of the background buffer interchange. Therefore, the surface
Flip is a display device to point to the pointer to the memory, not a copy of the surface memory. The only exception is that when DirectDraw is flipped with software simulation, it is simply copy table.
surface. DirectDraw uses software simulation to flip operations with software simulation when a background buffer cannot be loaded into memory or hardware does not support DirectDraw. When a flip chain contains one
When the main surface and multiple background buffers, the transition of the pointer uses the cycle of the way, as shown below:
Other additional surfaces of the DirectDraw object are not part of the flip chain, not affected by the FLIP method. Remember, the DirectDraw flip surface is swaping DirectDrawSurface
The object surface memory pointer is implemented instead of exchanging these objects. This means that when the bit block is transmitted to the background buffer, you must always use the same DirectDrawSurface object.
The buffer is a background buffer you create a flip chain. The pointing operation is always done by calling the FLIP method of the front desk buffer.
4.4.6 Losing Surface When the DirectDrawSurface object characterizing the surface memory is unnecessary, the surface memory associated with the surface is released. This is to lose the surface. DirectDrawSurface
Object When you have its surface memory, many methods do not perform other operations and return DDERR_SURFACELOST.
Since the display mode or another application has released all surface memory that is currently allocated, the surface may be lost.
The iDirectdrawsurface3 :: RESTORE method Recreate these lost surfaces and re-connects with the DirectDrawSurface object. The recovery surface does not place the position before the surface is lost.
Fig. Therefore, if the lost surface must be completely reloaded into the previously loaded graphics.
4.4.7, release surface (Releaseing Surface)
Like all COM interfaces, you must call the Release method to release the surface when you don't need a surface. Each individually created surface must be explicitly released. If it is a tuning
Explicitly created multiple surfaces (such as flip chains, etc.) explicitly created with IDirectdraw2 :: CreateSurface or iDirectdraw :: CreateSurface, you only need to release the front buffer. in
In this case, any pointer pointing to the surface of the background buffer will be explicitly released, and it is not available.
4.4.8, update surface characteristics (Updating Surface Characteristics)
You can use the iDirectdrawsurface3 :: setsurfaceDesc method to update features of the surface. Use this method to change the pixel format, or change DirectDrawSurface
There is a location in the system memory in the surface of the object, which is explicitly assigned by the application. It allows a surface directly using data in the previously assigned buffer without having to copy,
This new surface memory is allocated by the customer application and is also released by the customer.
When calling the idirectdrawsurface3 :: setsurfaceDesc method, the LPDDSD parameter must be the address of the structure of the new surface memory, which is point to
The memory address pointer. In the DDSurfaceDesc structure, only DWFLAGS members can be set to reflect the location, size, and pixel format of the surface memory. So dwflags can only
Contains a combination of DDSD_WIDTH, DDSD_HEIGHT, DDSD_PITCH, DDSD_LPSURFACE, and DDSD_PIXELFORMAT, etc., use these combinations to set
Effective structural members.
Before setting the value of the structure, you must allocate the memory to load the surface. The size of the assigned memory is very important. Not only do you need to assign enough memory to accommodate the width and high surface, you still need
To leave a sufficient memory space for the surface spacing (PITCH), the surface spacing is a Qword (8 bytes), the spacing is height rather than the pixel metric.
When setting the value of the surface in the structure, the LPSURFACE member is a pointer you assigned, DwHeight and DWWIDTH members describe the size of the surface in pixel units. If specified
The size of the surface also needs to populate the IPITCH member to reflect the surface spacing. DDPFPixelformat members describe the pixel format of the surface. In addition to the LPSurface members, if you don't make these
Corresponding value, IDirectDrawSurface3 :: setSurfaceDesc method uses the default value from the current surface.
Pay attention to some problems when calling the IDirectDrawsurface3 :: setSurfaceDesc method. For example, LPSurface must be a valid pointer for system memory (this method is not currently supported
Video memory pointer); DWPIDTH and DWHEIGHT must be a non-zero value; the main surface or other surface cannot be reassigned in the primary conversion chain. You can assign the same memory for multiple DirectDrawSurface objects, but you must notice that the memory is allocated to the memory when the memory is assigned to any surface object. Correct
The incorrect use of the setSurfaceDesc method can result in unpredictable reactions. Therefore, when you no longer need surface memory, you must remember to release it. However, when calling this method, DirectDraw
The surface memory explicitly assigned when the release is created.
4.4.9, directly access the frame buffer (Accessing the frame-buffer directly)
You can use the iDirectdrawsurface3 :: Lock method to directly access the surface memory in the frame buffer or system memory. When this method is called, the LPDESTRECT parameter is a RECT.
Structure pointer. This structure describes a rectangle on the surface to be directly accessed. To lock the entire surface, you can set the LPDESTRECT to NULL. You can also specify a surface that only contains the surface.
Part of RECT. If there is no two rectangles overlap, two processes can lock multiple rectangles in a surface.
The LOCK method fills the DDSurfaceDesc structure with all the information that needs to properly access the surface memory. This structure contains information about surface spacing and pixel format (in the same master
The pixel format of the surface is not at the same time). After completing access to the surface, call the iDirectdrawsurface3 :: UNLOCK method to unlock it.
4.4.10, use non-local video memory surface (use non-local video memory ")
DirectDraw supports advanced graphics port AGP (Advanced Graphics Port) features that can create surfaces in non-local video memory. In the AGP system, if the local view
Frequency memory has been used or the application explicitly requires non-local memory, and DirectDRAW will create a surface using a non-local video memory.
Currently, there are two AGP systems. One is "Execute Model), one is Direct Memory Access Model. In the execution model,
The display device supports non-local video memory and local video memory the same feature. Therefore, when you use the IDirectDraw2 :: getCaps method to obtain the performance of the hardware, the same bit block transmission is related
The logo DWNLVBCAPS, DWNLVBCAPS2, DWNLVBCKEYCAPS, DWNLVBFXCAPS, and DWNLVBROPS will indicate that the local video memory is used. In execution mode,
If the local video memory is run, DirectDRAW will automatically use non-local video memory.
In the DMA model, support for texture map transmitted from non-local video memory is limited. When the display device uses the DMA model, you want to get the performance of the hardware.
DWCAPS members will be set to the DDCaps2_nonlocalvidMemcaps flag. The same bit block transmission related logo is included in DWNLVBCAPS, DWNLVBCAPS2,
DwnLvbcKeyCaps, DwnLvbFXCaps, and DwnLvbrops. DirectDraw will not use non-local video memory to create surfaces unless explicitly indicated. DMA
The implementation of the model is different in support for non-local video memory surfaces. If the driver supports texture map from a non-local video memory surface, use iDirect3ddevice2 :: getcaps
Method When obtaining a performance of a 3D device, the D3DDEVCAPS_TEXTURENONONLOCALVIDMEM flag will be set.
4.4.11 Conversion Color and Format Non-RGB Surface Format is represented by the four characters of the code (FOURCC CODES). If the application calls the idirectdrawsurface3 :: getpixelformat method to request
The pixel format, and the surface is a non-RGB surface, the DDPF_FOURCC flag will be set, and the members dwfourcc in the DDPixElFormat structure will become effective. Such as
Fruit Fourcc code indicates a YUV format, DDPF_YUV flag will be set, dwyuvbitcount, dwybits, dwubits, dwvbits and dwyuvalphabits
Members will be a valid mask to be used to extract information from pixels.
If the current RGB format is current, the DDPF_RGB flag will be set, DWRGBITCOUNT, DWRBITS, DWGBITS, DWBBITS and DWRGBALPHABITS members will be able
Enough to a valid mask of advance information from the pixels.
During the colors and formats, there are two groups of FOURCC code for the application. A set of capabilities identified the power of hardware block transmission, and the other group identified hardware coverage.
4.4.12, cover surface (overlay surfaces)
The cover surface is a surface with special hardware support capabilities, which is usually used to display active video, record video, or still bitmap without requiring bit blocks to transfer to the main surface or change the main surface.
Rong. This is entirely provided by the word coverage surface, and DirectDraw supports the features supported by the display device driver, and DirectDRAW does not simulate the surface. Can cover the surface
As a plastic paper, we can draw this plastic and placed it in front of the display. When plastic paper is covered in front of the display, you can see the overlay and main surface, remove the plastic
After the paper, the main surface has not changed. The working principle of covering the surface is similar to the principle of transparent plastic paper. What is the display of the device driver when displaying a cover surface
How to make the cover surface visible. When the display device scan line is swatched to the display, it checks each pixel on the main surface to see if it is overwritten. If so, the display device is from
The data replacement of related pixels is extracted in the cover surface.
Using this method, display the adapter card generates the main surface and the synthetic surface of the cover surface, generating transparent and stretching effects without changing the content of each surface. synthesis
The surface is sent to the video data stream directly to the display. Because this processing and pixel replacement is the hardware level operation, there is no significant performance loss. In addition, this method also makes it possible
Synthesize the main surface and cover the surface in different pixel formats.
Creating a coverage surface You need to specify the DDSCAPS_OVERLAY flag in the DDSCAPS structure, then call the idirectdraw2 :: createSurFace method to overwrite the surface can only be inward
Create in the deposit, so you must also include the DDSCAPS_VIDEMEMORY flag. Like other types of surfaces, by including the appropriate logo, you can create a single coverage surface.
You can also create a flip chain consisting of multiple overrides.
You can call the iDirectdraw2 :: getCaps method to get information about supported overlay features. This method fills a DDCAPS structure with the description of all feature information. in
When reporting the hardware feature, the device driver sets the flag of the DWCAPS member to indicate when to enforce some type of constraint provided by the hardware. After the ability to get the driver, pass
Check the flag of the DWCAPS member to know the information provided. The DDCAPS structure contains nine members, which describes the constraints of coverage of the surface. The subscript is listed
Overwrites related members of their logo.
member
Sign
DWMaxVisibleOverlays
The member is always effective
DWCurrvisibleOverlays
The member is always effective
DwalignboundarySRCDCAPS_ALIGNBOUNDARYSRC
Dwalignsizesrc
DDCAPS_ALIGNSIZESRC
DwalignboundaryDest
DDCAPS_ALIGNBOUNDARYDES
T
DwalignsizeDest
DDCAPS_ALIGNSIZEDEST
DWMINOVERLAYSTRETCH
DDCAPS_OVERLAYSTRETCH
DWMAXOVERLAYSTRETCH
DDCAPS_OVERLAYSTRETCH
DwMaxvisibleOverlays and dwcurrvisibleoverlays members indicate the maximum number of overrides that the hardware can be displayed, as well as how many visible.
DwalignBoundarySRC, DwalignSizesrc, DwalignBoundaryDest, Dwalignsizedest, and DwalignstrideAlign members are the rectangular position and size of the hardware report
Constraint. The values of these members refer to how to determine the size and position of the source rectangle and the destination rectangle when the cover is displayed.
DWMINOVERLAYSTRETCH and DWMAXOverLaystretch are information about tensile factors.
A, source rectangular and destination rectangle (Source and Destination Rectangles)
To display an overlay surface, you need to call the idirectdrawsurface3 :: updateoverLay method, specify the DDOVER_SHOW flag in the dwflags parameter. This method requires you
A source rectangle and destination rectangle are specified in the LPSRCRECT and LPDESTRECT parameters. If the entire surface is used, the LPSRCRECT parameter is set to NULL. The destination rectangle is on the main surface
Generate a location where the surface is covered.
Source, the destination rectangle does not have to be the same. Generally, the destination rectangle must be large or small, and the hardware is automatically compressed or stretched when the hardware is displayed. To show a successful display
The cover surface may need to adjust the sources, the size of the destination rectangle, whether this process is necessary to depend on the limitations of the device driver.
B, boundary and size adjustment (Boundary and size alignment)
Due to different hardware restrictions, some device drivers are constrained on the size and position of the source rectangles and the destination rectangle of the cover surface. To find out the constraints of the device application,
Call the IDirectdraw2 :: getCaps method, then check the flag of the DDCaps structure that covered the relevant DWCAPS. The subscript lists members of the specified boundary and size adjustment constraints
And logo.
category
Sign
member
Boundary constraint
DDCAPS_ALIGNBOUNDARYSRC
DwalignboundarySRC
DDCAPS_ALIGNBOUNDARYDEST
DwalignboundaryDest
Size constraint
DDCAPS_ALIGNSIZESRC
Dwalignsizesrc
DDCAPS_ALIGNSIZEDEST
DwalignsizeDest
There are two, boundary constraints, and size constraints. Both constraints are represented by pixels, and can be used for source rectles and destination rectangles. Of course, due to the coverage of the surface and the main surface
These constraints can be different from the format.
The boundary constraint affects the position of the source rectangle and the rectangular rectangle. The value of DwalignBoundarySRC and DwalignBoundaryDest members tells you how to adjust the upper left corner of the related rectangle.
The X coordinate in the upper left corner of the rectangle (the LEFT member in the RECT structure) must be an integer multiple of the reported values.
The size constraint affects the effective width of the source rectangle and the rectangular rectangle. The value of DwalignSizesRC and DwalIgnsizedest members indicate how to adjust the width of the correlation rectangle in pixel format. in case
According to a minimum tensile factor tensile rectangle, it should be ensured that the stretching rectangle is still adjusted. After the stretching rectangle, the width is adjusted by the upward round, it can be kept minimal.
Tensile factor.
C, maximum and minimum tensile factor (Minimum and Maximum Stretch Factors)
Due to the limitations of hardware, some devices limits the comparison of the destination rectangular rectangular width. DirectDraw uses these constraints as tensile factors. A stretch factor is the source
The ratio between the rectangular rectangles of the rectangle. If the driver provides information about the stretching factor, it will be in the DDCAPS structure after calling the IDirectDraw2 :: getCaps method.
Set the DDCAPS_OVERLAYSTRETCH logo. Note that all tensile factors have been multiplied by 1000, so the tensile factor having a value of 1300 is actually 1.3.
The maximum minimum tensile factor reported by non-compression and stretching covered rectangular devices is usually 0.
The minimum tensile factor indicates how much or narrower in the rectangular rectangular rectangle. If the minimum tensile factor is greater than 1000, the width of the objective rectangle must be increased. For example, if the stretch factor is
1300, the width of the destination rectangle should be at least 1.3 times the source rectangular width. If the tensile factor is less than 1000, the destination rectangle is smaller than the width of the source rectangle. The maximum tensile factor is the purpose
The rectangle can stretch the maximum multiple. For example, if the maximum tensile factor is 2000, the width of the destination rectangle can be 2 times the source rectangular width. If the maximum tensile fact is less than 1000,
The destination rectangle needs to be compressed. After stretching, the destination rectangle must comply with any size adjustment constraints required by the device. Therefore, it is finally stretched with the rectangle before the size is adjusted. Hardware
Do not require adjustment of the height of the destination rectangle. You can increase the height of the rectangle to keep the direction ratio.
D, cover Color Key
Like other types of surfaces, the cover surface also uses the source, the destination color key to control the transparent bit block transmission operation between the surface. Because the display of the cover surface is not passed by the block
Transfer is done, so you need to take different ways when calling the IDirectDrawSurface3 :: Updateoverlay method. Control the way the overlay surface is displayed on the main surface. Answer
It is covered with Color Key. The color key related to the same bit block is similar, covering the Color Key also has a source of Color Key and the purpose of the purpose, can pass the call method
IdirectDrawSurface3 :: setColorKey and use the DDCKEY_DESTOVERLAY flag to set the source color key and the destination Color Key. The cover surface can be transmitted and
Covering the Color Key combined to control the block transfer operation and override display operations, two different types of Color Key do not conflict with each other.
IdirectDrawSurface3 :: Updateoverlay method Source Color Key Check which pixel in the overlay surface should be transparent, allowing the main surface to be displayed through the overlay surface. same,
This method uses the purpose to override the Color Key to determine which part allows the main surface display that allows the overlay surface to be overwritten, and its display effect is the same as the same bit blocks the color key.
E, positioning coverage surface (positioning overlay surfaces)
When you call the idirectdrawsurface3 :: updateoverlay method, you can use the method iDirectdrawsurface3 :: setoverlayPosition to update your destination
rectangle. You must ensure that the location of the destination rectangles you specify follows the boundary alignment constraint, iDirectdraw2 :: setoverlayPosition method does not perform clipping work, using it may cause
The coordinates of the covering boundary will make the call failure and return DDERR_INVALIDPSITION.
f, create coverage surfaces (CREANGERLAY SURFCES)
Like all surfaces, you can call the iDirectdraw2 :: createSurFace method to create a cover surface. Creating a coverage surface also requires related structures DDSCAPS
Contains the DDSCAPS_OVERLAY flag. Covering a number of display devices, therefore cannot determine if a given pixel format is supported by most drivers, must be prepared to make it work in a variety of pixel formats. You can call the IDirectdraw2 :: getFourcccodes method to get the driver supported information about non-RGB formats. To create
One coverage surface, it is best to use the most commonly used pixel format, if a given pixel format is not supported, DirectDRAW uses the other pixel format supported by the display device. Create a coverage table
The flip chain is also allowed.
g, flipping overlay surface (Flipping overlay Surfaces)
Like other types of surfaces, you can create overwritten surface flip chains. Once the overwritten flip chain is created, you can call Method IDirectDrawsurface3 :: flip to flip these
cover. Software decompression can use DDFLIP_ODD and DDFLIP_EVEN flags to reduce sports artifacts when calling the FLIP method to display the coverage surface. If the driver supports 奇 - even
Flip, after obtaining the ability of the driver, the DDCaps2_canflipodDeven flag will be set in the DDCAPS structure. Once set
DDCAPS2_CANFLIPODDEVEN, you can include the DDOVER_BOB flag when calling the iDirectdrawsurface3 :: updateoverlay method to notify the driver to use "BOB"
Algorithm minimizes sporty icon. Thereafter, when FLIP is called with DDFLIP_ODD or DDFLIP_EVEN flags, the driver will automatically adjust the overworked source rectangle to make up for jitter.
If you do not set the DDCAPS2_CANFLIPODDEVEN flag after getting hardware, but use it when you call UpdateOverlay.
DDOVER_BOB logo, then the call will fail.
5, palette (Palette)
The toning surface needs to be displayed correctly. A toning surface (color index) is a simple collection of numbers, each of which is characterized by each number.
Pixel. The value of the number is an index of a color table, which tells DirectDraw to display what color when each pixel is used. DirectDrawPalette objects are often referred to as palette, it provides
Simple method for managing color tables. The palette is not used using a 16-bit or higher pixel format.
The DirectDrawPalette object characterizes an index color table for a color index surface with 2, 4, 16 or 256 entities. Each entity in the palette is a RGB ternary
The group describes the color used in the display surface. Color tables can include 16-bit and 24-bit RGB ternary groups to characterize the color used. For 16-color palette, color table can also
Contains an index of another 256 colored palette. The palette can be applied to textures, exterior surfaces, and coverage surfaces, they do not require the same palette as the main surface.
You can call the iDirectdraw2 :: createPalette method to create a palette that acquires the pointer of the IDirectdrawPalette interface of the palette object. Then you can use this connection
The method of the mouth handles the entity of the palette, obtain information or initialization objects related to object capabilities (if the palette is created with COM function CoCreateInstance).
Call the idirectdrawsurface3 :: setPalette method to attach a palette on a surface. A single palette can be applied to multiple surfaces. DirectDrawPalette
Objects to 8-bit palette reserve entities 0 and entities 255 unless you specify that the DDPCAPS_ALLOW256 flag requires that these two entities are available. you can use it
IdirectDrawpalette :: Gentries method Get a palette entity, modify the palette entity with the idirectdrawpalette :: setEntries method.
5.1, palette type
DirectDraw supports 1-bit, 2, 4-bit, and 8-bit palette. A palette can only be attached to a surface with the same pixel format. For example, a 2 entity palette created by the DDPCAPS_1bit flag can only be attached to the 1-bit surface created with the DDPF_PALETTEINDEXED1 flag. In addition, you can also create a palette that does not contain a color table, that is, an index.
Palette. Different from the color table, the index palette contains an index value, which is characterized by another palette color table.
To create an index palette, call the idirectdraw2 :: createpalette method, specify the DDPCAPS_8BITENTRIES logo. For example, to create a 4-digit palette,
You also need to specify DDPCAPS_4BIT and DDPCAPS_8Bitentries. When you create an index palette, pass a pointer to the byte array.
5.2 Setting the palette on the non-main surface (Setting Palettes on Nonprimary Surfaces)
The palette can be attached to an arbitrary toning surface (main surface, background buffer, external surface and texture map), but only the palette attached to the main surface can affect the system palette.
It must be noted that the DirectDRAW bit block transmission does not perform a color transform operation, and any source surface and destination surface attached to the bit block are ignored. The palette on the non-main surface is mainly used.
Direct3D application.
5.3, shared palette (Sharing Palettes)
The palette can be shared between multiple surfaces. The same palette can be attached to a forward buffer and background buffer, or a plurality of texture surfaces. Use
The IDIRECTDRAWSURFACE3 :: setPalette method When attached to one surface, the surface adds the index value of the palette. When the index value of the surface reaches 0, the surface
The index value of the attached palette will be reduced. In addition, if a palette is separated from the same surface, the index value of the palette of the surface is also reduced.
5.4, palette animation (Palette Animation)
The palette animation refers to the process of changing the appearance of the surface by changing the palette of the surface at the time of display. Repeat the palette, the surface looks like a change, but in fact,
The real content of the surface has no change. Therefore, the palette animation provides a method of changing the display performance of the surface without changing the specific content of the surface. For linear palette animations
To provide two ways:
i. Modify the palette entity in a single palette
II. Switch between multiple palettes
Using the previous method, you can change the entities that delay those related colors in the palette, then call the IDirectDrawPalette :: STENTRIES method to reset these entities at a time. Second type
Method requires 2 or more DirectDrawPalette objects, then call the idirectdrawsurface3 :: setPalette method to attach one of the palette objects to surface objects to generate
Animation. Both methods are independent of hardware, so which way to use is mainly to see if the application is suitable.
6, clipboard (Clipper)
The shear plate or DirectDrawClipper object allows the bit block to be transferred to the selected part of the surface. A clipboard object pulls a list of one or more clipboards in the sea. A list of clipboards
It is a bounded rectangular or several bounded rectangular columns, which is a piece or several area that allows the bit block to be transmitted in the surface. These areas are represented by the Rect structure in a screen coordinate.
The clip list is a very useful tool, which is the most commonly used to prohibit the application to write data blocks to places that are outside the screen. For example, if you want to display a wizard from the screen
The boundary enters, you don't want the elf to pop up on the screen, but slowly move slowly from the screen border to the center of the screen. If there is no clipboard object, you need to include the logic that restrict bit block operations to protect surface memory. The following figure shows the shear of this class.
You can use the shear board object to be a certain area of the sesame rectangle, which will be writable, and DirectDRAW will transfer the bit block to the bit block to protect the specified shear moment.
Pixels other than shape. This shear method is shown below:
6.1, Clip List (CLIP LIST)
DirectDraw uses the DirectDrawClipper object to manage the clip list. A clip-cut list is a series of rectangles that describe the surface visible area. A DirectDrawClipper
The image can be attached to any surface. One window handle can also be attached to the DirectDrawClipper object, in which case DirectDraw will use the clippers updated in the window.
Modify the DirectDrawClipper clip list.
Although the clipping list in DirectDraw Hal is visible, DirectDraw also calls HAL only when using rectangular bit blocks to meet the clip list requirements. For example, if the left of the surface
The upper corner rectangle is cut off, when the application writes the surface block to the main surface, DirectDRAW will use HAL to perform two bit block transfer operations, the first time, the upper left corner of the transmission surface,
The second operation is the lower half of the transmission surface.
This clipped list can be transferred to the driver (if the driver supports cut), instead of calling the driver if the driver supports shearing.
In addition, you can call the idirectdrawclipper :: sethwnd method to a single window by the handle of the specified window. Only when the overlay hardware supports shear or
The COLOR Key has not been activated, and the cover is covered with the shear function.
6.1, share the DirectDrawClipper object
The DirectDrawClipper object can be shared between multiple surfaces. For example, the same DirectDrawClipper object can be used at the same time and the front desk and background buffers of the chain. Use
The program is attached when the DirectDrawSurface3 :: setClipper method attached to one surface, and the secondary surface adds the index value of the object. If one
The DirectDrawClipper object is the same surface (this surface is created by an idirectdrawsurface3 :: setClipper method by an empty shearing board interface pointer) separated, the surface
The index value of the DirectDrawClipper object will be reduced.
6.3, independent clipboard object
You can create a DirectDrawClipper object that is not directly from any DirectDraw object. This clipboard object can be a total of multiple DirectDRAW objects
enjoy. The driver independent clipboard object can be created with the new DirectDraw function DirectDrawCreateClipper, and the application can call before creating any DirectDraw object.
This function.
Because the DirectDRAW object does not have these independent DirectDrawClipper objects, these DirectDrawClipper objects are not self-imported when the objects are released.
Release. If the application does not explicitly release these clipboard objects, DirectDraw will release them at the end of the program.
Of course, you can also create a DirectDrawClipper object with iDirectdraw2 :: CreateClipper method, and use the clipboard object created with this method in DirectDraw related to it.
Automatically released after the object is released.
6.4, create a DirectDrawClipper object with a COM function
The DirectDrawClipper object fully supports COM applications. In addition to using standard IDirectDraw2 :: CreateClipper methods, you can create a clipboard object with a COM function COGETCLASSOBJECT. Here is to create a cutting board with the CoCreateInstance function and the iDirectdrawclipper :: initialize method
Example of an object:
DDRVAL = CoCreateInstance (& clsid_directdrawclipper,
NULL, CLSCTX_ALL, & IID_IDIRECTDRAWCLIPPER, & LPCLIPPER
IF (! failed (ddrval))
DDRVAL = IdirectDrawClipper_initialize (lpclipper, lpdd, 0ul);
In the call to COCREATEINSTANCE, the first parameter clsid_directdrawclipper is a class flag of the shear board object class, and the IID_IDIRECTDRAWCLIPPER parameter indicates.
The currently supported interface, the lpclipper parameter is a pointer to the shearing board object.
The application must have to use the idirectdrawclipper :: initialize method to initialize the shearing board object, 0UL is the value of the dwflags parameter, in this example, there is no use of any standard
Ambition. LPDD is an DirectDraw object with the clipboard object; if you use null instead of LPDD, you will create a separate DirectDrawClipper object, which will also be equivalent to
DirectDrawCreateClipper function created a shearing board object. Before shutting down the application, you should use the CounInitialize function to close COM.
DirectDraw usually provides users with a method of booting using a mouse. The only choice is in a wizard to use the page.
The cursor of the mouse, relies on the mouse message from DirectInput from the data or window acquired from the device. Any application that does not use the page flip can also use the system's mouse
Cursor support.
When using the system's mouse cursor, image artifacts may appear when the block is part of the main surface. In the bit block transmission operation, the shearing plate object prevents the appearance of these artifacts.
In the application, first create a clipboard object with the idirectdraw2 :: createclipper method, and then assign the handle of the app to the clipboard with the idirectdrawclipper :: sethwnd method. One
Once the shear plate is attached, the operation of the bit block transmitted by the iDirectdrawsurface3 :: bLT method will not appear.
You can write a clipboard object block to multiple windows. First create a DirectDraw object with only one main surface, then create a clipboard object, reuse
IdirectDrawSurface3 :: SetClipper method Assign the shear board object to the main surface. To write to the client area of the window, you need to use it before the block is written to the main surface.
IDirectdrawclipper :: sethwnd method Set the clipboard to the window of the window. If you need a block to write to the customer area of another window, use the handle of the target window to call
IDirectdrawclipper :: sethwnd method once.
Fourth, DirectDRAW advanced features
1. Direct memory access DMA
Some display devices can support bit block transfer operations (or other operations) on the system memory surface, which are direct memory access DMA (Direct Memory Access). you
The support of DMA can be used to accelerate a certain operation. For example, in this device you can transfer from the system memory block to the video memory, and the processor is also ready to process the next frame.
Before using the DMA operation, it is necessary to detect whether the device supports DMA and support. The step is to get the ability to get the device with the iDirectdraw2 :: getcaps method, then
A re-view dwcaps member contains whether DWCAPS members contain DDCAPS_CANBLTSYSMEM flags, and if they indicate that the device supports DMA.
If the device supports DMA, you need to know how the driver is supported. This requires viewing the relevant structural members, which contains the system memory - video memory,
Video Memory - System Memory and System Memory - Information between Block Transfer Actions between System Memory. Several members of the DDCAPS structure provide this information, as shown in the following table:
System-to-Video
Video-to-system
SYSTEM-TO-SYSTEM
DWSVBCAPS
DWVSBCAPS
DWSSBCAPS
DWSVBCKEYCAPS
DWVSBCKEYCAPS
DWSSBCKEYCAPS
DWSVBFXCAPS
DWVSBFXCAPS
DWSSBFXCAPS
DWSVBROPS
DWVSBROPS
DWSSBROPS
For example, the performance flag of bit block transmission of the system memory to video memory is provided by DWSVBCAPS, DWSVBCKEYCAPS, DWSVBFXCAPS, and DWSVBROPS. Video memory
The bit block transmission performance flag to the system memory is included in a member starting with the "dwvsb", and the bit block transmission performance flag between the system memory is included in the "DWSSB" start.
Members.
The most critical characteristics of these members are support for transmission operations for asynchronous DMA bit blocks. If the driver supports the asynchronous DMA bit block transmission operation between the surface, DDCAPS_BLTQUEUE
The logo will be located in DWSVBCAPS, DWVSBCAPS, and DWSSBCAPS members. If the flag does not exist, it indicates that the driver does not support asynchronous DMA bit block transfer operations.
SRCPY transmission between the system memory to video memory is the most common bit block transmission operation supported by hardware. Therefore, the most typical application of this operation is from the system surface memory
Many textures move to video memory. The DMA transfer of the system memory to video memory is approximately as fast as the processor control, but it has a greater advantage because these operations can be
The host processor runs in parallel.
Hardware transfer uses physical memory addresses instead of virtual memory addresses, some device drivers require physical memory. This mechanism is through
The call to the iDirectdrawsurface3 :: PageLock method is done. If the device driver does not require a page lock, use the iDirectdraw2 :: getCaps method to get the hardware ability,
The DDCaps2_nopageLockRequired flag will be set.
Page locking a surface prevents the system from doing the physical memory of the surface and keeps the surface of the physical memory constant until IdirectDrawSurface3 :: Pageunlock
Sail. If the device driver request page is locked, DirectDraw only allows the DMA to operate on the system memory surface that is already locked. If there is no in this case
There is a call idirectdrawsurface3 :: PageLock, DirectDraw will perform transfer work with software simulation. It should be noted that the locking surface will be greatly reduced by Windows.
Running efficiency. Therefore, it is preferable to handle more quantity of system memory only in full-screen exclusive mode, and can unlock these surfaces when the application minimizes. Of course, the application
After the order is restored, the system memory surface page should be re-locked.
2, use the DirectDraw palette in window mode
When it is displayed in full-screen exclusive mode, the iDirectdrawpalette interface method is directly written to the hardware. When the window mode is displayed, the iDirectdrawpalette interface method will call the GDI palette processing function to make it harmonically with other Windows applications.
2.1, window mode Type of palette entity
Unlike all-screen exclusive applications, window mode applications must share desktop palettes with other applications. Used in DirectDrawPalette objects and GDI one
The PaletteEntry structure of the same work contains a PEFLAGS member that contains how the system will explain the information of the PaletteEntry structure. PEFLAGS member describes
Three types of palette entities.
2.1.1, window static entity
In standard mode, Windows reserves palette entities 0 ~ 9 and entities 246 ~ 255 for system color, display menu, menu text, and window boundaries. In order to make the application
The appearance of the order is maintained to avoid damage to the appearance of other applications, and you need to protect these entities that are set to the main surface. Usually, programmers can call Win32 functions
GetSystemPaletteEntries Take the system palette and explicitly set the same palette in the custom palette to match the system palette in front of the main table. Exhaust
The entity of the tube system palette is copied to the custom palette in the custom palette, but when the user changes the color of the desktop color, the custom palette will become invalid.
In order to avoid the user's ability to change the color color color, you can provide an index of a system palette to replace the specified color value to protect the appropriate entity. Use this
Method, no matter what color is used, the palette will always match, no need to do any update work. PC_EXPLICIT logo for PEFLAGS members
You can directly index to a system palette entity. After using this flag, the system will no longer think that other members of the structure contain color information. You can set the value of the Pred member
Setting the other colors to 0 in need of the required system palette index. For example, if you want to ensure that the appropriate entity in your palette always matches the color palette color matching of the system, you can make
Use the following code:
// set the first and last 10 Entries to match the system pastete.
Paletteentry PE [256];
ZeromeMory (PE, SIZEOF (PE));
For (int i = 0; i <10; i ) {
PE [i] .peflags = pe [i 246] .peflags = pc_explicit;
PE [i] .pled = i;
PE [i 246] .pled = i 246;
}
You can call the Win32 function setSystemPaletteuse to force Windows only use the first and last palette entities 0 and 255. In this case, it should be
Only the entities 0 and 255 are set to PC_EXPLICI in the PaletteEntry structure.
2.1.2, ANIMATED ENTRIES
You can use the PC_RESERVED flag in the PaletteEntry structure to specify that the motion is a palette entity. Windows does not allow other applications to pay themselves
The logical palette entity maps to your specified physical palette entity, allowing other applications to change their color when your application motion palette.
2.1.3, nonaNamated entries
You can use the PC_nocollapse flag in the PaletteEntry structure to specify a non-motion palette entity. PC_NOCOLLAPSE logo Notification Windows No need
The assigned palette entity replaces the non-sports entity.
2.2 In Window Mode Creating a palette Next is an example of creating a DirectDraw palette in non-exclusive window mode. In order to make the palette work normally, it is best to submit it to the idirectdraw2 :: CreatePalette
256 entities are set up in the PaletteEntry structure of the law.
LPDIRECTDRAW LPDD; // Assumed to Be Initialized Previously
Paletteentry PPaleTeentry [256];
Int index;
HRESULT DDRVAL;
LPDIRECTDRAWPALETTE LPDDPAL;
// first set up The Windows Static Entries.
For (INDEX = 0; Index <10; Index )
{
// The first 10 static entries:
PPALETTEENTRY [INDEX] .peflags = pc_explicit;
PPALETTEENTRY [INDEX] .pered = index;
PPALETTEENTRY [INDEX] .pegreen = 0;
PPALETTEENTRY [INDEX] .peblue = 0;
// The last 10 static entries:
PPALETTEENTRY [INDEX 246] .peflags = pc_explicit;
PPALETTEENTRY [INDEX 246] .pered = index 246;
PPALETTEENTRY [INDEX 246] .pegreen = 0;
PPALETTEENTRY [INDEX 246] .peblue = 0;
}
// NOW SET UP Private Entries. In this Example, The First 16
// Available Entries Are Animated.
For (INDEX = 10; Index <26; Index )
{
PPALETTEENTRY [INDEX] .peflags = pc_nocollapse | PC_RESERVED;
PPALETTEENTRY [INDEX] .pered = 255;
PPALETTEENTRY [INDEX] .pegreen = 64;
PPALETTEENTRY [INDEX] .peblue = 32;
}
// Now set up the rest, the nonanimated entries.
For (; index <246; index ) // index is set up by previous for loop
{
PPALETTEENTRY [INDEX] .peflags = pc_nocollapse;
PPALETTEENTRY [INDEX] .pered = 25;
PPALETTEENTRY [INDEX] .pegreen = 6;
PPALETTEENTRY [INDEX] .peblue = 63;
}
// All 256 Entries Are Filled. Create the Palette.
DDRVAL = LPDD-> CREATEPALETTE (DDPCaps_8bit, PPALETTEENTRY,
& lpddpal, NULL);
2.3, set the palette entity in window mode
The rules in the PaletteEntry for the iDiretdraw2 :: CreatePalette method are also applicable to the iDirectDrawPalette :: setNtries method. Therefore, you can maintain the PaletteEntry group without reconstructing it. When needed, change the structure group and call the IDirectDrawPalette :: setNtries method. In most environments, in
When window mode, do not try to set any window static entities, otherwise the unpredictable result will occur. The window still entity is allowed only when resetting the entity.
For the palette animation, you only need to change very little part of the entity in the PaletteEntry group, submit these entities to the IDirectDrawpalette :: setEntries method.
If you want to perform a reset operation, you can only reset the entities that are marked with the PC_NOCOLLLAPSE flag and the PC_RESERVED logo. Trying to move other entities
It will bring unpredictable errors. The following is an example of a palette animation in non-exclusive mode:
LPDIRECTDRAW LPDD; // Already Initialized
Paletteentry pPaletteEntry [256]; // already initialized
LPDIRECTDRAWPALETTE LPDDPAL; // Already Initialized
Int index;
HRESULT DDRVAL;
Paletteentry Temp;
// Animate Some Entries. Cycle The First 16 Available Entries.
// they were already animated.
Temp = PPALETTEENTRY [10];
For (INDEX = 10; Index <25; Index )
{
PPALETTEENTRY [INDEX] = PPALETTEENTRY [INDEX 1];
}
PPALETTEENTRY [25] = TEMP;
// set the values. Do not pass a pointer to the entire palette entry
// structrue, but only to the change entries.
DDRVAL = LPDDPAL-> setENTRIES
0, // Flags Must Be Zero
10, // first entry
16, // Number of Entries
& (PPALETTEENTRY [10])); // Where to get the data
3, multi-display system
Windows 98 (Memphis) and Windows NT support multiple display devices and displays on a single system. Multi-display system (commonly referred to as "multimon") makes operations
The system can use two or more display devices and displays to create a single logical desktop. For example, in the Multimon system with two displays, users can
A display is displayed on a display, and you can also drag and drop the window from one display to another display. DirectDraw supports this architecture. A DirectDraw application
The program can list hardware devices, select one device, and then use the device's GUID to create a DirectDRAW object for the device. This technology guarantees no matter in Multimon
The system can also achieve the best performance performance in a single display system.
The current active display device is considered "default device", or "null device" (null device "because the currently active display device is null as its GUID as it is listed. Many applications can create a DirectDraw object for "empty devices", assuming that the device is hardware acceleration. But in the Multimon system, "empty equipment"
It is not always hardware acceleration, which relies on the collaboration level used at the time.
In full-screen exclusive mode, "empty equipment" is hardware acceleration, but the system does not know other installed devices. This means that the full-screen exclusive model runs in Multimon
The speed on the system is as fast as running on other systems, but cannot use embedded support for image operations that span the display device. Need to use a full screen exclusive mode of multiple devices
Applications create a DirectDraw object for each device to use. Note that the DirectDraw object is created for the specified device, and you must provide the GUID of the object. Adjust
When using the DirectDrawenumeRate method, you can list the GUID of each device.
When the standard collaboration level is set, the "empty device" does not have hardware acceleration capabilities. In fact, it simulates the resources of the two physical devices to simulate a logical device.
On the other hand, the "empty device" automatically has graphical operational capabilities across the display. Therefore, when the logical position of the second display is in the left side of the main display, the negative coordinate value is
legal.
If the application requires the hardware acceleration function after setting the standard collaboration level, it must create a single DirectDraw object using the GUID of the specified device. in case
Without "empty equipment", you cannot get image operation capabilities across display devices. That is, the bit block transmission operation across the main surface boundary will be cut (if a shear board is used)
Or fail (return DDERR_INVALIDRECT).
Regardless of which system, you should set the collaboration level immediately after getting the DirectDraw object before you check the DirectDraw object before the other interfaces, and avoid it in Multimon
Collaboration levels are set multiple times in the system. If you need to switch from full screen mode to standard mode, you'd better create new DirectDraw objects, not to use old DirectDraw objects.
4, video port (Video Ports)
The DirectDraw video port extension is a low-level programming interface, which is not used for current system multimedia programming. The object of the video port interface is a video software company, such as
Develop a company such as DirectShow. Programmers who want to use video technology in their own software can also use video port extensions. However, advanced programming in many software is connected
The mouth is enough to meet the needs.
The DirectDrawVideoPort object is characterized by the video port hardware installed in some computer systems. In general, the video port object controls how video port hardware will be from videos.
The video signals accepted by the decoder are directly applied to the frame buffer. You can create multiple DirectDrawVideoPort objects to control multiple video channels as needed. Because each channel can be
To list and configure, video hardware does not need to be completely identical to each channel.
Video port hardware can access the surface directly in the frame buffer, and bypass the CPU and PCI bus. Direct access to the frame buffer makes effective playing activity video and
Recording a video without having to load it into the CPU. Once there is a surface, the image can be displayed on the screen, which can be used for Direct3D texture, CPU interceptive access
And other processing.
In a computer equipped with a video port device, the data in the video stream can directly flow from the video decoder and the video port to the frame buffer. These components are usually and displayed
The adapter is connected together or can be connected to each other as a separate hardware. The following figure shows the processing of the data stream:
What is the video source? In the video port technology, strict, the video source is a Video INPUT device, such as Zoom video port, MPEG encoder, etc. These hardware sources will be sent to the physical connection of the video decoder by connecting the signal in different formats (including NTSC, PAL, and SECAM). Video decoder (Viceo
Decoder is another hardware component. It works is to translate the information provided by the video source and send it to the video port with the connection format followed. The decoder keeps the physics with the video port
Connection, it is also responsible for sending video data, hourglass information, and synchronization information to the video port.
Video port is also a set of hardware. It exists on the VGA chip that displays the adapter, with the ability to directly access the frame buffer. It handles letters from the decoder
Interest and placed in the frame buffer for display. During the processing of data, the video port can operate image data to provide proportional changes, stretch compression, color control, and shear.
Frame Buffer accepts video data provided by the video port, and then processes these image data with programmed methods to transfer their bit blocks to other locations.
Or use the overlay to display it on the screen.
The essence of the DirectDraw video port extension is to include the DirectDrawVideoPort object, which can be used via IDDVIDEOPORTCONTAINER and IDIRECTDRAWVIDEOPORT interface.
Frequency port technology provides video services. The DirectDrawVideoPort object does not control the video decoder and can only provide your own service. DirectDraw does not control video sources because
Source has exceeded the range of video ports. The DirectDrawVideoPort object is just characterized by the video port itself. It sends the input signal and image data to the parameters set by the interface method.
The frame buffer performs flip or other processing. The IDDVIDEOPORTCONTAINER interface (available through iDirectdraw2 :: queryinterface) provides a query hardware to create a video port pair
The ability of icons. You can create a video port object with the IDDVIDEOPORTCONTAINER :: CreateVideoPort method, which shows its feature via the iDirectDrawVideoPort interface.
With these interfaces, you can check the ability of the video port, allocate override surfaces to receive image data, start and stop video playback, setting hardware parameters to process image data to generate cut,
Color conversion, scale zoom, and stretching compression. The DirectDraw video port extension supports multiple video ports on the same computer, allowing you to create multiple video port objects.
5, get flipping and bit block transmission status
We already know that after calling the IDirectdrawSurface3 :: Flip method, the main surface and the background buffer will exchange each other. But the action of the exchange is not immediately happening immediately. E.g,
If the previous flip task is not completed, the method returns DDERR_WASSTILLDRAWING. DirectDraw continues to call the idirectdrawsurface3 :: flip
Go back to DD_OK. If the application is in a wait state before calling the idirectdrawsurface3 :: flip method, then the efficiency of the program will be very
low. Instead, you can create a function call in the background buffer
IdirectdrawSurface3 :: getflipstatus method The front flipping work is completed. If you are not completed, returned or DDERR_WASSTILLDRAWING, application
The program can perform other tasks within a period of time between the state. Here is an example of this idea:
While (lpddsback-> getflipstatus (ddgfs_isflipdone) == DDERR_WASSTILLDRAWING); // Waiting for the Previous Flip to finish. The Application CAN
// Perform Another Task Here.
DDRVAL = LPDDSPRIMARY-> FLIP (NULL, 0);
You can also call IDirectDrawsurface3 :: getBltstatus with the same method to detect whether the primary block transfer is completed. Because IdirectdrawSurface3 :: getflipstatus and
IDirectdrawSurface3 :: getBltstatus can immediately return the current status of the application, so you can use them in the program without the running speed of the program.
degree.
The work that performs color fill needs to call the idirectdrawsurface3 :: blt method. For example, if the most often displayed color in the program is blue, you can call with a blue
IDirectDrawsurface3 :: BLT method, use the DDBLT_COLORFILL flag first filled the surface, and then write other objects to the top. This method allows you to fill very quickly
Charge the most common color, then only need to write a small number of colors to the surface. Below is an example of performing color filling:
DDBLTFX DDBLTFX;
DDBLTFX.DWSIZE = SizeOf (DDBLTFX);
DDBLTFX.DWFILLCOLOR = 0;
DDRVAL = LPDDSPRIMARY-> BLT (
Null, // Destination
NULL, NULL, / / SOURCE Rectangle
DDBLT_COLORFILL, & DDBLTFX;
Switch (DDRVAL)
{
Case Dderr_wasstilldrawing:
.
.
.
Case Dderr_surfacelost:
.
.
.
Case DD_OK:
.
.
.
DEFAULT:
}
6, detect the ability to display hardware
DirectDRAW uses software simulations to perform DirectDraw features that are not supported by the user. In order to improve the execution speed of the DirectDRAW application, you should be created
After the DirectDraw object, the ability to display the hardware is immediately detected, and then use the feature component program provided by the hardware as much as possible. You can use the idirectdraw2 :: getcaps method to detect hard
The performance of the pieces. Not all hardware features can be simulated with software. If you want to use a feature that is just supported by some hardware, it is best to do this.
The hardware is prepared, that is to provide a solution to this hardware if the hardware does not support this hardware.
7, store bitmap in display memory
Typically, the bit block transmission between the display memory to the display memory is high than the bit block transmission efficiency between the slave system memory to the display memory. Therefore, it is best to display as much as possible in the display of memory.
The wizard bitmap that will be used will be stored. Most display adapters contain sufficient additional memory to store more than one main surface and background buffer. You can use DDCAPS structure
DWVIDMEMTAAL and DWVIDMEMFREE members to detect how much memory in memory can be used to store bitmaps. DirectX Viewer Examples included in DirectX SDK
The program gives this process.
8, Triple Buffering)
In some cases, the display adapter may have more display memory, which may use three cushions to increase the display speed. Three buffers use a main surface and two background buffers
Area. Here is an example of initializing a three buffer:
// The LPDDSPRIMARY, LPDDSMIDDLE, AND LPDDSBACK Are Globally
// Declared, uninitialized lpdirectdrawsurface variables.ddsurfacedesc ddsd;
ZeromeMory (& DDSD, SIZEOF (DDSD));
// Create The Primary Surface with Two Back Buffers.
Ddsd.dwsize = sizeof (ddsd);
DDSD.DWFLAGS = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
DDSD.DDSCAPS.DWCAPS = DDSCAPS_PRIMARYSURFACE |
DDSCAPS_FLIP | DDSCAPS_COMPLEX;
DDSD.DWBACKBUFFERCOUNT = 2;
DDRVAL = LPDD-> CreateSurface (& DDSD, & LPDDSPRIMARY, NULL);
// if we success creted the flipping chain,
// Retrieve Pointers to the Surfaces We need for
// flipping and blitting.
IF (DDRVAL == DD_OK)
{
// Get The Surface Directly Attached To The Primary (The Back Buffer).
DDSD.DDSCAPS.DWCAPS = DDSCAPS_BACKBUFFER;
DDRVAL = LPDDSPRIMARY-> GetAttachedSurface (& DDSD.DDSCAPS,
& lpddsmiddle;
IF (DDRVAL! = DD_OK);
// Display an error message here.
}
You don't need to retain the trajectory of all the surfaces in the three buffered turn chains, just keep the main surface and the pointer to the background buffer surface. The main surface pointer is used to flip the main surface in the flip chain.
The background buffered pointer is used for bit block transmission. The three buffer allows the application continuation bit block to the background buffer, as long as the last bit block transmission of the background buffer has been completed, even in turn
It doesn't matter if it is not completed. Execution flip is not a synchronous event, and once the flip may be longer than the other flip. Therefore, if only one background buffer is used, when
The program may consume a waiting state before returning DD_OK, and the iDirectdrawsurface3 :: flip method.
9, DirectDraw applications and window style
If the application uses DirectDraw in window mode, you can use any windows. The appearance of full screen exclusive mode cannot use WS_EX_TOOLWINDOW
Style is created, it should be used with the WS_EX_TOPMOST extension window style and WS_Visible window style to make sure the image is displayed correctly. These two styles can keep the app in
The front end of the window z direction, avoiding GDI to the main surface. The following example shows how to make an application that makes exclusive full screen mode:
// register the window Class, Display The Window, And Init All Directx and Graphic Objects.
Bool WinApi InitApp (Int Nwinmode)
{
WNDCLASSEX WCEX;
Wcex.cbsize = sizeof (wndclassex);
WCEX.HINSTANCE = g_hinst;
WCEX.LPSZCLASSNAME = g_szwinname;
Wcex.lpfnwndproc = WndProc; wcex.style = CS_VREDRAW | CS_HREDREDRAW | CS_DBLCLKS;
WCEX.HICON = LOADICON (NULL, IDI_Application);
WCEX.HICONSM = Loadicon (NULL, IDI_WINLOGO);
Wcex.hcursor = loadingcursor (null, idc_arrow);
WCEX.LPSZMENUNAME = MakeintResource (IDR_AppMenu);
Wcex.cbclsextra = 0;
Wcex.cbWndextra = 0;
Wcex.hbrbackground = getStockObject (null_brush);
RegisterClassex (& WCEX);
g_hwndmain = CREATEWINDOWEX (
WS_EX_TOPMOST,
g_szwinname,
g_szwincaption,
WS_VISIBLE | WS_POPUP,
0,0, cx_screen, cy_screen,
NULL,
NULL,
g_hinst,
NULL);
IF (! g_hwndmain)
Return (False);
SetFocus (g_hwndmain);
ShowWindow (g_hwndmain, nwinmode);
UpdateWindow (g_hwndmain);
Return True;
}
DirectX5.0 Latest Game Programming Guide
DirectDraw tutorial
DirectX is prepared for users of Visual C , so the DirectDraw game program is to be prepared, and it is best to have a certain understanding of VC. Users who don't want to use VC can also
Using Message Arakelian Soft developed ActiveX control DirectStudio98 or Tegosoft's Tegosoft ActiveX for Visual for Visual Basic5.0 users
Basic. However, if you want to give full play to DirectX performance, and you want to keep the program's compatibility, it is best to use Visual C .
For the convenience of narrative, it is assumed that DirectX5.0 SDK and Visual C 5.0 have been installed, and its directory is C: / DX5SDK and C: / Program Files / DevStudio. If you make
With another compiler or installed in other directory, the following example must be used to make appropriate modifications. After someone has installed DirectX SDK, I don't know how to use it because it
Based on Visual C , there is no interface-friendly integrated development environment, so it is necessary to properly formulate Visual C .
First, configure DirectX SDK
1.1, Configuring Microsoft Developer Studio In order to compile the example provided by DirectX SDK, you need to open a new Project Workspace, insert the appropriate file, set the ring.
The contraventor enables the compiler to find the required link library and include files, which describe all the processes set. Start Microsoft Developer Studio, install the following steps to create work
Cheng:
In the File menu, choose New;
In the New dialog box, select Win32 Application in Project, enter DDEX1 in Project Name. Enter the location of the project file in the location text box, point OK button
A new DDEX1 Classes folder appears on the left of the Workspace window.
After the project is created, you need to use the following steps to insert the appropriate file to the project:
Select Add Toproject | Files in the Project menu
Browse to C: / DX5SDK / SDK / Samples / DDEX1 directory, select all files
Select OK, Ddex1.cpp, Ddex1.rc, resource.h in this directory is added.
Then set the path to the file:
. In the Tools menu, select Options, pop-up OPTIONS dialog box
Select Directories, select include Files in the Show Directories for list box
In the Directories: list box double-click the blank line at the bottom of the list, enter C: / DX5SDK / SDK / INC.
Again, add another path C: / DX5SDK / SDK / Samples / Misc
. Select the OK button,
Set the link library directory:
Select Library Files in the Show Directories for list box
In the Directories: list box double-click the bottom blank line, enter C: / DX5SDK / SDK / LIB.
. Click the OK button.
Finally set the module that links when the application is established:
Click Settings in the Project menu.
. Select LINK
Select General in the Category drop-down box.
Add DDRAW.LIB and WINMM.LIB in the Object / Library module list box.
Click OK.
1.2, formulate NMAKE path
Sometimes the way the command line is more convenient than the integrated environment, so many experienced programmers are more willing to build applications in the way they are command line. Below is a file and link library module
route of:
@echo off
SET PATH = C: / Program Files / DevStudio / Sharedide / Bin; C: / Program Files / DevStudio / VC / BIN;% PATH%
SET INCLUDE = C: / Program Files / DevStudio / VC / include; C: / Program Files / DevStudio / VC / MFC / INCLUDE; C: / DX5SDK / SDK / INC;% incrude%
Set lib = c: / program files / devstudio / sharedide / vc / lib; c: / program files / devstudio / vc / mfc / lib; C: / DX5SDK / SDK / LIB;% LIB%
Set init = c: / program files / devstudio;% init%
Add the above to Autoexec.bat. Enter in the directory of the example
Nmake
A debug directory will be created in the current directory and place the generated executable in this directory.
In order to be familiar with DirectX SDK during the learning process, we will follow the sequence of the sample programs provided by DirectX SDK, step by step.
3, configure DirectX SDK for Borland C 5.0
Although DirectX 5 SDK is prepared for Visual C users, Microsoft has not forgotten a large number of Borland C users, so it is also available in DirectX SDK.
DirectX's Borland C library. However, it may not be the Borland C library in the DirectX SDK after the competition (guess). This requires users to handle this annoying problem. We know, DirectX 5 SDK is released in an idx5sdk.exe, after running IDX5SDK, it first decompressed all compressed files to a certain
In the directory (such as D: / DX5SDK), then run the setup.exe installation DirectX SDK in this directory (assuming the directory is C: / DX5SDK). In fact, in the decompressed directory
Include a D: / DX5SDK / SDK / lib / borlandc directory, which is the link library file for Borland C . But when the setup is installed, the installer does not put this purpose.
Record to the installation directory. The solution is very simple, that is, after the setup installation is complete, build a C: / DX5SDK / SDK / lib / borland, will Directory D: / DX5SDK / SDK / LIB / BORLAND
All files below are copied to the C: / DX5SDK / SDK / LIB / BORLAND directory. Then Configure the project in the integrated environment of Borland C 5.0 as configuring Visual C 5.0.
Part.
Second, the first DirectDraw instance
To use DirectDraw, you must first create an instance of the DirectDRAW object to characterize the display adapter card on your computer and then use the interface method to process the object. In addition
To create an instance of one or more DirectDrawSurface objects to display the game. DDEX1 first creates a DirectDraw object, create a primary surface (Primary Surface)
And a background buffer and then convert between the surface. DDEXX examples are written in C . If you use a C compiler, you must make the code appropriately change
Move, at least to join the doubt and pointer to the interface method.
1, first initialize the DirectDraw object
The DDEX1 program contains DIINIT functions containing the initialization code of DirectDraw:
// Create a primary DirectDraw object
DDRVAL = DirectDrawCreate (NULL, & LPDD, NULL);
IF (DDRVAL == DD_OK)
{
// Get exclusive mode
DDRVAL = LPDD-> SetCooperativeElevel (HWnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
IF (DDRVAL == DD_OK)
{
DDRVAL = LPDD-> setDisplayMode (640, 480, 8);
IF (DDRVAL == DD_OK)
{
// Create a main surface with a background buffer
Ddsd.dwsize = sizeof (ddsd);
DDSD.DWFLAGS = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
DDSD.DDSCAPS.DWCAPS = DDSCAPS_PRIMARYSURFACE |
DDSCAPS_FLIP |
DDSCAPS_COMPLEX;
DDSD.DWBACKBUFFERCOUNT = 1;
DDRVAL = LPDD-> CreateSurface (& DDSD, & LPDDSPRIMARY, NULL);
IF (DDRVAL == DD_OK) {
/ / Get pointers in the background buffer
DDSCAPS.DWCAPS = DDSCAPS_BACKBUFFER;
DDRVAL = LPDDSPRIMARY-> GetAttachedSurface (& DDSCAPS, & LPDDSBACK);
IF (DDRVAL == DD_OK)
{
// Picture some text
IF (LPDDSPRIMARY-> GetDC (& HDC) == DD_OK) {
SetBkcolor (HDC, RGB (0, 0, 255));
SetTextColor (HDC, RGB (255, 255, 0));
Textout (HDC, 0, 0, SZFRONTMSG, LSTRLEN (SZFRONTMSG);
LPDDSPRIMARY-> ReleaseDC (HDC);
}
IF (LPDDSBACK-> Getdc (& HDC) == DD_OK) {
SetBkcolor (HDC, RGB (0, 0, 255));
SetTextColor (HDC, RGB (255, 255, 0));
Textout (HDC, 0, 0, SzBackMSG, LSTRLEN (SZBackMSG);
LPDDSBACK-> ReleaseDC (HDC);
}
// Create a timer of the flip page
IF (SetTimer (HWnd, Timer_ID, Timer_Rate, Null)
{
Return True;
}
}
}
}
}
}
WSPRINTF (BUF, "Direct Draw Init Failed (% 08LX) / N", DDRVAL);
..........
Each of the steps of the creation of the DirectDRAW object will be described in detail below.
2. Create a DirectDraw object
Creating an instance of the DirectDraw object, you should use the DirectDrawCreate API function, you can also use the CoCreateInstance function in COM. DirectDrawCreate
Characterizing the display device with a global unified marker Guid (GlobalLoBally Identifier), in most cases, GUID is NULL (using the default display device of the system, both "empty
Device "); pointer points to the address of the DirectDraw object; the third parameter is always NULL (for future extension). The following code indicates how to create a DirectDraw object, and
Whether the inspection is successful.
DDRVAL = DirectDrawCreate (NULL, & LPDD, NULL);
IF (DDRVAL == DD_OK)
{
// LPDD IS is a legitimate DirectDraw object
}
Else
{
// DirectDRAW object cannot be created
}
3, set display mode
Setting up the display mode of the DirectDraw application requires two steps: first call the iDirectdraw :: setCoopeRarativeAVEVELEVELEVELEVELEVELE method to set the requirements in this mode, once you have determined
Q, use the IDirectDraw :: SetDisplayMode method to select the display resolution.
Before changing the display resolution, you must also specify the DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN flags via the iDirectDraw :: SetCooperativeEvelEvel method.
This allows the game program to fully control the display device, and other applications cannot share the display device at the same time. The DDSCL_FULLSCREEN flag indicates that the program is set to full screen mode. under
The code shows how to use iDirectdraw :: setCooperativeElevel method: HRESULT DDRVAL;
LPDIRECTDRAW LPDD; // Already Created by DirectDrawCreate
DDRVAL = LPDD-> SetCooperativeElevel (HWnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
IF (DDRVAL == DD_OK) {
/ / Full screen exclusive way setting success
}
Else {
// The call is unsuccessful, but the program can continue to run
}
If iDIRECTDRAW :: SETCOOPERATIVELEVEL does not return DD_OK, you can still run the program, but not full screen mode, sometimes some unpredictable errors.
So you should display an error message, let the user know what happened, by the user to decide whether to continue the game.
When using iDirectdraw :: SetCoopeRATIVELEVEL, you must transfer a handle to the window (HWND), allowing the window to determine when the application is not normally stopped. For example, if it happens
GP error or GDI is flipped (FLIP) to the background buffer, and the user cannot access the current screen. In order to avoid this, DirectDraw has a background waiting process, which captures
There is a message sent to the window that uses these messages to determine when the application terminates. If a new window is created, you must make sure that the window is active, otherwise, there will be a series of events.
Unable to continue.
4, change display mode
Once the application's operating mode is selected, you can use the idirectdraw :: setDisplayMode method to change the display mode, the following code sets the display mode to
640x480x256:
HRESULT DDRVAL;
LPDIRECTDRAW LPDD; // Already CREATED
DDRVAL = LPDD-> setDisplayMode (640, 480, 8);
IF (DDRVAL == DD_OK) {
// change the mode success
}
Else {
// Display mode cannot be changed
// The system may not support this mode
}
When setting the display mode, make sure that if the user's device does not support higher resolution, the application should return to the standard mode supported by the system. If the display is not supported
The resolution of the count, idirectdraw :: setDisplaymode returns a Dderr_INVALIDMODE error value. Therefore, when setting the resolution, it should be used first.
IDirectDraw :: EnumdisplayMode method Detects the performance of the user's display device.
5. Create a flippable surface (Flippable Surface)
After setting the display mode, you must create the surface of the placed application. In DDEX1, we use the iDirectDraw :: setCooperativeEvel method to set the program exclusive
Full-screen mode, then you can create a flip surface. If you use iDirectDraw :: SetCooperativeEvel, you can only create a block of writing.
.
6, define surface requirements
The first step in creating a flipped surface is to define the requirements of the surface in the DDSurfaceDesc structure. The following code describes the definition of the structure and the creation of fluttered surfaces.
Sign:
// Create a main surface with a background buffer
Ddsd.dwsize = sizeof (ddsd);
DDSD.DWFLAGS = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
DDSD.DDSCAPS.DWCAPS = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX; DDSD.DWBACKBUFFERCOUNT = 1;
In the example, the member variable DWSIZE is set to the size of the DDSurfaceDesc structure. DWFlags flag Specifies which domains in the DDSurfaceDesc structure can store valid information. in
DDEX1 examples, DWFlags pointed out that you need to use the DDSCAPS structure (DDSD_CAPS) and create a background buffer (DDSD_BACKBUFFERCOUNT). DWCAPS
The DDSCAPS structure will be used, in this example, it specifies a major surface (DDSCAPS_PRIMARYSURFACE), a flip surface (DDSCAPS_FLIP) and a complex
Idum surface (DDSCAPS_COMPLEX). Finally, the program specifies a background buffer. The background buffer is the background image and the person will be written, which can be converted to the main surface.
In this example, the number of background buffers is 1, in fact, as long as there is enough display memory, you can create any multiple background buffers, usually every 1m display memory can only be used to create one.
Background buffer. The surface of the surface can be either displayed, or a system memory. DirectDraw is created when using the memory (for example, only 1m display memory)
Two background buffers will automatically use system memory. You can set the DWCAPS in the DDSCAPS structure to DDSCAPS_SYSTEMMORY or
DDSCAPS_VIDEOMEMORY to specify that only system memory or only display memory. If DDSCAPS_VIDEOMEMORY is specified, there is not enough display memory.
Create a surface, iDirectdraw :: CreateSurface will return a Dderr_OutofVideoMemory error.
7, create a surface
Fill the DDSurfaceDesc structure, you can use this structure and LPDD, LPDD is a pointer to the DirectDraw object created with the DirectDrawCreate method, under
The code of the surface shows this process:
DDRVAL = LPDD-> CreateSurface (& DDSD, & LPDDSPRIMARY, NULL);
IF (DDRVAL == DD_OK) {
// LPDDSPRIMARY POINTS TO New Surface
}
Else {
// Surface Was Not Created
Return False;
}
If the call is successful, the IDirectDraw :: CreateSurface function returns the pointer LPDDSPRIMARY to the main surface. If the main surface pointer is available, you can call
The iDirectdrawsurface :: getattachedSurface method acquires the pointer to the background buffer as follows:
DDSCAPS.DWCAPS = DDSCAPS_BACKBUFFER;
DDRVAL = LPDDSPRIMARY-> GetAttachedSurface (& DDCAPS, & LPDDSBACK);
IF (DDRVAL == DD_OK) {
// LPDDSBACK POINTS to the Back Buffer
}
Else {
Return False;
}
If the iDirectdrawsurface :: getattachedSurface calls success, by providing the address of the main surface and settings DDSCAPS_BACKBUFFER flag, LPDDSBACK
Number points to the background buffer.
8, coloring surface
After creating the main surface and the background buffer, DDEX1 uses the standard Windows GDI function to submit some text to the main surface and background buffer, the code is as follows: if (LPDDSPRIMARY-> getDC (& HDC) == DD_OK) {
SetBkcolor (HDC, RGB (0, 0, 255));
SetTextColor (HDC, RGB (255, 255, 0));
Textout (HDC, 0, 0, SZFRONTMSG, LSTRLEN (SZFRONTMSG);
LPDDSPRIMARY-> ReleaseDC (HDC);
}
IF (LPDDSBACK-> Getdc (& HDC) == DD_OK) {
SetBkcolor (HDC, RGB (0, 0, 255));
SetTextColor (HDC, RGB (255, 255, 0));
Textout (HDC, 0, 0, SzBackMSG, LSTRLEN (SZBackMSG);
LPDDSBACK-> ReleaseDC (HDC);
}
The IDIRECTDRAWSURFACE :: GETDC method is used in the example to lock the surface and lock the surface. If you don't want to use the Windows function asking your handle, you can use it.
IdirectDrawSurface :: Lock and iDirectDrawsurface :: UNLOCK method to lock and unlock the background buffer. Lock the surface of the surface (whether the entire surface is also one
Ensure to ensure that your applications and systems will not access this memory at the same time. In addition, the program cannot flush the surface unless the memory is unlocked. This example uses a Windows GDI letter after locking the surface
Number SetBKColor to set up background colors, use setTextColor to set text colors, then use Textout to output text to the surface. When the text is written into the buffer, use
The idirectdrawsurface :: ReleaseDC method to unlock the surface and release the handle. Good habits are that after writing data to the background buffer,
IdirectdrawSurface :: releasedc or idirectdrawsurface :: unlock.
In general, when writing data to the surface, the surface is the background buffer, and then the buffer is turned out into the main surface. In Ddex1, there is a first flip surface.
An important delay. So DDEX1 writes data to a main buffer to avoid too long time intervals when the start is displayed. It will be said later that DDEX1 is only in the WM_TIMER
Write data between the background. Initialization functions or header heads may be written to the main buffer. It should be noted that once the IDIRECTDRAWSURFACE :: Unlock is unlocked to the surface, point to the surface
The pointer becomes invalid, and the iDirectdrawsurface :: Lock method must be used again to obtain the valid pointer of the surface memory.
9, write surface and flip surface
After completing the initialization, DDEX1 starts processing a message loop. During the message loop, complete the lockup background buffer - write new text - unlock the background buffer -
The process of flipping the surface. WM_TIMER contains most of the code in writing data and flipping surfaces.
The first half of the WM_TIMER message is used to write data to the background buffer, and the "Phase" variable is determined whether to write the main buffer message or write the background buffer message. If Phase is 1,
Indicates the message written in the main buffer, and then changes Phase to 0; if 0, represents the message written in the background buffer, and then changes the phase to 1. Note that the news in both cases is
Write a background buffer. After writing the message, the background buffer is unlocked using the idirectdrawsurface :: releasedc method. The following code implements this: Case WM_TIMER:
// Flip Surfaces
IF (BACTIVE) {
IF (LPDDSBACK-> Getdc (& HDC) == DD_OK)
{
SetBkcolor (HDC, RGB (0, 0, 255));
SetTextColor (HDC, RGB (255, 255, 0));
IF (Phase) {
Textout (HDC, 0, 0, SZFRONTMSG, LSTRLEN (SZFRONTMSG);
PHASE = 0;
}
Else {
Textout (HDC, 0, 0, SzBackMSG, LSTRLEN (SZBackMSG);
Phase = 1;
}
LPDDSBACK-> ReleaseDC (HDC);
}
After the surface is blocked, use the iDirectdrawsurface :: flip method to turn the background buffer into the main surface, the code is as follows:
While (1) {
HRESULT DDRVAL;
DDRVAL = LPDDSPRIMARY-> FLIP (NULL, 0);
IF (DDRVAL == DD_OK)
{
Break;
}
IF (DDRVAL == DDERR_SURFACELOST)
{
IF (DDRVAL = LPDDSPRIMARY- & G> VAL! = DD_OK)
{
Break;
}
}
IF (DDRVAL! = DDERR_WASSTILLDRAWING)
{
Break;
}
}
In the example, LPDDSPRIMARY indicates the main surface and its rear buffer. After calling the idirectdrawsurface :: FLIP method, the main surface and the rear surface are swapped. After the call is successful, return
DD_OK, the program terminates the While loop; if Dderr_Surfacelost is returned, it may be that the surface is lost, you need to use the idirectdrawsurface :: restore method to restore this
Surface, if the recovery is successful, call the idirectdrawsurface :: flip method again; if it fails, the program terminates the While loop and returns an error value. In addition, as mentioned above,
Make the call IDirectDrawSurface :: flip, the exchange is not immediately complete, it will wait until the system is completed after this. For example, the top surface
IdirectdrawSurface :: flip returns Dderr_wasstildrawing when it is not happened. In this example, idirectdrawsurface :: flip continues to loop until returns DD_OK ..
10, release the DirectDraw object
When F12 is pressed, the DDEX1 program processes the WM_DESTROY message before exiting, the message calls the Finiobjects function, and the Finiobjects function contains all
The call of IUNKNOWN RELEASE, the code is as follows:
Static void finiobjects (void) {
IF (LPDD! = null) {
IF (LPDDSPRIMARY! = NULL) {
LPDDSPRIMARY-> Release ();
LPDDSPRIMARY = NULL;
LPDD-> Release ();
LPDD = NULL;
}
} / * FiniObjects * /
The program detects the pointer (LPDDSPRIMARY) of the DirectDrawSurface object is equal to NULL. This example is apparent from NULL. Course
After DDEX1 calls IDirectdrawSurface :: release method reduces the reference value of the DirectDrawSurface object, which will make its reference value becomes 0, DirectDrawSurface
The like is released, and the DirectDrawSurface's pointer is set to the NULL value, then undo. The program is called idirectdraw :: Release reduces the reference value of the DirectDraw object
To 0, release the DirectDraw object and its pointer.
The above DDEX1 is the most basic application of DirectDraw. It first creates a DirectDraw object and a DirectDrawSurface object, create a main surface and its rear buffer,
Output text to the background buffer and then transform the surface. The second example DDEX2 extends the function of DDEX1, which can transfer a bitmap file into the backbrew. Third case
Sub-DDEX3 further, in addition to a major surface and the background buffer, two screens are created, transferring the bitmap into each screen outside, then use
IDirectDrawSurface :: BLTFast method Transports a content bit block of a screen to the background buffer, then flip the surface and transfer the content bit block of another screen to the background.
Chongzu. These features will be discussed in detail below.
11, tune the bitmap into the surface
For example, in DDEX1, the DOINIT function is the initialization function of DDEX2, and the substance of both, until the following code:
LPDDPAL = DDLOADPALETTE (LPDD, SZBACKGROUND);
IF (LPDDPAL == NULL)
Goto error;
DDRVAL = LPDDSPRIMARY-> SetPalette (LPDDPAL);
IF (DDRVAL! = DD_OK)
Goto error;
// load a bitmap INTO The Back Buffer.
DDRVAL = DDRELOADBITMAP (LPDDSBACK, SZBACKGROUND);
IF (DDRVAL! = DD_OK)
Goto error;
The first row of the code returns a value from the function DDLoadPalette, which is compiled in the ddutil.cpp file in C: / DX5SDK / SDK / Samples / Misc, so compiling DDEX2
The DDUTIL.CPP and DDUTIL.H are required to join the process. Most DirectDraw programs require this file. In DDEX2, the DDLoadPalette function is from the back.bmp file.
Create a DirectDrawPalette object. The DDLoadPalette function first checks the file or resource used to create a palette, if not, create a default color
board. In DDEX2, it extracts the palette information from the bitmap file and stores the structure pointed to by the APE, then create the DirectDrawPalette object as follows:
PDD-> CREATEPALETTE (DDPCAPS_8bit, APE, & DDPAL, NULL);
Return ddpal;
DDPAL points to the DirectDrawPalette object when the IDiretDraw :: Creatette method returns. APE is a pointer to a structure that includes 2/4/16/256 linear entities, and the number of entities is determined by the dwflags parameter called by idirectdraw :: CreatePalette. In this example, DWFLAGS is set to DDPCAPS_8bit, which means that the knot
There are 256 entities in the construct, each of which has four bytes (red, green, blue, and logo bytes).
12, set the palette, transfer the bitmap into the backbound buffer
After creating a palette, you can transfer the pointer DDPAL of the DirectDrawPalette object to the main surface by calling the IDiretTe method. The code is as follows:
DDRVAL = LPDDSPRIMARY-> SetPalette (LPDDPAL);
IF (DDRVAL! = DD_OK)
// setPalette failed
After calling the IDirectDrawsurface :: setPalette method, the DirectDrawPalette object is in the DirectDrawSurface object, and you need to change the palette.
When you only need to create a new palette to set it.
After the DirectDrawPalette object is hanging together with the DirectDrawSurface object, DDEX2 uses the following code to load the back.bmp file into the background buffer:
// load a bitmap INTO The Back Buffer.
DDRVAL = DDRELOADBITMAP (LPDDSBACK, SZBACKGROUND);
IF (DDRVAL! = DD_OK)
// load failed
DDRELOADBITMAP is another function in ddutil.cpp, which transfers bitmaps to the existing DirectDRAW surface from files or resources. In this example, it will szBackground
Pointed back.bmp is loaded into the background buffer pointing to the LPDDSBACK. DDRELOADBITMAP calls DDCopyBitmap function copies files to the background buffer and extends as appropriate
size. The DDCopyBitmap function removes bitmaps into memory, use the getObject function to get the size of the bitmap, then use the code below to get the size of the background buffer to place the bitmap:
// Get size of surface.
Ddsd.dwsize = sizeof (ddsd);
DDSD.DWFLAGS = DDSD_HEIGHT | DDSD_WIDTH;
PDDS-> GetSurfaceDesc (& DDSD);
DDSD is a pointer to the DDSurfaceDesc structure that stores the current description of the DirectDraw surface. Members of the DDSurfaceDesc structure
DDSD_HEIGHT and DDSD_WIDTH specify the high and width of the surface. IDirectdrawsurface :: getSurfaceDesc method Use the appropriate value to be inserted, and the example is 480,
Width is 640. The DDCopyBitmap function locks the surface and copies the bitmap to the background buffer, and then stretch or compress the bitmap with the StretchBLT function. The code is as follows:
IF ((hr = pdds-> getdc (& hdc)) == DD_OK) {
Stretchblt (HDC, 0, 0, DDSD.dwwidth, ddsd.dwheight, HDCImage, X, Y, DX, DY, SRCCopy);
PDDS-> ReleaseDC (HDC);
13, transfer from the exterior surface block
DDEX2 is basically the same as DDEX1. DDEX2 opens a bitmap file and sent it to the background buffer and flip the background buffer and main surface. But this is not the display bitmap.
Special ideals, DDEX3 extends the function of DDEX2, which adds two exterior buffers, and each buffer stores a bitmap. Below is a part of the Doinit function in DDEX3
The function is to create two exterior buffers:
// Create an offscreen bitmap.
DDSD.DWFLAGS = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
DDSD.DDSCAPS.DWCAPS = DDSCAPS_OFFSCREENPLAIN
DDSD.DWHEIGHT = 480;
Ddsd.dwwidth = 640;
DDRVAL = LPDD-> CreateSurface (& DDSD, & lpddsone, NULL);
IF (DDRVAL! = DD_OK) {
Return INITFAIL (HWND);
}
// CREATE ANOTHER OFFSCREEN BITMAP.
DDRVAL = LPDD-> CreateSurface (& DDSD, & LPDDSTWO, NULL);
IF (DDRVAL! = DD_OK) {
Return INITFAIL (HWND);
}
As can be seen from the code, DWFlags indicates that the program uses the DDSCAPS structure and sets the high and width of the buffer. DDSCAPS_OFFSCREEN in the DDSCAPS structure
The logo specifies that the surface is the exterior buffer, which will be high and wide to 480 and 640 in the DDSurfaceDesc structure, and then use the idirectdraw :: createSurface method to create a table.
surface. Because the size of the outer surface of the two screens, create a second buffer only need to run idirectdraw :: CreateSurface (of course, different pointers). you still can
Set DDSCAPS_SYSTEMORY or DDSCAPS_VIDEMEMORY in DDSCAPS to specify that the screen outer buffer is placed in the display memory or system memory. Position
The map is placed in display memory to speed up the data transfer speed between the background buffer and the outer surface of the screen, which is very important in bitmap animation. However, if you specify it for the exterior buffer
DDSCAPS_VIDEMEMORY does not have enough display memory to transfer the entire bitmap. When the surface is created, the program will return a DderR_OutofVideoMory.
Error value.
14. Turn the bitmap file into the exterior surface
After creating two exterior surfaces, DDEX3 uses the INITSURFACES function to load the bitmap from the frntback.bmp file to both surfaces. The INITSURFACES function is used
The DDCopyBitmap function is transferred to two bitmaps, the code is as follows:
// loadur bitmap resource.
HBM = (Hbitmap) loading (getModuleHandle (NULL), SZBitmap,
Image_bitmap, 0, 0, lr_createdibsection;
IF (hbm == null)
Return False;
DDCopyBitmap (LPDDsone, HBM, 0, 0, 640, 480);
DDCopyBitmap (LPDDSTWO, HBM, 0, 480, 640, 480);
DeleteObject (HBM);
Return True;
FRNTBACK.BMP file consists of two parts, half on, half is under. The DDCopyBitmap function is transferred to the first half of the first screen LPDDSOONE, and the lower half is transferred to the second surface LPDDSTWO.
15. Transfer the exterior surface bit block to the background buffer
WM_TIMER contains code that writes the surface and flip surface. In DDEX3, it selects the appropriate screen of the appropriate screen and transfer its bit block to the background buffer, the code is as follows:
RcRect.Left = 0;
RcRect.top = 0;
RcRect.Right = 640;
RcRect.bottom = 480;
IF (PHASE)
{
PDDS = LPDDSTWO;
PHASE = 0;
}
Else {
PDDS = lpddsone;
Phase = 1;
}
While (1) {
DDRVAL = LPDDSBACK-> BLTFAST (0, 0, PDDS, & RCRECT, FALSE);
IF (DDRVAL == DD_OK)
{
Break;
}
"PHASE" determines which screen is ready to transfer from the outer surface bit block to the background buffer, then call the idirectdrawsurface :: BLTFast method to transfer the selected screen outdoor block to
The background buffer starts from the position of the upper left corner 0, 0. RcRect points to the RECT structure that defines the left corner of the exterior surface and the lower right corner. The last parameter is set to false or 0, indicating
Do not use special transmission signs. Once the exterior surface is transferred to the background buffer, the front method can be utilized to flush the background buffer and the main surface each other.
Third, create an animation
The above example is just written data into the background buffer, and then flip the background buffer with the main surface, and its speed is not too fast. The following examples DDEX4 and DDEX5 are optimized
Real-time features make it more like a real game. DDEX4 shows how to set the color key for the surface, how to use the idirectdrawsurface :: bltfast method to put the outside surface
Partially copies to the background buffer to produce animations. DDEX5 adds a read tone plate and changing the palette when moving.
1, Color Key and Downport Animation
In DDEX3, a primary way to place a bitmap is placed in an exterior buffer. DDEX4 uses the background and a series of elves (Sprite, this example is a ring)
The technique of the exterior surface, then use, iDirectdrawsurface :: BLTFast method copies each part of the exterior surface to the background buffer. DOINIT functions except for the function in the previous example
In addition, it also includes code for setting the color key for the elf. Color Key is a color value for setting transparency. When using hardware blocks, the rectangular area is set to Color Key.
The pixels, the other pixels are written, thereby generating a non-tumble elf on the surface. The code to set the color key is as follows:
// set the color key for this bitmap (Black)
// Note This Bitmap Has Black As Entry 255 in The Color Table.
// DDCK.DWCOLORSPA PartLOWVALUE = 0xff;
// DDCK.DWCOLORSPACEHIGHVALUE = 0xff;
// LPDDSONE-> SetColorKey (DDCKEY_SRCBLT, & DDCK);
// if we did not want to hard code the parapte index (0xff)
// We can Also Set The Color Key Like So ...
DDSETCOLORKEY (LPDDSONE, RGB (0,0,0)); Return True;
Two different methods of setting the Color Key are given. The first method is 3 lines within the comment, first set the range of the Color Key in the DDColorKey structure, and then call
IdirectDrawSurface :: setColorKey method Sets the Color Key to black (false locations in the color table as the palette index 255). The second method is to call
The DDSETCOLORKEY function sets the color RGB value to select Color Key, black is RGB (0, 0, 0). The DDSETCOLORKEY function calls the DDColormatch function,
DdColormatch stores the color value of 0,0 position pixels on the bitmap of the LPDDsone surface, and then assigns pixels of 0,0 position with the supplied RGB value, and shields the color value.
After completing this step, the original color can reselect 0, 0 and use the correct color key to call the DDSETCOLORKEY function. After the call is successful, the Color Key is put in
Member variables in the DDColorKey structure DWColorspaceLowValue, and copy to DWColorspacehighValue members, and then call
IdirectDrawSurface :: setColorKey Sets Color Key.
CLR_INVALID is another useful variable in the DDSetColorKey and DDColormatch functions. If this value is used as a color key, bitmap is used in DDSETCOLORKEY
The pixels in the upper left corner will be used as a Color Key. To implement this feature, you need to transfer the bitmap file all.bmp, turn the pixel value of 0,0 to black, save your changes, then as follows
Change to DDSETCOLORKEY:
DDSETCOLORKEY (LPDDSONE, CLR_INVALID);
Re-compiling DDEX4, DDEX4 will use the pixel values at 0,0 as the Color Key.
2, animation in DDEX4
DDEX4 uses the red circle in all.bmp to create a simple animation. Animation consists of 3 spaces of the circles. Example by comparing Win32
GetTickCount and the last function start running the time to determine which ring is retransmond, then use the idirectdrawsurface :: bltfast method to bring the background from the exterior surface
The LPDDsone bit block is transferred to the background buffer, and then written the circle to the background buffer using the Color Key that has set. After all the rings are written to the background buffer, adjust
Turn over the background buffer and main surface with the idirectdrawsurface :: flip method.
3, dynamically change the palette
DDEX5 describes any dynamically chase palettes during program runtime, although this is not always used in the game. DirectDraw really can control the palette well. DDEX5
The following code puts the palette in the lower half of the all.bmp file:
// first, set all colors as unused
For (i = 0; i <256; i )
{
Toruscolors [i] = 0;
}
// Lock The Surface and Scan The Lower Part (The Torus Area)
// and repeember all the index's we find.
Ddsd.dwsize = sizeof (ddsd);
While (LPDDsone-> Lock (NULL, & DDSD, 0, NULL) == DDERR_WASSTILLDRAWING
// Now Search Through The Torus Frames and Mark Used Colorsfor (Y = 480; Y <480 384; Y ) {
For (x = 0; x <640; x )
{
Toruscolors [(Byte *) DDSD.LPSURFACE) [Y * DDSD.LPITCH X] = 1;
}
}
LPDDSONE-> UNLOCK (NULL);
Array TorusColors is used to specify the index value of the lower semi-semi-semi-palette in all.bmp, and the array is initialized to 0 before use. Then lock the outer surface of the screen to detect a color index.
Whether the value is used. Array TorusColors start at the 0th row of bitmaps, columns, and the color index value in the array is placed in one byte of the location of the memory, which location is determined.
The LPSurface member variable in the DDSurfaceDesc structure is determined that LPSurFace points to the memory address corresponding to the bitmap (0,480) (Y * LPITCH X). Color set in array
The color index value is used to detect which colors in the palette are replaced. Because there is no common color between the background and the red ring, there is only those color values that are combined with the circular circle to be replaced.
4, replace the palette
The updateframe function in DDEX5 is the same as the DDEX4, first writes the background block into the background buffer, and writes 3 red circles to the foreground. But in the flip surface
Before the UpdateFrame creates a palette index value created by the Doinit function, change the palette of the main surface, the code is as follows:
// Change the Palette
IF (lpddpal-> getENTRIES (0, 0, 256, pe)! = dd_ok) {
Return;
}
For (i = 1; i <256; i ) {
IF (! toruscolors [i]) {
CONTINUE;
}
PE [i] .pled = (PE [i] .pered 2)% 256;
PE [i] .pegreen = (PE [i] .pegreen 1)% 256;
PE [i] .peblue = (PE [i] .peblue 3)% 256;
}
IF (lpddpal-> setENTRIES (0, 0, 256, pe)! = dd_ok) {
Return;
}
IDirectDrawpalette :: getNtries method query the value of the palette in the DirectDrawPalette object, because the value of the palette entity points to PE is valid, the method is returned
DD_OK, the program continues to run. Then the loop detection whether TorusColors is set to 1 in the initialization, if the index value is set to 1, the red, green, blue, blue, blue by the palette pointing by PE
The color value is replaced. After all of the marked palette entities are replaced, then call the IDirectDrawPalette :: STENTRIES method to truly change the implementation of DirectDrawPalette.
body. If the palette has been set to the main surface, the above change will be completed immediately. After completing this, the rest is the same flip surface as in front.
Fourth, use the cover surface
This example will use the DirectX SDK MOSQUITO sample program to explain how to use DirectDRAW and hardware support coverage surfaces in the program step by step. Mosquito
Use the flip chain covering the surface of the surface without the bit block to the main surface to display the motion bitmap on the desktop. The MOSquito program adjusts the feature of the cover surface to accommodate hardware.
1. Create a main surface
To use the overlay surface, you must first initialize a major surface, and the override surface will be displayed on the main surface. Mosquito creates a major surface with the following code:
// Zero-Out The Structure and Set The DWSIZE MEMBER.ZEROMEMORY (& DDSD, SIZEOF (DDSD));
Ddsd.dwsize = sizeof (ddsd);
// set flags and create a primary surface.
DDSD.DWFLAGS = DDSD_CAPS;
DDSD.DDSCAPS.DWCAPS = DDSCAPS_PRIMARYSURFACE;
DDRVAL = G_LPDD-> CreateSurface (& DDSD, & G_LPDDSPRIMARY, NULL);
The program first initializes the DDSurfaceDesc structure that will be used, and then set the appropriate flag to call the IDirectDraw2 :: createSurface method to create the main surface. In this method
In the call, the first parameter is a pointer to the DDSurfaceDesc structure that will be created; the second parameter is a pointer of a variable, and if the call is successful, the variable will
Receive the pointer to the IDirectDrawSurface interface; the third parameter is set to null indicates that there is no COM collection.
2. Detect hardware to cover support
After initializing DirectDraw, you need to detect whether the device supports the cover surface. Because DirectDraw can't simulate override, if the hardware does not support overwriting, you cannot continue
work. You can get the ability to detect overlay support for hardware device drivers with iDirectDraw2 :: getCaps. After calling this method, view dwflags in the DDCAPS structure.
Whether the member contains a DDCaps_overlay flag. If there is, it indicates that support coverage, otherwise it will not be supported.
The following code is part of the MOSquito program that shows how to detect hardware coverage support capabilities:
Bool isoverlayssupported ()
{
DDCAPS Capsdrv;
HRESULT DDRVAL;
// Get Driver Capabilities To Determine overlay support.
ZeromeMory (& CapsDRV, SIZEOF (CAPSDRV));
Capsdrv.dwsize = sizeof (capsdrv);
DDRVAL = g_lpdd-> getCaps (& CapsDRV, NULL);
IF (Failed (DDRVAL))
Return False;
// does the Driver Support overlays in the current mode?
// (Currently The DirectDraw Emulation Layer Does Not Support overlays.
// Overlay Related Apis Will Fail without Hardware Support.
IF (! (Capsdrv.dwcaps & DDCAPS_OVERLAY))
Return False;
Return True;
}
The program first calls the iDirectdraw2 :: getCaps method to get the power of the device driver. The first parameter is the address pointer of the DDCAPS structure; because the program does not need to be closed simulation
Information, so the second parameter is set to NULL. After getting the ability to get the driver, the program uses the logic "and" to check if the dwflags member contains DDCAPS_OVERLAY.
Sign. If not, the program returns FALSE indicates that failed. If so, returns True to indicate that the display device supports the cover surface.
3. Create a cover surface
If you know that the display device supports the overlay surface, you can create one. Because the device does not specify how the device supports the standards covered surface, it is not expected to create any pixels.
Surface of format. Also, do not expect the first time to create a coverage surface will succeed. Therefore, it is necessary to prepare an attempt to create multiple creating until there is a work. The MOSQUITO program follows the principle of "Best Case to Worst Case" when you create a surface, first try to create a three buffer flip-flush complex coverage surface. If the trial failed, the program
Try to configure other universal rapid formats on changes. The following code is the performance of this idea:
ZeromeMory (& DDSDOVERLAY, SIZEOF (DDSDOVERLAY));
DDSDOVERLAY.DWSIZE = SizeOf (DDSDoverLay);
DDSDOVERLAY.DWFLAGS = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH |
DDSD_BACKBUFFERCOUNT | DDSD_PIXELFORMAT;
DDSDOVERLAY.DDSCAPS.DWCAPS = DDSCAPS_OVERLAY | DDSCAPS_FLIP |
DDSCAPS_COMPLEX | DDSCAPS_VIDEMEMORY;
DDSDOVERLAY.DWWIDTH = 320;
DDSDOVERLAY.DWHEIGHT = 240;
DDSDOVERLAY.DWBACKBUFFERCOUNT = 2;
// try to create an overlay surface use one of the pixel formats in ou
// Global List.
i = 0;
Do {
DDSDOVERLAY.DDPFPIXELFORMAT = g_ddpfoverlayformats [i];
// Try to create the overlay surface
DDRVAL = G_LPDD-> CreateSurface (& DDSDOVERLAY, & G_LPDDSOVERLAY, NULL);
} While (Failed (DDRVAL) && ( i The program sets the flags and values in the DDSurfaceDesc structure to reflect the three buffer flops flip complex cover surface, and then perform a loop. In the loop, the program tries to use a variety of commonly used Create a request for the pixel format. If the attempt is successful, the loop is terminated. If the trial fails, it is very likely that the display of the hardware does not have enough display memory to support the three buffering scheme or The hardware does not support flipping surfaces. In this case, use a single non-flip cover surface under the minimum required configuration, the code is as follows: // if we failed to create a triple buffered complex overlay surface, TRY // Again with a single non-flippable buffer. IF (Failed (DDRVAL)) { DDSDOVERLAY.DWBACKBUFFERCOUNT = 0; DDSDOVERLAY.DDSCAPS.DWCAPS = DDSCAPS_OVERLAY | DDSCAPS_VIDEMEMORY DDSDOVERLAY.DWFLAGS = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT; // Try to create the overlay surface DDRVAL = G_LPDD-> CreateSurface (& DDSDOVERLAY, & G_LPDDSOVERLAY, NULL); i = 0; Do { DDSDOVERLAY.DDPFPIXELFORMAT = g_ddpfoverLayFormats [i]; ddrval = g_lpdd-> createsssurface (& DDSDOVERLAY, & G_LPDDSOVERLAY, NULL); } While (Failed (DDRVAL) && ( i // We couldn't create an overlay surface. EXIT, RETURNING FAILURE. IF (Failed (DDRVAL)) Return False; } The above code refers to a single non-flip overlay surface on the DDSurfaceDesc structure, and then attempts to create a surface through a pixel format loop. in case Creating a surface is successful and the loop stops. If it is not successful, the program returns false indicates that the creation surface failed. After successfully created the cover surface, you can load the bitmap to supply it. Indicated. 4, display cover surface You can display it after you create a coverage. Typically, the hardware adds alignment constraints on the location and pixel format of the covered rectangle. In addition, it also needs to be adjusted The wide range of rectangles will illustrate the minimum required tensile factor to successfully display the cover surface. The MOSQUITO program is prepared and display the overlay surface as follows. 4.1, detect the minimum requirements displayed Most of the display hardware will add constraints when displaying overrides. You must take care of the overlay to satisfy these constraints. You can call iDirectdraw2 :: getCaps method Get information about these constraints. The structure filling structure DDCAPS contains information about coverage and use constraints. The constraints of different hardware are different, so they must always always To see a flag contained in the DWFlags member to determine which constraint is. The MOSQUITO program begins to get hardware capabilities, and then use the method based on the minimum tensile factor, as shown below: // Get Driver Capabilities DDRVAL = g_lpdd-> getCaps (& CapsDRV, NULL); IF (Failed (DDRVAL)) Return False; // Check the minimum stretch and set the local variable acidingly. IF (Capsdrv.dwcaps & DDCAPS_OVERLAYSTRETCH) USTRETCHFACTOR1000 = (Capsdrv.dwminoverLaystretch> 1000)? Capsdrv.dwminoverlaystretch: 1000; Else USTRETCHFACTOR1000 = 1000; The above code calls IDirectDraw2 :: getCaps method to get hardware capabilities. In this example, the first parameter is a pointer to the DDCAPS structure; the second parameter is NULL, It shows that there is no need to get information about simulation. The program retains the minimum tensile factor in a temporary variable for use. If the tensile factor reported by the driver is greater than 1000, It is shown that the driver requires all the destination rectangles to stretch along the direction of the X-axis. For example, if the stretching factor is 1.3, the source rectangle is 320 pixels wide, and the rectangle of the destination must be at least 416. (320 x1.3 = 416) width of pixels. If the tensile factor reported in the driver is less than 1000, it indicates that the driver can display smaller coverage than the source rectangle, but cannot be extended. The following code is the value of the measurement of the size alignment constraint of the driver: // Grab Any Alignment Restrictions and set the local variables acordingly. USRCSIZEALIGN = (Capsdrv.dwcaps & ddcaps_alignsizesrc)? Capsdrv.dwalignsizesrc: 0; udestsizEalign = (Capsdrv.dwcaps & DDCAPS_ALIGNSESIZESRC)? Capsdrv.dwalignsizedest: 0; More temporary variables are used in Example to save the size alignment constraints obtained from DwalignSizesRC and DwalignSizeDest members. These values provide relevant pixel width alignment The information of the constraint is required to be used in the same time after setting the source rectangle and the destination rectangle. The source rectangles and destination rectangles must be multiple multiple of these values. Finally, the program determines the value of the destination rectangular boundary alignment constraint: // set the "Destination Position Alignment" Global So We Won't have to // Keep Calling getCaps () Every Time We move the overlay surface. IF (Capsdrv.dwcaps & DDCAPS_ALIGNBOUNDARYDEST) g_dwoverlayxpositionalignment = capsdrv.dwalignboundaryDest; Else g_dwoverlayxpositionalignment = 0; The above code uses a global variable to save the value of the rectangular boundary constraint, which is from DwalignBoundaryDest member, reset it in later programs It will be used when it is overwritten. You must set the X coordinates in the upper left corner of the destination rectangle to align in the pixel format. That is, if the value is 4, it can only specify the X coordinate of the upper left corner. The purpose rectangle of the pixel width of 0, 4, 8, and 12. The MOSQUITO program is first displayed at 0,0, so it is not necessary to obtain constraint information before the first display overlay is displayed. But because The implementation process of different applications may be different, so you may need to check this information before displaying overrides to adjust the destination rectangle. 2, set source rectangles and destination rectangles After obtaining the overlay constraint of the driver, the value of the source rectangle and the destination rectangle should be set to ensure that the overlay can be displayed correctly. The following code sets the source of the source rectangle Logistics: // set initial value in the source. Rs.left = 0; rs.top = 0; Rs.right = 320; RS.BOTTOM = 240; // Apply Size Alignment Restrictions, if Necessary. IF (Capsdrv.dwcaps & DDCAPS_ALIGNSIZESRC && USRCSIGN) Rs.right - = rs.right% usrcsizEalign; The above code sets an initial value that contains the entire surface size. If the device driver requires size alignment, the program adjusts the source rectangle to ensure. The program is adjusted to the width of the source rectangle It is not possible to make it smaller than the initial value, because if it is not completely recreated, it is not possible to extend the width. After setting the source rectangle, you need to set and adjust the size of the destination rectangle. This process takes a little more work because the destination rectangle may need to be stretched first. Compliance with sized alignment constraints. The following code sets and adjusts the size of the destination rectangle according to the minimum tensile factor: // set up The destination Rect, Starting with The Source Rect Values. // We use the source rect Dimensions Instead of the Surface Dimensions in // Case the Differ. Rd.Left = 0; rd.top = 0; Rd.right = (RS.right * uStretchFactor1000 999) / 1000; // (Add 999 Avoids Integer Truncation Problems.) // (this isn't Required by DDRAW, But We'll Stretch the // HEIGHT, TOO, TO Maintain Aspect Ratio. Rd.bottom = rs.bottom * uStretchFactor1000 / 1000; The front code first sets the upper left corner position of the object, and then sets the width of the destination rectangle according to the minimum tensile factor. When adjusting the rectangle according to tensile factor, the payment is in width and pulling. Addition of 999 in the product of the extension factor, this is to avoid the cutting of an integer, and the cutting truncation will cause the rectangular requirements as the minimum tensile factor. The program also stretched after the stretch width The height of the rectangle. However, the stretching of the height is not necessary, here is just to maintain the phenomenon of distortion in order to maintain the growth rate of the bitmap. After the stretching rectangle, the program is adjusted to keep and the magnitude alignment constraint, the following is the corresponding code: // Adjust The Destination Reth Width To Comply with any imposed // Alignment Restrictions. IF (Capsdrv.dwcaps & DDCaps_alignsizedest && UDestsizEalign) Rd.right = (int) ((Rd.right udestsizEalign-1) / udestsizEalign) * uDestsizealign; The program detects the logo of the hardware capabilities, check whether the driver has added rectangular alignment constraints. If so, the width of the increase in the rectangle is increased to satisfy the size alignment constraint. Here The rectangular adjustment is extended to extend its width without reducing its width because the width may result in a smaller rectangle than the minimum tensile factor, thereby causing display coverage surface failure. 3, display cover surface After setting the source rectangle and the destination rectangle, it can be displayed. If the preparation date before the overlay is displayed correctly, the display coverage will be simple. MOSQUITO program uses the following generation Code to display override: // set the flags we'll send to updateoverlay DwupdateFlags = DDOVER_SHOW | DDOVER_DDFX; // Does the overlay hardware support source color keying? // if so, we can hide the black background involved the image. // this probably Won't work with yuv formats IF (Capsdrv.dwcKeycaps & DdcKeycaps_srcoverlay) DwupdateFlags | = DDOVER_KEYSRCOVERRIDE; // Create An Overlay FX Structure So We can Specify A Source Color Key. // this information is ignored if the ddover_srckeyoverride flag isn't set. ZeromeMory (& Ovfx, SizeOf (OVFX)); Ovfx.dwsize = sizeof (ovfx); Ovfx.dcksrccolorKey.dwcolorspacelowValue = 0; // specify black as the color keyovfx.dcksrcolort.dwcolorspacehighValue = 0; // Call Updateoverlay () To Displays The overlay on the screen. DDRVAL = g_lpddsoverlay-> Updateoverlay (& RS, G_LPDDSPRIMARY, & RD, DWUPDATEFLAGS, & OVFX); IF (Failed (DDRVAL)) Return False; The program starts to set the DDOVER_SHOW and DDOVER_DDFX flags in the temporary variable dwupdateflags, indicating that the overlay is the first time, and the hardware should use the package. The effect information is included in the DDOVERLAYFX structure. Then, the program checks the DDCAPS structure to determine if the override supports the source color Key. in the case of, The DDOVER_KEYSRCOVERRIDE flag is included in the dwupdateflags variable, which is also available in the Color Key accordingly. After the preparation is completed, the program calls IDirectDrawSurface3 :: updateoverlay method to display overwriting. In the call to this method, the first parameter and the third parameter are The adjusted source rectangle and the address of the destination rectangle. The second parameter is to override the address of the main surface displayed thereon. The fourth parameter is to include dwupdateflags placed in previous preparation. Sign in the variable. The fifth parameter is the address of the DDOVERLAYFX structure, and the members in this structure will match the same flag. If the hardware only supports a coverage surface and the surface is being used, the UpdateoverLay method will fail and return DDERR_OUTOFCAPS. In addition, it is possible to hardware The minimum tensile factor reported too small. After the Updateoverlay method fails, you need to try to reduce the width of the destination rectangle to cope with this possibility. However, this situation is very small. Health, only simply returns an error message in Mosquito. 5, update overwriting display position After displaying the cover surface, sometimes you may not need to operate the left left. However, some software also needs to reset override, change the display position override. Mosquito program Use the iDirectdrawsurface3 :: setoverlayPosition method to reset override, the code is as follows: // set X- and y-coordinates . . . // We need to check for any alignment restrictions on the x position // and align it if nesessary. IF (g_dwoverlayxpositionalignment) Dwxaligned = g_noverlayxpos - g_noverlayxpos% g_dwoverlayXPositionalIgnment; Else Dwxaligned = g_noverlayXPOS; // set the overlay to its new position. DDRVAL = g_lpddsoverlay-> setoverlayPosition (dwxaligned, g_noverlayypos); IF (DDRVAL == DDERR_SURFACELOST) { IF (! restoreallsurface ()) Return; } The program begins to align the rectangular boundary alignment constraints to meet any destination boundaries that may exist. When the program previously calls the IDirectdraw2 :: getCaps method, the global variable g_dwoverlayXPositionAlignment has been set to the value reported by DWALIGNBOUNDARYDEST members in the DDCAPS structure. If there is a destination rectangle constraint, the program According to this, adjust the new X coordinate as a pixel. If you do not meet the requirements, the cover cannot be displayed. After completing the adjustment of the X coordinate, the program calls IDirectDrawSurface3 :: setoverlayPosition method Re-placed overwrites. The first parameter in the call is the new new The X coordinate, the new Y coordinate of the second parameter. These values indicate a new location in the upper left corner. There is no need to get width and height information, because DirectDraw is starting The iDirectdrawsurface3 :: updateoverlay method shows that the surface size is available. If you cause a reposition override table due to one or more surfaces Failure, the Mosquito program calls an application-defined function to restore these surfaces and reload their bitmaps. Note that do not use the coordinates of the right and lower boundaries of the target surface. Because the idirectdraw2 :: setoverlayPosition method does not perform cutting function, use those Can cause coordinates that override to be more than the target surface boundary, will cause the call to fail and return DDERR_INVALIDPSITION. 6, hidden cover surface If you no longer need an overlay surface or just want the overlay, you can set the appropriate flag to call the IDirectDrawsurface3 :: updateoverlay method to hide the overlay table surface. MOSQUITO hides the cover surface with the following code and prepares to close the application: void destroyoverlay () { IF (g_lpddsoverlay) { // use updateoverlay () with the ddover_hide flag to remove an overlay // from the display. G_lpddsoverlay-> Updateoverlay (Null, G_LPDDsPrimary, Null, Ddover_Hide, Null); g_lpddsoverlay-> release (); g_lpddsoverlay = null; } } When calling idirectdrawsurface3 :: updateover, NULL is specified for the source rectangle and destination rectangles because there is no need for source rectangles and destination rectangles during hidden coverage. Similarly, the fifth parameters are also designated as NULL because it does not use overlay. The second parameter is a pointer to the target surface. Finally, the program uses DDOVER_HIDE in the fourth parameter The logo indicates that the overlay will be canceled from the viewport. After the program is hidden, it releases its IDirectdrawSurface3 interface and set the global variable to null to make it invalid. For MOSquito programs, overcast The cover is no longer needed. If you need to use it in the application, you just need to simply hide override, not to release it, and then redisplay it when you need it. 5. Examples of other DirectDraw in DirectDraw To master the application about DirectDraw, you should also study the following examples in DirectX SDK: 1, Stretch Describe how to create an unique mode in one window, which has the function of the shear bit block transmission and the stretching clip bit block transmission. 2, Donut The application of multiple monographs is described with interaction between the use of non-exclusive mode applications. 3, Wormhole This example describes the detailed palette animation. 4, DXVIEW Detailed describes how to get the ability to display hardware.