1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
|
/*
* Copyright 2019-2021 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include <mutex>
#include <deque>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include "TextureUploaderGL.hpp"
#include "ThreadSignal.hpp"
#include "GraphicsAccessories.hpp"
#include "Align.hpp"
namespace Diligent
{
namespace
{
class UploadBufferGL : public UploadBufferBase
{
public:
UploadBufferGL(IReferenceCounters* pRefCounters, const UploadBufferDesc& Desc) :
// clang-format off
UploadBufferBase{pRefCounters, Desc},
m_SubresourceOffsets(Desc.MipLevels * Desc.ArraySize + 1),
m_SubresourceStrides(Desc.MipLevels * Desc.ArraySize )
// clang-format on
{
TextureDesc TexDesc;
TexDesc.Format = Desc.Format;
TexDesc.Width = Desc.Width;
TexDesc.Height = Desc.Height;
TexDesc.Depth = Desc.Depth;
TexDesc.Type = Desc.ArraySize == 1 ? RESOURCE_DIM_TEX_2D : RESOURCE_DIM_TEX_2D_ARRAY;
Uint32 SubRes = 0;
for (Uint32 Slice = 0; Slice < Desc.ArraySize; ++Slice)
{
for (Uint32 Mip = 0; Mip < Desc.MipLevels; ++Mip)
{
auto MipProps = GetMipLevelProperties(TexDesc, Mip);
// Stride must be 32-bit aligned in OpenGL
auto RowStride = AlignUp(MipProps.RowSize, Uint32{4});
m_SubresourceStrides[SubRes] = RowStride;
auto MipSize = MipProps.StorageHeight * RowStride;
m_SubresourceOffsets[SubRes + 1] = m_SubresourceOffsets[SubRes] + MipSize;
++SubRes;
}
}
}
// http://en.cppreference.com/w/cpp/thread/condition_variable
void WaitForMap()
{
m_BufferMappedSignal.Wait();
}
void SignalMapped()
{
m_BufferMappedSignal.Trigger();
}
void SignalCopyScheduled()
{
m_CopyScheduledSignal.Trigger();
}
virtual void WaitForCopyScheduled() override final
{
m_CopyScheduledSignal.Wait();
}
bool DbgIsCopyScheduled() const { return m_CopyScheduledSignal.IsTriggered(); }
void SetDataPtr(Uint8* pBufferData)
{
for (Uint32 Slice = 0; Slice < m_Desc.ArraySize; ++Slice)
{
for (Uint32 Mip = 0; Mip < m_Desc.MipLevels; ++Mip)
{
SetMappedData(Mip, Slice, MappedTextureSubresource{pBufferData + GetOffset(Mip, Slice), GetStride(Mip, Slice), 0});
}
}
}
Uint32 GetOffset(Uint32 Mip, Uint32 Slice)
{
VERIFY_EXPR(Mip < m_Desc.MipLevels && Slice < m_Desc.ArraySize);
return m_SubresourceOffsets[m_Desc.MipLevels * Slice + Mip];
}
void Reset()
{
m_BufferMappedSignal.Reset();
m_CopyScheduledSignal.Reset();
UploadBufferBase::Reset();
}
Uint32 GetTotalSize() const
{
return m_SubresourceOffsets.back();
}
private:
Uint32 GetStride(Uint32 Mip, Uint32 Slice)
{
VERIFY_EXPR(Mip < m_Desc.MipLevels && Slice < m_Desc.ArraySize);
return m_SubresourceStrides[m_Desc.MipLevels * Slice + Mip];
}
friend TextureUploaderGL;
ThreadingTools::Signal m_BufferMappedSignal;
ThreadingTools::Signal m_CopyScheduledSignal;
RefCntAutoPtr<IBuffer> m_pStagingBuffer;
std::vector<Uint32> m_SubresourceOffsets;
std::vector<Uint32> m_SubresourceStrides;
};
} // namespace
struct TextureUploaderGL::InternalData
{
void SwapMapQueues()
{
std::lock_guard<std::mutex> QueueLock(m_PendingOperationsMtx);
m_PendingOperations.swap(m_InWorkOperations);
}
void EnqueCopy(UploadBufferGL* pUploadBuffer, ITexture* pDstTexture, Uint32 dstSlice, Uint32 dstMip)
{
std::lock_guard<std::mutex> QueueLock(m_PendingOperationsMtx);
m_PendingOperations.emplace_back(PendingBufferOperation::Operation::Copy, pUploadBuffer, pDstTexture, dstSlice, dstMip);
}
void EnqueMap(UploadBufferGL* pUploadBuffer)
{
std::lock_guard<std::mutex> QueueLock(m_PendingOperationsMtx);
m_PendingOperations.emplace_back(PendingBufferOperation::Operation::Map, pUploadBuffer);
}
struct PendingBufferOperation
{
enum Operation
{
Map,
Copy
} operation;
RefCntAutoPtr<UploadBufferGL> pUploadBuffer;
RefCntAutoPtr<ITexture> pDstTexture;
Uint32 DstSlice = 0;
Uint32 DstMip = 0;
// clang-format off
PendingBufferOperation(Operation op, UploadBufferGL* pBuff) :
operation {op },
pUploadBuffer{pBuff}
{}
PendingBufferOperation(Operation op, UploadBufferGL* pBuff, ITexture *pDstTex, Uint32 dstSlice, Uint32 dstMip) :
operation {op },
pUploadBuffer{pBuff },
pDstTexture {pDstTex },
DstSlice {dstSlice},
DstMip {dstMip }
{}
// clang-format on
};
void Execute(IRenderDevice* pDevice,
IDeviceContext* pContext,
PendingBufferOperation& OperationInfo);
std::mutex m_PendingOperationsMtx;
std::vector<PendingBufferOperation> m_PendingOperations;
std::vector<PendingBufferOperation> m_InWorkOperations;
std::mutex m_UploadBuffCacheMtx;
std::unordered_map<UploadBufferDesc, std::deque<RefCntAutoPtr<UploadBufferGL>>> m_UploadBufferCache;
};
TextureUploaderGL::TextureUploaderGL(IReferenceCounters* pRefCounters, IRenderDevice* pDevice, const TextureUploaderDesc Desc) :
TextureUploaderBase{pRefCounters, pDevice, Desc},
m_pInternalData{new InternalData{}}
{
}
TextureUploaderGL::~TextureUploaderGL()
{
auto Stats = TextureUploaderGL::GetStats();
if (Stats.NumPendingOperations != 0)
{
LOG_WARNING_MESSAGE("TextureUploaderGL::~TextureUploaderGL(): there ", (Stats.NumPendingOperations > 1 ? "are " : "is "),
Stats.NumPendingOperations, (Stats.NumPendingOperations > 1 ? " pending operations" : " pending operation"),
" in the queue. If other threads wait for ", (Stats.NumPendingOperations > 1 ? "these operations" : "this operation"),
", they may deadlock.");
}
for (auto BuffQueueIt : m_pInternalData->m_UploadBufferCache)
{
if (BuffQueueIt.second.size())
{
const auto& desc = BuffQueueIt.first;
auto& FmtInfo = m_pDevice->GetTextureFormatInfo(desc.Format);
LOG_INFO_MESSAGE("TextureUploaderGL: releasing ", BuffQueueIt.second.size(), ' ', desc.Width, 'x',
desc.Height, 'x', desc.Depth, ' ', FmtInfo.Name, " upload buffer", (BuffQueueIt.second.size() != 1 ? "s" : ""));
}
}
}
void TextureUploaderGL::RenderThreadUpdate(IDeviceContext* pContext)
{
m_pInternalData->SwapMapQueues();
if (!m_pInternalData->m_InWorkOperations.empty())
{
for (auto& OperationInfo : m_pInternalData->m_InWorkOperations)
{
m_pInternalData->Execute(m_pDevice, pContext, OperationInfo);
}
m_pInternalData->m_InWorkOperations.clear();
}
}
void TextureUploaderGL::InternalData::Execute(IRenderDevice* pDevice,
IDeviceContext* pContext,
PendingBufferOperation& OperationInfo)
{
auto& pBuffer = OperationInfo.pUploadBuffer;
const auto& UploadBuffDesc = pBuffer->GetDesc();
switch (OperationInfo.operation)
{
case InternalData::PendingBufferOperation::Map:
{
if (pBuffer->m_pStagingBuffer == nullptr)
{
BufferDesc BuffDesc;
BuffDesc.Name = "Staging buffer for UploadBufferGL";
BuffDesc.CPUAccessFlags = CPU_ACCESS_WRITE;
BuffDesc.Usage = USAGE_STAGING;
BuffDesc.uiSizeInBytes = pBuffer->GetTotalSize();
RefCntAutoPtr<IBuffer> pStagingBuffer;
pDevice->CreateBuffer(BuffDesc, nullptr, &pBuffer->m_pStagingBuffer);
}
PVoid CpuAddress = nullptr;
pContext->MapBuffer(pBuffer->m_pStagingBuffer, MAP_WRITE, MAP_FLAG_DISCARD, CpuAddress);
pBuffer->SetDataPtr(reinterpret_cast<Uint8*>(CpuAddress));
pBuffer->SignalMapped();
}
break;
case InternalData::PendingBufferOperation::Copy:
{
const auto& TexDesc = OperationInfo.pDstTexture->GetDesc();
pContext->UnmapBuffer(pBuffer->m_pStagingBuffer, MAP_WRITE);
for (Uint32 Slice = 0; Slice < UploadBuffDesc.ArraySize; ++Slice)
{
for (Uint32 Mip = 0; Mip < UploadBuffDesc.MipLevels; ++Mip)
{
auto SrcOffset = pBuffer->GetOffset(Mip, Slice);
auto SrcStride = pBuffer->GetMappedData(Mip, Slice).Stride;
TextureSubResData SubResData(pBuffer->m_pStagingBuffer, SrcOffset, SrcStride);
auto MipLevelProps = GetMipLevelProperties(TexDesc, OperationInfo.DstMip + Mip);
Box DstBox;
DstBox.MaxX = MipLevelProps.LogicalWidth;
DstBox.MaxY = MipLevelProps.LogicalHeight;
pContext->UpdateTexture(OperationInfo.pDstTexture, OperationInfo.DstMip + Mip, OperationInfo.DstSlice + Slice, DstBox,
SubResData, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
}
}
pBuffer->SignalCopyScheduled();
}
break;
}
}
void TextureUploaderGL::AllocateUploadBuffer(IDeviceContext* pContext,
const UploadBufferDesc& Desc,
IUploadBuffer** ppBuffer)
{
*ppBuffer = nullptr;
RefCntAutoPtr<UploadBufferGL> pUploadBuffer;
{
std::lock_guard<std::mutex> CacheLock(m_pInternalData->m_UploadBuffCacheMtx);
auto& Cache = m_pInternalData->m_UploadBufferCache;
if (!Cache.empty())
{
auto DequeIt = Cache.find(Desc);
if (DequeIt != Cache.end())
{
auto& Deque = DequeIt->second;
if (!Deque.empty())
{
pUploadBuffer.Attach(Deque.front().Detach());
Deque.pop_front();
}
}
}
}
if (!pUploadBuffer)
{
pUploadBuffer = MakeNewRCObj<UploadBufferGL>()(Desc);
LOG_INFO_MESSAGE("TextureUploaderGL: created upload buffer for ", Desc.Width, 'x', Desc.Height, 'x',
Desc.Depth, ' ', Desc.MipLevels, "-mip ", Desc.ArraySize, "-slice ",
m_pDevice->GetTextureFormatInfo(Desc.Format).Name, " texture");
}
if (pContext != nullptr)
{
// Render thread
InternalData::PendingBufferOperation MapOp{InternalData::PendingBufferOperation::Operation::Map, pUploadBuffer};
m_pInternalData->Execute(m_pDevice, pContext, MapOp);
}
else
{
// Worker thread
m_pInternalData->EnqueMap(pUploadBuffer);
pUploadBuffer->WaitForMap();
}
*ppBuffer = pUploadBuffer.Detach();
}
void TextureUploaderGL::ScheduleGPUCopy(IDeviceContext* pContext,
ITexture* pDstTexture,
Uint32 ArraySlice,
Uint32 MipLevel,
IUploadBuffer* pUploadBuffer)
{
auto* pUploadBufferGL = ValidatedCast<UploadBufferGL>(pUploadBuffer);
if (pContext != nullptr)
{
// Render thread
InternalData::PendingBufferOperation CopyOp //
{
InternalData::PendingBufferOperation::Operation::Copy,
pUploadBufferGL,
pDstTexture,
ArraySlice,
MipLevel //
};
m_pInternalData->Execute(m_pDevice, pContext, CopyOp);
}
else
{
// Worker thread
m_pInternalData->EnqueCopy(pUploadBufferGL, pDstTexture, ArraySlice, MipLevel);
}
}
void TextureUploaderGL::RecycleBuffer(IUploadBuffer* pUploadBuffer)
{
auto* pUploadBufferGL = ValidatedCast<UploadBufferGL>(pUploadBuffer);
VERIFY(pUploadBufferGL->DbgIsCopyScheduled(), "Upload buffer must be recycled only after copy operation has been scheduled on the GPU");
pUploadBufferGL->Reset();
std::lock_guard<std::mutex> CacheLock(m_pInternalData->m_UploadBuffCacheMtx);
auto& Cache = m_pInternalData->m_UploadBufferCache;
auto& Deque = Cache[pUploadBufferGL->GetDesc()];
Deque.emplace_back(pUploadBufferGL);
}
TextureUploaderStats TextureUploaderGL::GetStats()
{
TextureUploaderStats Stats;
std::lock_guard<std::mutex> QueueLock(m_pInternalData->m_PendingOperationsMtx);
Stats.NumPendingOperations = static_cast<Uint32>(m_pInternalData->m_PendingOperations.size());
return Stats;
}
} // namespace Diligent
|