コード例 #1
0
    protected override void CreateBuffers()
    {
        base.CreateBuffers();
        _constantBuffer = CreateConstantBuffer(out _constantBufferDataBegin);

        ID3D12Resource *CreateConstantBuffer(out byte *constantBufferDataBegin)
        {
            ID3D12Resource *constantBuffer;

            var heapProperties = new D3D12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
            var bufferDesc     = D3D12_RESOURCE_DESC.Buffer(1024 * 64);

            ThrowIfFailed(D3DDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, pOptimizedClearValue: null, __uuidof <ID3D12Resource>(), (void **)&constantBuffer));

            var cbvDesc = new D3D12_CONSTANT_BUFFER_VIEW_DESC {
                BufferLocation = constantBuffer->GetGPUVirtualAddress(),
                SizeInBytes    = (uint)((sizeof(SceneConstantBuffer) + 255) & ~255) // CB size is required to be 256-byte aligned.
            };

            D3DDevice->CreateConstantBufferView(&cbvDesc, _cbvHeap->GetCPUDescriptorHandleForHeapStart());

            // Map and initialize the constant buffer. We don't unmap this until the
            // app closes. Keeping things mapped for the lifetime of the resource is okay.

            fixed(byte **pConstantBufferDataBegin = &constantBufferDataBegin)
            {
                var readRange = new D3D12_RANGE(); // We do not intend to read from this resource on the CPU.

                ThrowIfFailed(constantBuffer->Map(Subresource: 0, &readRange, (void **)pConstantBufferDataBegin));
                Unsafe.CopyBlock(ref constantBufferDataBegin[0], ref Unsafe.As <SceneConstantBuffer, byte>(ref _constantBufferData), (uint)sizeof(SceneConstantBuffer));
            }

            return(constantBuffer);
        }
    }
コード例 #2
0
ファイル: ID3D12Device.cs プロジェクト: ousttrue/ShrimpDX
        public virtual void CreateConstantBufferView(
            ref D3D12_CONSTANT_BUFFER_VIEW_DESC pDesc,
            D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor
            )
        {
            var fp = GetFunctionPointer(17);

            if (m_CreateConstantBufferViewFunc == null)
            {
                m_CreateConstantBufferViewFunc = (CreateConstantBufferViewFunc)Marshal.GetDelegateForFunctionPointer(fp, typeof(CreateConstantBufferViewFunc));
            }

            m_CreateConstantBufferViewFunc(m_ptr, ref pDesc, DestDescriptor);
        }
