Direct X 11:在屏幕上绘制简单的彩色矩形

时间:2019-07-05 12:05:42

标签: c++ winapi rendering directx-11

现在我知道这个问题已经被问了无数次了(相同的问题,但是代码不同),并且我知道这很难调试,但是这是一项作业,应该在1周后完成,而我为此已经苦苦挣扎了4天(这意味着我只有3天的时间,包括今天在内)最多只能在星期一或星期二早上提交,所以请帮助我:(。

我只想在屏幕上以直接x 11绘制一个简单的彩色正方形(我支持的功能级别是9_1)。现在我到目前为止所做的

1)检查每个函数返回的每个HRESULT。即使失败,该应用程序也会终止。 全部都通过了!!!

2)以调试模式创建设备和着色器。任何地方都没有错误!

你可以明白为什么我感到沮丧。我要在此处发布的代码可以直接复制和粘贴,并且可以正常运行(在Visual Studio 2017中编译,但这没什么大不了的。)

必须创建6个文件

1)DirectX.h
2)DirectX.cpp
3)Scene.h
4)Scene.cpp
5)VShader.hlsl
6)PShader.hlsl

现在是代码

DirectX.h

#ifndef DIRECTX_H
#define DIRECTX_H

#include "stdafx.h"
#include <d3d11.h>

class D3D11Device
{
 private:
 D3D11_TEXTURE2D_DESC depthStencilDesc;
 ID3D11Device* device;
 ID3D11DeviceContext* context;
 IDXGISwapChain* swapChain;

 private:
 ID3D11RenderTargetView* target;
 ID3D11DepthStencilView* buffer;
 ID3D11RasterizerState*  rState;

 private:
 int errors;
 D3D11Device(HWND, int, int);


 public:
 static D3D11Device* Create(HWND, int, int);
 void bindTargets();
 int resize(int, int);
 ID3D11Device* getDevice();
 ID3D11DeviceContext* getContext();
 void clear(float,float,float,float);
 void present();
 ~D3D11Device();
};

#endif DIRECTX_H

