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 9 Texturing / TexColumns / TexColumnsApp.cpp < prev   
Encoding:
C/C++ Source or Header  |  2016-03-02  |  36.3 KB  |  961 lines

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