DirectX 3D Programming - PowerPoint PPT Presentation

1 / 35
About This Presentation
Title:

DirectX 3D Programming

Description:

... methods can return success codes even though the rendering ... focus, such as when the user presses ALT TAB or when a system dialog is initialized ... – PowerPoint PPT presentation

Number of Views:203
Avg rating:3.0/5.0
Slides: 36
Provided by: abdennour8
Category:

less

Transcript and Presenter's Notes

Title: DirectX 3D Programming


1
DirectX 3D Programming
Abdennour El Rhalibi
2
The Rise and Fall of the 3D Engine
  • What caused the great turnaround was the
    introduction of the first 3D accelerators into
    the market.
  • 3D products with huge polygon counts, advanced
    lighting, texture mapping (such as Quake III
    Arena shown in Figure 10), and all the latest
    whizzy features now jostle for position on the
    shelf.  

Fig. 10 Quake III Arena
3
The Features Of DirectX
  • Today's games use DirectX and so support many if
    not all of the graphical features provided by
    this SDK.
  • Polygons
  • Lights
  • Environmental Effects
  • Hardware

4
D3D Architecture
  • Microsoft Direct3D provides device independence
    through the hardware abstraction layer (HAL)
  • HAL is a device-specific interface
  • Application doesnt directly access video card

5
Basic Concepts
  • DX uses Left Hand Coordinate System. OpenGL uses
    Right Hand Coordinate System
  • Primitives are built using vertices, stored in
    vertex buffers
  • Different types of primitives D3DPT_POINTLIST,
    D3DPT_LINELIST, D3DPT_LINESTRIP,
    D3DPT_TRIANGLELIST,  D3DPT_TRIANGLESTRIP, D3DPT_T
    RIANGLEFAN
  • Each face has a normal associated with it.
    Normals are vectors perpendicular to the faces
    surface and point the way the face is facing
  • Face normals are specified using order of
    vertices, Clock-Wise or Counter-Clock-Wise
  • Faces with normal facing away from the camera are
    usually backfaced culled

6
Different Primitives
  • D3DPT_POINTLIST, D3DPT_LINELIST, D3DPT_LINESTRIP,
    D3DPT_TRIANGLELIST,  D3DPT_TRIANGLESTRIP, D3DPT_T
    RIANGLEFAN

7
Flexible Vertex Formats
  • A flexible vertex format
  • (FVF) code describes
  • the contents of vertices
  • stored interleaved in a
  • single data stream
  • struct BLENDVERTEX
  • D3DXVECTOR3 v // Referenced as v0 in the vertex
    shader
  • FLOAT blend1 // Referenced as v1.x in the vertex
    shader
  • FLOAT blend2 // Referenced as v1.y in the vertex
    shader
  • FLOAT blend3 // Referenced as v1.z in the vertex
    shader
  • // v1.w 1.0 - (v1.x v1.y v1.z)
  • D3DXVECTOR3 n // Referenced as v3 in the vertex
    shader
  • FLOAT tu, tv // Referenced as v7 in the vertex
    shader
  • define D3DFVF_BLENDVERTEX (D3DFVF_XYZB3D3DFVF_NO
    RMALD3DFVF_TEX1)

8
Transforms
  • Vertices are transformed or projected from 3D
    space into 2D space by multiplying them by a
    series of Matrices
  • World Matrix defines the transformation of the
    entire world aka applies to every object
  • View transformation defines the camera and where
    the camera is looking
  • Projection transformation projects vertices from
    3D to 2D

9
3D Transformations
  • Notice that DirectX right multiplies matrix! Not
    a big problem just remember, Ax xTAT
  • Translation Matrix
  • Scaling Matrix
  • Rotate around x-axis
  • Rotate around y-axis
  • Rotate around z-axis

10
Matrix Concatenation
  • Matrices can be concatenated to form a single
    transformation
  • Ex T(x,y,z)R(x,y,z)S(x,y,z)x
  • means scale x, then rotate x, then translate x
    which is very different from translate x, then
    rotate it, then scale it.
  • Since DirectX right multiplies matrices to
    vertices, the above order should be reversed to
    get the desired effect aka xSRT
  • Generally, you want to first scale, rotate, and
    then translate