DirectX.cpp

 #include "stdafx.h"
    #include "DirectX.h"

    D3D11Device::D3D11Device(HWND window,int w,int h)
    {
     errors = 0;
     device = nullptr;
     context = nullptr;
     swapChain = nullptr;
     rState = nullptr;
     target = nullptr;
     buffer = nullptr;
     D3D_FEATURE_LEVEL level = {};

     D3D_FEATURE_LEVEL levels[] = {
           D3D_FEATURE_LEVEL_9_1,
           D3D_FEATURE_LEVEL_9_2,
           D3D_FEATURE_LEVEL_9_3,
           D3D_FEATURE_LEVEL_10_0,
           D3D_FEATURE_LEVEL_10_1,
           D3D_FEATURE_LEVEL_11_0,
           D3D_FEATURE_LEVEL_11_1
        };


     //CREATE DEVICE AND CONTEXT
     HRESULT hr = D3D11CreateDevice(nullptr,D3D_DRIVER_TYPE_HARDWARE,0,D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_DEBUG
                                   ,levels,ARRAYSIZE(levels),D3D11_SDK_VERSION
                                   ,&device,&level,&context);
     if (FAILED(hr))
     {
      MessageBox(NULL, L"Failed To Create Device And Context", L"Failed D3D Init", MB_OK);
      errors = 1;
      return;
     }






     //CREATE SWAP CHAIN
     DXGI_SWAP_CHAIN_DESC desc = {};

     desc.Windowed = TRUE;
     desc.OutputWindow = window;
     desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
     desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

     desc.BufferCount = 2;
     desc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
     desc.BufferDesc.Width = w;
     desc.BufferDesc.Height = h;
     desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

     desc.SampleDesc.Count=1;
     desc.SampleDesc.Quality = 0;


     IDXGIDevice* dxgidevice =nullptr;
     IDXGIAdapter* adapter=nullptr;
     IDXGIFactory* factory=nullptr;
     if (FAILED(device->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgidevice)))
     {
      MessageBox(NULL, L"Failed To Get DXGI Device", L"Failed D3D Init", MB_OK);
      errors = 1;
      return;
     }
     if (FAILED(dxgidevice->GetParent(__uuidof(IDXGIAdapter), (void**)&adapter)))
     {
      MessageBox(NULL, L"Failed To Get DXGI Adapter", L"Failed D3D Init", MB_OK);
      errors = 1;
      return;
     }
     if (FAILED(adapter->GetParent(__uuidof(IDXGIFactory), (void**)&factory)))
     {
      MessageBox(NULL, L"Failed To Get DXGI Factory", L"Failed D3D Init", MB_OK);
      errors = 1;
      return;
     }
     if (FAILED(factory->CreateSwapChain(device, &desc, &swapChain)))
     {
      MessageBox(NULL, L"Failed To Create Swap Chain", L"Failed Swap Chain", MB_OK);
      errors = 1;
      return;
     }
     dxgidevice->Release();
     adapter->Release();
     factory->Release();






     //CREATING RENDER TARGET AND DEPTH&STENCIL BUFFER
     ID3D11Texture2D* texture;

     if (FAILED(swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&texture)))
     {
      MessageBox(NULL, L"Failed To Aquire Back Buffer", L"Failed D3D Init", MB_OK);
      errors = 1;
      return;
     }
     if (FAILED(device->CreateRenderTargetView(texture, NULL, &target)))
     {
      MessageBox(NULL, L"Failed To Create Render Target", L"Failed D3D Init", MB_OK);
      errors = 1;
      return;
     }
     texture->Release();


     depthStencilDesc = {};

     depthStencilDesc.Width = w;
     depthStencilDesc.Height = h;
     depthStencilDesc.ArraySize = 1;
     depthStencilDesc.MipLevels = 1;

     depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
     depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
     depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;

     depthStencilDesc.SampleDesc.Count = 1;
     depthStencilDesc.SampleDesc.Quality = 0;
     depthStencilDesc.CPUAccessFlags = 0;
     depthStencilDesc.MiscFlags = 0;

     if (FAILED(device->CreateTexture2D(&depthStencilDesc, NULL, &texture)))
     {
      MessageBox(NULL, L"Failed To Create DepthStencil Texture", L"Failed D3D Init", MB_OK);
      errors = 1;
      return;
     }
     if (FAILED(device->CreateDepthStencilView(texture, 0, &buffer)))
     {
      MessageBox(NULL, L"Failed To Create DepthStencil Buffer", L"Failed D3D Init", MB_OK);
      errors = 1;
      return;
     }
     texture->Release();





     //SET RASTERIZER STATE
     D3D11_RASTERIZER_DESC rDesc = {};
     rDesc.CullMode = D3D11_CULL_NONE;
     rDesc.FillMode = D3D11_FILL_SOLID;
     rDesc.FrontCounterClockwise = true;
     rDesc.DepthClipEnable = true;
     if (FAILED(device->CreateRasterizerState(&rDesc, &rState)))
     {
      MessageBox(NULL, L"Failed To Create Rasterizer State", L"Failed Rasterizer State", MB_OK);
      errors = 1;
      return;
     }
     context->RSSetState(rState);





     //SET VIEW PORT
     D3D11_VIEWPORT viewPort = {};
     viewPort.TopLeftX=0;
     viewPort.TopLeftY=0;
     viewPort.Width =(float)w;
     viewPort.Height =(float)h;
     viewPort.MinDepth = 0.0f;
     viewPort.MaxDepth = 1.0f;
     context->RSSetViewports(1, &viewPort);
    }

    D3D11Device* D3D11Device::Create(HWND parent,int w,int h)
    {
     D3D11Device* directx = new D3D11Device(parent,w,h);
     if (directx->errors == 1)
     {
      delete directx;
      directx = nullptr;
     }
     return directx;
    }

    int D3D11Device::resize(int width,int height)
    {
     target->Release();
     buffer->Release();
     target = nullptr;
     buffer = nullptr;

     context->OMSetRenderTargets(0, nullptr, nullptr);
     context->Flush();
     if (FAILED(swapChain->ResizeBuffers(2, width, height, DXGI_FORMAT_UNKNOWN, 0)))
     {
      MessageBox(NULL, L"Failed To Resize Buffers", L"Failed Resize", MB_OK);
      return -1;
     }


     ID3D11Texture2D* texture=nullptr;

     if (FAILED(swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&texture)))
     {
      MessageBox(NULL, L"Failed To Aquire Back Buffer", L"Failed D3D Init", MB_OK);
      return -1;
     }
     if (FAILED(device->CreateRenderTargetView(texture, NULL, &target)))
     {
      MessageBox(NULL, L"Failed To Create Render Target", L"Failed D3D Init", MB_OK);
      return -1;
     }
     texture->Release();
     texture = nullptr;



     depthStencilDesc.Width = width;
     depthStencilDesc.Height = height;
     if (FAILED(device->CreateTexture2D(&depthStencilDesc, NULL, &texture)))
     {
      MessageBox(NULL, L"Failed To Create DepthStencil Texture", L"Failed D3D Init", MB_OK);
      return -1;
     }
     if (FAILED(device->CreateDepthStencilView(texture, 0, &buffer)))
     {
      MessageBox(NULL, L"Failed To Create DepthStencil Buffer", L"Failed D3D Init", MB_OK);
      return -1;
     }
     texture->Release();
     texture = nullptr;


     D3D11_VIEWPORT viewPort = {};
     viewPort.TopLeftX = 0;
     viewPort.TopLeftY = 0;
     viewPort.Width =(float)width;
     viewPort.Height =(float)height;
     viewPort.MinDepth = 0.0f;
     viewPort.MaxDepth = 1.0f;
     context->RSSetViewports(1, &viewPort);

     return 1;
    }

    ID3D11Device* D3D11Device::getDevice() { return device; }
    ID3D11DeviceContext* D3D11Device::getContext() { return context; }

    void D3D11Device::bindTargets() { context->OMSetRenderTargets(1, &target, buffer); }
    void D3D11Device::clear(float r, float g, float b, float a)
    {
     float color[4] = { r,g,b,a };
     context->ClearRenderTargetView(target, color);
 context->ClearDepthStencilView(buffer, D3D11_CLEAR_DEPTH |D3D11_CLEAR_STENCIL,0, 0);
    }
    void D3D11Device::present() { swapChain->Present(0,0); }

    D3D11Device::~D3D11Device()
    {
     if (rState != nullptr) { rState->Release(); }
     if (target != nullptr) { target->Release(); }
     if (buffer != nullptr) { buffer->Release(); }

     if (swapChain != nullptr)
     {
      swapChain->SetFullscreenState(FALSE,NULL);
      swapChain->Release();
     }
     if (device != nullptr) { device->Release(); }
     if (context != nullptr) { context->Release(); }
    }

