summaryrefslogtreecommitdiffstats
path: root/Graphics/GraphicsEngine/include/RenderDeviceBase.hpp
blob: 110e2bc26055b674accaa1f4e891fe5600a7c437 (plain)
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
/*
 *  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.
 */

#pragma once

/// \file
/// Implementation of the Diligent::RenderDeviceBase template class and related structures

#include "RenderDevice.h"
#include "DeviceObjectBase.hpp"
#include "Defines.h"
#include "ResourceMappingImpl.hpp"
#include "StateObjectsRegistry.hpp"
#include "HashUtils.hpp"
#include "ObjectBase.hpp"
#include "DeviceContext.h"
#include "SwapChain.h"
#include "GraphicsAccessories.hpp"
#include "FixedBlockMemoryAllocator.hpp"
#include "EngineMemory.h"
#include "STDAllocator.hpp"

namespace std
{
/// Hash function specialization for Diligent::SamplerDesc structure.
template <>
struct hash<Diligent::SamplerDesc>
{
    size_t operator()(const Diligent::SamplerDesc& SamDesc) const
    {
        // Sampler name is ignored in comparison operator
        // and should not be hashed
        return Diligent::ComputeHash( // SamDesc.Name,
            static_cast<int>(SamDesc.MinFilter),
            static_cast<int>(SamDesc.MagFilter),
            static_cast<int>(SamDesc.MipFilter),
            static_cast<int>(SamDesc.AddressU),
            static_cast<int>(SamDesc.AddressV),
            static_cast<int>(SamDesc.AddressW),
            SamDesc.MipLODBias,
            SamDesc.MaxAnisotropy,
            static_cast<int>(SamDesc.ComparisonFunc),
            SamDesc.BorderColor[0],
            SamDesc.BorderColor[1],
            SamDesc.BorderColor[2],
            SamDesc.BorderColor[3],
            SamDesc.MinLOD, SamDesc.MaxLOD);
    }
};

/// Hash function specialization for Diligent::StencilOpDesc structure.
template <>
struct hash<Diligent::StencilOpDesc>
{
    size_t operator()(const Diligent::StencilOpDesc& StOpDesc) const
    {
        return Diligent::ComputeHash(static_cast<int>(StOpDesc.StencilFailOp),
                                     static_cast<int>(StOpDesc.StencilDepthFailOp),
                                     static_cast<int>(StOpDesc.StencilPassOp),
                                     static_cast<int>(StOpDesc.StencilFunc));
    }
};

/// Hash function specialization for Diligent::DepthStencilStateDesc structure.
template <>
struct hash<Diligent::DepthStencilStateDesc>
{
    size_t operator()(const Diligent::DepthStencilStateDesc& DepthStencilDesc) const
    {
        return Diligent::ComputeHash(DepthStencilDesc.DepthEnable,
                                     DepthStencilDesc.DepthWriteEnable,
                                     static_cast<int>(DepthStencilDesc.DepthFunc),
                                     DepthStencilDesc.StencilEnable,
                                     DepthStencilDesc.StencilReadMask,
                                     DepthStencilDesc.StencilWriteMask,
                                     DepthStencilDesc.FrontFace,
                                     DepthStencilDesc.BackFace);
    }
};

/// Hash function specialization for Diligent::RasterizerStateDesc structure.
template <>
struct hash<Diligent::RasterizerStateDesc>
{
    size_t operator()(const Diligent::RasterizerStateDesc& RasterizerDesc) const
    {
        return Diligent::ComputeHash(static_cast<int>(RasterizerDesc.FillMode),
                                     static_cast<int>(RasterizerDesc.CullMode),
                                     RasterizerDesc.FrontCounterClockwise,
                                     RasterizerDesc.DepthBias,
                                     RasterizerDesc.DepthBiasClamp,
                                     RasterizerDesc.SlopeScaledDepthBias,
                                     RasterizerDesc.DepthClipEnable,
                                     RasterizerDesc.ScissorEnable,
                                     RasterizerDesc.AntialiasedLineEnable);
    }
};

/// Hash function specialization for Diligent::BlendStateDesc structure.
template <>
struct hash<Diligent::BlendStateDesc>
{
    size_t operator()(const Diligent::BlendStateDesc& BSDesc) const
    {
        std::size_t Seed = 0;
        for (size_t i = 0; i < Diligent::MAX_RENDER_TARGETS; ++i)
        {
            const auto& rt = BSDesc.RenderTargets[i];
            Diligent::HashCombine(Seed,
                                  rt.BlendEnable,
                                  static_cast<int>(rt.SrcBlend),
                                  static_cast<int>(rt.DestBlend),
                                  static_cast<int>(rt.BlendOp),
                                  static_cast<int>(rt.SrcBlendAlpha),
                                  static_cast<int>(rt.DestBlendAlpha),
                                  static_cast<int>(rt.BlendOpAlpha),
                                  rt.RenderTargetWriteMask);
        }
        Diligent::HashCombine(Seed,
                              BSDesc.AlphaToCoverageEnable,
                              BSDesc.IndependentBlendEnable);
        return Seed;
    }
};


/// Hash function specialization for Diligent::TextureViewDesc structure.
template <>
struct hash<Diligent::TextureViewDesc>
{
    size_t operator()(const Diligent::TextureViewDesc& TexViewDesc) const
    {
        std::size_t Seed = 0;
        Diligent::HashCombine(Seed,
                              static_cast<Diligent::Int32>(TexViewDesc.ViewType),
                              static_cast<Diligent::Int32>(TexViewDesc.TextureDim),
                              static_cast<Diligent::Int32>(TexViewDesc.Format),
                              TexViewDesc.MostDetailedMip,
                              TexViewDesc.NumMipLevels,
                              TexViewDesc.FirstArraySlice,
                              TexViewDesc.NumArraySlices,
                              static_cast<Diligent::Uint32>(TexViewDesc.AccessFlags),
                              static_cast<Diligent::Uint32>(TexViewDesc.Flags));
        return Seed;
    }
};
} // namespace std

