Guest User

Untitled

a guest
Apr 23rd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.19 KB | None | 0 0
  1. //--------------------------------------------------------------------------------------
  2. // File: DrawLineDemo.cpp
  3. //
  4. // Example: Draw line using D3D10
  5. //
  6. // Copyright (c) Stefan Petersson 2008. All rights reserved.
  7. //--------------------------------------------------------------------------------------
  8. #include "stdafx.h"
  9. #include "Lights.h"
  10. //--------------------------------------------------------------------------------------
  11. // Global Variables
  12. //--------------------------------------------------------------------------------------
  13. HINSTANCE g_hInst = NULL;
  14. HWND g_hWnd = NULL;
  15. D3D10_DRIVER_TYPE g_driverType = D3D10_DRIVER_TYPE_NULL;
  16. ID3D10Device* g_pd3dDevice = NULL;
  17. IDXGISwapChain* g_pSwapChain = NULL;
  18. ID3D10RenderTargetView* g_pRenderTargetView = NULL;
  19. ID3D10Texture2D* g_pDepthStencil = NULL;
  20. ID3D10DepthStencilView* g_pDepthStencilView = NULL;
  21.  
  22. //camera data
  23. D3DXVECTOR3 g_vCameraPos = D3DXVECTOR3(0,0,-15);
  24. D3DXMATRIX g_mView;
  25. D3DXMATRIX g_mProj;
  26.  
  27. //buffer data
  28. ID3D10InputLayout* g_pVertexLayout;
  29. ID3D10Buffer* g_pVB;
  30.  
  31. //shader variables
  32. ID3D10Effect* g_pEffect;
  33. ID3D10EffectTechnique* g_pTechRenderLine;
  34.  
  35. //Lights
  36. D3DXVECTOR4 ambientLight;
  37. DirectionalLight directionalLight;
  38. Material material;
  39.  
  40. int m_VertexCount = 4;
  41.  
  42. struct LineVertex
  43. {
  44. D3DXVECTOR3 pos;
  45. D3DXVECTOR4 color;
  46. D3DXVECTOR3 normal;
  47. D3DXVECTOR2 tc;
  48.  
  49. LineVertex(D3DXVECTOR3 _pos, D3DXVECTOR4 _color, D3DXVECTOR3 _normal, D3DXVECTOR2 _tc)
  50. {
  51. pos = _pos;
  52. color = _color;
  53. normal = _normal;
  54. tc = _tc;
  55. }
  56. };
  57.  
  58.  
  59.  
  60. //--------------------------------------------------------------------------------------
  61. // Forward declarations
  62. //--------------------------------------------------------------------------------------
  63. HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow );
  64. LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
  65. HRESULT InitDevice();
  66. HRESULT Render(float deltaTime);
  67. void Update(float deltaTime);
  68. void CleanupDevice();
  69.  
  70. //--------------------------------------------------------------------------------------
  71. // Create Direct3D device and swap chain
  72. //--------------------------------------------------------------------------------------
  73.  
  74. HRESULT InitDevice()
  75. {
  76. HRESULT hr = S_OK;;
  77.  
  78. RECT rc;
  79. GetClientRect( g_hWnd, &rc );
  80. UINT width = rc.right - rc.left;
  81. UINT height = rc.bottom - rc.top;
  82.  
  83. UINT createDeviceFlags = 0;
  84. #ifdef _DEBUG
  85. createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
  86. #endif
  87.  
  88. D3D10_DRIVER_TYPE driverTypes[] =
  89. {
  90. D3D10_DRIVER_TYPE_HARDWARE,
  91. D3D10_DRIVER_TYPE_REFERENCE,
  92. };
  93. UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]);
  94.  
  95. DXGI_SWAP_CHAIN_DESC sd;
  96. ZeroMemory( &sd, sizeof(sd) );
  97. sd.BufferCount = 1;
  98. sd.BufferDesc.Width = width;
  99. sd.BufferDesc.Height = height;
  100. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  101. sd.BufferDesc.RefreshRate.Numerator = 60;
  102. sd.BufferDesc.RefreshRate.Denominator = 1;
  103. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  104. sd.OutputWindow = g_hWnd;
  105. sd.SampleDesc.Count = 1;
  106. sd.SampleDesc.Quality = 0;
  107. sd.Windowed = TRUE;
  108.  
  109. for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
  110. {
  111. g_driverType = driverTypes[driverTypeIndex];
  112. hr = D3D10CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags,
  113. D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice );
  114. if( SUCCEEDED( hr ) )
  115. break;
  116. }
  117. if( FAILED(hr) )
  118. return hr;
  119.  
  120. // Create a render target view
  121. ID3D10Texture2D* pBackBuffer;
  122. hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), (LPVOID*)&pBackBuffer );
  123. if( FAILED(hr) )
  124. return hr;
  125.  
  126. hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView );
  127. pBackBuffer->Release();
  128. if( FAILED(hr) )
  129. return hr;
  130.  
  131.  
  132. // Create depth stencil texture
  133. D3D10_TEXTURE2D_DESC descDepth;
  134. descDepth.Width = width;
  135. descDepth.Height = height;
  136. descDepth.MipLevels = 1;
  137. descDepth.ArraySize = 1;
  138. descDepth.Format = DXGI_FORMAT_D32_FLOAT;
  139. descDepth.SampleDesc.Count = 1;
  140. descDepth.SampleDesc.Quality = 0;
  141. descDepth.Usage = D3D10_USAGE_DEFAULT;
  142. descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL;
  143. descDepth.CPUAccessFlags = 0;
  144. descDepth.MiscFlags = 0;
  145. hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil );
  146. if( FAILED(hr) )
  147. return hr;
  148.  
  149. // Create the depth stencil view
  150. D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
  151. descDSV.Format = descDepth.Format;
  152. descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
  153. descDSV.Texture2D.MipSlice = 0;
  154. hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView );
  155. if( FAILED(hr) )
  156. return hr;
  157.  
  158.  
  159. g_pd3dDevice->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView );
  160.  
  161. // Setup the viewport
  162. D3D10_VIEWPORT vp;
  163. vp.Width = width;
  164. vp.Height = height;
  165. vp.MinDepth = 0.0f;
  166. vp.MaxDepth = 1.0f;
  167. vp.TopLeftX = 0;
  168. vp.TopLeftY = 0;
  169. g_pd3dDevice->RSSetViewports( 1, &vp );
  170.  
  171.  
  172. //Create vertex buffer to hold maxAmount of particles
  173. D3D10_BUFFER_DESC bd;
  174. bd.Usage = D3D10_USAGE_DYNAMIC;
  175. bd.ByteWidth = sizeof( LineVertex ) * m_VertexCount;
  176. bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
  177. bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  178. bd.MiscFlags = 0;
  179.  
  180. if( FAILED( g_pd3dDevice->CreateBuffer( &bd, 0, &g_pVB ) ) )
  181. MessageBox( 0, "Unable to create Vertex Buffer", "VB Error", 0 );
  182.  
  183.  
  184.  
  185. //Init shader effect
  186. DWORD dwShaderFlags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY;
  187. if(FAILED(D3DX10CreateEffectFromFile( "Line.fx",
  188. NULL,
  189. NULL,
  190. "fx_4_0",
  191. dwShaderFlags,
  192. 0,
  193. g_pd3dDevice,
  194. NULL,
  195. NULL,
  196. &g_pEffect,
  197. NULL,
  198. NULL)))
  199. {
  200. MessageBox(0, "Error compiling shader!", "Shader error!", 0);
  201. }
  202.  
  203. g_pTechRenderLine = g_pEffect->GetTechniqueByName("DrawLine");
  204.  
  205. // Define our vertex data layout
  206. const D3D10_INPUT_ELEMENT_DESC lineVertexLayout[] =
  207. {
  208. { "POS", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
  209. { "COL", 0, DXGI_FORMAT_R32G32B32A32_FLOAT,0,12,D3D10_INPUT_PER_VERTEX_DATA, 0 },
  210. { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 28, D3D10_INPUT_PER_VERTEX_DATA, 0 },
  211. { "TC", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 40, D3D10_INPUT_PER_VERTEX_DATA, 0 }
  212. };
  213.  
  214. D3D10_PASS_DESC PassDesc;
  215. g_pTechRenderLine->GetPassByIndex(0)->GetDesc(&PassDesc);
  216.  
  217. //Create Input Layout (== Vertex Declaration)
  218. g_pd3dDevice->CreateInputLayout(lineVertexLayout,
  219. sizeof(lineVertexLayout) / sizeof(D3D10_INPUT_ELEMENT_DESC),
  220. PassDesc.pIAInputSignature,
  221. PassDesc.IAInputSignatureSize,
  222. &g_pVertexLayout );
  223.  
  224. //SETTING TEXTURE
  225. ID3D10ShaderResourceView* mDiffuseMapRV;
  226. D3DX10CreateShaderResourceViewFromFile(g_pd3dDevice,"bigskull.png", 0, 0, &mDiffuseMapRV, 0 );
  227.  
  228. ID3D10EffectShaderResourceVariable* mfxDiffuseMapVar;
  229. mfxDiffuseMapVar = g_pEffect->GetVariableByName(
  230. "gDiffuseMap")->AsShaderResource();
  231.  
  232. // Set the C++ texture resource view to the effect texture variable.
  233. mfxDiffuseMapVar->SetResource(mDiffuseMapRV);
  234.  
  235. return S_OK;
  236. }
  237.  
  238. void Map(void** b)
  239. {
  240. g_pVB->Map( D3D10_MAP_WRITE_DISCARD, 0, reinterpret_cast< void** >(b) );
  241. }
  242.  
  243. void Update(float deltaTime)
  244. {
  245. LineVertex* pData = NULL;
  246. //if( SUCCEEDED( g_pVB->Map( D3D10_MAP_WRITE_DISCARD, 0, reinterpret_cast< void** >(&pData) ) ) )
  247. //{
  248. Map((void**)&pData);
  249.  
  250. pData[0].pos = D3DXVECTOR3(0,3,0);
  251. pData[1].pos = D3DXVECTOR3(0,0,0);
  252. pData[2].pos = D3DXVECTOR3(3,3,0);
  253. pData[3].pos = D3DXVECTOR3(3,0,0);
  254.  
  255. pData[0].tc = D3DXVECTOR2(0,0);
  256. pData[1].tc = D3DXVECTOR2(0,1);
  257. pData[2].tc = D3DXVECTOR2(1,0);
  258. pData[3].tc = D3DXVECTOR2(1,1);
  259.  
  260.  
  261.  
  262. for(int i = 0; i < m_VertexCount; i++)
  263. {
  264. pData[i].color = D3DXVECTOR4(pData[i].pos , 0.1f);
  265. pData[i].normal = D3DXVECTOR3(0,0,1);
  266. }
  267.  
  268. //CREATE LIGHTS AND MATERIAL
  269. //--------------------------------------------------------------------------------
  270. ambientLight = D3DXVECTOR4(1.0f,1.0f,1.0f,1.0f);
  271.  
  272. //set directional light - MAKE sure light direction is a unit vector
  273. directionalLight.color = D3DXVECTOR4(1.0f,1.0f,1.0f,1.0f);
  274. directionalLight.direction = D3DXVECTOR3(0,0,1);
  275. D3DXVec3Normalize(&directionalLight.direction, &directionalLight.direction);
  276.  
  277. material.ambient = 0.1f;
  278. material.diffuse = 0.5f;
  279. material.specular = 0.5f;
  280. material.shininess = 30;
  281.  
  282. //set variables
  283. ID3D10EffectVariable* pVar = g_pEffect->GetVariableByName( "light" );
  284. pVar->SetRawValue(&directionalLight, 0, sizeof(DirectionalLight));
  285.  
  286. pVar = g_pEffect->GetVariableByName( "material" );
  287. pVar->SetRawValue(&material, 0, sizeof(Material));
  288.  
  289. pVar = g_pEffect->GetVariableByName( "ambientLight" );
  290. pVar->SetRawValue( &ambientLight, 0, 16 );
  291.  
  292.  
  293. PointLight herp;
  294. herp.ambient = D3DXCOLOR(0.4f, 0.4f, 0.4f, 1.0f);
  295. herp.diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
  296. herp.spec = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
  297. herp.attenuation = D3DXVECTOR3(0.0f,0.1f,0.0f);
  298. herp.range = 50.0f;
  299. herp.Pos = D3DXVECTOR3(0,0,0);
  300.  
  301. g_pEffect->GetVariableByName("derp")->SetRawValue(&herp, 0, sizeof(herp));
  302.  
  303.  
  304. g_pVB->Unmap();
  305. }
  306.  
  307.  
  308.  
  309. HRESULT Render(float deltaTime)
  310. {
  311. // Render the result
  312. D3DXMATRIX mWorldViewProj;
  313.  
  314. //RECT rc;
  315. float width = 1024;
  316. float height = 768;
  317.  
  318. //calculate WVP matrix
  319. static float rotY = 0.0f;
  320. rotY += deltaTime;
  321.  
  322. D3DXMATRIX world, view, proj;
  323. D3DXMatrixRotationY(&world, rotY);
  324.  
  325. D3DXMatrixLookAtLH(&view, &g_vCameraPos, &D3DXVECTOR3(0,0,0), &D3DXVECTOR3(0,1,0));
  326. D3DXMatrixPerspectiveFovLH(&proj, (float)D3DX_PI * 0.45f, 1024.0f / 768.0f, 1.0f, 100.0f);
  327. mWorldViewProj = world * view * proj;
  328.  
  329. // Set variables
  330. g_pEffect->GetVariableByName( "g_mWorldViewProjection" )->AsMatrix()->SetMatrix( (float*)&mWorldViewProj );
  331. g_pEffect->GetVariableByName("CameraPos")->AsVector()->SetFloatVector((float*)&g_vCameraPos);
  332.  
  333.  
  334. //create matrix effect pointers
  335. g_pEffect->GetVariableByName( "View" )->AsMatrix()->SetMatrix((float*)&view);
  336. g_pEffect->GetVariableByName( "Projection" )->AsMatrix()->SetMatrix((float*)&proj);
  337. g_pEffect->GetVariableByName( "World" )->AsMatrix()->SetMatrix((float*)&world);
  338.  
  339. // Set Input Assembler params
  340. UINT stride = sizeof(LineVertex);
  341. UINT offset = 0;
  342. g_pd3dDevice->IASetInputLayout( g_pVertexLayout );
  343. g_pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP );
  344. g_pd3dDevice->IASetVertexBuffers( 0, 1, &g_pVB, &stride, &offset );
  345.  
  346. static float ClearColor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
  347.  
  348. //clear render target
  349. g_pd3dDevice->ClearRenderTargetView( g_pRenderTargetView, ClearColor );
  350.  
  351. //clear depth info
  352. g_pd3dDevice->ClearDepthStencilView( g_pDepthStencilView, D3D10_CLEAR_DEPTH, 1.0f, 0 );
  353.  
  354. // Render line using the technique g_pRenderTextured
  355. D3D10_TECHNIQUE_DESC techDesc;
  356. g_pTechRenderLine->GetDesc( &techDesc );
  357. for( UINT p = 0; p < techDesc.Passes; p++ )
  358. {
  359. g_pTechRenderLine->GetPassByIndex( p )->Apply(0);
  360. g_pd3dDevice->Draw(m_VertexCount, 0);
  361. }
  362.  
  363. if(FAILED(g_pSwapChain->Present( 0, 0 )))
  364. return E_FAIL;
  365.  
  366. return S_OK;
  367. }
  368.  
  369. //--------------------------------------------------------------------------------------
  370. // Entry point to the program. Initializes everything and goes into a message processing
  371. // loop. Idle time is used to render the scene.
  372. //--------------------------------------------------------------------------------------
  373. int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
  374. {
  375. if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
  376. return 0;
  377.  
  378. if( FAILED( InitDevice() ) )
  379. return 0;
  380.  
  381. __int64 cntsPerSec = 0;
  382. QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec);
  383. float secsPerCnt = 1.0f / (float)cntsPerSec;
  384.  
  385. __int64 prevTimeStamp = 0;
  386. QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp);
  387.  
  388. // Main message loop
  389. MSG msg = {0};
  390. while(WM_QUIT != msg.message)
  391. {
  392. if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE) )
  393. {
  394. TranslateMessage( &msg );
  395. DispatchMessage( &msg );
  396. }
  397. else
  398. {
  399. __int64 currTimeStamp = 0;
  400. QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp);
  401. float dt = (currTimeStamp - prevTimeStamp) * secsPerCnt;
  402.  
  403. //render
  404. Update(dt);
  405. Render(dt);
  406.  
  407. prevTimeStamp = currTimeStamp;
  408. }
  409. }
  410.  
  411. CleanupDevice();
  412.  
  413. return (int) msg.wParam;
  414. }
  415.  
  416.  
  417. //--------------------------------------------------------------------------------------
  418. // Register class and create window
  419. //--------------------------------------------------------------------------------------
  420. HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
  421. {
  422. // Register class
  423. WNDCLASSEX wcex;
  424. wcex.cbSize = sizeof(WNDCLASSEX);
  425. wcex.style = CS_HREDRAW | CS_VREDRAW;
  426. wcex.lpfnWndProc = WndProc;
  427. wcex.cbClsExtra = 0;
  428. wcex.cbWndExtra = 0;
  429. wcex.hInstance = hInstance;
  430. wcex.hIcon = 0;
  431. wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
  432. wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
  433. wcex.lpszMenuName = NULL;
  434. wcex.lpszClassName = "D3DLines";
  435. wcex.hIconSm = 0;
  436. if( !RegisterClassEx(&wcex) )
  437. return E_FAIL;
  438.  
  439. // Create window
  440. g_hInst = hInstance;
  441. RECT rc = { 0, 0, 1024, 768 };
  442. AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
  443.  
  444. if(!(g_hWnd = CreateWindow( "D3DLines",
  445. "Direct3D 10 : Line Drawing",
  446. WS_OVERLAPPEDWINDOW,
  447. CW_USEDEFAULT,
  448. CW_USEDEFAULT,
  449. rc.right - rc.left,
  450. rc.bottom - rc.top,
  451. NULL,
  452. NULL,
  453. hInstance,
  454. NULL)))
  455. {
  456. return E_FAIL;
  457. }
  458.  
  459. ShowWindow( g_hWnd, nCmdShow );
  460.  
  461. return S_OK;
  462. }
  463.  
  464.  
  465. //--------------------------------------------------------------------------------------
  466. // Called every time the application receives a message
  467. //--------------------------------------------------------------------------------------
  468. LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
  469. {
  470. PAINTSTRUCT ps;
  471. HDC hdc;
  472.  
  473. switch (message)
  474. {
  475. case WM_PAINT:
  476. hdc = BeginPaint(hWnd, &ps);
  477. EndPaint(hWnd, &ps);
  478. break;
  479.  
  480. case WM_DESTROY:
  481. PostQuitMessage(0);
  482. break;
  483.  
  484. case WM_KEYDOWN:
  485.  
  486. switch(wParam)
  487. {
  488. case VK_ESCAPE:
  489. PostQuitMessage(0);
  490. break;
  491. }
  492. break;
  493.  
  494. default:
  495. return DefWindowProc(hWnd, message, wParam, lParam);
  496. }
  497.  
  498. return 0;
  499. }
  500.  
  501. //--------------------------------------------------------------------------------------
  502. // Clean up the objects we've created
  503. //--------------------------------------------------------------------------------------
  504. void CleanupDevice()
  505. {
  506. if( g_pd3dDevice ) g_pd3dDevice->ClearState();
  507.  
  508. SAFE_RELEASE(g_pRenderTargetView);
  509. SAFE_RELEASE(g_pDepthStencilView);
  510. SAFE_RELEASE(g_pSwapChain);
  511. SAFE_RELEASE(g_pd3dDevice);
  512. SAFE_RELEASE(g_pVB);
  513. }
Add Comment
Please, Sign In to add comment