Scene.h

#ifndef SCENE_H
#define SCENE_H

#include "stdafx.h"
#include "DirectX.h"
#include <atlstr.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>

class Scene;

class Window
{
 private:
 HWND window;
 Scene* scene;
 int errors;

 private:
 Window(HINSTANCE, int, int, int, int);
 static LRESULT CALLBACK winProc(HWND, UINT, WPARAM, LPARAM);

 public:
 static Window* Create(HINSTANCE, int, int, int, int);
 void display(int);
 Scene* getScene();
 ~Window();
};

struct ShaderInfo
{
 LPCWSTR vFile;
 LPCSTR  vEntry;
 LPCSTR  vVersion;

 LPCWSTR pFile;
 LPCSTR  pEntry;
 LPCSTR  pVersion;
 ID3DInclude* pIncludes;
};

class Include : public ID3DInclude
{
 private:
 ID3DBlob* blob;

 public:
 HRESULT _stdcall Open(D3D_INCLUDE_TYPE, LPCSTR, LPCVOID, LPCVOID*, UINT*);
 HRESULT _stdcall Close(LPCVOID);
};

class RasterShader
{
 private:
 int errors;
 ID3D11InputLayout* inputLayout;
 ID3D11VertexShader* vShader;
 ID3D11PixelShader*  pShader;

 private:
 RasterShader(ID3D11Device*,ShaderInfo*);
 HRESULT Compile(LPCWSTR,LPCSTR,LPCSTR,ID3DInclude*,ID3DBlob**);

