diff --git a/Common/GPU/Metal/MetalRenderManager.h b/Common/GPU/Metal/MetalRenderManager.h index a1f5743d92..0b98f15f81 100644 --- a/Common/GPU/Metal/MetalRenderManager.h +++ b/Common/GPU/Metal/MetalRenderManager.h @@ -28,6 +28,11 @@ #import #import +// Foundation's ABS macro breaks ARM64XEmitter::ABS, which gets included along with the vertex decoders. +#ifdef ABS +#undef ABS +#endif + #include #include #include diff --git a/Common/GPU/Metal/MetalRenderManager.mm b/Common/GPU/Metal/MetalRenderManager.mm index 9e1cbc5600..5152878af7 100644 --- a/Common/GPU/Metal/MetalRenderManager.mm +++ b/Common/GPU/Metal/MetalRenderManager.mm @@ -79,7 +79,7 @@ MetalPushAlloc MetalPushBuffer::Allocate(size_t size, size_t align) { } Block block; block.size = std::max(blockSize_, size); - block.buffer = [device_ newBufferWithLength:block.size options:MTLResourceStorageModeShared | MTLResourceCPUCacheModeWriteCombined]; + block.buffer = [device_ newBufferWithLength:block.size options:MTLResourceStorageModeShared]; _assert_msg_(block.buffer, "Failed to allocate push buffer block of %d bytes", (int)block.size); block.buffer.label = [NSString stringWithUTF8String:tag_.c_str()]; block.ptr = (uint8_t *)block.buffer.contents; @@ -125,11 +125,8 @@ bool TranslateVulkanGLSLToMSL(ShaderStage stage, const char *glsl, MetalTranslat #else options.platform = spirv_cross::CompilerMSL::Options::macOS; #endif - if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) { - options.msl_version = spirv_cross::CompilerMSL::Options::make_msl_version(2, 3); - } else { - options.msl_version = spirv_cross::CompilerMSL::Options::make_msl_version(2, 1); - } + // macOS 11 and iOS 15 are the minimum, and both have MSL 2.3. + options.msl_version = spirv_cross::CompilerMSL::Options::make_msl_version(2, 3); options.pad_fragment_output_components = true; // Point size is only written for point primitives, which we don't draw (they're expanded to quads). options.enable_point_size_builtin = false; @@ -198,11 +195,9 @@ bool TranslateVulkanGLSLToMSL(ShaderStage stage, const char *glsl, MetalTranslat id CreateMetalFunction(id device, const MetalTranslatedShader &shader, const char *tag, std::string *errorMessage) { MTLCompileOptions *options = [MTLCompileOptions new]; - if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) { - options.languageVersion = MTLLanguageVersion2_3; - } else { - options.languageVersion = MTLLanguageVersion2_1; - } + options.languageVersion = MTLLanguageVersion2_3; + // Multipass effects depend on identical positions from different vertex shaders (equal depth tests). + options.preserveInvariance = YES; NSError *error = nil; id library = [device newLibraryWithSource:[NSString stringWithUTF8String:shader.msl.c_str()] options:options error:&error]; if (!library) { @@ -222,9 +217,7 @@ MetalRenderManager::MetalRenderManager(id device, CAMetalLayer *layer queue_ = [device_ newCommandQueue]; queue_.label = @"PPSSPP"; unifiedMemory_ = device_.hasUnifiedMemory; - if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { - appleGPU_ = [device_ supportsFamily:MTLGPUFamilyApple1]; - } + appleGPU_ = [device_ supportsFamily:MTLGPUFamilyApple1]; for (int i = 0; i < METAL_MAX_INFLIGHT_FRAMES; i++) { frames_[i].push.Init(device_, 4 * 1024 * 1024, StringFromFormat("push%d", i).c_str()); @@ -465,9 +458,15 @@ void MetalRenderManager::BindBackbufferPass(MTLLoadAction colorLoad, MTLClearCol } void MetalRenderManager::BindRenderPass(const MetalRenderPassDesc &desc) { - if (!passIsBackbuffer_ && renderEncoder_ && desc.color == pass_.color && desc.depth == pass_.depth && - desc.colorLoad == MTLLoadActionLoad && desc.depthLoad == MTLLoadActionLoad && desc.stencilLoad == MTLLoadActionLoad) { - // Just continue the current pass. + if (!passIsBackbuffer_ && HasRenderPass() && desc.color == pass_.color && desc.depth == pass_.depth) { + // Binding the target we're already on continues the pass, like in the Vulkan backend: clears are applied, + // and DontCare is ignored since there's content to keep. + bool clearColor = desc.colorLoad == MTLLoadActionClear; + bool clearDepth = desc.depthLoad == MTLLoadActionClear; + bool clearStencil = desc.stencilLoad == MTLLoadActionClear; + if (clearColor || clearDepth || clearStencil) { + Clear(clearColor, clearDepth, clearStencil, desc.clearColor, desc.clearDepth, desc.clearStencil); + } return; } EndEncoders(); diff --git a/Common/GPU/Metal/thin3d_metal.mm b/Common/GPU/Metal/thin3d_metal.mm index 00bc60ba29..229ee736ee 100644 --- a/Common/GPU/Metal/thin3d_metal.mm +++ b/Common/GPU/Metal/thin3d_metal.mm @@ -156,11 +156,7 @@ static MTLSamplerAddressMode AddressModeToMetal(TextureAddressMode mode) { case TextureAddressMode::REPEAT: return MTLSamplerAddressModeRepeat; case TextureAddressMode::REPEAT_MIRROR: return MTLSamplerAddressModeMirrorRepeat; case TextureAddressMode::CLAMP_TO_EDGE: return MTLSamplerAddressModeClampToEdge; - case TextureAddressMode::CLAMP_TO_BORDER: - if (@available(iOS 14.0, tvOS 14.0, *)) { - return MTLSamplerAddressModeClampToBorderColor; - } - return MTLSamplerAddressModeClampToZero; + case TextureAddressMode::CLAMP_TO_BORDER: return MTLSamplerAddressModeClampToBorderColor; } return MTLSamplerAddressModeClampToEdge; } @@ -536,7 +532,7 @@ MetalDrawContext::MetalDrawContext(MetalRenderManager *renderManager) : rm_(rend caps_.framebufferCopySupported = true; caps_.framebufferBlitSupported = false; caps_.framebufferDepthCopySupported = true; - caps_.framebufferSeparateDepthCopySupported = false; + caps_.framebufferSeparateDepthCopySupported = true; caps_.framebufferDepthBlitSupported = false; caps_.framebufferStencilBlitSupported = false; caps_.framebufferFetchSupported = false; @@ -544,7 +540,7 @@ MetalDrawContext::MetalDrawContext(MetalRenderManager *renderManager) : rm_(rend caps_.fragmentShaderFullPrecisionFloat = true; caps_.fragmentShaderInt32Supported = true; caps_.fragmentShaderDepthWriteSupported = true; - caps_.fragmentShaderStencilWriteSupported = false; + caps_.fragmentShaderStencilWriteSupported = true; caps_.textureDepthSupported = true; caps_.blendMinMaxSupported = true; caps_.multiViewSupported = false; @@ -597,7 +593,7 @@ std::vector MetalDrawContext::GetFeatureList() const { std::vector features; features.push_back(StringFromFormat("Unified memory: %s", rm_->HasUnifiedMemory() ? "yes" : "no")); features.push_back(StringFromFormat("Apple GPU family: %s", rm_->IsAppleGPU() ? "yes" : "no")); - if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) { + if (@available(iOS 16.4, tvOS 16.4, *)) { features.push_back(StringFromFormat("BC texture compression: %s", device_.supportsBCTextureCompression ? "yes" : "no")); } return features; @@ -625,7 +621,7 @@ uint32_t MetalDrawContext::GetDataFormatSupport(DataFormat fmt) const { case DataFormat::BC4_UNORM_BLOCK: case DataFormat::BC5_UNORM_BLOCK: case DataFormat::BC7_UNORM_BLOCK: - if (@available(macOS 11.0, iOS 16.4, tvOS 16.4, *)) { + if (@available(iOS 16.4, tvOS 16.4, *)) { supported = device_.supportsBCTextureCompression; } break; @@ -689,12 +685,10 @@ SamplerState *MetalDrawContext::CreateSamplerState(const SamplerStateDesc &desc) if (desc.shadowCompareEnabled) { sd.compareFunction = compareToMetal[(int)desc.shadowCompareFunc]; } - if (@available(iOS 14.0, tvOS 14.0, *)) { - switch (desc.borderColor) { - case BorderColor::OPAQUE_BLACK: sd.borderColor = MTLSamplerBorderColorOpaqueBlack; break; - case BorderColor::OPAQUE_WHITE: sd.borderColor = MTLSamplerBorderColorOpaqueWhite; break; - default: sd.borderColor = MTLSamplerBorderColorTransparentBlack; break; - } + switch (desc.borderColor) { + case BorderColor::OPAQUE_BLACK: sd.borderColor = MTLSamplerBorderColorOpaqueBlack; break; + case BorderColor::OPAQUE_WHITE: sd.borderColor = MTLSamplerBorderColorOpaqueWhite; break; + default: sd.borderColor = MTLSamplerBorderColorTransparentBlack; break; } sd.lodMinClamp = 0.0f; sd.lodMaxClamp = FLT_MAX; @@ -971,9 +965,23 @@ void MetalDrawContext::CopyFramebufferImage(Framebuffer *srcfb, int level, int x [blit copyFromTexture:src->color sourceSlice:0 sourceLevel:level sourceOrigin:MTLOriginMake(x, y, 0) sourceSize:MTLSizeMake(width, height, 1) toTexture:dst->color destinationSlice:0 destinationLevel:dstLevel destinationOrigin:MTLOriginMake(dstX, dstY, 0)]; } - if ((aspects & (Aspect::DEPTH_BIT | Aspect::STENCIL_BIT)) && src->depth && dst->depth) { - [blit copyFromTexture:src->depth sourceSlice:0 sourceLevel:level sourceOrigin:MTLOriginMake(x, y, 0) sourceSize:MTLSizeMake(width, height, 1) - toTexture:dst->depth destinationSlice:0 destinationLevel:dstLevel destinationOrigin:MTLOriginMake(dstX, dstY, 0)]; + const bool copyDepth = (aspects & Aspect::DEPTH_BIT) != 0; + const bool copyStencil = (aspects & Aspect::STENCIL_BIT) != 0; + if ((copyDepth || copyStencil) && src->depth && dst->depth) { + if (copyDepth && copyStencil) { + [blit copyFromTexture:src->depth sourceSlice:0 sourceLevel:level sourceOrigin:MTLOriginMake(x, y, 0) sourceSize:MTLSizeMake(width, height, 1) + toTexture:dst->depth destinationSlice:0 destinationLevel:dstLevel destinationOrigin:MTLOriginMake(dstX, dstY, 0)]; + } else { + // Texture-to-texture copies take both planes of a combined format, so a single one goes through a buffer. + const bool depth = copyDepth; + const MTLBlitOption option = depth ? MTLBlitOptionDepthFromDepthStencil : MTLBlitOptionStencilFromDepthStencil; + const int bytesPerRow = width * (depth ? 4 : 1); + MetalPushAlloc alloc = rm_->Push().Allocate(bytesPerRow * height, 16); + [blit copyFromTexture:src->depth sourceSlice:0 sourceLevel:level sourceOrigin:MTLOriginMake(x, y, 0) sourceSize:MTLSizeMake(width, height, 1) + toBuffer:alloc.buffer destinationOffset:alloc.offset destinationBytesPerRow:bytesPerRow destinationBytesPerImage:bytesPerRow * height options:option]; + [blit copyFromBuffer:alloc.buffer sourceOffset:alloc.offset sourceBytesPerRow:bytesPerRow sourceBytesPerImage:bytesPerRow * height sourceSize:MTLSizeMake(width, height, 1) + toTexture:dst->depth destinationSlice:0 destinationLevel:dstLevel destinationOrigin:MTLOriginMake(dstX, dstY, 0) options:option]; + } } } @@ -1384,11 +1392,7 @@ std::string MetalDrawContext::GetInfoString(InfoField info) const { case InfoField::VENDORSTRING: return [[device_ name] UTF8String]; case InfoField::VENDOR: return ""; case InfoField::DRIVER: return "-"; - case InfoField::SHADELANGVERSION: - if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) { - return "MSL 2.3"; - } - return "MSL 2.1"; + case InfoField::SHADELANGVERSION: return "MSL 2.3"; default: return "?"; } } @@ -1400,6 +1404,8 @@ uint64_t MetalDrawContext::GetNativeObject(NativeObject obj, void *srcObject) { case NativeObject::RENDER_MANAGER: return (uint64_t)(uintptr_t)rm_; case NativeObject::TEXTURE_VIEW: return (uint64_t)(uintptr_t)(__bridge void *)((MetalTexture *)srcObject)->texture; case NativeObject::NULL_IMAGEVIEW: return (uint64_t)(uintptr_t)(__bridge void *)nullTexture_; + case NativeObject::BOUND_TEXTURE0_IMAGEVIEW: return (uint64_t)(uintptr_t)(__bridge void *)boundTextures_[0]; + case NativeObject::BOUND_TEXTURE1_IMAGEVIEW: return (uint64_t)(uintptr_t)(__bridge void *)boundTextures_[1]; default: return 0; } } diff --git a/GPU/CMakeLists.txt b/GPU/CMakeLists.txt index a17a4a48a5..9df9e1ea89 100644 --- a/GPU/CMakeLists.txt +++ b/GPU/CMakeLists.txt @@ -71,6 +71,22 @@ endif() if(WIN32) list(APPEND GPU_IMPLS ${GPU_D3D11}) endif() +if(APPLE) + set(GPU_METAL + Metal/DrawEngineMetal.h + Metal/DrawEngineMetal.mm + Metal/FramebufferManagerMetal.h + Metal/FramebufferManagerMetal.mm + Metal/GPU_Metal.h + Metal/GPU_Metal.mm + Metal/ShaderManagerMetal.h + Metal/ShaderManagerMetal.mm + Metal/TextureCacheMetal.h + Metal/TextureCacheMetal.mm + ) + set_source_files_properties(Metal/DrawEngineMetal.mm Metal/FramebufferManagerMetal.mm Metal/GPU_Metal.mm Metal/ShaderManagerMetal.mm Metal/TextureCacheMetal.mm PROPERTIES COMPILE_FLAGS -fobjc-arc) + list(APPEND GPU_IMPLS ${GPU_METAL}) +endif() set(GPU_SOURCES ${GPUArch} diff --git a/GPU/GPU.cpp b/GPU/GPU.cpp index 7b1d9a0284..4e6d4e9dea 100644 --- a/GPU/GPU.cpp +++ b/GPU/GPU.cpp @@ -37,6 +37,10 @@ #include "GPU/D3D11/GPU_D3D11.h" #endif +#if PPSSPP_PLATFORM(MAC) || PPSSPP_PLATFORM(IOS) +#include "GPU/Metal/GPU_Metal.h" +#endif + GPUStatistics gpuStats; GPUCommon *gpu; @@ -71,8 +75,11 @@ static GPUCommon *CreateGPUCore(GPUCore gpuCore, GraphicsContext *ctx, Draw::Dra return new GPU_Vulkan(ctx, draw); #endif case GPUCORE_METAL: - // TODO: The Metal GPU backend. Until then, nothing is drawn. - return CreateNullGPU(ctx); +#if PPSSPP_PLATFORM(MAC) || PPSSPP_PLATFORM(IOS) + return new GPU_Metal(ctx, draw); +#else + return nullptr; +#endif case GPUCORE_NULL: return CreateNullGPU(ctx); default: diff --git a/GPU/Metal/DrawEngineMetal.h b/GPU/Metal/DrawEngineMetal.h new file mode 100644 index 0000000000..c46989d439 --- /dev/null +++ b/GPU/Metal/DrawEngineMetal.h @@ -0,0 +1,166 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +// Objective-C++ only. + +#include + +#include "Common/Data/Collections/Hashmaps.h" +#include "Common/GPU/Metal/MetalRenderManager.h" +#include "GPU/GPUState.h" +#include "GPU/Common/DrawEngineCommon.h" +#include "GPU/Common/GPUStateUtils.h" +#include "GPU/Common/ShaderId.h" + +class ShaderManagerMetal; +class TextureCacheMetal; +class FramebufferManagerMetal; + +// What goes into a MTLRenderPipelineState, other than the shaders. +struct MetalBlendKey { + union { + uint32_t value; + struct { + uint32_t blendEnable : 1; + uint32_t srcColor : 5; // BlendFactor + uint32_t dstColor : 5; + uint32_t srcAlpha : 5; + uint32_t dstAlpha : 5; + uint32_t eqColor : 3; // BlendEq + uint32_t eqAlpha : 3; + uint32_t colorWriteMask : 4; // R=1, G=2, B=4, A=8 + }; + }; +}; + +struct MetalDepthStencilKey { + union { + uint64_t value; + struct { + uint64_t depthTestEnable : 1; + uint64_t depthWriteEnable : 1; + uint64_t depthCompare : 3; // GEComparison + uint64_t stencilTestEnable : 1; + uint64_t stencilCompare : 3; // GEComparison + uint64_t stencilPass : 3; // GEStencilOp + uint64_t stencilFail : 3; + uint64_t stencilDepthFail : 3; + uint64_t writeMask : 8; + uint64_t compareMask : 8; + }; + }; +}; + +struct MetalPipelineKey { + VShaderID vsid; + FShaderID fsid; + uint32_t vtxFmtId; // The decoded format ID, or SOFTWARE_TRANSFORM_VTXFMT. + uint32_t blend; // MetalBlendKey + uint32_t targetFormat; // MetalRenderTargetFormat::Key() + uint32_t pad = 0; +}; + +struct MetalDynamicState { + MTLViewport viewport; + int scissor[4]; + bool useBlendColor; + float blendColor[4]; + uint8_t stencilRef; + MTLCullMode cull; + bool depthClamp; +}; + +class DrawEngineMetal : public DrawEngineCommon { +public: + DrawEngineMetal(Draw::DrawContext *draw); + ~DrawEngineMetal(); + + void SetShaderManager(ShaderManagerMetal *shaderManager) { shaderManager_ = shaderManager; } + void SetTextureCache(TextureCacheMetal *textureCache) { textureCache_ = textureCache; } + void SetFramebufferManager(FramebufferManagerMetal *fbManager) { framebufferManager_ = fbManager; } + + void DeviceLost() override; + void DeviceRestore(Draw::DrawContext *draw) override; + + void BeginFrame() override; + void Flush() override; + void FinishDeferred() { + // The indices are read from PSP memory at flush time, and the game may change them (#10095). + Flush(); + } + + void ClearPipelines(); + int GetNumPipelines() const { return (int)pipelines_.size(); } + + void SetDepalTexture(id depal, bool smooth) { + if (boundDepal_ != depal) { + boundDepal_ = depal; + boundDepalSmoothed_ = smooth; + gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE); + } + } + +private: + void InitDeviceObjects(); + void Invalidate(InvalidationCallbackFlags flags); + void ConvertStateToKeys(int prim); + void BindShaderBlendTex(); + id GetPipeline(const VShaderID &vsid, const FShaderID &fsid, bool useHWTransform); + id GetDepthStencilState(const MetalDepthStencilKey &key); + bool ApplyState(id pipeline, bool overrideStencilRef, uint8_t stencilRef); + void BindResources(); + void ResetAfterSkippedDraw(); + void DrawPrimitives(MTLPrimitiveType prim, id vbuf, uint32_t vbOffset, int count, const uint16_t *inds); + + Draw::DrawContext *draw_; + MetalRenderManager *rm_ = nullptr; + + ShaderManagerMetal *shaderManager_ = nullptr; + TextureCacheMetal *textureCache_ = nullptr; + FramebufferManagerMetal *framebufferManager_ = nullptr; + + struct Pipeline { + id pso; + uint32_t fragmentArrayTextureMask; + }; + DenseHashMap pipelines_; + std::unordered_map> depthStencilCache_; + std::unordered_map vertexDescriptors_; + + // The current state. + MetalBlendKey blendKey_{}; + MetalDepthStencilKey depthStencilKey_{}; + MetalDynamicState dynState_{}; + uint32_t fragmentArrayTextureMask_ = 0; + GEPrimitiveType lastPrim_ = GE_PRIM_INVALID; + __unsafe_unretained id lastPipeline_ = nil; + + id boundSecondary_; + id boundDepal_; + bool boundDepalSmoothed_ = false; + id nullTexture_; + id samplerNearest_; + id samplerLinear_; + + FBOTexState fboTexBindState_ = FBO_TEX_NONE; + + MetalPushAlloc baseUBO_; + MetalPushAlloc lightUBO_; + uint64_t uboFrame_ = (uint64_t)-1; +}; diff --git a/GPU/Metal/DrawEngineMetal.mm b/GPU/Metal/DrawEngineMetal.mm new file mode 100644 index 0000000000..42c2e7ea8f --- /dev/null +++ b/GPU/Metal/DrawEngineMetal.mm @@ -0,0 +1,747 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "ppsspp_config.h" + +#include +#include + +#include "Common/Log.h" +#include "Common/Profiler/Profiler.h" +#include "Common/GPU/thin3d.h" +#include "Core/Config.h" +#include "GPU/GPUState.h" +#include "GPU/GPUCommon.h" +#include "GPU/ge_constants.h" +#include "GPU/Common/SoftwareTransformCommon.h" +#include "GPU/Common/VertexDecoderCommon.h" +#include "GPU/Common/FramebufferManagerCommon.h" +#include "GPU/Metal/DrawEngineMetal.h" +#include "GPU/Metal/ShaderManagerMetal.h" +#include "GPU/Metal/TextureCacheMetal.h" +#include "GPU/Metal/FramebufferManagerMetal.h" + +static const MTLBlendFactor blendFactorToMetal[(size_t)BlendFactor::COUNT] = { + MTLBlendFactorZero, + MTLBlendFactorOne, + MTLBlendFactorSourceColor, + MTLBlendFactorOneMinusSourceColor, + MTLBlendFactorDestinationColor, + MTLBlendFactorOneMinusDestinationColor, + MTLBlendFactorSourceAlpha, + MTLBlendFactorOneMinusSourceAlpha, + MTLBlendFactorDestinationAlpha, + MTLBlendFactorOneMinusDestinationAlpha, + MTLBlendFactorBlendColor, + MTLBlendFactorOneMinusBlendColor, + MTLBlendFactorBlendAlpha, + MTLBlendFactorOneMinusBlendAlpha, + MTLBlendFactorSource1Color, + MTLBlendFactorOneMinusSource1Color, + MTLBlendFactorSource1Alpha, + MTLBlendFactorOneMinusSource1Alpha, + MTLBlendFactorZero, // INVALID +}; + +static const MTLBlendOperation blendEqToMetal[(size_t)BlendEq::COUNT] = { + MTLBlendOperationAdd, + MTLBlendOperationSubtract, + MTLBlendOperationReverseSubtract, + MTLBlendOperationMin, + MTLBlendOperationMax, +}; + +// In GE order. +static const MTLCompareFunction compareToMetal[8] = { + MTLCompareFunctionNever, + MTLCompareFunctionAlways, + MTLCompareFunctionEqual, + MTLCompareFunctionNotEqual, + MTLCompareFunctionLess, + MTLCompareFunctionLessEqual, + MTLCompareFunctionGreater, + MTLCompareFunctionGreaterEqual, +}; + +static const MTLStencilOperation stencilOpToMetal[8] = { + MTLStencilOperationKeep, + MTLStencilOperationZero, + MTLStencilOperationReplace, + MTLStencilOperationInvert, + MTLStencilOperationIncrementClamp, + MTLStencilOperationDecrementClamp, + MTLStencilOperationKeep, + MTLStencilOperationKeep, +}; + +// Not a valid decoded format ID (those can be 0). +static constexpr uint32_t SOFTWARE_TRANSFORM_VTXFMT = 0xFFFFFFFF; + +static MTLVertexFormat DecFmtToMetal(int fmt) { + switch (fmt) { + case DEC_FLOAT_1: return MTLVertexFormatFloat; + case DEC_FLOAT_2: return MTLVertexFormatFloat2; + case DEC_FLOAT_3: return MTLVertexFormatFloat3; + case DEC_FLOAT_4: return MTLVertexFormatFloat4; + case DEC_S8_3: return MTLVertexFormatChar4Normalized; + case DEC_S16_3: return MTLVertexFormatShort4Normalized; + case DEC_U8_1: + case DEC_U8_2: + case DEC_U8_3: + case DEC_U8_4: return MTLVertexFormatUChar4Normalized; + case DEC_U16_1: + case DEC_U16_2: return MTLVertexFormatUShort2Normalized; + case DEC_U16_3: + case DEC_U16_4: return MTLVertexFormatUShort4Normalized; + default: return MTLVertexFormatInvalid; + } +} + +static void SetAttribute(MTLVertexDescriptor *vd, PspAttributeLocation location, int fmt, int offset) { + MTLVertexAttributeDescriptor *attr = vd.attributes[(int)location]; + attr.format = DecFmtToMetal(fmt); + attr.offset = offset; + attr.bufferIndex = METAL_VERTEX_BUFFER_INDEX; +} + +static MTLVertexDescriptor *CreateVertexDescriptor(const DecVtxFormat *decFmt) { + MTLVertexDescriptor *vd = [MTLVertexDescriptor vertexDescriptor]; + if (decFmt) { + if (decFmt->w0fmt != 0) SetAttribute(vd, PspAttributeLocation::W1, decFmt->w0fmt, decFmt->w0off); + if (decFmt->w1fmt != 0) SetAttribute(vd, PspAttributeLocation::W2, decFmt->w1fmt, decFmt->w1off); + if (decFmt->uvfmt != 0) SetAttribute(vd, PspAttributeLocation::TEXCOORD, decFmt->uvfmt, decFmt->uvoff); + if (decFmt->c0fmt != 0) SetAttribute(vd, PspAttributeLocation::COLOR0, decFmt->c0fmt, decFmt->c0off); + if (decFmt->c1fmt != 0) SetAttribute(vd, PspAttributeLocation::COLOR1, decFmt->c1fmt, decFmt->c1off); + if (decFmt->nrmfmt != 0) SetAttribute(vd, PspAttributeLocation::NORMAL, decFmt->nrmfmt, decFmt->nrmoff); + SetAttribute(vd, PspAttributeLocation::POSITION, DecVtxFormat::PosFmt(), decFmt->posoff); + vd.layouts[METAL_VERTEX_BUFFER_INDEX].stride = decFmt->stride; + } else { + // Software transformed. Unused attributes don't hurt. + SetAttribute(vd, PspAttributeLocation::POSITION, DEC_FLOAT_4, offsetof(TransformedVertex, pos)); + SetAttribute(vd, PspAttributeLocation::TEXCOORD, DEC_FLOAT_3, offsetof(TransformedVertex, uv)); + SetAttribute(vd, PspAttributeLocation::COLOR0, DEC_U8_4, offsetof(TransformedVertex, color0_32)); + SetAttribute(vd, PspAttributeLocation::COLOR1, DEC_U8_4, offsetof(TransformedVertex, color1_32)); + SetAttribute(vd, PspAttributeLocation::NORMAL, DEC_FLOAT_1, offsetof(TransformedVertex, fog)); + vd.layouts[METAL_VERTEX_BUFFER_INDEX].stride = sizeof(TransformedVertex); + } + vd.layouts[METAL_VERTEX_BUFFER_INDEX].stepFunction = MTLVertexStepFunctionPerVertex; + return vd; +} + +DrawEngineMetal::DrawEngineMetal(Draw::DrawContext *draw) : draw_(draw), pipelines_(256) { + decOptions_.expand8BitNormalsToFloat = false; + InitDeviceObjects(); +} + +DrawEngineMetal::~DrawEngineMetal() { + ClearPipelines(); + if (draw_) { + draw_->SetInvalidationCallback(InvalidationCallback()); + } +} + +void DrawEngineMetal::InitDeviceObjects() { + rm_ = (MetalRenderManager *)draw_->GetNativeObject(Draw::NativeObject::RENDER_MANAGER); + id device = rm_->Device(); + MTLSamplerDescriptor *sd = [MTLSamplerDescriptor new]; + sd.sAddressMode = MTLSamplerAddressModeClampToEdge; + sd.tAddressMode = MTLSamplerAddressModeClampToEdge; + sd.rAddressMode = MTLSamplerAddressModeClampToEdge; + samplerNearest_ = [device newSamplerStateWithDescriptor:sd]; + sd.minFilter = MTLSamplerMinMagFilterLinear; + sd.magFilter = MTLSamplerMinMagFilterLinear; + samplerLinear_ = [device newSamplerStateWithDescriptor:sd]; + nullTexture_ = (__bridge id)(void *)draw_->GetNativeObject(Draw::NativeObject::NULL_IMAGEVIEW); +} + +void DrawEngineMetal::DeviceLost() { + ClearPipelines(); + depthStencilCache_.clear(); + vertexDescriptors_.clear(); + if (draw_) { + draw_->SetInvalidationCallback(InvalidationCallback()); + invalidationCallbackInstalled_ = false; + } + boundSecondary_ = nil; + boundDepal_ = nil; + draw_ = nullptr; + rm_ = nullptr; +} + +void DrawEngineMetal::DeviceRestore(Draw::DrawContext *draw) { + draw_ = draw; + InitDeviceObjects(); +} + +void DrawEngineMetal::ClearPipelines() { + pipelines_.Iterate([](const MetalPipelineKey &, Pipeline *pipeline) { + delete pipeline; + }); + pipelines_.Clear(); + lastPipeline_ = nil; +} + +void DrawEngineMetal::BeginFrame() { + DrawEngineCommon::BeginFrame(); + if (!invalidationCallbackInstalled_) { + draw_->SetInvalidationCallback(std::bind(&DrawEngineMetal::Invalidate, this, std::placeholders::_1)); + invalidationCallbackInstalled_ = true; + } + lastPipeline_ = nil; + boundDepal_ = nil; + boundSecondary_ = nil; + baseUBO_ = MetalPushAlloc{}; + lightUBO_ = MetalPushAlloc{}; + gstate_c.Dirty(DIRTY_TEXTURE_IMAGE); + AssertEmpty(); +} + +void DrawEngineMetal::Invalidate(InvalidationCallbackFlags flags) { + if (flags & InvalidationCallbackFlags::RENDER_PASS_STATE) { + // The render target might have a different format. The encoder state itself is tracked by the render manager. + gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_BLEND_STATE | DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS); + lastPipeline_ = nil; + } +} + +id DrawEngineMetal::GetDepthStencilState(const MetalDepthStencilKey &key) { + auto iter = depthStencilCache_.find(key.value); + if (iter != depthStencilCache_.end()) { + return iter->second; + } + MTLDepthStencilDescriptor *dd = [MTLDepthStencilDescriptor new]; + if (key.depthTestEnable) { + dd.depthCompareFunction = compareToMetal[key.depthCompare]; + dd.depthWriteEnabled = key.depthWriteEnable; + } else { + dd.depthCompareFunction = MTLCompareFunctionAlways; + dd.depthWriteEnabled = NO; + } + if (key.stencilTestEnable) { + MTLStencilDescriptor *sd = [MTLStencilDescriptor new]; + sd.stencilCompareFunction = compareToMetal[key.stencilCompare]; + sd.stencilFailureOperation = stencilOpToMetal[key.stencilFail]; + sd.depthFailureOperation = stencilOpToMetal[key.stencilDepthFail]; + sd.depthStencilPassOperation = stencilOpToMetal[key.stencilPass]; + sd.readMask = (uint32_t)key.compareMask; + sd.writeMask = (uint32_t)key.writeMask; + dd.frontFaceStencil = sd; + dd.backFaceStencil = sd; + } + id dss = [rm_->Device() newDepthStencilStateWithDescriptor:dd]; + depthStencilCache_[key.value] = dss; + return dss; +} + +id DrawEngineMetal::GetPipeline(const VShaderID &vsid, const FShaderID &fsid, bool useHWTransform) { + const MetalRenderTargetFormat &format = rm_->CurTargetFormat(); + MetalPipelineKey key{}; + key.vsid = vsid; + key.fsid = fsid; + key.vtxFmtId = useHWTransform ? dec_->decFmt.id : SOFTWARE_TRANSFORM_VTXFMT; + key.blend = blendKey_.value; + key.targetFormat = format.Key(); + + Pipeline *pipeline = pipelines_.GetOrNull(key); + if (pipeline) { + fragmentArrayTextureMask_ = pipeline->fragmentArrayTextureMask; + return pipeline->pso; + } + + MetalVertexShader *vs = shaderManager_->GetVertexShaderFromID(vsid); + MetalFragmentShader *fs = shaderManager_->GetFragmentShaderFromID(fsid); + pipeline = new Pipeline(); + pipeline->fragmentArrayTextureMask = fs->info.arrayTextureMask; + pipelines_.Insert(key, pipeline); + if (vs->Failed() || fs->Failed()) { + return nil; + } + + MTLVertexDescriptor *vd; + auto iter = vertexDescriptors_.find(key.vtxFmtId); + if (iter != vertexDescriptors_.end()) { + vd = iter->second; + } else { + vd = CreateVertexDescriptor(useHWTransform ? &dec_->decFmt : nullptr); + vertexDescriptors_[key.vtxFmtId] = vd; + } + + MTLRenderPipelineDescriptor *desc = [MTLRenderPipelineDescriptor new]; + desc.vertexFunction = vs->function; + desc.fragmentFunction = fs->function; + desc.vertexDescriptor = vd; + desc.rasterSampleCount = format.sampleCount; + desc.depthAttachmentPixelFormat = format.depth; + desc.stencilAttachmentPixelFormat = format.stencil; + if (format.color != MTLPixelFormatInvalid) { + MTLRenderPipelineColorAttachmentDescriptor *att = desc.colorAttachments[0]; + att.pixelFormat = format.color; + MTLColorWriteMask mask = MTLColorWriteMaskNone; + if (blendKey_.colorWriteMask & 1) mask |= MTLColorWriteMaskRed; + if (blendKey_.colorWriteMask & 2) mask |= MTLColorWriteMaskGreen; + if (blendKey_.colorWriteMask & 4) mask |= MTLColorWriteMaskBlue; + if (blendKey_.colorWriteMask & 8) mask |= MTLColorWriteMaskAlpha; + att.writeMask = mask; + att.blendingEnabled = blendKey_.blendEnable; + if (blendKey_.blendEnable) { + att.rgbBlendOperation = blendEqToMetal[blendKey_.eqColor]; + att.alphaBlendOperation = blendEqToMetal[blendKey_.eqAlpha]; + att.sourceRGBBlendFactor = blendFactorToMetal[blendKey_.srcColor]; + att.destinationRGBBlendFactor = blendFactorToMetal[blendKey_.dstColor]; + att.sourceAlphaBlendFactor = blendFactorToMetal[blendKey_.srcAlpha]; + att.destinationAlphaBlendFactor = blendFactorToMetal[blendKey_.dstAlpha]; + } + } + + NSError *error = nil; + pipeline->pso = [rm_->Device() newRenderPipelineStateWithDescriptor:desc error:&error]; + if (!pipeline->pso) { + ERROR_LOG(Log::G3D, "Failed to create pipeline (%s / %s): %s", vs->desc.c_str(), fs->desc.c_str(), error ? [[error localizedDescription] UTF8String] : "?"); + } + fragmentArrayTextureMask_ = pipeline->fragmentArrayTextureMask; + return pipeline->pso; +} + +void DrawEngineMetal::ConvertStateToKeys(int prim) { + bool useBufferedRendering = framebufferManager_->UseBufferedRendering(); + + if (gstate_c.IsDirty(DIRTY_BLEND_STATE)) { + if (gstate.isModeClear()) { + blendKey_.blendEnable = false; + blendKey_.eqColor = (uint32_t)BlendEq::ADD; + blendKey_.eqAlpha = (uint32_t)BlendEq::ADD; + blendKey_.srcColor = (uint32_t)BlendFactor::ONE; + blendKey_.srcAlpha = (uint32_t)BlendFactor::ONE; + blendKey_.dstColor = (uint32_t)BlendFactor::ZERO; + blendKey_.dstAlpha = (uint32_t)BlendFactor::ZERO; + blendKey_.colorWriteMask = ClearModeChannelMask(); + dynState_.useBlendColor = false; + } else { + pipelineState_.Convert(draw_->GetShaderLanguageDesc().bitwiseOps, gstate_c.Use(GPU_USE_SHADER_BLENDING)); + GenericMaskState &maskState = pipelineState_.maskState; + GenericBlendState &blendState = pipelineState_.blendState; + + if (pipelineState_.FramebufferRead() && useBufferedRendering) { + ApplyFramebufferRead(&fboTexBindState_); + // The shader takes over the responsibility for blending, so recompute. + ApplyStencilReplaceAndLogicOpIgnoreBlend(blendState.replaceAlphaWithStencil, blendState); + dirtyRequiresRecheck_ |= DIRTY_FRAGMENTSHADER_STATE; + gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE); + } else if (fboTexBound_) { + boundSecondary_ = nil; + fboTexBound_ = false; + dirtyRequiresRecheck_ |= DIRTY_FRAGMENTSHADER_STATE; + gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE); + } + + if (blendState.blendEnabled) { + blendKey_.blendEnable = true; + blendKey_.eqColor = (uint32_t)blendState.eqColor; + blendKey_.eqAlpha = (uint32_t)blendState.eqAlpha; + blendKey_.srcColor = (uint32_t)blendState.srcColor; + blendKey_.srcAlpha = (uint32_t)blendState.srcAlpha; + blendKey_.dstColor = (uint32_t)blendState.dstColor; + blendKey_.dstAlpha = (uint32_t)blendState.dstAlpha; + if (blendState.dirtyShaderBlendFixValues) { + dirtyRequiresRecheck_ |= DIRTY_SHADERBLEND; + gstate_c.Dirty(DIRTY_SHADERBLEND); + } + dynState_.useBlendColor = blendState.useBlendColor; + if (blendState.useBlendColor) { + blendState.blendColorToFloat4(dynState_.blendColor); + } + } else { + blendKey_.blendEnable = false; + blendKey_.eqColor = (uint32_t)BlendEq::ADD; + blendKey_.eqAlpha = (uint32_t)BlendEq::ADD; + blendKey_.srcColor = (uint32_t)BlendFactor::ONE; + blendKey_.srcAlpha = (uint32_t)BlendFactor::ONE; + blendKey_.dstColor = (uint32_t)BlendFactor::ZERO; + blendKey_.dstAlpha = (uint32_t)BlendFactor::ZERO; + dynState_.useBlendColor = false; + } + blendKey_.colorWriteMask = maskState.channelMask; + } + } + + if (gstate_c.IsDirty(DIRTY_RASTER_STATE)) { + bool wantCull = !gstate.isModeClear() && prim != GE_PRIM_RECTANGLES && prim > GE_PRIM_LINE_STRIP && gstate.isCullEnabled(); + dynState_.cull = wantCull ? (gstate.getCullMode() ? MTLCullModeFront : MTLCullModeBack) : MTLCullModeNone; + if (gstate.isModeClear() || gstate.isModeThrough()) { + dynState_.depthClamp = false; + } else if (gstate.getDepthRangeMin() == 0 || gstate.getDepthRangeMax() == 65535) { + dynState_.depthClamp = gstate.isDepthClipEnabled() && gstate_c.Use(GPU_USE_DEPTH_CLAMP); + } else { + dynState_.depthClamp = false; + } + } + + if (gstate_c.IsDirty(DIRTY_DEPTHSTENCIL_STATE)) { + GenericStencilFuncState stencilState; + ConvertStencilFuncState(stencilState); + MetalDepthStencilKey &key = depthStencilKey_; + key.value = 0; + + if (gstate.isModeClear()) { + key.depthTestEnable = true; + key.depthCompare = GE_COMP_ALWAYS; + key.depthWriteEnable = gstate.isClearModeDepthMask(); + if (gstate.isClearModeAlphaMask()) { + key.stencilTestEnable = true; + key.stencilCompare = GE_COMP_ALWAYS; + key.stencilPass = GE_STENCILOP_REPLACE; + key.stencilFail = GE_STENCILOP_REPLACE; + key.stencilDepthFail = GE_STENCILOP_REPLACE; + key.writeMask = stencilState.writeMask; + key.compareMask = 0xFF; + // Overridden from software transform for clear rectangles. + dynState_.stencilRef = 0xFF; + } + } else { + if (!IsDepthTestEffectivelyDisabled()) { + key.depthTestEnable = true; + key.depthCompare = gstate.getDepthTestFunction(); + key.depthWriteEnable = gstate.isDepthWriteEnabled(); + UpdateEverUsedEqualDepth(gstate.getDepthTestFunction()); + } + if (stencilState.enabled) { + key.stencilTestEnable = true; + key.stencilCompare = stencilState.testFunc; + key.stencilPass = stencilState.zPass; + key.stencilFail = stencilState.sFail; + key.stencilDepthFail = stencilState.zFail; + key.writeMask = stencilState.writeMask; + key.compareMask = stencilState.testMask; + dynState_.stencilRef = stencilState.testRef; + + // Nasty special case for Spongebob and similar, see StateMappingVulkan.cpp. + if (SpongebobDepthInverseConditions(stencilState)) { + blendKey_.blendEnable = true; + blendKey_.eqAlpha = (uint32_t)BlendEq::ADD; + blendKey_.eqColor = (uint32_t)BlendEq::ADD; + blendKey_.srcColor = (uint32_t)BlendFactor::ZERO; + blendKey_.dstColor = (uint32_t)BlendFactor::ZERO; + blendKey_.srcAlpha = (uint32_t)BlendFactor::ZERO; + blendKey_.dstAlpha = (uint32_t)BlendFactor::ZERO; + blendKey_.colorWriteMask = 8; + key.depthCompare = GE_COMP_LESS; // Inverse of GREATER_EQUAL + key.stencilCompare = GE_COMP_ALWAYS; + key.stencilPass = GE_STENCILOP_ZERO; + key.stencilFail = GE_STENCILOP_ZERO; + key.stencilDepthFail = GE_STENCILOP_KEEP; + dirtyRequiresRecheck_ |= DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE; + gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE); + } + } + } + } + + if (gstate_c.IsDirty(DIRTY_VIEWPORTSCISSOR_STATE)) { + ViewportAndScissor vpAndScissor; + ConvertViewportAndScissor( + framebufferManager_->GetDisplayLayoutConfigCopy(), + useBufferedRendering, + framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), + framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), + vpAndScissor); + dynState_.viewport = MTLViewport{ vpAndScissor.viewportX, vpAndScissor.viewportY, vpAndScissor.viewportW, vpAndScissor.viewportH, 0.0, 1.0 }; + dynState_.scissor[0] = vpAndScissor.scissorX; + dynState_.scissor[1] = vpAndScissor.scissorY; + dynState_.scissor[2] = std::max(0, vpAndScissor.scissorW); + dynState_.scissor[3] = std::max(0, vpAndScissor.scissorH); + } +} + +void DrawEngineMetal::BindShaderBlendTex() { + if (!gstate.isModeClear() && fboTexBindState_ == FBO_TEX_COPY_BIND_TEX) { + VirtualFramebuffer *curRenderVfb = framebufferManager_->GetCurrentRenderVFB(); + bool bindResult = framebufferManager_->BindFramebufferAsColorTexture(1, curRenderVfb, BINDFBCOLOR_MAY_COPY | BINDFBCOLOR_UNCACHED, Draw::ALL_LAYERS); + _dbg_assert_(bindResult); + boundSecondary_ = (__bridge id)(void *)draw_->GetNativeObject(Draw::NativeObject::BOUND_TEXTURE1_IMAGEVIEW); + fboTexBound_ = true; + fboTexBindState_ = FBO_TEX_NONE; + // Must dirty blend state here so we re-copy next time. Example: Lunar's spell effects. + dirtyRequiresRecheck_ |= DIRTY_BLEND_STATE; + } else if (gstate.isModeClear() || !fboTexBound_) { + boundSecondary_ = nil; + } +} + +bool DrawEngineMetal::ApplyState(id pipeline, bool overrideStencilRef, uint8_t stencilRef) { + if (!rm_->RenderEncoder()) { + return false; + } + rm_->SetPipeline(pipeline); + rm_->SetDepthStencilState(GetDepthStencilState(depthStencilKey_)); + if (depthStencilKey_.stencilTestEnable) { + rm_->SetStencilRef(overrideStencilRef ? stencilRef : dynState_.stencilRef); + } + if (dynState_.useBlendColor) { + rm_->SetBlendColor(dynState_.blendColor[0], dynState_.blendColor[1], dynState_.blendColor[2], dynState_.blendColor[3]); + } + rm_->SetCullMode(dynState_.cull); + rm_->SetFrontFacing(MTLWindingCounterClockwise); + rm_->SetDepthClip(dynState_.depthClamp ? MTLDepthClipModeClamp : MTLDepthClipModeClip); + rm_->SetViewport(dynState_.viewport); + return rm_->SetScissor(dynState_.scissor[0], dynState_.scissor[1], dynState_.scissor[2], dynState_.scissor[3]); +} + +void DrawEngineMetal::BindResources() { + uint64_t dirty = shaderManager_->UpdateUniforms(framebufferManager_->UseBufferedRendering(), false); + if ((dirty & DIRTY_BASE_UNIFORMS) || !baseUBO_.buffer || uboFrame_ != rm_->FrameNumber()) { + baseUBO_ = rm_->Push().Push(&shaderManager_->BaseUniforms(), sizeof(UB_VS_FS_Base), 256); + } + if ((dirty & DIRTY_LIGHT_UNIFORMS) || !lightUBO_.buffer || uboFrame_ != rm_->FrameNumber()) { + lightUBO_ = rm_->Push().Push(&shaderManager_->LightUniforms(), sizeof(UB_VS_Lights), 256); + } + uboFrame_ = rm_->FrameNumber(); + rm_->SetVertexBuffer(baseUBO_.buffer, baseUBO_.offset, METAL_DRAW_BINDING_DYNUBO_BASE); + rm_->SetFragmentBuffer(baseUBO_.buffer, baseUBO_.offset, METAL_DRAW_BINDING_DYNUBO_BASE); + rm_->SetVertexBuffer(lightUBO_.buffer, lightUBO_.offset, METAL_DRAW_BINDING_DYNUBO_LIGHT); + + auto bindTexture = [&](id tex, id sampler, int index) { + if (!tex) { + tex = nullTexture_; + } + if (fragmentArrayTextureMask_ & (1 << index)) { + tex = rm_->ArrayView(tex); + } + rm_->SetFragmentTexture(tex, index); + rm_->SetFragmentSampler(sampler ? sampler : samplerNearest_, index); + }; + bindTexture(textureCache_->BoundTexture(), textureCache_->BoundSampler(), METAL_DRAW_BINDING_TEXTURE); + bindTexture(boundSecondary_, samplerNearest_, METAL_DRAW_BINDING_2ND_TEXTURE); + bindTexture(boundDepal_, boundDepalSmoothed_ ? samplerLinear_ : samplerNearest_, METAL_DRAW_BINDING_DEPAL_TEXTURE); +} + +void DrawEngineMetal::DrawPrimitives(MTLPrimitiveType prim, id vbuf, uint32_t vbOffset, int count, const uint16_t *inds) { + id enc = rm_->RenderEncoder(); + rm_->SetVertexBuffer(vbuf, vbOffset, METAL_VERTEX_BUFFER_INDEX); + if (inds) { + MetalPushAlloc ialloc = rm_->Push().Push(inds, count * sizeof(uint16_t), 4); + [enc drawIndexedPrimitives:prim indexCount:count indexType:MTLIndexTypeUInt16 indexBuffer:ialloc.buffer indexBufferOffset:ialloc.offset]; + } else { + [enc drawPrimitives:prim vertexStart:0 vertexCount:count]; + } +} + +void DrawEngineMetal::ResetAfterSkippedDraw() { + indexGen.Reset(); + numDecodedVerts_ = 0; + numDrawVerts_ = 0; + numDrawInds_ = 0; + vertexCountInDrawCalls_ = 0; + expandedVertsInDrawCalls_ = 0; + numVertsToDecode_ = 0; + decodeIndsCounter_ = 0; + decodeVertsCounter_ = 0; + gstate_c.vertexFullAlpha = true; +} + +void DrawEngineMetal::Flush() { + if (!numDrawVerts_) { + return; + } + PROFILE_THIS_SCOPE("Flush"); + + GEPrimitiveType prim = prevPrim_; + + // Metal's provoking vertex is the first one, so flat shading goes through software transform. + bool provokingVertexOk = gstate.getShadeMode() != GE_SHADE_FLAT; + bool useHWTransform = CanUseHardwareTransform(prim) && provokingVertexOk; + if (clipInfoFlags_ & ClipInfoFlags::Valid) { + if (clipInfoFlags_ & ClipInfoFlags::SoftClipCull) { + useHWTransform = false; + } + } + if (clipInfoFlags_ != lastClipInfoFlags_) { + ClipInfoFlags changed = (ClipInfoFlags)((u32)clipInfoFlags_ ^ (u32)lastClipInfoFlags_); + if (changed & (ClipInfoFlags::DepthClampFragment | ClipInfoFlags::MinMaxZDiscard)) { + gstate_c.Dirty(DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_RASTER_STATE); + } + if (changed & ClipInfoFlags::FlatZ) { + gstate_c.Dirty(DIRTY_TEXTURE_PARAMS); + } + lastClipInfoFlags_ = clipInfoFlags_; + } + if (useHWTransform != lastUseHwTransform_) { + gstate_c.Dirty(DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_RASTER_STATE); + lastUseHwTransform_ = useHWTransform; + } + + auto updateVertexFullAlpha = [&]() { + bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; + if (gstate.isModeThrough()) { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255); + } else { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255); + } + }; + + auto updatePipeline = [&](bool hwTransform) -> id { + if (!lastPipeline_ || gstate_c.IsDirty(DIRTY_BLEND_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_RASTER_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE) || prim != lastPrim_) { + if (prim != lastPrim_ || gstate_c.IsDirty(DIRTY_BLEND_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_RASTER_STATE | DIRTY_DEPTHSTENCIL_STATE)) { + ConvertStateToKeys(prim); + } + VShaderID vsid; + FShaderID fsid; + shaderManager_->GetShaderIDs(prim, dec_->VertexType(), &vsid, &fsid, pipelineState_, hwTransform, clipInfoFlags_); + // This might copy the framebuffer, which interrupts the render pass. So it goes before the pipeline lookup, + // which depends on the render target. + BindShaderBlendTex(); + lastPipeline_ = GetPipeline(vsid, fsid, hwTransform); + gstate_c.Clean(DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_RASTER_STATE | DIRTY_VIEWPORTSCISSOR_STATE); + gstate_c.Dirty(dirtyRequiresRecheck_); + dirtyRequiresRecheck_ = 0; + } + lastPrim_ = prim; + return lastPipeline_; + }; + + if (useHWTransform) { + MetalPushAlloc valloc; + if (lastVType_ & GE_VTYPE_WEIGHT_MASK) { + // If skinning, we're predecoding into "decoded". So make sure we're done, then push that content. + DecodeVerts(dec_, decoded_); + valloc = rm_->Push().Push(decoded_, numDecodedVerts_ * dec_->GetDecVtxFmt().stride, 16); + } else { + int vertsToDecode = ComputeNumVertsToDecode(); + valloc = rm_->Push().Allocate(vertsToDecode * dec_->GetDecVtxFmt().stride, 16); + DecodeVerts(dec_, valloc.ptr); + } + + int vertexCount; + int maxIndex; + bool useElements; + DecodeIndsAndGetData(&prim, &vertexCount, &maxIndex, &useElements, false); + gpuStats.perFrame.numVertsDrawn += vertexCount; + updateVertexFullAlpha(); + + if (gstate_c.IsDirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS) && !gstate.isModeClear() && gstate.isTextureMapEnabled()) { + gstate_c.Clean(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS); + const TextureApplyResult textureResult = textureCache_->ApplyTexture(true); + textureCache_->ApplySampler(textureResult, clipInfoFlags_ & ClipInfoFlags::FlatZ, false); + } else if (gstate.getTextureAddress(0) == (gstate.getFrameBufRawAddress() | 0x04000000)) { + // This catches the case of clearing a texture. + gstate_c.Dirty(DIRTY_TEXTURE_IMAGE); + } + + id pipeline = updatePipeline(true); + if (!pipeline || !ApplyState(pipeline, false, 0)) { + ResetAfterSkippedDraw(); + return; + } + BindResources(); + MTLPrimitiveType mtlPrim = prim == GE_PRIM_TRIANGLE_STRIP ? MTLPrimitiveTypeTriangleStrip : MTLPrimitiveTypeTriangle; + DrawPrimitives(mtlPrim, valloc.buffer, valloc.offset, vertexCount, useElements ? decIndex_ : nullptr); + if (useDepthRaster_) { + DepthRasterSubmitRaw(prim, dec_, dec_->VertexType(), vertexCount); + } + } else { + gpuStats.perFrame.numSoftTransformedDraws++; + PROFILE_THIS_SCOPE("soft"); + + DecodeVerts(dec_, decoded_); + int vertexCount = DecodeInds(); + updateVertexFullAlpha(); + + gpuStats.perFrame.numVertsDrawn += vertexCount; + prim = IndexGenerator::GeneralPrim((GEPrimitiveType)drawInds_[0].prim); + + if (useDepthRaster_) { + DepthRasterPredecoded(prim, decoded_, numDecodedVerts_, dec_, vertexCount); + } + + u16 *inds = decIndex_; + if (gstate.getShadeMode() == GE_SHADE_FLAT) { + // Rotate the index buffer to simulate a different provoking vertex. + IndexBufferProvokingLastToFirst(prim, inds, vertexCount); + } + + bool textureNeedsApply = false; + TextureApplyResult textureResult; + if (gstate_c.IsDirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS) && !gstate.isModeClear() && gstate.isTextureMapEnabled()) { + gstate_c.Clean(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS); + gstate_c.dstSquared = false; + textureResult = textureCache_->ApplyTexture(true); + // NOTE: After this is set, we MUST call ApplySampler before returning. + textureNeedsApply = true; + } else if (gstate.getTextureAddress(0) == (gstate.getFrameBufRawAddress() | 0x04000000)) { + gstate_c.Dirty(DIRTY_TEXTURE_IMAGE); + } + + SoftwareTransformResult result{}; + SoftwareTransformParams params{}; + params.decoded = decoded_; + params.transformed = transformed_; + params.transformedExpanded = transformedExpanded_; + // Clears through the render pass don't respect the scissor, so only allow them when buffered. + params.allowClear = framebufferManager_->UseBufferedRendering(); + params.allowSeparateAlphaClear = false; + params.everUsedEqualDepth = everUsedEqualDepth_; + params.clipInfoFlags = clipInfoFlags_; + params.trianglesReversed = BatchTrianglesReversed(); + + const SoftwareTransformAction action = RunSoftwareTransform(params, prim, dec_->VertexType(), dec_->GetDecVtxFmt(), numDecodedVerts_, VERTEX_BUFFER_MAX, vertexCount, inds, RemainingIndices(inds), &result); + if (textureNeedsApply) { + textureCache_->ApplySampler(textureResult, clipInfoFlags_ & ClipInfoFlags::FlatZ, result.pixelMapped); + if (gstate_c.dstSquared) { + gstate_c.Dirty(DIRTY_BLEND_STATE); + } + } + if (action == SW_DRAW_INDEXED) { + id pipeline = updatePipeline(false); + if (!pipeline || !ApplyState(pipeline, result.setStencil, result.stencilValue)) { + ResetAfterSkippedDraw(); + return; + } + // UpdateUniforms in BindResources would otherwise use pixelMapped = false. + uint64_t dirty = shaderManager_->UpdateUniforms(framebufferManager_->UseBufferedRendering(), result.pixelMapped); + if (dirty & DIRTY_BASE_UNIFORMS) { + baseUBO_ = MetalPushAlloc{}; + } + if (dirty & DIRTY_LIGHT_UNIFORMS) { + lightUBO_ = MetalPushAlloc{}; + } + BindResources(); + MetalPushAlloc valloc = rm_->Push().Push(result.drawBuffer, result.drawVertexCount * sizeof(TransformedVertex), 16); + DrawPrimitives(MTLPrimitiveTypeTriangle, valloc.buffer, valloc.offset, result.drawIndexCount, inds); + } else if (action == SW_CLEAR) { + // Note: we won't get here if the clear is alpha but not color, or color but not alpha. + bool clearColor = gstate.isClearModeColorMask(); + bool clearAlpha = gstate.isClearModeAlphaMask(); // and stencil + bool clearDepth = gstate.isClearModeDepthMask(); + Draw::Aspect mask = Draw::Aspect::NO_BIT; + if (clearColor || clearAlpha) mask |= Draw::Aspect::COLOR_BIT; + if (clearDepth) mask |= Draw::Aspect::DEPTH_BIT; + if (clearAlpha) mask |= Draw::Aspect::STENCIL_BIT; + // The alpha channel and the stencil channel are shared on the PSP. + draw_->Clear(mask, result.color, result.depth, result.color >> 24); + if (gstate_c.Use(GPU_USE_CLEAR_RAM_HACK) && gstate.isClearModeColorMask() && (gstate.isClearModeAlphaMask() || gstate.FrameBufFormat() == GE_FORMAT_565)) { + int scissorX1 = gstate.getScissorX1(); + int scissorY1 = gstate.getScissorY1(); + int scissorX2 = gstate.getScissorX2() + 1; + int scissorY2 = gstate.getScissorY2() + 1; + framebufferManager_->ApplyClearToMemory(scissorX1, scissorY1, scissorX2, scissorY2, result.color); + } + } + } + + ResetAfterDrawInline(); + framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); + gpuCommon_->NotifyFlush(); +} diff --git a/GPU/Metal/FramebufferManagerMetal.h b/GPU/Metal/FramebufferManagerMetal.h new file mode 100644 index 0000000000..4fdd271e36 --- /dev/null +++ b/GPU/Metal/FramebufferManagerMetal.h @@ -0,0 +1,25 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "GPU/Common/FramebufferManagerCommon.h" + +class FramebufferManagerMetal : public FramebufferManagerCommon { +public: + FramebufferManagerMetal(Draw::DrawContext *draw); +}; diff --git a/GPU/Metal/FramebufferManagerMetal.mm b/GPU/Metal/FramebufferManagerMetal.mm new file mode 100644 index 0000000000..6b3a307934 --- /dev/null +++ b/GPU/Metal/FramebufferManagerMetal.mm @@ -0,0 +1,23 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "GPU/Common/PresentationCommon.h" +#include "GPU/Metal/FramebufferManagerMetal.h" + +FramebufferManagerMetal::FramebufferManagerMetal(Draw::DrawContext *draw) : FramebufferManagerCommon(draw) { + presentation_->SetLanguage(GLSL_VULKAN); +} diff --git a/GPU/Metal/GPU_Metal.h b/GPU/Metal/GPU_Metal.h new file mode 100644 index 0000000000..b26ebd03a3 --- /dev/null +++ b/GPU/Metal/GPU_Metal.h @@ -0,0 +1,51 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +// Plain C++, so GPU.cpp can create it. The parts are Objective-C++. + +#include "GPU/GPUCommonHW.h" + +class FramebufferManagerMetal; +class ShaderManagerMetal; +class TextureCacheMetal; +class DrawEngineMetal; +class StringWriter; + +class GPU_Metal : public GPUCommonHW { +public: + GPU_Metal(GraphicsContext *gfxCtx, Draw::DrawContext *draw); + ~GPU_Metal(); + + u32 CheckGPUFeatures() const override; + + void BeginHostFrame(const DisplayLayoutConfig &config) override; + + void GetStats(StringWriter &w) override; + void DeviceLost() override; + void DeviceRestore(Draw::DrawContext *draw) override; + +protected: + void FinishDeferred() override; + +private: + FramebufferManagerMetal *framebufferManagerMetal_; + TextureCacheMetal *textureCacheMetal_; + ShaderManagerMetal *shaderManagerMetal_; + DrawEngineMetal *drawEngine_; +}; diff --git a/GPU/Metal/GPU_Metal.mm b/GPU/Metal/GPU_Metal.mm new file mode 100644 index 0000000000..2447db190c --- /dev/null +++ b/GPU/Metal/GPU_Metal.mm @@ -0,0 +1,114 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "ppsspp_config.h" + +#include "Common/Log.h" +#include "Common/Data/Text/StringWriter.h" +#include "Common/GPU/thin3d.h" +#include "Core/Reporting.h" +#include "GPU/GPUState.h" +#include "GPU/Metal/GPU_Metal.h" +#include "GPU/Metal/DrawEngineMetal.h" +#include "GPU/Metal/FramebufferManagerMetal.h" +#include "GPU/Metal/ShaderManagerMetal.h" +#include "GPU/Metal/TextureCacheMetal.h" + +GPU_Metal::GPU_Metal(GraphicsContext *gfxCtx, Draw::DrawContext *draw) : GPUCommonHW(gfxCtx, draw) { + gstate_c.SetUseFlags(CheckGPUFeatures()); + + drawEngine_ = new DrawEngineMetal(draw); + shaderManagerMetal_ = new ShaderManagerMetal(draw); + framebufferManagerMetal_ = new FramebufferManagerMetal(draw); + framebufferManager_ = framebufferManagerMetal_; + textureCacheMetal_ = new TextureCacheMetal(draw, framebufferManager_->GetDraw2D()); + textureCache_ = textureCacheMetal_; + drawEngineCommon_ = drawEngine_; + shaderManager_ = shaderManagerMetal_; + + drawEngine_->SetGPUCommon(this); + drawEngine_->SetTextureCache(textureCacheMetal_); + drawEngine_->SetFramebufferManager(framebufferManagerMetal_); + drawEngine_->SetShaderManager(shaderManagerMetal_); + drawEngine_->Init(); + framebufferManagerMetal_->SetTextureCache(textureCacheMetal_); + framebufferManagerMetal_->SetDrawEngine(drawEngine_); + framebufferManagerMetal_->SetShaderManager(shaderManagerMetal_); + framebufferManagerMetal_->Init(msaaLevel_); + textureCacheMetal_->SetFramebufferManager(framebufferManagerMetal_); + textureCacheMetal_->SetShaderManager(shaderManagerMetal_); + textureCacheMetal_->SetDrawEngine(drawEngine_); + + UpdateCmdInfo(); + BuildReportingInfo(); + textureCache_->NotifyConfigChanged(); +} + +GPU_Metal::~GPU_Metal() { + if (draw_) { + MetalRenderManager *rm = (MetalRenderManager *)draw_->GetNativeObject(Draw::NativeObject::RENDER_MANAGER); + rm->WaitIdle(); + } + // The other managers are deleted in ~GPUCommonHW. + delete drawEngine_; + drawEngine_ = nullptr; + drawEngineCommon_ = nullptr; +} + +u32 GPU_Metal::CheckGPUFeatures() const { + u32 features = GPUCommonHW::CheckGPUFeatures(); + return CheckGPUFeaturesLate(features); +} + +void GPU_Metal::BeginHostFrame(const DisplayLayoutConfig &config) { + GPUCommonHW::BeginHostFrame(config); + + drawEngine_->BeginFrame(); + textureCache_->StartFrame(); + framebufferManager_->BeginFrame(config); + + gstate_c.Dirty(DIRTY_ALL); + + if (gstate_c.useFlagsChanged) { + WARN_LOG(Log::G3D, "Shader use flags changed, clearing all shaders and depth buffers"); + drawEngine_->ClearPipelines(); + shaderManager_->ClearShaders(); + framebufferManager_->ClearAllDepthBuffers(); + gstate_c.useFlagsChanged = false; + } +} + +void GPU_Metal::FinishDeferred() { + drawEngine_->FinishDeferred(); +} + +void GPU_Metal::DeviceLost() { + drawEngine_->ClearPipelines(); + GPUCommonHW::DeviceLost(); +} + +void GPU_Metal::DeviceRestore(Draw::DrawContext *draw) { + GPUCommonHW::DeviceRestore(draw); +} + +void GPU_Metal::GetStats(StringWriter &w) { + w.F("Vertex, Fragment shaders, Pipelines loaded: %d, %d, %d\n", + shaderManagerMetal_->GetNumVertexShaders(), + shaderManagerMetal_->GetNumFragmentShaders(), + drawEngine_->GetNumPipelines()); + FormatGPUStatsCommon(w); +} diff --git a/GPU/Metal/ShaderManagerMetal.h b/GPU/Metal/ShaderManagerMetal.h new file mode 100644 index 0000000000..de0968d4ac --- /dev/null +++ b/GPU/Metal/ShaderManagerMetal.h @@ -0,0 +1,111 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +// Objective-C++ only. + +#include + +#include "Common/Data/Collections/Hashmaps.h" +#include "Common/GPU/Metal/MetalRenderManager.h" +#include "GPU/Common/ShaderCommon.h" +#include "GPU/Common/ShaderId.h" +#include "GPU/Common/ShaderUniforms.h" +#include "GPU/Common/VertexShaderGenerator.h" +#include "GPU/Common/FragmentShaderGenerator.h" + +enum class ClipInfoFlags; +struct ComputedPipelineState; + +// The game shaders are the Vulkan ones, translated to MSL. So these follow DRAW_BINDING_* in DrawEngineVulkan.h. +enum { + METAL_DRAW_BINDING_TEXTURE = 0, + METAL_DRAW_BINDING_2ND_TEXTURE = 1, + METAL_DRAW_BINDING_DEPAL_TEXTURE = 2, + METAL_DRAW_BINDING_DYNUBO_BASE = 3, + METAL_DRAW_BINDING_DYNUBO_LIGHT = 4, +}; + +class MetalShader { +public: + MetalShader(id device, ShaderStage stage, const std::string &source, const std::string &desc); + + bool Failed() const { return function == nil; } + std::string GetShaderString(DebugShaderStringType type) const; + + id function; + MetalTranslatedShader info; + std::string source; + std::string desc; +}; + +class MetalVertexShader : public MetalShader { +public: + MetalVertexShader(id device, VShaderID vsid, VertexShaderFlags flags, const std::string &source) + : MetalShader(device, ShaderStage::Vertex, source, vsid.Description()), id_(vsid), flags_(flags) {} + VShaderID id_; + VertexShaderFlags flags_; +}; + +class MetalFragmentShader : public MetalShader { +public: + MetalFragmentShader(id device, FShaderID fsid, FragmentShaderFlags flags, const std::string &source) + : MetalShader(device, ShaderStage::Fragment, source, fsid.Description()), id_(fsid), flags_(flags) {} + FShaderID id_; + FragmentShaderFlags flags_; +}; + +class ShaderManagerMetal : public ShaderManagerCommon { +public: + ShaderManagerMetal(Draw::DrawContext *draw); + ~ShaderManagerMetal(); + + void DeviceLost() override; + void DeviceRestore(Draw::DrawContext *draw) override; + void ClearShaders() override; + + void GetShaderIDs(int prim, u32 vertexType, VShaderID *vshader, FShaderID *fshader, const ComputedPipelineState &pipelineState, bool useHWTransform, ClipInfoFlags clipInfoFlags); + + MetalVertexShader *GetVertexShaderFromID(VShaderID vsid); + MetalFragmentShader *GetFragmentShaderFromID(FShaderID fsid); + + int GetNumVertexShaders() const { return (int)vsCache_.size(); } + int GetNumFragmentShaders() const { return (int)fsCache_.size(); } + + std::vector DebugGetShaderIDs(DebugShaderType type) override; + std::string DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType) override; + + // Returns the dirty uniform flags. + uint64_t UpdateUniforms(bool useBufferedRendering, bool pixelMapped); + const UB_VS_FS_Base &BaseUniforms() const { return ub_base_; } + const UB_VS_Lights &LightUniforms() const { return ub_lights_; } + +private: + void Clear(); + + ShaderLanguageDesc compat_; + DenseHashMap vsCache_; + DenseHashMap fsCache_; + char *codeBuffer_; + + UB_VS_FS_Base ub_base_{}; + UB_VS_Lights ub_lights_{}; + + VShaderID lastVSID_; + FShaderID lastFSID_; +}; diff --git a/GPU/Metal/ShaderManagerMetal.mm b/GPU/Metal/ShaderManagerMetal.mm new file mode 100644 index 0000000000..1bbcbc5d83 --- /dev/null +++ b/GPU/Metal/ShaderManagerMetal.mm @@ -0,0 +1,187 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "ppsspp_config.h" + +#include "Common/Log.h" +#include "Common/LogReporting.h" +#include "Common/Profiler/Profiler.h" +#include "Common/StringUtils.h" +#include "Common/GPU/thin3d.h" +#include "GPU/GPUState.h" +#include "GPU/Common/DrawEngineCommon.h" +#include "GPU/Metal/ShaderManagerMetal.h" + +static constexpr size_t CODE_BUFFER_SIZE = 32768; + +MetalShader::MetalShader(id device, ShaderStage stage, const std::string &src, const std::string &description) : source(src), desc(description) { + PROFILE_THIS_SCOPE("shadercomp"); + std::string errorMessage; + if (!TranslateVulkanGLSLToMSL(stage, source.c_str(), &info, &errorMessage)) { + ERROR_LOG(Log::G3D, "Failed to translate %s shader (%s): %s\n%s", ShaderStageAsString(stage), desc.c_str(), errorMessage.c_str(), LineNumberString(source).c_str()); + Reporting::ReportMessage("Metal shader translation failed: %s / code: %s", errorMessage.c_str(), source.c_str()); + return; + } + function = CreateMetalFunction(device, info, desc.c_str(), &errorMessage); + if (!function) { + ERROR_LOG(Log::G3D, "%s\n%s", errorMessage.c_str(), LineNumberString(info.msl).c_str()); + } +} + +std::string MetalShader::GetShaderString(DebugShaderStringType type) const { + switch (type) { + case SHADER_STRING_SOURCE_CODE: return source + "\n\n// MSL:\n\n" + info.msl; + case SHADER_STRING_SHORT_DESC: return desc; + default: return "N/A"; + } +} + +ShaderManagerMetal::ShaderManagerMetal(Draw::DrawContext *draw) + : ShaderManagerCommon(draw), compat_(GLSL_VULKAN), vsCache_(16), fsCache_(16) { + codeBuffer_ = new char[CODE_BUFFER_SIZE]; +} + +ShaderManagerMetal::~ShaderManagerMetal() { + Clear(); + delete[] codeBuffer_; +} + +void ShaderManagerMetal::DeviceLost() { + Clear(); + draw_ = nullptr; +} + +void ShaderManagerMetal::DeviceRestore(Draw::DrawContext *draw) { + draw_ = draw; +} + +void ShaderManagerMetal::Clear() { + vsCache_.Iterate([](const VShaderID &, MetalVertexShader *shader) { + delete shader; + }); + fsCache_.Iterate([](const FShaderID &, MetalFragmentShader *shader) { + delete shader; + }); + vsCache_.Clear(); + fsCache_.Clear(); + lastVSID_.set_invalid(); + lastFSID_.set_invalid(); + gstate_c.Dirty(DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); +} + +void ShaderManagerMetal::ClearShaders() { + Clear(); + gstate_c.Dirty(DIRTY_ALL_UNIFORMS | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); +} + +uint64_t ShaderManagerMetal::UpdateUniforms(bool useBufferedRendering, bool pixelMapped) { + uint64_t dirty = gstate_c.GetDirtyUniforms(); + if (dirty != 0) { + if (dirty & DIRTY_BASE_UNIFORMS) + BaseUpdateUniforms(&ub_base_, dirty, useBufferedRendering, pixelMapped); + if (dirty & DIRTY_LIGHT_UNIFORMS) + LightUpdateUniforms(&ub_lights_, dirty); + } + gstate_c.CleanUniforms(); + return dirty; +} + +MetalVertexShader *ShaderManagerMetal::GetVertexShaderFromID(VShaderID vsid) { + MetalVertexShader *vs = vsCache_.GetOrNull(vsid); + if (vs) { + return vs; + } + std::string genErrorString; + uint64_t uniformMask = 0; + uint32_t attributeMask = 0; + VertexShaderFlags flags{}; + bool success = GenerateVertexShader(vsid, codeBuffer_, compat_, draw_->GetBugs(), &attributeMask, &uniformMask, &flags, &genErrorString); + _assert_msg_(success, "VS gen error: %s", genErrorString.c_str()); + id device = (__bridge id)(void *)draw_->GetNativeObject(Draw::NativeObject::DEVICE); + vs = new MetalVertexShader(device, vsid, flags, codeBuffer_); + vsCache_.Insert(vsid, vs); + return vs; +} + +MetalFragmentShader *ShaderManagerMetal::GetFragmentShaderFromID(FShaderID fsid) { + MetalFragmentShader *fs = fsCache_.GetOrNull(fsid); + if (fs) { + return fs; + } + std::string genErrorString; + uint64_t uniformMask = 0; + FragmentShaderFlags flags{}; + bool success = GenerateFragmentShader(fsid, codeBuffer_, compat_, draw_->GetBugs(), &uniformMask, &flags, &genErrorString); + _assert_msg_(success, "FS gen error: %s", genErrorString.c_str()); + id device = (__bridge id)(void *)draw_->GetNativeObject(Draw::NativeObject::DEVICE); + fs = new MetalFragmentShader(device, fsid, flags, codeBuffer_); + fsCache_.Insert(fsid, fs); + return fs; +} + +void ShaderManagerMetal::GetShaderIDs(int prim, u32 vertexType, VShaderID *vshader, FShaderID *fshader, const ComputedPipelineState &pipelineState, bool useHWTransform, ClipInfoFlags clipInfoFlags) { + if (gstate_c.IsDirty(DIRTY_VERTEXSHADER_STATE)) { + gstate_c.Clean(DIRTY_VERTEXSHADER_STATE); + ComputeVertexShaderID(&lastVSID_, vertexType, useHWTransform, clipInfoFlags); + } + *vshader = lastVSID_; + + if (gstate_c.IsDirty(DIRTY_FRAGMENTSHADER_STATE)) { + gstate_c.Clean(DIRTY_FRAGMENTSHADER_STATE); + ComputeFragmentShaderID(&lastFSID_, pipelineState, draw_->GetBugs(), clipInfoFlags); + } + *fshader = lastFSID_; + + _dbg_assert_(lastFSID_.Bit(FS_BIT_FLATSHADE) == lastVSID_.Bit(VS_BIT_FLATSHADE)); + _dbg_assert_msg_(lastVSID_.Bit(VS_BIT_USE_HW_TRANSFORM) == useHWTransform, "Bad vshader ID was computed"); +} + +std::vector ShaderManagerMetal::DebugGetShaderIDs(DebugShaderType type) { + std::vector ids; + switch (type) { + case SHADER_TYPE_VERTEX: + vsCache_.Iterate([&](const VShaderID &id, MetalVertexShader *) { + ids.push_back(id.ToUint64()); + }); + break; + case SHADER_TYPE_FRAGMENT: + fsCache_.Iterate([&](const FShaderID &id, MetalFragmentShader *) { + ids.push_back(id.ToUint64()); + }); + break; + default: + break; + } + return ToSortedDebugShaderIdVec(ids); +} + +std::string ShaderManagerMetal::DebugGetShaderString(std::string idStr, DebugShaderType type, DebugShaderStringType stringType) { + ShaderID shaderId; + shaderId.FromString(idStr); + switch (type) { + case SHADER_TYPE_VERTEX: { + MetalVertexShader *vs = vsCache_.GetOrNull(VShaderID(shaderId)); + return vs ? vs->GetShaderString(stringType) : ""; + } + case SHADER_TYPE_FRAGMENT: { + MetalFragmentShader *fs = fsCache_.GetOrNull(FShaderID(shaderId)); + return fs ? fs->GetShaderString(stringType) : ""; + } + default: + return "N/A"; + } +} diff --git a/GPU/Metal/TextureCacheMetal.h b/GPU/Metal/TextureCacheMetal.h new file mode 100644 index 0000000000..725329cf23 --- /dev/null +++ b/GPU/Metal/TextureCacheMetal.h @@ -0,0 +1,72 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +// Objective-C++ only. + +#include + +#include "Common/GPU/Metal/MetalRenderManager.h" +#include "GPU/Common/TextureCacheCommon.h" + +class FramebufferManagerMetal; +class ShaderManagerMetal; +class DrawEngineMetal; + +class TextureCacheMetal : public TextureCacheCommon { +public: + TextureCacheMetal(Draw::DrawContext *draw, Draw2D *draw2D); + ~TextureCacheMetal(); + + void SetFramebufferManager(FramebufferManagerMetal *fbManager); + void SetDrawEngine(DrawEngineMetal *drawEngine) { drawEngine_ = drawEngine; } + + void ForgetLastTexture() override {} + bool GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level, bool *isFramebuffer) override; + + void DeviceLost() override; + void DeviceRestore(Draw::DrawContext *draw) override; + + void *GetNativeTextureView(const TexCacheEntry *entry, bool flat) const override; + + // What the draw engine should bind at METAL_DRAW_BINDING_TEXTURE. Can be nil. + id BoundTexture() const { return boundTexture_; } + id BoundSampler() const { return boundSampler_; } + +protected: + void BindTexture(TexCacheEntry *entry) override; + void Unbind() override; + void ReleaseTexture(TexCacheEntry *entry, bool delete_them) override; + void BindAsClutTexture(Draw::Texture *tex, bool smooth) override; + void ApplySamplerByKey(const SamplerCacheKey &key) override; + void BoundFramebufferTexture() override; + void BuildTexture(TexCacheEntry *const entry) override; + +private: + static id Tex(const TexCacheEntry *entry) { + return (__bridge id)entry->texturePtr; + } + + MetalRenderManager *rm_ = nullptr; + DrawEngineMetal *drawEngine_ = nullptr; + + std::unordered_map> samplerCache_; + + id boundTexture_; + id boundSampler_; +}; diff --git a/GPU/Metal/TextureCacheMetal.mm b/GPU/Metal/TextureCacheMetal.mm new file mode 100644 index 0000000000..f3c7579bc3 --- /dev/null +++ b/GPU/Metal/TextureCacheMetal.mm @@ -0,0 +1,258 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "ppsspp_config.h" + +#include +#include + +#include "Common/Log.h" +#include "Common/GPU/thin3d.h" +#include "GPU/GPUState.h" +#include "GPU/Common/GPUDebugInterface.h" +#include "GPU/Metal/TextureCacheMetal.h" +#include "GPU/Metal/DrawEngineMetal.h" +#include "GPU/Metal/FramebufferManagerMetal.h" + +static MTLPixelFormat ToMetalFormat(Draw::DataFormat fmt) { + switch (fmt) { + case Draw::DataFormat::BC1_RGBA_UNORM_BLOCK: return MTLPixelFormatBC1_RGBA; + case Draw::DataFormat::BC2_UNORM_BLOCK: return MTLPixelFormatBC2_RGBA; + case Draw::DataFormat::BC3_UNORM_BLOCK: return MTLPixelFormatBC3_RGBA; + case Draw::DataFormat::BC4_UNORM_BLOCK: return MTLPixelFormatBC4_RUnorm; + case Draw::DataFormat::BC5_UNORM_BLOCK: return MTLPixelFormatBC5_RGUnorm; + case Draw::DataFormat::BC7_UNORM_BLOCK: return MTLPixelFormatBC7_RGBAUnorm; + case Draw::DataFormat::ASTC_4x4_UNORM_BLOCK: return MTLPixelFormatASTC_4x4_LDR; + case Draw::DataFormat::ETC2_R8G8B8_UNORM_BLOCK: return MTLPixelFormatETC2_RGB8; + case Draw::DataFormat::ETC2_R8G8B8A1_UNORM_BLOCK: return MTLPixelFormatETC2_RGB8A1; + case Draw::DataFormat::ETC2_R8G8B8A8_UNORM_BLOCK: return MTLPixelFormatEAC_RGBA8; + case Draw::DataFormat::R8_UNORM: return MTLPixelFormatR8Unorm; + case Draw::DataFormat::R8G8B8A8_UNORM: + default: + return MTLPixelFormatRGBA8Unorm; + } +} + +TextureCacheMetal::TextureCacheMetal(Draw::DrawContext *draw, Draw2D *draw2D) : TextureCacheCommon(draw, draw2D) { + rm_ = (MetalRenderManager *)draw->GetNativeObject(Draw::NativeObject::RENDER_MANAGER); +} + +TextureCacheMetal::~TextureCacheMetal() { + Clear(true); +} + +void TextureCacheMetal::SetFramebufferManager(FramebufferManagerMetal *fbManager) { + framebufferManager_ = fbManager; +} + +void TextureCacheMetal::DeviceLost() { + TextureCacheCommon::DeviceLost(); + samplerCache_.clear(); + boundTexture_ = nil; + boundSampler_ = nil; + draw_ = nullptr; + rm_ = nullptr; +} + +void TextureCacheMetal::DeviceRestore(Draw::DrawContext *draw) { + rm_ = (MetalRenderManager *)draw->GetNativeObject(Draw::NativeObject::RENDER_MANAGER); + TextureCacheCommon::DeviceRestore(draw); +} + +void TextureCacheMetal::ReleaseTexture(TexCacheEntry *entry, bool delete_them) { + if (entry->texturePtr) { + // Balances the __bridge_retained in BuildTexture. Command buffers that use it keep it alive as needed. + id tex = (__bridge_transfer id)entry->texturePtr; + tex = nil; + entry->texturePtr = nullptr; + } +} + +void TextureCacheMetal::BindTexture(TexCacheEntry *entry) { + if (!entry || !entry->texturePtr) { + Unbind(); + return; + } + drawEngine_->SetDepalTexture(nil, false); + boundTexture_ = Tex(entry); +} + +void TextureCacheMetal::Unbind() { + boundTexture_ = nil; + boundSampler_ = nil; +} + +void TextureCacheMetal::BindAsClutTexture(Draw::Texture *tex, bool smooth) { + id clut = (__bridge id)(void *)draw_->GetNativeObject(Draw::NativeObject::TEXTURE_VIEW, tex); + drawEngine_->SetDepalTexture(clut, smooth); +} + +void TextureCacheMetal::BoundFramebufferTexture() { + boundTexture_ = (__bridge id)(void *)draw_->GetNativeObject(Draw::NativeObject::BOUND_TEXTURE0_IMAGEVIEW); +} + +void TextureCacheMetal::ApplySamplerByKey(const SamplerCacheKey &key) { + auto iter = samplerCache_.find(key.fullKey); + if (iter != samplerCache_.end()) { + boundSampler_ = iter->second; + return; + } + MTLSamplerDescriptor *sd = [MTLSamplerDescriptor new]; + sd.minFilter = key.minFilt ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest; + sd.magFilter = key.magFilt ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest; + if (key.mipEnable) { + sd.mipFilter = key.mipFilt ? MTLSamplerMipFilterLinear : MTLSamplerMipFilterNearest; + } else { + sd.mipFilter = MTLSamplerMipFilterNotMipmapped; + } + sd.sAddressMode = key.sClamp ? MTLSamplerAddressModeClampToEdge : MTLSamplerAddressModeRepeat; + sd.tAddressMode = key.tClamp ? MTLSamplerAddressModeClampToEdge : MTLSamplerAddressModeRepeat; + sd.rAddressMode = MTLSamplerAddressModeClampToEdge; + // Metal only allows anisotropy with linear filters, like we want anyway. + if (key.aniso && key.minFilt && key.magFilt) { + sd.maxAnisotropy = std::clamp(1 << key.anisoLevel, 1, 16); + } + sd.lodMinClamp = std::max(0.0f, key.minLevel / 256.0f); + sd.lodMaxClamp = std::max(sd.lodMinClamp, key.maxLevel / 256.0f); + // Metal samplers have no LOD bias, the shaders apply it (GPU_USE_SHADER_LOD_BIAS). + id sampler = [rm_->Device() newSamplerStateWithDescriptor:sd]; + samplerCache_[key.fullKey] = sampler; + boundSampler_ = sampler; +} + +void TextureCacheMetal::BuildTexture(TexCacheEntry *const entry) { + BuildTexturePlan plan; + if (!PrepareBuildTexture(plan, entry)) { + ReleaseTexture(entry, true); + return; + } + + Draw::DataFormat dstFmt = Draw::DataFormat::R8G8B8A8_UNORM; + if (plan.decodeToClut8) { + dstFmt = Draw::DataFormat::R8_UNORM; + } else if (plan.doReplace) { + dstFmt = plan.replaced->Format(); + } + MTLPixelFormat mtlFmt = ToMetalFormat(dstFmt); + int blockSize = 0; + const bool compressed = Draw::DataFormatIsBlockCompressed(dstFmt, &blockSize); + const int bpp = (int)Draw::DataFormatSizeInBytes(dstFmt); + + // We don't generate mips (yet), so only create the ones we load. + int levels = plan.depth == 1 ? std::min(plan.levelsToCreate, plan.levelsToLoad) : 1; + + int tw, th; + plan.GetMipSize(0, &tw, &th); + tw = std::min(tw, 16384); + th = std::min(th, 16384); + + MTLTextureDescriptor *td = [MTLTextureDescriptor new]; + td.textureType = plan.depth > 1 ? MTLTextureType3D : MTLTextureType2D; + td.pixelFormat = mtlFmt; + td.width = tw; + td.height = th; + td.depth = plan.depth; + td.mipmapLevelCount = levels; + td.usage = MTLTextureUsageShaderRead; + td.storageMode = MTLStorageModePrivate; + id texture = [rm_->Device() newTextureWithDescriptor:td]; + if (!texture) { + ERROR_LOG(Log::G3D, "Failed to create texture (%dx%d)", tw, th); + ReleaseTexture(entry, true); + return; + } + texture.label = [NSString stringWithFormat:@"tex_%08x", entry->addr]; + + id upload = rm_->UploadEncoder(); + const int uploadCount = plan.depth > 1 ? plan.depth : levels; + for (int i = 0; i < uploadCount; i++) { + // For 3D textures, the loop goes over slices of the single level. + const int mipLevel = plan.depth > 1 ? 0 : i; + const int srcLevel = (i == 0) ? plan.baseLevelSrc : i; + int mipWidth, mipHeight; + plan.GetMipSize(i, &mipWidth, &mipHeight); + + int stride, rows; + if (compressed) { + stride = ((mipWidth + 3) / 4) * blockSize; + rows = (mipHeight + 3) / 4; + } else { + stride = mipWidth * bpp; + rows = mipHeight; + } + size_t size = (size_t)stride * rows; + if (plan.doReplace && compressed) { + size = std::max(size, (size_t)plan.replaced->GetLevelDataSizeAfterCopy(plan.baseLevelSrc + i)); + } + MetalPushAlloc alloc = rm_->Push().Allocate(size, 16); + LoadTextureLevel(*entry, alloc.ptr, size, stride, plan, srcLevel, dstFmt, TexDecodeFlags{}); + + MTLSize copySize = MTLSizeMake(std::min(mipWidth, tw >> mipLevel), std::min(mipHeight, th >> mipLevel), 1); + [upload copyFromBuffer:alloc.buffer sourceOffset:alloc.offset sourceBytesPerRow:stride sourceBytesPerImage:size sourceSize:copySize + toTexture:texture destinationSlice:0 destinationLevel:mipLevel destinationOrigin:MTLOriginMake(0, 0, plan.depth > 1 ? i : 0)]; + } + + ReleaseTexture(entry, true); + entry->texturePtr = (__bridge_retained void *)texture; + + if (plan.depth > 1) { + entry->status |= TexStatus::IS_3D; + } + if (levels == 1) { + entry->status |= TexStatus::NO_MIPS; + } else { + entry->status &= ~TexStatus::NO_MIPS; + } + if (plan.doReplace) { + entry->SetAlphaStatus(plan.replaced->AlphaStatus()); + } +} + +void *TextureCacheMetal::GetNativeTextureView(const TexCacheEntry *entry, bool flat) const { + return entry->texturePtr; +} + +bool TextureCacheMetal::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level, bool *isFramebuffer) { + TextureApplyResult textureResult = ApplyTexture(false); + if (textureResult.framebuffer) { + *isFramebuffer = true; + return GetFramebufferTextureDebug(textureResult.framebuffer, textureResult.framebufferTextureChannel, buffer); + } + const TexCacheEntry *entry = textureResult.texCacheEntry; + if (!entry || !entry->texturePtr) { + return false; + } + id texture = Tex(entry); + if (texture.textureType != MTLTextureType2D || level >= (int)texture.mipmapLevelCount) { + return false; + } + int bpp; + switch (texture.pixelFormat) { + case MTLPixelFormatRGBA8Unorm: buffer.Allocate((u32)(texture.width >> level), (u32)(texture.height >> level), GPU_DBG_FORMAT_8888); bpp = 4; break; + case MTLPixelFormatR8Unorm: buffer.Allocate((u32)(texture.width >> level), (u32)(texture.height >> level), GPU_DBG_FORMAT_8BIT); bpp = 1; break; + default: return false; + } + int w = std::max(1, (int)texture.width >> level); + int h = std::max(1, (int)texture.height >> level); + id readback = [rm_->Device() newBufferWithLength:w * h * bpp options:MTLResourceStorageModeShared]; + [rm_->BlitEncoder() copyFromTexture:texture sourceSlice:0 sourceLevel:level sourceOrigin:MTLOriginMake(0, 0, 0) sourceSize:MTLSizeMake(w, h, 1) + toBuffer:readback destinationOffset:0 destinationBytesPerRow:w * bpp destinationBytesPerImage:w * h * bpp]; + rm_->Flush(true); + memcpy(buffer.GetData(), readback.contents, w * h * bpp); + *isFramebuffer = false; + return true; +}