DirectX 入门例程

本文提供了一个DirectX入门级别的示例程序,讲解了DirectX对象、主平面、辅助平面和位图平面的概念,并展示了如何使用DirectX进行画面控制、位图和文字的绘制。示例中包含了创建DirectX实例、显示位图和文字的步骤,以及精灵图像的运动更新。适合初学者了解DirectX的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个事例程序是本人在SDK样例程序中改写的,将其中无关的内容删除。希望对刚入门的学习者有帮助。

DirectX中的Dreaw的使用方法:
我看过几篇文章写得不错,想表达一下我的理解。
DirectX对象是对一个屏幕的控制权的操作,主要的方法有:创建,刷新,卸载。
平面(表面,缓存等几个名称)是一块显存空间,使用的平面有三种:
1、主平面(前平面),前平面是屏幕显示的内容,显卡读取主平面内容显示在屏幕上。
2、辅助平面(后平面),后平面是存放程序将要显示的内容,当辅助平面内容完成后,交换主平面与辅助平面,是屏幕

显示辅助平面的内容,不停的在辅助平面内画,不停的交换,使屏幕不出现闪烁。
3、位图(文字)平面,此平面用来将位图或文字画在一个平面内,需要时将位图或文字拷贝到辅助平面。位图(文字)

平面在创建时大小已经固定,位图平面加在的位图变化后(使用CSurface::DrawBitmap函数),如果尺寸改变,这位图

将要变形(限于此程序,此方法使StretchBlt( hDC, 0, 0, ddsd.dwWidth, ddsd.dwHeight,hDCImage, 0, 0,

bmp.bmWidth, bmp.bmHeight,SRCCOPY )位图变形),文字平面改变文字内容后(使用CSurface::DrawText函数),如果

文字变多则超出部分不能显示,如果变少则前面的文字不能覆盖,本人解决的方式是
GetTextExtentPoint32( hDC, strText, _tcslen(strText), &sizeText ); //得到显示文字的尺寸
dwHeight = sizeText.cx ; //保留字体的大小
dwHeight = sizeText.cy;
得到有效的宽度和高度,在显示时只显示有效部分
 prc.top = 1;
 prc.bottom = g_pTextSurface->GetHeight();
 prc.left = 1;
 prc.right = g_pTextSurface->GetWidth();
 g_pDisplay->Blt( 10, 10, g_pTextSurface, NULL ); //在指定位置显示文字 

下面我是程序

Client.cpp

#include <windows.h>
#include <mmsystem.h>
#include "resource.h"
#include "ddutil.h"

#define SCREEN_WIDTH 800 //创建DirectX的宽度,高度,颜色深度
#define SCREEN_HEIGHT 600
#define SCREEN_BPP 16 //XXXXX(红)XXXXXX(绿)XXXXX(蓝)
#define RGB16_GREEN 0x07E0 //0000,0111,1110,0000
#define RGB16_WHITE 0xFFFF //1111,1111,1111,1111
#define RGB16_BLACK 0x0000 //0000,0000,0000,0000

#define YUNDONG_UP    1  //定义运动的方向
#define YUNDONG_DOWN  2
#define YUNDONG_LEFT  3
#define YUNDONG_RIGHT 4

#define NUM_SPRITES 1 //定义出现的精灵图像个数

struct SPRITE   //定义精灵的运动结构
{
 FLOAT fPosX;  //出现的位置
 FLOAT fPosY;
 FLOAT fVelX;  //水平或垂直运动的速度
 FLOAT fVelY;
 DWORD dwWidth;  //定义的大小;  
 DWORD dwHeight;
 INT iFangXiang;  //精灵运动的方向
};

CDisplay* g_pDisplay;  //创建DirectX类的实例
CSurface* g_pLogoSurface; //创建一个位图表面
CSurface* g_pTextSurface; //创建一个文字表面
SPRITE g_Sprite[NUM_SPRITES]; //创建图像精灵  
DWORD g_dwLastTick ;  //记录时间
BOOL g_bActive;    //判断DirectX是否能活动
BOOL g_bLianJie;   //跳过窗口的判断变量

LRESULT CALLBACK MainWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam );//窗口的消息处理函数
HRESULT ProcessNextFrame();   //显示下一帧
void UpdateSprite( SPRITE* pSprite, FLOAT fTimeDelta );  //更新精灵的范围的边界情况
HRESULT DisplayFrame();  //显示帧的内容
HRESULT RestoreSurfaces(); //当平面信息丢失时更新平面的内容
VOID FreeDirectDraw();  //释放表面及DirectX实例