 public:
 static RasterShader* Create(ID3D11Device*,ShaderInfo*);
 void render(ID3D11DeviceContext*);
 ~RasterShader();
};

class QuadGeometry
{
 private:
 int errors;
 ID3D11Buffer* vertexBuffer;
 ID3D11Buffer* colorBuffer;
 ID3D11Buffer* indexBuffer;

 private:
 QuadGeometry(ID3D11Device*);
 HRESULT createBuffer(ID3D11Device* device,UINT,D3D11_SUBRESOURCE_DATA*,int,ID3D11Buffer**);

 public:
 static QuadGeometry* Create(ID3D11Device*);
 void render(ID3D11DeviceContext*);
 ~QuadGeometry();
};

class Scene
{
 private:
 int errors;
 D3D11Device* directx;
 RasterShader* shader;
 QuadGeometry* geometry;

 private:
 Scene(HWND,int,int);

 public:
 static Scene* Create(HWND,int,int);
 void render();
 int resize(int, int);
 ~Scene();
};

#endif SCENE_H

Scene.cpp

#include "stdafx.h"
#include "Scene.h"

Window::Window(HINSTANCE app, int x, int y, int w, int h)
{
 errors = 0;

 WNDCLASSEX wClass = {};
 wClass.cbSize = sizeof(WNDCLASSEX);
 wClass.hInstance = app;
 wClass.lpszClassName = L"Window";
 wClass.lpfnWndProc = winProc;
 if (!RegisterClassEx(&wClass))
 {
  MessageBox(NULL, L"Failed To Register Window Class", L"Window Class", MB_OK);
  errors = 1;
  return;
 }

 window = CreateWindowEx(WS_EX_CLIENTEDGE, L"Window", L"Direct X", WS_OVERLAPPEDWINDOW
                        ,x, y, w, h
                        ,NULL, 0, app, this);
 if(!window)
 {
  MessageBox(NULL, L"Failed To Create Window", L"Window", MB_OK);
  errors = 1; 
 }
}

LRESULT Window::winProc(HWND parent, UINT msg, WPARAM high, LPARAM low)
{
 if (msg == WM_CREATE)
 {
  LPCREATESTRUCT create = (LPCREATESTRUCT)(low);
  Window* thisClass = (Window*)create->lpCreateParams;

  RECT rect = {};
  GetWindowRect(parent, &rect);
  thisClass->scene = Scene::Create(parent, rect.right - rect.left, rect.bottom - rect.top);
  if (thisClass->scene == nullptr) { return -1; }

  SetWindowLongPtr(parent, GWLP_USERDATA, (LONGLONG)thisClass);
  return 1;
 }
 else if (msg == WM_SIZE)
 {
  Window* window = (Window*)GetWindowLongPtr(parent, GWLP_USERDATA);
  int newWidth = (int)LOWORD(low);
  int newHeight = (int)HIWORD(low);
  return window->scene->resize(newWidth,newHeight);
 }
 else if (msg == WM_CLOSE)
 {
  DestroyWindow(parent);
  return 1;
 }
 else if (msg == WM_DESTROY)
 {
  PostQuitMessage(0);
  return 1;
 }
 return DefWindowProc(parent, msg, high, low);
}

Window* Window::Create(HINSTANCE app, int x, int y, int w, int h)
{
 Window* window = new Window(app, x, y, w, h);
 if (window->errors == 1)
 {
  delete window;
  window = nullptr;
 }
 return window;
}

void Window::display(int code) { ShowWindow(window, code); }
Scene* Window::getScene() { return scene; }
Window::~Window()
{
 if (scene != nullptr) { delete scene; }
 UnregisterClass(L"Window", GetModuleHandle(NULL));
}













HRESULT Include::Open
(
    D3D_INCLUDE_TYPE IncludeType,
    LPCSTR           pFileName,
    LPCVOID          pParentData,
    LPCVOID          *ppData,
    UINT             *pBytes
)
{
 CString D(pFileName);
 if (FAILED(D3DReadFileToBlob(D.GetBuffer(), &blob)))
 {
  CString fileName(pFileName);
  MessageBox(NULL, L"Failed To Load File", fileName.GetBuffer(), MB_OK);
  fileName.ReleaseBuffer();
  return D3D10_ERROR_FILE_NOT_FOUND;
 }
 D.ReleaseBuffer();

 (*ppData) = blob->GetBufferPointer();
 (*pBytes) = blob->GetBufferSize();

 return S_OK;
}

