Last active
July 27, 2016 16:28
-
-
Save yorung/f7b1c1f17c969a63d502f50a2318da26 to your computer and use it in GitHub Desktop.
[DX12] Simple texture uploader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| void afWriteBuffer(const ComPtr<ID3D12Resource> res, const void* buf, int size) | |
| { | |
| void* p; | |
| D3D12_RANGE readRange = {}; | |
| res->Map(0, &readRange, &p); | |
| memcpy(p, buf, size); | |
| D3D12_RANGE wroteRange = {0, (SIZE_T)size}; | |
| id->Unmap(0, &wroteRange); | |
| } | |
| ComPtr<ID3D12Resource> afCreateBuffer(int size, const void* buf) | |
| { | |
| D3D12_HEAP_PROPERTIES prop = { D3D12_HEAP_TYPE_UPLOAD, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 1, 1 }; | |
| D3D12_RESOURCE_DESC desc = { D3D12_RESOURCE_DIMENSION_BUFFER, 0, (UINT64)size, 1, 1, 1, DXGI_FORMAT_UNKNOWN, { 1, 0 }, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE }; | |
| UBOID o; | |
| deviceMan.GetDevice()->CreateCommittedResource(&prop, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&o)); | |
| afWriteBuffer(o, buf, size); | |
| return o; | |
| } | |
| void UploadTexture(ComPtr<ID3D12Resource> tex, const void* buf) | |
| { | |
| D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint; | |
| UINT64 uploadSize, rowSizeInBytes; | |
| const D3D12_RESOURCE_DESC destDesc = tex->GetDesc(); | |
| deviceMan.GetDevice()->GetCopyableFootprints(&destDesc, 0, 1, 0, &footprint, nullptr, &rowSizeInBytes, &uploadSize); | |
| assert(rowSizeInBytes == footprint.Footprint.RowPitch); // It is safe in most case! | |
| ComPtr<ID3D12Resource> uploadBuf = afCreateBuffer((int)uploadSize, buf); | |
| D3D12_TEXTURE_COPY_LOCATION uploadBufLocation = { uploadBuf.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, footprint }, nativeBufLocation = { tex.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, 0 }; | |
| ID3D12GraphicsCommandList* list = deviceMan.GetCommandList(); | |
| D3D12_RESOURCE_BARRIER transition1 = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, { tex.Get(), 0, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST } }; | |
| list->ResourceBarrier(1, &transition1); | |
| list->CopyTextureRegion(&nativeBufLocation, 0, 0, 0, &uploadBufLocation, nullptr); | |
| D3D12_RESOURCE_BARRIER transition2 = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, { tex.Get(), 0, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE } }; | |
| list->ResourceBarrier(1, &transition2); | |
| deviceMan.AddIntermediateCommandlistDependentResource(uploadBuf); // keep until the command queue has been flushed | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment