xref: /aosp_15_r20/external/angle/src/libANGLE/renderer/d3d/d3d11/Image11.cpp (revision 8975f5c5ed3d1c378011245431ada316dfb6f244)
1 //
2 // Copyright 2012 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 // Image11.h: Implements the rx::Image11 class, which acts as the interface to
8 // the actual underlying resources of a Texture
9 
10 #include "libANGLE/renderer/d3d/d3d11/Image11.h"
11 
12 #include "common/utilities.h"
13 #include "image_util/loadimage.h"
14 #include "libANGLE/Context.h"
15 #include "libANGLE/Framebuffer.h"
16 #include "libANGLE/FramebufferAttachment.h"
17 #include "libANGLE/formatutils.h"
18 #include "libANGLE/renderer/d3d/d3d11/Context11.h"
19 #include "libANGLE/renderer/d3d/d3d11/RenderTarget11.h"
20 #include "libANGLE/renderer/d3d/d3d11/Renderer11.h"
21 #include "libANGLE/renderer/d3d/d3d11/TextureStorage11.h"
22 #include "libANGLE/renderer/d3d/d3d11/formatutils11.h"
23 #include "libANGLE/renderer/d3d/d3d11/renderer11_utils.h"
24 #include "libANGLE/renderer/d3d/d3d11/texture_format_table.h"
25 
26 namespace rx
27 {
28 
Image11(Renderer11 * renderer)29 Image11::Image11(Renderer11 *renderer)
30     : mRenderer(renderer),
31       mDXGIFormat(DXGI_FORMAT_UNKNOWN),
32       mStagingTexture(),
33       mStagingSubresource(0),
34       mRecoverFromStorage(false),
35       mAssociatedStorage(nullptr),
36       mAssociatedImageIndex(),
37       mRecoveredFromStorageCount(0)
38 {}
39 
~Image11()40 Image11::~Image11()
41 {
42     disassociateStorage();
43     releaseStagingTexture();
44 }
45 
46 // static
GenerateMipmap(const gl::Context * context,Image11 * dest,Image11 * src,const Renderer11DeviceCaps & rendererCaps)47 angle::Result Image11::GenerateMipmap(const gl::Context *context,
48                                       Image11 *dest,
49                                       Image11 *src,
50                                       const Renderer11DeviceCaps &rendererCaps)
51 {
52     ASSERT(src->getDXGIFormat() == dest->getDXGIFormat());
53     ASSERT(src->getWidth() == 1 || src->getWidth() / 2 == dest->getWidth());
54     ASSERT(src->getHeight() == 1 || src->getHeight() / 2 == dest->getHeight());
55 
56     D3D11_MAPPED_SUBRESOURCE destMapped;
57     ANGLE_TRY(dest->map(context, D3D11_MAP_WRITE, &destMapped));
58     d3d11::ScopedUnmapper<Image11> destRAII(dest);
59 
60     D3D11_MAPPED_SUBRESOURCE srcMapped;
61     ANGLE_TRY(src->map(context, D3D11_MAP_READ, &srcMapped));
62     d3d11::ScopedUnmapper<Image11> srcRAII(src);
63 
64     const uint8_t *sourceData = static_cast<const uint8_t *>(srcMapped.pData);
65     uint8_t *destData         = static_cast<uint8_t *>(destMapped.pData);
66 
67     auto mipGenerationFunction =
68         d3d11::Format::Get(src->getInternalFormat(), rendererCaps).format().mipGenerationFunction;
69     mipGenerationFunction(src->getWidth(), src->getHeight(), src->getDepth(), sourceData,
70                           srcMapped.RowPitch, srcMapped.DepthPitch, destData, destMapped.RowPitch,
71                           destMapped.DepthPitch);
72 
73     dest->markDirty();
74 
75     return angle::Result::Continue;
76 }
77 
78 // static
CopyImage(const gl::Context * context,Image11 * dest,Image11 * source,const gl::Box & sourceBox,const gl::Offset & destOffset,bool unpackFlipY,bool unpackPremultiplyAlpha,bool unpackUnmultiplyAlpha,const Renderer11DeviceCaps & rendererCaps)79 angle::Result Image11::CopyImage(const gl::Context *context,
80                                  Image11 *dest,
81                                  Image11 *source,
82                                  const gl::Box &sourceBox,
83                                  const gl::Offset &destOffset,
84                                  bool unpackFlipY,
85                                  bool unpackPremultiplyAlpha,
86                                  bool unpackUnmultiplyAlpha,
87                                  const Renderer11DeviceCaps &rendererCaps)
88 {
89     D3D11_MAPPED_SUBRESOURCE destMapped;
90     ANGLE_TRY(dest->map(context, D3D11_MAP_WRITE, &destMapped));
91     d3d11::ScopedUnmapper<Image11> destRAII(dest);
92 
93     D3D11_MAPPED_SUBRESOURCE srcMapped;
94     ANGLE_TRY(source->map(context, D3D11_MAP_READ, &srcMapped));
95     d3d11::ScopedUnmapper<Image11> sourceRAII(source);
96 
97     const auto &sourceFormat =
98         d3d11::Format::Get(source->getInternalFormat(), rendererCaps).format();
99     GLuint sourcePixelBytes =
100         gl::GetSizedInternalFormatInfo(sourceFormat.fboImplementationInternalFormat).pixelBytes;
101 
102     GLenum destUnsizedFormat = gl::GetUnsizedFormat(dest->getInternalFormat());
103     const auto &destFormat   = d3d11::Format::Get(dest->getInternalFormat(), rendererCaps).format();
104     const auto &destFormatInfo =
105         gl::GetSizedInternalFormatInfo(destFormat.fboImplementationInternalFormat);
106     GLuint destPixelBytes = destFormatInfo.pixelBytes;
107 
108     const uint8_t *sourceData = static_cast<const uint8_t *>(srcMapped.pData) +
109                                 sourceBox.x * sourcePixelBytes + sourceBox.y * srcMapped.RowPitch +
110                                 sourceBox.z * srcMapped.DepthPitch;
111     uint8_t *destData = static_cast<uint8_t *>(destMapped.pData) + destOffset.x * destPixelBytes +
112                         destOffset.y * destMapped.RowPitch + destOffset.z * destMapped.DepthPitch;
113 
114     CopyImageCHROMIUM(sourceData, srcMapped.RowPitch, sourcePixelBytes, srcMapped.DepthPitch,
115                       sourceFormat.pixelReadFunction, destData, destMapped.RowPitch, destPixelBytes,
116                       destMapped.DepthPitch, destFormat.pixelWriteFunction, destUnsizedFormat,
117                       destFormatInfo.componentType, sourceBox.width, sourceBox.height,
118                       sourceBox.depth, unpackFlipY, unpackPremultiplyAlpha, unpackUnmultiplyAlpha);
119 
120     dest->markDirty();
121 
122     return angle::Result::Continue;
123 }
124 
isDirty() const125 bool Image11::isDirty() const
126 {
127     // If mDirty is true AND mStagingTexture doesn't exist AND mStagingTexture doesn't need to be
128     // recovered from TextureStorage AND the texture doesn't require init data (i.e. a blank new
129     // texture will suffice) AND robust resource initialization is not enabled then isDirty should
130     // still return false.
131     if (mDirty && !mStagingTexture.valid() && !mRecoverFromStorage)
132     {
133         const Renderer11DeviceCaps &deviceCaps = mRenderer->getRenderer11DeviceCaps();
134         const auto &formatInfo                 = d3d11::Format::Get(mInternalFormat, deviceCaps);
135         if (formatInfo.dataInitializerFunction == nullptr)
136         {
137             return false;
138         }
139     }
140 
141     return mDirty;
142 }
143 
copyToStorage(const gl::Context * context,TextureStorage * storage,const gl::ImageIndex & index,const gl::Box & region)144 angle::Result Image11::copyToStorage(const gl::Context *context,
145                                      TextureStorage *storage,
146                                      const gl::ImageIndex &index,
147                                      const gl::Box &region)
148 {
149     TextureStorage11 *storage11 = GetAs<TextureStorage11>(storage);
150 
151     // If an app's behavior results in an Image11 copying its data to/from to a TextureStorage
152     // multiple times, then we should just keep the staging texture around to prevent the copying
153     // from impacting perf. We allow the Image11 to copy its data to/from TextureStorage once. This
154     // accounts for an app making a late call to glGenerateMipmap.
155     bool attemptToReleaseStagingTexture = (mRecoveredFromStorageCount < 2);
156 
157     if (attemptToReleaseStagingTexture)
158     {
159         // If another image is relying on this Storage for its data, then we must let it recover its
160         // data before we overwrite it.
161         ANGLE_TRY(storage11->releaseAssociatedImage(context, index, this));
162     }
163 
164     const TextureHelper11 *stagingTexture = nullptr;
165     unsigned int stagingSubresourceIndex  = 0;
166     ANGLE_TRY(getStagingTexture(context, &stagingTexture, &stagingSubresourceIndex));
167     ANGLE_TRY(storage11->updateSubresourceLevel(context, *stagingTexture, stagingSubresourceIndex,
168                                                 index, region));
169 
170     // Once the image data has been copied into the Storage, we can release it locally.
171     if (attemptToReleaseStagingTexture)
172     {
173         storage11->associateImage(this, index);
174         releaseStagingTexture();
175         mRecoverFromStorage   = true;
176         mAssociatedStorage    = storage11;
177         mAssociatedImageIndex = index;
178     }
179 
180     return angle::Result::Continue;
181 }
182 
verifyAssociatedStorageValid(TextureStorage11 * textureStorageEXT) const183 void Image11::verifyAssociatedStorageValid(TextureStorage11 *textureStorageEXT) const
184 {
185     ASSERT(mAssociatedStorage == textureStorageEXT);
186 }
187 
recoverFromAssociatedStorage(const gl::Context * context)188 angle::Result Image11::recoverFromAssociatedStorage(const gl::Context *context)
189 {
190     if (mRecoverFromStorage)
191     {
192         ANGLE_TRY(createStagingTexture(context));
193 
194         mAssociatedStorage->verifyAssociatedImageValid(mAssociatedImageIndex, this);
195 
196         // CopySubResource from the Storage to the Staging texture
197         gl::Box region(0, 0, 0, mWidth, mHeight, mDepth);
198         ANGLE_TRY(mAssociatedStorage->copySubresourceLevel(
199             context, mStagingTexture, mStagingSubresource, mAssociatedImageIndex, region));
200         mRecoveredFromStorageCount += 1;
201 
202         // Reset all the recovery parameters, even if the texture storage association is broken.
203         disassociateStorage();
204 
205         markDirty();
206     }
207 
208     return angle::Result::Continue;
209 }
210 
disassociateStorage()211 void Image11::disassociateStorage()
212 {
213     if (mRecoverFromStorage)
214     {
215         // Make the texturestorage release the Image11 too
216         mAssociatedStorage->disassociateImage(mAssociatedImageIndex, this);
217 
218         mRecoverFromStorage   = false;
219         mAssociatedStorage    = nullptr;
220         mAssociatedImageIndex = gl::ImageIndex();
221     }
222 }
223 
redefine(gl::TextureType type,GLenum internalformat,const gl::Extents & size,bool forceRelease)224 bool Image11::redefine(gl::TextureType type,
225                        GLenum internalformat,
226                        const gl::Extents &size,
227                        bool forceRelease)
228 {
229     if (mWidth != size.width || mHeight != size.height || mDepth != size.depth ||
230         mInternalFormat != internalformat || forceRelease)
231     {
232         // End the association with the TextureStorage, since that data will be out of date.
233         // Also reset mRecoveredFromStorageCount since this Image is getting completely redefined.
234         disassociateStorage();
235         mRecoveredFromStorageCount = 0;
236 
237         mWidth          = size.width;
238         mHeight         = size.height;
239         mDepth          = size.depth;
240         mInternalFormat = internalformat;
241         mType           = type;
242 
243         // compute the d3d format that will be used
244         const d3d11::Format &formatInfo =
245             d3d11::Format::Get(internalformat, mRenderer->getRenderer11DeviceCaps());
246         mDXGIFormat = formatInfo.texFormat;
247         mRenderable = (formatInfo.rtvFormat != DXGI_FORMAT_UNKNOWN);
248 
249         releaseStagingTexture();
250         mDirty = (formatInfo.dataInitializerFunction != nullptr);
251 
252         return true;
253     }
254 
255     return false;
256 }
257 
getDXGIFormat() const258 DXGI_FORMAT Image11::getDXGIFormat() const
259 {
260     // this should only happen if the image hasn't been redefined first
261     // which would be a bug by the caller
262     ASSERT(mDXGIFormat != DXGI_FORMAT_UNKNOWN);
263 
264     return mDXGIFormat;
265 }
266 
267 // Store the pixel rectangle designated by xoffset,yoffset,width,height with pixels stored as
268 // format/type at input
269 // into the target pixel rectangle.
loadData(const gl::Context * context,const gl::Box & area,const gl::PixelUnpackState & unpack,GLenum type,const void * input,bool applySkipImages)270 angle::Result Image11::loadData(const gl::Context *context,
271                                 const gl::Box &area,
272                                 const gl::PixelUnpackState &unpack,
273                                 GLenum type,
274                                 const void *input,
275                                 bool applySkipImages)
276 {
277     Context11 *context11 = GetImplAs<Context11>(context);
278 
279     const gl::InternalFormat &formatInfo = gl::GetSizedInternalFormatInfo(mInternalFormat);
280     GLuint inputRowPitch                 = 0;
281     ANGLE_CHECK_GL_MATH(context11, formatInfo.computeRowPitch(type, area.width, unpack.alignment,
282                                                               unpack.rowLength, &inputRowPitch));
283     GLuint inputDepthPitch = 0;
284     ANGLE_CHECK_GL_MATH(context11, formatInfo.computeDepthPitch(area.height, unpack.imageHeight,
285                                                                 inputRowPitch, &inputDepthPitch));
286     GLuint inputSkipBytes = 0;
287     ANGLE_CHECK_GL_MATH(context11,
288                         formatInfo.computeSkipBytes(type, inputRowPitch, inputDepthPitch, unpack,
289                                                     applySkipImages, &inputSkipBytes));
290 
291     const d3d11::DXGIFormatSize &dxgiFormatInfo = d3d11::GetDXGIFormatSizeInfo(mDXGIFormat);
292     GLuint outputPixelSize                      = dxgiFormatInfo.pixelBytes;
293 
294     const d3d11::Format &d3dFormatInfo =
295         d3d11::Format::Get(mInternalFormat, mRenderer->getRenderer11DeviceCaps());
296     LoadImageFunction loadFunction = d3dFormatInfo.getLoadFunctions()(type).loadFunction;
297 
298     D3D11_MAPPED_SUBRESOURCE mappedImage;
299     ANGLE_TRY(map(context, D3D11_MAP_WRITE, &mappedImage));
300 
301     uint8_t *offsetMappedData = (static_cast<uint8_t *>(mappedImage.pData) +
302                                  (area.y * mappedImage.RowPitch + area.x * outputPixelSize +
303                                   area.z * mappedImage.DepthPitch));
304     loadFunction(context11->getImageLoadContext(), area.width, area.height, area.depth,
305                  static_cast<const uint8_t *>(input) + inputSkipBytes, inputRowPitch,
306                  inputDepthPitch, offsetMappedData, mappedImage.RowPitch, mappedImage.DepthPitch);
307 
308     unmap();
309 
310     return angle::Result::Continue;
311 }
312 
loadCompressedData(const gl::Context * context,const gl::Box & area,const void * input)313 angle::Result Image11::loadCompressedData(const gl::Context *context,
314                                           const gl::Box &area,
315                                           const void *input)
316 {
317     Context11 *context11 = GetImplAs<Context11>(context);
318 
319     const gl::InternalFormat &formatInfo = gl::GetSizedInternalFormatInfo(mInternalFormat);
320     GLuint inputRowPitch                 = 0;
321     ANGLE_CHECK_GL_MATH(
322         context11, formatInfo.computeRowPitch(GL_UNSIGNED_BYTE, area.width, 1, 0, &inputRowPitch));
323     GLuint inputDepthPitch = 0;
324     ANGLE_CHECK_GL_MATH(
325         context11, formatInfo.computeDepthPitch(area.height, 0, inputRowPitch, &inputDepthPitch));
326 
327     const d3d11::DXGIFormatSize &dxgiFormatInfo = d3d11::GetDXGIFormatSizeInfo(mDXGIFormat);
328     GLuint outputPixelSize                      = dxgiFormatInfo.pixelBytes;
329     GLuint outputBlockWidth                     = dxgiFormatInfo.blockWidth;
330     GLuint outputBlockHeight                    = dxgiFormatInfo.blockHeight;
331 
332     ASSERT(area.x % outputBlockWidth == 0);
333     ASSERT(area.y % outputBlockHeight == 0);
334 
335     const d3d11::Format &d3dFormatInfo =
336         d3d11::Format::Get(mInternalFormat, mRenderer->getRenderer11DeviceCaps());
337     LoadImageFunction loadFunction =
338         d3dFormatInfo.getLoadFunctions()(GL_UNSIGNED_BYTE).loadFunction;
339 
340     D3D11_MAPPED_SUBRESOURCE mappedImage;
341     ANGLE_TRY(map(context, D3D11_MAP_WRITE, &mappedImage));
342 
343     uint8_t *offsetMappedData =
344         static_cast<uint8_t *>(mappedImage.pData) +
345         ((area.y / outputBlockHeight) * mappedImage.RowPitch +
346          (area.x / outputBlockWidth) * outputPixelSize + area.z * mappedImage.DepthPitch);
347 
348     loadFunction(context11->getImageLoadContext(), area.width, area.height, area.depth,
349                  static_cast<const uint8_t *>(input), inputRowPitch, inputDepthPitch,
350                  offsetMappedData, mappedImage.RowPitch, mappedImage.DepthPitch);
351 
352     unmap();
353 
354     return angle::Result::Continue;
355 }
356 
copyFromTexStorage(const gl::Context * context,const gl::ImageIndex & imageIndex,TextureStorage * source)357 angle::Result Image11::copyFromTexStorage(const gl::Context *context,
358                                           const gl::ImageIndex &imageIndex,
359                                           TextureStorage *source)
360 {
361     TextureStorage11 *storage11 = GetAs<TextureStorage11>(source);
362 
363     const TextureHelper11 *textureHelper = nullptr;
364     ANGLE_TRY(storage11->getResource(context, &textureHelper));
365 
366     UINT subresourceIndex = 0;
367     ANGLE_TRY(storage11->getSubresourceIndex(context, imageIndex, &subresourceIndex));
368 
369     gl::Box sourceBox(0, 0, 0, mWidth, mHeight, mDepth);
370     return copyWithoutConversion(context, gl::Offset(), sourceBox, *textureHelper,
371                                  subresourceIndex);
372 }
373 
copyFromFramebuffer(const gl::Context * context,const gl::Offset & destOffset,const gl::Rectangle & sourceArea,const gl::Framebuffer * sourceFBO)374 angle::Result Image11::copyFromFramebuffer(const gl::Context *context,
375                                            const gl::Offset &destOffset,
376                                            const gl::Rectangle &sourceArea,
377                                            const gl::Framebuffer *sourceFBO)
378 {
379     Context11 *context11 = GetImplAs<Context11>(context);
380 
381     const gl::FramebufferAttachment *srcAttachment = sourceFBO->getReadColorAttachment();
382     ASSERT(srcAttachment);
383 
384     GLenum sourceInternalFormat = srcAttachment->getFormat().info->sizedInternalFormat;
385     const auto &d3d11Format =
386         d3d11::Format::Get(sourceInternalFormat, mRenderer->getRenderer11DeviceCaps());
387 
388     if (d3d11Format.texFormat == mDXGIFormat && sourceInternalFormat == mInternalFormat)
389     {
390         RenderTarget11 *rt11 = nullptr;
391         ANGLE_TRY(srcAttachment->getRenderTarget(context, 0, &rt11));
392         ASSERT(rt11->getTexture().get());
393 
394         TextureHelper11 textureHelper  = rt11->getTexture();
395         unsigned int sourceSubResource = rt11->getSubresourceIndex();
396 
397         const int z = textureHelper.is3D() ? srcAttachment->layer() : 0;
398         gl::Box sourceBox(sourceArea.x, sourceArea.y, z, sourceArea.width, sourceArea.height, 1);
399         return copyWithoutConversion(context, destOffset, sourceBox, textureHelper,
400                                      sourceSubResource);
401     }
402 
403     // This format requires conversion, so we must copy the texture to staging and manually convert
404     // via readPixels
405     D3D11_MAPPED_SUBRESOURCE mappedImage;
406     ANGLE_TRY(map(context, D3D11_MAP_WRITE, &mappedImage));
407 
408     // determine the offset coordinate into the destination buffer
409     const auto &dxgiFormatInfo = d3d11::GetDXGIFormatSizeInfo(mDXGIFormat);
410     GLsizei rowOffset          = dxgiFormatInfo.pixelBytes * destOffset.x;
411 
412     uint8_t *dataOffset = static_cast<uint8_t *>(mappedImage.pData) +
413                           mappedImage.RowPitch * destOffset.y + rowOffset +
414                           destOffset.z * mappedImage.DepthPitch;
415 
416     const gl::InternalFormat &destFormatInfo = gl::GetSizedInternalFormatInfo(mInternalFormat);
417     const auto &destD3D11Format =
418         d3d11::Format::Get(mInternalFormat, mRenderer->getRenderer11DeviceCaps());
419 
420     auto loadFunction    = destD3D11Format.getLoadFunctions()(destFormatInfo.type);
421     angle::Result result = angle::Result::Continue;
422     if (loadFunction.requiresConversion)
423     {
424         size_t bufferSize = destFormatInfo.pixelBytes * sourceArea.width * sourceArea.height;
425         angle::MemoryBuffer *memoryBuffer = nullptr;
426         result = mRenderer->getScratchMemoryBuffer(context11, bufferSize, &memoryBuffer);
427 
428         if (result == angle::Result::Continue)
429         {
430             GLuint memoryBufferRowPitch = destFormatInfo.pixelBytes * sourceArea.width;
431 
432             result = mRenderer->readFromAttachment(
433                 context, *srcAttachment, sourceArea, destFormatInfo.format, destFormatInfo.type,
434                 memoryBufferRowPitch, gl::PixelPackState(), memoryBuffer->data());
435 
436             loadFunction.loadFunction(context11->getImageLoadContext(), sourceArea.width,
437                                       sourceArea.height, 1, memoryBuffer->data(),
438                                       memoryBufferRowPitch, 0, dataOffset, mappedImage.RowPitch,
439                                       mappedImage.DepthPitch);
440         }
441     }
442     else
443     {
444         result = mRenderer->readFromAttachment(
445             context, *srcAttachment, sourceArea, destFormatInfo.format, destFormatInfo.type,
446             mappedImage.RowPitch, gl::PixelPackState(), dataOffset);
447     }
448 
449     unmap();
450     mDirty = true;
451 
452     return result;
453 }
454 
copyWithoutConversion(const gl::Context * context,const gl::Offset & destOffset,const gl::Box & sourceArea,const TextureHelper11 & textureHelper,UINT sourceSubResource)455 angle::Result Image11::copyWithoutConversion(const gl::Context *context,
456                                              const gl::Offset &destOffset,
457                                              const gl::Box &sourceArea,
458                                              const TextureHelper11 &textureHelper,
459                                              UINT sourceSubResource)
460 {
461     // No conversion needed-- use copyback fastpath
462     const TextureHelper11 *stagingTexture = nullptr;
463     unsigned int stagingSubresourceIndex  = 0;
464     ANGLE_TRY(getStagingTexture(context, &stagingTexture, &stagingSubresourceIndex));
465 
466     ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
467 
468     const gl::Extents &extents = textureHelper.getExtents();
469 
470     D3D11_BOX srcBox;
471     srcBox.left   = sourceArea.x;
472     srcBox.right  = sourceArea.x + sourceArea.width;
473     srcBox.top    = sourceArea.y;
474     srcBox.bottom = sourceArea.y + sourceArea.height;
475     srcBox.front  = sourceArea.z;
476     srcBox.back   = sourceArea.z + sourceArea.depth;
477 
478     if (textureHelper.is2D() && textureHelper.getSampleCount() > 1)
479     {
480         D3D11_TEXTURE2D_DESC resolveDesc;
481         resolveDesc.Width              = extents.width;
482         resolveDesc.Height             = extents.height;
483         resolveDesc.MipLevels          = 1;
484         resolveDesc.ArraySize          = 1;
485         resolveDesc.Format             = textureHelper.getFormat();
486         resolveDesc.SampleDesc.Count   = 1;
487         resolveDesc.SampleDesc.Quality = 0;
488         resolveDesc.Usage              = D3D11_USAGE_DEFAULT;
489         resolveDesc.BindFlags          = 0;
490         resolveDesc.CPUAccessFlags     = 0;
491         resolveDesc.MiscFlags          = 0;
492 
493         d3d11::Texture2D resolveTex;
494         ANGLE_TRY(
495             mRenderer->allocateResource(GetImplAs<Context11>(context), resolveDesc, &resolveTex));
496 
497         deviceContext->ResolveSubresource(resolveTex.get(), 0, textureHelper.get(),
498                                           sourceSubResource, textureHelper.getFormat());
499 
500         deviceContext->CopySubresourceRegion(stagingTexture->get(), stagingSubresourceIndex,
501                                              destOffset.x, destOffset.y, destOffset.z,
502                                              resolveTex.get(), 0, &srcBox);
503     }
504     else
505     {
506         deviceContext->CopySubresourceRegion(stagingTexture->get(), stagingSubresourceIndex,
507                                              destOffset.x, destOffset.y, destOffset.z,
508                                              textureHelper.get(), sourceSubResource, &srcBox);
509     }
510 
511     mDirty = true;
512     return angle::Result::Continue;
513 }
514 
getStagingTexture(const gl::Context * context,const TextureHelper11 ** outStagingTexture,unsigned int * outSubresourceIndex)515 angle::Result Image11::getStagingTexture(const gl::Context *context,
516                                          const TextureHelper11 **outStagingTexture,
517                                          unsigned int *outSubresourceIndex)
518 {
519     ANGLE_TRY(createStagingTexture(context));
520 
521     *outStagingTexture   = &mStagingTexture;
522     *outSubresourceIndex = mStagingSubresource;
523     return angle::Result::Continue;
524 }
525 
releaseStagingTexture()526 void Image11::releaseStagingTexture()
527 {
528     mStagingTexture.reset();
529     mStagingTextureSubresourceVerifier.reset();
530 }
531 
createStagingTexture(const gl::Context * context)532 angle::Result Image11::createStagingTexture(const gl::Context *context)
533 {
534     if (mStagingTexture.valid())
535     {
536         return angle::Result::Continue;
537     }
538 
539     ASSERT(mWidth > 0 && mHeight > 0 && mDepth > 0);
540 
541     const DXGI_FORMAT dxgiFormat = getDXGIFormat();
542     const auto &formatInfo =
543         d3d11::Format::Get(mInternalFormat, mRenderer->getRenderer11DeviceCaps());
544 
545     int lodOffset  = 1;
546     GLsizei width  = mWidth;
547     GLsizei height = mHeight;
548 
549     // adjust size if needed for compressed textures
550     d3d11::MakeValidSize(false, dxgiFormat, &width, &height, &lodOffset);
551 
552     Context11 *context11 = GetImplAs<Context11>(context);
553 
554     switch (mType)
555     {
556         case gl::TextureType::_3D:
557         {
558             D3D11_TEXTURE3D_DESC desc;
559             desc.Width          = width;
560             desc.Height         = height;
561             desc.Depth          = mDepth;
562             desc.MipLevels      = lodOffset + 1;
563             desc.Format         = dxgiFormat;
564             desc.Usage          = D3D11_USAGE_STAGING;
565             desc.BindFlags      = 0;
566             desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
567             desc.MiscFlags      = 0;
568 
569             if (formatInfo.dataInitializerFunction != nullptr)
570             {
571                 gl::TexLevelArray<D3D11_SUBRESOURCE_DATA> initialData;
572                 ANGLE_TRY(d3d11::GenerateInitialTextureData(
573                     context, mInternalFormat, mRenderer->getRenderer11DeviceCaps(), width, height,
574                     mDepth, lodOffset + 1, &initialData));
575 
576                 ANGLE_TRY(mRenderer->allocateTexture(context11, desc, formatInfo,
577                                                      initialData.data(), &mStagingTexture));
578             }
579             else
580             {
581                 ANGLE_TRY(
582                     mRenderer->allocateTexture(context11, desc, formatInfo, &mStagingTexture));
583             }
584 
585             mStagingTexture.setInternalName("Image11::StagingTexture3D");
586             mStagingSubresource = D3D11CalcSubresource(lodOffset, 0, lodOffset + 1);
587             mStagingTextureSubresourceVerifier.setDesc(desc);
588         }
589         break;
590 
591         case gl::TextureType::_2D:
592         case gl::TextureType::_2DArray:
593         case gl::TextureType::CubeMap:
594         {
595             D3D11_TEXTURE2D_DESC desc;
596             desc.Width              = width;
597             desc.Height             = height;
598             desc.MipLevels          = lodOffset + 1;
599             desc.ArraySize          = 1;
600             desc.Format             = dxgiFormat;
601             desc.SampleDesc.Count   = 1;
602             desc.SampleDesc.Quality = 0;
603             desc.Usage              = D3D11_USAGE_STAGING;
604             desc.BindFlags          = 0;
605             desc.CPUAccessFlags     = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
606             desc.MiscFlags          = 0;
607 
608             if (formatInfo.dataInitializerFunction != nullptr)
609             {
610                 gl::TexLevelArray<D3D11_SUBRESOURCE_DATA> initialData;
611                 ANGLE_TRY(d3d11::GenerateInitialTextureData(
612                     context, mInternalFormat, mRenderer->getRenderer11DeviceCaps(), width, height,
613                     1, lodOffset + 1, &initialData));
614 
615                 ANGLE_TRY(mRenderer->allocateTexture(context11, desc, formatInfo,
616                                                      initialData.data(), &mStagingTexture));
617             }
618             else
619             {
620                 ANGLE_TRY(
621                     mRenderer->allocateTexture(context11, desc, formatInfo, &mStagingTexture));
622             }
623 
624             mStagingTexture.setInternalName("Image11::StagingTexture2D");
625             mStagingSubresource = D3D11CalcSubresource(lodOffset, 0, lodOffset + 1);
626             mStagingTextureSubresourceVerifier.setDesc(desc);
627         }
628         break;
629 
630         default:
631             UNREACHABLE();
632     }
633 
634     mDirty = false;
635     return angle::Result::Continue;
636 }
637 
map(const gl::Context * context,D3D11_MAP mapType,D3D11_MAPPED_SUBRESOURCE * map)638 angle::Result Image11::map(const gl::Context *context,
639                            D3D11_MAP mapType,
640                            D3D11_MAPPED_SUBRESOURCE *map)
641 {
642     // We must recover from the TextureStorage if necessary, even for D3D11_MAP_WRITE.
643     ANGLE_TRY(recoverFromAssociatedStorage(context));
644 
645     const TextureHelper11 *stagingTexture = nullptr;
646     unsigned int subresourceIndex         = 0;
647     ANGLE_TRY(getStagingTexture(context, &stagingTexture, &subresourceIndex));
648 
649     ASSERT(stagingTexture && stagingTexture->valid());
650 
651     ANGLE_TRY(
652         mRenderer->mapResource(context, stagingTexture->get(), subresourceIndex, mapType, 0, map));
653 
654     if (!mStagingTextureSubresourceVerifier.wrap(mapType, map))
655     {
656         ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
657         deviceContext->Unmap(mStagingTexture.get(), mStagingSubresource);
658         Context11 *context11 = GetImplAs<Context11>(context);
659         context11->handleError(GL_OUT_OF_MEMORY,
660                                "Failed to allocate staging texture mapping verifier buffer.",
661                                __FILE__, ANGLE_FUNCTION, __LINE__);
662         return angle::Result::Stop;
663     }
664 
665     mDirty = true;
666 
667     return angle::Result::Continue;
668 }
669 
unmap()670 void Image11::unmap()
671 {
672     if (mStagingTexture.valid())
673     {
674         mStagingTextureSubresourceVerifier.unwrap();
675         ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
676         deviceContext->Unmap(mStagingTexture.get(), mStagingSubresource);
677     }
678 }
679 
680 }  // namespace rx
681