This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

DX11 Drawing a triangle

By: a guest on Jan 2nd, 2013  |  syntax: C++  |  size: 10.88 KB  |  views: 59  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #pragma comment(lib, "d3d10.lib")
  2. #pragma comment(lib, "d3dx11.lib")
  3. #pragma comment(lib,"d3d11.lib")
  4. #pragma comment(lib, "DXErr.lib")
  5. //Include necessary Headers//
  6. #include <windows.h>
  7. #include<DxErr.h>
  8. #include <d3dx11.h>
  9. #include <D3D11.h>
  10. #include <D3D10.h>
  11. #include <D3DX10math.h>
  12. #include <xnamath.h>
  13. #include <string>
  14.  
  15. ///////// INIT D3D
  16. ID3D11Device* d3d11Device;
  17. IDXGISwapChain* SwapChain;
  18. ID3D11DeviceContext* d3d11DevCon;
  19. ID3D11RenderTargetView* renderTargetView;
  20.  
  21.  
  22. ID3D11Buffer* triangleVertBuffer;
  23. ID3D11VertexShader* VS;
  24. ID3D11PixelShader* PS;
  25. ID3D10Blob* VS_Buffer;
  26. ID3D10Blob* PS_Buffer;
  27. ID3D11InputLayout* vertLayout;
  28.  
  29.  
  30.  
  31.  
  32. float red = 0.0f;
  33. float green = 0.0f;
  34. float blue = 0.0f;
  35. int colormodr = 1;
  36. int colormodg = 1;
  37. int colormodb = 1;
  38.  
  39.  
  40. //Define variables/constants//
  41.  
  42. //LP - Pointer
  43. // C - Constant
  44. // T - TCHAR
  45. // STR - String
  46. // WndClassName is the name for the window class
  47. LPCTSTR WndClassName = "firstwindow";   //Define our window class name
  48. HWND hwnd = NULL;       //Sets our windows handle to NULL
  49. HRESULT hr;
  50.  
  51. const int Width  = 800; //window width
  52. const int Height = 600; //window height
  53.  
  54. //
  55. bool InitializeDirect3d11App(HINSTANCE hInstance);
  56. //void ReleaseObjects();
  57. bool InitScene();
  58. void UpdateScene();
  59. void DrawScene();
  60. void CleanUp();
  61.  
  62. //Functions//
  63. bool InitializeWindow(HINSTANCE hInstance,      //Initialize our window
  64.                  int ShowWnd,
  65.                  int width, int height,
  66.                  bool windowed);
  67. int messageloop();      //Main part of the program
  68. LRESULT CALLBACK WndProc(HWND hWnd,     //Windows callback procedure
  69.                  UINT msg,
  70.                  WPARAM wParam,
  71.                  LPARAM lParam);
  72.  
  73.  
  74. struct Vertex //Overloader vertex Structure
  75. {
  76.                 Vertex(){}
  77.                 Vertex(float x, float y, float z)
  78.                         : pos(x,y,z){}
  79.                 XMFLOAT3 pos;
  80. };
  81.  
  82. D3D11_INPUT_ELEMENT_DESC layout[] =
  83. {
  84.         {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,0, D3D11_INPUT_PER_VERTEX_DATA, 0},
  85. };
  86.  
  87. UINT numElements = ARRAYSIZE(layout);
  88.  
  89.  
  90.  
  91.  
  92.  
  93. int WINAPI WinMain(HINSTANCE hInstance, //Main windows function
  94.                    HINSTANCE hPrevInstance,
  95.                    LPSTR lpCmdLine,
  96.                    int nShowCmd)
  97. {
  98.         //Initialize Window//
  99.         if(!InitializeWindow(hInstance, nShowCmd, Width, Height, true))
  100.         {
  101.                 //If initialization failed, display an error message
  102.                 MessageBox(0, "Window Initialization - Failed",
  103.                                 "Error", MB_OK);
  104.                 return 0;
  105.         }
  106.  
  107.         ////D3D
  108.         if(!InitializeDirect3d11App(hInstance))
  109.         {
  110.                 MessageBox(0, "Direct3D Intialization - Failed",
  111.                         "Error", MB_OK);
  112.                 return 0;
  113.         }
  114.  
  115.         if(!InitScene())
  116.         {
  117.                 MessageBox(0, "Scene Initialization - Failed",
  118.                         "Error", MB_OK);
  119.                 return 0;
  120.         }
  121.  
  122.         messageloop();  //Jump into the heart of our program
  123.  
  124.         CleanUp();
  125.  
  126.         return 0;
  127. }
  128.  
  129. bool InitializeWindow(HINSTANCE hInstance,      //Initialize our window
  130.                                                  int ShowWnd,
  131.                                                  int width, int height,
  132.                                                  bool windowed)
  133. {
  134.         //Start creating the window//
  135.  
  136.         WNDCLASSEX wc;  //Create a new extended windows class
  137.  
  138.         wc.cbSize = sizeof(WNDCLASSEX); //Size of our windows class
  139.         wc.style = CS_HREDRAW | CS_VREDRAW;     //class styles
  140.         wc.lpfnWndProc = WndProc;       //Default windows procedure function
  141.         wc.cbClsExtra = NULL;   //Extra bytes after our wc structure
  142.         wc.cbWndExtra = NULL;   //Extra bytes after our windows instance
  143.         wc.hInstance = hInstance;       //Instance to current application
  144.         wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); //Title bar Icon
  145.         wc.hCursor = LoadCursor(NULL, IDC_ARROW);       //Default mouse Icon
  146.         wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 2);  //Window bg color
  147.         wc.lpszMenuName = NULL; //Name of the menu attached to our window
  148.         wc.lpszClassName = WndClassName;        //Name of our windows class
  149.         wc.hIconSm = LoadIcon(NULL, IDI_WINLOGO); //Icon in your taskbar
  150.  
  151.         if (!RegisterClassEx(&wc))      //Register our windows class
  152.         {
  153.                 //if registration failed, display error
  154.                 MessageBox(NULL, "Error registering class",    
  155.                         "Error", MB_OK | MB_ICONERROR);
  156.                 return 1;
  157.         }
  158.  
  159.         hwnd = CreateWindowEx(  //Create our Extended Window
  160.                 NULL,   //Extended style
  161.                 WndClassName,   //Name of our windows class
  162.                 "First window", //Name in the title bar of our window
  163.                 WS_OVERLAPPEDWINDOW,    //style of our window
  164.                 CW_USEDEFAULT, CW_USEDEFAULT,   //Top left corner of window
  165.                 width,  //Width of our window
  166.                 height, //Height of our window
  167.                 NULL,   //Handle to parent window
  168.                 NULL,   //Handle to a Menu
  169.                 hInstance,      //Specifies instance of current program
  170.                 NULL    //used for an MDI client window
  171.                 );
  172.  
  173.         if (!hwnd)      //Make sure our window has been created
  174.         {
  175.         //If not, display error
  176.                 MessageBox(NULL, "Error creating window",
  177.                         "Error", MB_OK | MB_ICONERROR);
  178.                 return 1;
  179.         }
  180.  
  181.         ShowWindow(hwnd, ShowWnd);      //Shows our window
  182.         UpdateWindow(hwnd);     //Its good to update our window
  183.  
  184.         return true;    //if there were no errors, return true
  185. }
  186.  
  187. void CleanUp()
  188. {
  189.         SwapChain->Release();
  190.         d3d11Device->Release();
  191.         d3d11DevCon->Release();
  192.         renderTargetView->Release();
  193.         triangleVertBuffer->Release();
  194.         VS->Release();
  195.         PS->Release();
  196.         VS_Buffer->Release();
  197.         PS_Buffer->Release();
  198.         vertLayout->Release();
  199. }
  200.  
  201.  
  202. bool InitializeDirect3d11App(HINSTANCE hInstance)
  203. {
  204.         //HRESULT hr;
  205.  
  206.         //Describe our Buffer
  207.         DXGI_MODE_DESC bufferDesc;
  208.  
  209.         ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC));
  210.  
  211.         bufferDesc.Width = Width;
  212.         bufferDesc.Height = Height;
  213.         bufferDesc.RefreshRate.Numerator = 60;
  214.         bufferDesc.RefreshRate.Denominator = 1;
  215.         bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  216.         bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  217.         bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  218.        
  219.         //Describe our SwapChain
  220.         DXGI_SWAP_CHAIN_DESC swapChainDesc;
  221.                
  222.         ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
  223.  
  224.         swapChainDesc.BufferDesc = bufferDesc;
  225.         swapChainDesc.SampleDesc.Count = 1;
  226.         swapChainDesc.SampleDesc.Quality = 0;
  227.         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  228.         swapChainDesc.BufferCount = 1;
  229.         swapChainDesc.OutputWindow = hwnd;
  230.         swapChainDesc.Windowed = TRUE;
  231.         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  232.  
  233.  
  234.         //Create our SwapChain
  235.         hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL,
  236.                 D3D11_SDK_VERSION, &swapChainDesc, &SwapChain, &d3d11Device, NULL, &d3d11DevCon);
  237.         if(FAILED(hr))
  238.         {
  239.                 MessageBox(NULL, DXGetErrorDescription(hr),
  240.                         TEXT(" D3D11CreateDeviceAndSwapChain"), MB_OK);
  241.                 return 0;
  242.         }
  243.         //Create our BackBuffer
  244.         ID3D11Texture2D* BackBuffer;
  245.         hr = SwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), (void**)&BackBuffer );
  246.         if(FAILED(hr))
  247.         {
  248.                 MessageBox(NULL, DXGetErrorDescription(hr),
  249.                         TEXT("SwapChain->GetBuffer"), MB_OK);
  250.                 return 0;
  251.         }
  252.         //Create our Render Target
  253.         hr = d3d11Device->CreateRenderTargetView( BackBuffer, NULL, &renderTargetView );
  254.         BackBuffer->Release();
  255.         if(FAILED(hr))
  256.         {
  257.                 MessageBox(NULL, DXGetErrorDescription(hr),
  258.                         TEXT("d3d11Device->CreateRenderTargetView"), MB_OK);
  259.                 return 0;
  260.         }
  261.         //Set our Render Target
  262.         d3d11DevCon->OMSetRenderTargets( 1, &renderTargetView, NULL );
  263.  
  264.         return true;
  265. }
  266.  
  267. bool InitScene()
  268. {
  269.        
  270.         hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "VS", "vs_4_0", 0, 0, 0, &VS_Buffer, 0, 0);
  271.         hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "PS", "ps_4_0", 0, 0, 0, &PS_Buffer, 0, 0);
  272.  
  273.         hr = d3d11Device->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS);
  274.         hr = d3d11Device->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS);
  275.  
  276.         d3d11DevCon->VSSetShader(VS,0,0);
  277.         d3d11DevCon->PSSetShader(PS,0,0);
  278.  
  279.  
  280.         //set the vertex and pixel shaders
  281.         Vertex v[] =
  282.         {
  283.                 //X / Y/ Z
  284.                 Vertex(0.0f, 0.5f, 0.5f),
  285.                 Vertex(0.5f, -0.5f, 0.5f),
  286.                 Vertex(-0.5f, -0.5f, 0.5f),
  287.                 //Vertex(0.2f, 0.5f, -0.5f),
  288.         };
  289.  
  290.         D3D11_BUFFER_DESC vertexBufferDesc;
  291.         ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
  292.  
  293.         vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
  294.         vertexBufferDesc.ByteWidth = sizeof(Vertex) * _countof(v); //was * 3
  295.         vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  296.         vertexBufferDesc.CPUAccessFlags = 0;
  297.         vertexBufferDesc.MiscFlags = 0;
  298.  
  299.         D3D11_SUBRESOURCE_DATA vertexBufferData;
  300.  
  301.         ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
  302.         vertexBufferData.pSysMem = v;
  303.         hr = d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &triangleVertBuffer);
  304.  
  305.         //set the vertex buffer
  306.         UINT stride = sizeof(Vertex);
  307.         UINT offset = 0;
  308.         d3d11DevCon->IASetVertexBuffers(0,1, &triangleVertBuffer, &stride, &offset);
  309.  
  310.         //create the input layout
  311.         d3d11Device->CreateInputLayout(layout, numElements, VS_Buffer->GetBufferPointer(),
  312.                 VS_Buffer->GetBufferSize(), &vertLayout);
  313.        
  314.         //Set the input layout
  315.         d3d11DevCon->IASetInputLayout(vertLayout);
  316.  
  317.         //set primitive topology
  318.         d3d11DevCon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  319.  
  320.  
  321.         //create the viewport
  322.         D3D11_VIEWPORT viewport;
  323.         ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
  324.  
  325.         viewport.TopLeftX = 0;
  326.         viewport.TopLeftY = 0;
  327.         viewport.Width = Width;
  328.         viewport.Height = Height;
  329.  
  330.         //set the viewport
  331.         d3d11DevCon->RSSetViewports(1, &viewport);
  332.         return true;
  333. }
  334.  
  335. void UpdateScene()
  336. {
  337.         red += colormodr * 0.00005f;
  338.         green += colormodg * 0.00002f;
  339.         blue += colormodb * 0.00001f;
  340.  
  341.         if(red >= 1.0f || red <= 0.0f)
  342.                 colormodr *= -1;
  343.         if(green >= 1.0f || green <= 0.0f)
  344.                 colormodg *= -1;
  345.         if(blue >= 1.0f || blue <= 0.0f)
  346.                 colormodb *= -1;
  347. }
  348.  
  349. void DrawScene()
  350. {
  351.         //Clear backbuffer
  352.         D3DXCOLOR bgColor(red, green, blue, 1.0f);
  353.         d3d11DevCon->ClearRenderTargetView(renderTargetView, bgColor);
  354.  
  355.         ///draw the triangled
  356.         d3d11DevCon->Draw(3,0);
  357.  
  358.         SwapChain->Present(0,0);
  359. }
  360.  
  361.  
  362. int messageloop(){      //The message loop
  363.  
  364.         MSG msg;        //Create a new message structure
  365.         ZeroMemory(&msg, sizeof(MSG));  //clear message structure to NULL
  366.  
  367.         while(true)     //while there is a message
  368.     {
  369.                 //if there was a windows message
  370.         if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
  371.         {
  372.             if (msg.message == WM_QUIT) //if the message was WM_QUIT
  373.                 break;  //Exit the message loop
  374.  
  375.             TranslateMessage(&msg);     //Translate the message
  376.            
  377.             //Send the message to default windows procedure
  378.             DispatchMessage(&msg);
  379.         }
  380.  
  381.                 else{   //Otherewise, keep the flow going
  382.                         UpdateScene();
  383.                         DrawScene();
  384.                 }
  385.                
  386.  
  387.         }
  388.  
  389.         return (int)msg.wParam;         //return the message
  390.  
  391. }
  392.  
  393. LRESULT CALLBACK WndProc(HWND hwnd,     //Default windows procedure
  394.                          UINT msg,
  395.                          WPARAM wParam,
  396.                          LPARAM lParam)
  397. {
  398. switch( msg )   //Check message
  399. {
  400.  
  401.         case WM_KEYDOWN:        //For a key down
  402.                 //if escape key was pressed, display popup box
  403.                 if( wParam == VK_ESCAPE ){
  404.                         if(MessageBox(0, "Are you sure you want to exit?",
  405.                 "Really?", MB_YESNO | MB_ICONQUESTION) == IDYES)
  406.                    
  407.                 //Release the windows allocated memory  
  408.                                 DestroyWindow(hwnd);
  409.                 }
  410.         return 0;
  411.  
  412.         case WM_DESTROY:        //if x button in top right was pressed
  413.                 PostQuitMessage(0);
  414.         return 0;
  415. }
  416.     //return the message for windows to handle it
  417.         return DefWindowProc(hwnd,     
  418.                          msg,
  419.                          wParam,
  420.                          lParam);
  421. }
clone this paste RAW Paste Data