MCPcopy Create free account
hub / github.com/DavidColson/Polybox / ReadbackPixels

Function ReadbackPixels

source/graphics_platform_d3d11.cpp:188–249  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

186// ***********************************************************************
187
188void ReadbackPixels(int x, int y, int w, int h, void *pixels) {
189 // get current render target
190 ID3D11RenderTargetView* render_target_view = NULL;
191 _sg.d3d11.ctx->OMGetRenderTargets(1, &render_target_view, NULL);
192
193 // fallback to window render target
194 if(!render_target_view)
195 render_target_view = (ID3D11RenderTargetView*)_sg.d3d11.cur_pass.render_view;
196
197 if (render_target_view == nullptr)
198 return;
199
200 // get the back buffer texture
201 ID3D11Texture2D *back_buffer = NULL;
202 render_target_view->GetResource((ID3D11Resource**)&back_buffer);
203
204 // create a staging texture to copy the screen's data to
205 D3D11_TEXTURE2D_DESC staging_desc;
206 back_buffer->GetDesc(&staging_desc);
207 staging_desc.Width = w;
208 staging_desc.Height = h;
209 staging_desc.BindFlags = 0;
210 staging_desc.MiscFlags = 0;
211 staging_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
212 staging_desc.Usage = D3D11_USAGE_STAGING;
213 ID3D11Texture2D *staging_tex = NULL;
214 _sg_d3d11_CreateTexture2D(_sg.d3d11.dev, &staging_desc, NULL, &staging_tex);
215
216 // copy the desired portion of the back buffer to the staging texture
217 D3D11_BOX src_box = {
218 .left = (UINT)x,
219 .top = (UINT)y,
220 .front = 0,
221 .right = (UINT)(x + w),
222 .bottom = (UINT)(y + h),
223 .back = 1,
224 };
225 _sg.d3d11.ctx->CopySubresourceRegion(
226 (ID3D11Resource*)staging_tex,
227 0, 0, 0, 0,
228 (ID3D11Resource*)back_buffer,
229 0, &src_box);
230
231 // map the staging texture's data to CPU-accessible memory
232 D3D11_MAPPED_SUBRESOURCE msr = {.pData = NULL};
233 _sg_d3d11_Map(_sg.d3d11.ctx, (ID3D11Resource*)staging_tex, 0, D3D11_MAP_READ, 0, &msr);
234
235 // copy the data into the desired buffer, converting pixels to the desired format at the same time
236 int res = SDL_ConvertPixels(
237 w, h,
238 _sg_d3d11_dxgi_format_to_sdl_pixel_format(staging_desc.Format),
239 msr.pData, msr.RowPitch,
240 SDL_PIXELFORMAT_RGBA32,
241 pixels, w * 4);
242 _SOKOL_UNUSED(res);
243
244 // unmap the texture
245 _sg_d3d11_Unmap(_sg.d3d11.ctx, (ID3D11Resource*)staging_tex, 0);

Callers

nothing calls this directly

Tested by

no test coverage detected