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/MtlUtils.h" 9 10#include "experimental/graphite/src/mtl/MtlGpu.h" 11#include "include/private/SkSLString.h" 12#include "src/core/SkTraceEvent.h" 13 14namespace skgpu::mtl { 15 16bool FormatIsDepthOrStencil(MTLPixelFormat format) { 17 switch (format) { 18 case MTLPixelFormatStencil8: // fallthrough 19 case MTLPixelFormatDepth32Float_Stencil8: 20 return true; 21 default: 22 return false; 23 } 24} 25 26MTLPixelFormat SkColorTypeToFormat(SkColorType colorType) { 27 switch (colorType) { 28 case kRGBA_8888_SkColorType: 29 return MTLPixelFormatRGBA8Unorm; 30 case kAlpha_8_SkColorType: 31 return MTLPixelFormatR8Unorm; 32 case kRGBA_F16_SkColorType: 33 return MTLPixelFormatRGBA16Float; 34 default: 35 // TODO: fill in the rest of the formats 36 SkUNREACHABLE; 37 } 38} 39 40MTLPixelFormat DepthStencilTypeToFormat(DepthStencilType type) { 41 // TODO: Decide if we want to change this to always return a combined depth and stencil format 42 // to allow more sharing of depth stencil allocations. 43 switch (type) { 44 case DepthStencilType::kDepthOnly: 45 // MTLPixelFormatDepth16Unorm is also a universally supported option here 46 return MTLPixelFormatDepth32Float; 47 case DepthStencilType::kStencilOnly: 48 return MTLPixelFormatStencil8; 49 case DepthStencilType::kDepthStencil: 50 // MTLPixelFormatDepth24Unorm_Stencil8 is supported on Mac family GPUs. 51 return MTLPixelFormatDepth32Float_Stencil8; 52 } 53} 54 55sk_cfp<id<MTLLibrary>> CompileShaderLibrary(const Gpu* gpu, 56 const SkSL::String& msl) { 57 TRACE_EVENT0("skia.shaders", "driver_compile_shader"); 58 auto nsSource = [[NSString alloc] initWithBytesNoCopy:const_cast<char*>(msl.c_str()) 59 length:msl.size() 60 encoding:NSUTF8StringEncoding 61 freeWhenDone:NO]; 62 MTLCompileOptions* options = [[MTLCompileOptions alloc] init]; 63 // array<> is supported in MSL 2.0 on MacOS 10.13+ and iOS 11+, 64 // and in MSL 1.2 on iOS 10+ (but not MacOS). 65 if (@available(macOS 10.13, iOS 11.0, *)) { 66 options.languageVersion = MTLLanguageVersion2_0; 67#if defined(SK_BUILD_FOR_IOS) 68 } else if (@available(macOS 10.12, iOS 10.0, *)) { 69 options.languageVersion = MTLLanguageVersion1_2; 70#endif 71 } 72 73 NSError* error = nil; 74 // TODO: do we need a version with a timeout? 75 sk_cfp<id<MTLLibrary>> compiledLibrary([gpu->device() newLibraryWithSource:nsSource 76 options:options 77 error:&error]); 78 if (!compiledLibrary) { 79 SkDebugf("Shader compilation error\n" 80 "------------------------\n"); 81 SkDebugf("%s", msl.c_str()); 82 SkDebugf("Errors:\n%s", error.debugDescription.UTF8String); 83 84 return nil; 85 } 86 87 return compiledLibrary; 88} 89 90} // namespace skgpu::mtl 91