11
World Transform
  • Vertices defined in relation to a specific
    origin. Theyre said to be defined in model
    space.
  • World transform moves the vertices from model
    space to world space
  • Ex You have a cube defined in relation to the
    origin. You want your cube to move around so you
    dont redefine the cube but define a matrix that
    moves the cube around and you set that matrix as
    the world matrix

12
View Matrix
  • The view transformation locates the viewer in
    world space, transforming vertices into camera
    space.
  • In camera space, camera is at the origin, looking
    in the positive z-direction

13
Projection Matrix
  • Perspective projection transformation converts
    the viewing frustum into a cuboid shape. The near
    end of the viewing frustum is smaller than the
    far end, thus objects that are near are bigger
    than faraway objects
  • Orthographic projection doesnt apply scaling
    because the near and far planes are set to be
    equal in height

14
Depth Buffers
  • Two types (W or) Z-Buffer and Stencil buffer
  • Purpose is to provide a way to determine which
    object is in front of which object
  • When pixels are about to be drawn on screen,
    theyre z-value is compared to the Z-buffer. If
    pixels z-value is less than z-value of
    previously drawn pixel, then the old pixel is
    overwritten and a new z-value is stored.
  • Compare function can be changed (doesnt have to
    be less than) and you can also use Z-bias for
    pixels with the same z-value
  • Stencil Buffers are exactly like Z buffers but
    you can modify them. Useful for masks or
    dissolves.

15
Streams
  • Stream is a uniform array of component data of
    one or more elements representing a single entity
    such as position, normal, or even an entire vertex
  • Rendering primitives consists of two steps.
    First, set up one or more vertex component
    streams by IDirect3DDevice9SetStreamSource
  • Second, invoke a IDirect3DDevice9DrawPrimitive
    method to render from those streams

16
Shading
  • Flat shading - use the color of the polygon
    material at first vertex as the color for the
    entire polygon
  • Gouraud Shading computes color for each vertex
    by using the vertex normal and lighting
    parameters

17
Light
  • Basically, lights illuminate your objects and
    give objects depth
  • Different types of lights directional,
    spotlight, point
  • Color is defined in as 0-255 (int) or 0-1 (f) for
    each R,G,B,A channel
  • New video cards (Geforce FX) support 16 bits per
    channel and up to 32 bits per channel
  • Materials define the way your object interacts
    with the light in the scene (aka what type of
    light it reflects/absorbs. Ex material reflects
    only red and emits green)

18
Different Lighting
  • Ambient lighting Diffuse Lighting Specular
    Lighting Final Result
  • Emissive lighting lights all vertices with the
    same color. Effect is shown when added to other
    colors

19
Direct3D object
  • Direct3D is implemented through Component Object
    Model (COM) objects and interfaces.
  • Direct3D object is the first object that your
    application creates and the last object that your
    application releases
  • Functions for enumerating and retrieving
    capabilities of a Direct3D device are accessible
    through the Direct3D object. This enables
    applications to select devices without creating
    them
  • EXLPDIRECT3D9 g_pD3D NULL
  • if( NULL (g_pD3D Direct3DCreate9(D3D_SDK_VER
    SION)))
  • return E_FAIL

20
D3D Device
  • Is the rendering component of Direct3D
  • Encapsulates and stores the rendering state
  • Performs transformations and lighting operations
    and rasterizes an image to a surface.
  • Two types of devices HAL and software
  • You can think of these devices as two separate
    drivers, one is a software/reference driver and
    the other is the hardware driver
  • Can have three different vertex processing modes
    software vertex processing, hardware vertex
    processing, and mixed vertex

21
Creating Device
  • Set Presentation parameters
  • LPDIRECT3DDEVICE9 pDevice NULL
  • D3DPRESENT_PARAMETERS d3dpp
  • ZeroMemory( d3dpp, sizeof(d3dpp) )
  • d3dpp.Windowed TRUE
  • d3dpp.SwapEffect D3DSWAPEFFECT_COPY
  • Create the device
  • if( FAILED( g_pD3D-gtCreateDevice(
    D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
    D3DCREATE_SOFTWARE_VERTEXPROCESSING, d3dpp,
    d3dDevice ) ) )
  • return E_FAIL

22
Selecting Device
  • Applications query hardware to detect the
    supported device types.
  • Although we created device, we need to select
    an appropriate device i.e. figure out what it
    supports and what parameters we need

