DirectX机制

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////Cpp文件//////////////////////////////////////////////////////////////////////////////////////////////////////////

//--------------------------------------------------------------------------------------
// File: Tutorial07.cpp
//
// This application demonstrates texturing
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include <windows.h>
#include "DXHeader\D3D11.h"
#include "DXHeader\D3DX11.h"
#include "DXHeader\D3Dcompiler.h"
#include "DXHeader\xnamath.h"
#include "resource.h"
//包含静态链接库
#pragma comment(lib, "d3dx11d.lib")

//--------------------------------------------------------------------------------------
// Structures
//--------------------------------------------------------------------------------------
//-----------------------------------------------------
//   因为CPU和GPU是通过发送消息来进行异构编程的
//   所以CPP文件中和HLSL中的变量格式应该一致
//-----------------------------------------------------
struct SimpleVertex
{
    XMFLOAT3 Pos;  //  顶点坐标
    XMFLOAT2 Tex; //  纹理坐标
};

struct CBNeverChanges
{
    XMMATRIX mView; // 用于视图变换的矩阵
};

struct CBChangeOnResize
{
    XMMATRIX mProjection; // 用于透视变换的矩阵
};

struct CBChangesEveryFrame
{
    XMMATRIX mWorld;
    XMFLOAT4 vMeshColor;
};


//--------------------------------------------------------------------------------------
// Global Variables
//--------------------------------------------------------------------------------------
HINSTANCE                           g_hInst = NULL;
HWND                                g_hWnd = NULL;
// ------------------------------------
//    D3D_DIRVER_TYPE:
//                  
//--------------------------------------
D3D_DRIVER_TYPE                     g_driverType = D3D_DRIVER_TYPE_NULL;
D3D_FEATURE_LEVEL                   g_featureLevel = D3D_FEATURE_LEVEL_11_0;
//----------------------------------------------------------------------------------------------------------
//   ID3D11Device  ID3D11DeviceContext  IDXGISwapChain
//   使用D3D时必须要的三个接口:
//          ID3D11Device: 设备接口: 用于创建所有(是所有)设备相关的资源,例如:深度模板缓存,纹理缓存
//                                                     着色器(VertexShader顶点着色器,HullShader外壳着色器,DomainShader域着色器,
//                                                      GeometryShader几何着色器,ComputeShader计算着色器,PixelShader像素着色器
//                                                     )等等
//          ID3D11DeviceContext: 设备上下文:用于D3D的渲染:
//                                                   1、将编译好了的HLSL文件通过**SetShader(VSSetShader()顶点着色器、HSSetShader()外壳着色器、
//                                                    DSSetShader()域着色器、GSSetShader()几何着色器、CSSetShader()计算着色器、PixelShader()像素着色器
//                                                    )绑定到固定流水管线上
//                                                  2、将CPU的变量与HLSL中的变量关联:**SetConstantBuffer(VSSetConstantBuffer、HSSetConstantBuffer、
//                                                     DSSetContantBuffer, GSSetConstantBuffer,CSSetConstantBuffer,PSSetConstantBuffer
//                                                    )。我看过一本书《并行程序设计原理》中我讲了,异构编程(CPU和GPU是异构的),而异构编程的实现有两种方式:
//                                                        A:共享存储(即共享全局变量)   B:消息传递(即将处理好了的数据通过消息机制传递到另一个处理器)。
//                                                        而明显HLSL和CPP中是通过共享变量来实现的,而这里是在CPP文件中使用UpdateSubresource()函数来更改CPU
//                                                         中的数据的,再在渲染时使用**SetConstantBuffer来改变固定流水管线中的数据,而HLSL中的变量是与固定流水管线
//                                                        一致的,因此达到了数据一致!
//                                                  3、同2中一样:纹理的采样是通过PSSetSamplers()函数来将Cpp文件中的变量和HLSL中的变量绑定的
//                                                  4、因为ID3D11DeviceContext:进行了渲染的所有方面,所以还有很多! 我只是说了CPP和GPU的数据交换。
//           IDXGISwapChain:   交换链。IDXGISwapChain应该封装了一块缓冲区,用来存放渲染的结果。也封装了一些成员函数,例如:Present()
//                                                    而最终将数据呈现出来是调用Present()函数。然而最重要的是SwapChain中数据的来源:IDXGISwapChain::GetBuffer()和
//                                                    ID3D11DeviceContext::OMSetRenderTargets(), ID3D11DeviceContext::CreateRenderTargetView()。使用GetBuffer()来得到SwapChain中的缓存,使用OMSetRenderTargets()
//                                                    将固定流水管线渲染的结果流转到SwapChain中的,其中CreateRenderTargetView()函数给SwapChain的缓存创建一个过渡桥梁。
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
ID3D11Device*                       g_pd3dDevice = NULL; // 用于创建D3D的所有资源
ID3D11DeviceContext*                g_pImmediateContext = NULL;// 渲染的方方面面
IDXGISwapChain*                     g_pSwapChain = NULL; // 交换链,用来容装数据和呈现到显示器

