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 / Common / UploadBuffer.h < prev   
Encoding:
C/C++ Source or Header  |  2016-03-02  |  2.1 KB  |  64 lines

  1. #pragma once
  2.  
  3. #include "d3dUtil.h"
  4.  
  5. template<typename T>
  6. class UploadBuffer
  7. {
  8. public:
  9.     UploadBuffer(ID3D12Device* device, UINT elementCount, bool isConstantBuffer) : 
  10.         mIsConstantBuffer(isConstantBuffer)
  11.     {
  12.         mElementByteSize = sizeof(T);
  13.  
  14.         // Constant buffer elements need to be multiples of 256 bytes.
  15.         // This is because the hardware can only view constant data 
  16.         // at m*256 byte offsets and of n*256 byte lengths. 
  17.         // typedef struct D3D12_CONSTANT_BUFFER_VIEW_DESC {
  18.         // UINT64 OffsetInBytes; // multiple of 256
  19.         // UINT   SizeInBytes;   // multiple of 256
  20.         // } D3D12_CONSTANT_BUFFER_VIEW_DESC;
  21.         if(isConstantBuffer)
  22.             mElementByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(T));
  23.  
  24.         ThrowIfFailed(device->CreateCommittedResource(
  25.             &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
  26.             D3D12_HEAP_FLAG_NONE,
  27.             &CD3DX12_RESOURCE_DESC::Buffer(mElementByteSize*elementCount),
  28.             D3D12_RESOURCE_STATE_GENERIC_READ,
  29.             nullptr,
  30.             IID_PPV_ARGS(&mUploadBuffer)));
  31.  
  32.         ThrowIfFailed(mUploadBuffer->Map(0, nullptr, reinterpret_cast<void**>(&mMappedData)));
  33.  
  34.         // We do not need to unmap until we are done with the resource.  However, we must not write to
  35.         // the resource while it is in use by the GPU (so we must use synchronization techniques).
  36.     }
  37.  
  38.     UploadBuffer(const UploadBuffer& rhs) = delete;
  39.     UploadBuffer& operator=(const UploadBuffer& rhs) = delete;
  40.     ~UploadBuffer()
  41.     {
  42.         if(mUploadBuffer != nullptr)
  43.             mUploadBuffer->Unmap(0, nullptr);
  44.  
  45.         mMappedData = nullptr;
  46.     }
  47.  
  48.     ID3D12Resource* Resource()const
  49.     {
  50.         return mUploadBuffer.Get();
  51.     }
  52.  
  53.     void CopyData(int elementIndex, const T& data)
  54.     {
  55.         memcpy(&mMappedData[elementIndex*mElementByteSize], &data, sizeof(T));
  56.     }
  57.  
  58. private:
  59.     Microsoft::WRL::ComPtr<ID3D12Resource> mUploadBuffer;
  60.     BYTE* mMappedData = nullptr;
  61.  
  62.     UINT mElementByteSize = 0;
  63.     bool mIsConstantBuffer = false;
  64. };