Direct3D 纹理映射

1 (3)


纹理映射是将2D的图片映射到一个3D物体上面,物体上漂亮图案被称为纹理贴图, 一个表面可以支持多张贴图等等,下面简单介绍下纹理贴图

纹理贴图UV: 贴图是一个个像素点组成,每一个像素点都由一个坐标最后形成一张贴图,贴图纹理坐标系UV两个轴组成, 从左上为原点

image


那我们在学习下如何在Direct3D中创建一个纹理,绘制到一个正方形上面去。
设计顶点格式:
struct  CUSTOMVERTEX
{
    float x,y,z,rhw;
    float u,v;
};
//至少要一张贴图D3DFVF_TEX1
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_TEX1)
创建纹理:
LPDIRECT3DTEXTURE9 g_pTexture = NULL;
//使用本地图片,创建纹理
D3DXCreateTextureFromFile(g_pd3dDevice,L"p5.jpg",&g_pTexture);

设置纹理:

g_pd3dDevice->SetTexture(0,g_pTexture);

效果图:

image

整体代码:

#include <d3d9.h>
#include <d3dx9.h>
#include <tchar.h>

#pragma comment(lib,"winmm.lib")
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")

#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600
#define WINDOW_TITLE L"盘子脸的程序"
#define SAFE_RELEASE(p) { if(p) { (p) -> Release();(p)=NULL;} }

struct  CUSTOMVERTEX
{
    float x,y,z,rhw;
    float u,v;
};
//至少要一张贴图D3DFVF_TEX1
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_TEX1) 


//声明变量
LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
ID3DXFont* g_pFont = NULL;                    
float g_FPS = 0.0f;
wchar_t g_strFPS[50];                                    //包含帧速率的字符
LPDIRECT3DVERTEXBUFFER9 g_pVertexBuffer = NULL;            //顶点缓冲区对象
LPDIRECT3DINDEXBUFFER9 g_pIndexBuffer = NULL;            //索引缓存
LPDIRECT3DTEXTURE9 g_pTexture = NULL;
    

//全局函数声明部分
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam);
HRESULT Direct3DInit(HWND hwnd);
HRESULT ObjectsInit(HWND hwnd);
VOID Direct3DRender(HWND hwnd);
VOID Direct3DCleanUp();



//主函数
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
    //设置一个完整的窗口类,没有设置图标
    WNDCLASSEX wndClass = {0};
    wndClass.cbSize = sizeof(WNDCLASSEX);
    wndClass.style = CS_HREDRAW | CS_VREDRAW;            //设置窗口样式
    wndClass.lpfnWndProc = WndProc;
    wndClass.cbClsExtra = 0;
    wndClass.cbWndExtra = 0;
    wndClass.hInstance = hInstance;
    wndClass.hCursor = LoadCursor(NULL,IDC_ARROW);
    wndClass.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH);
    wndClass.lpszMenuName = NULL;
    wndClass.lpszClassName = L"GameDevelop";


    //注册窗口类
    if(!RegisterClassEx(&wndClass))
    {
        return -1;
    }

    //正式创建窗口
    HWND hwnd = CreateWindow(L"GameDevelop",WINDOW_TITLE,WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,WINDOW_WIDTH,
        WINDOW_HEIGHT,NULL,NULL,hInstance,NULL);

    //初始化Direct3D资源
    if(!(S_OK == Direct3DInit(hwnd)))
    {
        MessageBox(hwnd,_T("初始化Direct3D失败"),_T("盘子脸的消息窗口"),0);
    }


    MoveWindow(hwnd,250,80,WINDOW_WIDTH,WINDOW_HEIGHT,true);
    ShowWindow(hwnd,nShowCmd);
    UpdateWindow(hwnd);

    //消息循环过程
    MSG msg = {0};        
    while(msg.message != WM_QUIT)
    {
        if(PeekMessage(&msg,0,0,0,PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }else
        {
            Direct3DRender(hwnd);
        }
    }

    //窗口类的注销
    UnregisterClass(L"GameDevelop",wndClass.hInstance);

    return 0;
}

//消息处理函数
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
    switch (message)
    {
    case WM_PAINT:
        Direct3DRender(hwnd);
        ValidateRect(hwnd,NULL);
        break;
    case WM_KEYDOWN:
        if(wParam == VK_ESCAPE)
        {
            DestroyWindow(hwnd);
        }
        break;
    case WM_DESTROY:
        Direct3DCleanUp();                //失败Direct3D资源
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd,message,wParam,lParam);
    }

    return 0;
}