ID3D11RenderTargetView*             g_pRenderTargetView = NULL;  // SwapChain的过渡桥梁
ID3D11Texture2D*                    g_pDepthStencil = NULL;//本质就是一块纹理: 深度模板,用来进行被遮挡物的剔除
ID3D11DepthStencilView*             g_pDepthStencilView = NULL; //View:相当于句柄
ID3D11VertexShader*                 g_pVertexShader = NULL;//顶点着色器接口
ID3D11PixelShader*                  g_pPixelShader = NULL;//像素着色器接口
ID3D11InputLayout*                  g_pVertexLayout = NULL;//输入布局接口,控制绘制的格式
ID3D11Buffer*                       g_pVertexBuffer = NULL;//缓存
ID3D11Buffer*                       g_pIndexBuffer = NULL;
ID3D11Buffer*                       g_pCBNeverChanges = NULL;
ID3D11Buffer*                       g_pCBChangeOnResize = NULL;
ID3D11Buffer*                       g_pCBChangesEveryFrame = NULL;
ID3D11ShaderResourceView*           g_pTextureRV = NULL; // 着色器资源视图, 用来访问着色器中的资源,就像Win32中的句柄一样
ID3D11SamplerState*                 g_pSamplerLinear = NULL;  //纹理采样
XMMATRIX                            g_World;//将局部坐标转换到世界坐标中,一般在Vertex Shader中进行
XMMATRIX                            g_View;//视图变换,将世界坐标转换到视图坐标。一般在VertexShader中进行
XMMATRIX                            g_Projection;//投影变换,将3D转为2D,一般在VertexShader中进行
XMFLOAT4                            g_vMeshColor( 0.7f, 0.7f, 0.7f, 1.0f );


//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow );
HRESULT InitDevice();
void CleanupDevice();
LRESULT CALLBACK    WndProc( HWND, UINT, WPARAM, LPARAM );
void Render();


//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
    UNREFERENCED_PARAMETER( hPrevInstance );
    UNREFERENCED_PARAMETER( lpCmdLine );

    if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
        return 0;

    if( FAILED( InitDevice() ) )
    {
        CleanupDevice();
        return 0;
    }

    // Main message loop
    MSG msg = {0};
    while( WM_QUIT != msg.message )
    {
        if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
        else
        {
            Render();
        }
    }

    CleanupDevice();

    return ( int )msg.wParam;
}


//--------------------------------------------------------------------------------------
// Register class and create window
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
{
    // Register class
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof( WNDCLASSEX );
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon( hInstance, ( LPCTSTR )IDI_TUTORIAL1 );
    wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = L"TutorialWindowClass";
    wcex.hIconSm = LoadIcon( wcex.hInstance, ( LPCTSTR )IDI_TUTORIAL1 );
    if( !RegisterClassEx( &wcex ) )
        return E_FAIL;

    // Create window
    g_hInst = hInstance;
    RECT rc = { 0, 0, 640, 480 };
    AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
    g_hWnd = CreateWindow( L"TutorialWindowClass", L"Direct3D 11 Tutorial 7", WS_OVERLAPPEDWINDOW,
                           CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance,
                           NULL );
    if( !g_hWnd )
        return E_FAIL;

    ShowWindow( g_hWnd, nCmdShow );

    return S_OK;
}