namespace Diligent
{

/// Base implementation of a render device

/// \tparam EngineImplTraits - Engine implementation type traits.
///
/// \warning    Render device must *NOT* hold strong references to any object it creates
///             to avoid cyclic dependencies. Device context, swap chain and all object
///             the device creates keep strong reference to the device.
///             Device only holds weak reference to the immediate context.
template <typename EngineImplTraits>
class RenderDeviceBase : public ObjectBase<typename EngineImplTraits::RenderDeviceInterface>
{
public:
    using BaseInterface = typename EngineImplTraits::RenderDeviceInterface;
    using TObjectBase   = ObjectBase<BaseInterface>;

    using RenderDeviceImplType              = typename EngineImplTraits::RenderDeviceImplType;
    using PipelineStateImplType             = typename EngineImplTraits::PipelineStateImplType;
    using ShaderResourceBindingImplType     = typename EngineImplTraits::ShaderResourceBindingImplType;
    using BufferImplType                    = typename EngineImplTraits::BufferImplType;
    using BufferViewImplType                = typename EngineImplTraits::BufferViewImplType;
    using TextureImplType                   = typename EngineImplTraits::TextureImplType;
    using TextureViewImplType               = typename EngineImplTraits::TextureViewImplType;
    using ShaderImplType                    = typename EngineImplTraits::ShaderImplType;
    using SamplerImplType                   = typename EngineImplTraits::SamplerImplType;
    using FenceImplType                     = typename EngineImplTraits::FenceImplType;
    using QueryImplType                     = typename EngineImplTraits::QueryImplType;
    using RenderPassImplType                = typename EngineImplTraits::RenderPassImplType;
    using FramebufferImplType               = typename EngineImplTraits::FramebufferImplType;
    using BottomLevelASImplType             = typename EngineImplTraits::BottomLevelASImplType;
    using TopLevelASImplType                = typename EngineImplTraits::TopLevelASImplType;
    using ShaderBindingTableImplType        = typename EngineImplTraits::ShaderBindingTableImplType;
    using PipelineResourceSignatureImplType = typename EngineImplTraits::PipelineResourceSignatureImplType;

