home *** CD-ROM | disk | FTP | other *** search
/ Introduction to 3D Game …ogramming with DirectX 12 / Introduction-to-3D-Game-Programming-with-DirectX-12.ISO / Code.Textures / Chapter 19 Normal Mapping / NormalMap / NormalMapApp.cpp < prev   
Encoding:
C/C++ Source or Header  |  2016-03-02  |  40.0 KB  |  1,063 lines

  1. //***************************************************************************************
  2. // NormalMapApp.cpp by Frank Luna (C) 2015 All Rights Reserved.
  3. //***************************************************************************************
  4.  
  5. #include "../../Common/d3dApp.h"
  6. #include "../../Common/MathHelper.h"
  7. #include "../../Common/UploadBuffer.h"
  8. #include "../../Common/GeometryGenerator.h"
  9. #include "../../Common/Camera.h"
  10. #include "FrameResource.h"
  11.  
  12. using Microsoft::WRL::ComPtr;
  13. using namespace DirectX;
  14. using namespace DirectX::PackedVector;
  15.  
  16. #pragma comment(lib, "d3dcompiler.lib")
  17. #pragma comment(lib, "D3D12.lib")
  18.  
  19. const int gNumFrameResources = 3;
  20.  
  21. // Lightweight structure stores parameters to draw a shape.  This will
  22. // vary from app-to-app.
  23. struct RenderItem
  24. {
  25.     RenderItem() = default;
  26.     RenderItem(const RenderItem& rhs) = delete;
  27.  
  28.     // World matrix of the shape that describes the object's local space
  29.     // relative to the world space, which defines the position, orientation,
  30.     // and scale of the object in the world.
  31.     XMFLOAT4X4 World = MathHelper::Identity4x4();
  32.  
  33.     XMFLOAT4X4 TexTransform = MathHelper::Identity4x4();
  34.  
  35.     // Dirty flag indicating the object data has changed and we need to update the constant buffer.
  36.     // Because we have an object cbuffer for each FrameResource, we have to apply the
  37.     // update to each FrameResource.  Thus, when we modify obect data we should set 
  38.     // NumFramesDirty = gNumFrameResources so that each frame resource gets the update.
  39.     int NumFramesDirty = gNumFrameResources;
  40.  
  41.     // Index into GPU constant buffer corresponding to the ObjectCB for this render item.
  42.     UINT ObjCBIndex = -1;
  43.  
  44.     Material* Mat = nullptr;
  45.     MeshGeometry* Geo = nullptr;
  46.  
  47.     // Primitive topology.
  48.     D3D12_PRIMITIVE_TOPOLOGY PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  49.  
  50.     // DrawIndexedInstanced parameters.
  51.     UINT IndexCount = 0;
  52.     UINT StartIndexLocation = 0;
  53.     int BaseVertexLocation = 0;
  54. };
  55.  
  56. enum class RenderLayer : int
  57. {
  58.     Opaque = 0,
  59.     Sky,
  60.     Count
  61. };
  62.  
  63. class NormalMapApp : public D3DApp
  64. {
  65. public:
  66.     NormalMapApp(HINSTANCE hInstance);
  67.     NormalMapApp(const NormalMapApp& rhs) = delete;
  68.     NormalMapApp& operator=(const NormalMapApp& rhs) = delete;
  69.     ~NormalMapApp();
  70.  
  71.     virtual bool Initialize()override;
  72.  
  73. private:
  74.     virtual void OnResize()override;
  75.     virtual void Update(const GameTimer& gt)override;
  76.     virtual void Draw(const GameTimer& gt)override;
  77.  
  78.     virtual void OnMouseDown(WPARAM btnState, int x, int y)override;
  79.     virtual void OnMouseUp(WPARAM btnState, int x, int y)override;
  80.     virtual void OnMouseMove(WPARAM btnState, int x, int y)override;
  81.  
  82.     void OnKeyboardInput(const GameTimer& gt);
  83.     void AnimateMaterials(const GameTimer& gt);
  84.     void UpdateObjectCBs(const GameTimer& gt);
  85.     void UpdateMaterialBuffer(const GameTimer& gt);
  86.     void UpdateMainPassCB(const GameTimer& gt);
  87.  
  88.     void LoadTextures();
  89.     void BuildRootSignature();
  90.     void BuildDescriptorHeaps();
  91.     void BuildShadersAndInputLayout();
  92.     void BuildShapeGeometry();
  93.     void BuildPSOs();
  94.     void BuildFrameResources();
  95.     void BuildMaterials();
  96.     void BuildRenderItems();
  97.     void DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems);
  98.  
  99.     std::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> GetStaticSamplers();
  100.  
  101. private:
  102.  
  103.     std::vector<std::unique_ptr<FrameResource>> mFrameResources;
  104.     FrameResource* mCurrFrameResource = nullptr;
  105.     int mCurrFrameResourceIndex = 0;
  106.  
  107.     UINT mCbvSrvDescriptorSize = 0;
  108.  
  109.     ComPtr<ID3D12RootSignature> mRootSignature = nullptr;
  110.  
  111.     ComPtr<ID3D12DescriptorHeap> mSrvDescriptorHeap = nullptr;
  112.  
  113.     std::unordered_map<std::string, std::unique_ptr<MeshGeometry>> mGeometries;
  114.     std::unordered_map<std::string, std::unique_ptr<Material>> mMaterials;
  115.     std::unordered_map<std::string, std::unique_ptr<Texture>> mTextures;
  116.     std::unordered_map<std::string, ComPtr<ID3DBlob>> mShaders;
  117.     std::unordered_map<std::string, ComPtr<ID3D12PipelineState>> mPSOs;
  118.  
  119.     std::vector<D3D12_INPUT_ELEMENT_DESC> mInputLayout;
  120.  
  121.     // List of all the render items.
  122.     std::vector<std::unique_ptr<RenderItem>> mAllRitems;
  123.  
  124.     // Render items divided by PSO.
  125.     std::vector<RenderItem*> mRitemLayer[(int)RenderLayer::Count];
  126.  
  127.     UINT mSkyTexHeapIndex = 0;
  128.  
  129.     PassConstants mMainPassCB;
  130.  
  131.     Camera mCamera;
  132.  
  133.     POINT mLastMousePos;
  134. };
  135.  
  136. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
  137.     PSTR cmdLine, int showCmd)
  138. {
  139.     // Enable run-time memory check for debug builds.
  140. #if defined(DEBUG) | defined(_DEBUG)
  141.     _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  142. #endif
  143.  
  144.     try
  145.     {
  146.         NormalMapApp theApp(hInstance);
  147.         if(!theApp.Initialize())
  148.             return 0;
  149.  
  150.         return theApp.Run();
  151.     }
  152.     catch(DxException& e)
  153.     {
  154.         MessageBox(nullptr, e.ToString().c_str(), L"HR Failed", MB_OK);
  155.         return 0;
  156.     }
  157. }
  158.  
  159. NormalMapApp::NormalMapApp(HINSTANCE hInstance)
  160.     : D3DApp(hInstance)
  161. {
  162. }
  163.  
  164. NormalMapApp::~NormalMapApp()
  165. {
  166.     if(md3dDevice != nullptr)
  167.         FlushCommandQueue();
  168. }
  169.  
  170. bool NormalMapApp::Initialize()
  171. {
  172.     if(!D3DApp::Initialize())
  173.         return false;
  174.  
  175.     // Reset the command list to prep for initialization commands.
  176.     ThrowIfFailed(mCommandList->Reset(mDirectCmdListAlloc.Get(), nullptr));
  177.  
  178.     // Get the increment size of a descriptor in this heap type.  This is hardware specific, 
  179.     // so we have to query this information.
  180.     mCbvSrvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  181.  
  182.     mCamera.SetPosition(0.0f, 2.0f, -15.0f);
  183.  
  184.     LoadTextures();
  185.     BuildRootSignature();
  186.     BuildDescriptorHeaps();
  187.     BuildShadersAndInputLayout();
  188.     BuildShapeGeometry();
  189.     BuildMaterials();
  190.     BuildRenderItems();
  191.     BuildFrameResources();
  192.     BuildPSOs();
  193.  
  194.     // Execute the initialization commands.
  195.     ThrowIfFailed(mCommandList->Close());
  196.     ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
  197.     mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
  198.  
  199.     // Wait until initialization is complete.
  200.     FlushCommandQueue();
  201.  
  202.     return true;
  203. }
  204.  
  205. void NormalMapApp::OnResize()
  206. {
  207.     D3DApp::OnResize();
  208.  
  209.     mCamera.SetLens(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);
  210. }
  211.  
  212. void NormalMapApp::Update(const GameTimer& gt)
  213. {
  214.     OnKeyboardInput(gt);
  215.  
  216.     // Cycle through the circular frame resource array.
  217.     mCurrFrameResourceIndex = (mCurrFrameResourceIndex + 1) % gNumFrameResources;
  218.     mCurrFrameResource = mFrameResources[mCurrFrameResourceIndex].get();
  219.  
  220.     // Has the GPU finished processing the commands of the current frame resource?
  221.     // If not, wait until the GPU has completed commands up to this fence point.
  222.     if(mCurrFrameResource->Fence != 0 && mFence->GetCompletedValue() < mCurrFrameResource->Fence)
  223.     {
  224.         HANDLE eventHandle = CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS);
  225.         ThrowIfFailed(mFence->SetEventOnCompletion(mCurrFrameResource->Fence, eventHandle));
  226.         WaitForSingleObject(eventHandle, INFINITE);
  227.         CloseHandle(eventHandle);
  228.     }
  229.  
  230.     AnimateMaterials(gt);
  231.     UpdateObjectCBs(gt);
  232.     UpdateMaterialBuffer(gt);
  233.     UpdateMainPassCB(gt);
  234. }
  235.  
  236. void NormalMapApp::Draw(const GameTimer& gt)
  237. {
  238.     auto cmdListAlloc = mCurrFrameResource->CmdListAlloc;
  239.  
  240.     // Reuse the memory associated with command recording.
  241.     // We can only reset when the associated command lists have finished execution on the GPU.
  242.     ThrowIfFailed(cmdListAlloc->Reset());
  243.  
  244.     // A command list can be reset after it has been added to the command queue via ExecuteCommandList.
  245.     // Reusing the command list reuses memory.
  246.     ThrowIfFailed(mCommandList->Reset(cmdListAlloc.Get(), mPSOs["opaque"].Get()));
  247.  
  248.     mCommandList->RSSetViewports(1, &mScreenViewport);
  249.     mCommandList->RSSetScissorRects(1, &mScissorRect);
  250.  
  251.     // Indicate a state transition on the resource usage.
  252.     mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
  253.         D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));
  254.  
  255.     // Clear the back buffer and depth buffer.
  256.     mCommandList->ClearRenderTargetView(CurrentBackBufferView(), Colors::LightSteelBlue, 0, nullptr);
  257.     mCommandList->ClearDepthStencilView(DepthStencilView(), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr);
  258.  
  259.     // Specify the buffers we are going to render to.
  260.     mCommandList->OMSetRenderTargets(1, &CurrentBackBufferView(), true, &DepthStencilView());
  261.  
  262.     ID3D12DescriptorHeap* descriptorHeaps[] = { mSrvDescriptorHeap.Get() };
  263.     mCommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);
  264.  
  265.     mCommandList->SetGraphicsRootSignature(mRootSignature.Get());
  266.  
  267.     auto passCB = mCurrFrameResource->PassCB->Resource();
  268.     mCommandList->SetGraphicsRootConstantBufferView(1, passCB->GetGPUVirtualAddress());
  269.  
  270.     // Bind all the materials used in this scene.  For structured buffers, we can bypass the heap and 
  271.     // set as a root descriptor.
  272.     auto matBuffer = mCurrFrameResource->MaterialBuffer->Resource();
  273.     mCommandList->SetGraphicsRootShaderResourceView(2, matBuffer->GetGPUVirtualAddress());
  274.  
  275.     // Bind the sky cube map.  For our demos, we just use one "world" cube map representing the environment
  276.     // from far away, so all objects will use the same cube map and we only need to set it once per-frame.  
  277.     // If we wanted to use "local" cube maps, we would have to change them per-object, or dynamically
  278.     // index into an array of cube maps.
  279.  
  280.     CD3DX12_GPU_DESCRIPTOR_HANDLE skyTexDescriptor(mSrvDescriptorHeap->GetGPUDescriptorHandleForHeapStart());
  281.     skyTexDescriptor.Offset(mSkyTexHeapIndex, mCbvSrvDescriptorSize);
  282.     mCommandList->SetGraphicsRootDescriptorTable(3, skyTexDescriptor);
  283.  
  284.     // Bind all the textures used in this scene.  Observe
  285.     // that we only have to specify the first descriptor in the table.  
  286.     // The root signature knows how many descriptors are expected in the table.
  287.     mCommandList->SetGraphicsRootDescriptorTable(4, mSrvDescriptorHeap->GetGPUDescriptorHandleForHeapStart());
  288.  
  289.     DrawRenderItems(mCommandList.Get(), mRitemLayer[(int)RenderLayer::Opaque]);
  290.  
  291.     mCommandList->SetPipelineState(mPSOs["sky"].Get());
  292.     DrawRenderItems(mCommandList.Get(), mRitemLayer[(int)RenderLayer::Sky]);
  293.  
  294.     // Indicate a state transition on the resource usage.
  295.     mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
  296.         D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT));
  297.  
  298.     // Done recording commands.
  299.     ThrowIfFailed(mCommandList->Close());
  300.  
  301.     // Add the command list to the queue for execution.
  302.     ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
  303.     mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
  304.  
  305.     // Swap the back and front buffers
  306.     ThrowIfFailed(mSwapChain->Present(0, 0));
  307.     mCurrBackBuffer = (mCurrBackBuffer + 1) % SwapChainBufferCount;
  308.  
  309.     // Advance the fence value to mark commands up to this fence point.
  310.     mCurrFrameResource->Fence = ++mCurrentFence;
  311.  
  312.     // Add an instruction to the command queue to set a new fence point. 
  313.     // Because we are on the GPU timeline, the new fence point won't be 
  314.     // set until the GPU finishes processing all the commands prior to this Signal().
  315.     mCommandQueue->Signal(mFence.Get(), mCurrentFence);
  316. }
  317.  
  318. void NormalMapApp::OnMouseDown(WPARAM btnState, int x, int y)
  319. {
  320.     mLastMousePos.x = x;
  321.     mLastMousePos.y = y;
  322.  
  323.     SetCapture(mhMainWnd);
  324. }
  325.  
  326. void NormalMapApp::OnMouseUp(WPARAM btnState, int x, int y)
  327. {
  328.     ReleaseCapture();
  329. }
  330.  
  331. void NormalMapApp::OnMouseMove(WPARAM btnState, int x, int y)
  332. {
  333.     if((btnState & MK_LBUTTON) != 0)
  334.     {
  335.         // Make each pixel correspond to a quarter of a degree.
  336.         float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));
  337.         float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));
  338.  
  339.         mCamera.Pitch(dy);
  340.         mCamera.RotateY(dx);
  341.     }
  342.  
  343.     mLastMousePos.x = x;
  344.     mLastMousePos.y = y;
  345. }
  346.  
  347. void NormalMapApp::OnKeyboardInput(const GameTimer& gt)
  348. {
  349.     const float dt = gt.DeltaTime();
  350.  
  351.     if(GetAsyncKeyState('W') & 0x8000)
  352.         mCamera.Walk(10.0f*dt);
  353.  
  354.     if(GetAsyncKeyState('S') & 0x8000)
  355.         mCamera.Walk(-10.0f*dt);
  356.  
  357.     if(GetAsyncKeyState('A') & 0x8000)
  358.         mCamera.Strafe(-10.0f*dt);
  359.  
  360.     if(GetAsyncKeyState('D') & 0x8000)
  361.         mCamera.Strafe(10.0f*dt);
  362.  
  363.     mCamera.UpdateViewMatrix();
  364. }
  365.  
  366. void NormalMapApp::AnimateMaterials(const GameTimer& gt)
  367. {
  368.     
  369. }
  370.  
  371. void NormalMapApp::UpdateObjectCBs(const GameTimer& gt)
  372. {
  373.     auto currObjectCB = mCurrFrameResource->ObjectCB.get();
  374.     for(auto& e : mAllRitems)
  375.     {
  376.         // Only update the cbuffer data if the constants have changed.  
  377.         // This needs to be tracked per frame resource.
  378.         if(e->NumFramesDirty > 0)
  379.         {
  380.             XMMATRIX world = XMLoadFloat4x4(&e->World);
  381.             XMMATRIX texTransform = XMLoadFloat4x4(&e->TexTransform);
  382.  
  383.             ObjectConstants objConstants;
  384.             XMStoreFloat4x4(&objConstants.World, XMMatrixTranspose(world));
  385.             XMStoreFloat4x4(&objConstants.TexTransform, XMMatrixTranspose(texTransform));
  386.             objConstants.MaterialIndex = e->Mat->MatCBIndex;
  387.  
  388.             currObjectCB->CopyData(e->ObjCBIndex, objConstants);
  389.  
  390.             // Next FrameResource need to be updated too.
  391.             e->NumFramesDirty--;
  392.         }
  393.     }
  394. }
  395.  
  396. void NormalMapApp::UpdateMaterialBuffer(const GameTimer& gt)
  397. {
  398.     auto currMaterialBuffer = mCurrFrameResource->MaterialBuffer.get();
  399.     for(auto& e : mMaterials)
  400.     {
  401.         // Only update the cbuffer data if the constants have changed.  If the cbuffer
  402.         // data changes, it needs to be updated for each FrameResource.
  403.         Material* mat = e.second.get();
  404.         if(mat->NumFramesDirty > 0)
  405.         {
  406.             XMMATRIX matTransform = XMLoadFloat4x4(&mat->MatTransform);
  407.  
  408.             MaterialData matData;
  409.             matData.DiffuseAlbedo = mat->DiffuseAlbedo;
  410.             matData.FresnelR0 = mat->FresnelR0;
  411.             matData.Roughness = mat->Roughness;
  412.             XMStoreFloat4x4(&matData.MatTransform, XMMatrixTranspose(matTransform));
  413.             matData.DiffuseMapIndex = mat->DiffuseSrvHeapIndex;
  414.             matData.NormalMapIndex = mat->NormalSrvHeapIndex;
  415.  
  416.             currMaterialBuffer->CopyData(mat->MatCBIndex, matData);
  417.  
  418.             // Next FrameResource need to be updated too.
  419.             mat->NumFramesDirty--;
  420.         }
  421.     }
  422. }
  423.  
  424. void NormalMapApp::UpdateMainPassCB(const GameTimer& gt)
  425. {
  426.     XMMATRIX view = mCamera.GetView();
  427.     XMMATRIX proj = mCamera.GetProj();
  428.  
  429.     XMMATRIX viewProj = XMMatrixMultiply(view, proj);
  430.     XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view);
  431.     XMMATRIX invProj = XMMatrixInverse(&XMMatrixDeterminant(proj), proj);
  432.     XMMATRIX invViewProj = XMMatrixInverse(&XMMatrixDeterminant(viewProj), viewProj);
  433.  
  434.     XMStoreFloat4x4(&mMainPassCB.View, XMMatrixTranspose(view));
  435.     XMStoreFloat4x4(&mMainPassCB.InvView, XMMatrixTranspose(invView));
  436.     XMStoreFloat4x4(&mMainPassCB.Proj, XMMatrixTranspose(proj));
  437.     XMStoreFloat4x4(&mMainPassCB.InvProj, XMMatrixTranspose(invProj));
  438.     XMStoreFloat4x4(&mMainPassCB.ViewProj, XMMatrixTranspose(viewProj));
  439.     XMStoreFloat4x4(&mMainPassCB.InvViewProj, XMMatrixTranspose(invViewProj));
  440.     mMainPassCB.EyePosW = mCamera.GetPosition3f();
  441.     mMainPassCB.RenderTargetSize = XMFLOAT2((float)mClientWidth, (float)mClientHeight);
  442.     mMainPassCB.InvRenderTargetSize = XMFLOAT2(1.0f / mClientWidth, 1.0f / mClientHeight);
  443.     mMainPassCB.NearZ = 1.0f;
  444.     mMainPassCB.FarZ = 1000.0f;
  445.     mMainPassCB.TotalTime = gt.TotalTime();
  446.     mMainPassCB.DeltaTime = gt.DeltaTime();
  447.     mMainPassCB.AmbientLight = { 0.25f, 0.25f, 0.35f, 1.0f };
  448.     mMainPassCB.Lights[0].Direction = { 0.57735f, -0.57735f, 0.57735f };
  449.     mMainPassCB.Lights[0].Strength = { 0.8f, 0.8f, 0.8f };
  450.     mMainPassCB.Lights[1].Direction = { -0.57735f, -0.57735f, 0.57735f };
  451.     mMainPassCB.Lights[1].Strength = { 0.4f, 0.4f, 0.4f };
  452.     mMainPassCB.Lights[2].Direction = { 0.0f, -0.707f, -0.707f };
  453.     mMainPassCB.Lights[2].Strength = { 0.2f, 0.2f, 0.2f };
  454.  
  455.     auto currPassCB = mCurrFrameResource->PassCB.get();
  456.     currPassCB->CopyData(0, mMainPassCB);
  457. }
  458.  
  459. void NormalMapApp::LoadTextures()
  460. {
  461.     std::vector<std::string> texNames = 
  462.     {
  463.         "bricksDiffuseMap",
  464.         "bricksNormalMap",
  465.         "tileDiffuseMap",
  466.         "tileNormalMap",
  467.         "defaultDiffuseMap",
  468.         "defaultNormalMap",
  469.         "skyCubeMap"
  470.     };
  471.     
  472.     std::vector<std::wstring> texFilenames = 
  473.     {
  474.         L"../../Textures/bricks2.dds",
  475.         L"../../Textures/bricks2_nmap.dds",
  476.         L"../../Textures/tile.dds",
  477.         L"../../Textures/tile_nmap.dds",
  478.         L"../../Textures/white1x1.dds",
  479.         L"../../Textures/default_nmap.dds",
  480.         L"../../Textures/snowcube1024.dds"
  481.     };
  482.     
  483.     for(int i = 0; i < (int)texNames.size(); ++i)
  484.     {
  485.         auto texMap = std::make_unique<Texture>();
  486.         texMap->Name = texNames[i];
  487.         texMap->Filename = texFilenames[i];
  488.         ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
  489.             mCommandList.Get(), texMap->Filename.c_str(),
  490.             texMap->Resource, texMap->UploadHeap));
  491.             
  492.         mTextures[texMap->Name] = std::move(texMap);
  493.     }        
  494. }
  495.  
  496. void NormalMapApp::BuildRootSignature()
  497. {
  498.     CD3DX12_DESCRIPTOR_RANGE texTable0;
  499.     texTable0.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0);
  500.  
  501.     CD3DX12_DESCRIPTOR_RANGE texTable1;
  502.     texTable1.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 10, 1, 0);
  503.  
  504.     // Root parameter can be a table, root descriptor or root constants.
  505.     CD3DX12_ROOT_PARAMETER slotRootParameter[5];
  506.  
  507.     // Perfomance TIP: Order from most frequent to least frequent.
  508.     slotRootParameter[0].InitAsConstantBufferView(0);
  509.     slotRootParameter[1].InitAsConstantBufferView(1);
  510.     slotRootParameter[2].InitAsShaderResourceView(0, 1);
  511.     slotRootParameter[3].InitAsDescriptorTable(1, &texTable0, D3D12_SHADER_VISIBILITY_PIXEL);
  512.     slotRootParameter[4].InitAsDescriptorTable(1, &texTable1, D3D12_SHADER_VISIBILITY_PIXEL);
  513.  
  514.  
  515.     auto staticSamplers = GetStaticSamplers();
  516.  
  517.     // A root signature is an array of root parameters.
  518.     CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(5, slotRootParameter,
  519.         (UINT)staticSamplers.size(), staticSamplers.data(),
  520.         D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  521.  
  522.     // create a root signature with a single slot which points to a descriptor range consisting of a single constant buffer
  523.     ComPtr<ID3DBlob> serializedRootSig = nullptr;
  524.     ComPtr<ID3DBlob> errorBlob = nullptr;
  525.     HRESULT hr = D3D12SerializeRootSignature(&rootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1,
  526.         serializedRootSig.GetAddressOf(), errorBlob.GetAddressOf());
  527.  
  528.     if(errorBlob != nullptr)
  529.     {
  530.         ::OutputDebugStringA((char*)errorBlob->GetBufferPointer());
  531.     }
  532.     ThrowIfFailed(hr);
  533.  
  534.     ThrowIfFailed(md3dDevice->CreateRootSignature(
  535.         0,
  536.         serializedRootSig->GetBufferPointer(),
  537.         serializedRootSig->GetBufferSize(),
  538.         IID_PPV_ARGS(mRootSignature.GetAddressOf())));
  539. }
  540.  
  541. void NormalMapApp::BuildDescriptorHeaps()
  542. {
  543.     //
  544.     // Create the SRV heap.
  545.     //
  546.     D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
  547.     srvHeapDesc.NumDescriptors = 10;
  548.     srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  549.     srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  550.     ThrowIfFailed(md3dDevice->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(&mSrvDescriptorHeap)));
  551.  
  552.     //
  553.     // Fill out the heap with actual descriptors.
  554.     //
  555.     CD3DX12_CPU_DESCRIPTOR_HANDLE hDescriptor(mSrvDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
  556.  
  557.     std::vector<ComPtr<ID3D12Resource>> tex2DList = 
  558.     {
  559.         mTextures["bricksDiffuseMap"]->Resource,
  560.         mTextures["bricksNormalMap"]->Resource,
  561.         mTextures["tileDiffuseMap"]->Resource,
  562.         mTextures["tileNormalMap"]->Resource,
  563.         mTextures["defaultDiffuseMap"]->Resource,
  564.         mTextures["defaultNormalMap"]->Resource
  565.     };
  566.     
  567.     auto skyCubeMap = mTextures["skyCubeMap"]->Resource;
  568.  
  569.     D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
  570.     srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  571.     srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  572.     srvDesc.Texture2D.MostDetailedMip = 0;
  573.     srvDesc.Texture2D.ResourceMinLODClamp = 0.0f;
  574.     
  575.     for(UINT i = 0; i < (UINT)tex2DList.size(); ++i)
  576.     {
  577.         srvDesc.Format = tex2DList[i]->GetDesc().Format;
  578.         srvDesc.Texture2D.MipLevels = tex2DList[i]->GetDesc().MipLevels;
  579.         md3dDevice->CreateShaderResourceView(tex2DList[i].Get(), &srvDesc, hDescriptor);
  580.  
  581.         // next descriptor
  582.         hDescriptor.Offset(1, mCbvSrvDescriptorSize);
  583.     }
  584.     
  585.     srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
  586.     srvDesc.TextureCube.MostDetailedMip = 0;
  587.     srvDesc.TextureCube.MipLevels = skyCubeMap->GetDesc().MipLevels;
  588.     srvDesc.TextureCube.ResourceMinLODClamp = 0.0f;
  589.     srvDesc.Format = skyCubeMap->GetDesc().Format;
  590.     md3dDevice->CreateShaderResourceView(skyCubeMap.Get(), &srvDesc, hDescriptor);
  591.     
  592.     mSkyTexHeapIndex = (UINT)tex2DList.size();
  593. }
  594.  
  595. void NormalMapApp::BuildShadersAndInputLayout()
  596. {
  597.     const D3D_SHADER_MACRO alphaTestDefines[] =
  598.     {
  599.         "ALPHA_TEST", "1",
  600.         NULL, NULL
  601.     };
  602.  
  603.     mShaders["standardVS"] = d3dUtil::CompileShader(L"Shaders\\Default.hlsl", nullptr, "VS", "vs_5_1");
  604.     mShaders["opaquePS"] = d3dUtil::CompileShader(L"Shaders\\Default.hlsl", nullptr, "PS", "ps_5_1");
  605.     
  606.     mShaders["skyVS"] = d3dUtil::CompileShader(L"Shaders\\Sky.hlsl", nullptr, "VS", "vs_5_1");
  607.     mShaders["skyPS"] = d3dUtil::CompileShader(L"Shaders\\Sky.hlsl", nullptr, "PS", "ps_5_1");
  608.  
  609.     mInputLayout =
  610.     {
  611.         { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  612.         { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  613.         { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  614.         { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 32, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  615.     };
  616. }
  617.  
  618. void NormalMapApp::BuildShapeGeometry()
  619. {
  620.     GeometryGenerator geoGen;
  621.     GeometryGenerator::MeshData box = geoGen.CreateBox(1.0f, 1.0f, 1.0f, 3);
  622.     GeometryGenerator::MeshData grid = geoGen.CreateGrid(20.0f, 30.0f, 60, 40);
  623.     GeometryGenerator::MeshData sphere = geoGen.CreateSphere(0.5f, 20, 20);
  624.     GeometryGenerator::MeshData cylinder = geoGen.CreateCylinder(0.5f, 0.3f, 3.0f, 20, 20);
  625.  
  626.     //
  627.     // We are concatenating all the geometry into one big vertex/index buffer.  So
  628.     // define the regions in the buffer each submesh covers.
  629.     //
  630.  
  631.     // Cache the vertex offsets to each object in the concatenated vertex buffer.
  632.     UINT boxVertexOffset = 0;
  633.     UINT gridVertexOffset = (UINT)box.Vertices.size();
  634.     UINT sphereVertexOffset = gridVertexOffset + (UINT)grid.Vertices.size();
  635.     UINT cylinderVertexOffset = sphereVertexOffset + (UINT)sphere.Vertices.size();
  636.  
  637.     // Cache the starting index for each object in the concatenated index buffer.
  638.     UINT boxIndexOffset = 0;
  639.     UINT gridIndexOffset = (UINT)box.Indices32.size();
  640.     UINT sphereIndexOffset = gridIndexOffset + (UINT)grid.Indices32.size();
  641.     UINT cylinderIndexOffset = sphereIndexOffset + (UINT)sphere.Indices32.size();
  642.  
  643.     SubmeshGeometry boxSubmesh;
  644.     boxSubmesh.IndexCount = (UINT)box.Indices32.size();
  645.     boxSubmesh.StartIndexLocation = boxIndexOffset;
  646.     boxSubmesh.BaseVertexLocation = boxVertexOffset;
  647.  
  648.     SubmeshGeometry gridSubmesh;
  649.     gridSubmesh.IndexCount = (UINT)grid.Indices32.size();
  650.     gridSubmesh.StartIndexLocation = gridIndexOffset;
  651.     gridSubmesh.BaseVertexLocation = gridVertexOffset;
  652.  
  653.     SubmeshGeometry sphereSubmesh;
  654.     sphereSubmesh.IndexCount = (UINT)sphere.Indices32.size();
  655.     sphereSubmesh.StartIndexLocation = sphereIndexOffset;
  656.     sphereSubmesh.BaseVertexLocation = sphereVertexOffset;
  657.  
  658.     SubmeshGeometry cylinderSubmesh;
  659.     cylinderSubmesh.IndexCount = (UINT)cylinder.Indices32.size();
  660.     cylinderSubmesh.StartIndexLocation = cylinderIndexOffset;
  661.     cylinderSubmesh.BaseVertexLocation = cylinderVertexOffset;
  662.  
  663.     //
  664.     // Extract the vertex elements we are interested in and pack the
  665.     // vertices of all the meshes into one vertex buffer.
  666.     //
  667.  
  668.     auto totalVertexCount =
  669.         box.Vertices.size() +
  670.         grid.Vertices.size() +
  671.         sphere.Vertices.size() +
  672.         cylinder.Vertices.size();
  673.  
  674.     std::vector<Vertex> vertices(totalVertexCount);
  675.  
  676.     UINT k = 0;
  677.     for(size_t i = 0; i < box.Vertices.size(); ++i, ++k)
  678.     {
  679.         vertices[k].Pos = box.Vertices[i].Position;
  680.         vertices[k].Normal = box.Vertices[i].Normal;
  681.         vertices[k].TexC = box.Vertices[i].TexC;
  682.         vertices[k].TangentU = box.Vertices[i].TangentU;
  683.     }
  684.  
  685.     for(size_t i = 0; i < grid.Vertices.size(); ++i, ++k)
  686.     {
  687.         vertices[k].Pos = grid.Vertices[i].Position;
  688.         vertices[k].Normal = grid.Vertices[i].Normal;
  689.         vertices[k].TexC = grid.Vertices[i].TexC;
  690.         vertices[k].TangentU = grid.Vertices[i].TangentU;
  691.     }
  692.  
  693.     for(size_t i = 0; i < sphere.Vertices.size(); ++i, ++k)
  694.     {
  695.         vertices[k].Pos = sphere.Vertices[i].Position;
  696.         vertices[k].Normal = sphere.Vertices[i].Normal;
  697.         vertices[k].TexC = sphere.Vertices[i].TexC;
  698.         vertices[k].TangentU = sphere.Vertices[i].TangentU;
  699.     }
  700.  
  701.     for(size_t i = 0; i < cylinder.Vertices.size(); ++i, ++k)
  702.     {
  703.         vertices[k].Pos = cylinder.Vertices[i].Position;
  704.         vertices[k].Normal = cylinder.Vertices[i].Normal;
  705.         vertices[k].TexC = cylinder.Vertices[i].TexC;
  706.         vertices[k].TangentU = cylinder.Vertices[i].TangentU;
  707.     }
  708.  
  709.     std::vector<std::uint16_t> indices;
  710.     indices.insert(indices.end(), std::begin(box.GetIndices16()), std::end(box.GetIndices16()));
  711.     indices.insert(indices.end(), std::begin(grid.GetIndices16()), std::end(grid.GetIndices16()));
  712.     indices.insert(indices.end(), std::begin(sphere.GetIndices16()), std::end(sphere.GetIndices16()));
  713.     indices.insert(indices.end(), std::begin(cylinder.GetIndices16()), std::end(cylinder.GetIndices16()));
  714.  
  715.     const UINT vbByteSize = (UINT)vertices.size() * sizeof(Vertex);
  716.     const UINT ibByteSize = (UINT)indices.size()  * sizeof(std::uint16_t);
  717.  
  718.     auto geo = std::make_unique<MeshGeometry>();
  719.     geo->Name = "shapeGeo";
  720.  
  721.     ThrowIfFailed(D3DCreateBlob(vbByteSize, &geo->VertexBufferCPU));
  722.     CopyMemory(geo->VertexBufferCPU->GetBufferPointer(), vertices.data(), vbByteSize);
  723.  
  724.     ThrowIfFailed(D3DCreateBlob(ibByteSize, &geo->IndexBufferCPU));
  725.     CopyMemory(geo->IndexBufferCPU->GetBufferPointer(), indices.data(), ibByteSize);
  726.  
  727.     geo->VertexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  728.         mCommandList.Get(), vertices.data(), vbByteSize, geo->VertexBufferUploader);
  729.  
  730.     geo->IndexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  731.         mCommandList.Get(), indices.data(), ibByteSize, geo->IndexBufferUploader);
  732.  
  733.     geo->VertexByteStride = sizeof(Vertex);
  734.     geo->VertexBufferByteSize = vbByteSize;
  735.     geo->IndexFormat = DXGI_FORMAT_R16_UINT;
  736.     geo->IndexBufferByteSize = ibByteSize;
  737.  
  738.     geo->DrawArgs["box"] = boxSubmesh;
  739.     geo->DrawArgs["grid"] = gridSubmesh;
  740.     geo->DrawArgs["sphere"] = sphereSubmesh;
  741.     geo->DrawArgs["cylinder"] = cylinderSubmesh;
  742.  
  743.     mGeometries[geo->Name] = std::move(geo);
  744. }
  745.  
  746. void NormalMapApp::BuildPSOs()
  747. {
  748.     D3D12_GRAPHICS_PIPELINE_STATE_DESC opaquePsoDesc;
  749.  
  750.     //
  751.     // PSO for opaque objects.
  752.     //
  753.     ZeroMemory(&opaquePsoDesc, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
  754.     opaquePsoDesc.InputLayout = { mInputLayout.data(), (UINT)mInputLayout.size() };
  755.     opaquePsoDesc.pRootSignature = mRootSignature.Get();
  756.     opaquePsoDesc.VS = 
  757.     { 
  758.         reinterpret_cast<BYTE*>(mShaders["standardVS"]->GetBufferPointer()), 
  759.         mShaders["standardVS"]->GetBufferSize()
  760.     };
  761.     opaquePsoDesc.PS = 
  762.     { 
  763.         reinterpret_cast<BYTE*>(mShaders["opaquePS"]->GetBufferPointer()),
  764.         mShaders["opaquePS"]->GetBufferSize()
  765.     };
  766.     opaquePsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
  767.     opaquePsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
  768.     opaquePsoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
  769.     opaquePsoDesc.SampleMask = UINT_MAX;
  770.     opaquePsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  771.     opaquePsoDesc.NumRenderTargets = 1;
  772.     opaquePsoDesc.RTVFormats[0] = mBackBufferFormat;
  773.     opaquePsoDesc.SampleDesc.Count = m4xMsaaState ? 4 : 1;
  774.     opaquePsoDesc.SampleDesc.Quality = m4xMsaaState ? (m4xMsaaQuality - 1) : 0;
  775.     opaquePsoDesc.DSVFormat = mDepthStencilFormat;
  776.     ThrowIfFailed(md3dDevice->CreateGraphicsPipelineState(&opaquePsoDesc, IID_PPV_ARGS(&mPSOs["opaque"])));
  777.  
  778.     //
  779.     // PSO for sky.
  780.     //
  781.     D3D12_GRAPHICS_PIPELINE_STATE_DESC skyPsoDesc = opaquePsoDesc;
  782.  
  783.     // The camera is inside the sky sphere, so just turn off culling.
  784.     skyPsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
  785.  
  786.     // Make sure the depth function is LESS_EQUAL and not just LESS.  
  787.     // Otherwise, the normalized depth values at z = 1 (NDC) will 
  788.     // fail the depth test if the depth buffer was cleared to 1.
  789.     skyPsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
  790.     skyPsoDesc.pRootSignature = mRootSignature.Get();
  791.     skyPsoDesc.VS =
  792.     {
  793.         reinterpret_cast<BYTE*>(mShaders["skyVS"]->GetBufferPointer()),
  794.         mShaders["skyVS"]->GetBufferSize()
  795.     };
  796.     skyPsoDesc.PS =
  797.     {
  798.         reinterpret_cast<BYTE*>(mShaders["skyPS"]->GetBufferPointer()),
  799.         mShaders["skyPS"]->GetBufferSize()
  800.     };
  801.     ThrowIfFailed(md3dDevice->CreateGraphicsPipelineState(&skyPsoDesc, IID_PPV_ARGS(&mPSOs["sky"])));
  802.  
  803. }
  804.  
  805. void NormalMapApp::BuildFrameResources()
  806. {
  807.     for(int i = 0; i < gNumFrameResources; ++i)
  808.     {
  809.         mFrameResources.push_back(std::make_unique<FrameResource>(md3dDevice.Get(),
  810.             1, (UINT)mAllRitems.size(), (UINT)mMaterials.size()));
  811.     }
  812. }
  813.  
  814. void NormalMapApp::BuildMaterials()
  815. {
  816.     auto bricks0 = std::make_unique<Material>();
  817.     bricks0->Name = "bricks0";
  818.     bricks0->MatCBIndex = 0;
  819.     bricks0->DiffuseSrvHeapIndex = 0;
  820.     bricks0->NormalSrvHeapIndex = 1;
  821.     bricks0->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
  822.     bricks0->FresnelR0 = XMFLOAT3(0.1f, 0.1f, 0.1f);
  823.     bricks0->Roughness = 0.3f;
  824.  
  825.     auto tile0 = std::make_unique<Material>();
  826.     tile0->Name = "tile0";
  827.     tile0->MatCBIndex = 2;
  828.     tile0->DiffuseSrvHeapIndex = 2;
  829.     tile0->NormalSrvHeapIndex = 3;
  830.     tile0->DiffuseAlbedo = XMFLOAT4(0.9f, 0.9f, 0.9f, 1.0f);
  831.     tile0->FresnelR0 = XMFLOAT3(0.2f, 0.2f, 0.2f);
  832.     tile0->Roughness = 0.1f;
  833.  
  834.     auto mirror0 = std::make_unique<Material>();
  835.     mirror0->Name = "mirror0";
  836.     mirror0->MatCBIndex = 3;
  837.     mirror0->DiffuseSrvHeapIndex = 4;
  838.     mirror0->NormalSrvHeapIndex = 5;
  839.     mirror0->DiffuseAlbedo = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
  840.     mirror0->FresnelR0 = XMFLOAT3(0.98f, 0.97f, 0.95f);
  841.     mirror0->Roughness = 0.1f;
  842.  
  843.     auto sky = std::make_unique<Material>();
  844.     sky->Name = "sky";
  845.     sky->MatCBIndex = 4;
  846.     sky->DiffuseSrvHeapIndex = 6;
  847.     sky->NormalSrvHeapIndex = 7;
  848.     sky->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
  849.     sky->FresnelR0 = XMFLOAT3(0.1f, 0.1f, 0.1f);
  850.     sky->Roughness = 1.0f;
  851.     
  852.     mMaterials["bricks0"] = std::move(bricks0);
  853.     mMaterials["tile0"] = std::move(tile0);
  854.     mMaterials["mirror0"] = std::move(mirror0);
  855.     mMaterials["sky"] = std::move(sky);
  856. }
  857.  
  858. void NormalMapApp::BuildRenderItems()
  859. {
  860.     auto skyRitem = std::make_unique<RenderItem>();
  861.     XMStoreFloat4x4(&skyRitem->World, XMMatrixScaling(5000.0f, 5000.0f, 5000.0f));
  862.     skyRitem->TexTransform = MathHelper::Identity4x4();
  863.     skyRitem->ObjCBIndex = 0;
  864.     skyRitem->Mat = mMaterials["sky"].get();
  865.     skyRitem->Geo = mGeometries["shapeGeo"].get();
  866.     skyRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  867.     skyRitem->IndexCount = skyRitem->Geo->DrawArgs["sphere"].IndexCount;
  868.     skyRitem->StartIndexLocation = skyRitem->Geo->DrawArgs["sphere"].StartIndexLocation;
  869.     skyRitem->BaseVertexLocation = skyRitem->Geo->DrawArgs["sphere"].BaseVertexLocation;
  870.  
  871.     mRitemLayer[(int)RenderLayer::Sky].push_back(skyRitem.get());
  872.     mAllRitems.push_back(std::move(skyRitem));
  873.  
  874.     auto boxRitem = std::make_unique<RenderItem>();
  875.     XMStoreFloat4x4(&boxRitem->World, XMMatrixScaling(2.0f, 1.0f, 2.0f)*XMMatrixTranslation(0.0f, 0.5f, 0.0f));
  876.     XMStoreFloat4x4(&boxRitem->TexTransform, XMMatrixScaling(1.0f, 0.5f, 1.0f));
  877.     boxRitem->ObjCBIndex = 1;
  878.     boxRitem->Mat = mMaterials["bricks0"].get();
  879.     boxRitem->Geo = mGeometries["shapeGeo"].get();
  880.     boxRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  881.     boxRitem->IndexCount = boxRitem->Geo->DrawArgs["box"].IndexCount;
  882.     boxRitem->StartIndexLocation = boxRitem->Geo->DrawArgs["box"].StartIndexLocation;
  883.     boxRitem->BaseVertexLocation = boxRitem->Geo->DrawArgs["box"].BaseVertexLocation;
  884.  
  885.     mRitemLayer[(int)RenderLayer::Opaque].push_back(boxRitem.get());
  886.     mAllRitems.push_back(std::move(boxRitem));
  887.  
  888.     auto globeRitem = std::make_unique<RenderItem>();
  889.     XMStoreFloat4x4(&globeRitem->World, XMMatrixScaling(2.0f, 2.0f, 2.0f)*XMMatrixTranslation(0.0f, 2.0f, 0.0f));
  890.     XMStoreFloat4x4(&globeRitem->TexTransform, XMMatrixScaling(1.0f, 1.0f, 1.0f));
  891.     globeRitem->ObjCBIndex = 2;
  892.     globeRitem->Mat = mMaterials["mirror0"].get();
  893.     globeRitem->Geo = mGeometries["shapeGeo"].get();
  894.     globeRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  895.     globeRitem->IndexCount = globeRitem->Geo->DrawArgs["sphere"].IndexCount;
  896.     globeRitem->StartIndexLocation = globeRitem->Geo->DrawArgs["sphere"].StartIndexLocation;
  897.     globeRitem->BaseVertexLocation = globeRitem->Geo->DrawArgs["sphere"].BaseVertexLocation;
  898.  
  899.     mRitemLayer[(int)RenderLayer::Opaque].push_back(globeRitem.get());
  900.     mAllRitems.push_back(std::move(globeRitem));
  901.  
  902.     auto gridRitem = std::make_unique<RenderItem>();
  903.     gridRitem->World = MathHelper::Identity4x4();
  904.     XMStoreFloat4x4(&gridRitem->TexTransform, XMMatrixScaling(8.0f, 8.0f, 1.0f));
  905.     gridRitem->ObjCBIndex = 3;
  906.     gridRitem->Mat = mMaterials["tile0"].get();
  907.     gridRitem->Geo = mGeometries["shapeGeo"].get();
  908.     gridRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  909.     gridRitem->IndexCount = gridRitem->Geo->DrawArgs["grid"].IndexCount;
  910.     gridRitem->StartIndexLocation = gridRitem->Geo->DrawArgs["grid"].StartIndexLocation;
  911.     gridRitem->BaseVertexLocation = gridRitem->Geo->DrawArgs["grid"].BaseVertexLocation;
  912.  
  913.     mRitemLayer[(int)RenderLayer::Opaque].push_back(gridRitem.get());
  914.     mAllRitems.push_back(std::move(gridRitem));
  915.  
  916.     XMMATRIX brickTexTransform = XMMatrixScaling(1.5f, 2.0f, 1.0f);
  917.     UINT objCBIndex = 4;
  918.     for(int i = 0; i < 5; ++i)
  919.     {
  920.         auto leftCylRitem = std::make_unique<RenderItem>();
  921.         auto rightCylRitem = std::make_unique<RenderItem>();
  922.         auto leftSphereRitem = std::make_unique<RenderItem>();
  923.         auto rightSphereRitem = std::make_unique<RenderItem>();
  924.  
  925.         XMMATRIX leftCylWorld = XMMatrixTranslation(-5.0f, 1.5f, -10.0f + i*5.0f);
  926.         XMMATRIX rightCylWorld = XMMatrixTranslation(+5.0f, 1.5f, -10.0f + i*5.0f);
  927.  
  928.         XMMATRIX leftSphereWorld = XMMatrixTranslation(-5.0f, 3.5f, -10.0f + i*5.0f);
  929.         XMMATRIX rightSphereWorld = XMMatrixTranslation(+5.0f, 3.5f, -10.0f + i*5.0f);
  930.  
  931.         XMStoreFloat4x4(&leftCylRitem->World, rightCylWorld);
  932.         XMStoreFloat4x4(&leftCylRitem->TexTransform, brickTexTransform);
  933.         leftCylRitem->ObjCBIndex = objCBIndex++;
  934.         leftCylRitem->Mat = mMaterials["bricks0"].get();
  935.         leftCylRitem->Geo = mGeometries["shapeGeo"].get();
  936.         leftCylRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  937.         leftCylRitem->IndexCount = leftCylRitem->Geo->DrawArgs["cylinder"].IndexCount;
  938.         leftCylRitem->StartIndexLocation = leftCylRitem->Geo->DrawArgs["cylinder"].StartIndexLocation;
  939.         leftCylRitem->BaseVertexLocation = leftCylRitem->Geo->DrawArgs["cylinder"].BaseVertexLocation;
  940.  
  941.         XMStoreFloat4x4(&rightCylRitem->World, leftCylWorld);
  942.         XMStoreFloat4x4(&rightCylRitem->TexTransform, brickTexTransform);
  943.         rightCylRitem->ObjCBIndex = objCBIndex++;
  944.         rightCylRitem->Mat = mMaterials["bricks0"].get();
  945.         rightCylRitem->Geo = mGeometries["shapeGeo"].get();
  946.         rightCylRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  947.         rightCylRitem->IndexCount = rightCylRitem->Geo->DrawArgs["cylinder"].IndexCount;
  948.         rightCylRitem->StartIndexLocation = rightCylRitem->Geo->DrawArgs["cylinder"].StartIndexLocation;
  949.         rightCylRitem->BaseVertexLocation = rightCylRitem->Geo->DrawArgs["cylinder"].BaseVertexLocation;
  950.  
  951.         XMStoreFloat4x4(&leftSphereRitem->World, leftSphereWorld);
  952.         leftSphereRitem->TexTransform = MathHelper::Identity4x4();
  953.         leftSphereRitem->ObjCBIndex = objCBIndex++;
  954.         leftSphereRitem->Mat = mMaterials["mirror0"].get();
  955.         leftSphereRitem->Geo = mGeometries["shapeGeo"].get();
  956.         leftSphereRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  957.         leftSphereRitem->IndexCount = leftSphereRitem->Geo->DrawArgs["sphere"].IndexCount;
  958.         leftSphereRitem->StartIndexLocation = leftSphereRitem->Geo->DrawArgs["sphere"].StartIndexLocation;
  959.         leftSphereRitem->BaseVertexLocation = leftSphereRitem->Geo->DrawArgs["sphere"].BaseVertexLocation;
  960.  
  961.         XMStoreFloat4x4(&rightSphereRitem->World, rightSphereWorld);
  962.         rightSphereRitem->TexTransform = MathHelper::Identity4x4();
  963.         rightSphereRitem->ObjCBIndex = objCBIndex++;
  964.         rightSphereRitem->Mat = mMaterials["mirror0"].get();
  965.         rightSphereRitem->Geo = mGeometries["shapeGeo"].get();
  966.         rightSphereRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  967.         rightSphereRitem->IndexCount = rightSphereRitem->Geo->DrawArgs["sphere"].IndexCount;
  968.         rightSphereRitem->StartIndexLocation = rightSphereRitem->Geo->DrawArgs["sphere"].StartIndexLocation;
  969.         rightSphereRitem->BaseVertexLocation = rightSphereRitem->Geo->DrawArgs["sphere"].BaseVertexLocation;
  970.  
  971.         mRitemLayer[(int)RenderLayer::Opaque].push_back(leftCylRitem.get());
  972.         mRitemLayer[(int)RenderLayer::Opaque].push_back(rightCylRitem.get());
  973.         mRitemLayer[(int)RenderLayer::Opaque].push_back(leftSphereRitem.get());
  974.         mRitemLayer[(int)RenderLayer::Opaque].push_back(rightSphereRitem.get());
  975.  
  976.         mAllRitems.push_back(std::move(leftCylRitem));
  977.         mAllRitems.push_back(std::move(rightCylRitem));
  978.         mAllRitems.push_back(std::move(leftSphereRitem));
  979.         mAllRitems.push_back(std::move(rightSphereRitem));
  980.     }
  981. }
  982.  
  983. void NormalMapApp::DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems)
  984. {
  985.     UINT objCBByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(ObjectConstants));
  986.  
  987.     auto objectCB = mCurrFrameResource->ObjectCB->Resource();
  988.  
  989.     // For each render item...
  990.     for(size_t i = 0; i < ritems.size(); ++i)
  991.     {
  992.         auto ri = ritems[i];
  993.  
  994.         cmdList->IASetVertexBuffers(0, 1, &ri->Geo->VertexBufferView());
  995.         cmdList->IASetIndexBuffer(&ri->Geo->IndexBufferView());
  996.         cmdList->IASetPrimitiveTopology(ri->PrimitiveType);
  997.  
  998.         D3D12_GPU_VIRTUAL_ADDRESS objCBAddress = objectCB->GetGPUVirtualAddress() + ri->ObjCBIndex*objCBByteSize;
  999.  
  1000.         cmdList->SetGraphicsRootConstantBufferView(0, objCBAddress);
  1001.  
  1002.         cmdList->DrawIndexedInstanced(ri->IndexCount, 1, ri->StartIndexLocation, ri->BaseVertexLocation, 0);
  1003.     }
  1004. }
  1005.  
  1006. std::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> NormalMapApp::GetStaticSamplers()
  1007. {
  1008.     // Applications usually only need a handful of samplers.  So just define them all up front
  1009.     // and keep them available as part of the root signature.  
  1010.  
  1011.     const CD3DX12_STATIC_SAMPLER_DESC pointWrap(
  1012.         0, // shaderRegister
  1013.         D3D12_FILTER_MIN_MAG_MIP_POINT, // filter
  1014.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU
  1015.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV
  1016.         D3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW
  1017.  
  1018.     const CD3DX12_STATIC_SAMPLER_DESC pointClamp(
  1019.         1, // shaderRegister
  1020.         D3D12_FILTER_MIN_MAG_MIP_POINT, // filter
  1021.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU
  1022.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV
  1023.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW
  1024.  
  1025.     const CD3DX12_STATIC_SAMPLER_DESC linearWrap(
  1026.         2, // shaderRegister
  1027.         D3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter
  1028.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU
  1029.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV
  1030.         D3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW
  1031.  
  1032.     const CD3DX12_STATIC_SAMPLER_DESC linearClamp(
  1033.         3, // shaderRegister
  1034.         D3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter
  1035.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU
  1036.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV
  1037.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW
  1038.  
  1039.     const CD3DX12_STATIC_SAMPLER_DESC anisotropicWrap(
  1040.         4, // shaderRegister
  1041.         D3D12_FILTER_ANISOTROPIC, // filter
  1042.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU
  1043.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV
  1044.         D3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressW
  1045.         0.0f,                             // mipLODBias
  1046.         8);                               // maxAnisotropy
  1047.  
  1048.     const CD3DX12_STATIC_SAMPLER_DESC anisotropicClamp(
  1049.         5, // shaderRegister
  1050.         D3D12_FILTER_ANISOTROPIC, // filter
  1051.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU
  1052.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV
  1053.         D3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressW
  1054.         0.0f,                              // mipLODBias
  1055.         8);                                // maxAnisotropy
  1056.  
  1057.     return { 
  1058.         pointWrap, pointClamp,
  1059.         linearWrap, linearClamp, 
  1060.         anisotropicWrap, anisotropicClamp };
  1061. }
  1062.  
  1063.