//--------------------------------------------------------------------------------------
// Helper for compiling shaders with D3DX11
// 纹理的使用三个步骤:
//       1、编译HLSL得到编译的结果
//       2、调用ID3D11Device::CreateVertexShader(), CreateHullShader(),CreateDomainShader(),
//                                            CreateGeometryShader(),CreateComputeShader(),createPixelShader()创建着色器
//      3、将创建的着色器与固定流水管线绑定:调用ID3D11DeviceContext::VSSetShader(), PSSetShader()等
//--------------------------------------------------------------------------------------
HRESULT CompileShaderFromFile( WCHAR* szFileName, // HLSL文件名称
                                       LPCSTR szEntryPoint, // HLSL文件中的函数,就像Cpp文件中的WinMain()函数一样
            LPCSTR szShaderModel, // 第几代HLSL编译器
            ID3DBlob** ppBlobOut // 传出参数,即输出结果
            )
{
    HRESULT hr = S_OK;

    DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
    // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
    // Setting this flag improves the shader debugging experience, but still allows
    // the shaders to be optimized and to run exactly the way they will run in
    // the release configuration of this program.
    dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif

    ID3DBlob* pErrorBlob;
    hr = D3DX11CompileFromFile( szFileName, NULL, NULL, szEntryPoint, szShaderModel,
        dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL );
    if( FAILED(hr) )
    {
        if( pErrorBlob != NULL )
            OutputDebugStringA( (char*)pErrorBlob->GetBufferPointer() );
        if( pErrorBlob ) pErrorBlob->Release();
        return hr;
    }
    if( pErrorBlob ) pErrorBlob->Release();

    return S_OK;
}


//--------------------------------------------------------------------------------------
// Create Direct3D device and swap chain
//--------------------------------------------------------------------------------------
HRESULT InitDevice()
{
    HRESULT hr = S_OK;

    RECT rc;
    GetClientRect( g_hWnd, &rc );
    UINT width = rc.right - rc.left;
    UINT height = rc.bottom - rc.top;

    UINT createDeviceFlags = 0;
#ifdef _DEBUG
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

    D3D_DRIVER_TYPE driverTypes[] =
    {
        D3D_DRIVER_TYPE_HARDWARE,
        D3D_DRIVER_TYPE_WARP,
        D3D_DRIVER_TYPE_REFERENCE,
    };
    UINT numDriverTypes = ARRAYSIZE( driverTypes );

    D3D_FEATURE_LEVEL featureLevels[] =
    {
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
    };
    UINT numFeatureLevels = ARRAYSIZE( featureLevels );

    DXGI_SWAP_CHAIN_DESC sd;
    ZeroMemory( &sd, sizeof( sd ) );
    sd.BufferCount = 1 * 2;
    sd.BufferDesc.Width = width;
    sd.BufferDesc.Height = height;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = g_hWnd;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = TRUE;

    for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
    {
        g_driverType = driverTypes[driverTypeIndex];
  //----------------------------------------------------------
  //   一口气将D3D中的核心部分都创建了:
  //       ID3D11Device
  //      ID3D11DeviceContext
  //      IDXGISwapChain
  //----------------------------------------------------------
        hr = D3D11CreateDeviceAndSwapChain( NULL, 
                                             g_driverType,
               NULL,
               createDeviceFlags,
               featureLevels,
               numFeatureLevels,
                                                     D3D11_SDK_VERSION,
              &sd,
              &g_pSwapChain,         // 传出SwapChain
              &g_pd3dDevice,         // 传出Device
              &g_featureLevel,
              &g_pImmediateContext // 传出DeviceContext
              );
        if( SUCCEEDED( hr ) )
            break;
    }
    if( FAILED( hr ) )
        return hr;

    // Create a render target view
    ID3D11Texture2D* pBackBuffer = NULL;
 //--------------------------------------------------------------
 //   获取SwapChain的交换链:
 //            以便将SwapChain中的缓存与固定流水管线的最终结果绑定
 //-------------------------------------------------------------
    hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer );
    if( FAILED( hr ) )
        return hr;
 //----------------------------------------------------------------------------
 //  注意:还只是创建,并没有绑定到固定流水管线上,绑定在下面
 //  A:创建一个渲染目标视图,B:同时实现将SwapChain中的缓存与g_pRenderTargetView绑定
 //----------------------------------------------------------------------------
    hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView );
    pBackBuffer->Release();
    if( FAILED( hr ) )
        return hr;

    // Create depth stencil texture
    D3D11_TEXTURE2D_DESC descDepth;
    ZeroMemory( &descDepth, sizeof(descDepth) );
    descDepth.Width = width;
    descDepth.Height = height;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    descDepth.SampleDesc.Count = 1;
    descDepth.SampleDesc.Quality = 0;
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;
    hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil );
    if( FAILED( hr ) )
        return hr;
 
    // Create the depth stencil view
    D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
    ZeroMemory( &descDSV, sizeof(descDSV) );
    descDSV.Format = descDepth.Format;
    descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    descDSV.Texture2D.MipSlice = 0;
 // 创建深度模板缓存,以便深度剔除
    hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView );
    if( FAILED( hr ) )
        return hr;
 //-------------------------------------------------------------------
 // 将深度模板和渲染目标视图绑定到固定流水管线上
 // 从而是实现ID3D11DeviceContext和IDXGISwapChain绑定
 //   使得数据从固定流水管线流到交换链中。
 //:这是数据流向交换链的核心!!
 //----------------------------------------------------------------
    g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView );

    // Setup the viewport
    D3D11_VIEWPORT vp;
    vp.Width = (FLOAT)width;
    vp.Height = (FLOAT)height;
 vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0;
    vp.TopLeftY = 0;
    g_pImmediateContext->RSSetViewports( 1, &vp ); // 设置视口的大小

    // Compile the vertex shader
    ID3DBlob* pVSBlob = NULL;
    hr = CompileShaderFromFile( L"Tutorial07.fx", "VS", "vs_4_0", &pVSBlob ); // 编译顶点着色器
    if( FAILED( hr ) )
    {
        MessageBox( NULL,
                    L"The FX file cannot be compiled.  Please run this executable from the directory that contains the FX file.", L"Error", MB_OK );
        return hr;
    }

    // Create the vertex shader
    //---------------------------------------------------------
 //   创建顶点着色器(当然一切皆由ID3D11Device创建)
 // --------------------------------------------------------
 hr = g_pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader );
    if( FAILED( hr ) )
    {   
        pVSBlob->Release();
        return hr;
    }

    // Define the input layout
    D3D11_INPUT_ELEMENT_DESC layout[] =
    {
  //--------------------------------------
  //  因为CPU和GPU是通过消息传递来实现异构编程的,
  //  所以cpp和hlsl中的数据流格式要一致
  //--------------------------------------
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    };
    UINT numElements = ARRAYSIZE( layout );

    // Create the input layout
 // 创建输入布局
    hr = g_pd3dDevice->CreateInputLayout( layout,
                                             numElements,
               pVSBlob->GetBufferPointer(),
                                                   pVSBlob->GetBufferSize(),
               &g_pVertexLayout
               );
    pVSBlob->Release();
    if( FAILED( hr ) )
        return hr;

    // Set the input layout
 // 将输入布局绑定到固定流水管线上
    g_pImmediateContext->IASetInputLayout( g_pVertexLayout );

    // Compile the pixel shader
    ID3DBlob* pPSBlob = NULL;
 // 编译像素着色器
    hr = CompileShaderFromFile( L"Tutorial07.fx", "PS", "ps_4_0", &pPSBlob );
    if( FAILED( hr ) )
    {
        MessageBox( NULL,
                    L"The FX file cannot be compiled.  Please run this executable from the directory that contains the FX file.", L"Error", MB_OK );
        return hr;
    }

    // Create the pixel shader
 // 创建像素着色器,一切皆由ID3D11Device创建
    hr = g_pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(),
                                             pPSBlob->GetBufferSize(),
               NULL,
               &g_pPixelShader
               );
    pPSBlob->Release();
    if( FAILED( hr ) )
        return hr;

    // Create vertex buffer
    SimpleVertex vertices[] =
    {// 创建绘制图形的所有顶点,也可以从3DxMax中导入模型
        { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
    };

    D3D11_BUFFER_DESC bd;
    ZeroMemory( &bd, sizeof(bd) );
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof( SimpleVertex ) * 24;
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // 说明缓冲区的作用
    bd.CPUAccessFlags = 0;
    D3D11_SUBRESOURCE_DATA InitData;
    ZeroMemory( &InitData, sizeof(InitData) );
    InitData.pSysMem = vertices;
    hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer );
    if( FAILED( hr ) )
        return hr;

    // Set vertex buffer
    UINT stride = sizeof( SimpleVertex );
    UINT offset = 0;
 // 设置输入的缓存数据
    g_pImmediateContext->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &stride, &offset );

    // Create index buffer
    // Create vertex buffer
    WORD indices[] =
    {// 顶点的索引,D3D这样设计可以是减少内存的使用,聪明吧!
        3,1,0,
        2,1,3,

        6,4,5,
        7,4,6,

        11,9,8,
        10,9,11,

        14,12,13,
        15,12,14,

        19,17,16,
        18,17,19,

        22,20,21,
        23,20,22
    };

    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof( WORD ) * 36;
    bd.BindFlags = D3D11_BIND_INDEX_BUFFER; // 缓存的作用
    bd.CPUAccessFlags = 0;
    InitData.pSysMem = indices;
    hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pIndexBuffer );
    if( FAILED( hr ) )
        return hr;

    // Set index buffer
 //  设置顶点的索引
    g_pImmediateContext->IASetIndexBuffer( g_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0 );

    // Set primitive topology
 // 设置固定管线中的输入布局,可以确定顶点着色器中输入的是什么了!
    g_pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

    // Create the constant buffers
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof(CBNeverChanges);  // 其实:有的时候结构体不仅可以创建变量,还可以用来对一块内存进行描述
    bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    bd.CPUAccessFlags = 0;
    hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pCBNeverChanges );
    if( FAILED( hr ) )
        return hr;
   
    bd.ByteWidth = sizeof(CBChangeOnResize);
    hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pCBChangeOnResize );
    if( FAILED( hr ) )
        return hr;
   
    bd.ByteWidth = sizeof(CBChangesEveryFrame);
    hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pCBChangesEveryFrame );
    if( FAILED( hr ) )
        return hr;

    // Load the Texture
 // 导入纹理,并给纹理创建一个视图(句柄)
 // 其实我也不太理解,好像内存中的数据必须创建一个视图句柄,才可以在D3D中使用,并于HLSL中的纹理变量绑定
    hr = D3DX11CreateShaderResourceViewFromFile( g_pd3dDevice,
                                                         L"seafloor.dds",
                  NULL,
                  NULL,
                  &g_pTextureRV,
                  NULL
                  );
    if( FAILED( hr ) )
        return hr;

    // Create the sample state
 // 纹理采样方式
    D3D11_SAMPLER_DESC sampDesc;
    ZeroMemory( &sampDesc, sizeof(sampDesc) );
    sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; // 过滤
    sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;   //U的采样 超过范围就重复
    sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; // 比较函数,最终该像素能否通过
    sampDesc.MinLOD = 0;
    sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
 // ID3D11Device: 只是创建资源,最后还要绑定到ID3D11DeviceContext才行
    hr = g_pd3dDevice->CreateSamplerState( &sampDesc, &g_pSamplerLinear );
    if( FAILED( hr ) )
        return hr;

    // Initialize the world matrices
 //  1.0   0   0   0
 //  0    1.0  0   0
 //  0    0    1.0  0
 //  0    0    0    1.0
    g_World = XMMatrixIdentity(); // 单位矩阵, 设置世界变换

    // Initialize the view matrix
    XMVECTOR Eye = XMVectorSet( 0.0f, 3.0f, -6.0f, 0.0f );
    XMVECTOR At = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
    XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
    g_View = XMMatrixLookAtLH( Eye, At, Up ); // 设置视图投影矩阵

    CBNeverChanges cbNeverChanges;
    cbNeverChanges.mView = XMMatrixTranspose( g_View );
 // 修改g_pCBNeverChanges变量, 而g_pCBNeverChanges与hlsl中的变量对应
    g_pImmediateContext->UpdateSubresource( g_pCBNeverChanges, 0, NULL, &cbNeverChanges, 0, 0 );

    // Initialize the projection matrix
 // 投影矩阵  
    g_Projection = XMMatrixPerspectiveFovLH( XM_PIDIV4, width / (FLOAT)height, 0.01f, 100.0f );
   
    CBChangeOnResize cbChangesOnResize;
    cbChangesOnResize.mProjection = XMMatrixTranspose( g_Projection );
 //g_pCBChangesOnResize与hlsl中的变量对应
    g_pImmediateContext->UpdateSubresource( g_pCBChangeOnResize, 0, NULL, &cbChangesOnResize, 0, 0 );

    return S_OK;
}