    /// \param pRefCounters        - Reference counters object that controls the lifetime of this render device
    /// \param RawMemAllocator     - Allocator that will be used to allocate memory for all device objects (including render device itself)
    /// \param pEngineFactory      - Engine factory that was used to create this device
    /// \param NumDeferredContexts - The number of deferred device contexts
    ///
    /// \remarks Render device uses fixed block allocators (see FixedBlockMemoryAllocator) to allocate memory for
    ///          device objects. The object sizes provided to constructor are used to initialize the allocators.
    RenderDeviceBase(IReferenceCounters* pRefCounters,
                     IMemoryAllocator&   RawMemAllocator,
                     IEngineFactory*     pEngineFactory,
                     Uint32              NumDeferredContexts) :
        // clang-format off
        TObjectBase             {pRefCounters},
        m_pEngineFactory        {pEngineFactory},
        m_SamplersRegistry      {RawMemAllocator, "sampler"},
        m_TextureFormatsInfo    (TEX_FORMAT_NUM_FORMATS, TextureFormatInfoExt(), STD_ALLOCATOR_RAW_MEM(TextureFormatInfoExt, RawMemAllocator, "Allocator for vector<TextureFormatInfoExt>")),
        m_TexFmtInfoInitFlags   (TEX_FORMAT_NUM_FORMATS, false, STD_ALLOCATOR_RAW_MEM(bool, RawMemAllocator, "Allocator for vector<bool>")),
        m_wpDeferredContexts    (NumDeferredContexts, RefCntWeakPtr<IDeviceContext>(), STD_ALLOCATOR_RAW_MEM(RefCntWeakPtr<IDeviceContext>, RawMemAllocator, "Allocator for vector< RefCntWeakPtr<IDeviceContext> >")),
        m_RawMemAllocator       {RawMemAllocator},
        m_TexObjAllocator       {RawMemAllocator, sizeof(TextureImplType),                    64},
        m_TexViewObjAllocator   {RawMemAllocator, sizeof(TextureViewImplType),                64},
        m_BufObjAllocator       {RawMemAllocator, sizeof(BufferImplType),                    128},
        m_BuffViewObjAllocator  {RawMemAllocator, sizeof(BufferViewImplType),                128},
        m_ShaderObjAllocator    {RawMemAllocator, sizeof(ShaderImplType),                     32},
        m_SamplerObjAllocator   {RawMemAllocator, sizeof(SamplerImplType),                    32},
        m_PSOAllocator          {RawMemAllocator, sizeof(PipelineStateImplType),             128},
        m_SRBAllocator          {RawMemAllocator, sizeof(ShaderResourceBindingImplType),    1024},
        m_ResMappingAllocator   {RawMemAllocator, sizeof(ResourceMappingImpl),                16},
        m_FenceAllocator        {RawMemAllocator, sizeof(FenceImplType),                      16},
        m_QueryAllocator        {RawMemAllocator, sizeof(QueryImplType),                      16},
        m_RenderPassAllocator   {RawMemAllocator, sizeof(RenderPassImplType),                 16},
        m_FramebufferAllocator  {RawMemAllocator, sizeof(FramebufferImplType),                16},
        m_BLASAllocator         {RawMemAllocator, sizeof(BottomLevelASImplType),              16},
        m_TLASAllocator         {RawMemAllocator, sizeof(TopLevelASImplType),                 16},
        m_SBTAllocator          {RawMemAllocator, sizeof(ShaderBindingTableImplType),         16},
        m_PipeResSignAllocator  {RawMemAllocator, sizeof(PipelineResourceSignatureImplType), 128},
        m_DeviceProperties      {}
    // clang-format on
    {
        // Initialize texture format info
        for (Uint32 Fmt = TEX_FORMAT_UNKNOWN; Fmt < TEX_FORMAT_NUM_FORMATS; ++Fmt)
            static_cast<TextureFormatAttribs&>(m_TextureFormatsInfo[Fmt]) = GetTextureFormatAttribs(static_cast<TEXTURE_FORMAT>(Fmt));

        // https://msdn.microsoft.com/en-us/library/windows/desktop/ff471325(v=vs.85).aspx
        TEXTURE_FORMAT FilterableFormats[] =
            {
                TEX_FORMAT_RGBA32_FLOAT, // OpenGL ES3.1 does not require this format to be filterable
                TEX_FORMAT_RGBA16_FLOAT,
                TEX_FORMAT_RGBA16_UNORM,
                TEX_FORMAT_RGBA16_SNORM,
                TEX_FORMAT_RG32_FLOAT, // OpenGL ES3.1 does not require this format to be filterable
                TEX_FORMAT_R32_FLOAT_X8X24_TYPELESS,
                //TEX_FORMAT_R10G10B10A2_UNORM,
                TEX_FORMAT_R11G11B10_FLOAT,
                TEX_FORMAT_RGBA8_UNORM,
                TEX_FORMAT_RGBA8_UNORM_SRGB,
                TEX_FORMAT_RGBA8_SNORM,
                TEX_FORMAT_RG16_FLOAT,
                TEX_FORMAT_RG16_UNORM,
                TEX_FORMAT_RG16_SNORM,
                TEX_FORMAT_R32_FLOAT, // OpenGL ES3.1 does not require this format to be filterable
                TEX_FORMAT_R24_UNORM_X8_TYPELESS,
                TEX_FORMAT_RG8_UNORM,
                TEX_FORMAT_RG8_SNORM,
                TEX_FORMAT_R16_FLOAT,
                TEX_FORMAT_R16_UNORM,
                TEX_FORMAT_R16_SNORM,
                TEX_FORMAT_R8_UNORM,
                TEX_FORMAT_R8_SNORM,
                TEX_FORMAT_A8_UNORM,
                TEX_FORMAT_RGB9E5_SHAREDEXP,
                TEX_FORMAT_RG8_B8G8_UNORM,
                TEX_FORMAT_G8R8_G8B8_UNORM,
                TEX_FORMAT_BC1_UNORM,
                TEX_FORMAT_BC1_UNORM_SRGB,
                TEX_FORMAT_BC2_UNORM,
                TEX_FORMAT_BC2_UNORM_SRGB,
                TEX_FORMAT_BC3_UNORM,
                TEX_FORMAT_BC3_UNORM_SRGB,
                TEX_FORMAT_BC4_UNORM,
                TEX_FORMAT_BC4_SNORM,
                TEX_FORMAT_BC5_UNORM,
                TEX_FORMAT_BC5_SNORM,
                TEX_FORMAT_B5G6R5_UNORM};
        for (Uint32 fmt = 0; fmt < _countof(FilterableFormats); ++fmt)
            m_TextureFormatsInfo[FilterableFormats[fmt]].Filterable = true;
    }