23
Steps to selecting device
  • Enumerate the display adapters on the system.
    Applications that are not concerned with
    multimonitor support can disregard this step, and
    pass D3DADAPTER_DEFAULT to method in step 2
  • For each adapter, the application enumerates the
    supported display modes by calling
    IDirect3D9EnumAdapterModes
  • If required, the application checks for the
    presence of hardware acceleration in each
    enumerated display mode by calling
    IDirect3D9CheckDeviceType. Look up Determining
    Hardware support for more info in the SDK
  • The application checks for the desired level of
    functionality for the device on this adapter by
    calling the IDirect3D9GetDeviceCaps method
  • If the application is required to render to a
    surface of a different format, it can call
    IDirect3D9CheckDeviceFormat
  • Lastly, the application can determine if
    multisampling techniques, such as full-scene
    antialiasing, are supported for a render format
    by using the IDirect3D9CheckDeviceMultiSampleTyp
    e method.

24
Lost Devices
  • Device can be in either an operational state or a
    lost state
  • Device makes a transition to the lost state when
    an event, such as the loss of keyboard focus in a
    full-screen application, causes rendering to
    become impossible.
  • The lost state is characterized by the silent
    failure of all rendering operations, which means
    that the rendering methods can return success
    codes even though the rendering operations fail.
  • The error code D3DERR_DEVICELOST is returned by
    IDirect3DDevice9Present.
  • Typical examples include loss of focus, such as
    when the user presses ALTTAB or when a system
    dialog is initialized
  • This is important so, go read more information in
    the SDK about Lost Devices and restoring them

25
Using Depth Buffers in High Level
  • Must query to see if Depth buffer is supported
    and format of the Depth buffer that is supported
    (different for zbuffers stencil buffers)
  • Create Depth Buffer
  • Enable Depth Buffering state

26
Using Depth Buffers Example
  • //This is done at the start of the application,
    when the d3dobj/device are created
  • //The following example assumes that pCaps is a
    valid pointer to an
  • // initialized D3DCAPS9 structure. Checking Depth
    Buffer format
  • if(FAILED(m_pD3D-gtCheckDeviceFormat(pCaps-gtAdapter
    Ordinal,

  • pCaps-gtDeviceType,

  • AdapterFormat,

  • D3DUSAGE_DEPTHSTENCIL,

  • D3DRTYPE_SURFACE,

  • D3DFMT_D16)))
  • return E_FAIL
  • // Reject devices that cannot create a render
    target of RTFormat while
  • // the back buffer is of RTFormat and the
    depth-stencil buffer is
  • // at least 8 bits of stencil
  • if(FAILED(m_pD3D-gtCheckDepthStencilMatch(pCaps-gtAd
    apterOrdinal,

  • pCaps-gtDeviceType,

  • AdapterFormat,

  • RTFormat,

  • D3DFMT_D24S8)))
  • return E_FAIL

27
Rendering/Presenting Scene
  • Must clear the buffers that are going to be used
    so you dont have leftover image artifacts
  • g_pd3dDevice-gtClear( 0, NULL, D3DCLEAR_TARGETD3DC
    LEAR_ZBUFFER D3DCLEAR_STENCIL ,
    D3DCOLOR_XRGB(0,0,255), 1.0f, 0L )
  • Rendering takes place between Begin() End()
  • // Begin the scene
  • g_pd3dDevice-gtBeginScene()
  • //Setting renderstates/rendering of scene
  • // End the scene
  • g_pd3dDevice-gtEndScene()
  • After rendering calls have been made, you must
    present the back buffer
  • g_pd3dDevice-gtPresent( NULL, NULL, NULL, NULL )

28
Fixed Function Pipeline Render States
  • Render states control the behavior of how the D3D
    Device renders the scene.Different States
  • Alpha Blending State
  • Alpha Testing State
  • Ambient Lighting State
  • Antialiasing State
  • Culling State
  • Depth Buffering State
  • Fog State
  • Lighting State
  • Outline and Fill State
  • Per-Vertex Color State
  • Primitive Clipping State
  • Shading State
  • Stencil Buffer State
  • Texture Wrapping State

29
D3D Resources
  • Resources are the textures and buffers that are
    used to render a scene. You probably wont have
    to deal specifically with a lot of the stuff
    except for the Memory Pool. Suggest skimming
    over the material in the SDK
  • Stuff can be put into Managed, SysMem or
    D3D_Default
  • Mostly dealing with Vertex Index Buffers