//--------------------------------------------------------------------------------------
// Clean up the objects we've created
//--------------------------------------------------------------------------------------
void CleanupDevice()
{
 //释放内存
    if( g_pImmediateContext ) g_pImmediateContext->ClearState();

    if( g_pSamplerLinear ) g_pSamplerLinear->Release();
    if( g_pTextureRV ) g_pTextureRV->Release();
    if( g_pCBNeverChanges ) g_pCBNeverChanges->Release();
    if( g_pCBChangeOnResize ) g_pCBChangeOnResize->Release();
    if( g_pCBChangesEveryFrame ) g_pCBChangesEveryFrame->Release();
    if( g_pVertexBuffer ) g_pVertexBuffer->Release();
    if( g_pIndexBuffer ) g_pIndexBuffer->Release();
    if( g_pVertexLayout ) g_pVertexLayout->Release();
    if( g_pVertexShader ) g_pVertexShader->Release();
    if( g_pPixelShader ) g_pPixelShader->Release();
    if( g_pDepthStencil ) g_pDepthStencil->Release();
    if( g_pDepthStencilView ) g_pDepthStencilView->Release();
    if( g_pRenderTargetView ) g_pRenderTargetView->Release();
    if( g_pSwapChain ) g_pSwapChain->Release();
    if( g_pImmediateContext ) g_pImmediateContext->Release();
    if( g_pd3dDevice ) g_pd3dDevice->Release();
}