//////////////////////////////////////
//   应用程序入口   //
//////////////////////////////////////
int APIENTRY WinMain( HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR pCmdLine, int nCmdShow )
{
 WNDCLASS wc;
 HWND hWnd;
 HACCEL hAccel;
 MSG msg;
   
 ZeroMemory( &g_Sprite, sizeof(SPRITE) * NUM_SPRITES );
    srand( GetTickCount() );
 

 //////////////////////////////////////
 //   创建游戏窗体   //
 //////////////////////////////////////
 wc.lpszClassName = TEXT("Client"); //窗口类名称
 wc.lpfnWndProc = MainWndProc;  //消息处理函数
 wc.style = CS_VREDRAW | CS_HREDRAW; //窗口的类型
 wc.hInstance = hInst;    //窗口实例(继承)
 wc.hIcon = LoadIcon( hInst, MAKEINTRESOURCE(IDI_MAIN) ); //窗口图标
 wc.hCursor = LoadCursor( NULL, IDC_ARROW );    //窗口鼠标
 wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); //窗口的背景
 wc.lpszMenuName = NULL; //窗口菜单
 wc.cbClsExtra = 0; //保留
 wc.cbWndExtra = 0; //保留

 if( RegisterClass( &wc ) == 0 ) //判断窗口类是否注册成功
  return E_FAIL;


 hWnd = CreateWindow( TEXT("Client"), TEXT("Client1"), //创建窗口
       WS_SYSMENU | WS_MAXIMIZEBOX, 180,110,
       430, 230, NULL, NULL, hInst, NULL );

    if( hWnd == NULL ) //判断窗口是否创建成功
     return E_FAIL;

 ShowWindow( hWnd, nCmdShow ); //显示窗口
 UpdateWindow( hWnd );  //更新窗口
 //以下四行内容显示一个窗口,可删除
 g_bLianJie = false;  //设置窗口退出条件
 while(GetMessage( &msg, NULL, 0, 0 ) && !g_bLianJie) //显示窗口并处理消息
 {
  TranslateMessage( &msg );
  DispatchMessage( &msg );
 }

 hAccel = LoadAccelerators( hInst, MAKEINTRESOURCE(IDR_MAIN_ACCEL) ); //创建按键关联表

 //////////////////////////////////
 //   创建DirectDraw  //
 //////////////////////////////////
 HRESULT hr;
 
 g_pDisplay = new CDisplay(); //定义DirectX实例
 //创建一个全屏的窗体
 if( FAILED( hr = g_pDisplay->Create( hWnd, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP ) ) )
  return hr;

 //创建一个平面,并且在画上一个位图资源,用于显示位图
 if( FAILED( hr = g_pDisplay->CreateSurfaceFromBitmap(&g_pLogoSurface, MAKEINTRESOURCE( IDB_DIRECTX ), 0, 0) ) )
  return hr;
 //设置位图显示时的透明颜色
 if( FAILED( hr = g_pLogoSurface->SetColorKey( RGB16_BLACK ) ) )
  return hr;
 //创建一个平面,并且在输出文字资源,用于显示文字
 if( FAILED( hr = g_pDisplay->CreateSurfaceFromText( &g_pTextSurface, NULL, "123456789",
              RGB(0,255,0), RGB(255, 255, 0) ) ) )
  return hr;
 //设置文字显示时的透明颜色(应该与文字背景色一致)
 if( FAILED( hr = g_pTextSurface->SetColorKey( RGB16_GREEN ) ) )
  return hr;

 for( int i = 0; i < NUM_SPRITES; i++ ) //定义精灵初始值
 {
  g_Sprite[i].fPosX = 0.0f;
  g_Sprite[i].fPosY = 0.0f;
        g_Sprite[i].fVelX = 0.0f;
        g_Sprite[i].fVelY = 0.0f;
  g_Sprite[i].dwWidth = g_pLogoSurface->GetWidth(); //得到位图平面的宽度和高度
  g_Sprite[i].dwHeight = g_pLogoSurface->GetHeight();
  g_Sprite[i].iFangXiang = YUNDONG_UP;
 }

 g_dwLastTick = timeGetTime(); //记录当前时间

 while(true)//进入消息循环,以下内容不明白,请有心人帮忙解释一下
 {
  if( PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE ) ) //判断是否收到消息
  {
   //WM_QUIT退出消息
   if( 0 == GetMessage(&msg, NULL, 0, 0 ) ) 
   {
    return (int)msg.wParam;
   }
 
   //翻译并且分派消息
   if( 0 == TranslateAccelerator( hWnd, hAccel, &msg ) ) //是否是按键表对应的消息
   {
    TranslateMessage( &msg );
    DispatchMessage( &msg );
   }
  }
  else
  {
   if( g_bActive )  //当可以重画屏幕时
   {
    if( FAILED( ProcessNextFrame() ) ) //显示下一帧
     return 0;
   }
   else
   {
    WaitMessage();  //等待消息
    g_dwLastTick = timeGetTime(); 
   }
  }
 }
 return 0;
}