    ~RenderDeviceBase()
    {
    }

    IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_RenderDevice, ObjectBase<BaseInterface>)

    // It is important to have final implementation of Release() method to avoid
    // virtual calls
    inline virtual ReferenceCounterValueType DILIGENT_CALL_TYPE Release() override final
    {
        return TObjectBase::Release();
    }

    /// Implementation of IRenderDevice::CreateResourceMapping().
    virtual void DILIGENT_CALL_TYPE CreateResourceMapping(const ResourceMappingDesc& MappingDesc, IResourceMapping** ppMapping) override final
    {
        DEV_CHECK_ERR(ppMapping != nullptr, "Null pointer provided");
        if (ppMapping == nullptr)
            return;
        DEV_CHECK_ERR(*ppMapping == nullptr, "Overwriting reference to existing object may cause memory leaks");

        auto* pResourceMapping{NEW_RC_OBJ(m_ResMappingAllocator, "ResourceMappingImpl instance", ResourceMappingImpl)(GetRawAllocator())};
        pResourceMapping->QueryInterface(IID_ResourceMapping, reinterpret_cast<IObject**>(ppMapping));
        if (MappingDesc.pEntries)
        {
            for (auto* pEntry = MappingDesc.pEntries; pEntry->Name && pEntry->pObject; ++pEntry)
            {
                (*ppMapping)->AddResourceArray(pEntry->Name, pEntry->ArrayIndex, &pEntry->pObject, 1, true);
            }
        }
    }


    /// Implementation of IRenderDevice::GetDeviceCaps().
    virtual const DeviceCaps& DILIGENT_CALL_TYPE GetDeviceCaps() const override final
    {
        return m_DeviceCaps;
    }

    /// Implementation of IRenderDevice::GetDeviceProperties().
    virtual const DeviceProperties& DILIGENT_CALL_TYPE GetDeviceProperties() const override final
    {
        return m_DeviceProperties;
    }

    /// Implementation of IRenderDevice::GetTextureFormatInfo().
    virtual const TextureFormatInfo& DILIGENT_CALL_TYPE GetTextureFormatInfo(TEXTURE_FORMAT TexFormat) override final
    {
        VERIFY(TexFormat >= TEX_FORMAT_UNKNOWN && TexFormat < TEX_FORMAT_NUM_FORMATS, "Texture format out of range");
        const auto& TexFmtInfo = m_TextureFormatsInfo[TexFormat];
        VERIFY(TexFmtInfo.Format == TexFormat, "Sanity check failed");
        return TexFmtInfo;
    }

    /// Implementation of IRenderDevice::GetTextureFormatInfoExt().
    virtual const TextureFormatInfoExt& DILIGENT_CALL_TYPE GetTextureFormatInfoExt(TEXTURE_FORMAT TexFormat) override final
    {
        VERIFY(TexFormat >= TEX_FORMAT_UNKNOWN && TexFormat < TEX_FORMAT_NUM_FORMATS, "Texture format out of range");
        const auto& TexFmtInfo = m_TextureFormatsInfo[TexFormat];
        VERIFY(TexFmtInfo.Format == TexFormat, "Sanity check failed");
        if (!m_TexFmtInfoInitFlags[TexFormat])
        {
            if (TexFmtInfo.Supported)
                TestTextureFormat(TexFormat);
            m_TexFmtInfoInitFlags[TexFormat] = true;
        }
        return TexFmtInfo;
    }

    virtual IEngineFactory* DILIGENT_CALL_TYPE GetEngineFactory() const override final
    {
        return m_pEngineFactory.RawPtr<IEngineFactory>();
    }

    StateObjectsRegistry<SamplerDesc>& GetSamplerRegistry() { return m_SamplersRegistry; }

    /// Set weak reference to the immediate context
    void SetImmediateContext(IDeviceContext* pImmediateContext)
    {
        VERIFY(m_wpImmediateContext.Lock() == nullptr, "Immediate context has already been set");
        m_wpImmediateContext = pImmediateContext;
    }

    /// Set weak reference to the deferred context
    void SetDeferredContext(size_t Ctx, IDeviceContext* pDeferredCtx)
    {
        VERIFY(m_wpDeferredContexts[Ctx].Lock() == nullptr, "Deferred context has already been set");
        m_wpDeferredContexts[Ctx] = pDeferredCtx;
    }

    /// Returns number of deferred contexts
    size_t GetNumDeferredContexts() const
    {
        return m_wpDeferredContexts.size();
    }

    RefCntAutoPtr<IDeviceContext> GetImmediateContext() { return m_wpImmediateContext.Lock(); }
    RefCntAutoPtr<IDeviceContext> GetDeferredContext(size_t Ctx) { return m_wpDeferredContexts[Ctx].Lock(); }

    FixedBlockMemoryAllocator& GetTexViewObjAllocator() { return m_TexViewObjAllocator; }
    FixedBlockMemoryAllocator& GetBuffViewObjAllocator() { return m_BuffViewObjAllocator; }
    FixedBlockMemoryAllocator& GetSRBAllocator() { return m_SRBAllocator; }

protected:
    virtual void TestTextureFormat(TEXTURE_FORMAT TexFormat) = 0;

    /// Helper template function to facilitate device object creation