HRESULT Direct3DInit(HWND hwnd)
{
    //创建Direct3D接口对象
    LPDIRECT3D9 pD3D = NULL;
    if(NULL == (pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
    {
        return E_FAIL;
    }

    //获取硬件消息
    D3DCAPS9 caps;
    int vp = 0;
    if(FAILED(pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,&caps)))
    {
        return E_FAIL;
    }

    if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
    {
        //支出硬件顶点运算
        vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
    }
    else
    {
        vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
    }


    //填充Direct3Dpresent参数
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory(&d3dpp,sizeof(d3dpp));
    d3dpp.BackBufferWidth = WINDOW_WIDTH;
    d3dpp.BackBufferHeight = WINDOW_HEIGHT;
    d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
    d3dpp.BackBufferCount = 1;
    d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
    d3dpp.MultiSampleQuality = 0;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.hDeviceWindow = hwnd;
    d3dpp.Windowed = true;
    d3dpp.EnableAutoDepthStencil = true;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
    d3dpp.Flags = 0;
    d3dpp.FullScreen_RefreshRateInHz = 0;
    d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;


    //创建Direct3D设备接口
    if(FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,vp,&d3dpp,&g_pd3dDevice)))
    {
        return E_FAIL;
    }

    SAFE_RELEASE(pD3D);

    if(!(S_OK == ObjectsInit(hwnd)))
    {
        return E_FAIL;
    }

    return S_OK;
}

HRESULT ObjectsInit(HWND hwnd)
{
    //创建字体
    if(FAILED(D3DXCreateFont(g_pd3dDevice,36,0,0,1,false,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,DEFAULT_QUALITY,0,_T("微软雅黑"),&g_pFont)))
    {
        return E_FAIL;
    }

    //创建顶点缓存
    if(FAILED(g_pd3dDevice->CreateVertexBuffer(4*sizeof(CUSTOMVERTEX),0,D3DFVF_CUSTOMVERTEX,D3DPOOL_DEFAULT,&g_pVertexBuffer,NULL)))
    {
        return E_FAIL;
    }

    //创建索引缓存
    if(FAILED(g_pd3dDevice->CreateIndexBuffer(6 * sizeof(WORD),D3DUSAGE_WRITEONLY,D3DFMT_INDEX16,D3DPOOL_MANAGED,&g_pIndexBuffer,0)))
    {
        return E_FAIL;
    }

    //创建顶点数据
    CUSTOMVERTEX vertices [] = 
    {
        { 100.0f, 100.0f, 0.0f, 1.0f, 0.0f,0.0f },
        { 300.0f, 100.0f, 0.0f, 1.0f, 1.0f,0.0f }, 
        { 300.0f, 300.0f, 0.0f, 1.0f, 1.0f,1.0f},
        { 100.0f, 300.0f, 0.0f, 1.0f, 0.0f,1.0f},
    };

    //填充顶点缓冲区
    VOID *pVertices;
    if(FAILED(g_pVertexBuffer->Lock(0,sizeof(vertices),(void**)&pVertices,0)))        //加锁
    {
        return E_FAIL;
    }

    memcpy(pVertices,vertices,sizeof(vertices));        //把顶点数据保存到顶点缓存中
    g_pVertexBuffer->Unlock();                            //解锁

    //这是索引缓存数据
    WORD * indices = 0;
    g_pIndexBuffer->Lock(0,0,(void**)&indices,0);

    //第一个三角形由0,1,3顶点组成
    indices[0] = 0;
    indices[1] = 1;
    indices[2] = 2;
    
    //第二个三角形由1,2,3顶点组成
    indices[3] = 0;
    indices[4] = 2;
    indices[5] = 3;

    g_pIndexBuffer->Unlock();


    //使用本地图片,创建纹理
    D3DXCreateTextureFromFile(g_pd3dDevice,L"p5.jpg",&g_pTexture);



    return S_OK;

}

void Direct3DRender(HWND hwnd)
{
    g_pd3dDevice->Clear(0,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(245,245,245),1.0f,0);
    
    //定义一个矩形
    RECT formatRect;
    GetClientRect(hwnd,&formatRect);

    g_pd3dDevice->BeginScene();
    g_pd3dDevice->SetRenderState(D3DRS_SHADEMODE,D3DSHADE_GOURAUD);
    g_pd3dDevice->SetRenderState(D3DRS_CULLMODE,false);
    g_pd3dDevice->SetRenderState(D3DRS_LIGHTING,false);

    g_pd3dDevice->SetTexture(0,g_pTexture);
    //绘制图形
    g_pd3dDevice->SetStreamSource(0,g_pVertexBuffer,0,sizeof(CUSTOMVERTEX));        //设置绘制的顶点数据
    g_pd3dDevice->SetIndices(g_pIndexBuffer);                                        //设置索引缓存
    g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);                                        //设置灵活顶点格式
    g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,4,0,2);                //根据索引绘制图形,4代表使用4个顶点,2代表两个三角形,其他查询API了解吧

    //g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST,0,4);

    //绘制文本信息
    g_pFont->DrawTextW(NULL,L"盘子脸",3,&formatRect,DT_TOP | DT_RIGHT , D3DCOLOR_XRGB(255,39,136));

    g_pd3dDevice->EndScene();
    g_pd3dDevice->Present(NULL,NULL,NULL,NULL);
}

void Direct3DCleanUp()
{
    SAFE_RELEASE(g_pVertexBuffer);
    SAFE_RELEASE(g_pFont);
    SAFE_RELEASE(g_pd3dDevice);
}

转载于:https://www.cnblogs.com/plateFace/p/4970461.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值