//////////////////////////////////////////////
//   游戏窗体消息处理函数   //
//////////////////////////////////////////////
LRESULT CALLBACK MainWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
 HDC hdc;
 PAINTSTRUCT ps;

 switch (msg)
 {
  case WM_KEYDOWN: //当任意键按下时退出开始的窗口
   g_bLianJie = true;
   return 0L;
  case WM_PAINT: //重画屏幕消息与DirectX无关
  {
   hdc = BeginPaint(hWnd, &ps); //得到DC
   HFONT hFont = CreateFont(30,0,0,0,0,0,0,0,0,0,0,0,0,"宋体"); //创建字体
   SelectObject(hdc, hFont); //设置字体
   DeleteObject(hFont); //删除字体
   //GetClientRect( hWnd, &rect );
   SetTextColor(hdc, RGB(0, 0, 0)); //设置颜色
   TextOut(hdc, 100, 50, "欢迎使用游戏", 12); //显示文字
   SetTextColor(hdc, RGB(0, 0, 255));
   TextOut(hdc, 100, 100, "我的DirectXDraw", 15);

   EndPaint( hWnd, &ps); //删除DC
            return 0L;
  }
  case WM_COMMAND: 
   switch ( LOWORD(wParam) )
   {
    case IDM_EXIT: //按键表中的退出消息
     PostMessage( hWnd, WM_CLOSE, 0, 0 );
     return 0L;
    case IDM_UP: //按键表中的向上消息
     g_Sprite[0].fVelX = 0.0f; //水平不运动
     g_Sprite[0].fVelY = -100.0f; //竖直向上
     g_Sprite[0].iFangXiang = YUNDONG_UP; //运动方向
     break;
    case IDM_DOWN: //按键表中的向下消息
     g_Sprite[0].fVelX = 0.0f;
     g_Sprite[0].fVelY = 100.0f;
     g_Sprite[0].iFangXiang = YUNDONG_DOWN;
   &

directx 3d 实例#include #include "d3d9.h" #include "d3dx9.h" #include "Direct3D.h" // Direct3D objects IDirect3D9 *g_pD3D = NULL; IDirect3DDevice9 *g_pD3DDevice = NULL; // Sky vertex structure, fvf, vertex buffer, and texture typedef struct { float x, y, z, rhw; float u, v; } sSkyVertex; #define SKYFVF (D3DFVF_XYZRHW | D3DFVF_TEX1) IDirect3DVertexBuffer9 *g_SkyVB = NULL; IDirect3DTexture9 *g_SkyTexture = NULL; // Land and water meshes D3DXMESHCONTAINER_EX *g_WaterMesh = NULL; D3DXMESHCONTAINER_EX *g_LandMesh = NULL; // Window class and caption text char g_szClass[] = "TextureTransformationClass"; char g_szCaption[] = "Texture Transformation Demo by Jim Adams"; // Function prototypes int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow); long FAR PASCAL WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); void Matrix4x4To3x3(D3DXMATRIX *matOut, D3DXMATRIX *matIn); BOOL DoInit(HWND hWnd, BOOL Windowed = TRUE); void DoShutdown(); void DoFrame(); int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow) { WNDCLASSEX wcex; MSG Msg; HWND hWnd; // Initialize the COM system CoInitialize(NULL); // Create the window class here and register it wcex.cbSize = sizeof(wcex); wcex.style = CS_CLASSDC; wcex.lpfnWndProc = WindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInst; wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.lpszClassName = g_szClass; wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wcex)) return FALSE; // Create the main window hWnd = CreateWindow(g_szClass, g_szCaption, WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 0, 0, 640, 480, NULL, NULL, hInst, NULL); if(!hWnd) return FALSE; ShowWindow(hWnd, SW_NORMAL); UpdateWindow(hWnd); // Call init function and enter message pump if(DoInit(hWnd) == TRUE) { // Start message pump, waiting for user to exit ZeroMemory(&Msg, sizeof(MSG)); while(Msg.message != WM_QUIT) { if(PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } // Render a single frame DoFrame(); } } // Call shutdown DoShutdown(); // Unregister the window class UnregisterClass(g_szClass, hInst); // Shut down the COM system CoUninitialize(); return 0; } long FAR PASCAL WindowProc(HWND hWnd, UINT uMsg, \ WPARAM wParam, LPARAM lParam) { // Only handle window destruction messages switch(uMsg) { case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, uMsg, wParam, lParam); } return 0; } BOOL DoInit(HWND hWnd, BOOL Windowed) { // Initialize Direct3D InitD3D(&g_pD3D, &g_pD3DDevice, hWnd); // Load the land and water meshes LoadMesh(&g_WaterMesh, g_pD3DDevice, "..\\Data\\Water.x", "..\\Data\\"); LoadMesh(&g_LandMesh, g_pD3DDevice, "..\\Data\\Land.x", "..\\Data\\"); // Create the sky backdrop sSkyVertex SkyVerts[4] = { { 0.0f, 0.0, 1.0, 1.0f, 0.0f, 0.0f }, { 640.0f, 0.0, 1.0, 1.0f, 1.0f, 0.0f }, { 0.0f, 480.0, 1.0, 1.0f, 0.0f, 1.0f }, { 640.0f, 480.0, 1.0, 1.0f, 1.0f, 1.0f } }; g_pD3DDevice->CreateVertexBuffer(sizeof(SkyVerts), D3DUSAGE_WRITEONLY, SKYFVF, D3DPOOL_DEFAULT, &g_SkyVB, NULL); char *Ptr; g_SkyVB->Lock(0,0, (void**)&Ptr, 0); memcpy(Ptr, SkyVerts, sizeof(SkyVerts)); g_SkyVB->Unlock(); D3DXCreateTextureFromFile(g_pD3DDevice, "..\\Data\\Sky.bmp", &g_SkyTexture); // Setup a light D3DLIGHT9 Light; ZeroMemory(&Light, sizeof(Light)); Light.Diffuse.r = Light.Diffuse.g = Light.Diffuse.b = Light.Diffuse.a = 1.0f; Light.Type = D3DLIGHT_DIRECTIONAL; D3DXVECTOR3 vecLight = D3DXVECTOR3(-1.0f, -1.0f, 0.5f); D3DXVec3Normalize(&vecLight, &vecLight); Light.Direction = vecLight; g_pD3DDevice->SetLight(0, &Light); g_pD3DDevice->LightEnable(0, TRUE); // Start playing a waterfall sound PlaySound("..\\Data\\Waterfall.wav", NULL, SND_ASYNC | SND_LOOP); return TRUE; } void DoShutdown() { // Stop playing an ocean sound PlaySound(NULL, NULL, 0); // Free meshes delete g_WaterMesh; g_WaterMesh = NULL; delete g_LandMesh; g_LandMesh = NULL; // Release sky data ReleaseCOM(g_SkyVB); ReleaseCOM(g_SkyTexture); // Release D3D objects ReleaseCOM(g_pD3DDevice); ReleaseCOM(g_pD3D); } void DoFrame() { // Create and set the view transformation D3DXMATRIX matView; D3DXMatrixLookAtLH(&matView, &D3DXVECTOR3(360.0f, -170.0f, -430.0f), &D3DXVECTOR3(65.0f, 70.0f, -15.0f), &D3DXVECTOR3(0.0f, 1.0f, 0.0f)); g_pD3DDevice->SetTransform(D3DTS_VIEW, &matView); // Clear the device and start drawing the scene g_pD3DDevice->Clear(NULL, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0,0,64,255), 1.0, 0); if(SUCCEEDED(g_pD3DDevice->BeginScene())) { // Set identity matrix for world transformation D3DXMATRIX matWorld; D3DXMatrixIdentity(&matWorld); g_pD3DDevice->SetTransform(D3DTS_WORLD, &matWorld); // Draw the sky g_pD3DDevice->SetFVF(SKYFVF); g_pD3DDevice->SetStreamSource(0, g_SkyVB, 0, sizeof(sSkyVertex)); g_pD3DDevice->SetTexture(0, g_SkyTexture); g_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); // Enable lighting g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, TRUE); // Draw the land meshes DrawMeshes(g_LandMesh); // Setup the texture transformation float TimeFactor = (float)(timeGetTime() / 500.0f); D3DXMATRIX matTexture; D3DXMatrixTranslation(&matTexture, 0.0f, -TimeFactor, 0.0f); Matrix4x4To3x3(&matTexture, &matTexture); g_pD3DDevice->SetTransform(D3DTS_TEXTURE0, &matTexture); g_pD3DDevice->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2); // Draw the water (using alpha blending) DrawMeshes(g_WaterMesh); g_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); // Disable lighting g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE); // Turn off texture transformations g_pD3DDevice->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); // End the scene g_pD3DDevice->EndScene(); } // Present the scene to the user g_pD3DDevice->Present(NULL, NULL, NULL, NULL); } void Matrix4x4To3x3(D3DXMATRIX *matOut, D3DXMATRIX *matIn) { matOut->_11 = matIn->_11; // Copy over 1st row matOut->_12 = matIn->_12; matOut->_13 = matIn->_13; matOut->_14 = 0.0f; matOut->_21 = matIn->_21; // Copy over 2nd row matOut->_22 = matIn->_22; matOut->_23 = matIn->_23; matOut->_24 = 0.0f; matOut->_31 = matIn->_41; // Copy bottom row matOut->_32 = matIn->_42; // used for translation matOut->_33 = matIn->_43; matOut->_34 = 0.0f; matOut->_41 = 0.0f; // Clear the bottom row matOut->_42 = 0.0f; matOut->_43 = 0.0f; matOut->_44 = 1.0f; }
不错的dx11入门教程 Tutorial 1: Setting up DirectX 11 with Visual Studio Tutorial 2: Creating a Framework and Window Tutorial 3: Initializing DirectX 11 Tutorial 4: Buffers, Shaders, and HLSL Tutorial 5: Texturing Tutorial 6: Diffuse Lighting Tutorial 7: 3D Model Rendering Tutorial 8: Loading Maya 2011 Models Tutorial 9: Ambient Lighting Tutorial 10: Specular Lighting Tutorial 11: 2D Rendering Tutorial 12: Font Engine Tutorial 13: Direct Input Tutorial 14: Direct Sound Tutorial 15: FPS, CPU Usage, and Timers Tutorial 16: Frustum Culling Tutorial 17: Multitexturing and Texture Arrays Tutorial 18: Light Maps Tutorial 19: Alpha Mapping Tutorial 20: Bump Mapping Tutorial 21: Specular Mapping Tutorial 22: Render to Texture Tutorial 23: Fog Tutorial 24: Clipping Planes Tutorial 25: Texture Translation Tutorial 26: Transparency Tutorial 27: Reflection Tutorial 28: Screen Fades Tutorial 29: Water Tutorial 30: Multiple Point Lights Tutorial 31: 3D Sound Tutorial 32: Glass and Ice Tutorial 33: Fire Tutorial 34: Billboarding Tutorial 35: Depth Buffer Tutorial 36: Blur Tutorial 37: Coming Soon... DirectX 10 Tutorials: Tutorial 1: Setting up DirectX 10 with Visual Studio Tutorial 2: Creating a Framework and Window Tutorial 3: Initializing DirectX 10 Tutorial 4: Buffers, Shaders, and HLSL Tutorial 5: Texturing Tutorial 6: Diffuse Lighting Tutorial 7: 3D Model Rendering Tutorial 8: Loading Maya 2011 Models Tutorial 9: Ambient Lighting Tutorial 10: Specular Lighting Tutorial 11: 2D Rendering Tutorial 12: Font Engine Tutorial 13: Direct Input Tutorial 14: Direct Sound Tutorial 15: FPS, CPU Usage, and Timers Tutorial 16: Frustum Culling Tutorial 17: Multitexturing and Texture Arrays Tutorial 18: Light Maps Tutorial 19: Alpha Mapping Tutorial 20: Bump Mapping Tutorial 21: Specular Mapping Tutorial 22: Render to Texture Tutorial 23: Fog Tutorial 24: Clipping Planes Tutorial 25: Texture Translation Tutorial 26: Transparency Tutorial 27: Reflection Tutorial 28: Screen Fades Tutorial 29: Water Tutorial 30: Multiple Point Lights Tutorial 31: 3D Sound Tutorial 32: Glass and Ice Tutorial 33: Fire Tutorial 34: Billboarding Tutorial 35: Depth Buffer Tutorial 36: Blur Tutorial 37: Coming Soon... DirectX 10 Terrain Tutorials: Tutorial 1: Grid and Camera Movement Tutorial 2: Height Maps Tutorial 3: Terrain Lighting Tutorial 4: Terrain Texturing Tutorial 5: Color Mapped Terrain Tutorial 6: Quad Trees Tutorial 7: Coming Soon... 。。。。。。。。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值