<p>Ok, so I made little example of how to do this.</p>

<h2><strong>Short version</strong></h2>

<p>You need to allocate additional buffer with heap type <code>D3D12_HEAP_TYPE_READBACK</code> and resource state set to <code>D3D12_RESOURCE_STATE_COPY_DEST</code>. Then create command list with type <code>D3D12_COMMAND_LIST_TYPE_COPY</code>. After dispatch compute shader use fence to check if buffer is ready, then copy from this buffer to buffer on <code>D3D12_HEAP_TYPE_READBACK</code> heap. Check again with fence if copying is finished and call <code>Map</code> on this buffer.</p>

<p>I would suggest that you stop reading here and try implement it from description above and check longer version if its still doesn't work. Copy/Past isn't the best way to learn :)</p>

<h2><strong>Longer version</strong></h2>

<p>First lets create new command list.</p>

<pre><code>ID3D12CommandQueue* copyQueue;
ID3D12CommandAllocator* copyAllocator;
ID3D12GraphicsCommandList* copyList;

D3D12_COMMAND_QUEUE_DESC descCopyQueue = {};
descCopyQueue.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
descCopyQueue.Type = D3D12_COMMAND_LIST_TYPE_COPY;
device-&gt;CreateCommandQueue(&amp;descCopyQueue, IID_PPV_ARGS(&amp;copyQueue));
device-&gt;CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY, IID_PPV_ARGS(&amp;copyAllocator));
device-&gt;CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, copyAllocator, nullptr, IID_PPV_ARGS(&amp;copyList));
</code></pre>

<p>Notice type <code>D3D12_COMMAND_LIST_TYPE_COPY</code>.</p>

<p>Next thing is new buffer.</p>

<pre><code>D3D12_HEAP_PROPERTIES const heapPropertiesReadback =
{
    /*Type*/                    D3D12_HEAP_TYPE_READBACK
    /*CPUPageProperty*/         ,D3D12_CPU_PAGE_PROPERTY_UNKNOWN
    /*MemoryPoolPreference*/    ,D3D12_MEMORY_POOL_UNKNOWN
    /*CreationNodeMask*/        ,0
    /*VisibleNodeMask*/         ,0
};

D3D12_RESOURCE_DESC buffersDesc = {};
buffersDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffersDesc.Alignment = 0;
buffersDesc.Width = sizeof( unsigned int ) * 5;
buffersDesc.Height = 1;
buffersDesc.DepthOrArraySize = 1;
buffersDesc.MipLevels = 1;
buffersDesc.Format = DXGI_FORMAT_UNKNOWN;
buffersDesc.SampleDesc.Count = 1;
buffersDesc.SampleDesc.Quality = 0;
buffersDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
buffersDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

ID3D12Resource* bufferReadback;

device-&gt;CreateCommittedResource(&amp;heapPropertiesReadback, D3D12_HEAP_FLAG_NONE, &amp;buffersDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&amp;bufferReadback));
</code></pre>

<p>Remember to set <code>D3D12_RESOURCE_DESC ::Width</code> to size of your buffers.</p>

<p>Then after you <code>Dispatch</code> compute list and call <code>ExecuteCommandLists</code> on compute queue you need to use fence, copy buffer and use fence again.</p>

<pre><code>computeQueue-&gt;Signal(fence, fenceValue);
fence-&gt;SetEventOnCompletion(fenceValue, fenceEvent);
++fenceValue;
WaitForSingleObject(fenceEvent, INFINITE);

copyList-&gt;CopyResource(bufferReadback, bufferB);
copyList-&gt;Close();
copyQueue-&gt;ExecuteCommandLists(1, (ID3D12CommandList**)(&amp;copyList));

copyQueue-&gt;Signal(fence, fenceValue);
fence-&gt;SetEventOnCompletion(fenceValue, fenceEvent);
++fenceValue;
WaitForSingleObject(fenceEvent, INFINITE);
</code></pre>

<p>After this you can call <code>Map</code> on resource.</p>

<pre><code>unsigned int* data;
bufferReadback-&gt;Map(0, nullptr, reinterpret_cast&lt;void**&gt;(&amp;data));
</code></pre>

<p>I hope this will help, let me know if you have any questions.</p>