    /// \tparam ObjectType            - The type of the object being created (IBuffer, ITexture, etc.).
    /// \tparam ObjectDescType        - The type of the object description structure (BufferDesc, TextureDesc, etc.).
    /// \tparam ObjectConstructorType - The type of the function that constructs the object.
    ///
    /// \param ObjectTypeName      - String name of the object type ("buffer", "texture", etc.).
    /// \param Desc                - Object description.
    /// \param ppObject            - Memory address where the pointer to the created object will be stored.
    /// \param ConstructObject     - Function that constructs the object.
    template <typename ObjectType, typename ObjectDescType, typename ObjectConstructorType>
    void CreateDeviceObject(const Char*           ObjectTypeName,
                            const ObjectDescType& Desc,
                            ObjectType**          ppObject,
                            ObjectConstructorType ConstructObject)
    {
        DEV_CHECK_ERR(ppObject != nullptr, "Null pointer provided");
        if (!ppObject)
            return;

        DEV_CHECK_ERR(*ppObject == nullptr, "Overwriting reference to existing object may cause memory leaks");
        // Do not release *ppObject here!
        // Should this happen, RefCntAutoPtr<> will take care of this!
        //if( *ppObject )
        //{
        //    (*ppObject)->Release();
        //    *ppObject = nullptr;
        //}

        *ppObject = nullptr;

        try
        {
            ConstructObject();
        }
        catch (...)
        {
            VERIFY(*ppObject == nullptr, "Object was created despite error");
            if (*ppObject)
            {
                (*ppObject)->Release();
                *ppObject = nullptr;
            }
            const auto ObjectDescString = GetObjectDescString(Desc);
            if (!ObjectDescString.empty())
            {
                LOG_ERROR("Failed to create ", ObjectTypeName, " object '", (Desc.Name ? Desc.Name : ""), "'\n", ObjectDescString);
            }
            else
            {
                LOG_ERROR("Failed to create ", ObjectTypeName, " object '", (Desc.Name ? Desc.Name : ""), "'");
            }
        }
    }

    template <typename PSOCreateInfoType, typename... ExtraArgsType>
    void CreatePipelineStateImpl(IPipelineState** ppPipelineState, const PSOCreateInfoType& PSOCreateInfo, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("Pipeline State", PSOCreateInfo.PSODesc, ppPipelineState,
                           [&]() //
                           {
                               auto* pPipelineStateImpl{NEW_RC_OBJ(m_PSOAllocator, "Pipeline State instance", PipelineStateImplType)(static_cast<RenderDeviceImplType*>(this), PSOCreateInfo, ExtraArgs...)};
                               pPipelineStateImpl->QueryInterface(IID_PipelineState, reinterpret_cast<IObject**>(ppPipelineState));
                           });
    }

    template <typename... ExtraArgsType>
    void CreateBufferImpl(IBuffer** ppBuffer, const BufferDesc& BuffDesc, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("Buffer", BuffDesc, ppBuffer,
                           [&]() //
                           {
                               auto* pBufferImpl{NEW_RC_OBJ(m_BufObjAllocator, "Buffer instance", BufferImplType)(m_BuffViewObjAllocator, static_cast<RenderDeviceImplType*>(this), BuffDesc, ExtraArgs...)};
                               pBufferImpl->QueryInterface(IID_Buffer, reinterpret_cast<IObject**>(ppBuffer));
                               pBufferImpl->CreateDefaultViews();
                           });
    }

    template <typename... ExtraArgsType>
    void CreateTextureImpl(ITexture** ppTexture, const TextureDesc& TexDesc, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("Texture", TexDesc, ppTexture,
                           [&]() //
                           {
                               auto* pTextureImpl{NEW_RC_OBJ(m_TexObjAllocator, "Texture instance", TextureImplType)(m_TexViewObjAllocator, static_cast<RenderDeviceImplType*>(this), TexDesc, ExtraArgs...)};
                               pTextureImpl->QueryInterface(IID_Texture, reinterpret_cast<IObject**>(ppTexture));
                               pTextureImpl->CreateDefaultViews();
                           });
    }

    template <typename... ExtraArgsType>
    void CreateShaderImpl(IShader** ppShader, const ShaderCreateInfo& ShaderCI, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("Shader", ShaderCI.Desc, ppShader,
                           [&]() //
                           {
                               auto* pShaderImpl{NEW_RC_OBJ(m_ShaderObjAllocator, "Shader instance", ShaderImplType)(static_cast<RenderDeviceImplType*>(this), ShaderCI, ExtraArgs...)};
                               pShaderImpl->QueryInterface(IID_Shader, reinterpret_cast<IObject**>(ppShader));
                           });
    }