30
Vertex Buffers
  • Vertex buffers, represented by the
    IDirect3DVertexBuffer9 interface, are memory
    buffers that contain vertex data
  • Vertex buffers can contain any vertex type -
    transformed or untransformed, lit or unlit
  • The flexibility of vertex buffers make them ideal
    staging points for reusing transformed geometry
  • Ex Rendering models that use multiple textures
    the geometry is transformed only once, and then
    portions of it can be rendered as needed,
    interleaved with the required texture changes
  • Vertex buffer is described in terms of its
    capabilities if it can exist only in system
    memory, if it is only used for write operations,
    and the type and number of vertices it can
    contain traits described by D3DVERTEXBUFFER_DESC

31
Rendering from VB
  • Set the stream source by calling the
    IDirect3DDevice9SetStreamSource method
  • d3dDevice-gtSetStreamSource( 0, g_pVB,
    sizeof(CUSTOMVERTEX) )
  • Inform Direct3D which vertex shader to use by
    calling the IDirect3DDevice9SetVertexShader or
    IDirect3DDevice9SetFVF method
  • d3dDevice-gtSetFVF( D3DFVF_CUSTOMVERTEX )
  • After setting the stream source and vertex
    shader, any draw methods will use the vertex
    buffer
  • d3dDevice-gtDrawPrimitive( D3DPT_TRIANGLELIST, 0,
    1 )

32
Dealing w/ Vertex Buffer
  • Creating Vertex Buffer
  • //g_pVB is a variable of type LPDIRECT3DVERTEXBUFF
    ER9
  • if( FAILED( d3dDevice-gtCreateVertexBuffer(
    3sizeof(CUSTOMVERTEX), 0 / Usage /,
    D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT,
    g_pVB ) ) )
  • return E_FAIL
  • Accessing Vertex Buffer. Need to lock because VB
    can be in device memory
  • // Lock the buffer to gain access to the vertices
  • VOID pVertices
  • if(FAILED(g_pVB-gtLock(0, sizeof(g_Vertices),
    (BYTE)pVertices, 0 ) ) )
  • return E_FAIL
  • memcpy(pVertices, g_Vertices, sizeof(g_Vertices))
  • g_pVB-gtUnlock()
  • Make sure your application properly accesses the
    allocated memory. Otherwise, you risk rendering
    that memory invalid. Use the stride of the vertex
    format

33
D3DX Helper Library
  • Has a bunch of useful functions, especially math
    ones
  • Small number of Ex D3DXMatrixDeterminant ,
    D3DXMatrixIdentity, D3DXMatrixInverse ,
    D3DXMatrixScaling, D3DXMatrixRotationX,
    D3DXMatrixRotationY, D3DXMatrixRotationZ,
    D3DXMatrixTranslation , D3DXMatrixLookAtLH,
    D3DXMatrixPerspectiveLH, D3DXMatrixOrthoLH

34
Other areas of interest
  • Important How to set up lights and different
    effects of lights/materials, its very simple,
    its just setting some states and flags (under
    DirectX Graphics-gtProgramming Guide-gtFixed
    Function Pipeline-gtLights and Materials)
  • Important D3DX library. Browse it because it is
    an awesome helper library that has a bunch of
    functions/Macros that you can use without having
    to understand them (ex quaternion rotations)
  • Important Try to do the 6 tutorials to get the
    basics done
  • Important The Using DirectX SDK section provides
    some good information about error checking
    functions, tools, and how to set up DX with MSVS.
    Also has intro to COM
  • Fog, very simple b/c you just have to set a
    couple of states
  • Programmable Pipeline! Very cool stuff in there
  • Direct3D Surfaces for messing with textures are
    the pixel level
  • Texture Coordinate details
  • X file format

35
Summary 20 easy steps ?
  • Setup
  • Direct3DCreate9()
  • GetDeviceCaps()
  • GetAdapterCount() and GetAdapterModeCount()
  • D3DPRESENT_PARAMETERS
  • CreateDevice()
  • Resources
  • CreateVertexBuffer
  • CreateIndexBuffer
  • CreateTexture
  • CreateVertexShader()
  • CreatePixelShader()
  • Rendering
  • Begin/EndScene()
  • SetMaterial(...)
  • SetLight(...)
  • LightEnable(...)
  • SetViewport(...)
  • SetTransform(...) - World, view and projection
Write a Comment
User Comments (0)
About PowerShow.com