1/* 2 * Copyright 2021 Google Inc. 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 "experimental/graphite/src/mtl/MtlBuffer.h" 9 10#include "experimental/graphite/src/mtl/MtlGpu.h" 11 12namespace skgpu::mtl { 13 14#ifdef SK_ENABLE_MTL_DEBUG_INFO 15NSString* kBufferTypeNames[kBufferTypeCount] = { 16 @"Vertex", 17 @"Index", 18 @"Xfer CPU to GPU", 19 @"Xfer GPU to CPU", 20 @"Uniform", 21}; 22#endif 23 24sk_sp<Buffer> Buffer::Make(const Gpu* gpu, 25 size_t size, 26 BufferType type, 27 PrioritizeGpuReads prioritizeGpuReads) { 28 if (size <= 0) { 29 return nullptr; 30 } 31 32 const Caps& mtlCaps = gpu->mtlCaps(); 33 34 NSUInteger options = 0; 35 if (@available(macOS 10.11, iOS 9.0, *)) { 36 if (prioritizeGpuReads == PrioritizeGpuReads::kNo) { 37#ifdef SK_BUILD_FOR_MAC 38 if (mtlCaps.isMac()) { 39 options |= MTLResourceStorageModeManaged; 40 } else { 41 SkASSERT(mtlCaps.isApple()); 42 options |= MTLResourceStorageModeShared; 43 } 44#else 45 options |= MTLResourceStorageModeShared; 46#endif 47 } else { 48 options |= MTLResourceStorageModePrivate; 49 } 50 } 51 52 size = SkAlignTo(size, mtlCaps.getMinBufferAlignment()); 53 sk_cfp<id<MTLBuffer>> buffer([gpu->device() newBufferWithLength: size options: options]); 54#ifdef SK_ENABLE_MTL_DEBUG_INFO 55 (*buffer).label = kBufferTypeNames[(int)type]; 56#endif 57 58 return sk_sp<Buffer>(new Buffer(gpu, size, type, prioritizeGpuReads, std::move(buffer))); 59} 60 61Buffer::Buffer(const Gpu* gpu, 62 size_t size, 63 BufferType type, 64 PrioritizeGpuReads prioritizeGpuReads, 65 sk_cfp<id<MTLBuffer>> buffer) 66 : skgpu::Buffer(gpu, size, type, prioritizeGpuReads) 67 , fBuffer(std::move(buffer)) {} 68 69void Buffer::onMap() { 70 SkASSERT(fBuffer); 71 SkASSERT(!this->isMapped()); 72 73 if ((*fBuffer).storageMode == MTLStorageModePrivate) { 74 return; 75 } 76 77 fMapPtr = static_cast<char*>((*fBuffer).contents); 78} 79 80void Buffer::onUnmap() { 81 SkASSERT(fBuffer); 82 SkASSERT(this->isMapped()); 83#ifdef SK_BUILD_FOR_MAC 84 if ((*fBuffer).storageMode == MTLStorageModeManaged) { 85 [*fBuffer didModifyRange: NSMakeRange(0, this->size())]; 86 } 87#endif 88 fMapPtr = nullptr; 89} 90 91void Buffer::onFreeGpuData() { 92 fBuffer.reset(); 93} 94 95} // namespace skgpu::mtl 96 97