    template <typename... ExtraArgsType>
    void CreateSamplerImpl(ISampler** ppSampler, const SamplerDesc& SamplerDesc, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("Sampler", SamplerDesc, ppSampler,
                           [&]() //
                           {
                               m_SamplersRegistry.Find(SamplerDesc, reinterpret_cast<IDeviceObject**>(ppSampler));
                               if (*ppSampler == nullptr)
                               {
                                   auto* pSamplerImpl{NEW_RC_OBJ(m_SamplerObjAllocator, "Sampler instance", SamplerImplType)(static_cast<RenderDeviceImplType*>(this), SamplerDesc, ExtraArgs...)};
                                   pSamplerImpl->QueryInterface(IID_Sampler, reinterpret_cast<IObject**>(ppSampler));
                                   m_SamplersRegistry.Add(SamplerDesc, *ppSampler);
                               }
                           });
    }

    void CreateFenceImpl(IFence** ppFence, const FenceDesc& Desc)
    {
        CreateDeviceObject("Fence", Desc, ppFence,
                           [&]() //
                           {
                               auto* pFenceImpl{NEW_RC_OBJ(m_FenceAllocator, "Fence instance", FenceImplType)(static_cast<RenderDeviceImplType*>(this), Desc)};
                               pFenceImpl->QueryInterface(IID_Fence, reinterpret_cast<IObject**>(ppFence));
                           });
    }

    void CreateQueryImpl(IQuery** ppQuery, const QueryDesc& Desc)
    {
        CreateDeviceObject("Query", Desc, ppQuery,
                           [&]() //
                           {
                               auto* pQueryImpl{NEW_RC_OBJ(m_QueryAllocator, "Query instance", QueryImplType)(static_cast<RenderDeviceImplType*>(this), Desc)};
                               pQueryImpl->QueryInterface(IID_Query, reinterpret_cast<IObject**>(ppQuery));
                           });
    }

    template <typename... ExtraArgsType>
    void CreateRenderPassImpl(IRenderPass** ppRenderPass, const RenderPassDesc& Desc, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("RenderPass", Desc, ppRenderPass,
                           [&]() //
                           {
                               auto* pRenderPassImpl{NEW_RC_OBJ(m_RenderPassAllocator, "Render instance", RenderPassImplType)(static_cast<RenderDeviceImplType*>(this), Desc, ExtraArgs...)};
                               pRenderPassImpl->QueryInterface(IID_RenderPass, reinterpret_cast<IObject**>(ppRenderPass));
                           });
    }

    template <typename... ExtraArgsType>
    void CreateFramebufferImpl(IFramebuffer** ppFramebuffer, const FramebufferDesc& Desc, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("Framebuffer", Desc, ppFramebuffer,
                           [&]() //
                           {
                               auto* pFramebufferImpl{NEW_RC_OBJ(m_FramebufferAllocator, "Framebuffer instance", FramebufferImplType)(static_cast<RenderDeviceImplType*>(this), Desc, ExtraArgs...)};
                               pFramebufferImpl->QueryInterface(IID_Framebuffer, reinterpret_cast<IObject**>(ppFramebuffer));
                           });
    }

    template <typename... ExtraArgsType>
    void CreateBLASImpl(IBottomLevelAS** ppBLAS, const BottomLevelASDesc& Desc, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("BottomLevelAS", Desc, ppBLAS,
                           [&]() //
                           {
                               auto* pBottomLevelASImpl(NEW_RC_OBJ(m_BLASAllocator, "BottomLevelAS instance", BottomLevelASImplType)(static_cast<RenderDeviceImplType*>(this), Desc, ExtraArgs...));
                               pBottomLevelASImpl->QueryInterface(IID_BottomLevelAS, reinterpret_cast<IObject**>(ppBLAS));
                           });
    }

    template <typename... ExtraArgsType>
    void CreateTLASImpl(ITopLevelAS** ppTLAS, const TopLevelASDesc& Desc, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("TopLevelAS", Desc, ppTLAS,
                           [&]() //
                           {
                               auto* pTopLevelASImpl(NEW_RC_OBJ(m_TLASAllocator, "TopLevelAS instance", TopLevelASImplType)(static_cast<RenderDeviceImplType*>(this), Desc, ExtraArgs...));
                               pTopLevelASImpl->QueryInterface(IID_TopLevelAS, reinterpret_cast<IObject**>(ppTLAS));
                           });
    }

