1/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/gpu/d3d/GrD3DAMDMemoryAllocator.h"
9#include "src/gpu/d3d/GrD3DUtil.h"
10
11sk_sp<GrD3DMemoryAllocator> GrD3DAMDMemoryAllocator::Make(IDXGIAdapter* adapter,
12                                                          ID3D12Device* device) {
13    D3D12MA::ALLOCATOR_DESC allocatorDesc = {};
14    allocatorDesc.pAdapter = adapter;
15    allocatorDesc.pDevice = device;
16    allocatorDesc.Flags = D3D12MA::ALLOCATOR_FLAG_SINGLETHREADED; // faster if we're single-threaded
17
18    D3D12MA::Allocator* allocator;
19    HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);
20    if (!SUCCEEDED(hr)) {
21        return nullptr;
22    }
23
24    return sk_sp<GrD3DMemoryAllocator>(new GrD3DAMDMemoryAllocator(allocator));
25}
26
27gr_cp<ID3D12Resource> GrD3DAMDMemoryAllocator::createResource(
28        D3D12_HEAP_TYPE heapType, const D3D12_RESOURCE_DESC* resourceDesc,
29        D3D12_RESOURCE_STATES initialResourceState, sk_sp<GrD3DAlloc>* allocation,
30        const D3D12_CLEAR_VALUE* clearValue) {
31    D3D12MA::ALLOCATION_DESC allocationDesc = {};
32    allocationDesc.HeapType = heapType;
33    // TODO: Determine flags. For now create new heaps regardless of budget,
34    //       and always suballocate and use CreatePlacedResource.
35    // allocationDesc.Flags = ?
36
37    gr_cp<ID3D12Resource> resource;
38    D3D12MA::Allocation* d3d12maAllocation;
39    HRESULT hr = fAllocator->CreateResource(&allocationDesc, resourceDesc,
40                                            initialResourceState, clearValue,
41                                            &d3d12maAllocation, IID_PPV_ARGS(&resource));
42    if (!SUCCEEDED(hr)) {
43        return nullptr;
44    }
45
46    allocation->reset(new Alloc(d3d12maAllocation));
47    return resource;
48}
49
50gr_cp<ID3D12Resource> GrD3DAMDMemoryAllocator::createAliasingResource(
51        sk_sp<GrD3DAlloc>& allocation, uint64_t localOffset,
52        const D3D12_RESOURCE_DESC* resourceDesc, D3D12_RESOURCE_STATES initialResourceState,
53        const D3D12_CLEAR_VALUE* clearValue) {
54    Alloc* alloc = (Alloc*)allocation.get();
55    gr_cp<ID3D12Resource> resource;
56    HRESULT hr = fAllocator->CreateAliasingResource(alloc->fAllocation, localOffset, resourceDesc,
57                                                    initialResourceState, clearValue,
58                                                    IID_PPV_ARGS(&resource));
59    if (!SUCCEEDED(hr)) {
60        return nullptr;
61    }
62
63    return resource;
64}
65