//--------------------------------------------------------------------------------------
// Called every time the application receives a message
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
    PAINTSTRUCT ps;
    HDC hdc;

    switch( message )
    {
        case WM_PAINT:
            hdc = BeginPaint( hWnd, &ps );
            EndPaint( hWnd, &ps );
            break;

        case WM_DESTROY:
            PostQuitMessage( 0 );
            break;

        default:
            return DefWindowProc( hWnd, message, wParam, lParam );
    }

    return 0;
}


//--------------------------------------------------------------------------------------
// Render a frame
//--------------------------------------------------------------------------------------
void Render()
{
 //渲染
    // Update our time
    static float t = 0.0f;
    if( g_driverType == D3D_DRIVER_TYPE_REFERENCE )
    {
        t += ( float )XM_PI * 0.0125f;
    }
    else
    {
        static DWORD dwTimeStart = 0;
        DWORD dwTimeCur = GetTickCount();
        if( dwTimeStart == 0 )
            dwTimeStart = dwTimeCur;
        t = ( dwTimeCur - dwTimeStart ) / 1000.0f;
    }

    // Rotate cube around the origin
    g_World = XMMatrixRotationY( t ); // 不停的设置世界变化,从而得到旋转

    // Modify the color
    g_vMeshColor.x = ( sinf( t * 1.0f ) + 1.0f ) * 0.5f;
    g_vMeshColor.y = ( cosf( t * 3.0f ) + 1.0f ) * 0.5f;
    g_vMeshColor.z = ( sinf( t * 5.0f ) + 1.0f ) * 0.5f;

    //
    // Clear the back buffer
    //
    float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; // red, green, blue, alpha
 //清空渲染目标
    g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, ClearColor );

    //
    // Clear the depth buffer to 1.0 (max depth)
    //
 // 重新设置深度模板缓存
    g_pImmediateContext->ClearDepthStencilView( g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 );

    //
    // Update variables that change once per frame
    //
    CBChangesEveryFrame cb;
    cb.mWorld = XMMatrixTranspose( g_World );
    cb.vMeshColor = g_vMeshColor;
 // 修改g_pCBChangesVeveryFrame
    g_pImmediateContext->UpdateSubresource( g_pCBChangesEveryFrame, 0, NULL, &cb, 0, 0 );

    //
    // Render the cube
    //
    g_pImmediateContext->VSSetShader( g_pVertexShader, NULL, 0 );
 //-------------------------------------------------------
 //   GPU和CPU是通过发送消息来进行异构编程的
 //    从而然数据从CPU流向GPU
 //    CPU和GPU的数据交换就是ConstantBuffer
 //   
 // 因为我看过《并行程序设计原理》,我也学过《设计模式》所以我从高层看待问题:
 //  我将处理器(CPU,GPU)抽象(提取核心本质,而忽略细节),得出结论:处理器由两部份组成:
 //   A:运算的部分    B:存储的部分
 //  所以VSSetConstantBuffers()设置了GPU的存储部分
 //-------------------------------------------------------
    g_pImmediateContext->VSSetConstantBuffers( 0, 1, &g_pCBNeverChanges );
    g_pImmediateContext->VSSetConstantBuffers( 1, 1, &g_pCBChangeOnResize );
    g_pImmediateContext->VSSetConstantBuffers( 2, 1, &g_pCBChangesEveryFrame );
 //重新设置GPU中的像素着色器
    g_pImmediateContext->PSSetShader( g_pPixelShader, NULL, 0 );
    //
 // GPU和CPU是通过发送消息来进行异构编程的
 //  A: Constant Buffer
 //  B: ShaderResource   <======>  GPU: HLSL中有Texture2D
 //  C: SamplerState
 g_pImmediateContext->PSSetConstantBuffers( 2, 1, &g_pCBChangesEveryFrame );
    g_pImmediateContext->PSSetShaderResources( 0, 1, &g_pTextureRV ); // 将纹理从CPU流向GPU
    g_pImmediateContext->PSSetSamplers( 0, 1, &g_pSamplerLinear ); //设置GPU中的纹理过滤
 //
    g_pImmediateContext->DrawIndexed( 36, 0, 0 ); // 将数据流向RenderTargets

    //
    // Present our back buffer to our front buffer
    //
    g_pSwapChain->Present( 0, 0 ); //最终呈现效果
}

 

 

 

 

 

 

 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////HLSL////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//--------------------------------------------------------------------------------------