コード例 #3
0
        // Load the sample assets.
        private void LoadAssets()
        {
            Guid      iid;
            ID3DBlob *signature    = null;
            ID3DBlob *error        = null;
            ID3DBlob *vertexShader = null;
            ID3DBlob *pixelShader  = null;

            try
            {
                // Create a root signature consisting of a descriptor table with a single CBV.
                {
                    var featureData = new D3D12_FEATURE_DATA_ROOT_SIGNATURE {
                        // This is the highest version the sample supports. If CheckFeatureSupport succeeds, the HighestVersion returned will not be greater than this.
                        HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_1
                    };

                    if (FAILED(_device->CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &featureData, (uint)sizeof(D3D12_FEATURE_DATA_ROOT_SIGNATURE))))
                    {
                        featureData.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_0;
                    }

                    const int RangesCount         = 1;
                    var       ranges              = stackalloc D3D12_DESCRIPTOR_RANGE1[RangesCount];
                    const int RootParametersCount = 1;
                    var       rootParameters      = stackalloc D3D12_ROOT_PARAMETER1[RootParametersCount];

                    ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC);
                    rootParameters[0].InitAsDescriptorTable(RangesCount, ranges, D3D12_SHADER_VISIBILITY_VERTEX);

                    // Allow input layout and deny unnecessary access to certain pipeline stages.
                    var rootSignatureFlags =
                        D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
                        D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
                        D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
                        D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
                        D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;

                    var rootSignatureDesc = new D3D12_VERSIONED_ROOT_SIGNATURE_DESC();
                    rootSignatureDesc.Init_1_1(RootParametersCount, rootParameters, 0, null, rootSignatureFlags);

                    ThrowIfFailed(nameof(D3D12SerializeRootSignature), D3D12SerializeVersionedRootSignature(&rootSignatureDesc, featureData.HighestVersion, &signature, &error));

                    fixed(ID3D12RootSignature **rootSignature = &_rootSignature)
                    {
                        iid = IID_ID3D12RootSignature;
                        ThrowIfFailed(nameof(ID3D12Device.CreateRootSignature), _device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), &iid, (void **)rootSignature));
                    }
                }

                // Create the pipeline state, which includes compiling and loading shaders.
                {
                    var compileFlags = 0u;

#if DEBUG
                    // Enable better shader debugging with the graphics debugging tools.
                    compileFlags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
                    fixed(char *fileName = GetAssetFullPath(@"D3D12\Assets\Shaders\HelloConstBuffer.hlsl"))
                    {
                        var entryPoint = 0x00006E69614D5356;    // VSMain
                        var target     = 0x0000305F355F7376;    // vs_5_0

                        ThrowIfFailed(nameof(D3DCompileFromFile), D3DCompileFromFile((ushort *)fileName, pDefines: null, pInclude: null, (sbyte *)&entryPoint, (sbyte *)&target, compileFlags, Flags2: 0, &vertexShader, ppErrorMsgs: null));

                        entryPoint = 0x00006E69614D5350;        // PSMain
                        target     = 0x0000305F355F7370;        // ps_5_0
                        ThrowIfFailed(nameof(D3DCompileFromFile), D3DCompileFromFile((ushort *)fileName, pDefines: null, pInclude: null, (sbyte *)&entryPoint, (sbyte *)&target, compileFlags, Flags2: 0, &pixelShader, ppErrorMsgs: null));
                    }

                    // Define the vertex input layout.
                    const int InputElementDescsCount = 2;

                    var semanticName0 = stackalloc ulong[2] {
                        0x4E4F495449534F50,     // POSITION
                        0x0000000000000000,
                    };

                    var semanticName1 = stackalloc ulong[1] {
                        0x000000524F4C4F43,     // COLOR
                    };

                    var inputElementDescs = stackalloc D3D12_INPUT_ELEMENT_DESC[InputElementDescsCount] {
                        new D3D12_INPUT_ELEMENT_DESC {
                            SemanticName   = (sbyte *)semanticName0,
                            Format         = DXGI_FORMAT_R32G32B32_FLOAT,
                            InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
                        },
                        new D3D12_INPUT_ELEMENT_DESC {
                            SemanticName      = (sbyte *)semanticName1,
                            Format            = DXGI_FORMAT_R32G32B32A32_FLOAT,
                            AlignedByteOffset = 12,
                            InputSlotClass    = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
                        },
                    };

                    // Describe and create the graphics pipeline state object (PSO).
                    var psoDesc = new D3D12_GRAPHICS_PIPELINE_STATE_DESC {
                        InputLayout = new D3D12_INPUT_LAYOUT_DESC {
                            pInputElementDescs = inputElementDescs,
                            NumElements        = InputElementDescsCount,
                        },
                        pRootSignature        = _rootSignature,
                        VS                    = new D3D12_SHADER_BYTECODE(vertexShader),
                        PS                    = new D3D12_SHADER_BYTECODE(pixelShader),
                        RasterizerState       = D3D12_RASTERIZER_DESC.DEFAULT,
                        BlendState            = D3D12_BLEND_DESC.DEFAULT,
                        DepthStencilState     = D3D12_DEPTH_STENCIL_DESC.DEFAULT,
                        SampleMask            = uint.MaxValue,
                        PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
                        NumRenderTargets      = 1,
                        SampleDesc            = new DXGI_SAMPLE_DESC(count: 1, quality: 0),
                    };
                    psoDesc.DepthStencilState.DepthEnable = FALSE;
                    psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;

                    fixed(ID3D12PipelineState **pipelineState = &_pipelineState)
                    {
                        iid = IID_ID3D12PipelineState;
                        ThrowIfFailed(nameof(ID3D12Device.CreateGraphicsPipelineState), _device->CreateGraphicsPipelineState(&psoDesc, &iid, (void **)pipelineState));
                    }
                }

                // Create the command list.
                fixed(ID3D12GraphicsCommandList **commandList = &_commandList)
                {
                    iid = IID_ID3D12GraphicsCommandList;
                    ThrowIfFailed(nameof(ID3D12Device.CreateCommandList), _device->CreateCommandList(nodeMask: 0, D3D12_COMMAND_LIST_TYPE_DIRECT, _commandAllocator, _pipelineState, &iid, (void **)commandList));
                }

                // Command lists are created in the recording state, but there is nothing
                // to record yet. The main loop expects it to be closed, so close it now.
                ThrowIfFailed(nameof(ID3D12GraphicsCommandList.Close), _commandList->Close());

                // Create the vertex buffer.
                {
                    // Define the geometry for a triangle.
                    const int TriangleVerticesCount = 3;
                    var       triangleVertices      = stackalloc Vertex[TriangleVerticesCount] {
                        new Vertex {
                            Position = new Vector3(0.0f, 0.25f * AspectRatio, 0.0f),
                            Color    = new Vector4(1.0f, 0.0f, 0.0f, 1.0f)
                        },
                        new Vertex {
                            Position = new Vector3(0.25f, -0.25f * AspectRatio, 0.0f),
                            Color    = new Vector4(0.0f, 1.0f, 0.0f, 1.0f)
                        },
                        new Vertex {
                            Position = new Vector3(-0.25f, -0.25f * AspectRatio, 0.0f),
                            Color    = new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
                        },
                    };

                    var vertexBufferSize = (uint)sizeof(Vertex) * TriangleVerticesCount;

                    // Note: using upload heaps to transfer static data like vert buffers is not
                    // recommended. Every time the GPU needs it, the upload heap will be marshalled
                    // over. Please read up on Default Heap usage. An upload heap is used here for
                    // code simplicity and because there are very few verts to actually transfer.
                    fixed(ID3D12Resource **vertexBuffer = &_vertexBuffer)
                    {
                        var heapProperties = new D3D12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
                        var bufferDesc     = D3D12_RESOURCE_DESC.Buffer(vertexBufferSize);

                        iid = IID_ID3D12Resource;
                        ThrowIfFailed(nameof(ID3D12Device.CreateCommittedResource), _device->CreateCommittedResource(
                                          &heapProperties,
                                          D3D12_HEAP_FLAG_NONE,
                                          &bufferDesc,
                                          D3D12_RESOURCE_STATE_GENERIC_READ,
                                          pOptimizedClearValue: null,
                                          &iid,
                                          (void **)vertexBuffer
                                          ));
                    }

                    // Copy the triangle data to the vertex buffer.
                    var readRange = new D3D12_RANGE();

                    byte *pVertexDataBegin;
                    ThrowIfFailed(nameof(ID3D12Resource.Map), _vertexBuffer->Map(Subresource: 0, &readRange, (void **)&pVertexDataBegin));
                    Unsafe.CopyBlock(pVertexDataBegin, triangleVertices, vertexBufferSize);
                    _vertexBuffer->Unmap(0, null);

                    // Initialize the vertex buffer view.
                    _vertexBufferView.BufferLocation = _vertexBuffer->GetGPUVirtualAddress();
                    _vertexBufferView.StrideInBytes  = (uint)sizeof(Vertex);
                    _vertexBufferView.SizeInBytes    = vertexBufferSize;
                }

                // Create the constant buffer.
                {
                    fixed(ID3D12Resource **pConstantBuffer = &_constantBuffer)
                    {
                        var heapProperties = new D3D12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
                        var bufferDesc     = D3D12_RESOURCE_DESC.Buffer(1024 * 64);

                        iid = IID_ID3D12Resource;
                        ThrowIfFailed(nameof(ID3D12Device.CreateCommittedResource), _device->CreateCommittedResource(
                                          &heapProperties,
                                          D3D12_HEAP_FLAG_NONE,
                                          &bufferDesc,
                                          D3D12_RESOURCE_STATE_GENERIC_READ,
                                          pOptimizedClearValue: null,
                                          &iid,
                                          (void **)pConstantBuffer));
                    }

                    // Describe and create a constant buffer view.
                    var cbvDesc = new D3D12_CONSTANT_BUFFER_VIEW_DESC {
                        BufferLocation = _constantBuffer->GetGPUVirtualAddress(),
                        SizeInBytes    = (uint)((sizeof(SceneConstantBuffer) + 255) & ~255) // CB size is required to be 256-byte aligned.
                    };

                    _device->CreateConstantBufferView(&cbvDesc, _cbvHeap->GetCPUDescriptorHandleForHeapStart());

                    // Map and initialize the constant buffer. We don't unmap this until the
                    // app closes. Keeping things mapped for the lifetime of the resource is okay.
                    var readRange = new D3D12_RANGE(); // We do not intend to read from this resource on the CPU.

                    fixed(byte **ppCbvDataBegin = &_pCbvDataBegin)
                    {
                        ThrowIfFailed(nameof(ID3D12Resource.Map), _constantBuffer->Map(Subresource: 0, &readRange, (void **)ppCbvDataBegin));
                        Unsafe.CopyBlock(ref _pCbvDataBegin[0], ref Unsafe.As <SceneConstantBuffer, byte>(ref _constantBufferData), (uint)sizeof(SceneConstantBuffer));
                    }

                    // Create synchronization objects and wait until assets have been uploaded to the GPU.
                    {
                        fixed(ID3D12Fence **fence = &_fence)
                        {
                            iid = IID_ID3D12Fence;
                            ThrowIfFailed(nameof(ID3D12Device.CreateFence), _device->CreateFence(0, D3D12_FENCE_FLAG_NONE, &iid, (void **)fence));
                            _fenceValue = 1;
                        }

                        // Create an event handle to use for frame synchronization.
                        _fenceEvent = CreateEventW(lpEventAttributes: null, bManualReset: FALSE, bInitialState: FALSE, lpName: null);
                        if (_fenceEvent == null)
                        {
                            var hr = Marshal.GetHRForLastWin32Error();
                            Marshal.ThrowExceptionForHR(hr);
                        }

                        // Wait for the command list to execute; we are reusing the same command
                        // list in our main loop but for now, we just want to wait for setup to
                        // complete before continuing.
                        WaitForPreviousFrame();
                    }
                }
            }
            finally
            {
                if (signature != null)
                {
                    signature->Release();
                }

                if (error != null)
                {
                    error->Release();
                }

                if (vertexShader != null)
                {
                    vertexShader->Release();
                }

                if (pixelShader != null)
                {
                    pixelShader->Release();
                }
            }
        }