HRESULT Include::Close(LPCVOID data) 
{
 blob->Release();
 return S_OK; 
}


RasterShader::RasterShader(ID3D11Device* device,ShaderInfo* info)
{
 ID3DBlob* compiledCode=nullptr;
 inputLayout = nullptr;
 vShader = nullptr;
 pShader = nullptr;
 errors = 0;

 if (FAILED(Compile(info->vFile,info->vEntry,info->vVersion,nullptr,&compiledCode)))
 {
  errors = 1;
  return;
 }
 if (FAILED(device->CreateVertexShader(compiledCode->GetBufferPointer(), compiledCode->GetBufferSize(),nullptr, &vShader)))
 {
  compiledCode->Release();
  MessageBox(NULL, L"Failed To Create Vertex Shader", L"Failed Vertex Shader", MB_OK);
  errors = 1;
  return;
 }

 D3D11_INPUT_ELEMENT_DESC desc[] =
 {
   {"POSITION",0,DXGI_FORMAT_R32G32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0}
  ,{"COLOR",0,DXGI_FORMAT_R32G32B32_FLOAT,1,0,D3D11_INPUT_PER_VERTEX_DATA,0}
 };
 if (FAILED(device->CreateInputLayout(desc,2,compiledCode->GetBufferPointer(),compiledCode->GetBufferSize(),&inputLayout)))
 {
  compiledCode->Release();
  MessageBox(NULL, L"Failed To Create Input Layout", L"Failed Input Layout", MB_OK);
  errors = 1;
  return;
 }
 compiledCode->Release();
 compiledCode = nullptr;


 if (FAILED(Compile(info->pFile, info->pEntry, info->pVersion,info->pIncludes,&compiledCode)))
 {
  errors = 1;
  return;
 }
 if (FAILED(device->CreatePixelShader(compiledCode->GetBufferPointer(), compiledCode->GetBufferSize(), nullptr, &pShader)))
 {
  compiledCode->Release();
  MessageBox(NULL, L"Failed To Create Pixel Shader", L"Failed Pixel Shader", MB_OK);
  errors = 1;
  return;
 }
 compiledCode->Release();
 compiledCode = nullptr;
}

HRESULT RasterShader::Compile(LPCWSTR fileName,LPCSTR entry,LPCSTR version,ID3DInclude* include,ID3DBlob** code)
{
 ID3DBlob* errors=nullptr;
 HRESULT hr = D3DCompileFromFile(fileName,nullptr,include
                                ,entry,version
                                ,D3DCOMPILE_WARNINGS_ARE_ERRORS,0,code,&errors);
 if (FAILED(hr))
 {
  if (errors!=nullptr)
  {
   CString data((char*)errors->GetBufferPointer());
   MessageBox(NULL, data.GetBuffer(),fileName, MB_OK);

   data.ReleaseBuffer();
   errors->Release();
  }
 }
 return hr;
}

RasterShader * RasterShader::Create(ID3D11Device* device,ShaderInfo* info)
{
 RasterShader* shader = new RasterShader(device,info);
 if (shader->errors == 1)
 {
  delete shader;
  shader = nullptr;
 }
 return shader;
}

void RasterShader::render(ID3D11DeviceContext* context)
{
 context->IASetInputLayout(inputLayout);
 context->VSSetShader(vShader, nullptr, 0);
 context->PSSetShader(pShader, nullptr, 0);
}

RasterShader::~RasterShader()
{
 if (inputLayout != nullptr) { inputLayout->Release(); }
 if (vShader != nullptr) { vShader->Release(); }
 if (pShader != nullptr) { pShader->Release(); }
}













