Tech Talk: DirectDraw Alex Riemann University of Illinois, Urbana-Champaign February 13, 2000.
-
Upload
douglas-summers -
Category
Documents
-
view
216 -
download
2
Transcript of Tech Talk: DirectDraw Alex Riemann University of Illinois, Urbana-Champaign February 13, 2000.
Tech Talk: Tech Talk: DirectDrawDirectDraw
Alex RiemannAlex RiemannUniversity of Illinois, University of Illinois, Urbana-ChampaignUrbana-Champaign
February 13, 2000February 13, 2000
Graphics Programming in Graphics Programming in DOSDOS
Very Limited Video HardwareVery Limited Video Hardware Required the developer to know Required the developer to know
what features the video hardware what features the video hardware providedprovided
Video Electronics Standards Video Electronics Standards Association (VESA)Association (VESA) Helped relieve this situationHelped relieve this situation Provided semi-common interface to Provided semi-common interface to
video memoryvideo memory
Graphics Programming in Graphics Programming in WindowsWindows
Common set of API’s to access graphics Common set of API’s to access graphics subsystemsubsystem
Numerous layers of indirection between Numerous layers of indirection between the programmer and the hardwarethe programmer and the hardware
Graphics Device Interface (GDI) objectsGraphics Device Interface (GDI) objects Great for Circles, Squares, and other simple Great for Circles, Squares, and other simple
objectsobjects Far too slow to handle effects for video Far too slow to handle effects for video
games!games!
Enter the Game SDKEnter the Game SDK
Introduced to promote game Introduced to promote game development on the Windows development on the Windows PlatformPlatform
Designed to shift responsibility Designed to shift responsibility away from the developer and to the away from the developer and to the hardware manufacturerhardware manufacturer
Soon became known as DirectXSoon became known as DirectX
What does DirectX What does DirectX provide?provide?
Fast, low latency access to hardwareFast, low latency access to hardware Hardware emulation for certain tasks (if Hardware emulation for certain tasks (if
required)required) A single set of API calls regardless of A single set of API calls regardless of
system hardwaresystem hardware Multiplayer support that is indifferent to Multiplayer support that is indifferent to
transport media (TCP/IP, IPX, Null Modem, transport media (TCP/IP, IPX, Null Modem, etc.)etc.)
And so much more!And so much more!
The Hardware Abstraction The Hardware Abstraction Layer (HAL)Layer (HAL)
Standard interface to any Standard interface to any hardware device supported by hardware device supported by Windows and DirectXWindows and DirectX
The HAL is a very thin software The HAL is a very thin software layer provided by the vendor to layer provided by the vendor to interface with the hardware deviceinterface with the hardware device
The Hardware Emulation The Hardware Emulation Layer (HEL)Layer (HEL)
Used to provide those functions in Used to provide those functions in software that are not available in software that are not available in hardwarehardware
A much slower solution, however it A much slower solution, however it allows all systems to provide at allows all systems to provide at least a minimal amount of DirectX least a minimal amount of DirectX functionalityfunctionality
Components of DirectXComponents of DirectX
DirectDrawDirectDraw Direct3DDirect3D DirectSoundDirectSound DirectPlayDirectPlay DirectInputDirectInput DirectSetupDirectSetup DirectMusicDirectMusic DirectShowDirectShow
DirectDraw BasicsDirectDraw Basics
Provides an interface to the 2D Provides an interface to the 2D hardware available on modern hardware available on modern video cardsvideo cards
Important ConceptsImportant Concepts Graphics ModesGraphics Modes The DirectDraw ObjectThe DirectDraw Object Primary DirectDraw SurfacePrimary DirectDraw Surface
Data Structure Data Structure InitializationInitialization
Critical in DirectXCritical in DirectX ExampleExample
Typically, DirectX structures require Typically, DirectX structures require that the dwSize parameter be initializedthat the dwSize parameter be initialized
DDSURFACEDESC ddsdesc;
ZeroMemory(&ddsdesc, sizeof(ddsdesc));
ddsdesc.dwSize = sizeof(ddsdesc);
Page FlippingPage Flipping
Requires addition of a Back Buffer Requires addition of a Back Buffer SurfaceSurface
Prevents “tearing” from occurringPrevents “tearing” from occurring
No Page Flipping Demo
Page Flipping Demo
Page Flipping – IllustrationPage Flipping – Illustration
Surface 1
Surface 2
Before Page Flip
DisplayAddress Front
Buffer
BackBuffer
Monitor
Surface 1
Surface 2
After Page Flip
DisplayAddress Front
Buffer
BackBuffer
Monitor
The SurfaceThe Surface
Typically “imagined” as a 2D surface, Typically “imagined” as a 2D surface, however is actually a linear bufferhowever is actually a linear buffer
Described by the DDSurfaceDesc Described by the DDSurfaceDesc structurestructure A DDSURFACEDESC structure is used to A DDSURFACEDESC structure is used to
either define a surface when either define a surface when CreateSurface is called or to describe CreateSurface is called or to describe the current condition of a buffer using the current condition of a buffer using GetSurfaceDescGetSurfaceDesc
MSDN – Your FriendMSDN – Your Friend
Exercise – Look up DDSurfaceDesc Exercise – Look up DDSurfaceDesc and read the description of its and read the description of its member variablesmember variables
Launch MSDNLaunch MSDN Important Member VariablesImportant Member Variables
PitchPitch lpSurfacelpSurface ddckCKDestBlt, ddckCKSrcBltddckCKDestBlt, ddckCKSrcBlt
Blitting to a SurfaceBlitting to a Surface
A blit is the process of copying an A blit is the process of copying an image from one surface onto image from one surface onto anotheranother
Two Types of blitting in DirectDrawTwo Types of blitting in DirectDraw Direct access of the surface to Direct access of the surface to
perform the blitperform the blit Using Blt and BltFast to perform the Using Blt and BltFast to perform the
blitting operationblitting operation
Blt and BltFastBlt and BltFast
Used to fill surfaces or copy an Used to fill surfaces or copy an image to a surfaceimage to a surface
BltFast has less options than BltBltFast has less options than Blt BltFast provides a speed increase BltFast provides a speed increase
when the HEL is being used (~10%)when the HEL is being used (~10%) Blt DemoBlt Demo
But I don’t want to have only But I don’t want to have only squares!squares!
Loading Images into an Off-Screen SurfaceLoading Images into an Off-Screen Surface Typically requires direct access of the screen Typically requires direct access of the screen
buffer to allow for custom file formatsbuffer to allow for custom file formats Raw 24bpp images require no decompression, Raw 24bpp images require no decompression,
however they are largehowever they are large Bitmaps can be blitted through the GDIBitmaps can be blitted through the GDI The Lock() and Unlock() functionsThe Lock() and Unlock() functions
Used to “grab” a surface to blt toUsed to “grab” a surface to blt to Must be used together or other functions will be Must be used together or other functions will be
unable to access the surface!unable to access the surface!
File I/OFile I/O
CreateFile, ReadFile, CloseHandleCreateFile, ReadFile, CloseHandle CreateFile returns a handle to a new or existing CreateFile returns a handle to a new or existing
file so read/write operations can occurfile so read/write operations can occur ReadFile returns a specified number of bytesReadFile returns a specified number of bytes CloseHandle closes the fileCloseHandle closes the file
Transparent BltsTransparent Blts
DDCOLORKEY StructureDDCOLORKEY Structure Two member variables used to define a color Two member variables used to define a color
space that will appear transparentspace that will appear transparent Select the color key for a surface using Select the color key for a surface using
the SetColorKey() Methodthe SetColorKey() Method Select either the Destination Color Key or Select either the Destination Color Key or
the Source Color Keythe Source Color Key Call Blt or BltFast using the appropriate Call Blt or BltFast using the appropriate
flag to create the transparent Bltflag to create the transparent Blt
Transparent Blt DemoTransparent Blt Demo
DemoDemo The selected color key is The selected color key is
RGB(255,0,255) – the pink in this RGB(255,0,255) – the pink in this picturepicture
Interfacing to the UserInterfacing to the User
Win32 MessagesWin32 Messages WM_MOUSEMOVE, WM_LBUTTONDOWN, etc.WM_MOUSEMOVE, WM_LBUTTONDOWN, etc. Excellent for applicationsExcellent for applications Dependent upon message queue to handle Dependent upon message queue to handle
user inputuser input Direct InputDirect Input
Requires polling of the deviceRequires polling of the device Can be synced to get new input every frameCan be synced to get new input every frame Allows use of specialized game devicesAllows use of specialized game devices
USB Joysticks, Flight Pedals, etc.USB Joysticks, Flight Pedals, etc.
Direct InputDirect Input
USB ConsiderationsUSB Considerations USB allows for up to 127 devices to USB allows for up to 127 devices to
be connected!be connected! The user may have more than one The user may have more than one
mouse, joystick or keyboard mouse, joystick or keyboard connected to the systemconnected to the system
Needs to “gracefully” recover from Needs to “gracefully” recover from having a device disconnected from having a device disconnected from the systemthe system
Multi-Threaded Application Multi-Threaded Application DevelopmentDevelopment
Threads rock!Threads rock! Every programmer loves threads the Every programmer loves threads the
first time they use themfirst time they use them A multi-threaded application can A multi-threaded application can
perform multiple tasks at “once”perform multiple tasks at “once” Very useful to allow GUIs to appear Very useful to allow GUIs to appear
“alive” as an intensive calculation “alive” as an intensive calculation occurs in the backgroundoccurs in the background
Multi-Threaded DemoMulti-Threaded Demo
Thread SynchronizationThread Synchronization
Critical SectionsCritical Sections Kernel ObjectsKernel Objects
Ex. Mutex, Semaphore, Event, Ex. Mutex, Semaphore, Event, Thread, Process and many moreThread, Process and many more
Critical SectionCritical Section
A segment of code that needs to be A segment of code that needs to be executed without being pre-emptedexecuted without being pre-empted
Started by making a call to Started by making a call to EnterCriticalSectionEnterCriticalSection
Completed by calling LeaveCriticalSectionCompleted by calling LeaveCriticalSection System will appear “locked” during a critical System will appear “locked” during a critical
sectionsection Important to keep these sections to a minimal Important to keep these sections to a minimal
sizesize Only use in areas that require it to be usedOnly use in areas that require it to be used
Kernel ObjectsKernel Objects An object that is shared between An object that is shared between
threadsthreads WaitForSingleObject and WaitForSingleObject and
WaitForMultipleObject will wait until WaitForMultipleObject will wait until a specified kernel object is signaleda specified kernel object is signaled Important to thoroughly analyze the Important to thoroughly analyze the
return value to prevent from return value to prevent from misinterpreting the resultsmisinterpreting the results
WAIT_FAILED, WAIT_OBJECT_0, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT, WAIT_ABANDONED_0WAIT_TIMEOUT, WAIT_ABANDONED_0
Example – Buggy CodeExample – Buggy Code
DWORD dwWaitResult;
dwWaitResult = WaitForSingleObject(hMutex, 1000);
If (WAIT_FAILED == dwWaitResult)
{ // Handle Failure }
Else
{ // Assume Success – Potential Bug! }
Example – Solid CodeExample – Solid Code
DWORD dwWaitResult;
dwWaitResult = WaitForSingleObject(hMutex, 1000);
If (WAIT_OBJECT_0 == dwWaitResult)
{ // The mutex is now owned }
Else
{ // Handle Wait failure. Differentiate between the 3 possible failures }
Dangers of Multi-Threaded Dangers of Multi-Threaded DevelopmentDevelopment
““Dueling” conditions between Dueling” conditions between threadsthreads Race ConditionsRace Conditions
Exist where two or more threads are Exist where two or more threads are competing to share the same resourcecompeting to share the same resource
Very difficult to track – good design will Very difficult to track – good design will prevent bugs of this natureprevent bugs of this nature
StarvationStarvation Occurs when a single thread controls a Occurs when a single thread controls a
resource due to scheduling priorityresource due to scheduling priority
Race Condition ExampleRace Condition Example
Two threads A and B share a Two threads A and B share a common DirectDraw Surfacecommon DirectDraw Surface
Thread A locks the surfaceThread A locks the surface Before it is unlocked, A is pre-Before it is unlocked, A is pre-
empted by B, which needs to access empted by B, which needs to access the surfacethe surface
Solution: Use a critical section to Solution: Use a critical section to prevent a conflict or consolidate the prevent a conflict or consolidate the two threadstwo threads
Starvation ExampleStarvation Example
Two threads – A and BTwo threads – A and B A has higher priority than BA has higher priority than B They share a common resourceThey share a common resource A completes so quickly that it A completes so quickly that it
immediately reacquires the immediately reacquires the resource preventing B from resource preventing B from executingexecuting
Application to Game Application to Game DevelopmentDevelopment
Allows background processing of dataAllows background processing of data Example:Example:
One thread for system messagesOne thread for system messages One thread for drawing the frame bufferOne thread for drawing the frame buffer One thread to handle input (user or network)One thread to handle input (user or network)
Potential increase in speed by using Potential increase in speed by using multiprocessor systemsmultiprocessor systems Quake 3Quake 3
Basics to start Basics to start programmingprogramming
The latest DirectX SDKThe latest DirectX SDK Make sure to add ddraw.lib to the Make sure to add ddraw.lib to the
link option in Visual C++ (under link option in Visual C++ (under the Project->Settings menu)the Project->Settings menu)
Have patience! Debugging Have patience! Debugging DirectDraw is difficultDirectDraw is difficult
MSDNMSDN
Further ReadingFurther Reading
Inside DirectXInside DirectX, Bargen and , Bargen and Donnelly. Microsoft PressDonnelly. Microsoft Press
Win32 Multithreaded ProgrammingWin32 Multithreaded Programming, , Cohen and Woodring. O’Reilly.Cohen and Woodring. O’Reilly.
Programming WindowsProgramming Windows, Charles , Charles Petzold. Microsoft Press. (No Petzold. Microsoft Press. (No Windows programmer should be Windows programmer should be without this!)without this!)
ContactsContacts
Alex RiemannAlex Riemann [email protected]@uiuc.edu
Microsoft UIUC Recruiter - Tracy Microsoft UIUC Recruiter - Tracy FoltzFoltz [email protected]@microsoft.com