// File: Tutorial07.fx
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------

//---------------------------------------------------
//   VS2012和VS2013可以用来对HLSL进行调试
//   我调试过,感觉还行!!
//   我看网上说VS2012和VS2013对HLSL调试是进行的
//   逆向工程,就像反汇编一样!
//-------------------------------------------------

//-----------------------------------------------------------------------------------------------------------
//   在思维上将着色器应当看作一个功能模块,实现它对应的功能。 就像我们编程时编的一个函数一样,
//   将你的数据输入对应的参数,然后返回你想要的结果。只不过这里更为的抽象而已。
//   所谓固定渲染管道,就是一段输入,另一端输出。就像Linux下敲击CmdShell时有一个管道命令一样!
//   而固定管道中,每个部分有自己对应的功能:VertexShader实现顶点的变化MVP(模型视图投影)变换
//   HullShader设置曲面细分因子(当然也可以不在HullShader中设置,而使用固定的曲面细分因子)
//   DoMainShader  GeometryShader(我看的例子中讲的是粒子系统,模仿烟花的爆放) ComputeShader
//  PixelShader设置像素的操作,例如颜色、纹理采样等等。
//--------------------------------------------------------------------------------------

 

 

 

 


//--------------------------------------------------------------------------------------
// Constant Buffer Variables
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------
// Direct9将Texture2D和SamplerState是绑定在一起的
// Direct10和Direct11将Texture和SamplerState是分离的
//---------------------------------------------------------------
Texture2D txDiffuse : register( t0 );    //纹理
SamplerState samLinear : register( s0 ); //采样方式,它提供了纹理采样的函数Sample()