QuadGeometry::QuadGeometry(ID3D11Device* device)
{
 errors = 0;
 vertexBuffer = nullptr;
 colorBuffer = nullptr;
 indexBuffer = nullptr;
 D3D11_SUBRESOURCE_DATA Data = {};


 DirectX::XMFLOAT2 verts[]=
 {
   DirectX::XMFLOAT2(0.5f,0.5f)
  ,DirectX::XMFLOAT2(-0.5f,0.5f)
  ,DirectX::XMFLOAT2(-0.5f,-0.5f)
  ,DirectX::XMFLOAT2(0.5f,-0.5f)
 };
 Data.pSysMem = verts;
 Data.SysMemPitch = 0;
 Data.SysMemSlicePitch = 0;
 if(FAILED(createBuffer(device, D3D11_BIND_VERTEX_BUFFER,&Data,sizeof(DirectX::XMFLOAT2) * 4,&vertexBuffer)))
 {
  MessageBox(NULL, L"Failed To Create Vertex Buffer", L"Failed Vertex Buffer", MB_OK);
  errors = 1;
  return;
 }

 DirectX::XMFLOAT3 colors[] =
 {
   DirectX::XMFLOAT3(1,0,0)
  ,DirectX::XMFLOAT3(0,1,0)
  ,DirectX::XMFLOAT3(1,0,1)
  ,DirectX::XMFLOAT3(1,1,0)
 };
 Data.pSysMem = colors;
 Data.SysMemPitch = 0;
 Data.SysMemSlicePitch = 0;
 if (FAILED(createBuffer(device, D3D11_BIND_VERTEX_BUFFER,&Data, sizeof(DirectX::XMFLOAT3) * 4, &colorBuffer)))
 {
  MessageBox(NULL, L"Failed To Create Color Buffer", L"Failed Color Buffer", MB_OK);
  errors = 1;
  return;
 }

 UINT indices[]=
 {
   0,1,2
  ,0,2,3
 };
 Data.pSysMem = indices;
 Data.SysMemPitch = 0;
 Data.SysMemSlicePitch = 0;
 if (FAILED(createBuffer(device, D3D11_BIND_INDEX_BUFFER, &Data, sizeof(UINT) * 6, &indexBuffer)))
 {
  MessageBox(NULL, L"Failed To Create Index Buffer", L"Failed Index Buffer", MB_OK);
  errors = 1;
  return;
 }
}

HRESULT QuadGeometry::createBuffer(ID3D11Device* device,UINT bind,D3D11_SUBRESOURCE_DATA* data,int byteSize,ID3D11Buffer** buffer)
{
 D3D11_BUFFER_DESC desc = {};
 desc.BindFlags = bind;
 desc.ByteWidth = byteSize;
 desc.Usage = D3D11_USAGE_IMMUTABLE;
 desc.CPUAccessFlags = 0;
 desc.MiscFlags = 0;
 desc.StructureByteStride = 0;

 return device->CreateBuffer(&desc,data,buffer);
}

QuadGeometry * QuadGeometry::Create(ID3D11Device* device)
{
 QuadGeometry* geom = new QuadGeometry(device);
 if (geom->errors == 1)
 {
  delete geom;
  geom = nullptr;
 }
 return geom;
}

void QuadGeometry::render(ID3D11DeviceContext* context)
{
 UINT strides[] = { sizeof(DirectX::XMFLOAT2),sizeof(DirectX::XMFLOAT3)};
 UINT offsets[] = { 0,0 };
 ID3D11Buffer* buffers[] = {vertexBuffer,colorBuffer};

 context->IASetVertexBuffers(0, 2, buffers, strides, offsets);
 context->IASetIndexBuffer(indexBuffer,DXGI_FORMAT_R16_UINT, 0);
 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

 context->DrawIndexed(6, 0, 0);
}

QuadGeometry::~QuadGeometry()
{
 if (vertexBuffer != nullptr) { vertexBuffer->Release(); }
 if (colorBuffer != nullptr) { colorBuffer->Release(); }
 if (indexBuffer != nullptr) { indexBuffer->Release(); }
}











