diff --git a/CMakeLists.txt b/CMakeLists.txt index 9cf7548188..11a68a3ed9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -426,6 +426,15 @@ if(WIN32) endif() +set(CommonJIT + Core/MIPS/JitCommon/JitCommon.cpp + Core/MIPS/JitCommon/JitCommon.h + Core/MIPS/JitCommon/JitBlockCache.cpp + Core/MIPS/JitCommon/JitBlockCache.h + Core/MIPS/JitCommon/JitState.cpp + Core/MIPS/JitCommon/JitState.h +) + set(CommonX86 Common/ABI.cpp Common/ABI.h @@ -464,6 +473,7 @@ set(CommonMIPS source_group(MIPS FILES ${CommonMIPS}) set(CommonRISCV64 + ${CommonJIT} Common/RiscVCPUDetect.cpp Core/MIPS/fake/FakeJit.cpp Core/MIPS/fake/FakeJit.h @@ -1530,8 +1540,8 @@ set(GPU_SOURCES ${GPU_NEON} GPU/Common/Draw2D.cpp GPU/Common/Draw2D.h - GPU/Common/DepalettizeCommon.cpp - GPU/Common/DepalettizeCommon.h + GPU/Common/TextureShaderCommon.cpp + GPU/Common/TextureShaderCommon.h GPU/Common/DepalettizeShaderCommon.cpp GPU/Common/DepalettizeShaderCommon.h GPU/Common/FragmentShaderGenerator.cpp @@ -1630,6 +1640,7 @@ set(GPU_SOURCES # SHARED on ANDROID, STATIC everywhere else add_library(${CoreLibName} ${CoreLinkType} ${CoreExtra} + ${CommonJIT} Core/Config.cpp Core/Config.h Core/ConfigValues.h @@ -1937,12 +1948,6 @@ add_library(${CoreLibName} ${CoreLinkType} Core/FileLoaders/RamCachingFileLoader.h Core/FileLoaders/RetryingFileLoader.cpp Core/FileLoaders/RetryingFileLoader.h - Core/MIPS/JitCommon/JitCommon.cpp - Core/MIPS/JitCommon/JitCommon.h - Core/MIPS/JitCommon/JitBlockCache.cpp - Core/MIPS/JitCommon/JitBlockCache.h - Core/MIPS/JitCommon/JitState.cpp - Core/MIPS/JitCommon/JitState.h Core/MIPS/MIPS.cpp Core/MIPS/MIPS.h Core/MIPS/MIPSAnalyst.cpp diff --git a/Common/GPU/D3D9/thin3d_d3d9.cpp b/Common/GPU/D3D9/thin3d_d3d9.cpp index 938789479c..e420646a40 100644 --- a/Common/GPU/D3D9/thin3d_d3d9.cpp +++ b/Common/GPU/D3D9/thin3d_d3d9.cpp @@ -665,7 +665,7 @@ D3D9Context::D3D9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, ID caps_.tesselationShaderSupported = false; caps_.framebufferBlitSupported = true; caps_.framebufferCopySupported = false; - caps_.framebufferDepthBlitSupported = true; + caps_.framebufferDepthBlitSupported = false; caps_.framebufferStencilBlitSupported = false; caps_.framebufferDepthCopySupported = false; caps_.framebufferSeparateDepthCopySupported = false; diff --git a/Common/GPU/ShaderWriter.cpp b/Common/GPU/ShaderWriter.cpp index 900e2d1160..0332e4d346 100644 --- a/Common/GPU/ShaderWriter.cpp +++ b/Common/GPU/ShaderWriter.cpp @@ -423,3 +423,19 @@ ShaderWriter &ShaderWriter::SampleTexture2D(const char *sampName, const char *uv } return *this; } + +ShaderWriter &ShaderWriter::GetTextureSize(const char *szVariable, const char *texName) { + switch (lang_.shaderLanguage) { + case HLSL_D3D11: + F(" float2 %s; %s.GetDimensions(%s.x, %s.y);", szVariable, texName, szVariable, szVariable); + break; + case HLSL_D3D9: + F(" float2 %s; %s.GetDimensions(%s.x, %s.y);", szVariable, texName, szVariable, szVariable); + break; + default: + // Note: we ignore the sampler. make sure you bound samplers to the textures correctly. + F("vec2 %s = textureSize(%s, 0);", szVariable, texName); + break; + } + return *this; +} diff --git a/Common/GPU/ShaderWriter.h b/Common/GPU/ShaderWriter.h index f07d4159f5..a2d80a6910 100644 --- a/Common/GPU/ShaderWriter.h +++ b/Common/GPU/ShaderWriter.h @@ -83,7 +83,8 @@ public: void ConstFloat(const char *name, float value); - ShaderWriter &SampleTexture2D(const char *sampName, const char *uv); + ShaderWriter &SampleTexture2D(const char *texName, const char *uv); + ShaderWriter &GetTextureSize(const char *szVariable, const char *texName); // Simple shaders with no special tricks. void BeginVSMain(Slice inputs, Slice uniforms, Slice varyings); @@ -93,6 +94,9 @@ public: void EndVSMain(Slice varyings); void EndFSMain(const char *vec4_color_variable, FSFlags flags); + const ShaderLanguageDesc &Lang() const { + return lang_; + } void Rewind(size_t offset) { p_ -= offset; diff --git a/Common/GPU/Vulkan/VulkanContext.cpp b/Common/GPU/Vulkan/VulkanContext.cpp index 23a854dd8e..63351eaf45 100644 --- a/Common/GPU/Vulkan/VulkanContext.cpp +++ b/Common/GPU/Vulkan/VulkanContext.cpp @@ -648,6 +648,7 @@ VkResult VulkanContext::CreateDevice() { } _dbg_assert_(found); + // TODO: A lot of these are on by default in later Vulkan versions, should check for that, technically. extensionsLookup_.KHR_maintenance1 = EnableDeviceExtension(VK_KHR_MAINTENANCE1_EXTENSION_NAME); extensionsLookup_.KHR_maintenance2 = EnableDeviceExtension(VK_KHR_MAINTENANCE2_EXTENSION_NAME); extensionsLookup_.KHR_maintenance3 = EnableDeviceExtension(VK_KHR_MAINTENANCE3_EXTENSION_NAME); @@ -684,7 +685,7 @@ VkResult VulkanContext::CreateDevice() { } else { VulkanLoadDeviceFunctions(device_, extensionsLookup_); } - INFO_LOG(G3D, "Device created.\n"); + INFO_LOG(G3D, "Vulkan Device created"); VulkanSetAvailable(true); VmaAllocatorCreateInfo allocatorInfo = {}; diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index 72236d5e74..9cb7393512 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -667,7 +667,7 @@ public: s.magFilter = desc.magFilter == TextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; s.minFilter = desc.minFilter == TextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; s.mipmapMode = desc.mipFilter == TextureFilter::LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; - s.maxLod = desc.maxLod; + s.maxLod = VK_LOD_CLAMP_NONE; VkResult res = vkCreateSampler(vulkan_->GetDevice(), &s, nullptr, &sampler_); _assert_(VK_SUCCESS == res); } diff --git a/Common/GPU/thin3d.h b/Common/GPU/thin3d.h index 264e240fa9..ce06ec79c3 100644 --- a/Common/GPU/thin3d.h +++ b/Common/GPU/thin3d.h @@ -494,7 +494,6 @@ struct SamplerStateDesc { TextureAddressMode wrapU; TextureAddressMode wrapV; TextureAddressMode wrapW; - float maxLod; bool shadowCompareEnabled; Comparison shadowCompareFunc; BorderColor borderColor; diff --git a/Core/Compatibility.cpp b/Core/Compatibility.cpp index c56cf702f8..f17c1fd6a1 100644 --- a/Core/Compatibility.cpp +++ b/Core/Compatibility.cpp @@ -97,6 +97,7 @@ void Compatibility::CheckSettings(IniFile &iniFile, const std::string &gameID) { CheckSetting(iniFile, gameID, "ZZT3SelectHack", &flags_.ZZT3SelectHack); CheckSetting(iniFile, gameID, "AllowLargeFBTextureOffsets", &flags_.AllowLargeFBTextureOffsets); CheckSetting(iniFile, gameID, "AtracLoopHack", &flags_.AtracLoopHack); + CheckSetting(iniFile, gameID, "DeswizzleDepth", &flags_.DeswizzleDepth); } void Compatibility::CheckSetting(IniFile &iniFile, const std::string &gameID, const char *option, bool *flag) { diff --git a/Core/Compatibility.h b/Core/Compatibility.h index c293fdfa17..29345aee42 100644 --- a/Core/Compatibility.h +++ b/Core/Compatibility.h @@ -87,6 +87,7 @@ struct CompatFlags { bool ZZT3SelectHack; bool AllowLargeFBTextureOffsets; bool AtracLoopHack; + bool DeswizzleDepth; }; class IniFile; diff --git a/Core/Config.cpp b/Core/Config.cpp index d53a0a95c5..055a9036d9 100644 --- a/Core/Config.cpp +++ b/Core/Config.cpp @@ -748,7 +748,7 @@ int Config::NextValidBackend() { if (failed.count((GPUBackend)iGPUBackend)) { ERROR_LOG(LOADER, "Graphics backend failed for %d, trying another", iGPUBackend); -#if (PPSSPP_PLATFORM(WINDOWS) || PPSSPP_PLATFORM(ANDROID)) && !PPSSPP_PLATFORM(UWP) +#if !PPSSPP_PLATFORM(UWP) if (!failed.count(GPUBackend::VULKAN) && VulkanMayBeAvailable()) { return (int)GPUBackend::VULKAN; } @@ -797,6 +797,9 @@ bool Config::IsBackendEnabled(GPUBackend backend, bool validate) { #if PPSSPP_PLATFORM(UWP) if (backend != GPUBackend::DIRECT3D11) return false; +#elif PPSSPP_PLATFORM(SWITCH) + if (backend != GPUBackend::OPENGL) + return false; #elif PPSSPP_PLATFORM(WINDOWS) if (validate) { if (backend == GPUBackend::DIRECT3D11 && !DoesVersionMatchWindows(6, 0, 0, 0, true)) @@ -1113,15 +1116,6 @@ static ConfigSetting networkSettings[] = { ConfigSetting(false), }; -static int DefaultPSPModel() { - // TODO: Can probably default this on, but not sure about its memory differences. -#if !PPSSPP_ARCH(AMD64) && !defined(_WIN32) - return PSP_MODEL_FAT; -#else - return PSP_MODEL_SLIM; -#endif -} - static int DefaultSystemParamLanguage() { int defaultLang = PSP_SYSTEMPARAM_LANGUAGE_ENGLISH; if (g_Config.bFirstRun) { @@ -1135,7 +1129,7 @@ static int DefaultSystemParamLanguage() { } static ConfigSetting systemParamSettings[] = { - ReportedConfigSetting("PSPModel", &g_Config.iPSPModel, &DefaultPSPModel, true, true), + ReportedConfigSetting("PSPModel", &g_Config.iPSPModel, PSP_MODEL_SLIM, true, true), ReportedConfigSetting("PSPFirmwareVersion", &g_Config.iFirmwareVersion, PSP_DEFAULT_FIRMWARE, true, true), ConfigSetting("NickName", &g_Config.sNickName, "PPSSPP", true, true), ConfigSetting("MacAddress", &g_Config.sMACAddress, "", true, true), diff --git a/Core/Core.cpp b/Core/Core.cpp index 5fb5357352..52a1df8f4c 100644 --- a/Core/Core.cpp +++ b/Core/Core.cpp @@ -419,6 +419,7 @@ const char *MemoryExceptionTypeAsString(MemoryExceptionType type) { case MemoryExceptionType::WRITE_WORD: return "Write Word"; case MemoryExceptionType::READ_BLOCK: return "Read Block"; case MemoryExceptionType::WRITE_BLOCK: return "Read/Write Block"; + case MemoryExceptionType::ALIGNMENT: return "Alignment"; default: return "N/A"; } @@ -486,16 +487,19 @@ void Core_ExecException(u32 address, u32 pc, ExecExceptionType type) { e.exec_type = type; e.address = address; e.pc = pc; - Core_EnableStepping(true, "cpu.exception", pc); + // This just records the closest value that could be useful as reference. + e.ra = currentMIPS->r[MIPS_REG_RA]; + Core_EnableStepping(true, "cpu.exception", address); } -void Core_Break() { +void Core_Break(u32 pc) { ERROR_LOG(CPU, "BREAK!"); ExceptionInfo &e = g_exceptionInfo; e = {}; e.type = ExceptionType::BREAK; e.info = ""; + e.pc = pc; if (!g_Config.bIgnoreBadMemAccess) { Core_EnableStepping(true, "cpu.breakInstruction", currentMIPS->pc); diff --git a/Core/Core.h b/Core/Core.h index 62018b832d..d706e7afec 100644 --- a/Core/Core.h +++ b/Core/Core.h @@ -93,6 +93,7 @@ enum class MemoryExceptionType { WRITE_WORD, READ_BLOCK, WRITE_BLOCK, + ALIGNMENT, }; enum class ExecExceptionType { JUMP, @@ -105,7 +106,7 @@ void Core_MemoryException(u32 address, u32 pc, MemoryExceptionType type); void Core_MemoryExceptionInfo(u32 address, u32 pc, MemoryExceptionType type, std::string additionalInfo); void Core_ExecException(u32 address, u32 pc, ExecExceptionType type); -void Core_Break(); +void Core_Break(u32 pc); // Call when loading save states, etc. void Core_ResetException(); @@ -124,6 +125,7 @@ struct ExceptionInfo { MemoryExceptionType memory_type; uint32_t pc; uint32_t address; + uint32_t ra = 0; // Reuses pc and address from memory type, where address is the failed destination. ExecExceptionType exec_type; diff --git a/Core/CoreParameter.h b/Core/CoreParameter.h index 7e9ea60b2e..9ef01c4d9b 100644 --- a/Core/CoreParameter.h +++ b/Core/CoreParameter.h @@ -66,7 +66,7 @@ struct CoreParameter { bool headLess; // Try to avoid messageboxes etc // Internal PSP rendering resolution and scale factor. - int renderScaleFactor; + int renderScaleFactor = 1; int renderWidth; int renderHeight; diff --git a/Core/Dialog/PSPDialog.h b/Core/Dialog/PSPDialog.h index 54a9488e36..636fc20334 100644 --- a/Core/Dialog/PSPDialog.h +++ b/Core/Dialog/PSPDialog.h @@ -99,7 +99,7 @@ protected: void ChangeStatus(DialogStatus newStatus, int delayUs); void ChangeStatusInit(int delayUs); void ChangeStatusShutdown(int delayUs); - DialogStatus ReadStatus() { + DialogStatus ReadStatus() const { return status; } @@ -117,10 +117,10 @@ protected: unsigned int lastButtons = 0; unsigned int buttons = 0; - float fadeTimer; - bool isFading; - bool fadeIn; - u32 fadeValue; + float fadeTimer = 0.0f; + bool isFading = false; + bool fadeIn = false; + u32 fadeValue = 0; ImageID okButtonImg; ImageID cancelButtonImg; diff --git a/Core/Dialog/PSPGamedataInstallDialog.h b/Core/Dialog/PSPGamedataInstallDialog.h index 3dfd8687ef..e669a31873 100644 --- a/Core/Dialog/PSPGamedataInstallDialog.h +++ b/Core/Dialog/PSPGamedataInstallDialog.h @@ -59,16 +59,16 @@ private: void CloseCurrentFile(); void WriteSfoFile(); - SceUtilityGamedataInstallParam request; + SceUtilityGamedataInstallParam request{}; PSPPointer param; std::vector inFileNames; - int numFiles; - int readFiles; - u64 allFilesSize; // use this to calculate progress value. - u64 allReadSize; // use this to calculate progress value. - int progressValue; + int numFiles = 0; + int readFiles = 0; + u64 allFilesSize = 0; // use this to calculate progress value. + u64 allReadSize = 0; // use this to calculate progress value. + int progressValue = 0; - int currentInputFile; - u32 currentInputBytesLeft; - int currentOutputFile; + int currentInputFile = 0; + u32 currentInputBytesLeft = 0; + int currentOutputFile = 0; }; diff --git a/Core/Dialog/PSPMsgDialog.h b/Core/Dialog/PSPMsgDialog.h index e5912d2ee3..78ee4e54f4 100644 --- a/Core/Dialog/PSPMsgDialog.h +++ b/Core/Dialog/PSPMsgDialog.h @@ -94,11 +94,11 @@ private: u32 flag = 0; - pspMessageDialog messageDialog; - int messageDialogAddr; + pspMessageDialog messageDialog{}; + int messageDialogAddr = 0; char msgText[512]; - int yesnoChoice; + int yesnoChoice = 0; float scrollPos_ = 0.0f; int framesUpHeld_ = 0; int framesDownHeld_ = 0; diff --git a/Core/Dialog/PSPOskDialog.h b/Core/Dialog/PSPOskDialog.h index 8eb55586c0..c760afb1e4 100644 --- a/Core/Dialog/PSPOskDialog.h +++ b/Core/Dialog/PSPOskDialog.h @@ -148,7 +148,6 @@ struct SceUtilityOskParams SceUtilityOskState_le state; // Maybe just padding? s32_le unk_60; - }; // Internal enum, not from PSP. @@ -245,16 +244,16 @@ private: std::string oskIntext; std::string oskOuttext; - int selectedChar; + int selectedChar = 0; std::u16string inputChars; OskKeyboardDisplay currentKeyboard; OskKeyboardLanguage currentKeyboardLanguage; - bool isCombinated; + bool isCombinated = false; std::mutex nativeMutex_; PSPOskNativeStatus nativeStatus_ = PSPOskNativeStatus::IDLE; std::string nativeValue_; - int i_level; // for Korean Keyboard support - int i_value[3]; // for Korean Keyboard support + int i_level = 0; // for Korean Keyboard support + int i_value[3]{}; // for Korean Keyboard support }; diff --git a/Core/Dialog/PSPSaveDialog.h b/Core/Dialog/PSPSaveDialog.h index 8058d8a962..90f8d6312a 100644 --- a/Core/Dialog/PSPSaveDialog.h +++ b/Core/Dialog/PSPSaveDialog.h @@ -139,13 +139,13 @@ private: DisplayState display = DS_NONE; SavedataParam param; - SceUtilitySavedataParam request; + SceUtilitySavedataParam request{}; // For detecting changes made by the game. - SceUtilitySavedataParam originalRequest; + SceUtilitySavedataParam originalRequest{}; u32 requestAddr = 0; int currentSelectedSave = 0; - int yesnoChoice; + int yesnoChoice = 0; enum SaveIOStatus { diff --git a/Core/Dialog/SavedataParam.cpp b/Core/Dialog/SavedataParam.cpp index f4ba47a20e..980a3edf31 100644 --- a/Core/Dialog/SavedataParam.cpp +++ b/Core/Dialog/SavedataParam.cpp @@ -193,16 +193,7 @@ void SaveFileInfo::DoState(PointerWrap &p) } } -SavedataParam::SavedataParam() - : pspParam(0) - , selectedSave(0) - , saveDataList(0) - , noSaveIcon(0) - , saveDataListCount(0) - , saveNameListDataCount(0) -{ - -} +SavedataParam::SavedataParam() { } void SavedataParam::Init() { diff --git a/Core/Dialog/SavedataParam.h b/Core/Dialog/SavedataParam.h index b7daa02845..e7bdf9ad46 100644 --- a/Core/Dialog/SavedataParam.h +++ b/Core/Dialog/SavedataParam.h @@ -265,7 +265,6 @@ struct SceUtilitySavedataParam // Function 22 GETSIZES PSPPointer sizeInfo; - }; // Non native, this one we can reorganize as we like @@ -377,10 +376,10 @@ private: std::set GetSecureFileNames(const std::string &dirPath); bool GetExpectedHash(const std::string &dirPath, const std::string &filename, u8 hash[16]); - SceUtilitySavedataParam* pspParam; - int selectedSave; - SaveFileInfo *saveDataList; - SaveFileInfo *noSaveIcon; - int saveDataListCount; - int saveNameListDataCount; + SceUtilitySavedataParam* pspParam = nullptr; + int selectedSave = 0; + SaveFileInfo *saveDataList = nullptr; + SaveFileInfo *noSaveIcon = nullptr; + int saveDataListCount = 0; + int saveNameListDataCount = 0; }; diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 57f62944f4..86a234cd3b 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -1086,6 +1086,12 @@ void __KernelStartIdleThreads(SceUID moduleId) } } +void KernelValidateThreadTarget(uint32_t pc) { + if (!Memory::IsValidAddress(pc) || (pc & 3) != 0) { + Core_ExecException(pc, currentMIPS->pc, ExecExceptionType::THREAD); + } +} + bool __KernelSwitchOffThread(const char *reason) { if (!reason) @@ -1141,9 +1147,7 @@ bool __KernelSwitchToThread(SceUID threadID, const char *reason) if (current && current->isRunning()) __KernelChangeReadyState(current, currentThread, true); - if (!Memory::IsValidAddress(t->context.pc)) { - Core_ExecException(t->context.pc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(t->context.pc); __KernelSwitchContext(t, reason); return true; @@ -1471,9 +1475,7 @@ void __KernelLoadContext(PSPThreadContext *ctx, bool vfpuEnabled) { memcpy(currentMIPS->vfpuCtrl, ctx->vfpuCtrl, sizeof(ctx->vfpuCtrl)); } - if (!Memory::IsValidAddress(ctx->pc)) { - Core_ExecException(ctx->pc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(ctx->pc); memcpy(currentMIPS->other, ctx->other, sizeof(ctx->other)); // Not locking here, we assume the jit isn't switched during execution. @@ -1924,9 +1926,7 @@ SceUID __KernelSetupRootThread(SceUID moduleID, int args, const char *argp, int strcpy(thread->nt.name, "root"); - if (!Memory::IsValidAddress(thread->context.pc)) { - Core_ExecException(thread->context.pc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(thread->context.pc); __KernelLoadContext(&thread->context, (attr & PSP_THREAD_ATTR_VFPU) != 0); currentMIPS->r[MIPS_REG_A0] = args; @@ -2057,9 +2057,7 @@ int __KernelStartThread(SceUID threadToStartID, int argSize, u32 argBlockPtr, bo // Smaller is better for priority. Only switch if the new thread is better. if (cur && cur->nt.currentPriority > startThread->nt.currentPriority) { - if (!Memory::IsValidAddress(startThread->context.pc)) { - Core_ExecException(startThread->context.pc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(startThread->context.pc); __KernelChangeReadyState(cur, currentThread, true); if (__InterruptsEnabled()) hleReSchedule("thread started"); @@ -2939,9 +2937,7 @@ u32 sceKernelExtendThreadStack(u32 size, u32 entryAddr, u32 entryParameter) Memory::Write_U32(currentMIPS->r[MIPS_REG_SP], thread->currentStack.end - 8); Memory::Write_U32(currentMIPS->pc, thread->currentStack.end - 12); - if (!Memory::IsValidAddress(entryAddr)) { - Core_ExecException(entryAddr, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(entryAddr); currentMIPS->pc = entryAddr; currentMIPS->r[MIPS_REG_A0] = entryParameter; @@ -2975,9 +2971,7 @@ void __KernelReturnFromExtendStack() return; } - if (!Memory::IsValidAddress(restorePC)) { - Core_ExecException(restorePC, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(restorePC); DEBUG_LOG(SCEKERNEL, "__KernelReturnFromExtendStack()"); currentMIPS->r[MIPS_REG_RA] = restoreRA; @@ -3259,9 +3253,7 @@ bool __KernelExecuteMipsCallOnCurrentThread(u32 callId, bool reschedAfter) call->savedId = cur->currentMipscallId; call->reschedAfter = reschedAfter; - if (!Memory::IsValidAddress(call->entryPoint)) { - Core_ExecException(call->entryPoint, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(call->entryPoint); // Set up the new state currentMIPS->pc = call->entryPoint; @@ -3312,9 +3304,7 @@ void __KernelReturnFromMipsCall() currentMIPS->r[MIPS_REG_RA] = Memory::Read_U32(sp + MIPS_REG_RA * 4); sp += 32 * 4; - if (!Memory::IsValidAddress(call->savedPc)) { - Core_ExecException(call->savedPc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(call->savedPc); currentMIPS->pc = call->savedPc; // This is how we set the return value. diff --git a/Core/MIPS/ARM/ArmCompBranch.cpp b/Core/MIPS/ARM/ArmCompBranch.cpp index bf687c045d..ec3d180be9 100644 --- a/Core/MIPS/ARM/ArmCompBranch.cpp +++ b/Core/MIPS/ARM/ArmCompBranch.cpp @@ -466,7 +466,7 @@ void ArmJit::Comp_Jump(MIPSOpcode op) { u32 targetAddr = (GetCompilerPC() & 0xF0000000) | off; // Might be a stubbed address or something? - if (!Memory::IsValidAddress(targetAddr)) { + if (!Memory::IsValidAddress(targetAddr) || (targetAddr & 3) != 0) { if (js.nextExit == 0) { ERROR_LOG_REPORT(JIT, "Jump to invalid address: %08x", targetAddr); } else { diff --git a/Core/MIPS/ARM64/Arm64CompBranch.cpp b/Core/MIPS/ARM64/Arm64CompBranch.cpp index ee86994211..026cf539e3 100644 --- a/Core/MIPS/ARM64/Arm64CompBranch.cpp +++ b/Core/MIPS/ARM64/Arm64CompBranch.cpp @@ -481,7 +481,7 @@ void Arm64Jit::Comp_Jump(MIPSOpcode op) { u32 targetAddr = (GetCompilerPC() & 0xF0000000) | off; // Might be a stubbed address or something? - if (!Memory::IsValidAddress(targetAddr)) { + if (!Memory::IsValidAddress(targetAddr) || (targetAddr & 3) != 0) { if (js.nextExit == 0) { ERROR_LOG_REPORT(JIT, "Jump to invalid address: %08x", targetAddr); } else { diff --git a/Core/MIPS/IR/IRCompVFPU.cpp b/Core/MIPS/IR/IRCompVFPU.cpp index 2a5e00a861..4fffc6765d 100644 --- a/Core/MIPS/IR/IRCompVFPU.cpp +++ b/Core/MIPS/IR/IRCompVFPU.cpp @@ -330,6 +330,8 @@ namespace MIPSComp { ir.Write(IROp::LoadVec4, vregs[0], rs, ir.AddConstant(imm)); } else { // Let's not even bother with "vertical" loads for now. + if (!g_Config.bFastMemory) + ir.Write({ IROp::ValidateAddress128, { 0 }, (u8)rs, 0, (u32)imm }); ir.Write(IROp::LoadFloat, vregs[0], rs, ir.AddConstant(imm)); ir.Write(IROp::LoadFloat, vregs[1], rs, ir.AddConstant(imm + 4)); ir.Write(IROp::LoadFloat, vregs[2], rs, ir.AddConstant(imm + 8)); @@ -342,6 +344,8 @@ namespace MIPSComp { ir.Write(IROp::StoreVec4, vregs[0], rs, ir.AddConstant(imm)); } else { // Let's not even bother with "vertical" stores for now. + if (!g_Config.bFastMemory) + ir.Write({ IROp::ValidateAddress128, { 0 }, (u8)rs, 1, (u32)imm }); ir.Write(IROp::StoreFloat, vregs[0], rs, ir.AddConstant(imm)); ir.Write(IROp::StoreFloat, vregs[1], rs, ir.AddConstant(imm + 4)); ir.Write(IROp::StoreFloat, vregs[2], rs, ir.AddConstant(imm + 8)); diff --git a/Core/MIPS/IR/IRFrontend.cpp b/Core/MIPS/IR/IRFrontend.cpp index c3a2df444a..66a3efbafe 100644 --- a/Core/MIPS/IR/IRFrontend.cpp +++ b/Core/MIPS/IR/IRFrontend.cpp @@ -260,6 +260,7 @@ void IRFrontend::DoJit(u32 em_address, std::vector &instructions, u32 &m IRWriter *code = &ir; if (!js.hadBreakpoints) { static const IRPassFunc passes[] = { + &ApplyMemoryValidation, &RemoveLoadStoreLeftRight, &OptimizeFPMoves, &PropagateConstants, diff --git a/Core/MIPS/IR/IRInst.cpp b/Core/MIPS/IR/IRInst.cpp index b8339896e7..13b2509f18 100644 --- a/Core/MIPS/IR/IRInst.cpp +++ b/Core/MIPS/IR/IRInst.cpp @@ -163,6 +163,11 @@ static const IRMeta irMeta[] = { { IROp::Breakpoint, "Breakpoint", "", IRFLAG_EXIT }, { IROp::MemoryCheck, "MemoryCheck", "_GC", IRFLAG_EXIT }, + { IROp::ValidateAddress8, "ValidAddr8", "_GC", IRFLAG_EXIT }, + { IROp::ValidateAddress16, "ValidAddr16", "_GC", IRFLAG_EXIT }, + { IROp::ValidateAddress32, "ValidAddr32", "_GC", IRFLAG_EXIT }, + { IROp::ValidateAddress128, "ValidAddr128", "_GC", IRFLAG_EXIT }, + { IROp::RestoreRoundingMode, "RestoreRoundingMode", "" }, { IROp::ApplyRoundingMode, "ApplyRoundingMode", "" }, { IROp::UpdateRoundingMode, "UpdateRoundingMode", "" }, diff --git a/Core/MIPS/IR/IRInst.h b/Core/MIPS/IR/IRInst.h index 1e2b6c1410..8c7b67b00a 100644 --- a/Core/MIPS/IR/IRInst.h +++ b/Core/MIPS/IR/IRInst.h @@ -213,8 +213,15 @@ enum class IROp : u8 { SetPCConst, // hack to make replacement know PC CallReplacement, Break, + + // Debugging breakpoints. Breakpoint, MemoryCheck, + + ValidateAddress8, + ValidateAddress16, + ValidateAddress32, + ValidateAddress128, }; enum IRComparison { diff --git a/Core/MIPS/IR/IRInterpreter.cpp b/Core/MIPS/IR/IRInterpreter.cpp index 8538748a21..27b0ba0ca3 100644 --- a/Core/MIPS/IR/IRInterpreter.cpp +++ b/Core/MIPS/IR/IRInterpreter.cpp @@ -79,6 +79,25 @@ u32 RunMemCheck(u32 pc, u32 addr) { return coreState != CORE_RUNNING ? 1 : 0; } +template +u32 RunValidateAddress(u32 pc, u32 addr, u32 isWrite) { + const auto toss = [&](MemoryExceptionType t) { + Core_MemoryException(addr, pc, t); + return coreState != CORE_RUNNING ? 1 : 0; + }; + + if (!Memory::IsValidRange(addr, alignment)) { + MemoryExceptionType t = isWrite == 1 ? MemoryExceptionType::WRITE_WORD : MemoryExceptionType::READ_WORD; + if (alignment > 4) + t = isWrite ? MemoryExceptionType::WRITE_BLOCK : MemoryExceptionType::READ_BLOCK; + return toss(t); + } + if (alignment > 1 && (addr & (alignment - 1)) != 0) { + return toss(MemoryExceptionType::ALIGNMENT); + } + return 0; +} + // We cannot use NEON on ARM32 here until we make it a hard dependency. We can, however, on ARM64. u32 IRInterpret(MIPSState *mips, const IRInst *inst, int count) { const IRInst *end = inst + count; @@ -142,6 +161,31 @@ u32 IRInterpret(MIPSState *mips, const IRInst *inst, int count) { mips->r[inst->dest] = ReverseBits32(mips->r[inst->src1]); break; + case IROp::ValidateAddress8: + if (RunValidateAddress<1>(mips->pc, mips->r[inst->src1] + inst->constant, inst->src2)) { + CoreTiming::ForceCheck(); + return mips->pc; + } + break; + case IROp::ValidateAddress16: + if (RunValidateAddress<2>(mips->pc, mips->r[inst->src1] + inst->constant, inst->src2)) { + CoreTiming::ForceCheck(); + return mips->pc; + } + break; + case IROp::ValidateAddress32: + if (RunValidateAddress<4>(mips->pc, mips->r[inst->src1] + inst->constant, inst->src2)) { + CoreTiming::ForceCheck(); + return mips->pc; + } + break; + case IROp::ValidateAddress128: + if (RunValidateAddress<16>(mips->pc, mips->r[inst->src1] + inst->constant, inst->src2)) { + CoreTiming::ForceCheck(); + return mips->pc; + } + break; + case IROp::Load8: mips->r[inst->dest] = Memory::ReadUnchecked_U8(mips->r[inst->src1] + inst->constant); break; @@ -954,7 +998,7 @@ u32 IRInterpret(MIPSState *mips, const IRInst *inst, int count) { } case IROp::Break: - Core_Break(); + Core_Break(mips->pc); return mips->pc + 4; case IROp::SetCtrlVFPU: diff --git a/Core/MIPS/IR/IRJit.cpp b/Core/MIPS/IR/IRJit.cpp index f029f56731..66608fc86f 100644 --- a/Core/MIPS/IR/IRJit.cpp +++ b/Core/MIPS/IR/IRJit.cpp @@ -227,9 +227,10 @@ void IRJit::RunLoopUntil(u64 globalticks) { if (opcode == MIPS_EMUHACK_OPCODE) { u32 data = inst & 0xFFFFFF; IRBlock *block = blocks_.GetBlock(data); + u32 startPC = mips_->pc; mips_->pc = IRInterpret(mips_, block->GetInstructions(), block->GetNumInstructions()); - if (!Memory::IsValidAddress(mips_->pc)) { - Core_ExecException(mips_->pc, mips_->pc, ExecExceptionType::JUMP); + if (!Memory::IsValidAddress(mips_->pc) || (mips_->pc & 3) != 0) { + Core_ExecException(mips_->pc, startPC, ExecExceptionType::JUMP); break; } } else { diff --git a/Core/MIPS/IR/IRPassSimplify.cpp b/Core/MIPS/IR/IRPassSimplify.cpp index 80aa692f86..5725454841 100644 --- a/Core/MIPS/IR/IRPassSimplify.cpp +++ b/Core/MIPS/IR/IRPassSimplify.cpp @@ -5,6 +5,7 @@ #include "Common/BitSet.h" #include "Common/Data/Convert/SmallDataConvert.h" #include "Common/Log.h" +#include "Core/Config.h" #include "Core/MIPS/IR/IRInterpreter.h" #include "Core/MIPS/IR/IRPassSimplify.h" #include "Core/MIPS/IR/IRRegCache.h" @@ -622,6 +623,18 @@ bool PropagateConstants(const IRWriter &in, IRWriter &out, const IROptions &opts } break; + case IROp::ValidateAddress8: + case IROp::ValidateAddress16: + case IROp::ValidateAddress32: + case IROp::ValidateAddress128: + if (gpr.IsImm(inst.src1)) { + out.Write(inst.op, inst.dest, 0, out.AddConstant(gpr.GetImm(inst.src1) + inst.constant)); + } else { + gpr.MapIn(inst.src1); + goto doDefault; + } + break; + case IROp::Downcount: case IROp::SetPCConst: goto doDefault; @@ -1428,3 +1441,58 @@ bool MergeLoadStore(const IRWriter &in, IRWriter &out, const IROptions &opts) { } return logBlocks; } + +bool ApplyMemoryValidation(const IRWriter &in, IRWriter &out, const IROptions &opts) { + CONDITIONAL_DISABLE; + if (g_Config.bFastMemory) + DISABLE; + + const auto addValidate = [&out](IROp validate, const IRInst &inst, bool isStore) { + out.Write({ validate, { 0 }, inst.src1, isStore ? (u8)1 : (u8)0, inst.constant }); + }; + + // TODO: Could be smart about not double-validating an address that has a load / store, etc. + bool logBlocks = false; + for (IRInst inst : in.GetInstructions()) { + switch (inst.op) { + case IROp::Load8: + case IROp::Load8Ext: + case IROp::Store8: + addValidate(IROp::ValidateAddress8, inst, inst.op == IROp::Store8); + break; + + case IROp::Load16: + case IROp::Load16Ext: + case IROp::Store16: + addValidate(IROp::ValidateAddress16, inst, inst.op == IROp::Store16); + break; + + case IROp::Load32: + case IROp::LoadFloat: + case IROp::Store32: + case IROp::StoreFloat: + addValidate(IROp::ValidateAddress32, inst, inst.op == IROp::Store32 || inst.op == IROp::StoreFloat); + break; + + case IROp::LoadVec4: + case IROp::StoreVec4: + addValidate(IROp::ValidateAddress128, inst, inst.op == IROp::StoreVec4); + break; + + case IROp::Load32Left: + case IROp::Load32Right: + case IROp::Store32Left: + case IROp::Store32Right: + // This explicitly does not require alignment, so validate as an 8-bit operation. + addValidate(IROp::ValidateAddress8, inst, inst.op == IROp::Store32Left || inst.op == IROp::Store32Right); + break; + + default: + break; + } + + // Always write out the original. We're only adding. + out.Write(inst); + } + return logBlocks; +} diff --git a/Core/MIPS/IR/IRPassSimplify.h b/Core/MIPS/IR/IRPassSimplify.h index e3020a4f61..7fdc5d1c7d 100644 --- a/Core/MIPS/IR/IRPassSimplify.h +++ b/Core/MIPS/IR/IRPassSimplify.h @@ -14,3 +14,4 @@ bool ThreeOpToTwoOp(const IRWriter &in, IRWriter &out, const IROptions &opts); bool OptimizeFPMoves(const IRWriter &in, IRWriter &out, const IROptions &opts); bool ReorderLoadStore(const IRWriter &in, IRWriter &out, const IROptions &opts); bool MergeLoadStore(const IRWriter &in, IRWriter &out, const IROptions &opts); +bool ApplyMemoryValidation(const IRWriter &in, IRWriter &out, const IROptions &opts); diff --git a/Core/MIPS/MIPSInt.cpp b/Core/MIPS/MIPSInt.cpp index 305041ecb6..46585b69a9 100644 --- a/Core/MIPS/MIPSInt.cpp +++ b/Core/MIPS/MIPSInt.cpp @@ -57,8 +57,7 @@ static inline void DelayBranchTo(u32 where) { - if (!Memory::IsValidAddress(where)) { - // TODO: What about misaligned? + if (!Memory::IsValidAddress(where) || (where & 3) != 0) { Core_ExecException(where, PC, ExecExceptionType::JUMP); } PC += 4; @@ -158,7 +157,7 @@ namespace MIPSInt void Int_Break(MIPSOpcode op) { Reporting::ReportMessage("BREAK instruction hit"); - Core_Break(); + Core_Break(PC); PC += 4; } diff --git a/Core/MIPS/x86/CompBranch.cpp b/Core/MIPS/x86/CompBranch.cpp index 835768bf96..9bd167d2e2 100644 --- a/Core/MIPS/x86/CompBranch.cpp +++ b/Core/MIPS/x86/CompBranch.cpp @@ -612,7 +612,7 @@ void Jit::Comp_Jump(MIPSOpcode op) { u32 targetAddr = (GetCompilerPC() & 0xF0000000) | off; // Might be a stubbed address or something? - if (!Memory::IsValidAddress(targetAddr)) { + if (!Memory::IsValidAddress(targetAddr) || (targetAddr & 3) != 0) { if (js.nextExit == 0) { ERROR_LOG_REPORT(JIT, "Jump to invalid address: %08x PC %08x LR %08x", targetAddr, GetCompilerPC(), currentMIPS->r[MIPS_REG_RA]); } else { diff --git a/Core/MIPS/x86/Jit.cpp b/Core/MIPS/x86/Jit.cpp index 5c3f2121f9..c27ee3b502 100644 --- a/Core/MIPS/x86/Jit.cpp +++ b/Core/MIPS/x86/Jit.cpp @@ -275,7 +275,7 @@ void Jit::Compile(u32 em_address) { ClearCache(); } - if (!Memory::IsValidAddress(em_address)) { + if (!Memory::IsValidAddress(em_address) || (em_address & 3) != 0) { Core_ExecException(em_address, em_address, ExecExceptionType::JUMP); return; } @@ -672,7 +672,7 @@ static void HitInvalidBranch(uint32_t dest) { void Jit::WriteExit(u32 destination, int exit_num) { _dbg_assert_msg_(exit_num < MAX_JIT_BLOCK_EXITS, "Expected a valid exit_num"); - if (!Memory::IsValidAddress(destination)) { + if (!Memory::IsValidAddress(destination) || (destination & 3) != 0) { ERROR_LOG_REPORT(JIT, "Trying to write block exit to illegal destination %08x: pc = %08x", destination, currentMIPS->pc); MOV(32, MIPSSTATE_VAR(pc), Imm32(GetCompilerPC())); ABI_CallFunctionC(&HitInvalidBranch, destination); @@ -721,6 +721,12 @@ void Jit::WriteExit(u32 destination, int exit_num) { } } +static u32 IsValidJumpTarget(uint32_t addr) { + if (Memory::IsValidAddress(addr) && (addr & 3) == 0) + return 1; + return 0; +} + static void HitInvalidJumpReg(uint32_t source) { Core_ExecException(currentMIPS->pc, source, ExecExceptionType::JUMP); currentMIPS->pc = source + 8; @@ -762,7 +768,7 @@ void Jit::WriteExitDestInReg(X64Reg reg) { SetJumpTarget(tooLow); SetJumpTarget(tooHigh); - ABI_CallFunctionA((const void *)&Memory::IsValidAddress, R(reg)); + ABI_CallFunctionA((const void *)&IsValidJumpTarget, R(reg)); // If we're ignoring, coreState didn't trip - so trip it now. CMP(32, R(EAX), Imm32(0)); diff --git a/Core/TextureReplacer.cpp b/Core/TextureReplacer.cpp index 48c9905e38..c0b965e9b1 100644 --- a/Core/TextureReplacer.cpp +++ b/Core/TextureReplacer.cpp @@ -49,7 +49,8 @@ static const int VERSION = 1; static const int MAX_MIP_LEVELS = 12; // 12 should be plenty, 8 is the max mip levels supported by the PSP. TextureReplacer::TextureReplacer() { - none_.alphaStatus_ = ReplacedTextureAlpha::UNKNOWN; + none_.initDone_ = true; + none_.prepareDone_ = true; } TextureReplacer::~TextureReplacer() { @@ -373,7 +374,7 @@ u32 TextureReplacer::ComputeHash(u32 addr, int bufw, int w, int h, GETextureForm } } -ReplacedTexture &TextureReplacer::FindReplacement(u64 cachekey, u32 hash, int w, int h) { +ReplacedTexture &TextureReplacer::FindReplacement(u64 cachekey, u32 hash, int w, int h, double budget) { // Only actually replace if we're replacing. We might just be saving. if (!Enabled() || !g_Config.bReplaceTextures) { return none_; @@ -382,13 +383,18 @@ ReplacedTexture &TextureReplacer::FindReplacement(u64 cachekey, u32 hash, int w, ReplacementCacheKey replacementKey(cachekey, hash); auto it = cache_.find(replacementKey); if (it != cache_.end()) { + if (!it->second.prepareDone_ && budget > 0.0) { + // We don't do this on a thread, but we only do it while within budget. + PopulateReplacement(&it->second, cachekey, hash, w, h); + } return it->second; } // Okay, let's construct the result. ReplacedTexture &result = cache_[replacementKey]; - result.alphaStatus_ = ReplacedTextureAlpha::UNKNOWN; - PopulateReplacement(&result, cachekey, hash, w, h); + if (!g_Config.bReplaceTexturesAllowLate || budget > 0.0) { + PopulateReplacement(&result, cachekey, hash, w, h); + } return result; } @@ -433,7 +439,7 @@ void TextureReplacer::PopulateReplacement(ReplacedTexture *result, u64 cachekey, break; } - result->alphaStatus_ = ReplacedTextureAlpha::UNKNOWN; + result->prepareDone_ = true; } enum class ReplacedImageType { @@ -815,11 +821,13 @@ bool ReplacedTexture::IsReady(double budget) { } // Loaded already, or not yet on a thread? - if (!levelData_.empty()) + if (initDone_ && !levelData_.empty()) return true; // Let's not even start a new texture if we're already behind. if (budget < 0.0) return false; + if (!prepareDone_) + return false; if (g_Config.bReplaceTexturesAllowLate) { if (threadWaitable_) @@ -829,10 +837,11 @@ bool ReplacedTexture::IsReady(double budget) { if (threadWaitable_->WaitFor(budget)) { // If we finished all the levels, we're done. - return !levelData_.empty(); + return initDone_ && !levelData_.empty(); } } else { Prepare(); + _assert_(initDone_); return true; } @@ -842,16 +851,19 @@ bool ReplacedTexture::IsReady(double budget) { void ReplacedTexture::Prepare() { std::unique_lock lock(mutex_); - if (cancelPrepare_) + if (cancelPrepare_) { + initDone_ = true; return; + } - levelData_.resize(NumLevels()); - for (int i = 0; i < NumLevels(); ++i) { + levelData_.resize(levels_.size()); + for (int i = 0; i < (int)levels_.size(); ++i) { if (cancelPrepare_) break; PrepareData(i); } + initDone_ = true; if (!cancelPrepare_ && threadWaitable_) threadWaitable_->Notify(); } @@ -975,6 +987,8 @@ bool ReplacedTexture::Load(int level, void *out, int rowPitch) { _assert_msg_((size_t)level < levels_.size(), "Invalid miplevel"); _assert_msg_(out != nullptr && rowPitch > 0, "Invalid out/pitch"); + if (!initDone_) + return false; if (levelData_.empty()) return false; diff --git a/Core/TextureReplacer.h b/Core/TextureReplacer.h index e01a03d2a4..b32d31a7d3 100644 --- a/Core/TextureReplacer.h +++ b/Core/TextureReplacer.h @@ -118,10 +118,20 @@ struct ReplacedTexture { ~ReplacedTexture(); inline bool Valid() const { + if (!initDone_) + return false; return !levels_.empty(); } + inline bool IsInvalid() const { + if (!initDone_) + return false; + return levels_.empty(); + } + bool GetSize(int level, int &w, int &h) const { + if (!initDone_) + return false; if ((size_t)level < levels_.size()) { w = levels_[level].w; h = levels_[level].h; @@ -131,12 +141,16 @@ struct ReplacedTexture { } int NumLevels() const { + if (!initDone_) + return 0; return (int)levels_.size(); } Draw::DataFormat Format(int level) const { - if ((size_t)level < levels_.size()) { - return levels_[level].fmt; + if (initDone_) { + if ((size_t)level < levels_.size()) { + return levels_[level].fmt; + } } return Draw::DataFormat::R8G8B8A8_UNORM; } @@ -156,11 +170,13 @@ protected: std::vector levels_; std::vector> levelData_; - ReplacedTextureAlpha alphaStatus_; + ReplacedTextureAlpha alphaStatus_ = ReplacedTextureAlpha::UNKNOWN; double lastUsed_ = 0.0; LimitedWaitable *threadWaitable_ = nullptr; std::mutex mutex_; bool cancelPrepare_ = false; + bool initDone_ = false; + bool prepareDone_ = false; friend TextureReplacer; friend ReplacedTextureTask; @@ -196,7 +212,7 @@ public: u32 ComputeHash(u32 addr, int bufw, int w, int h, GETextureFormat fmt, u16 maxSeenV); - ReplacedTexture &FindReplacement(u64 cachekey, u32 hash, int w, int h); + ReplacedTexture &FindReplacement(u64 cachekey, u32 hash, int w, int h, double budget); bool FindFiltering(u64 cachekey, u32 hash, TextureFiltering *forceFiltering); ReplacedTexture &FindNone() { return none_; diff --git a/GPU/Common/DepalettizeCommon.cpp b/GPU/Common/DepalettizeCommon.cpp deleted file mode 100644 index 85c74d4c55..0000000000 --- a/GPU/Common/DepalettizeCommon.cpp +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright (c) 2014- 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 - -#include "Common/Log.h" -#include "Common/StringUtils.h" -#include "Common/GPU/Shader.h" -#include "Common/GPU/ShaderWriter.h" -#include "Common/Data/Convert/ColorConv.h" -#include "Core/Reporting.h" -#include "GPU/Common/DrawEngineCommon.h" -#include "GPU/Common/TextureCacheCommon.h" -#include "GPU/Common/DepalettizeShaderCommon.h" -#include "GPU/Common/DepalettizeCommon.h" - -static const VaryingDef varyings[1] = { - { "vec2", "v_texcoord", Draw::SEM_TEXCOORD0, 0, "highp" }, -}; - -static const SamplerDef samplers[2] = { - { "tex" }, - { "pal" }, -}; - -DepalShaderCache::DepalShaderCache(Draw::DrawContext *draw) : draw_(draw) { } - -DepalShaderCache::~DepalShaderCache() { - DeviceLost(); -} - -void DepalShaderCache::DeviceRestore(Draw::DrawContext *draw) { - draw_ = draw; -} - -void DepalShaderCache::DeviceLost() { - Clear(); -} - -Draw::Texture *DepalShaderCache::GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut) { - u32 clutId = GetClutID(clutFormat, clutHash); - - auto oldtex = texCache_.find(clutId); - if (oldtex != texCache_.end()) { - oldtex->second->lastFrame = gpuStats.numFlips; - return oldtex->second->texture; - } - - int texturePixels = clutFormat == GE_CMODE_32BIT_ABGR8888 ? 256 : 512; - - DepalTexture *tex = new DepalTexture(); - - Draw::TextureDesc desc{}; - desc.width = texturePixels; - desc.height = 1; - desc.depth = 1; - desc.mipLevels = 1; - desc.tag = "clut"; - desc.type = Draw::TextureType::LINEAR2D; // TODO: Try LINEAR1D? - desc.format = Draw::DataFormat::R8G8B8A8_UNORM; // TODO: Also support an BGR format. We won't bother with the 16-bit formats here. - - uint8_t convTemp[2048]{}; - - switch (clutFormat) { - case GEPaletteFormat::GE_CMODE_32BIT_ABGR8888: - desc.initData.push_back((const uint8_t *)rawClut); - break; - case GEPaletteFormat::GE_CMODE_16BIT_BGR5650: - ConvertRGBA5551ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); - desc.initData.push_back(convTemp); - break; - case GEPaletteFormat::GE_CMODE_16BIT_ABGR5551: - ConvertRGB565ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); - desc.initData.push_back(convTemp); - break; - case GEPaletteFormat::GE_CMODE_16BIT_ABGR4444: - ConvertRGBA4444ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); - desc.initData.push_back(convTemp); - break; - } - - tex->texture = draw_->CreateTexture(desc); - tex->lastFrame = gpuStats.numFlips; - - texCache_[clutId] = tex; - return tex->texture; -} - -void DepalShaderCache::Clear() { - for (auto shader = cache_.begin(); shader != cache_.end(); ++shader) { - shader->second->fragShader->Release(); - if (shader->second->pipeline) { - shader->second->pipeline->Release(); - } - delete shader->second; - } - cache_.clear(); - for (auto tex = texCache_.begin(); tex != texCache_.end(); ++tex) { - tex->second->texture->Release(); - delete tex->second; - } - texCache_.clear(); - if (vertexShader_) { - vertexShader_->Release(); - vertexShader_ = nullptr; - } - if (nearestSampler_) { - nearestSampler_->Release(); - nearestSampler_ = nullptr; - } -} - -void DepalShaderCache::Decimate() { - for (auto tex = texCache_.begin(); tex != texCache_.end(); ) { - if (tex->second->lastFrame + DEPAL_TEXTURE_OLD_AGE < gpuStats.numFlips) { - tex->second->texture->Release(); - delete tex->second; - texCache_.erase(tex++); - } else { - ++tex; - } - } -} - -Draw::SamplerState *DepalShaderCache::GetSampler() { - if (!nearestSampler_) { - Draw::SamplerStateDesc desc{}; - desc.wrapU = Draw::TextureAddressMode::CLAMP_TO_EDGE; - desc.wrapV = Draw::TextureAddressMode::CLAMP_TO_EDGE; - desc.wrapW = Draw::TextureAddressMode::CLAMP_TO_EDGE; - nearestSampler_ = draw_->CreateSamplerState(desc); - } - return nearestSampler_; -} - -DepalShader *DepalShaderCache::GetDepalettizeShader(uint32_t clutMode, GEBufferFormat pixelFormat) { - using namespace Draw; - - u32 id = GenerateShaderID(clutMode, pixelFormat); - - auto shader = cache_.find(id); - if (shader != cache_.end()) { - DepalShader *depal = shader->second; - return shader->second; - } - - char *buffer = new char[4096]; - - if (!vertexShader_) { - GenerateDepalVs(buffer, draw_->GetShaderLanguageDesc()); - vertexShader_ = draw_->CreateShaderModule(ShaderStage::Vertex, draw_->GetShaderLanguageDesc().shaderLanguage, (const uint8_t *)buffer, strlen(buffer), "depal_vs"); - } - - // TODO: Parse these out of clutMode some nice way, to become a bit more stateless. - DepalConfig config; - config.clutFormat = gstate.getClutPaletteFormat(); - config.startPos = gstate.getClutIndexStartPos(); - config.shift = gstate.getClutIndexShift(); - config.mask = gstate.getClutIndexMask(); - config.pixelFormat = pixelFormat; - - GenerateDepalFs(buffer, config, draw_->GetShaderLanguageDesc()); - - std::string src(buffer); - ShaderModule *fragShader = draw_->CreateShaderModule(ShaderStage::Fragment, draw_->GetShaderLanguageDesc().shaderLanguage, (const uint8_t *)buffer, strlen(buffer), "depal_fs"); - - DepalShader *depal = new DepalShader(); - - static const InputLayoutDesc desc = { - { - { 16, false }, - }, - { - { 0, SEM_POSITION, DataFormat::R32G32_FLOAT, 0 }, - { 0, SEM_TEXCOORD0, DataFormat::R32G32_FLOAT, 8 }, - }, - }; - InputLayout *inputLayout = draw_->CreateInputLayout(desc); - BlendState *blendOff = draw_->CreateBlendState({ false, 0xF }); - DepthStencilStateDesc dsDesc{}; - DepthStencilState *noDepthStencil = draw_->CreateDepthStencilState(dsDesc); - RasterState *rasterNoCull = draw_->CreateRasterState({}); - - PipelineDesc depalPipelineDesc{ - Primitive::TRIANGLE_STRIP, // Could have use a single triangle too (in which case we'd use LIST here) but want to be prepared to do subrectangles. - { vertexShader_, fragShader }, - inputLayout, noDepthStencil, blendOff, rasterNoCull, nullptr, samplers - }; - - Pipeline *pipeline = draw_->CreateGraphicsPipeline(depalPipelineDesc); - - inputLayout->Release(); - blendOff->Release(); - noDepthStencil->Release(); - rasterNoCull->Release(); - - _assert_(pipeline); - - depal->pipeline = pipeline; - depal->fragShader = fragShader; - depal->code = buffer; - cache_[id] = depal; - - delete[] buffer; - return depal->pipeline ? depal : nullptr; -} - -std::vector DepalShaderCache::DebugGetShaderIDs(DebugShaderType type) { - std::vector ids; - for (auto &iter : cache_) { - ids.push_back(StringFromFormat("%08x", iter.first)); - } - return ids; -} - -std::string DepalShaderCache::DebugGetShaderString(std::string idstr, DebugShaderType type, DebugShaderStringType stringType) { - uint32_t id; - sscanf(idstr.c_str(), "%08x", &id); - auto iter = cache_.find(id); - if (iter == cache_.end()) - return ""; - switch (stringType) { - case SHADER_STRING_SHORT_DESC: - return idstr; - case SHADER_STRING_SOURCE_CODE: - return iter->second->code; - default: - return ""; - } -} diff --git a/GPU/Common/DepalettizeCommon.h b/GPU/Common/DepalettizeCommon.h deleted file mode 100644 index c394f47eb7..0000000000 --- a/GPU/Common/DepalettizeCommon.h +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) 2014- 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 -#include -#include - -#include "Common/CommonTypes.h" -#include "Common/GPU/Shader.h" -#include "Common/GPU/thin3d.h" -#include "GPU/ge_constants.h" -#include "GPU/Common/Draw2D.h" -#include "GPU/Common/ShaderCommon.h" -#include "GPU/Common/DepalettizeShaderCommon.h" - -class DepalShader { -public: - Draw::ShaderModule *fragShader; - Draw::Pipeline *pipeline; - std::string code; -}; - -class DepalTexture { -public: - Draw::Texture *texture; - int lastFrame; -}; - -// Caches both shaders and palette textures. -class DepalShaderCache { -public: - DepalShaderCache(Draw::DrawContext *draw); - ~DepalShaderCache(); - - // This also uploads the palette and binds the correct texture. - DepalShader *GetDepalettizeShader(uint32_t clutMode, GEBufferFormat pixelFormat); - Draw::Texture *GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); - - Draw::SamplerState *GetSampler(); - - void Clear(); - void Decimate(); - std::vector DebugGetShaderIDs(DebugShaderType type); - std::string DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType); - - void DeviceLost(); - void DeviceRestore(Draw::DrawContext *draw); - -private: - static uint32_t GenerateShaderID(uint32_t clutMode, GEBufferFormat pixelFormat) { - return (clutMode & 0xFFFFFF) | (pixelFormat << 24); - } - - static uint32_t GetClutID(GEPaletteFormat clutFormat, uint32_t clutHash) { - // Simplistic. - return clutHash ^ (uint32_t)clutFormat; - } - - Draw::DrawContext *draw_; - Draw::ShaderModule *vertexShader_ = nullptr; - Draw::SamplerState *nearestSampler_ = nullptr; - - std::map cache_; - std::map texCache_; -}; - -// TODO: Merge with DepalShaderCache? -class TextureShaderApplier { -public: - struct Pos { - float x; - float y; - }; - struct UV { - float u; - float v; - }; - - TextureShaderApplier(Draw::DrawContext *draw, DepalShader *shader, float bufferW, float bufferH, int renderW, int renderH) - : draw_(draw), shader_(shader), bufferW_(bufferW), bufferH_(bufferH), renderW_(renderW), renderH_(renderH) { - static const Pos pos[4] = { - {-1, -1 }, - { 1, -1 }, - {-1, 1 }, - { 1, 1 }, - }; - memcpy(pos_, pos, sizeof(pos_)); - - static const UV uv[4] = { - { 0, 0 }, - { 1, 0 }, - { 0, 1 }, - { 1, 1 }, - }; - memcpy(uv_, uv, sizeof(uv_)); - } - - void ApplyBounds(const KnownVertexBounds &bounds, u32 uoff, u32 voff) { - // If min is not < max, then we don't have values (wasn't set during decode.) - if (bounds.minV < bounds.maxV) { - const float invWidth = 1.0f / bufferW_; - const float invHeight = 1.0f / bufferH_; - // Inverse of half = double. - const float invHalfWidth = invWidth * 2.0f; - const float invHalfHeight = invHeight * 2.0f; - - const int u1 = bounds.minU + uoff; - const int v1 = bounds.minV + voff; - const int u2 = bounds.maxU + uoff; - const int v2 = bounds.maxV + voff; - - const float left = u1 * invHalfWidth - 1.0f; - const float right = u2 * invHalfWidth - 1.0f; - const float top = v1 * invHalfHeight - 1.0f; - const float bottom = v2 * invHalfHeight - 1.0f; - // Points are: BL, BR, TR, TL. - pos_[0] = Pos{ left, bottom }; - pos_[1] = Pos{ right, bottom }; - pos_[2] = Pos{ left, top }; - pos_[3] = Pos{ right, top }; - - // And also the UVs, same order. - const float uvleft = u1 * invWidth; - const float uvright = u2 * invWidth; - const float uvtop = v1 * invHeight; - const float uvbottom = v2 * invHeight; - uv_[0] = UV{ uvleft, uvbottom }; - uv_[1] = UV{ uvright, uvbottom }; - uv_[2] = UV{ uvleft, uvtop }; - uv_[3] = UV{ uvright, uvtop }; - - // We need to reapply the texture next time since we cropped UV. - gstate_c.Dirty(DIRTY_TEXTURE_PARAMS); - } - } - - void Use() { - draw_->BindPipeline(shader_->pipeline); - struct SimpleVertex { - float pos[2]; - float uv[2]; - }; - for (int i = 0; i < 4; i++) { - memcpy(&verts_[i].x, &pos_[i], sizeof(Pos)); - memcpy(&verts_[i].u, &uv_[i], sizeof(UV)); - } - } - - void Shade() { - Draw::Viewport vp{ 0.0f, 0.0f, (float)renderW_, (float)renderH_, 0.0f, 1.0f }; - draw_->SetViewports(1, &vp); - draw_->SetScissorRect(0, 0, renderW_, renderH_); - draw_->DrawUP((const uint8_t *)verts_, 4); - } - -protected: - Draw::DrawContext *draw_; - DepalShader *shader_; - Pos pos_[4]; - UV uv_[4]; - Draw2DVertex verts_[4]; - float bufferW_; - float bufferH_; - int renderW_; - int renderH_; -}; diff --git a/GPU/Common/DepalettizeShaderCommon.cpp b/GPU/Common/DepalettizeShaderCommon.cpp index 0ec0b6c66c..15906c616e 100644 --- a/GPU/Common/DepalettizeShaderCommon.cpp +++ b/GPU/Common/DepalettizeShaderCommon.cpp @@ -27,14 +27,12 @@ #include "GPU/Common/GPUStateUtils.h" #include "GPU/Common/DepalettizeShaderCommon.h" -#define WRITE p+=sprintf - static const InputDef vsInputs[2] = { { "vec2", "a_position", Draw::SEM_POSITION, }, { "vec2", "a_texcoord0", Draw::SEM_TEXCOORD0, }, }; -// TODO: Deduplicate with DepalettizeCommon.cpp +// TODO: Deduplicate with TextureShaderCommon.cpp static const SamplerDef samplers[2] = { { "tex" }, { "pal" }, @@ -44,12 +42,12 @@ static const VaryingDef varyings[1] = { { "vec2", "v_texcoord", Draw::SEM_TEXCOORD0, 0, "highp" }, }; -// Uses integer instructions available since OpenGL 3.0. Suitable for ES 3.0 as well. -void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, const ShaderLanguageDesc &lang) { +// Uses integer instructions available since OpenGL 3.0, ES 3.0 (and 2.0 with extensions), and of course Vulkan and D3D11. +void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config) { const int shift = config.shift; const int mask = config.mask; - if (config.pixelFormat == GE_FORMAT_DEPTH16) { + if (config.bufferFormat == GE_FORMAT_DEPTH16) { DepthScaleFactors factors = GetDepthScaleFactors(); writer.ConstFloat("z_scale", factors.scale); writer.ConstFloat("z_offset", factors.offset); @@ -71,7 +69,7 @@ void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, con writer.C(" vec4 color = ").SampleTexture2D("tex", "v_texcoord").C(";\n"); int shiftedMask = mask << shift; - switch (config.pixelFormat) { + switch (config.bufferFormat) { case GE_FORMAT_8888: if (shiftedMask & 0xFF) writer.C(" int r = int(color.r * 255.99);\n"); else writer.C(" int r = 0;\n"); if (shiftedMask & 0xFF00) writer.C(" int g = int(color.g * 255.99);\n"); else writer.C(" int g = 0;\n"); @@ -102,6 +100,17 @@ void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, con case GE_FORMAT_DEPTH16: // Remap depth buffer. writer.C(" float depth = (color.x - z_offset) * z_scale;\n"); + + if (config.bufferFormat == GE_FORMAT_DEPTH16 && config.textureFormat == GE_TFMT_5650) { + // Convert depth to 565, without going through a CLUT. + writer.C(" int idepth = int(clamp(depth, 0.0, 65535.0));\n"); + writer.C(" float r = (idepth & 31) / 31.0f;\n"); + writer.C(" float g = ((idepth >> 5) & 63) / 63.0f;\n"); + writer.C(" float b = ((idepth >> 11) & 31) / 31.0f;\n"); + writer.C(" vec4 outColor = vec4(r, g, b, 1.0);\n"); + return; + } + writer.C(" int index = int(clamp(depth, 0.0, 65535.0));\n"); break; default: @@ -128,23 +137,25 @@ void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, con writer.C(" vec4 outColor = ").SampleTexture2D("pal", "uv").C(";\n"); } -// FP only, to suit GL(ES) 2.0 -void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, const ShaderLanguageDesc &lang) { +// FP only, to suit GL(ES) 2.0 and DX9 +void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config) { char lookupMethod[128] = "index.r"; const int shift = config.shift; const int mask = config.mask; - if (config.pixelFormat == GE_FORMAT_DEPTH16) { + if (config.bufferFormat == GE_FORMAT_DEPTH16) { DepthScaleFactors factors = GetDepthScaleFactors(); writer.ConstFloat("z_scale", factors.scale); writer.ConstFloat("z_offset", factors.offset); } + writer.C(" vec4 index = ").SampleTexture2D("tex", "v_texcoord").C(";\n"); + float index_multiplier = 1.0f; // pixelformat is the format of the texture we are sampling. bool formatOK = true; - switch (config.pixelFormat) { + switch (config.bufferFormat) { case GE_FORMAT_8888: if ((mask & (mask + 1)) == 0) { // If the value has all bits contiguous (bitmask check above), we can mod by it + 1. @@ -222,6 +233,19 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c case GE_FORMAT_DEPTH16: { // TODO: I think we can handle most scenarios here, but texturing from depth buffers requires an extension on ES 2.0 anyway. + // Not on D3D9 though, so this path is still relevant. + + if (config.bufferFormat == GE_FORMAT_DEPTH16 && config.textureFormat == GE_TFMT_5650) { + // Convert depth to 565, without going through a CLUT. + writer.C(" float depth = (index.x - z_offset) * z_scale;\n"); + writer.C(" float idepth = floor(clamp(depth, 0.0, 65535.0));\n"); + writer.C(" float r = mod(idepth, 32.0) / 31.0f;\n"); + writer.C(" float g = mod(floor(idepth / 32.0), 64.0) / 63.0f;\n"); + writer.C(" float b = mod(floor(idepth / 2048.0), 32.0) / 31.0f;\n"); + writer.C(" vec4 outColor = vec4(r, g, b, 1.0);\n"); + return; + } + if (shift < 16) { index_multiplier = 1.0f / (float)(1 << shift); truncate_cpy(lookupMethod, "((index.x - z_offset) * z_scale)"); @@ -249,7 +273,7 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c // index_multiplier -= 0.01f / texturePixels; if (!formatOK) { - ERROR_LOG_REPORT_ONCE(depal, G3D, "%i depal unsupported: shift=%i mask=%02x offset=%d", config.pixelFormat, shift, mask, config.startPos); + ERROR_LOG_REPORT_ONCE(depal, G3D, "%s depal unsupported: shift=%d mask=%02x offset=%d", GeBufferFormatToString(config.bufferFormat), shift, mask, config.startPos); } // Offset by half a texel (plus clutBase) to turn NEAREST filtering into FLOOR. @@ -258,38 +282,67 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c char offset[128] = ""; sprintf(offset, " + %f", texel_offset); - writer.C(" vec4 index = ").SampleTexture2D("tex", "v_texcoord").C(";\n"); writer.F(" float coord = (%s * %f)%s;\n", lookupMethod, index_multiplier, offset); writer.C(" vec4 outColor = ").SampleTexture2D("pal", "vec2(coord, 0.0)").C(";\n"); } -void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang) { - ShaderWriter writer(buffer, lang, ShaderStage::Fragment); +void GenerateDepalSmoothed(ShaderWriter &writer, const DepalConfig &config) { + const char *sourceChannel = "error"; + float indexMultiplier = 32.0f; + + if (config.bufferFormat == GE_FORMAT_5551) { + _dbg_assert_(config.mask == 0x1F); + switch (config.shift) { + case 0: sourceChannel = "r"; break; + case 5: sourceChannel = "g"; break; + case 10: sourceChannel = "b"; break; + default: _dbg_assert_(false); + } + } else if (config.bufferFormat == GE_FORMAT_565) { + _dbg_assert_(config.mask == 0x1F || config.mask == 0x3F); + switch (config.shift) { + case 0: sourceChannel = "r"; break; + case 5: sourceChannel = "g"; indexMultiplier = 64.0f; break; + case 11: sourceChannel = "b"; break; + default: _dbg_assert_(false); + } + } else { + _dbg_assert_(false); + } + + writer.C(" float index = ").SampleTexture2D("tex", "v_texcoord").F(".%s * %0.1f;\n", sourceChannel, indexMultiplier); + + float texturePixels = 256.f; + if (config.clutFormat != GE_CMODE_32BIT_ABGR8888) { + texturePixels = 512.f; + } + + writer.F(" float coord = (index + 0.5) * %f;\n", 1.0 / texturePixels); + writer.C(" vec4 outColor = ").SampleTexture2D("pal", "vec2(coord, 0.0)").C(";\n"); +} + +void GenerateDepalFs(ShaderWriter &writer, const DepalConfig &config) { writer.DeclareSamplers(samplers); writer.HighPrecisionFloat(); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_NONE); - switch (lang.shaderLanguage) { - case HLSL_D3D9: - case GLSL_1xx: - GenerateDepalShaderFloat(writer, config, lang); - break; - case GLSL_VULKAN: - case GLSL_3xx: - case HLSL_D3D11: - GenerateDepalShader300(writer, config, lang); - break; - default: - _assert_msg_(false, "Depal shader language not supported: %d", (int)lang.shaderLanguage); + if (config.smoothedDepal) { + // Handles a limited set of cases, but doesn't need any integer math so we don't + // need two variants. + GenerateDepalSmoothed(writer, config); + } else { + switch (writer.Lang().shaderLanguage) { + case HLSL_D3D9: + case GLSL_1xx: + GenerateDepalShaderFloat(writer, config); + break; + case GLSL_VULKAN: + case GLSL_3xx: + case HLSL_D3D11: + GenerateDepalShader300(writer, config); + break; + default: + _assert_msg_(false, "Shader language not supported for depal: %d", (int)writer.Lang().shaderLanguage); + } } writer.EndFSMain("outColor", FSFLAG_NONE); } - -void GenerateDepalVs(char *buffer, const ShaderLanguageDesc &lang) { - ShaderWriter writer(buffer, lang, ShaderStage::Vertex, nullptr, 0); - writer.BeginVSMain(vsInputs, Slice::empty(), varyings); - writer.C(" v_texcoord = a_texcoord0;\n"); - writer.C(" gl_Position = vec4(a_position, 0.0, 1.0);\n"); - writer.EndVSMain(varyings); -} - -#undef WRITE diff --git a/GPU/Common/DepalettizeShaderCommon.h b/GPU/Common/DepalettizeShaderCommon.h index 5ce5ef88a8..433dfa74df 100644 --- a/GPU/Common/DepalettizeShaderCommon.h +++ b/GPU/Common/DepalettizeShaderCommon.h @@ -22,6 +22,8 @@ #include "Common/GPU/Shader.h" #include "GPU/ge_constants.h" +class ShaderWriter; + static const int DEPAL_TEXTURE_OLD_AGE = 120; struct DepalConfig { @@ -29,8 +31,9 @@ struct DepalConfig { int shift; u32 startPos; GEPaletteFormat clutFormat; - GEBufferFormat pixelFormat; + GETextureFormat textureFormat; + GEBufferFormat bufferFormat; + bool smoothedDepal; }; -void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang); -void GenerateDepalVs(char *buffer, const ShaderLanguageDesc &lang); +void GenerateDepalFs(ShaderWriter &writer, const DepalConfig &config); diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index ccffd4e611..b9ac114f92 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -25,6 +25,7 @@ #include "GPU/Common/DrawEngineCommon.h" #include "GPU/Common/FramebufferManagerCommon.h" #include "GPU/Common/TextureCacheCommon.h" +#include "GPU/Common/GPUStateUtils.h" static const InputDef inputs[2] = { { "vec2", "a_position", Draw::SEM_POSITION }, @@ -39,19 +40,88 @@ static const SamplerDef samplers[1] = { { "tex" }, }; -void GenerateDraw2DFs(ShaderWriter &writer) { +static const UniformDef uniforms[2] = { + { "vec2", "texSize", 0 }, + { "float", "scaleFactor", 1}, +}; + +struct Draw2DUB { + float texSizeX; + float texSizeY; + float scaleFactor; +}; + +const UniformBufferDesc draw2DUBDesc{ sizeof(Draw2DUB), { + { "texSize", -1, 0, UniformType::FLOAT2, 0 }, + { "scaleFactor", -1, 1, UniformType::FLOAT1, 0 }, +} }; + + +Draw2DPipelineInfo GenerateDraw2DCopyColorFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_NONE); writer.C(" vec4 outColor = ").SampleTexture2D("tex", "v_texcoord.xy").C(";\n"); writer.EndFSMain("outColor", FSFLAG_NONE); + + return Draw2DPipelineInfo{ + RASTER_COLOR, + RASTER_COLOR, + }; } -void GenerateDraw2DDepthFs(ShaderWriter &writer) { +Draw2DPipelineInfo GenerateDraw2DCopyDepthFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_WRITEDEPTH); writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); writer.C(" gl_FragDepth = ").SampleTexture2D("tex", "v_texcoord.xy").C(".x;\n"); writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); + + return Draw2DPipelineInfo{ + RASTER_DEPTH, + RASTER_DEPTH, + }; +} + +Draw2DPipelineInfo GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { + writer.DeclareSamplers(samplers); + writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_WRITEDEPTH); + writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); + // Unlike when just copying a depth buffer, here we're generating new depth values so we'll + // have to apply the scaling. + DepthScaleFactors factors = GetDepthScaleFactors(); + writer.C(" vec3 rgb = ").SampleTexture2D("tex", "v_texcoord.xy").C(".xyz;\n"); + writer.F(" highp float depthValue = (floor(rgb.x * 31.99) + floor(rgb.y * 63.99) * 32.0 + floor(rgb.z * 31.99) * 2048.0); \n"); + writer.F(" gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale, factors.offset); + writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); + + return Draw2DPipelineInfo{ + RASTER_COLOR, + RASTER_DEPTH, + }; +} + +Draw2DPipelineInfo GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { + writer.DeclareSamplers(samplers); + writer.BeginFSMain(uniforms, varyings, FSFLAG_WRITEDEPTH); + writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); + // Unlike when just copying a depth buffer, here we're generating new depth values so we'll + // have to apply the scaling. + DepthScaleFactors factors = GetDepthScaleFactors(); + writer.C(" vec2 tsize = texSize;\n"); + writer.C(" vec2 coord = v_texcoord * tsize;\n"); + writer.F(" float strip = 4.0 * scaleFactor;\n"); + writer.C(" float in_strip = mod(coord.y, strip);\n"); + writer.C(" coord.y = coord.y - in_strip + strip - in_strip;\n"); + writer.C(" coord /= tsize;\n"); + writer.C(" vec3 rgb = ").SampleTexture2D("tex", "coord").C(".xyz;\n"); + writer.F(" highp float depthValue = (floor(rgb.x * 31.99) + floor(rgb.y * 63.99) * 32.0 + floor(rgb.z * 31.99) * 2048.0); \n"); + writer.F(" gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale, factors.offset); + writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); + + return Draw2DPipelineInfo{ + RASTER_COLOR, + RASTER_DEPTH + }; } void GenerateDraw2DVS(ShaderWriter &writer) { @@ -63,7 +133,24 @@ void GenerateDraw2DVS(ShaderWriter &writer) { writer.EndVSMain(varyings); } -void FramebufferManagerCommon::Ensure2DResources() { +template +static void DoRelease(T *&obj) { + if (obj) + obj->Release(); + obj = nullptr; +} + +void Draw2D::DeviceLost() { + DoRelease(draw2DVs_); + DoRelease(draw2DSamplerLinear_); + DoRelease(draw2DSamplerNearest_); +} + +void Draw2D::DeviceRestore(Draw::DrawContext *draw) { + +} + +void Draw2D::Ensure2DResources() { using namespace Draw; const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); @@ -84,6 +171,7 @@ void FramebufferManagerCommon::Ensure2DResources() { descLinear.mipFilter = TextureFilter::LINEAR; descLinear.wrapU = TextureAddressMode::CLAMP_TO_EDGE; descLinear.wrapV = TextureAddressMode::CLAMP_TO_EDGE; + descLinear.wrapW = TextureAddressMode::CLAMP_TO_EDGE; draw2DSamplerLinear_ = draw_->CreateSamplerState(descLinear); } @@ -94,20 +182,22 @@ void FramebufferManagerCommon::Ensure2DResources() { descNearest.mipFilter = TextureFilter::NEAREST; descNearest.wrapU = TextureAddressMode::CLAMP_TO_EDGE; descNearest.wrapV = TextureAddressMode::CLAMP_TO_EDGE; + descNearest.wrapW = TextureAddressMode::CLAMP_TO_EDGE; draw2DSamplerNearest_ = draw_->CreateSamplerState(descNearest); } } -Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(void (*generate)(ShaderWriter &)) { +Draw2DPipeline *Draw2D::Create2DPipeline(std::function generate) { + Ensure2DResources(); + using namespace Draw; const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); char *fsCode = new char[4000]; ShaderWriter writer(fsCode, shaderLanguageDesc, ShaderStage::Fragment); - generate(writer); + Draw2DPipelineInfo info = generate(writer); ShaderModule *fs = draw_->CreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), "draw2d_fs"); - delete[] fsCode; _assert_(fs); @@ -123,22 +213,24 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(void (*generate)(Shad }; InputLayout *inputLayout = draw_->CreateInputLayout(desc); - BlendState *blendOff = draw_->CreateBlendState({ false, 0xF }); - BlendState *blendDiscard = draw_->CreateBlendState({ false, 0x0 }); + BlendState *blend = draw_->CreateBlendState({ false, info.writeChannel == RASTER_COLOR ? 0xF : 0 }); - DepthStencilState *noDepthStencil = draw_->CreateDepthStencilState(DepthStencilStateDesc{}); + DepthStencilStateDesc dsDesc{}; + if (info.writeChannel == RASTER_DEPTH) { + dsDesc.depthTestEnabled = true; + dsDesc.depthWriteEnabled = true; + dsDesc.depthCompare = Draw::Comparison::ALWAYS; + } + + DepthStencilState *depthStencil = draw_->CreateDepthStencilState(dsDesc); RasterState *rasterNoCull = draw_->CreateRasterState({}); - DepthStencilStateDesc dsWriteDesc{}; - dsWriteDesc.depthTestEnabled = true; - dsWriteDesc.depthWriteEnabled = true; - dsWriteDesc.depthCompare = Draw::Comparison::ALWAYS; - DepthStencilState *depthWriteAlways = draw_->CreateDepthStencilState(dsWriteDesc); - PipelineDesc pipelineDesc{ Primitive::TRIANGLE_STRIP, { draw2DVs_, fs }, - inputLayout, noDepthStencil, blendOff, rasterNoCull, nullptr, + inputLayout, + depthStencil, + blend, rasterNoCull, &draw2DUBDesc, }; Draw::Pipeline *pipeline = draw_->CreateGraphicsPipeline(pipelineDesc); @@ -146,45 +238,97 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(void (*generate)(Shad fs->Release(); rasterNoCull->Release(); - blendOff->Release(); - blendDiscard->Release(); - noDepthStencil->Release(); - depthWriteAlways->Release(); + blend->Release(); + depthStencil->Release(); inputLayout->Release(); - return pipeline; + return new Draw2DPipeline { + pipeline, + info, + fsCode, + }; } -void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, RasterChannel channel) { + +void Draw2D::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DPipeline *pipeline, float texW, float texH, int scaleFactor) { using namespace Draw; - Ensure2DResources(); + _dbg_assert_(pipeline); - const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); + if (pipeline->info.writeChannel == RASTER_DEPTH) { + _dbg_assert_(draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported); - switch (channel) { - case RASTER_COLOR: - if (!draw2DPipelineColor_) { - draw2DPipelineColor_ = Create2DPipeline(&GenerateDraw2DFs); - } - draw_->BindPipeline(draw2DPipelineColor_); - break; - - case RASTER_DEPTH: - if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { - // Can't do it - return; - } - if (!draw2DPipelineDepth_) { - draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DFs); - } - draw_->BindPipeline(draw2DPipelineDepth_); - break; + // We don't filter inputs when writing depth, results will be bad. + linearFilter = false; } + Draw2DUB ub; + ub.texSizeX = tex ? tex->Width() : texW; + ub.texSizeY = tex ? tex->Height() : texH; + ub.scaleFactor = (float)scaleFactor; + + draw_->BindPipeline(pipeline->pipeline); + draw_->UpdateDynamicUniformBuffer(&ub, sizeof(ub)); + if (tex) { draw_->BindTextures(TEX_SLOT_PSP_TEXTURE, 1, &tex); } draw_->BindSamplerStates(TEX_SLOT_PSP_TEXTURE, 1, linearFilter ? &draw2DSamplerLinear_ : &draw2DSamplerNearest_); draw_->DrawUP(verts, vertexCount); + + draw_->InvalidateCachedState(); + + gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE | DIRTY_VERTEXSHADER_STATE); +} + +Draw2DPipeline *FramebufferManagerCommon::Get2DPipeline(Draw2DShader shader) { + using namespace Draw; + + const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); + + Draw2DPipeline *pipeline = nullptr; + + switch (shader) { + case DRAW2D_COPY_COLOR: + if (!draw2DPipelineColor_) { + draw2DPipelineColor_ = draw2D_.Create2DPipeline(&GenerateDraw2DCopyColorFs); + } + pipeline = draw2DPipelineColor_; + break; + + case DRAW2D_COPY_DEPTH: + if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { + // Can't do it + return nullptr; + } + if (!draw2DPipelineDepth_) { + draw2DPipelineDepth_ = draw2D_.Create2DPipeline(&GenerateDraw2DCopyDepthFs); + } + pipeline = draw2DPipelineDepth_; + break; + + case DRAW2D_565_TO_DEPTH: + if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { + // Can't do it + return nullptr; + } + if (!draw2DPipeline565ToDepth_) { + draw2DPipeline565ToDepth_ = draw2D_.Create2DPipeline(&GenerateDraw2D565ToDepthFs); + } + pipeline = draw2DPipeline565ToDepth_; + break; + + case DRAW2D_565_TO_DEPTH_DESWIZZLE: + if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { + // Can't do it + return nullptr; + } + if (!draw2DPipeline565ToDepthDeswizzle_) { + draw2DPipeline565ToDepthDeswizzle_ = draw2D_.Create2DPipeline(&GenerateDraw2D565ToDepthDeswizzleFs); + } + pipeline = draw2DPipeline565ToDepthDeswizzle_; + break; + } + + return pipeline; } diff --git a/GPU/Common/Draw2D.h b/GPU/Common/Draw2D.h index 34c171e7a0..b9516e8d39 100644 --- a/GPU/Common/Draw2D.h +++ b/GPU/Common/Draw2D.h @@ -1,5 +1,7 @@ #pragma once +#include "GPU/GPU.h" + // For framebuffer copies and similar things that just require passthrough. struct Draw2DVertex { float x; @@ -7,3 +9,60 @@ struct Draw2DVertex { float u; float v; }; + +enum Draw2DShader { + DRAW2D_COPY_COLOR, + DRAW2D_COPY_DEPTH, + DRAW2D_565_TO_DEPTH, + DRAW2D_565_TO_DEPTH_DESWIZZLE, +}; + +inline RasterChannel Draw2DSourceChannel(Draw2DShader shader) { + switch (shader) { + case DRAW2D_COPY_DEPTH: + return RASTER_DEPTH; + case DRAW2D_COPY_COLOR: + case DRAW2D_565_TO_DEPTH: + case DRAW2D_565_TO_DEPTH_DESWIZZLE: + default: + return RASTER_COLOR; + } +} + +struct Draw2DPipelineInfo { + RasterChannel readChannel; + RasterChannel writeChannel; + bool secondTexture; +}; + +struct Draw2DPipeline { + Draw::Pipeline *pipeline; + Draw2DPipelineInfo info; + char *code; + void Release() { + pipeline->Release(); + delete[] code; + delete this; + } +}; + +class ShaderWriter; + +class Draw2D { +public: + Draw2D(Draw::DrawContext *draw) : draw_(draw) {} + void DeviceLost(); + void DeviceRestore(Draw::DrawContext *draw); + + Draw2DPipeline *Create2DPipeline(std::function generate); + + void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DPipeline *pipeline, float texW = 0.0f, float texH = 0.0f, int scaleFactor = 0); + void Ensure2DResources(); + +private: + Draw::DrawContext *draw_; + + Draw::SamplerState *draw2DSamplerLinear_ = nullptr; + Draw::SamplerState *draw2DSamplerNearest_ = nullptr; + Draw::ShaderModule *draw2DVs_ = nullptr; +}; diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index ad3f22af8c..f278363e5f 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -23,8 +23,10 @@ #include "Common/GPU/OpenGL/GLFeatures.h" #include "Common/GPU/ShaderWriter.h" #include "Common/GPU/thin3d.h" +#include "Core/Compatibility.h" #include "Core/Reporting.h" #include "Core/Config.h" +#include "Core/System.h" #include "GPU/Common/GPUStateUtils.h" #include "GPU/Common/ShaderId.h" #include "GPU/Common/ShaderUniforms.h" @@ -88,9 +90,9 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu bool doFlatShading = id.Bit(FS_BIT_FLATSHADE) && !flatBug; bool shaderDepal = id.Bit(FS_BIT_SHADER_DEPAL) && !texture3D; // combination with texture3D not supported. Enforced elsewhere too. + bool smoothedDepal = id.Bit(FS_BIT_SHADER_SMOOTHED_DEPAL); bool bgraTexture = id.Bit(FS_BIT_BGRA_TEXTURE); bool colorWriteMask = id.Bit(FS_BIT_COLOR_WRITEMASK) && compat.bitwiseOps; - bool colorToDepth = id.Bit(FS_BIT_COLOR_TO_DEPTH); GEComparison alphaTestFunc = (GEComparison)id.Bits(FS_BIT_ALPHA_TEST_FUNC, 3); GEComparison colorTestFunc = (GEComparison)id.Bits(FS_BIT_COLOR_TEST_FUNC, 2); @@ -123,7 +125,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu bool readFramebufferTex = readFramebuffer && !gstate_c.Supports(GPU_SUPPORTS_ANY_FRAMEBUFFER_FETCH); bool needFragCoord = readFramebuffer || gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT); - bool writeDepth = gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT) || colorToDepth; + bool writeDepth = gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT); if (shaderDepal && !doTexture) { *errorString = "depal requires a texture"; @@ -136,11 +138,6 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu } if (compat.shaderLanguage == ShaderLanguage::GLSL_VULKAN) { - if (colorToDepth) { - WRITE(p, "precision highp int;\n"); - WRITE(p, "precision highp float;\n"); - } - if (useDiscardStencilBugWorkaround && !gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT)) { WRITE(p, "layout (depth_unchanged) out float gl_FragDepth;\n"); } @@ -293,7 +290,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "};\n"); } } else if (ShaderLanguageIsOpenGL(compat.shaderLanguage)) { - if ((shaderDepal || colorWriteMask || colorToDepth) && gl_extensions.IsGLES) { + if ((shaderDepal || colorWriteMask) && gl_extensions.IsGLES) { WRITE(p, "precision highp int;\n"); } @@ -461,9 +458,6 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "PS_OUT main( PS_IN In ) {\n"); WRITE(p, " PS_OUT outfragment;\n"); WRITE(p, " vec4 target;\n"); - if (colorToDepth) { - WRITE(p, " float gl_FragDepth;\n"); - } } else { WRITE(p, "void main() {\n"); } @@ -599,6 +593,31 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu } } } + } else if (shaderDepal && smoothedDepal) { + // Specific mode for Test Drive. Fixes the banding. + if (doTextureProjection) { + // We don't use textureProj because we need better control and it's probably not much of a savings anyway. + // However it is good for precision on older hardware like PowerVR. + WRITE(p, " vec2 uv = %s.xy/%s.z;\n vec2 uv_round;\n", texcoord, texcoord); + } else { + WRITE(p, " vec2 uv = %s.xy;\n vec2 uv_round;\n", texcoord); + } + // Restrictions on this are checked before setting the smoothed flag. + // Only RGB565 and RGBA5551 are supported, and only the specific shifts hitting the + // channels directly. + WRITE(p, " vec4 t = %s(tex, %s.xy);\n", compat.texture, texcoord); + WRITE(p, " uint depalShift = (u_depal_mask_shift_off_fmt >> 8) & 0xFFU;\n"); + WRITE(p, " uint depalFmt = (u_depal_mask_shift_off_fmt >> 24) & 0x3U;\n"); + WRITE(p, " float index0 = t.r;\n"); + WRITE(p, " float mul = 32.0 / 256.0;\n"); + WRITE(p, " if (depalFmt == 0) {\n"); // yes, different versions of Test Drive use different formats. Could do compile time by adding more compat flags but meh. + WRITE(p, " if (depalShift == 5) { index0 = t.g; mul = 64.0 / 256.0; }\n"); + WRITE(p, " else if (depalShift == 11) { index0 = t.b; }\n"); + WRITE(p, " } else {\n"); + WRITE(p, " if (depalShift == 5) { index0 = t.g; }\n"); + WRITE(p, " else if (depalShift == 10) { index0 = t.b; }\n"); + WRITE(p, " }\n"); + WRITE(p, " t = %s(pal, vec2(index0 * mul, 0.0));\n", compat.texture); } else { if (doTextureProjection) { // We don't use textureProj because we need better control and it's probably not much of a savings anyway. @@ -1070,22 +1089,6 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, " %s = vec4(0.0, 0.0, 0.0, %s.z); // blue to alpha\n", compat.fragColor0, compat.fragColor0); } - if (colorToDepth) { - DepthScaleFactors factors = GetDepthScaleFactors(); - - if (compat.bitwiseOps) { - WRITE(p, " highp float depthValue = float(int(%s.x * 31.99) | (int(%s.y * 63.99) << 5) | (int(%s.z * 31.99) << 11)) / 65535.0;\n", "v", "v", "v"); // compat.fragColor0, compat.fragColor0, compat.fragColor0); - } else { - // D3D9-compatible alternative - WRITE(p, " highp float depthValue = (floor(%s.x * 31.99) + floor(%s.y * 63.99) * 32.0 + floor(%s.z * 31.99) * 2048.0) / 65535.0;\n", "v", "v", "v"); // compat.fragColor0, compat.fragColor0, compat.fragColor0); - } - if (factors.scale != 1.0 || factors.offset != 0.0) { - WRITE(p, " gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale / 65535.0f, factors.offset); - } else { - WRITE(p, " gl_FragDepth = depthValue;\n"); - } - } - if (gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT)) { const double scale = DepthSliceFactor() * 65535.0; diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 1855d088ff..31cb65b0c5 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -41,13 +41,14 @@ #include "GPU/Common/PresentationCommon.h" #include "GPU/Common/TextureCacheCommon.h" #include "GPU/Common/ReinterpretFramebuffer.h" +#include "GPU/Debugger/Debugger.h" #include "GPU/Debugger/Record.h" #include "GPU/Debugger/Stepping.h" #include "GPU/GPUInterface.h" #include "GPU/GPUState.h" FramebufferManagerCommon::FramebufferManagerCommon(Draw::DrawContext *draw) - : draw_(draw) { + : draw_(draw), draw2D_(draw_) { presentation_ = new PresentationCommon(draw); } @@ -105,6 +106,7 @@ void FramebufferManagerCommon::SetDisplayFramebuffer(u32 framebuf, u32 stride, G displayFramebufPtr_ = framebuf; displayStride_ = stride; displayFormat_ = format; + GPUDebug::NotifyDisplay(framebuf, stride, format); GPURecord::NotifyDisplay(framebuf, stride, format); } @@ -124,7 +126,7 @@ VirtualFramebuffer *FramebufferManagerCommon::GetVFBAt(u32 addr) const { } u32 FramebufferManagerCommon::ColorBufferByteSize(const VirtualFramebuffer *vfb) const { - return vfb->fb_stride * vfb->height * (vfb->format == GE_FORMAT_8888 ? 4 : 2); + return vfb->fb_stride * vfb->height * (vfb->fb_format == GE_FORMAT_8888 ? 4 : 2); } bool FramebufferManagerCommon::ShouldDownloadFramebuffer(const VirtualFramebuffer *vfb) const { @@ -190,7 +192,7 @@ void FramebufferManagerCommon::EstimateDrawingSize(u32 fb_address, GEBufferForma // Unless the game is using overlapping buffers, the next buffer should be far enough away. // This catches some cases where we can know this. // Hmm. The problem is that we could only catch it for the first of two buffers... - const u32 bpp = fb_format == GE_FORMAT_8888 ? 4 : 2; + const u32 bpp = BufferFormatBytesPerPixel(fb_format); int avail_height = (nearest_address - fb_address) / (fb_stride * bpp); if (avail_height < drawing_height && avail_height == region_height) { drawing_width = std::min(region_width, fb_stride); @@ -220,7 +222,7 @@ void GetFramebufferHeuristicInputs(FramebufferHeuristicParams *params, const GPU params->z_stride = 0; } - params->fmt = gstate_c.framebufFormat; + params->fb_format = gstate_c.framebufFormat; params->isClearingDepth = gstate.isModeClear() && gstate.isClearModeDepthMask(); // Technically, it may write depth later, but we're trying to detect it only when it's really true. @@ -269,7 +271,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame // As there are no clear "framebuffer width" and "framebuffer height" registers, // we need to infer the size of the current framebuffer somehow. int drawing_width, drawing_height; - EstimateDrawingSize(params.fb_address, params.fmt, params.viewportWidth, params.viewportHeight, params.regionWidth, params.regionHeight, params.scissorWidth, params.scissorHeight, std::max(params.fb_stride, (u16)4), drawing_width, drawing_height); + EstimateDrawingSize(params.fb_address, params.fb_format, params.viewportWidth, params.viewportHeight, params.regionWidth, params.regionHeight, params.scissorWidth, params.scissorHeight, std::max(params.fb_stride, (u16)4), drawing_width, drawing_height); gstate_c.SetCurRTOffset(0, 0); bool vfbFormatChanged = false; @@ -280,14 +282,12 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame WARN_LOG_ONCE(color_equal_z, G3D, "Framebuffer bound with color addr == z addr, likely will not use Z in this pass: %08x", params.fb_address); } - RasterMode mode = RASTER_MODE_NORMAL; - // Find a matching framebuffer VirtualFramebuffer *vfb = nullptr; for (size_t i = 0; i < vfbs_.size(); ++i) { VirtualFramebuffer *v = vfbs_[i]; - const u32 bpp = v->format == GE_FORMAT_8888 ? 4 : 2; + const u32 bpp = BufferFormatBytesPerPixel(v->fb_format); if (params.fb_address == v->fb_address) { vfb = v; @@ -296,8 +296,8 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->fb_stride = params.fb_stride; vfbFormatChanged = true; } - if (vfb->format != params.fmt) { - vfb->format = params.fmt; + if (vfb->fb_format != params.fb_format) { + vfb->fb_format = params.fb_format; vfbFormatChanged = true; } @@ -318,21 +318,8 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->height = drawing_height; } break; - } else if (params.fb_address == v->z_address && params.fmt != GE_FORMAT_8888 && params.fb_stride == v->z_stride && !params.isBlending) { - // Looks like the game might be intending to use color to write directly to a Z buffer. - // This is seen in Kuroyou 2. - - // Ignore this in this loop, BUT, we do a lookup in the depth tracking afterwards to - // make sure we get the latest one. - WARN_LOG_ONCE(color_matches_z, G3D, "Color framebuffer bound at %08x with likely intent to write explicit Z values using color. fmt = %s", params.fb_address, GeBufferFormatToString(params.fmt)); - // Seems impractical to use the other 16-bit formats for this due to the limited control over alpha, - // so we'll simply only support 565. - if (params.fmt == GE_FORMAT_565) { - mode = RASTER_MODE_COLOR_TO_DEPTH; - break; - } - } else if (v->fb_stride == params.fb_stride && v->format == params.fmt) { - u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * 4; // This should be * bpp, but leaving like this until after 1.13 to be safe. The God of War games use this for shadows. + } else if (v->fb_stride == params.fb_stride && v->fb_format == params.fb_format) { + u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * bpp; u32 v_fb_end_ptr = v->fb_address + v->fb_stride * v->height * bpp; if (params.fb_address > v->fb_address && params.fb_address < v_fb_first_line_end_ptr) { @@ -347,17 +334,6 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame drawing_width += x_offset; break; } - } else if (params.fb_address > v->fb_address && params.fb_address < v_fb_end_ptr && PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) { - if (params.fb_address % params.fb_stride == v->fb_address % params.fb_stride) { - // Framebuffers are overlapping on the Y axis. - const int y_offset = (params.fb_address - v->fb_address) / (bpp * params.fb_stride); - - vfb = v; - gstate_c.SetCurRTOffset(0, y_offset); - // To prevent the newSize code from being confused. - drawing_height += y_offset; - break; - } } else { // We ignore this match. // TODO: We can allow X/Y overlaps too, but haven't seen any so safer to not. @@ -365,19 +341,6 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame } } - if (mode == RASTER_MODE_COLOR_TO_DEPTH) { - // Lookup in the depth tracking to find which VFB has the latest version of this Z buffer. - // Then bind it in color-to-depth mode. - // - // We do this by having a special render mode where we take color and move to - // depth in the fragment shader, and set color writes to off. - // - // We use a special fragment shader flag to convert color to depth. - vfb = GetLatestDepthBufferAt(params.fb_address /* !!! */, params.fb_stride); - } - - gstate_c.SetFramebufferRenderMode(mode); - if (vfb) { if ((drawing_width != vfb->bufferWidth || drawing_height != vfb->bufferHeight)) { // Even if it's not newly wrong, if this is larger we need to resize up. @@ -413,6 +376,8 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame // None found? Create one. if (!vfb) { + gstate_c.usingDepth = false; // reset depth buffer tracking + vfb = new VirtualFramebuffer{}; vfb->fbo = nullptr; vfb->fb_address = params.fb_address; @@ -426,9 +391,9 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->newWidth = drawing_width; vfb->newHeight = drawing_height; vfb->lastFrameNewSize = gpuStats.numFlips; - vfb->format = params.fmt; - vfb->drawnFormat = params.fmt; - vfb->usageFlags = FB_USAGE_RENDERTARGET; + vfb->fb_format = params.fb_format; + vfb->drawnFormat = params.fb_format; + vfb->usageFlags = FB_USAGE_RENDER_COLOR; u32 byteSize = ColorBufferByteSize(vfb); if (Memory::IsVRAMAddress(params.fb_address) && params.fb_address + byteSize > framebufRangeEnd_) { @@ -439,20 +404,13 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame ResizeFramebufFBO(vfb, drawing_width, drawing_height, true); NotifyRenderFramebufferCreated(vfb); - // Looks up by z_address, so if one is found here and not have last pointers equal to this one, - // there is another one. - VirtualFramebuffer *prevDepth = GetLatestDepthBufferAt(vfb->z_address, vfb->z_stride); - - // We might already want to copy depth, in case this is a temp buffer. See #7810. - if (prevDepth != vfb) { - if (!params.isClearingDepth && prevDepth) { - BlitFramebufferDepth(prevDepth, vfb); - } - } + // Note that we do not even think about depth right now. That'll be handled + // on the first depth access, which will call SetDepthFramebuffer. + CopyToColorFromOverlappingFramebuffers(vfb); SetColorUpdated(vfb, skipDrawReason); - INFO_LOG(FRAMEBUF, "Creating FBO for %08x (z: %08x) : %d x %d x %s", vfb->fb_address, vfb->z_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->format)); + INFO_LOG(FRAMEBUF, "Creating FBO for %08x (z: %08x) : %d x %d x %s", vfb->fb_address, vfb->z_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format)); vfb->last_frame_render = gpuStats.numFlips; frameLastFramebufUsed_ = gpuStats.numFlips; @@ -486,18 +444,18 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame } else if (vfbs_[i]->z_stride != 0 && params.z_address == vfbs_[i]->z_address && params.fb_address != vfbs_[i]->fb_address && !sharingReported) { // This happens a lot, but virtually always it's cleared. // It's possible the other might not clear, but when every game is reported it's not useful. - if (params.isWritingDepth) { + if (params.isWritingDepth && (vfbs_[i]->usageFlags & FB_USAGE_RENDER_DEPTH)) { WARN_LOG(SCEGE, "FBO reusing depthbuffer, c=%08x/d=%08x and c=%08x/d=%08x", params.fb_address, params.z_address, vfbs_[i]->fb_address, vfbs_[i]->z_address); sharingReported = true; } } } - // We already have it! + // We already have it! } else if (vfb != currentRenderVfb_) { // Use it as a render target. - DEBUG_LOG(FRAMEBUF, "Switching render target to FBO for %08x: %d x %d x %d ", vfb->fb_address, vfb->width, vfb->height, vfb->format); - vfb->usageFlags |= FB_USAGE_RENDERTARGET; + DEBUG_LOG(FRAMEBUF, "Switching render target to FBO for %08x: %d x %d x %d ", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format); + vfb->usageFlags |= FB_USAGE_RENDER_COLOR; vfb->last_frame_render = gpuStats.numFlips; frameLastFramebufUsed_ = gpuStats.numFlips; vfb->dirtyAfterDisplay = true; @@ -507,18 +465,20 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame VirtualFramebuffer *prev = currentRenderVfb_; currentRenderVfb_ = vfb; NotifyRenderFramebufferSwitched(prev, vfb, params.isClearingDepth); + CopyToColorFromOverlappingFramebuffers(vfb); + gstate_c.usingDepth = false; // reset depth buffer tracking } else { + // Something changed, but we still got the same framebuffer we were already rendering to. + // Might not be a lot to do here, we check in NotifyRenderFramebufferUpdated vfb->last_frame_render = gpuStats.numFlips; frameLastFramebufUsed_ = gpuStats.numFlips; vfb->dirtyAfterDisplay = true; if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0) vfb->reallyDirtyAfterDisplay = true; - NotifyRenderFramebufferUpdated(vfb, vfbFormatChanged); } vfb->colorBindSeq = GetBindSeqCount(); - vfb->depthBindSeq = GetBindSeqCount(); gstate_c.curRTWidth = vfb->width; gstate_c.curRTHeight = vfb->height; @@ -527,6 +487,182 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame return vfb; } +// Called on the first use of depth in a render pass. +void FramebufferManagerCommon::SetDepthFrameBuffer(bool isClearingDepth) { + if (!currentRenderVfb_) { + return; + } + + // If this first draw call is anything other than a clear, "resolve" the depth buffer, + // by copying from any overlapping buffers with fresher content. + if (!isClearingDepth) { + CopyToDepthFromOverlappingFramebuffers(currentRenderVfb_); + } + + currentRenderVfb_->usageFlags |= FB_USAGE_RENDER_DEPTH; + currentRenderVfb_->depthBindSeq = GetBindSeqCount(); +} + +struct CopySource { + VirtualFramebuffer *vfb; + RasterChannel channel; + int xOffset; + int yOffset; + + int seq() const { + return channel == RASTER_DEPTH ? vfb->depthBindSeq : vfb->colorBindSeq; + } + + bool operator < (const CopySource &other) const { + return seq() < other.seq(); + } +}; + +// Not sure if it's more profitable to always do these copies with raster (which may screw up early-Z due to explicit depth buffer write) +// or to use image copies when possible (which may make it easier for the driver to preserve early-Z, but on the other hand, will cost additional memory +// bandwidth on tilers due to the load operation, which we might otherwise be able to skip). +void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest) { + std::vector sources; + for (auto src : vfbs_) { + if (src == dest) + continue; + + if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->fb_format == GE_FORMAT_565) { + if (src->colorBindSeq > dest->depthBindSeq) { + // Source has newer data than the current buffer, use it. + sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 }); + } + } else if (src->z_address == dest->z_address && src->z_stride == dest->z_stride && src->depthBindSeq > dest->depthBindSeq) { + sources.push_back(CopySource{ src, RASTER_DEPTH, 0, 0 }); + } else { + // TODO: Do more detailed overlap checks here. + } + } + + std::sort(sources.begin(), sources.end()); + + // TODO: A full copy will overwrite anything else. So we can eliminate + // anything that comes before such a copy. + + // For now, let's just do the last thing, if there are multiple. + + // for (auto &source : sources) { + if (!sources.empty()) { + draw_->InvalidateCachedState(); + + auto &source = sources.back(); + if (source.channel == RASTER_DEPTH) { + // Good old depth->depth copy. + BlitFramebufferDepth(source.vfb, dest); + gpuStats.numDepthCopies++; + dest->last_frame_depth_updated = gpuStats.numFlips; + } else if (source.channel == RASTER_COLOR && draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { + VirtualFramebuffer *src = source.vfb; + if (src->drawnFormat != GE_FORMAT_565) { + WARN_LOG_ONCE(not565, G3D, "Drawn fb_format of buffer at %08x not 565 as expected", src->fb_address); + } + + // Really hate to do this, but tracking the depth swizzle state across multiple + // copies is not easy. + Draw2DShader shader = DRAW2D_565_TO_DEPTH; + if (PSP_CoreParameter().compat.flags().DeswizzleDepth) { + shader = DRAW2D_565_TO_DEPTH_DESWIZZLE; + } + + gpuStats.numReinterpretCopies++; + + // Copying color to depth. + BlitUsingRaster( + src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, + dest->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, + false, Get2DPipeline(shader), "565_to_depth"); + } + } + + gstate_c.Dirty(DIRTY_TEXTURE_IMAGE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_RASTER_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_BLEND_STATE); +} + +// Call this after the target has been bound for rendering. For color, raster is probably always going to win over blits/copies. +void FramebufferManagerCommon::CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dst) { + std::vector sources; + for (auto src : vfbs_) { + // Discard old and equal potential inputs. + if (src == dst || src->colorBindSeq < dst->colorBindSeq) + continue; + + if (src->fb_address == dst->fb_address && src->fb_stride == dst->fb_stride) { + // Another render target at the exact same location but gotta be a different format, otherwise + // it would be the same. + _dbg_assert_(src->fb_format != dst->fb_format); + WARN_LOG_ONCE(reint, G3D, "Reinterpret detected at %08x", src->fb_address); + // This is where we'll do reinterprets in the future. + } else if (src->fb_stride == dst->fb_stride && src->fb_format == dst->fb_format) { + u32 bytesPerPixel = BufferFormatBytesPerPixel(src->fb_format); + + u32 strideInBytes = src->fb_stride * bytesPerPixel; // Same for both src and dest + + u32 srcColorStart = src->fb_address; + u32 srcFirstLineEnd = src->fb_address + strideInBytes; + u32 srcColorEnd = strideInBytes * src->height; + + u32 dstColorStart = dst->fb_address; + u32 dstFirstLineEnd = dst->fb_address + strideInBytes; + u32 dstColorEnd = strideInBytes * dst->height; + + // Initially we'll only allow pure horizontal and vertical overlap, + // to reduce the risk for false positives. We can allow diagonal overlap too if needed + // in the future. + + // Check for potential vertical overlap, like in Juiced 2. + int xOffset = 0; + int yOffset = 0; + + // TODO: Get rid of the compatibility flag check. + if ((dstColorStart - srcColorStart) % strideInBytes == 0 + && PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) { + // Buffers are aligned. + yOffset = ((int)dstColorStart - (int)srcColorStart) / strideInBytes; + if (yOffset <= -(int)src->height) { + // Not overlapping + continue; + } else if (yOffset >= dst->height) { + // Not overlapping + continue; + } + } else { + // Buffers not stride-aligned - ignoring for now. + continue; + } + gpuStats.numColorCopies++; + sources.push_back(CopySource{ src, RASTER_COLOR, xOffset, yOffset }); + } + } + + std::sort(sources.begin(), sources.end()); + + draw_->InvalidateCachedState(); + + for (const CopySource &source : sources) { + VirtualFramebuffer *src = source.vfb; + + // Copy a rectangle from the original to the new buffer. + // Yes, we mean to look at src->width/height for the dest rectangle. + int srcWidth = src->width * src->renderScaleFactor; + int srcHeight = src->height * src->renderScaleFactor; + int dstWidth = src->width * dst->renderScaleFactor; + int dstHeight = src->height * dst->renderScaleFactor; + + int dstX1 = -source.xOffset * dst->renderScaleFactor; + int dstY1 = -source.yOffset * dst->renderScaleFactor; + int dstX2 = dstX1 + dstWidth; + int dstY2 = dstY1 + dstHeight; + + BlitUsingRaster(src->fbo, 0.0f, 0.0f, srcWidth, srcHeight, + dst->fbo, dstX1, dstY1, dstX2, dstY2, false, Get2DPipeline(DRAW2D_COPY_COLOR), "copy_color"); + } +} + + void FramebufferManagerCommon::DestroyFramebuf(VirtualFramebuffer *v) { // Notify the texture cache of both the color and depth buffers. textureCache_->NotifyFramebuffer(v, NOTIFY_FB_DESTROYED); @@ -597,25 +733,10 @@ void FramebufferManagerCommon::BlitFramebufferDepth(VirtualFramebuffer *src, Vir draw_->BlitFramebuffer(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, Draw::FB_DEPTH_BIT, Draw::FB_BLIT_NEAREST, "BlitFramebufferDepth"); RebindFramebuffer("After BlitFramebufferDepth"); } else if (useRaster) { - BlitUsingRaster(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, false, RasterChannel::RASTER_DEPTH); + BlitUsingRaster(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, false, Get2DPipeline(Draw2DShader::DRAW2D_COPY_DEPTH), "BlitDepthRaster"); } draw_->InvalidateCachedState(); - - gpuStats.numDepthCopies++; - dst->last_frame_depth_updated = gpuStats.numFlips; -} - -VirtualFramebuffer *FramebufferManagerCommon::GetLatestDepthBufferAt(u32 z_address, u16 z_stride) { - int maxSeq = -1; - VirtualFramebuffer *latestDepth = nullptr; - for (auto vfb : vfbs_) { - if (vfb->z_address == z_address && vfb->z_stride == z_stride && vfb->depthBindSeq > maxSeq) { - maxSeq = vfb->depthBindSeq; - latestDepth = vfb; - } - } - return latestDepth; } void FramebufferManagerCommon::NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) { @@ -641,8 +762,8 @@ void FramebufferManagerCommon::NotifyRenderFramebufferCreated(VirtualFramebuffer void FramebufferManagerCommon::NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) { if (vfbFormatChanged) { textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_UPDATED); - if (vfb->drawnFormat != vfb->format) { - ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->format); + if (vfb->drawnFormat != vfb->fb_format) { + ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->fb_format); } } @@ -666,19 +787,8 @@ void FramebufferManagerCommon::NotifyRenderFramebufferSwitched(VirtualFramebuffe textureCache_->ForgetLastTexture(); shaderManager_->DirtyLastShader(); - // Copy depth between the framebuffers, if the z_address is the same (checked inside.) - VirtualFramebuffer * prevDepth = GetLatestDepthBufferAt(vfb->z_address, vfb->z_stride); - - // We might already want to copy depth, in case this is a temp buffer. See #7810. - if (prevDepth != vfb) { - if (!isClearingDepth && prevDepth) { - BlitFramebufferDepth(prevDepth, vfb); - } - prevDepth = vfb; - } - - if (vfb->drawnFormat != vfb->format) { - ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->format); + if (vfb->drawnFormat != vfb->fb_format) { + ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->fb_format); } if (useBufferedRendering_) { @@ -723,9 +833,9 @@ void FramebufferManagerCommon::NotifyVideoUpload(u32 addr, int size, int width, // TODO: Could possibly be an offset... VirtualFramebuffer *vfb = GetVFBAt(addr); if (vfb) { - if (vfb->format != fmt || vfb->drawnFormat != fmt) { - DEBUG_LOG(ME, "Changing format for %08x from %d to %d", addr, vfb->drawnFormat, fmt); - vfb->format = fmt; + if (vfb->fb_format != fmt || vfb->drawnFormat != fmt) { + DEBUG_LOG(ME, "Changing fb_format for %08x from %d to %d", addr, vfb->drawnFormat, fmt); + vfb->fb_format = fmt; vfb->drawnFormat = fmt; // Let's count this as a "render". This will also force us to use the correct format. @@ -734,7 +844,7 @@ void FramebufferManagerCommon::NotifyVideoUpload(u32 addr, int size, int width, if (vfb->fb_stride < width) { DEBUG_LOG(ME, "Changing stride for %08x from %d to %d", addr, vfb->fb_stride, width); - const int bpp = fmt == GE_FORMAT_8888 ? 4 : 2; + const int bpp = BufferFormatBytesPerPixel(fmt); ResizeFramebufFBO(vfb, width, size / (bpp * width)); // Resizing may change the viewport/etc. gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE); @@ -762,7 +872,7 @@ void FramebufferManagerCommon::UpdateFromMemory(u32 addr, int size, bool safe) { FlushBeforeCopy(); if (useBufferedRendering_ && vfb->fbo) { - GEBufferFormat fmt = vfb->format; + GEBufferFormat fmt = vfb->fb_format; if (vfb->last_frame_render + 1 < gpuStats.numFlips && isDisplayBuf) { // If we're not rendering to it, format may be wrong. Use displayFormat_ instead. fmt = displayFormat_; @@ -770,7 +880,7 @@ void FramebufferManagerCommon::UpdateFromMemory(u32 addr, int size, bool safe) { DrawPixels(vfb, 0, 0, Memory::GetPointer(addr), fmt, vfb->fb_stride, vfb->width, vfb->height); SetColorUpdated(vfb, gstate_c.skipDrawReason); } else { - INFO_LOG(FRAMEBUF, "Invalidating FBO for %08x (%i x %i x %i)", vfb->fb_address, vfb->width, vfb->height, vfb->format); + INFO_LOG(FRAMEBUF, "Invalidating FBO for %08x (%i x %i x %i)", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format); DestroyFramebuf(vfb); vfbs_.erase(vfbs_.begin() + i--); } @@ -1045,7 +1155,7 @@ void FramebufferManagerCommon::CopyDisplayToOutput(bool reallyDirty) { const u32 v_addr = v->fb_address & 0x3FFFFFFF; const u32 v_size = ColorBufferByteSize(v); if (addr >= v_addr && addr < v_addr + v_size) { - const u32 dstBpp = v->format == GE_FORMAT_8888 ? 4 : 2; + const u32 dstBpp = BufferFormatBytesPerPixel(v->fb_format); const u32 v_offsetX = ((addr - v_addr) / dstBpp) % v->fb_stride; const u32 v_offsetY = ((addr - v_addr) / dstBpp) / v->fb_stride; // We have enough space there for the display, right? @@ -1068,10 +1178,10 @@ void FramebufferManagerCommon::CopyDisplayToOutput(bool reallyDirty) { } } - if (vfb && vfb->format != displayFormat_) { + if (vfb && vfb->fb_format != displayFormat_) { if (vfb->last_frame_render + FBO_OLD_AGE < gpuStats.numFlips) { // The game probably switched formats on us. - vfb->format = displayFormat_; + vfb->fb_format = displayFormat_; } else { vfb = 0; } @@ -1171,7 +1281,7 @@ void FramebufferManagerCommon::DecimateFBOs() { if (vfb != displayFramebuf_ && vfb != prevDisplayFramebuf_ && vfb != prevPrevDisplayFramebuf_) { if (age > FBO_OLD_AGE) { - INFO_LOG(FRAMEBUF, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->format, age); + INFO_LOG(FRAMEBUF, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format, age); DestroyFramebuf(vfb); vfbs_.erase(vfbs_.begin() + i--); } @@ -1193,7 +1303,7 @@ void FramebufferManagerCommon::DecimateFBOs() { VirtualFramebuffer *vfb = bvfbs_[i]; int age = frameLastFramebufUsed_ - vfb->last_frame_render; if (age > FBO_OLD_AGE) { - INFO_LOG(FRAMEBUF, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->format, age); + INFO_LOG(FRAMEBUF, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format, age); DestroyFramebuf(vfb); bvfbs_.erase(bvfbs_.begin() + i--); } @@ -1269,7 +1379,7 @@ void FramebufferManagerCommon::ResizeFramebufFBO(VirtualFramebuffer *vfb, int w, shaderManager_->DirtyLastShader(); char tag[128]; - size_t len = snprintf(tag, sizeof(tag), "FB_%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->format)); + size_t len = snprintf(tag, sizeof(tag), "FB_%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->fb_format)); vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, 1, true, tag }); if (Memory::IsVRAMAddress(vfb->fb_address) && vfb->fb_stride != 0) { NotifyMemInfo(MemBlockFlags::ALLOC, vfb->fb_address, ColorBufferByteSize(vfb), tag, len); @@ -1280,7 +1390,7 @@ void FramebufferManagerCommon::ResizeFramebufFBO(VirtualFramebuffer *vfb, int w, NotifyMemInfo(MemBlockFlags::ALLOC, vfb->z_address, vfb->fb_stride * vfb->height * sizeof(uint16_t), buf, len); } if (old.fbo) { - INFO_LOG(FRAMEBUF, "Resizing FBO for %08x : %dx%dx%s", vfb->fb_address, w, h, GeBufferFormatToString(vfb->format)); + INFO_LOG(FRAMEBUF, "Resizing FBO for %08x : %dx%dx%s", vfb->fb_address, w, h, GeBufferFormatToString(vfb->fb_format)); if (vfb->fbo) { draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "ResizeFramebufFBO"); if (!skipCopy) { @@ -1327,7 +1437,7 @@ bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, // We only remove the kernel and uncached bits when comparing. const u32 vfb_address = vfb->fb_address & 0x3FFFFFFF; const u32 vfb_size = ColorBufferByteSize(vfb); - const u32 vfb_bpp = vfb->format == GE_FORMAT_8888 ? 4 : 2; + const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->fb_format); const u32 vfb_byteStride = vfb->fb_stride * vfb_bpp; const int vfb_byteWidth = vfb->width * vfb_bpp; @@ -1375,7 +1485,7 @@ bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, // Note - if we're here, we're in a memcpy, not a block transfer. Not allowing IntraVRAMBlockTransferAllowCreateFB. // Technically, that makes BlockTransferAllowCreateFB a bit of a misnomer. if (PSP_CoreParameter().compat.flags().BlockTransferAllowCreateFB) { - dstBuffer = CreateRAMFramebuffer(dst, srcBuffer->width, srcBuffer->height, srcBuffer->fb_stride, srcBuffer->format); + dstBuffer = CreateRAMFramebuffer(dst, srcBuffer->width, srcBuffer->height, srcBuffer->fb_stride, srcBuffer->fb_format); dstY = 0; } } @@ -1401,7 +1511,7 @@ bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, WARN_LOG_ONCE(btucpy, G3D, "Memcpy fbo upload %08x -> %08x (size: %x)", src, dst, size); FlushBeforeCopy(); const u8 *srcBase = Memory::GetPointerUnchecked(src); - DrawPixels(dstBuffer, 0, dstY, srcBase, dstBuffer->format, dstBuffer->fb_stride, dstBuffer->width, dstH); + DrawPixels(dstBuffer, 0, dstY, srcBase, dstBuffer->fb_format, dstBuffer->fb_stride, dstBuffer->width, dstH); SetColorUpdated(dstBuffer, skipDrawReason); RebindFramebuffer("RebindFramebuffer - Memcpy fbo upload"); // This is a memcpy, let's still copy just in case. @@ -1437,7 +1547,7 @@ void FramebufferManagerCommon::FindTransferFramebuffers(VirtualFramebuffer *&dst VirtualFramebuffer *vfb = vfbs_[i]; const u32 vfb_address = vfb->fb_address & 0x3FFFFFFF; const u32 vfb_size = ColorBufferByteSize(vfb); - const u32 vfb_bpp = vfb->format == GE_FORMAT_8888 ? 4 : 2; + const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->fb_format); const u32 vfb_byteStride = vfb->fb_stride * vfb_bpp; const u32 vfb_byteWidth = vfb->width * vfb_bpp; @@ -1512,10 +1622,10 @@ void FramebufferManagerCommon::FindTransferFramebuffers(VirtualFramebuffer *&dst if (bpp == 4) { // Only one possibility unless it's doing split pixel tricks (which we could detect through stride maybe). ramFormat = GE_FORMAT_8888; - } else if (srcBuffer->format != GE_FORMAT_8888) { + } else if (srcBuffer->fb_format != GE_FORMAT_8888) { // We guess that the game will interpret the data the same as it was in the source of the copy. // Seems like a likely good guess, and works in Test Drive Unlimited. - ramFormat = srcBuffer->format; + ramFormat = srcBuffer->fb_format; } else { // No info left - just fall back to something. But this is definitely split pixel tricks. ramFormat = GE_FORMAT_5551; @@ -1538,7 +1648,7 @@ void FramebufferManagerCommon::FindTransferFramebuffers(VirtualFramebuffer *&dst } VirtualFramebuffer *FramebufferManagerCommon::CreateRAMFramebuffer(uint32_t fbAddress, int width, int height, int stride, GEBufferFormat format) { - INFO_LOG(G3D, "Creating RAM framebuffer at %08x (%dx%d, stride %d, format %d)", fbAddress, width, height, stride, format); + INFO_LOG(G3D, "Creating RAM framebuffer at %08x (%dx%d, stride %d, fb_format %d)", fbAddress, width, height, stride, format); // A target for the destination is missing - so just create one! // Make sure this one would be found by the algorithm above so we wouldn't @@ -1559,9 +1669,9 @@ VirtualFramebuffer *FramebufferManagerCommon::CreateRAMFramebuffer(uint32_t fbAd vfb->renderHeight = (u16)(vfb->height * renderScaleFactor_); vfb->bufferWidth = vfb->width; vfb->bufferHeight = vfb->height; - vfb->format = format; + vfb->fb_format = format; vfb->drawnFormat = GE_FORMAT_8888; - vfb->usageFlags = FB_USAGE_RENDERTARGET; + vfb->usageFlags = FB_USAGE_RENDER_COLOR; SetColorUpdated(vfb, 0); char name[64]; snprintf(name, sizeof(name), "%08x_color_RAM", vfb->fb_address); @@ -1585,7 +1695,7 @@ VirtualFramebuffer *FramebufferManagerCommon::FindDownloadTempBuffer(VirtualFram // We maintain a separate vector of framebuffer objects for blitting. for (VirtualFramebuffer *v : bvfbs_) { - if (v->fb_address == vfb->fb_address && v->format == vfb->format) { + if (v->fb_address == vfb->fb_address && v->fb_format == vfb->fb_format) { if (v->bufferWidth == vfb->bufferWidth && v->bufferHeight == vfb->bufferHeight) { nvfb = v; v->fb_stride = vfb->fb_stride; @@ -1611,10 +1721,10 @@ VirtualFramebuffer *FramebufferManagerCommon::FindDownloadTempBuffer(VirtualFram nvfb->renderScaleFactor = 1; // For readbacks we resize to the original size, of course. nvfb->bufferWidth = vfb->bufferWidth; nvfb->bufferHeight = vfb->bufferHeight; - nvfb->format = vfb->format; + nvfb->fb_format = vfb->fb_format; nvfb->drawnWidth = vfb->drawnWidth; nvfb->drawnHeight = vfb->drawnHeight; - nvfb->drawnFormat = vfb->format; + nvfb->drawnFormat = vfb->fb_format; char name[64]; snprintf(name, sizeof(name), "download_temp"); @@ -1629,7 +1739,7 @@ VirtualFramebuffer *FramebufferManagerCommon::FindDownloadTempBuffer(VirtualFram UpdateDownloadTempBuffer(nvfb); } - nvfb->usageFlags |= FB_USAGE_RENDERTARGET; + nvfb->usageFlags |= FB_USAGE_RENDER_COLOR; nvfb->last_frame_render = gpuStats.numFlips; nvfb->dirtyAfterDisplay = true; @@ -1649,7 +1759,7 @@ void FramebufferManagerCommon::ApplyClearToMemory(int x1, int y1, int x2, int y2 } u8 *addr = Memory::GetPointerWriteUnchecked(gstate.getFrameBufAddress()); - const int bpp = gstate_c.framebufFormat == GE_FORMAT_8888 ? 4 : 2; + const int bpp = BufferFormatBytesPerPixel(gstate_c.framebufFormat); u32 clearBits = clearColor; if (bpp == 2) { @@ -1782,7 +1892,7 @@ bool FramebufferManagerCommon::NotifyBlockTransferBefore(u32 dstBasePtr, int dst dstBasePtr, dstX, dstY, dstStride); FlushBeforeCopy(); if (g_Config.bBlockTransferGPU && !srcBuffer->memoryUpdated) { - const int srcBpp = srcBuffer->format == GE_FORMAT_8888 ? 4 : 2; + const int srcBpp = BufferFormatBytesPerPixel(srcBuffer->fb_format); const float srcXFactor = (float)bpp / srcBpp; const bool tooTall = srcY + srcHeight > srcBuffer->bufferHeight; if (srcHeight <= 0 || (tooTall && srcY != 0)) { @@ -1833,7 +1943,7 @@ void FramebufferManagerCommon::NotifyBlockTransferAfter(u32 dstBasePtr, int dstS WARN_LOG_ONCE(btu, G3D, "Block transfer upload %08x -> %08x", srcBasePtr, dstBasePtr); FlushBeforeCopy(); const u8 *srcBase = Memory::GetPointerUnchecked(srcBasePtr) + (srcX + srcY * srcStride) * bpp; - int dstBpp = dstBuffer->format == GE_FORMAT_8888 ? 4 : 2; + int dstBpp = BufferFormatBytesPerPixel(dstBuffer->fb_format); float dstXFactor = (float)bpp / dstBpp; if (dstWidth > dstBuffer->width || dstHeight > dstBuffer->height) { // The buffer isn't big enough, and we have a clear hint of size. Resize. @@ -1846,7 +1956,7 @@ void FramebufferManagerCommon::NotifyBlockTransferAfter(u32 dstBasePtr, int dstS // Resizing may change the viewport/etc. gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE); } - DrawPixels(dstBuffer, static_cast(dstX * dstXFactor), dstY, srcBase, dstBuffer->format, static_cast(srcStride * dstXFactor), static_cast(dstWidth * dstXFactor), dstHeight); + DrawPixels(dstBuffer, static_cast(dstX * dstXFactor), dstY, srcBase, dstBuffer->fb_format, static_cast(srcStride * dstXFactor), static_cast(dstWidth * dstXFactor), dstHeight); SetColorUpdated(dstBuffer, skipDrawReason); RebindFramebuffer("RebindFramebuffer - NotifyBlockTransferAfter"); } @@ -1892,7 +2002,7 @@ void FramebufferManagerCommon::DestroyAllFBOs() { prevPrevDisplayFramebuf_ = nullptr; for (VirtualFramebuffer *vfb : vfbs_) { - INFO_LOG(FRAMEBUF, "Destroying FBO for %08x : %i x %i x %i", vfb->fb_address, vfb->width, vfb->height, vfb->format); + INFO_LOG(FRAMEBUF, "Destroying FBO for %08x : %i x %i x %i", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format); DestroyFramebuf(vfb); } vfbs_.clear(); @@ -1923,7 +2033,7 @@ Draw::Framebuffer *FramebufferManagerCommon::GetTempFBO(TempFBO reason, u16 w, u bool z_stencil = reason == TempFBO::STENCIL; char name[128]; - snprintf(name, sizeof(name), "temp_fbo_%dx%d%s", w, h, z_stencil ? "_depth" : ""); + snprintf(name, sizeof(name), "temp_fbo_%dx%d%s", w / renderScaleFactor_, h / renderScaleFactor_, z_stencil ? "_depth" : ""); Draw::Framebuffer *fbo = draw_->CreateFramebuffer({ w, h, 1, 1, z_stencil, name }); if (!fbo) { return nullptr; @@ -1946,7 +2056,7 @@ void FramebufferManagerCommon::UpdateFramebufUsage(VirtualFramebuffer *vfb) { checkFlag(FB_USAGE_DISPLAYED_FRAMEBUFFER, vfb->last_frame_displayed); checkFlag(FB_USAGE_TEXTURE, vfb->last_frame_used); - checkFlag(FB_USAGE_RENDERTARGET, vfb->last_frame_render); + checkFlag(FB_USAGE_RENDER_COLOR, vfb->last_frame_render); checkFlag(FB_USAGE_CLUT, vfb->last_frame_clut); } @@ -2136,7 +2246,7 @@ void FramebufferManagerCommon::PackFramebufferSync_(VirtualFramebuffer *vfb, int const u32 fb_address = vfb->fb_address & 0x3FFFFFFF; - Draw::DataFormat destFormat = GEFormatToThin3D(vfb->format); + Draw::DataFormat destFormat = GEFormatToThin3D(vfb->fb_format); const int dstBpp = (int)DataFormatSizeInBytes(destFormat); const int dstByteOffset = (y * vfb->fb_stride + x) * dstBpp; @@ -2156,7 +2266,7 @@ void FramebufferManagerCommon::PackFramebufferSync_(VirtualFramebuffer *vfb, int if (destPtr) { draw_->CopyFramebufferToMemorySync(vfb->fbo, Draw::FB_COLOR_BIT, x, y, w, h, destFormat, destPtr, vfb->fb_stride, "PackFramebufferSync_"); char tag[128]; - size_t len = snprintf(tag, sizeof(tag), "FramebufferPack/%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->format)); + size_t len = snprintf(tag, sizeof(tag), "FramebufferPack/%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->fb_format)); NotifyMemInfo(MemBlockFlags::WRITE, fb_address + dstByteOffset, dstSize, tag, len); } else { ERROR_LOG(G3D, "PackFramebufferSync_: Tried to readback to bad address %08x (stride = %d)", fb_address + dstByteOffset, vfb->fb_stride); @@ -2233,7 +2343,7 @@ void FramebufferManagerCommon::FlushBeforeCopy() { void FramebufferManagerCommon::DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) { VirtualFramebuffer *vfb = GetVFBAt(fb_address); if (vfb && vfb->fb_stride != 0) { - const u32 bpp = vfb->drawnFormat == GE_FORMAT_8888 ? 4 : 2; + const u32 bpp = BufferFormatBytesPerPixel(vfb->drawnFormat); int x = 0; int y = 0; int pixels = loadBytes / bpp; @@ -2287,7 +2397,7 @@ std::vector FramebufferManagerCommon::GetFramebufferList() cons FramebufferInfo info; info.fb_address = vfb->fb_address; info.z_address = vfb->z_address; - info.format = vfb->format; + info.format = vfb->fb_format; info.width = vfb->width; info.height = vfb->height; info.fbo = vfb->fbo; @@ -2314,22 +2424,21 @@ void FramebufferManagerCommon::DeviceLost() { DoRelease(reinterpretFromTo_[i][j]); } } - DoRelease(reinterpretVBuf_); - DoRelease(reinterpretSampler_); - DoRelease(reinterpretVS_); DoRelease(stencilUploadSampler_); DoRelease(stencilUploadPipeline_); - DoRelease(draw2DSamplerNearest_); - DoRelease(draw2DSamplerLinear_); - DoRelease(draw2DVs_); DoRelease(draw2DPipelineColor_); DoRelease(draw2DPipelineDepth_); + DoRelease(draw2DPipeline565ToDepth_); + DoRelease(draw2DPipeline565ToDepthDeswizzle_); + + draw2D_.DeviceLost(); draw_ = nullptr; } void FramebufferManagerCommon::DeviceRestore(Draw::DrawContext *draw) { draw_ = draw; + draw2D_.DeviceRestore(draw_); presentation_->DeviceRestore(draw); } @@ -2381,7 +2490,7 @@ void FramebufferManagerCommon::DrawActiveTexture(float x, float y, float w, floa // Rearrange to strip form. std::swap(coord[2], coord[3]); - DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, RASTER_COLOR); + draw2D_.DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, Get2DPipeline(DRAW2D_COPY_COLOR)); gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_RASTER_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } @@ -2430,8 +2539,9 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX float srcXFactor = src->renderScaleFactor; float srcYFactor = src->renderScaleFactor; - const int srcBpp = src->format == GE_FORMAT_8888 ? 4 : 2; + const int srcBpp = BufferFormatBytesPerPixel(src->fb_format); if (srcBpp != bpp && bpp != 0) { + // If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white). srcXFactor = (srcXFactor * bpp) / srcBpp; } int srcX1 = srcX * srcXFactor; @@ -2441,8 +2551,9 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX float dstXFactor = dst->renderScaleFactor; float dstYFactor = dst->renderScaleFactor; - const int dstBpp = dst->format == GE_FORMAT_8888 ? 4 : 2; + const int dstBpp = BufferFormatBytesPerPixel(dst->fb_format); if (dstBpp != bpp && bpp != 0) { + // If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white). dstXFactor = (dstXFactor * bpp) / dstBpp; } int dstX1 = dstX * dstXFactor; @@ -2475,13 +2586,14 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX draw_->BlitFramebuffer(src->fbo, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, channel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, Draw::FB_BLIT_NEAREST, tag); } else { + Draw2DPipeline *pipeline = Get2DPipeline(channel == RASTER_COLOR ? DRAW2D_COPY_COLOR : DRAW2D_COPY_DEPTH); Draw::Framebuffer *srcFBO = src->fbo; if (src == dst) { Draw::Framebuffer *tempFBO = GetTempFBO(TempFBO::BLIT, src->renderWidth, src->renderHeight); - BlitUsingRaster(src->fbo, srcX1, srcY1, srcX2, srcY2, tempFBO, dstX1, dstY1, dstX2, dstY2, false, channel); + BlitUsingRaster(src->fbo, srcX1, srcY1, srcX2, srcY2, tempFBO, dstX1, dstY1, dstX2, dstY2, false, pipeline, tag); srcFBO = tempFBO; } - BlitUsingRaster(srcFBO, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, false, channel); + BlitUsingRaster(srcFBO, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, false, pipeline, tag); } draw_->InvalidateCachedState(); @@ -2489,13 +2601,14 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_RASTER_STATE); } +// The input is raw pixel coordinates, scale not taken into account. void FramebufferManagerCommon::BlitUsingRaster( Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2, Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, bool linearFilter, - RasterChannel channel) { + Draw2DPipeline *pipeline, const char *tag) { - if (channel == RASTER_DEPTH) { + if (pipeline->info.writeChannel == RASTER_DEPTH) { _dbg_assert_(draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported); } @@ -2517,13 +2630,14 @@ void FramebufferManagerCommon::BlitUsingRaster( // Unbind the texture first to avoid the D3D11 hazard check (can't set render target to things bound as textures and vice versa, not even temporarily). draw_->BindTexture(0, nullptr); // This will get optimized away in case it's already bound (in VK and GL at least..) - draw_->BindFramebufferAsRenderTarget(dest, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "BlitUsingRaster"); - draw_->BindFramebufferAsTexture(src, 0, channel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, 0); + draw_->BindFramebufferAsRenderTarget(dest, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag ? tag : "BlitUsingRaster"); + draw_->BindFramebufferAsTexture(src, 0, pipeline->info.readChannel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, 0); Draw::Viewport vp{ 0.0f, 0.0f, (float)dest->Width(), (float)dest->Height(), 0.0f, 1.0f }; draw_->SetViewports(1, &vp); draw_->SetScissorRect(0, 0, (int)dest->Width(), (int)dest->Height()); - DrawStrip2D(nullptr, vtx, 4, linearFilter, channel); + + draw2D_.DrawStrip2D(nullptr, vtx, 4, linearFilter, pipeline, src->Width(), src->Height(), renderScaleFactor_); gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_RASTER_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 7952e83827..23b505b772 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -37,13 +37,14 @@ enum { FB_USAGE_DISPLAYED_FRAMEBUFFER = 1, - FB_USAGE_RENDERTARGET = 2, + FB_USAGE_RENDER_COLOR = 2, FB_USAGE_TEXTURE = 4, FB_USAGE_CLUT = 8, FB_USAGE_DOWNLOAD = 16, FB_USAGE_DOWNLOAD_CLEAR = 32, FB_USAGE_BLUE_TO_ALPHA = 64, FB_USAGE_FIRST_FRAME_SAVED = 128, + FB_USAGE_RENDER_DEPTH = 256, }; enum { @@ -71,6 +72,11 @@ struct VirtualFramebuffer { u16 fb_stride; u16 z_stride; + // The original PSP format of the framebuffer. + // In reality they are all RGBA8888 for better quality but this is what the PSP thinks it is. This is necessary + // when we need to interpret the bits directly (depal or buffer aliasing). + GEBufferFormat fb_format; + // width/height: The detected size of the current framebuffer, in original PSP pixels. u16 width; u16 height; @@ -98,11 +104,6 @@ struct VirtualFramebuffer { // The scale factor at which we are rendering (to achieve higher resolution). u8 renderScaleFactor; - // The original PSP format of the framebuffer. - // In reality they are all RGBA8888 for better quality but this is what the PSP thinks it is. This is necessary - // when we need to interpret the bits directly (depal or buffer aliasing). - GEBufferFormat format; - // The configured buffer format at the time of the latest/current draw. This will change first, then // if different we'll "reinterpret" the framebuffer to match 'format' as needed. GEBufferFormat drawnFormat; @@ -152,7 +153,7 @@ struct FramebufferHeuristicParams { u32 z_address; u16 fb_stride; u16 z_stride; - GEBufferFormat fmt; + GEBufferFormat fb_format; bool isClearingDepth; bool isWritingDepth; bool isDrawing; @@ -266,6 +267,8 @@ public: return vfb; } } + void SetDepthFrameBuffer(bool isClearingDepth); + void RebindFramebuffer(const char *tag); std::vector GetFramebufferList() const; @@ -288,8 +291,6 @@ public: void DownloadFramebufferForClut(u32 fb_address, u32 loadBytes); void DrawFramebufferToOutput(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride); - VirtualFramebuffer *GetLatestDepthBufferAt(u32 z_address, u16 z_stride); - void DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height); size_t NumVFBs() const { return vfbs_.size(); } @@ -340,14 +341,8 @@ public: int GetTargetBufferWidth() const { return currentRenderVfb_ ? currentRenderVfb_->bufferWidth : 480; } int GetTargetBufferHeight() const { return currentRenderVfb_ ? currentRenderVfb_->bufferHeight : 272; } int GetTargetStride() const { return currentRenderVfb_ ? currentRenderVfb_->fb_stride : 512; } - GEBufferFormat GetTargetFormat() const { return currentRenderVfb_ ? currentRenderVfb_->format : displayFormat_; } + GEBufferFormat GetTargetFormat() const { return currentRenderVfb_ ? currentRenderVfb_->fb_format : displayFormat_; } - void SetDepthUpdated() { - if (currentRenderVfb_) { - currentRenderVfb_->last_frame_depth_render = gpuStats.numFlips; - currentRenderVfb_->last_frame_depth_updated = gpuStats.numFlips; - } - } void SetColorUpdated(int skipDrawReason) { if (currentRenderVfb_) { SetColorUpdated(currentRenderVfb_, skipDrawReason); @@ -374,15 +369,20 @@ public: } void ReinterpretFramebuffer(VirtualFramebuffer *vfb, GEBufferFormat oldFormat, GEBufferFormat newFormat); + Draw2D *GetDraw2D() { + return &draw2D_; + } + protected: virtual void PackFramebufferSync_(VirtualFramebuffer *vfb, int x, int y, int w, int h); void SetViewport2D(int x, int y, int w, int h); Draw::Texture *MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height); void DrawActiveTexture(float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, int uvRotation, int flags); - void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, RasterChannel channel); - void Ensure2DResources(); - Draw::Pipeline *Create2DPipeline(void (*generate)(ShaderWriter &)); + Draw2DPipeline *Get2DPipeline(Draw2DShader shader); + + void CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dest); + void CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest); bool UpdateSize(); @@ -394,7 +394,7 @@ protected: void BlitUsingRaster( Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2, - Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, bool linearFilter, RasterChannel channel); + Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, bool linearFilter, Draw2DPipeline *pipeline, const char *tag); void CopyFramebufferForColorTexture(VirtualFramebuffer *dst, VirtualFramebuffer *src, int flags); @@ -426,7 +426,7 @@ protected: dstBuffer->dirtyAfterDisplay = true; dstBuffer->drawnWidth = dstBuffer->width; dstBuffer->drawnHeight = dstBuffer->height; - dstBuffer->drawnFormat = dstBuffer->format; + dstBuffer->drawnFormat = dstBuffer->fb_format; if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0) dstBuffer->reallyDirtyAfterDisplay = true; } @@ -500,10 +500,7 @@ protected: // Thin3D stuff for reinterpreting image data between the various 16-bit formats. // Safe, not optimal - there might be input attachment tricks, etc, but we can't use them // since we don't want N different implementations. - Draw::Pipeline *reinterpretFromTo_[3][3]{}; - Draw::ShaderModule *reinterpretVS_ = nullptr; - Draw::SamplerState *reinterpretSampler_ = nullptr; - Draw::Buffer *reinterpretVBuf_ = nullptr; + Draw2DPipeline *reinterpretFromTo_[3][3]{}; // Common implementation of stencil buffer upload. Also not 100% optimal, but not performance // critical either. @@ -511,10 +508,11 @@ protected: Draw::SamplerState *stencilUploadSampler_ = nullptr; // Draw2D pipelines - Draw::Pipeline *draw2DPipelineColor_ = nullptr; - Draw::Pipeline *draw2DPipelineDepth_ = nullptr; - Draw::SamplerState *draw2DSamplerLinear_ = nullptr; - Draw::SamplerState *draw2DSamplerNearest_ = nullptr; - Draw::ShaderModule *draw2DVs_ = nullptr; + Draw2DPipeline *draw2DPipelineColor_ = nullptr; + Draw2DPipeline *draw2DPipelineDepth_ = nullptr; + Draw2DPipeline *draw2DPipeline565ToDepth_ = nullptr; + Draw2DPipeline *draw2DPipeline565ToDepthDeswizzle_ = nullptr; + + Draw2D draw2D_; // The fragment shaders are "owned" by the pipelines since they're 1:1. }; diff --git a/GPU/Common/GPUStateUtils.cpp b/GPU/Common/GPUStateUtils.cpp index e86c056c5a..1272a0d7c0 100644 --- a/GPU/Common/GPUStateUtils.cpp +++ b/GPU/Common/GPUStateUtils.cpp @@ -557,9 +557,7 @@ DepthScaleFactors GetDepthScaleFactors() { } void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, float renderHeight, int bufferWidth, int bufferHeight, ViewportAndScissor &out) { - bool throughmode = gstate.isModeThrough(); - out.dirtyProj = false; - out.dirtyDepth = false; + out.throughMode = gstate.isModeThrough(); float renderWidthFactor, renderHeightFactor; float renderX = 0.0f, renderY = 0.0f; @@ -610,7 +608,7 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo float offsetX = gstate.getOffsetX(); float offsetY = gstate.getOffsetY(); - if (throughmode) { + if (out.throughMode) { out.viewportX = renderX * renderWidthFactor + displayOffsetX; out.viewportY = renderY * renderHeightFactor + displayOffsetY; out.viewportW = curRTWidth * renderWidthFactor; @@ -647,10 +645,10 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo float right = left + vpWidth; float bottom = top + vpHeight; - float wScale = 1.0f; - float xOffset = 0.0f; - float hScale = 1.0f; - float yOffset = 0.0f; + out.widthScale = 1.0f; + out.xOffset = 0.0f; + out.heightScale = 1.0f; + out.yOffset = 0.0f; // If we're within the bounds, we want clipping the viewport way. So leave it be. { @@ -678,8 +676,8 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo right = left + 1.0f; } - wScale = vpWidth / (right - left); - xOffset = drift / (right - left); + out.widthScale = vpWidth / (right - left); + out.xOffset = drift / (right - left); } } @@ -707,8 +705,8 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo bottom = top + 1.0f; } - hScale = vpHeight / (bottom - top); - yOffset = drift / (bottom - top); + out.heightScale = vpHeight / (bottom - top); + out.yOffset = drift / (bottom - top); } } @@ -740,13 +738,13 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo } // Okay. So, in our shader, -1 will map to minz, and +1 will map to maxz. float halfActualZRange = (maxz - minz) * (1.0f / 2.0f); - float zScale = halfActualZRange < std::numeric_limits::epsilon() ? 1.0f : vpZScale / halfActualZRange; + out.depthScale = halfActualZRange < std::numeric_limits::epsilon() ? 1.0f : vpZScale / halfActualZRange; // This adjusts the center from halfActualZRange to vpZCenter. - float zOffset = halfActualZRange < std::numeric_limits::epsilon() ? 0.0f : (vpZCenter - (minz + halfActualZRange)) / halfActualZRange; + out.zOffset = halfActualZRange < std::numeric_limits::epsilon() ? 0.0f : (vpZCenter - (minz + halfActualZRange)) / halfActualZRange; if (!gstate_c.Supports(GPU_SUPPORTS_ACCURATE_DEPTH)) { - zScale = 1.0f; - zOffset = 0.0f; + out.depthScale = 1.0f; + out.zOffset = 0.0f; out.depthRangeMin = ToScaledDepthFromIntegerScale(vpZCenter - vpZScale); out.depthRangeMax = ToScaledDepthFromIntegerScale(vpZCenter + vpZScale); } else { @@ -757,19 +755,27 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo // OpenGL will clamp these for us anyway, and Direct3D will error if not clamped. out.depthRangeMin = std::max(out.depthRangeMin, 0.0f); out.depthRangeMax = std::min(out.depthRangeMax, 1.0f); + } +} - bool scaleChanged = gstate_c.vpWidthScale != wScale || gstate_c.vpHeightScale != hScale; - bool offsetChanged = gstate_c.vpXOffset != xOffset || gstate_c.vpYOffset != yOffset; - bool depthChanged = gstate_c.vpDepthScale != zScale || gstate_c.vpZOffset != zOffset; - if (scaleChanged || offsetChanged || depthChanged) { - gstate_c.vpWidthScale = wScale; - gstate_c.vpHeightScale = hScale; - gstate_c.vpDepthScale = zScale; - gstate_c.vpXOffset = xOffset; - gstate_c.vpYOffset = yOffset; - gstate_c.vpZOffset = zOffset; - out.dirtyProj = true; - out.dirtyDepth = depthChanged; +void UpdateCachedViewportState(const ViewportAndScissor &vpAndScissor) { + if (vpAndScissor.throughMode) + return; + + bool scaleChanged = gstate_c.vpWidthScale != vpAndScissor.widthScale || gstate_c.vpHeightScale != vpAndScissor.heightScale; + bool offsetChanged = gstate_c.vpXOffset != vpAndScissor.xOffset || gstate_c.vpYOffset != vpAndScissor.yOffset; + bool depthChanged = gstate_c.vpDepthScale != vpAndScissor.depthScale || gstate_c.vpZOffset != vpAndScissor.zOffset; + if (scaleChanged || offsetChanged || depthChanged) { + gstate_c.vpWidthScale = vpAndScissor.widthScale; + gstate_c.vpHeightScale = vpAndScissor.heightScale; + gstate_c.vpDepthScale = vpAndScissor.depthScale; + gstate_c.vpXOffset = vpAndScissor.xOffset; + gstate_c.vpYOffset = vpAndScissor.yOffset; + gstate_c.vpZOffset = vpAndScissor.zOffset; + + gstate_c.Dirty(DIRTY_PROJMATRIX); + if (depthChanged) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); } } } @@ -1018,16 +1024,6 @@ void ConvertMaskState(GenericMaskState &maskState, bool allowFramebufferRead) { return; } - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Suppress color writes entirely in this mode. - maskState.applyFramebufferRead = false; - maskState.rgba[0] = false; - maskState.rgba[1] = false; - maskState.rgba[2] = false; - maskState.rgba[3] = false; - return; - } - // Invert to convert masks from the PSP's format where 1 is don't draw to PC where 1 is draw. uint32_t colorMask = ~((gstate.pmskc & 0xFFFFFF) | (gstate.pmska << 24)); diff --git a/GPU/Common/GPUStateUtils.h b/GPU/Common/GPUStateUtils.h index 956a71e7f6..41ee3adc73 100644 --- a/GPU/Common/GPUStateUtils.h +++ b/GPU/Common/GPUStateUtils.h @@ -75,10 +75,16 @@ struct ViewportAndScissor { float viewportH; float depthRangeMin; float depthRangeMax; - bool dirtyProj; - bool dirtyDepth; + float widthScale; + float heightScale; + float depthScale; + float xOffset; + float yOffset; + float zOffset; + bool throughMode; }; void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, float renderHeight, int bufferWidth, int bufferHeight, ViewportAndScissor &out); +void UpdateCachedViewportState(const ViewportAndScissor &vpAndScissor); float ToScaledDepthFromIntegerScale(float z); struct DepthScaleFactors { diff --git a/GPU/Common/ReinterpretFramebuffer.cpp b/GPU/Common/ReinterpretFramebuffer.cpp index b453a4d3d6..a981742aa8 100644 --- a/GPU/Common/ReinterpretFramebuffer.cpp +++ b/GPU/Common/ReinterpretFramebuffer.cpp @@ -20,11 +20,7 @@ static const SamplerDef samplers[1] = { // TODO: We could possibly have an option to preserve any extra color precision? But gonna start without it. // Requires full size integer math. It would be possible to make a floating point-only version with lots of // modulo and stuff, might do it one day. -void GenerateReinterpretFragmentShader(char *buffer, GEBufferFormat from, GEBufferFormat to, const ShaderLanguageDesc &lang) { - _assert_(lang.bitwiseOps); - - ShaderWriter writer(buffer, lang, ShaderStage::Fragment); - +Draw2DPipelineInfo GenerateReinterpretFragmentShader(ShaderWriter &writer, GEBufferFormat from, GEBufferFormat to) { writer.HighPrecisionFloat(); writer.DeclareSamplers(samplers); @@ -70,22 +66,13 @@ void GenerateReinterpretFragmentShader(char *buffer, GEBufferFormat from, GEBuff } writer.EndFSMain("outColor", FSFLAG_NONE); + + return Draw2DPipelineInfo{ + RASTER_COLOR, + RASTER_COLOR, + }; } -void GenerateReinterpretVertexShader(char *buffer, const ShaderLanguageDesc &lang) { - _assert_(lang.bitwiseOps); - ShaderWriter writer(buffer, lang, ShaderStage::Vertex); - - writer.BeginVSMain(Slice::empty(), Slice::empty(), varyings); - - writer.C(" float x = -1.0 + float((gl_VertexIndex & 1) << 2);\n"); - writer.C(" float y = -1.0 + float((gl_VertexIndex & 2) << 1);\n"); - writer.C(" v_texcoord = (vec2(x, y) + vec2(1.0, 1.0)) * 0.5;\n"); - writer.C(" gl_Position = vec4(x, y, 0.0, 1.0);\n"); - writer.EndVSMain(varyings); -} - - // Can't easily dynamically create these strings, we just pass along the pointer. static const char *reinterpretStrings[3][3] = { { @@ -112,7 +99,7 @@ void FramebufferManagerCommon::ReinterpretFramebuffer(VirtualFramebuffer *vfb, G _assert_(newFormat != oldFormat); // The caller is responsible for updating the format. - _assert_(newFormat == vfb->format); + _assert_(newFormat == vfb->fb_format); ShaderLanguage lang = draw_->GetShaderLanguageDesc().shaderLanguage; @@ -150,60 +137,15 @@ void FramebufferManagerCommon::ReinterpretFramebuffer(VirtualFramebuffer *vfb, G return; } - if (!reinterpretVS_) { - char *vsCode = new char[4000]; - const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); - GenerateReinterpretVertexShader(vsCode, shaderLanguageDesc); - reinterpretVS_ = draw_->CreateShaderModule(ShaderStage::Vertex, shaderLanguageDesc.shaderLanguage, (const uint8_t *)vsCode, strlen(vsCode), "reinterpret_vs"); - _assert_(reinterpretVS_); - delete[] vsCode; - } - - if (!reinterpretSampler_) { - Draw::SamplerStateDesc samplerDesc{}; - samplerDesc.magFilter = Draw::TextureFilter::LINEAR; - samplerDesc.minFilter = Draw::TextureFilter::LINEAR; - reinterpretSampler_ = draw_->CreateSamplerState(samplerDesc); - } - - if (!reinterpretVBuf_) { - reinterpretVBuf_ = draw_->CreateBuffer(12 * 3, Draw::BufferUsageFlag::DYNAMIC | Draw::BufferUsageFlag::VERTEXDATA); - } - // See if we need to create a new pipeline. - Draw::Pipeline *pipeline = reinterpretFromTo_[(int)oldFormat][(int)newFormat]; + Draw2DPipeline *pipeline = reinterpretFromTo_[(int)oldFormat][(int)newFormat]; if (!pipeline) { - char *fsCode = new char[4000]; - const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); - GenerateReinterpretFragmentShader(fsCode, oldFormat, newFormat, shaderLanguageDesc); - Draw::ShaderModule *reinterpretFS = draw_->CreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), "reinterpret_fs"); - _assert_(reinterpretFS); - delete[] fsCode; + pipeline = draw2D_.Create2DPipeline([=](ShaderWriter &shaderWriter) -> Draw2DPipelineInfo { + return GenerateReinterpretFragmentShader(shaderWriter, oldFormat, newFormat); + }); - std::vector shaders; - shaders.push_back(reinterpretVS_); - shaders.push_back(reinterpretFS); - - using namespace Draw; - Draw::PipelineDesc desc{}; - // We use a "fullscreen triangle". - // TODO: clear the stencil buffer. Hard to actually initialize it with the new alpha, though possible - let's see if - // we need it. - DepthStencilState *depth = draw_->CreateDepthStencilState({ false, false, Comparison::LESS }); - BlendState *blendstateOff = draw_->CreateBlendState({ false, 0xF }); - RasterState *rasterNoCull = draw_->CreateRasterState({}); - - // No uniforms for these, only a single texture input. - PipelineDesc pipelineDesc{ Primitive::TRIANGLE_LIST, shaders, nullptr, depth, blendstateOff, rasterNoCull, nullptr }; - pipeline = draw_->CreateGraphicsPipeline(pipelineDesc); - _assert_(pipeline != nullptr); reinterpretFromTo_[(int)oldFormat][(int)newFormat] = pipeline; - - depth->Release(); - blendstateOff->Release(); - rasterNoCull->Release(); - reinterpretFS->Release(); } // Copy to a temp framebuffer. @@ -213,18 +155,9 @@ void FramebufferManagerCommon::ReinterpretFramebuffer(VirtualFramebuffer *vfb, G // itself while writing. draw_->InvalidateCachedState(); draw_->CopyFramebufferImage(vfb->fbo, 0, 0, 0, 0, temp, 0, 0, 0, 0, vfb->renderWidth, vfb->renderHeight, 1, Draw::FBChannel::FB_COLOR_BIT, "reinterpret_prep"); - draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::DONT_CARE, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, reinterpretStrings[(int)oldFormat][(int)newFormat]); - draw_->BindPipeline(pipeline); - draw_->BindFramebufferAsTexture(temp, 0, Draw::FBChannel::FB_COLOR_BIT, 0); - draw_->BindSamplerStates(0, 1, &reinterpretSampler_); - draw_->SetScissorRect(0, 0, vfb->renderWidth, vfb->renderHeight); - Draw::Viewport vp = Draw::Viewport{ 0.0f, 0.0f, (float)vfb->renderWidth, (float)vfb->renderHeight, 0.0f, 1.0f }; - draw_->SetViewports(1, &vp); - // Vertex buffer not used - vertices generated in shader. - // TODO: Switch to a vertex buffer for GLES2/D3D9 compat. - draw_->BindVertexBuffers(0, 1, &reinterpretVBuf_, nullptr); - draw_->Draw(3, 0); - draw_->InvalidateCachedState(); + + BlitUsingRaster(temp, 0.0f, 0.0f, vfb->renderWidth, vfb->renderHeight, + vfb->fbo, 0.0f, 0.0f, vfb->renderWidth, vfb->renderHeight, false, pipeline, "reinterpret"); // Unbind. draw_->BindTexture(0, nullptr); diff --git a/GPU/Common/ReinterpretFramebuffer.h b/GPU/Common/ReinterpretFramebuffer.h index 5819366887..ac97e46a9e 100644 --- a/GPU/Common/ReinterpretFramebuffer.h +++ b/GPU/Common/ReinterpretFramebuffer.h @@ -1,11 +1,9 @@ #pragma once +#include "Common/GPU/ShaderWriter.h" + #include "GPU/ge_constants.h" #include "GPU/GPUCommon.h" -#include "Common/GPU/ShaderWriter.h" +#include "GPU/Common/Draw2D.h" -void GenerateReinterpretFragmentShader(char *buffer, GEBufferFormat from, GEBufferFormat to, const ShaderLanguageDesc &lang); - -// Just a single one. Can probably be shared with a lot of similar use cases. -// Generates the coordinates for a fullscreen triangle. -void GenerateReinterpretVertexShader(char *buffer, const ShaderLanguageDesc &lang); +Draw2DPipelineInfo GenerateReinterpretFragmentShader(ShaderWriter &writer, GEBufferFormat from, GEBufferFormat to); diff --git a/GPU/Common/ShaderCommon.h b/GPU/Common/ShaderCommon.h index d15d666e0f..1a69e5c387 100644 --- a/GPU/Common/ShaderCommon.h +++ b/GPU/Common/ShaderCommon.h @@ -29,7 +29,7 @@ enum DebugShaderType { SHADER_TYPE_GEOMETRY = 2, SHADER_TYPE_VERTEXLOADER = 3, // Not really a shader, but might as well re-use this mechanism SHADER_TYPE_PIPELINE = 4, // Vulkan and DX12 combines a bunch of state into pipeline objects. Might as well make them inspectable. - SHADER_TYPE_DEPAL = 5, + SHADER_TYPE_TEXTURE = 5, SHADER_TYPE_SAMPLER = 6, // Not really a shader either. Need to rename this enum... }; diff --git a/GPU/Common/ShaderId.cpp b/GPU/Common/ShaderId.cpp index 1176200799..849a1b8b19 100644 --- a/GPU/Common/ShaderId.cpp +++ b/GPU/Common/ShaderId.cpp @@ -240,8 +240,6 @@ std::string FragmentShaderDesc(const FShaderID &id) { if (id.Bit(FS_BIT_COLOR_AGAINST_ZERO)) desc << "ColorTest0 " << alphaTestFuncs[id.Bits(FS_BIT_COLOR_TEST_FUNC, 2)] << " "; // first 4 match; else if (id.Bit(FS_BIT_COLOR_TEST)) desc << "ColorTest " << alphaTestFuncs[id.Bits(FS_BIT_COLOR_TEST_FUNC, 2)] << " "; // first 4 match - if (id.Bit(FS_BIT_COLOR_TO_DEPTH)) desc << "ColorToDepth "; - return desc.str(); } @@ -263,8 +261,8 @@ void ComputeFragmentShaderID(FShaderID *id_out, const Draw::Bugs &bugs) { bool doTextureAlpha = gstate.isTextureAlphaUsed(); bool doFlatShading = gstate.getShadeMode() == GE_SHADE_FLAT; bool useShaderDepal = gstate_c.useShaderDepal; + bool useSmoothedDepal = gstate_c.useSmoothedShaderDepal; bool colorWriteMask = IsColorWriteMaskComplex(gstate_c.allowFramebufferRead); - bool colorToDepth = gstate_c.renderMode == RasterMode::RASTER_MODE_COLOR_TO_DEPTH; // Note how we here recompute some of the work already done in state mapping. // Not ideal! At least we share the code. @@ -293,11 +291,10 @@ void ComputeFragmentShaderID(FShaderID *id_out, const Draw::Bugs &bugs) { } id.SetBit(FS_BIT_BGRA_TEXTURE, gstate_c.bgraTexture); id.SetBit(FS_BIT_SHADER_DEPAL, useShaderDepal); + id.SetBit(FS_BIT_SHADER_SMOOTHED_DEPAL, useSmoothedDepal); id.SetBit(FS_BIT_3D_TEXTURE, gstate_c.curTextureIs3D); } - id.SetBit(FS_BIT_COLOR_TO_DEPTH, colorToDepth); - id.SetBit(FS_BIT_LMODE, lmode); if (enableAlphaTest) { // 5 bits total. diff --git a/GPU/Common/ShaderId.h b/GPU/Common/ShaderId.h index bcdf4f723c..a105af6746 100644 --- a/GPU/Common/ShaderId.h +++ b/GPU/Common/ShaderId.h @@ -94,7 +94,7 @@ enum FShaderBit : uint8_t { FS_BIT_NO_DEPTH_CANNOT_DISCARD_STENCIL = 49, FS_BIT_COLOR_WRITEMASK = 50, FS_BIT_3D_TEXTURE = 51, - FS_BIT_COLOR_TO_DEPTH = 52, + FS_BIT_SHADER_SMOOTHED_DEPAL = 52, }; static inline FShaderBit operator +(FShaderBit bit, int i) { diff --git a/GPU/Common/StencilCommon.cpp b/GPU/Common/StencilCommon.cpp index 5cd0f9d795..44cc9304bb 100644 --- a/GPU/Common/StencilCommon.cpp +++ b/GPU/Common/StencilCommon.cpp @@ -153,7 +153,7 @@ bool FramebufferManagerCommon::PerformStencilUpload(u32 addr, int size, StencilU if (!src) return false; - switch (dstBuffer->format) { + switch (dstBuffer->fb_format) { case GE_FORMAT_565: // Well, this doesn't make much sense. return false; @@ -290,7 +290,7 @@ bool FramebufferManagerCommon::PerformStencilUpload(u32 addr, int size, StencilU draw_->SetViewports(1, &viewport); // TODO: Switch the format to a single channel format? - Draw::Texture *tex = MakePixelTexture(src, dstBuffer->format, dstBuffer->fb_stride, dstBuffer->width, dstBuffer->height); + Draw::Texture *tex = MakePixelTexture(src, dstBuffer->fb_format, dstBuffer->fb_stride, dstBuffer->width, dstBuffer->height); if (!tex) { // Bad! return false; @@ -309,10 +309,10 @@ bool FramebufferManagerCommon::PerformStencilUpload(u32 addr, int size, StencilU continue; } StencilUB ub{}; - if (dstBuffer->format == GE_FORMAT_4444) { + if (dstBuffer->fb_format == GE_FORMAT_4444) { draw_->SetStencilParams(0xFF, (i << 4) | i, 0xFF); ub.stencilValue = i * (16.0f / 255.0f); - } else if (dstBuffer->format == GE_FORMAT_5551) { + } else if (dstBuffer->fb_format == GE_FORMAT_5551) { draw_->SetStencilParams(0xFF, 0xFF, 0xFF); ub.stencilValue = i * (128.0f / 255.0f); } else { diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 6049b4e787..aaa38bb7c7 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -105,14 +105,8 @@ inline int dimHeight(u16 dim) { // Vulkan color formats: // TODO -TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw) - : draw_(draw), - clutLastFormat_(0xFFFFFFFF), - clutTotalBytes_(0), - clutMaxBytes_(0), - clutRenderAddress_(0xFFFFFFFF), - clutAlphaLinear_(false), - isBgraBackend_(false) { +TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw, Draw2D *draw2D) + : draw_(draw), draw2D_(draw2D) { decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL; // TODO: Clamp down to 256/1KB? Need to check mipmapShareClut and clamp loadclut. @@ -130,11 +124,11 @@ TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw) replacer_.Init(); - depalShaderCache_ = new DepalShaderCache(draw); + textureShaderCache_ = new TextureShaderCache(draw, draw2D_); } TextureCacheCommon::~TextureCacheCommon() { - delete depalShaderCache_; + delete textureShaderCache_; FreeAlignedMemory(clutBufConverted_); FreeAlignedMemory(clutBufRaw_); @@ -265,10 +259,6 @@ SamplerCacheKey TextureCacheCommon::GetSamplingParams(int maxLevel, const TexCac } } - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - forceFiltering = TEX_FILTER_FORCE_NEAREST; - } - switch (forceFiltering) { case TEX_FILTER_AUTO: break; @@ -492,7 +482,14 @@ TexCacheEntry *TextureCacheCommon::SetTexture() { int h0 = gstate.getTextureHeight(0); int d0 = 1; ReplacedTexture &replaced = FindReplacement(entry, w0, h0, d0); - if (replaced.Valid()) { + if (replaced.IsInvalid()) { + entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE; + if (g_Config.bSaveNewTextures) { + // Load once more to actually save. + match = false; + reason = "replacing"; + } + } else { match = false; reason = "replacing"; } @@ -515,6 +512,7 @@ TexCacheEntry *TextureCacheCommon::SetTexture() { nextNeedsChange_ = false; // Might need a rebuild if the hash fails, but that will be set later. nextNeedsRebuild_ = false; + failedTexture_ = false; VERBOSE_LOG(G3D, "Texture at %08x found in cache, applying", texaddr); return entry; //Done! } else { @@ -610,10 +608,9 @@ TexCacheEntry *TextureCacheCommon::SetTexture() { gstate_c.curTextureHeight = h; gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0); + failedTexture_ = false; nextTexture_ = entry; - if (nextFramebufferTexture_) { - nextFramebufferTexture_ = nullptr; // in case it was accidentally set somehow? - } + nextFramebufferTexture_ = nullptr; nextNeedsRehash_ = true; // We still need to rebuild, to allocate a texture. But we'll bail early. nextNeedsRebuild_ = true; @@ -625,35 +622,27 @@ std::vector TextureCacheCommon::GetFramebufferCandidates(const std::vector candidates; - RasterChannel channel = Memory::IsDepthTexVRAMAddress(entry.addr) ? RasterChannel::RASTER_DEPTH : RasterChannel::RASTER_COLOR; - if (channel == RasterChannel::RASTER_DEPTH && !gstate_c.Supports(GPU_SUPPORTS_DEPTH_TEXTURE)) { - // Depth texture not supported. Don't try to match it, fall back to the memory behind.. - return std::vector(); - } - const std::vector &framebuffers = framebufferManager_->Framebuffers(); for (VirtualFramebuffer *framebuffer : framebuffers) { - FramebufferMatchInfo match = MatchFramebuffer(entry, framebuffer, texAddrOffset, channel); - switch (match.match) { - case FramebufferMatch::VALID: - candidates.push_back(AttachCandidate{ match, entry, framebuffer, channel }); - break; - default: - break; + FramebufferMatchInfo match{}; + if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_COLOR, &match)) { + candidates.push_back(AttachCandidate{ match, entry, framebuffer, RASTER_COLOR, framebuffer->colorBindSeq }); + } + match = {}; + if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_DEPTH, &match)) { + candidates.push_back(AttachCandidate{ match, entry, framebuffer, RASTER_DEPTH, framebuffer->depthBindSeq }); } } if (candidates.size() > 1) { - bool depth = channel == RasterChannel::RASTER_DEPTH; - std::string cands; for (auto &candidate : candidates) { cands += candidate.ToString() + " "; } - WARN_LOG_REPORT_ONCE(multifbcandidate, G3D, "GetFramebufferCandidates(%s): Multiple (%d) candidate framebuffers. First will be chosen. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s", - depth ? "DEPTH" : "COLOR", (int)candidates.size(), + WARN_LOG_REPORT_ONCE(multifbcandidate, G3D, "GetFramebufferCandidates: Multiple (%d) candidate framebuffers. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s", + (int)candidates.size(), entry.addr, texAddrOffset, dimWidth(entry.dim), dimHeight(entry.dim), entry.bufw, GeTextureFormatToString(entry.format), cands.c_str() ); @@ -677,29 +666,22 @@ int TextureCacheCommon::GetBestCandidateIndex(const std::vector // a comparison function. for (int i = 0; i < (int)candidates.size(); i++) { const AttachCandidate &candidate = candidates[i]; - int relevancy = 0; - switch (candidate.match.match) { - case FramebufferMatch::VALID: - relevancy += 1000; - break; - default: - break; - } + int relevancy = candidate.seqCount; // Bonus point for matching stride. if (candidate.channel == RASTER_COLOR && candidate.fb->fb_stride == candidate.entry.bufw) { - relevancy += 100; + relevancy += 1000; } // Bonus points for no offset. if (candidate.match.xOffset == 0 && candidate.match.yOffset == 0) { - relevancy += 10; + relevancy += 100; } if (candidate.channel == RASTER_COLOR && candidate.fb->last_frame_render == gpuStats.numFlips) { - relevancy += 5; + relevancy += 50; } else if (candidate.channel == RASTER_DEPTH && candidate.fb->last_frame_depth_render == gpuStats.numFlips) { - relevancy += 5; + relevancy += 50; } if (relevancy > bestRelevancy) { @@ -825,7 +807,7 @@ void TextureCacheCommon::NotifyFramebuffer(VirtualFramebuffer *framebuffer, Fram const u32 z_addr = framebuffer->z_address & ~mirrorMask; // Probably unnecessary. - const u32 fb_bpp = framebuffer->format == GE_FORMAT_8888 ? 4 : 2; + const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->fb_format); const u32 z_bpp = 2; // No other format exists. const u32 fb_stride = framebuffer->fb_stride; const u32 z_stride = framebuffer->z_stride; @@ -876,12 +858,26 @@ void TextureCacheCommon::NotifyFramebuffer(VirtualFramebuffer *framebuffer, Fram } } -FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( +bool TextureCacheCommon::MatchFramebuffer( const TextureDefinition &entry, - VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel) const { + VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel, FramebufferMatchInfo *matchInfo) const { static const u32 MAX_SUBAREA_Y_OFFSET_SAFE = 32; uint32_t fb_address = channel == RASTER_DEPTH ? framebuffer->z_address : framebuffer->fb_address; + uint32_t fb_stride = channel == RASTER_DEPTH ? framebuffer->z_stride : framebuffer->fb_stride; + GEBufferFormat fb_format = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : framebuffer->fb_format; + + if (channel == RASTER_DEPTH && framebuffer->z_address == framebuffer->fb_address) { + // Try to avoid silly matches to somewhat malformed buffers. + return false; + } + + switch (entry.format) { + case GE_TFMT_DXT1: + case GE_TFMT_DXT3: + case GE_TFMT_DXT5: + return false; + } u32 addr = fb_address & 0x3FFFFFFF; u32 texaddr = entry.addr + texaddrOffset; @@ -891,40 +887,19 @@ FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( if (texInVRAM != fbInVRAM) { // Shortcut. Cannot possibly be a match. - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } if (texInVRAM) { const u32 mirrorMask = 0x00600000; - // This bit controls swizzle. The swizzles at 0x00200000 and 0x00600000 are designed - // to perfectly match reading depth as color (which one to use I think might be related - // to the bpp of the color format used when rendering to it). - // It's fairly unlikely that games would screw this up since the result will be garbage so - // we use it to filter out unlikely matches. - switch (entry.addr & mirrorMask) { - case 0x00000000: - case 0x00400000: - // Don't match the depth channel with these addresses when texturing. - if (channel == RasterChannel::RASTER_DEPTH) { - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; - } - break; - case 0x00200000: - case 0x00600000: - // Don't match the color channel with these addresses when texturing. - if (channel == RasterChannel::RASTER_COLOR) { - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; - } - break; - } - addr &= ~mirrorMask; texaddr &= ~mirrorMask; } const bool noOffset = texaddr == addr; const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR; + const u32 w = 1 << ((entry.dim >> 0) & 0xf); const u32 h = 1 << ((entry.dim >> 8) & 0xf); // 512 on a 272 framebuffer is sane, so let's be lenient. @@ -932,103 +907,101 @@ FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( // If they match "exactly", it's non-CLUT and from the top left. if (exactMatch) { - if (framebuffer->fb_stride != entry.bufw) { - WARN_LOG_ONCE(diffStrides1, G3D, "Texturing from framebuffer with different strides %d != %d", entry.bufw, framebuffer->fb_stride); + if (fb_stride != entry.bufw) { + WARN_LOG_ONCE(diffStrides1, G3D, "Texturing from framebuffer with different strides %d != %d", entry.bufw, (int)fb_stride); } // NOTE: This check is okay because the first texture formats are the same as the buffer formats. if (IsTextureFormatBufferCompatible(entry.format)) { - if (TextureFormatMatchesBufferFormat(entry.format, framebuffer->format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) { - return FramebufferMatchInfo{ FramebufferMatch::VALID }; - } else if (IsTextureFormat16Bit(entry.format) && IsBufferFormat16Bit(framebuffer->format)) { - WARN_LOG_ONCE(diffFormat1, G3D, "Texturing from framebuffer with reinterpretable format: %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format)); - return FramebufferMatchInfo{ FramebufferMatch::VALID, 0, 0, true, TextureFormatToBufferFormat(entry.format) }; + if (TextureFormatMatchesBufferFormat(entry.format, fb_format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) { + return true; + } else if (IsTextureFormat16Bit(entry.format) && IsBufferFormat16Bit(fb_format) && channel == RASTER_COLOR) { + WARN_LOG_ONCE(diffFormat1, G3D, "Texturing from framebuffer with reinterpretable fb_format: %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); + *matchInfo = FramebufferMatchInfo{ 0, 0, true, TextureFormatToBufferFormat(entry.format) }; + return true; } else { - WARN_LOG_ONCE(diffFormat2, G3D, "Texturing from framebuffer with incompatible formats %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format)); - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + WARN_LOG_ONCE(diffFormat2, G3D, "Not texturing from framebuffer with incompatible formats %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); + return false; } } else { // Format incompatible, ignoring without comment. (maybe some really gnarly hacks will end up here...) - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } } else { // Apply to buffered mode only. if (!framebufferManager_->UseBufferedRendering()) { - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } // Check works for D16 too (???) const bool matchingClutFormat = - (channel != RASTER_COLOR && entry.format == GE_TFMT_CLUT16) || - (channel == RASTER_COLOR && framebuffer->format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || - (channel == RASTER_COLOR && framebuffer->format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); - - // To avoid ruining git blame, kept the same name as the old struct. - FramebufferMatchInfo fbInfo{ FramebufferMatch::VALID }; + (fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_CLUT16) || + (fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_5650) || + (fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || + (fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); const u32 bitOffset = (texaddr - addr) * 8; if (bitOffset != 0) { const u32 pixelOffset = bitOffset / std::max(1U, (u32)textureBitsPerPixel[entry.format]); - fbInfo.yOffset = entry.bufw == 0 ? 0 : pixelOffset / entry.bufw; - fbInfo.xOffset = entry.bufw == 0 ? 0 : pixelOffset % entry.bufw; + matchInfo->yOffset = entry.bufw == 0 ? 0 : pixelOffset / entry.bufw; + matchInfo->xOffset = entry.bufw == 0 ? 0 : pixelOffset % entry.bufw; } - if (fbInfo.yOffset + minSubareaHeight >= framebuffer->height) { + if (matchInfo->yOffset + minSubareaHeight >= framebuffer->height) { // Can't be inside the framebuffer. - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } - if (framebuffer->fb_stride != entry.bufw) { + if (fb_stride != entry.bufw) { if (noOffset) { - WARN_LOG_ONCE(diffStrides2, G3D, "Texturing from framebuffer (matching_clut=%s) different strides %d != %d", matchingClutFormat ? "yes" : "no", entry.bufw, framebuffer->fb_stride); + WARN_LOG_ONCE(diffStrides2, G3D, "Texturing from framebuffer (matching_clut=%s) different strides %d != %d", matchingClutFormat ? "yes" : "no", entry.bufw, fb_stride); // Continue on with other checks. // Not actually sure why we even try here. There's no way it'll go well if the strides are different. } else { // Assume any render-to-tex with different bufw + offset is a render from ram. - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } } // Check if it's in bufferWidth (which might be higher than width and may indicate the framebuffer includes the data.) - if (fbInfo.xOffset >= framebuffer->bufferWidth && fbInfo.xOffset + w <= (u32)framebuffer->fb_stride) { + if (matchInfo->xOffset >= framebuffer->bufferWidth && matchInfo->xOffset + w <= (u32)fb_stride) { // This happens in Brave Story, see #10045 - the texture is in the space between strides, with matching stride. - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } // Trying to play it safe. Below 0x04110000 is almost always framebuffers. // TODO: Maybe we can reduce this check and find a better way above 0x04110000? - if (fbInfo.yOffset > MAX_SUBAREA_Y_OFFSET_SAFE && addr > 0x04110000 && !PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) { - WARN_LOG_REPORT_ONCE(subareaIgnored, G3D, "Ignoring possible texturing from framebuffer at %08x +%dx%d / %dx%d", fb_address, fbInfo.xOffset, fbInfo.yOffset, framebuffer->width, framebuffer->height); - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + if (matchInfo->yOffset > MAX_SUBAREA_Y_OFFSET_SAFE && addr > 0x04110000 && !PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) { + WARN_LOG_REPORT_ONCE(subareaIgnored, G3D, "Ignoring possible texturing from framebuffer at %08x +%dx%d / %dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset, framebuffer->width, framebuffer->height); + return false; } // Check for CLUT. The framebuffer is always RGB, but it can be interpreted as a CLUT texture. // 3rd Birthday (and a bunch of other games) render to a 16 bit clut texture. if (matchingClutFormat) { if (!noOffset) { - WARN_LOG_ONCE(subareaClut, G3D, "Texturing from framebuffer using CLUT with offset at %08x +%dx%d", fb_address, fbInfo.xOffset, fbInfo.yOffset); + WARN_LOG_ONCE(subareaClut, G3D, "Texturing from framebuffer (%s) using %s with offset at %08x +%dx%d", channel == RASTER_DEPTH ? "DEPTH" : "COLOR", GeTextureFormatToString(entry.format), fb_address, matchInfo->xOffset, matchInfo->yOffset); } - fbInfo.match = FramebufferMatch::VALID; // We check the format again later, no need to return a special value here. - return fbInfo; + return true; } else if (IsClutFormat((GETextureFormat)(entry.format)) || IsDXTFormat((GETextureFormat)(entry.format))) { - WARN_LOG_ONCE(fourEightBit, G3D, "%s format not supported when texturing from framebuffer of format %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format)); - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + WARN_LOG_ONCE(fourEightBit, G3D, "%s fb_format not supported when texturing from framebuffer of format %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); + return false; } // This is either normal or we failed to generate a shader to depalettize - if ((int)framebuffer->format == (int)entry.format || matchingClutFormat) { - if ((int)framebuffer->format != (int)entry.format) { + if ((int)fb_format == (int)entry.format || matchingClutFormat) { + if ((int)fb_format != (int)entry.format) { WARN_LOG_ONCE(diffFormat2, G3D, "Texturing from framebuffer with different formats %s != %s at %08x", - GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format), fb_address); - return fbInfo; + GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address); + return true; } else { - WARN_LOG_ONCE(subarea, G3D, "Texturing from framebuffer at %08x +%dx%d", fb_address, fbInfo.xOffset, fbInfo.yOffset); - return fbInfo; + WARN_LOG_ONCE(subarea, G3D, "Texturing from framebuffer at %08x +%dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset); + return true; } } else { WARN_LOG_ONCE(diffFormat2, G3D, "Texturing from framebuffer with incompatible format %s != %s at %08x", - GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format), fb_address); - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address); + return false; } } } @@ -1038,18 +1011,20 @@ void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) FramebufferMatchInfo fbInfo = candidate.match; if (candidate.match.reinterpret) { - GEBufferFormat oldFormat = candidate.fb->format; - candidate.fb->format = candidate.match.reinterpretTo; + GEBufferFormat oldFormat = candidate.fb->fb_format; + candidate.fb->fb_format = candidate.match.reinterpretTo; framebufferManager_->ReinterpretFramebuffer(candidate.fb, oldFormat, candidate.match.reinterpretTo); } _dbg_assert_msg_(framebuffer != nullptr, "Framebuffer must not be null."); framebuffer->usageFlags |= FB_USAGE_TEXTURE; - if (framebufferManager_->UseBufferedRendering()) { - // Keep the framebuffer alive. - framebuffer->last_frame_used = gpuStats.numFlips; + // Keep the framebuffer alive. + framebuffer->last_frame_used = gpuStats.numFlips; + nextFramebufferTextureChannel_ = RASTER_COLOR; + + if (framebufferManager_->UseBufferedRendering()) { // We need to force it, since we may have set it on a texture before attaching. gstate_c.curTextureWidth = framebuffer->bufferWidth; gstate_c.curTextureHeight = framebuffer->bufferHeight; @@ -1068,7 +1043,15 @@ void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) gstate_c.SetNeedShaderTexclamp(true); } - nextFramebufferTexture_ = framebuffer; + if (candidate.channel == RASTER_DEPTH && !gstate_c.Supports(GPU_SUPPORTS_DEPTH_TEXTURE)) { + // Flag to bind a null texture if we can't support depth textures. + // Should only happen on old OpenGL. + nextFramebufferTexture_ = nullptr; + failedTexture_ = true; + } else { + nextFramebufferTexture_ = framebuffer; + nextFramebufferTextureChannel_ = candidate.channel; + } nextTexture_ = nullptr; } else { if (framebuffer->fbo) { @@ -1168,7 +1151,7 @@ void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes) { const std::vector &framebuffers = framebufferManager_->Framebuffers(); for (VirtualFramebuffer *framebuffer : framebuffers) { const u32 fb_address = framebuffer->fb_address & 0x3FFFFFFF; - const u32 bpp = framebuffer->drawnFormat == GE_FORMAT_8888 ? 4 : 2; + const u32 bpp = BufferFormatBytesPerPixel(framebuffer->drawnFormat); u32 offset = clutFramebufAddr - fb_address; // Is this inside the framebuffer at all? @@ -1327,22 +1310,22 @@ ReplacedTexture &TextureCacheCommon::FindReplacement(TexCacheEntry *entry, int & constexpr double MAX_BUDGET_PER_TEX = 0.25 / 60.0; double replaceStart = time_now_d(); + double budget = std::min(MAX_BUDGET_PER_TEX, replacementFrameBudget_ - replacementTimeThisFrame_); u64 cachekey = replacer_.Enabled() ? entry->CacheKey() : 0; - ReplacedTexture &replaced = replacer_.FindReplacement(cachekey, entry->fullhash, w, h); - if (replaced.IsReady(std::min(MAX_BUDGET_PER_TEX, replacementFrameBudget_ - replacementTimeThisFrame_))) { + ReplacedTexture &replaced = replacer_.FindReplacement(cachekey, entry->fullhash, w, h, budget); + if (replaced.IsReady(budget)) { if (replaced.GetSize(0, w, h)) { - replacementTimeThisFrame_ += time_now_d() - replaceStart; - - // Consider it already "scaled" and remove any delayed replace flag. + // Consider it already "scaled." entry->status |= TexCacheEntry::STATUS_IS_SCALED; - entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE; - return replaced; } - } else if (replaced.Valid()) { + + // Remove the flag, even if it was invalid. + entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE; + } else if (!replaced.IsInvalid()) { entry->status |= TexCacheEntry::STATUS_TO_REPLACE; } replacementTimeThisFrame_ += time_now_d() - replaceStart; - return replacer_.FindNone(); + return replaced; } // This is only used in the GLES backend, where we don't point these to video memory. @@ -1692,7 +1675,9 @@ CheckAlphaResult TextureCacheCommon::ReadIndexedTex(u8 *out, int outPitch, int l texptr = (u8 *)tmpTexBuf32_.data(); } - const bool mipmapShareClut = gstate.isClutSharedForMipmaps(); + // Misshitsu no Sacrifice has separate CLUT data, this is a hack to allow it. + // Normally separate CLUTs are not allowed for 8-bit or higher indices. + const bool mipmapShareClut = gstate.isClutSharedForMipmaps() || gstate.getClutLoadBlocks() != 0x40; const int clutSharingOffset = mipmapShareClut ? 0 : (level & 1) * 256; GEPaletteFormat palFormat = (GEPaletteFormat)gstate.getClutPaletteFormat(); @@ -1779,10 +1764,12 @@ void TextureCacheCommon::ApplyTexture() { if (!entry) { // Maybe we bound a framebuffer? InvalidateLastTexture(); - if (nextFramebufferTexture_) { - bool depth = Memory::IsDepthTexVRAMAddress(gstate.getTextureAddress(0)); + if (failedTexture_) { + // Backends should handle this by binding a black texture with 0 alpha. + BindTexture(nullptr); + } else if (nextFramebufferTexture_) { // ApplyTextureFrameBuffer is responsible for setting SetTextureFullAlpha. - ApplyTextureFramebuffer(nextFramebufferTexture_, gstate.getTextureFormat(), depth ? RASTER_DEPTH : RASTER_COLOR); + ApplyTextureFramebuffer(nextFramebufferTexture_, gstate.getTextureFormat(), nextFramebufferTextureChannel_); nextFramebufferTexture_ = nullptr; } @@ -1845,18 +1832,69 @@ void TextureCacheCommon::ApplyTexture() { gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0); } +bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferFormat) { + if (IsClutFormat(texFormat)) { + switch (bufferFormat) { + case GE_FORMAT_4444: + case GE_FORMAT_565: + case GE_FORMAT_5551: + case GE_FORMAT_DEPTH16: + if (texFormat == GE_TFMT_CLUT16) { + return true; + } + break; + case GE_FORMAT_8888: + if (texFormat == GE_TFMT_CLUT32) { + return true; + } + break; + } + WARN_LOG(G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat)); + return false; + } else if (texFormat == GE_TFMT_5650 && bufferFormat == GE_FORMAT_DEPTH16) { + // We can also "depal" 565 format, this is used to read depth buffers as 565 on occasion (#15491). + return true; + } else { + return false; + } +} + +// If the palette is detected as a smooth ramp, we can interpolate for higher color precision. +// But we only do it if the mask/shift exactly matches a color channel, else something different might be going +// on and we definitely don't want to interpolate. +// Great enhancement for Test Drive. +static bool CanUseSmoothDepal(const GPUgstate &gstate, GEBufferFormat framebufferFormat, int rampLength) { + if (gstate.getClutIndexStartPos() == 0 && + gstate.getClutIndexMask() <= rampLength) { + switch (framebufferFormat) { + case GE_FORMAT_565: + if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 11) { + return gstate.getClutIndexMask() == 0x1F; + } else if (gstate.getClutIndexShift() == 5) { + return gstate.getClutIndexMask() == 0x3F; + } + break; + case GE_FORMAT_5551: + if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 5 || gstate.getClutIndexShift() == 10) { + return gstate.getClutIndexMask() == 0x1F; + } + break; + } + } + return false; +} + void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, RasterChannel channel) { - DepalShader *depalShader = nullptr; + Draw2DPipeline *textureShader = nullptr; uint32_t clutMode = gstate.clutformat & 0xFFFFFF; - bool need_depalettize = IsClutFormat(texFormat); bool depth = channel == RASTER_DEPTH; + bool need_depalettize = CanDepalettize(texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat); bool useShaderDepal = framebufferManager_->GetCurrentRenderVFB() != framebuffer && !depth && !gstate_c.curTextureIs3D; // TODO: Implement shader depal in the fragment shader generator for D3D11 at least. if (!draw_->GetDeviceCaps().fragmentShaderInt32Supported) { useShaderDepal = false; - depth = false; // Can't support this } switch (draw_->GetShaderLanguageDesc().shaderLanguage) { @@ -1868,13 +1906,18 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer break; } + const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); + ClutTexture clutTexture{}; + bool smoothedDepal = false; + if (need_depalettize && !g_Config.bDisableSlowFramebufEffects) { + clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); + smoothedDepal = CanUseSmoothDepal(gstate, framebuffer->drawnFormat, clutTexture.rampLength); + if (useShaderDepal) { - const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); // Very icky conflation here of native and thin3d rendering. This will need careful work per backend in BindAsClutTexture. - Draw::Texture *clutTexture = depalShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); - BindAsClutTexture(clutTexture); + BindAsClutTexture(clutTexture.texture); framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET); // Vulkan needs to do some extra work here to pick out the native handle from Draw. @@ -1888,7 +1931,8 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer // Since we started/ended render passes, might need these. gstate_c.Dirty(DIRTY_DEPAL); - gstate_c.SetUseShaderDepal(true); + + gstate_c.SetUseShaderDepal(true, smoothedDepal); gstate_c.depalFramebufferFormat = framebuffer->drawnFormat; const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16); const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor; @@ -1900,13 +1944,13 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer return; } - depalShader = depalShaderCache_->GetDepalettizeShader(clutMode, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat); - gstate_c.SetUseShaderDepal(false); + textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat, smoothedDepal); + gstate_c.SetUseShaderDepal(false, false); } - if (depalShader) { + if (textureShader) { const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); - Draw::Texture *clutTexture = depalShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); + ClutTexture clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); Draw::Framebuffer *depalFBO = framebufferManager_->GetTempFBO(TempFBO::DEPAL, framebuffer->renderWidth, framebuffer->renderHeight); draw_->BindTexture(0, nullptr); draw_->BindTexture(1, nullptr); @@ -1916,17 +1960,17 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer Draw::Viewport vp{ 0.0f, 0.0f, (float)framebuffer->renderWidth, (float)framebuffer->renderHeight, 0.0f, 1.0f }; draw_->SetViewports(1, &vp); - TextureShaderApplier shaderApply(draw_, depalShader, framebuffer->bufferWidth, framebuffer->bufferHeight, framebuffer->renderWidth, framebuffer->renderHeight); - shaderApply.ApplyBounds(gstate_c.vertBounds, gstate_c.curTextureXOffset, gstate_c.curTextureYOffset); - shaderApply.Use(); - draw_->BindFramebufferAsTexture(framebuffer->fbo, 0, depth ? Draw::FB_DEPTH_BIT : Draw::FB_COLOR_BIT, 0); - draw_->BindTexture(1, clutTexture); - Draw::SamplerState *nearest = depalShaderCache_->GetSampler(); + draw_->BindTexture(1, clutTexture.texture); + Draw::SamplerState *nearest = textureShaderCache_->GetSampler(false); + Draw::SamplerState *clutSampler = textureShaderCache_->GetSampler(smoothedDepal); draw_->BindSamplerStates(0, 1, &nearest); - draw_->BindSamplerStates(1, 1, &nearest); + draw_->BindSamplerStates(1, 1, &clutSampler); + + textureShaderCache_->ApplyShader(textureShader, + framebuffer->bufferWidth, framebuffer->bufferHeight, framebuffer->renderWidth, framebuffer->renderHeight, + gstate_c.vertBounds, gstate_c.curTextureXOffset, gstate_c.curTextureYOffset); - shaderApply.Shade(); draw_->BindTexture(0, nullptr); framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer"); @@ -1946,7 +1990,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET); BoundFramebufferTexture(); - gstate_c.SetUseShaderDepal(false); + gstate_c.SetUseShaderDepal(false, false); gstate_c.SetTextureFullAlpha(gstate.getTextureFormat() == GE_TFMT_5650); } @@ -1958,7 +2002,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer } void TextureCacheCommon::Clear(bool delete_them) { - depalShaderCache_->Clear(); + textureShaderCache_->Clear(); ForgetLastTexture(); for (TexCache::iterator iter = cache_.begin(); iter != cache_.end(); ++iter) { @@ -2158,8 +2202,8 @@ void TextureCacheCommon::ClearNextFrame() { clearCacheNextFrame_ = true; } -std::string AttachCandidate::ToString() { - return StringFromFormat("[C:%08x/%d Z:%08x/%d X:%d Y:%d reint: %s]", this->fb->fb_address, this->fb->fb_stride, this->fb->z_address, this->fb->z_stride, this->match.xOffset, this->match.yOffset, this->match.reinterpret ? "true" : "false"); +std::string AttachCandidate::ToString() const { + return StringFromFormat("[%s seq:%d C:%08x/%d Z:%08x/%d X:%d Y:%d reint: %s]", this->channel == RASTER_COLOR ? "COLOR" : "DEPTH", this->seqCount, this->fb->fb_address, this->fb->fb_stride, this->fb->z_address, this->fb->z_stride, this->match.xOffset, this->match.yOffset, this->match.reinterpret ? "true" : "false"); } bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEntry *entry) { @@ -2261,11 +2305,6 @@ bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEnt plan.scaleFactor = 1; } - // Don't upscale textures in color-to-depth mode. - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - plan.scaleFactor = 1; - } - if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) != 0 && plan.scaleFactor != 1 && plan.slowScaler) { // Remember for later that we /wanted/ to scale this texture. entry->status |= TexCacheEntry::STATUS_TO_SCALE; @@ -2374,7 +2413,7 @@ void TextureCacheCommon::LoadTextureLevel(TexCacheEntry &entry, uint8_t *data, i } } - if (replacer_.Enabled()) { + if (replacer_.Enabled() && replaced.IsInvalid()) { ReplacedTextureDecodeInfo replacedInfo; replacedInfo.cachekey = entry.CacheKey(); replacedInfo.hash = entry.fullhash; @@ -2405,5 +2444,5 @@ CheckAlphaResult TextureCacheCommon::CheckCLUTAlpha(const uint8_t *pixelData, GE } void TextureCacheCommon::StartFrame() { - depalShaderCache_->Decimate(); + textureShaderCache_->Decimate(); } diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 3095efc466..145e0ee2e2 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -29,7 +29,9 @@ #include "GPU/Common/GPUDebugInterface.h" #include "GPU/Common/TextureDecoder.h" #include "GPU/Common/TextureScalerCommon.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" + +class Draw2D; enum FramebufferNotification { NOTIFY_FB_CREATED, @@ -206,15 +208,7 @@ typedef std::map> TexCache; #undef IGNORE #endif -enum class FramebufferMatch { - // Valid, exact match. - VALID = 0, - // Not a match, remove if currently attached. - NO_MATCH, -}; - struct FramebufferMatchInfo { - FramebufferMatch match; u32 xOffset; u32 yOffset; bool reinterpret; @@ -226,8 +220,9 @@ struct AttachCandidate { TextureDefinition entry; VirtualFramebuffer *fb; RasterChannel channel; + int seqCount; - std::string ToString(); + std::string ToString() const; }; class FramebufferManagerCommon; @@ -278,7 +273,7 @@ struct BuildTexturePlan { class TextureCacheCommon { public: - TextureCacheCommon(Draw::DrawContext *draw); + TextureCacheCommon(Draw::DrawContext *draw, Draw2D *draw2D); virtual ~TextureCacheCommon(); void LoadClut(u32 clutAddr, u32 loadBytes); @@ -298,7 +293,7 @@ public: void InvalidateAll(GPUInvalidationType type); void ClearNextFrame(); - DepalShaderCache *GetDepalShaderCache() { return depalShaderCache_; } + TextureShaderCache *GetTextureShaderCache() { return textureShaderCache_; } virtual void ForgetLastTexture() = 0; virtual void InvalidateLastTexture() = 0; @@ -365,7 +360,7 @@ protected: SamplerCacheKey GetFramebufferSamplingParams(u16 bufferWidth, u16 bufferHeight); void UpdateMaxSeenV(TexCacheEntry *entry, bool throughMode); - FramebufferMatchInfo MatchFramebuffer(const TextureDefinition &entry, VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel) const; + bool MatchFramebuffer(const TextureDefinition &entry, VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel, FramebufferMatchInfo *matchInfo) const; std::vector GetFramebufferCandidates(const TextureDefinition &entry, u32 texAddrOffset); int GetBestCandidateIndex(const std::vector &candidates); @@ -407,10 +402,12 @@ protected: } Draw::DrawContext *draw_; + Draw2D *draw2D_; + TextureReplacer replacer_; TextureScalerCommon scaler_; FramebufferManagerCommon *framebufferManager_; - DepalShaderCache *depalShaderCache_; + TextureShaderCache *textureShaderCache_; ShaderManagerCommon *shaderManager_; bool clearCacheNextFrame_ = false; @@ -440,7 +437,9 @@ protected: SimpleBuf tmpTexBufRearrange_; TexCacheEntry *nextTexture_ = nullptr; + bool failedTexture_ = false; VirtualFramebuffer *nextFramebufferTexture_ = nullptr; + RasterChannel nextFramebufferTextureChannel_ = RASTER_COLOR; u32 clutHash_ = 0; @@ -449,13 +448,13 @@ protected: u32 *clutBufConverted_; // This is the active one. u32 *clutBuf_; - u32 clutLastFormat_; - u32 clutTotalBytes_; - u32 clutMaxBytes_; - u32 clutRenderAddress_; + u32 clutLastFormat_ = 0xFFFFFFFF; + u32 clutTotalBytes_ = 0; + u32 clutMaxBytes_ = 0; + u32 clutRenderAddress_ = 0xFFFFFFFF; u32 clutRenderOffset_; // True if the clut is just alpha values in the same order (RGBA4444-bit only.) - bool clutAlphaLinear_; + bool clutAlphaLinear_ = false; u16 clutAlphaLinearColor_; int standardScaleFactor_; @@ -466,7 +465,7 @@ protected: bool nextNeedsChange_; bool nextNeedsRebuild_; - bool isBgraBackend_; + bool isBgraBackend_ = false; u32 expandClut_[256]; }; diff --git a/GPU/Common/TextureShaderCommon.cpp b/GPU/Common/TextureShaderCommon.cpp new file mode 100644 index 0000000000..694a646131 --- /dev/null +++ b/GPU/Common/TextureShaderCommon.cpp @@ -0,0 +1,295 @@ +// Copyright (c) 2014- 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 + +#include "Common/Log.h" +#include "Common/StringUtils.h" +#include "Common/GPU/Shader.h" +#include "Common/GPU/ShaderWriter.h" +#include "Common/Data/Convert/ColorConv.h" +#include "Core/Reporting.h" +#include "GPU/Common/Draw2D.h" +#include "GPU/Common/DrawEngineCommon.h" +#include "GPU/Common/TextureCacheCommon.h" +#include "GPU/Common/TextureShaderCommon.h" +#include "GPU/Common/DepalettizeShaderCommon.h" + +static const VaryingDef varyings[1] = { + { "vec2", "v_texcoord", Draw::SEM_TEXCOORD0, 0, "highp" }, +}; + +static const SamplerDef samplers[2] = { + { "tex" }, + { "pal" }, +}; + +TextureShaderCache::TextureShaderCache(Draw::DrawContext *draw, Draw2D *draw2D) : draw_(draw), draw2D_(draw2D) { } + +TextureShaderCache::~TextureShaderCache() { + DeviceLost(); +} + +void TextureShaderCache::DeviceRestore(Draw::DrawContext *draw) { + draw_ = draw; +} + +void TextureShaderCache::DeviceLost() { + Clear(); +} + +ClutTexture TextureShaderCache::GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut) { + // Simplistic, but works well enough. + u32 clutId = clutHash ^ (uint32_t)clutFormat; + + auto oldtex = texCache_.find(clutId); + if (oldtex != texCache_.end()) { + oldtex->second->lastFrame = gpuStats.numFlips; + return *oldtex->second; + } + + int maxClutEntries = clutFormat == GE_CMODE_32BIT_ABGR8888 ? 256 : 512; + + ClutTexture *tex = new ClutTexture(); + + Draw::TextureDesc desc{}; + desc.width = maxClutEntries; + desc.height = 1; + desc.depth = 1; + desc.mipLevels = 1; + desc.tag = "clut"; + desc.type = Draw::TextureType::LINEAR2D; // TODO: Try LINEAR1D? + desc.format = Draw::DataFormat::R8G8B8A8_UNORM; // TODO: Also support an BGR format. We won't bother with the 16-bit formats here. + + uint8_t convTemp[2048]{}; + + switch (clutFormat) { + case GEPaletteFormat::GE_CMODE_32BIT_ABGR8888: + desc.initData.push_back((const uint8_t *)rawClut); + break; + case GEPaletteFormat::GE_CMODE_16BIT_BGR5650: + ConvertRGB565ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, maxClutEntries); + desc.initData.push_back(convTemp); + break; + case GEPaletteFormat::GE_CMODE_16BIT_ABGR5551: + ConvertRGBA5551ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, maxClutEntries); + desc.initData.push_back(convTemp); + break; + case GEPaletteFormat::GE_CMODE_16BIT_ABGR4444: + ConvertRGBA4444ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, maxClutEntries); + desc.initData.push_back(convTemp); + break; + } + + int lastR = 0; + int lastG = 0; + int lastB = 0; + int lastA = 0; + + int rampLength = 0; + // Quick check for how many continouosly growing entries we have at the start. + // Bilinearly filtering CLUTs only really makes sense for this kind of ramp. + for (int i = 0; i < maxClutEntries; i++) { + rampLength = i + 1; + int r = desc.initData[0][i * 4]; + int g = desc.initData[0][i * 4 + 1]; + int b = desc.initData[0][i * 4 + 2]; + int a = desc.initData[0][i * 4 + 3]; + if (r < lastR || g < lastG || b < lastB || a < lastA) { + break; + } else { + lastR = r; + lastG = g; + lastB = b; + lastA = a; + } + } + + tex->texture = draw_->CreateTexture(desc); + tex->lastFrame = gpuStats.numFlips; + tex->rampLength = rampLength; + + texCache_[clutId] = tex; + return *tex; +} + +void TextureShaderCache::Clear() { + for (auto shader = depalCache_.begin(); shader != depalCache_.end(); ++shader) { + if (shader->second->pipeline) { + shader->second->pipeline->Release(); + } + delete shader->second; + } + depalCache_.clear(); + for (auto tex = texCache_.begin(); tex != texCache_.end(); ++tex) { + tex->second->texture->Release(); + delete tex->second; + } + texCache_.clear(); + if (nearestSampler_) { + nearestSampler_->Release(); + nearestSampler_ = nullptr; + } + if (linearSampler_) { + linearSampler_->Release(); + linearSampler_ = nullptr; + } +} + +Draw::SamplerState *TextureShaderCache::GetSampler(bool linearFilter) { + if (linearFilter) { + if (!linearSampler_) { + Draw::SamplerStateDesc desc{}; + desc.magFilter = Draw::TextureFilter::LINEAR; + desc.minFilter = Draw::TextureFilter::LINEAR; + desc.wrapU = Draw::TextureAddressMode::CLAMP_TO_EDGE; + desc.wrapV = Draw::TextureAddressMode::CLAMP_TO_EDGE; + desc.wrapW = Draw::TextureAddressMode::CLAMP_TO_EDGE; + linearSampler_ = draw_->CreateSamplerState(desc); + } + return linearSampler_; + } else { + if (!nearestSampler_) { + Draw::SamplerStateDesc desc{}; + desc.wrapU = Draw::TextureAddressMode::CLAMP_TO_EDGE; + desc.wrapV = Draw::TextureAddressMode::CLAMP_TO_EDGE; + desc.wrapW = Draw::TextureAddressMode::CLAMP_TO_EDGE; + nearestSampler_ = draw_->CreateSamplerState(desc); + } + return nearestSampler_; + } +} + +void TextureShaderCache::Decimate() { + for (auto tex = texCache_.begin(); tex != texCache_.end(); ) { + if (tex->second->lastFrame + DEPAL_TEXTURE_OLD_AGE < gpuStats.numFlips) { + tex->second->texture->Release(); + delete tex->second; + texCache_.erase(tex++); + } else { + ++tex; + } + } +} + +Draw2DPipeline *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETextureFormat textureFormat, GEBufferFormat bufferFormat, bool smoothedDepal) { + using namespace Draw; + + // Generate an ID for depal shaders. + u32 id = (clutMode & 0xFFFFFF) | (textureFormat << 24) | (bufferFormat << 28); + + auto shader = depalCache_.find(id); + if (shader != depalCache_.end()) { + return shader->second; + } + + // TODO: Parse these out of clutMode some nice way, to become a bit more stateless. + DepalConfig config; + config.clutFormat = gstate.getClutPaletteFormat(); + config.startPos = gstate.getClutIndexStartPos(); + config.shift = gstate.getClutIndexShift(); + config.mask = gstate.getClutIndexMask(); + config.bufferFormat = bufferFormat; + config.textureFormat = textureFormat; + config.smoothedDepal = smoothedDepal; + + char *buffer = new char[4096]; + Draw2DPipeline *ts = draw2D_->Create2DPipeline([=](ShaderWriter &writer) -> Draw2DPipelineInfo { + GenerateDepalFs(writer, config); + return Draw2DPipelineInfo{ + config.bufferFormat == GE_FORMAT_DEPTH16 ? RASTER_DEPTH : RASTER_COLOR, + RASTER_COLOR, + }; + }); + delete[] buffer; + + depalCache_[id] = ts; + + return ts->pipeline ? ts : nullptr; +} + +std::vector TextureShaderCache::DebugGetShaderIDs(DebugShaderType type) { + std::vector ids; + for (auto &iter : depalCache_) { + ids.push_back(StringFromFormat("%08x", iter.first)); + } + return ids; +} + +std::string TextureShaderCache::DebugGetShaderString(std::string idstr, DebugShaderType type, DebugShaderStringType stringType) { + uint32_t id; + sscanf(idstr.c_str(), "%08x", &id); + auto iter = depalCache_.find(id); + if (iter == depalCache_.end()) + return ""; + switch (stringType) { + case SHADER_STRING_SHORT_DESC: + return idstr; + case SHADER_STRING_SOURCE_CODE: + return iter->second->code; + default: + return ""; + } +} + +void TextureShaderCache::ApplyShader(Draw2DPipeline *pipeline, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff) { + Draw2DVertex verts[4] = { + {-1, -1, 0, 0 }, + { 1, -1, 1, 0 }, + {-1, 1, 0, 1 }, + { 1, 1, 1, 1 }, + }; + + // If min is not < max, then we don't have values (wasn't set during decode.) + if (bounds.minV < bounds.maxV) { + const float invWidth = 1.0f / bufferW; + const float invHeight = 1.0f / bufferH; + // Inverse of half = double. + const float invHalfWidth = invWidth * 2.0f; + const float invHalfHeight = invHeight * 2.0f; + + const int u1 = bounds.minU + uoff; + const int v1 = bounds.minV + voff; + const int u2 = bounds.maxU + uoff; + const int v2 = bounds.maxV + voff; + + const float left = u1 * invHalfWidth - 1.0f; + const float right = u2 * invHalfWidth - 1.0f; + const float top = v1 * invHalfHeight - 1.0f; + const float bottom = v2 * invHalfHeight - 1.0f; + + const float uvleft = u1 * invWidth; + const float uvright = u2 * invWidth; + const float uvtop = v1 * invHeight; + const float uvbottom = v2 * invHeight; + + // Points are: BL, BR, TR, TL. + verts[0] = Draw2DVertex{ left, bottom, uvleft, uvbottom }; + verts[1] = Draw2DVertex{ right, bottom, uvright, uvbottom }; + verts[2] = Draw2DVertex{ left, top, uvleft, uvtop }; + verts[3] = Draw2DVertex{ right, top, uvright, uvtop }; + + // We need to reapply the texture next time since we cropped UV. + gstate_c.Dirty(DIRTY_TEXTURE_PARAMS); + } + + Draw::Viewport vp{ 0.0f, 0.0f, (float)renderW, (float)renderH, 0.0f, 1.0f }; + draw_->BindPipeline(pipeline->pipeline); + draw_->SetViewports(1, &vp); + draw_->SetScissorRect(0, 0, renderW, renderH); + draw_->DrawUP((const uint8_t *)verts, 4); +} diff --git a/GPU/Common/TextureShaderCommon.h b/GPU/Common/TextureShaderCommon.h new file mode 100644 index 0000000000..5e0c5fe476 --- /dev/null +++ b/GPU/Common/TextureShaderCommon.h @@ -0,0 +1,69 @@ +// Copyright (c) 2014- 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 +#include +#include + +#include "Common/CommonTypes.h" +#include "Common/GPU/Shader.h" +#include "Common/GPU/thin3d.h" +#include "GPU/ge_constants.h" +#include "GPU/Common/Draw2D.h" +#include "GPU/Common/ShaderCommon.h" +#include "GPU/Common/DepalettizeShaderCommon.h" + +class ClutTexture { +public: + Draw::Texture *texture; + int lastFrame; + int rampLength; +}; + +// For CLUT depal shaders, and other pre-bind texture shaders. +// Caches both shaders and palette textures. +class TextureShaderCache { +public: + TextureShaderCache(Draw::DrawContext *draw, Draw2D *draw2D); + ~TextureShaderCache(); + + Draw2DPipeline *GetDepalettizeShader(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat, bool smoothedDepal); + ClutTexture GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); + + Draw::SamplerState *GetSampler(bool linearFilter); + + void ApplyShader(Draw2DPipeline *pipeline, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff); + + void Clear(); + void Decimate(); + std::vector DebugGetShaderIDs(DebugShaderType type); + std::string DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType); + + void DeviceLost(); + void DeviceRestore(Draw::DrawContext *draw); + +private: + Draw::DrawContext *draw_; + Draw::SamplerState *nearestSampler_ = nullptr; + Draw::SamplerState *linearSampler_ = nullptr; + Draw2D *draw2D_; + + std::map depalCache_; + std::map texCache_; +}; diff --git a/GPU/D3D11/DrawEngineD3D11.cpp b/GPU/D3D11/DrawEngineD3D11.cpp index 6bc808ef6a..1822fc5256 100644 --- a/GPU/D3D11/DrawEngineD3D11.cpp +++ b/GPU/D3D11/DrawEngineD3D11.cpp @@ -617,12 +617,13 @@ rotateVBO: framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); } int maxIndex = indexGen.MaxIndex(); SoftwareTransform swTransform(params); - const Lin::Vec3 trans(gstate_c.vpXOffset, gstate_c.vpYOffset, gstate_c.vpZOffset * 0.5f + 0.5f); + const Lin::Vec3 trans(gstate_c.vpXOffset, -gstate_c.vpYOffset, gstate_c.vpZOffset * 0.5f + 0.5f); const Lin::Vec3 scale(gstate_c.vpWidthScale, -gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); swTransform.SetProjMatrix(gstate.projMatrix, gstate_c.vpWidth < 0, gstate_c.vpHeight < 0, trans, scale); @@ -693,9 +694,6 @@ rotateVBO: if (gstate.isClearModeAlphaMask()) clearFlag |= Draw::FBChannel::FB_STENCIL_BIT; if (gstate.isClearModeDepthMask()) clearFlag |= Draw::FBChannel::FB_DEPTH_BIT; - if (clearFlag & Draw::FBChannel::FB_DEPTH_BIT) { - framebufferManager_->SetDepthUpdated(); - } if (clearFlag & Draw::FBChannel::FB_COLOR_BIT) { framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); } diff --git a/GPU/D3D11/GPU_D3D11.cpp b/GPU/D3D11/GPU_D3D11.cpp index ba41521fde..94bfa6afa9 100644 --- a/GPU/D3D11/GPU_D3D11.cpp +++ b/GPU/D3D11/GPU_D3D11.cpp @@ -35,7 +35,6 @@ #include "GPU/GeDisasm.h" #include "GPU/Common/FramebufferManagerCommon.h" -#include "GPU/Debugger/Debugger.h" #include "GPU/D3D11/ShaderManagerD3D11.h" #include "GPU/D3D11/GPU_D3D11.h" #include "GPU/D3D11/FramebufferManagerD3D11.h" @@ -60,7 +59,7 @@ GPU_D3D11::GPU_D3D11(GraphicsContext *gfxCtx, Draw::DrawContext *draw) shaderManagerD3D11_ = new ShaderManagerD3D11(draw, device_, context_, featureLevel); framebufferManagerD3D11_ = new FramebufferManagerD3D11(draw); framebufferManager_ = framebufferManagerD3D11_; - textureCacheD3D11_ = new TextureCacheD3D11(draw); + textureCacheD3D11_ = new TextureCacheD3D11(draw, framebufferManager_->GetDraw2D()); textureCache_ = textureCacheD3D11_; drawEngineCommon_ = &drawEngine_; shaderManager_ = shaderManagerD3D11_; @@ -239,13 +238,6 @@ void GPU_D3D11::BeginFrame() { gstate_c.Dirty(DIRTY_PROJTHROUGHMATRIX); } -void GPU_D3D11::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { - // TODO: Some games like Spongebob - Yellow Avenger, never change framebuffer, they blit to it. - // So breaking on frames doesn't work. Might want to move this to sceDisplay vsync. - GPUDebug::NotifyDisplay(framebuf, stride, format); - framebufferManagerD3D11_->SetDisplayFramebuffer(framebuf, stride, format); -} - void GPU_D3D11::CopyDisplayToOutput(bool reallyDirty) { // Flush anything left over. drawEngine_.Flush(); @@ -332,8 +324,8 @@ std::vector GPU_D3D11::DebugGetShaderIDs(DebugShaderType type) { switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderIDs(); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderIDs(type); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderIDs(type); default: return shaderManagerD3D11_->DebugGetShaderIDs(type); } @@ -343,8 +335,8 @@ std::string GPU_D3D11::DebugGetShaderString(std::string id, DebugShaderType type switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderString(id, stringType); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderString(id, type, stringType); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderString(id, type, stringType); default: return shaderManagerD3D11_->DebugGetShaderString(id, type, stringType); } diff --git a/GPU/D3D11/GPU_D3D11.h b/GPU/D3D11/GPU_D3D11.h index 94a0aef915..d1e5287782 100644 --- a/GPU/D3D11/GPU_D3D11.h +++ b/GPU/D3D11/GPU_D3D11.h @@ -23,7 +23,7 @@ #include "GPU/GPUCommon.h" #include "GPU/D3D11/DrawEngineD3D11.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Common/VertexDecoderCommon.h" class FramebufferManagerD3D11; @@ -41,7 +41,6 @@ public: void ExecuteOp(u32 op, u32 diff) override; void ReapplyGfxState() override; - void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void GetStats(char *buffer, size_t bufsize) override; void ClearCacheNextFrame() override; void DeviceLost() override; // Only happens on Android. Drop all textures and shaders. diff --git a/GPU/D3D11/StateMappingD3D11.cpp b/GPU/D3D11/StateMappingD3D11.cpp index 79a169a8ab..11db65c553 100644 --- a/GPU/D3D11/StateMappingD3D11.cpp +++ b/GPU/D3D11/StateMappingD3D11.cpp @@ -293,21 +293,11 @@ void DrawEngineD3D11::ApplyDrawState(int prim) { GenericStencilFuncState stencilState; ConvertStencilFuncState(stencilState); - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Enforce plain depth writing. - keys_.depthStencil.value = 0; - keys_.depthStencil.depthTestEnable = true; - keys_.depthStencil.depthWriteEnable = true; - keys_.depthStencil.stencilTestEnable = false; - keys_.depthStencil.depthCompareOp = D3D11_COMPARISON_ALWAYS; - } else if (gstate.isModeClear()) { + if (gstate.isModeClear()) { keys_.depthStencil.value = 0; keys_.depthStencil.depthTestEnable = true; keys_.depthStencil.depthCompareOp = D3D11_COMPARISON_ALWAYS; keys_.depthStencil.depthWriteEnable = gstate.isClearModeDepthMask(); - if (gstate.isClearModeDepthMask()) { - framebufferManager_->SetDepthUpdated(); - } // Stencil Test bool alphaMask = gstate.isClearModeAlphaMask(); @@ -336,9 +326,6 @@ void DrawEngineD3D11::ApplyDrawState(int prim) { keys_.depthStencil.depthTestEnable = true; keys_.depthStencil.depthCompareOp = compareOps[gstate.getDepthTestFunction()]; keys_.depthStencil.depthWriteEnable = gstate.isDepthWriteEnabled(); - if (gstate.isDepthWriteEnabled()) { - framebufferManager_->SetDepthUpdated(); - } } else { keys_.depthStencil.depthTestEnable = false; keys_.depthStencil.depthWriteEnable = false; @@ -387,15 +374,13 @@ void DrawEngineD3D11::ApplyDrawState(int prim) { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); float depthMin = vpAndScissor.depthRangeMin; float depthMax = vpAndScissor.depthRangeMax; if (depthMin < 0.0f) depthMin = 0.0f; if (depthMax > 1.0f) depthMax = 1.0f; - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } Draw::Viewport &vp = dynState_.viewport; vp.TopLeftX = vpAndScissor.viewportX; @@ -405,10 +390,6 @@ void DrawEngineD3D11::ApplyDrawState(int prim) { vp.MinDepth = depthMin; vp.MaxDepth = depthMax; - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - D3D11_RECT &scissor = dynState_.scissor; scissor.left = vpAndScissor.scissorX; scissor.top = vpAndScissor.scissorY; diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index 8479a3dcb1..1288db58d8 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -31,7 +31,7 @@ #include "GPU/D3D11/TextureCacheD3D11.h" #include "GPU/D3D11/FramebufferManagerD3D11.h" #include "GPU/D3D11/ShaderManagerD3D11.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/D3D11/D3D11Util.h" #include "GPU/Common/FramebufferManagerCommon.h" #include "GPU/Common/TextureDecoder.h" @@ -127,8 +127,8 @@ ID3D11SamplerState *SamplerCacheD3D11::GetOrCreateSampler(ID3D11Device *device, return sampler; } -TextureCacheD3D11::TextureCacheD3D11(Draw::DrawContext *draw) - : TextureCacheCommon(draw) { +TextureCacheD3D11::TextureCacheD3D11(Draw::DrawContext *draw, Draw2D *draw2D) + : TextureCacheCommon(draw, draw2D) { device_ = (ID3D11Device *)draw->GetNativeObject(Draw::NativeObject::DEVICE); context_ = (ID3D11DeviceContext *)draw->GetNativeObject(Draw::NativeObject::CONTEXT); @@ -236,6 +236,11 @@ void TextureCacheD3D11::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBa } void TextureCacheD3D11::BindTexture(TexCacheEntry *entry) { + if (!entry) { + ID3D11ShaderResourceView *textureView = nullptr; + context_->PSSetShaderResources(0, 1, &textureView); + return; + } ID3D11ShaderResourceView *textureView = DxView(entry); if (textureView != lastBoundTexture) { context_->PSSetShaderResources(0, 1, &textureView); @@ -460,6 +465,8 @@ bool TextureCacheD3D11::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE); // We may have blitted to a temp FBO. framebufferManager_->RebindFramebuffer("RebindFramebuffer - GetCurrentTextureDebug"); + if (!retval) + ERROR_LOG(G3D, "Failed to get debug texture: copy to memory failed"); return retval; } else { return false; diff --git a/GPU/D3D11/TextureCacheD3D11.h b/GPU/D3D11/TextureCacheD3D11.h index 433f6e824e..86313d0be1 100644 --- a/GPU/D3D11/TextureCacheD3D11.h +++ b/GPU/D3D11/TextureCacheD3D11.h @@ -28,7 +28,7 @@ struct VirtualFramebuffer; class FramebufferManagerD3D11; -class DepalShaderCache; +class TextureShaderCache; class ShaderManagerD3D11; class SamplerCacheD3D11 { @@ -43,7 +43,7 @@ private: class TextureCacheD3D11 : public TextureCacheCommon { public: - TextureCacheD3D11(Draw::DrawContext *draw); + TextureCacheD3D11(Draw::DrawContext *draw, Draw2D *draw2D); ~TextureCacheD3D11(); void StartFrame() override; diff --git a/GPU/Debugger/Debugger.cpp b/GPU/Debugger/Debugger.cpp index 04fb647f1d..439c763e8e 100644 --- a/GPU/Debugger/Debugger.cpp +++ b/GPU/Debugger/Debugger.cpp @@ -154,6 +154,15 @@ void NotifyDisplay(u32 framebuf, u32 stride, int format) { } } +void NotifyBeginFrame() { + if (!active) + return; + if (breakNext == BreakNext::VSYNC) { + // Just start stepping as soon as we can once the vblank finishes. + breakNext = BreakNext::OP; + } +} + int PrimsThisFrame() { return primsThisFrame; } diff --git a/GPU/Debugger/Debugger.h b/GPU/Debugger/Debugger.h index 43ec3174b9..b17c6b4ad0 100644 --- a/GPU/Debugger/Debugger.h +++ b/GPU/Debugger/Debugger.h @@ -28,6 +28,7 @@ enum class BreakNext { TEX, NONTEX, FRAME, + VSYNC, PRIM, CURVE, COUNT, @@ -43,6 +44,7 @@ void SetBreakCount(int c, bool relative = false); bool NotifyCommand(u32 pc); void NotifyDraw(); void NotifyDisplay(u32 framebuf, u32 stride, int format); +void NotifyBeginFrame(); int PrimsThisFrame(); int PrimsLastFrame(); diff --git a/GPU/Debugger/Record.cpp b/GPU/Debugger/Record.cpp index 0a15fb8f43..cc63dccf72 100644 --- a/GPU/Debugger/Record.cpp +++ b/GPU/Debugger/Record.cpp @@ -50,6 +50,7 @@ namespace GPURecord { static bool active = false; static bool nextFrame = false; static int flipLastAction = -1; +static int flipFinishAt = -1; static std::function writeCallback; static std::vector pushbuf; @@ -145,6 +146,7 @@ static void BeginRecording() { lastTextures.clear(); lastRenderTargets.clear(); flipLastAction = gpuStats.numFlips; + flipFinishAt = -1; u32 ptr = (u32)pushbuf.size(); u32 sz = 512 * 4; @@ -454,7 +456,9 @@ static void EmitTransfer(u32 op) { static void EmitClut(u32 op) { u32 addr = gstate.getClutAddress(); - u32 bytes = (op & 0x3F) * 32; + // Actually should only be 0x3F, but we allow enhanced CLUTs. See #15727. + u32 blocks = (op & 0x7F) == 0x40 ? 0x40 : (op & 0x3F); + u32 bytes = blocks * 32; bytes = Memory::ValidSize(addr, bytes); if (bytes != 0) { @@ -492,6 +496,7 @@ bool Activate() { if (!nextFrame) { nextFrame = true; flipLastAction = gpuStats.numFlips; + flipFinishAt = -1; return true; } return false; @@ -510,6 +515,7 @@ static void FinishRecording() { NOTICE_LOG(SYSTEM, "Recording finished"); active = false; flipLastAction = gpuStats.numFlips; + flipFinishAt = -1; if (writeCallback) writeCallback(filename); @@ -671,10 +677,10 @@ void NotifyDisplay(u32 framebuf, int stride, int fmt) { } } -void NotifyFrame() { +void NotifyBeginFrame() { const bool noDisplayAction = flipLastAction + 4 < gpuStats.numFlips; - // We do this only to catch things that don't call NotifyFrame. - if (active && HasDrawCommands() && noDisplayAction) { + // We do this only to catch things that don't call NotifyDisplay. + if (active && HasDrawCommands() && (noDisplayAction || gpuStats.numFlips == flipFinishAt)) { NOTICE_LOG(SYSTEM, "Recording complete on frame"); struct DisplayBufData { @@ -698,6 +704,8 @@ void NotifyFrame() { if (nextFrame && (gstate_c.skipDrawReason & SKIPDRAW_SKIPFRAME) == 0 && noDisplayAction) { NOTICE_LOG(SYSTEM, "Recording starting on frame..."); BeginRecording(); + // If we began on a BeginFrame, end on a BeginFrame. + flipFinishAt = gpuStats.numFlips + 1; } } diff --git a/GPU/Debugger/Record.h b/GPU/Debugger/Record.h index b66a2ea17f..5c5d2f6dbc 100644 --- a/GPU/Debugger/Record.h +++ b/GPU/Debugger/Record.h @@ -36,7 +36,7 @@ void NotifyMemcpy(u32 dest, u32 src, u32 sz); void NotifyMemset(u32 dest, int v, u32 sz); void NotifyUpload(u32 dest, u32 sz); void NotifyDisplay(u32 addr, int stride, int fmt); -void NotifyFrame(); +void NotifyBeginFrame(); void NotifyCPU(); }; diff --git a/GPU/Directx9/DrawEngineDX9.cpp b/GPU/Directx9/DrawEngineDX9.cpp index ffad2bd469..1ab4da1a63 100644 --- a/GPU/Directx9/DrawEngineDX9.cpp +++ b/GPU/Directx9/DrawEngineDX9.cpp @@ -582,18 +582,17 @@ rotateVBO: framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); } int maxIndex = indexGen.MaxIndex(); SoftwareTransform swTransform(params); // Half pixel offset hack. - float xScale = gstate_c.vpWidth < 0 ? -1.0f : 1.0f; float xOffset = -1.0f / gstate_c.curRTRenderWidth; - float yScale = gstate_c.vpHeight > 0 ? -1.0f : 1.0f; float yOffset = 1.0f / gstate_c.curRTRenderHeight; - const Lin::Vec3 trans(gstate_c.vpXOffset * xScale + xOffset, gstate_c.vpYOffset * yScale + yOffset, gstate_c.vpZOffset * 0.5f + 0.5f); + const Lin::Vec3 trans(gstate_c.vpXOffset + xOffset, -gstate_c.vpYOffset + yOffset, gstate_c.vpZOffset * 0.5f + 0.5f); const Lin::Vec3 scale(gstate_c.vpWidthScale, gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); swTransform.SetProjMatrix(gstate.projMatrix, gstate_c.vpWidth < 0, gstate_c.vpHeight > 0, trans, scale); @@ -640,9 +639,6 @@ rotateVBO: if (gstate.isClearModeAlphaMask()) mask |= D3DCLEAR_STENCIL; if (gstate.isClearModeDepthMask()) mask |= D3DCLEAR_ZBUFFER; - if (mask & D3DCLEAR_ZBUFFER) { - framebufferManager_->SetDepthUpdated(); - } if (mask & D3DCLEAR_TARGET) { framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); } diff --git a/GPU/Directx9/FramebufferManagerDX9.cpp b/GPU/Directx9/FramebufferManagerDX9.cpp index 610940584c..8de6f438a9 100644 --- a/GPU/Directx9/FramebufferManagerDX9.cpp +++ b/GPU/Directx9/FramebufferManagerDX9.cpp @@ -140,7 +140,7 @@ } const u32 fb_address = vfb->fb_address & 0x3FFFFFFF; - const int dstBpp = vfb->format == GE_FORMAT_8888 ? 4 : 2; + const int dstBpp = vfb->fb_format == GE_FORMAT_8888 ? 4 : 2; // We always need to convert from the framebuffer native format. // Right now that's always 8888. @@ -163,7 +163,7 @@ // TODO: Handle the other formats? We don't currently create them, I think. const int dstByteOffset = (y * vfb->fb_stride + x) * dstBpp; // Pixel size always 4 here because we always request BGRA8888. - ConvertFromBGRA8888(Memory::GetPointerWrite(fb_address + dstByteOffset), (u8 *)locked.pBits, vfb->fb_stride, locked.Pitch / 4, w, h, vfb->format); + ConvertFromBGRA8888(Memory::GetPointerWrite(fb_address + dstByteOffset), (u8 *)locked.pBits, vfb->fb_stride, locked.Pitch / 4, w, h, vfb->fb_format); offscreen->UnlockRect(); } else { ERROR_LOG_REPORT(G3D, "Unable to lock rect from %08x: %d,%d %dx%d of %dx%d", fb_address, (int)rect.left, (int)rect.top, (int)rect.right, (int)rect.bottom, vfb->renderWidth, vfb->renderHeight); diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index c3f4476fcb..bd37b01aee 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -38,7 +38,6 @@ #include "GPU/GeDisasm.h" #include "GPU/Common/FramebufferManagerCommon.h" -#include "GPU/Debugger/Debugger.h" #include "GPU/Directx9/ShaderManagerDX9.h" #include "GPU/Directx9/GPU_DX9.h" #include "GPU/Directx9/FramebufferManagerDX9.h" @@ -58,7 +57,7 @@ GPU_DX9::GPU_DX9(GraphicsContext *gfxCtx, Draw::DrawContext *draw) shaderManagerDX9_ = new ShaderManagerDX9(draw, device_); framebufferManagerDX9_ = new FramebufferManagerDX9(draw); framebufferManager_ = framebufferManagerDX9_; - textureCacheDX9_ = new TextureCacheDX9(draw); + textureCacheDX9_ = new TextureCacheDX9(draw, framebufferManager_->GetDraw2D()); textureCache_ = textureCacheDX9_; drawEngineCommon_ = &drawEngine_; shaderManager_ = shaderManagerDX9_; @@ -160,6 +159,7 @@ void GPU_DX9::CheckGPUFeatures() { u32 features = 0; features |= GPU_SUPPORTS_16BIT_FORMATS; features |= GPU_SUPPORTS_BLEND_MINMAX; + features |= GPU_SUPPORTS_DEPTH_TEXTURE; features |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; // Accurate depth is required because the Direct3D API does not support inverse Z. @@ -285,11 +285,6 @@ void GPU_DX9::BeginFrame() { framebufferManager_->BeginFrame(); } -void GPU_DX9::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { - GPUDebug::NotifyDisplay(framebuf, stride, format); - framebufferManagerDX9_->SetDisplayFramebuffer(framebuf, stride, format); -} - void GPU_DX9::CopyDisplayToOutput(bool reallyDirty) { dxstate.depthWrite.set(true); dxstate.colorMask.set(0xF); @@ -374,8 +369,8 @@ std::vector GPU_DX9::DebugGetShaderIDs(DebugShaderType type) { switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderIDs(); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderIDs(type); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderIDs(type); default: return shaderManagerDX9_->DebugGetShaderIDs(type); } @@ -385,8 +380,8 @@ std::string GPU_DX9::DebugGetShaderString(std::string id, DebugShaderType type, switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderString(id, stringType); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderString(id, type, stringType); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderString(id, type, stringType); default: return shaderManagerDX9_->DebugGetShaderString(id, type, stringType); } diff --git a/GPU/Directx9/GPU_DX9.h b/GPU/Directx9/GPU_DX9.h index 349d2bd0a8..0e313da397 100644 --- a/GPU/Directx9/GPU_DX9.h +++ b/GPU/Directx9/GPU_DX9.h @@ -23,7 +23,7 @@ #include "GPU/GPUCommon.h" #include "GPU/Directx9/FramebufferManagerDX9.h" #include "GPU/Directx9/DrawEngineDX9.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Common/VertexDecoderCommon.h" class ShaderManagerDX9; @@ -40,7 +40,6 @@ public: void ExecuteOp(u32 op, u32 diff) override; void ReapplyGfxState() override; - void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void GetStats(char *buffer, size_t bufsize) override; void ClearCacheNextFrame() override; void DeviceLost() override; // Only happens on Android. Drop all textures and shaders. diff --git a/GPU/Directx9/StateMappingDX9.cpp b/GPU/Directx9/StateMappingDX9.cpp index 0de9c1774d..9fb92db6fe 100644 --- a/GPU/Directx9/StateMappingDX9.cpp +++ b/GPU/Directx9/StateMappingDX9.cpp @@ -211,21 +211,11 @@ void DrawEngineDX9::ApplyDrawState(int prim) { ConvertStencilFuncState(stencilState); // Set Stencil/Depth - - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Enforce plain depth writing. - dxstate.depthTest.enable(); - dxstate.depthFunc.set(D3DCMP_ALWAYS); - dxstate.depthWrite.set(true); - dxstate.stencilTest.disable(); - } else if (gstate.isModeClear()) { + if (gstate.isModeClear()) { // Depth Test dxstate.depthTest.enable(); dxstate.depthFunc.set(D3DCMP_ALWAYS); dxstate.depthWrite.set(gstate.isClearModeDepthMask()); - if (gstate.isClearModeDepthMask()) { - framebufferManager_->SetDepthUpdated(); - } // Stencil Test bool alphaMask = gstate.isClearModeAlphaMask(); @@ -246,9 +236,6 @@ void DrawEngineDX9::ApplyDrawState(int prim) { dxstate.depthTest.enable(); dxstate.depthFunc.set(ztests[gstate.getDepthTestFunction()]); dxstate.depthWrite.set(gstate.isDepthWriteEnabled()); - if (gstate.isDepthWriteEnabled()) { - framebufferManager_->SetDepthUpdated(); - } } else { dxstate.depthTest.disable(); } @@ -273,6 +260,7 @@ void DrawEngineDX9::ApplyDrawState(int prim) { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); dxstate.scissorTest.enable(); dxstate.scissorRect.set(vpAndScissor.scissorX, vpAndScissor.scissorY, vpAndScissor.scissorX + vpAndScissor.scissorW, vpAndScissor.scissorY + vpAndScissor.scissorH); @@ -281,12 +269,6 @@ void DrawEngineDX9::ApplyDrawState(int prim) { float depthMax = vpAndScissor.depthRangeMax; dxstate.viewport.set(vpAndScissor.viewportX, vpAndScissor.viewportY, vpAndScissor.viewportW, vpAndScissor.viewportH, depthMin, depthMax); - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } } gstate_c.Clean(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_RASTER_STATE | DIRTY_BLEND_STATE); diff --git a/GPU/Directx9/TextureCacheDX9.cpp b/GPU/Directx9/TextureCacheDX9.cpp index 1394183f1b..a300ad6b82 100644 --- a/GPU/Directx9/TextureCacheDX9.cpp +++ b/GPU/Directx9/TextureCacheDX9.cpp @@ -28,7 +28,7 @@ #include "GPU/Directx9/FramebufferManagerDX9.h" #include "GPU/Directx9/ShaderManagerDX9.h" #include "Common/GPU/D3D9/D3D9StateCache.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Common/FramebufferManagerCommon.h" #include "GPU/Common/TextureDecoder.h" #include "Core/Config.h" @@ -59,8 +59,8 @@ static const D3DVERTEXELEMENT9 g_FramebufferVertexElements[] = { D3DDECL_END() }; -TextureCacheDX9::TextureCacheDX9(Draw::DrawContext *draw) - : TextureCacheCommon(draw) { +TextureCacheDX9::TextureCacheDX9(Draw::DrawContext *draw, Draw2D *draw2D) + : TextureCacheCommon(draw, draw2D) { lastBoundTexture = INVALID_TEX; isBgraBackend_ = true; @@ -204,6 +204,10 @@ void TextureCacheDX9::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBase } void TextureCacheDX9::BindTexture(TexCacheEntry *entry) { + if (!entry) { + device_->SetTexture(0, nullptr); + return; + } LPDIRECT3DBASETEXTURE9 texture = DxTex(entry); if (texture != lastBoundTexture) { device_->SetTexture(0, texture); @@ -215,7 +219,7 @@ void TextureCacheDX9::BindTexture(TexCacheEntry *entry) { } void TextureCacheDX9::Unbind() { - device_->SetTexture(0, NULL); + device_->SetTexture(0, nullptr); InvalidateLastTexture(); } diff --git a/GPU/Directx9/TextureCacheDX9.h b/GPU/Directx9/TextureCacheDX9.h index 47005cbd5c..8773b18273 100644 --- a/GPU/Directx9/TextureCacheDX9.h +++ b/GPU/Directx9/TextureCacheDX9.h @@ -24,14 +24,14 @@ #include "GPU/Common/TextureCacheCommon.h" struct VirtualFramebuffer; -class DepalShaderCache; +class TextureShaderCache; class FramebufferManagerDX9; class ShaderManagerDX9; class TextureCacheDX9 : public TextureCacheCommon { public: - TextureCacheDX9(Draw::DrawContext *draw); + TextureCacheDX9(Draw::DrawContext *draw, Draw2D *draw2D); ~TextureCacheDX9(); void StartFrame() override; diff --git a/GPU/GLES/DrawEngineGLES.cpp b/GPU/GLES/DrawEngineGLES.cpp index ab0960abd5..96dc11ea22 100644 --- a/GPU/GLES/DrawEngineGLES.cpp +++ b/GPU/GLES/DrawEngineGLES.cpp @@ -364,6 +364,7 @@ void DrawEngineGLES::DoFlush() { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); } int maxIndex = indexGen.MaxIndex(); @@ -423,9 +424,6 @@ void DrawEngineGLES::DoFlush() { bool colorMask = gstate.isClearModeColorMask(); bool alphaMask = gstate.isClearModeAlphaMask(); bool depthMask = gstate.isClearModeDepthMask(); - if (depthMask) { - framebufferManager_->SetDepthUpdated(); - } GLbitfield target = 0; // Without this, we will clear RGB when clearing stencil, which breaks games. diff --git a/GPU/GLES/GPU_GLES.cpp b/GPU/GLES/GPU_GLES.cpp index f774e4bebd..ad83bd3637 100644 --- a/GPU/GLES/GPU_GLES.cpp +++ b/GPU/GLES/GPU_GLES.cpp @@ -36,7 +36,6 @@ #include "GPU/ge_constants.h" #include "GPU/GeDisasm.h" #include "GPU/Common/FramebufferManagerCommon.h" -#include "GPU/Debugger/Debugger.h" #include "GPU/GLES/ShaderManagerGLES.h" #include "GPU/GLES/GPU_GLES.h" #include "GPU/GLES/FramebufferManagerGLES.h" @@ -60,7 +59,7 @@ GPU_GLES::GPU_GLES(GraphicsContext *gfxCtx, Draw::DrawContext *draw) shaderManagerGL_ = new ShaderManagerGLES(draw); framebufferManagerGL_ = new FramebufferManagerGLES(draw); framebufferManager_ = framebufferManagerGL_; - textureCacheGL_ = new TextureCacheGLES(draw); + textureCacheGL_ = new TextureCacheGLES(draw, framebufferManager_->GetDraw2D()); textureCache_ = textureCacheGL_; drawEngineCommon_ = &drawEngine_; shaderManager_ = shaderManagerGL_; @@ -360,11 +359,6 @@ void GPU_GLES::BeginFrame() { framebufferManagerGL_->BeginFrame(); } -void GPU_GLES::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { - GPUDebug::NotifyDisplay(framebuf, stride, format); - framebufferManagerGL_->SetDisplayFramebuffer(framebuf, stride, format); -} - void GPU_GLES::CopyDisplayToOutput(bool reallyDirty) { // Flush anything left over. framebufferManagerGL_->RebindFramebuffer("RebindFramebuffer - CopyDisplayToOutput"); @@ -453,8 +447,8 @@ std::vector GPU_GLES::DebugGetShaderIDs(DebugShaderType type) { switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderIDs(); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderIDs(type); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderIDs(type); default: return shaderManagerGL_->DebugGetShaderIDs(type); } @@ -464,8 +458,8 @@ std::string GPU_GLES::DebugGetShaderString(std::string id, DebugShaderType type, switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderString(id, stringType); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderString(id, type, stringType); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderString(id, type, stringType); default: return shaderManagerGL_->DebugGetShaderString(id, type, stringType); } diff --git a/GPU/GLES/GPU_GLES.h b/GPU/GLES/GPU_GLES.h index a6e521763a..cbe6bc00b0 100644 --- a/GPU/GLES/GPU_GLES.h +++ b/GPU/GLES/GPU_GLES.h @@ -23,7 +23,7 @@ #include "Common/File/Path.h" #include "GPU/GPUCommon.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/GLES/FramebufferManagerGLES.h" #include "GPU/GLES/DrawEngineGLES.h" #include "GPU/GLES/FragmentTestCacheGLES.h" @@ -47,7 +47,6 @@ public: void ExecuteOp(u32 op, u32 diff) override; void ReapplyGfxState() override; - void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void GetStats(char *buffer, size_t bufsize) override; void ClearCacheNextFrame() override; diff --git a/GPU/GLES/StateMappingGLES.cpp b/GPU/GLES/StateMappingGLES.cpp index 54c94ccbd3..4ebdd165d2 100644 --- a/GPU/GLES/StateMappingGLES.cpp +++ b/GPU/GLES/StateMappingGLES.cpp @@ -251,24 +251,14 @@ void DrawEngineGLES::ApplyDrawState(int prim) { GenericStencilFuncState stencilState; ConvertStencilFuncState(stencilState); - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Enforce plain depth writing. - renderManager->SetStencilDisabled(); - renderManager->SetDepth(true, true, GL_ALWAYS); - } else if (gstate.isModeClear()) { + if (gstate.isModeClear()) { // Depth Test - if (gstate.isClearModeDepthMask()) { - framebufferManager_->SetDepthUpdated(); - } renderManager->SetStencilFunc(gstate.isClearModeAlphaMask(), GL_ALWAYS, 0xFF, 0xFF); renderManager->SetStencilOp(stencilState.writeMask, GL_REPLACE, GL_REPLACE, GL_REPLACE); renderManager->SetDepth(true, gstate.isClearModeDepthMask() ? true : false, GL_ALWAYS); } else { // Depth Test renderManager->SetDepth(gstate.isDepthTestEnabled(), gstate.isDepthWriteEnabled(), compareOps[gstate.getDepthTestFunction()]); - if (gstate.isDepthTestEnabled() && gstate.isDepthWriteEnabled()) { - framebufferManager_->SetDepthUpdated(); - } // Stencil Test if (stencilState.enabled) { @@ -286,19 +276,13 @@ void DrawEngineGLES::ApplyDrawState(int prim) { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); renderManager->SetScissor(GLRect2D{ vpAndScissor.scissorX, vpAndScissor.scissorY, vpAndScissor.scissorW, vpAndScissor.scissorH }); renderManager->SetViewport({ vpAndScissor.viewportX, vpAndScissor.viewportY, vpAndScissor.viewportW, vpAndScissor.viewportH, vpAndScissor.depthRangeMin, vpAndScissor.depthRangeMax }); - - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } } } diff --git a/GPU/GLES/TextureCacheGLES.cpp b/GPU/GLES/TextureCacheGLES.cpp index beb89c6b43..97e51dcd6c 100644 --- a/GPU/GLES/TextureCacheGLES.cpp +++ b/GPU/GLES/TextureCacheGLES.cpp @@ -36,7 +36,7 @@ #include "GPU/GLES/TextureCacheGLES.h" #include "GPU/GLES/FramebufferManagerGLES.h" #include "GPU/Common/FragmentShaderGenerator.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/GLES/ShaderManagerGLES.h" #include "GPU/GLES/DrawEngineGLES.h" #include "GPU/Common/TextureDecoder.h" @@ -45,8 +45,8 @@ #include #endif -TextureCacheGLES::TextureCacheGLES(Draw::DrawContext *draw) - : TextureCacheCommon(draw) { +TextureCacheGLES::TextureCacheGLES(Draw::DrawContext *draw, Draw2D *draw2D) + : TextureCacheCommon(draw, draw2D) { render_ = (GLRenderManager *)draw_->GetNativeObject(Draw::NativeObject::RENDER_MANAGER); nextTexture_ = nullptr; @@ -225,7 +225,7 @@ void TextureCacheGLES::BindTexture(TexCacheEntry *entry) { int maxLevel = (entry->status & TexCacheEntry::STATUS_NO_MIPS) ? 0 : entry->maxLevel; SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry); ApplySamplingParams(samplerKey); - gstate_c.SetUseShaderDepal(false); + gstate_c.SetUseShaderDepal(false, false); } void TextureCacheGLES::Unbind() { @@ -382,19 +382,8 @@ Draw::DataFormat TextureCacheGLES::GetDestFormat(GETextureFormat format, GEPalet } bool TextureCacheGLES::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level) { - GPUgstate saved; - if (level != 0) { - saved = gstate; - - // The way we set textures is a bit complex. Let's just override level 0. - gstate.texsize[0] = gstate.texsize[level]; - gstate.texaddr[0] = gstate.texaddr[level]; - gstate.texbufwidth[0] = gstate.texbufwidth[level]; - } - InvalidateLastTexture(); SetTexture(); - if (!nextTexture_) { if (nextFramebufferTexture_) { VirtualFramebuffer *vfb = nextFramebufferTexture_; @@ -427,10 +416,6 @@ bool TextureCacheGLES::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level) int w = gstate.getTextureWidth(level); int h = gstate.getTextureHeight(level); - if (level != 0) { - gstate = saved; - } - bool result = entry->textureName != nullptr; if (result) { buffer.Allocate(w, h, GE_FORMAT_8888, false); @@ -445,7 +430,7 @@ bool TextureCacheGLES::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level) } void TextureCacheGLES::DeviceLost() { - depalShaderCache_->DeviceLost(); + textureShaderCache_->DeviceLost(); Clear(false); draw_ = nullptr; render_ = nullptr; @@ -454,5 +439,5 @@ void TextureCacheGLES::DeviceLost() { void TextureCacheGLES::DeviceRestore(Draw::DrawContext *draw) { draw_ = draw; render_ = (GLRenderManager *)draw_->GetNativeObject(Draw::NativeObject::RENDER_MANAGER); - depalShaderCache_->DeviceRestore(draw); + textureShaderCache_->DeviceRestore(draw); } diff --git a/GPU/GLES/TextureCacheGLES.h b/GPU/GLES/TextureCacheGLES.h index ac5313c3cb..a0f2ed5840 100644 --- a/GPU/GLES/TextureCacheGLES.h +++ b/GPU/GLES/TextureCacheGLES.h @@ -27,22 +27,22 @@ struct VirtualFramebuffer; class FramebufferManagerGLES; -class DepalShaderCache; +class TextureShaderCache; class ShaderManagerGLES; class DrawEngineGLES; class GLRTexture; class TextureCacheGLES : public TextureCacheCommon { public: - TextureCacheGLES(Draw::DrawContext *draw); + TextureCacheGLES(Draw::DrawContext *draw, Draw2D *draw2D); ~TextureCacheGLES(); void Clear(bool delete_them) override; void StartFrame() override; void SetFramebufferManager(FramebufferManagerGLES *fbManager); - void SetDepalShaderCache(DepalShaderCache *dpCache) { - depalShaderCache_ = dpCache; + void SetDepalShaderCache(TextureShaderCache *dpCache) { + textureShaderCache_ = dpCache; } void SetDrawEngine(DrawEngineGLES *td) { drawEngine_ = td; diff --git a/GPU/GPU.h b/GPU/GPU.h index ecb9ae33c4..0d7fd03430 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -24,11 +24,6 @@ class GPUInterface; class GPUDebugInterface; class GraphicsContext; -enum RasterMode { - RASTER_MODE_NORMAL = 0, - RASTER_MODE_COLOR_TO_DEPTH = 1, -}; - // PSP rasterization has two outputs, color and depth. Stencil is packed // into the alpha channel of color (if exists), so possibly RASTER_COLOR // should be named RASTER_COLOR_STENCIL but it gets kinda hard to read. @@ -89,6 +84,8 @@ struct GPUStatistics { numUploads = 0; numClears = 0; numDepthCopies = 0; + numReinterpretCopies = 0; + numColorCopies = 0; msProcessingDisplayLists = 0; vertexGPUCycles = 0; otherGPUCycles = 0; @@ -115,6 +112,8 @@ struct GPUStatistics { int numUploads; int numClears; int numDepthCopies; + int numReinterpretCopies; + int numColorCopies; double msProcessingDisplayLists; int vertexGPUCycles; int otherGPUCycles; diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 86d21d3690..1f37652321 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -338,7 +338,7 @@ - + @@ -452,7 +452,7 @@ - + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index cb2832c032..d581cb4bad 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -255,7 +255,7 @@ Common - + Common @@ -503,7 +503,7 @@ Common - + Common diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index a0deb403aa..ffbe076d12 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -1109,7 +1109,8 @@ void GPUCommon::BeginFrame() { } else if (dumpThisFrame_) { dumpThisFrame_ = false; } - GPURecord::NotifyFrame(); + GPUDebug::NotifyBeginFrame(); + GPURecord::NotifyBeginFrame(); } void GPUCommon::SlowRunLoop(DisplayList &list) @@ -1624,6 +1625,21 @@ void GPUCommon::Execute_VertexTypeSkinning(u32 op, u32 diff) { gstate_c.Dirty(DIRTY_RASTER_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_CULLRANGE); } +void GPUCommon::CheckDepthUsage(VirtualFramebuffer *vfb) { + if (!gstate_c.usingDepth) { + bool isClearingDepth = gstate.isModeClear() && gstate.isClearModeDepthMask(); + + if ((gstate.isDepthTestEnabled() || isClearingDepth)) { + gstate_c.usingDepth = true; + gstate_c.clearingDepth = isClearingDepth; + vfb->last_frame_depth_render = gpuStats.numFlips; + if (isClearingDepth || gstate.isDepthWriteEnabled()) { + vfb->last_frame_depth_updated = gpuStats.numFlips; + } + framebufferManager_->SetDepthFrameBuffer(isClearingDepth); + } + } +} void GPUCommon::Execute_Prim(u32 op, u32 diff) { // This drives all drawing. All other state we just buffer up, then we apply it only @@ -1685,6 +1701,8 @@ void GPUCommon::Execute_Prim(u32 op, u32 diff) { return; } + CheckDepthUsage(vfb); + const void *verts = Memory::GetPointerUnchecked(gstate_c.vertexAddr); const void *inds = nullptr; u32 vertexType = gstate.vertType; @@ -1883,12 +1901,14 @@ void GPUCommon::Execute_Bezier(u32 op, u32 diff) { gstate_c.framebufFormat = gstate.FrameBufFormat(); // This also make skipping drawing very effective. - framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); + VirtualFramebuffer *vfb = framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // TODO: Should this eat some cycles? Probably yes. Not sure if important. return; } + CheckDepthUsage(vfb); + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); return; @@ -1953,12 +1973,14 @@ void GPUCommon::Execute_Spline(u32 op, u32 diff) { gstate_c.framebufFormat = gstate.FrameBufFormat(); // This also make skipping drawing very effective. - framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); + VirtualFramebuffer *vfb = framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // TODO: Should this eat some cycles? Probably yes. Not sure if important. return; } + CheckDepthUsage(vfb); + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); return; @@ -2686,7 +2708,8 @@ void GPUCommon::ResetListState(int listID, DisplayListState state) { GPUDebugOp GPUCommon::DissassembleOp(u32 pc, u32 op) { char buffer[1024]; - GeDisassembleOp(pc, op, Memory::Read_U32(pc - 4), buffer, sizeof(buffer)); + u32 prev = Memory::IsValidAddress(pc - 4) ? Memory::ReadUnchecked_U32(pc - 4) : 0; + GeDisassembleOp(pc, op, prev, buffer, sizeof(buffer)); GPUDebugOp info; info.pc = pc; @@ -2744,6 +2767,10 @@ void GPUCommon::SetCmdValue(u32 op) { downcount = 0; } +void GPUCommon::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { + framebufferManager_->SetDisplayFramebuffer(framebuf, stride, format); +} + void GPUCommon::DoBlockTransfer(u32 skipDrawReason) { // TODO: This is used a lot to copy data around between render targets and textures, // and also to quickly load textures from RAM to VRAM. So we should do checks like the following: @@ -3041,7 +3068,8 @@ size_t GPUCommon::FormatGPUStatsCommon(char *buffer, size_t size) { "Vertices: %d cached: %d uncached: %d\n" "FBOs active: %d (evaluations: %d)\n" "Textures: %d, dec: %d, invalidated: %d, hashed: %d kB\n" - "Readbacks: %d, uploads: %d, depth copies: %d\n" + "Readbacks: %d, uploads: %d\n" + "Copies: depth %d, color %d, reinterpret: %d\n" "GPU cycles executed: %d (%f per vertex)\n", gpuStats.msProcessingDisplayLists * 1000.0f, gpuStats.numDrawCalls, @@ -3062,6 +3090,8 @@ size_t GPUCommon::FormatGPUStatsCommon(char *buffer, size_t size) { gpuStats.numReadbacks, gpuStats.numUploads, gpuStats.numDepthCopies, + gpuStats.numColorCopies, + gpuStats.numReinterpretCopies, gpuStats.vertexGPUCycles + gpuStats.otherGPUCycles, vertexAverageCycles ); diff --git a/GPU/GPUCommon.h b/GPU/GPUCommon.h index 59298d8e92..f389b788e2 100644 --- a/GPU/GPUCommon.h +++ b/GPU/GPUCommon.h @@ -15,6 +15,8 @@ class FramebufferManagerCommon; class TextureCacheCommon; class DrawEngineCommon; class GraphicsContext; +struct VirtualFramebuffer; + namespace Draw { class DrawContext; } @@ -115,6 +117,7 @@ public: u32 Break(int mode) override; void ReapplyGfxState() override; + void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void CopyDisplayToOutput(bool reallyDirty) override = 0; void InitClear() override = 0; bool PerformMemoryCopy(u32 dest, u32 src, int size) override; @@ -282,17 +285,11 @@ protected: void SlowRunLoop(DisplayList &list); void UpdatePC(u32 currentPC, u32 newPC); void UpdateState(GPURunState state); - void PopDLQueue(); - void CheckDrawSync(); - int GetNextListIndex(); - virtual void FastLoadBoneMatrix(u32 target); + void FastLoadBoneMatrix(u32 target); // TODO: Unify this. virtual void FinishDeferred() {} - void DoBlockTransfer(u32 skipDrawReason); - void DoExecuteCall(u32 target); - void AdvanceVerts(u32 vertType, int count, int bytesRead) { if ((vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { int indexShift = ((vertType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT) - 1; @@ -362,6 +359,13 @@ protected: private: void FlushImm(); + void CheckDepthUsage(VirtualFramebuffer *vfb); + void DoBlockTransfer(u32 skipDrawReason); + void DoExecuteCall(u32 target); + void PopDLQueue(); + void CheckDrawSync(); + int GetNextListIndex(); + // Debug stats. double timeSteppingStarted_; double timeSpentStepping_; diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 8d6d04039b..f75a09fdad 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -300,8 +300,14 @@ struct GPUgstate { bool isTextureFormatIndexed() const { return (texformat & 4) != 0; } // GE_TFMT_CLUT4 - GE_TFMT_CLUT32 are 0b1xx. int getTextureEnvColRGB() const { return texenvcolor & 0x00FFFFFF; } u32 getClutAddress() const { return (clutaddr & 0x00FFFFF0) | ((clutaddrupper << 8) & 0x0F000000); } - int getClutLoadBytes() const { return (loadclut & 0x7F) * 32; } - int getClutLoadBlocks() const { return (loadclut & 0x7F); } + int getClutLoadBytes() const { return getClutLoadBlocks() * 32; } + int getClutLoadBlocks() const { + // The PSP only supports 0x3F, but Misshitsu no Sacrifice has extra color data (see #15727.) + // 0x40 would be 0, which would be a no-op, so we allow it. + if ((loadclut & 0x7F) == 0x40) + return 0x40; + return loadclut & 0x3F; + } GEPaletteFormat getClutPaletteFormat() const { return static_cast(clutformat & 3); } int getClutIndexShift() const { return (clutformat >> 2) & 0x1F; } int getClutIndexMask() const { return (clutformat >> 8) & 0xFF; } @@ -523,9 +529,10 @@ struct GPUStateCache { bool IsDirty(u64 what) const { return (dirty & what) != 0ULL; } - void SetUseShaderDepal(bool depal) { + void SetUseShaderDepal(bool depal, bool smoothed) { if (depal != useShaderDepal) { useShaderDepal = depal; + useSmoothedShaderDepal = smoothed; Dirty(DIRTY_FRAGMENTSHADER_STATE); } } @@ -555,14 +562,6 @@ struct GPUStateCache { Dirty(DIRTY_FRAGMENTSHADER_STATE | (is3D ? DIRTY_MIPBIAS : 0)); } } - void SetFramebufferRenderMode(RasterMode mode) { - if (mode != renderMode) { - // This mode modifies the fragment shader to write depth, the depth state to write without testing, and the blend state to write nothing to color. - // So we need to re-evaluate those states. - Dirty(DIRTY_FRAGMENTSHADER_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_TEXTURE_PARAMS); - renderMode = mode; - } - } u32 featureFlags; @@ -572,6 +571,9 @@ struct GPUStateCache { uint64_t dirty; + bool usingDepth; // For deferred depth copies. + bool clearingDepth; + bool textureFullAlpha; bool vertexFullAlpha; @@ -613,9 +615,6 @@ struct GPUStateCache { // We detect this case and go into a special drawing mode. bool blueToAlpha; - // Some games try to write to the Z buffer using color. Catch that and actually do the writes to the Z buffer instead. - RasterMode renderMode; - // TODO: These should be accessed from the current VFB object directly. u32 curRTWidth; u32 curRTHeight; @@ -637,6 +636,7 @@ struct GPUStateCache { int spline_num_points_u; bool useShaderDepal; + bool useSmoothedShaderDepal; GEBufferFormat depalFramebufferFormat; u32 getRelativeAddress(u32 data) const; diff --git a/GPU/GeConstants.cpp b/GPU/GeConstants.cpp index ab627ee473..b093d96d56 100644 --- a/GPU/GeConstants.cpp +++ b/GPU/GeConstants.cpp @@ -6,6 +6,7 @@ const char *GeBufferFormatToString(GEBufferFormat fmt) { case GE_FORMAT_5551: return "5551"; case GE_FORMAT_565: return "565"; case GE_FORMAT_8888: return "8888"; + case GE_FORMAT_DEPTH16: return "DEPTH16"; default: return "N/A"; } } diff --git a/GPU/Software/BinManager.cpp b/GPU/Software/BinManager.cpp index 4005e42945..7f8f1ad453 100644 --- a/GPU/Software/BinManager.cpp +++ b/GPU/Software/BinManager.cpp @@ -210,6 +210,9 @@ void BinManager::UpdateState() { } if (HasDirty(SoftDirty::BINNER_OVERLAP)) { + // This is a good place to record any dependencies for block transfer overlap. + MarkPendingReads(state); + // Disallow threads when rendering to the target, even offset. bool selfRender = HasTextureWrite(state); int newMaxTasks = selfRender ? 1 : g_threadManager.GetNumLooperThreads(); @@ -251,6 +254,34 @@ bool BinManager::HasTextureWrite(const RasterizerState &state) { return false; } +void BinManager::MarkPendingReads(const Rasterizer::RasterizerState &state) { + if (!state.enableTextures) + return; + + const uint8_t textureBits = textureBitsPerPixel[state.samplerID.texfmt]; + for (int i = 0; i <= state.maxTexLevel; ++i) { + uint32_t byteStride = (state.texbufw[i] * textureBits) / 8; + uint32_t byteWidth = (state.samplerID.cached.sizes[i].w * textureBits) / 8; + uint32_t h = state.samplerID.cached.sizes[i].h; + auto it = pendingReads_.find(state.texaddr[i]); + if (it != pendingReads_.end()) { + uint32_t total = byteStride * (h - 1) + byteWidth; + uint32_t existing = it->second.strideBytes * (it->second.height - 1) + it->second.widthBytes; + if (existing < total) { + it->second.strideBytes = std::max(it->second.strideBytes, byteStride); + it->second.widthBytes = std::max(it->second.widthBytes, byteWidth); + it->second.height = std::max(it->second.height, h); + } + } else { + auto &range = pendingReads_[state.texaddr[i]]; + range.base = state.texaddr[i]; + range.strideBytes = byteStride; + range.widthBytes = byteWidth; + range.height = h; + } + } +} + inline void BinDirtyRange::Expand(uint32_t newBase, uint32_t bpp, uint32_t stride, DrawingCoords &tl, DrawingCoords &br) { const uint32_t w = br.x - tl.x + 1; const uint32_t h = br.y - tl.y + 1; @@ -465,9 +496,10 @@ void BinManager::Flush(const char *reason) { for (auto &pending : pendingWrites_) pending.base = 0; pendingOverlap_ = false; + pendingReads_.clear(); - // We'll need to set the pending writes again, since we just flushed it. - dirty_ |= SoftDirty::BINNER_RANGE; + // We'll need to set the pending writes and reads again, since we just flushed it. + dirty_ |= SoftDirty::BINNER_RANGE | SoftDirty::BINNER_OVERLAP; if (coreCollectDebugStats) { double et = time_now_d(); @@ -486,7 +518,7 @@ bool BinManager::HasPendingWrite(uint32_t start, uint32_t stride, uint32_t w, ui // Ignore mirrors for overlap detection. start &= 0x0FFFFFFF & ~0x00600000; - uint32_t size = stride * h; + uint32_t size = stride * (h - 1) + w; for (const auto &range : pendingWrites_) { if (range.base == 0 || range.strideBytes == 0) continue; @@ -512,6 +544,28 @@ bool BinManager::HasPendingWrite(uint32_t start, uint32_t stride, uint32_t w, ui return false; } +bool BinManager::HasPendingRead(uint32_t start, uint32_t stride, uint32_t w, uint32_t h) { + if (Memory::IsVRAMAddress(start)) { + // Ignore VRAM mirrors. + start &= 0x0FFFFFFF & ~0x00600000; + } else { + // Ignore only regular RAM mirrors. + start &= 0x3FFFFFFF; + } + + uint32_t size = stride * (h - 1) + w; + for (const auto &pair : pendingReads_) { + const auto &range = pair.second; + if (start >= range.base + range.height * range.strideBytes || start + size <= range.base) + continue; + + // Stride gaps are uncommon with reads, so don't bother. + return true; + } + + return false; +} + void BinManager::GetStats(char *buffer, size_t bufsize) { double allTotal = 0.0; double slowestTotalTime = 0.0; diff --git a/GPU/Software/BinManager.h b/GPU/Software/BinManager.h index 44ae81e2b2..01b6837d20 100644 --- a/GPU/Software/BinManager.h +++ b/GPU/Software/BinManager.h @@ -198,6 +198,8 @@ public: void Drain(); void Flush(const char *reason); bool HasPendingWrite(uint32_t start, uint32_t stride, uint32_t w, uint32_t h); + // Assumes you've also checked for a write (writes are partial so are automatically reads.) + bool HasPendingRead(uint32_t start, uint32_t stride, uint32_t w, uint32_t h); void GetStats(char *buffer, size_t bufsize); void ResetStats(); @@ -252,6 +254,8 @@ private: BinWaitable *waitable_ = nullptr; BinDirtyRange pendingWrites_[2]{}; + std::unordered_map pendingReads_; + bool pendingOverlap_ = false; std::unordered_map flushReasonTimes_; @@ -262,6 +266,7 @@ private: int enqueues_ = 0; int mostThreads_ = 0; + void MarkPendingReads(const Rasterizer::RasterizerState &state); bool HasTextureWrite(const Rasterizer::RasterizerState &state); BinCoords Scissor(BinCoords range); BinCoords Range(const VertexData &v0, const VertexData &v1, const VertexData &v2); diff --git a/GPU/Software/Rasterizer.cpp b/GPU/Software/Rasterizer.cpp index 36cd871ecb..48e51cd9b2 100644 --- a/GPU/Software/Rasterizer.cpp +++ b/GPU/Software/Rasterizer.cpp @@ -1408,7 +1408,7 @@ bool GetCurrentTexture(GPUDebugBuffer &buffer, int level) SamplerID id; ComputeSamplerID(&id); - id.cached.clut = (const u8 *)clut; + id.cached.clut = clut; Sampler::FetchFunc sampler = Sampler::GetFetchFunc(id); diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index 8015a9db05..dd4b71b166 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -52,7 +52,7 @@ const int FB_WIDTH = 480; const int FB_HEIGHT = 272; -u32 clut[4096]; +uint8_t clut[1024]; FormatBuffer fb; FormatBuffer depthbuf; @@ -201,14 +201,14 @@ const SoftwareCommandTableEntry softgpuCommandTable[] = { { GE_CMD_CLUTFORMAT, 0, SoftDirty::SAMPLER_BASIC }, // Morph weights. TODO: Remove precomputation? - { GE_CMD_MORPHWEIGHT0, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT1, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT2, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT3, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT4, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT5, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT6, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT7, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT0, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT1, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT2, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT3, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT4, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT5, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT6, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT7, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, // No state of flushing required for patch parameters, currently. { GE_CMD_PATCHDIVISION }, @@ -787,8 +787,8 @@ void SoftGPU::Execute_BlockTransferStart(u32 op, u32 diff) { const uint32_t dstSize = height * dstStride * bpp; // Need to flush both source and target, so we overwrite properly. - drawEngine_->transformUnit.FlushIfOverlap("blockxfer", src, srcStride, width * bpp, height); - drawEngine_->transformUnit.FlushIfOverlap("blockxfer", dst, dstStride, width * bpp, height); + drawEngine_->transformUnit.FlushIfOverlap("blockxfer", false, src, srcStride, width * bpp, height); + drawEngine_->transformUnit.FlushIfOverlap("blockxfer", true, dst, dstStride, width * bpp, height); DEBUG_LOG(G3D, "Block transfer: %08x/%x -> %08x/%x, %ix%ix%i (%i,%i)->(%i,%i)", srcBasePtr, srcStride, dstBasePtr, dstStride, width, height, bpp, srcX, srcY, dstX, dstY); @@ -971,10 +971,13 @@ void SoftGPU::Execute_Spline(u32 op, u32 diff) { void SoftGPU::Execute_LoadClut(u32 op, u32 diff) { u32 clutAddr = gstate.getClutAddress(); - u32 clutTotalBytes = gstate.getClutLoadBytes(); + // Avoid the hack in getClutLoadBytes() to inaccurately allow more palette data. + u32 clutTotalBytes = (gstate.getClutLoadBlocks() & 0x3F) * 32; + if (clutTotalBytes > 1024) + clutTotalBytes = 1024; // Might be copying drawing into the CLUT, so flush. - drawEngine_->transformUnit.FlushIfOverlap("loadclut", clutAddr, clutTotalBytes, clutTotalBytes, 1); + drawEngine_->transformUnit.FlushIfOverlap("loadclut", false, clutAddr, clutTotalBytes, clutTotalBytes, 1); bool changed = false; if (Memory::IsValidAddress(clutAddr)) { diff --git a/GPU/Software/SoftGpu.h b/GPU/Software/SoftGpu.h index 712ec6bbdd..11d5dd16f3 100644 --- a/GPU/Software/SoftGpu.h +++ b/GPU/Software/SoftGpu.h @@ -216,7 +216,7 @@ private: }; // TODO: These shouldn't be global. -extern u32 clut[4096]; +extern uint8_t clut[1024]; extern FormatBuffer fb; extern FormatBuffer depthbuf; diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index b765df8404..db50f48bb6 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -797,9 +797,11 @@ void TransformUnit::GetStats(char *buffer, size_t bufsize) { binner_->GetStats(buffer, bufsize); } -void TransformUnit::FlushIfOverlap(const char *reason, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h) { +void TransformUnit::FlushIfOverlap(const char *reason, bool modifying, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h) { if (binner_->HasPendingWrite(addr, stride, w, h)) Flush(reason); + if (modifying && binner_->HasPendingRead(addr, stride, w, h)) + Flush(reason); } void TransformUnit::NotifyClutUpdate(const void *src) { diff --git a/GPU/Software/TransformUnit.h b/GPU/Software/TransformUnit.h index 9f17ed1197..54f9fb5f5e 100644 --- a/GPU/Software/TransformUnit.h +++ b/GPU/Software/TransformUnit.h @@ -123,7 +123,7 @@ public: bool GetCurrentSimpleVertices(int count, std::vector &vertices, std::vector &indices); void Flush(const char *reason); - void FlushIfOverlap(const char *reason, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h); + void FlushIfOverlap(const char *reason, bool modifying, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h); void NotifyClutUpdate(const void *src); void GetStats(char *buffer, size_t bufsize); diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 7be943ed63..27d1fda33f 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -185,8 +185,8 @@ void DrawEngineVulkan::InitDeviceObjects() { samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; samp.flags = 0; - samp.magFilter = VK_FILTER_NEAREST; - samp.minFilter = VK_FILTER_NEAREST; + samp.magFilter = VK_FILTER_LINEAR; + samp.minFilter = VK_FILTER_LINEAR; res = vkCreateSampler(device, &samp, nullptr, &samplerSecondary_); _dbg_assert_(VK_SUCCESS == res); res = vkCreateSampler(device, &samp, nullptr, &nullSampler_); @@ -856,6 +856,7 @@ void DrawEngineVulkan::DoFlush() { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index 48b8369fd7..e4a75f2a35 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -218,7 +218,7 @@ private: // Secondary texture for shader blending VkImageView boundSecondary_ = VK_NULL_HANDLE; VkImageView boundDepal_ = VK_NULL_HANDLE; - VkSampler samplerSecondary_ = VK_NULL_HANDLE; // This one is actually never used since we use fetch. + VkSampler samplerSecondary_ = VK_NULL_HANDLE; // This one is actually never used since we use fetch (except in SmoothedDepal mode for Test Drive). PrehashMap vai_; VulkanPushBuffer *vertexCache_; diff --git a/GPU/Vulkan/FramebufferManagerVulkan.cpp b/GPU/Vulkan/FramebufferManagerVulkan.cpp index 7748f24371..7061f68ae7 100644 --- a/GPU/Vulkan/FramebufferManagerVulkan.cpp +++ b/GPU/Vulkan/FramebufferManagerVulkan.cpp @@ -75,7 +75,4 @@ void FramebufferManagerVulkan::NotifyClear(bool clearColor, bool clearAlpha, boo if (clearColor || clearAlpha) { SetColorUpdated(gstate_c.skipDrawReason); } - if (clearDepth) { - SetDepthUpdated(); - } } diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 7d2dc8b5c0..b5ee507bc1 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -37,7 +37,6 @@ #include "GPU/ge_constants.h" #include "GPU/GeDisasm.h" #include "GPU/Common/FramebufferManagerCommon.h" -#include "GPU/Debugger/Debugger.h" #include "GPU/Vulkan/ShaderManagerVulkan.h" #include "GPU/Vulkan/GPU_Vulkan.h" #include "GPU/Vulkan/FramebufferManagerVulkan.h" @@ -63,7 +62,7 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *gfxCtx, Draw::DrawContext *draw) pipelineManager_ = new PipelineManagerVulkan(vulkan); framebufferManagerVulkan_ = new FramebufferManagerVulkan(draw); framebufferManager_ = framebufferManagerVulkan_; - textureCacheVulkan_ = new TextureCacheVulkan(draw, vulkan); + textureCacheVulkan_ = new TextureCacheVulkan(draw, framebufferManager_->GetDraw2D(), vulkan); textureCache_ = textureCacheVulkan_; drawEngineCommon_ = &drawEngine_; shaderManager_ = shaderManagerVulkan_; @@ -431,11 +430,6 @@ void GPU_Vulkan::InitClear() { } } -void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { - GPUDebug::NotifyDisplay(framebuf, stride, format); - framebufferManager_->SetDisplayFramebuffer(framebuf, stride, format); -} - void GPU_Vulkan::CopyDisplayToOutput(bool reallyDirty) { // Flush anything left over. drawEngine_.Flush(); @@ -604,9 +598,8 @@ std::vector GPU_Vulkan::DebugGetShaderIDs(DebugShaderType type) { return drawEngine_.DebugGetVertexLoaderIDs(); } else if (type == SHADER_TYPE_PIPELINE) { return pipelineManager_->DebugGetObjectIDs(type); - } else if (type == SHADER_TYPE_DEPAL) { - ///... - return std::vector(); + } else if (type == SHADER_TYPE_TEXTURE) { + return textureCache_->GetTextureShaderCache()->DebugGetShaderIDs(type); } else if (type == SHADER_TYPE_VERTEX || type == SHADER_TYPE_FRAGMENT) { return shaderManagerVulkan_->DebugGetShaderIDs(type); } else if (type == SHADER_TYPE_SAMPLER) { @@ -621,8 +614,8 @@ std::string GPU_Vulkan::DebugGetShaderString(std::string id, DebugShaderType typ return drawEngine_.DebugGetVertexLoaderString(id, stringType); } else if (type == SHADER_TYPE_PIPELINE) { return pipelineManager_->DebugGetObjectString(id, type, stringType); - } else if (type == SHADER_TYPE_DEPAL) { - return ""; + } else if (type == SHADER_TYPE_TEXTURE) { + return textureCache_->GetTextureShaderCache()->DebugGetShaderString(id, type, stringType); } else if (type == SHADER_TYPE_SAMPLER) { return textureCacheVulkan_->DebugGetSamplerString(id, stringType); } else if (type == SHADER_TYPE_VERTEX || type == SHADER_TYPE_FRAGMENT) { diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index 87e54dbf19..3c13d57621 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -25,7 +25,7 @@ #include "GPU/GPUCommon.h" #include "GPU/Vulkan/DrawEngineVulkan.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" class FramebufferManagerVulkan; class ShaderManagerVulkan; @@ -50,7 +50,6 @@ public: void PreExecuteOp(u32 op, u32 diff) override; void ExecuteOp(u32 op, u32 diff) override; - void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void GetStats(char *buffer, size_t bufsize) override; void ClearCacheNextFrame() override; void DeviceLost() override; // Only happens on Android. Drop all textures and shaders. diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 6aa176c864..566708480a 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -250,20 +250,10 @@ void DrawEngineVulkan::ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManag GenericStencilFuncState stencilState; ConvertStencilFuncState(stencilState); - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Enforce plain depth writing. - key.depthTestEnable = true; - key.depthWriteEnable = true; - key.stencilTestEnable = false; - key.depthCompareOp = VK_COMPARE_OP_ALWAYS; - key.depthClampEnable = false; - } else if (gstate.isModeClear()) { + if (gstate.isModeClear()) { key.depthTestEnable = true; key.depthCompareOp = VK_COMPARE_OP_ALWAYS; key.depthWriteEnable = gstate.isClearModeDepthMask(); - if (gstate.isClearModeDepthMask()) { - fbManager.SetDepthUpdated(); - } // Stencil Test bool alphaMask = gstate.isClearModeAlphaMask(); @@ -294,9 +284,6 @@ void DrawEngineVulkan::ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManag key.depthTestEnable = true; key.depthCompareOp = compareOps[gstate.getDepthTestFunction()]; key.depthWriteEnable = gstate.isDepthWriteEnabled(); - if (gstate.isDepthWriteEnabled()) { - fbManager.SetDepthUpdated(); - } } else { key.depthTestEnable = false; key.depthWriteEnable = false; @@ -331,15 +318,13 @@ void DrawEngineVulkan::ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManag fbManager.GetRenderWidth(), fbManager.GetRenderHeight(), fbManager.GetTargetBufferWidth(), fbManager.GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); float depthMin = vpAndScissor.depthRangeMin; float depthMax = vpAndScissor.depthRangeMax; if (depthMin < 0.0f) depthMin = 0.0f; if (depthMax > 1.0f) depthMax = 1.0f; - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } VkViewport &vp = dynState.viewport; vp.x = vpAndScissor.viewportX; @@ -349,10 +334,6 @@ void DrawEngineVulkan::ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManag vp.minDepth = vpAndScissor.depthRangeMin; vp.maxDepth = vpAndScissor.depthRangeMax; - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - ScissorRect &scissor = dynState.scissor; scissor.x = vpAndScissor.scissorX; scissor.y = vpAndScissor.scissorY; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index eb6ab9507a..555e23b1fd 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -41,7 +41,7 @@ #include "GPU/ge_constants.h" #include "GPU/GPUState.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Common/PostShader.h" #include "GPU/Common/TextureCacheCommon.h" #include "GPU/Common/TextureDecoder.h" @@ -184,8 +184,8 @@ std::vector SamplerCache::DebugGetSamplerIDs() const { return ids; } -TextureCacheVulkan::TextureCacheVulkan(Draw::DrawContext *draw, VulkanContext *vulkan) - : TextureCacheCommon(draw), +TextureCacheVulkan::TextureCacheVulkan(Draw::DrawContext *draw, Draw2D *draw2D, VulkanContext *vulkan) + : TextureCacheCommon(draw, draw2D), computeShaderManager_(vulkan), samplerCache_(vulkan) { DeviceRestore(draw); @@ -200,7 +200,7 @@ void TextureCacheVulkan::SetFramebufferManager(FramebufferManagerVulkan *fbManag } void TextureCacheVulkan::DeviceLost() { - depalShaderCache_->DeviceLost(); + textureShaderCache_->DeviceLost(); VulkanContext *vulkan = draw_ ? (VulkanContext *)draw_->GetNativeObject(Draw::NativeObject::CONTEXT) : nullptr; @@ -227,7 +227,7 @@ void TextureCacheVulkan::DeviceRestore(Draw::DrawContext *draw) { _assert_(!allocator_); samplerCache_.DeviceRestore(vulkan); - depalShaderCache_->DeviceRestore(draw); + textureShaderCache_->DeviceRestore(draw); VkSamplerCreateInfo samp{ VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; @@ -320,7 +320,7 @@ void TextureCacheVulkan::StartFrame() { TextureCacheCommon::StartFrame(); InvalidateLastTexture(); - depalShaderCache_->Decimate(); + textureShaderCache_->Decimate(); timesInvalidatedAllThisFrame_ = 0; texelsScaledThisFrame_ = 0; @@ -388,16 +388,21 @@ void TextureCacheVulkan::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutB } void TextureCacheVulkan::BindTexture(TexCacheEntry *entry) { - _assert_(entry); - _assert_(entry->vkTex); + if (!entry) { + imageView_ = VK_NULL_HANDLE; + curSampler_ = VK_NULL_HANDLE; + return; + } + _dbg_assert_(entry->vkTex); entry->vkTex->Touch(); - imageView_ = entry->vkTex->GetImageView(); + int maxLevel = (entry->status & TexCacheEntry::STATUS_NO_MIPS) ? 0 : entry->maxLevel; SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry); curSampler_ = samplerCache_.GetOrCreateSampler(samplerKey); + imageView_ = entry->vkTex->GetImageView(); drawEngine_->SetDepalTexture(VK_NULL_HANDLE); - gstate_c.SetUseShaderDepal(false); + gstate_c.SetUseShaderDepal(false, false); } void TextureCacheVulkan::ApplySamplingParams(const SamplerCacheKey &key) { @@ -459,7 +464,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { // Any texture scaling is gonna move away from the original 16-bit format, if any. VkFormat actualFmt = plan.scaleFactor > 1 ? VULKAN_8888_FORMAT : dstFmt; if (plan.replaced->Valid()) { - actualFmt = ToVulkanFormat(plan.replaced->Format(0)); + actualFmt = ToVulkanFormat(plan.replaced->Format(plan.baseLevelSrc)); } bool computeUpload = false; @@ -531,7 +536,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { ReplacedTextureDecodeInfo replacedInfo; bool willSaveTex = false; - if (replacer_.Enabled() && !plan.replaced->Valid() && plan.depth == 1) { + if (replacer_.Enabled() && plan.replaced->IsInvalid() && plan.depth == 1) { replacedInfo.cachekey = entry->CacheKey(); replacedInfo.hash = entry->fullhash; replacedInfo.addr = entry->addr; @@ -560,7 +565,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { int mipWidth = mipUnscaledWidth * plan.scaleFactor; int mipHeight = mipUnscaledHeight * plan.scaleFactor; if (plan.replaced->Valid()) { - plan.replaced->GetSize(i, mipWidth, mipHeight); + plan.replaced->GetSize(plan.baseLevelSrc + i, mipWidth, mipHeight); } int bpp = actualFmt == VULKAN_8888_FORMAT ? 4 : 2; // output bpp @@ -590,7 +595,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { // Directly load the replaced image. data = drawEngine_->GetPushBufferForTextureData()->PushAligned(size, &bufferOffset, &texBuf, pushAlignment); double replaceStart = time_now_d(); - plan.replaced->Load(i, data, stride); // if it fails, it'll just be garbage data... OK for now. + plan.replaced->Load(plan.baseLevelSrc + i, data, stride); // if it fails, it'll just be garbage data... OK for now. replacementTimeThisFrame_ += time_now_d() - replaceStart; VK_PROFILE_BEGIN(vulkan, cmdInit, VK_PIPELINE_STAGE_TRANSFER_BIT, "Copy Upload (replaced): %dx%d", mipWidth, mipHeight); @@ -631,7 +636,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { int w = dataScaled ? mipWidth : mipUnscaledWidth; int h = dataScaled ? mipHeight : mipUnscaledHeight; // At this point, data should be saveData, and not slow. - replacer_.NotifyTextureDecoded(replacedInfo, data, stride, i, w, h); + replacer_.NotifyTextureDecoded(replacedInfo, data, stride, plan.baseLevelSrc + i, w, h); } } } @@ -772,6 +777,8 @@ bool TextureCacheVulkan::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int leve gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE); // We may have blitted to a temp FBO. framebufferManager_->RebindFramebuffer("RebindFramebuffer - GetCurrentTextureDebug"); + if (!retval) + ERROR_LOG(G3D, "Failed to get debug texture: copy to memory failed"); return retval; } else { return false; diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index c3fc55945e..2fe4b4d59c 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -22,7 +22,7 @@ #include "GPU/GPUState.h" #include "Common/GPU/Vulkan/VulkanContext.h" #include "GPU/Common/TextureCacheCommon.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Vulkan/VulkanUtil.h" struct VirtualFramebuffer; @@ -54,7 +54,7 @@ private: class TextureCacheVulkan : public TextureCacheCommon { public: - TextureCacheVulkan(Draw::DrawContext *draw, VulkanContext *vulkan); + TextureCacheVulkan(Draw::DrawContext *draw, Draw2D *draw2D, VulkanContext *vulkan); ~TextureCacheVulkan(); void StartFrame() override; diff --git a/GPU/ge_constants.h b/GPU/ge_constants.h index 78363c3879..8cd455ba79 100644 --- a/GPU/ge_constants.h +++ b/GPU/ge_constants.h @@ -435,6 +435,11 @@ inline bool IsBufferFormat16Bit(GEBufferFormat bfmt) { inline bool IsTextureFormat16Bit(GETextureFormat tfmt) { return (int)tfmt < 3; } + +inline int BufferFormatBytesPerPixel(GEBufferFormat format) { + return format == GE_FORMAT_8888 ? 4 : 2; // applies to depth as well. +} + inline bool TextureFormatMatchesBufferFormat(GETextureFormat fmt, GEBufferFormat bfmt) { // First four matches perfectly. if ((int)fmt < 4) { diff --git a/UI/DevScreens.cpp b/UI/DevScreens.cpp index 1c938596ac..a804eb98f0 100644 --- a/UI/DevScreens.cpp +++ b/UI/DevScreens.cpp @@ -1151,7 +1151,7 @@ struct { DebugShaderType type; const char *name; } shaderTypes[] = { // { SHADER_TYPE_GEOMETRY, "Geometry" }, { SHADER_TYPE_VERTEXLOADER, "VertexLoader" }, { SHADER_TYPE_PIPELINE, "Pipeline" }, - { SHADER_TYPE_DEPAL, "Depal" }, + { SHADER_TYPE_TEXTURE, "Texture" }, { SHADER_TYPE_SAMPLER, "Sampler" }, }; diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index aa08576467..1b98b91bb8 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -1209,16 +1209,25 @@ PC: %08x } else if (info.type == ExceptionType::BAD_EXEC_ADDR) { snprintf(statbuf, sizeof(statbuf), R"( Destination: %s to %08x -PC: %08x)", +PC: %08x +RA: %08x)", ExecExceptionTypeAsString(info.exec_type), info.address, - info.pc); + info.pc, + info.ra); + ctx->Draw()->DrawTextShadow(ubuntu24, statbuf, x, y, 0xFFFFFFFF); + y += 180; + } else if (info.type == ExceptionType::BREAK) { + snprintf(statbuf, sizeof(statbuf), R"( +BREAK +PC: %08x +)", info.pc); ctx->Draw()->DrawTextShadow(ubuntu24, statbuf, x, y, 0xFFFFFFFF); y += 180; } else { snprintf(statbuf, sizeof(statbuf), R"( -BREAK -)"); +Invalid / Unknown (%d) +)", (int)info.type); ctx->Draw()->DrawTextShadow(ubuntu24, statbuf, x, y, 0xFFFFFFFF); y += 180; } diff --git a/UWP/GPU_UWP/GPU_UWP.vcxproj b/UWP/GPU_UWP/GPU_UWP.vcxproj index 9a24b23185..277526509c 100644 --- a/UWP/GPU_UWP/GPU_UWP.vcxproj +++ b/UWP/GPU_UWP/GPU_UWP.vcxproj @@ -379,7 +379,7 @@ - + @@ -439,7 +439,7 @@ - + @@ -527,4 +527,4 @@ - \ No newline at end of file + diff --git a/UWP/GPU_UWP/GPU_UWP.vcxproj.filters b/UWP/GPU_UWP/GPU_UWP.vcxproj.filters index affb707ff7..2a797c0d2e 100644 --- a/UWP/GPU_UWP/GPU_UWP.vcxproj.filters +++ b/UWP/GPU_UWP/GPU_UWP.vcxproj.filters @@ -57,7 +57,7 @@ - + @@ -117,6 +117,6 @@ - + - \ No newline at end of file + diff --git a/Windows/GEDebugger/GEDebugger.cpp b/Windows/GEDebugger/GEDebugger.cpp index 60ae3a0b3b..7c78dcf80e 100644 --- a/Windows/GEDebugger/GEDebugger.cpp +++ b/Windows/GEDebugger/GEDebugger.cpp @@ -649,11 +649,13 @@ void CGEDebugger::SecondPreviewHover(int x, int y) { } DescribeSecondPreview(state, desc); } else { - u32 pix = secondBuffer_->GetRawPixel(x, y); if (showClut_) { - // Show the clut index, rather than coords. - DescribePixel(pix, secondBuffer_->GetFormat(), y * 16 + x, 0, desc); + // Use the clut index, rather than coords. + uint32_t clutWidth = secondBuffer_->GetStride() / 16; + u32 pix = secondBuffer_->GetRawPixel(y * clutWidth + x, 0); + DescribePixel(pix, secondBuffer_->GetFormat(), y * clutWidth + x, 0, desc); } else { + u32 pix = secondBuffer_->GetRawPixel(x, y); DescribePixel(pix, secondBuffer_->GetFormat(), x, y, desc); } } @@ -977,6 +979,10 @@ BOOL CGEDebugger::DlgProc(UINT message, WPARAM wParam, LPARAM lParam) { SetBreakNext(BreakNext::FRAME); break; + case IDC_GEDBG_STEPVSYNC: + SetBreakNext(BreakNext::VSYNC); + break; + case IDC_GEDBG_STEPPRIM: SetBreakNext(BreakNext::PRIM); break; diff --git a/Windows/ppsspp.rc b/Windows/ppsspp.rc index e2f38fd8e6..3bc7dfed34 100644 --- a/Windows/ppsspp.rc +++ b/Windows/ppsspp.rc @@ -202,7 +202,7 @@ EXSTYLE WS_EX_ACCEPTFILES | WS_EX_TOOLWINDOW CAPTION "GE" FONT 8, "MS Shell Dlg", 0, 0, 0x1 BEGIN - PUSHBUTTON "Step &Frame",IDC_GEDBG_STEPFRAME,10,2,44,14 + PUSHBUTTON "Step &Frame",IDC_GEDBG_STEPVSYNC,10,2,44,14 PUSHBUTTON "Step &Tex",IDC_GEDBG_STEPTEX,60,2,44,14 PUSHBUTTON "Step &Draw",IDC_GEDBG_STEPDRAW,105,2,44,14 PUSHBUTTON "Step &Prim",IDC_GEDBG_STEPPRIM,150,2,44,14 @@ -679,7 +679,8 @@ BEGIN MENUITEM "Next &Curve", IDC_GEDBG_STEPCURVE MENUITEM "Next &Texture", IDC_GEDBG_STEPTEX MENUITEM "Next &Draw Flush", IDC_GEDBG_STEPDRAW - MENUITEM "Next &Frame", IDC_GEDBG_STEPFRAME + MENUITEM "Next Display &Framebuf", IDC_GEDBG_STEPFRAME + MENUITEM "Next &Vsync Frame", IDC_GEDBG_STEPVSYNC MENUITEM "", 0, MFT_SEPARATOR MENUITEM "&Auto Flush Pending", IDC_GEDBG_FLUSHAUTO END diff --git a/Windows/resource.h b/Windows/resource.h index eacb42760b..13104152e9 100644 --- a/Windows/resource.h +++ b/Windows/resource.h @@ -331,6 +331,7 @@ #define ID_GEDBG_SHOWONLEFT 40219 #define ID_GEDBG_SHOWONRIGHT 40220 #define ID_GEDBG_SHOWONTOPRIGHT 40221 +#define IDC_GEDBG_STEPVSYNC 40222 // Dummy option to let the buffered rendering hotkey cycle through all the options. @@ -344,7 +345,7 @@ #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 256 -#define _APS_NEXT_COMMAND_VALUE 40222 +#define _APS_NEXT_COMMAND_VALUE 40223 #define _APS_NEXT_CONTROL_VALUE 1202 #define _APS_NEXT_SYMED_VALUE 101 #endif diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 71fcf8de3a..7f3afa7849 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -319,7 +319,7 @@ EXEC_AND_LIB_FILES := \ $(SRC)/GPU/GeConstants.cpp \ $(SRC)/GPU/GeDisasm.cpp \ $(SRC)/GPU/Common/Draw2D.cpp \ - $(SRC)/GPU/Common/DepalettizeCommon.cpp \ + $(SRC)/GPU/Common/TextureShaderCommon.cpp \ $(SRC)/GPU/Common/DepalettizeShaderCommon.cpp \ $(SRC)/GPU/Common/FragmentShaderGenerator.cpp \ $(SRC)/GPU/Common/FramebufferManagerCommon.cpp \ diff --git a/assets/compat.ini b/assets/compat.ini index c6011605d7..974a6216de 100644 --- a/assets/compat.ini +++ b/assets/compat.ini @@ -1102,6 +1102,10 @@ NPEH00029 = true ULUS10455 = true [BlueToAlpha] +# Some games render first to RGB of a 4444 texture, then they switch to 565 and render masked to blue, +# just to be able to render to the alpha channel of the 4444. We can detect that and reroute rendering +# to avoid problems. + # Split/Second ULES01402 = true ULUS10513 = true @@ -1121,10 +1125,6 @@ ULES00262 = true ULUS10064 = true ULKS46087 = true -# Some games render first to RGB of a 4444 texture, then they switch to 565 and render masked to blue, -# just to be able to render to the alpha channel of the 4444. We can detect that and reroute rendering -# to avoid problems. - [DateLimited] # Car Jack Streets - issue #12698 NPUZ00043 = true @@ -1266,3 +1266,13 @@ ULES00618 = true # Silver Fall ULES00808 = true ULUS10270 = true + +[DeswizzleDepth] +UCUS98633 = true +UCAS40145 = true +UCES00420 = true +UCJS10052 = true +UCKS45048 = true +UCJS18030 = true +UCJS18047 = true +NPJG00015 = true diff --git a/assets/lang/ko_KR.ini b/assets/lang/ko_KR.ini index 3236d8b6cd..b83bb8a381 100644 --- a/assets/lang/ko_KR.ini +++ b/assets/lang/ko_KR.ini @@ -1,150 +1,150 @@ [Audio] Alternate speed volume = 대체 속도 볼륨 -Audio backend = 오디오 처리자 (재시작 필요) -Audio Error = Audio Error -AudioBufferingForBluetooth = 블루투스 친화적 버퍼링 (느림) +Audio backend = 오디오 백엔드 (재시작 요구) +Audio Error = 오디오 오류 +AudioBufferingForBluetooth = 블루투스 친화적 버퍼 (느림) Auto = 자동 Device = 장치 -Disabled = Disabled -DSound (compatible) = DSound (호환됨) +Disabled = 비활성화 +DSound (compatible) = DSound (호환) Enable Sound = 사운드 활성화 -Global volume = 전역 볼륨 -Microphone = Microphone -Microphone Device = Microphone device +Global volume = 글로벌 볼륨 +Microphone = 마이크로폰 +Microphone Device = 마이크로폰 장치 Mute = 음소거 -Reverb volume = Reverb volume -Use new audio devices automatically = 새로운 오디오 장치로 전환 -Use global volume = 전역 볼륨 사용 +Reverb volume = 반향 볼륨 +Use new audio devices automatically = 새 오디오 장치를 자동으로 사용 +Use global volume = 글로벌 볼륨 사용 WASAPI (fast) = WASAPI (빠름) [Controls] -Analog Binding = Analog Binding -Analog Settings = Analog Settings -Analog Style = Analog Style -Auto-rotation speed = 아날로그 자동 회전 속도 -Analog Limiter = 아날로그 제한 +Analog Binding = 아날로그 바인딩 +Analog Limiter = 아날로그 리미터 +Analog Settings = 아날로그 설정 Analog Stick = 아날로그 스틱 -AnalogLimiter Tip = 아날로그 제한 버튼이 눌러졌을 때 아날로그를 제한합니다. +Analog Style = 아날로그 스타일 +AnalogLimiter Tip = 아날로그 리미터 버튼을 눌렀을 때 Auto = 자동 -Auto-centering analog stick = 아날로그 스틱 자동으로 중앙 고정 -Auto-hide buttons after seconds = 버튼 자동 숨김 -Auto-switch = Auto-switch -Base tilt position = Base tilt position -Binds = Binds -Button Binding = Button Binding -Button Opacity = 버튼 투명도 +Auto-centering analog stick = 자동 센터링 아날로그 스틱 +Auto-hide buttons after seconds = 몇 초 후 버튼 자동 숨기기 +Auto-rotation speed = 자동 회전 속도 +Auto-switch = 자동 스위치 +Base tilt position = 기본 기울기 위치 +Binds = 바인드 +Button Binding = 버튼 바인딩 +Button Opacity = 버튼 불투명도 Button style = 버튼 스타일 -Calibrate Analog Stick = Calibrate Analog Stick -Calibrate D-Pad = 십자 패드 보정 -Calibrated = Calibrated -Calibration = 보정 -Circular stick input = Circular stick input +Calibrate Analog Stick = 아날로그 스틱 보정 +Calibrate D-Pad = 보정 +Calibrated = 보정됨 +Calibration = 교정 +Circular stick input = 원형 스틱 입력 Classic = 클래식 -Confine Mouse = 창/화면 안에 커서를 가두기 -Control Mapping = 컨트롤 맵핑 -Custom Key Setting = Custom Key Setting -Customize = Customize -Customize Touch Controls = 터치 컨트롤 레이아웃 편집... -Customize tilt = 기울기 사용자화... -D-PAD = 십자 패드 -Deadzone radius = 데드존 범위 -Disable D-Pad diagonals (4-way touch) = 십자 패드 대각선 비활성 (4방향 터치) -Disable diagonal input = Disable diagonal input -Double tap = Double tap -Enable gesture control = Enable gesture control -Enable standard shortcut keys = Enable standard shortcut keys -Gesture = Gesture -Gesture mapping = Gesture mapping -Glowing borders = 빛나는 테두리 +Confine Mouse = 창/표시 영역 내에서 마우스 트랩 +Control Mapping = 제어 맵핑 +Custom Key Setting = 커스텀 키 설정 +Customize = 맞춤설정 +Customize Touch Controls = 터치 제어 레이아웃 수정... +Customize tilt = 기울기 맞춤설정... +D-PAD = D-패드 +Deadzone radius = 데드존 반경 +Disable D-Pad diagonals (4-way touch) = D-패드 대각선 비활성화 (4 방향 터치) +Disable diagonal input = 대각선 입력 비활성화 +Double tap = 두 번 탭 +Enable gesture control = 제스처 제어 활성화 +Enable standard shortcut keys = 표준 단축키 활성화 +Gesture = 제스처 +Gesture mapping = 제스처 맵핑 +Glowing borders = 광선 테두리 HapticFeedback = 햅틱 피드백 (진동) -Hide touch analog stick background circle = Hide touch analog stick background circle -Icon = Icon -Ignore gamepads when not focused = 창이 활성화 되지 않았을 때 게임패드 무시 -Ignore Windows Key = 윈도우 키 무시 +Hide touch analog stick background circle = 터치 아날로그 스틱 배경 원 숨기기 +Icon = 아이콘 +Ignore gamepads when not focused = 초점이 맞지 않을 때 게임패드 무시 +Ignore Windows Key = Windows 키 비활성화 Invert Axes = 축 반전 -Invert Tilt along X axis = X축 기울기 반전 -Invert Tilt along Y axis = Y축 기울기 반전 -Keep this button pressed when right analog is pressed = 오른쪽 아날로그가 눌렸을 때 이 버튼을 눌리게끔 유지 -Keyboard = 키보드 조작 설정 +Invert Tilt along X axis = X 축을 따라 기울기 반전 +Invert Tilt along Y axis = Y 축을 따라 기울기 반전 +Keep this button pressed when right analog is pressed = 오른쪽 아날로그를 눌렀을 때 이 버튼을 계속 누른 상태 유지 +Keyboard = 키보드 제어 설정 L/R Trigger Buttons = L/R 트리거 버튼 -Landscape = 가로 -Landscape Auto = 가로 자동 -Landscape Reversed = 가로 반전 -Low end radius = Low end radius +Landscape = 가로 방향 +Landscape Auto = 가로 방향 자동 +Landscape Reversed = 가로 방향 반전 +Low end radius = 하단 반경 Mouse = 마우스 설정 -Mouse sensitivity = 마우스 민감도 -Mouse smoothing = 마우스 가속도(Smoothing) -MouseControl Tip = 'M' 아이콘을 눌러 조작 매핑 화면에 들어가 마우스를 매핑할 수 있습니다. -None (Disabled) = 없음 (비활성) -Off = 끄기 -OnScreen = 화면 터치 컨트롤 -Portrait = 세로 -Portrait Reversed = 세로 반전 +Mouse sensitivity = 마우스 감도 +Mouse smoothing = 마우스 스무딩 +MouseControl Tip = 이제 'M' 아이콘을 눌러 제어 매핑 화면에서 마우스를 매핑할 수 있습니다. +None (Disabled) = 없음 (비활성화) +Off = 끔 +OnScreen = 화면 터치 제어 +Portrait = 세로 방향 +Portrait Reversed = 세로 방향 반전 PSP Action Buttons = PSP 액션 버튼 -Raw input = Raw input -Repeat mode = Repeat mode -Reset to defaults = Reset to defaults -Screen aligned to ground = Screen aligned to ground -Screen at right angle to ground = Screen at right angle to ground +Raw input = 원시 입력 +Reset to defaults = 기본값으로 재설정 +Screen aligned to ground = 지면에 맞춰진 화면 +Screen at right angle to ground = 지면과 직각의 스크린 Screen Rotation = 화면 회전 -seconds, 0 : off = 초 단위, 0 : 끄기 -Sensitivity (scale) = Sensitivity (scale) -Sensitivity = 민감도 -Shape = Shape -Show Touch Pause Menu Button = 일시 정지 메뉴 버튼 표시 -Swipe = Swipe -Swipe sensitivity = Swipe sensitivity -Swipe smoothing = Swipe smoothing +seconds, 0 : off = 초 단위, 0 = 끔 +Sensitivity = 감도 +Sensitivity (scale) = 감도 (스케일) +Shape = 모양 +Show Touch Pause Menu Button = 일시중지 메뉴 버튼 표시 +Swipe = 스와이프 +Swipe sensitivity = 스와이프 감도 +Swipe smoothing = 스와이프 스무딩 Thin borders = 얇은 테두리 -Tilt Base Radius = Tilt base radius -Tilt Input Type = 기울기 입력 방식 -Tilt Sensitivity along X axis = X축 기울기 민감도 -Tilt Sensitivity along Y axis = Y축 기울기 민감도 -To Calibrate = 보정하려면, 기기를 평평한 곳에 놓고 "보정"을 눌러주십시오. -Toggle mode = Toggle mode -Touch Control Visibility = 터치 컨트롤 표시 -Use custom right analog = 사용자 정의 오른쪽 아날로그 사용 -Use Mouse Control = 마우스 사용하기 -Visibility = 표시 -Visible = Visible +Tilt Base Radius = 기울기 기반 반경 +Tilt Input Type = 기울기 입력 유형 +Tilt Sensitivity along X axis = X 축 기울기 감도 +Tilt Sensitivity along Y axis = Y 축 기울기 감도 +To Calibrate = 보정하려면 장치를 평평한 표면에 놓고 "보정"을 누르세요. +Toggle mode = 토글 모드 +Repeat mode = 반복 모드 +Touch Control Visibility = 터치 제어 가시성 +Use custom right analog = 커스텀 오른쪽 아날로그 사용 +Use Mouse Control = 마우스 제어 사용 +Visibility = 가시성 +Visible = 가시적 X = X Y = Y [CwCheats] Cheats = 치트 -Edit Cheat File = 치트 파일 편집 +Edit Cheat File = 치트 파일 수정 Enable/Disable All = 모든 치트 활성화/비활성화 -Import Cheats = 치트 가져오기 (cheat.db에서) +Import Cheats = cheat.db에서 가져오기 Options = 옵션 -Refresh Rate = 재생률 +Refresh Rate = 주사율 [DesktopUI] # If your language does not show well with the default font, you can use Font to specify a different one. # Just add it to your language's ini file and uncomment it (remove the # by Font). -Auto Max Quality = Auto Max &Quality Font = NanumGothic About PPSSPP... = PPSSPP 정보(&A)... Auto = 자동(&A) -Backend = 렌더링 처리자(&B) (PPSSPP 재시작) -Bicubic = 쌍입방(&B) -Break = 중단 -Break on Load = 불러올 때 중단 +Auto Max Quality = 자동 최대 품질(&Q) +Backend = 렌더링 백엔드(&B) (PPSSPP 재시작) +Bicubic = 고등차수보간(&B) +Break = 증딘 +Break on Load = 불러오기 시 중단 Buffered Rendering = 버퍼링된 렌더링(&B) Buy Gold = 골드 버전 구매(&G) -Control Mapping... = 컨트롤 맵핑(&O)... +Control Mapping... = 제어 맵핑(&O)... Debugging = 디버그(&D) Deposterize = 색조 융합(&D) -Direct3D9 = Direct3D 9(&D) -Direct3D11 = Direct3D &11 +Direct3D9 = Direct3D 9(&9) +Direct3D11 = Direct3D 11(&1) Disassembly = 역어셈블리(&D)... -Discord = Discord -Display Layout Editor = 화면 레이아웃 편집기... +Discord = 디스코드 +Display Layout Editor = 레이아웃 편집기 표시... Display Rotation = 화면 회전 Dump Next Frame to Log = 로그에 다음 프레임 덤프(&U) Emulation = 에뮬레이션(&E) Enable Cheats = 치트 활성화(&C) Enable Sound = 사운드 활성화(&O) -Exit = 종료(&X) +Exit =종료(&X) Extract File... = 파일 추출(&X)... File = 파일(&F) Frame Skipping = 프레임 생략(&F) @@ -152,55 +152,55 @@ Frame Skipping Type = 프레임 생략 유형 Fullscreen = 전체 화면(&L) Game Settings = 게임 설정(&G) GE Debugger... = GE 디버거(&R)... -GitHub = Git&Hub +GitHub = 깃허브(&H) Hardware Transform = 하드웨어 변환(&H) Help = 도움말(&H) Hybrid = 혼합(&H) -Hybrid + Bicubic = 혼합 + 쌍입방(&Y) +Hybrid + Bicubic = 혼합 + 고등차수보간(&Y) Ignore Illegal Reads/Writes = 잘못된 읽기/쓰기 무시(&I) -Ignore Windows Key = 윈도우 키 무시 +Ignore Windows Key = 윈도우즈 키 무시 Keep PPSSPP On Top = PPSSPP 항상 위에 표시(&K) -Landscape = 가로 -Landscape reversed = 가로 반전 +Landscape = 가로방향 +Landscape reversed = 가로방향 반전 Language... = 언어(&N)... Linear = 선형 필터링(&L) Load = 불러오기(&L)... Load .sym File... = sym 파일 불러오기(&A)... -Load Map File... = 맵 파일 불러오기(&M)... +Load Map File... = Map 파일 불러오기(&M)... Load State = 상태 불러오기(&O) Load State File... = 상태 파일 불러오기(&L)... Log Console = 콘솔 로그(&L) -Memory View... = 메모리 뷰(&V)... +Memory View... = 메모리 보기(&V)... More Settings... = 기타 설정(&M)... Nearest = 근접 필터링(&N) -Non-Buffered Rendering = 버퍼 없는 렌더링(&S) -Off = 끄기(&O) -Open Chat = Open Chat +Non-Buffered Rendering = 버퍼 효과 건너뛰기(버퍼되지 않음, 더 빠름)(&S) +Off = 끔(&O) +Open Chat = 채팅 열기 Open Directory... = 디렉터리 열기(&D)... Open from MS:/PSP/GAME... = MS:/PSP/GAME에서 열기(&P)... Open Memory Stick = 메모리 스틱 열기(&M) -Open New Instance = Open new instance +Open New Instance = 새로운 인스턴트 열기 OpenGL = OpenGL(&O) Pause = 일시 정지(&P) Pause When Not Focused = 포커싱되지 않았을 때 일시 정지(&P) -Portrait = 세로 -Portrait reversed = 세로 반전 +Portrait = 세로방향 +Portrait reversed = 세로방향 반전 Postprocessing Shader = 후처리 셰이더(&G) PPSSPP Forums = PPSSPP 포럼(&F) -Record = 기록(&R) -Record Audio = 소리 녹음(&A) +Record = 녹음(&R) +Record Audio = 사운드 녹음(&A) Record Display = 영상 녹화(&D) -Rendering Mode = 렌더링 방식(&O) +Rendering Mode = 렌더링 모드(&O) Rendering Resolution = 렌더링 해상도(&R) -Reset = 리셋(&E) -Reset Symbol Table = 심볼 테이블 리셋(&Y) +Reset = 재설정(&E) +Reset Symbol Table = 심볼 테이블 재설정(&Y) Run = 실행(&R) Save .sym File... = sym 파일 저장하기(&E)... -Save Map File... = 맵 파일 저장하기(&S)... +Save Map File... = map 파일 저장하기(&S)... Save State = 상태 저장하기(&A) Save State File... = 상태 파일 저장하기(&S)... Savestate Slot = 상태 저장 슬롯(&T) -Screen Scaling Filter = 화면 크기 조절 필터(&E) +Screen Scaling Filter = 화면 크기 조정 필터(&E) Show Debug Statistics = 디버그 통계 표시(&G) Show FPS Counter = FPS 카운터 표시(&F) Skip Number of Frames = 프레임 수 생략 @@ -212,210 +212,210 @@ Texture Filtering = 텍스처 필터링(&X) Texture Scaling = 텍스처 크기 조절(&T) Use Lossless Video Codec (FFV1) = 무손실 비디오 코덱 사용 (FFV1)(&U) Use output buffer for video = 비디오에 출력 버퍼 사용 -Vertex Cache = 버텍스 캐시(&V) -VSync = 수직 동기(&Y) -Vulkan = 벌칸(Vulkan) +Vertex Cache = 정점 캐시(&V) +VSync = 수직 동기화(&Y) +Vulkan = Vulkan Window Size = 창 크기(&W) -www.ppsspp.org = www.ppsspp.org 방문(&P) -xBRZ = xBRZ(&X) +www.ppsspp.org = www.&ppsspp.org 방문 +xBRZ = xBRZ 필터(&X) [Developer] -Allocator Viewer = 할당기(Allocator) 뷰어 (Vulkan) +Allocator Viewer = 할당기 뷰어 (Vulkan) Allow remote debugger = 원격 디버거 허용 Backspace = 백스페이스 -Block address = 주소를 차단 -By Address = 주소로 -Copy savestates to memstick root = Copy save states to Memory Stick root -Create/Open textures.ini file for current game = 현재 게임의 textures.ini 파일 생성 및 열기 +Block address = 주소 차단 +By Address = 주소별 +Copy savestates to memstick root = 메모리 스틱 루트에 저장 상태 복사 +Create/Open textures.ini file for current game = 현재 게임에 대한 textures.ini 파일 생성/열기 Current = 현재 -Dev Tools = 개발자 도구 -DevMenu = 개발 메뉴 -Disabled JIT functionality = 비활성화 된 JIT 기능 -Draw Frametimes Graph = 프레임 레이트 그래프 그리기 -Dump Decrypted Eboot = 게임 부팅 시 복호화된 EBOOT.BIN 덤프 (암호화 되어 있는 경우) -Dump Frame GPU Commands = 프레임 GPU 명령어를 덤프 -Enable driver bug workarounds = Enable driver bug workarounds +Dev Tools = 개발 도구 +DevMenu = 개발메뉴 +Disabled JIT functionality = 비활성화된 JIT 기능 +Draw Frametimes Graph = 프레임 시간 그래프 그리기 +Dump Decrypted Eboot = 게임 부팅 시 해독된 EBOOT.BIN 덤프 +Dump Frame GPU Commands = 덤프 프레임 GPU 명령 +Enable driver bug workarounds = 드라이버 버그 해결 방법 활성화 Enable Logging = 디버그 로깅 활성화 Enter address = 주소 입력 FPU = FPU -Framedump tests = Framedump tests +Framedump tests = 프레임 덤프 테스트 Frame Profiler = 프레임 프로파일러 GPU Driver Test = GPU 드라이버 테스트 -GPU Log Profiler = GPU Log Profiler GPU Profile = GPU 프로파일 +GPU Log Profiler = GPU 로그 프로파일러 Jit Compare = JIT 비교 -JIT debug tools = JIT 디버그 툴 +JIT debug tools = JIT 디버그 도구 Language = 언어 Load language ini = 언어 ini 불러오기 -Log Dropped Frame Statistics = 프레임 저하 통계 기록하기 -Log Level = 로그 깊이 +Log Dropped Frame Statistics = 삭제된 프레임 통계 기록 +Log Level = 로그 레벨 Log View = 로그 보기 Logging Channels = 로깅 채널 Next = 다음 -No block = 블록 없음 +No block = 차단 없음 Prev = 이전 Random = 랜덤 -Replace textures = 텍스처 덮어쓰기 -Reset = Reset -Reset limited logging = Reset limited logging -RestoreDefaultSettings = 모든 설정을 다시 기본으로 복원 하시겠습니까?\n컨트롤 맵핑 설정은 변경되지 않습니다.\n\n\n이 작업은 되돌릴 수 없습니다.\n변경 사항을 적용하기 위해 PPSSPP를 재시작해 주십시오. -RestoreGameDefaultSettings = 게임 지정 설정을 다시\nPPSSPP 기본 설정으로 복원하시겠습니까? -Resume = Resume +Replace textures = 텍스처 교체 +Reset = 재설정 +Reset limited logging = 제한된 로깅 재설정 +RestoreDefaultSettings = 모든 설정을 기본값으로 되돌리겠습니까?\n제어 매핑 설정은 변경되지 않습니다.\n\n이 작업은 취소할 수 없습니다.\n변경 사항을 적용하려면 PPSSPP를 다시 시작하세요. +RestoreGameDefaultSettings = 게임별 설정을\nPPSSPP 기본값으로 복원하겠습니까? +Resume = 다시 시작 Run CPU Tests = CPU 테스트 실행 -Save language ini = 언어 ini 저장하기 +Save language ini = 언어 ini 저장 Save new textures = 새로운 텍스처 저장 Shader Viewer = 셰이더 뷰어 Show Developer Menu = 개발자 메뉴 표시 -Show on-screen messages = Show on-screen messages +Show on-screen messages = 화면 메시지 표시 Stats = 상태 System Information = 시스템 정보 -Texture ini file created = Texture ini file created -Texture Replacement = 텍스처 교체하기 +Texture ini file created = 텍스처 ini 파일 생성 +Texture Replacement = 텍스쳐 교체 Toggle Audio Debug = 오디오 디버그 토글 -Toggle Freeze = 토글 프리징 -Touchscreen Test = 터치 스크린 테스트 +Toggle Freeze = 프리징 토글 +Touchscreen Test = 터치화면 테스트 VFPU = VFPU [Dialog] * PSP res = * PSP 리소스 Active = 활성화 -Back = 뒤로 +Back = 뒤로가기 Cancel = 취소 Center = 중앙 -ChangingGPUBackends = GPU 처리자를 변경하기 위해서는 PPSSPP를 재시작해야 합니다. 재시작할까요? -ChangingInflightFrames = 그래픽 커멘드 버퍼링을 변경하기 위해서는 PPSSPP를 재시작해야 합니다. 재시작할까요? -Channel: = Channel: +ChangingGPUBackends = GPU 백엔드를 변경하려면 PPSSPP를 다시 시작해야 합니다. 지금 다시 시작하겠습니까? +ChangingInflightFrames = 그래픽 명령 버퍼링을 변경하려면 PPSSPP를 다시 시작해야 합니다. 지금 다시 시작하겠습니까? +Channel: = 채널: Choose PPSSPP save folder = PPSSPP 저장 폴더 선택 -Confirm Overwrite = 데이터를 덮어쓰시겠습니까? -Confirm Save = 이 데이터를 저장하시겠습니까? -ConfirmLoad = 이 데이터를 불러오시겠습니까? -ConnectingAP = Connecting to the access point.\nPlease wait... -ConnectingPleaseWait = Connecting.\nPlease wait... -ConnectionName = Connection name -Corrupted Data = Corrupted data +Confirm Overwrite = 데이터를 덮어쓰겠습니까? +Confirm Save = 이 데이터를 저장하겠습니까? +ConfirmLoad = 이 데이터를 불러오겠습니까? +ConnectingAP = 접속 포인트에 연결하는 중입니다.\n잠시만 기다려 주세요... +ConnectingPleaseWait = 연결 중입니다.\n잠시만 기다려 주세요... +ConnectionName = 결 이름 +Corrupted Data = 손상된 데이터 Delete = 삭제 -Delete all = 전체 삭제 -Delete completed = 삭제를 완료했습니다. -DeleteConfirm = 이 데이터는 삭제됩니다.\n계속하시겠습니까? -DeleteConfirmAll = 이 게임에 대한 모든 저장 데이터를\n삭제하시겠습니까? -DeleteConfirmGame = 이 게임을 정말로 당신의 장치에서\n삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다. -DeleteConfirmGameConfig = 이 게임의 설정을 정말로 삭제하시겠습니까? -DeleteFailed = 삭제할 수 없습니다. -Deleting = 삭제 중입니다.\n잠시 기다려 주세요... +Delete all = 모두 삭제 +Delete completed = 삭제가 완료되었습니다. +DeleteConfirm = 이 저장 데이터는 삭제됩니다.\n계속하겠습니까? +DeleteConfirmAll = 이 게임에 대한 모든 저장 데이터를\n삭제하겠습니까? +DeleteConfirmGame = 이 게임을 정말로 장치에서\n삭제하겠습니까? 이 작업은 취소할 수 없습니다. +DeleteConfirmGameConfig = 이 게임의 설정을 삭제하겠습니까? +DeleteFailed = 데이터를 삭제할 수 없습니다. +Deleting = 삭제 중\n잠시만 기다려 주세요... Disable All = 모두 비활성화 -Dumps = Dumps -Edit = Edit +Dumps = 덤프 +Edit = 편집 Enable All = 모두 활성화 -Enter = 결정 -Filter = Filter -Finish = 완료 -GE Frame Dumps = GE Frame Dumps -Grid = 격자 -Inactive = 비활성화 -InternalError = An internal error has occurred. +Enter = 입력 +Filter = 필터 +Finish = 마침 +GE Frame Dumps = GE 프레임 덤프 +Grid = 그리드 +Inactive = 비활성 +InternalError = 내부 오류가 발생했습니다. Load = 불러오기 -Load completed = 불러오기를 완료했습니다. -Loading = 불러오는 중입니다.\n잠시 기다려 주세요... -LoadingFailed = 불러올 수 없습니다. +Load completed = 불러오기가 완료되었습니다. +Loading = 로딩 중\n잠시만 기다려 주세요... +LoadingFailed = 데이터를 불러올 수 없습니다. Move = 이동 Network Connection = 네트워크 연결 NEW DATA = 새로운 데이터 No = 아니오 -ObtainingIP = Obtaining IP address.\nPlease wait... +ObtainingIP = IP 주소를 가져오는 중입니다.\n잠시만 기다려 주세요... OK = 확인 -Old savedata detected = 구 버전 저장 데이터 감지됨 +Old savedata detected = 오래된 저장 데이터 감지됨 Options = 옵션 -Reset = 리셋 +Reset = 재설정 Resize = 크기 조정 -Retry = 다시 시도 -Save = 저장하기 -Save completed = 저장을 완료했습니다. -Saving = 저장 중입니다.\n잠시 기다려 주세요... -SavingFailed = 저장할 수 없습니다. -Search = Search +Retry = 재시도 +Save = 저장 +Save completed = 저장이 완료되었습니다. +Saving = 저장 중\n잠시만 기다려 주세요... +SavingFailed = 데이터를 저장할 수 없습니다. +Search = 검색 Select = 선택 Shift = 전환 -Skip = Skip -Snap = Snap -Space = 스페이스 +Skip = 건너뜀 +Snap = 스냅 +Space = 공간 SSID = SSID Submit = 전송 Supported = 지원 There is no data = 데이터가 없습니다. -Toggle All = 전체 선택 -Toggle List = Toggle list -Unsupported = 지원되지 않음 -When you save, it will load on a PSP, but not an older PPSSPP = 저장할 경우 PSP에서는 불러올 수 있지만 구 버전의 PPSSPP에서는 불러올 수 없습니다. -When you save, it will not work on outdated PSP Firmware anymore = 저장할 경우 더 이상 구 버전의 PSP 펌웨어에서는 작동하지 않을 것입니다. -Yes = 네 -Zoom = 확대 +Toggle All = 모두 토글 +Toggle List = 토글 목록 +Unsupported = 미지원 +When you save, it will load on a PSP, but not an older PPSSPP = 저장하면 PSP에 불러오지만 이전 PPSSPP에는 부러오지 않습니다. +When you save, it will not work on outdated PSP Firmware anymore = 저장하면 오래된 PSP 펌웨어에서는 더 이상 작동하지 않습니다. +Yes = 예 +Zoom = 확대/축소 [Error] -7z file detected (Require 7-Zip) = 파일이 7z 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (7-Zip 또는 WinRAR) +7z file detected (Require 7-Zip) = 파일은 (7z로) 압축되어 있습니다.\n먼저 압축을 해제하십시오 (7-Zip 또는 WinRAR 시도). A PSP game couldn't be found on the disc. = 디스크에서 PSP 게임을 찾을 수 없습니다. -Cannot boot ELF located outside mountRoot. = 삽입된 Root 이외의 경로에 위치한 ELF는 부팅할 수 없습니다. +Cannot boot ELF located outside mountRoot. = mountRoot 외부에 있는 ELF를 부팅할 수 없습니다. Could not save screenshot file = 스크린샷 파일을 저장할 수 없습니다. -D3D9or11 = Direct3D 9를 사용할까요? ("아니오"를 선택할 경우 Direct3D 11를 사용합니다.) -D3D11CompilerMissing = D3DCompiler_47.dll 을 찾을 수 없었습니다. 설치한 후 재시도하거나 대신 예 버튼을 눌러 Direct3D 9 를 사용할 수 있습니다. +D3D9or11 = 다이렉트3D 9? (또는 Direct3D 11의 경우 "아니오") +D3D11CompilerMissing = D3DCompiler_47.dll을 찾을 수 없습니다. 설치하세요. 또는 예를 눌러 대신 Direct3D 9를 사용하여 다시 시도하세요. D3D11InitializationError = Direct3D 11 초기화 오류 -D3D11Missing = 현재 사용중인 OS가 D3D11을 포함하지 않고 있습니다. 업데이트를 진행해 보십시오.\n\n예를 눌러 Direct3D 9를 대신 사용합니다. -D3D11NotSupported = 현재 사용중인 GPU가 Direct3D 11을 지원하지 않습니다.\n\n예를 눌러 Direct3D 9를 대신 사용할 수 있습니다. -Disk full while writing data = 데이터를 쓰는 도중 디스크가 가득 찼습니다. -ELF file truncated - can't load = ELF 파일이 불완전합니다 - 불러올 수 없습니다. -Error loading file = 파일 불러오는 중 오류 : -Error reading file = 파일을 읽는 동안 오류가 발생했습니다. -Failed initializing CPU/Memory = Failed initializing CPU or memory -Failed to load executable: = 실행 파일을 불러오는데 실패했습니다: -File corrupt = 파일이 손상되었습니다. -Game disc read error - ISO corrupt = 게임 디스크 읽기 오류: ISO 파일이 손상되었습니다. -GenericAllStartupError = PPSSPP failed to start up with any graphics backend. Try upgrading your graphics and other drivers. -GenericBackendSwitchCrash = PPSSPP crashed while starting.\n\nThis usually means a graphics driver problem. Try upgrading your graphics drivers.\n\nGraphics backend has been switched: -GenericDirect3D9Error = Direct 3D 9 그래픽 초기화에 실패했습니다. 그래픽 드라이버와 DirectX 9 런타임을 업데이트해 보십시오.\n\nOpenGL으로 전환해 보시겠습니까?\n\오류 메시지: +D3D11Missing = 운영 체제 버전에 D3D11이 포함되어 있지 않습니다. 윈도우즈 업데이트를 실행하세요.\n\n대신 Direct3D 9를 사용하여 다시 시도하려면 예를 누르세요. +D3D11NotSupported = GPU가 Direct3D 11을 지원하지 않는 것 같습니다.\n\n대신 Direct3D 9를 사용하여 다시 시도하겠습니까? +Disk full while writing data = 데이터를 쓰는 동안 디스크가 가득 찼습니다. +ELF file truncated - can't load = ELF 파일이 불완전함 - 불러올 수 없음 +Error loading file = 게임을 불러올 수 없습니다. +Error reading file = 파일 읽기 오류입니다. +Failed initializing CPU/Memory = CPU 또는 메모리 초기화 실패 +Failed to load executable: = 실행 파일 불러오기 실패: +File corrupt = 파일 손상 +Game disc read error - ISO corrupt = 게임 디스크 읽기 오류: ISO 손상되었습니다. +GenericAllStartupError = PPSSPP가 그래픽 백엔드로 시작하지 못했습니다. 그래픽 및 기타 드라이버를 업그레이드해 보세요. +GenericBackendSwitchCrash = 시작하는 동안 PPSSPP가 충돌했습니다.\n\n이것은 일반적으로 그래픽 드라이버 문제를 의미합니다. 그래픽 드라이버를 업그레이드해 보세요.\n\n그래픽 백엔드가 전환되었습니다: +GenericDirect3D9Error = 그래픽 초기화에 실패했습니다. 그래픽 드라이버와 DirectX 9 런타임을 업그레이드해 보세요.\n\nOpenGL로 전환하시겠습니까?\n\n오류 메세지: GenericGraphicsError = 그래픽 오류 -GenericOpenGLError = OpenGL 그래픽 초기화에 실패했습니다. 그래픽 드라이버를 업데이트해 보십시오.\n\nDirectX 9로 전환해 보시겠습니까?\n\n오류 메시지: -GenericVulkanError = Vulkan 그래픽 초기화에 실패했습니다. 그래픽 드라이버를 업데이트해 보십시오.\n\nOpenGL으로 전환해 보시겠습니까?\n\n오류 메시지: -InsufficientOpenGLDriver = OpenGL 드라이버 지원 부족 감지!\n\n현재 PPSSPP를 실행하는데 필요한 OpenGL 2.0을 지원하지 않는 것 같습니다.\n\n당신의 GPU가 OpenGL 2.0과 호환되는지 확인해 주십시오. 호환되는 경우, 당신의 GPU 공급업체의 웹사이트에서 새로운 그래픽 드라이버를 찾아서 설치해야 합니다.\n\n자세한 내용은 https://forums.ppsspp.org 포럼을 방문하십시오. -Just a directory. = 디렉토리 입니다. -Missing key = 키가 누락되었습니다. -MsgErrorCode = Error code: -MsgErrorSavedataDataBroken = Save data was corrupt. -MsgErrorSavedataMSFull = Memory Stick full. Check your storage space. -MsgErrorSavedataNoData = Warning: no save data was found. -MsgErrorSavedataNoMS = Memory Stick not inserted. -No EBOOT.PBP, misidentified game = EBOOT.PBP가 없으면, 게임을 식별할 수 없습니다. +GenericOpenGLError = 그래픽 초기화에 실패했습니다. 그래픽 드라이버를 업그레이드해 보세요.\n\nDirectX 9로 전환하겠습니까?\n\n오류 메세지: +GenericVulkanError = 그래픽 초기화에 실패했습니다. 그래픽 드라이버를 업그레이드해 보세요.\n\nOpenGL로 전환하겠습니까?\n\n오류 메세지: +InsufficientOpenGLDriver = 불충분한 OpenGL 드라이버 지원이 감지되었습니다!\n\nGPU가 OpenGL 2.0을 지원하지 않는다고 보고합니다. DirectX를 대신 사용하겠습니까?\n\nDirectX는 현재 더 적은 수의 게임과 호환되지만 GPU에서는 유일한 선택일 수 있습니다.\n\n자세한 내용은 https://forums.ppsspp.org의 포럼을 방문하세요.\n\n +Just a directory. = 그냥 디렉토리입니다. +Missing key = 키 누락 +MsgErrorCode = 오류 코드: +MsgErrorSavedataDataBroken = 저장 데이터가 손상되었습니다. +MsgErrorSavedataMSFull = 메모리 스틱이 가득 찼습니다. 저장 공간을 확인하세요. +MsgErrorSavedataNoData = 경고: 저장 데이터를 찾을 수 없습니다. +MsgErrorSavedataNoMS = 메모리 스틱이 삽입되지 않았습니다. +No EBOOT.PBP, misidentified game = EBOOT.PBP 없음, 잘못 식별된 게임입니다. Not a valid disc image. = 유효한 디스크 이미지가 아닙니다. OpenGLDriverError = OpenGL 드라이버 오류 -PPSSPP doesn't support UMD Music. = PPSSPP는 UMD 음악을 지원하지 않습니다. +PPSSPP doesn't support UMD Music. = PPSSPP는 UMD Music을 지원하지 않습니다. PPSSPP doesn't support UMD Video. = PPSSPP는 UMD 비디오를 지원하지 않습니다. -PPSSPP plays PSP games, not PlayStation 1 or 2 games. = PPSSPP plays PSP games, not PlayStation 1 or 2 games. -PPSSPPDoesNotSupportInternet = PPSSPP는 현재 DLC, PSN, 게임 업데이트에 대한 인터넷 연결을 지원하지 않습니다. -PS1 EBOOTs are not supported by PPSSPP. = PS1 EBOOTs는 PPSSPP에서 지원되지 않습니다. -PSX game image detected. = MODE2 이미지 파일입니다. PPSSPP는 PS1 게임을 지원하지 않습니다. -RAR file detected (Require UnRAR) = 파일이 RAR 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (UnRAR로 시도) -RAR file detected (Require WINRAR) = 파일이 RAR 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (WinRAR로 시도) -Running slow: try frameskip, sound is choppy when slow = 느리게 작동 중입니다: 게임 소리가 제대로 재생되지 않을 경우 프레임 스킵을 시도해 보십시오. -Running slow: Try turning off Software Rendering = 느리게 작동 중입니다: 소프트웨어 렌더링 모드를 해제해 보십시오. -Save encryption failed. This save won't work on real PSP = 저장 파일 암호화에 실패했습니다. 이 저장 파일은 실제 PSP상에서 동작하지 않을 것입니다. -textures.ini filenames may not be cross-platform = 다른 운영체제의 "textures.ini" 파일을 사용할 수 없습니다. -This is a saved state, not a game. = 게임이 아닌 상태 저장 파일입니다. 게임 파일을 선택해 주십시오. -This is save data, not a game. = 게임이 아닌 저장 파일입니다. 게임 파일을 선택해 주십시오. -Unable to create cheat file, disk may be full = 치트 파일을 생성할 수 없습니다. 디스크 용량이 꽉 찼을 수도 있습니다. +PPSSPP plays PSP games, not PlayStation 1 or 2 games. = PPSSPP는 플레이스테이션 1 또는 2 게임이 아닌 PSP 게임을 실행합니다. +PPSSPPDoesNotSupportInternet = PPSSPP는 현재 DLC, PSN 또는 게임 업데이트를 위한 인터넷 연결을 지원하지 않습니다. +PS1 EBOOTs are not supported by PPSSPP. = 플레이스테이션 1 EBOOT는 PPSSPP에서 지원되지 않습니다. +PSX game image detected. = 파일은 MODE2 이미지입니다. PPSSPP는 플레이스테이션 1 게임을 지원하지 않습니다. +RAR file detected (Require UnRAR) = 파일은 (RAR로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (UnRAR 시도). +RAR file detected (Require WINRAR) = 파일은 (RAR로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (WinRAR 시도). +Running slow: try frameskip, sound is choppy when slow = 느리게 실행: 프레임생략 시도, 느릴 때 소리가 고르지 않음 +Running slow: Try turning off Software Rendering = 느리게 실행: "소프트웨어 렌더링" 끄기 시도 +Save encryption failed. This save won't work on real PSP = 저장 암호화에 실패했습니다. 이 저장은 실제 PSP에서 작동하지 않습니다. +textures.ini filenames may not be cross-platform = "textures.ini" 파일 이름은 크로스 플랫폼이 아닐 수 있습니다. +This is a saved state, not a game. = 이것은 게임이 아닌 저장된 상태입니다. +This is save data, not a game. = 이것은 게임이 아닌 세이브 데이터입니다. +Unable to create cheat file, disk may be full = 치트 파일을 생성할 수 없습니다. 디스크가 가득 찼을 수 있습니다. Unable to initialize rendering engine. = 렌더링 엔진을 초기화할 수 없습니다. -Unable to write savedata, disk may be full = 저장 파일을 작성할 수 없습니다. 디스크 용량이 꽉 찼을 수도 있습니다. -Warning: Video memory FULL, reducing upscaling and switching to slow caching mode = 경고: 비디오 메모리가 꽉 찼습니다. 업스케일링을 줄이고 느린 캐시 모드로 전환합니다. -Warning: Video memory FULL, switching to slow caching mode = 경고: 비디오 메모리가 꽉 찼습니다. 느린 캐시 모드로 전환합니다. -ZIP file detected (Require UnRAR) = 파일이 ZIP 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (UnRAR로 시도) -ZIP file detected (Require WINRAR) = 파일이 ZIP 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (WinRAR로 시도) +Unable to write savedata, disk may be full = 저장 데이터를 쓸 수 없습니다. 디스크가 가득 찼을 수 있습니다. +Warning: Video memory FULL, reducing upscaling and switching to slow caching mode = 경고: 비디오 메모리가 가득 찼서, 업스케일링을 줄이고 느린 캐싱 모드로 전환합니다. +Warning: Video memory FULL, switching to slow caching mode = 비디오 메모리가 가득 찼서, 저속 캐싱 모드로 전환합니다. +ZIP file detected (Require UnRAR) = 파일은 (ZIP으로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (UnRAR 시도). +ZIP file detected (Require WINRAR) = 파일은 (ZIP으로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (WinRAR 시도). [Game] Asia = 아시아 -Calculate CRC = Calculate CRC +Calculate CRC = CRC 계산 ConfirmDelete = 삭제 -Create Game Config = 게임 설정파일 만들기 -Create Shortcut = 바로가기 만들기 +Create Game Config = 게임 구성 생성 +Create Shortcut = 단축 키 생성 Delete Game = 게임 삭제 -Delete Game Config = 게임 설정파일 삭제 -Delete Save Data = 저장 데이터 삭제 +Delete Game Config = 게임 구성 삭제 +Delete Save Data = 저장데이터 삭제 Europe = 유럽 Game = 게임 Game Settings = 게임 설정 @@ -423,22 +423,22 @@ Homebrew = 홈브류 Hong Kong = 홍콩 InstallData = 데이터 설치 Japan = 일본 -Korea = 대한민국 +Korea = 한국 MB = MB -One moment please... = 잠시만 기다려 주세요... +One moment please... = 잠깐만 기다려 주세요... Play = 재생 -Remove From Recent = 최근 기록 제거 -SaveData = 저장 데이터 -Setting Background = 배경화면 설정 -Show In Folder = 폴더에 표시 -USA = 북미 -Use UI background = UI 배경화면 사용 +Remove From Recent = "최근"에서 제거 +SaveData = 저장데이터 +Setting Background = 배경 설정 +Show In Folder = 폴더에 표기 +USA = 미국 +Use UI background = UI 배경 사용 [Graphics] -% of the void = 무효 영역의 백분율 -% of viewport = 뷰포트의 백분율 +% of the void = 공백의 % +% of viewport = 뷰포트의 % %, 0:unlimited = %, 0 = 무제한 -(supersampling) = (슈퍼 샘플링) +(supersampling) = (슈퍼샘플링) (upscaling) = (업스케일링) 1x PSP = PSP 1배 2x = 2배 @@ -456,172 +456,172 @@ Use UI background = UI 배경화면 사용 9x PSP = PSP 9배 10x PSP = PSP 10배 16x = 16배 -Aggressive = 급격한 -Alternative Speed = 대체 속도 -Alternative Speed 2 = 대체 속도 2 (단위 퍼센트, 0 = 무제한) +Aggressive = 과격 +Alternative Speed = 대체 속도 (%, 0 = 무제한) +Alternative Speed 2 = 대체 속도 2 (%, 0 = 무제한) Anisotropic Filtering = 비등방성 필터링 Auto = 자동 Auto (1:1) = 자동 (1:1) -Auto (same as Rendering) = 자동 (렌더링 해상도와 같음) -Auto FrameSkip = 자동 프레임 생략 -Auto Max Quality = Auto Max Quality +Auto (same as Rendering) = 자동 (렌더링 해상도와 동일) +Auto FrameSkip = 자동 프레임생략 +Auto Max Quality = 자동 최대 품질 Auto Scaling = 자동 스케일링 -Backend = 처리자 +Backend = 백엔드 Balanced = 평형 -Bicubic = 쌍입방 -BlockTransfer Tip = 몇몇 게임들의 그래픽 오류를 고치기 위해 이 설정이 필요합니다. -BlockTransferRequired = 주의 - 이 설정을 키기 위해 이 게임은 "블럭단위 전송 효과 시뮬레이트"를 사용해야 합니다. -Both = 모두 표시 -Buffer graphics commands (faster, input lag) = 버퍼 그래픽 커맨드 (빠름, 입력 렉 발생) +Bicubic = 고등차수보간 +BlockTransfer Tip = 일부 게임에서는 올바른 그래픽을 위해 이 기능을 켜야 합니다. +BlockTransferRequired = 경고: 이 게임은 "블록 전송 효과 시뮬레이션"을 켬으로 설정해야 합니다. +Both = 둘 다 +Buffer graphics commands (faster, input lag) = 버퍼 그래픽 명령 (빠름, 입력 지연) Buffered Rendering = 버퍼링된 렌더링 -BufferedRenderingRequired = 주의 - 이 게임은 "렌더링 모드"가 "버퍼됨" 이어야 합니다. +BufferedRenderingRequired = 경고: 이 게임은 "렌더링 모드"를 "버퍼링"으로 설정해야 합니다. Camera = 카메라 Camera Device = 카메라 장치 -Cardboard Screen Size = 화면 크기 (뷰포트의 백분율) -Cardboard Screen X Shift = X축 이동 (여백의 백분율) -Cardboard Screen Y Shift = Y축 이동 (여백의 백분율) -Cardboard VR Settings = 구글 카드보드 설정 +Cardboard Screen Size = 화면 크기(뷰포트의 %) +Cardboard Screen X Shift = X 축 이동 (공백의 %) +Cardboard Screen Y Shift = Y 축 이동 (공백의 %) +Cardboard VR Settings = 구글 카드보드 VR 설정 Cheats = 치트 CPU Core = CPU 코어 Debugging = 디버깅 -DefaultCPUClockRequired = 주의 - 이 게임은 CPU 클럭이 기본 설정이어야 합니다. +DefaultCPUClockRequired = 경고: 이 게임은 CPU 클럭을 기본값으로 설정해야 합니다. Deposterize = 색조 융합 -Deposterize Tip = 업스케일링된 텍스처의 왜곡 현상 고치기 +Deposterize Tip = 업스케일링된 텍스처의 시각적 밴딩 결함 수정 Device = 장치 Direct3D 9 = Direct3D 9 Direct3D 11 = Direct3D 11 -Disable slower effects (speedup) = 느림 효과를 비활성화 (속도 상승) +Disable slower effects (speedup) = 느린 효과 비활성화 (속도 향상) Disabled = 비활성화 Display layout editor = 화면 레이아웃 편집기 -Display Resolution (HW scaler) = 화면 해상도 (하드웨어 스케일러) -Dump next frame to log = 로그에 다음 프레임 덤프 -Enable Cardboard VR = 구글 카드보드 활성화 +Display Resolution (HW scaler) = 화면 해상도(HW 스케일러) +Dump next frame to log = 다음 프레임을 로그로 덤프 +Enable Cardboard VR = 카드보드 VR 활성화 FPS = FPS -Frame Rate Control = 프레임 비율 제어 +Frame Rate Control = 프레임속도 제어 Frame Skipping = 프레임 생략 Frame Skipping Type = 프레임 생략 유형 -FullScreen = 전체 화면 -GPU log profiler = GPU log profiler -Hack Settings = 핵 설정 (이것은 오류의 원인이 됩니다) -Hardware Tessellation = 하드웨어 테셀레이션 +FullScreen = 전체화면 +Hack Settings = 핵 설정 (결함을 일으킬 수 있음) +Hardware Tessellation = 하드웨어 조각화 Hardware Transform = 하드웨어 변환 -hardware transform error - falling back to software = 하드웨어 변환 오류 - 소프트웨어로 전환 -HardwareTessellation Tip = 하드웨어가 곡선을 그리게 하여 언제나 고정된 품질을 사용합니다. +hardware transform error - falling back to software = 하드웨어 변환 오류, 소프트웨어로 폴백 +HardwareTessellation Tip = 곡선을 만들기 위해 하드웨어 사용 High = 높음 Hybrid = 혼합 -Hybrid + Bicubic = 혼합 + 쌍입방 -Ignore camera notch when centering = Ignore camera notch when centering +Hybrid + Bicubic = 혼합 + 고등차수보간 +Ignore camera notch when centering = 센터링 시 카메라 노치 무시 Internal Resolution = 내부 해상도 -Lazy texture caching = 텍스처 캐싱을 줄임 (속도 상승) -Lazy texture caching Tip = Faster, but can cause text problems in a few games +Lazy texture caching = 레이지 텍스처 캐싱 (속도 상승) +Lazy texture caching Tip = 더 빠르지만 몇몇 게임에서 텍스트 문제를 일으킬 수 있음 Linear = 선형 필터링 Low = 낮음 -LowCurves = 낮은 품질의 스플라인 및 베지어 곡선 (속도 상승) -LowCurves Tip = 몇몇 게임에만 사용됩니다. 곡선의 부드러움의 정도를 조정합니다. -Lower resolution for effects (reduces artifacts) = 효과 해상도 저하 (질감 감소) +LowCurves = 스플라인/베지어 곡선 품질 +LowCurves Tip = 일부 게임에서만 사용되며 곡선의 부드러움을 제어합니다. +Lower resolution for effects (reduces artifacts) = 효과에 대한 낮은 해상도 (인공물 감소) Manual Scaling = 수동 스케일링 Medium = 중간 -Mode = 방식 -Must Restart = 이 설정을 적용하기 위해서는 PPSSPP를 재시작해 주십시오. +Mode = 모드 +Must Restart = 이 변경 사항을 적용하려면 PPSSPP를 다시 시작해야 합니다. Native device resolution = 기본 장치 해상도 Nearest = 근접 필터링 No buffer = 버퍼 없음 -Non-Buffered Rendering = 버퍼 없는 렌더링 (속도 상승) +Non-Buffered Rendering = 버퍼 효과 건너뛰기(버퍼되지 않음, 더 빠름) None = 없음 Number of Frames = 프레임 수 -Off = 끄기 +Off = 끔 OpenGL = OpenGL Overlay Information = 오버레이 정보 Partial Stretch = 부분 늘이기 Percent of FPS = FPS 비율 Performance = 성능 -Postprocessing effect = Postprocessing effects -Postprocessing Shader = 후처리 셰이더 -Recreate Activity = Recreate activity -Render duplicate frames to 60hz = 중복된 프레임을 60Hz로 렌더링 -RenderDuplicateFrames Tip = 낮은 프레임 레이트에서 동작하는 게임을 부드럽게 해 줍니다. -Rendering Mode = 렌더링 방식 +Postprocessing effect = 후처리 효과 +Postprocessing Shader = 후처리 쉐이더 +Recreate Activity = 활동 재생성 +Render duplicate frames to 60hz = 중복 프레임을 60Hz로 렌더링 +RenderDuplicateFrames Tip = 낮은 프레임 속도에서 실행되는 게임에서 프레임 속도를 더 부드럽게 만들 수 있습니다. +Rendering Mode = 렌더링 모드 Rendering Resolution = 렌더링 해상도 -RenderingMode NonBuffered Tip = 빠르지만 몇몇 게임에서는 작동하지 않을 수 있습니다. -Retain changed textures = 변경된 텍스처를 보유 (속도 감소) -RetainChangedTextures Tip = 많은 게임들이 이 설정을 적용하면 대부분 느려지지만 몇몇 게임은 더 빨라질 수 있습니다. +RenderingMode NonBuffered Tip = 더 빠르지만 일부 게임에서는 아무 것도 표현되지 않을 수 있습니다. +Retain changed textures = 변경된 텍스처 유지 (때로는 느림) +RetainChangedTextures Tip = 많은 게임을 느리게 하지만 일부 게임은 훨씬 빠르게 만듭니다. Rotation = 회전 Safe = 안전 -Screen layout = Screen layout -Screen Scaling Filter = 화면 크기 조절 필터 +Screen layout = 화면 레이아웃 +Screen Scaling Filter = 화면 크기 조정 필터 Show Debug Statistics = 디버그 통계 표시 Show FPS Counter = FPS 카운터 표시 -Simulate Block Transfer = 블록 전송 효과를 시뮬레이션 -Software Rendering = 소프트웨어 렌더링 (실험적) +Simulate Block Transfer = 블록 전송 효과 시뮬레이션 +Software Rendering = 소프트웨어 렌더링 (느림) Software Skinning = 소프트웨어 스키닝 -SoftwareSkinning Tip = 스키닝 된 모델을 합쳐 CPU에 그립니다. 대부분에 게임이 빨라집니다. +SoftwareSkinning Tip = 대부분의 게임에서 더 빠르게 CPU에서 스킨 모델 드로우를 결합합니다. Speed = 속도 Stretching = 늘이기 Texture Filter = 텍스처 필터링 Texture Filtering = 텍스처 필터링 -Texture Scaling = 텍스처 크기 조절 -Texture Shader = Texture shader -Turn off Hardware Tessellation - unsupported = "하드웨어 테셀레이션" 끄기: 지원하지 않음 +Texture Scaling = 텍스처 스케일링 +Texture Shader = 텍스처 쉐이더 +Turn off Hardware Tessellation - unsupported = "하드웨어 조각화" 끄기: 지원되지 않음 Unlimited = 무제한 Up to 1 = 최대 1까지 Up to 2 = 최대 2까지 -Upscale Level = 확대 수준 -Upscale Type = 확대 종류 -UpscaleLevel Tip = CPU가 할 일이 많아집니다 - 또한 끊김 현상을 줄이기 위해 스케일링이 늦어질 수 있습니다. -Use all displays = 모든 디스플레이 사용하기 -Vertex Cache = 버텍스 캐시 -VertexCache Tip = 빠르지만 잠시동안 화면이 깜빡거릴 수 있습니다. -VSync = 수직 동기 -Vulkan = 벌칸(Vulkan) +Upscale Level = 업스케일 레벨 +Upscale Type = 업스케일 유형 +UpscaleLevel Tip = CPU 사용률 높음 - 버벅거림을 방지하기 위해 일부 확장이 지연될 수 있음 +Use all displays = 모든 화면 사용 +Vertex Cache = 정점 캐시 +VertexCache Tip = 더 빠르지만 일시적인 깜박임이 발생할 수 있습니다. +VSync = 수직 동기화 +Vulkan = Vulkan Window Size = 창 크기 -xBRZ = xBRZ +xBRZ = xBRZ 필터 +GPU log profiler = GPU 로그 프로파일러 [InstallZip] Delete ZIP file = ZIP 파일 삭제 Install = 설치 -Install game from ZIP file? = ZIP 파일로부터 게임을 설치하시겠습니까? -Install textures from ZIP file? = ZIP 파일로부터 텍스처팩을 설치하시겠습니까? +Install game from ZIP file? = ZIP 파일에서 게임을 설치하겠습니까? +Install textures from ZIP file? = ZIP 파일에서 텍스처를 설치하겠습니까? Installed! = 설치되었습니다! -Texture pack doesn't support install = 이 텍스처팩의 설치는 지원하지 않습니다. -Zip archive corrupt = ZIP 파일이 손상되었습니다. -Zip file does not contain PSP software = ZIP 파일에 PSP 소프트웨어가 들어있지 않습니다. +Texture pack doesn't support install = 텍스처 팩은 설치를 지원하지 않습니다. +Zip archive corrupt = ZIP 아카이브가 손상되었습니다. +Zip file does not contain PSP software = ZIP 파일에 PSP 소프트웨어가 포함되어 있지 않음 [KeyMapping] -Autoconfigure = 자동 설정 -Autoconfigure for device = 디바이스에 맞게 자동 설정 -Bind All = Bind All -Clear All = 모두 지우기 +Autoconfigure = 자동 구성 +Autoconfigure for device = 장치 자동 구성 +Bind All = 모두 바인딩 +Clear All = 모두 지움 Default All = 기본값 복원 Map a new key for = 새로운 키 입력 Map Key = 키 매핑 Map Mouse = 마우스 매핑 -Replace = Replace -Show PSP = Show PSP -You can press ESC to cancel. = 취소하려면 ESC를 눌러주십시오. +Replace = 교체 +Show PSP = PSP 표시 +You can press ESC to cancel. = Esc를 눌러 취소할 수 있습니다. [MainMenu] Browse = 찾아보기... Buy PPSSPP Gold = PPSSPP Gold 구매 -Choose folder = 폴더 선택하기 -Credits = 만든이 -PPSSPP Homebrew Store = PPSSPP 홈브류 스토어. +Choose folder = 폴더 선택 +Credits = 크레딧 +PPSSPP Homebrew Store = PPSSPP 홈브류 스토어 Exit = 종료 -Game Settings = 게임 설정 +Game Settings = 설정 Games = 게임 -Give PPSSPP permission to access storage = 저장공간에 접근하기 위해 PPSSPP에 권한이 필요합니다. -Homebrew & Demos = 홈브류 및 데모 -How to get games = 어떻게 게임을 구할 수 있나요? -How to get homebrew & demos = 어떻게 홈브류 및 데모를 구할 수 있나요? +Give PPSSPP permission to access storage = PPSSPP에 저장공간 접속 권한 부여 +Homebrew & Demos = 홈브류 && 데모 +How to get games = 게임을 어떻게 구할 수 있나요? +How to get homebrew & demos = 홈브류 및 데모를 어떻게 구할 수 있나요? Load = 불러오기... Loading... = 불러오는 중... PinPath = 경로 고정 -PPSSPP can't load games or save right now = 현재 PPSSPP에서 게임을 불러오거나 저장할 수 없습니다 -Recent = 최근 게임 -SavesAreTemporary = 임시 저장장치에 저장하는 중 -SavesAreTemporaryGuidance = 영구적으로 사용하기 위해 PPSSPP를 기억장치에 복사해 주십시오. -SavesAreTemporaryIgnore = 무시하기 +PPSSPP can't load games or save right now = PPSSPP는 지금 게임을 불러오거나 저장할 수 없습니다. +Recent = 최근 +SavesAreTemporary = PPSSPP가 임시 저장공간에 저장 중입니다. +SavesAreTemporaryGuidance = 영구적으로 저장하기 위해 어딘가에 PPSSPP 추출 +SavesAreTemporaryIgnore = 경고 무시 UnpinPath = 고정 해제 -UseBrowseOrLoad = Use Browse to choose a folder, or Load to choose a file. +UseBrowseOrLoad = 찾아보기를 사용하여 폴더를 선택하거나 불러오기를 사용하여 파일을 선택합니다. www.ppsspp.org = www.ppsspp.org [MainSettings] @@ -629,282 +629,251 @@ Audio = 오디오 Controls = 조작 Graphics = 그래픽 Networking = 네트워킹 -Search = Search System = 시스템 Tools = 도구 +Search = 검색 [MappableControls] Alt speed 1 = 대체 속도 1 Alt speed 2 = 대체 속도 2 -An.Down = 아날로그.하 -An.Left = 아날로그.좌 -An.Right = 아날로그.우 -An.Up = 아날로그.상 -Analog limiter = 아날로그 제한자 +An.Down = 아날로그 아래쪽 +An.Left = 아날로그 왼쪽 +An.Right = 아날로그 오른쪽 +An.Up = 아날로그 위쪽 +Analog limiter = 아날로그 리미터 Analog Stick = 아날로그 스틱 -Audio/Video Recording = 소리/영상 녹화 +Audio/Video Recording = 오디오/비디오 녹화 AxisSwap = 축 스왑 Circle = 동그라미 Cross = 십자 -Custom 1 = Custom 1 -Custom 10 = Custom 10 -Custom 2 = Custom 2 -Custom 3 = Custom 3 -Custom 4 = Custom 4 -Custom 5 = Custom 5 -Custom 6 = Custom 6 -Custom 7 = Custom 7 -Custom 8 = Custom 8 -Custom 9 = Custom 9 -D-pad down = 방향 패드.하 -D-pad left = 방향 패드.좌 -D-pad right = 방향 패드.우 -D-pad up = 방향 패드.상 -DevMenu = 개발 메뉴 -Display Landscape = Display Landscape -Display Landscape Reversed = Display Landscape Reversed -Display Portrait = Display Portrait -Display Portrait Reversed = Display Portrait Reversed -Double tap button = Double tap button -Down = 방향 패드.하 -Dpad = 방향 패드 -Frame Advance = 프레임 건너뛰기 +Custom 1 = 커스텀 1 +Custom 2 = 커스텀 2 +Custom 3 = 커스텀 3 +Custom 4 = 커스텀 4 +Custom 5 = 커스텀 5 +Custom 6 = 커스텀 6 +Custom 7 = 커스텀 7 +Custom 8 = 커스텀 8 +Custom 9 = 커스텀 9 +Custom 10 = 커스텀 10 +D-pad down = D-패드 아래쪽 +D-pad left = D-패드 왼쪽 +D-pad right = D-패드 오른쪽 +D-pad up = D-패드 위쪽 +DevMenu = 개발메뉴 +Double tap button = 두 번 탭 버튼 +Down = D패드 아래쪽 +Dpad = D패드 +Frame Advance = 프레임 어드밴스 Hold = 잠금 Home = 홈 L = L -Left = 방향 패드.좌 +Left = D패드 왼쪽 Load State = 상태 불러오기 -Mute toggle = 음소거 전환 +Mute toggle = 무음 토글 Next Slot = 다음 슬롯 None = 없음 Note = 참고 -OpenChat = 대화 열기 +OpenChat = 채팅 열기 Pause = 일시 정지 R = R RapidFire = 연사 -Record = Record +Record = 녹화 Remote hold = 리모트 잠금 Rewind = 되감기 -Right = 방향 패드.우 -Right Analog Stick = Right Analog Stick -RightAn.Down = 우측An.하 -RightAn.Left = 우측An.좌 -RightAn.Right = 우측An.우 -RightAn.Up = 우측An.상 +Right = D패드 오른쪽 +Right Analog Stick = 오른쪽 아날로그 스틱 +RightAn.Down = 우측 아날로그 아래쪽 +RightAn.Left = 우측 아날로그 왼쪽 +RightAn.Right = 우측 아날로그 오른쪽 +RightAn.Up = 우측 아날로그 위쪽 Rotate Analog (CCW) = 아날로그 회전 (CCW) Rotate Analog (CW) = 아날로그 회전 (CW) Save State = 상태 저장하기 Screen = 화면 Screenshot = 스크린샷 Select = 선택 -SpeedToggle = 속도 전환 +SpeedToggle = 속도 토글 Square = 네모 Start = 시작 -Swipe Down = Swipe Down -Swipe Left = Swipe Left -Swipe Right = Swipe Right -Swipe Up = Swipe Up -tap to customize = tap to customize -Texture Dumping = 텍스처 덤프 +Swipe Down = 아래로 쓸어내림 +Swipe Left = 왼쪽으로 쓸어내림 +Swipe Right = 오른쪽으로 쓸어내림 +Swipe Up = 위로 쓸어내림 +tap to customize = 탭하여 맞춤 설정 +Texture Dumping = 텍스처 덤핑 Texture Replacement = 텍스처 교체 -Toggle Fullscreen = 전체화면 고정 +Toggle Fullscreen = 전체 화면 토글 Toggle mode = 토글 모드 Triangle = 세모 -Fast-forward = 터보 -Up = 방향 패드.상 +Fast-forward = 빨리 감기 +Up = Dpad Up Vol + = 볼륨 + Vol - = 볼륨 - Wlan = 무선랜 - -[MemStick] -Already contains PSP data = Already contains PSP data -Create or Choose a PSP folder = Create or Choose a PSP folder -Current = Current -DataCanBeShared = Data can be shared between PPSSPP regular/Gold -DataCannotBeShared = Data CANNOT be shared between PPSSPP regular/Gold! -DataWillBeLostOnUninstall = Warning! Data will be lost when you uninstall PPSSPP! -DataWillStay = Data will stay even if you uninstall PPSSPP. -Done! = Done! -EasyUSBAccess = Easy USB access -Failed to move some files! = Failed to move some files! -Failed to save config = Failed to save config -Free space = Free space -Manually specify PSP folder = Manually specify PSP folder -MemoryStickDescription = Choose where to keep PSP data (Memory Stick) -Move Data = Move Data -Selected PSP Data Folder = Selected PSP Data Folder -No data will be changed = No data will be changed -PPSSPP will restart after the change = PPSSPP will restart after the change -Skip for now = Skip for now -Starting move... = Starting move... -That folder doesn't work as a memstick folder. = That folder doesn't work as a memstick folder. -USBAccessThrough = USB access through Android/data/org.ppsspp.ppsspp/files -USBAccessThroughGold = USB access through Android/data/org.ppsspp.ppssppgold/files -Use App Private Data = Use App Private Data -Use PSP folder at root of storage = Use PSP folder at root of storage -Welcome to PPSSPP! = Welcome to PPSSPP! -WhatsThis = What's this? +Display Landscape = 가로방향 표시 +Display Landscape Reversed = 가로방향 반전 표시 +Display Portrait = 세로방향 표시 +Display Portrait Reversed = 세로방향 반전 표시 [Networking] -AdHoc Server = Ad hoc server -AdhocServer Failed to Bind Port = Ad hoc server failed to bind port -AM: Data from Unknown Port = AM: Data from Unknown Port -Auto = Auto -Bottom Center = Bottom center -Bottom Left = Bottom left -Bottom Right = Bottom right -Center Left = Center left -Center Right = Center right -Change Mac Address = Mac 주소 변경 -Change proAdhocServer Address = PRO 애드혹 서버 IP 주소 변경 (localhost = multiple instances) -ChangeMacSaveConfirm = Generate a new MAC address? -ChangeMacSaveWarning = Some games verify the MAC address when loading savedata, so this may break old saves. -Chat = 대화 -Chat Button Position = 대화 버튼 위치 -Chat Here = 여기에 입력 -Chat message = Chat message -Chat Screen Position = 대화 화면 위치 -Disconnected from AdhocServer = Disconnected from ad hoc server -DNS Error Resolving = DNS error resolving -Enable built-in PRO Adhoc Server = 내장된 PRO 애드혹 서버 활성화 -Enable network chat = 네트워크 대화 활성화 -Enable networking = 네트워킹/무선 랜 활성화 (베타, 게임 작동을 방해할 수 있음) -Enable UPnP = Enable UPnP (need a few seconds to detect) -EnableQuickChat = 빠른 대화 활성화 +AdHoc Server = Ad hoc 서버 +AdhocServer Failed to Bind Port = Ad Hoc 서버가 포트를 바인딩하지 못했습니다. +AM: Data from Unknown Port = AM: 알 수 없는 포트의 데이터 +Auto = 자동 +Bottom Center = 하단 중앙 +Bottom Left = 하단 왼쪽 +Bottom Right = 하단 오른쪽 +Center Left = 중앙 왼쪽 +Center Right = 중앙 오른쪽 +Change Mac Address = MAC 주소 변경 +ChangeMacSaveConfirm = 새로운 MAC 주소를 생성하시겠습니까? +ChangeMacSaveWarning = 일부 게임은 저장 데이터를 불러올 때 MAC 주소를 확인하므로 이전 저장이 손상될 수 있습니다. +Change proAdhocServer Address = PRO ad hoc 서버 IP 주소 변경 (로컬호스트 = 다중 인스턴스) +Chat = 채팅 +Chat Button Position = 채팅 버튼 위치 +Chat Here = 여기에서 채팅 +Chat message = 채팅 메세지 +Chat Screen Position = 채팅 화면 위치 +Disconnected from AdhocServer = Ad Hoc 서버에서 연결 해제됨 +DNS Error Resolving = DNS 오류 해결 +Enable built-in PRO Adhoc Server = 내장 PRO Ad Hoc 서버 활성화 +Enable network chat = 네트워크 채팅 활성화 +Enable networking = 네트워킹/무선랜 활성화 (베타, 게임이 중단될 수 있음) +Enable UPnP = UPnP 활성화 (감지하는 데 몇 초 필요) +EnableQuickChat = 빠른 채팅 활성화 Enter a new PSP nickname = 새로운 PSP 별명 입력 -Enter Quick Chat 1 = 빠른 대화 1 참가 -Enter Quick Chat 2 = 빠른 대화 2 참가 -Enter Quick Chat 3 = 빠른 대화 3 참가 -Enter Quick Chat 4 = 빠른 대화 4 참가 -Enter Quick Chat 5 = 빠른 대화 5 참가 -Error = Error -Failed to Bind Localhost IP = Failed to bind localhost IP -Failed to Bind Port = Failed to bind port -Failed to connect to Adhoc Server = Failed to connect to ad hoc server -Forced First Connect = Forced first connect (faster connect) -GM: Data from Unknown Port = GM: Data from Unknown Port -Hostname = Hostname -Invalid IP or hostname = 올바르지 않은 IP 또는 호스트 이름 -Minimum Timeout = Minimum timeout (override in ms, 0 = default) -Misc = Miscellaneous (default = PSP compatibility) -Network Initialized = 네트워크 초기화됨 -None = None -Please change your Port Offset = Please change your port offset -Port offset = 포트 오프셋(0 = PSP 호환) -Open PPSSPP Multiplayer Wiki Page = Open PPSSPP Multiplayer Wiki Page -proAdhocServer Address: = Ad hoc server address: -Quick Chat 1 = 빠른 대화 1 -Quick Chat 2 = 빠른 대화 2 -Quick Chat 3 = 빠른 대화 3 -Quick Chat 4 = 빠른 대화 4 -Quick Chat 5 = 빠른 대화 5 -QuickChat = 빠른 대화 +Enter Quick Chat 1 = 빠른 채팅 1 입력 +Enter Quick Chat 2 = 빠른 채팅 2 입력 +Enter Quick Chat 3 = 빠른 채팅 3 입력 +Enter Quick Chat 4 = 빠른 채팅 4 입력 +Enter Quick Chat 5 = 빠른 채팅 5 입력 +Error = 오류 +Failed to Bind Localhost IP = 로컬 호스트 IP를 바인딩하지 못했습니다. +Failed to Bind Port = 포트를 바인딩하지 못했습니다. +Failed to connect to Adhoc Server = Ad Hoc 서버에 연결하지 못했습니다. +Forced First Connect = 강제 첫 번째 연결 (빠른 연결) +GM: Data from Unknown Port = GM: 알 수 없는 포트의 데이터 +Hostname = 호스트 이름 +Invalid IP or hostname = 잘못된 IP 또는 호스트 이름 +Minimum Timeout = 최소 시간 초과 (ms 단위로 재정의, 0 = 기본값) +Misc = 기타 (기본값 = PSP 호환성) +Network Initialized = 네트워크 초기화 +None = 없음 +Please change your Port Offset = 포트 오프셋을 변경하세요. +Port offset = 포트 오프셋 (0 = PSP 호환성) +Open PPSSPP Multiplayer Wiki Page = PPSSPP 멀티플레이어 위키 페이지 열기 +proAdhocServer Address: = Ad hoc 서버 주소: +Quick Chat 1 = 빠른 채팅 1 +Quick Chat 2 = 빠른 채팅 2 +Quick Chat 3 = 빠른 채팅 3 +Quick Chat 4 = 빠른 채팅 4 +Quick Chat 5 = 빠른 채팅 5 +QuickChat = 빠른 채팅 Send = 보내기 -Send Discord Presence information = Discord 프로필에 PPSSPP 표시 -Top Center = Top center -Top Left = Top left -Top Right = Top right -Unable to find UPnP device = Unable to find UPnP device -UPnP (port-forwarding) = UPnP (port forwarding) -UPnP need to be reinitialized = UPnP need to be reinitialized -UPnP use original port = UPnP use original port (enabled = PSP compatibility) +Send Discord Presence information = 디스코드 "리치 프레즌스" 정보 보내기 +Top Center = 상단 중앙 +Top Left = 상단 왼쪽 +Top Right = 상단 오른쪽 +Unable to find UPnP device = UPnP 장치를 찾을 수 없습니다. +UPnP (port-forwarding) = UPnP (포트 포워딩) +UPnP need to be reinitialized = UPnP를 다시 초기화해야 합니다. +UPnP use original port = UPnP는 원래 포트를 사용합니다 (활성화됨 = PSP 호환성) Validating address... = 주소 검증하는 중... -WLAN Channel = WLAN channel -You're in Offline Mode, go to lobby or online hall = 현재 오프라인 모드입니다. 로비나 온라인 홀로 돌아갑니다. +WLAN Channel = 무선랜 채널 +You're in Offline Mode, go to lobby or online hall = 오프라인 모드입니다. 로비 또는 온라인 홀으로 이동합니다. [Pause] Cheats = 치트 Continue = 계속 -Create Game Config = 게임 설정파일 생성 -Delete Game Config = 게임 설정파일 제거 -Exit to menu = 종료 후 메뉴로 +Create Game Config = 게임 구성 생성 +Delete Game Config = 게임 구성 삭제 +Exit to menu = 메뉴로 나가기 Game Settings = 게임 설정 Load State = 상태 불러오기 Rewind = 되감기 Save State = 상태 저장하기 Settings = 설정 Switch UMD = UMD 교체 -Undo last load = Undo last load -Undo last save = Undo last save +Undo last load = 마지막 불러오기 실행 취소 +Undo last save = 마지막 저장 실행 취소 [PostShaders] -(duplicated setting, previous slider will be used) = (duplicated setting, previous slider will be used) -4xHqGLSL = 4배 HQ GLSL (OpenGL 셰이딩 언어) +(duplicated setting, previous slider will be used) = (설정이 중복되면 이전 슬라이더가 사용됩니다.) +4xHqGLSL = 4×HQ GLSL 5xBR = 5xBR 5xBR-lv2 = 5xBR-lv2 -AAColor = AA 색상 -Amount = Amount -Animation speed (0 -> disable) = Animation speed (0 -> disable) +AAColor = AA-색상 +Amount = 양 Black border = 검정 테두리 Bloom = 블룸 Brightness = 밝기 Cartoon = 카툰 -CatmullRom = Bicubic (Catmull-Rom) Upscaler ColorCorrection = 색상 교정 Contrast = 명암 CRT = CRT 스캔라인 -FXAA = FXAA (Fast Approximate Anti-Aliasing) +FXAA = FXAA 안티 에일리어싱 Gamma = 감마 Grayscale = 그레이스케일 Intensity = 강도 InverseColors = 색 반전 -MitchellNetravali = Bicubic (Mitchell-Netravali) Upscaler -Natural = 자연 색상 -NaturalA = 자연 색상 (블러 없음) -Off = 끄기 -Power = Power -PSPColor = PSP color +Natural = 자연스러운 색상 +NaturalA = 자연스러운 색상 (흐림 없음) +Off = 끔 +Power = 전원 +PSPColor = PSP 색상 Saturation = 채도 Scanlines = 스캔라인 (CRT) -Sharpen = 선명하게 -SSAA(Gauss) = 슈퍼샘플링 AA (가우스) +Sharpen = 선명함 +SSAA(Gauss) = 슈퍼샘플 AA (가우스) Tex4xBRZ = 4xBRZ TexMMPX = MMPX -UpscaleSpline36 = 스플라인36 확대 -VideoSmoothingAA = VideoSmoothingAA -Vignette = 비네트 +UpscaleSpline36 = 스플라인36 업스케일러 +VideoSmoothingAA = 비디오 스무딩 AA +Vignette = 비네트 효과 +Animation speed (0 -> disable) = 애니메이션 속도 (0 -> 비활성화) +CatmullRom = 고등차수보간 (카트물-롬) 업스케일러 +MitchellNetravali = 고등차수보간 (미첼-네트라발리) 업스케일러 [PSPCredits] all the forum mods = 모든 포럼 모드 build server = 빌드 서버 Buy Gold = 골드 버전 구매 -check = 최고의 Wii/GC 에뮬 Dolphin 또한 확인하십시오. -CheckOutPPSSPP = 멋진 PSP 에뮬레이터 PPSSPP를 확인해 보십시오: https://www.ppsspp.org/ +check = 또한 최고의 Wii/GC 에뮤인 돌핀도 확인하세요: +CheckOutPPSSPP = 멋진 PSP 에뮬레이터인 PPSSPP를 확인하세요: https://www.ppsspp.org/ contributors = 도움을 주신 분들: -created = 만든이: -Discord = Discord -info1 = PPSSPP는 교육적인 목적으로만 사용할 수 있습니다. -info2 = 설치한 게임의 소유 권리가 분명한지를 확인해 주십시오. -info3 = 해당 게임의 UMD를 소유하거나 디지털로 구매하여 플레이하십시오. -info4 = 해당 게임을 실제 PSP에 존재하는 PSN Store에서 구매해 주십시오. -info5 = PSP는 주식회사 소니의 등록 상표입니다. +created = 만든이 +Discord = 디스코드 +info1 = PPSSPP는 교육 목적으로만 사용됩니다. +info2 = 모든 게임에 대한 권리를 소유하고 있는지 확인하세요. +info3 = UMD를 소유하거나 디지털을 구매하여 플레이합니다. +info4 = 실제 PSP의 PSN 스토어에서 다운로드하십시오. +info5 = PSP는 Sony, Inc.의 상표입니다. iOS builds = iOS 빌드 -license = GPL 2.0+ 라이선스를 따르는 무료 소프트웨어 -list = 호환 목록, 포럼 및 개발 정보 +license = GPL 2.0+에 따른 무료 소프트웨어 +list = 호환성 목록, 포럼 및 개발 정보 PPSSPP Forums = PPSSPP 포럼 Privacy Policy = 개인 정보 정책 Share PPSSPP = PPSSPP 공유 -specialthanks = 특별히 감사드립니다: -specialthanksKeithGalocy = - NVIDIA 로부터 (하드웨어, 지도) -specialthanksMaxim = - 놀라운 Atrac3+ 디코더 지원 +specialthanks = 특별히 감사한 분: +specialthanksKeithGalocy = NVIDIA (하드웨어, 조언) +specialthanksMaxim = 놀라운 Atrac3+ 디코더 작업 testing = 테스트 -this translation by = 번역: -title = 빠르고 휴대성이 높은 PSP 에뮬레이터 -tools = 사용된 무료 도구들: +this translation by = 번역자: +title = 빠르고 휴대 가능한 PSP 에뮬레이터 +tools = 사용된 무료 도구: # Add translators or contributors who translated PPSSPP into your language here. # Add translators1-6 for up to 6 lines of translator credits. # Leave extra lines blank. 4 contributors per line seems to look best. -# It is character-set for keyboard(atlas) -# ㄱㄲㄳㄴㄵㄶㄷㄸㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅃㅄㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎㅏㅐㅑㅒㅓㅔㅕㅖㅗㅛㅜㅠㅡㅣ translators1 = mgaver Hisman_Yosika 오원식 MrGiKILL translators2 = DDinghoya translators3 = translators4 = translators5 = translators6 = -Twitter @PPSSPP_emu = Twitter @PPSSPP_emu -website = 웹 사이트에서 확인하세요: -written = 속도와 이식성을 보장하기 위해 C++로 작성되었습니다. +Twitter @PPSSPP_emu = 트위터 @PPSSPP_emu +website = 웹사이트를 확인하세요: +written = 속도와 이식성을 위해 C++로 작성되었습니다. [RemoteISO] Browse Games = 게임 찾아보기 @@ -926,300 +895,350 @@ Share on PPSSPP startup = PPSSPP 시작시 자동으로 공유하기 Stop Sharing = 공유 끝내기 Stopping.. = 중지하는 중... +[MemStick] +Already contains PSP data = 이미 PSP 데이터가 포함되어 있습니다. +Create or Choose a PSP folder = PSP 폴더 생성 또는 선택 +Current = 현재 +DataCanBeShared = PPSSPP 레귤러/골드 간에 데이터 공유 가능 +DataCannotBeShared = PPSSPP 레귤러/골드 간에 데이터를 공유할 수 없습니다! +DataWillBeLostOnUninstall = 경고! PPSSPP를 제거하면 데이터가 손실됩니다! +DataWillStay = PPSSPP를 제거해도 데이터는 유지됩니다. +Done! = 완료! +EasyUSBAccess = 쉬운 USB 접속 +Failed to move some files! = 일부 파일을 이동하지 못했습니다! +Failed to save config = 구성을 저장하지 못했습니다. +Free space = 여유 공간 +Manually specify PSP folder = 수동으로 PSP 폴더 지정 +MemoryStickDescription = PSP 데이터를 보관할 위치 선택 (메모리 스틱) +Move Data = 데이터 이동 +Selected PSP Data Folder = 선택한 PSP 데이터 폴더 +Skip for now = 일단은 건너뜀 +No data will be changed = 데이터가 변경되지 않습니다. +PPSSPP will restart after the change = 변경 후 PPSSPP가 다시 시작됩니다. +Starting move... = 이동 시작 중... +That folder doesn't work as a memstick folder. = 해당 폴더는 메모리스틱 폴더로 작동하지 않습니다. +USBAccessThrough = Android/data/org.ppsspp.ppsspp/files를 통한 USB 접속 +USBAccessThroughGold = Android/data/org.ppsspp.ppssppgold/files를 통한 USB 접속 +Use App Private Data = 앱 개인 데이터 사용 +Use PSP folder at root of storage = 저장공간 루트에서 PSP 폴더 사용 +Welcome to PPSSPP! = PPSSPP에 오신 것을 환영합니다! +WhatsThis = 이것은 무엇입니까? + +[RemoteISO] +Browse Games = 게임 찾아보기 +Local Server Port = 로컬 서버 포트 +Manual Mode Client = 수동으로 클라이언트 구성 +Remote disc streaming = 원격 디스크 스트리밍 +Remote Port = 원격 포트 +Remote Server = 원격 서버 +Remote Subdirectory = 원격 하위 디렉토리 +RemoteISODesc = "최근" 목록에 있는 게임이 공유됩니다. +RemoteISOLoading = 연결됨, 게임 목록 불러오기 중... +RemoteISOScanning = 검색 중... 서버 장치에서 "게임 공유"를 클릭하세요. +RemoteISOScanningTimeout = 검색 중... 바탕 화면의 방화벽 설정을 확인하세요. +RemoteISOWifi = 참고: 두 장치를 동일한 와이파이 네트워크에 연결하세요. +RemoteISOWinFirewall = 경고: 윈도우즈 방화벽이 공유를 차단하고 있습니다. +Settings = 설정 +Share Games (Server) = 게임 공유하기 (서버) +Share on PPSSPP startup = PPSSPP 시작시 자동으로 공유하기 +Stop Sharing = 공유 끝내기 +Stopping.. = 중지하는 중... + [Reporting] Bad = 나쁨 -FeedbackCRCCalculating = Disc CRC: Calculating... -FeedbackCRCValue = Disc CRC: %1 -FeedbackDelayInfo = 피드백 데이터를 전송 중입니다. -FeedbackDesc = 게임이 어땠나요? 저희에게 알려주십시오! -FeedbackDisabled = 서버에 호환성 문제 보고를 체크해 주십시오. -FeedbackIncludeCRC = 참고: 디스크 CRC를 위해 배터리가 사용될 수 있습니다. -FeedbackIncludeScreen = 스크린샷 포함하기 -FeedbackSubmitDone = 피드백 데이터가 전송되었습니다. -FeedbackSubmitFail = 서버에 피드백을 전송할 수 없었습니다. PPSSPP를 업데이트해 보십시오. -FeedbackThanks = 피드백 고맙습니다! -Gameplay = 게임 플레이 +FeedbackCRCCalculating = 디스크 CRC: 계산 중... +FeedbackCRCValue = 디스크 CRC: %1 +FeedbackDelayInfo = 데이터가 백그라운드에서 제출되고 있습니다. +FeedbackDesc = 에뮬레이션은 어떻습니까? 우리와 커뮤니티에 알려주세요! +FeedbackDisabled = 호환성 서버 보고서를 활성화해야 합니다. +FeedbackIncludeCRC = 참고: 배터리는 디스크 CRC를 보내는 데 사용됩니다. +FeedbackIncludeScreen = 스크린샷 포함 +FeedbackSubmitDone = 데이터가 제출되었습니다. +FeedbackSubmitFail = 서버에 데이터를 제출할 수 없습니다. PPSSPP 업데이트를 시도하세요. +FeedbackThanks = 피드백 주셔서 감사합니다! +Gameplay = 게임플레이 Graphics = 그래픽 Great = 좋음 In-game = 게임 내 -In-game Description = 게임이 실행되었지만 제대로 작동하지 않았습니다 +In-game Description = 게임이 실행되었지만 제대로 작동하지 않았습니다. Menu/Intro = 메뉴/인트로 -Menu/Intro Description = 게임 내에 진입할 수 없었습니다 -Nothing = 전부 -Nothing Description = 전혀 동작하지 않았습니다 -OK = 괜찮음 -Open Browser = 브라우저 열기 -Overall = 평가 -Perfect = 완벽함 -Perfect Description = 게임 전체가 흠 없이 매끄럽게 작동했습니다 - 대박! -Plays = 플레이 중 -Plays Description = 게임을 즐길 수는 있지만 문제가 있을 수 있습니다 -ReportButton = 피드백 남기기 -Show disc CRC = Show disc CRC +Menu/Intro Description = 게임 자체에 참여할 수 없음 +Nothing = 아무것도 없음 +Nothing Description = 완전히 파손됨 +OK = 확인 +Open Browser = 보고 웹사이트 열기 +Overall = 전체 +Perfect = 완벽 +Perfect Description = 전체 게임을 위한 완벽한 에뮬레이션 - 훌륭함! +Plays = 게임 중 +Plays Description = 완전히 재생할 수 있지만 결함이 있을 수 있음 +ReportButton = 피드백 보고 +Show disc CRC = 디스크 CRC 표시 Speed = 속도 Submit Feedback = 피드백 전송 -SuggestionConfig = 적합한 설정을 위해 웹사이트에 올라온 보고서들을 확인해 보십시오. -SuggestionCPUSpeed0 = 잠긴 CPU 설정을 비활성화해 주십시오. -SuggestionDowngrade = 구 버전의 PPSSPP로 내려보십시오. (그리고 이 버그를 신고해 주십시오). -SuggestionsFound = 다른 유저들이 더 나은 결과를 보고했습니다. 피드백 보기를 눌러 확인해 주십시오. -SuggestionsNone = 다른 유저들도 이 게임이 제대로 작동하지 않았습니다. -SuggestionsWaiting = 전송 및 다른 유저의 보고서 확인 중... -SuggestionUpgrade = 새로운 PPSSPP 버전으로 업데이트 하십시오. -SuggestionVerifyDisc = ISO 파일이 제대로 디스크로부터 복사되었는지 확인해 보십시오. -Unselected Overall Description = 이 게임이 얼마만큼 잘 작동했나요? +SuggestionConfig = 좋은 설정은 웹사이트의 보고서를 참조하세요. +SuggestionCPUSpeed0 = 잠긴 CPU 속도 설정을 비활성화합니다. +SuggestionDowngrade = 이전 PPSSPP 버전으로 다운그레이드합니다 (이 버그를 보고하세요). +SuggestionsFound = 다른 사용자가 더 나은 결과를 보고했습니다. 자세한 내용은 "피드백 보기"를 탭하세요. +SuggestionsNone = 이 게임은 다른 사용자에게도 작동하지 않습니다. +SuggestionsWaiting = 다른 사용자 의견 제출 및 확인 중... +SuggestionUpgrade = 최신 PPSSPP 빌드로 업그레이드하세요. +SuggestionVerifyDisc = ISO가 제대로 디스크로부터 복사되었는지 확인하세요. +Unselected Overall Description = 이 게임은 얼마나 잘 에뮬레이트하나요? View Feedback = 모든 피드백 보기 [Savedata] Date = 날짜 -Filename = 파일 이름 +Filename = 파일이름 No screenshot = 스크린샷 없음 -None yet. Things will appear here after you save. = 아직 없음. 저장하면 나타납니다. -Nothing matching '%1' was found. = Nothing matching '%1' was found. +None yet. Things will appear here after you save. = 아직 없습니다. 저장하면 여기에 항목이 표시됩니다. +Nothing matching '%1' was found. = '%1'과(와) 일치하는 항목이 없습니다. Save Data = 저장 데이터 Save States = 상태 저장 -Savedata Manager = 저장 데이터 관리자 -Showing matches for '%1'. = Showing matches for '%1'. +Savedata Manager = 저장데이터 관리자 +Showing matches for '%1'. = '%1'에 대한 일치 항목을 표시합니다. Size = 크기 [Screen] -Cardboard VR OFF = 구글 카드보드 끄기 -Chainfire3DWarning = 경고: 체인파이어 3D가 검출되었습니다. 문제가 발생할 수 있습니다. -Failed to load state = 상태 불러오기에 실패했습니다 -Failed to save state = 상태 저장에 실패했습니다 -fixed = 속도: 고정 -GLToolsWarning = 경고: GLTools가 감지되었습니다. 문제가 발생할 수 있습니다. +Cardboard VR OFF = 카드보드 VR off +Chainfire3DWarning = 경고: Chainfire3D가 감지되어 문제를 일으킬 수 있습니다. +Failed to load state = 상태를 불러오지 못함 +Failed to save state = 상태를 저장하지 못함 +fixed = 속도: 대체 +GLToolsWarning = 경고: GLTools가 감지되어 문제를 일으킬 수 있습니다. In menu = 메뉴 -Load savestate failed = 상태 불러오기 실패 -Loaded State = 상태 불러옴 -Loaded. Game may refuse to save over different savedata. = Loaded. Game may refuse to save over different savedata. -Loaded. Game may refuse to save over newer savedata. = Loaded. Game may refuse to save over newer savedata. -Loaded. Save in game, restart, and load for less bugs. = 불러왔습니다. 게임을 저장한 다음 재시작하면 적은 버그로 로드됩니다. -LoadStateDoesntExist = 상태를 불러오지 못했습니다: 상태 저장이 존재하지 않습니다! -LoadStateWrongVersion = 상태를 불러오지 못했습니다: 구 버전의 상태 저장입니다! -norewind = 되감기 저장 상태가 없습니다. -Playing = 실행 -PressESC = ESC를 누르면 중지 메뉴가 열립니다. -replaceTextures_false = 텍스처가 더 이상 대체되지 않습니다. +Load savestate failed = 저장 상태 불러오기 실패 +Loaded State = 불러온 상태 +Loaded. Save in game, restart, and load for less bugs. = 불러왔습니다. 버그를 줄이기 위해 게임을 저장하고 다시 시작하고 불러오세요. +Loaded. Game may refuse to save over different savedata. = 불러왔습니다. 게임이 다른 저장 데이터에 대한 저장을 거부할 수 있습니다. +Loaded. Game may refuse to save over newer savedata. = 불러왔습니다. 게임이 최신 저장 데이터에 대한 저장을 거부할 수 있습니다. +LoadStateDoesntExist = 상태 불러오기 실패: 저장상태가 존재하지 않습니다! +LoadStateWrongVersion = 상태 불러오기 실패: 저장상태는 이전 버전의 PPSSPP용입니다! +norewind = 되감기 저장 상태를 사용할 수 없습니다. +Playing = 게임 중 +PressESC = 일시 중지 메뉴를 열려면 ESC를 누르세요. +replaceTextures_false = 텍스처가 더 이상 교체되지 않습니다. replaceTextures_true = 텍스처 교체가 활성화되었습니다. -Save State Failed = 상태를 저장하지 못했습니다! -Saved State = 상태 저장됨 +Save State Failed = 상태 저장 실패! +Saved State = 저장된 상태 saveNewTextures_false = 텍스처 저장이 비활성화되었습니다. -saveNewTextures_true = 텍스처가 이제 저장 공간에 저장됩니다. -SpeedCustom2 = 속도: 고정 속도 2 +saveNewTextures_true = 이제 텍스처가 저장 공간에 저장됩니다. +SpeedCustom2 = Speed: 대체 2 standard = 속도: 표준 -State load undone = State load undone -Untitled PSP game = 이름 없는 PSP 게임 - -[Search] -Clear filter = Clear filter -Filter = Filter -Filtering settings by '%1' = Filtering settings by '%1' -Find settings = Find settings -No settings matched '%1' = No settings matched '%1' +State load undone = 상태 불러오기 취소 +Untitled PSP game = 제목 없는 PSP 게임 [Store] -Already Installed = 이미 설치되어 있습니다 +Already Installed = 이미 설치됨 Connection Error = 연결 오류 Install = 설치 Launch Game = 게임 실행 -Loading... = 불러오는 중... +Loading... = 로딩 중... MB = MB Size = 크기 Uninstall = 제거 [SysInfo] -%d (%d per core, %d cores) = %d (코어 당 %d, 코어 %d개) +%d (%d per core, %d cores) = %d (코어 당 %d, 코어 %d 개) %d bytes = %d 바이트 (none detected) = (감지되지 않음) 3D API = 3D API ABI = ABI API Version = API 버전 Audio Information = 오디오 정보 -Board = Board -Build Config = 빌드 설정 -Build Configuration = 빌드 설정 -Built by = 빌드 실행자 +Board = 보드 +Build Config = 빌드 구성 +Build Configuration = 빌드 구성 +Built by = 빌더 Core Context = 코어 컨텍스트 Cores = 코어 CPU Extensions = CPU 확장 CPU Information = CPU 정보 CPU Name = 이름 -D3DCompiler Version = D3DCompiler 버전 +D3DCompiler Version = D3D컴파일러 버전 Debug = 디버그 -Debugger Present = 디버거 표시 +Debugger Present = 디버거 탐지 Device Info = 장치 정보 -Directories = Directories -Display Color Formats = Display Color Formats -Display Information = 디스플레이 정보 -Driver bugs = Driver bugs +Directories = 디렉토리 +Display Information = 정보 표시 +Driver bugs = 드라이버 버그 Driver Version = 드라이버 버전 EGL Extensions = EGL 확장 Frames per buffer = 버퍼당 프레임 GPU Information = GPU 정보 -High precision float range = High precision float range -High precision int range = 정밀한 정수 범위 +High precision float range = 고정밀 부동소수점 범위 +High precision int range = 고정밀 정수 범위 Lang/Region = 언어/지역 Memory Page Size = 메모리 페이지 크기 Native Resolution = 기본 해상도 -No GPU driver bugs detected = No GPU driver bugs detected +No GPU driver bugs detected = GPU 드라이버 버그가 감지되지 않았음 OGL Extensions = OGL 확장 OpenGL ES 2.0 Extensions = OpenGL ES 2.0 확장 OpenGL ES 3.0 Extensions = OpenGL ES 3.0 확장 OpenGL Extensions = OpenGL 확장 Optimal frames per buffer = 버퍼당 최적 프레임 -Optimal sample rate = 최적 샘플 속도 +Optimal sample rate = 최적의 샘플 속도 OS Information = OS 정보 PPSSPP build = PPSSPP 빌드 Refresh rate = 주사율 -Release = 출시 -RW/RX exclusive = RW/RX 독점 +Release = 개정 +RW/RX exclusive = RW/RX 전용 Sample rate = 샘플 속도 -Shading Language = 셰이딩 언어 -Storage = Storage +Shading Language = 쉐이딩 언어 +Storage = 저장소 Sustained perf mode = 지속 성능 모드 System Information = 시스템 정보 -System Name = 시스템 이름 +System Name = 이름 System Version = 시스템 버전 Threads = 스레드 -Vendor = 공급 업체 -Vendor (detected) = 공급 업체 (감지됨) +Vendor = 공급업체 +Vendor (detected) = 공급업체 (탐지됨) Version Information = 버전 정보 -Vulkan Extensions = 벌칸 확장 -Vulkan Features = 벌칸 기능 +Vulkan Extensions = Vulkan 확장 +Vulkan Features = Vulkan 기능 +Display Color Formats = 디스플레이 색상 형식 [System] -(broken) = (이용 불가) +(broken) = (고장) 12HR = 12시간 24HR = 24시간 Auto = 자동 Auto Load Savestate = 상태 저장 자동 불러오기 -AVI Dump started. = AVI 덤프 시작됨 -AVI Dump stopped. = AVI 덤프 정지됨 -Cache ISO in RAM = ISO 전체를 램에 캐싱 -Change CPU Clock = CPU 클럭 변경 (불안정) -Color Saturation = Color Saturation -Color Tint = Color Tint -Error: load undo state is from a different game = Error: load undo state is from a different game -Failed to load state for load undo. Error in the file system. = Failed to load state for load undo. Error in the file system. -Floating symbols = Floating symbols -Memory Stick folder = 메모리 스틱 폴더 변경 -Memory Stick size = Memory Stick size +AVI Dump started. = AVI 덤프가 시작됨 +AVI Dump stopped. = AVI 덤프가 중지됨 +Cache ISO in RAM = RAM에 전체 ISO 캐시 +Change CPU Clock = 에뮬레이트된 PSP의 CPU 클럭 변경 (불안정) +Memory Stick folder = 메모리 스틱 폴더 +Memory Stick size = 메모리 스틱 크기 Change Nickname = 별명 변경 -ChangingMemstickPath = 게임 저장, 상태 저장, 기타 데이터는 이 폴더에 복사되지 않습니다.\n\n메모리 스틱 폴더를 변경하시겠습니까? -ChangingMemstickPathInvalid = 이 경로는 메모리 스틱 파일을 저장하는데 사용할 수 없습니다. -Cheats = 치트 (실험적, 포럼 참조) +ChangingMemstickPath = 게임 저장, 상태 저장, 기타 데이터는 이 폴더에 복사되지 않습니다.\n\n메모리 스틱 폴더를 변경하겠습니까? +ChangingMemstickPathInvalid = 해당 경로는 메모리 스틱 파일을 저장하는 데 사용할 수 없습니다. +Cheats = 치트 Clear Recent = "최근" 지우기 -Clear Recent Games List = 최근 게임 목록 지우기 -Clear UI background = UI 배경화면 초기화 +Clear Recent Games List = "최근" 목록 지우기 +Clear UI background = UI 배경 지움 Confirmation Button = 확인 버튼 -Date Format = 날짜 표시 방식 +Date Format = 날짜 형식 Day Light Saving = 서머 타임 DDMMYYYY = DDMMYYYY Decrease size = 크기 줄이기 Developer Tools = 개발자 도구 Display Extra Info = 추가 정보 표시 -Display Games on a grid = 그리드에 "게임 탭" 표시 -Display Homebrew on a grid = 그리드에 "홈브류 및 데모 탭" 표시 -Display Recent on a grid = 그리드에 "최근 탭" 표시 +Display Games on a grid = 그리드에 "게임" 표시 +Display Homebrew on a grid = 그리드에 "홈브류 && 데모" 표시 +Display Recent on a grid = 그리드에 "최근" 표시 Dynarec (JIT) = 동적 재컴파일 (JIT) Emulation = 에뮬레이션 Enable Cheats = 치트 활성화 -Enable Compatibility Server Reports = 서버에 호환성 문제를 보고 -Failed to load state. Error in the file system. = 상태 저장을 불러올 수 없었습니다. 파일 시스템에 오류가 있습니다. -Failed to save state. Error in the file system. = 상태 저장을 저장할 수 없었습니다. 파일 시스템에 오류가 있습니다. -Fast (lag on slow storage) = 빠름 (느린 저장 장치에서 지연 발생) +Enable Compatibility Server Reports = 호환성 서버 보고서 활성화 +Error: load undo state is from a different game = 오류: 불러오기 취소 상태는 다른 게임에서 가져옴 +Failed to load state. Error in the file system. = 상태를 불러오지 못했습니다. 파일 시스템에 오류가 있습니다. +Failed to save state. Error in the file system. = 상태를 저장하지 못했습니다. 파일 시스템에 오류가 있습니다. +Failed to load state for load undo. Error in the file system. = 불러오기 실행 취소 상태를 불러오지 못했습니다. 파일 시스템에 오류가 있습니다. +Fast (lag on slow storage) = 빠름 (저속 저장 시 지연) Fast Memory = 빠른 메모리 (불안정) -Force real clock sync (slower, less lag) = 강제 실제 클럭 동기화 (느림, 약간의 지연) -frames, 0:off = 프레임, 0 = 끄기 +Floating symbols = 부동 기호 +Force real clock sync (slower, less lag) = 실제 클럭 동기화 강제 실행(느림, 지연 감소) +frames, 0:off = 프레임, 0 = 끔 Games list settings = 게임 목록 설정 General = 일반 Grid icon size = 그리드 아이콘 크기 Help the PPSSPP team = PPSSPP 팀 돕기 -Host (bugs, less lag) = 호스트 (버그, 약간의 지연) -Ignore bad memory accesses = Ignore bad memory accesses -Increase size = 크기 늘리기 +Host (bugs, less lag) = 호스트 (버그, 지연 감소) +Ignore bad memory accesses = 잘못된 메모리 접속 무시 +Increase size = 크기 증가 Interpreter = 해석기 -IO timing method = I/O 타이밍 방법 -IR Interpreter = IR 인터프리터 +IO timing method = I/O 타이밍 방식 +IR Interpreter = IR 해석기 Memory Stick Folder = 메모리 스틱 폴더 -Memory Stick inserted = 메모리 스틱 삽입됨 -MHz, 0:default = MHz, 0 = 기본 값 +Memory Stick inserted = 메모리 스틱 삽입 +MHz, 0:default = MHz, 0 = 기본 MMDDYYYY = MMDDYYYY -Moving background = Moving background -Newest Save = 제일 새로운 저장 -No animation = No animation +Moving background = 움직이는 배경 +Newest Save = 가장 최신 저장 +No animation = 애니메이션 없음 Not a PSP game = PSP 게임이 아님 -Off = 끄기 -Oldest Save = 제일 오래된 저장 -Path does not exist! = Path does not exist! -PSP Memory Stick = PSP Memory Stick -PSP Model = PSP 기종 +Off = 끔 +Oldest Save = 가장 오래된 저장 +Path does not exist! = 경로가 존재하지 않습니다! +PSP Memory Stick = PSP 메모리 스틱 +PSP Model = PSP 모델 PSP Settings = PSP 설정 PSP-1000 = PSP-1000 PSP-2000/3000 = PSP-2000/3000 -Recent games = Recent games -Record Audio = 소리 녹음하기 -Record Display = 영상 녹화하기 -Reset Recording on Save/Load State = 저장/불러올 때 기록된 것을 재설정하기 -Restore Default Settings = PPSSPP의 설정을 기본으로 복원 -Rewind Snapshot Frequency = 스냅샷 주기 되감기 (mem hog) -Save path in installed.txt = 경로를 installed.txt에 저장 -Save path in My Documents = 경로를 내 문서에 저장 -Savestate Slot = 상태 저장 슬롯 -Savestate slot backups = 상태 저장 백업 -Screenshots as PNG = PNG 형식으로 스크린샷 저장 -Set UI background... = UI 배경화면 지정하기... -Show ID = ID 보기 -Show Memory Stick folder = Show Memory Stick folder -Show region flag = 지역코드 플래그 보기 +Recent games = 최근 게임 +Record Audio = 오디오 녹음 +Record Display = 녹화 표시 +Reset Recording on Save/Load State = 저장/불러오기 상태에서 녹화 재설정 +Restore Default Settings = PPSSPP의 설정을 기본값으로 복원 +Rewind Snapshot Frequency = 되감기 스냅샷 빈도 (메모리 호그) +Save path in installed.txt = install.txt에 경로 저장 +Save path in My Documents = 내 문서에 경로 저장 +Savestate Slot = 저장 상태 슬롯 +Savestate slot backups = 저장 상태 슬롯 백업 +Screenshots as PNG = 스크린샷을 PNG 형식으로 저장 +Set UI background... = UI 배경 설정... +Show ID = ID 표시 +Show region flag = 지역 플래그 표시 Simulate UMD delays = UMD 지연 시뮬레이션 Slot 1 = 슬롯 1 Slot 2 = 슬롯 2 Slot 3 = 슬롯 3 Slot 4 = 슬롯 4 Slot 5 = 슬롯 5 -Storage full = 저장 공간 가득참 +Storage full = 저장 공간 가득 참 Sustained performance mode = 지속 성능 모드 -Theme = Theme -Time Format = 시간 표시 방식 -UI = 사용자 인터페이스 -UI background animation = UI background animation -UI Sound = UI sound +Time Format = 시간 형식 +UI = UI +UI Sound = UI 사운드 +UI background animation = UI 배경 애니메이션 undo %c = %c 백업 USB = USB Use Lossless Video Codec (FFV1) = 무손실 비디오 코덱 사용 (FFV1) -Use O to confirm = 확인 버튼으로 O 사용 -Use output buffer (with overlay) for recording = 기록에 출력 버퍼(오버레이 포함) 사용 +Use O to confirm = O를 확인 버튼으로 사용 +Use output buffer (with overlay) for recording = 기록을 위해 (오버레이가 있는) 출력 버퍼 사용 Use system native keyboard = 시스템 기본 키보드 사용 -Use X to confirm = 확인 버튼으로 X 사용 -VersionCheck = PPSSPP의 새로운 버전을 확인 -WARNING: Android battery save mode is on = 주의: 안드로이드 배터리 절약 모드가 켜짐 -WARNING: Battery save mode is on = 주의: 배터리 절약 모드가 켜짐 -Waves = Waves +Use X to confirm = X를 확인 버튼으로 사용 +VersionCheck = PPSSPP의 새 버전 확인 +WARNING: Android battery save mode is on = 경고: 안드로이드 배터리 절약 모드가 켜져 있음 +WARNING: Battery save mode is on = 경고: 배터리 절약 모드가 켜져 있음 +Waves = 파형 YYYYMMDD = YYYYMMDD - -[TextureShaders] -Off = Off -TexMMPX = TexMMPX -Tex2xBRZ = Tex2xBRZ -Tex4xBRZ = Tex4xBRZ +Theme = 테마 +Color Tint = 색조 +Color Saturation = 채도 +Show Memory Stick folder = 메모리 스틱 폴더 표시 [Themes] -Default = Default +Default = 기본 + +[TextureShaders] +Off = 끔 +TexMMPX = TexMMPX +Tex2xBRZ = Tex2xBRZ +Tex4xBRZ = Tex4xBRZ + +[Search] +No settings matched '%1' = '%1'과(와) 일치하는 설정이 없음 +Filtering settings by '%1' = '%1'(으)로 설정 필터링 +Find settings = 찾기 설정 +Filter = 필터 +Clear filter = 필터 지움 -[UI Elements] -%1 button = %1 button -%1 checkbox = %1 checkbox -%1 choice = %1 choice -%1 heading = %1 heading -%1 radio button = %1 radio button -%1 text field = %1 text field -Choices: = Choices: -List: = List: -Progress: %1% = Progress: %1% -Screen representation = Screen representation [Upgrade] -Details = Details +Details = 상세 Dismiss = 거절 Download = 다운로드 -New version of PPSSPP available = 새로운 버전의 PPSSPP를 이용할 수 있습니다. +New version of PPSSPP available = PPSSPP의 새 버전 사용 가능 + +[UI Elements] +%1 button = %1 버튼 +%1 checkbox = %1 체크박스 +%1 choice = %1 선택 +%1 heading = %1 제목 +%1 radio button = %1 라디오 버튼 +%1 text field = %1 텍스트 필드 +Choices: = 선택: +List: = 목록: +Progress: %1% = 진행율: %1% +Screen representation = 화면 표현 diff --git a/headless/Compare.cpp b/headless/Compare.cpp index 890ff6cc6a..f5127e5ee0 100644 --- a/headless/Compare.cpp +++ b/headless/Compare.cpp @@ -326,7 +326,7 @@ std::vector TranslateDebugBufferToCompare(const GPUDebugBuffer *buffer, u32 int outStride = buffer->GetStride(); if (!buffer->GetFlipped()) { // Bitmaps are flipped, so we have to compare backwards in this case. - int toLastRow = outStride * (buffer->GetHeight() - 1); + int toLastRow = outStride * (h > buffer->GetHeight() ? buffer->GetHeight() - 1 : h - 1); pixels32 += toLastRow; pixels16 += toLastRow; outStride = -outStride; diff --git a/headless/Headless.cpp b/headless/Headless.cpp index bb8a0225b7..cad0c9fb20 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -416,6 +416,7 @@ int main(int argc, const char* argv[]) g_Config.bEnableLogging = fullLog; g_Config.bSoftwareSkinning = true; g_Config.bVertexDecoderJit = true; + g_Config.bSoftwareRendering = coreParameter.gpuCore == GPUCORE_SOFTWARE; g_Config.bSoftwareRenderingJit = true; g_Config.bBlockTransferGPU = true; g_Config.iSplineBezierQuality = 2; diff --git a/libretro/Makefile.common b/libretro/Makefile.common index 183afdf060..6e5a9726cb 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -327,7 +327,7 @@ SOURCES_CXX += \ $(GPUCOMMONDIR)/ShaderCommon.cpp \ $(GPUCOMMONDIR)/ShaderUniforms.cpp \ $(GPUCOMMONDIR)/GPUDebugInterface.cpp \ - $(GPUCOMMONDIR)/DepalettizeCommon.cpp \ + $(GPUCOMMONDIR)/TextureShaderCommon.cpp \ $(GPUCOMMONDIR)/DepalettizeShaderCommon.cpp \ $(GPUCOMMONDIR)/TransformCommon.cpp \ $(GPUCOMMONDIR)/IndexGenerator.cpp \ diff --git a/unittest/TestShaderGenerators.cpp b/unittest/TestShaderGenerators.cpp index 19b0b0d2e9..0b87831536 100644 --- a/unittest/TestShaderGenerators.cpp +++ b/unittest/TestShaderGenerators.cpp @@ -180,27 +180,6 @@ bool TestReinterpretShaders() { // Generate all despite failures - it's only 6. bool failed = false; - for (int k = 0; k < ARRAY_SIZE(languages); k++) { - printf("=== %s ===\n\n", ShaderLanguageToString(languages[k])); - - ShaderLanguageDesc desc(languages[k]); - - // These require bitwise operations. - if (!desc.bitwiseOps) { - continue; - } - - GenerateReinterpretVertexShader(buffer, desc); - std::string errorMessage; - if (!TestCompileShader(buffer, languages[k], ShaderStage::Vertex, &errorMessage)) { - printf("Error compiling fragment shader:\n\n%s\n\n%s\n", LineNumberString(buffer).c_str(), errorMessage.c_str()); - failed = true; - return false; - } else { - //printf("===\n%s\n===\n", buffer); - } - } - for (int k = 0; k < ARRAY_SIZE(languages); k++) { printf("=== %s ===\n\n", ShaderLanguageToString(languages[k])); @@ -217,7 +196,8 @@ bool TestReinterpretShaders() { for (int j = 0; j < 3; j++) { if (i == j) continue; // useless shader! - GenerateReinterpretFragmentShader(buffer, fmts[i], fmts[j], desc); + ShaderWriter writer(buffer, desc, ShaderStage::Fragment, nullptr, 0); + GenerateReinterpretFragmentShader(writer, fmts[i], fmts[j]); if (!TestCompileShader(buffer, languages[k], ShaderStage::Fragment, &errorMessage)) { printf("Error compiling fragment shader %d:\n\n%s\n\n%s\n", (int)j, LineNumberString(buffer).c_str(), errorMessage.c_str()); failed = true; @@ -309,9 +289,11 @@ bool TestDepalShaders() { config.shift = 8; config.startPos = 64; config.mask = 0xFF; - config.pixelFormat = GE_FORMAT_8888; + config.bufferFormat = GE_FORMAT_8888; + config.textureFormat = GE_TFMT_CLUT32; - GenerateDepalFs(buffer, config, desc); + ShaderWriter writer(buffer, desc, ShaderStage::Fragment); + GenerateDepalFs(writer, config); if (!TestCompileShader(buffer, languages[k], ShaderStage::Fragment, &errorMessage)) { printf("Error compiling depal shader:\n\n%s\n\n%s\n", LineNumberString(buffer).c_str(), errorMessage.c_str()); failed = true; @@ -319,15 +301,6 @@ bool TestDepalShaders() { } else { printf("===\n%s\n===\n", buffer); } - - GenerateDepalVs(buffer, desc); - if (!TestCompileShader(buffer, languages[k], ShaderStage::Vertex, &errorMessage)) { - printf("Error compiling depal shader:\n\n%s\n\n%s\n", LineNumberString(buffer).c_str(), errorMessage.c_str()); - failed = true; - return false; - } else { - printf("===\n%s\n===\n", buffer); - } } delete[] buffer;