    void CreateSBTImpl(IShaderBindingTable** ppSBT, const ShaderBindingTableDesc& Desc)
    {
        CreateDeviceObject("ShaderBindingTable", Desc, ppSBT,
                           [&]() //
                           {
                               auto* pSBTImpl(NEW_RC_OBJ(m_SBTAllocator, "ShaderBindingTable instance", ShaderBindingTableImplType)(static_cast<RenderDeviceImplType*>(this), Desc));
                               pSBTImpl->QueryInterface(IID_ShaderBindingTable, reinterpret_cast<IObject**>(ppSBT));
                           });
    }

    template <typename... ExtraArgsType>
    void CreatePipelineResourceSignatureImpl(IPipelineResourceSignature** ppSignature, const PipelineResourceSignatureDesc& Desc, const ExtraArgsType&... ExtraArgs)
    {
        CreateDeviceObject("PipelineResourceSignature", Desc, ppSignature,
                           [&]() //
                           {
                               auto* pPRSImpl(NEW_RC_OBJ(m_PipeResSignAllocator, "PipelineResourceSignature instance", PipelineResourceSignatureImplType)(static_cast<RenderDeviceImplType*>(this), Desc, ExtraArgs...));
                               pPRSImpl->QueryInterface(IID_PipelineResourceSignature, reinterpret_cast<IObject**>(ppSignature));
                           });
    }


protected:
    RefCntAutoPtr<IEngineFactory> m_pEngineFactory;

    DeviceCaps       m_DeviceCaps;
    DeviceProperties m_DeviceProperties;

    // All state object registries hold raw pointers.
    // This is safe because every object unregisters itself
    // when it is deleted.
    StateObjectsRegistry<SamplerDesc>                                           m_SamplersRegistry; ///< Sampler state registry
    std::vector<TextureFormatInfoExt, STDAllocatorRawMem<TextureFormatInfoExt>> m_TextureFormatsInfo;
    std::vector<bool, STDAllocatorRawMem<bool>>                                 m_TexFmtInfoInitFlags;

    /// Weak reference to the immediate context. Immediate context holds strong reference
    /// to the device, so we must use weak reference to avoid circular dependencies.
    RefCntWeakPtr<IDeviceContext> m_wpImmediateContext;

    /// Weak references to deferred contexts.
    std::vector<RefCntWeakPtr<IDeviceContext>, STDAllocatorRawMem<RefCntWeakPtr<IDeviceContext>>> m_wpDeferredContexts;

    IMemoryAllocator&         m_RawMemAllocator;      ///< Raw memory allocator
    FixedBlockMemoryAllocator m_TexObjAllocator;      ///< Allocator for texture objects
    FixedBlockMemoryAllocator m_TexViewObjAllocator;  ///< Allocator for texture view objects
    FixedBlockMemoryAllocator m_BufObjAllocator;      ///< Allocator for buffer objects
    FixedBlockMemoryAllocator m_BuffViewObjAllocator; ///< Allocator for buffer view objects
    FixedBlockMemoryAllocator m_ShaderObjAllocator;   ///< Allocator for shader objects
    FixedBlockMemoryAllocator m_SamplerObjAllocator;  ///< Allocator for sampler objects
    FixedBlockMemoryAllocator m_PSOAllocator;         ///< Allocator for pipeline state objects
    FixedBlockMemoryAllocator m_SRBAllocator;         ///< Allocator for shader resource binding objects
    FixedBlockMemoryAllocator m_ResMappingAllocator;  ///< Allocator for resource mapping objects
    FixedBlockMemoryAllocator m_FenceAllocator;       ///< Allocator for fence objects
    FixedBlockMemoryAllocator m_QueryAllocator;       ///< Allocator for query objects
    FixedBlockMemoryAllocator m_RenderPassAllocator;  ///< Allocator for render pass objects
    FixedBlockMemoryAllocator m_FramebufferAllocator; ///< Allocator for framebuffer objects
    FixedBlockMemoryAllocator m_BLASAllocator;        ///< Allocator for bottom-level acceleration structure objects
    FixedBlockMemoryAllocator m_TLASAllocator;        ///< Allocator for top-level acceleration structure objects
    FixedBlockMemoryAllocator m_SBTAllocator;         ///< Allocator for shader binding table objects
    FixedBlockMemoryAllocator m_PipeResSignAllocator; ///< Allocator for pipeline resource signature objects
};

} // namespace Diligent