Scene::Scene(HWND window, int w, int h)
{
 errors = 0;
 directx = nullptr;
 shader = nullptr;
 geometry = nullptr;

 directx = D3D11Device::Create(window, w, h);
 if (directx == nullptr)
 {
  errors = 1;
  return;
 }

 ShaderInfo info = {};
 info.vFile = L"VShader.hlsl";
 info.vEntry = "VShader";
 info.vVersion = "vs_4_0_level_9_1";
 info.pFile = L"PShader.hlsl";
 info.pEntry = "PShader";
 info.pVersion = "ps_4_0_level_9_1";
 info.pIncludes = (ID3DInclude*)new Include();
 shader = RasterShader::Create(directx->getDevice(), &info);
 if (shader == nullptr)
 {
  errors = 1;
  return;
 }

 geometry = QuadGeometry::Create(directx->getDevice());
 if (geometry == nullptr){errors = 1;}
}

Scene * Scene::Create(HWND window, int w, int h)
{
 Scene* scene = new Scene(window, w, h);
 if (scene->errors == 1)
 {
  delete scene;
  scene = nullptr;
 }
 return scene;
}

void Scene::render()
{
 directx->clear(0, 0, 0.5f, 0);

 directx->bindTargets();
 shader->render(directx->getContext());
 geometry->render(directx->getContext());

 directx->present();
}

int Scene::resize(int w, int h) { return directx->resize(w, h); }

Scene::~Scene()
{
 if (shader != nullptr) { delete shader; }
 if (geometry != nullptr) { delete geometry; }
 if (directx != nullptr) { delete directx; }
}

VShader.hlsl

struct VIn
{
 float2 position: POSITION;
 float3 color   : COLOR;
};

struct VOut
{
 float4 pos : SV_POSITION;
 float3 clr :     COLOR;
};

VOut VShader(in VIn input)
{
 VOut output;

 output.pos = float4(input.position.x,input.position.y,0,1.0f);
 output.clr = input.color;

 return output;
}

PShader.hlsl

# include "VShader.hlsl"

float4 PShader(in VOut input) : SV_TARGET
{
  return float4(1,0,1,0);
}

就像我说的那样,此代码可以复制并粘贴,没有任何问题。库文件要求是d3d11.lib和d3dcompiler.lib

我不知道问题出在哪里或出了什么问题,但希望如果有人设法找到问题,我希望这段代码可以帮助某人开始使用x 11:)。

我得到的是一个蓝屏,它可以在全屏和窗口显示之间切换(预期输出的一半)。但是四边形不存在。

请帮助某人。谢谢。

2 个答案:

答案 0 :(得分:0)

我不知道为什么它不起作用,但是我在这里看到了一些问题。

  1. 在PS中,您将返回alpha = 0的颜色。显然,您没有设置alpha混合,并且默认的混合状态禁用了alpha混合,但是出于测试目的,仍然尝试输出alpha = 1.0。

  2. 您正在使用32位索引创建索引缓冲区,UINT是32位整数。但是,您告诉D3D索引缓冲区包含16位索引DXGI_FORMAT_R16_UINT

结合有关代码的一般说明。

您正在运行时编译着色器源。别。脱机编译它们以获得最低的功能级别(9.1?),然后在运行时从DXBC文件中加载着色器。编译着色器会在代码中造成很多不必要的复杂性,并且还需要时间。如果您使用的是VC ++,请在项目中包含hlsl文件,右键单击“属性”,在“目标文件”中的“ HLSL编译器/常规”设置着色器类型和模型,在“ HLSL编译器/输出文件”中设置$(OutDir)%(Filename).cso名称”。然后在运行时,从磁盘读取这两个.cso文件,然后调用ID3D11Device::CreateVertexShader / CreatePixelShader

您要为位置和颜色创建2个顶点缓冲区。一个就足够了。人们在更新某些顶点属性而不是其他顶点属性时通常会使用多个顶点缓冲区。当一切都像您一样都是不可变的时,使用单个缓冲区会更简单,更高效。定义一个包含两个字段的结构,并相应地更改输入布局。

您正在使用D3D11_CREATE_DEVICE_DEBUG创建设备,但显然您没有读取调试输出。使用调试器启动您的应用,然后在Visual Studio中读取输出窗口。有了该标志,运行时通常只会打印您的资源/着色器/状态/所涉及的其他问题。

答案 1 :(得分:0)

这完全不是一种解决方案,就像告诉某人打开或关闭计算机以解决对我有用的问题。

我刚刚创建了一个新项目,并将所有文件粘贴在那里,现在一切正常。

是的...无法解释。

谢谢大家结案。