CC BY-SA 3.0
2017-04-28T23:53:15.670Z
Thank you for you recommendation @Derag. However, the values in the readback buffer are incorrect. 
Can this be because of the readback buffer description, that the numbers are not being interpreted correctly?
Madhu
CC BY-SA 3.0
2017-04-29T11:07:40.650Z
What values do you get? If you get only zeros you probably have some bug in code. If buffer you pass to `Map` have different type than `UAV` buffer that you read values can vary.
And I don't think that `D3D12_RESOURCE_DESC` should be problem here as long as `D3D12_RESOURCE_DESC::Width` is set to right size and `D3D12_RESOURCE_DESC::Format` is set to `DXGI_FORMAT_UNKNOWN`
Derag
CC BY-SA 3.0
2017-05-01T16:50:18.383Z
The definition of the readback buffer is the same as what you suggested, the buffer which the shader actually calls (or in the example above "bufferB) has the following properties:
D3D12_HEAP_PROPERTIES defaultHeapProperties = { D3D12_HEAP_TYPE_DEFAULT,D3D12_CPU_PAGE_PROPERTY_UNKNOWN,D3D12_MEMORY_POOL_UNKNOWN,0,0 };
ThrowIfFailed(m_device->CreateCommittedResource(&defaultHeapProperties, D3D12_HEAP_FLAG_NONE, &buffersDesc1, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&m_computeBuffer)));
Madhu
CC BY-SA 3.0
2017-05-02T09:20:15.083Z
What size of buffers did you set? And what types of data? (int, float...)
Derag
CC BY-SA 3.0
2017-04-25T22:42:55.887Z
2017-04-25T22:42:55.887Z
Derag
<p>I am pretty new to the dx12 world. As a sample project I am trying to add 2 buffers and store the output in yet another output buffer. As apart of this debugging I am trying to see if the buffers that I am loading actually have the right values. 
Thus, once the buffer is loaded, I want to put in a fence and "read back the data uploaded" into the CPU and print out the contents of the buffer. 
After a lot of googling I thought i should use the map function in DXD12. </p>

<p>But I am not entirely sure how I should go about doing this. Any thoughts?</p>