//-----------------------------------------------------------
//HLSL中声明缓存有两种方式:
//   cbuffer: 声明的变量经常与CPU打交道
//   tbuffer:声明的变量支持随机访问,通常用于纹理
//-----------------------------------------------------------
//-------------------------------------------------------------------------
// Constant Buffer:  同Cpp文件中使用VSSetContstantBuffer()
//         HullSetConstantBuffer()、DSSetConstantBuffer()
//        CSSetConstantBuffer()、GSSetConstantBuffer()
//       PSSetConstantBuffer()中的数据打交道
//
//   而Direct10中Cpp文件和HLSL中是通过GetVaribleByname()等函数来逆向将HLSL
//   中的变量与Cpp中的变量关联的!!
//------------------------------------------------------------------------
cbuffer cbNeverChanges : register( b0 )
{
    matrix View;
};

cbuffer cbChangeOnResize : register( b1 )//register(b1)是第二个,而调用void VSSetConstantBuffers(
                                                  //                                           [in]  UINT StartSlot,
                                                  //                                            [in]  UINT NumBuffers,
                                                  //                                            [in]  ID3D11Buffer *const *ppConstantBuffers
                                                  //                                            );
              //中的StartSlot就要与这个对应
{
    matrix Projection;
};

cbuffer cbChangesEveryFrame : register( b2 )
{
    matrix World;
    float4 vMeshColor;
};


//--------------------------------------------------------------------------------------
struct VS_INPUT   // 因为CPP和HLSL中是通过发送消息来进行CPU和GPU异构的异构编程
                     // 所有HLSL中的结构体变量要与Cpp文件中的结构体变量在格式上对应
{
    float4 Pos : POSITION; // POSITIOIN 变量的语言,位置
    float2 Tex : TEXCOORD0;//TEXCOORD0 变量的语言,纹理
};

struct PS_INPUT
{
    float4 Pos : SV_POSITION; // SP_POSITION:  系统语义
    float2 Tex : TEXCOORD0;
};


//--------------------------------------------------------------------------------------
// Vertex Shader
//--------------------------------------------------------------------------------------
PS_INPUT VS( VS_INPUT input )
{
    PS_INPUT output = (PS_INPUT)0;
 //--------------------
 //  实现世界变换
 //  实现视图变换
 //  实现透视变换
 // ---------------------
    output.Pos = mul( input.Pos, World );
    output.Pos = mul( output.Pos, View );
    output.Pos = mul( output.Pos, Projection );
    output.Tex = input.Tex;   // 纹理没有操作, 而纹理的操作一般在PixelShader
   
    return output;
}


//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 PS( PS_INPUT input) : SV_Target
{
    return txDiffuse.Sample( samLinear, input.Tex ) * vMeshColor; // 调用SampleState的函数,进行纹理采样
 //return float4(1.0f, 0.0f, 0.0f, 1.0f); // 整个模型就变为红色了
}

 

 

 

 

 

 

//////////////////////////////////////////////////////////////////////////////////////////附件几张调试HLSL的图片/////////////////////////////////////////////////////////////////


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值