CC BY-SA 3.0
2017-04-20T13:57:11.980Z
I think you can also use [ID3D12Resource::ReadFromSubresource](https://msdn.microsoft.com/en-us/library/windows/desktop/dn914415(v=vs.85).aspx)
 it is a little simpler.
Derag
CC BY-SA 3.0
2017-04-20T16:37:28.903Z
But I am trying to read out of a compute buffer. I was under the impression that ReadFromSubresource is used primarily on textures and layouts.
Madhu
CC BY-SA 3.0
2017-04-20T21:18:10.633Z
I never used this with `UAV` but maybe it will work, just set `DstRowPitch` and `DstDepthPitch` to buffer size (in bytes) and you will see if its work. I don't see why it shouldn't work (but maybe it don't)
Derag
CC BY-SA 3.0
2017-04-21T00:43:15.963Z
I created the Input buffer with the following properties:

ThrowIfFailed(m_device->CreateCommittedResource( &defaultHeapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc,
D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
IID_PPV_ARGS(&m_InputBuffer1[0])));

and later on when I try to read it back as follows, the compiler throws an exception!

UINT8* pDataBegin;
m_InputBuffer1[0]->ReadFromSubresource(reinterpret_cast<void**>(&pDataBegin),5,5,0,0);
printf("The value pointed to is %d", *pDataBegin);

any idea why this is happening ?
Madhu
CC BY-SA 3.0
2017-04-21T09:07:35.853Z
`ID3D12Resource::ReadFromSubresource` doesn't allocate memory for you and it get pointer not pointer to pointer, so you need to allocate memory and cast `pDataBegin` to `void*` not `void**`. Remember to free allocated memory
Derag
CC BY-SA 3.0
2017-04-21T09:18:06.320Z
Also i'm not sure about `D3D12_RESOURCE_STATE_COPY_DEST` but i don't see whole code so can't tell if its should be this resource state.
Derag
CC BY-SA 3.0
2017-04-24T18:36:13.967Z
But wouldn't it be easier if i use the Map and Unmap pair?

std::vector<UINT8> pDataBegin;
ThrowIfFailed(m_InputBuffer1[0]->Map(0, NULL, reinterpret_cast<void**>(&pDataBegin)));

but then again even this throws an error :(
Madhu
CC BY-SA 3.0
2017-04-24T22:43:10.197Z
What error do you get? Did you try `ReadFromSubresource`? Did you do steps pointed [on Microsoft page](https://msdn.microsoft.com/en-us/library/windows/desktop/dn899202(v=vs.85).aspx)?
Derag
CC BY-SA 3.0
2017-04-24T23:06:21.883Z
I was not able to declare my heap as type D3D12_HEAP_TYPE_READBACK. Because the second I do that, I am not able to call CreateCommitResource and even create the buffer.

If i keep the heap type DEFAULT and call Map, there is nothing returned into *pDataBegin
Madhu
<directx12>
Readback Data through Buffers
Madhu
# Readback Data through Buffers

(Asked by: username_0 on 2017-04-20)

I am pretty new to the dx12 world. As a sample project I am trying to add 2 buffers and store the output in yet another output buffer. As apart of this debugging I am trying to see if the buffers that I am loading actually have the right values.
Thus, once the buffer is loaded, I want to put in a fence and "read back the data uploaded" into the CPU and print out the contents of the buffer.
After a lot of googling I thought i should use the map function in DXD12.

But I am not entirely sure how I should go about doing this. Any thoughts?

**Tags:** directx12

> **Comments:**
> **username_1**: I think you can also use [ID3D12Resource::ReadFromSubresource](https://msdn.microsoft.com/en-us/library/windows/desktop/dn914415(v=vs.85).aspx)  it is a little simpler.  
> **username_0**: But I am trying to read out of a compute buffer. I was under the impression that ReadFromSubresource is used primarily on textures and layouts.  
> **username_1**: I never used this with `UAV` but maybe it will work, just set `DstRowPitch` and `DstDepthPitch` to buffer size (in bytes) and you will see if its work. I don't see why it shouldn't work (but maybe it don't)  
> **username_0**: I created the Input buffer with the following properties:  ThrowIfFailed(m_device->CreateCommittedResource( &defaultHeapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&m_InputBuffer1[0])));  and later on when I try to read it back as follows, the compiler throws an exception!  UINT8* pDataBegin; m_InputBuffer1[0]->ReadFromSubresource(reinterpret_cast<void**>(&pDataBegin),5,5,0,0); printf("The value pointed to is %d", *pDataBegin);  any idea why this is happening ?  
> **username_1**: `ID3D12Resource::ReadFromSubresource` doesn't allocate memory for you and it get pointer not pointer to pointer, so you need to allocate memory and cast `pDataBegin` to `void*` not `void**`. Remember to free allocated memory  
> **username_1**: Also i'm not sure about `D3D12_RESOURCE_STATE_COPY_DEST` but i don't see whole code so can't tell if its should be this resource state.  
> **username_0**: But wouldn't it be easier if i use the Map and Unmap pair?  std::vector<UINT8> pDataBegin; ThrowIfFailed(m_InputBuffer1[0]->Map(0, NULL, reinterpret_cast<void**>(&pDataBegin)));  but then again even this throws an error :(  
> **username_1**: What error do you get? Did you try `ReadFromSubresource`? Did you do steps pointed [on Microsoft page](https://msdn.microsoft.com/en-us/library/windows/desktop/dn899202(v=vs.85).aspx)?  
> **username_0**: I was not able to declare my heap as type D3D12_HEAP_TYPE_READBACK. Because the second I do that, I am not able to call CreateCommitResource and even create the buffer.  If i keep the heap type DEFAULT and call Map, there is nothing returned into *pDataBegin  

---

## 1 answers

### Answer by username_1 on 2017-04-25. Score: 1 | Accepted answer

Ok, so I made little example of how to do this.

## **Short version**

You need to allocate additional buffer with heap type `D3D12_HEAP_TYPE_READBACK` and resource state set to `D3D12_RESOURCE_STATE_COPY_DEST`. Then create command list with type `D3D12_COMMAND_LIST_TYPE_COPY`. After dispatch compute shader use fence to check if buffer is ready, then copy from this buffer to buffer on `D3D12_HEAP_TYPE_READBACK` heap. Check again with fence if copying is finished and call `Map` on this buffer.

I would suggest that you stop reading here and try implement it from description above and check longer version if its still doesn't work. Copy/Past isn't the best way to learn :)

## **Longer version**

First lets create new command list.

```
ID3D12CommandQueue* copyQueue;
ID3D12CommandAllocator* copyAllocator;
ID3D12GraphicsCommandList* copyList;

D3D12_COMMAND_QUEUE_DESC descCopyQueue = {};
descCopyQueue.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
descCopyQueue.Type = D3D12_COMMAND_LIST_TYPE_COPY;
device->CreateCommandQueue(&descCopyQueue, IID_PPV_ARGS(&copyQueue));
device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY, IID_PPV_ARGS(&copyAllocator));
device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, copyAllocator, nullptr, IID_PPV_ARGS(&copyList));

```

Notice type `D3D12_COMMAND_LIST_TYPE_COPY`.

Next thing is new buffer.

```
D3D12_HEAP_PROPERTIES const heapPropertiesReadback =
{
    /*Type*/                    D3D12_HEAP_TYPE_READBACK
    /*CPUPageProperty*/         ,D3D12_CPU_PAGE_PROPERTY_UNKNOWN
    /*MemoryPoolPreference*/    ,D3D12_MEMORY_POOL_UNKNOWN
    /*CreationNodeMask*/        ,0
    /*VisibleNodeMask*/         ,0
};

D3D12_RESOURCE_DESC buffersDesc = {};
buffersDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffersDesc.Alignment = 0;
buffersDesc.Width = sizeof( unsigned int ) * 5;
buffersDesc.Height = 1;
buffersDesc.DepthOrArraySize = 1;
buffersDesc.MipLevels = 1;
buffersDesc.Format = DXGI_FORMAT_UNKNOWN;
buffersDesc.SampleDesc.Count = 1;
buffersDesc.SampleDesc.Quality = 0;
buffersDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
buffersDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

ID3D12Resource* bufferReadback;

device->CreateCommittedResource(&heapPropertiesReadback, D3D12_HEAP_FLAG_NONE, &buffersDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&bufferReadback));

```

Remember to set `D3D12_RESOURCE_DESC ::Width` to size of your buffers.

Then after you `Dispatch` compute list and call `ExecuteCommandLists` on compute queue you need to use fence, copy buffer and use fence again.

```
computeQueue->Signal(fence, fenceValue);
fence->SetEventOnCompletion(fenceValue, fenceEvent);
++fenceValue;
WaitForSingleObject(fenceEvent, INFINITE);

copyList->CopyResource(bufferReadback, bufferB);
copyList->Close();
copyQueue->ExecuteCommandLists(1, (ID3D12CommandList**)(&copyList));

copyQueue->Signal(fence, fenceValue);
fence->SetEventOnCompletion(fenceValue, fenceEvent);
++fenceValue;
WaitForSingleObject(fenceEvent, INFINITE);

```

After this you can call `Map` on resource.

```
unsigned int* data;
bufferReadback->Map(0, nullptr, reinterpret_cast<void**>(&data));

```

I hope this will help, let me know if you have any questions.

> **Comments:**
> **username_0**: Thank you for you recommendation @username_1. However, the values in the readback buffer are incorrect.  Can this be because of the readback buffer description, that the numbers are not being interpreted correctly?  
> **username_1**: What values do you get? If you get only zeros you probably have some bug in code. If buffer you pass to `Map` have different type than `UAV` buffer that you read values can vary. And I don't think that `D3D12_RESOURCE_DESC` should be problem here as long as `D3D12_RESOURCE_DESC::Width` is set to right size and `D3D12_RESOURCE_DESC::Format` is set to `DXGI_FORMAT_UNKNOWN`  
> **username_0**: The definition of the readback buffer is the same as what you suggested, the buffer which the shader actually calls (or in the example above "bufferB) has the following properties: D3D12_HEAP_PROPERTIES defaultHeapProperties = { D3D12_HEAP_TYPE_DEFAULT,D3D12_CPU_PAGE_PROPERTY_UNKNOWN,D3D12_MEMORY_POOL_UNKNOWN,0,0 }; ThrowIfFailed(m_device->CreateCommittedResource(&defaultHeapProperties, D3D12_HEAP_FLAG_NONE, &buffersDesc1, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&m_computeBuffer)));  
> **username_1**: What size of buffers did you set? And what types of data? (int, float...)  

---

