Misc: Replace log printf calls with fmt

This commit is contained in:
Stenzek 2024-05-23 20:20:16 +10:00
parent 49b2e76dea
commit b6d019db66
No known key found for this signature in database
117 changed files with 1585 additions and 1615 deletions

View File

@ -43,6 +43,7 @@ BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true BreakStringLiterals: true
BreakAfterAttributes: Leave
ColumnLimit: 120 ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:' CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false CompactNamespaces: false

View File

@ -283,17 +283,11 @@ public:
#if defined(_WIN32) #if defined(_WIN32)
// delete the temporary file // delete the temporary file
if (!DeleteFileW(FileSystem::GetWin32Path(m_temporaryFileName).c_str())) if (!DeleteFileW(FileSystem::GetWin32Path(m_temporaryFileName).c_str()))
{ Log_WarningFmt("Failed to delete temporary file '{}'", m_temporaryFileName);
Log_WarningPrintf(
"AtomicUpdatedFileByteStream::~AtomicUpdatedFileByteStream(): Failed to delete temporary file '%s'",
m_temporaryFileName.c_str());
}
#else #else
// delete the temporary file // delete the temporary file
if (remove(m_temporaryFileName.c_str()) < 0) if (remove(m_temporaryFileName.c_str()) < 0)
Log_WarningPrintf( Log_WarningFmt("Failed to delete temporary file '{}'", m_temporaryFileName);
"AtomicUpdatedFileByteStream::~AtomicUpdatedFileByteStream(): Failed to delete temporary file '%s'",
m_temporaryFileName.c_str());
#endif #endif
} }
else if (!m_committed) else if (!m_committed)
@ -317,8 +311,7 @@ public:
if (!MoveFileExW(FileSystem::GetWin32Path(m_temporaryFileName).c_str(), if (!MoveFileExW(FileSystem::GetWin32Path(m_temporaryFileName).c_str(),
FileSystem::GetWin32Path(m_originalFileName).c_str(), MOVEFILE_REPLACE_EXISTING)) FileSystem::GetWin32Path(m_originalFileName).c_str(), MOVEFILE_REPLACE_EXISTING))
{ {
Log_WarningPrintf("AtomicUpdatedFileByteStream::Commit(): Failed to rename temporary file '%s' to '%s'", Log_WarningFmt("Failed to rename temporary file '{}' to '{}'", m_temporaryFileName, m_originalFileName);
m_temporaryFileName.c_str(), m_originalFileName.c_str());
m_discarded = true; m_discarded = true;
} }
else else
@ -329,8 +322,7 @@ public:
// move the atomic file name to the original file name // move the atomic file name to the original file name
if (rename(m_temporaryFileName.c_str(), m_originalFileName.c_str()) < 0) if (rename(m_temporaryFileName.c_str(), m_originalFileName.c_str()) < 0)
{ {
Log_WarningPrintf("AtomicUpdatedFileByteStream::Commit(): Failed to rename temporary file '%s' to '%s'", Log_WarningFmt("Failed to rename temporary file '{}' to '{}'", m_temporaryFileName, m_originalFileName);
m_temporaryFileName.c_str(), m_originalFileName.c_str());
m_discarded = true; m_discarded = true;
} }
else else

View File

@ -1766,11 +1766,9 @@ bool FileSystem::RenamePath(const char* old_path, const char* new_path, Error* e
const std::wstring old_wpath = GetWin32Path(old_path); const std::wstring old_wpath = GetWin32Path(old_path);
const std::wstring new_wpath = GetWin32Path(new_path); const std::wstring new_wpath = GetWin32Path(new_path);
if (!MoveFileExW(old_wpath.c_str(), new_wpath.c_str(), MOVEFILE_REPLACE_EXISTING)) if (!MoveFileExW(old_wpath.c_str(), new_wpath.c_str(), MOVEFILE_REPLACE_EXISTING)) [[unlikely]]
{ {
const DWORD err = GetLastError(); Error::SetWin32(error, "MoveFileExW() failed: ", GetLastError());
Error::SetWin32(error, "MoveFileExW() failed: ", err);
Log_ErrorPrintf("MoveFileEx('%s', '%s') failed: %08X", old_path, new_path, err);
return false; return false;
} }
@ -2289,7 +2287,6 @@ bool FileSystem::RenamePath(const char* old_path, const char* new_path, Error* e
{ {
const int err = errno; const int err = errno;
Error::SetErrno(error, "rename() failed: ", err); Error::SetErrno(error, "rename() failed: ", err);
Log_ErrorPrintf("rename('%s', '%s') failed: %d", old_path, new_path, err);
return false; return false;
} }
@ -2410,13 +2407,13 @@ static bool SetLock(int fd, bool lock)
const off_t offs = lseek(fd, 0, SEEK_CUR); const off_t offs = lseek(fd, 0, SEEK_CUR);
if (offs < 0) if (offs < 0)
{ {
Log_ErrorPrintf("lseek(%d) failed: %d", fd, errno); Log_ErrorFmt("lseek({}) failed: {}", fd, errno);
return false; return false;
} }
if (offs != 0 && lseek(fd, 0, SEEK_SET) < 0) if (offs != 0 && lseek(fd, 0, SEEK_SET) < 0)
{ {
Log_ErrorPrintf("lseek(%d, 0) failed: %d", fd, errno); Log_ErrorFmt("lseek({}, 0) failed: {}", fd, errno);
return false; return false;
} }
@ -2425,7 +2422,7 @@ static bool SetLock(int fd, bool lock)
Panic("Repositioning file descriptor after lock failed."); Panic("Repositioning file descriptor after lock failed.");
if (!res) if (!res)
Log_ErrorPrintf("lockf() for %s failed: %d", lock ? "lock" : "unlock", errno); Log_ErrorFmt("lockf() for {} failed: {}", lock ? "lock" : "unlock", errno);
return res; return res;
} }

View File

@ -17,11 +17,11 @@ enum LOGLEVEL
LOGLEVEL_NONE = 0, // Silences all log traffic LOGLEVEL_NONE = 0, // Silences all log traffic
LOGLEVEL_ERROR = 1, // "ErrorPrint" LOGLEVEL_ERROR = 1, // "ErrorPrint"
LOGLEVEL_WARNING = 2, // "WarningPrint" LOGLEVEL_WARNING = 2, // "WarningPrint"
LOGLEVEL_PERF = 3, // "PerfPrint" LOGLEVEL_PERF = 3, // "PerfPrint" // TODO: Purge
LOGLEVEL_INFO = 4, // "InfoPrint" LOGLEVEL_INFO = 4, // "InfoPrint"
LOGLEVEL_VERBOSE = 5, // "VerbosePrint" LOGLEVEL_VERBOSE = 5, // "VerbosePrint"
LOGLEVEL_DEV = 6, // "DevPrint" LOGLEVEL_DEV = 6, // "DevPrint"
LOGLEVEL_PROFILE = 7, // "ProfilePrint" LOGLEVEL_PROFILE = 7, // "ProfilePrint" // TODO: Purge
LOGLEVEL_DEBUG = 8, // "DebugPrint" LOGLEVEL_DEBUG = 8, // "DebugPrint"
LOGLEVEL_TRACE = 9, // "TracePrint" LOGLEVEL_TRACE = 9, // "TracePrint"
LOGLEVEL_COUNT = 10 LOGLEVEL_COUNT = 10

View File

@ -36,7 +36,7 @@ bool MemMap::MemProtect(void* baseaddr, size_t size, PageProtect mode)
DWORD old_protect; DWORD old_protect;
if (!VirtualProtect(baseaddr, size, static_cast<DWORD>(mode), &old_protect)) if (!VirtualProtect(baseaddr, size, static_cast<DWORD>(mode), &old_protect))
{ {
Log_ErrorPrintf("VirtualProtect() failed with error %u", GetLastError()); Log_ErrorFmt("VirtualProtect() failed with error {}", GetLastError());
return false; return false;
} }
@ -205,7 +205,7 @@ u8* SharedMemoryMappingArea::Map(void* file_handle, size_t file_offset, void* ma
if (!MapViewOfFile3(static_cast<HANDLE>(file_handle), GetCurrentProcess(), map_base, file_offset, map_size, if (!MapViewOfFile3(static_cast<HANDLE>(file_handle), GetCurrentProcess(), map_base, file_offset, map_size,
MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0))
{ {
Log_ErrorPrintf("MapViewOfFile3() failed: %u", GetLastError()); Log_ErrorFmt("MapViewOfFile3() failed: {}", GetLastError());
return nullptr; return nullptr;
} }
@ -231,7 +231,7 @@ bool SharedMemoryMappingArea::Unmap(void* map_base, size_t map_size)
// unmap the specified range // unmap the specified range
if (!UnmapViewOfFile2(GetCurrentProcess(), map_base, MEM_PRESERVE_PLACEHOLDER)) if (!UnmapViewOfFile2(GetCurrentProcess(), map_base, MEM_PRESERVE_PLACEHOLDER))
{ {
Log_ErrorPrintf("UnmapViewOfFile2() failed: %u", GetLastError()); Log_ErrorFmt("UnmapViewOfFile2() failed: {}", GetLastError());
return false; return false;
} }
@ -285,9 +285,9 @@ bool MemMap::MemProtect(void* baseaddr, size_t size, PageProtect mode)
DebugAssertMsg((size & (HOST_PAGE_SIZE - 1)) == 0, "Size is page aligned"); DebugAssertMsg((size & (HOST_PAGE_SIZE - 1)) == 0, "Size is page aligned");
const int result = mprotect(baseaddr, size, static_cast<int>(mode)); const int result = mprotect(baseaddr, size, static_cast<int>(mode));
if (result != 0) if (result != 0) [[unlikely]]
{ {
Log_ErrorPrintf("mprotect() for %zu at %p failed", size, baseaddr); Log_ErrorFmt("mprotect() for {} at {} failed", size, baseaddr);
return false; return false;
} }

View File

@ -420,7 +420,7 @@ bool Achievements::Initialize()
std::string api_token = Host::GetBaseStringSettingValue("Cheevos", "Token"); std::string api_token = Host::GetBaseStringSettingValue("Cheevos", "Token");
if (!username.empty() && !api_token.empty()) if (!username.empty() && !api_token.empty())
{ {
Log_InfoPrintf("Attempting login with user '%s'...", username.c_str()); Log_InfoFmt("Attempting login with user '{}'...", username);
s_login_request = rc_client_begin_login_with_token(s_client, username.c_str(), api_token.c_str(), s_login_request = rc_client_begin_login_with_token(s_client, username.c_str(), api_token.c_str(),
ClientLoginWithTokenCallback, nullptr); ClientLoginWithTokenCallback, nullptr);
} }
@ -769,7 +769,7 @@ void Achievements::ClientEventHandler(const rc_client_event_t* event, rc_client_
break; break;
default: default:
Log_ErrorPrintf("Unhandled event: %u", event->type); [[unlikely]] Log_ErrorFmt("Unhandled event: {}", event->type);
break; break;
} }
} }
@ -793,7 +793,7 @@ void Achievements::UpdateRichPresence(std::unique_lock<std::recursive_mutex>& lo
s_rich_presence_string.assign(sv); s_rich_presence_string.assign(sv);
Log_InfoPrintf("Rich presence updated: %s", s_rich_presence_string.c_str()); Log_InfoFmt("Rich presence updated: {}", s_rich_presence_string);
Host::OnAchievementsRefreshed(); Host::OnAchievementsRefreshed();
#ifdef ENABLE_DISCORD_PRESENCE #ifdef ENABLE_DISCORD_PRESENCE
@ -828,7 +828,7 @@ void Achievements::IdentifyGame(const std::string& path, CDImage* image)
temp_image = CDImage::Open(path.c_str(), g_settings.cdrom_load_image_patches, nullptr); temp_image = CDImage::Open(path.c_str(), g_settings.cdrom_load_image_patches, nullptr);
image = temp_image.get(); image = temp_image.get();
if (!temp_image) if (!temp_image)
Log_ErrorPrintf("Failed to open temporary CD image '%s'", path.c_str()); Log_ErrorFmt("Failed to open temporary CD image '{}'", path);
} }
std::string game_hash; std::string game_hash;
@ -838,7 +838,7 @@ void Achievements::IdentifyGame(const std::string& path, CDImage* image)
if (s_game_hash == game_hash) if (s_game_hash == game_hash)
{ {
// only the path has changed - different format/save state/etc. // only the path has changed - different format/save state/etc.
Log_InfoPrintf("Detected path change from '%s' to '%s'", s_game_path.c_str(), path.c_str()); Log_InfoFmt("Detected path change from '{}' to '{}'", s_game_path, path);
s_game_path = path; s_game_path = path;
return; return;
} }
@ -861,7 +861,7 @@ void Achievements::IdentifyGame(const std::string& path, CDImage* image)
// bail out if we're not logged in, just save the hash // bail out if we're not logged in, just save the hash
if (!IsLoggedInOrLoggingIn()) if (!IsLoggedInOrLoggingIn())
{ {
Log_InfoPrintf("Skipping load game because we're not logged in."); Log_InfoPrint("Skipping load game because we're not logged in.");
DisableHardcoreMode(); DisableHardcoreMode();
return; return;
} }
@ -903,7 +903,7 @@ void Achievements::ClientLoadGameCallback(int result, const char* error_message,
if (result == RC_NO_GAME_LOADED) if (result == RC_NO_GAME_LOADED)
{ {
// Unknown game. // Unknown game.
Log_InfoPrintf("Unknown game '%s', disabling achievements.", s_game_hash.c_str()); Log_InfoFmt("Unknown game '%s', disabling achievements.", s_game_hash);
DisableHardcoreMode(); DisableHardcoreMode();
return; return;
} }
@ -1053,7 +1053,7 @@ void Achievements::DisplayHardcoreDeferredMessage()
void Achievements::HandleResetEvent(const rc_client_event_t* event) void Achievements::HandleResetEvent(const rc_client_event_t* event)
{ {
// We handle system resets ourselves, but still need to reset the client's state. // We handle system resets ourselves, but still need to reset the client's state.
Log_InfoPrintf("Resetting runtime due to reset event"); Log_InfoPrint("Resetting runtime due to reset event");
rc_client_reset(s_client); rc_client_reset(s_client);
if (HasActiveGame()) if (HasActiveGame())
@ -1065,7 +1065,7 @@ void Achievements::HandleUnlockEvent(const rc_client_event_t* event)
const rc_client_achievement_t* cheevo = event->achievement; const rc_client_achievement_t* cheevo = event->achievement;
DebugAssert(cheevo); DebugAssert(cheevo);
Log_InfoPrintf("Achievement %s (%u) for game %u unlocked", cheevo->title, cheevo->id, s_game_id); Log_InfoFmt("Achievement {} ({}) for game {} unlocked", cheevo->title, cheevo->id, s_game_id);
UpdateGameSummary(); UpdateGameSummary();
if (g_settings.achievements_notifications && FullscreenUI::Initialize()) if (g_settings.achievements_notifications && FullscreenUI::Initialize())
@ -1089,7 +1089,7 @@ void Achievements::HandleUnlockEvent(const rc_client_event_t* event)
void Achievements::HandleGameCompleteEvent(const rc_client_event_t* event) void Achievements::HandleGameCompleteEvent(const rc_client_event_t* event)
{ {
Log_InfoPrintf("Game %u complete", s_game_id); Log_InfoFmt("Game {} complete", s_game_id);
UpdateGameSummary(); UpdateGameSummary();
if (g_settings.achievements_notifications && FullscreenUI::Initialize()) if (g_settings.achievements_notifications && FullscreenUI::Initialize())
@ -1108,7 +1108,7 @@ void Achievements::HandleGameCompleteEvent(const rc_client_event_t* event)
void Achievements::HandleLeaderboardStartedEvent(const rc_client_event_t* event) void Achievements::HandleLeaderboardStartedEvent(const rc_client_event_t* event)
{ {
Log_DevPrintf("Leaderboard %u (%s) started", event->leaderboard->id, event->leaderboard->title); Log_DevFmt("Leaderboard {} ({}) started", event->leaderboard->id, event->leaderboard->title);
if (g_settings.achievements_leaderboard_notifications && FullscreenUI::Initialize()) if (g_settings.achievements_leaderboard_notifications && FullscreenUI::Initialize())
{ {
@ -1123,7 +1123,7 @@ void Achievements::HandleLeaderboardStartedEvent(const rc_client_event_t* event)
void Achievements::HandleLeaderboardFailedEvent(const rc_client_event_t* event) void Achievements::HandleLeaderboardFailedEvent(const rc_client_event_t* event)
{ {
Log_DevPrintf("Leaderboard %u (%s) failed", event->leaderboard->id, event->leaderboard->title); Log_DevFmt("Leaderboard {} ({}) failed", event->leaderboard->id, event->leaderboard->title);
if (g_settings.achievements_leaderboard_notifications && FullscreenUI::Initialize()) if (g_settings.achievements_leaderboard_notifications && FullscreenUI::Initialize())
{ {
@ -1138,7 +1138,7 @@ void Achievements::HandleLeaderboardFailedEvent(const rc_client_event_t* event)
void Achievements::HandleLeaderboardSubmittedEvent(const rc_client_event_t* event) void Achievements::HandleLeaderboardSubmittedEvent(const rc_client_event_t* event)
{ {
Log_DevPrintf("Leaderboard %u (%s) submitted", event->leaderboard->id, event->leaderboard->title); Log_DevFmt("Leaderboard {} ({}) submitted", event->leaderboard->id, event->leaderboard->title);
if (g_settings.achievements_leaderboard_notifications && FullscreenUI::Initialize()) if (g_settings.achievements_leaderboard_notifications && FullscreenUI::Initialize())
{ {
@ -1167,8 +1167,8 @@ void Achievements::HandleLeaderboardSubmittedEvent(const rc_client_event_t* even
void Achievements::HandleLeaderboardScoreboardEvent(const rc_client_event_t* event) void Achievements::HandleLeaderboardScoreboardEvent(const rc_client_event_t* event)
{ {
Log_DevPrintf("Leaderboard %u scoreboard rank %u of %u", event->leaderboard_scoreboard->leaderboard_id, Log_DevFmt("Leaderboard {} scoreboard rank {} of {}", event->leaderboard_scoreboard->leaderboard_id,
event->leaderboard_scoreboard->new_rank, event->leaderboard_scoreboard->num_entries); event->leaderboard_scoreboard->new_rank, event->leaderboard_scoreboard->num_entries);
if (g_settings.achievements_leaderboard_notifications && FullscreenUI::Initialize()) if (g_settings.achievements_leaderboard_notifications && FullscreenUI::Initialize())
{ {
@ -1195,8 +1195,8 @@ void Achievements::HandleLeaderboardScoreboardEvent(const rc_client_event_t* eve
void Achievements::HandleLeaderboardTrackerShowEvent(const rc_client_event_t* event) void Achievements::HandleLeaderboardTrackerShowEvent(const rc_client_event_t* event)
{ {
Log_DevPrintf("Showing leaderboard tracker: %u: %s", event->leaderboard_tracker->id, Log_DevFmt("Showing leaderboard tracker: {}: {}", event->leaderboard_tracker->id,
event->leaderboard_tracker->display); event->leaderboard_tracker->display);
TinyString width_string; TinyString width_string;
width_string.append(ICON_FA_STOPWATCH); width_string.append(ICON_FA_STOPWATCH);
@ -1219,7 +1219,7 @@ void Achievements::HandleLeaderboardTrackerHideEvent(const rc_client_event_t* ev
if (it == s_active_leaderboard_trackers.end()) if (it == s_active_leaderboard_trackers.end())
return; return;
Log_DevPrintf("Hiding leaderboard tracker: %u", id); Log_DevFmt("Hiding leaderboard tracker: {}", id);
it->active = false; it->active = false;
it->show_hide_time.Reset(); it->show_hide_time.Reset();
} }
@ -1232,8 +1232,8 @@ void Achievements::HandleLeaderboardTrackerUpdateEvent(const rc_client_event_t*
if (it == s_active_leaderboard_trackers.end()) if (it == s_active_leaderboard_trackers.end())
return; return;
Log_DevPrintf("Updating leaderboard tracker: %u: %s", event->leaderboard_tracker->id, Log_DevFmt("Updating leaderboard tracker: {}: {}", event->leaderboard_tracker->id,
event->leaderboard_tracker->display); event->leaderboard_tracker->display);
it->text = event->leaderboard_tracker->display; it->text = event->leaderboard_tracker->display;
it->active = true; it->active = true;
@ -1257,7 +1257,7 @@ void Achievements::HandleAchievementChallengeIndicatorShowEvent(const rc_client_
indicator.active = true; indicator.active = true;
s_active_challenge_indicators.push_back(std::move(indicator)); s_active_challenge_indicators.push_back(std::move(indicator));
Log_DevPrintf("Show challenge indicator for %u (%s)", event->achievement->id, event->achievement->title); Log_DevFmt("Show challenge indicator for {} ({})", event->achievement->id, event->achievement->title);
} }
void Achievements::HandleAchievementChallengeIndicatorHideEvent(const rc_client_event_t* event) void Achievements::HandleAchievementChallengeIndicatorHideEvent(const rc_client_event_t* event)
@ -1268,15 +1268,15 @@ void Achievements::HandleAchievementChallengeIndicatorHideEvent(const rc_client_
if (it == s_active_challenge_indicators.end()) if (it == s_active_challenge_indicators.end())
return; return;
Log_DevPrintf("Hide challenge indicator for %u (%s)", event->achievement->id, event->achievement->title); Log_DevFmt("Hide challenge indicator for {} ({})", event->achievement->id, event->achievement->title);
it->show_hide_time.Reset(); it->show_hide_time.Reset();
it->active = false; it->active = false;
} }
void Achievements::HandleAchievementProgressIndicatorShowEvent(const rc_client_event_t* event) void Achievements::HandleAchievementProgressIndicatorShowEvent(const rc_client_event_t* event)
{ {
Log_DevPrintf("Showing progress indicator: %u (%s): %s", event->achievement->id, event->achievement->title, Log_DevFmt("Showing progress indicator: {} ({}): {}", event->achievement->id, event->achievement->title,
event->achievement->measured_progress); event->achievement->measured_progress);
if (!s_active_progress_indicator.has_value()) if (!s_active_progress_indicator.has_value())
s_active_progress_indicator.emplace(); s_active_progress_indicator.emplace();
@ -1294,15 +1294,15 @@ void Achievements::HandleAchievementProgressIndicatorHideEvent(const rc_client_e
if (!s_active_progress_indicator.has_value()) if (!s_active_progress_indicator.has_value())
return; return;
Log_DevPrintf("Hiding progress indicator"); Log_DevPrint("Hiding progress indicator");
s_active_progress_indicator->show_hide_time.Reset(); s_active_progress_indicator->show_hide_time.Reset();
s_active_progress_indicator->active = false; s_active_progress_indicator->active = false;
} }
void Achievements::HandleAchievementProgressIndicatorUpdateEvent(const rc_client_event_t* event) void Achievements::HandleAchievementProgressIndicatorUpdateEvent(const rc_client_event_t* event)
{ {
Log_DevPrintf("Updating progress indicator: %u (%s): %s", event->achievement->id, event->achievement->title, Log_DevFmt("Updating progress indicator: {} ({}): {}", event->achievement->id, event->achievement->title,
event->achievement->measured_progress); event->achievement->measured_progress);
s_active_progress_indicator->achievement = event->achievement; s_active_progress_indicator->achievement = event->achievement;
s_active_progress_indicator->active = true; s_active_progress_indicator->active = true;
} }
@ -1319,7 +1319,7 @@ void Achievements::HandleServerErrorEvent(const rc_client_event_t* event)
void Achievements::HandleServerDisconnectedEvent(const rc_client_event_t* event) void Achievements::HandleServerDisconnectedEvent(const rc_client_event_t* event)
{ {
Log_WarningPrintf("Server disconnected."); Log_WarningPrint("Server disconnected.");
if (FullscreenUI::Initialize()) if (FullscreenUI::Initialize())
{ {
@ -1333,7 +1333,7 @@ void Achievements::HandleServerDisconnectedEvent(const rc_client_event_t* event)
void Achievements::HandleServerReconnectedEvent(const rc_client_event_t* event) void Achievements::HandleServerReconnectedEvent(const rc_client_event_t* event)
{ {
Log_WarningPrintf("Server reconnected."); Log_WarningPrint("Server reconnected.");
if (FullscreenUI::Initialize()) if (FullscreenUI::Initialize())
{ {
@ -1474,7 +1474,7 @@ bool Achievements::DoState(StateWrapper& sw)
if (data_size == 0) if (data_size == 0)
{ {
// reset runtime, no data (state might've been created without cheevos) // reset runtime, no data (state might've been created without cheevos)
Log_DevPrintf("State is missing cheevos data, resetting runtime"); Log_DevPrint("State is missing cheevos data, resetting runtime");
#ifdef ENABLE_RAINTEGRATION #ifdef ENABLE_RAINTEGRATION
if (IsUsingRAIntegration()) if (IsUsingRAIntegration())
RA_OnReset(); RA_OnReset();
@ -1502,7 +1502,7 @@ bool Achievements::DoState(StateWrapper& sw)
const int result = rc_client_deserialize_progress(s_client, data.get()); const int result = rc_client_deserialize_progress(s_client, data.get());
if (result != RC_OK) if (result != RC_OK)
{ {
Log_WarningPrintf("Failed to deserialize cheevos state (%d), resetting", result); Log_WarningFmt("Failed to deserialize cheevos state ({}), resetting", result);
rc_client_reset(s_client); rc_client_reset(s_client);
} }
} }
@ -1543,7 +1543,7 @@ bool Achievements::DoState(StateWrapper& sw)
if (result != RC_OK) if (result != RC_OK)
{ {
// set data to zero, effectively serializing nothing // set data to zero, effectively serializing nothing
Log_WarningPrintf("Failed to serialize cheevos state (%d)", result); Log_WarningFmt("Failed to serialize cheevos state ({})", result);
data_size = 0; data_size = 0;
} }
} }
@ -1679,7 +1679,7 @@ void Achievements::ClientLoginWithPasswordCallback(int result, const char* error
if (result != RC_OK) if (result != RC_OK)
{ {
Log_ErrorPrintf("Login failed: %s: %s", rc_error_str(result), error_message ? error_message : "Unknown"); Log_ErrorFmt("Login failed: {}: {}", rc_error_str(result), error_message ? error_message : "Unknown");
Error::SetString(params->error, Error::SetString(params->error,
fmt::format("{}: {}", rc_error_str(result), error_message ? error_message : "Unknown")); fmt::format("{}: {}", rc_error_str(result), error_message ? error_message : "Unknown"));
params->result = false; params->result = false;
@ -1959,7 +1959,7 @@ void Achievements::DrawGameOverlays()
if (!indicator.active && opacity <= 0.01f) if (!indicator.active && opacity <= 0.01f)
{ {
Log_DevPrintf("Remove challenge indicator"); Log_DevPrint("Remove challenge indicator");
it = s_active_challenge_indicators.erase(it); it = s_active_challenge_indicators.erase(it);
} }
else else
@ -2003,7 +2003,7 @@ void Achievements::DrawGameOverlays()
if (!indicator.active && opacity <= 0.01f) if (!indicator.active && opacity <= 0.01f)
{ {
Log_DevPrintf("Remove progress indicator"); Log_DevPrint("Remove progress indicator");
s_active_progress_indicator.reset(); s_active_progress_indicator.reset();
} }
@ -2046,7 +2046,7 @@ void Achievements::DrawGameOverlays()
if (!indicator.active && opacity <= 0.01f) if (!indicator.active && opacity <= 0.01f)
{ {
Log_DevPrintf("Remove tracker indicator"); Log_DevPrint("Remove tracker indicator");
it = s_active_leaderboard_trackers.erase(it); it = s_active_leaderboard_trackers.erase(it);
} }
else else
@ -2974,7 +2974,7 @@ void Achievements::DrawLeaderboardListEntry(const rc_client_leaderboard_t* lboar
void Achievements::OpenLeaderboard(const rc_client_leaderboard_t* lboard) void Achievements::OpenLeaderboard(const rc_client_leaderboard_t* lboard)
{ {
Log_DevPrintf("Opening leaderboard '%s' (%u)", lboard->title, lboard->id); Log_DevFmt("Opening leaderboard '{}' ({})", lboard->title, lboard->id);
CloseLeaderboard(); CloseLeaderboard();
@ -3058,7 +3058,7 @@ void Achievements::FetchNextLeaderboardEntries()
for (rc_client_leaderboard_entry_list_t* list : s_leaderboard_entry_lists) for (rc_client_leaderboard_entry_list_t* list : s_leaderboard_entry_lists)
start += list->num_entries; start += list->num_entries;
Log_DevPrintf("Fetching entries %u to %u", start, start + LEADERBOARD_ALL_FETCH_SIZE); Log_DevFmt("Fetching entries {} to {}", start, start + LEADERBOARD_ALL_FETCH_SIZE);
if (s_leaderboard_fetch_handle) if (s_leaderboard_fetch_handle)
rc_client_abort_async(s_client, s_leaderboard_fetch_handle); rc_client_abort_async(s_client, s_leaderboard_fetch_handle);

View File

@ -296,16 +296,15 @@ void AnalogController::SetAnalogMode(bool enabled, bool show_message)
if (m_analog_mode == enabled) if (m_analog_mode == enabled)
return; return;
Log_InfoPrintf("Controller %u switched to %s mode.", m_index + 1u, enabled ? "analog" : "digital"); Log_InfoFmt("Controller {} switched to {} mode.", m_index + 1u, m_analog_mode ? "analog" : "digital");
if (show_message) if (show_message)
{ {
Host::AddIconOSDMessage(fmt::format("Controller{}AnalogMode", m_index), ICON_FA_GAMEPAD, Host::AddIconOSDMessage(
fmt::format(enabled ? fmt::format("analog_mode_toggle_{}", m_index), ICON_FA_GAMEPAD,
TRANSLATE_FS("AnalogController", "Controller {} switched to analog mode.") : enabled ? fmt::format(TRANSLATE_FS("Controller", "Controller {} switched to analog mode."), m_index + 1u) :
TRANSLATE_FS("AnalogController", "Controller {} switched to digital mode."), fmt::format(TRANSLATE_FS("Controller", "Controller {} switched to digital mode."), m_index + 1u));
m_index + 1u),
5.0f);
} }
m_analog_mode = enabled; m_analog_mode = enabled;
} }
@ -433,12 +432,12 @@ bool AnalogController::Transfer(const u8 data_in, u8* data_out)
if (data_in == 0x01) if (data_in == 0x01)
{ {
Log_DebugPrintf("ACK controller access"); Log_DebugPrint("ACK controller access");
m_command = Command::Ready; m_command = Command::Ready;
return true; return true;
} }
Log_DevPrintf("Unknown data_in = 0x%02X", data_in); Log_DevFmt("Unknown data_in = 0x{:02X}", data_in);
return false; return false;
} }
break; break;
@ -509,7 +508,7 @@ bool AnalogController::Transfer(const u8 data_in, u8* data_out)
else else
{ {
if (m_configuration_mode) if (m_configuration_mode)
Log_ErrorPrintf("Unimplemented config mode command 0x%02X", data_in); Log_ErrorFmt("Unimplemented config mode command 0x{:02X}", data_in);
*data_out = 0xFF; *data_out = 0xFF;
return false; return false;
@ -659,7 +658,7 @@ bool AnalogController::Transfer(const u8 data_in, u8* data_out)
m_status_byte = 0x5A; m_status_byte = 0x5A;
} }
Log_DevPrintf("0x%02x(%s) config mode", m_rx_buffer[2], m_configuration_mode ? "enter" : "leave"); Log_DevFmt("0x{:02x}({}) config mode", m_rx_buffer[2], m_configuration_mode ? "enter" : "leave");
} }
} }
break; break;
@ -668,14 +667,14 @@ bool AnalogController::Transfer(const u8 data_in, u8* data_out)
{ {
if (m_command_step == 2) if (m_command_step == 2)
{ {
Log_DevPrintf("analog mode val 0x%02x", data_in); Log_DevFmt("analog mode val 0x{:02x}", data_in);
if (data_in == 0x00 || data_in == 0x01) if (data_in == 0x00 || data_in == 0x01)
SetAnalogMode((data_in == 0x01), true); SetAnalogMode((data_in == 0x01), true);
} }
else if (m_command_step == 3) else if (m_command_step == 3)
{ {
Log_DevPrintf("analog mode lock 0x%02x", data_in); Log_DevFmt("analog mode lock 0x{:02x}", data_in);
if (data_in == 0x02 || data_in == 0x03) if (data_in == 0x02 || data_in == 0x03)
m_analog_locked = (data_in == 0x03); m_analog_locked = (data_in == 0x03);
@ -772,10 +771,10 @@ bool AnalogController::Transfer(const u8 data_in, u8* data_out)
{ {
m_command = Command::Idle; m_command = Command::Idle;
Log_DebugPrintf("Rx: %02x %02x %02x %02x %02x %02x %02x %02x", m_rx_buffer[0], m_rx_buffer[1], m_rx_buffer[2], Log_DebugFmt("Rx: {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x}", m_rx_buffer[0], m_rx_buffer[1],
m_rx_buffer[3], m_rx_buffer[4], m_rx_buffer[5], m_rx_buffer[6], m_rx_buffer[7]); m_rx_buffer[2], m_rx_buffer[3], m_rx_buffer[4], m_rx_buffer[5], m_rx_buffer[6], m_rx_buffer[7]);
Log_DebugPrintf("Tx: %02x %02x %02x %02x %02x %02x %02x %02x", m_tx_buffer[0], m_tx_buffer[1], m_tx_buffer[2], Log_DebugFmt("Tx: {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x}", m_tx_buffer[0], m_tx_buffer[1],
m_tx_buffer[3], m_tx_buffer[4], m_tx_buffer[5], m_tx_buffer[6], m_tx_buffer[7]); m_tx_buffer[2], m_tx_buffer[3], m_tx_buffer[4], m_tx_buffer[5], m_tx_buffer[6], m_tx_buffer[7]);
m_rx_buffer.fill(0x00); m_rx_buffer.fill(0x00);
m_tx_buffer.fill(0x00); m_tx_buffer.fill(0x00);
@ -873,14 +872,13 @@ static const SettingInfo s_settings[] = {
nullptr, s_invert_settings, 0.0f}, nullptr, s_invert_settings, 0.0f},
}; };
const Controller::ControllerInfo AnalogController::INFO = { const Controller::ControllerInfo AnalogController::INFO = {ControllerType::AnalogController,
ControllerType::AnalogController, "AnalogController",
"AnalogController", TRANSLATE_NOOP("ControllerType", "Analog Controller"),
TRANSLATE_NOOP("ControllerType", "Analog Controller"), ICON_PF_GAMEPAD,
ICON_PF_GAMEPAD, s_binding_info,
s_binding_info, s_settings,
s_settings, Controller::VibrationCapabilities::LargeSmallMotors};
Controller::VibrationCapabilities::LargeSmallMotors};
void AnalogController::LoadSettings(SettingsInterface& si, const char* section) void AnalogController::LoadSettings(SettingsInterface& si, const char* section)
{ {

View File

@ -12,6 +12,7 @@
#include "common/log.h" #include "common/log.h"
#include "common/string_util.h" #include "common/string_util.h"
#include "IconsFontAwesome5.h"
#include "IconsPromptFont.h" #include "IconsPromptFont.h"
#include <cmath> #include <cmath>
@ -65,10 +66,10 @@ bool AnalogJoystick::DoState(StateWrapper& sw, bool apply_input_state)
if (sw.IsReading() && (old_analog_mode != m_analog_mode)) if (sw.IsReading() && (old_analog_mode != m_analog_mode))
{ {
Host::AddFormattedOSDMessage(5.0f, Host::AddIconOSDMessage(
m_analog_mode ? TRANSLATE("AnalogJoystick", "Controller %u switched to analog mode.") : fmt::format("analog_mode_toggle_{}", m_index), ICON_FA_GAMEPAD,
TRANSLATE("AnalogJoystick", "Controller %u switched to digital mode."), m_analog_mode ? fmt::format(TRANSLATE_FS("Controller", "Controller {} switched to analog mode."), m_index + 1u) :
m_index + 1u); fmt::format(TRANSLATE_FS("Controller", "Controller {} switched to digital mode."), m_index + 1u));
} }
return true; return true;
} }
@ -239,11 +240,11 @@ void AnalogJoystick::ToggleAnalogMode()
{ {
m_analog_mode = !m_analog_mode; m_analog_mode = !m_analog_mode;
Log_InfoPrintf("Joystick %u switched to %s mode.", m_index + 1u, m_analog_mode ? "analog" : "digital"); Log_InfoFmt("Joystick {} switched to {} mode.", m_index + 1u, m_analog_mode ? "analog" : "digital");
Host::AddFormattedOSDMessage(5.0f, Host::AddIconOSDMessage(
m_analog_mode ? TRANSLATE("AnalogJoystick", "Controller %u switched to analog mode.") : fmt::format("analog_mode_toggle_{}", m_index), ICON_FA_GAMEPAD,
TRANSLATE("AnalogJoystick", "Controller %u switched to digital mode."), m_analog_mode ? fmt::format(TRANSLATE_FS("Controller", "Controller {} switched to analog mode."), m_index + 1u) :
m_index + 1u); fmt::format(TRANSLATE_FS("Controller", "Controller {} switched to digital mode."), m_index + 1u));
} }
bool AnalogJoystick::Transfer(const u8 data_in, u8* data_out) bool AnalogJoystick::Transfer(const u8 data_in, u8* data_out)

View File

@ -223,7 +223,7 @@ const BIOS::ImageInfo* BIOS::GetInfoForImage(const Image& image, const Hash& has
return &ii; return &ii;
} }
Log_WarningPrintf("Unknown BIOS hash: %s", hash.ToString().c_str()); Log_WarningFmt("Unknown BIOS hash: {}", hash.ToString());
return nullptr; return nullptr;
} }
@ -246,14 +246,14 @@ void BIOS::PatchBIOS(u8* image, u32 image_size, u32 address, u32 value, u32 mask
SmallString old_disasm, new_disasm; SmallString old_disasm, new_disasm;
CPU::DisassembleInstruction(&old_disasm, address, existing_value); CPU::DisassembleInstruction(&old_disasm, address, existing_value);
CPU::DisassembleInstruction(&new_disasm, address, new_value); CPU::DisassembleInstruction(&new_disasm, address, new_value);
Log_DevPrintf("BIOS-Patch 0x%08X (+0x%X): 0x%08X %s -> %08X %s", address, offset, existing_value, old_disasm.c_str(), Log_DevFmt("BIOS-Patch 0x{:08X} (+0x{:X}): 0x{:08X} {} -> {:08X} {}", address, offset, existing_value, old_disasm,
new_value, new_disasm.c_str()); new_value, new_disasm);
} }
bool BIOS::PatchBIOSFastBoot(u8* image, u32 image_size) bool BIOS::PatchBIOSFastBoot(u8* image, u32 image_size)
{ {
// Replace the shell entry point with a return back to the bootstrap. // Replace the shell entry point with a return back to the bootstrap.
Log_InfoPrintf("Patching BIOS to skip intro"); Log_InfoPrint("Patching BIOS to skip intro");
PatchBIOS(image, image_size, 0x1FC18000, 0x3C011F80); // lui at, 1f80 PatchBIOS(image, image_size, 0x1FC18000, 0x3C011F80); // lui at, 1f80
PatchBIOS(image, image_size, 0x1FC18004, 0x3C0A0300); // lui t2, 0300h PatchBIOS(image, image_size, 0x1FC18004, 0x3C0A0300); // lui t2, 0300h
PatchBIOS(image, image_size, 0x1FC18008, 0xAC2A1814); // sw zero, 1814h(at) ; turn the display on PatchBIOS(image, image_size, 0x1FC18008, 0xAC2A1814); // sw zero, 1814h(at) ; turn the display on
@ -308,8 +308,8 @@ bool BIOS::IsValidPSExeHeader(const PSEXEHeader& header, u32 file_size)
if ((header.file_size + sizeof(PSEXEHeader)) > file_size) if ((header.file_size + sizeof(PSEXEHeader)) > file_size)
{ {
Log_WarningPrintf("Incorrect file size in PS-EXE header: %u bytes should not be greater than %u bytes", Log_WarningFmt("Incorrect file size in PS-EXE header: {} bytes should not be greater than {} bytes",
header.file_size, static_cast<unsigned>(file_size - sizeof(PSEXEHeader))); header.file_size, static_cast<unsigned>(file_size - sizeof(PSEXEHeader)));
} }
return true; return true;

View File

@ -234,7 +234,7 @@ bool Bus::AllocateMemory(Error* error)
return false; return false;
} }
Log_InfoPrintf("Fastmem base: %p", s_fastmem_arena.BasePointer()); Log_InfoFmt("Fastmem base: {}", static_cast<void*>(s_fastmem_arena.BasePointer()));
#endif #endif
#ifndef __ANDROID__ #ifndef __ANDROID__
@ -452,15 +452,15 @@ void Bus::RecalculateMemoryTimings()
std::tie(g_spu_access_time[0], g_spu_access_time[1], g_spu_access_time[2]) = std::tie(g_spu_access_time[0], g_spu_access_time[1], g_spu_access_time[2]) =
CalculateMemoryTiming(s_MEMCTRL.spu_delay_size, s_MEMCTRL.common_delay); CalculateMemoryTiming(s_MEMCTRL.spu_delay_size, s_MEMCTRL.common_delay);
Log_TracePrintf("BIOS Memory Timing: %u bit bus, byte=%d, halfword=%d, word=%d", Log_TraceFmt("BIOS Memory Timing: {} bit bus, byte={}, halfword={}, word={}",
s_MEMCTRL.bios_delay_size.data_bus_16bit ? 16 : 8, g_bios_access_time[0] + 1, s_MEMCTRL.bios_delay_size.data_bus_16bit ? 16 : 8, g_bios_access_time[0] + 1, g_bios_access_time[1] + 1,
g_bios_access_time[1] + 1, g_bios_access_time[2] + 1); g_bios_access_time[2] + 1);
Log_TracePrintf("CDROM Memory Timing: %u bit bus, byte=%d, halfword=%d, word=%d", Log_TraceFmt("CDROM Memory Timing: {} bit bus, byte={}, halfword={}, word={}",
s_MEMCTRL.cdrom_delay_size.data_bus_16bit ? 16 : 8, g_cdrom_access_time[0] + 1, s_MEMCTRL.cdrom_delay_size.data_bus_16bit ? 16 : 8, g_cdrom_access_time[0] + 1,
g_cdrom_access_time[1] + 1, g_cdrom_access_time[2] + 1); g_cdrom_access_time[1] + 1, g_cdrom_access_time[2] + 1);
Log_TracePrintf("SPU Memory Timing: %u bit bus, byte=%d, halfword=%d, word=%d", Log_TraceFmt("SPU Memory Timing: {} bit bus, byte={}, halfword={}, word={}",
s_MEMCTRL.spu_delay_size.data_bus_16bit ? 16 : 8, g_spu_access_time[0] + 1, g_spu_access_time[1] + 1, s_MEMCTRL.spu_delay_size.data_bus_16bit ? 16 : 8, g_spu_access_time[0] + 1, g_spu_access_time[1] + 1,
g_spu_access_time[2] + 1); g_spu_access_time[2] + 1);
} }
CPUFastmemMode Bus::GetFastmemMode() CPUFastmemMode Bus::GetFastmemMode()
@ -504,9 +504,10 @@ void Bus::UpdateFastmemViews(CPUFastmemMode mode)
{ {
auto MapRAM = [](u32 base_address) { auto MapRAM = [](u32 base_address) {
u8* map_address = s_fastmem_arena.BasePointer() + base_address; u8* map_address = s_fastmem_arena.BasePointer() + base_address;
if (!s_fastmem_arena.Map(s_shmem_handle, 0, map_address, g_ram_size, PageProtect::ReadWrite)) if (!s_fastmem_arena.Map(s_shmem_handle, 0, map_address, g_ram_size, PageProtect::ReadWrite)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to map RAM at fastmem area %p (offset 0x%08X)", map_address, g_ram_size); Log_ErrorFmt("Failed to map RAM at fastmem area {} (offset 0x{:08X})", static_cast<void*>(map_address),
g_ram_size);
return; return;
} }
@ -516,9 +517,9 @@ void Bus::UpdateFastmemViews(CPUFastmemMode mode)
if (g_ram_code_bits[i]) if (g_ram_code_bits[i])
{ {
u8* page_address = map_address + (i * HOST_PAGE_SIZE); u8* page_address = map_address + (i * HOST_PAGE_SIZE);
if (!MemMap::MemProtect(page_address, HOST_PAGE_SIZE, PageProtect::ReadOnly)) if (!MemMap::MemProtect(page_address, HOST_PAGE_SIZE, PageProtect::ReadOnly)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to write-protect code page at %p", page_address); Log_ErrorFmt("Failed to write-protect code page at {}", static_cast<void*>(page_address));
s_fastmem_arena.Unmap(map_address, g_ram_size); s_fastmem_arena.Unmap(map_address, g_ram_size);
return; return;
} }
@ -546,7 +547,7 @@ void Bus::UpdateFastmemViews(CPUFastmemMode mode)
s_fastmem_lut = static_cast<u8**>(std::malloc(sizeof(u8*) * FASTMEM_LUT_SLOTS)); s_fastmem_lut = static_cast<u8**>(std::malloc(sizeof(u8*) * FASTMEM_LUT_SLOTS));
Assert(s_fastmem_lut); Assert(s_fastmem_lut);
Log_InfoPrintf("Fastmem base (software): %p", s_fastmem_lut); Log_InfoFmt("Fastmem base (software): {}", static_cast<void*>(s_fastmem_lut));
} }
// This assumes the top 4KB of address space is not mapped. It shouldn't be on any sane OSes. // This assumes the top 4KB of address space is not mapped. It shouldn't be on any sane OSes.
@ -652,8 +653,8 @@ void Bus::SetRAMPageWritable(u32 page_index, bool writable)
u8* page_address = it.first + (page_index * HOST_PAGE_SIZE); u8* page_address = it.first + (page_index * HOST_PAGE_SIZE);
if (!MemMap::MemProtect(page_address, HOST_PAGE_SIZE, protect)) [[unlikely]] if (!MemMap::MemProtect(page_address, HOST_PAGE_SIZE, protect)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to %s code page %u (0x%08X) @ %p", writable ? "unprotect" : "protect", page_index, Log_ErrorFmt("Failed to {} code page {} (0x{:08X}) @ {}", writable ? "unprotect" : "protect", page_index,
page_index * static_cast<u32>(HOST_PAGE_SIZE), page_address); page_index * static_cast<u32>(HOST_PAGE_SIZE), static_cast<void*>(page_address));
} }
} }
@ -676,9 +677,7 @@ void Bus::ClearRAMCodePageFlags()
for (const auto& it : s_fastmem_ram_views) for (const auto& it : s_fastmem_ram_views)
{ {
if (!MemMap::MemProtect(it.first, it.second, PageProtect::ReadWrite)) if (!MemMap::MemProtect(it.first, it.second, PageProtect::ReadWrite))
{ Log_ErrorFmt("Failed to unprotect code pages for fastmem view @ %p", static_cast<void*>(it.first));
Log_ErrorPrintf("Failed to unprotect code pages for fastmem view @ %p", it.first);
}
} }
} }
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@ -25,7 +25,7 @@ void CDROMAsyncReader::StartThread(u32 readahead_count)
m_shutdown_flag.store(false); m_shutdown_flag.store(false);
m_read_thread = std::thread(&CDROMAsyncReader::WorkerThreadEntryPoint, this); m_read_thread = std::thread(&CDROMAsyncReader::WorkerThreadEntryPoint, this);
Log_InfoPrintf("Read thread started with readahead of %u sectors", readahead_count); Log_InfoFmt("Read thread started with readahead of {} sectors", readahead_count);
} }
void CDROMAsyncReader::StopThread() void CDROMAsyncReader::StopThread()
@ -80,9 +80,9 @@ bool CDROMAsyncReader::Precache(ProgressCallback* callback)
if (memory_image) if (memory_image)
{ {
const CDImage::LBA lba = m_media->GetPositionOnDisc(); const CDImage::LBA lba = m_media->GetPositionOnDisc();
if (!memory_image->Seek(lba)) if (!memory_image->Seek(lba)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to seek to LBA %u in memory image", lba); Log_ErrorFmt("Failed to seek to LBA {} in memory image", lba);
return false; return false;
} }
@ -115,7 +115,7 @@ void CDROMAsyncReader::QueueReadSector(CDImage::LBA lba)
const u32 buffer_front = m_buffer_front.load(); const u32 buffer_front = m_buffer_front.load();
if (m_buffers[buffer_front].lba == lba) if (m_buffers[buffer_front].lba == lba)
{ {
Log_DebugPrintf("Skipping re-reading same sector %u", lba); Log_DebugFmt("Skipping re-reading same sector {}", lba);
return; return;
} }
@ -124,7 +124,7 @@ void CDROMAsyncReader::QueueReadSector(CDImage::LBA lba)
if (m_buffer_count > 1 && m_buffers[next_buffer].lba == lba) if (m_buffer_count > 1 && m_buffers[next_buffer].lba == lba)
{ {
// great, don't need a seek, but still kick the thread to start reading ahead again // great, don't need a seek, but still kick the thread to start reading ahead again
Log_DebugPrintf("Readahead buffer hit for sector %u", lba); Log_DebugFmt("Readahead buffer hit for sector {}", lba);
m_buffer_front.store(next_buffer); m_buffer_front.store(next_buffer);
m_buffer_count.fetch_sub(1); m_buffer_count.fetch_sub(1);
m_can_readahead.store(true); m_can_readahead.store(true);
@ -134,7 +134,7 @@ void CDROMAsyncReader::QueueReadSector(CDImage::LBA lba)
} }
// we need to toss away our readahead and start fresh // we need to toss away our readahead and start fresh
Log_DebugPrintf("Readahead buffer miss, queueing seek to %u", lba); Log_DebugFmt("Readahead buffer miss, queueing seek to {}", lba);
std::unique_lock<std::mutex> lock(m_mutex); std::unique_lock<std::mutex> lock(m_mutex);
m_next_position_set.store(true); m_next_position_set.store(true);
m_next_position = lba; m_next_position = lba;
@ -154,9 +154,9 @@ bool CDROMAsyncReader::ReadSectorUncached(CDImage::LBA lba, CDImage::SubChannelQ
// read while the lock is held so it has to wait // read while the lock is held so it has to wait
const CDImage::LBA prev_lba = m_media->GetPositionOnDisc(); const CDImage::LBA prev_lba = m_media->GetPositionOnDisc();
const bool result = InternalReadSectorUncached(lba, subq, data); const bool result = InternalReadSectorUncached(lba, subq, data);
if (!m_media->Seek(prev_lba)) if (!m_media->Seek(prev_lba)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to re-seek to cached position %u", prev_lba); Log_ErrorFmt("Failed to re-seek to cached position {}", prev_lba);
m_can_readahead.store(false); m_can_readahead.store(false);
} }
@ -165,15 +165,15 @@ bool CDROMAsyncReader::ReadSectorUncached(CDImage::LBA lba, CDImage::SubChannelQ
bool CDROMAsyncReader::InternalReadSectorUncached(CDImage::LBA lba, CDImage::SubChannelQ* subq, SectorBuffer* data) bool CDROMAsyncReader::InternalReadSectorUncached(CDImage::LBA lba, CDImage::SubChannelQ* subq, SectorBuffer* data)
{ {
if (m_media->GetPositionOnDisc() != lba && !m_media->Seek(lba)) if (m_media->GetPositionOnDisc() != lba && !m_media->Seek(lba)) [[unlikely]]
{ {
Log_WarningPrintf("Seek to LBA %u failed", lba); Log_WarningFmt("Seek to LBA {} failed", lba);
return false; return false;
} }
if (!m_media->ReadRawSector(data, subq)) if (!m_media->ReadRawSector(data, subq)) [[unlikely]]
{ {
Log_WarningPrintf("Read of LBA %u failed", lba); Log_WarningFmt("Read of LBA {} failed", lba);
return false; return false;
} }
@ -185,17 +185,17 @@ bool CDROMAsyncReader::WaitForReadToComplete()
// Safe without locking with memory_order_seq_cst. // Safe without locking with memory_order_seq_cst.
if (!m_next_position_set.load() && m_buffer_count.load() > 0) if (!m_next_position_set.load() && m_buffer_count.load() > 0)
{ {
Log_TracePrintf("Returning sector %u", m_buffers[m_buffer_front.load()].lba); Log_TraceFmt("Returning sector {}", m_buffers[m_buffer_front.load()].lba);
return m_buffers[m_buffer_front.load()].result; return m_buffers[m_buffer_front.load()].result;
} }
Common::Timer wait_timer; Common::Timer wait_timer;
Log_DebugPrintf("Sector read pending, waiting"); Log_DebugPrint("Sector read pending, waiting");
std::unique_lock<std::mutex> lock(m_mutex); std::unique_lock<std::mutex> lock(m_mutex);
m_notify_read_complete_cv.wait( m_notify_read_complete_cv.wait(
lock, [this]() { return (m_buffer_count.load() > 0 || m_seek_error.load()) && !m_next_position_set.load(); }); lock, [this]() { return (m_buffer_count.load() > 0 || m_seek_error.load()) && !m_next_position_set.load(); });
if (m_seek_error.load()) if (m_seek_error.load()) [[unlikely]]
{ {
m_seek_error.store(false); m_seek_error.store(false);
return false; return false;
@ -203,10 +203,10 @@ bool CDROMAsyncReader::WaitForReadToComplete()
const u32 front = m_buffer_front.load(); const u32 front = m_buffer_front.load();
const double wait_time = wait_timer.GetTimeMilliseconds(); const double wait_time = wait_timer.GetTimeMilliseconds();
if (wait_time > 1.0f) if (wait_time > 1.0f) [[unlikely]]
Log_WarningPrintf("Had to wait %.2f msec for LBA %u", wait_time, m_buffers[front].lba); Log_WarningFmt("Had to wait {:.2f} msec for LBA {}", wait_time, m_buffers[front].lba);
Log_TracePrintf("Returning sector %u after waiting", m_buffers[front].lba); Log_TraceFmt("Returning sector {} after waiting", m_buffers[front].lba);
return m_buffers[front].result; return m_buffers[front].result;
} }
@ -238,18 +238,18 @@ bool CDROMAsyncReader::ReadSectorIntoBuffer(std::unique_lock<std::mutex>& lock)
m_is_reading.store(true); m_is_reading.store(true);
lock.unlock(); lock.unlock();
Log_TracePrintf("Reading LBA %u...", buffer.lba); Log_TraceFmt("Reading LBA {}...", buffer.lba);
buffer.result = m_media->ReadRawSector(buffer.data.data(), &buffer.subq); buffer.result = m_media->ReadRawSector(buffer.data.data(), &buffer.subq);
if (buffer.result) if (buffer.result) [[likely]]
{ {
const double read_time = timer.GetTimeMilliseconds(); const double read_time = timer.GetTimeMilliseconds();
if (read_time > 1.0f) if (read_time > 1.0f) [[unlikely]]
Log_DevPrintf("Read LBA %u took %.2f msec", buffer.lba, read_time); Log_DevFmt("Read LBA {} took {:.2f} msec", buffer.lba, read_time);
} }
else else
{ {
Log_ErrorPrintf("Read of LBA %u failed", buffer.lba); Log_ErrorFmt("Read of LBA {} failed", buffer.lba);
} }
lock.lock(); lock.lock();
@ -269,7 +269,7 @@ void CDROMAsyncReader::ReadSectorNonThreaded(CDImage::LBA lba)
if (m_media->GetPositionOnDisc() != lba && !m_media->Seek(lba)) if (m_media->GetPositionOnDisc() != lba && !m_media->Seek(lba))
{ {
Log_WarningPrintf("Seek to LBA %u failed", lba); Log_WarningFmt("Seek to LBA {} failed", lba);
m_seek_error.store(true); m_seek_error.store(true);
return; return;
} }
@ -277,18 +277,18 @@ void CDROMAsyncReader::ReadSectorNonThreaded(CDImage::LBA lba)
BufferSlot& buffer = m_buffers.front(); BufferSlot& buffer = m_buffers.front();
buffer.lba = m_media->GetPositionOnDisc(); buffer.lba = m_media->GetPositionOnDisc();
Log_TracePrintf("Reading LBA %u...", buffer.lba); Log_TraceFmt("Reading LBA {}...", buffer.lba);
buffer.result = m_media->ReadRawSector(buffer.data.data(), &buffer.subq); buffer.result = m_media->ReadRawSector(buffer.data.data(), &buffer.subq);
if (buffer.result) if (buffer.result) [[likely]]
{ {
const double read_time = timer.GetTimeMilliseconds(); const double read_time = timer.GetTimeMilliseconds();
if (read_time > 1.0f) if (read_time > 1.0f) [[unlikely]]
Log_DevPrintf("Read LBA %u took %.2f msec", buffer.lba, read_time); Log_DevFmt("Read LBA {} took {:.2f} msec", buffer.lba, read_time);
} }
else else
{ {
Log_ErrorPrintf("Read of LBA %u failed", buffer.lba); Log_ErrorFmt("Read of LBA {} failed", buffer.lba);
} }
m_buffer_count.fetch_add(1); m_buffer_count.fetch_add(1);
@ -296,7 +296,7 @@ void CDROMAsyncReader::ReadSectorNonThreaded(CDImage::LBA lba)
void CDROMAsyncReader::CancelReadahead() void CDROMAsyncReader::CancelReadahead()
{ {
Log_DevPrintf("Cancelling readahead"); Log_DevPrint("Cancelling readahead");
std::unique_lock lock(m_mutex); std::unique_lock lock(m_mutex);
@ -332,7 +332,7 @@ void CDROMAsyncReader::WorkerThreadEntryPoint()
lock.unlock(); lock.unlock();
// seek without lock held in case it takes time // seek without lock held in case it takes time
Log_DebugPrintf("Seeking to LBA %u...", seek_location); Log_DebugFmt("Seeking to LBA {}...", seek_location);
const bool seek_result = (m_media->GetPositionOnDisc() == seek_location || m_media->Seek(seek_location)); const bool seek_result = (m_media->GetPositionOnDisc() == seek_location || m_media->Seek(seek_location));
lock.lock(); lock.lock();
@ -343,10 +343,10 @@ void CDROMAsyncReader::WorkerThreadEntryPoint()
continue; continue;
// did we fail the seek? // did we fail the seek?
if (!seek_result) if (!seek_result) [[unlikely]]
{ {
// add the error result, and don't try to read ahead // add the error result, and don't try to read ahead
Log_WarningPrintf("Seek to LBA %u failed", seek_location); Log_WarningFmt("Seek to LBA {} failed", seek_location);
m_seek_error.store(true); m_seek_error.store(true);
m_notify_read_complete_cv.notify_all(); m_notify_read_complete_cv.notify_all();
break; break;
@ -360,7 +360,7 @@ void CDROMAsyncReader::WorkerThreadEntryPoint()
break; break;
// readahead time! read as many sectors as we have space for // readahead time! read as many sectors as we have space for
Log_DebugPrintf("Reading ahead %u sectors...", static_cast<u32>(m_buffers.size()) - m_buffer_count.load()); Log_DebugFmt("Reading ahead {} sectors...", static_cast<u32>(m_buffers.size()) - m_buffer_count.load());
while (m_buffer_count.load() < static_cast<u32>(m_buffers.size())) while (m_buffer_count.load() < static_cast<u32>(m_buffers.size()))
{ {
if (m_next_position_set.load()) if (m_next_position_set.load())

View File

@ -311,7 +311,7 @@ bool CheatList::LoadFromPCSXRString(const std::string& str)
m_codes.push_back(std::move(current_code)); m_codes.push_back(std::move(current_code));
} }
Log_InfoPrintf("Loaded %zu cheats (PCSXR format)", m_codes.size()); Log_InfoFmt("Loaded {} cheats (PCSXR format)", m_codes.size());
return !m_codes.empty(); return !m_codes.empty();
} }
@ -402,7 +402,7 @@ bool CheatList::LoadFromLibretroString(const std::string& str)
const std::string* enable = FindKey(kvp, TinyString::from_format("cheat{}_enable", i)); const std::string* enable = FindKey(kvp, TinyString::from_format("cheat{}_enable", i));
if (!desc || !code || !enable) if (!desc || !code || !enable)
{ {
Log_WarningPrintf("Missing desc/code/enable for cheat %u", i); Log_WarningFmt("Missing desc/code/enable for cheat {}", i);
continue; continue;
} }
@ -414,7 +414,7 @@ bool CheatList::LoadFromLibretroString(const std::string& str)
m_codes.push_back(std::move(cc)); m_codes.push_back(std::move(cc));
} }
Log_InfoPrintf("Loaded %zu cheats (libretro format)", m_codes.size()); Log_InfoFmt("Loaded {} cheats (libretro format)", m_codes.size());
return !m_codes.empty(); return !m_codes.empty();
} }
@ -501,7 +501,7 @@ bool CheatList::LoadFromEPSXeString(const std::string& str)
if (current_code.Valid()) if (current_code.Valid())
m_codes.push_back(std::move(current_code)); m_codes.push_back(std::move(current_code));
Log_InfoPrintf("Loaded %zu cheats (EPSXe format)", m_codes.size()); Log_InfoFmt("Loaded {} cheats (EPSXe format)", m_codes.size());
return !m_codes.empty(); return !m_codes.empty();
} }
@ -523,7 +523,7 @@ bool CheatList::ParseLibretroCheat(CheatCode* cc, const char* line)
{ {
if (!IsLibretroSeparator(*end_ptr)) if (!IsLibretroSeparator(*end_ptr))
{ {
Log_WarningPrintf("Malformed code '%s'", line); Log_WarningFmt("Malformed code '{}'", line);
break; break;
} }
@ -536,7 +536,7 @@ bool CheatList::ParseLibretroCheat(CheatCode* cc, const char* line)
{ {
if (!IsLibretroSeparator(*end_ptr)) if (!IsLibretroSeparator(*end_ptr))
{ {
Log_WarningPrintf("Malformed code '%s'", line); Log_WarningFmt("Malformed code '{}'", line);
break; break;
} }
@ -791,11 +791,11 @@ bool CheatList::LoadFromPackage(const std::string& serial)
if (current_code.Valid()) if (current_code.Valid())
m_codes.push_back(std::move(current_code)); m_codes.push_back(std::move(current_code));
Log_InfoPrintf("Loaded %zu codes from package for %s", m_codes.size(), serial.c_str()); Log_InfoFmt("Loaded {} codes from package for {}", m_codes.size(), serial);
return !m_codes.empty(); return !m_codes.empty();
} }
Log_WarningPrintf("No codes found in package for %s", serial.c_str()); Log_WarningFmt("No codes found in package for {}", serial);
return false; return false;
} }
@ -1266,7 +1266,7 @@ void CheatCode::Apply() const
if ((index + 4) >= instructions.size()) if ((index + 4) >= instructions.size())
{ {
Log_ErrorPrintf("Incomplete find/replace instruction"); Log_ErrorPrint("Incomplete find/replace instruction");
return; return;
} }
const Instruction& inst2 = instructions[index + 1]; const Instruction& inst2 = instructions[index + 1];
@ -1754,7 +1754,7 @@ void CheatCode::Apply() const
break; break;
} }
default: default:
Log_ErrorPrintf("Incorrect conditional instruction (see chtdb.txt for supported instructions)"); Log_ErrorPrint("Incorrect conditional instruction (see chtdb.txt for supported instructions)");
return; return;
} }
} }
@ -1866,14 +1866,14 @@ void CheatCode::Apply() const
break; break;
} }
default: default:
Log_ErrorPrintf("Incorrect conditional instruction (see chtdb.txt for supported instructions)"); Log_ErrorPrint("Incorrect conditional instruction (see chtdb.txt for supported instructions)");
return; return;
} }
} }
} }
else else
{ {
Log_ErrorPrintf("Incomplete multi conditional instruction"); Log_ErrorPrint("Incomplete multi conditional instruction");
return; return;
} }
if (conditions_check == true) if (conditions_check == true)
@ -2518,7 +2518,7 @@ void CheatCode::Apply() const
{ {
if ((index + 1) >= instructions.size()) if ((index + 1) >= instructions.size())
{ {
Log_ErrorPrintf("Incomplete slide instruction"); Log_ErrorPrint("Incomplete slide instruction");
return; return;
} }
@ -2550,7 +2550,7 @@ void CheatCode::Apply() const
} }
else else
{ {
Log_ErrorPrintf("Invalid command in second slide parameter 0x%02X", static_cast<unsigned>(write_type)); Log_ErrorFmt("Invalid command in second slide parameter 0x{:02X}", static_cast<unsigned>(write_type));
} }
index += 2; index += 2;
@ -2561,7 +2561,7 @@ void CheatCode::Apply() const
{ {
if ((index + 1) >= instructions.size()) if ((index + 1) >= instructions.size())
{ {
Log_ErrorPrintf("Incomplete slide instruction"); Log_ErrorPrint("Incomplete slide instruction");
return; return;
} }
@ -2622,7 +2622,7 @@ void CheatCode::Apply() const
} }
else else
{ {
Log_ErrorPrintf("Invalid command in second slide parameter 0x%02X", static_cast<unsigned>(write_type)); Log_ErrorFmt("Invalid command in second slide parameter 0x{:02X}", static_cast<unsigned>(write_type));
} }
index += 2; index += 2;
@ -2633,7 +2633,7 @@ void CheatCode::Apply() const
{ {
if ((index + 1) >= instructions.size()) if ((index + 1) >= instructions.size())
{ {
Log_ErrorPrintf("Incomplete memory copy instruction"); Log_ErrorPrint("Incomplete memory copy instruction");
return; return;
} }
@ -2656,8 +2656,8 @@ void CheatCode::Apply() const
default: default:
{ {
Log_ErrorPrintf("Unhandled instruction code 0x%02X (%08X %08X)", static_cast<u8>(inst.code.GetValue()), Log_ErrorFmt("Unhandled instruction code 0x{:02X} ({:08X} {:08X})", static_cast<u8>(inst.code.GetValue()),
inst.first, inst.second); inst.first, inst.second);
index++; index++;
} }
break; break;
@ -2755,13 +2755,13 @@ void CheatCode::ApplyOnDisable() const
} }
break; break;
default: [[unlikely]] default:
{ {
Log_ErrorPrintf("Unhandled instruction code 0x%02X (%08X %08X)", static_cast<u8>(inst.code.GetValue()), Log_ErrorFmt("Unhandled instruction code 0x{:02X} ({:08X} {:08X})", static_cast<u8>(inst.code.GetValue()),
inst.first, inst.second); inst.first, inst.second);
index++; index++;
} }
break; break;
} }
} }
} }

View File

@ -525,7 +525,7 @@ bool CPU::CodeCache::RevalidateBlock(Block* block)
if (!IsBlockCodeCurrent(block)) if (!IsBlockCodeCurrent(block))
{ {
// changed, needs recompiling // changed, needs recompiling
Log_DebugPrintf("Block at PC %08X has changed and needs recompiling", block->pc); Log_DebugFmt("Block at PC {:08X} has changed and needs recompiling", block->pc);
return false; return false;
} }
@ -948,18 +948,18 @@ bool CPU::CodeCache::ReadBlockInstructions(u32 start_pc, BlockInstructionList* i
const BlockInstructionInfoPair& prev = instructions->back(); const BlockInstructionInfoPair& prev = instructions->back();
if (!prev.second.is_unconditional_branch_instruction || !prev.second.is_direct_branch_instruction) if (!prev.second.is_unconditional_branch_instruction || !prev.second.is_direct_branch_instruction)
{ {
Log_WarningPrintf("Conditional or indirect branch delay slot at %08X, skipping block", info.pc); Log_WarningFmt("Conditional or indirect branch delay slot at {:08X}, skipping block", info.pc);
return false; return false;
} }
if (!IsDirectBranchInstruction(instruction)) if (!IsDirectBranchInstruction(instruction))
{ {
Log_WarningPrintf("Indirect branch in delay slot at %08X, skipping block", info.pc); Log_WarningFmt("Indirect branch in delay slot at {:08X}, skipping block", info.pc);
return false; return false;
} }
// we _could_ fetch the delay slot from the first branch's target, but it's probably in a different // we _could_ fetch the delay slot from the first branch's target, but it's probably in a different
// page, and that's an invalidation nightmare. so just fallback to the int, this is very rare anyway. // page, and that's an invalidation nightmare. so just fallback to the int, this is very rare anyway.
Log_WarningPrintf("Direct branch in delay slot at %08X, skipping block", info.pc); Log_WarningFmt("Direct branch in delay slot at {:08X}, skipping block", info.pc);
return false; return false;
} }
@ -992,12 +992,12 @@ bool CPU::CodeCache::ReadBlockInstructions(u32 start_pc, BlockInstructionList* i
#ifdef _DEBUG #ifdef _DEBUG
SmallString disasm; SmallString disasm;
Log_DebugPrintf("Block at 0x%08X", start_pc); Log_DebugFmt("Block at 0x{:08X}", start_pc);
for (const auto& cbi : *instructions) for (const auto& cbi : *instructions)
{ {
CPU::DisassembleInstruction(&disasm, cbi.second.pc, cbi.first.bits); CPU::DisassembleInstruction(&disasm, cbi.second.pc, cbi.first.bits);
Log_DebugPrintf("[%s %s 0x%08X] %08X %s", cbi.second.is_branch_delay_slot ? "BD" : " ", Log_DebugFmt("[{} {} 0x{:08X}] {:08X} {}", cbi.second.is_branch_delay_slot ? "BD" : " ",
cbi.second.is_load_delay_slot ? "LD" : " ", cbi.second.pc, cbi.first.bits, disasm.c_str()); cbi.second.is_load_delay_slot ? "LD" : " ", cbi.second.pc, cbi.first.bits, disasm);
} }
#endif #endif
@ -1158,7 +1158,7 @@ void CPU::CodeCache::FillBlockRegInfo(Block* block)
break; break;
default: default:
Log_ErrorPrintf("Unknown funct %u", static_cast<u32>(iinst->r.funct.GetValue())); Log_ErrorFmt("Unknown funct {}", static_cast<u32>(iinst->r.funct.GetValue()));
break; break;
} }
} }
@ -1257,7 +1257,7 @@ void CPU::CodeCache::FillBlockRegInfo(Block* block)
break; break;
default: default:
Log_ErrorPrintf("Unknown op %u", static_cast<u32>(iinst->r.funct.GetValue())); Log_ErrorFmt("Unknown op {}", static_cast<u32>(iinst->r.funct.GetValue()));
break; break;
} }
} // end switch } // end switch
@ -1338,7 +1338,7 @@ void CPU::CodeCache::DiscardAndRecompileBlock(u32 start_pc)
{ {
MemMap::BeginCodeWrite(); MemMap::BeginCodeWrite();
Log_DevPrintf("Discard block %08X with manual protection", start_pc); Log_DevFmt("Discard block {:08X} with manual protection", start_pc);
Block* block = LookupBlock(start_pc); Block* block = LookupBlock(start_pc);
DebugAssert(block && block->state == BlockState::Valid); DebugAssert(block && block->state == BlockState::Valid);
InvalidateBlock(block, BlockState::NeedsRecompile); InvalidateBlock(block, BlockState::NeedsRecompile);
@ -1374,8 +1374,8 @@ const void* CPU::CodeCache::CreateBlockLink(Block* block, void* code, u32 newpc)
block->exit_links[block->num_exit_links++] = iter; block->exit_links[block->num_exit_links++] = iter;
} }
Log_DebugPrintf("Linking %p with dst pc %08X to %p%s", code, newpc, dst, Log_DebugFmt("Linking {} with dst pc {:08X} to {}{}", code, newpc, dst,
(dst == g_compile_or_revalidate_block) ? "[compiler]" : ""); (dst == g_compile_or_revalidate_block) ? "[compiler]" : "");
return dst; return dst;
} }
@ -1387,8 +1387,8 @@ void CPU::CodeCache::BacklinkBlocks(u32 pc, const void* dst)
const auto link_range = s_block_links.equal_range(pc); const auto link_range = s_block_links.equal_range(pc);
for (auto it = link_range.first; it != link_range.second; ++it) for (auto it = link_range.first; it != link_range.second; ++it)
{ {
Log_DebugPrintf("Backlinking %p with dst pc %08X to %p%s", it->second, pc, dst, Log_DebugFmt("Backlinking {} with dst pc {:08X} to {}{}", it->second, pc, dst,
(dst == g_compile_or_revalidate_block) ? "[compiler]" : ""); (dst == g_compile_or_revalidate_block) ? "[compiler]" : "");
EmitJump(it->second, dst, true); EmitJump(it->second, dst, true);
} }
} }

View File

@ -322,10 +322,10 @@ ALWAYS_INLINE_RELEASE void CPU::RaiseException(u32 CAUSE_bits, u32 EPC, u32 vect
if (g_state.cop0_regs.cause.Excode != Exception::INT && g_state.cop0_regs.cause.Excode != Exception::Syscall && if (g_state.cop0_regs.cause.Excode != Exception::INT && g_state.cop0_regs.cause.Excode != Exception::Syscall &&
g_state.cop0_regs.cause.Excode != Exception::BP) g_state.cop0_regs.cause.Excode != Exception::BP)
{ {
Log_DevPrintf("Exception %u at 0x%08X (epc=0x%08X, BD=%s, CE=%u)", Log_DevFmt("Exception {} at 0x{:08X} (epc=0x{:08X}, BD={}, CE={})",
static_cast<u8>(g_state.cop0_regs.cause.Excode.GetValue()), g_state.current_instruction_pc, static_cast<u8>(g_state.cop0_regs.cause.Excode.GetValue()), g_state.current_instruction_pc,
g_state.cop0_regs.EPC, g_state.cop0_regs.cause.BD ? "true" : "false", g_state.cop0_regs.EPC, g_state.cop0_regs.cause.BD ? "true" : "false",
g_state.cop0_regs.cause.CE.GetValue()); g_state.cop0_regs.cause.CE.GetValue());
DisassembleAndPrint(g_state.current_instruction_pc, 4u, 0u); DisassembleAndPrint(g_state.current_instruction_pc, 4u, 0u);
if (s_trace_to_log) if (s_trace_to_log)
{ {
@ -523,14 +523,14 @@ ALWAYS_INLINE_RELEASE void CPU::WriteCop0Reg(Cop0Reg reg, u32 value)
case Cop0Reg::BPC: case Cop0Reg::BPC:
{ {
g_state.cop0_regs.BPC = value; g_state.cop0_regs.BPC = value;
Log_DevPrintf("COP0 BPC <- %08X", value); Log_DevFmt("COP0 BPC <- {:08X}", value);
} }
break; break;
case Cop0Reg::BPCM: case Cop0Reg::BPCM:
{ {
g_state.cop0_regs.BPCM = value; g_state.cop0_regs.BPCM = value;
Log_DevPrintf("COP0 BPCM <- %08X", value); Log_DevFmt("COP0 BPCM <- {:08X}", value);
if (UpdateDebugDispatcherFlag()) if (UpdateDebugDispatcherFlag())
ExitExecution(); ExitExecution();
} }
@ -539,20 +539,20 @@ ALWAYS_INLINE_RELEASE void CPU::WriteCop0Reg(Cop0Reg reg, u32 value)
case Cop0Reg::BDA: case Cop0Reg::BDA:
{ {
g_state.cop0_regs.BDA = value; g_state.cop0_regs.BDA = value;
Log_DevPrintf("COP0 BDA <- %08X", value); Log_DevFmt("COP0 BDA <- {:08X}", value);
} }
break; break;
case Cop0Reg::BDAM: case Cop0Reg::BDAM:
{ {
g_state.cop0_regs.BDAM = value; g_state.cop0_regs.BDAM = value;
Log_DevPrintf("COP0 BDAM <- %08X", value); Log_DevFmt("COP0 BDAM <- {:08X}", value);
} }
break; break;
case Cop0Reg::JUMPDEST: case Cop0Reg::JUMPDEST:
{ {
Log_WarningPrintf("Ignoring write to Cop0 JUMPDEST"); Log_WarningPrint("Ignoring write to Cop0 JUMPDEST");
} }
break; break;
@ -560,7 +560,7 @@ ALWAYS_INLINE_RELEASE void CPU::WriteCop0Reg(Cop0Reg reg, u32 value)
{ {
g_state.cop0_regs.dcic.bits = g_state.cop0_regs.dcic.bits =
(g_state.cop0_regs.dcic.bits & ~Cop0Registers::DCIC::WRITE_MASK) | (value & Cop0Registers::DCIC::WRITE_MASK); (g_state.cop0_regs.dcic.bits & ~Cop0Registers::DCIC::WRITE_MASK) | (value & Cop0Registers::DCIC::WRITE_MASK);
Log_DevPrintf("COP0 DCIC <- %08X (now %08X)", value, g_state.cop0_regs.dcic.bits); Log_DevFmt("COP0 DCIC <- {:08X} (now {:08X})", value, g_state.cop0_regs.dcic.bits);
if (UpdateDebugDispatcherFlag()) if (UpdateDebugDispatcherFlag())
ExitExecution(); ExitExecution();
} }
@ -570,7 +570,7 @@ ALWAYS_INLINE_RELEASE void CPU::WriteCop0Reg(Cop0Reg reg, u32 value)
{ {
g_state.cop0_regs.sr.bits = g_state.cop0_regs.sr.bits =
(g_state.cop0_regs.sr.bits & ~Cop0Registers::SR::WRITE_MASK) | (value & Cop0Registers::SR::WRITE_MASK); (g_state.cop0_regs.sr.bits & ~Cop0Registers::SR::WRITE_MASK) | (value & Cop0Registers::SR::WRITE_MASK);
Log_DebugPrintf("COP0 SR <- %08X (now %08X)", value, g_state.cop0_regs.sr.bits); Log_DebugFmt("COP0 SR <- {:08X} (now {:08X})", value, g_state.cop0_regs.sr.bits);
UpdateMemoryPointers(); UpdateMemoryPointers();
CheckForPendingInterrupt(); CheckForPendingInterrupt();
} }
@ -580,13 +580,12 @@ ALWAYS_INLINE_RELEASE void CPU::WriteCop0Reg(Cop0Reg reg, u32 value)
{ {
g_state.cop0_regs.cause.bits = g_state.cop0_regs.cause.bits =
(g_state.cop0_regs.cause.bits & ~Cop0Registers::CAUSE::WRITE_MASK) | (value & Cop0Registers::CAUSE::WRITE_MASK); (g_state.cop0_regs.cause.bits & ~Cop0Registers::CAUSE::WRITE_MASK) | (value & Cop0Registers::CAUSE::WRITE_MASK);
Log_DebugPrintf("COP0 CAUSE <- %08X (now %08X)", value, g_state.cop0_regs.cause.bits); Log_DebugFmt("COP0 CAUSE <- {:08X} (now {:08X})", value, g_state.cop0_regs.cause.bits);
CheckForPendingInterrupt(); CheckForPendingInterrupt();
} }
break; break;
default: [[unlikely]] default : Log_DevFmt("Unknown COP0 reg write {} ({:08X})", static_cast<u8>(reg), value);
Log_DevPrintf("Unknown COP0 reg write %u (%08X)", ZeroExtend32(static_cast<u8>(reg)), value);
break; break;
} }
} }
@ -632,7 +631,7 @@ ALWAYS_INLINE_RELEASE void CPU::Cop0ExecutionBreakpointCheck()
if (bpcm == 0 || ((pc ^ bpc) & bpcm) != 0u) if (bpcm == 0 || ((pc ^ bpc) & bpcm) != 0u)
return; return;
Log_DevPrintf("Cop0 execution breakpoint at %08X", pc); Log_DevFmt("Cop0 execution breakpoint at {:08X}", pc);
g_state.cop0_regs.dcic.status_any_break = true; g_state.cop0_regs.dcic.status_any_break = true;
g_state.cop0_regs.dcic.status_bpc_code_break = true; g_state.cop0_regs.dcic.status_bpc_code_break = true;
DispatchCop0Breakpoint(); DispatchCop0Breakpoint();
@ -658,7 +657,7 @@ ALWAYS_INLINE_RELEASE void CPU::Cop0DataBreakpointCheck(VirtualMemoryAddress add
if (bdam == 0 || ((address ^ bda) & bdam) != 0u) if (bdam == 0 || ((address ^ bda) & bdam) != 0u)
return; return;
Log_DevPrintf("Cop0 data breakpoint for %08X at %08X", address, g_state.current_instruction_pc); Log_DevFmt("Cop0 data breakpoint for {:08X} at {:08X}", address, g_state.current_instruction_pc);
g_state.cop0_regs.dcic.status_any_break = true; g_state.cop0_regs.dcic.status_any_break = true;
g_state.cop0_regs.dcic.status_bda_data_break = true; g_state.cop0_regs.dcic.status_bda_data_break = true;
@ -711,7 +710,7 @@ void CPU::PrintInstruction(u32 bits, u32 pc, bool regs, const char* prefix)
} }
} }
Log_DevPrintf("%s%08x: %08x %s", prefix, pc, bits, instr.c_str()); Log_DevFmt("{}{:08x}: {:08x} %s", prefix, pc, bits, instr);
} }
void CPU::LogInstruction(u32 bits, u32 pc, bool regs) void CPU::LogInstruction(u32 bits, u32 pc, bool regs)
@ -1745,7 +1744,7 @@ restart_instruction:
{ {
if (InUserMode() && !g_state.cop0_regs.sr.CU0) if (InUserMode() && !g_state.cop0_regs.sr.CU0)
{ {
Log_WarningPrintf("Coprocessor 0 not present in user mode"); Log_WarningPrint("Coprocessor 0 not present in user mode");
RaiseException(Exception::CpU); RaiseException(Exception::CpU);
return; return;
} }
@ -1775,7 +1774,8 @@ restart_instruction:
break; break;
default: default:
Log_ErrorPrintf("Unhandled instruction at %08X: %08X", g_state.current_instruction_pc, inst.bits); [[unlikely]] Log_ErrorFmt("Unhandled instruction at {:08X}: {:08X}", g_state.current_instruction_pc,
inst.bits);
break; break;
} }
} }
@ -1800,7 +1800,8 @@ restart_instruction:
break; break;
default: default:
Log_ErrorPrintf("Unhandled instruction at %08X: %08X", g_state.current_instruction_pc, inst.bits); [[unlikely]] Log_ErrorFmt("Unhandled instruction at {:08X}: {:08X}", g_state.current_instruction_pc,
inst.bits);
break; break;
} }
} }
@ -1811,7 +1812,7 @@ restart_instruction:
{ {
if (!g_state.cop0_regs.sr.CE2) if (!g_state.cop0_regs.sr.CE2)
{ {
Log_WarningPrintf("Coprocessor 2 not enabled"); Log_WarningPrint("Coprocessor 2 not enabled");
RaiseException(Exception::CpU); RaiseException(Exception::CpU);
return; return;
} }
@ -1864,7 +1865,8 @@ restart_instruction:
break; break;
default: default:
Log_ErrorPrintf("Unhandled instruction at %08X: %08X", g_state.current_instruction_pc, inst.bits); [[unlikely]] Log_ErrorFmt("Unhandled instruction at {:08X}: {:08X}", g_state.current_instruction_pc,
inst.bits);
break; break;
} }
} }
@ -1879,7 +1881,7 @@ restart_instruction:
{ {
if (!g_state.cop0_regs.sr.CE2) if (!g_state.cop0_regs.sr.CE2)
{ {
Log_WarningPrintf("Coprocessor 2 not enabled"); Log_WarningPrint("Coprocessor 2 not enabled");
RaiseException(Exception::CpU); RaiseException(Exception::CpU);
return; return;
} }
@ -1901,7 +1903,7 @@ restart_instruction:
{ {
if (!g_state.cop0_regs.sr.CE2) if (!g_state.cop0_regs.sr.CE2)
{ {
Log_WarningPrintf("Coprocessor 2 not enabled"); Log_WarningPrint("Coprocessor 2 not enabled");
RaiseException(Exception::CpU); RaiseException(Exception::CpU);
return; return;
} }
@ -1935,10 +1937,10 @@ restart_instruction:
{ {
u32 ram_value; u32 ram_value;
if (SafeReadInstruction(g_state.current_instruction_pc, &ram_value) && if (SafeReadInstruction(g_state.current_instruction_pc, &ram_value) &&
ram_value != g_state.current_instruction.bits) ram_value != g_state.current_instruction.bits) [[unlikely]]
{ {
Log_ErrorPrintf("Stale icache at 0x%08X - ICache: %08X RAM: %08X", g_state.current_instruction_pc, Log_ErrorFmt("Stale icache at 0x{:08X} - ICache: {:08X} RAM: {:08X}", g_state.current_instruction_pc,
g_state.current_instruction.bits, ram_value); g_state.current_instruction.bits, ram_value);
g_state.current_instruction.bits = ram_value; g_state.current_instruction.bits = ram_value;
goto restart_instruction; goto restart_instruction;
} }
@ -1984,7 +1986,7 @@ bool CPU::UpdateDebugDispatcherFlag()
if (use_debug_dispatcher == g_state.use_debug_dispatcher) if (use_debug_dispatcher == g_state.use_debug_dispatcher)
return false; return false;
Log_DevPrintf("%s debug dispatcher", use_debug_dispatcher ? "Now using" : "No longer using"); Log_DevFmt("{} debug dispatcher", use_debug_dispatcher ? "Now using" : "No longer using");
g_state.use_debug_dispatcher = use_debug_dispatcher; g_state.use_debug_dispatcher = use_debug_dispatcher;
return true; return true;
} }

View File

@ -71,7 +71,7 @@ void CPU::NewRec::Compiler::BeginBlock()
if (m_block->protection == CodeCache::PageProtectionMode::ManualCheck) if (m_block->protection == CodeCache::PageProtectionMode::ManualCheck)
{ {
Log_DebugPrintf("Generate manual protection for PC %08X", m_block->pc); Log_DebugFmt("Generate manual protection for PC {:08X}", m_block->pc);
const u8* ram_ptr = Bus::g_ram + VirtualAddressToPhysical(m_block->pc); const u8* ram_ptr = Bus::g_ram + VirtualAddressToPhysical(m_block->pc);
const u8* shadow_ptr = reinterpret_cast<const u8*>(m_block->Instructions()); const u8* shadow_ptr = reinterpret_cast<const u8*>(m_block->Instructions());
GenerateBlockProtectCheck(ram_ptr, shadow_ptr, m_block->size * sizeof(Instruction)); GenerateBlockProtectCheck(ram_ptr, shadow_ptr, m_block->size * sizeof(Instruction));
@ -103,7 +103,7 @@ const void* CPU::NewRec::Compiler::CompileBlock(CodeCache::Block* block, u32* ho
Reset(block, buffer.GetFreeCodePointer(), buffer.GetFreeCodeSpace(), buffer.GetFreeFarCodePointer(), Reset(block, buffer.GetFreeCodePointer(), buffer.GetFreeCodeSpace(), buffer.GetFreeFarCodePointer(),
buffer.GetFreeFarCodeSpace()); buffer.GetFreeFarCodeSpace());
Log_DebugPrintf("Block range: %08X -> %08X", block->pc, block->pc + block->size * 4); Log_DebugFmt("Block range: {:08X} -> {:08X}", block->pc, block->pc + block->size * 4);
BeginBlock(); BeginBlock();
@ -167,8 +167,8 @@ void CPU::NewRec::Compiler::SetConstantReg(Reg r, u32 v)
if (const std::optional<u32> hostreg = CheckHostReg(0, HR_TYPE_CPU_REG, r); hostreg.has_value()) if (const std::optional<u32> hostreg = CheckHostReg(0, HR_TYPE_CPU_REG, r); hostreg.has_value())
{ {
Log_DebugPrintf("Discarding guest register %s in host register %s due to constant set", GetRegName(r), Log_DebugFmt("Discarding guest register {} in host register {} due to constant set", GetRegName(r),
GetHostRegName(hostreg.value())); GetHostRegName(hostreg.value()));
FreeHostReg(hostreg.value()); FreeHostReg(hostreg.value());
} }
} }
@ -178,7 +178,7 @@ void CPU::NewRec::Compiler::CancelLoadDelaysToReg(Reg reg)
if (m_load_delay_register != reg) if (m_load_delay_register != reg)
return; return;
Log_DebugPrintf("Cancelling load delay to %s", GetRegName(reg)); Log_DebugFmt("Cancelling load delay to {}", GetRegName(reg));
m_load_delay_register = Reg::count; m_load_delay_register = Reg::count;
if (m_load_delay_value_register != NUM_HOST_REGS) if (m_load_delay_value_register != NUM_HOST_REGS)
ClearHostReg(m_load_delay_value_register); ClearHostReg(m_load_delay_value_register);
@ -196,7 +196,7 @@ void CPU::NewRec::Compiler::UpdateLoadDelay()
// thankfully since this only happens on the first instruction, we can get away with just killing anything which // thankfully since this only happens on the first instruction, we can get away with just killing anything which
// isn't in write mode, because nothing could've been written before it, and the new value overwrites any // isn't in write mode, because nothing could've been written before it, and the new value overwrites any
// load-delayed value // load-delayed value
Log_DebugPrintf("Invalidating non-dirty registers, and flushing load delay from state"); Log_DebugPrint("Invalidating non-dirty registers, and flushing load delay from state");
constexpr u32 req_flags = (HR_ALLOCATED | HR_MODE_WRITE); constexpr u32 req_flags = (HR_ALLOCATED | HR_MODE_WRITE);
@ -206,7 +206,7 @@ void CPU::NewRec::Compiler::UpdateLoadDelay()
if (ra.type != HR_TYPE_CPU_REG || !IsHostRegAllocated(i) || ((ra.flags & req_flags) == req_flags)) if (ra.type != HR_TYPE_CPU_REG || !IsHostRegAllocated(i) || ((ra.flags & req_flags) == req_flags))
continue; continue;
Log_DebugPrintf("Freeing non-dirty cached register %s in %s", GetRegName(ra.reg), GetHostRegName(i)); Log_DebugFmt("Freeing non-dirty cached register {} in {}", GetRegName(ra.reg), GetHostRegName(i));
DebugAssert(!(ra.flags & HR_MODE_WRITE)); DebugAssert(!(ra.flags & HR_MODE_WRITE));
ClearHostReg(i); ClearHostReg(i);
} }
@ -217,7 +217,7 @@ void CPU::NewRec::Compiler::UpdateLoadDelay()
if (!HasConstantReg(static_cast<Reg>(i)) || HasDirtyConstantReg(static_cast<Reg>(i))) if (!HasConstantReg(static_cast<Reg>(i)) || HasDirtyConstantReg(static_cast<Reg>(i)))
continue; continue;
Log_DebugPrintf("Clearing non-dirty constant %s", GetRegName(static_cast<Reg>(i))); Log_DebugFmt("Clearing non-dirty constant {}", GetRegName(static_cast<Reg>(i)));
ClearConstantReg(static_cast<Reg>(i)); ClearConstantReg(static_cast<Reg>(i));
} }
@ -264,8 +264,8 @@ void CPU::NewRec::Compiler::FinishLoadDelay()
// kill any (old) cached value for this register // kill any (old) cached value for this register
DeleteMIPSReg(m_load_delay_register, false); DeleteMIPSReg(m_load_delay_register, false);
Log_DebugPrintf("Finished delayed load to %s in host register %s", GetRegName(m_load_delay_register), Log_DebugFmt("Finished delayed load to {} in host register {}", GetRegName(m_load_delay_register),
GetHostRegName(m_load_delay_value_register)); GetHostRegName(m_load_delay_value_register));
// and swap the mode over so it gets written back later // and swap the mode over so it gets written back later
HostRegAlloc& ra = m_host_regs[m_load_delay_value_register]; HostRegAlloc& ra = m_host_regs[m_load_delay_value_register];
@ -275,7 +275,7 @@ void CPU::NewRec::Compiler::FinishLoadDelay()
ra.type = HR_TYPE_CPU_REG; ra.type = HR_TYPE_CPU_REG;
// constants are gone // constants are gone
Log_DebugPrintf("Clearing constant in %s due to load delay", GetRegName(m_load_delay_register)); Log_DebugFmt("Clearing constant in {} due to load delay", GetRegName(m_load_delay_register));
ClearConstantReg(m_load_delay_register); ClearConstantReg(m_load_delay_register);
m_load_delay_register = Reg::count; m_load_delay_register = Reg::count;
@ -598,8 +598,8 @@ u32 CPU::NewRec::Compiler::GetFreeHostReg(u32 flags)
if (caller_saved_lowest_count < lowest_count) if (caller_saved_lowest_count < lowest_count)
{ {
Log_DebugPrintf("Moving caller-saved host register %s with MIPS register %s to %s for allocation", Log_DebugFmt("Moving caller-saved host register {} with MIPS register {} to {} for allocation",
GetHostRegName(lowest), GetRegName(ra.reg), GetHostRegName(caller_saved_lowest)); GetHostRegName(lowest), GetRegName(ra.reg), GetHostRegName(caller_saved_lowest));
if (IsHostRegAllocated(caller_saved_lowest)) if (IsHostRegAllocated(caller_saved_lowest))
FreeHostReg(caller_saved_lowest); FreeHostReg(caller_saved_lowest);
CopyHostReg(caller_saved_lowest, lowest); CopyHostReg(caller_saved_lowest, lowest);
@ -609,20 +609,20 @@ u32 CPU::NewRec::Compiler::GetFreeHostReg(u32 flags)
} }
} }
Log_DebugPrintf("Freeing register %s in host register %s for allocation", GetRegName(ra.reg), Log_DebugFmt("Freeing register {} in host register {} for allocation", GetRegName(ra.reg),
GetHostRegName(lowest)); GetHostRegName(lowest));
} }
break; break;
case HR_TYPE_LOAD_DELAY_VALUE: case HR_TYPE_LOAD_DELAY_VALUE:
{ {
Log_DebugPrintf("Freeing load delay register %s in host register %s for allocation", GetHostRegName(lowest), Log_DebugFmt("Freeing load delay register {} in host register {} for allocation", GetHostRegName(lowest),
GetRegName(ra.reg)); GetRegName(ra.reg));
} }
break; break;
case HR_TYPE_NEXT_LOAD_DELAY_VALUE: case HR_TYPE_NEXT_LOAD_DELAY_VALUE:
{ {
Log_DebugPrintf("Freeing next load delay register %s in host register %s due for allocation", GetRegName(ra.reg), Log_DebugFmt("Freeing next load delay register {} in host register {} due for allocation", GetRegName(ra.reg),
GetHostRegName(lowest)); GetHostRegName(lowest));
} }
break; break;
default: default:
@ -680,8 +680,8 @@ u32 CPU::NewRec::Compiler::AllocateHostReg(u32 flags, HostRegAllocType type /* =
{ {
DebugAssert(reg != Reg::zero); DebugAssert(reg != Reg::zero);
Log_DebugPrintf("Allocate host reg %s to guest reg %s in %s mode", GetHostRegName(hreg), GetRegName(reg), Log_DebugFmt("Allocate host reg {} to guest reg {} in {} mode", GetHostRegName(hreg), GetRegName(reg),
GetReadWriteModeString(flags)); GetReadWriteModeString(flags));
if (flags & HR_MODE_READ) if (flags & HR_MODE_READ)
{ {
@ -690,8 +690,7 @@ u32 CPU::NewRec::Compiler::AllocateHostReg(u32 flags, HostRegAllocType type /* =
if (HasConstantReg(reg)) if (HasConstantReg(reg))
{ {
// may as well flush it now // may as well flush it now
Log_DebugPrintf("Flush constant register in guest reg %s to host reg %s", GetRegName(reg), Log_DebugFmt("Flush constant register in guest reg {} to host reg {}", GetRegName(reg), GetHostRegName(hreg));
GetHostRegName(hreg));
LoadHostRegWithConstant(hreg, GetConstantRegU32(reg)); LoadHostRegWithConstant(hreg, GetConstantRegU32(reg));
m_constant_regs_dirty.reset(static_cast<u8>(reg)); m_constant_regs_dirty.reset(static_cast<u8>(reg));
ra.flags |= HR_MODE_WRITE; ra.flags |= HR_MODE_WRITE;
@ -705,8 +704,8 @@ u32 CPU::NewRec::Compiler::AllocateHostReg(u32 flags, HostRegAllocType type /* =
if (flags & HR_MODE_WRITE && HasConstantReg(reg)) if (flags & HR_MODE_WRITE && HasConstantReg(reg))
{ {
DebugAssert(reg != Reg::zero); DebugAssert(reg != Reg::zero);
Log_DebugPrintf("Clearing constant register in guest reg %s due to write mode in %s", GetRegName(reg), Log_DebugFmt("Clearing constant register in guest reg {} due to write mode in {}", GetRegName(reg),
GetHostRegName(hreg)); GetHostRegName(hreg));
ClearConstantReg(reg); ClearConstantReg(reg);
} }
@ -716,8 +715,8 @@ u32 CPU::NewRec::Compiler::AllocateHostReg(u32 flags, HostRegAllocType type /* =
case HR_TYPE_LOAD_DELAY_VALUE: case HR_TYPE_LOAD_DELAY_VALUE:
{ {
DebugAssert(!m_load_delay_dirty && (!HasLoadDelay() || !(flags & HR_MODE_WRITE))); DebugAssert(!m_load_delay_dirty && (!HasLoadDelay() || !(flags & HR_MODE_WRITE)));
Log_DebugPrintf("Allocating load delayed guest register %s in host reg %s in %s mode", GetRegName(reg), Log_DebugFmt("Allocating load delayed guest register {} in host reg {} in {} mode", GetRegName(reg),
GetHostRegName(hreg), GetReadWriteModeString(flags)); GetHostRegName(hreg), GetReadWriteModeString(flags));
m_load_delay_register = reg; m_load_delay_register = reg;
m_load_delay_value_register = hreg; m_load_delay_value_register = hreg;
if (flags & HR_MODE_READ) if (flags & HR_MODE_READ)
@ -727,8 +726,8 @@ u32 CPU::NewRec::Compiler::AllocateHostReg(u32 flags, HostRegAllocType type /* =
case HR_TYPE_NEXT_LOAD_DELAY_VALUE: case HR_TYPE_NEXT_LOAD_DELAY_VALUE:
{ {
Log_DebugPrintf("Allocating next load delayed guest register %s in host reg %s in %s mode", GetRegName(reg), Log_DebugFmt("Allocating next load delayed guest register {} in host reg {} in {} mode", GetRegName(reg),
GetHostRegName(hreg), GetReadWriteModeString(flags)); GetHostRegName(hreg), GetReadWriteModeString(flags));
m_next_load_delay_register = reg; m_next_load_delay_register = reg;
m_next_load_delay_value_register = hreg; m_next_load_delay_value_register = hreg;
if (flags & HR_MODE_READ) if (flags & HR_MODE_READ)
@ -739,7 +738,7 @@ u32 CPU::NewRec::Compiler::AllocateHostReg(u32 flags, HostRegAllocType type /* =
case HR_TYPE_TEMP: case HR_TYPE_TEMP:
{ {
DebugAssert(!(flags & (HR_MODE_READ | HR_MODE_WRITE))); DebugAssert(!(flags & (HR_MODE_READ | HR_MODE_WRITE)));
Log_DebugPrintf("Allocate host reg %s as temporary", GetHostRegName(hreg)); Log_DebugFmt("Allocate host reg {} as temporary", GetHostRegName(hreg));
} }
break; break;
@ -765,16 +764,13 @@ std::optional<u32> CPU::NewRec::Compiler::CheckHostReg(u32 flags, HostRegAllocTy
{ {
DebugAssert(type == HR_TYPE_CPU_REG); DebugAssert(type == HR_TYPE_CPU_REG);
if (!(ra.flags & HR_MODE_WRITE)) if (!(ra.flags & HR_MODE_WRITE))
{ Log_DebugFmt("Switch guest reg {} from read to read-write in host reg {}", GetRegName(reg), GetHostRegName(i));
Log_DebugPrintf("Switch guest reg %s from read to read-write in host reg %s", GetRegName(reg),
GetHostRegName(i));
}
if (HasConstantReg(reg)) if (HasConstantReg(reg))
{ {
DebugAssert(reg != Reg::zero); DebugAssert(reg != Reg::zero);
Log_DebugPrintf("Clearing constant register in guest reg %s due to write mode in %s", GetRegName(reg), Log_DebugFmt("Clearing constant register in guest reg {} due to write mode in {}", GetRegName(reg),
GetHostRegName(i)); GetHostRegName(i));
ClearConstantReg(reg); ClearConstantReg(reg);
} }
@ -788,7 +784,7 @@ std::optional<u32> CPU::NewRec::Compiler::CheckHostReg(u32 flags, HostRegAllocTy
{ {
// Need to move it to one which is // Need to move it to one which is
const u32 new_reg = GetFreeHostReg(HR_CALLEE_SAVED); const u32 new_reg = GetFreeHostReg(HR_CALLEE_SAVED);
Log_DebugPrintf("Rename host reg %s to %s for callee saved", GetHostRegName(i), GetHostRegName(new_reg)); Log_DebugFmt("Rename host reg {} to {} for callee saved", GetHostRegName(i), GetHostRegName(new_reg));
CopyHostReg(new_reg, i); CopyHostReg(new_reg, i);
SwapHostRegAlloc(i, new_reg); SwapHostRegAlloc(i, new_reg);
@ -830,7 +826,7 @@ void CPU::NewRec::Compiler::FlushHostReg(u32 reg)
case HR_TYPE_CPU_REG: case HR_TYPE_CPU_REG:
{ {
DebugAssert(ra.reg > Reg::zero && ra.reg < Reg::count); DebugAssert(ra.reg > Reg::zero && ra.reg < Reg::count);
Log_DebugPrintf("Flushing register %s in host register %s to state", GetRegName(ra.reg), GetHostRegName(reg)); Log_DebugFmt("Flushing register {} in host register {} to state", GetRegName(ra.reg), GetHostRegName(reg));
StoreHostRegToCPUPointer(reg, &g_state.regs.r[static_cast<u8>(ra.reg)]); StoreHostRegToCPUPointer(reg, &g_state.regs.r[static_cast<u8>(ra.reg)]);
} }
break; break;
@ -838,8 +834,8 @@ void CPU::NewRec::Compiler::FlushHostReg(u32 reg)
case HR_TYPE_LOAD_DELAY_VALUE: case HR_TYPE_LOAD_DELAY_VALUE:
{ {
DebugAssert(m_load_delay_value_register == reg); DebugAssert(m_load_delay_value_register == reg);
Log_DebugPrintf("Flushing load delayed register %s in host register %s to state", GetRegName(ra.reg), Log_DebugFmt("Flushing load delayed register {} in host register {} to state", GetRegName(ra.reg),
GetHostRegName(reg)); GetHostRegName(reg));
StoreHostRegToCPUPointer(reg, &g_state.load_delay_value); StoreHostRegToCPUPointer(reg, &g_state.load_delay_value);
m_load_delay_value_register = NUM_HOST_REGS; m_load_delay_value_register = NUM_HOST_REGS;
@ -849,8 +845,8 @@ void CPU::NewRec::Compiler::FlushHostReg(u32 reg)
case HR_TYPE_NEXT_LOAD_DELAY_VALUE: case HR_TYPE_NEXT_LOAD_DELAY_VALUE:
{ {
DebugAssert(m_next_load_delay_value_register == reg); DebugAssert(m_next_load_delay_value_register == reg);
Log_WarningPrintf("Flushing NEXT load delayed register %s in host register %s to state", GetRegName(ra.reg), Log_WarningFmt("Flushing NEXT load delayed register {} in host register {} to state", GetRegName(ra.reg),
GetHostRegName(reg)); GetHostRegName(reg));
StoreHostRegToCPUPointer(reg, &g_state.next_load_delay_value); StoreHostRegToCPUPointer(reg, &g_state.next_load_delay_value);
m_next_load_delay_value_register = NUM_HOST_REGS; m_next_load_delay_value_register = NUM_HOST_REGS;
@ -868,7 +864,7 @@ void CPU::NewRec::Compiler::FlushHostReg(u32 reg)
void CPU::NewRec::Compiler::FreeHostReg(u32 reg) void CPU::NewRec::Compiler::FreeHostReg(u32 reg)
{ {
DebugAssert(IsHostRegAllocated(reg)); DebugAssert(IsHostRegAllocated(reg));
Log_DebugPrintf("Freeing host register %s", GetHostRegName(reg)); Log_DebugFmt("Freeing host register {}", GetHostRegName(reg));
FlushHostReg(reg); FlushHostReg(reg);
ClearHostReg(reg); ClearHostReg(reg);
} }
@ -910,18 +906,18 @@ void CPU::NewRec::Compiler::RenameHostReg(u32 reg, u32 new_flags, HostRegAllocTy
if (new_type == HR_TYPE_CPU_REG) if (new_type == HR_TYPE_CPU_REG)
{ {
Log_DebugPrintf("Renaming host reg %s to guest reg %s", GetHostRegName(reg), GetRegName(new_reg)); Log_DebugFmt("Renaming host reg {} to guest reg {}", GetHostRegName(reg), GetRegName(new_reg));
} }
else if (new_type == HR_TYPE_NEXT_LOAD_DELAY_VALUE) else if (new_type == HR_TYPE_NEXT_LOAD_DELAY_VALUE)
{ {
Log_DebugPrintf("Renaming host reg %s to load delayed guest reg %s", GetHostRegName(reg), GetRegName(new_reg)); Log_DebugFmt("Renaming host reg {} to load delayed guest reg {}", GetHostRegName(reg), GetRegName(new_reg));
DebugAssert(m_next_load_delay_register == Reg::count && m_next_load_delay_value_register == NUM_HOST_REGS); DebugAssert(m_next_load_delay_register == Reg::count && m_next_load_delay_value_register == NUM_HOST_REGS);
m_next_load_delay_register = new_reg; m_next_load_delay_register = new_reg;
m_next_load_delay_value_register = reg; m_next_load_delay_value_register = reg;
} }
else else
{ {
Log_DebugPrintf("Renaming host reg %s to temp", GetHostRegName(reg)); Log_DebugFmt("Renaming host reg {} to temp", GetHostRegName(reg));
} }
HostRegAlloc& ra = m_host_regs[reg]; HostRegAlloc& ra = m_host_regs[reg];
@ -987,7 +983,7 @@ bool CPU::NewRec::Compiler::TryRenameMIPSReg(Reg to, Reg from, u32 fromhost, Reg
if (to == from || to == other || !iinfo->RenameTest(from)) if (to == from || to == other || !iinfo->RenameTest(from))
return false; return false;
Log_DebugPrintf("Renaming MIPS register %s to %s", GetRegName(from), GetRegName(to)); Log_DebugFmt("Renaming MIPS register {} to {}", GetRegName(from), GetRegName(to));
if (iinfo->LiveTest(from)) if (iinfo->LiveTest(from))
FlushHostReg(fromhost); FlushHostReg(fromhost);
@ -1094,8 +1090,8 @@ void CPU::NewRec::Compiler::Flush(u32 flags)
void CPU::NewRec::Compiler::FlushConstantReg(Reg r) void CPU::NewRec::Compiler::FlushConstantReg(Reg r)
{ {
DebugAssert(m_constant_regs_valid.test(static_cast<u32>(r))); DebugAssert(m_constant_regs_valid.test(static_cast<u32>(r)));
Log_DebugPrintf("Writing back register %s with constant value 0x%08X", GetRegName(r), Log_DebugFmt("Writing back register {} with constant value 0x{:08X}", GetRegName(r),
m_constant_reg_values[static_cast<u32>(r)]); m_constant_reg_values[static_cast<u32>(r)]);
StoreConstantToCPUPointer(m_constant_reg_values[static_cast<u32>(r)], &g_state.regs.r[static_cast<u32>(r)]); StoreConstantToCPUPointer(m_constant_reg_values[static_cast<u32>(r)], &g_state.regs.r[static_cast<u32>(r)]);
m_constant_regs_dirty.reset(static_cast<u32>(r)); m_constant_regs_dirty.reset(static_cast<u32>(r));
} }
@ -1394,7 +1390,7 @@ void CPU::NewRec::Compiler::CompileTemplate(void (Compiler::*const_func)(Compile
if (!(tflags & TF_NO_NOP) && (!g_settings.cpu_recompiler_memory_exceptions || !(tflags & TF_CAN_OVERFLOW)) && if (!(tflags & TF_NO_NOP) && (!g_settings.cpu_recompiler_memory_exceptions || !(tflags & TF_CAN_OVERFLOW)) &&
((tflags & TF_WRITES_T && rt == Reg::zero) || (tflags & TF_WRITES_D && rd == Reg::zero))) ((tflags & TF_WRITES_T && rt == Reg::zero) || (tflags & TF_WRITES_D && rd == Reg::zero)))
{ {
Log_DebugPrintf("Skipping instruction because it writes to zero"); Log_DebugPrint("Skipping instruction because it writes to zero");
return; return;
} }
@ -1441,7 +1437,7 @@ void CPU::NewRec::Compiler::CompileTemplate(void (Compiler::*const_func)(Compile
if (tflags & TF_COMMUTATIVE && !(tflags & TF_WRITES_T) && if (tflags & TF_COMMUTATIVE && !(tflags & TF_WRITES_T) &&
((HasConstantReg(rs) && !HasConstantReg(rt)) || (tflags & TF_WRITES_D && rd == rt))) ((HasConstantReg(rs) && !HasConstantReg(rt)) || (tflags & TF_WRITES_D && rd == rt)))
{ {
Log_DebugPrintf("Swapping S:%s and T:%s due to commutative op and constants", GetRegName(rs), GetRegName(rt)); Log_DebugFmt("Swapping S:{} and T:{} due to commutative op and constants", GetRegName(rs), GetRegName(rt));
std::swap(rs, rt); std::swap(rs, rt);
} }
@ -2202,7 +2198,7 @@ void CPU::NewRec::Compiler::Compile_mfc0(CompileFlags cf)
const u32* ptr = GetCop0RegPtr(r); const u32* ptr = GetCop0RegPtr(r);
if (!ptr) if (!ptr)
{ {
Log_ErrorPrintf("Read from unknown cop0 reg %u", static_cast<u32>(r)); Log_ErrorFmt("Read from unknown cop0 reg {}", static_cast<u32>(r));
Compile_Fallback(); Compile_Fallback();
return; return;
} }
@ -2308,7 +2304,7 @@ void CPU::NewRec::Compiler::AddGTETicks(TickCount ticks)
{ {
// TODO: check, int has +1 here // TODO: check, int has +1 here
m_gte_done_cycle = m_cycles + ticks; m_gte_done_cycle = m_cycles + ticks;
Log_DebugPrintf("Adding %d GTE ticks", ticks); Log_DebugFmt("Adding {} GTE ticks", ticks);
} }
void CPU::NewRec::Compiler::StallUntilGTEComplete() void CPU::NewRec::Compiler::StallUntilGTEComplete()
@ -2323,14 +2319,14 @@ void CPU::NewRec::Compiler::StallUntilGTEComplete()
// simple case - in block scheduling // simple case - in block scheduling
if (m_gte_done_cycle > m_cycles) if (m_gte_done_cycle > m_cycles)
{ {
Log_DebugPrintf("Stalling for %d ticks from GTE", m_gte_done_cycle - m_cycles); Log_DebugFmt("Stalling for {} ticks from GTE", m_gte_done_cycle - m_cycles);
m_cycles += (m_gte_done_cycle - m_cycles); m_cycles += (m_gte_done_cycle - m_cycles);
} }
} }
else else
{ {
// switch to in block scheduling // switch to in block scheduling
Log_DebugPrintf("Flushing GTE stall from state"); Log_DebugPrint("Flushing GTE stall from state");
Flush(FLUSH_GTE_STALL_FROM_STATE); Flush(FLUSH_GTE_STALL_FROM_STATE);
} }
@ -2353,7 +2349,7 @@ void CPU::NewRec::BackpatchLoadStore(void* exception_pc, const CodeCache::Loadst
info.gpr_bitmask, info.address_register, info.data_register, info.AccessSize(), info.is_signed, info.is_load); info.gpr_bitmask, info.address_register, info.data_register, info.AccessSize(), info.is_signed, info.is_load);
#if 0 #if 0
Log_DebugPrintf("**Backpatch Thunk**"); Log_DebugPrint("**Backpatch Thunk**");
CodeCache::DisassembleAndLogHostCode(thunk_address, thunk_size); CodeCache::DisassembleAndLogHostCode(thunk_address, thunk_size);
#endif #endif

View File

@ -438,7 +438,7 @@ void CPU::NewRec::AArch32Compiler::EndAndLinkBlock(const std::optional<u32>& new
if (newpc.value() == m_block->pc) if (newpc.value() == m_block->pc)
{ {
// Special case: ourselves! No need to backlink then. // Special case: ourselves! No need to backlink then.
Log_DebugPrintf("Linking block at %08X to self", m_block->pc); Log_DebugFmt("Linking block at {:08X} to self", m_block->pc);
armEmitJmp(armAsm, armAsm->GetBuffer()->GetStartAddress<const void*>(), true); armEmitJmp(armAsm, armAsm->GetBuffer()->GetStartAddress<const void*>(), true);
} }
else else
@ -575,7 +575,7 @@ void CPU::NewRec::AArch32Compiler::MoveSToReg(const vixl::aarch32::Register& dst
} }
else else
{ {
Log_WarningPrintf("Hit memory path in MoveSToReg() for %s", GetRegName(cf.MipsS())); Log_WarningFmt("Hit memory path in MoveSToReg() for {}", GetRegName(cf.MipsS()));
armAsm->ldr(dst, PTR(&g_state.regs.r[cf.mips_s])); armAsm->ldr(dst, PTR(&g_state.regs.r[cf.mips_s]));
} }
} }
@ -594,7 +594,7 @@ void CPU::NewRec::AArch32Compiler::MoveTToReg(const vixl::aarch32::Register& dst
} }
else else
{ {
Log_WarningPrintf("Hit memory path in MoveTToReg() for %s", GetRegName(cf.MipsT())); Log_WarningFmt("Hit memory path in MoveTToReg() for {}", GetRegName(cf.MipsT()));
armAsm->ldr(dst, PTR(&g_state.regs.r[cf.mips_t])); armAsm->ldr(dst, PTR(&g_state.regs.r[cf.mips_t]));
} }
} }
@ -1927,7 +1927,7 @@ void CPU::NewRec::AArch32Compiler::Compile_mtc0(CompileFlags cf)
if (mask == 0) if (mask == 0)
{ {
// if it's a read-only register, ignore // if it's a read-only register, ignore
Log_DebugPrintf("Ignoring write to read-only cop0 reg %u", static_cast<u32>(reg)); Log_DebugFmt("Ignoring write to read-only cop0 reg {}", static_cast<u32>(reg));
return; return;
} }
@ -1984,7 +1984,7 @@ void CPU::NewRec::AArch32Compiler::Compile_mtc0(CompileFlags cf)
if (reg == Cop0Reg::DCIC && g_settings.cpu_recompiler_memory_exceptions) if (reg == Cop0Reg::DCIC && g_settings.cpu_recompiler_memory_exceptions)
{ {
// TODO: DCIC handling for debug breakpoints // TODO: DCIC handling for debug breakpoints
Log_WarningPrintf("TODO: DCIC handling for debug breakpoints"); Log_WarningPrint("TODO: DCIC handling for debug breakpoints");
} }
} }

View File

@ -410,7 +410,7 @@ void CPU::NewRec::AArch64Compiler::EndAndLinkBlock(const std::optional<u32>& new
if (newpc.value() == m_block->pc) if (newpc.value() == m_block->pc)
{ {
// Special case: ourselves! No need to backlink then. // Special case: ourselves! No need to backlink then.
Log_DebugPrintf("Linking block at %08X to self", m_block->pc); Log_DebugFmt("Linking block at {:08X} to self", m_block->pc);
armEmitJmp(armAsm, armAsm->GetBuffer()->GetStartAddress<const void*>(), true); armEmitJmp(armAsm, armAsm->GetBuffer()->GetStartAddress<const void*>(), true);
} }
else else
@ -542,7 +542,7 @@ void CPU::NewRec::AArch64Compiler::MoveSToReg(const vixl::aarch64::WRegister& ds
} }
else else
{ {
Log_WarningPrintf("Hit memory path in MoveSToReg() for %s", GetRegName(cf.MipsS())); Log_WarningFmt("Hit memory path in MoveSToReg() for {}", GetRegName(cf.MipsS()));
armAsm->ldr(dst, PTR(&g_state.regs.r[cf.mips_s])); armAsm->ldr(dst, PTR(&g_state.regs.r[cf.mips_s]));
} }
} }
@ -564,7 +564,7 @@ void CPU::NewRec::AArch64Compiler::MoveTToReg(const vixl::aarch64::WRegister& ds
} }
else else
{ {
Log_WarningPrintf("Hit memory path in MoveTToReg() for %s", GetRegName(cf.MipsT())); Log_WarningFmt("Hit memory path in MoveTToReg() for {}", GetRegName(cf.MipsT()));
armAsm->ldr(dst, PTR(&g_state.regs.r[cf.mips_t])); armAsm->ldr(dst, PTR(&g_state.regs.r[cf.mips_t]));
} }
} }
@ -1906,7 +1906,7 @@ void CPU::NewRec::AArch64Compiler::Compile_mtc0(CompileFlags cf)
if (mask == 0) if (mask == 0)
{ {
// if it's a read-only register, ignore // if it's a read-only register, ignore
Log_DebugPrintf("Ignoring write to read-only cop0 reg %u", static_cast<u32>(reg)); Log_DebugFmt("Ignoring write to read-only cop0 reg {}", static_cast<u32>(reg));
return; return;
} }
@ -1961,7 +1961,7 @@ void CPU::NewRec::AArch64Compiler::Compile_mtc0(CompileFlags cf)
if (reg == Cop0Reg::DCIC && g_settings.cpu_recompiler_memory_exceptions) if (reg == Cop0Reg::DCIC && g_settings.cpu_recompiler_memory_exceptions)
{ {
// TODO: DCIC handling for debug breakpoints // TODO: DCIC handling for debug breakpoints
Log_WarningPrintf("TODO: DCIC handling for debug breakpoints"); Log_WarningPrint("TODO: DCIC handling for debug breakpoints");
} }
} }

View File

@ -173,7 +173,7 @@ void CPU::CodeCache::DisassembleAndLogHostCode(const void* start, u32 size)
size_t instlen; size_t instlen;
inst_fetch(cur, &inst, &instlen); inst_fetch(cur, &inst, &instlen);
disasm_inst(buf, std::size(buf), rv64, static_cast<u64>(reinterpret_cast<uintptr_t>(cur)), inst); disasm_inst(buf, std::size(buf), rv64, static_cast<u64>(reinterpret_cast<uintptr_t>(cur)), inst);
Log_DebugPrintf("\t0x%016" PRIx64 "\t%s", static_cast<u64>(reinterpret_cast<uintptr_t>(cur)), buf); Log_DebugFmt("\t0x{:016X}\t{}", static_cast<u64>(reinterpret_cast<uintptr_t>(cur)), buf);
cur += instlen; cur += instlen;
} }
#else #else
@ -665,7 +665,7 @@ void CPU::NewRec::RISCV64Compiler::EndAndLinkBlock(const std::optional<u32>& new
if (newpc.value() == m_block->pc) if (newpc.value() == m_block->pc)
{ {
// Special case: ourselves! No need to backlink then. // Special case: ourselves! No need to backlink then.
Log_DebugPrintf("Linking block at %08X to self", m_block->pc); Log_DebugFmt("Linking block at {:08X} to self", m_block->pc);
rvEmitJmp(rvAsm, rvAsm->GetBufferPointer(0)); rvEmitJmp(rvAsm, rvAsm->GetBufferPointer(0));
} }
else else
@ -754,7 +754,7 @@ biscuit::GPR CPU::NewRec::RISCV64Compiler::CFGetSafeRegS(CompileFlags cf, const
} }
else else
{ {
Log_WarningPrintf("Hit memory path in CFGetSafeRegS() for %s", GetRegName(cf.MipsS())); Log_WarningFmt("Hit memory path in CFGetSafeRegS() for {}", GetRegName(cf.MipsS()));
rvAsm->LW(temp_reg, PTR(&g_state.regs.r[cf.mips_s])); rvAsm->LW(temp_reg, PTR(&g_state.regs.r[cf.mips_s]));
return temp_reg; return temp_reg;
} }
@ -776,7 +776,7 @@ biscuit::GPR CPU::NewRec::RISCV64Compiler::CFGetSafeRegT(CompileFlags cf, const
} }
else else
{ {
Log_WarningPrintf("Hit memory path in CFGetSafeRegT() for %s", GetRegName(cf.MipsT())); Log_WarningFmt("Hit memory path in CFGetSafeRegT() for {}", GetRegName(cf.MipsT()));
rvAsm->LW(temp_reg, PTR(&g_state.regs.r[cf.mips_t])); rvAsm->LW(temp_reg, PTR(&g_state.regs.r[cf.mips_t]));
return temp_reg; return temp_reg;
} }
@ -825,7 +825,7 @@ void CPU::NewRec::RISCV64Compiler::MoveSToReg(const biscuit::GPR& dst, CompileFl
} }
else else
{ {
Log_WarningPrintf("Hit memory path in MoveSToReg() for %s", GetRegName(cf.MipsS())); Log_WarningFmt("Hit memory path in MoveSToReg() for {}", GetRegName(cf.MipsS()));
rvAsm->LW(dst, PTR(&g_state.regs.r[cf.mips_s])); rvAsm->LW(dst, PTR(&g_state.regs.r[cf.mips_s]));
} }
} }
@ -843,7 +843,7 @@ void CPU::NewRec::RISCV64Compiler::MoveTToReg(const biscuit::GPR& dst, CompileFl
} }
else else
{ {
Log_WarningPrintf("Hit memory path in MoveTToReg() for %s", GetRegName(cf.MipsT())); Log_WarningFmt("Hit memory path in MoveTToReg() for {}", GetRegName(cf.MipsT()));
rvAsm->LW(dst, PTR(&g_state.regs.r[cf.mips_t])); rvAsm->LW(dst, PTR(&g_state.regs.r[cf.mips_t]));
} }
} }
@ -2214,7 +2214,7 @@ void CPU::NewRec::RISCV64Compiler::Compile_mtc0(CompileFlags cf)
if (mask == 0) if (mask == 0)
{ {
// if it's a read-only register, ignore // if it's a read-only register, ignore
Log_DebugPrintf("Ignoring write to read-only cop0 reg %u", static_cast<u32>(reg)); Log_DebugFmt("Ignoring write to read-only cop0 reg {}", static_cast<u32>(reg));
return; return;
} }
@ -2273,7 +2273,7 @@ void CPU::NewRec::RISCV64Compiler::Compile_mtc0(CompileFlags cf)
if (reg == Cop0Reg::DCIC && g_settings.cpu_recompiler_memory_exceptions) if (reg == Cop0Reg::DCIC && g_settings.cpu_recompiler_memory_exceptions)
{ {
// TODO: DCIC handling for debug breakpoints // TODO: DCIC handling for debug breakpoints
Log_WarningPrintf("TODO: DCIC handling for debug breakpoints"); Log_WarningPrint("TODO: DCIC handling for debug breakpoints");
} }
} }

View File

@ -312,7 +312,7 @@ void CPU::NewRec::X64Compiler::EndAndLinkBlock(const std::optional<u32>& newpc,
if (newpc.value() == m_block->pc) if (newpc.value() == m_block->pc)
{ {
// Special case: ourselves! No need to backlink then. // Special case: ourselves! No need to backlink then.
Log_DebugPrintf("Linking block at %08X to self", m_block->pc); Log_DebugFmt("Linking block at {:08X} to self", m_block->pc);
cg->jmp(cg->getCode()); cg->jmp(cg->getCode());
} }
else else
@ -1877,7 +1877,7 @@ void CPU::NewRec::X64Compiler::Compile_mtc0(CompileFlags cf)
if (mask == 0) if (mask == 0)
{ {
// if it's a read-only register, ignore // if it's a read-only register, ignore
Log_DebugPrintf("Ignoring write to read-only cop0 reg %u", static_cast<u32>(reg)); Log_DebugFmt("Ignoring write to read-only cop0 reg {}", static_cast<u32>(reg));
return; return;
} }
@ -1940,7 +1940,7 @@ void CPU::NewRec::X64Compiler::Compile_mtc0(CompileFlags cf)
if (reg == Cop0Reg::DCIC && g_settings.cpu_recompiler_memory_exceptions) if (reg == Cop0Reg::DCIC && g_settings.cpu_recompiler_memory_exceptions)
{ {
// TODO: DCIC handling for debug breakpoints // TODO: DCIC handling for debug breakpoints
Log_WarningPrintf("TODO: DCIC handling for debug breakpoints"); Log_WarningPrint("TODO: DCIC handling for debug breakpoints");
} }
} }

View File

@ -980,7 +980,7 @@ void CodeGenerator::BlockPrologue()
if (m_block->protection == CodeCache::PageProtectionMode::ManualCheck) if (m_block->protection == CodeCache::PageProtectionMode::ManualCheck)
{ {
Log_DebugPrintf("Generate manual protection for PC %08X", m_block->pc); Log_DebugFmt("Generate manual protection for PC {:08X}", m_block->pc);
const u8* ram_ptr = Bus::g_ram + VirtualAddressToPhysical(m_block->pc); const u8* ram_ptr = Bus::g_ram + VirtualAddressToPhysical(m_block->pc);
const u8* shadow_ptr = reinterpret_cast<const u8*>(m_block->Instructions()); const u8* shadow_ptr = reinterpret_cast<const u8*>(m_block->Instructions());
EmitBlockProtectCheck(ram_ptr, shadow_ptr, m_block->size * sizeof(Instruction)); EmitBlockProtectCheck(ram_ptr, shadow_ptr, m_block->size * sizeof(Instruction));
@ -1097,7 +1097,7 @@ void CodeGenerator::InstructionEpilogue(Instruction instruction, const CodeCache
void CodeGenerator::TruncateBlockAtCurrentInstruction() void CodeGenerator::TruncateBlockAtCurrentInstruction()
{ {
Log_DevPrintf("Truncating block %08X at %08X", m_block->pc, m_current_instruction.info->pc); Log_DevFmt("Truncating block {:08X} at {:08X}", m_block->pc, m_current_instruction.info->pc);
m_block_end.instruction = m_current_instruction.instruction + 1; m_block_end.instruction = m_current_instruction.instruction + 1;
m_block_end.info = m_current_instruction.info + 1; m_block_end.info = m_current_instruction.info + 1;
WriteNewPC(CalculatePC(), true); WriteNewPC(CalculatePC(), true);
@ -1141,7 +1141,7 @@ void CodeGenerator::AddPendingCycles(bool commit)
void CodeGenerator::AddGTETicks(TickCount ticks) void CodeGenerator::AddGTETicks(TickCount ticks)
{ {
m_gte_done_cycle = m_delayed_cycles_add + ticks; m_gte_done_cycle = m_delayed_cycles_add + ticks;
Log_DebugPrintf("Adding %d GTE ticks", ticks); Log_DebugFmt("Adding {} GTE ticks", ticks);
} }
void CodeGenerator::StallUntilGTEComplete() void CodeGenerator::StallUntilGTEComplete()
@ -1151,7 +1151,7 @@ void CodeGenerator::StallUntilGTEComplete()
// simple case - in block scheduling // simple case - in block scheduling
if (m_gte_done_cycle > m_delayed_cycles_add) if (m_gte_done_cycle > m_delayed_cycles_add)
{ {
Log_DebugPrintf("Stalling for %d ticks from GTE", m_gte_done_cycle - m_delayed_cycles_add); Log_DebugFmt("Stalling for {} ticks from GTE", m_gte_done_cycle - m_delayed_cycles_add);
m_delayed_cycles_add += (m_gte_done_cycle - m_delayed_cycles_add); m_delayed_cycles_add += (m_gte_done_cycle - m_delayed_cycles_add);
} }
@ -1325,11 +1325,10 @@ bool CodeGenerator::Compile_Bitwise(Instruction instruction, const CodeCache::In
((lhs.HasConstantValue(0) && instruction.r.rt != Reg::zero && dest != instruction.r.rs) || ((lhs.HasConstantValue(0) && instruction.r.rt != Reg::zero && dest != instruction.r.rs) ||
(rhs.HasConstantValue(0) && instruction.r.rs != Reg::zero && dest != instruction.r.rt))) (rhs.HasConstantValue(0) && instruction.r.rs != Reg::zero && dest != instruction.r.rt)))
{ {
const auto rs = lhs.HasConstantValue(0) ? static_cast<CPU::Reg>(instruction.r.rt) : static_cast<CPU::Reg>(instruction.r.rs); const auto rs = lhs.HasConstantValue(0) ? static_cast<CPU::Reg>(instruction.r.rt) :
static_cast<CPU::Reg>(instruction.r.rs);
EmitFunctionCall(nullptr, &PGXP::CPU_MOVE_Packed, EmitFunctionCall(nullptr, &PGXP::CPU_MOVE_Packed, Value::FromConstantU32(PGXP::PackMoveArgs(dest, rs)),
Value::FromConstantU32(
PGXP::PackMoveArgs(dest, rs)),
lhs.HasConstantValue(0) ? rhs : lhs); lhs.HasConstantValue(0) ? rhs : lhs);
} }
} }
@ -1359,11 +1358,10 @@ bool CodeGenerator::Compile_Bitwise(Instruction instruction, const CodeCache::In
((lhs.HasConstantValue(0) && instruction.r.rt != Reg::zero && dest != instruction.r.rs) || ((lhs.HasConstantValue(0) && instruction.r.rt != Reg::zero && dest != instruction.r.rs) ||
(rhs.HasConstantValue(0) && instruction.r.rs != Reg::zero && dest != instruction.r.rt))) (rhs.HasConstantValue(0) && instruction.r.rs != Reg::zero && dest != instruction.r.rt)))
{ {
const auto rs = lhs.HasConstantValue(0) ? static_cast<CPU::Reg>(instruction.r.rt) : static_cast<CPU::Reg>(instruction.r.rs); const auto rs = lhs.HasConstantValue(0) ? static_cast<CPU::Reg>(instruction.r.rt) :
static_cast<CPU::Reg>(instruction.r.rs);
EmitFunctionCall(nullptr, &PGXP::CPU_MOVE_Packed, EmitFunctionCall(nullptr, &PGXP::CPU_MOVE_Packed, Value::FromConstantU32(PGXP::PackMoveArgs(dest, rs)),
Value::FromConstantU32(
PGXP::PackMoveArgs(dest, rs)),
lhs.HasConstantValue(0) ? rhs : lhs); lhs.HasConstantValue(0) ? rhs : lhs);
} }
} }
@ -1669,8 +1667,9 @@ bool CodeGenerator::Compile_Store(Instruction instruction, const CodeCache::Inst
VirtualAddressToPhysical(m_block->pc + (m_block->size * sizeof(Instruction))); VirtualAddressToPhysical(m_block->pc + (m_block->size * sizeof(Instruction)));
if (phys_addr >= block_start && phys_addr < block_end) if (phys_addr >= block_start && phys_addr < block_end)
{ {
Log_WarningPrintf("Instruction %08X speculatively writes to %08X inside block %08X-%08X. Truncating block.", Log_WarningFmt(
info.pc, phys_addr, block_start, block_end); "Instruction {:08X} speculatively writes to {:08X} inside block {:08X}-{:08X}. Truncating block.", info.pc,
phys_addr, block_start, block_end);
TruncateBlockAtCurrentInstruction(); TruncateBlockAtCurrentInstruction();
} }
} }
@ -1711,7 +1710,7 @@ bool CodeGenerator::Compile_LoadLeftRight(Instruction instruction, const CodeCac
// we don't actually care if it's our target reg or not, if it's not, it won't affect anything // we don't actually care if it's our target reg or not, if it's not, it won't affect anything
if (m_load_delay_dirty) if (m_load_delay_dirty)
{ {
Log_DevPrintf("Flushing interpreter load delay for lwl/lwr instruction at 0x%08X", info.pc); Log_DevFmt("Flushing interpreter load delay for lwl/lwr instruction at 0x{:08X}", info.pc);
EmitFlushInterpreterLoadDelay(); EmitFlushInterpreterLoadDelay();
m_register_cache.InvalidateGuestRegister(instruction.r.rt); m_register_cache.InvalidateGuestRegister(instruction.r.rt);
m_load_delay_dirty = false; m_load_delay_dirty = false;
@ -2388,8 +2387,8 @@ bool CodeGenerator::Compile_Branch(Instruction instruction, const CodeCache::Ins
if (branch_target.IsConstant()) if (branch_target.IsConstant())
{ {
Log_WarningPrintf("Misaligned constant target branch 0x%08X, this is strange", Log_WarningFmt("Misaligned constant target branch 0x{:08X}, this is strange",
Truncate32(branch_target.constant_value)); Truncate32(branch_target.constant_value));
} }
else else
{ {

View File

@ -279,8 +279,8 @@ void CPU::CodeCache::DisassembleAndLogHostCode(const void* start, u32 size)
protected: protected:
void ProcessOutput(const a64::Instruction* instr) override void ProcessOutput(const a64::Instruction* instr) override
{ {
Log_DebugPrintf("0x%016" PRIx64 " %08" PRIx32 "\t\t%s", reinterpret_cast<uint64_t>(instr), Log_DebugFmt("0x{:016X} {:08X}\t\t{}", reinterpret_cast<uint64_t>(instr), instr->GetInstructionBits(),
instr->GetInstructionBits(), GetOutput()); GetOutput());
} }
}; };

View File

@ -64,19 +64,20 @@ Value CodeGenerator::EmitLoadGuestMemory(Instruction instruction, const CodeCach
Value result = m_register_cache.AllocateScratch(HostPointerSize); Value result = m_register_cache.AllocateScratch(HostPointerSize);
const bool use_fastmem = !g_settings.cpu_recompiler_memory_exceptions && const bool use_fastmem = !g_settings.cpu_recompiler_memory_exceptions &&
(address_spec ? Bus::CanUseFastmemForAddress(*address_spec) : true) && !SpeculativeIsCacheIsolated(); (address_spec ? Bus::CanUseFastmemForAddress(*address_spec) : true) &&
!SpeculativeIsCacheIsolated();
if (address_spec) if (address_spec)
{ {
if (!use_fastmem) if (!use_fastmem)
{ {
Log_ProfilePrintf("Non-constant load at 0x%08X, speculative address 0x%08X, using fastmem = %s", info.pc, Log_ProfileFmt("Non-constant load at 0x{:08X}, speculative address 0x{:08X}, using fastmem = {}", info.pc,
*address_spec, use_fastmem ? "yes" : "no"); *address_spec, use_fastmem ? "yes" : "no");
} }
} }
else else
{ {
Log_ProfilePrintf("Non-constant load at 0x%08X, speculative address UNKNOWN, using fastmem = %s", info.pc, Log_ProfileFmt("Non-constant load at 0x{:08X}, speculative address UNKNOWN, using fastmem = {}", info.pc,
use_fastmem ? "yes" : "no"); use_fastmem ? "yes" : "no");
} }
if (CodeCache::IsUsingFastmem() && use_fastmem) if (CodeCache::IsUsingFastmem() && use_fastmem)
@ -138,19 +139,20 @@ void CodeGenerator::EmitStoreGuestMemory(Instruction instruction, const CodeCach
} }
const bool use_fastmem = !g_settings.cpu_recompiler_memory_exceptions && const bool use_fastmem = !g_settings.cpu_recompiler_memory_exceptions &&
(address_spec ? Bus::CanUseFastmemForAddress(*address_spec) : true) && !SpeculativeIsCacheIsolated(); (address_spec ? Bus::CanUseFastmemForAddress(*address_spec) : true) &&
!SpeculativeIsCacheIsolated();
if (address_spec) if (address_spec)
{ {
if (!use_fastmem) if (!use_fastmem)
{ {
Log_ProfilePrintf("Non-constant store at 0x%08X, speculative address 0x%08X, using fastmem = %s", info.pc, Log_ProfileFmt("Non-constant store at 0x{:08X}, speculative address 0x{:08X}, using fastmem = {}", info.pc,
*address_spec, use_fastmem ? "yes" : "no"); *address_spec, use_fastmem ? "yes" : "no");
} }
} }
else else
{ {
Log_ProfilePrintf("Non-constant store at 0x%08X, speculative address UNKNOWN, using fastmem = %s", info.pc, Log_ProfileFmt("Non-constant store at 0x{:08X}, speculative address UNKNOWN, using fastmem = {}", info.pc,
use_fastmem ? "yes" : "no"); use_fastmem ? "yes" : "no");
} }
if (CodeCache::IsUsingFastmem() && use_fastmem) if (CodeCache::IsUsingFastmem() && use_fastmem)

View File

@ -231,21 +231,21 @@ bool RegisterCache::AllocateHostReg(HostReg reg, HostRegState state /*= HostRegS
void RegisterCache::DiscardHostReg(HostReg reg) void RegisterCache::DiscardHostReg(HostReg reg)
{ {
DebugAssert(IsHostRegInUse(reg)); DebugAssert(IsHostRegInUse(reg));
Log_DebugPrintf("Discarding host register %s", m_code_generator.GetHostRegName(reg)); Log_DebugFmt("Discarding host register {}", m_code_generator.GetHostRegName(reg));
m_state.host_reg_state[reg] |= HostRegState::Discarded; m_state.host_reg_state[reg] |= HostRegState::Discarded;
} }
void RegisterCache::UndiscardHostReg(HostReg reg) void RegisterCache::UndiscardHostReg(HostReg reg)
{ {
DebugAssert(IsHostRegInUse(reg)); DebugAssert(IsHostRegInUse(reg));
Log_DebugPrintf("Undiscarding host register %s", m_code_generator.GetHostRegName(reg)); Log_DebugFmt("Undiscarding host register {}", m_code_generator.GetHostRegName(reg));
m_state.host_reg_state[reg] &= ~HostRegState::Discarded; m_state.host_reg_state[reg] &= ~HostRegState::Discarded;
} }
void RegisterCache::FreeHostReg(HostReg reg) void RegisterCache::FreeHostReg(HostReg reg)
{ {
DebugAssert(IsHostRegInUse(reg)); DebugAssert(IsHostRegInUse(reg));
Log_DebugPrintf("Freeing host register %s", m_code_generator.GetHostRegName(reg)); Log_DebugFmt("Freeing host register {}", m_code_generator.GetHostRegName(reg));
m_state.host_reg_state[reg] &= ~HostRegState::InUse; m_state.host_reg_state[reg] &= ~HostRegState::InUse;
} }
@ -279,7 +279,7 @@ Value RegisterCache::AllocateScratch(RegSize size, HostReg reg /* = HostReg_Inva
Panic("Failed to allocate specific host register"); Panic("Failed to allocate specific host register");
} }
Log_DebugPrintf("Allocating host register %s as scratch", m_code_generator.GetHostRegName(reg)); Log_DebugFmt("Allocating host register {} as scratch", m_code_generator.GetHostRegName(reg));
return Value::FromScratch(this, reg, size); return Value::FromScratch(this, reg, size);
} }
@ -542,8 +542,8 @@ Value RegisterCache::ReadGuestRegister(Reg guest_reg, bool cache /* = true */, b
host_reg = forced_host_reg; host_reg = forced_host_reg;
} }
Log_DebugPrintf("Allocated host register %s for constant guest register %s (0x%" PRIX64 ")", Log_DebugFmt("Allocated host register {} for constant guest register {} (0x{:X})",
m_code_generator.GetHostRegName(host_reg), GetRegName(guest_reg), cache_value.constant_value); m_code_generator.GetHostRegName(host_reg), GetRegName(guest_reg), cache_value.constant_value);
m_code_generator.EmitCopyValue(host_reg, cache_value); m_code_generator.EmitCopyValue(host_reg, cache_value);
cache_value.AddHostReg(this, host_reg); cache_value.AddHostReg(this, host_reg);
@ -576,8 +576,8 @@ Value RegisterCache::ReadGuestRegister(Reg guest_reg, bool cache /* = true */, b
m_code_generator.EmitLoadGuestRegister(host_reg, guest_reg); m_code_generator.EmitLoadGuestRegister(host_reg, guest_reg);
Log_DebugPrintf("Loading guest register %s to host register %s%s", GetRegName(guest_reg), Log_DebugFmt("Loading guest register {} to host register {}{}", GetRegName(guest_reg),
m_code_generator.GetHostRegName(host_reg, RegSize_32), cache ? " (cached)" : ""); m_code_generator.GetHostRegName(host_reg, RegSize_32), cache ? " (cached)" : "");
if (cache) if (cache)
{ {
@ -604,23 +604,23 @@ Value RegisterCache::ReadGuestRegisterToScratch(Reg guest_reg)
if (cache_value.IsConstant()) if (cache_value.IsConstant())
{ {
Log_DebugPrintf("Copying guest register %s from constant 0x%08X to scratch host register %s", Log_DebugFmt("Copying guest register {} from constant 0x{:08X} to scratch host register {}",
GetRegName(guest_reg), static_cast<u32>(cache_value.constant_value), GetRegName(guest_reg), static_cast<u32>(cache_value.constant_value),
m_code_generator.GetHostRegName(host_reg, RegSize_32)); m_code_generator.GetHostRegName(host_reg, RegSize_32));
} }
else else
{ {
Log_DebugPrintf("Copying guest register %s from %s to scratch host register %s", GetRegName(guest_reg), Log_DebugFmt("Copying guest register {} from {} to scratch host register {}", GetRegName(guest_reg),
m_code_generator.GetHostRegName(cache_value.host_reg, RegSize_32), m_code_generator.GetHostRegName(cache_value.host_reg, RegSize_32),
m_code_generator.GetHostRegName(host_reg, RegSize_32)); m_code_generator.GetHostRegName(host_reg, RegSize_32));
} }
} }
else else
{ {
m_code_generator.EmitLoadGuestRegister(host_reg, guest_reg); m_code_generator.EmitLoadGuestRegister(host_reg, guest_reg);
Log_DebugPrintf("Loading guest register %s to scratch host register %s", GetRegName(guest_reg), Log_DebugFmt("Loading guest register {} to scratch host register {}", GetRegName(guest_reg),
m_code_generator.GetHostRegName(host_reg, RegSize_32)); m_code_generator.GetHostRegName(host_reg, RegSize_32));
} }
return Value::FromScratch(this, host_reg, RegSize_32); return Value::FromScratch(this, host_reg, RegSize_32);
@ -636,7 +636,7 @@ Value RegisterCache::WriteGuestRegister(Reg guest_reg, Value&& value)
// cancel any load delay delay // cancel any load delay delay
if (m_state.load_delay_register == guest_reg) if (m_state.load_delay_register == guest_reg)
{ {
Log_DebugPrintf("Cancelling load delay of register %s because of non-delayed write", GetRegName(guest_reg)); Log_DebugFmt("Cancelling load delay of register {} because of non-delayed write", GetRegName(guest_reg));
m_state.load_delay_register = Reg::count; m_state.load_delay_register = Reg::count;
m_state.load_delay_value.ReleaseAndClear(); m_state.load_delay_value.ReleaseAndClear();
} }
@ -645,8 +645,8 @@ Value RegisterCache::WriteGuestRegister(Reg guest_reg, Value&& value)
if (cache_value.IsInHostRegister() && value.IsInHostRegister() && cache_value.host_reg == value.host_reg) if (cache_value.IsInHostRegister() && value.IsInHostRegister() && cache_value.host_reg == value.host_reg)
{ {
// updating the register value. // updating the register value.
Log_DebugPrintf("Updating guest register %s (in host register %s)", GetRegName(guest_reg), Log_DebugFmt("Updating guest register {} (in host register {})", GetRegName(guest_reg),
m_code_generator.GetHostRegName(value.host_reg, RegSize_32)); m_code_generator.GetHostRegName(value.host_reg, RegSize_32));
cache_value = std::move(value); cache_value = std::move(value);
cache_value.SetDirty(); cache_value.SetDirty();
return cache_value; return cache_value;
@ -668,8 +668,8 @@ Value RegisterCache::WriteGuestRegister(Reg guest_reg, Value&& value)
// If it's a temporary, we can bind that to the guest register. // If it's a temporary, we can bind that to the guest register.
if (value.IsScratch()) if (value.IsScratch())
{ {
Log_DebugPrintf("Binding scratch register %s to guest register %s", Log_DebugFmt("Binding scratch register {} to guest register {}",
m_code_generator.GetHostRegName(value.host_reg, RegSize_32), GetRegName(guest_reg)); m_code_generator.GetHostRegName(value.host_reg, RegSize_32), GetRegName(guest_reg));
cache_value = std::move(value); cache_value = std::move(value);
cache_value.flags &= ~ValueFlags::Scratch; cache_value.flags &= ~ValueFlags::Scratch;
@ -683,9 +683,9 @@ Value RegisterCache::WriteGuestRegister(Reg guest_reg, Value&& value)
cache_value.SetHostReg(this, host_reg, RegSize_32); cache_value.SetHostReg(this, host_reg, RegSize_32);
cache_value.SetDirty(); cache_value.SetDirty();
Log_DebugPrintf("Copying non-scratch register %s to %s to guest register %s", Log_DebugFmt("Copying non-scratch register {} to {} to guest register {}",
m_code_generator.GetHostRegName(value.host_reg, RegSize_32), m_code_generator.GetHostRegName(value.host_reg, RegSize_32),
m_code_generator.GetHostRegName(host_reg, RegSize_32), GetRegName(guest_reg)); m_code_generator.GetHostRegName(host_reg, RegSize_32), GetRegName(guest_reg));
return Value::FromHostReg(this, cache_value.host_reg, RegSize_32); return Value::FromHostReg(this, cache_value.host_reg, RegSize_32);
} }
@ -700,7 +700,7 @@ void RegisterCache::WriteGuestRegisterDelayed(Reg guest_reg, Value&& value)
// two load delays in a row? cancel the first one. // two load delays in a row? cancel the first one.
if (guest_reg == m_state.load_delay_register) if (guest_reg == m_state.load_delay_register)
{ {
Log_DebugPrintf("Cancelling load delay of register %s due to new load delay", GetRegName(guest_reg)); Log_DebugFmt("Cancelling load delay of register {} due to new load delay", GetRegName(guest_reg));
m_state.load_delay_register = Reg::count; m_state.load_delay_register = Reg::count;
m_state.load_delay_value.ReleaseAndClear(); m_state.load_delay_value.ReleaseAndClear();
} }
@ -716,8 +716,8 @@ void RegisterCache::WriteGuestRegisterDelayed(Reg guest_reg, Value&& value)
// If it's a temporary, we can bind that to the guest register. // If it's a temporary, we can bind that to the guest register.
if (value.IsScratch()) if (value.IsScratch())
{ {
Log_DebugPrintf("Binding scratch register %s to load-delayed guest register %s", Log_DebugFmt("Binding scratch register {} to load-delayed guest register {}",
m_code_generator.GetHostRegName(value.host_reg, RegSize_32), GetRegName(guest_reg)); m_code_generator.GetHostRegName(value.host_reg, RegSize_32), GetRegName(guest_reg));
cache_value = std::move(value); cache_value = std::move(value);
return; return;
@ -727,9 +727,9 @@ void RegisterCache::WriteGuestRegisterDelayed(Reg guest_reg, Value&& value)
cache_value = AllocateScratch(RegSize_32); cache_value = AllocateScratch(RegSize_32);
m_code_generator.EmitCopyValue(cache_value.host_reg, value); m_code_generator.EmitCopyValue(cache_value.host_reg, value);
Log_DebugPrintf("Copying non-scratch register %s to %s to load-delayed guest register %s", Log_DebugFmt("Copying non-scratch register {} to {} to load-delayed guest register {}",
m_code_generator.GetHostRegName(value.host_reg, RegSize_32), m_code_generator.GetHostRegName(value.host_reg, RegSize_32),
m_code_generator.GetHostRegName(cache_value.host_reg, RegSize_32), GetRegName(guest_reg)); m_code_generator.GetHostRegName(cache_value.host_reg, RegSize_32), GetRegName(guest_reg));
} }
void RegisterCache::UpdateLoadDelay() void RegisterCache::UpdateLoadDelay()
@ -758,7 +758,7 @@ void RegisterCache::CancelLoadDelay()
if (m_state.load_delay_register == Reg::count) if (m_state.load_delay_register == Reg::count)
return; return;
Log_DebugPrintf("Cancelling load delay of register %s", GetRegName(m_state.load_delay_register)); Log_DebugFmt("Cancelling load delay of register {}", GetRegName(m_state.load_delay_register));
m_state.load_delay_register = Reg::count; m_state.load_delay_register = Reg::count;
m_state.load_delay_value.ReleaseAndClear(); m_state.load_delay_value.ReleaseAndClear();
} }
@ -769,7 +769,7 @@ void RegisterCache::WriteLoadDelayToCPU(bool clear)
Assert(m_state.next_load_delay_register == Reg::count); Assert(m_state.next_load_delay_register == Reg::count);
if (m_state.load_delay_register != Reg::count) if (m_state.load_delay_register != Reg::count)
{ {
Log_DebugPrintf("Flushing pending load delay of %s", GetRegName(m_state.load_delay_register)); Log_DebugFmt("Flushing pending load delay of {}", GetRegName(m_state.load_delay_register));
m_code_generator.EmitStoreInterpreterLoadDelay(m_state.load_delay_register, m_state.load_delay_value); m_code_generator.EmitStoreInterpreterLoadDelay(m_state.load_delay_register, m_state.load_delay_value);
if (clear) if (clear)
{ {
@ -804,13 +804,13 @@ void RegisterCache::FlushGuestRegister(Reg guest_reg, bool invalidate, bool clea
{ {
if (cache_value.IsInHostRegister()) if (cache_value.IsInHostRegister())
{ {
Log_DebugPrintf("Flushing guest register %s from host register %s", GetRegName(guest_reg), Log_DebugFmt("Flushing guest register {} from host register {}", GetRegName(guest_reg),
m_code_generator.GetHostRegName(cache_value.host_reg, RegSize_32)); m_code_generator.GetHostRegName(cache_value.host_reg, RegSize_32));
} }
else if (cache_value.IsConstant()) else if (cache_value.IsConstant())
{ {
Log_DebugPrintf("Flushing guest register %s from constant 0x%" PRIX64, GetRegName(guest_reg), Log_DebugFmt("Flushing guest register {} from constant 0x{:X}", GetRegName(guest_reg),
cache_value.constant_value); cache_value.constant_value);
} }
m_code_generator.EmitStoreGuestRegister(guest_reg, cache_value); m_code_generator.EmitStoreGuestRegister(guest_reg, cache_value);
if (clear_dirty) if (clear_dirty)
@ -833,7 +833,7 @@ void RegisterCache::InvalidateGuestRegister(Reg guest_reg)
ClearRegisterFromOrder(guest_reg); ClearRegisterFromOrder(guest_reg);
} }
Log_DebugPrintf("Invalidating guest register %s", GetRegName(guest_reg)); Log_DebugFmt("Invalidating guest register {}", GetRegName(guest_reg));
cache_value.Clear(); cache_value.Clear();
} }
@ -875,7 +875,7 @@ bool RegisterCache::EvictOneGuestRegister()
// evict the register used the longest time ago // evict the register used the longest time ago
Reg evict_reg = m_state.guest_reg_order[m_state.guest_reg_order_count - 1]; Reg evict_reg = m_state.guest_reg_order[m_state.guest_reg_order_count - 1];
Log_ProfilePrintf("Evicting guest register %s", GetRegName(evict_reg)); Log_DebugFmt("Evicting guest register {}", GetRegName(evict_reg));
FlushGuestRegister(evict_reg, true, true); FlushGuestRegister(evict_reg, true, true);
return HasFreeHostRegister(); return HasFreeHostRegister();

View File

@ -504,7 +504,7 @@ void DMA::UpdateIRQ()
[[maybe_unused]] const auto old_dicr = s_DICR; [[maybe_unused]] const auto old_dicr = s_DICR;
s_DICR.UpdateMasterFlag(); s_DICR.UpdateMasterFlag();
if (!old_dicr.master_flag && s_DICR.master_flag) if (!old_dicr.master_flag && s_DICR.master_flag)
Log_TracePrintf("Firing DMA master interrupt"); Log_TracePrint("Firing DMA master interrupt");
InterruptController::SetLineState(InterruptController::IRQ::DMA, s_DICR.master_flag); InterruptController::SetLineState(InterruptController::IRQ::DMA, s_DICR.master_flag);
} }
@ -744,7 +744,7 @@ bool DMA::TransferChannel()
void DMA::HaltTransfer(TickCount duration) void DMA::HaltTransfer(TickCount duration)
{ {
s_halt_ticks_remaining += duration; s_halt_ticks_remaining += duration;
Log_DebugPrintf("Halting DMA for %d ticks", s_halt_ticks_remaining); Log_DebugFmt("Halting DMA for {} ticks", s_halt_ticks_remaining);
if (s_unhalt_event->IsActive()) if (s_unhalt_event->IsActive())
return; return;
@ -754,7 +754,7 @@ void DMA::HaltTransfer(TickCount duration)
void DMA::UnhaltTransfer(void*, TickCount ticks, TickCount ticks_late) void DMA::UnhaltTransfer(void*, TickCount ticks, TickCount ticks_late)
{ {
Log_DebugPrintf("Resuming DMA after %d ticks, %d ticks late", ticks, -(s_halt_ticks_remaining - ticks)); Log_DebugFmt("Resuming DMA after {} ticks, {} ticks late", ticks, -(s_halt_ticks_remaining - ticks));
s_halt_ticks_remaining -= ticks; s_halt_ticks_remaining -= ticks;
s_unhalt_event->Deactivate(); s_unhalt_event->Deactivate();
@ -834,7 +834,7 @@ TickCount DMA::TransferMemoryToDevice(u32 address, u32 increment, u32 word_count
case Channel::MDECout: case Channel::MDECout:
case Channel::PIO: case Channel::PIO:
default: default:
Log_ErrorPrintf("Unhandled DMA channel %u for device write", static_cast<u32>(channel)); Log_ErrorFmt("Unhandled DMA channel {} for device write", static_cast<u32>(channel));
break; break;
} }
@ -899,7 +899,7 @@ TickCount DMA::TransferDeviceToMemory(u32 address, u32 increment, u32 word_count
break; break;
default: default:
Log_ErrorPrintf("Unhandled DMA channel %u for device read", static_cast<u32>(channel)); Log_ErrorFmt("Unhandled DMA channel {} for device read", static_cast<u32>(channel));
std::fill_n(dest_pointer, word_count, UINT32_C(0xFFFFFFFF)); std::fill_n(dest_pointer, word_count, UINT32_C(0xFFFFFFFF));
break; break;
} }

View File

@ -5491,7 +5491,7 @@ void FullscreenUI::PopulateSaveStateScreenshot(SaveStateListEntry* li, const Ext
} }
if (!li->preview_texture) if (!li->preview_texture)
Log_ErrorPrintf("Failed to upload save state image to GPU"); Log_ErrorPrint("Failed to upload save state image to GPU");
} }
void FullscreenUI::ClearSaveStateEntryList() void FullscreenUI::ClearSaveStateEntryList()

View File

@ -307,7 +307,7 @@ const GameDatabase::Entry* GameDatabase::GetEntryForDisc(CDImage* image)
if (entry) if (entry)
return entry; return entry;
Log_WarningPrintf("No entry found for disc '%s'", id.c_str()); Log_WarningFmt("No entry found for disc '{}'", id);
return nullptr; return nullptr;
} }
@ -861,7 +861,7 @@ bool GameDatabase::LoadFromCache()
ByteStream::OpenFile(GetCacheFile().c_str(), BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED)); ByteStream::OpenFile(GetCacheFile().c_str(), BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED));
if (!stream) if (!stream)
{ {
Log_DevPrintf("Cache does not exist, loading full database."); Log_DevPrint("Cache does not exist, loading full database.");
return false; return false;
} }
@ -873,13 +873,13 @@ bool GameDatabase::LoadFromCache()
!stream->ReadU32(&num_entries) || !stream->ReadU32(&num_codes) || signature != GAME_DATABASE_CACHE_SIGNATURE || !stream->ReadU32(&num_entries) || !stream->ReadU32(&num_codes) || signature != GAME_DATABASE_CACHE_SIGNATURE ||
version != GAME_DATABASE_CACHE_VERSION) version != GAME_DATABASE_CACHE_VERSION)
{ {
Log_DevPrintf("Cache header is corrupted or version mismatch."); Log_DevPrint("Cache header is corrupted or version mismatch.");
return false; return false;
} }
if (gamedb_ts != file_gamedb_ts) if (gamedb_ts != file_gamedb_ts)
{ {
Log_DevPrintf("Cache is out of date, recreating."); Log_DevPrint("Cache is out of date, recreating.");
return false; return false;
} }
@ -917,7 +917,7 @@ bool GameDatabase::LoadFromCache()
!ReadOptionalFromStream(stream.get(), &entry.gpu_line_detect_mode) || !ReadOptionalFromStream(stream.get(), &entry.gpu_line_detect_mode) ||
!stream->ReadSizePrefixedString(&entry.disc_set_name) || !stream->ReadU32(&num_disc_set_serials)) !stream->ReadSizePrefixedString(&entry.disc_set_name) || !stream->ReadU32(&num_disc_set_serials))
{ {
Log_DevPrintf("Cache entry is corrupted."); Log_DevPrint("Cache entry is corrupted.");
return false; return false;
} }
@ -928,7 +928,7 @@ bool GameDatabase::LoadFromCache()
{ {
if (!stream->ReadSizePrefixedString(&entry.disc_set_serials.emplace_back())) if (!stream->ReadSizePrefixedString(&entry.disc_set_serials.emplace_back()))
{ {
Log_DevPrintf("Cache entry is corrupted."); Log_DevPrint("Cache entry is corrupted.");
return false; return false;
} }
} }
@ -950,7 +950,7 @@ bool GameDatabase::LoadFromCache()
if (!stream->ReadSizePrefixedString(&code) || !stream->ReadU32(&index) || if (!stream->ReadSizePrefixedString(&code) || !stream->ReadU32(&index) ||
index >= static_cast<u32>(s_entries.size())) index >= static_cast<u32>(s_entries.size()))
{ {
Log_DevPrintf("Cache code entry is corrupted."); Log_DevPrint("Cache code entry is corrupted.");
return false; return false;
} }

View File

@ -14,6 +14,7 @@
#include "common/assert.h" #include "common/assert.h"
#include "common/byte_stream.h" #include "common/byte_stream.h"
#include "common/error.h"
#include "common/file_system.h" #include "common/file_system.h"
#include "common/heterogeneous_containers.h" #include "common/heterogeneous_containers.h"
#include "common/log.h" #include "common/log.h"
@ -150,7 +151,7 @@ bool GameList::GetExeListEntry(const std::string& path, GameList::Entry* entry)
if (!BIOS::IsValidPSExeHeader(header, file_size)) if (!BIOS::IsValidPSExeHeader(header, file_size))
{ {
Log_DebugPrintf("%s is not a valid PS-EXE", path.c_str()); Log_WarningFmt("{} is not a valid PS-EXE", path);
return false; return false;
} }
@ -285,7 +286,7 @@ bool GameList::GetDiscListEntry(const std::string& path, Entry* entry)
{ {
if (!cdi->SwitchSubImage(i, nullptr)) if (!cdi->SwitchSubImage(i, nullptr))
{ {
Log_ErrorPrintf("Failed to switch to subimage %u in '%s'", i, entry->path.c_str()); Log_ErrorFmt("Failed to switch to subimage {} in '{}'", i, entry->path);
continue; continue;
} }
@ -322,7 +323,7 @@ bool GameList::LoadEntriesFromCache(ByteStream* stream)
if (!stream->ReadU32(&file_signature) || !stream->ReadU32(&file_version) || if (!stream->ReadU32(&file_signature) || !stream->ReadU32(&file_version) ||
file_signature != GAME_LIST_CACHE_SIGNATURE || file_version != GAME_LIST_CACHE_VERSION) file_signature != GAME_LIST_CACHE_SIGNATURE || file_version != GAME_LIST_CACHE_VERSION)
{ {
Log_WarningPrintf("Game list cache is corrupted"); Log_WarningPrint("Game list cache is corrupted");
return false; return false;
} }
@ -347,7 +348,7 @@ bool GameList::LoadEntriesFromCache(ByteStream* stream)
region >= static_cast<u8>(DiscRegion::Count) || type >= static_cast<u8>(EntryType::Count) || region >= static_cast<u8>(DiscRegion::Count) || type >= static_cast<u8>(EntryType::Count) ||
compatibility_rating >= static_cast<u8>(GameDatabase::CompatibilityRating::Count)) compatibility_rating >= static_cast<u8>(GameDatabase::CompatibilityRating::Count))
{ {
Log_WarningPrintf("Game list cache entry is corrupted"); Log_WarningPrint("Game list cache entry is corrupted");
return false; return false;
} }
@ -408,7 +409,7 @@ void GameList::LoadCache()
if (!LoadEntriesFromCache(stream.get())) if (!LoadEntriesFromCache(stream.get()))
{ {
Log_WarningPrintf("Deleting corrupted cache file '%s'", filename.c_str()); Log_WarningFmt("Deleting corrupted cache file '{}'", Path::GetFileName(filename));
stream.reset(); stream.reset();
s_cache_map.clear(); s_cache_map.clear();
DeleteCacheFile(); DeleteCacheFile();
@ -437,7 +438,7 @@ bool GameList::OpenCacheForWriting()
s_cache_write_stream.reset(); s_cache_write_stream.reset();
} }
Log_InfoPrintf("Creating new game list cache file: '%s'", cache_filename.c_str()); Log_InfoFmt("Creating new game list cache file: '{}'", Path::GetFileName(cache_filename));
s_cache_write_stream = ByteStream::OpenFile( s_cache_write_stream = ByteStream::OpenFile(
cache_filename.c_str(), BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_WRITE); cache_filename.c_str(), BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_WRITE);
@ -448,7 +449,7 @@ bool GameList::OpenCacheForWriting()
if (!s_cache_write_stream->WriteU32(GAME_LIST_CACHE_SIGNATURE) || if (!s_cache_write_stream->WriteU32(GAME_LIST_CACHE_SIGNATURE) ||
!s_cache_write_stream->WriteU32(GAME_LIST_CACHE_VERSION)) !s_cache_write_stream->WriteU32(GAME_LIST_CACHE_VERSION))
{ {
Log_ErrorPrintf("Failed to write game list cache header"); Log_ErrorPrint("Failed to write game list cache header");
s_cache_write_stream.reset(); s_cache_write_stream.reset();
FileSystem::DeleteFile(cache_filename.c_str()); FileSystem::DeleteFile(cache_filename.c_str());
return false; return false;
@ -474,10 +475,11 @@ void GameList::DeleteCacheFile()
if (!FileSystem::FileExists(filename.c_str())) if (!FileSystem::FileExists(filename.c_str()))
return; return;
if (FileSystem::DeleteFile(filename.c_str())) Error error;
Log_InfoPrintf("Deleted game list cache '%s'", filename.c_str()); if (FileSystem::DeleteFile(filename.c_str(), &error))
Log_InfoFmt("Deleted game list cache '{}'", Path::GetFileName(filename));
else else
Log_WarningPrintf("Failed to delete game list cache '%s'", filename.c_str()); Log_WarningFmt("Failed to delete game list cache '{}': {}", Path::GetFileName(filename), error.GetDescription());
} }
static bool IsPathExcluded(const std::vector<std::string>& excluded_paths, const std::string& path) static bool IsPathExcluded(const std::vector<std::string>& excluded_paths, const std::string& path)
@ -490,9 +492,9 @@ void GameList::ScanDirectory(const char* path, bool recursive, bool only_cache,
const std::vector<std::string>& excluded_paths, const PlayedTimeMap& played_time_map, const std::vector<std::string>& excluded_paths, const PlayedTimeMap& played_time_map,
ProgressCallback* progress) ProgressCallback* progress)
{ {
Log_InfoPrintf("Scanning %s%s", path, recursive ? " (recursively)" : ""); Log_InfoFmt("Scanning {}{}", path, recursive ? " (recursively)" : "");
progress->SetFormattedStatusText("Scanning directory '%s'%s...", path, recursive ? " (recursively)" : ""); progress->SetStatusText(SmallString::from_format(TRANSLATE_FS("GameList", "Scanning directory '{}'..."), path));
FileSystem::FindResultsArray files; FileSystem::FindResultsArray files;
FileSystem::FindFiles(path, "*", FileSystem::FindFiles(path, "*",
@ -524,7 +526,8 @@ void GameList::ScanDirectory(const char* path, bool recursive, bool only_cache,
continue; continue;
} }
progress->SetFormattedStatusText("Scanning '%s'...", FileSystem::GetDisplayNameFromPath(ffd.FileName).c_str()); progress->SetStatusText(SmallString::from_format(TRANSLATE_FS("GameList", "Scanning '{}'..."),
FileSystem::GetDisplayNameFromPath(ffd.FileName)));
ScanFile(std::move(ffd.FileName), ffd.ModificationTime, lock, played_time_map); ScanFile(std::move(ffd.FileName), ffd.ModificationTime, lock, played_time_map);
progress->SetProgressValue(files_scanned); progress->SetProgressValue(files_scanned);
} }
@ -556,7 +559,7 @@ bool GameList::ScanFile(std::string path, std::time_t timestamp, std::unique_loc
// don't block UI while scanning // don't block UI while scanning
lock.unlock(); lock.unlock();
Log_DevPrintf("Scanning '%s'...", path.c_str()); Log_DevFmt("Scanning '{}'...", path);
Entry entry; Entry entry;
if (!PopulateEntryFromPath(path, &entry)) if (!PopulateEntryFromPath(path, &entry))
@ -567,8 +570,8 @@ bool GameList::ScanFile(std::string path, std::time_t timestamp, std::unique_loc
if (s_cache_write_stream || OpenCacheForWriting()) if (s_cache_write_stream || OpenCacheForWriting())
{ {
if (!WriteEntryToCache(&entry)) if (!WriteEntryToCache(&entry)) [[unlikely]]
Log_WarningPrintf("Failed to write entry '%s' to cache", entry.path.c_str()); Log_WarningFmt("Failed to write entry '{}' to cache", entry.path);
} }
auto iter = played_time_map.find(entry.serial); auto iter = played_time_map.find(entry.serial);
@ -944,7 +947,7 @@ bool GameList::ParsePlayedTimeLine(char* line, std::string& serial, PlayedTimeEn
size_t len = std::strlen(line); size_t len = std::strlen(line);
if (len != (PLAYED_TIME_LINE_LENGTH + 1)) // \n if (len != (PLAYED_TIME_LINE_LENGTH + 1)) // \n
{ {
Log_WarningPrintf("Malformed line: '%s'", line); Log_WarningFmt("Malformed line: '{}'", line);
return false; return false;
} }
@ -958,7 +961,7 @@ bool GameList::ParsePlayedTimeLine(char* line, std::string& serial, PlayedTimeEn
const std::optional<u64> last_played_time(StringUtil::FromChars<u64>(last_played_time_tok)); const std::optional<u64> last_played_time(StringUtil::FromChars<u64>(last_played_time_tok));
if (serial_tok.empty() || !last_played_time.has_value() || !total_played_time.has_value()) if (serial_tok.empty() || !last_played_time.has_value() || !total_played_time.has_value())
{ {
Log_WarningPrintf("Malformed line: '%s'", line); Log_WarningFmt("Malformed line: '{}'", line);
return false; return false;
} }
@ -1007,7 +1010,7 @@ GameList::PlayedTimeMap GameList::LoadPlayedTimeMap(const std::string& path)
if (ret.find(serial) != ret.end()) if (ret.find(serial) != ret.end())
{ {
Log_WarningPrintf("Duplicate entry: '%s'", serial.c_str()); Log_WarningFmt("Duplicate entry: '%s'", serial);
continue; continue;
} }
@ -1040,7 +1043,7 @@ GameList::PlayedTimeEntry GameList::UpdatePlayedTimeFile(const std::string& path
if (!fp) if (!fp)
{ {
Log_ErrorPrintf("Failed to open '%s' for update.", path.c_str()); Log_ErrorFmt("Failed to open '{}' for update.", path);
return new_entry; return new_entry;
} }
@ -1071,7 +1074,7 @@ GameList::PlayedTimeEntry GameList::UpdatePlayedTimeFile(const std::string& path
if (FileSystem::FSeek64(fp.get(), line_pos, SEEK_SET) != 0 || if (FileSystem::FSeek64(fp.get(), line_pos, SEEK_SET) != 0 ||
std::fwrite(new_line.data(), new_line.length(), 1, fp.get()) != 1) std::fwrite(new_line.data(), new_line.length(), 1, fp.get()) != 1)
{ {
Log_ErrorPrintf("Failed to update '%s'.", path.c_str()); Log_ErrorFmt("Failed to update '%s'.", path);
} }
return line_entry; return line_entry;
@ -1084,7 +1087,7 @@ GameList::PlayedTimeEntry GameList::UpdatePlayedTimeFile(const std::string& path
if (FileSystem::FSeek64(fp.get(), 0, SEEK_END) != 0 || if (FileSystem::FSeek64(fp.get(), 0, SEEK_END) != 0 ||
std::fwrite(new_line.data(), new_line.length(), 1, fp.get()) != 1) std::fwrite(new_line.data(), new_line.length(), 1, fp.get()) != 1)
{ {
Log_ErrorPrintf("Failed to write '%s'.", path.c_str()); Log_ErrorFmt("Failed to write '%s'.", path);
} }
} }
@ -1097,8 +1100,8 @@ void GameList::AddPlayedTimeForSerial(const std::string& serial, std::time_t las
return; return;
const PlayedTimeEntry pt(UpdatePlayedTimeFile(GetPlayedTimeFile(), serial, last_time, add_time)); const PlayedTimeEntry pt(UpdatePlayedTimeFile(GetPlayedTimeFile(), serial, last_time, add_time));
Log_VerbosePrintf("Add %u seconds play time to %s -> now %u", static_cast<unsigned>(add_time), serial.c_str(), Log_VerboseFmt("Add {} seconds play time to {} -> now {}", static_cast<unsigned>(add_time), serial.c_str(),
static_cast<unsigned>(pt.total_played_time)); static_cast<unsigned>(pt.total_played_time));
std::unique_lock<std::recursive_mutex> lock(s_mutex); std::unique_lock<std::recursive_mutex> lock(s_mutex);
for (GameList::Entry& entry : s_entries) for (GameList::Entry& entry : s_entries)

View File

@ -167,7 +167,7 @@ static std::optional<std::string> Cmd$G(std::string_view data)
} }
else else
{ {
Log_ErrorPrintf("Wrong payload size for 'G' command, expected %d got %zu", NUM_GDB_REGISTERS * 8, data.size()); Log_ErrorFmt("Wrong payload size for 'G' command, expected {} got {}", NUM_GDB_REGISTERS * 8, data.size());
} }
return {""}; return {""};
@ -317,7 +317,7 @@ std::string ProcessPacket(std::string_view data)
auto packet = DeserializePacket(trimmedData); auto packet = DeserializePacket(trimmedData);
if (!packet) if (!packet)
{ {
Log_ErrorPrintf("Malformed packet '%*s'", static_cast<int>(trimmedData.size()), trimmedData.data()); Log_ErrorFmt("Malformed packet '{}'", trimmedData);
return "-"; return "-";
} }
@ -329,7 +329,7 @@ std::string ProcessPacket(std::string_view data)
{ {
if (packet->starts_with(command.first)) if (packet->starts_with(command.first))
{ {
Log_DebugPrintf("Processing command '%s'", command.first); Log_DebugFmt("Processing command '{}'", command.first);
// Invoke command, remove command name from payload. // Invoke command, remove command name from payload.
reply = command.second(packet->substr(strlen(command.first))); reply = command.second(packet->substr(strlen(command.first)));
@ -339,9 +339,8 @@ std::string ProcessPacket(std::string_view data)
} }
if (!processed) if (!processed)
{ Log_WarningFmt("Failed to process packet '{}'", trimmedData);
Log_WarningPrintf("Failed to process packet '%*s'", static_cast<int>(trimmedData.size()), trimmedData.data());
}
return reply ? "+" + SerializePacket(*reply) : "+"; return reply ? "+" + SerializePacket(*reply) : "+";
} }

View File

@ -486,7 +486,7 @@ u32 GPU::ReadRegister(u32 offset)
} }
default: default:
Log_ErrorPrintf("Unhandled register read: %02X", offset); Log_ErrorFmt("Unhandled register read: {:02X}", offset);
return UINT32_C(0xFFFFFFFF); return UINT32_C(0xFFFFFFFF);
} }
} }
@ -505,7 +505,7 @@ void GPU::WriteRegister(u32 offset, u32 value)
return; return;
default: default:
Log_ErrorPrintf("Unhandled register write: %02X <- %08X", offset, value); Log_ErrorFmt("Unhandled register write: {:02X} <- {:08X}", offset, value);
return; return;
} }
} }
@ -514,7 +514,7 @@ void GPU::DMARead(u32* words, u32 word_count)
{ {
if (m_GPUSTAT.dma_direction != DMADirection::GPUREADtoCPU) if (m_GPUSTAT.dma_direction != DMADirection::GPUREADtoCPU)
{ {
Log_ErrorPrintf("Invalid DMA direction from GPU DMA read"); Log_ErrorPrint("Invalid DMA direction from GPU DMA read");
std::fill_n(words, word_count, UINT32_C(0xFFFFFFFF)); std::fill_n(words, word_count, UINT32_C(0xFFFFFFFF));
return; return;
} }
@ -1017,7 +1017,7 @@ void GPU::CRTCTickEvent(TickCount ticks)
{ {
if (new_vblank) if (new_vblank)
{ {
Log_DebugPrintf("Now in v-blank"); Log_DebugPrint("Now in v-blank");
// flush any pending draws and "scan out" the image // flush any pending draws and "scan out" the image
// TODO: move present in here I guess // TODO: move present in here I guess
@ -1123,10 +1123,10 @@ void GPU::ConvertScreenCoordinatesToDisplayCoordinates(float window_x, float win
*display_x = scaled_display_x * static_cast<float>(m_crtc_state.display_width); *display_x = scaled_display_x * static_cast<float>(m_crtc_state.display_width);
*display_y = scaled_display_y * static_cast<float>(m_crtc_state.display_height); *display_y = scaled_display_y * static_cast<float>(m_crtc_state.display_height);
Log_DevPrintf("win %.0f,%.0f -> local %.0f,%.0f, disp %.2f,%.2f (size %u,%u frac %f,%f)", window_x, window_y, Log_DevFmt("win {:.0f},{:.0f} -> local {:.0f},{:.0f}, disp {:.2f},{:.2f} (size {},{} frac {},{})", window_x, window_y,
window_x - draw_rc.left, window_y - draw_rc.top, *display_x, *display_y, m_crtc_state.display_width, window_x - draw_rc.left, window_y - draw_rc.top, *display_x, *display_y, m_crtc_state.display_width,
m_crtc_state.display_height, *display_x / static_cast<float>(m_crtc_state.display_width), m_crtc_state.display_height, *display_x / static_cast<float>(m_crtc_state.display_width),
*display_y / static_cast<float>(m_crtc_state.display_height)); *display_y / static_cast<float>(m_crtc_state.display_height));
} }
bool GPU::ConvertDisplayCoordinatesToBeamTicksAndLines(float display_x, float display_y, float x_scale, u32* out_tick, bool GPU::ConvertDisplayCoordinatesToBeamTicksAndLines(float display_x, float display_y, float x_scale, u32* out_tick,
@ -1207,7 +1207,7 @@ u32 GPU::ReadGPUREAD()
if (++m_vram_transfer.row == m_vram_transfer.height) if (++m_vram_transfer.row == m_vram_transfer.height)
{ {
Log_DebugPrintf("End of VRAM->CPU transfer"); Log_DebugPrint("End of VRAM->CPU transfer");
m_vram_transfer = {}; m_vram_transfer = {};
m_blitter_state = BlitterState::Idle; m_blitter_state = BlitterState::Idle;
@ -1230,7 +1230,7 @@ void GPU::WriteGP1(u32 value)
{ {
case 0x00: // Reset GPU case 0x00: // Reset GPU
{ {
Log_DebugPrintf("GP1 reset GPU"); Log_DebugPrint("GP1 reset GPU");
m_command_tick_event->InvokeEarly(); m_command_tick_event->InvokeEarly();
SynchronizeCRTC(); SynchronizeCRTC();
SoftReset(); SoftReset();
@ -1239,7 +1239,7 @@ void GPU::WriteGP1(u32 value)
case 0x01: // Clear FIFO case 0x01: // Clear FIFO
{ {
Log_DebugPrintf("GP1 clear FIFO"); Log_DebugPrint("GP1 clear FIFO");
m_command_tick_event->InvokeEarly(); m_command_tick_event->InvokeEarly();
SynchronizeCRTC(); SynchronizeCRTC();
@ -1262,7 +1262,7 @@ void GPU::WriteGP1(u32 value)
case 0x02: // Acknowledge Interrupt case 0x02: // Acknowledge Interrupt
{ {
Log_DebugPrintf("Acknowledge interrupt"); Log_DebugPrint("Acknowledge interrupt");
m_GPUSTAT.interrupt_request = false; m_GPUSTAT.interrupt_request = false;
} }
break; break;
@ -1270,7 +1270,7 @@ void GPU::WriteGP1(u32 value)
case 0x03: // Display on/off case 0x03: // Display on/off
{ {
const bool disable = ConvertToBoolUnchecked(value & 0x01); const bool disable = ConvertToBoolUnchecked(value & 0x01);
Log_DebugPrintf("Display %s", disable ? "disabled" : "enabled"); Log_DebugFmt("Display {}", disable ? "disabled" : "enabled");
SynchronizeCRTC(); SynchronizeCRTC();
if (!m_GPUSTAT.display_disable && disable && m_GPUSTAT.vertical_interlace && !m_force_progressive_scan) if (!m_GPUSTAT.display_disable && disable && m_GPUSTAT.vertical_interlace && !m_force_progressive_scan)
@ -1282,7 +1282,7 @@ void GPU::WriteGP1(u32 value)
case 0x04: // DMA Direction case 0x04: // DMA Direction
{ {
Log_DebugPrintf("DMA direction <- 0x%02X", static_cast<u32>(param)); Log_DebugFmt("DMA direction <- 0x{:02X}", static_cast<u32>(param));
if (m_GPUSTAT.dma_direction != static_cast<DMADirection>(param)) if (m_GPUSTAT.dma_direction != static_cast<DMADirection>(param))
{ {
m_GPUSTAT.dma_direction = static_cast<DMADirection>(param); m_GPUSTAT.dma_direction = static_cast<DMADirection>(param);
@ -1294,7 +1294,7 @@ void GPU::WriteGP1(u32 value)
case 0x05: // Set display start address case 0x05: // Set display start address
{ {
const u32 new_value = param & CRTCState::Regs::DISPLAY_ADDRESS_START_MASK; const u32 new_value = param & CRTCState::Regs::DISPLAY_ADDRESS_START_MASK;
Log_DebugPrintf("Display address start <- 0x%08X", new_value); Log_DebugFmt("Display address start <- 0x{:08X}", new_value);
System::IncrementInternalFrameNumber(); System::IncrementInternalFrameNumber();
if (m_crtc_state.regs.display_address_start != new_value) if (m_crtc_state.regs.display_address_start != new_value)
@ -1309,7 +1309,7 @@ void GPU::WriteGP1(u32 value)
case 0x06: // Set horizontal display range case 0x06: // Set horizontal display range
{ {
const u32 new_value = param & CRTCState::Regs::HORIZONTAL_DISPLAY_RANGE_MASK; const u32 new_value = param & CRTCState::Regs::HORIZONTAL_DISPLAY_RANGE_MASK;
Log_DebugPrintf("Horizontal display range <- 0x%08X", new_value); Log_DebugFmt("Horizontal display range <- 0x{:08X}", new_value);
if (m_crtc_state.regs.horizontal_display_range != new_value) if (m_crtc_state.regs.horizontal_display_range != new_value)
{ {
@ -1323,7 +1323,7 @@ void GPU::WriteGP1(u32 value)
case 0x07: // Set vertical display range case 0x07: // Set vertical display range
{ {
const u32 new_value = param & CRTCState::Regs::VERTICAL_DISPLAY_RANGE_MASK; const u32 new_value = param & CRTCState::Regs::VERTICAL_DISPLAY_RANGE_MASK;
Log_DebugPrintf("Vertical display range <- 0x%08X", new_value); Log_DebugFmt("Vertical display range <- 0x{:08X}", new_value);
if (m_crtc_state.regs.vertical_display_range != new_value) if (m_crtc_state.regs.vertical_display_range != new_value)
{ {
@ -1358,7 +1358,7 @@ void GPU::WriteGP1(u32 value)
new_GPUSTAT.vertical_interlace = dm.vertical_interlace; new_GPUSTAT.vertical_interlace = dm.vertical_interlace;
new_GPUSTAT.horizontal_resolution_2 = dm.horizontal_resolution_2; new_GPUSTAT.horizontal_resolution_2 = dm.horizontal_resolution_2;
new_GPUSTAT.reverse_flag = dm.reverse_flag; new_GPUSTAT.reverse_flag = dm.reverse_flag;
Log_DebugPrintf("Set display mode <- 0x%08X", dm.bits); Log_DebugFmt("Set display mode <- 0x{:08X}", dm.bits);
if (!m_GPUSTAT.vertical_interlace && dm.vertical_interlace && !m_force_progressive_scan) if (!m_GPUSTAT.vertical_interlace && dm.vertical_interlace && !m_force_progressive_scan)
{ {
@ -1381,7 +1381,7 @@ void GPU::WriteGP1(u32 value)
case 0x09: // Allow texture disable case 0x09: // Allow texture disable
{ {
m_set_texture_disable_mask = ConvertToBoolUnchecked(param & 0x01); m_set_texture_disable_mask = ConvertToBoolUnchecked(param & 0x01);
Log_DebugPrintf("Set texture disable mask <- %s", m_set_texture_disable_mask ? "allowed" : "ignored"); Log_DebugFmt("Set texture disable mask <- {}", m_set_texture_disable_mask ? "allowed" : "ignored");
} }
break; break;
@ -1406,8 +1406,7 @@ void GPU::WriteGP1(u32 value)
} }
break; break;
default: [[unlikely]] default : Log_ErrorFmt("Unimplemented GP1 command 0x{:02X}", command);
Log_ErrorPrintf("Unimplemented GP1 command 0x%02X", command);
break; break;
} }
} }
@ -1426,14 +1425,14 @@ void GPU::HandleGetGPUInfoCommand(u32 value)
case 0x02: // Get Texture Window case 0x02: // Get Texture Window
{ {
Log_DebugPrintf("Get texture window"); Log_DebugPrint("Get texture window");
m_GPUREAD_latch = m_draw_mode.texture_window_value; m_GPUREAD_latch = m_draw_mode.texture_window_value;
} }
break; break;
case 0x03: // Get Draw Area Top Left case 0x03: // Get Draw Area Top Left
{ {
Log_DebugPrintf("Get drawing area top left"); Log_DebugPrint("Get drawing area top left");
m_GPUREAD_latch = m_GPUREAD_latch =
((m_drawing_area.left & UINT32_C(0b1111111111)) | ((m_drawing_area.top & UINT32_C(0b1111111111)) << 10)); ((m_drawing_area.left & UINT32_C(0b1111111111)) | ((m_drawing_area.top & UINT32_C(0b1111111111)) << 10));
} }
@ -1441,7 +1440,7 @@ void GPU::HandleGetGPUInfoCommand(u32 value)
case 0x04: // Get Draw Area Bottom Right case 0x04: // Get Draw Area Bottom Right
{ {
Log_DebugPrintf("Get drawing area bottom right"); Log_DebugPrint("Get drawing area bottom right");
m_GPUREAD_latch = m_GPUREAD_latch =
((m_drawing_area.right & UINT32_C(0b1111111111)) | ((m_drawing_area.bottom & UINT32_C(0b1111111111)) << 10)); ((m_drawing_area.right & UINT32_C(0b1111111111)) | ((m_drawing_area.bottom & UINT32_C(0b1111111111)) << 10));
} }
@ -1449,14 +1448,13 @@ void GPU::HandleGetGPUInfoCommand(u32 value)
case 0x05: // Get Drawing Offset case 0x05: // Get Drawing Offset
{ {
Log_DebugPrintf("Get drawing offset"); Log_DebugPrint("Get drawing offset");
m_GPUREAD_latch = m_GPUREAD_latch =
((m_drawing_offset.x & INT32_C(0b11111111111)) | ((m_drawing_offset.y & INT32_C(0b11111111111)) << 11)); ((m_drawing_offset.x & INT32_C(0b11111111111)) | ((m_drawing_offset.y & INT32_C(0b11111111111)) << 11));
} }
break; break;
default: [[unlikely]] default : Log_WarningFmt("Unhandled GetGPUInfo(0x{:02X})", subcommand);
Log_WarningPrintf("Unhandled GetGPUInfo(0x%02X)", ZeroExtend32(subcommand));
break; break;
} }
} }
@ -1699,7 +1697,7 @@ void GPU::SetTextureWindow(u32 value)
const u8 mask_y = Truncate8((value >> 5) & UINT32_C(0x1F)); const u8 mask_y = Truncate8((value >> 5) & UINT32_C(0x1F));
const u8 offset_x = Truncate8((value >> 10) & UINT32_C(0x1F)); const u8 offset_x = Truncate8((value >> 10) & UINT32_C(0x1F));
const u8 offset_y = Truncate8((value >> 15) & UINT32_C(0x1F)); const u8 offset_y = Truncate8((value >> 15) & UINT32_C(0x1F));
Log_DebugPrintf("Set texture window %02X %02X %02X %02X", mask_x, mask_y, offset_x, offset_y); Log_DebugFmt("Set texture window {:02X} {:02X} {:02X} {:02X}", mask_x, mask_y, offset_x, offset_y);
m_draw_mode.texture_window.and_x = ~(mask_x * 8); m_draw_mode.texture_window.and_x = ~(mask_x * 8);
m_draw_mode.texture_window.and_y = ~(mask_y * 8); m_draw_mode.texture_window.and_y = ~(mask_y * 8);
@ -2464,7 +2462,7 @@ bool CompressAndWriteTextureToFile(u32 width, u32 height, std::string filename,
} }
else else
{ {
Log_ErrorPrintf("Unknown extension in filename '%s' or save error: '%s'", filename.c_str(), extension); Log_ErrorFmt("Unknown extension in filename '{}' or save error: '{}'", filename, extension);
result = false; result = false;
} }
} }
@ -2475,7 +2473,7 @@ bool CompressAndWriteTextureToFile(u32 width, u32 height, std::string filename,
} }
else else
{ {
Log_ErrorPrintf("Unable to determine file extension for '%s'", filename.c_str()); Log_ErrorFmt("Unable to determine file extension for '{}'", filename);
result = false; result = false;
} }
@ -2573,10 +2571,11 @@ bool GPU::WriteDisplayTextureToFile(std::string filename, bool compress_on_threa
RestoreDeviceContext(); RestoreDeviceContext();
auto fp = FileSystem::OpenManagedCFile(filename.c_str(), "wb"); Error error;
auto fp = FileSystem::OpenManagedCFile(filename.c_str(), "wb", &error);
if (!fp) if (!fp)
{ {
Log_ErrorPrintf("Can't open file '%s': errno %d", filename.c_str(), errno); Log_ErrorFmt("Can't open file '{}': {}", Path::GetFileName(filename), error.GetDescription());
return false; return false;
} }
@ -2735,7 +2734,7 @@ bool GPU::DumpVRAMToFile(const char* filename)
} }
else else
{ {
Log_ErrorPrintf("Unknown extension: '%s'", filename); Log_ErrorFmt("Unknown extension: '{}'", filename);
return false; return false;
} }
} }

View File

@ -49,7 +49,7 @@ void GPU::TryExecuteCommands()
m_blit_buffer.push_back(FifoPop()); m_blit_buffer.push_back(FifoPop());
m_blit_remaining_words -= words_to_copy; m_blit_remaining_words -= words_to_copy;
Log_DebugPrintf("VRAM write burst of %u words, %u words remaining", words_to_copy, m_blit_remaining_words); Log_DebugFmt("VRAM write burst of {} words, {} words remaining", words_to_copy, m_blit_remaining_words);
if (m_blit_remaining_words == 0) if (m_blit_remaining_words == 0)
FinishVRAMWrite(); FinishVRAMWrite();
@ -84,12 +84,12 @@ void GPU::TryExecuteCommands()
m_blit_buffer.push_back(FifoPop()); m_blit_buffer.push_back(FifoPop());
} }
Log_DebugPrintf("Added %u words to polyline", words_to_copy); Log_DebugFmt("Added {} words to polyline", words_to_copy);
if (found_terminator) if (found_terminator)
{ {
// drop terminator // drop terminator
m_fifo.RemoveOne(); m_fifo.RemoveOne();
Log_DebugPrintf("Drawing poly-line with %u vertices", GetPolyLineVertexCount()); Log_DebugFmt("Drawing poly-line with {} vertices", GetPolyLineVertexCount());
DispatchRenderCommand(); DispatchRenderCommand();
m_blit_buffer.clear(); m_blit_buffer.clear();
EndCommand(); EndCommand();
@ -175,12 +175,12 @@ GPU::GP0CommandHandlerTable GPU::GenerateGP0CommandHandlerTable()
bool GPU::HandleUnknownGP0Command() bool GPU::HandleUnknownGP0Command()
{ {
const u32 command = FifoPeek() >> 24; const u32 command = FifoPeek() >> 24;
Log_ErrorPrintf("Unimplemented GP0 command 0x%02X", command); Log_ErrorFmt("Unimplemented GP0 command 0x{:02X}", command);
SmallString dump; SmallString dump;
for (u32 i = 0; i < m_fifo.GetSize(); i++) for (u32 i = 0; i < m_fifo.GetSize(); i++)
dump.append_format("{}{:08X}", (i > 0) ? " " : "", FifoPeek(i)); dump.append_format("{}{:08X}", (i > 0) ? " " : "", FifoPeek(i));
Log_ErrorPrintf("FIFO: %s", dump.c_str()); Log_ErrorFmt("FIFO: {}", dump);
m_fifo.RemoveOne(); m_fifo.RemoveOne();
EndCommand(); EndCommand();
@ -196,7 +196,7 @@ bool GPU::HandleNOPCommand()
bool GPU::HandleClearCacheCommand() bool GPU::HandleClearCacheCommand()
{ {
Log_DebugPrintf("GP0 clear cache"); Log_DebugPrint("GP0 clear cache");
m_draw_mode.SetTexturePageChanged(); m_draw_mode.SetTexturePageChanged();
InvalidateCLUT(); InvalidateCLUT();
m_fifo.RemoveOne(); m_fifo.RemoveOne();
@ -207,7 +207,7 @@ bool GPU::HandleClearCacheCommand()
bool GPU::HandleInterruptRequestCommand() bool GPU::HandleInterruptRequestCommand()
{ {
Log_DebugPrintf("GP0 interrupt request"); Log_DebugPrint("GP0 interrupt request");
m_GPUSTAT.interrupt_request = true; m_GPUSTAT.interrupt_request = true;
InterruptController::SetLineState(InterruptController::IRQ::GPU, m_GPUSTAT.interrupt_request); InterruptController::SetLineState(InterruptController::IRQ::GPU, m_GPUSTAT.interrupt_request);
@ -221,7 +221,7 @@ bool GPU::HandleInterruptRequestCommand()
bool GPU::HandleSetDrawModeCommand() bool GPU::HandleSetDrawModeCommand()
{ {
const u32 param = FifoPop() & 0x00FFFFFFu; const u32 param = FifoPop() & 0x00FFFFFFu;
Log_DebugPrintf("Set draw mode %08X", param); Log_DebugFmt("Set draw mode {:08X}", param);
SetDrawMode(Truncate16(param)); SetDrawMode(Truncate16(param));
AddCommandTicks(1); AddCommandTicks(1);
EndCommand(); EndCommand();
@ -242,7 +242,7 @@ bool GPU::HandleSetDrawingAreaTopLeftCommand()
const u32 param = FifoPop() & 0x00FFFFFFu; const u32 param = FifoPop() & 0x00FFFFFFu;
const u32 left = param & DRAWING_AREA_COORD_MASK; const u32 left = param & DRAWING_AREA_COORD_MASK;
const u32 top = (param >> 10) & DRAWING_AREA_COORD_MASK; const u32 top = (param >> 10) & DRAWING_AREA_COORD_MASK;
Log_DebugPrintf("Set drawing area top-left: (%u, %u)", left, top); Log_DebugFmt("Set drawing area top-left: ({}, {})", left, top);
if (m_drawing_area.left != left || m_drawing_area.top != top) if (m_drawing_area.left != left || m_drawing_area.top != top)
{ {
FlushRender(); FlushRender();
@ -263,7 +263,7 @@ bool GPU::HandleSetDrawingAreaBottomRightCommand()
const u32 right = param & DRAWING_AREA_COORD_MASK; const u32 right = param & DRAWING_AREA_COORD_MASK;
const u32 bottom = (param >> 10) & DRAWING_AREA_COORD_MASK; const u32 bottom = (param >> 10) & DRAWING_AREA_COORD_MASK;
Log_DebugPrintf("Set drawing area bottom-right: (%u, %u)", m_drawing_area.right, m_drawing_area.bottom); Log_DebugFmt("Set drawing area bottom-right: ({}, {})", m_drawing_area.right, m_drawing_area.bottom);
if (m_drawing_area.right != right || m_drawing_area.bottom != bottom) if (m_drawing_area.right != right || m_drawing_area.bottom != bottom)
{ {
FlushRender(); FlushRender();
@ -283,7 +283,7 @@ bool GPU::HandleSetDrawingOffsetCommand()
const u32 param = FifoPop() & 0x00FFFFFFu; const u32 param = FifoPop() & 0x00FFFFFFu;
const s32 x = SignExtendN<11, s32>(param & 0x7FFu); const s32 x = SignExtendN<11, s32>(param & 0x7FFu);
const s32 y = SignExtendN<11, s32>((param >> 11) & 0x7FFu); const s32 y = SignExtendN<11, s32>((param >> 11) & 0x7FFu);
Log_DebugPrintf("Set drawing offset (%d, %d)", m_drawing_offset.x, m_drawing_offset.y); Log_DebugFmt("Set drawing offset ({}, {})", m_drawing_offset.x, m_drawing_offset.y);
if (m_drawing_offset.x != x || m_drawing_offset.y != y) if (m_drawing_offset.x != x || m_drawing_offset.y != y)
{ {
FlushRender(); FlushRender();
@ -308,8 +308,8 @@ bool GPU::HandleSetMaskBitCommand()
FlushRender(); FlushRender();
m_GPUSTAT.bits = (m_GPUSTAT.bits & ~gpustat_mask) | gpustat_bits; m_GPUSTAT.bits = (m_GPUSTAT.bits & ~gpustat_mask) | gpustat_bits;
} }
Log_DebugPrintf("Set mask bit %u %u", BoolToUInt32(m_GPUSTAT.set_mask_while_drawing), Log_DebugFmt("Set mask bit {} {}", BoolToUInt32(m_GPUSTAT.set_mask_while_drawing),
BoolToUInt32(m_GPUSTAT.check_mask_before_draw)); BoolToUInt32(m_GPUSTAT.check_mask_before_draw));
AddCommandTicks(1); AddCommandTicks(1);
EndCommand(); EndCommand();
@ -335,11 +335,10 @@ bool GPU::HandleRenderPolygonCommand()
s_setup_time[BoolToUInt8(rc.quad_polygon)][BoolToUInt8(rc.shading_enable)][BoolToUInt8(rc.texture_enable)])); s_setup_time[BoolToUInt8(rc.quad_polygon)][BoolToUInt8(rc.shading_enable)][BoolToUInt8(rc.texture_enable)]));
AddCommandTicks(setup_ticks); AddCommandTicks(setup_ticks);
Log_TracePrintf("Render %s %s %s %s polygon (%u verts, %u words per vert), %d setup ticks", Log_TraceFmt("Render {} {} {} {} polygon ({} verts, {} words per vert), {} setup ticks",
rc.quad_polygon ? "four-point" : "three-point", rc.quad_polygon ? "four-point" : "three-point", rc.transparency_enable ? "semi-transparent" : "opaque",
rc.transparency_enable ? "semi-transparent" : "opaque", rc.texture_enable ? "textured" : "non-textured", rc.shading_enable ? "shaded" : "monochrome",
rc.texture_enable ? "textured" : "non-textured", rc.shading_enable ? "shaded" : "monochrome", num_vertices, words_per_vertex, setup_ticks);
ZeroExtend32(num_vertices), ZeroExtend32(words_per_vertex), setup_ticks);
// set draw state up // set draw state up
if (rc.texture_enable) if (rc.texture_enable)
@ -381,10 +380,9 @@ bool GPU::HandleRenderRectangleCommand()
const TickCount setup_ticks = 16; const TickCount setup_ticks = 16;
AddCommandTicks(setup_ticks); AddCommandTicks(setup_ticks);
Log_TracePrintf("Render %s %s %s rectangle (%u words), %d setup ticks", Log_TraceFmt("Render {} {} {} rectangle ({} words), {} setup ticks",
rc.transparency_enable ? "semi-transparent" : "opaque", rc.transparency_enable ? "semi-transparent" : "opaque", rc.texture_enable ? "textured" : "non-textured",
rc.texture_enable ? "textured" : "non-textured", rc.shading_enable ? "shaded" : "monochrome", rc.shading_enable ? "shaded" : "monochrome", total_words, setup_ticks);
total_words, setup_ticks);
m_counters.num_vertices++; m_counters.num_vertices++;
m_counters.num_primitives++; m_counters.num_primitives++;
@ -405,8 +403,8 @@ bool GPU::HandleRenderLineCommand()
if (IsInterlacedRenderingEnabled() && IsCRTCScanlinePending()) if (IsInterlacedRenderingEnabled() && IsCRTCScanlinePending())
SynchronizeCRTC(); SynchronizeCRTC();
Log_TracePrintf("Render %s %s line (%u total words)", rc.transparency_enable ? "semi-transparent" : "opaque", Log_TraceFmt("Render {} {} line ({} total words)", rc.transparency_enable ? "semi-transparent" : "opaque",
rc.shading_enable ? "shaded" : "monochrome", total_words); rc.shading_enable ? "shaded" : "monochrome", total_words);
m_counters.num_vertices += 2; m_counters.num_vertices += 2;
m_counters.num_primitives++; m_counters.num_primitives++;
@ -431,8 +429,8 @@ bool GPU::HandleRenderPolyLineCommand()
const TickCount setup_ticks = 16; const TickCount setup_ticks = 16;
AddCommandTicks(setup_ticks); AddCommandTicks(setup_ticks);
Log_TracePrintf("Render %s %s poly-line, %d setup ticks", rc.transparency_enable ? "semi-transparent" : "opaque", Log_TraceFmt("Render {} {} poly-line, {} setup ticks", rc.transparency_enable ? "semi-transparent" : "opaque",
rc.shading_enable ? "shaded" : "monochrome", setup_ticks); rc.shading_enable ? "shaded" : "monochrome", setup_ticks);
m_render_command.bits = rc.bits; m_render_command.bits = rc.bits;
m_fifo.RemoveOne(); m_fifo.RemoveOne();
@ -465,7 +463,7 @@ bool GPU::HandleFillRectangleCommand()
const u32 width = ((FifoPeek() & VRAM_WIDTH_MASK) + 0xF) & ~0xF; const u32 width = ((FifoPeek() & VRAM_WIDTH_MASK) + 0xF) & ~0xF;
const u32 height = (FifoPop() >> 16) & VRAM_HEIGHT_MASK; const u32 height = (FifoPop() >> 16) & VRAM_HEIGHT_MASK;
Log_DebugPrintf("Fill VRAM rectangle offset=(%u,%u), size=(%u,%u)", dst_x, dst_y, width, height); Log_DebugFmt("Fill VRAM rectangle offset=({},{}), size=({},{})", dst_x, dst_y, width, height);
if (width > 0 && height > 0) if (width > 0 && height > 0)
FillVRAM(dst_x, dst_y, width, height, color); FillVRAM(dst_x, dst_y, width, height, color);
@ -488,8 +486,7 @@ bool GPU::HandleCopyRectangleCPUToVRAMCommand()
const u32 num_pixels = copy_width * copy_height; const u32 num_pixels = copy_width * copy_height;
const u32 num_words = ((num_pixels + 1) / 2); const u32 num_words = ((num_pixels + 1) / 2);
Log_DebugPrintf("Copy rectangle from CPU to VRAM offset=(%u,%u), size=(%u,%u)", dst_x, dst_y, copy_width, Log_DebugFmt("Copy rectangle from CPU to VRAM offset=({},{}), size=({},{})", dst_x, dst_y, copy_width, copy_height);
copy_height);
EndCommand(); EndCommand();
@ -536,9 +533,8 @@ void GPU::FinishVRAMWrite()
const u32 transferred_full_rows = transferred_pixels / m_vram_transfer.width; const u32 transferred_full_rows = transferred_pixels / m_vram_transfer.width;
const u32 transferred_width_last_row = transferred_pixels % m_vram_transfer.width; const u32 transferred_width_last_row = transferred_pixels % m_vram_transfer.width;
Log_WarningPrintf( Log_WarningFmt("Partial VRAM write - transfer finished with {} of {} words remaining ({} full rows, {} last row)",
"Partial VRAM write - transfer finished with %u of %u words remaining (%u full rows, %u last row)", m_blit_remaining_words, num_words, transferred_full_rows, transferred_width_last_row);
m_blit_remaining_words, num_words, transferred_full_rows, transferred_width_last_row);
const u8* blit_ptr = reinterpret_cast<const u8*>(m_blit_buffer.data()); const u8* blit_ptr = reinterpret_cast<const u8*>(m_blit_buffer.data());
if (transferred_full_rows > 0) if (transferred_full_rows > 0)
@ -570,8 +566,8 @@ bool GPU::HandleCopyRectangleVRAMToCPUCommand()
m_vram_transfer.width = ((Truncate16(FifoPeek()) - 1) & VRAM_WIDTH_MASK) + 1; m_vram_transfer.width = ((Truncate16(FifoPeek()) - 1) & VRAM_WIDTH_MASK) + 1;
m_vram_transfer.height = ((Truncate16(FifoPop() >> 16) - 1) & VRAM_HEIGHT_MASK) + 1; m_vram_transfer.height = ((Truncate16(FifoPop() >> 16) - 1) & VRAM_HEIGHT_MASK) + 1;
Log_DebugPrintf("Copy rectangle from VRAM to CPU offset=(%u,%u), size=(%u,%u)", m_vram_transfer.x, m_vram_transfer.y, Log_DebugFmt("Copy rectangle from VRAM to CPU offset=({},{}), size=({},{})", m_vram_transfer.x, m_vram_transfer.y,
m_vram_transfer.width, m_vram_transfer.height); m_vram_transfer.width, m_vram_transfer.height);
DebugAssert(m_vram_transfer.col == 0 && m_vram_transfer.row == 0); DebugAssert(m_vram_transfer.col == 0 && m_vram_transfer.row == 0);
// all rendering should be done first... // all rendering should be done first...
@ -606,8 +602,8 @@ bool GPU::HandleCopyRectangleVRAMToVRAMCommand()
const u32 width = ReplaceZero(FifoPeek() & VRAM_WIDTH_MASK, 0x400); const u32 width = ReplaceZero(FifoPeek() & VRAM_WIDTH_MASK, 0x400);
const u32 height = ReplaceZero((FifoPop() >> 16) & VRAM_HEIGHT_MASK, 0x200); const u32 height = ReplaceZero((FifoPop() >> 16) & VRAM_HEIGHT_MASK, 0x200);
Log_DebugPrintf("Copy rectangle from VRAM to VRAM src=(%u,%u), dst=(%u,%u), size=(%u,%u)", src_x, src_y, dst_x, dst_y, Log_DebugFmt("Copy rectangle from VRAM to VRAM src=({},{}), dst=({},{}), size=({},{})", src_x, src_y, dst_x, dst_y,
width, height); width, height);
// Some VRAM copies aren't going to do anything. Most games seem to send a 2x2 VRAM copy at the end of a frame. // Some VRAM copies aren't going to do anything. Most games seem to send a 2x2 VRAM copy at the end of a frame.
const bool skip_copy = const bool skip_copy =

View File

@ -2556,7 +2556,7 @@ void GPU_HW::EnsureVertexBufferSpaceForCurrentCommand()
void GPU_HW::ResetBatchVertexDepth() void GPU_HW::ResetBatchVertexDepth()
{ {
Log_PerfPrint("Resetting batch vertex depth"); Log_DevPrint("Resetting batch vertex depth");
if (m_vram_depth_texture && !m_pgxp_depth_buffer) if (m_vram_depth_texture && !m_pgxp_depth_buffer)
UpdateDepthBufferFromMaskBit(); UpdateDepthBufferFromMaskBit();

View File

@ -99,8 +99,8 @@ GPUTexture* GPU_SW::GetDisplayTexture(u32 width, u32 height, GPUTexture::Format
g_gpu_device->RecycleTexture(std::move(m_upload_texture)); g_gpu_device->RecycleTexture(std::move(m_upload_texture));
m_upload_texture = m_upload_texture =
g_gpu_device->FetchTexture(width, height, 1, 1, 1, GPUTexture::Type::DynamicTexture, format, nullptr, 0); g_gpu_device->FetchTexture(width, height, 1, 1, 1, GPUTexture::Type::DynamicTexture, format, nullptr, 0);
if (!m_upload_texture) if (!m_upload_texture) [[unlikely]]
Log_ErrorPrintf("Failed to create %ux%u %u texture", width, height, static_cast<u32>(format)); Log_ErrorFmt("Failed to create {}x{} {} texture", width, height, static_cast<u32>(format));
} }
return m_upload_texture.get(); return m_upload_texture.get();
@ -586,8 +586,8 @@ void GPU_SW::DispatchRenderCommand()
if ((max_x - min_x) >= MAX_PRIMITIVE_WIDTH || (max_y - min_y) >= MAX_PRIMITIVE_HEIGHT) if ((max_x - min_x) >= MAX_PRIMITIVE_WIDTH || (max_y - min_y) >= MAX_PRIMITIVE_HEIGHT)
{ {
Log_DebugPrintf("Culling too-large polygon: %d,%d %d,%d %d,%d", cmd->vertices[0].x, cmd->vertices[0].y, Log_DebugFmt("Culling too-large polygon: {},{} {},{} {},{}", cmd->vertices[0].x, cmd->vertices[0].y,
cmd->vertices[1].x, cmd->vertices[1].y, cmd->vertices[2].x, cmd->vertices[2].y); cmd->vertices[1].x, cmd->vertices[1].y, cmd->vertices[2].x, cmd->vertices[2].y);
} }
else else
{ {
@ -607,9 +607,9 @@ void GPU_SW::DispatchRenderCommand()
// Cull polygons which are too large. // Cull polygons which are too large.
if ((max_x_123 - min_x_123) >= MAX_PRIMITIVE_WIDTH || (max_y_123 - min_y_123) >= MAX_PRIMITIVE_HEIGHT) if ((max_x_123 - min_x_123) >= MAX_PRIMITIVE_WIDTH || (max_y_123 - min_y_123) >= MAX_PRIMITIVE_HEIGHT)
{ {
Log_DebugPrintf("Culling too-large polygon (quad second half): %d,%d %d,%d %d,%d", cmd->vertices[2].x, Log_DebugFmt("Culling too-large polygon (quad second half): {},{} {},{} {},{}", cmd->vertices[2].x,
cmd->vertices[2].y, cmd->vertices[1].x, cmd->vertices[1].y, cmd->vertices[0].x, cmd->vertices[2].y, cmd->vertices[1].x, cmd->vertices[1].y, cmd->vertices[0].x,
cmd->vertices[0].y); cmd->vertices[0].y);
} }
else else
{ {
@ -667,7 +667,7 @@ void GPU_SW::DispatchRenderCommand()
if (cmd->width >= MAX_PRIMITIVE_WIDTH || cmd->height >= MAX_PRIMITIVE_HEIGHT) if (cmd->width >= MAX_PRIMITIVE_WIDTH || cmd->height >= MAX_PRIMITIVE_HEIGHT)
{ {
Log_DebugPrintf("Culling too-large rectangle: %d,%d %dx%d", cmd->x, cmd->y, cmd->width, cmd->height); Log_DebugFmt("Culling too-large rectangle: {},{} {}x{}", cmd->x, cmd->y, cmd->width, cmd->height);
return; return;
} }
} }
@ -724,8 +724,8 @@ void GPU_SW::DispatchRenderCommand()
const auto [min_y, max_y] = MinMax(cmd->vertices[0].y, cmd->vertices[1].y); const auto [min_y, max_y] = MinMax(cmd->vertices[0].y, cmd->vertices[1].y);
if ((max_x - min_x) >= MAX_PRIMITIVE_WIDTH || (max_y - min_y) >= MAX_PRIMITIVE_HEIGHT) if ((max_x - min_x) >= MAX_PRIMITIVE_WIDTH || (max_y - min_y) >= MAX_PRIMITIVE_HEIGHT)
{ {
Log_DebugPrintf("Culling too-large line: %d,%d - %d,%d", cmd->vertices[0].y, cmd->vertices[0].y, Log_DebugFmt("Culling too-large line: {},{} - {},{}", cmd->vertices[0].y, cmd->vertices[0].y,
cmd->vertices[1].x, cmd->vertices[1].y); cmd->vertices[1].x, cmd->vertices[1].y);
return; return;
} }
@ -759,8 +759,8 @@ void GPU_SW::DispatchRenderCommand()
const auto [min_y, max_y] = MinMax(cmd->vertices[i - 1].y, cmd->vertices[i].y); const auto [min_y, max_y] = MinMax(cmd->vertices[i - 1].y, cmd->vertices[i].y);
if ((max_x - min_x) >= MAX_PRIMITIVE_WIDTH || (max_y - min_y) >= MAX_PRIMITIVE_HEIGHT) if ((max_x - min_x) >= MAX_PRIMITIVE_WIDTH || (max_y - min_y) >= MAX_PRIMITIVE_HEIGHT)
{ {
Log_DebugPrintf("Culling too-large line: %d,%d - %d,%d", cmd->vertices[i - 1].x, cmd->vertices[i - 1].y, Log_DebugFmt("Culling too-large line: {},{} - {},{}", cmd->vertices[i - 1].x, cmd->vertices[i - 1].y,
cmd->vertices[i].x, cmd->vertices[i].y); cmd->vertices[i].x, cmd->vertices[i].y);
} }
else else
{ {

View File

@ -217,7 +217,7 @@ void GunCon::UpdatePosition()
!g_gpu->ConvertDisplayCoordinatesToBeamTicksAndLines(display_x, display_y, m_x_scale, &tick, &line) || !g_gpu->ConvertDisplayCoordinatesToBeamTicksAndLines(display_x, display_y, m_x_scale, &tick, &line) ||
m_shoot_offscreen) m_shoot_offscreen)
{ {
Log_DebugPrintf("Lightgun out of range for window coordinates %.0f,%.0f", window_x, window_y); Log_DebugFmt("Lightgun out of range for window coordinates {:.0f},{:.0f}", window_x, window_y);
m_position_x = 0x01; m_position_x = 0x01;
m_position_y = 0x0A; m_position_y = 0x0A;
return; return;
@ -227,8 +227,8 @@ void GunCon::UpdatePosition()
const double divider = static_cast<double>(g_gpu->GetCRTCFrequency()) / 8000000.0; const double divider = static_cast<double>(g_gpu->GetCRTCFrequency()) / 8000000.0;
m_position_x = static_cast<u16>(static_cast<float>(tick) / static_cast<float>(divider)); m_position_x = static_cast<u16>(static_cast<float>(tick) / static_cast<float>(divider));
m_position_y = static_cast<u16>(line); m_position_y = static_cast<u16>(line);
Log_DebugPrintf("Lightgun window coordinates %.0f,%.0f -> tick %u line %u 8mhz ticks %u", display_x, display_y, tick, Log_DebugFmt("Lightgun window coordinates {:.0f},{:.0f} -> tick {} line {} 8mhz ticks {}", display_x, display_y, tick,
line, m_position_x); line, m_position_x);
} }
std::pair<float, float> GunCon::GetAbsolutePositionFromRelativeAxes() const std::pair<float, float> GunCon::GetAbsolutePositionFromRelativeAxes() const

View File

@ -264,7 +264,7 @@ bool Host::CreateGPUDevice(RenderAPI api, Error* error)
{ {
DebugAssert(!g_gpu_device); DebugAssert(!g_gpu_device);
Log_InfoPrintf("Trying to create a %s GPU device...", GPUDevice::RenderAPIToString(api)); Log_InfoFmt("Trying to create a {} GPU device...", GPUDevice::RenderAPIToString(api));
g_gpu_device = GPUDevice::CreateDeviceForAPI(api); g_gpu_device = GPUDevice::CreateDeviceForAPI(api);
std::optional<bool> exclusive_fullscreen_control; std::optional<bool> exclusive_fullscreen_control;
@ -348,7 +348,7 @@ void Host::ResizeDisplayWindow(s32 width, s32 height, float scale)
if (!g_gpu_device) if (!g_gpu_device)
return; return;
Log_DevPrintf("Display window resized to %dx%d", width, height); Log_DevFmt("Display window resized to {}x{}", width, height);
g_gpu_device->ResizeWindow(width, height, scale); g_gpu_device->ResizeWindow(width, height, scale);
ImGuiManager::WindowResized(); ImGuiManager::WindowResized();
@ -377,7 +377,7 @@ void Host::ReleaseGPUDevice()
FullscreenUI::Shutdown(); FullscreenUI::Shutdown();
ImGuiManager::Shutdown(); ImGuiManager::Shutdown();
Log_InfoPrintf("Destroying %s GPU device...", GPUDevice::RenderAPIToString(g_gpu_device->GetRenderAPI())); Log_InfoFmt("Destroying {} GPU device...", GPUDevice::RenderAPIToString(g_gpu_device->GetRenderAPI()));
g_gpu_device->Destroy(); g_gpu_device->Destroy();
g_gpu_device.reset(); g_gpu_device.reset();
} }

View File

@ -130,7 +130,7 @@ void Host::DisplayLoadingScreen(const char* message, int progress_min /*= -1*/,
{ {
if (!g_gpu_device) if (!g_gpu_device)
{ {
Log_InfoPrintf("%s: %d/%d", message, progress_value, progress_max); Log_InfoFmt("{}: {}/{}", message, progress_value, progress_max);
return; return;
} }
@ -187,14 +187,14 @@ void Host::DisplayLoadingScreen(const char* message, int progress_min /*= -1*/,
ImGui::ProgressBar(static_cast<float>(progress_value) / static_cast<float>(progress_max - progress_min), ImGui::ProgressBar(static_cast<float>(progress_value) / static_cast<float>(progress_max - progress_min),
ImVec2(-1.0f, 0.0f), ""); ImVec2(-1.0f, 0.0f), "");
Log_InfoPrintf("%s: %d/%d", message, progress_value, progress_max); Log_InfoFmt("{}: {}", message, buf);
} }
else else
{ {
const ImVec2 text_size(ImGui::CalcTextSize(message)); const ImVec2 text_size(ImGui::CalcTextSize(message));
ImGui::SetCursorPosX((width - text_size.x) / 2.0f); ImGui::SetCursorPosX((width - text_size.x) / 2.0f);
ImGui::TextUnformatted(message); ImGui::TextUnformatted(message);
Log_InfoPrintf("%s", message); Log_InfoPrint(message);
} }
} }
ImGui::End(); ImGui::End();
@ -926,8 +926,8 @@ void SaveStateSelectorUI::InitializeListEntry(ListEntry* li, ExtendedSaveStateIn
li->preview_texture = g_gpu_device->FetchTexture( li->preview_texture = g_gpu_device->FetchTexture(
ssi->screenshot_width, ssi->screenshot_height, 1, 1, 1, GPUTexture::Type::Texture, GPUTexture::Format::RGBA8, ssi->screenshot_width, ssi->screenshot_height, 1, 1, 1, GPUTexture::Type::Texture, GPUTexture::Format::RGBA8,
ssi->screenshot_data.data(), sizeof(u32) * ssi->screenshot_width); ssi->screenshot_data.data(), sizeof(u32) * ssi->screenshot_width);
if (!li->preview_texture) if (!li->preview_texture) [[unlikely]]
Log_ErrorPrintf("Failed to upload save state image to GPU"); Log_ErrorPrint("Failed to upload save state image to GPU");
} }
} }
} }

View File

@ -72,8 +72,8 @@ u32 InterruptController::ReadRegister(u32 offset)
case 0x04: // I_MASK case 0x04: // I_MASK
return s_interrupt_mask_register; return s_interrupt_mask_register;
default: default: [[unlikely]]
Log_ErrorPrintf("Invalid read at offset 0x%08X", offset); Log_ErrorFmt("Invalid read at offset 0x{:08X}", offset);
return UINT32_C(0xFFFFFFFF); return UINT32_C(0xFFFFFFFF);
} }
} }
@ -100,14 +100,14 @@ void InterruptController::WriteRegister(u32 offset, u32 value)
case 0x04: // I_MASK case 0x04: // I_MASK
{ {
Log_DebugPrintf("Interrupt mask <- 0x%08X", value); Log_DebugFmt("Interrupt mask <- 0x{:08X}", value);
s_interrupt_mask_register = value & REGISTER_WRITE_MASK; s_interrupt_mask_register = value & REGISTER_WRITE_MASK;
UpdateCPUInterruptRequest(); UpdateCPUInterruptRequest();
} }
break; break;
default: default: [[unlikely]]
Log_ErrorPrintf("Invalid write at offset 0x%08X", offset); Log_ErrorFmt("Invalid write at offset 0x{:08X}", offset);
break; break;
} }
} }

View File

@ -202,15 +202,15 @@ u32 MDEC::ReadRegister(u32 offset)
case 4: case 4:
{ {
Log_TracePrintf("MDEC status register -> 0x%08X", s_status.bits); Log_TraceFmt("MDEC status register -> 0x{:08X}", s_status.bits);
return s_status.bits; return s_status.bits;
} }
default: [[unlikely]] default:
{ {
Log_ErrorPrintf("Unknown MDEC register read: 0x%08X", offset); Log_ErrorFmt("Unknown MDEC register read: 0x{:08X}", offset);
return UINT32_C(0xFFFFFFFF); return UINT32_C(0xFFFFFFFF);
} }
} }
} }
@ -226,7 +226,7 @@ void MDEC::WriteRegister(u32 offset, u32 value)
case 4: case 4:
{ {
Log_DebugPrintf("MDEC control register <- 0x%08X", value); Log_DebugFmt("MDEC control register <- 0x{:08X}", value);
const ControlRegister cr{value}; const ControlRegister cr{value};
if (cr.reset) if (cr.reset)
@ -238,11 +238,11 @@ void MDEC::WriteRegister(u32 offset, u32 value)
return; return;
} }
default: [[unlikely]] default:
{ {
Log_ErrorPrintf("Unknown MDEC register write: 0x%08X <- 0x%08X", offset, value); Log_ErrorFmt("Unknown MDEC register write: 0x{:08X} <- 0x{:08X}", offset, value);
return; return;
} }
} }
} }
@ -250,8 +250,7 @@ void MDEC::DMARead(u32* words, u32 word_count)
{ {
if (s_data_out_fifo.GetSize() < word_count) [[unlikely]] if (s_data_out_fifo.GetSize() < word_count) [[unlikely]]
{ {
Log_WarningPrintf("Insufficient data in output FIFO (requested %u, have %u)", word_count, Log_WarningFmt("Insufficient data in output FIFO (requested {}, have {})", word_count, s_data_out_fifo.GetSize());
s_data_out_fifo.GetSize());
} }
const u32 words_to_read = std::min(word_count, s_data_out_fifo.GetSize()); const u32 words_to_read = std::min(word_count, s_data_out_fifo.GetSize());
@ -262,7 +261,7 @@ void MDEC::DMARead(u32* words, u32 word_count)
word_count -= words_to_read; word_count -= words_to_read;
} }
Log_DebugPrintf("DMA read complete, %u bytes left", static_cast<u32>(s_data_out_fifo.GetSize() * sizeof(u32))); Log_DebugFmt("DMA read complete, {} bytes left", s_data_out_fifo.GetSize() * sizeof(u32));
if (s_data_out_fifo.IsEmpty()) if (s_data_out_fifo.IsEmpty())
Execute(); Execute();
} }
@ -271,7 +270,7 @@ void MDEC::DMAWrite(const u32* words, u32 word_count)
{ {
if (s_data_in_fifo.GetSpace() < (word_count * 2)) [[unlikely]] if (s_data_in_fifo.GetSpace() < (word_count * 2)) [[unlikely]]
{ {
Log_WarningPrintf("Input FIFO overflow (writing %u, space %u)", word_count * 2, s_data_in_fifo.GetSpace()); Log_WarningFmt("Input FIFO overflow (writing {}, space {})", word_count * 2, s_data_in_fifo.GetSpace());
} }
const u32 halfwords_to_write = std::min(word_count * 2, s_data_in_fifo.GetSpace() & ~u32(2)); const u32 halfwords_to_write = std::min(word_count * 2, s_data_in_fifo.GetSpace() & ~u32(2));
@ -339,7 +338,7 @@ u32 MDEC::ReadDataRegister()
} }
else else
{ {
Log_WarningPrintf("MDEC data out FIFO empty on read and no data processing"); Log_WarningPrint("MDEC data out FIFO empty on read and no data processing");
return UINT32_C(0xFFFFFFFF); return UINT32_C(0xFFFFFFFF);
} }
} }
@ -355,7 +354,7 @@ u32 MDEC::ReadDataRegister()
void MDEC::WriteCommandRegister(u32 value) void MDEC::WriteCommandRegister(u32 value)
{ {
Log_TracePrintf("MDEC command/data register <- 0x%08X", value); Log_TraceFmt("MDEC command/data register <- 0x{:08X}", value);
s_data_in_fifo.Push(Truncate16(value)); s_data_in_fifo.Push(Truncate16(value));
s_data_in_fifo.Push(Truncate16(value >> 16)); s_data_in_fifo.Push(Truncate16(value >> 16));
@ -402,15 +401,14 @@ void MDEC::Execute()
break; break;
default: default:
Log_DevPrintf("Invalid MDEC command 0x%08X", cw.bits); [[unlikely]] Log_DevFmt("Invalid MDEC command 0x{:08X}", cw.bits);
num_words = cw.parameter_word_count.GetValue(); num_words = cw.parameter_word_count.GetValue();
new_state = State::NoCommand; new_state = State::NoCommand;
break; break;
} }
Log_DebugPrintf("MDEC command: 0x%08X (%u, %u words in parameter, %u expected)", cw.bits, Log_DebugFmt("MDEC command: 0x{:08X} ({}, {} words in parameter, {} expected)", cw.bits,
ZeroExtend32(static_cast<u8>(cw.command.GetValue())), static_cast<u8>(cw.command.GetValue()), cw.parameter_word_count.GetValue(), num_words);
ZeroExtend32(cw.parameter_word_count.GetValue()), num_words);
s_remaining_halfwords = num_words * 2; s_remaining_halfwords = num_words * 2;
s_state = new_state; s_state = new_state;
@ -510,7 +508,7 @@ bool MDEC::DecodeMonoMacroblock()
IDCT(s_blocks[0].data()); IDCT(s_blocks[0].data());
Log_DebugPrintf("Decoded mono macroblock, %u words remaining", s_remaining_halfwords / 2); Log_DebugFmt("Decoded mono macroblock, {} words remaining", s_remaining_halfwords / 2);
ResetDecoder(); ResetDecoder();
s_state = State::WritingMacroblock; s_state = State::WritingMacroblock;
@ -536,7 +534,7 @@ bool MDEC::DecodeColoredMacroblock()
return false; return false;
// done decoding // done decoding
Log_DebugPrintf("Decoded colored macroblock, %u words remaining", s_remaining_halfwords / 2); Log_DebugFmt("Decoded colored macroblock, {} words remaining", s_remaining_halfwords / 2);
ResetDecoder(); ResetDecoder();
s_state = State::WritingMacroblock; s_state = State::WritingMacroblock;
@ -553,7 +551,7 @@ bool MDEC::DecodeColoredMacroblock()
void MDEC::ScheduleBlockCopyOut(TickCount ticks) void MDEC::ScheduleBlockCopyOut(TickCount ticks)
{ {
DebugAssert(!HasPendingBlockCopyOut()); DebugAssert(!HasPendingBlockCopyOut());
Log_DebugPrintf("Scheduling block copy out in %d ticks", ticks); Log_DebugFmt("Scheduling block copy out in {} ticks", ticks);
s_block_copy_out_event->SetIntervalAndSchedule(ticks); s_block_copy_out_event->SetIntervalAndSchedule(ticks);
} }
@ -687,8 +685,8 @@ void MDEC::CopyOutBlock(void* param, TickCount ticks, TickCount ticks_late)
break; break;
} }
Log_DebugPrintf("Block copied out, fifo size = %u (%u bytes)", s_data_out_fifo.GetSize(), Log_DebugFmt("Block copied out, fifo size = {} ({} bytes)", s_data_out_fifo.GetSize(),
static_cast<u32>(s_data_out_fifo.GetSize() * sizeof(u32))); s_data_out_fifo.GetSize() * sizeof(u32));
// if we've copied out all blocks, command is complete // if we've copied out all blocks, command is complete
s_state = (s_remaining_halfwords == 0) ? State::Idle : State::DecodingMacroblock; s_state = (s_remaining_halfwords == 0) ? State::Idle : State::DecodingMacroblock;

View File

@ -143,7 +143,7 @@ bool MemoryCard::Transfer(const u8 data_in, u8* data_out)
const u8 bits = m_data[ZeroExtend32(m_address) * MemoryCardImage::FRAME_SIZE + m_sector_offset]; const u8 bits = m_data[ZeroExtend32(m_address) * MemoryCardImage::FRAME_SIZE + m_sector_offset];
if (m_sector_offset == 0) if (m_sector_offset == 0)
{ {
Log_DevPrintf("Reading memory card sector %u", ZeroExtend32(m_address)); Log_DevFmt("Reading memory card sector {}", m_address);
m_checksum = Truncate8(m_address >> 8) ^ Truncate8(m_address) ^ bits; m_checksum = Truncate8(m_address >> 8) ^ Truncate8(m_address) ^ bits;
} }
else else
@ -177,7 +177,7 @@ bool MemoryCard::Transfer(const u8 data_in, u8* data_out)
{ {
if (m_sector_offset == 0) if (m_sector_offset == 0)
{ {
Log_InfoPrintf("Writing memory card sector %u", ZeroExtend32(m_address)); Log_InfoFmt("Writing memory card sector {}", m_address);
m_checksum = Truncate8(m_address >> 8) ^ Truncate8(m_address) ^ data_in; m_checksum = Truncate8(m_address >> 8) ^ Truncate8(m_address) ^ data_in;
m_FLAG.no_write_yet = false; m_FLAG.no_write_yet = false;
} }
@ -249,12 +249,13 @@ bool MemoryCard::Transfer(const u8 data_in, u8* data_out)
break; break;
default: default:
{ [[unlikely]]
Log_ErrorPrintf("Invalid command 0x%02X", ZeroExtend32(data_in)); {
*data_out = m_FLAG.bits; Log_ErrorFmt("Invalid command 0x{:02X}", data_in);
ack = false; *data_out = m_FLAG.bits;
m_state = State::Idle; ack = false;
} m_state = State::Idle;
}
} }
} }
break; break;
@ -264,8 +265,8 @@ bool MemoryCard::Transfer(const u8 data_in, u8* data_out)
break; break;
} }
Log_DebugPrintf("Transfer, old_state=%u, new_state=%u, data_in=0x%02X, data_out=0x%02X, ack=%s", Log_DebugFmt("Transfer, old_state={}, new_state={}, data_in=0x{:02X}, data_out=0x{:02X}, ack={}",
static_cast<u32>(old_state), static_cast<u32>(m_state), data_in, *data_out, ack ? "true" : "false"); static_cast<u32>(old_state), static_cast<u32>(m_state), data_in, *data_out, ack ? "true" : "false");
m_last_byte = data_in; m_last_byte = data_in;
return ack; return ack;
} }

View File

@ -148,7 +148,7 @@ bool Multitap::Transfer(const u8 data_in, u8* data_out)
if (!ack) if (!ack)
{ {
Log_DevPrintf("Memory card transfer ended"); Log_DevPrint("Memory card transfer ended");
m_transfer_state = TransferState::Idle; m_transfer_state = TransferState::Idle;
} }
} }
@ -206,7 +206,7 @@ bool Multitap::Transfer(const u8 data_in, u8* data_out)
if (!ack) if (!ack)
{ {
Log_DevPrintf("Controller transfer ended"); Log_DevPrint("Controller transfer ended");
m_transfer_state = TransferState::Idle; m_transfer_state = TransferState::Idle;
} }
} }

View File

@ -239,16 +239,15 @@ void NeGconRumble::SetAnalogMode(bool enabled, bool show_message)
if (m_analog_mode == enabled) if (m_analog_mode == enabled)
return; return;
Log_InfoPrintf("Controller %u switched to %s mode.", m_index + 1u, enabled ? "analog" : "digital"); Log_InfoFmt("Controller {} switched to {} mode.", m_index + 1u, m_analog_mode ? "analog" : "digital");
if (show_message) if (show_message)
{ {
Host::AddIconOSDMessage(fmt::format("Controller{}AnalogMode", m_index), ICON_FA_GAMEPAD, Host::AddIconOSDMessage(
fmt::format(enabled ? fmt::format("analog_mode_toggle_{}", m_index), ICON_FA_GAMEPAD,
TRANSLATE_FS("AnalogController", "Controller {} switched to analog mode.") : enabled ? fmt::format(TRANSLATE_FS("Controller", "Controller {} switched to analog mode."), m_index + 1u) :
TRANSLATE_FS("AnalogController", "Controller {} switched to digital mode."), fmt::format(TRANSLATE_FS("Controller", "Controller {} switched to digital mode."), m_index + 1u));
m_index + 1u),
5.0f);
} }
m_analog_mode = enabled; m_analog_mode = enabled;
} }
@ -362,12 +361,12 @@ bool NeGconRumble::Transfer(const u8 data_in, u8* data_out)
if (data_in == 0x01) if (data_in == 0x01)
{ {
Log_DebugPrintf("ACK controller access"); Log_DebugPrint("ACK controller access");
m_command = Command::Ready; m_command = Command::Ready;
return true; return true;
} }
Log_DevPrintf("Unknown data_in = 0x%02X", data_in); Log_DevFmt("Unknown data_in = 0x{:02X}", data_in);
return false; return false;
} }
break; break;
@ -438,7 +437,7 @@ bool NeGconRumble::Transfer(const u8 data_in, u8* data_out)
else else
{ {
if (m_configuration_mode) if (m_configuration_mode)
Log_ErrorPrintf("Unimplemented config mode command 0x%02X", data_in); Log_ErrorFmt("Unimplemented config mode command 0x{:02X}", data_in);
*data_out = 0xFF; *data_out = 0xFF;
return false; return false;
@ -588,7 +587,7 @@ bool NeGconRumble::Transfer(const u8 data_in, u8* data_out)
m_status_byte = 0x5A; m_status_byte = 0x5A;
} }
Log_DevPrintf("0x%02x(%s) config mode", m_rx_buffer[2], m_configuration_mode ? "enter" : "leave"); Log_DevFmt("0x{:02x}({}) config mode", m_rx_buffer[2], m_configuration_mode ? "enter" : "leave");
} }
} }
break; break;
@ -597,14 +596,14 @@ bool NeGconRumble::Transfer(const u8 data_in, u8* data_out)
{ {
if (m_command_step == 2) if (m_command_step == 2)
{ {
Log_DevPrintf("analog mode val 0x%02x", data_in); Log_DevFmt("analog mode val 0x{:02x}", data_in);
if (data_in == 0x00 || data_in == 0x01) if (data_in == 0x00 || data_in == 0x01)
SetAnalogMode((data_in == 0x01), true); SetAnalogMode((data_in == 0x01), true);
} }
else if (m_command_step == 3) else if (m_command_step == 3)
{ {
Log_DevPrintf("analog mode lock 0x%02x", data_in); Log_DevFmt("analog mode lock 0x{:02x}", data_in);
if (data_in == 0x02 || data_in == 0x03) if (data_in == 0x02 || data_in == 0x03)
m_analog_locked = (data_in == 0x03); m_analog_locked = (data_in == 0x03);
@ -701,10 +700,10 @@ bool NeGconRumble::Transfer(const u8 data_in, u8* data_out)
{ {
m_command = Command::Idle; m_command = Command::Idle;
Log_DebugPrintf("Rx: %02x %02x %02x %02x %02x %02x %02x %02x", m_rx_buffer[0], m_rx_buffer[1], m_rx_buffer[2], Log_DebugFmt("Rx: {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x}", m_rx_buffer[0], m_rx_buffer[1],
m_rx_buffer[3], m_rx_buffer[4], m_rx_buffer[5], m_rx_buffer[6], m_rx_buffer[7]); m_rx_buffer[2], m_rx_buffer[3], m_rx_buffer[4], m_rx_buffer[5], m_rx_buffer[6], m_rx_buffer[7]);
Log_DebugPrintf("Tx: %02x %02x %02x %02x %02x %02x %02x %02x", m_tx_buffer[0], m_tx_buffer[1], m_tx_buffer[2], Log_DebugFmt("Tx: {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x}", m_tx_buffer[0], m_tx_buffer[1],
m_tx_buffer[3], m_tx_buffer[4], m_tx_buffer[5], m_tx_buffer[6], m_tx_buffer[7]); m_tx_buffer[2], m_tx_buffer[3], m_tx_buffer[4], m_tx_buffer[5], m_tx_buffer[6], m_tx_buffer[7]);
m_rx_buffer.fill(0x00); m_rx_buffer.fill(0x00);
m_tx_buffer.fill(0x00); m_tx_buffer.fill(0x00);

View File

@ -214,11 +214,10 @@ bool Pad::DoStateController(StateWrapper& sw, u32 i)
state_cinfo ? state_cinfo->GetDisplayName() : "", i + 1u); state_cinfo ? state_cinfo->GetDisplayName() : "", i + 1u);
} }
// dev-friendly untranslated console log. Log_DevFmt("Controller type mismatch in slot {}: state={}({}) ui={}({}) load_from_state={}", i + 1u,
Log_DevPrintf("Controller type mismatch in slot %u: state=%s(%u) ui=%s(%u) load_from_state=%s", i + 1u, state_cinfo ? state_cinfo->name : "", static_cast<unsigned>(state_controller_type),
state_cinfo ? state_cinfo->name : "", static_cast<unsigned>(state_controller_type), Controller::GetControllerInfo(controller_type)->name, static_cast<unsigned>(controller_type),
Controller::GetControllerInfo(controller_type)->name, static_cast<unsigned>(controller_type), g_settings.load_devices_from_save_states ? "yes" : "no");
g_settings.load_devices_from_save_states ? "yes" : "no");
if (g_settings.load_devices_from_save_states) if (g_settings.load_devices_from_save_states)
{ {
@ -366,7 +365,7 @@ MemoryCard* Pad::GetDummyMemcard()
void Pad::BackupMemoryCardState() void Pad::BackupMemoryCardState()
{ {
Log_DevPrintf("Backing up memory card state."); Log_DevPrint("Backing up memory card state.");
if (!s_memory_card_backup) if (!s_memory_card_backup)
{ {
@ -389,7 +388,7 @@ void Pad::RestoreMemoryCardState()
{ {
DebugAssert(s_memory_card_backup); DebugAssert(s_memory_card_backup);
Log_VerbosePrintf("Restoring backed up memory card state."); Log_VerbosePrint("Restoring backed up memory card state.");
s_memory_card_backup->SeekAbsolute(0); s_memory_card_backup->SeekAbsolute(0);
StateWrapper sw(s_memory_card_backup.get(), StateWrapper::Mode::Read, SAVE_STATE_VERSION); StateWrapper sw(s_memory_card_backup.get(), StateWrapper::Mode::Read, SAVE_STATE_VERSION);
@ -559,9 +558,8 @@ MemoryCard* Pad::GetMemoryCard(u32 slot)
void Pad::SetMemoryCard(u32 slot, std::unique_ptr<MemoryCard> dev) void Pad::SetMemoryCard(u32 slot, std::unique_ptr<MemoryCard> dev)
{ {
Log_InfoPrintf("Memory card slot %u: %s", slot, Log_InfoFmt("Memory card slot {}: {}", slot,
dev ? (dev->GetFilename().empty() ? "<no file configured>" : dev->GetFilename().c_str()) : dev ? (dev->GetFilename().empty() ? "<no file configured>" : dev->GetFilename().c_str()) : "<unplugged>");
"<unplugged>");
s_memory_cards[slot] = std::move(dev); s_memory_cards[slot] = std::move(dev);
} }
@ -589,7 +587,7 @@ u32 Pad::ReadRegister(u32 offset)
s_transfer_event->InvokeEarly(); s_transfer_event->InvokeEarly();
const u8 value = s_receive_buffer_full ? s_receive_buffer : 0xFF; const u8 value = s_receive_buffer_full ? s_receive_buffer : 0xFF;
Log_DebugPrintf("JOY_DATA (R) -> 0x%02X%s", ZeroExtend32(value), s_receive_buffer_full ? "" : "(EMPTY)"); Log_DebugFmt("JOY_DATA (R) -> 0x{:02X}{}", value, s_receive_buffer_full ? "" : "(EMPTY)");
s_receive_buffer_full = false; s_receive_buffer_full = false;
UpdateJoyStat(); UpdateJoyStat();
@ -616,8 +614,8 @@ u32 Pad::ReadRegister(u32 offset)
case 0x0E: // JOY_BAUD case 0x0E: // JOY_BAUD
return ZeroExtend32(s_JOY_BAUD); return ZeroExtend32(s_JOY_BAUD);
default: [[unlikely]] default:
Log_ErrorPrintf("Unknown register read: 0x%X", offset); Log_ErrorFmt("Unknown register read: 0x{:X}", offset);
return UINT32_C(0xFFFFFFFF); return UINT32_C(0xFFFFFFFF);
} }
} }
@ -628,7 +626,7 @@ void Pad::WriteRegister(u32 offset, u32 value)
{ {
case 0x00: // JOY_DATA case 0x00: // JOY_DATA
{ {
Log_DebugPrintf("JOY_DATA (W) <- 0x%02X", value); Log_DebugFmt("JOY_DATA (W) <- 0x{:02X}", value);
if (s_transmit_buffer_full) if (s_transmit_buffer_full)
Log_WarningPrint("TX FIFO overrun"); Log_WarningPrint("TX FIFO overrun");
@ -644,7 +642,7 @@ void Pad::WriteRegister(u32 offset, u32 value)
case 0x0A: // JOY_CTRL case 0x0A: // JOY_CTRL
{ {
Log_DebugPrintf("JOY_CTRL <- 0x%04X", value); Log_DebugFmt("JOY_CTRL <- 0x{:04X}", value);
s_JOY_CTRL.bits = Truncate16(value); s_JOY_CTRL.bits = Truncate16(value);
if (s_JOY_CTRL.RESET) if (s_JOY_CTRL.RESET)
@ -677,21 +675,23 @@ void Pad::WriteRegister(u32 offset, u32 value)
case 0x08: // JOY_MODE case 0x08: // JOY_MODE
{ {
Log_DebugPrintf("JOY_MODE <- 0x%08X", value); Log_DebugFmt("JOY_MODE <- 0x{:08X}", value);
s_JOY_MODE.bits = Truncate16(value); s_JOY_MODE.bits = Truncate16(value);
return; return;
} }
case 0x0E: case 0x0E:
{ {
Log_DebugPrintf("JOY_BAUD <- 0x%08X", value); Log_DebugFmt("JOY_BAUD <- 0x{:08X}", value);
s_JOY_BAUD = Truncate16(value); s_JOY_BAUD = Truncate16(value);
return; return;
} }
default: [[unlikely]] default:
Log_ErrorPrintf("Unknown register write: 0x%X <- 0x%08X", offset, value); {
return; Log_ErrorFmt("Unknown register write: 0x{:X} <- 0x{:08X}", offset, value);
return;
}
} }
} }
@ -744,7 +744,7 @@ void Pad::TransferEvent(void*, TickCount ticks, TickCount ticks_late)
void Pad::BeginTransfer() void Pad::BeginTransfer()
{ {
DebugAssert(s_state == State::Idle && CanTransfer()); DebugAssert(s_state == State::Idle && CanTransfer());
Log_DebugPrintf("Starting transfer"); Log_DebugPrint("Starting transfer");
s_JOY_CTRL.RXEN = true; s_JOY_CTRL.RXEN = true;
s_transmit_value = s_transmit_buffer; s_transmit_value = s_transmit_buffer;
@ -771,7 +771,7 @@ void Pad::BeginTransfer()
void Pad::DoTransfer(TickCount ticks_late) void Pad::DoTransfer(TickCount ticks_late)
{ {
Log_DebugPrintf("Transferring slot %d", s_JOY_CTRL.SLOT.GetValue()); Log_DebugFmt("Transferring slot {}", s_JOY_CTRL.SLOT.GetValue());
const u8 device_index = s_multitaps[0].IsEnabled() ? 4u : s_JOY_CTRL.SLOT; const u8 device_index = s_multitaps[0].IsEnabled() ? 4u : s_JOY_CTRL.SLOT;
Controller* const controller = s_controllers[device_index].get(); Controller* const controller = s_controllers[device_index].get();
@ -793,8 +793,8 @@ void Pad::DoTransfer(TickCount ticks_late)
{ {
if ((ack = s_multitaps[s_JOY_CTRL.SLOT].Transfer(data_out, &data_in)) == true) if ((ack = s_multitaps[s_JOY_CTRL.SLOT].Transfer(data_out, &data_in)) == true)
{ {
Log_TracePrintf("Active device set to tap %d, sent 0x%02X, received 0x%02X", Log_TraceFmt("Active device set to tap {}, sent 0x{:02X}, received 0x{:02X}",
static_cast<int>(s_JOY_CTRL.SLOT), data_out, data_in); static_cast<int>(s_JOY_CTRL.SLOT), data_out, data_in);
s_active_device = ActiveDevice::Multitap; s_active_device = ActiveDevice::Multitap;
} }
} }
@ -805,12 +805,12 @@ void Pad::DoTransfer(TickCount ticks_late)
if (!memory_card || (ack = memory_card->Transfer(data_out, &data_in)) == false) if (!memory_card || (ack = memory_card->Transfer(data_out, &data_in)) == false)
{ {
// nothing connected to this port // nothing connected to this port
Log_TracePrintf("Nothing connected or ACK'ed"); Log_TracePrint("Nothing connected or ACK'ed");
} }
else else
{ {
// memory card responded, make it the active device until non-ack // memory card responded, make it the active device until non-ack
Log_TracePrintf("Transfer to memory card, data_out=0x%02X, data_in=0x%02X", data_out, data_in); Log_TraceFmt("Transfer to memory card, data_out=0x{:02X}, data_in=0x{:02X}", data_out, data_in);
s_active_device = ActiveDevice::MemoryCard; s_active_device = ActiveDevice::MemoryCard;
// back up memory card state in case we roll back to before this transfer begun // back up memory card state in case we roll back to before this transfer begun
@ -827,7 +827,7 @@ void Pad::DoTransfer(TickCount ticks_late)
else else
{ {
// controller responded, make it the active device until non-ack // controller responded, make it the active device until non-ack
Log_TracePrintf("Transfer to controller, data_out=0x%02X, data_in=0x%02X", data_out, data_in); Log_TraceFmt("Transfer to controller, data_out=0x{:02X}, data_in=0x{:02X}", data_out, data_in);
s_active_device = ActiveDevice::Controller; s_active_device = ActiveDevice::Controller;
} }
} }
@ -839,7 +839,7 @@ void Pad::DoTransfer(TickCount ticks_late)
if (controller) if (controller)
{ {
ack = controller->Transfer(data_out, &data_in); ack = controller->Transfer(data_out, &data_in);
Log_TracePrintf("Transfer to controller, data_out=0x%02X, data_in=0x%02X", data_out, data_in); Log_TraceFmt("Transfer to controller, data_out=0x{:02X}, data_in=0x{:02X}", data_out, data_in);
} }
} }
break; break;
@ -850,7 +850,7 @@ void Pad::DoTransfer(TickCount ticks_late)
{ {
s_last_memory_card_transfer_frame = System::GetFrameNumber(); s_last_memory_card_transfer_frame = System::GetFrameNumber();
ack = memory_card->Transfer(data_out, &data_in); ack = memory_card->Transfer(data_out, &data_in);
Log_TracePrintf("Transfer to memory card, data_out=0x%02X, data_in=0x%02X", data_out, data_in); Log_TraceFmt("Transfer to memory card, data_out=0x{:02X}, data_in=0x{:02X}", data_out, data_in);
} }
} }
break; break;
@ -860,8 +860,8 @@ void Pad::DoTransfer(TickCount ticks_late)
if (s_multitaps[s_JOY_CTRL.SLOT].IsEnabled()) if (s_multitaps[s_JOY_CTRL.SLOT].IsEnabled())
{ {
ack = s_multitaps[s_JOY_CTRL.SLOT].Transfer(data_out, &data_in); ack = s_multitaps[s_JOY_CTRL.SLOT].Transfer(data_out, &data_in);
Log_TracePrintf("Transfer tap %d, sent 0x%02X, received 0x%02X, acked: %s", static_cast<int>(s_JOY_CTRL.SLOT), Log_TraceFmt("Transfer tap {}, sent 0x{:02X}, received 0x{:02X}, acked: {}", static_cast<int>(s_JOY_CTRL.SLOT),
data_out, data_in, ack ? "true" : "false"); data_out, data_in, ack ? "true" : "false");
} }
} }
break; break;
@ -883,7 +883,7 @@ void Pad::DoTransfer(TickCount ticks_late)
(s_active_device == ActiveDevice::Multitap && s_multitaps[s_JOY_CTRL.SLOT].IsReadingMemoryCard()); (s_active_device == ActiveDevice::Multitap && s_multitaps[s_JOY_CTRL.SLOT].IsReadingMemoryCard());
const TickCount ack_timer = GetACKTicks(memcard_transfer); const TickCount ack_timer = GetACKTicks(memcard_transfer);
Log_DebugPrintf("Delaying ACK for %d ticks", ack_timer); Log_DebugFmt("Delaying ACK for {} ticks", ack_timer);
s_state = State::WaitingForACK; s_state = State::WaitingForACK;
s_transfer_event->SetPeriodAndSchedule(ack_timer); s_transfer_event->SetPeriodAndSchedule(ack_timer);
} }
@ -897,7 +897,7 @@ void Pad::DoACK()
if (s_JOY_CTRL.ACKINTEN) if (s_JOY_CTRL.ACKINTEN)
{ {
Log_DebugPrintf("Triggering ACK interrupt"); Log_DebugPrint("Triggering ACK interrupt");
s_JOY_STAT.INTR = true; s_JOY_STAT.INTR = true;
InterruptController::SetLineState(InterruptController::IRQ::PAD, true); InterruptController::SetLineState(InterruptController::IRQ::PAD, true);
} }
@ -912,7 +912,7 @@ void Pad::DoACK()
void Pad::EndTransfer() void Pad::EndTransfer()
{ {
DebugAssert(s_state == State::Transmitting || s_state == State::WaitingForACK); DebugAssert(s_state == State::Transmitting || s_state == State::WaitingForACK);
Log_DebugPrintf("Ending transfer"); Log_DebugPrint("Ending transfer");
s_state = State::Idle; s_state = State::Idle;
s_transfer_event->Deactivate(); s_transfer_event->Deactivate();

View File

@ -45,7 +45,7 @@ static s32 GetFreeFileHandle()
static void CloseAllFiles() static void CloseAllFiles()
{ {
if (!s_files.empty()) if (!s_files.empty())
Log_DevPrintf("Closing %zu open files.", s_files.size()); Log_DevFmt("Closing {} open files.", s_files.size());
s_files.clear(); s_files.clear();
} }
@ -54,7 +54,7 @@ static FILE* GetFileFromHandle(u32 handle)
{ {
if (handle >= static_cast<u32>(s_files.size()) || !s_files[handle]) if (handle >= static_cast<u32>(s_files.size()) || !s_files[handle])
{ {
Log_ErrorPrintf("Invalid file handle %d", static_cast<s32>(handle)); Log_ErrorFmt("Invalid file handle {}", static_cast<s32>(handle));
return nullptr; return nullptr;
} }
@ -65,7 +65,7 @@ static bool CloseFileHandle(u32 handle)
{ {
if (handle >= static_cast<u32>(s_files.size()) || !s_files[handle]) if (handle >= static_cast<u32>(s_files.size()) || !s_files[handle])
{ {
Log_ErrorPrintf("Invalid file handle %d", static_cast<s32>(handle)); Log_ErrorFmt("Invalid file handle {}", static_cast<s32>(handle));
return false; return false;
} }
@ -85,9 +85,9 @@ static std::string ResolveHostPath(const std::string& path)
!canonicalized_path.starts_with(root) || // and start with the host root, !canonicalized_path.starts_with(root) || // and start with the host root,
canonicalized_path[root.length()] != FS_OSPATH_SEPARATOR_CHARACTER) // and we can't access a sibling. canonicalized_path[root.length()] != FS_OSPATH_SEPARATOR_CHARACTER) // and we can't access a sibling.
{ {
Log_ErrorPrintf("Denying access to path outside of PCDrv directory. Requested path: '%s', " Log_ErrorFmt("Denying access to path outside of PCDrv directory. Requested path: '{}', "
"Resolved path: '%s', Root directory: '%s'", "Resolved path: '{}', Root directory: '{}'",
path.c_str(), root.c_str(), canonicalized_path.c_str()); path, root, canonicalized_path);
canonicalized_path.clear(); canonicalized_path.clear();
} }
@ -99,8 +99,8 @@ void PCDrv::Initialize()
if (!g_settings.pcdrv_enable) if (!g_settings.pcdrv_enable)
return; return;
Log_WarningPrintf("%s PCDrv is enabled at '%s'", g_settings.pcdrv_enable_writes ? "Read/Write" : "Read-Only", Log_WarningFmt("{} PCDrv is enabled at '{}'", g_settings.pcdrv_enable_writes ? "Read/Write" : "Read-Only",
g_settings.pcdrv_root.c_str()); g_settings.pcdrv_root);
} }
void PCDrv::Reset() void PCDrv::Reset()
@ -126,7 +126,7 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
{ {
case 0x101: // PCinit case 0x101: // PCinit
{ {
Log_DevPrintf("PCinit"); Log_DevPrint("PCinit");
CloseAllFiles(); CloseAllFiles();
regs.v0 = 0; regs.v0 = 0;
regs.v1 = 0; regs.v1 = 0;
@ -142,11 +142,11 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
std::string filename; std::string filename;
if (!CPU::SafeReadMemoryCString(regs.a1, &filename)) if (!CPU::SafeReadMemoryCString(regs.a1, &filename))
{ {
Log_ErrorPrintf("%s: Invalid string", func); Log_ErrorFmt("{}: Invalid string", func);
return false; return false;
} }
Log_DebugPrintf("%s: '%s' mode %u", func, filename.c_str(), mode); Log_DebugFmt("{}: '{}' mode {}", func, filename, mode);
if ((filename = ResolveHostPath(filename)).empty()) if ((filename = ResolveHostPath(filename)).empty())
{ {
RETURN_ERROR(); RETURN_ERROR();
@ -155,7 +155,7 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
if (!is_open && !g_settings.pcdrv_enable_writes) if (!is_open && !g_settings.pcdrv_enable_writes)
{ {
Log_ErrorPrintf("%s: Writes are not enabled", func); Log_ErrorFmt("{}: Writes are not enabled", func);
RETURN_ERROR(); RETURN_ERROR();
return true; return true;
} }
@ -163,7 +163,7 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
// Directories are unsupported for now, ignore other attributes // Directories are unsupported for now, ignore other attributes
if (mode & PCDRV_ATTRIBUTE_DIRECTORY) if (mode & PCDRV_ATTRIBUTE_DIRECTORY)
{ {
Log_ErrorPrintf("%s: Directories are unsupported", func); Log_ErrorFmt("{}: Directories are unsupported", func);
RETURN_ERROR(); RETURN_ERROR();
return true; return true;
} }
@ -180,12 +180,12 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
is_open ? (g_settings.pcdrv_enable_writes ? "r+b" : "rb") : "w+b"); is_open ? (g_settings.pcdrv_enable_writes ? "r+b" : "rb") : "w+b");
if (!s_files[handle]) if (!s_files[handle])
{ {
Log_ErrorPrintf("%s: Failed to open '%s'", func, filename.c_str()); Log_ErrorFmt("{}: Failed to open '{}'", func, filename);
RETURN_ERROR(); RETURN_ERROR();
return true; return true;
} }
Log_DebugPrintf("PCDrv: Opened '%s' => %d", filename.c_str(), handle); Log_ErrorFmt("PCDrv: Opened '{}' => {}", filename, handle);
regs.v0 = 0; regs.v0 = 0;
regs.v1 = static_cast<u32>(handle); regs.v1 = static_cast<u32>(handle);
return true; return true;
@ -193,7 +193,7 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
case 0x104: // PCclose case 0x104: // PCclose
{ {
Log_DebugPrintf("PCclose(%u)", regs.a1); Log_DebugFmt("PCclose({})", regs.a1);
if (!CloseFileHandle(regs.a1)) if (!CloseFileHandle(regs.a1))
{ {
@ -208,7 +208,7 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
case 0x105: // PCread case 0x105: // PCread
{ {
Log_DebugPrintf("PCread(%u, %u, 0x%08x)", regs.a1, regs.a2, regs.a3); Log_DebugFmt("PCread({}, {}, 0x{:08X})", regs.a1, regs.a2, regs.a3);
std::FILE* fp = GetFileFromHandle(regs.a1); std::FILE* fp = GetFileFromHandle(regs.a1);
if (!fp) if (!fp)
@ -246,7 +246,7 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
case 0x106: // PCwrite case 0x106: // PCwrite
{ {
Log_DebugPrintf("PCwrite(%u, %u, 0x%08x)", regs.a1, regs.a2, regs.a3); Log_DebugFmt("PCwrite({}, {}, 0x{:08x})", regs.a1, regs.a2, regs.a3);
std::FILE* fp = GetFileFromHandle(regs.a1); std::FILE* fp = GetFileFromHandle(regs.a1);
if (!fp) if (!fp)
@ -281,7 +281,7 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
case 0x107: // PClseek case 0x107: // PClseek
{ {
Log_DebugPrintf("PClseek(%u, %u, %u)", regs.a1, regs.a2, regs.a3); Log_DebugFmt("PClseek({}, {}, {})", regs.a1, regs.a2, regs.a3);
std::FILE* fp = GetFileFromHandle(regs.a1); std::FILE* fp = GetFileFromHandle(regs.a1);
if (!fp) if (!fp)
@ -311,7 +311,7 @@ bool PCDrv::HandleSyscall(u32 instruction_bits, CPU::Registers& regs)
if (FileSystem::FSeek64(fp, offset, hmode) != 0) if (FileSystem::FSeek64(fp, offset, hmode) != 0)
{ {
Log_ErrorPrintf("FSeek for PCDrv failed: %d %u", offset, hmode); Log_ErrorFmt("FSeek for PCDrv failed: {} {}", offset, hmode);
RETURN_ERROR(); RETURN_ERROR();
return true; return true;
} }

View File

@ -66,7 +66,7 @@ bool File::Load(const char* path)
std::optional<std::vector<u8>> file_data(FileSystem::ReadBinaryFile(path)); std::optional<std::vector<u8>> file_data(FileSystem::ReadBinaryFile(path));
if (!file_data.has_value() || file_data->empty()) if (!file_data.has_value() || file_data->empty())
{ {
Log_ErrorPrintf("Failed to open/read PSF file '%s'", path); Log_ErrorFmt("Failed to open/read PSF file '{}'", path);
return false; return false;
} }
@ -81,7 +81,7 @@ bool File::Load(const char* path)
header.compressed_program_size == 0 || header.compressed_program_size == 0 ||
(sizeof(header) + header.reserved_area_size + header.compressed_program_size) > file_size) (sizeof(header) + header.reserved_area_size + header.compressed_program_size) > file_size)
{ {
Log_ErrorPrintf("Invalid or incompatible header in PSF '%s'", path); Log_ErrorFmt("Invalid or incompatible header in PSF '{}'", path);
return false; return false;
} }
@ -98,7 +98,7 @@ bool File::Load(const char* path)
int err = inflateInit(&strm); int err = inflateInit(&strm);
if (err != Z_OK) if (err != Z_OK)
{ {
Log_ErrorPrintf("inflateInit() failed: %d", err); Log_ErrorFmt("inflateInit() failed: {}", err);
return false; return false;
} }
@ -106,13 +106,13 @@ bool File::Load(const char* path)
err = inflate(&strm, Z_NO_FLUSH); err = inflate(&strm, Z_NO_FLUSH);
if (err != Z_STREAM_END) if (err != Z_STREAM_END)
{ {
Log_ErrorPrintf("inflate() failed: %d", err); Log_ErrorFmt("inflate() failed: {}", err);
inflateEnd(&strm); inflateEnd(&strm);
return false; return false;
} }
else if (strm.total_in != header.compressed_program_size) else if (strm.total_in != header.compressed_program_size)
{ {
Log_WarningPrintf("Mismatch between compressed size in header and stream %u/%u", header.compressed_program_size, Log_WarningFmt("Mismatch between compressed size in header and stream {}/{}", header.compressed_program_size,
static_cast<u32>(strm.total_in)); static_cast<u32>(strm.total_in));
} }
@ -147,7 +147,7 @@ bool File::Load(const char* path)
if (!tag_key.empty()) if (!tag_key.empty())
{ {
Log_DevPrintf("PSF Tag: '%s' = '%s'", tag_key.c_str(), tag_value.c_str()); Log_DevFmt("PSF Tag: '{}' = '{}'", tag_key, tag_value);
m_tags.emplace(std::move(tag_key), std::move(tag_value)); m_tags.emplace(std::move(tag_key), std::move(tag_value));
} }
} }
@ -171,14 +171,14 @@ static bool LoadLibraryPSF(const char* path, bool use_pc_sp, u32 depth = 0)
// don't recurse past 10 levels just in case of broken files // don't recurse past 10 levels just in case of broken files
if (depth >= 10) if (depth >= 10)
{ {
Log_ErrorPrintf("Recursion depth exceeded when loading PSF '%s'", path); Log_ErrorFmt("Recursion depth exceeded when loading PSF '{}'", path);
return false; return false;
} }
File file; File file;
if (!file.Load(path)) if (!file.Load(path))
{ {
Log_ErrorPrintf("Failed to load main PSF '%s'", path); Log_ErrorFmt("Failed to load main PSF '{}'", path);
return false; return false;
} }
@ -187,13 +187,13 @@ static bool LoadLibraryPSF(const char* path, bool use_pc_sp, u32 depth = 0)
if (lib_name.has_value()) if (lib_name.has_value())
{ {
const std::string lib_path(Path::BuildRelativePath(path, lib_name.value())); const std::string lib_path(Path::BuildRelativePath(path, lib_name.value()));
Log_InfoPrintf("Loading main parent PSF '%s'", lib_path.c_str()); Log_InfoFmt("Loading main parent PSF '{}'", lib_path);
// We should use the initial SP/PC from the **first** parent lib. // We should use the initial SP/PC from the **first** parent lib.
const bool lib_use_pc_sp = (depth == 0); const bool lib_use_pc_sp = (depth == 0);
if (!LoadLibraryPSF(lib_path.c_str(), lib_use_pc_sp, depth + 1)) if (!LoadLibraryPSF(lib_path.c_str(), lib_use_pc_sp, depth + 1))
{ {
Log_ErrorPrintf("Failed to load main parent PSF '%s'", lib_path.c_str()); Log_ErrorFmt("Failed to load main parent PSF '{}'", lib_path);
return false; return false;
} }
@ -206,7 +206,7 @@ static bool LoadLibraryPSF(const char* path, bool use_pc_sp, u32 depth = 0)
if (!System::InjectEXEFromBuffer(file.GetProgramData().data(), static_cast<u32>(file.GetProgramData().size()), if (!System::InjectEXEFromBuffer(file.GetProgramData().data(), static_cast<u32>(file.GetProgramData().size()),
use_pc_sp)) use_pc_sp))
{ {
Log_ErrorPrintf("Failed to parse EXE from PSF '%s'", path); Log_ErrorFmt("Failed to parse EXE from PSF '{}'", path);
return false; return false;
} }
@ -219,10 +219,10 @@ static bool LoadLibraryPSF(const char* path, bool use_pc_sp, u32 depth = 0)
break; break;
const std::string lib_path(Path::BuildRelativePath(path, lib_name.value())); const std::string lib_path(Path::BuildRelativePath(path, lib_name.value()));
Log_InfoPrintf("Loading parent PSF '%s'", lib_path.c_str()); Log_InfoFmt("Loading parent PSF '{}'", lib_path);
if (!LoadLibraryPSF(lib_path.c_str(), false, depth + 1)) if (!LoadLibraryPSF(lib_path.c_str(), false, depth + 1))
{ {
Log_ErrorPrintf("Failed to load parent PSF '%s'", lib_path.c_str()); Log_ErrorFmt("Failed to load parent PSF '{}'", lib_path);
return false; return false;
} }
} }
@ -232,7 +232,7 @@ static bool LoadLibraryPSF(const char* path, bool use_pc_sp, u32 depth = 0)
bool Load(const char* path) bool Load(const char* path)
{ {
Log_InfoPrintf("Loading PSF file from '%s'", path); Log_InfoFmt("Loading PSF file from '{}'", path);
return LoadLibraryPSF(path, true); return LoadLibraryPSF(path, true);
} }

View File

@ -735,7 +735,7 @@ void Settings::FixIncompatibleSettings(bool display_osd_messages)
#ifndef ENABLE_MMAP_FASTMEM #ifndef ENABLE_MMAP_FASTMEM
if (g_settings.cpu_fastmem_mode == CPUFastmemMode::MMap) if (g_settings.cpu_fastmem_mode == CPUFastmemMode::MMap)
{ {
Log_WarningPrintf("mmap fastmem is not available on this platform, using LUT instead."); Log_WarningPrint("mmap fastmem is not available on this platform, using LUT instead.");
g_settings.cpu_fastmem_mode = CPUFastmemMode::LUT; g_settings.cpu_fastmem_mode = CPUFastmemMode::LUT;
} }
#endif #endif
@ -770,7 +770,7 @@ void Settings::FixIncompatibleSettings(bool display_osd_messages)
// be unlinked. Which would be thousands of blocks. // be unlinked. Which would be thousands of blocks.
if (g_settings.cpu_recompiler_block_linking) if (g_settings.cpu_recompiler_block_linking)
{ {
Log_WarningPrintf("Disabling block linking due to runahead."); Log_WarningPrint("Disabling block linking due to runahead.");
g_settings.cpu_recompiler_block_linking = false; g_settings.cpu_recompiler_block_linking = false;
} }
} }

View File

@ -106,7 +106,7 @@ u32 SIO::ReadRegister(u32 offset)
{ {
case 0x00: // SIO_DATA case 0x00: // SIO_DATA
{ {
Log_ErrorPrintf("Read SIO_DATA"); Log_ErrorPrint("Read SIO_DATA");
const u8 value = 0xFF; const u8 value = 0xFF;
return (ZeroExtend32(value) | (ZeroExtend32(value) << 8) | (ZeroExtend32(value) << 16) | return (ZeroExtend32(value) | (ZeroExtend32(value) << 8) | (ZeroExtend32(value) << 16) |
@ -128,8 +128,8 @@ u32 SIO::ReadRegister(u32 offset)
case 0x0E: // SIO_BAUD case 0x0E: // SIO_BAUD
return ZeroExtend32(s_SIO_BAUD); return ZeroExtend32(s_SIO_BAUD);
default: [[unlikely]] default:
Log_ErrorPrintf("Unknown register read: 0x%X", offset); Log_ErrorFmt("Unknown register read: 0x{:X}", offset);
return UINT32_C(0xFFFFFFFF); return UINT32_C(0xFFFFFFFF);
} }
} }
@ -140,13 +140,13 @@ void SIO::WriteRegister(u32 offset, u32 value)
{ {
case 0x00: // SIO_DATA case 0x00: // SIO_DATA
{ {
Log_WarningPrintf("SIO_DATA (W) <- 0x%02X", value); Log_WarningFmt("SIO_DATA (W) <- 0x{:02X}", value);
return; return;
} }
case 0x0A: // SIO_CTRL case 0x0A: // SIO_CTRL
{ {
Log_DebugPrintf("SIO_CTRL <- 0x%04X", value); Log_DebugFmt("SIO_CTRL <- 0x{:04X}", value);
s_SIO_CTRL.bits = Truncate16(value); s_SIO_CTRL.bits = Truncate16(value);
if (s_SIO_CTRL.RESET) if (s_SIO_CTRL.RESET)
@ -157,20 +157,20 @@ void SIO::WriteRegister(u32 offset, u32 value)
case 0x08: // SIO_MODE case 0x08: // SIO_MODE
{ {
Log_DebugPrintf("SIO_MODE <- 0x%08X", value); Log_DebugFmt("SIO_MODE <- 0x{:08X}", value);
s_SIO_MODE.bits = Truncate16(value); s_SIO_MODE.bits = Truncate16(value);
return; return;
} }
case 0x0E: case 0x0E:
{ {
Log_DebugPrintf("SIO_BAUD <- 0x%08X", value); Log_DebugFmt("SIO_BAUD <- 0x{:08X}", value);
s_SIO_BAUD = Truncate16(value); s_SIO_BAUD = Truncate16(value);
return; return;
} }
default: default:
Log_ErrorPrintf("Unknown register write: 0x%X <- 0x%08X", offset, value); Log_ErrorFmt("Unknown register write: 0x{:X} <- 0x{:08X}", offset, value);
return; return;
} }
} }

View File

@ -680,7 +680,7 @@ bool System::GetGameDetailsFromImage(CDImage* cdi, std::string* out_id, GameHash
XXH64_update(state, &track_1_length, sizeof(track_1_length)); XXH64_update(state, &track_1_length, sizeof(track_1_length));
const GameHash hash = XXH64_digest(state); const GameHash hash = XXH64_digest(state);
XXH64_freeState(state); XXH64_freeState(state);
Log_DevPrintf("Hash for '%s' - %" PRIX64, exe_name.c_str(), hash); Log_DevFmt("Hash for '{}' - {:016X}", exe_name, hash);
if (exe_name != FALLBACK_EXE_NAME) if (exe_name != FALLBACK_EXE_NAME)
{ {
@ -798,7 +798,7 @@ std::string System::GetExecutableNameForImage(IsoReader& iso, bool strip_subdire
if (code.compare(0, 6, "cdrom:") == 0) if (code.compare(0, 6, "cdrom:") == 0)
code.erase(0, 6); code.erase(0, 6);
else else
Log_WarningPrintf("Unknown prefix in executable path: '%s'", code.c_str()); Log_WarningFmt("Unknown prefix in executable path: '{}'", code);
// remove leading slashes // remove leading slashes
while (code[0] == '/' || code[0] == '\\') while (code[0] == '/' || code[0] == '\\')
@ -836,12 +836,12 @@ bool System::ReadExecutableFromImage(IsoReader& iso, std::string* out_executable
std::vector<u8>* out_executable_data) std::vector<u8>* out_executable_data)
{ {
const std::string executable_path = GetExecutableNameForImage(iso, false); const std::string executable_path = GetExecutableNameForImage(iso, false);
Log_DevPrintf("Executable path: '%s'", executable_path.c_str()); Log_DevFmt("Executable path: '{}'", executable_path);
if (!executable_path.empty() && out_executable_data) if (!executable_path.empty() && out_executable_data)
{ {
if (!iso.ReadFile(executable_path.c_str(), out_executable_data)) if (!iso.ReadFile(executable_path.c_str(), out_executable_data))
{ {
Log_ErrorPrintf("Failed to read executable '%s' from disc", executable_path.c_str()); Log_ErrorFmt("Failed to read executable '{}' from disc", executable_path);
return false; return false;
} }
} }
@ -979,7 +979,7 @@ bool System::RecreateGPU(GPURenderer renderer, bool force_recreate_device, bool
StateWrapper sw(state_stream.get(), StateWrapper::Mode::Write, SAVE_STATE_VERSION); StateWrapper sw(state_stream.get(), StateWrapper::Mode::Write, SAVE_STATE_VERSION);
const bool state_valid = g_gpu->DoState(sw, nullptr, false) && TimingEvents::DoState(sw); const bool state_valid = g_gpu->DoState(sw, nullptr, false) && TimingEvents::DoState(sw);
if (!state_valid) if (!state_valid)
Log_ErrorPrintf("Failed to save old GPU state when switching renderers"); Log_ErrorPrint("Failed to save old GPU state when switching renderers");
// create new renderer // create new renderer
g_gpu.reset(); g_gpu.reset();
@ -1160,17 +1160,17 @@ bool System::UpdateGameSettingsLayer()
std::string filename(GetGameSettingsPath(s_running_game_serial)); std::string filename(GetGameSettingsPath(s_running_game_serial));
if (FileSystem::FileExists(filename.c_str())) if (FileSystem::FileExists(filename.c_str()))
{ {
Log_InfoPrintf("Loading game settings from '%s'...", filename.c_str()); Log_InfoFmt("Loading game settings from '%s'...", Path::GetFileName(filename));
new_interface = std::make_unique<INISettingsInterface>(std::move(filename)); new_interface = std::make_unique<INISettingsInterface>(std::move(filename));
if (!new_interface->Load()) if (!new_interface->Load())
{ {
Log_ErrorPrintf("Failed to parse game settings ini '%s'", new_interface->GetFileName().c_str()); Log_ErrorFmt("Failed to parse game settings ini '%s'", new_interface->GetFileName());
new_interface.reset(); new_interface.reset();
} }
} }
else else
{ {
Log_InfoPrintf("No game settings found (tried '%s')", filename.c_str()); Log_InfoFmt("No game settings found (tried '%s')", Path::GetFileName(filename));
} }
} }
@ -1335,7 +1335,7 @@ bool System::LoadState(const char* filename, Error* error)
if (IsPaused()) if (IsPaused())
InvalidateDisplay(); InvalidateDisplay();
Log_VerbosePrintf("Loading state took %.2f msec", load_timer.GetTimeMilliseconds()); Log_VerboseFmt("Loading state took {:.2f} msec", load_timer.GetTimeMilliseconds());
return true; return true;
} }
@ -1343,9 +1343,13 @@ bool System::SaveState(const char* filename, Error* error, bool backup_existing_
{ {
if (backup_existing_save && FileSystem::FileExists(filename)) if (backup_existing_save && FileSystem::FileExists(filename))
{ {
const std::string backup_filename(Path::ReplaceExtension(filename, "bak")); Error backup_error;
if (!FileSystem::RenamePath(filename, backup_filename.c_str())) const std::string backup_filename = Path::ReplaceExtension(filename, "bak");
Log_ErrorPrintf("Failed to rename save state backup '%s'", backup_filename.c_str()); if (!FileSystem::RenamePath(filename, backup_filename.c_str(), &backup_error))
{
Log_ErrorFmt("Failed to rename save state backup '{}': {}", Path::GetFileName(backup_filename),
backup_error.GetDescription());
}
} }
Common::Timer save_timer; Common::Timer save_timer;
@ -1361,7 +1365,7 @@ bool System::SaveState(const char* filename, Error* error, bool backup_existing_
return false; return false;
} }
Log_InfoPrintf("Saving state to '%s'...", filename); Log_InfoFmt("Saving state to '{}'...", filename);
const u32 screenshot_size = 256; const u32 screenshot_size = 256;
const bool result = SaveStateToStream(stream.get(), error, screenshot_size, const bool result = SaveStateToStream(stream.get(), error, screenshot_size,
@ -1380,7 +1384,7 @@ bool System::SaveState(const char* filename, Error* error, bool backup_existing_
stream->Commit(); stream->Commit();
} }
Log_VerbosePrintf("Saving state took %.2f msec", save_timer.GetTimeMilliseconds()); Log_VerboseFmt("Saving state took {:.2f} msec", save_timer.GetTimeMilliseconds());
return result; return result;
} }
@ -1433,7 +1437,7 @@ bool System::BootSystem(SystemBootParameters parameters, Error* error)
{ {
const DiscRegion file_region = const DiscRegion file_region =
(do_exe_boot ? GetRegionForExe(parameters.filename.c_str()) : GetRegionForPsf(parameters.filename.c_str())); (do_exe_boot ? GetRegionForExe(parameters.filename.c_str()) : GetRegionForPsf(parameters.filename.c_str()));
Log_InfoPrintf("EXE/PSF Region: %s", Settings::GetDiscRegionDisplayName(file_region)); Log_InfoFmt("EXE/PSF Region: {}", Settings::GetDiscRegionDisplayName(file_region));
s_region = GetConsoleRegionForDiscRegion(file_region); s_region = GetConsoleRegionForDiscRegion(file_region);
} }
if (do_psf_boot) if (do_psf_boot)
@ -1443,7 +1447,7 @@ bool System::BootSystem(SystemBootParameters parameters, Error* error)
} }
else else
{ {
Log_InfoPrintf("Loading CD image '%s'...", parameters.filename.c_str()); Log_InfoFmt("Loading CD image '{}'...", Path::GetFileName(parameters.filename));
disc = CDImage::Open(parameters.filename.c_str(), g_settings.cdrom_load_image_patches, error); disc = CDImage::Open(parameters.filename.c_str(), g_settings.cdrom_load_image_patches, error);
if (!disc) if (!disc)
{ {
@ -1460,15 +1464,14 @@ bool System::BootSystem(SystemBootParameters parameters, Error* error)
if (disc_region != DiscRegion::Other) if (disc_region != DiscRegion::Other)
{ {
s_region = GetConsoleRegionForDiscRegion(disc_region); s_region = GetConsoleRegionForDiscRegion(disc_region);
Log_InfoPrintf("Auto-detected console %s region for '%s' (region %s)", Log_InfoFmt("Auto-detected console {} region for '{}' (region {})", Settings::GetConsoleRegionName(s_region),
Settings::GetConsoleRegionName(s_region), parameters.filename.c_str(), parameters.filename, Settings::GetDiscRegionName(disc_region));
Settings::GetDiscRegionName(disc_region));
} }
else else
{ {
s_region = ConsoleRegion::NTSC_U; s_region = ConsoleRegion::NTSC_U;
Log_WarningPrintf("Could not determine console region for disc region %s. Defaulting to %s.", Log_WarningFmt("Could not determine console region for disc region {}. Defaulting to {}.",
Settings::GetDiscRegionName(disc_region), Settings::GetConsoleRegionName(s_region)); Settings::GetDiscRegionName(disc_region), Settings::GetConsoleRegionName(s_region));
} }
} }
} }
@ -1480,7 +1483,7 @@ bool System::BootSystem(SystemBootParameters parameters, Error* error)
s_region = ConsoleRegion::NTSC_U; s_region = ConsoleRegion::NTSC_U;
} }
Log_InfoPrintf("Console Region: %s", Settings::GetConsoleRegionDisplayName(s_region)); Log_InfoFmt("Console Region: {}", Settings::GetConsoleRegionDisplayName(s_region));
// Switch subimage. // Switch subimage.
if (disc && parameters.media_playlist_index != 0 && !disc->SwitchSubImage(parameters.media_playlist_index, error)) if (disc && parameters.media_playlist_index != 0 && !disc->SwitchSubImage(parameters.media_playlist_index, error))
@ -1508,7 +1511,7 @@ bool System::BootSystem(SystemBootParameters parameters, Error* error)
return false; return false;
} }
Log_InfoPrintf("Overriding boot executable: '%s'", parameters.override_exe.c_str()); Log_InfoFmt("Overriding boot executable: '{}'", parameters.override_exe);
exe_boot = std::move(parameters.override_exe); exe_boot = std::move(parameters.override_exe);
} }
@ -2230,8 +2233,7 @@ bool System::DoState(StateWrapper& sw, GPUTexture** host_texture, bool update_di
sw.DoBytesEx(bios_hash.bytes, sizeof(bios_hash.bytes), 58, s_bios_hash.bytes); sw.DoBytesEx(bios_hash.bytes, sizeof(bios_hash.bytes), 58, s_bios_hash.bytes);
if (bios_hash != s_bios_hash) if (bios_hash != s_bios_hash)
{ {
Log_WarningPrintf("BIOS hash mismatch: System: %s | State: %s", s_bios_hash.ToString().c_str(), Log_WarningFmt("BIOS hash mismatch: System: {} | State: {}", s_bios_hash.ToString(), bios_hash.ToString());
bios_hash.ToString().c_str());
Host::AddKeyedOSDMessage("StateBIOSMismatch", Host::AddKeyedOSDMessage("StateBIOSMismatch",
TRANSLATE_STR("OSDMessage", TRANSLATE_STR("OSDMessage",
"This save state was created with a different BIOS version or patch " "This save state was created with a different BIOS version or patch "
@ -2342,9 +2344,9 @@ bool System::LoadBIOS(Error* error)
s_bios_hash = BIOS::GetImageHash(bios_image.value()); s_bios_hash = BIOS::GetImageHash(bios_image.value());
s_bios_image_info = BIOS::GetInfoForImage(bios_image.value(), s_bios_hash); s_bios_image_info = BIOS::GetInfoForImage(bios_image.value(), s_bios_hash);
if (s_bios_image_info) if (s_bios_image_info)
Log_InfoPrintf("Using BIOS: %s", s_bios_image_info->description); Log_InfoFmt("Using BIOS: {}", s_bios_image_info->description);
else else
Log_WarningPrintf("Using an unknown BIOS: %s", s_bios_hash.ToString().c_str()); Log_WarningFmt("Using an unknown BIOS: {}", s_bios_hash.ToString());
std::memcpy(Bus::g_bios, bios_image->data(), Bus::BIOS_SIZE); std::memcpy(Bus::g_bios, bios_image->data(), Bus::BIOS_SIZE);
return true; return true;
@ -2449,7 +2451,7 @@ bool System::LoadStateFromStream(ByteStream* state, Error* error, bool update_di
std::unique_ptr<CDImage> old_media = CDROM::RemoveMedia(false); std::unique_ptr<CDImage> old_media = CDROM::RemoveMedia(false);
if (old_media && old_media->GetFileName() == media_filename) if (old_media && old_media->GetFileName() == media_filename)
{ {
Log_InfoPrintf("Re-using same media '%s'", media_filename.c_str()); Log_InfoFmt("Re-using same media '{}'", media_filename);
media = std::move(old_media); media = std::move(old_media);
} }
else else
@ -2598,7 +2600,7 @@ bool System::SaveStateToStream(ByteStream* state, Error* error, u32 screenshot_s
const u32 screenshot_height = const u32 screenshot_height =
std::max(1u, static_cast<u32>(static_cast<float>(screenshot_width) / std::max(1u, static_cast<u32>(static_cast<float>(screenshot_width) /
((display_aspect_ratio > 0.0f) ? display_aspect_ratio : 1.0f))); ((display_aspect_ratio > 0.0f) ? display_aspect_ratio : 1.0f)));
Log_VerbosePrintf("Saving %ux%u screenshot for state", screenshot_width, screenshot_height); Log_VerboseFmt("Saving {}x{} screenshot for state", screenshot_width, screenshot_height);
std::vector<u32> screenshot_buffer; std::vector<u32> screenshot_buffer;
u32 screenshot_stride; u32 screenshot_stride;
@ -2611,8 +2613,8 @@ bool System::SaveStateToStream(ByteStream* state, Error* error, u32 screenshot_s
{ {
if (screenshot_stride != (screenshot_width * sizeof(u32))) if (screenshot_stride != (screenshot_width * sizeof(u32)))
{ {
Log_WarningPrintf("Failed to save %ux%u screenshot for save state due to incorrect stride(%u)", Log_WarningFmt("Failed to save {}x{} screenshot for save state due to incorrect stride(%u)", screenshot_width,
screenshot_width, screenshot_height, screenshot_stride); screenshot_height, screenshot_stride);
} }
else else
{ {
@ -2632,8 +2634,8 @@ bool System::SaveStateToStream(ByteStream* state, Error* error, u32 screenshot_s
} }
else else
{ {
Log_WarningPrintf("Failed to save %ux%u screenshot for save state due to render/conversion failure", Log_WarningFmt("Failed to save {}x{} screenshot for save state due to render/conversion failure",
screenshot_width, screenshot_height); screenshot_width, screenshot_height);
} }
} }
@ -2756,8 +2758,9 @@ void System::UpdatePerformanceCounters()
if (s_pre_frame_sleep) if (s_pre_frame_sleep)
UpdatePreFrameSleepTime(); UpdatePreFrameSleepTime();
Log_VerbosePrintf("FPS: %.2f VPS: %.2f CPU: %.2f GPU: %.2f Average: %.2fms Min: %.2fms Max: %.2f ms", s_fps, s_vps, Log_VerboseFmt("FPS: {:.2f} VPS: {:.2f} CPU: {:.2f} GPU: {:.2f} Average: {:.2f}ms Min: {:.2f}ms Max: {:.2f}ms", s_fps,
s_cpu_thread_usage, s_gpu_usage, s_average_frame_time, s_minimum_frame_time, s_maximum_frame_time); s_vps, s_cpu_thread_usage, s_gpu_usage, s_average_frame_time, s_minimum_frame_time,
s_maximum_frame_time);
Host::OnPerformanceCountersUpdated(); Host::OnPerformanceCountersUpdated();
} }
@ -2853,8 +2856,8 @@ void System::UpdateSpeedLimiterState()
{ {
const float ratio = host_refresh_rate.value() / System::GetThrottleFrequency(); const float ratio = host_refresh_rate.value() / System::GetThrottleFrequency();
s_syncing_to_host = (ratio >= 0.95f && ratio <= 1.05f); s_syncing_to_host = (ratio >= 0.95f && ratio <= 1.05f);
Log_InfoPrintf("Refresh rate: Host=%fhz Guest=%fhz Ratio=%f - %s", host_refresh_rate.value(), Log_InfoFmt("Refresh rate: Host={}hz Guest={}hz Ratio={} - {}", host_refresh_rate.value(),
System::GetThrottleFrequency(), ratio, s_syncing_to_host ? "can sync" : "can't sync"); System::GetThrottleFrequency(), ratio, s_syncing_to_host ? "can sync" : "can't sync");
if (s_syncing_to_host) if (s_syncing_to_host)
s_target_speed *= ratio; s_target_speed *= ratio;
} }
@ -2864,11 +2867,11 @@ void System::UpdateSpeedLimiterState()
s_syncing_to_host_with_vsync = (s_syncing_to_host && IsHostVSyncEffectivelyEnabled()); s_syncing_to_host_with_vsync = (s_syncing_to_host && IsHostVSyncEffectivelyEnabled());
if (s_syncing_to_host_with_vsync) if (s_syncing_to_host_with_vsync)
{ {
Log_InfoPrintf("Using host vsync for throttling."); Log_InfoPrint("Using host vsync for throttling.");
s_throttler_enabled = false; s_throttler_enabled = false;
} }
Log_VerbosePrintf("Target speed: %f%%", s_target_speed * 100.0f); Log_VerboseFmt("Target speed: {}%", s_target_speed * 100.0f);
// Update audio output. // Update audio output.
AudioStream* stream = SPU::GetOutputStream(); AudioStream* stream = SPU::GetOutputStream();
@ -3012,7 +3015,7 @@ static bool LoadEXEToRAM(const char* filename, bool patch_bios)
std::FILE* fp = FileSystem::OpenCFile(filename, "rb"); std::FILE* fp = FileSystem::OpenCFile(filename, "rb");
if (!fp) if (!fp)
{ {
Log_ErrorPrintf("Failed to open exe file '%s'", filename); Log_ErrorFmt("Failed to open exe file '{}'", filename);
return false; return false;
} }
@ -3023,7 +3026,7 @@ static bool LoadEXEToRAM(const char* filename, bool patch_bios)
BIOS::PSEXEHeader header; BIOS::PSEXEHeader header;
if (std::fread(&header, sizeof(header), 1, fp) != 1 || !BIOS::IsValidPSExeHeader(header, file_size)) if (std::fread(&header, sizeof(header), 1, fp) != 1 || !BIOS::IsValidPSExeHeader(header, file_size))
{ {
Log_ErrorPrintf("'%s' is not a valid PS-EXE", filename); Log_ErrorFmt("'{}' is not a valid PS-EXE", filename);
std::fclose(fp); std::fclose(fp);
return false; return false;
} }
@ -3073,7 +3076,7 @@ bool System::LoadEXE(const char* filename)
const std::string libps_path(Path::BuildRelativePath(filename, "libps.exe")); const std::string libps_path(Path::BuildRelativePath(filename, "libps.exe"));
if (!libps_path.empty() && FileSystem::FileExists(libps_path.c_str()) && !LoadEXEToRAM(libps_path.c_str(), false)) if (!libps_path.empty() && FileSystem::FileExists(libps_path.c_str()) && !LoadEXEToRAM(libps_path.c_str(), false))
{ {
Log_ErrorPrintf("Failed to load libps.exe from '%s'", libps_path.c_str()); Log_ErrorFmt("Failed to load libps.exe from '{}'", libps_path.c_str());
return false; return false;
} }
@ -3638,8 +3641,7 @@ bool System::CheckForSBIFile(CDImage* image, Error* error)
return true; return true;
} }
Log_WarningPrintf("SBI file missing but required for %s (%s)", s_running_game_serial.c_str(), Log_WarningFmt("SBI file missing but required for {} ({})", s_running_game_serial, s_running_game_title);
s_running_game_title.c_str());
if (Host::GetBoolSettingValue("CDROM", "AllowBootingWithoutSBIFile", false)) if (Host::GetBoolSettingValue("CDROM", "AllowBootingWithoutSBIFile", false))
{ {
@ -4161,9 +4163,9 @@ void System::UpdateMemorySaveStateSettings()
u64 ram_usage, vram_usage; u64 ram_usage, vram_usage;
CalculateRewindMemoryUsage(g_settings.rewind_save_slots, g_settings.gpu_resolution_scale, &ram_usage, &vram_usage); CalculateRewindMemoryUsage(g_settings.rewind_save_slots, g_settings.gpu_resolution_scale, &ram_usage, &vram_usage);
Log_InfoPrintf( Log_InfoFmt("Rewind is enabled, saving every {} frames, with {} slots and {}MB RAM and {}MB VRAM usage",
"Rewind is enabled, saving every %d frames, with %u slots and %" PRIu64 "MB RAM and %" PRIu64 "MB VRAM usage", std::max(s_rewind_save_frequency, 1), g_settings.rewind_save_slots, ram_usage / 1048576,
std::max(s_rewind_save_frequency, 1), g_settings.rewind_save_slots, ram_usage / 1048576, vram_usage / 1048576); vram_usage / 1048576);
} }
else else
{ {
@ -4177,7 +4179,7 @@ void System::UpdateMemorySaveStateSettings()
s_runahead_frames = g_settings.runahead_frames; s_runahead_frames = g_settings.runahead_frames;
s_runahead_replay_pending = false; s_runahead_replay_pending = false;
if (s_runahead_frames > 0) if (s_runahead_frames > 0)
Log_InfoPrintf("Runahead is active with %u frames", s_runahead_frames); Log_InfoFmt("Runahead is active with {} frames", s_runahead_frames);
} }
bool System::LoadMemoryState(const MemorySaveState& mss) bool System::LoadMemoryState(const MemorySaveState& mss)
@ -4237,8 +4239,8 @@ bool System::SaveRewindState()
s_rewind_states.push_back(std::move(mss)); s_rewind_states.push_back(std::move(mss));
#ifdef PROFILE_MEMORY_SAVE_STATES #ifdef PROFILE_MEMORY_SAVE_STATES
Log_DevPrintf("Saved rewind state (%" PRIu64 " bytes, took %.4f ms)", s_rewind_states.back().state_stream->GetSize(), Log_DevFmt("Saved rewind state ({} bytes, took {:.4f} ms)", s_rewind_states.back().state_stream->GetSize(),
save_timer.GetTimeMilliseconds()); save_timer.GetTimeMilliseconds());
#endif #endif
return true; return true;
@ -4267,7 +4269,7 @@ bool System::LoadRewindState(u32 skip_saves /*= 0*/, bool consume_state /*=true
s_rewind_states.pop_back(); s_rewind_states.pop_back();
#ifdef PROFILE_MEMORY_SAVE_STATES #ifdef PROFILE_MEMORY_SAVE_STATES
Log_DevPrintf("Rewind load took %.4f ms", load_timer.GetTimeMilliseconds()); Log_DevFmt("Rewind load took {:.4f} ms", load_timer.GetTimeMilliseconds());
#endif #endif
return true; return true;
@ -4350,7 +4352,7 @@ bool System::DoRunahead()
if (s_runahead_replay_pending) if (s_runahead_replay_pending)
{ {
#ifdef PROFILE_MEMORY_SAVE_STATES #ifdef PROFILE_MEMORY_SAVE_STATES
Log_DevPrintf("runahead starting at frame %u", s_frame_number); Log_DevFmt("runahead starting at frame {}", s_frame_number);
replay_timer.Reset(); replay_timer.Reset();
#endif #endif
@ -4372,7 +4374,7 @@ bool System::DoRunahead()
SPU::SetAudioOutputMuted(true); SPU::SetAudioOutputMuted(true);
#ifdef PROFILE_MEMORY_SAVE_STATES #ifdef PROFILE_MEMORY_SAVE_STATES
Log_VerbosePrintf("Rewound to frame %u, took %.2f ms", s_frame_number, replay_timer.GetTimeMilliseconds()); Log_VerboseFmt("Rewound to frame {}, took {:.2f} ms", s_frame_number, replay_timer.GetTimeMilliseconds());
#endif #endif
// we don't want to save the frame we just loaded. but we are "one frame ahead", because the frame we just tossed // we don't want to save the frame we just loaded. but we are "one frame ahead", because the frame we just tossed
@ -4393,15 +4395,14 @@ bool System::DoRunahead()
} }
#ifdef PROFILE_MEMORY_SAVE_STATES #ifdef PROFILE_MEMORY_SAVE_STATES
Log_VerbosePrintf("Running %d frames to catch up took %.2f ms", s_runahead_frames, Log_VerboseFmt("Running {} frames to catch up took {:.2f} ms", s_runahead_frames, replay_timer.GetTimeMilliseconds());
replay_timer.GetTimeMilliseconds());
#endif #endif
// we're all caught up. this frame gets saved in DoMemoryStates(). // we're all caught up. this frame gets saved in DoMemoryStates().
SPU::SetAudioOutputMuted(false); SPU::SetAudioOutputMuted(false);
#ifdef PROFILE_MEMORY_SAVE_STATES #ifdef PROFILE_MEMORY_SAVE_STATES
Log_DevPrintf("runahead ending at frame %u, took %.2f ms", s_frame_number, replay_timer.GetTimeMilliseconds()); Log_DevFmt("runahead ending at frame {}, took {:.2f} ms", s_frame_number, replay_timer.GetTimeMilliseconds());
#endif #endif
return false; return false;
@ -4413,7 +4414,7 @@ void System::SetRunaheadReplayFlag()
return; return;
#ifdef PROFILE_MEMORY_SAVE_STATES #ifdef PROFILE_MEMORY_SAVE_STATES
Log_DevPrintf("Runahead rewind pending..."); Log_DevPrint("Runahead rewind pending...");
#endif #endif
s_runahead_replay_pending = true; s_runahead_replay_pending = true;
@ -4479,7 +4480,7 @@ bool System::UndoLoadState()
return false; return false;
} }
Log_InfoPrintf("Loaded undo save state."); Log_InfoPrint("Loaded undo save state.");
m_undo_load_state.reset(); m_undo_load_state.reset();
return true; return true;
} }
@ -4500,7 +4501,7 @@ bool System::SaveUndoLoadState()
return false; return false;
} }
Log_InfoPrintf("Saved undo load state: %" PRIu64 " bytes", m_undo_load_state->GetSize()); Log_InfoFmt("Saved undo load state: {} bytes", m_undo_load_state->GetSize());
return true; return true;
} }
@ -4736,9 +4737,11 @@ void System::DeleteSaveStates(const char* serial, bool resume)
if (si.global || (!resume && si.slot < 0)) if (si.global || (!resume && si.slot < 0))
continue; continue;
Log_InfoPrintf("Removing save state at '%s'", si.path.c_str()); Log_InfoFmt("Removing save state '{}'", Path::GetFileName(si.path));
if (!FileSystem::DeleteFile(si.path.c_str()))
Log_ErrorPrintf("Failed to delete save state file '%s'", si.path.c_str()); Error error;
if (!FileSystem::DeleteFile(si.path.c_str(), &error)) [[unlikely]]
Log_ErrorFmt("Failed to delete save state file '{}': {}", Path::GetFileName(si.path), error.GetDescription());
} }
} }
@ -4900,7 +4903,7 @@ bool System::LoadCheatListFromDatabase()
if (!cl->LoadFromPackage(s_running_game_serial)) if (!cl->LoadFromPackage(s_running_game_serial))
return false; return false;
Log_InfoPrintf("Loaded %u cheats from database.", cl->GetCodeCount()); Log_InfoFmt("Loaded {} cheats from database.", cl->GetCodeCount());
SetCheatList(std::move(cl)); SetCheatList(std::move(cl));
return true; return true;
} }

View File

@ -113,9 +113,9 @@ void TextureReplacements::DumpVRAMWrite(u32 width, u32 height, const void* pixel
} }
} }
Log_InfoPrintf("Dumping %ux%u VRAM write to '%s'", width, height, filename.c_str()); Log_InfoFmt("Dumping {}x{} VRAM write to '{}'", width, height, Path::GetFileName(filename));
if (!image.SaveToFile(filename.c_str())) if (!image.SaveToFile(filename.c_str())) [[unlikely]]
Log_ErrorPrintf("Failed to dump %ux%u VRAM write to '%s'", width, height, filename.c_str()); Log_ErrorFmt("Failed to dump {}x{} VRAM write to '{}'", width, height, filename);
} }
void TextureReplacements::Shutdown() void TextureReplacements::Shutdown()
@ -255,7 +255,7 @@ void TextureReplacements::FindTextures(const std::string& dir)
auto it = m_vram_write_replacements.find(hash); auto it = m_vram_write_replacements.find(hash);
if (it != m_vram_write_replacements.end()) if (it != m_vram_write_replacements.end())
{ {
Log_WarningPrintf("Duplicate VRAM write replacement: '%s' and '%s'", it->second.c_str(), fd.FileName.c_str()); Log_WarningFmt("Duplicate VRAM write replacement: '{}' and '{}'", it->second, fd.FileName);
continue; continue;
} }
@ -265,7 +265,7 @@ void TextureReplacements::FindTextures(const std::string& dir)
} }
} }
Log_InfoPrintf("Found %zu replacement VRAM writes for '%s'", m_vram_write_replacements.size(), m_game_id.c_str()); Log_InfoFmt("Found {} replacement VRAM writes for '{}'", m_vram_write_replacements.size(), m_game_id);
} }
const TextureReplacementTexture* TextureReplacements::LoadTexture(const std::string& filename) const TextureReplacementTexture* TextureReplacements::LoadTexture(const std::string& filename)
@ -277,11 +277,11 @@ const TextureReplacementTexture* TextureReplacements::LoadTexture(const std::str
RGBA8Image image; RGBA8Image image;
if (!image.LoadFromFile(filename.c_str())) if (!image.LoadFromFile(filename.c_str()))
{ {
Log_ErrorPrintf("Failed to load '%s'", filename.c_str()); Log_ErrorFmt("Failed to load '%s'", Path::GetFileName(filename));
return nullptr; return nullptr;
} }
Log_InfoPrintf("Loaded '%s': %ux%u", filename.c_str(), image.GetWidth(), image.GetHeight()); Log_InfoFmt("Loaded '{}': {}x{}", Path::GetFileName(filename), image.GetWidth(), image.GetHeight());
it = m_texture_cache.emplace(filename, std::move(image)).first; it = m_texture_cache.emplace(filename, std::move(image)).first;
return &it->second; return &it->second;
} }

View File

@ -249,7 +249,7 @@ void Timers::CheckForIRQ(u32 timer, u32 old_counter)
if (!cs.irq_done || cs.mode.irq_repeat) if (!cs.irq_done || cs.mode.irq_repeat)
{ {
// this is actually low for a few cycles // this is actually low for a few cycles
Log_DebugPrintf("Raising timer %u pulse IRQ", timer); Log_DebugFmt("Raising timer {} pulse IRQ", timer);
InterruptController::SetLineState(irqnum, false); InterruptController::SetLineState(irqnum, false);
InterruptController::SetLineState(irqnum, true); InterruptController::SetLineState(irqnum, true);
} }
@ -262,7 +262,7 @@ void Timers::CheckForIRQ(u32 timer, u32 old_counter)
// TODO: How does the non-repeat mode work here? // TODO: How does the non-repeat mode work here?
cs.mode.interrupt_request_n ^= true; cs.mode.interrupt_request_n ^= true;
if (!cs.mode.interrupt_request_n) if (!cs.mode.interrupt_request_n)
Log_DebugPrintf("Raising timer %u alternate IRQ", timer); Log_DebugFmt("Raising timer {} alternate IRQ", timer);
InterruptController::SetLineState(irqnum, !cs.mode.interrupt_request_n); InterruptController::SetLineState(irqnum, !cs.mode.interrupt_request_n);
} }
@ -295,9 +295,9 @@ u32 Timers::ReadRegister(u32 offset)
{ {
const u32 timer_index = (offset >> 4) & u32(0x03); const u32 timer_index = (offset >> 4) & u32(0x03);
const u32 port_offset = offset & u32(0x0F); const u32 port_offset = offset & u32(0x0F);
if (timer_index >= 3) if (timer_index >= 3) [[unlikely]]
{ {
Log_ErrorPrintf("Timer read out of range: offset 0x%02X", offset); Log_ErrorFmt("Timer read out of range: offset 0x{:02X}", offset);
return UINT32_C(0xFFFFFFFF); return UINT32_C(0xFFFFFFFF);
} }
@ -340,7 +340,7 @@ u32 Timers::ReadRegister(u32 offset)
return cs.target; return cs.target;
default: default:
Log_ErrorPrintf("Read unknown register in timer %u (offset 0x%02X)", timer_index, offset); [[unlikely]] Log_ErrorFmt("Read unknown register in timer {} (offset 0x{:02X})", timer_index, offset);
return UINT32_C(0xFFFFFFFF); return UINT32_C(0xFFFFFFFF);
} }
} }
@ -349,9 +349,9 @@ void Timers::WriteRegister(u32 offset, u32 value)
{ {
const u32 timer_index = (offset >> 4) & u32(0x03); const u32 timer_index = (offset >> 4) & u32(0x03);
const u32 port_offset = offset & u32(0x0F); const u32 port_offset = offset & u32(0x0F);
if (timer_index >= 3) if (timer_index >= 3) [[unlikely]]
{ {
Log_ErrorPrintf("Timer write out of range: offset 0x%02X value 0x%08X", offset, value); Log_ErrorFmt("Timer write out of range: offset 0{:02X} value 0x{:08X}", offset, value);
return; return;
} }
@ -372,7 +372,7 @@ void Timers::WriteRegister(u32 offset, u32 value)
case 0x00: case 0x00:
{ {
const u32 old_counter = cs.counter; const u32 old_counter = cs.counter;
Log_DebugPrintf("Timer %u write counter %u", timer_index, value); Log_DebugFmt("Timer {} write counter {}", timer_index, value);
cs.counter = value & u32(0xFFFF); cs.counter = value & u32(0xFFFF);
CheckForIRQ(timer_index, old_counter); CheckForIRQ(timer_index, old_counter);
if (timer_index == 2 || !cs.external_counting_enabled) if (timer_index == 2 || !cs.external_counting_enabled)
@ -384,7 +384,7 @@ void Timers::WriteRegister(u32 offset, u32 value)
{ {
static constexpr u32 WRITE_MASK = 0b1110001111111111; static constexpr u32 WRITE_MASK = 0b1110001111111111;
Log_DebugPrintf("Timer %u write mode register 0x%04X", timer_index, value); Log_DebugFmt("Timer {} write mode register 0x{:04X}", timer_index, value);
cs.mode.bits = (value & WRITE_MASK) | (cs.mode.bits & ~WRITE_MASK); cs.mode.bits = (value & WRITE_MASK) | (cs.mode.bits & ~WRITE_MASK);
cs.use_external_clock = (cs.mode.clock_source & (timer_index == 2 ? 2 : 1)) != 0; cs.use_external_clock = (cs.mode.clock_source & (timer_index == 2 ? 2 : 1)) != 0;
cs.counter = 0; cs.counter = 0;
@ -400,7 +400,7 @@ void Timers::WriteRegister(u32 offset, u32 value)
case 0x08: case 0x08:
{ {
Log_DebugPrintf("Timer %u write target 0x%04X", timer_index, ZeroExtend32(Truncate16(value))); Log_DebugFmt("Timer %u write target 0x{:04X}", timer_index, ZeroExtend32(Truncate16(value)));
cs.target = value & u32(0xFFFF); cs.target = value & u32(0xFFFF);
CheckForIRQ(timer_index, cs.counter); CheckForIRQ(timer_index, cs.counter);
if (timer_index == 2 || !cs.external_counting_enabled) if (timer_index == 2 || !cs.external_counting_enabled)
@ -409,7 +409,7 @@ void Timers::WriteRegister(u32 offset, u32 value)
break; break;
default: default:
Log_ErrorPrintf("Write unknown register in timer %u (offset 0x%02X, value 0x%X)", timer_index, offset, value); Log_ErrorFmt("Write unknown register in timer {} (offset 0x{:02X}, value 0x{:X})", timer_index, offset, value);
break; break;
} }
} }

View File

@ -374,7 +374,7 @@ bool DoState(StateWrapper& sw)
TimingEvent* event = FindActiveEvent(event_name.c_str()); TimingEvent* event = FindActiveEvent(event_name.c_str());
if (!event) if (!event)
{ {
Log_WarningPrintf("Save state has event '%s', but couldn't find this event when loading.", event_name.c_str()); Log_WarningFmt("Save state has event '{}', but couldn't find this event when loading.", event_name);
continue; continue;
} }
@ -391,7 +391,7 @@ bool DoState(StateWrapper& sw)
sw.Do(&last_event_run_time); sw.Do(&last_event_run_time);
} }
Log_DebugPrintf("Loaded %u events from save state.", event_count); Log_DebugFmt("Loaded {} events from save state.", event_count);
SortEvents(); SortEvents();
} }
else else
@ -408,7 +408,7 @@ bool DoState(StateWrapper& sw)
sw.Do(&event->m_interval); sw.Do(&event->m_interval);
} }
Log_DebugPrintf("Wrote %u events to save state.", s_active_event_count); Log_DebugFmt("Wrote {} events to save state.", s_active_event_count);
} }
return !sw.HasError(); return !sw.HasError();

View File

@ -86,7 +86,7 @@ bool AutoUpdaterDialog::isSupported()
// For Linux, we need to check whether we're running from the appimage. // For Linux, we need to check whether we're running from the appimage.
if (!std::getenv("APPIMAGE")) if (!std::getenv("APPIMAGE"))
{ {
Log_InfoPrintf("We're a CI release, but not running from an AppImage. Disabling automatic updater."); Log_InfoPrint("We're a CI release, but not running from an AppImage. Disabling automatic updater.");
return false; return false;
} }
@ -465,16 +465,16 @@ bool AutoUpdaterDialog::updateNeeded() const
{ {
QString last_checked_sha = QString::fromStdString(Host::GetBaseStringSettingValue("AutoUpdater", "LastVersion")); QString last_checked_sha = QString::fromStdString(Host::GetBaseStringSettingValue("AutoUpdater", "LastVersion"));
Log_InfoPrintf("Current SHA: %s", g_scm_hash_str); Log_InfoFmt("Current SHA: {}", g_scm_hash_str);
Log_InfoPrintf("Latest SHA: %s", m_latest_sha.toUtf8().constData()); Log_InfoFmt("Latest SHA: {}", m_latest_sha.toUtf8().constData());
Log_InfoPrintf("Last Checked SHA: %s", last_checked_sha.toUtf8().constData()); Log_InfoFmt("Last Checked SHA: {}", last_checked_sha.toUtf8().constData());
if (m_latest_sha == g_scm_hash_str || m_latest_sha == last_checked_sha) if (m_latest_sha == g_scm_hash_str || m_latest_sha == last_checked_sha)
{ {
Log_InfoPrintf("No update needed."); Log_InfoPrint("No update needed.");
return false; return false;
} }
Log_InfoPrintf("Update needed."); Log_InfoPrint("Update needed.");
return true; return true;
} }
@ -735,9 +735,9 @@ bool AutoUpdaterDialog::processUpdate(const std::vector<u8>& update_data)
const QString new_appimage_path(qappimage_path + QStringLiteral(".new")); const QString new_appimage_path(qappimage_path + QStringLiteral(".new"));
const QString backup_appimage_path(qappimage_path + QStringLiteral(".backup")); const QString backup_appimage_path(qappimage_path + QStringLiteral(".backup"));
Log_InfoPrintf("APPIMAGE = %s", appimage_path); Log_InfoFmt("APPIMAGE = {}", appimage_path);
Log_InfoPrintf("Backup AppImage path = %s", backup_appimage_path.toUtf8().constData()); Log_InfoFmt("Backup AppImage path = {}", backup_appimage_path.toUtf8().constData());
Log_InfoPrintf("New AppImage path = %s", new_appimage_path.toUtf8().constData()); Log_InfoFmt("New AppImage path = {}", new_appimage_path.toUtf8().constData());
// Remove old "new" appimage and existing backup appimage. // Remove old "new" appimage and existing backup appimage.
if (QFile::exists(new_appimage_path) && !QFile::remove(new_appimage_path)) if (QFile::exists(new_appimage_path) && !QFile::remove(new_appimage_path))

View File

@ -481,7 +481,7 @@ void ControllerBindingWidget::bindBindingWidgets(QWidget* parent)
InputBindingWidget* widget = parent->findChild<InputBindingWidget*>(QString::fromUtf8(bi.name)); InputBindingWidget* widget = parent->findChild<InputBindingWidget*>(QString::fromUtf8(bi.name));
if (!widget) if (!widget)
{ {
Log_ErrorPrintf("No widget found for '%s' (%s)", bi.name, m_controller_info->name); Log_ErrorFmt("No widget found for '{}' ({})", bi.name, m_controller_info->name);
continue; continue;
} }

View File

@ -84,7 +84,7 @@ void DisplayWidget::updateRelativeMode(bool enabled)
if (m_relative_mouse_enabled == enabled && m_clip_mouse_enabled == clip_cursor) if (m_relative_mouse_enabled == enabled && m_clip_mouse_enabled == clip_cursor)
return; return;
Log_InfoPrintf("updateRelativeMode(): relative=%s, clip=%s", enabled ? "yes" : "no", clip_cursor ? "yes" : "no"); Log_InfoFmt("updateRelativeMode(): relative={}, clip={}", enabled ? "yes" : "no", clip_cursor ? "yes" : "no");
if (!clip_cursor && m_clip_mouse_enabled) if (!clip_cursor && m_clip_mouse_enabled)
{ {
@ -95,7 +95,7 @@ void DisplayWidget::updateRelativeMode(bool enabled)
if (m_relative_mouse_enabled == enabled) if (m_relative_mouse_enabled == enabled)
return; return;
Log_InfoPrintf("updateRelativeMode(): relative=%s", enabled ? "yes" : "no"); Log_InfoFmt("updateRelativeMode(): relative={}", enabled ? "yes" : "no");
#endif #endif
if (enabled) if (enabled)
@ -126,12 +126,12 @@ void DisplayWidget::updateCursor(bool hidden)
m_cursor_hidden = hidden; m_cursor_hidden = hidden;
if (hidden) if (hidden)
{ {
Log_DevPrintf("updateCursor(): Cursor is now hidden"); Log_DevPrint("updateCursor(): Cursor is now hidden");
setCursor(Qt::BlankCursor); setCursor(Qt::BlankCursor);
} }
else else
{ {
Log_DevPrintf("updateCursor(): Cursor is now shown"); Log_DevPrint("updateCursor(): Cursor is now shown");
unsetCursor(); unsetCursor();
} }
} }

View File

@ -11,8 +11,7 @@ GDBConnection::GDBConnection(GDBServer* parent, intptr_t descriptor) : QTcpSocke
{ {
if (!setSocketDescriptor(descriptor)) if (!setSocketDescriptor(descriptor))
{ {
Log_ErrorPrintf("(%" PRIdPTR ") Failed to set socket descriptor: %s", descriptor, Log_ErrorFmt("{} failed to set socket descriptor: {}", descriptor, errorString().toStdString());
errorString().toUtf8().constData());
deleteLater(); deleteLater();
return; return;
} }
@ -22,7 +21,7 @@ GDBConnection::GDBConnection(GDBServer* parent, intptr_t descriptor) : QTcpSocke
connect(this, &QTcpSocket::readyRead, this, &GDBConnection::receivedData); connect(this, &QTcpSocket::readyRead, this, &GDBConnection::receivedData);
connect(this, &QTcpSocket::disconnected, this, &GDBConnection::gotDisconnected); connect(this, &QTcpSocket::disconnected, this, &GDBConnection::gotDisconnected);
Log_InfoPrintf("(%" PRIdPTR ") Client connected", m_descriptor); Log_InfoFmt("{} client connected", m_descriptor);
m_seen_resume = System::IsPaused(); m_seen_resume = System::IsPaused();
g_emu_thread->setSystemPaused(true); g_emu_thread->setSystemPaused(true);
@ -30,7 +29,7 @@ GDBConnection::GDBConnection(GDBServer* parent, intptr_t descriptor) : QTcpSocke
void GDBConnection::gotDisconnected() void GDBConnection::gotDisconnected()
{ {
Log_InfoPrintf("(%" PRIdPTR ") Client disconnected", m_descriptor); Log_InfoFmt("{} client disconnected", m_descriptor);
deleteLater(); deleteLater();
} }
@ -47,19 +46,19 @@ void GDBConnection::receivedData()
if (GDBProtocol::IsPacketInterrupt(m_readBuffer)) if (GDBProtocol::IsPacketInterrupt(m_readBuffer))
{ {
Log_DebugPrintf("(%" PRIdPTR ") > Interrupt request", m_descriptor); Log_DebugFmt("{} > Interrupt request", m_descriptor);
g_emu_thread->setSystemPaused(true); g_emu_thread->setSystemPaused(true);
m_readBuffer.erase(); m_readBuffer.erase();
} }
else if (GDBProtocol::IsPacketContinue(m_readBuffer)) else if (GDBProtocol::IsPacketContinue(m_readBuffer))
{ {
Log_DebugPrintf("(%" PRIdPTR ") > Continue request", m_descriptor); Log_DebugFmt("{} > Continue request", m_descriptor);
g_emu_thread->setSystemPaused(false); g_emu_thread->setSystemPaused(false);
m_readBuffer.erase(); m_readBuffer.erase();
} }
else if (GDBProtocol::IsPacketComplete(m_readBuffer)) else if (GDBProtocol::IsPacketComplete(m_readBuffer))
{ {
Log_DebugPrintf("(%" PRIdPTR ") > %s", m_descriptor, m_readBuffer.c_str()); Log_DebugFmt("{} > %s", m_descriptor, m_readBuffer.c_str());
writePacket(GDBProtocol::ProcessPacket(m_readBuffer)); writePacket(GDBProtocol::ProcessPacket(m_readBuffer));
m_readBuffer.erase(); m_readBuffer.erase();
} }
@ -67,8 +66,7 @@ void GDBConnection::receivedData()
} }
if (bytesRead == -1) if (bytesRead == -1)
{ {
Log_ErrorPrintf("(%" PRIdPTR ") Failed to read from socket: %s", m_descriptor, Log_ErrorFmt("{} failed to read from socket: %s", m_descriptor, errorString().toStdString());
errorString().toUtf8().constData());
} }
} }
@ -91,10 +89,7 @@ void GDBConnection::onEmulationResumed()
void GDBConnection::writePacket(std::string_view packet) void GDBConnection::writePacket(std::string_view packet)
{ {
Log_DebugPrintf("(%" PRIdPTR ") < %.*s", m_descriptor, static_cast<int>(packet.length()), packet.data()); Log_DebugFmt("{} < {}", m_descriptor, packet);
if (write(packet.data(), packet.length()) == -1) if (write(packet.data(), packet.length()) == -1)
{ Log_ErrorFmt("{} failed to write to socket: {}", m_descriptor, errorString().toStdString());
Log_ErrorPrintf("(%" PRIdPTR ") Failed to write to socket: %s", m_descriptor,
errorString().toUtf8().constData());
}
} }

View File

@ -2,13 +2,12 @@
// SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0) // SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)
#include "gdbserver.h" #include "gdbserver.h"
#include "gdbconnection.h"
#include "common/log.h" #include "common/log.h"
#include "gdbconnection.h"
#include "qthost.h" #include "qthost.h"
Log_SetChannel(GDBServer); Log_SetChannel(GDBServer);
GDBServer::GDBServer(QObject *parent) GDBServer::GDBServer(QObject* parent) : QTcpServer(parent)
: QTcpServer(parent)
{ {
} }
@ -17,7 +16,8 @@ GDBServer::~GDBServer()
stop(); stop();
} }
void GDBServer::start(quint16 port) { void GDBServer::start(quint16 port)
{
if (isListening()) if (isListening())
{ {
return; return;
@ -25,12 +25,11 @@ void GDBServer::start(quint16 port) {
if (!listen(QHostAddress::LocalHost, port)) if (!listen(QHostAddress::LocalHost, port))
{ {
Log_ErrorPrintf("Failed to listen on TCP port %u for GDB server: %s", port, Log_ErrorFmt("Failed to listen on TCP port {} for GDB server: {}", port, errorString().toUtf8().constData());
errorString().toUtf8().constData());
return; return;
} }
Log_InfoPrintf("GDB server listening on TCP port %u", port); Log_InfoFmt("GDB server listening on TCP port {}", port);
} }
void GDBServer::stop() void GDBServer::stop()
@ -41,7 +40,8 @@ void GDBServer::stop()
Log_InfoPrint("GDB server stopped"); Log_InfoPrint("GDB server stopped");
} }
for (QObject* connection : children()) { for (QObject* connection : children())
{
connection->deleteLater(); connection->deleteLater();
} }
} }

View File

@ -246,8 +246,8 @@ bool MainWindow::nativeEvent(const QByteArray& eventType, void* message, qintptr
std::optional<WindowInfo> MainWindow::acquireRenderWindow(bool recreate_window, bool fullscreen, bool render_to_main, std::optional<WindowInfo> MainWindow::acquireRenderWindow(bool recreate_window, bool fullscreen, bool render_to_main,
bool surfaceless, bool use_main_window_pos) bool surfaceless, bool use_main_window_pos)
{ {
Log_DevPrintf( Log_DevFmt(
"acquireRenderWindow() recreate=%s fullscreen=%s render_to_main=%s surfaceless=%s use_main_window_pos=%s", "acquireRenderWindow() recreate={} fullscreen={} render_to_main={} surfaceless={} use_main_window_pos={}",
recreate_window ? "true" : "false", fullscreen ? "true" : "false", render_to_main ? "true" : "false", recreate_window ? "true" : "false", fullscreen ? "true" : "false", render_to_main ? "true" : "false",
surfaceless ? "true" : "false", use_main_window_pos ? "true" : "false"); surfaceless ? "true" : "false", use_main_window_pos ? "true" : "false");
@ -269,7 +269,7 @@ std::optional<WindowInfo> MainWindow::acquireRenderWindow(bool recreate_window,
if (m_display_created && !recreate_window && !is_rendering_to_main && !render_to_main && if (m_display_created && !recreate_window && !is_rendering_to_main && !render_to_main &&
has_container == needs_container && !needs_container && !changing_surfaceless) has_container == needs_container && !needs_container && !changing_surfaceless)
{ {
Log_DevPrintf("Toggling to %s without recreating surface", (fullscreen ? "fullscreen" : "windowed")); Log_DevFmt("Toggling to {} without recreating surface", (fullscreen ? "fullscreen" : "windowed"));
// since we don't destroy the display widget, we need to save it here // since we don't destroy the display widget, we need to save it here
if (!is_fullscreen && !is_rendering_to_main) if (!is_fullscreen && !is_rendering_to_main)

View File

@ -465,9 +465,9 @@ bool QtHost::SetCriticalFolders()
return false; return false;
// logging of directories in case something goes wrong super early // logging of directories in case something goes wrong super early
Log_DevPrintf("AppRoot Directory: %s", EmuFolders::AppRoot.c_str()); Log_DevFmt("AppRoot Directory: {}", EmuFolders::AppRoot);
Log_DevPrintf("DataRoot Directory: %s", EmuFolders::DataRoot.c_str()); Log_DevFmt("DataRoot Directory: {}", EmuFolders::DataRoot);
Log_DevPrintf("Resources Directory: %s", EmuFolders::Resources.c_str()); Log_DevFmt("Resources Directory: {}", EmuFolders::Resources);
// Write crash dumps to the data directory, since that'll be accessible for certain. // Write crash dumps to the data directory, since that'll be accessible for certain.
CrashHandler::SetWriteDirectory(EmuFolders::DataRoot); CrashHandler::SetWriteDirectory(EmuFolders::DataRoot);
@ -493,7 +493,7 @@ bool QtHost::ShouldUsePortableMode()
void QtHost::SetAppRoot() void QtHost::SetAppRoot()
{ {
const std::string program_path = FileSystem::GetProgramPath(); const std::string program_path = FileSystem::GetProgramPath();
Log_InfoPrintf("Program Path: %s", program_path.c_str()); Log_InfoFmt("Program Path: {}", program_path.c_str());
EmuFolders::AppRoot = Path::Canonicalize(Path::GetDirectory(program_path)); EmuFolders::AppRoot = Path::Canonicalize(Path::GetDirectory(program_path));
} }
@ -1813,14 +1813,9 @@ void Host::ReportFatalError(std::string_view title, std::string_view message)
void Host::ReportErrorAsync(std::string_view title, std::string_view message) void Host::ReportErrorAsync(std::string_view title, std::string_view message)
{ {
if (!title.empty() && !message.empty()) if (!title.empty() && !message.empty())
{ Log_ErrorFmt("ReportErrorAsync: {}: {}", title, message);
Log_ErrorPrintf("ReportErrorAsync: %.*s: %.*s", static_cast<int>(title.size()), title.data(),
static_cast<int>(message.size()), message.data());
}
else if (!message.empty()) else if (!message.empty())
{ Log_ErrorFmt("ReportErrorAsync: {}", message);
Log_ErrorPrintf("ReportErrorAsync: %.*s", static_cast<int>(message.size()), message.data());
}
QMetaObject::invokeMethod( QMetaObject::invokeMethod(
g_main_window, "reportError", Qt::QueuedConnection, g_main_window, "reportError", Qt::QueuedConnection,
@ -2292,88 +2287,88 @@ bool QtHost::ParseCommandLineParametersAndInitializeConfig(QApplication& app,
} }
else if (CHECK_ARG("-batch")) else if (CHECK_ARG("-batch"))
{ {
Log_InfoPrintf("Command Line: Using batch mode."); Log_InfoPrint("Command Line: Using batch mode.");
s_batch_mode = true; s_batch_mode = true;
continue; continue;
} }
else if (CHECK_ARG("-nogui")) else if (CHECK_ARG("-nogui"))
{ {
Log_InfoPrintf("Command Line: Using NoGUI mode."); Log_InfoPrint("Command Line: Using NoGUI mode.");
s_nogui_mode = true; s_nogui_mode = true;
s_batch_mode = true; s_batch_mode = true;
continue; continue;
} }
else if (CHECK_ARG("-bios")) else if (CHECK_ARG("-bios"))
{ {
Log_InfoPrintf("Command Line: Starting BIOS."); Log_InfoPrint("Command Line: Starting BIOS.");
AutoBoot(autoboot); AutoBoot(autoboot);
starting_bios = true; starting_bios = true;
continue; continue;
} }
else if (CHECK_ARG("-fastboot")) else if (CHECK_ARG("-fastboot"))
{ {
Log_InfoPrintf("Command Line: Forcing fast boot."); Log_InfoPrint("Command Line: Forcing fast boot.");
AutoBoot(autoboot)->override_fast_boot = true; AutoBoot(autoboot)->override_fast_boot = true;
continue; continue;
} }
else if (CHECK_ARG("-slowboot")) else if (CHECK_ARG("-slowboot"))
{ {
Log_InfoPrintf("Command Line: Forcing slow boot."); Log_InfoPrint("Command Line: Forcing slow boot.");
AutoBoot(autoboot)->override_fast_boot = false; AutoBoot(autoboot)->override_fast_boot = false;
continue; continue;
} }
else if (CHECK_ARG("-resume")) else if (CHECK_ARG("-resume"))
{ {
state_index = -1; state_index = -1;
Log_InfoPrintf("Command Line: Loading resume state."); Log_InfoPrint("Command Line: Loading resume state.");
continue; continue;
} }
else if (CHECK_ARG_PARAM("-state")) else if (CHECK_ARG_PARAM("-state"))
{ {
state_index = args[++i].toInt(); state_index = args[++i].toInt();
Log_InfoPrintf("Command Line: Loading state index: %d", state_index.value()); Log_InfoFmt("Command Line: Loading state index: {}", state_index.value());
continue; continue;
} }
else if (CHECK_ARG_PARAM("-statefile")) else if (CHECK_ARG_PARAM("-statefile"))
{ {
AutoBoot(autoboot)->save_state = args[++i].toStdString(); AutoBoot(autoboot)->save_state = args[++i].toStdString();
Log_InfoPrintf("Command Line: Loading state file: '%s'", autoboot->save_state.c_str()); Log_InfoFmt("Command Line: Loading state file: '{}'", autoboot->save_state);
continue; continue;
} }
else if (CHECK_ARG_PARAM("-exe")) else if (CHECK_ARG_PARAM("-exe"))
{ {
AutoBoot(autoboot)->override_exe = args[++i].toStdString(); AutoBoot(autoboot)->override_exe = args[++i].toStdString();
Log_InfoPrintf("Command Line: Overriding EXE file: '%s'", autoboot->override_exe.c_str()); Log_InfoFmt("Command Line: Overriding EXE file: '{}'", autoboot->override_exe);
continue; continue;
} }
else if (CHECK_ARG("-fullscreen")) else if (CHECK_ARG("-fullscreen"))
{ {
Log_InfoPrintf("Command Line: Using fullscreen."); Log_InfoPrint("Command Line: Using fullscreen.");
AutoBoot(autoboot)->override_fullscreen = true; AutoBoot(autoboot)->override_fullscreen = true;
s_start_fullscreen_ui_fullscreen = true; s_start_fullscreen_ui_fullscreen = true;
continue; continue;
} }
else if (CHECK_ARG("-nofullscreen")) else if (CHECK_ARG("-nofullscreen"))
{ {
Log_InfoPrintf("Command Line: Not using fullscreen."); Log_InfoPrint("Command Line: Not using fullscreen.");
AutoBoot(autoboot)->override_fullscreen = false; AutoBoot(autoboot)->override_fullscreen = false;
continue; continue;
} }
else if (CHECK_ARG("-portable")) else if (CHECK_ARG("-portable"))
{ {
Log_InfoPrintf("Command Line: Using portable mode."); Log_InfoPrint("Command Line: Using portable mode.");
EmuFolders::DataRoot = EmuFolders::AppRoot; EmuFolders::DataRoot = EmuFolders::AppRoot;
continue; continue;
} }
else if (CHECK_ARG_PARAM("-settings")) else if (CHECK_ARG_PARAM("-settings"))
{ {
settings_filename = args[++i].toStdString(); settings_filename = args[++i].toStdString();
Log_InfoPrintf("Command Line: Overriding settings filename: %s", settings_filename.c_str()); Log_InfoFmt("Command Line: Overriding settings filename: {}", settings_filename);
continue; continue;
} }
else if (CHECK_ARG("-bigpicture")) else if (CHECK_ARG("-bigpicture"))
{ {
Log_InfoPrintf("Command Line: Starting big picture mode."); Log_InfoPrint("Command Line: Starting big picture mode.");
s_start_fullscreen_ui = true; s_start_fullscreen_ui = true;
continue; continue;
} }

View File

@ -136,7 +136,7 @@ void QtHost::InstallTranslator(QWidget* dialog_parent)
return; return;
} }
Log_InfoPrintf("Loaded translation file for language %s", language.toUtf8().constData()); Log_InfoFmt("Loaded translation file for language {}", language.toUtf8().constData());
qApp->installTranslator(translator); qApp->installTranslator(translator);
s_translators.push_back(translator); s_translators.push_back(translator);

View File

@ -52,7 +52,7 @@ static std::string s_dump_game_directory;
bool RegTestHost::SetFolders() bool RegTestHost::SetFolders()
{ {
std::string program_path(FileSystem::GetProgramPath()); std::string program_path(FileSystem::GetProgramPath());
Log_InfoPrintf("Program Path: %s", program_path.c_str()); Log_InfoFmt("Program Path: {}", program_path);
EmuFolders::AppRoot = Path::Canonicalize(Path::GetDirectory(program_path)); EmuFolders::AppRoot = Path::Canonicalize(Path::GetDirectory(program_path));
EmuFolders::DataRoot = EmuFolders::AppRoot; EmuFolders::DataRoot = EmuFolders::AppRoot;
@ -67,9 +67,9 @@ bool RegTestHost::SetFolders()
// On Windows/Linux, these are in the binary directory. // On Windows/Linux, these are in the binary directory.
EmuFolders::Resources = Path::Combine(EmuFolders::AppRoot, "resources"); EmuFolders::Resources = Path::Combine(EmuFolders::AppRoot, "resources");
Log_DevPrintf("AppRoot Directory: %s", EmuFolders::AppRoot.c_str()); Log_DevFmt("AppRoot Directory: {}", EmuFolders::AppRoot);
Log_DevPrintf("DataRoot Directory: %s", EmuFolders::DataRoot.c_str()); Log_DevFmt("DataRoot Directory: {}", EmuFolders::DataRoot);
Log_DevPrintf("Resources Directory: %s", EmuFolders::Resources.c_str()); Log_DevFmt("Resources Directory: {}", EmuFolders::Resources);
// Write crash dumps to the data directory, since that'll be accessible for certain. // Write crash dumps to the data directory, since that'll be accessible for certain.
CrashHandler::SetWriteDirectory(EmuFolders::DataRoot); CrashHandler::SetWriteDirectory(EmuFolders::DataRoot);
@ -119,41 +119,31 @@ bool RegTestHost::InitializeConfig()
void Host::ReportFatalError(std::string_view title, std::string_view message) void Host::ReportFatalError(std::string_view title, std::string_view message)
{ {
Log_ErrorPrintf("ReportFatalError: %.*s", static_cast<int>(message.size()), message.data()); Log_ErrorFmt("ReportFatalError: {}", message);
abort(); abort();
} }
void Host::ReportErrorAsync(std::string_view title, std::string_view message) void Host::ReportErrorAsync(std::string_view title, std::string_view message)
{ {
if (!title.empty() && !message.empty()) if (!title.empty() && !message.empty())
{ Log_ErrorFmt("ReportErrorAsync: {}: {}", title, message);
Log_ErrorPrintf("ReportErrorAsync: %.*s: %.*s", static_cast<int>(title.size()), title.data(),
static_cast<int>(message.size()), message.data());
}
else if (!message.empty()) else if (!message.empty())
{ Log_ErrorFmt("ReportErrorAsync: {}", message);
Log_ErrorPrintf("ReportErrorAsync: %.*s", static_cast<int>(message.size()), message.data());
}
} }
bool Host::ConfirmMessage(std::string_view title, std::string_view message) bool Host::ConfirmMessage(std::string_view title, std::string_view message)
{ {
if (!title.empty() && !message.empty()) if (!title.empty() && !message.empty())
{ Log_ErrorFmt("ConfirmMessage: {}: {}", title, message);
Log_ErrorPrintf("ConfirmMessage: %.*s: %.*s", static_cast<int>(title.size()), title.data(),
static_cast<int>(message.size()), message.data());
}
else if (!message.empty()) else if (!message.empty())
{ Log_ErrorFmt("ConfirmMessage: {}", message);
Log_ErrorPrintf("ConfirmMessage: %.*s", static_cast<int>(message.size()), message.data());
}
return true; return true;
} }
void Host::ReportDebuggerMessage(std::string_view message) void Host::ReportDebuggerMessage(std::string_view message)
{ {
Log_ErrorPrintf("ReportDebuggerMessage: %.*s", static_cast<int>(message.size()), message.data()); Log_ErrorFmt("ReportDebuggerMessage: {}", message);
} }
std::span<const std::pair<const char*, const char*>> Host::GetAvailableLanguageList() std::span<const std::pair<const char*, const char*>> Host::GetAvailableLanguageList()
@ -219,7 +209,7 @@ std::optional<std::vector<u8>> Host::ReadResourceFile(std::string_view filename,
const std::string path(Path::Combine(EmuFolders::Resources, filename)); const std::string path(Path::Combine(EmuFolders::Resources, filename));
std::optional<std::vector<u8>> ret(FileSystem::ReadBinaryFile(path.c_str())); std::optional<std::vector<u8>> ret(FileSystem::ReadBinaryFile(path.c_str()));
if (!ret.has_value()) if (!ret.has_value())
Log_ErrorPrintf("Failed to read resource file '%s'", filename); Log_ErrorFmt("Failed to read resource file '{}'", filename);
return ret; return ret;
} }
@ -228,7 +218,7 @@ std::optional<std::string> Host::ReadResourceFileToString(std::string_view filen
const std::string path(Path::Combine(EmuFolders::Resources, filename)); const std::string path(Path::Combine(EmuFolders::Resources, filename));
std::optional<std::string> ret(FileSystem::ReadFileToString(path.c_str())); std::optional<std::string> ret(FileSystem::ReadFileToString(path.c_str()));
if (!ret.has_value()) if (!ret.has_value())
Log_ErrorPrintf("Failed to read resource file to string '%s'", filename); Log_ErrorFmt("Failed to read resource file to string '{}'", filename);
return ret; return ret;
} }
@ -238,7 +228,7 @@ std::optional<std::time_t> Host::GetResourceFileTimestamp(std::string_view filen
FILESYSTEM_STAT_DATA sd; FILESYSTEM_STAT_DATA sd;
if (!FileSystem::StatFile(path.c_str(), &sd)) if (!FileSystem::StatFile(path.c_str(), &sd))
{ {
Log_ErrorPrintf("Failed to stat resource file '%s'", filename); Log_ErrorFmt("Failed to stat resource file '{}'", filename);
return std::nullopt; return std::nullopt;
} }
@ -282,21 +272,21 @@ void Host::OnPerformanceCountersUpdated()
void Host::OnGameChanged(const std::string& disc_path, const std::string& game_serial, const std::string& game_name) void Host::OnGameChanged(const std::string& disc_path, const std::string& game_serial, const std::string& game_name)
{ {
Log_InfoPrintf("Disc Path: %s", disc_path.c_str()); Log_InfoFmt("Disc Path: {}", disc_path);
Log_InfoPrintf("Game Serial: %s", game_serial.c_str()); Log_InfoFmt("Game Serial: {}", game_serial);
Log_InfoPrintf("Game Name: %s", game_name.c_str()); Log_InfoFmt("Game Name: {}", game_name);
if (!s_dump_base_directory.empty()) if (!s_dump_base_directory.empty())
{ {
s_dump_game_directory = Path::Combine(s_dump_base_directory, game_name); s_dump_game_directory = Path::Combine(s_dump_base_directory, game_name);
if (!FileSystem::DirectoryExists(s_dump_game_directory.c_str())) if (!FileSystem::DirectoryExists(s_dump_game_directory.c_str()))
{ {
Log_InfoPrintf("Creating directory '%s'...", s_dump_game_directory.c_str()); Log_InfoFmt("Creating directory '{}'...", s_dump_game_directory);
if (!FileSystem::CreateDirectory(s_dump_game_directory.c_str(), false)) if (!FileSystem::CreateDirectory(s_dump_game_directory.c_str(), false))
Panic("Failed to create dump directory."); Panic("Failed to create dump directory.");
} }
Log_InfoPrintf("Dumping frames to '%s'...", s_dump_game_directory.c_str()); Log_InfoFmt("Dumping frames to '{}'...", s_dump_game_directory);
} }
} }
@ -550,7 +540,7 @@ bool RegTestHost::ParseCommandLineParameters(int argc, char* argv[], std::option
s_dump_base_directory = argv[++i]; s_dump_base_directory = argv[++i];
if (s_dump_base_directory.empty()) if (s_dump_base_directory.empty())
{ {
Log_ErrorPrintf("Invalid dump directory specified."); Log_ErrorPrint("Invalid dump directory specified.");
return false; return false;
} }
@ -561,7 +551,7 @@ bool RegTestHost::ParseCommandLineParameters(int argc, char* argv[], std::option
s_frame_dump_interval = StringUtil::FromChars<u32>(argv[++i]).value_or(0); s_frame_dump_interval = StringUtil::FromChars<u32>(argv[++i]).value_or(0);
if (s_frames_to_run <= 0) if (s_frames_to_run <= 0)
{ {
Log_ErrorPrintf("Invalid dump interval specified: %s", argv[i]); Log_ErrorFmt("Invalid dump interval specified: {}", argv[i]);
return false; return false;
} }
@ -572,7 +562,7 @@ bool RegTestHost::ParseCommandLineParameters(int argc, char* argv[], std::option
s_frames_to_run = StringUtil::FromChars<u32>(argv[++i]).value_or(0); s_frames_to_run = StringUtil::FromChars<u32>(argv[++i]).value_or(0);
if (s_frames_to_run == 0) if (s_frames_to_run == 0)
{ {
Log_ErrorPrintf("Invalid frame count specified: %s", argv[i]); Log_ErrorFmt("Invalid frame count specified: {}", argv[i]);
return false; return false;
} }
@ -583,7 +573,7 @@ bool RegTestHost::ParseCommandLineParameters(int argc, char* argv[], std::option
std::optional<LOGLEVEL> level = Settings::ParseLogLevelName(argv[++i]); std::optional<LOGLEVEL> level = Settings::ParseLogLevelName(argv[++i]);
if (!level.has_value()) if (!level.has_value())
{ {
Log_ErrorPrintf("Invalid log level specified."); Log_ErrorPrint("Invalid log level specified.");
return false; return false;
} }
@ -596,7 +586,7 @@ bool RegTestHost::ParseCommandLineParameters(int argc, char* argv[], std::option
std::optional<GPURenderer> renderer = Settings::ParseRendererName(argv[++i]); std::optional<GPURenderer> renderer = Settings::ParseRendererName(argv[++i]);
if (!renderer.has_value()) if (!renderer.has_value())
{ {
Log_ErrorPrintf("Invalid renderer specified."); Log_ErrorPrint("Invalid renderer specified.");
return false; return false;
} }
@ -650,7 +640,7 @@ bool RegTestHost::ParseCommandLineParameters(int argc, char* argv[], std::option
} }
else if (argv[i][0] == '-') else if (argv[i][0] == '-')
{ {
Log_ErrorPrintf("Unknown parameter: '%s'", argv[i]); Log_ErrorFmt("Unknown parameter: '{}'", argv[i]);
return false; return false;
} }
@ -702,7 +692,7 @@ int main(int argc, char* argv[])
Error error; Error error;
int result = -1; int result = -1;
Log_InfoPrintf("Trying to boot '%s'...", autoboot->filename.c_str()); Log_InfoFmt("Trying to boot '{}'...", autoboot->filename);
if (!System::BootSystem(std::move(autoboot.value()), &error)) if (!System::BootSystem(std::move(autoboot.value()), &error))
{ {
Log_ErrorFmt("Failed to boot system: {}", error.GetDescription()); Log_ErrorFmt("Failed to boot system: {}", error.GetDescription());
@ -717,13 +707,13 @@ int main(int argc, char* argv[])
goto cleanup; goto cleanup;
} }
Log_InfoPrintf("Dumping every %dth frame to '%s'.", s_frame_dump_interval, s_dump_base_directory.c_str()); Log_InfoFmt("Dumping every {}th frame to '{}'.", s_frame_dump_interval, s_dump_base_directory);
} }
Log_InfoPrintf("Running for %d frames...", s_frames_to_run); Log_InfoFmt("Running for %d frames...", s_frames_to_run);
System::Execute(); System::Execute();
Log_InfoPrintf("Exiting with success."); Log_InfoPrint("Exiting with success.");
result = 0; result = 0;
cleanup: cleanup:

View File

@ -290,7 +290,7 @@ void AudioStream::ReadFrames(SampleType* samples, u32 num_frames)
else else
{ {
m_filling = false; m_filling = false;
Log_VerbosePrintf("Underrun compensation done (%d frames buffered)", toFill); Log_VerboseFmt("Underrun compensation done ({} frames buffered)", toFill);
} }
} }
@ -441,7 +441,7 @@ void AudioStream::InternalWriteFrames(s16* data, u32 num_frames)
} }
else else
{ {
Log_DebugPrintf("Buffer overrun, chunk dropped"); Log_DebugPrint("Buffer overrun, chunk dropped");
return; return;
} }
} }
@ -891,7 +891,7 @@ void AudioStream::UpdateStretchTempo()
// state vars // state vars
if (m_stretch_reset >= STRETCH_RESET_THRESHOLD) if (m_stretch_reset >= STRETCH_RESET_THRESHOLD)
{ {
Log_VerbosePrintf("___ Stretcher is being reset."); Log_VerbosePrint("___ Stretcher is being reset.");
m_stretch_inactive = false; m_stretch_inactive = false;
m_stretch_ok_count = 0; m_stretch_ok_count = 0;
m_dynamic_target_usage = base_target_usage; m_dynamic_target_usage = base_target_usage;
@ -928,13 +928,13 @@ void AudioStream::UpdateStretchTempo()
if (m_stretch_ok_count >= INACTIVE_MIN_OK_COUNT) if (m_stretch_ok_count >= INACTIVE_MIN_OK_COUNT)
{ {
Log_VerbosePrintf("=== Stretcher is now inactive."); Log_VerbosePrint("=== Stretcher is now inactive.");
m_stretch_inactive = true; m_stretch_inactive = true;
} }
} }
else if (!IsInRange(tempo, 1.0f / INACTIVE_BAD_FACTOR, INACTIVE_BAD_FACTOR)) else if (!IsInRange(tempo, 1.0f / INACTIVE_BAD_FACTOR, INACTIVE_BAD_FACTOR))
{ {
Log_VerbosePrintf("~~~ Stretcher is now active @ tempo %f.", tempo); Log_VerboseFmt("~~~ Stretcher is now active @ tempo {}.", tempo);
m_stretch_inactive = false; m_stretch_inactive = false;
m_stretch_ok_count = 0; m_stretch_ok_count = 0;
} }
@ -951,9 +951,9 @@ void AudioStream::UpdateStretchTempo()
if (Common::Timer::ConvertValueToSeconds(now - last_log_time) > 1.0f) if (Common::Timer::ConvertValueToSeconds(now - last_log_time) > 1.0f)
{ {
Log_VerbosePrintf("buffers: %4u ms (%3.0f%%), tempo: %f, comp: %2.3f, iters: %d, reset:%d", Log_VerboseFmt("buffers: {:4d} ms ({:3.0f}%), tempo: {}, comp: {:2.3f}, iters: {}, reset:{}",
(ibuffer_usage * 1000u) / m_sample_rate, 100.0f * buffer_usage / base_target_usage, tempo, (ibuffer_usage * 1000u) / m_sample_rate, 100.0f * buffer_usage / base_target_usage, tempo,
m_dynamic_target_usage / base_target_usage, iterations, m_stretch_reset); m_dynamic_target_usage / base_target_usage, iterations, m_stretch_reset);
last_log_time = now; last_log_time = now;
iterations = 0; iterations = 0;

View File

@ -302,7 +302,7 @@ bool CDImage::ReadRawSector(void* buffer, SubChannelQ* subq)
// TODO: This is where we'd reconstruct the header for other mode tracks. // TODO: This is where we'd reconstruct the header for other mode tracks.
if (!ReadSectorFromIndex(buffer, *m_current_index, m_position_in_index)) if (!ReadSectorFromIndex(buffer, *m_current_index, m_position_in_index))
{ {
Log_ErrorPrintf("Read of LBA %u failed", m_position_on_disc); Log_ErrorFmt("Read of LBA {} failed", m_position_on_disc);
Seek(m_position_on_disc); Seek(m_position_on_disc);
return false; return false;
} }
@ -324,7 +324,7 @@ bool CDImage::ReadRawSector(void* buffer, SubChannelQ* subq)
if (subq && !ReadSubChannelQ(subq, *m_current_index, m_position_in_index)) if (subq && !ReadSubChannelQ(subq, *m_current_index, m_position_in_index))
{ {
Log_ErrorPrintf("Subchannel read of LBA %u failed", m_position_on_disc); Log_ErrorFmt("Subchannel read of LBA {} failed", m_position_on_disc);
Seek(m_position_on_disc); Seek(m_position_on_disc);
return false; return false;
} }

View File

@ -110,15 +110,15 @@ bool CDImageCueSheet::OpenAndParse(const char* filename, Error* error)
track_fp = FileSystem::OpenCFile(alternative_filename.c_str(), "rb"); track_fp = FileSystem::OpenCFile(alternative_filename.c_str(), "rb");
if (track_fp) if (track_fp)
{ {
Log_WarningPrintf("Your cue sheet references an invalid file '%s', but this was found at '%s' instead.", Log_WarningFmt("Your cue sheet references an invalid file '{}', but this was found at '{}' instead.",
track_filename.c_str(), alternative_filename.c_str()); track_filename, alternative_filename);
} }
} }
if (!track_fp) if (!track_fp)
{ {
Log_ErrorPrintf("Failed to open track filename '%s' (from '%s' and '%s'): %s", track_full_filename.c_str(), Log_ErrorFmt("Failed to open track filename '{}' (from '{}' and '{}'): {}", track_full_filename, track_filename,
track_filename.c_str(), filename, track_error.GetDescription().c_str()); filename, track_error.GetDescription());
Error::SetStringFmt(error, "Failed to open track filename '{}' (from '{}' and '{}'): {}", track_full_filename, Error::SetStringFmt(error, "Failed to open track filename '{}' (from '{}' and '{}'): {}", track_full_filename,
track_filename, Path::GetFileName(filename), track_error.GetDescription()); track_filename, Path::GetFileName(filename), track_error.GetDescription());
return false; return false;
@ -149,8 +149,8 @@ bool CDImageCueSheet::OpenAndParse(const char* filename, Error* error)
file_size /= track_sector_size; file_size /= track_sector_size;
if (track_start >= file_size) if (track_start >= file_size)
{ {
Log_ErrorPrintf("Failed to open track %u in '%s': track start is out of range (%u vs %" PRIu64 ")", track_num, Log_ErrorFmt("Failed to open track {} in '{}': track start is out of range ({} vs {})", track_num, filename,
filename, track_start, file_size); track_start, file_size);
Error::SetStringFmt(error, "Failed to open track {} in '{}': track start is out of range ({} vs {}))", Error::SetStringFmt(error, "Failed to open track {} in '{}': track start is out of range ({} vs {}))",
track_num, Path::GetFileName(filename), track_start, file_size); track_num, Path::GetFileName(filename), track_start, file_size);
return false; return false;
@ -285,7 +285,7 @@ bool CDImageCueSheet::OpenAndParse(const char* filename, Error* error)
if (m_tracks.empty()) if (m_tracks.empty())
{ {
Log_ErrorPrintf("File '%s' contains no tracks", filename); Log_ErrorFmt("File '{}' contains no tracks", filename);
Error::SetStringFmt(error, "File '{}' contains no tracks", Path::GetFileName(filename)); Error::SetStringFmt(error, "File '{}' contains no tracks", Path::GetFileName(filename));
return false; return false;
} }

View File

@ -290,7 +290,7 @@ bool CDImageDeviceWin32::Open(const char* filename, Error* error)
&bytes_returned, nullptr) || &bytes_returned, nullptr) ||
toc.LastTrack < toc.FirstTrack) toc.LastTrack < toc.FirstTrack)
{ {
Log_ErrorPrintf("DeviceIoCtl(IOCTL_CDROM_READ_TOC_EX) failed: %08X", GetLastError()); Log_ErrorFmt("DeviceIoCtl(IOCTL_CDROM_READ_TOC_EX) failed: {:08X}", GetLastError());
if (error) if (error)
error->SetWin32(GetLastError()); error->SetWin32(GetLastError());
@ -299,7 +299,7 @@ bool CDImageDeviceWin32::Open(const char* filename, Error* error)
DWORD last_track_address = 0; DWORD last_track_address = 0;
LBA disc_lba = 0; LBA disc_lba = 0;
Log_DevPrintf("FirstTrack=%u, LastTrack=%u", toc.FirstTrack, toc.LastTrack); Log_DevFmt("FirstTrack={}, LastTrack={}", toc.FirstTrack, toc.LastTrack);
const u32 num_tracks_to_check = (toc.LastTrack - toc.FirstTrack) + 1 + 1; const u32 num_tracks_to_check = (toc.LastTrack - toc.FirstTrack) + 1 + 1;
for (u32 track_index = 0; track_index < num_tracks_to_check; track_index++) for (u32 track_index = 0; track_index < num_tracks_to_check; track_index++)
@ -307,14 +307,14 @@ bool CDImageDeviceWin32::Open(const char* filename, Error* error)
const TRACK_DATA& td = toc.TrackData[track_index]; const TRACK_DATA& td = toc.TrackData[track_index];
const u8 track_num = td.TrackNumber; const u8 track_num = td.TrackNumber;
const DWORD track_address = BEToU32(td.Address); const DWORD track_address = BEToU32(td.Address);
Log_DevPrintf(" [%u]: Num=%02X, Address=%u", track_index, track_num, track_address); Log_DevFmt(" [{}]: Num={:02X}, Address={}", track_index, track_num, track_address);
// fill in the previous track's length // fill in the previous track's length
if (!m_tracks.empty()) if (!m_tracks.empty())
{ {
if (track_num < m_tracks.back().track_number) if (track_num < m_tracks.back().track_number)
{ {
Log_ErrorPrintf("Invalid TOC, track %u less than %u", track_num, m_tracks.back().track_number); Log_ErrorFmt("Invalid TOC, track {} less than {}", track_num, m_tracks.back().track_number);
return false; return false;
} }
@ -382,32 +382,29 @@ bool CDImageDeviceWin32::Open(const char* filename, Error* error)
if (m_tracks.empty()) if (m_tracks.empty())
{ {
Log_ErrorPrintf("File '%s' contains no tracks", filename); Log_ErrorFmt("File '{}' contains no tracks", filename);
Error::SetString(error, fmt::format("File '{}' contains no tracks", filename)); Error::SetString(error, fmt::format("File '{}' contains no tracks", filename));
return false; return false;
} }
m_lba_count = disc_lba; m_lba_count = disc_lba;
Log_DevPrintf("%u tracks, %u indices, %u lbas", static_cast<u32>(m_tracks.size()), static_cast<u32>(m_indices.size()), Log_DevFmt("{} tracks, {} indices, {} lbas", m_tracks.size(), m_indices.size(), m_lba_count);
static_cast<u32>(m_lba_count));
for (u32 i = 0; i < m_tracks.size(); i++) for (u32 i = 0; i < m_tracks.size(); i++)
{ {
Log_DevPrintf(" Track %u: Start %u, length %u, mode %u, control 0x%02X", static_cast<u32>(m_tracks[i].track_number), Log_DevFmt(" Track {}: Start {}, length {}, mode {}, control 0x{:02X}", m_tracks[i].track_number,
static_cast<u32>(m_tracks[i].start_lba), static_cast<u32>(m_tracks[i].length), m_tracks[i].start_lba, m_tracks[i].length, static_cast<u8>(m_tracks[i].mode), m_tracks[i].control.bits);
static_cast<u32>(m_tracks[i].mode), static_cast<u32>(m_tracks[i].control.bits));
} }
for (u32 i = 0; i < m_indices.size(); i++) for (u32 i = 0; i < m_indices.size(); i++)
{ {
Log_DevPrintf(" Index %u: Track %u, Index %u, Start %u, length %u, file sector size %u, file offset %" PRIu64, i, Log_DevFmt(" Index {}: Track {}, Index [], Start {}, length {}, file sector size {}, file offset {}", i,
static_cast<u32>(m_indices[i].track_number), static_cast<u32>(m_indices[i].index_number), m_indices[i].track_number, m_indices[i].index_number, m_indices[i].start_lba_on_disc,
static_cast<u32>(m_indices[i].start_lba_on_disc), static_cast<u32>(m_indices[i].length), m_indices[i].length, m_indices[i].file_sector_size, m_indices[i].file_offset);
static_cast<u32>(m_indices[i].file_sector_size), m_indices[i].file_offset);
} }
if (!DetermineReadMode(try_sptd)) if (!DetermineReadMode(try_sptd))
{ {
Log_ErrorPrintf("Could not determine read mode"); Log_ErrorPrint("Could not determine read mode");
Error::SetString(error, "Could not determine read mode"); Error::SetString(error, "Could not determine read mode");
return false; return false;
} }
@ -795,7 +792,7 @@ bool CDImageDeviceLinux::Open(const char* filename, Error* error)
{ {
if (track_num < m_tracks.back().track_number) if (track_num < m_tracks.back().track_number)
{ {
Log_ErrorPrintf("Invalid TOC, track %u less than %u", track_num, m_tracks.back().track_number); Log_ErrorFmt("Invalid TOC, track {} less than {}", track_num, m_tracks.back().track_number);
return false; return false;
} }
@ -858,7 +855,7 @@ bool CDImageDeviceLinux::Open(const char* filename, Error* error)
if (m_tracks.empty()) if (m_tracks.empty())
{ {
Log_ErrorPrintf("File '%s' contains no tracks", filename); Log_ErrorFmt("File '{}' contains no tracks", filename);
Error::SetString(error, fmt::format("File '{}' contains no tracks", filename)); Error::SetString(error, fmt::format("File '{}' contains no tracks", filename));
return false; return false;
} }
@ -887,20 +884,17 @@ bool CDImageDeviceLinux::Open(const char* filename, Error* error)
m_lba_count = disc_lba; m_lba_count = disc_lba;
Log_DevPrintf("%u tracks, %u indices, %u lbas", static_cast<u32>(m_tracks.size()), static_cast<u32>(m_indices.size()), Log_DevFmt("{} tracks, {} indices, {} lbas", m_tracks.size(), m_indices.size(), m_lba_count);
static_cast<u32>(m_lba_count));
for (u32 i = 0; i < m_tracks.size(); i++) for (u32 i = 0; i < m_tracks.size(); i++)
{ {
Log_DevPrintf(" Track %u: Start %u, length %u, mode %u, control 0x%02X", static_cast<u32>(m_tracks[i].track_number), Log_DevFmt(" Track {}: Start {}, length {}, mode {}, control 0x{:02X}", m_tracks[i].track_number,
static_cast<u32>(m_tracks[i].start_lba), static_cast<u32>(m_tracks[i].length), m_tracks[i].start_lba, m_tracks[i].length, static_cast<u8>(m_tracks[i].mode), m_tracks[i].control.bits);
static_cast<u32>(m_tracks[i].mode), static_cast<u32>(m_tracks[i].control.bits));
} }
for (u32 i = 0; i < m_indices.size(); i++) for (u32 i = 0; i < m_indices.size(); i++)
{ {
Log_DevPrintf(" Index %u: Track %u, Index %u, Start %u, length %u, file sector size %u, file offset %" PRIu64, i, Log_DevFmt(" Index {}: Track {}, Index [], Start {}, length {}, file sector size {}, file offset {}", i,
static_cast<u32>(m_indices[i].track_number), static_cast<u32>(m_indices[i].index_number), m_indices[i].track_number, m_indices[i].index_number, m_indices[i].start_lba_on_disc,
static_cast<u32>(m_indices[i].start_lba_on_disc), static_cast<u32>(m_indices[i].length), m_indices[i].length, m_indices[i].file_sector_size, m_indices[i].file_offset);
static_cast<u32>(m_indices[i].file_sector_size), m_indices[i].file_offset);
} }
if (!DetermineReadMode(error)) if (!DetermineReadMode(error))
@ -1380,7 +1374,7 @@ bool CDImageDeviceMacOS::Open(const char* filename, Error* error)
if (m_tracks.empty()) if (m_tracks.empty())
{ {
Log_ErrorPrintf("File '%s' contains no tracks", filename); Log_ErrorFmt("File '{}' contains no tracks", filename);
Error::SetString(error, fmt::format("File '{}' contains no tracks", filename)); Error::SetString(error, fmt::format("File '{}' contains no tracks", filename));
return false; return false;
} }
@ -1398,20 +1392,17 @@ bool CDImageDeviceMacOS::Open(const char* filename, Error* error)
m_lba_count = disc_lba; m_lba_count = disc_lba;
Log_DevPrintf("%u tracks, %u indices, %u lbas", static_cast<u32>(m_tracks.size()), static_cast<u32>(m_indices.size()), Log_DevFmt("{} tracks, {} indices, {} lbas", m_tracks.size(), m_indices.size(), m_lba_count);
static_cast<u32>(m_lba_count));
for (u32 i = 0; i < m_tracks.size(); i++) for (u32 i = 0; i < m_tracks.size(); i++)
{ {
Log_DevPrintf(" Track %u: Start %u, length %u, mode %u, control 0x%02X", static_cast<u32>(m_tracks[i].track_number), Log_DevFmt(" Track {}: Start {}, length {}, mode {}, control 0x{:02X}", m_tracks[i].track_number,
static_cast<u32>(m_tracks[i].start_lba), static_cast<u32>(m_tracks[i].length), m_tracks[i].start_lba, m_tracks[i].length, static_cast<u8>(m_tracks[i].mode), m_tracks[i].control.bits);
static_cast<u32>(m_tracks[i].mode), static_cast<u32>(m_tracks[i].control.bits));
} }
for (u32 i = 0; i < m_indices.size(); i++) for (u32 i = 0; i < m_indices.size(); i++)
{ {
Log_DevPrintf(" Index %u: Track %u, Index %u, Start %u, length %u, file sector size %u, file offset %" PRIu64, i, Log_DevFmt(" Index {}: Track {}, Index [], Start {}, length {}, file sector size {}, file offset {}", i,
static_cast<u32>(m_indices[i].track_number), static_cast<u32>(m_indices[i].index_number), m_indices[i].track_number, m_indices[i].index_number, m_indices[i].start_lba_on_disc,
static_cast<u32>(m_indices[i].start_lba_on_disc), static_cast<u32>(m_indices[i].length), m_indices[i].length, m_indices[i].file_sector_size, m_indices[i].file_offset);
static_cast<u32>(m_indices[i].file_sector_size), m_indices[i].file_offset);
} }
if (!DetermineReadMode(error)) if (!DetermineReadMode(error))

View File

@ -246,7 +246,7 @@ bool CDImageEcm::Open(const char* filename, Error* error)
if (FileSystem::FSeek64(m_fp, 0, SEEK_END) != 0 || (file_size = FileSystem::FTell64(m_fp)) <= 0 || if (FileSystem::FSeek64(m_fp, 0, SEEK_END) != 0 || (file_size = FileSystem::FTell64(m_fp)) <= 0 ||
FileSystem::FSeek64(m_fp, 0, SEEK_SET) != 0) FileSystem::FSeek64(m_fp, 0, SEEK_SET) != 0)
{ {
Log_ErrorPrintf("Get file size failed: errno %d", errno); Log_ErrorFmt("Get file size failed: errno {}", errno);
if (error) if (error)
error->SetErrno(errno); error->SetErrno(errno);
@ -257,7 +257,7 @@ bool CDImageEcm::Open(const char* filename, Error* error)
if (std::fread(header, sizeof(header), 1, m_fp) != 1 || header[0] != 'E' || header[1] != 'C' || header[2] != 'M' || if (std::fread(header, sizeof(header), 1, m_fp) != 1 || header[0] != 'E' || header[1] != 'C' || header[2] != 'M' ||
header[3] != 0) header[3] != 0)
{ {
Log_ErrorPrintf("Failed to read/invalid header"); Log_ErrorPrint("Failed to read/invalid header");
Error::SetStringView(error, "Failed to read/invalid header"); Error::SetStringView(error, "Failed to read/invalid header");
return false; return false;
} }
@ -271,7 +271,7 @@ bool CDImageEcm::Open(const char* filename, Error* error)
int bits = std::fgetc(m_fp); int bits = std::fgetc(m_fp);
if (bits == EOF) if (bits == EOF)
{ {
Log_ErrorPrintf("Unexpected EOF after %zu chunks", m_data_map.size()); Log_ErrorFmt("Unexpected EOF after {} chunks", m_data_map.size());
Error::SetStringFmt(error, "Unexpected EOF after {} chunks", m_data_map.size()); Error::SetStringFmt(error, "Unexpected EOF after {} chunks", m_data_map.size());
return false; return false;
} }
@ -285,7 +285,7 @@ bool CDImageEcm::Open(const char* filename, Error* error)
bits = std::fgetc(m_fp); bits = std::fgetc(m_fp);
if (bits == EOF) if (bits == EOF)
{ {
Log_ErrorPrintf("Unexpected EOF after %zu chunks", m_data_map.size()); Log_ErrorFmt("Unexpected EOF after {} chunks", m_data_map.size());
Error::SetStringFmt(error, "Unexpected EOF after {} chunks", m_data_map.size()); Error::SetStringFmt(error, "Unexpected EOF after {} chunks", m_data_map.size());
return false; return false;
} }
@ -303,7 +303,7 @@ bool CDImageEcm::Open(const char* filename, Error* error)
if (count >= 0x80000000u) if (count >= 0x80000000u)
{ {
Log_ErrorPrintf("Corrupted header after %zu chunks", m_data_map.size()); Log_ErrorFmt("Corrupted header after {} chunks", m_data_map.size());
Error::SetStringFmt(error, "Corrupted header after {} chunks", m_data_map.size()); Error::SetStringFmt(error, "Corrupted header after {} chunks", m_data_map.size());
return false; return false;
} }
@ -320,7 +320,7 @@ bool CDImageEcm::Open(const char* filename, Error* error)
if (static_cast<s64>(file_offset) > file_size) if (static_cast<s64>(file_offset) > file_size)
{ {
Log_ErrorPrintf("Out of file bounds after %zu chunks", m_data_map.size()); Log_ErrorFmt("Out of file bounds after {} chunks", m_data_map.size());
Error::SetStringFmt(error, "Out of file bounds after {} chunks", m_data_map.size()); Error::SetStringFmt(error, "Out of file bounds after {} chunks", m_data_map.size());
} }
} }
@ -337,7 +337,7 @@ bool CDImageEcm::Open(const char* filename, Error* error)
if (static_cast<s64>(file_offset) > file_size) if (static_cast<s64>(file_offset) > file_size)
{ {
Log_ErrorPrintf("Out of file bounds after %zu chunks", m_data_map.size()); Log_ErrorFmt("Out of file bounds after {} chunks", m_data_map.size());
Error::SetStringFmt(error, "Out of file bounds after {} chunks", m_data_map.size()); Error::SetStringFmt(error, "Out of file bounds after {} chunks", m_data_map.size());
} }
} }
@ -345,7 +345,7 @@ bool CDImageEcm::Open(const char* filename, Error* error)
if (std::fseek(m_fp, file_offset, SEEK_SET) != 0) if (std::fseek(m_fp, file_offset, SEEK_SET) != 0)
{ {
Log_ErrorPrintf("Failed to seek to offset %u after %zu chunks", file_offset, m_data_map.size()); Log_ErrorFmt("Failed to seek to offset {} after {} chunks", file_offset, m_data_map.size());
Error::SetStringFmt(error, "Failed to seek to offset {} after {} chunks", file_offset, m_data_map.size()); Error::SetStringFmt(error, "Failed to seek to offset {} after {} chunks", file_offset, m_data_map.size());
return false; return false;
} }
@ -353,14 +353,14 @@ bool CDImageEcm::Open(const char* filename, Error* error)
if (m_data_map.empty()) if (m_data_map.empty())
{ {
Log_ErrorPrintf("No data in image '%s'", filename); Log_ErrorFmt("No data in image '{}'", filename);
Error::SetStringFmt(error, "No data in image '{}'", filename); Error::SetStringFmt(error, "No data in image '{}'", filename);
return false; return false;
} }
m_lba_count = disc_offset / RAW_SECTOR_SIZE; m_lba_count = disc_offset / RAW_SECTOR_SIZE;
if ((disc_offset % RAW_SECTOR_SIZE) != 0) if ((disc_offset % RAW_SECTOR_SIZE) != 0)
Log_WarningPrintf("ECM image is misaligned with offset %u", disc_offset); Log_WarningFmt("ECM image is misaligned with offset {}", disc_offset);
if (m_lba_count == 0) if (m_lba_count == 0)
return false; return false;

View File

@ -107,11 +107,11 @@ bool CDImageM3u::Open(const char* path, bool apply_patches, Error* error)
else else
entry.filename = std::move(entry_filename); entry.filename = std::move(entry_filename);
Log_DevPrintf("Read path from m3u: '%s'", entry.filename.c_str()); Log_DevFmt("Read path from m3u: '{}'", entry.filename);
m_entries.push_back(std::move(entry)); m_entries.push_back(std::move(entry));
} }
Log_InfoPrintf("Loaded %zu paths from m3u '%s'", m_entries.size(), path); Log_InfoFmt("Loaded {} paths from m3u '{}'", m_entries.size(), path);
return !m_entries.empty() && SwitchSubImage(0, error); return !m_entries.empty() && SwitchSubImage(0, error);
} }
@ -146,7 +146,7 @@ bool CDImageM3u::SwitchSubImage(u32 index, Error* error)
std::unique_ptr<CDImage> new_image = CDImage::Open(entry.filename.c_str(), m_apply_patches, error); std::unique_ptr<CDImage> new_image = CDImage::Open(entry.filename.c_str(), m_apply_patches, error);
if (!new_image) if (!new_image)
{ {
Log_ErrorPrintf("Failed to load subimage %u (%s)", index, entry.filename.c_str()); Log_ErrorFmt("Failed to load subimage {} ({})", index, entry.filename);
return false; return false;
} }

View File

@ -82,7 +82,7 @@ bool CDImageMds::OpenAndParse(const char* filename, Error* error)
std::fclose(mds_fp); std::fclose(mds_fp);
if (!mds_data_opt.has_value() || mds_data_opt->size() < 0x54) if (!mds_data_opt.has_value() || mds_data_opt->size() < 0x54)
{ {
Log_ErrorPrintf("Failed to read mds file '%s'", filename); Log_ErrorFmt("Failed to read mds file '{}'", Path::GetFileName(filename));
Error::SetStringFmt(error, "Failed to read mds file '{}'", filename); Error::SetStringFmt(error, "Failed to read mds file '{}'", filename);
return false; return false;
} }
@ -99,7 +99,7 @@ bool CDImageMds::OpenAndParse(const char* filename, Error* error)
static constexpr char expected_signature[] = "MEDIA DESCRIPTOR"; static constexpr char expected_signature[] = "MEDIA DESCRIPTOR";
if (std::memcmp(&mds[0], expected_signature, sizeof(expected_signature) - 1) != 0) if (std::memcmp(&mds[0], expected_signature, sizeof(expected_signature) - 1) != 0)
{ {
Log_ErrorPrintf("Incorrect signature in '%s'", filename); Log_ErrorFmt("Incorrect signature in '{}'", Path::GetFileName(filename));
Error::SetStringFmt(error, "Incorrect signature in '{}'", Path::GetFileName(filename)); Error::SetStringFmt(error, "Incorrect signature in '{}'", Path::GetFileName(filename));
return false; return false;
} }
@ -108,7 +108,7 @@ bool CDImageMds::OpenAndParse(const char* filename, Error* error)
std::memcpy(&session_offset, &mds[0x50], sizeof(session_offset)); std::memcpy(&session_offset, &mds[0x50], sizeof(session_offset));
if ((session_offset + 24) > mds.size()) if ((session_offset + 24) > mds.size())
{ {
Log_ErrorPrintf("Invalid session offset in '%s'", filename); Log_ErrorFmt("Invalid session offset in '{}'", Path::GetFileName(filename));
Error::SetStringFmt(error, "Invalid session offset in '{}'", Path::GetFileName(filename)); Error::SetStringFmt(error, "Invalid session offset in '{}'", Path::GetFileName(filename));
return false; return false;
} }
@ -119,7 +119,7 @@ bool CDImageMds::OpenAndParse(const char* filename, Error* error)
std::memcpy(&track_offset, &mds[session_offset + 20], sizeof(track_offset)); std::memcpy(&track_offset, &mds[session_offset + 20], sizeof(track_offset));
if (track_count > 99 || track_offset >= mds.size()) if (track_count > 99 || track_offset >= mds.size())
{ {
Log_ErrorPrintf("Invalid track count/block offset %u/%u in '%s'", track_count, track_offset, filename); Log_ErrorFmt("Invalid track count/block offset {}/{} in '{}'", track_count, track_offset, Path::GetFileName(filename));
Error::SetStringFmt(error, "Invalid track count/block offset {}/{} in '{}'", track_count, track_offset, Error::SetStringFmt(error, "Invalid track count/block offset {}/{} in '{}'", track_count, track_offset,
Path::GetFileName(filename)); Path::GetFileName(filename));
return false; return false;
@ -139,7 +139,7 @@ bool CDImageMds::OpenAndParse(const char* filename, Error* error)
{ {
if ((track_offset + sizeof(TrackEntry)) > mds.size()) if ((track_offset + sizeof(TrackEntry)) > mds.size())
{ {
Log_ErrorPrintf("End of file in '%s' at track %u", filename, track_number); Log_ErrorFmt("End of file in '{}' at track {}", Path::GetFileName(filename), track_number);
Error::SetStringFmt(error, "End of file in '{}' at track {}", Path::GetFileName(filename), track_number); Error::SetStringFmt(error, "End of file in '{}' at track {}", Path::GetFileName(filename), track_number);
return false; return false;
} }
@ -150,7 +150,7 @@ bool CDImageMds::OpenAndParse(const char* filename, Error* error)
if (PackedBCDToBinary(track.track_number) != track_number) if (PackedBCDToBinary(track.track_number) != track_number)
{ {
Log_ErrorPrintf("Unexpected track number 0x%02X in track %u", track.track_number, track_number); Log_ErrorFmt("Unexpected track number 0x{:02X} in track {}", track.track_number, track_number);
Error::SetStringFmt(error, "Unexpected track number 0x{:02X} in track {}", track.track_number, track_number); Error::SetStringFmt(error, "Unexpected track number 0x{:02X} in track {}", track.track_number, track_number);
return false; return false;
} }
@ -161,7 +161,7 @@ bool CDImageMds::OpenAndParse(const char* filename, Error* error)
if ((track.extra_offset + sizeof(u32) + sizeof(u32)) > mds.size()) if ((track.extra_offset + sizeof(u32) + sizeof(u32)) > mds.size())
{ {
Log_ErrorPrintf("Invalid extra offset %u in track %u", track.extra_offset, track_number); Log_ErrorFmt("Invalid extra offset {} in track {}", track.extra_offset, track_number);
Error::SetStringFmt(error, "Invalid extra offset {} in track {}", track.extra_offset, track_number); Error::SetStringFmt(error, "Invalid extra offset {} in track {}", track.extra_offset, track_number);
return false; return false;
} }
@ -184,7 +184,7 @@ bool CDImageMds::OpenAndParse(const char* filename, Error* error)
{ {
if (track_pregap > track_start_lba) if (track_pregap > track_start_lba)
{ {
Log_ErrorPrintf("Track pregap %u is too large for start lba %u", track_pregap, track_start_lba); Log_ErrorFmt("Track pregap {} is too large for start lba {}", track_pregap, track_start_lba);
Error::SetStringFmt(error, "Track pregap {} is too large for start lba {}", track_pregap, track_start_lba); Error::SetStringFmt(error, "Track pregap {} is too large for start lba {}", track_pregap, track_start_lba);
return false; return false;
} }
@ -235,7 +235,7 @@ bool CDImageMds::OpenAndParse(const char* filename, Error* error)
if (m_tracks.empty()) if (m_tracks.empty())
{ {
Log_ErrorPrintf("File '%s' contains no tracks", filename); Log_ErrorFmt("File '{}' contains no tracks", Path::GetFileName(filename));
Error::SetStringFmt(error, "File '{}' contains no tracks", Path::GetFileName(filename)); Error::SetStringFmt(error, "File '{}' contains no tracks", Path::GetFileName(filename));
return false; return false;
} }

View File

@ -92,7 +92,7 @@ bool CDImageMemory::CopyImage(CDImage* image, ProgressCallback* progress)
{ {
if (!image->ReadSectorFromIndex(memory_ptr, index, lba)) if (!image->ReadSectorFromIndex(memory_ptr, index, lba))
{ {
Log_ErrorPrintf("Failed to read LBA %u in index %u", lba, i); Log_ErrorFmt("Failed to read LBA {} in index {}", lba, i);
return false; return false;
} }

View File

@ -298,7 +298,7 @@ bool CDImagePBP::LoadSFOTable()
if (FileSystem::FSeek64(m_file, abs_key_offset, SEEK_SET) != 0) if (FileSystem::FSeek64(m_file, abs_key_offset, SEEK_SET) != 0)
{ {
Log_ErrorPrintf("Failed seek to key for SFO table entry %zu", i); Log_ErrorFmt("Failed seek to key for SFO table entry {}", i);
return false; return false;
} }
@ -306,19 +306,19 @@ bool CDImagePBP::LoadSFOTable()
char key_cstr[20] = {}; char key_cstr[20] = {};
if (std::fgets(key_cstr, sizeof(key_cstr), m_file) == nullptr) if (std::fgets(key_cstr, sizeof(key_cstr), m_file) == nullptr)
{ {
Log_ErrorPrintf("Failed to read key string for SFO table entry %zu", i); Log_ErrorFmt("Failed to read key string for SFO table entry {}", i);
return false; return false;
} }
if (FileSystem::FSeek64(m_file, abs_data_offset, SEEK_SET) != 0) if (FileSystem::FSeek64(m_file, abs_data_offset, SEEK_SET) != 0)
{ {
Log_ErrorPrintf("Failed seek to data for SFO table entry %zu", i); Log_ErrorFmt("Failed seek to data for SFO table entry {}", i);
return false; return false;
} }
if (m_sfo_index_table[i].data_type == 0x0004) // "special mode" UTF-8 (not null terminated) if (m_sfo_index_table[i].data_type == 0x0004) // "special mode" UTF-8 (not null terminated)
{ {
Log_ErrorPrintf("Unhandled special mode UTF-8 type found in SFO table for entry %zu", i); Log_ErrorFmt("Unhandled special mode UTF-8 type found in SFO table for entry {}", i);
return false; return false;
} }
else if (m_sfo_index_table[i].data_type == 0x0204) // null-terminated UTF-8 character string else if (m_sfo_index_table[i].data_type == 0x0204) // null-terminated UTF-8 character string
@ -326,7 +326,7 @@ bool CDImagePBP::LoadSFOTable()
std::vector<char> data_cstr(m_sfo_index_table[i].data_size); std::vector<char> data_cstr(m_sfo_index_table[i].data_size);
if (fgets(data_cstr.data(), static_cast<int>(data_cstr.size() * sizeof(char)), m_file) == nullptr) if (fgets(data_cstr.data(), static_cast<int>(data_cstr.size() * sizeof(char)), m_file) == nullptr)
{ {
Log_ErrorPrintf("Failed to read data string for SFO table entry %zu", i); Log_ErrorFmt("Failed to read data string for SFO table entry {}", i);
return false; return false;
} }
@ -335,9 +335,9 @@ bool CDImagePBP::LoadSFOTable()
else if (m_sfo_index_table[i].data_type == 0x0404) // uint32_t else if (m_sfo_index_table[i].data_type == 0x0404) // uint32_t
{ {
u32 val; u32 val;
if (fread(&val, sizeof(u32), 1, m_file) != 1) if (std::fread(&val, sizeof(u32), 1, m_file) != 1)
{ {
Log_ErrorPrintf("Failed to read unsigned data value for SFO table entry %zu", i); Log_ErrorFmt("Failed to read unsigned data value for SFO table entry {}", i);
return false; return false;
} }
@ -345,7 +345,7 @@ bool CDImagePBP::LoadSFOTable()
} }
else else
{ {
Log_ErrorPrintf("Unhandled SFO data type 0x%04X found in SFO table for entry %zu", m_sfo_index_table[i].data_type, Log_ErrorFmt("Unhandled SFO data type 0x{:04X} found in SFO table for entry {}", m_sfo_index_table[i].data_type,
i); i);
return false; return false;
} }
@ -476,7 +476,7 @@ bool CDImagePBP::Open(const char* filename, Error* error)
// Ignore encrypted files // Ignore encrypted files
if (disc_table[0] == 0x44475000) // "\0PGD" if (disc_table[0] == 0x44475000) // "\0PGD"
{ {
Log_ErrorPrintf("Encrypted PBP images are not supported, skipping %s", m_filename.c_str()); Log_ErrorFmt("Encrypted PBP images are not supported, skipping %s", m_filename);
Error::SetString(error, "Encrypted PBP images are not supported"); Error::SetString(error, "Encrypted PBP images are not supported");
return false; return false;
} }
@ -492,7 +492,7 @@ bool CDImagePBP::Open(const char* filename, Error* error)
if (m_disc_offsets.size() < 1) if (m_disc_offsets.size() < 1)
{ {
Log_ErrorPrintf("Invalid number of discs (%u) in multi-disc PBP file", static_cast<u32>(m_disc_offsets.size())); Log_ErrorFmt("Invalid number of discs ({}) in multi-disc PBP file", m_disc_offsets.size());
return false; return false;
} }
} }
@ -509,7 +509,7 @@ bool CDImagePBP::OpenDisc(u32 index, Error* error)
{ {
if (index >= m_disc_offsets.size()) if (index >= m_disc_offsets.size())
{ {
Log_ErrorPrintf("File does not contain disc %u", index + 1); Log_ErrorFmt("File does not contain disc {}", index + 1);
Error::SetString(error, fmt::format("File does not contain disc {}", index + 1)); Error::SetString(error, fmt::format("File does not contain disc {}", index + 1));
return false; return false;
} }
@ -545,7 +545,7 @@ bool CDImagePBP::OpenDisc(u32 index, Error* error)
if (pgd_magic == 0x44475000) // "\0PGD" if (pgd_magic == 0x44475000) // "\0PGD"
{ {
Log_ErrorPrintf("Encrypted PBP images are not supported, skipping %s", m_filename.c_str()); Log_ErrorFmt("Encrypted PBP images are not supported, skipping {}", m_filename);
Error::SetString(error, "Encrypted PBP images are not supported"); Error::SetString(error, "Encrypted PBP images are not supported");
return false; return false;
} }
@ -623,7 +623,7 @@ bool CDImagePBP::OpenDisc(u32 index, Error* error)
const TOCEntry& t = m_toc[static_cast<size_t>(curr_track) + 2]; const TOCEntry& t = m_toc[static_cast<size_t>(curr_track) + 2];
const u8 track_num = PackedBCDToBinary(t.point); const u8 track_num = PackedBCDToBinary(t.point);
if (track_num != curr_track) if (track_num != curr_track)
Log_WarningPrintf("Mismatched TOC track number, expected %u but got %u", static_cast<u32>(curr_track), track_num); Log_WarningFmt("Mismatched TOC track number, expected {} but got {}", curr_track, track_num);
const bool is_audio_track = t.type == 0x01; const bool is_audio_track = t.type == 0x01;
const bool is_first_track = curr_track == 1; const bool is_first_track = curr_track == 1;
@ -643,14 +643,14 @@ bool CDImagePBP::OpenDisc(u32 index, Error* error)
{ {
if (!is_first_track || is_audio_track) if (!is_first_track || is_audio_track)
{ {
Log_ErrorPrintf("Invalid TOC entry at index %u, user data (%u) should not start before pregap (%u)", Log_ErrorFmt("Invalid TOC entry at index {}, user data ({}) should not start before pregap ({})", curr_track,
static_cast<u32>(curr_track), userdata_start, pregap_start); userdata_start, pregap_start);
return false; return false;
} }
Log_WarningPrintf( Log_WarningFmt(
"Invalid TOC entry at index %u, user data (%u) should not start before pregap (%u), assuming not in file.", "Invalid TOC entry at index {}, user data ({}) should not start before pregap ({}), assuming not in file.",
static_cast<u32>(curr_track), userdata_start, pregap_start); curr_track, userdata_start, pregap_start);
pregap_start = 0; pregap_start = 0;
pregap_frames = userdata_start; pregap_frames = userdata_start;
pregap_sector_size = 0; pregap_sector_size = 0;
@ -701,8 +701,7 @@ bool CDImagePBP::OpenDisc(u32 index, Error* error)
{ {
if (userdata_start >= m_lba_count) if (userdata_start >= m_lba_count)
{ {
Log_ErrorPrintf("Last user data index on disc for TOC entry %u should not be 0 or less in length", Log_ErrorFmt("Last user data index on disc for TOC entry {} should not be 0 or less in length", curr_track);
static_cast<u32>(curr_track));
return false; return false;
} }
userdata_index.length = m_lba_count - userdata_start; userdata_index.length = m_lba_count - userdata_start;
@ -716,7 +715,7 @@ bool CDImagePBP::OpenDisc(u32 index, Error* error)
if (next_track_num != curr_track + 1 || next_track_start < userdata_start) if (next_track_num != curr_track + 1 || next_track_start < userdata_start)
{ {
Log_ErrorPrintf("Unable to calculate user data index length for TOC entry %u", static_cast<u32>(curr_track)); Log_ErrorFmt("Unable to calculate user data index length for TOC entry {}", curr_track);
return false; return false;
} }
@ -809,9 +808,9 @@ bool CDImagePBP::DecompressBlock(const BlockInfo& block_info)
return false; return false;
int err = inflate(&m_inflate_stream, Z_FINISH); int err = inflate(&m_inflate_stream, Z_FINISH);
if (err != Z_STREAM_END) if (err != Z_STREAM_END) [[unlikely]]
{ {
Log_ErrorPrintf("Inflate error %d", err); Log_ErrorFmt("Inflate error {}", err);
return false; return false;
} }
@ -839,15 +838,15 @@ bool CDImagePBP::ReadSectorFromIndex(void* buffer, const Index& index, LBA lba_i
BlockInfo& bi = m_blockinfo_table[requested_block]; BlockInfo& bi = m_blockinfo_table[requested_block];
if (bi.size == 0) if (bi.size == 0) [[unlikely]]
{ {
Log_ErrorPrintf("Invalid block %u requested", requested_block); Log_ErrorFmt("Invalid block {} requested", requested_block);
return false; return false;
} }
if (m_current_block != requested_block && !DecompressBlock(bi)) if (m_current_block != requested_block && !DecompressBlock(bi)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to decompress block %u", requested_block); Log_ErrorFmt("Failed to decompress block {}", requested_block);
return false; return false;
} }

View File

@ -69,7 +69,7 @@ bool CDImagePPF::Open(const char* filename, std::unique_ptr<CDImage> parent_imag
auto fp = FileSystem::OpenManagedSharedCFile(filename, "rb", FileSystem::FileShareMode::DenyWrite); auto fp = FileSystem::OpenManagedSharedCFile(filename, "rb", FileSystem::FileShareMode::DenyWrite);
if (!fp) if (!fp)
{ {
Log_ErrorPrintf("Failed to open '%s'", filename); Log_ErrorFmt("Failed to open '%s'", filename);
return false; return false;
} }
@ -78,7 +78,7 @@ bool CDImagePPF::Open(const char* filename, std::unique_ptr<CDImage> parent_imag
u32 magic; u32 magic;
if (std::fread(&magic, sizeof(magic), 1, fp.get()) != 1) if (std::fread(&magic, sizeof(magic), 1, fp.get()) != 1)
{ {
Log_ErrorPrintf("Failed to read magic from '%s'", filename); Log_ErrorFmt("Failed to read magic from '%s'", filename);
return false; return false;
} }
@ -100,7 +100,7 @@ bool CDImagePPF::Open(const char* filename, std::unique_ptr<CDImage> parent_imag
else if (magic == 0x31465050) // PPF1 else if (magic == 0x31465050) // PPF1
return ReadV1Patch(fp.get()); return ReadV1Patch(fp.get());
Log_ErrorPrintf("Unknown PPF magic %08X", magic); Log_ErrorFmt("Unknown PPF magic {:08X}", magic);
return false; return false;
} }
@ -109,9 +109,9 @@ u32 CDImagePPF::ReadFileIDDiz(std::FILE* fp, u32 version)
const int lenidx = (version == 2) ? 4 : 2; const int lenidx = (version == 2) ? 4 : 2;
u32 magic; u32 magic;
if (std::fseek(fp, -(lenidx + 4), SEEK_END) != 0 || std::fread(&magic, sizeof(magic), 1, fp) != 1) if (std::fseek(fp, -(lenidx + 4), SEEK_END) != 0 || std::fread(&magic, sizeof(magic), 1, fp) != 1) [[unlikely]]
{ {
Log_WarningPrintf("Failed to read diz magic"); Log_WarningPrint("Failed to read diz magic");
return 0; return 0;
} }
@ -119,44 +119,45 @@ u32 CDImagePPF::ReadFileIDDiz(std::FILE* fp, u32 version)
return 0; return 0;
u32 dlen = 0; u32 dlen = 0;
if (std::fseek(fp, -lenidx, SEEK_END) != 0 || std::fread(&dlen, lenidx, 1, fp) != 1) if (std::fseek(fp, -lenidx, SEEK_END) != 0 || std::fread(&dlen, lenidx, 1, fp) != 1) [[unlikely]]
{ {
Log_WarningPrintf("Failed to read diz length"); Log_WarningPrint("Failed to read diz length");
return 0; return 0;
} }
if (dlen > static_cast<u32>(std::ftell(fp))) if (dlen > static_cast<u32>(std::ftell(fp))) [[unlikely]]
{ {
Log_WarningPrintf("diz length out of range"); Log_WarningPrint("diz length out of range");
return 0; return 0;
} }
std::string fdiz; std::string fdiz;
fdiz.resize(dlen); fdiz.resize(dlen);
if (std::fseek(fp, -(lenidx + 16 + static_cast<int>(dlen)), SEEK_END) != 0 || if (std::fseek(fp, -(lenidx + 16 + static_cast<int>(dlen)), SEEK_END) != 0 ||
std::fread(fdiz.data(), 1, dlen, fp) != dlen) std::fread(fdiz.data(), 1, dlen, fp) != dlen) [[unlikely]]
{ {
Log_WarningPrintf("Failed to read fdiz"); Log_WarningPrint("Failed to read fdiz");
return 0; return 0;
} }
Log_InfoPrintf("File_Id.diz: %s", fdiz.c_str()); Log_InfoFmt("File_Id.diz: %s", fdiz);
return dlen; return dlen;
} }
bool CDImagePPF::ReadV1Patch(std::FILE* fp) bool CDImagePPF::ReadV1Patch(std::FILE* fp)
{ {
char desc[DESC_SIZE + 1] = {}; char desc[DESC_SIZE + 1] = {};
if (std::fseek(fp, 6, SEEK_SET) != 0 || std::fread(desc, sizeof(char), DESC_SIZE, fp) != DESC_SIZE) if (std::fseek(fp, 6, SEEK_SET) != 0 || std::fread(desc, sizeof(char), DESC_SIZE, fp) != DESC_SIZE) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to read description"); Log_ErrorPrint("Failed to read description");
return false; return false;
} }
u32 filelen; u32 filelen;
if (std::fseek(fp, 0, SEEK_END) != 0 || (filelen = static_cast<u32>(std::ftell(fp))) == 0 || filelen < 56) if (std::fseek(fp, 0, SEEK_END) != 0 || (filelen = static_cast<u32>(std::ftell(fp))) == 0 || filelen < 56)
[[unlikely]]
{ {
Log_ErrorPrintf("Invalid ppf file"); Log_ErrorPrint("Invalid ppf file");
return false; return false;
} }
@ -173,53 +174,54 @@ bool CDImagePPF::ReadV1Patch(std::FILE* fp)
u32 offset; u32 offset;
u8 chunk_size; u8 chunk_size;
if (std::fread(&offset, sizeof(offset), 1, fp) != 1 || std::fread(&chunk_size, sizeof(chunk_size), 1, fp) != 1) if (std::fread(&offset, sizeof(offset), 1, fp) != 1 || std::fread(&chunk_size, sizeof(chunk_size), 1, fp) != 1)
[[unlikely]]
{ {
Log_ErrorPrintf("Incomplete ppf"); Log_ErrorPrint("Incomplete ppf");
return false; return false;
} }
temp.resize(chunk_size); temp.resize(chunk_size);
if (std::fread(temp.data(), 1, chunk_size, fp) != chunk_size) if (std::fread(temp.data(), 1, chunk_size, fp) != chunk_size) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to read patch data"); Log_ErrorPrint("Failed to read patch data");
return false; return false;
} }
if (!AddPatch(offset, temp.data(), chunk_size)) if (!AddPatch(offset, temp.data(), chunk_size)) [[unlikely]]
return false; return false;
count -= sizeof(offset) + sizeof(chunk_size) + chunk_size; count -= sizeof(offset) + sizeof(chunk_size) + chunk_size;
} }
Log_InfoPrintf("Loaded %zu replacement sectors from version 1 PPF", m_replacement_map.size()); Log_InfoFmt("Loaded {} replacement sectors from version 1 PPF", m_replacement_map.size());
return true; return true;
} }
bool CDImagePPF::ReadV2Patch(std::FILE* fp) bool CDImagePPF::ReadV2Patch(std::FILE* fp)
{ {
char desc[DESC_SIZE + 1] = {}; char desc[DESC_SIZE + 1] = {};
if (std::fseek(fp, 6, SEEK_SET) != 0 || std::fread(desc, sizeof(char), DESC_SIZE, fp) != DESC_SIZE) if (std::fseek(fp, 6, SEEK_SET) != 0 || std::fread(desc, sizeof(char), DESC_SIZE, fp) != DESC_SIZE) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to read description"); Log_ErrorPrint("Failed to read description");
return false; return false;
} }
Log_InfoPrintf("Patch description: %s", desc); Log_InfoFmt("Patch description: %s", desc);
const u32 idlen = ReadFileIDDiz(fp, 2); const u32 idlen = ReadFileIDDiz(fp, 2);
u32 origlen; u32 origlen;
if (std::fseek(fp, 56, SEEK_SET) != 0 || std::fread(&origlen, sizeof(origlen), 1, fp) != 1) if (std::fseek(fp, 56, SEEK_SET) != 0 || std::fread(&origlen, sizeof(origlen), 1, fp) != 1) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to read size"); Log_ErrorPrint("Failed to read size");
return false; return false;
} }
std::vector<u8> temp; std::vector<u8> temp;
temp.resize(BLOCKCHECK_SIZE); temp.resize(BLOCKCHECK_SIZE);
if (std::fread(temp.data(), 1, BLOCKCHECK_SIZE, fp) != BLOCKCHECK_SIZE) if (std::fread(temp.data(), 1, BLOCKCHECK_SIZE, fp) != BLOCKCHECK_SIZE) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to read blockcheck data"); Log_ErrorPrint("Failed to read blockcheck data");
return false; return false;
} }
@ -232,18 +234,19 @@ bool CDImagePPF::ReadV2Patch(std::FILE* fp)
if (m_parent_image->Seek(blockcheck_src_sector) && m_parent_image->ReadRawSector(src_sector.data(), nullptr)) if (m_parent_image->Seek(blockcheck_src_sector) && m_parent_image->ReadRawSector(src_sector.data(), nullptr))
{ {
if (std::memcmp(&src_sector[blockcheck_src_offset], temp.data(), BLOCKCHECK_SIZE) != 0) if (std::memcmp(&src_sector[blockcheck_src_offset], temp.data(), BLOCKCHECK_SIZE) != 0)
Log_WarningPrintf("Blockcheck failed. The patch may not apply correctly."); Log_WarningPrint("Blockcheck failed. The patch may not apply correctly.");
} }
else else
{ {
Log_WarningPrintf("Failed to read blockcheck sector %u", blockcheck_src_sector); Log_WarningFmt("Failed to read blockcheck sector {}", blockcheck_src_sector);
} }
} }
u32 filelen; u32 filelen;
if (std::fseek(fp, 0, SEEK_END) != 0 || (filelen = static_cast<u32>(std::ftell(fp))) == 0 || filelen < 1084) if (std::fseek(fp, 0, SEEK_END) != 0 || (filelen = static_cast<u32>(std::ftell(fp))) == 0 || filelen < 1084)
[[unlikely]]
{ {
Log_ErrorPrintf("Invalid ppf file"); Log_ErrorPrint("Invalid ppf file");
return false; return false;
} }
@ -262,15 +265,16 @@ bool CDImagePPF::ReadV2Patch(std::FILE* fp)
u32 offset; u32 offset;
u8 chunk_size; u8 chunk_size;
if (std::fread(&offset, sizeof(offset), 1, fp) != 1 || std::fread(&chunk_size, sizeof(chunk_size), 1, fp) != 1) if (std::fread(&offset, sizeof(offset), 1, fp) != 1 || std::fread(&chunk_size, sizeof(chunk_size), 1, fp) != 1)
[[unlikely]]
{ {
Log_ErrorPrintf("Incomplete ppf"); Log_ErrorPrint("Incomplete ppf");
return false; return false;
} }
temp.resize(chunk_size); temp.resize(chunk_size);
if (std::fread(temp.data(), 1, chunk_size, fp) != chunk_size) if (std::fread(temp.data(), 1, chunk_size, fp) != chunk_size) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to read patch data"); Log_ErrorPrint("Failed to read patch data");
return false; return false;
} }
@ -280,7 +284,7 @@ bool CDImagePPF::ReadV2Patch(std::FILE* fp)
count -= sizeof(offset) + sizeof(chunk_size) + chunk_size; count -= sizeof(offset) + sizeof(chunk_size) + chunk_size;
} }
Log_InfoPrintf("Loaded %zu replacement sectors from version 2 PPF", m_replacement_map.size()); Log_InfoFmt("Loaded {} replacement sectors from version 2 PPF", m_replacement_map.size());
return true; return true;
} }
@ -289,11 +293,11 @@ bool CDImagePPF::ReadV3Patch(std::FILE* fp)
char desc[DESC_SIZE + 1] = {}; char desc[DESC_SIZE + 1] = {};
if (std::fseek(fp, 6, SEEK_SET) != 0 || std::fread(desc, sizeof(char), DESC_SIZE, fp) != DESC_SIZE) if (std::fseek(fp, 6, SEEK_SET) != 0 || std::fread(desc, sizeof(char), DESC_SIZE, fp) != DESC_SIZE)
{ {
Log_ErrorPrintf("Failed to read description"); Log_ErrorPrint("Failed to read description");
return false; return false;
} }
Log_InfoPrintf("Patch description: %s", desc); Log_InfoFmt("Patch description: {}", desc);
u32 idlen = ReadFileIDDiz(fp, 3); u32 idlen = ReadFileIDDiz(fp, 3);
@ -303,7 +307,7 @@ bool CDImagePPF::ReadV3Patch(std::FILE* fp)
if (std::fseek(fp, 56, SEEK_SET) != 0 || std::fread(&image_type, sizeof(image_type), 1, fp) != 1 || if (std::fseek(fp, 56, SEEK_SET) != 0 || std::fread(&image_type, sizeof(image_type), 1, fp) != 1 ||
std::fread(&block_check, sizeof(block_check), 1, fp) != 1 || std::fread(&undo, sizeof(undo), 1, fp) != 1) std::fread(&block_check, sizeof(block_check), 1, fp) != 1 || std::fread(&undo, sizeof(undo), 1, fp) != 1)
{ {
Log_ErrorPrintf("Failed to read headers"); Log_ErrorPrint("Failed to read headers");
return false; return false;
} }
@ -315,7 +319,7 @@ bool CDImagePPF::ReadV3Patch(std::FILE* fp)
u32 seekpos = (block_check) ? 1084 : 60; u32 seekpos = (block_check) ? 1084 : 60;
if (seekpos >= count) if (seekpos >= count)
{ {
Log_ErrorPrintf("File is too short"); Log_ErrorPrint("File is too short");
return false; return false;
} }
@ -325,7 +329,7 @@ bool CDImagePPF::ReadV3Patch(std::FILE* fp)
const u32 extralen = idlen + 18 + 16 + 2; const u32 extralen = idlen + 18 + 16 + 2;
if (count < extralen) if (count < extralen)
{ {
Log_ErrorPrintf("File is too short (diz)"); Log_ErrorPrint("File is too short (diz)");
return false; return false;
} }
@ -343,14 +347,14 @@ bool CDImagePPF::ReadV3Patch(std::FILE* fp)
u8 chunk_size; u8 chunk_size;
if (std::fread(&offset, sizeof(offset), 1, fp) != 1 || std::fread(&chunk_size, sizeof(chunk_size), 1, fp) != 1) if (std::fread(&offset, sizeof(offset), 1, fp) != 1 || std::fread(&chunk_size, sizeof(chunk_size), 1, fp) != 1)
{ {
Log_ErrorPrintf("Incomplete ppf"); Log_ErrorPrint("Incomplete ppf");
return false; return false;
} }
temp.resize(chunk_size); temp.resize(chunk_size);
if (std::fread(temp.data(), 1, chunk_size, fp) != chunk_size) if (std::fread(temp.data(), 1, chunk_size, fp) != chunk_size)
{ {
Log_ErrorPrintf("Failed to read patch data"); Log_ErrorPrint("Failed to read patch data");
return false; return false;
} }
@ -360,13 +364,13 @@ bool CDImagePPF::ReadV3Patch(std::FILE* fp)
count -= sizeof(offset) + sizeof(chunk_size) + chunk_size; count -= sizeof(offset) + sizeof(chunk_size) + chunk_size;
} }
Log_InfoPrintf("Loaded %zu replacement sectors from version 3 PPF", m_replacement_map.size()); Log_InfoFmt("Loaded {} replacement sectors from version 3 PPF", m_replacement_map.size());
return true; return true;
} }
bool CDImagePPF::AddPatch(u64 offset, const u8* patch, u32 patch_size) bool CDImagePPF::AddPatch(u64 offset, const u8* patch, u32 patch_size)
{ {
Log_DebugPrintf("Starting applying patch of %u bytes at at offset %" PRIu64, patch_size, offset); Log_DebugFmt("Starting applying patch of {} bytes at at offset {}", patch_size, offset);
while (patch_size > 0) while (patch_size > 0)
{ {
@ -374,7 +378,7 @@ bool CDImagePPF::AddPatch(u64 offset, const u8* patch, u32 patch_size)
const u32 sector_offset = Truncate32(offset % RAW_SECTOR_SIZE); const u32 sector_offset = Truncate32(offset % RAW_SECTOR_SIZE);
if (sector_index >= m_parent_image->GetLBACount()) if (sector_index >= m_parent_image->GetLBACount())
{ {
Log_ErrorPrintf("Sector %u in patch is out of range", sector_index); Log_ErrorFmt("Sector {} in patch is out of range", sector_index);
return false; return false;
} }
@ -388,7 +392,7 @@ bool CDImagePPF::AddPatch(u64 offset, const u8* patch, u32 patch_size)
if (!m_parent_image->Seek(sector_index) || if (!m_parent_image->Seek(sector_index) ||
!m_parent_image->ReadRawSector(&m_replacement_data[replacement_buffer_start], nullptr)) !m_parent_image->ReadRawSector(&m_replacement_data[replacement_buffer_start], nullptr))
{ {
Log_ErrorPrintf("Failed to read sector %u from parent image", sector_index); Log_ErrorFmt("Failed to read sector {} from parent image", sector_index);
return false; return false;
} }
@ -396,7 +400,7 @@ bool CDImagePPF::AddPatch(u64 offset, const u8* patch, u32 patch_size)
} }
// patch it! // patch it!
Log_DebugPrintf(" Patching %u bytes at sector %u offset %u", bytes_to_patch, sector_index, sector_offset); Log_DebugFmt(" Patching {} bytes at sector {} offset {}", bytes_to_patch, sector_index, sector_offset);
std::memcpy(&m_replacement_data[iter->second + sector_offset], patch, bytes_to_patch); std::memcpy(&m_replacement_data[iter->second + sector_offset], patch, bytes_to_patch);
offset += bytes_to_patch; offset += bytes_to_patch;
patch += bytes_to_patch; patch += bytes_to_patch;

View File

@ -282,7 +282,7 @@ void CubebAudioStream::SetPaused(bool paused)
const int rv = paused ? cubeb_stream_stop(stream) : cubeb_stream_start(stream); const int rv = paused ? cubeb_stream_stop(stream) : cubeb_stream_start(stream);
if (rv != CUBEB_OK) if (rv != CUBEB_OK)
{ {
Log_ErrorPrintf("Could not %s stream: %d", paused ? "pause" : "resume", rv); Log_ErrorFmt("Could not {} stream: {}", paused ? "pause" : "resume", rv);
return; return;
} }

View File

@ -79,7 +79,7 @@ void CueParser::File::SetError(u32 line_number, Error* error, const char* format
str.vsprintf(format, ap); str.vsprintf(format, ap);
va_end(ap); va_end(ap);
Log_ErrorPrintf("Cue parse error at line %u: %s", line_number, str.c_str()); Log_ErrorFmt("Cue parse error at line {}: {}", line_number, str.c_str());
Error::SetString(error, fmt::format("Cue parse error at line {}: {}", line_number, str)); Error::SetString(error, fmt::format("Cue parse error at line {}: {}", line_number, str));
} }
@ -194,7 +194,7 @@ bool CueParser::File::ParseLine(const char* line, u32 line_number, Error* error)
if (TokenMatch(command, "POSTGAP")) if (TokenMatch(command, "POSTGAP"))
{ {
Log_WarningPrintf("Ignoring '%*s' command", static_cast<int>(command.size()), command.data()); Log_WarningFmt("Ignoring '{}' command", command);
return true; return true;
} }
@ -231,7 +231,7 @@ bool CueParser::File::HandleFileCommand(const char* line, u32 line_number, Error
} }
m_current_file = filename; m_current_file = filename;
Log_DebugPrintf("File '%s'", m_current_file->c_str()); Log_DebugFmt("File '{}'", filename);
return true; return true;
} }
@ -392,7 +392,7 @@ bool CueParser::File::HandleFlagCommand(const char* line, u32 line_number, Error
else if (TokenMatch(token, "SCMS")) else if (TokenMatch(token, "SCMS"))
m_current_track->SetFlag(TrackFlag::SerialCopyManagement); m_current_track->SetFlag(TrackFlag::SerialCopyManagement);
else else
Log_WarningPrintf("Unknown track flag '%*s'", static_cast<int>(token.size()), token.data()); Log_WarningFmt("Unknown track flag '{}'", token);
} }
return true; return true;
@ -428,7 +428,7 @@ bool CueParser::File::CompleteLastTrack(u32 line_number, Error* error)
const MSF* index0 = m_current_track->GetIndex(0); const MSF* index0 = m_current_track->GetIndex(0);
if (index0 && m_current_track->zero_pregap.has_value()) if (index0 && m_current_track->zero_pregap.has_value())
{ {
Log_WarningPrintf("Zero pregap and index 0 specified in track %u, ignoring zero pregap", m_current_track->number); Log_WarningFmt("Zero pregap and index 0 specified in track {}, ignoring zero pregap", m_current_track->number);
m_current_track->zero_pregap.reset(); m_current_track->zero_pregap.reset();
} }

View File

@ -126,7 +126,7 @@ bool D3D11Device::CreateDevice(std::string_view adapter, bool threaded_presentat
ComPtr<IDXGIDevice> dxgi_device; ComPtr<IDXGIDevice> dxgi_device;
if (SUCCEEDED(m_device.As(&dxgi_device)) && if (SUCCEEDED(m_device.As(&dxgi_device)) &&
SUCCEEDED(dxgi_device->GetParent(IID_PPV_ARGS(dxgi_adapter.GetAddressOf())))) SUCCEEDED(dxgi_device->GetParent(IID_PPV_ARGS(dxgi_adapter.GetAddressOf()))))
Log_InfoPrintf("D3D Adapter: %s", D3DCommon::GetAdapterName(dxgi_adapter.Get()).c_str()); Log_InfoFmt("D3D Adapter: %s", D3DCommon::GetAdapterName(dxgi_adapter.Get()));
else else
Log_ErrorPrint("Failed to obtain D3D adapter name."); Log_ErrorPrint("Failed to obtain D3D adapter name.");
Log_InfoFmt("Max device feature level: {}", D3DCommon::GetFeatureLevelString(m_max_feature_level)); Log_InfoFmt("Max device feature level: {}", D3DCommon::GetFeatureLevelString(m_max_feature_level));
@ -263,12 +263,12 @@ bool D3D11Device::CreateSwapChain()
fs_desc.Scaling = fullscreen_mode.Scaling; fs_desc.Scaling = fullscreen_mode.Scaling;
fs_desc.Windowed = FALSE; fs_desc.Windowed = FALSE;
Log_VerbosePrintf("Creating a %dx%d exclusive fullscreen swap chain", fs_sd_desc.Width, fs_sd_desc.Height); Log_VerboseFmt("Creating a {}x{} exclusive fullscreen swap chain", fs_sd_desc.Width, fs_sd_desc.Height);
hr = m_dxgi_factory->CreateSwapChainForHwnd(m_device.Get(), window_hwnd, &fs_sd_desc, &fs_desc, hr = m_dxgi_factory->CreateSwapChainForHwnd(m_device.Get(), window_hwnd, &fs_sd_desc, &fs_desc,
fullscreen_output.Get(), m_swap_chain.ReleaseAndGetAddressOf()); fullscreen_output.Get(), m_swap_chain.ReleaseAndGetAddressOf());
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_WarningPrintf("Failed to create fullscreen swap chain, trying windowed."); Log_WarningPrint("Failed to create fullscreen swap chain, trying windowed.");
m_is_exclusive_fullscreen = false; m_is_exclusive_fullscreen = false;
m_using_allow_tearing = m_allow_tearing_supported && m_using_flip_model_swap_chain; m_using_allow_tearing = m_allow_tearing_supported && m_using_flip_model_swap_chain;
} }
@ -276,15 +276,15 @@ bool D3D11Device::CreateSwapChain()
if (!m_is_exclusive_fullscreen) if (!m_is_exclusive_fullscreen)
{ {
Log_VerbosePrintf("Creating a %dx%d %s windowed swap chain", swap_chain_desc.Width, swap_chain_desc.Height, Log_VerboseFmt("Creating a {}x{} {} windowed swap chain", swap_chain_desc.Width, swap_chain_desc.Height,
m_using_flip_model_swap_chain ? "flip-discard" : "discard"); m_using_flip_model_swap_chain ? "flip-discard" : "discard");
hr = m_dxgi_factory->CreateSwapChainForHwnd(m_device.Get(), window_hwnd, &swap_chain_desc, nullptr, nullptr, hr = m_dxgi_factory->CreateSwapChainForHwnd(m_device.Get(), window_hwnd, &swap_chain_desc, nullptr, nullptr,
m_swap_chain.ReleaseAndGetAddressOf()); m_swap_chain.ReleaseAndGetAddressOf());
} }
if (FAILED(hr) && m_using_flip_model_swap_chain) if (FAILED(hr) && m_using_flip_model_swap_chain)
{ {
Log_WarningPrintf("Failed to create a flip-discard swap chain, trying discard."); Log_WarningPrint("Failed to create a flip-discard swap chain, trying discard.");
swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swap_chain_desc.Flags = 0; swap_chain_desc.Flags = 0;
m_using_flip_model_swap_chain = false; m_using_flip_model_swap_chain = false;
@ -292,9 +292,9 @@ bool D3D11Device::CreateSwapChain()
hr = m_dxgi_factory->CreateSwapChainForHwnd(m_device.Get(), window_hwnd, &swap_chain_desc, nullptr, nullptr, hr = m_dxgi_factory->CreateSwapChainForHwnd(m_device.Get(), window_hwnd, &swap_chain_desc, nullptr, nullptr,
m_swap_chain.ReleaseAndGetAddressOf()); m_swap_chain.ReleaseAndGetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("CreateSwapChainForHwnd failed: 0x%08X", hr); Log_ErrorFmt("CreateSwapChainForHwnd failed: 0x{:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
} }
@ -304,7 +304,7 @@ bool D3D11Device::CreateSwapChain()
if (FAILED(m_swap_chain->GetParent(IID_PPV_ARGS(parent_factory.GetAddressOf()))) || if (FAILED(m_swap_chain->GetParent(IID_PPV_ARGS(parent_factory.GetAddressOf()))) ||
FAILED(parent_factory->MakeWindowAssociation(window_hwnd, DXGI_MWA_NO_WINDOW_CHANGES))) FAILED(parent_factory->MakeWindowAssociation(window_hwnd, DXGI_MWA_NO_WINDOW_CHANGES)))
{ {
Log_WarningPrintf("MakeWindowAssociation() to disable ALT+ENTER failed"); Log_WarningPrint("MakeWindowAssociation() to disable ALT+ENTER failed");
} }
if (!CreateSwapChainRTV()) if (!CreateSwapChainRTV())
@ -323,9 +323,9 @@ bool D3D11Device::CreateSwapChainRTV()
{ {
ComPtr<ID3D11Texture2D> backbuffer; ComPtr<ID3D11Texture2D> backbuffer;
HRESULT hr = m_swap_chain->GetBuffer(0, IID_PPV_ARGS(backbuffer.GetAddressOf())); HRESULT hr = m_swap_chain->GetBuffer(0, IID_PPV_ARGS(backbuffer.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("GetBuffer for RTV failed: 0x%08X", hr); Log_ErrorFmt("GetBuffer for RTV failed: 0x{:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
@ -335,9 +335,9 @@ bool D3D11Device::CreateSwapChainRTV()
CD3D11_RENDER_TARGET_VIEW_DESC rtv_desc(D3D11_RTV_DIMENSION_TEXTURE2D, backbuffer_desc.Format, 0, 0, CD3D11_RENDER_TARGET_VIEW_DESC rtv_desc(D3D11_RTV_DIMENSION_TEXTURE2D, backbuffer_desc.Format, 0, 0,
backbuffer_desc.ArraySize); backbuffer_desc.ArraySize);
hr = m_device->CreateRenderTargetView(backbuffer.Get(), &rtv_desc, m_swap_chain_rtv.ReleaseAndGetAddressOf()); hr = m_device->CreateRenderTargetView(backbuffer.Get(), &rtv_desc, m_swap_chain_rtv.ReleaseAndGetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("CreateRenderTargetView for swap chain failed: 0x%08X", hr); Log_ErrorFmt("CreateRenderTargetView for swap chain failed: 0x{:08X}", static_cast<unsigned>(hr));
m_swap_chain_rtv.Reset(); m_swap_chain_rtv.Reset();
return false; return false;
} }
@ -345,7 +345,7 @@ bool D3D11Device::CreateSwapChainRTV()
m_window_info.surface_width = backbuffer_desc.Width; m_window_info.surface_width = backbuffer_desc.Width;
m_window_info.surface_height = backbuffer_desc.Height; m_window_info.surface_height = backbuffer_desc.Height;
m_window_info.surface_format = s_swap_chain_format; m_window_info.surface_format = s_swap_chain_format;
Log_VerbosePrintf("Swap chain buffer size: %ux%u", m_window_info.surface_width, m_window_info.surface_height); Log_VerboseFmt("Swap chain buffer size: {}x{}", m_window_info.surface_width, m_window_info.surface_height);
if (m_window_info.type == WindowInfo::Type::Win32) if (m_window_info.type == WindowInfo::Type::Win32)
{ {
@ -391,7 +391,7 @@ bool D3D11Device::UpdateWindow()
if (m_window_info.type != WindowInfo::Type::Surfaceless && !CreateSwapChain()) if (m_window_info.type != WindowInfo::Type::Surfaceless && !CreateSwapChain())
{ {
Log_ErrorPrintf("Failed to create swap chain on updated window"); Log_ErrorPrint("Failed to create swap chain on updated window");
return false; return false;
} }
@ -420,8 +420,8 @@ void D3D11Device::ResizeWindow(s32 new_window_width, s32 new_window_height, floa
HRESULT hr = m_swap_chain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, HRESULT hr = m_swap_chain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN,
m_using_allow_tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0); m_using_allow_tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0);
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
Log_ErrorPrintf("ResizeBuffers() failed: 0x%08X", hr); Log_ErrorFmt("ResizeBuffers() failed: 0x{:08X}", static_cast<unsigned>(hr));
if (!CreateSwapChainRTV()) if (!CreateSwapChainRTV())
Panic("Failed to recreate swap chain RTV after resize"); Panic("Failed to recreate swap chain RTV after resize");
@ -470,7 +470,7 @@ bool D3D11Device::CreateBuffers()
!m_index_buffer.Create(D3D11_BIND_INDEX_BUFFER, INDEX_BUFFER_SIZE, INDEX_BUFFER_SIZE) || !m_index_buffer.Create(D3D11_BIND_INDEX_BUFFER, INDEX_BUFFER_SIZE, INDEX_BUFFER_SIZE) ||
!m_uniform_buffer.Create(D3D11_BIND_CONSTANT_BUFFER, MIN_UNIFORM_BUFFER_SIZE, MAX_UNIFORM_BUFFER_SIZE)) !m_uniform_buffer.Create(D3D11_BIND_CONSTANT_BUFFER, MIN_UNIFORM_BUFFER_SIZE, MAX_UNIFORM_BUFFER_SIZE))
{ {
Log_ErrorPrintf("Failed to create vertex/index/uniform buffers."); Log_ErrorPrint("Failed to create vertex/index/uniform buffers.");
return false; return false;
} }
@ -776,7 +776,7 @@ void D3D11Device::PopTimestampQuery()
if (disjoint.Disjoint) if (disjoint.Disjoint)
{ {
Log_VerbosePrintf("GPU timing disjoint, resetting."); Log_VerbosePrint("GPU timing disjoint, resetting.");
m_read_timestamp_query = 0; m_read_timestamp_query = 0;
m_write_timestamp_query = 0; m_write_timestamp_query = 0;
m_waiting_timestamp_queries = 0; m_waiting_timestamp_queries = 0;

View File

@ -152,8 +152,8 @@ D3D11Device::ComPtr<ID3D11RasterizerState> D3D11Device::GetRasterizationState(co
// desc.MultisampleEnable ??? // desc.MultisampleEnable ???
HRESULT hr = m_device->CreateRasterizerState(&desc, drs.GetAddressOf()); HRESULT hr = m_device->CreateRasterizerState(&desc, drs.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
Log_ErrorPrintf("Failed to create depth state with %08X", hr); Log_ErrorFmt("Failed to create depth state with {:08X}", static_cast<unsigned>(hr));
m_rasterization_states.emplace(rs.key, drs); m_rasterization_states.emplace(rs.key, drs);
return drs; return drs;
@ -187,8 +187,8 @@ D3D11Device::ComPtr<ID3D11DepthStencilState> D3D11Device::GetDepthState(const GP
desc.DepthWriteMask = ds.depth_write ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; desc.DepthWriteMask = ds.depth_write ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
HRESULT hr = m_device->CreateDepthStencilState(&desc, dds.GetAddressOf()); HRESULT hr = m_device->CreateDepthStencilState(&desc, dds.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
Log_ErrorPrintf("Failed to create depth state with %08X", hr); Log_ErrorFmt("Failed to create depth state with {:08X}", static_cast<unsigned>(hr));
m_depth_states.emplace(ds.key, dds); m_depth_states.emplace(ds.key, dds);
return dds; return dds;
@ -245,8 +245,8 @@ D3D11Device::ComPtr<ID3D11BlendState> D3D11Device::GetBlendState(const GPUPipeli
} }
HRESULT hr = m_device->CreateBlendState(&blend_desc, dbs.GetAddressOf()); HRESULT hr = m_device->CreateBlendState(&blend_desc, dbs.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
Log_ErrorPrintf("Failed to create blend state with %08X", hr); Log_ErrorFmt("Failed to create blend state with {:08X}", static_cast<unsigned>(hr));
m_blend_states.emplace(bs.key, dbs); m_blend_states.emplace(bs.key, dbs);
return dbs; return dbs;
@ -297,8 +297,8 @@ D3D11Device::ComPtr<ID3D11InputLayout> D3D11Device::GetInputLayout(const GPUPipe
HRESULT hr = m_device->CreateInputLayout(elems, static_cast<UINT>(il.vertex_attributes.size()), HRESULT hr = m_device->CreateInputLayout(elems, static_cast<UINT>(il.vertex_attributes.size()),
vs->GetBytecode().data(), vs->GetBytecode().size(), dil.GetAddressOf()); vs->GetBytecode().data(), vs->GetBytecode().size(), dil.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
Log_ErrorPrintf("Failed to create input layout with %08X", hr); Log_ErrorFmt("Failed to create input layout with {:08X}", static_cast<unsigned>(hr));
m_input_layouts.emplace(il, dil); m_input_layouts.emplace(il, dil);
return dil; return dil;

View File

@ -6,6 +6,7 @@
#include "common/align.h" #include "common/align.h"
#include "common/assert.h" #include "common/assert.h"
#include "common/error.h"
#include "common/log.h" #include "common/log.h"
Log_SetChannel(D3D11Device); Log_SetChannel(D3D11Device);
@ -30,7 +31,7 @@ bool D3D11StreamBuffer::Create(D3D11_BIND_FLAG bind_flags, u32 min_size, u32 max
{ {
D3D11_FEATURE_DATA_D3D11_OPTIONS options = {}; D3D11_FEATURE_DATA_D3D11_OPTIONS options = {};
HRESULT hr = D3D11Device::GetD3DDevice()->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &options, sizeof(options)); HRESULT hr = D3D11Device::GetD3DDevice()->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &options, sizeof(options));
if (SUCCEEDED(hr)) if (SUCCEEDED(hr)) [[likely]]
{ {
if (bind_flags & D3D11_BIND_CONSTANT_BUFFER) if (bind_flags & D3D11_BIND_CONSTANT_BUFFER)
{ {
@ -54,14 +55,14 @@ bool D3D11StreamBuffer::Create(D3D11_BIND_FLAG bind_flags, u32 min_size, u32 max
if (!m_use_map_no_overwrite) if (!m_use_map_no_overwrite)
{ {
Log_WarningPrintf("Unable to use MAP_NO_OVERWRITE on buffer with bind flag %u, this may affect performance. " Log_WarningFmt("Unable to use MAP_NO_OVERWRITE on buffer with bind flag {}, this may affect performance. "
"Update your driver/operating system.", "Update your driver/operating system.",
static_cast<unsigned>(bind_flags)); static_cast<unsigned>(bind_flags));
} }
} }
else else
{ {
Log_WarningPrintf("ID3D11Device::CheckFeatureSupport() failed: 0x%08X", hr); Log_WarningFmt("ID3D11Device::CheckFeatureSupport() failed: {}", Error::CreateHResult(hr).GetDescription());
m_use_map_no_overwrite = false; m_use_map_no_overwrite = false;
} }
@ -69,9 +70,9 @@ bool D3D11StreamBuffer::Create(D3D11_BIND_FLAG bind_flags, u32 min_size, u32 max
const CD3D11_BUFFER_DESC desc(create_size, bind_flags, D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE, 0, 0); const CD3D11_BUFFER_DESC desc(create_size, bind_flags, D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE, 0, 0);
ComPtr<ID3D11Buffer> buffer; ComPtr<ID3D11Buffer> buffer;
hr = D3D11Device::GetD3DDevice()->CreateBuffer(&desc, nullptr, &buffer); hr = D3D11Device::GetD3DDevice()->CreateBuffer(&desc, nullptr, &buffer);
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Creating buffer failed: 0x%08X", hr); Log_ErrorFmt("Creating buffer failed: {}", Error::CreateHResult(hr).GetDescription());
return false; return false;
} }
@ -112,9 +113,9 @@ D3D11StreamBuffer::MappingResult D3D11StreamBuffer::Map(ID3D11DeviceContext1* co
new_desc.ByteWidth = new_size; new_desc.ByteWidth = new_size;
hr = D3D11Device::GetD3DDevice()->CreateBuffer(&new_desc, nullptr, m_buffer.ReleaseAndGetAddressOf()); hr = D3D11Device::GetD3DDevice()->CreateBuffer(&new_desc, nullptr, m_buffer.ReleaseAndGetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorFmt("Creating buffer failed: 0x{:08X}", static_cast<unsigned>(hr)); Log_ErrorFmt("Creating buffer failed: {}", Error::CreateHResult(hr).GetDescription());
Panic("Failed to grow buffer"); Panic("Failed to grow buffer");
} }
@ -125,10 +126,10 @@ D3D11StreamBuffer::MappingResult D3D11StreamBuffer::Map(ID3D11DeviceContext1* co
D3D11_MAPPED_SUBRESOURCE sr; D3D11_MAPPED_SUBRESOURCE sr;
const D3D11_MAP map_type = (m_position == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE; const D3D11_MAP map_type = (m_position == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE;
hr = context->Map(m_buffer.Get(), 0, map_type, 0, &sr); hr = context->Map(m_buffer.Get(), 0, map_type, 0, &sr);
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Map failed: 0x%08X (alignment %u, minsize %u, size %u, position %u, map type %u)", hr, alignment, Log_ErrorFmt("Map failed: 0x{:08X} (alignment {}, minsize {}, size {}, position [], map type {})",
min_size, m_size, m_position, static_cast<u32>(map_type)); static_cast<unsigned>(hr), alignment, min_size, m_size, m_position, static_cast<u32>(map_type));
Panic("Map failed"); Panic("Map failed");
} }

View File

@ -84,9 +84,9 @@ std::unique_ptr<GPUSampler> D3D11Device::CreateSampler(const GPUSampler::Config&
ComPtr<ID3D11SamplerState> ss; ComPtr<ID3D11SamplerState> ss;
const HRESULT hr = m_device->CreateSamplerState(&desc, ss.GetAddressOf()); const HRESULT hr = m_device->CreateSamplerState(&desc, ss.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("CreateSamplerState() failed: %08X", hr); Log_ErrorFmt("CreateSamplerState() failed: {:08X}", static_cast<unsigned>(hr));
return {}; return {};
} }
@ -187,9 +187,9 @@ bool D3D11Texture::Map(void** map, u32* map_stride, u32 x, u32 y, u32 width, u32
D3D11_MAPPED_SUBRESOURCE sr; D3D11_MAPPED_SUBRESOURCE sr;
HRESULT hr = context->Map(m_texture.Get(), srnum, discard ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_READ_WRITE, 0, &sr); HRESULT hr = context->Map(m_texture.Get(), srnum, discard ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_READ_WRITE, 0, &sr);
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Map pixels texture failed: %08X", hr); Log_ErrorFmt("Map pixels texture failed: {:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
@ -267,9 +267,10 @@ std::unique_ptr<D3D11Texture> D3D11Texture::Create(ID3D11Device* device, u32 wid
const HRESULT tex_hr = device->CreateTexture2D(&desc, initial_data ? &srd : nullptr, texture.GetAddressOf()); const HRESULT tex_hr = device->CreateTexture2D(&desc, initial_data ? &srd : nullptr, texture.GetAddressOf());
if (FAILED(tex_hr)) if (FAILED(tex_hr))
{ {
Log_ErrorPrintf( Log_ErrorFmt(
"Create texture failed: 0x%08X (%ux%u levels:%u samples:%u format:%u bind_flags:%X initial_data:%p)", tex_hr, "Create texture failed: 0x{:08X} ({}x{} levels:{} samples:{} format:{} bind_flags:{:X} initial_data:{})",
width, height, levels, samples, static_cast<unsigned>(format), bind_flags, initial_data); static_cast<unsigned>(tex_hr), width, height, levels, samples, static_cast<unsigned>(format), bind_flags,
initial_data);
return nullptr; return nullptr;
} }
@ -288,9 +289,9 @@ std::unique_ptr<D3D11Texture> D3D11Texture::Create(ID3D11Device* device, u32 wid
(desc.ArraySize > 1 ? D3D11_SRV_DIMENSION_TEXTURE2DARRAY : D3D11_SRV_DIMENSION_TEXTURE2D); (desc.ArraySize > 1 ? D3D11_SRV_DIMENSION_TEXTURE2DARRAY : D3D11_SRV_DIMENSION_TEXTURE2D);
const CD3D11_SHADER_RESOURCE_VIEW_DESC srv_desc(srv_dimension, fm.srv_format, 0, desc.MipLevels, 0, desc.ArraySize); const CD3D11_SHADER_RESOURCE_VIEW_DESC srv_desc(srv_dimension, fm.srv_format, 0, desc.MipLevels, 0, desc.ArraySize);
const HRESULT hr = device->CreateShaderResourceView(texture.Get(), &srv_desc, srv.GetAddressOf()); const HRESULT hr = device->CreateShaderResourceView(texture.Get(), &srv_desc, srv.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Create SRV for texture failed: 0x%08X", hr); Log_ErrorFmt("Create SRV for texture failed: 0x{:08X}", static_cast<unsigned>(hr));
return nullptr; return nullptr;
} }
} }
@ -303,9 +304,9 @@ std::unique_ptr<D3D11Texture> D3D11Texture::Create(ID3D11Device* device, u32 wid
const CD3D11_RENDER_TARGET_VIEW_DESC rtv_desc(rtv_dimension, fm.rtv_format, 0, 0, desc.ArraySize); const CD3D11_RENDER_TARGET_VIEW_DESC rtv_desc(rtv_dimension, fm.rtv_format, 0, 0, desc.ArraySize);
ComPtr<ID3D11RenderTargetView> rtv; ComPtr<ID3D11RenderTargetView> rtv;
const HRESULT hr = device->CreateRenderTargetView(texture.Get(), &rtv_desc, rtv.GetAddressOf()); const HRESULT hr = device->CreateRenderTargetView(texture.Get(), &rtv_desc, rtv.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Create RTV for texture failed: 0x%08X", hr); Log_ErrorFmt("Create RTV for texture failed: 0x{:08X}", static_cast<unsigned>(hr));
return nullptr; return nullptr;
} }
@ -318,9 +319,9 @@ std::unique_ptr<D3D11Texture> D3D11Texture::Create(ID3D11Device* device, u32 wid
const CD3D11_DEPTH_STENCIL_VIEW_DESC dsv_desc(dsv_dimension, fm.dsv_format, 0, 0, desc.ArraySize); const CD3D11_DEPTH_STENCIL_VIEW_DESC dsv_desc(dsv_dimension, fm.dsv_format, 0, 0, desc.ArraySize);
ComPtr<ID3D11DepthStencilView> dsv; ComPtr<ID3D11DepthStencilView> dsv;
const HRESULT hr = device->CreateDepthStencilView(texture.Get(), &dsv_desc, dsv.GetAddressOf()); const HRESULT hr = device->CreateDepthStencilView(texture.Get(), &dsv_desc, dsv.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Create DSV for texture failed: 0x%08X", hr); Log_ErrorFmt("Create DSV for texture failed: 0x{:08X}", static_cast<unsigned>(hr));
return nullptr; return nullptr;
} }
@ -351,9 +352,9 @@ bool D3D11TextureBuffer::CreateBuffer()
m_size_in_elements); m_size_in_elements);
const HRESULT hr = const HRESULT hr =
D3D11Device::GetD3DDevice()->CreateShaderResourceView(m_buffer.GetD3DBuffer(), &srv_desc, m_srv.GetAddressOf()); D3D11Device::GetD3DDevice()->CreateShaderResourceView(m_buffer.GetD3DBuffer(), &srv_desc, m_srv.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("CreateShaderResourceView() failed: %08X", hr); Log_ErrorFmt("CreateShaderResourceView() failed: {:08X}", static_cast<unsigned>(hr));
return false; return false;
} }

View File

@ -34,7 +34,7 @@ Microsoft::WRL::ComPtr<ID3D12PipelineState> D3D12::GraphicsPipelineBuilder::Crea
HRESULT hr = device->CreateGraphicsPipelineState(&m_desc, IID_PPV_ARGS(ps.GetAddressOf())); HRESULT hr = device->CreateGraphicsPipelineState(&m_desc, IID_PPV_ARGS(ps.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("CreateGraphicsPipelineState() failed: %08X", hr); Log_ErrorFmt("CreateGraphicsPipelineState() failed: {:08X}", static_cast<unsigned>(hr));
return {}; return {};
} }
@ -223,9 +223,9 @@ Microsoft::WRL::ComPtr<ID3D12PipelineState> D3D12::ComputePipelineBuilder::Creat
{ {
Microsoft::WRL::ComPtr<ID3D12PipelineState> ps; Microsoft::WRL::ComPtr<ID3D12PipelineState> ps;
HRESULT hr = device->CreateComputePipelineState(&m_desc, IID_PPV_ARGS(ps.GetAddressOf())); HRESULT hr = device->CreateComputePipelineState(&m_desc, IID_PPV_ARGS(ps.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("CreateComputePipelineState() failed: %08X", hr); Log_ErrorFmt("CreateComputePipelineState() failed: {:08X}", static_cast<unsigned>(hr));
return {}; return {};
} }

View File

@ -19,9 +19,9 @@ bool D3D12DescriptorHeapManager::Create(ID3D12Device* device, D3D12_DESCRIPTOR_H
D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0u}; D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0u};
HRESULT hr = device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(m_descriptor_heap.ReleaseAndGetAddressOf())); HRESULT hr = device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(m_descriptor_heap.ReleaseAndGetAddressOf()));
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("CreateDescriptorHeap() failed: %08X", hr); Log_ErrorFmt("CreateDescriptorHeap() failed: {:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
@ -117,7 +117,7 @@ bool D3D12DescriptorAllocator::Create(ID3D12Device* device, D3D12_DESCRIPTOR_HEA
const HRESULT hr = device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(m_descriptor_heap.ReleaseAndGetAddressOf())); const HRESULT hr = device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(m_descriptor_heap.ReleaseAndGetAddressOf()));
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("CreateDescriptorHeap() failed: %08X", hr); Log_ErrorFmt("CreateDescriptorHeap() failed: {:08X}", static_cast<unsigned>(hr));
return false; return false;
} }

View File

@ -87,11 +87,11 @@ D3D12Device::ComPtr<ID3DBlob> D3D12Device::SerializeRootSignature(const D3D12_RO
ComPtr<ID3DBlob> error_blob; ComPtr<ID3DBlob> error_blob;
const HRESULT hr = const HRESULT hr =
D3D12SerializeRootSignature(desc, D3D_ROOT_SIGNATURE_VERSION_1, blob.GetAddressOf(), error_blob.GetAddressOf()); D3D12SerializeRootSignature(desc, D3D_ROOT_SIGNATURE_VERSION_1, blob.GetAddressOf(), error_blob.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("D3D12SerializeRootSignature() failed: %08X", hr); Log_ErrorFmt("D3D12SerializeRootSignature() failed: {:08X}", static_cast<unsigned>(hr));
if (error_blob) if (error_blob)
Log_ErrorPrintf("%s", error_blob->GetBufferPointer()); Log_ErrorPrint(static_cast<const char*>(error_blob->GetBufferPointer()));
return {}; return {};
} }
@ -108,9 +108,9 @@ D3D12Device::ComPtr<ID3D12RootSignature> D3D12Device::CreateRootSignature(const
ComPtr<ID3D12RootSignature> rs; ComPtr<ID3D12RootSignature> rs;
const HRESULT hr = const HRESULT hr =
m_device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(rs.GetAddressOf())); m_device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(rs.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("CreateRootSignature() failed: %08X", hr); Log_ErrorFmt("CreateRootSignature() failed: {:08X}", static_cast<unsigned>(hr));
return {}; return {};
} }
@ -142,7 +142,7 @@ bool D3D12Device::CreateDevice(std::string_view adapter, bool threaded_presentat
} }
else else
{ {
Log_ErrorPrintf("Debug layer requested but not available."); Log_ErrorPrint("Debug layer requested but not available.");
m_debug_device = false; m_debug_device = false;
} }
} }
@ -160,7 +160,7 @@ bool D3D12Device::CreateDevice(std::string_view adapter, bool threaded_presentat
{ {
const LUID luid(m_device->GetAdapterLuid()); const LUID luid(m_device->GetAdapterLuid());
if (FAILED(m_dxgi_factory->EnumAdapterByLuid(luid, IID_PPV_ARGS(m_adapter.GetAddressOf())))) if (FAILED(m_dxgi_factory->EnumAdapterByLuid(luid, IID_PPV_ARGS(m_adapter.GetAddressOf()))))
Log_ErrorPrintf("Failed to get lookup adapter by device LUID"); Log_ErrorPrint("Failed to get lookup adapter by device LUID");
} }
if (m_debug_device) if (m_debug_device)
@ -333,7 +333,7 @@ bool D3D12Device::GetPipelineCacheData(DynamicHeapArray<u8>* data)
const size_t size = m_pipeline_library->GetSerializedSize(); const size_t size = m_pipeline_library->GetSerializedSize();
if (size == 0) if (size == 0)
{ {
Log_WarningPrintf("Empty serialized pipeline state returned."); Log_WarningPrint("Empty serialized pipeline state returned.");
return false; return false;
} }
@ -341,7 +341,7 @@ bool D3D12Device::GetPipelineCacheData(DynamicHeapArray<u8>* data)
const HRESULT hr = m_pipeline_library->Serialize(data->data(), data->size()); const HRESULT hr = m_pipeline_library->Serialize(data->data(), data->size());
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("Serialize() failed with HRESULT %08X", hr); Log_ErrorFmt("Serialize() failed with HRESULT {:08X}", static_cast<unsigned>(hr));
data->deallocate(); data->deallocate();
return false; return false;
} }
@ -362,7 +362,7 @@ bool D3D12Device::CreateCommandLists()
IID_PPV_ARGS(res.command_allocators[j].GetAddressOf())); IID_PPV_ARGS(res.command_allocators[j].GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("CreateCommandAllocator() failed: %08X", hr); Log_ErrorFmt("CreateCommandAllocator() failed: {:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
@ -370,7 +370,7 @@ bool D3D12Device::CreateCommandLists()
IID_PPV_ARGS(res.command_lists[j].GetAddressOf())); IID_PPV_ARGS(res.command_lists[j].GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("CreateCommandList() failed: %08X", hr); Log_ErrorFmt("CreateCommandList() failed: {:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
@ -378,7 +378,7 @@ bool D3D12Device::CreateCommandLists()
hr = res.command_lists[j]->Close(); hr = res.command_lists[j]->Close();
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("Close() failed: %08X", hr); Log_ErrorFmt("Close() failed: {:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
} }
@ -386,13 +386,13 @@ bool D3D12Device::CreateCommandLists()
if (!res.descriptor_allocator.Create(m_device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, if (!res.descriptor_allocator.Create(m_device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
MAX_DESCRIPTORS_PER_FRAME)) MAX_DESCRIPTORS_PER_FRAME))
{ {
Log_ErrorPrintf("Failed to create per frame descriptor allocator"); Log_ErrorPrint("Failed to create per frame descriptor allocator");
return false; return false;
} }
if (!res.sampler_allocator.Create(m_device.Get(), MAX_SAMPLERS_PER_FRAME)) if (!res.sampler_allocator.Create(m_device.Get(), MAX_SAMPLERS_PER_FRAME))
{ {
Log_ErrorPrintf("Failed to create per frame sampler allocator"); Log_ErrorPrint("Failed to create per frame sampler allocator");
return false; return false;
} }
} }
@ -439,7 +439,7 @@ void D3D12Device::MoveToNextCommandList()
} }
else else
{ {
Log_WarningPrintf("Map() for timestamp query failed: %08X", hr); Log_WarningFmt("Map() for timestamp query failed: {:08X}", static_cast<unsigned>(hr));
} }
} }
@ -549,18 +549,18 @@ void D3D12Device::SubmitCommandList(bool wait_for_completion)
if (res.init_list_used) if (res.init_list_used)
{ {
hr = res.command_lists[0]->Close(); hr = res.command_lists[0]->Close();
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Closing init command list failed with HRESULT %08X", hr); Log_ErrorFmt("Closing init command list failed with HRESULT {:08X}", static_cast<unsigned>(hr));
Panic("TODO cannot continue"); Panic("TODO cannot continue");
} }
} }
// Close and queue command list. // Close and queue command list.
hr = res.command_lists[1]->Close(); hr = res.command_lists[1]->Close();
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Closing main command list failed with HRESULT %08X", hr); Log_ErrorFmt("Closing main command list failed with HRESULT {:08X}", static_cast<unsigned>(hr));
Panic("TODO cannot continue"); Panic("TODO cannot continue");
} }
@ -592,7 +592,7 @@ void D3D12Device::SubmitCommandList(bool wait_for_completion, const char* reason
const std::string reason_str(StringUtil::StdStringFromFormatV(reason, ap)); const std::string reason_str(StringUtil::StdStringFromFormatV(reason, ap));
va_end(ap); va_end(ap);
Log_WarningPrintf("Executing command buffer due to '%s'", reason_str.c_str()); Log_WarningFmt("Executing command buffer due to '{}'", reason_str);
SubmitCommandList(wait_for_completion); SubmitCommandList(wait_for_completion);
} }
@ -647,7 +647,7 @@ bool D3D12Device::CreateTimestampQuery()
HRESULT hr = m_device->CreateQueryHeap(&desc, IID_PPV_ARGS(m_timestamp_query_heap.GetAddressOf())); HRESULT hr = m_device->CreateQueryHeap(&desc, IID_PPV_ARGS(m_timestamp_query_heap.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("CreateQueryHeap() for timestamp failed with %08X", hr); Log_ErrorFmt("CreateQueryHeap() for timestamp failed with {:08X}", static_cast<unsigned>(hr));
m_features.gpu_timing = false; m_features.gpu_timing = false;
return false; return false;
} }
@ -669,7 +669,7 @@ bool D3D12Device::CreateTimestampQuery()
IID_PPV_ARGS(m_timestamp_query_buffer.GetAddressOf())); IID_PPV_ARGS(m_timestamp_query_buffer.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("CreateResource() for timestamp failed with %08X", hr); Log_ErrorFmt("CreateResource() for timestamp failed with {:08X}", static_cast<unsigned>(hr));
m_features.gpu_timing = false; m_features.gpu_timing = false;
return false; return false;
} }
@ -678,7 +678,7 @@ bool D3D12Device::CreateTimestampQuery()
hr = m_command_queue->GetTimestampFrequency(&frequency); hr = m_command_queue->GetTimestampFrequency(&frequency);
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("GetTimestampFrequency() failed: %08X", hr); Log_ErrorFmt("GetTimestampFrequency() failed: {:08X}", static_cast<unsigned>(hr));
m_features.gpu_timing = false; m_features.gpu_timing = false;
return false; return false;
} }
@ -860,7 +860,7 @@ bool D3D12Device::CreateSwapChain()
fs_desc.Scaling = fullscreen_mode.Scaling; fs_desc.Scaling = fullscreen_mode.Scaling;
fs_desc.Windowed = FALSE; fs_desc.Windowed = FALSE;
Log_VerbosePrintf("Creating a %dx%d exclusive fullscreen swap chain", fs_sd_desc.Width, fs_sd_desc.Height); Log_VerboseFmt("Creating a {}x{} exclusive fullscreen swap chain", fs_sd_desc.Width, fs_sd_desc.Height);
hr = m_dxgi_factory->CreateSwapChainForHwnd(m_command_queue.Get(), window_hwnd, &fs_sd_desc, &fs_desc, hr = m_dxgi_factory->CreateSwapChainForHwnd(m_command_queue.Get(), window_hwnd, &fs_sd_desc, &fs_desc,
fullscreen_output.Get(), m_swap_chain.ReleaseAndGetAddressOf()); fullscreen_output.Get(), m_swap_chain.ReleaseAndGetAddressOf());
if (FAILED(hr)) if (FAILED(hr))
@ -873,7 +873,7 @@ bool D3D12Device::CreateSwapChain()
if (!m_is_exclusive_fullscreen) if (!m_is_exclusive_fullscreen)
{ {
Log_VerbosePrintf("Creating a %dx%d windowed swap chain", swap_chain_desc.Width, swap_chain_desc.Height); Log_VerboseFmt("Creating a {}x{} windowed swap chain", swap_chain_desc.Width, swap_chain_desc.Height);
hr = m_dxgi_factory->CreateSwapChainForHwnd(m_command_queue.Get(), window_hwnd, &swap_chain_desc, nullptr, nullptr, hr = m_dxgi_factory->CreateSwapChainForHwnd(m_command_queue.Get(), window_hwnd, &swap_chain_desc, nullptr, nullptr,
m_swap_chain.ReleaseAndGetAddressOf()); m_swap_chain.ReleaseAndGetAddressOf());
} }
@ -908,7 +908,7 @@ bool D3D12Device::CreateSwapChainRTV()
hr = m_swap_chain->GetBuffer(i, IID_PPV_ARGS(backbuffer.GetAddressOf())); hr = m_swap_chain->GetBuffer(i, IID_PPV_ARGS(backbuffer.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("GetBuffer for RTV failed: 0x%08X", hr); Log_ErrorFmt("GetBuffer for RTV failed: 0x{:08X}", static_cast<unsigned>(hr));
DestroySwapChainRTVs(); DestroySwapChainRTVs();
return false; return false;
} }
@ -918,7 +918,7 @@ bool D3D12Device::CreateSwapChainRTV()
D3D12DescriptorHandle rtv; D3D12DescriptorHandle rtv;
if (!m_rtv_heap_manager.Allocate(&rtv)) if (!m_rtv_heap_manager.Allocate(&rtv))
{ {
Log_ErrorPrintf("Failed to allocate RTV handle"); Log_ErrorPrint("Failed to allocate RTV handle");
DestroySwapChainRTVs(); DestroySwapChainRTVs();
return false; return false;
} }
@ -930,7 +930,7 @@ bool D3D12Device::CreateSwapChainRTV()
m_window_info.surface_width = swap_chain_desc.BufferDesc.Width; m_window_info.surface_width = swap_chain_desc.BufferDesc.Width;
m_window_info.surface_height = swap_chain_desc.BufferDesc.Height; m_window_info.surface_height = swap_chain_desc.BufferDesc.Height;
m_window_info.surface_format = s_swap_chain_format; m_window_info.surface_format = s_swap_chain_format;
Log_VerbosePrintf("Swap chain buffer size: %ux%u", m_window_info.surface_width, m_window_info.surface_height); Log_VerboseFmt("Swap chain buffer size: {}x{}", m_window_info.surface_width, m_window_info.surface_height);
if (m_window_info.type == WindowInfo::Type::Win32) if (m_window_info.type == WindowInfo::Type::Win32)
{ {
@ -1014,7 +1014,7 @@ bool D3D12Device::UpdateWindow()
if (!CreateSwapChain()) if (!CreateSwapChain())
{ {
Log_ErrorPrintf("Failed to create swap chain on updated window"); Log_ErrorPrint("Failed to create swap chain on updated window");
return false; return false;
} }
@ -1040,7 +1040,7 @@ void D3D12Device::ResizeWindow(s32 new_window_width, s32 new_window_height, floa
HRESULT hr = m_swap_chain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, HRESULT hr = m_swap_chain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN,
m_using_allow_tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0); m_using_allow_tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0);
if (FAILED(hr)) if (FAILED(hr))
Log_ErrorPrintf("ResizeBuffers() failed: 0x%08X", hr); Log_ErrorFmt("ResizeBuffers() failed: 0x{:08X}", static_cast<unsigned>(hr));
if (!CreateSwapChainRTV()) if (!CreateSwapChainRTV())
Panic("Failed to recreate swap chain RTV after resize"); Panic("Failed to recreate swap chain RTV after resize");

View File

@ -231,7 +231,7 @@ std::unique_ptr<GPUPipeline> D3D12Device::CreatePipeline(const GPUPipeline::Grap
{ {
// E_INVALIDARG = not found. // E_INVALIDARG = not found.
if (hr != E_INVALIDARG) if (hr != E_INVALIDARG)
Log_ErrorPrintf("LoadGraphicsPipeline() failed with HRESULT %08X", hr); Log_ErrorFmt("LoadGraphicsPipeline() failed with HRESULT {:08X}", static_cast<unsigned>(hr));
// Need to create it normally. // Need to create it normally.
pipeline = gpb.Create(m_device.Get(), false); pipeline = gpb.Create(m_device.Get(), false);
@ -241,7 +241,7 @@ std::unique_ptr<GPUPipeline> D3D12Device::CreatePipeline(const GPUPipeline::Grap
{ {
hr = m_pipeline_library->StorePipeline(name.c_str(), pipeline.Get()); hr = m_pipeline_library->StorePipeline(name.c_str(), pipeline.Get());
if (FAILED(hr)) if (FAILED(hr))
Log_ErrorPrintf("StorePipeline() failed with HRESULT %08X", hr); Log_ErrorFmt("StorePipeline() failed with HRESULT {:08X}", static_cast<unsigned>(hr));
} }
} }
} }

View File

@ -36,18 +36,18 @@ bool D3D12StreamBuffer::Create(u32 size)
HRESULT hr = D3D12Device::GetInstance().GetAllocator()->CreateResource( HRESULT hr = D3D12Device::GetInstance().GetAllocator()->CreateResource(
&allocationDesc, &resource_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, allocation.ReleaseAndGetAddressOf(), &allocationDesc, &resource_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, allocation.ReleaseAndGetAddressOf(),
IID_PPV_ARGS(buffer.GetAddressOf())); IID_PPV_ARGS(buffer.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("CreateResource() failed: %08X", hr); Log_ErrorFmt("CreateResource() failed: {:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
static const D3D12_RANGE read_range = {}; static const D3D12_RANGE read_range = {};
u8* host_pointer; u8* host_pointer;
hr = buffer->Map(0, &read_range, reinterpret_cast<void**>(&host_pointer)); hr = buffer->Map(0, &read_range, reinterpret_cast<void**>(&host_pointer));
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Map() failed: %08X", hr); Log_ErrorFmt("Map() failed: {:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
@ -66,10 +66,10 @@ bool D3D12StreamBuffer::ReserveMemory(u32 num_bytes, u32 alignment)
const u32 required_bytes = num_bytes + alignment; const u32 required_bytes = num_bytes + alignment;
// Check for sane allocations // Check for sane allocations
if (num_bytes > m_size) if (num_bytes > m_size) [[unlikely]]
{ {
Log_ErrorPrintf("Attempting to allocate %u bytes from a %u byte stream buffer", static_cast<u32>(num_bytes), Log_ErrorFmt("Attempting to allocate {} bytes from a {} byte stream buffer", static_cast<u32>(num_bytes),
static_cast<u32>(m_size)); static_cast<u32>(m_size));
Panic("Stream buffer overflow"); Panic("Stream buffer overflow");
} }

View File

@ -115,11 +115,11 @@ std::unique_ptr<GPUTexture> D3D12Device::CreateTexture(u32 width, u32 height, u3
(type == GPUTexture::Type::RenderTarget || type == GPUTexture::Type::DepthStencil) ? &optimized_clear_value : (type == GPUTexture::Type::RenderTarget || type == GPUTexture::Type::DepthStencil) ? &optimized_clear_value :
nullptr, nullptr,
allocation.GetAddressOf(), IID_PPV_ARGS(resource.GetAddressOf())); allocation.GetAddressOf(), IID_PPV_ARGS(resource.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
// OOM isn't fatal. // OOM isn't fatal.
if (hr != E_OUTOFMEMORY) if (hr != E_OUTOFMEMORY)
Log_ErrorPrintf("Create texture failed: 0x%08X", hr); Log_ErrorFmt("Create texture failed: 0x{:08X}", static_cast<unsigned>(hr));
return {}; return {};
} }
@ -358,17 +358,17 @@ ID3D12Resource* D3D12Texture::AllocateUploadStagingBuffer(const void* data, u32
HRESULT hr = D3D12Device::GetInstance().GetAllocator()->CreateResource( HRESULT hr = D3D12Device::GetInstance().GetAllocator()->CreateResource(
&allocation_desc, &resource_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, allocation.GetAddressOf(), &allocation_desc, &resource_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, allocation.GetAddressOf(),
IID_PPV_ARGS(resource.GetAddressOf())); IID_PPV_ARGS(resource.GetAddressOf()));
if (FAILED(hr)) if (FAILED(hr))[[unlikely]]
{ {
Log_ErrorPrintf("CreateResource() failed with %08X", hr); Log_ErrorFmt("CreateResource() failed with {:08X}", static_cast<unsigned>(hr));
return nullptr; return nullptr;
} }
void* map_ptr; void* map_ptr;
hr = resource->Map(0, nullptr, &map_ptr); hr = resource->Map(0, nullptr, &map_ptr);
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_ErrorPrintf("Map() failed with %08X", hr); Log_ErrorFmt("Map() failed with {:08X}", static_cast<unsigned>(hr));
return nullptr; return nullptr;
} }
@ -419,9 +419,9 @@ bool D3D12Texture::Update(u32 x, u32 y, u32 width, u32 height, const void* data,
{ {
D3D12Device::GetInstance().SubmitCommandList(false, "While waiting for %u bytes in texture upload buffer", D3D12Device::GetInstance().SubmitCommandList(false, "While waiting for %u bytes in texture upload buffer",
required_size); required_size);
if (!sbuffer.ReserveMemory(required_size, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT)) if (!sbuffer.ReserveMemory(required_size, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to reserve texture upload memory (%u bytes).", required_size); Log_ErrorFmt("Failed to reserve texture upload memory ({} bytes).", required_size);
return false; return false;
} }
} }

View File

@ -124,7 +124,7 @@ std::vector<std::string> D3DCommon::GetAdapterNames(IDXGIFactory5* factory)
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("IDXGIFactory2::EnumAdapters() returned %08X", hr); Log_ErrorFmt("IDXGIFactory2::EnumAdapters() returned {:08X}", static_cast<unsigned>(hr));
continue; continue;
} }
@ -146,21 +146,21 @@ std::vector<std::string> D3DCommon::GetFullscreenModes(IDXGIFactory5* factory, s
Microsoft::WRL::ComPtr<IDXGIOutput> output; Microsoft::WRL::ComPtr<IDXGIOutput> output;
if (FAILED(hr = adapter->EnumOutputs(0, &output))) if (FAILED(hr = adapter->EnumOutputs(0, &output)))
{ {
Log_ErrorPrintf("EnumOutputs() failed: %08X", hr); Log_ErrorFmt("EnumOutputs() failed: {:08X}", static_cast<unsigned>(hr));
return modes; return modes;
} }
UINT num_modes = 0; UINT num_modes = 0;
if (FAILED(hr = output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &num_modes, nullptr))) if (FAILED(hr = output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &num_modes, nullptr)))
{ {
Log_ErrorPrintf("GetDisplayModeList() failed: %08X", hr); Log_ErrorFmt("GetDisplayModeList() failed: {:08X}", static_cast<unsigned>(hr));
return modes; return modes;
} }
std::vector<DXGI_MODE_DESC> dmodes(num_modes); std::vector<DXGI_MODE_DESC> dmodes(num_modes);
if (FAILED(hr = output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &num_modes, dmodes.data()))) if (FAILED(hr = output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &num_modes, dmodes.data())))
{ {
Log_ErrorPrintf("GetDisplayModeList() (2) failed: %08X", hr); Log_ErrorFmt("GetDisplayModeList() (2) failed: {:08X}", static_cast<unsigned>(hr));
return modes; return modes;
} }
@ -223,7 +223,7 @@ bool D3DCommon::GetRequestedExclusiveFullscreenModeDesc(IDXGIFactory5* factory,
{ {
if (!first_output) if (!first_output)
{ {
Log_ErrorPrintf("No DXGI output found. Can't use exclusive fullscreen."); Log_ErrorPrint("No DXGI output found. Can't use exclusive fullscreen.");
return false; return false;
} }
@ -241,7 +241,7 @@ bool D3DCommon::GetRequestedExclusiveFullscreenModeDesc(IDXGIFactory5* factory,
if (FAILED(hr = intersecting_output->FindClosestMatchingMode(&request_mode, fullscreen_mode, nullptr)) || if (FAILED(hr = intersecting_output->FindClosestMatchingMode(&request_mode, fullscreen_mode, nullptr)) ||
request_mode.Format != format) request_mode.Format != format)
{ {
Log_ErrorPrintf("Failed to find closest matching mode, hr=%08X", hr); Log_ErrorFmt("Failed to find closest matching mode, hr={:08X}", static_cast<unsigned>(hr));
return false; return false;
} }
@ -268,14 +268,14 @@ Microsoft::WRL::ComPtr<IDXGIAdapter1> D3DCommon::GetAdapterByName(IDXGIFactory5*
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("IDXGIFactory2::EnumAdapters() returned %08X"); Log_ErrorFmt("IDXGIFactory2::EnumAdapters() returned {:08X}", static_cast<unsigned>(hr));
continue; continue;
} }
std::string adapter_name = FixupDuplicateAdapterNames(adapter_names, GetAdapterName(adapter.Get())); std::string adapter_name = FixupDuplicateAdapterNames(adapter_names, GetAdapterName(adapter.Get()));
if (adapter_name == name) if (adapter_name == name)
{ {
Log_VerbosePrintf("Found adapter '%s'", adapter_name.c_str()); Log_VerboseFmt("Found adapter '{}'", adapter_name);
return adapter; return adapter;
} }
@ -291,7 +291,7 @@ Microsoft::WRL::ComPtr<IDXGIAdapter1> D3DCommon::GetFirstAdapter(IDXGIFactory5*
Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter; Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
HRESULT hr = factory->EnumAdapters1(0, adapter.GetAddressOf()); HRESULT hr = factory->EnumAdapters1(0, adapter.GetAddressOf());
if (FAILED(hr)) if (FAILED(hr))
Log_ErrorPrintf("IDXGIFactory2::EnumAdapters() for first adapter returned %08X", hr); Log_ErrorFmt("IDXGIFactory2::EnumAdapters() for first adapter returned {:08X}", static_cast<unsigned>(hr));
return adapter; return adapter;
} }
@ -317,7 +317,7 @@ std::string D3DCommon::GetAdapterName(IDXGIAdapter1* adapter)
} }
else else
{ {
Log_ErrorPrintf("IDXGIAdapter1::GetDesc() returned %08X", hr); Log_ErrorFmt("IDXGIAdapter1::GetDesc() returned {:08X}", static_cast<unsigned>(hr));
} }
if (ret.empty()) if (ret.empty())

View File

@ -64,7 +64,7 @@ bool DInputSource::Initialize(SettingsInterface& si, std::unique_lock<std::mutex
m_dinput_module = LoadLibraryW(L"dinput8"); m_dinput_module = LoadLibraryW(L"dinput8");
if (!m_dinput_module) if (!m_dinput_module)
{ {
Log_ErrorPrintf("Failed to load DInput module."); Log_ErrorPrint("Failed to load DInput module.");
return false; return false;
} }
@ -74,7 +74,7 @@ bool DInputSource::Initialize(SettingsInterface& si, std::unique_lock<std::mutex
reinterpret_cast<PFNGETDFDIJOYSTICK>(GetProcAddress(m_dinput_module, "GetdfDIJoystick")); reinterpret_cast<PFNGETDFDIJOYSTICK>(GetProcAddress(m_dinput_module, "GetdfDIJoystick"));
if (!create || !get_joystick_data_format) if (!create || !get_joystick_data_format)
{ {
Log_ErrorPrintf("Failed to get DInput function pointers."); Log_ErrorPrint("Failed to get DInput function pointers.");
return false; return false;
} }
@ -83,7 +83,7 @@ bool DInputSource::Initialize(SettingsInterface& si, std::unique_lock<std::mutex
m_joystick_data_format = get_joystick_data_format(); m_joystick_data_format = get_joystick_data_format();
if (FAILED(hr) || !m_joystick_data_format) if (FAILED(hr) || !m_joystick_data_format)
{ {
Log_ErrorPrintf("DirectInput8Create() failed: %08X", hr); Log_ErrorFmt("DirectInput8Create() failed: {}", static_cast<unsigned>(hr));
return false; return false;
} }
@ -94,7 +94,7 @@ bool DInputSource::Initialize(SettingsInterface& si, std::unique_lock<std::mutex
if (!toplevel_wi.has_value() || toplevel_wi->type != WindowInfo::Type::Win32) if (!toplevel_wi.has_value() || toplevel_wi->type != WindowInfo::Type::Win32)
{ {
Log_ErrorPrintf("Missing top level window, cannot add DInput devices."); Log_ErrorPrint("Missing top level window, cannot add DInput devices.");
return false; return false;
} }
@ -123,7 +123,7 @@ bool DInputSource::ReloadDevices()
std::vector<DIDEVICEINSTANCEW> devices; std::vector<DIDEVICEINSTANCEW> devices;
m_dinput->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumCallback, &devices, DIEDFL_ATTACHEDONLY); m_dinput->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumCallback, &devices, DIEDFL_ATTACHEDONLY);
Log_VerbosePrintf("Enumerated %zu devices", devices.size()); Log_VerboseFmt("Enumerated {} devices", devices.size());
bool changed = false; bool changed = false;
for (DIDEVICEINSTANCEW inst : devices) for (DIDEVICEINSTANCEW inst : devices)
@ -139,9 +139,11 @@ bool DInputSource::ReloadDevices()
ControllerData cd; ControllerData cd;
cd.guid = inst.guidInstance; cd.guid = inst.guidInstance;
HRESULT hr = m_dinput->CreateDevice(inst.guidInstance, cd.device.GetAddressOf(), nullptr); HRESULT hr = m_dinput->CreateDevice(inst.guidInstance, cd.device.GetAddressOf(), nullptr);
if (FAILED(hr)) if (FAILED(hr)) [[unlikely]]
{ {
Log_WarningPrintf("Failed to create instance of device [%s, %s]", inst.tszProductName, inst.tszInstanceName); Log_WarningFmt("Failed to create instance of device [{}, {}]",
StringUtil::WideStringToUTF8String(inst.tszProductName),
StringUtil::WideStringToUTF8String(inst.tszInstanceName));
continue; continue;
} }
@ -177,24 +179,24 @@ bool DInputSource::AddDevice(ControllerData& cd, const std::string& name)
hr = cd.device->SetCooperativeLevel(m_toplevel_window, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE); hr = cd.device->SetCooperativeLevel(m_toplevel_window, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE);
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("Failed to set cooperative level for '%s'", name.c_str()); Log_ErrorFmt("Failed to set cooperative level for '{}'", name);
return false; return false;
} }
Log_WarningPrintf("Failed to set exclusive mode for '%s'", name.c_str()); Log_WarningFmt("Failed to set exclusive mode for '{}'", name);
} }
hr = cd.device->SetDataFormat(m_joystick_data_format); hr = cd.device->SetDataFormat(m_joystick_data_format);
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("Failed to set data format for '%s'", name.c_str()); Log_ErrorFmt("Failed to set data format for '{}'", name);
return false; return false;
} }
hr = cd.device->Acquire(); hr = cd.device->Acquire();
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("Failed to acquire device '%s'", name.c_str()); Log_ErrorFmt("Failed to acquire device '{}'", name);
return false; return false;
} }
@ -203,7 +205,7 @@ bool DInputSource::AddDevice(ControllerData& cd, const std::string& name)
hr = cd.device->GetCapabilities(&caps); hr = cd.device->GetCapabilities(&caps);
if (FAILED(hr)) if (FAILED(hr))
{ {
Log_ErrorPrintf("Failed to get capabilities for '%s'", name.c_str()); Log_ErrorFmt("Failed to get capabilities for '{}'", name);
return false; return false;
} }
@ -237,14 +239,14 @@ bool DInputSource::AddDevice(ControllerData& cd, const std::string& name)
if (hr == DI_NOEFFECT) if (hr == DI_NOEFFECT)
cd.needs_poll = false; cd.needs_poll = false;
else if (hr != DI_OK) else if (hr != DI_OK)
Log_WarningPrintf("Polling device '%s' failed: %08X", name.c_str(), hr); Log_WarningFmt("Polling device '{}' failed: {:08X}", name, static_cast<unsigned>(hr));
hr = cd.device->GetDeviceState(sizeof(cd.last_state), &cd.last_state); hr = cd.device->GetDeviceState(sizeof(cd.last_state), &cd.last_state);
if (hr != DI_OK) if (hr != DI_OK)
Log_WarningPrintf("GetDeviceState() for '%s' failed: %08X", name.c_str(), hr); Log_WarningFmt("GetDeviceState() for '{}' failed: {:08X}", name, static_cast<unsigned>(hr));
Log_InfoPrintf("%s has %u buttons, %u axes, %u hats", name.c_str(), cd.num_buttons, Log_InfoFmt("{} has {} buttons, {} axes, {} hats", name, cd.num_buttons, static_cast<u32>(cd.axis_offsets.size()),
static_cast<u32>(cd.axis_offsets.size()), cd.num_hats); cd.num_hats);
return (cd.num_buttons > 0 || !cd.axis_offsets.empty() || cd.num_hats > 0); return (cd.num_buttons > 0 || !cd.axis_offsets.empty() || cd.num_hats > 0);
} }
@ -276,7 +278,7 @@ void DInputSource::PollEvents()
} }
else if (hr != DI_OK) else if (hr != DI_OK)
{ {
Log_WarningPrintf("GetDeviceState() failed: %08X", hr); Log_WarningFmt("GetDeviceState() failed: {:08X}", static_cast<unsigned>(hr));
i++; i++;
continue; continue;
} }

View File

@ -296,7 +296,7 @@ bool GPUDevice::Create(std::string_view adapter, std::string_view shader_cache_p
return false; return false;
} }
Log_InfoPrintf("Graphics Driver Info:\n%s", GetDriverInfo().c_str()); Log_InfoFmt("Graphics Driver Info:\n{}", GetDriverInfo());
OpenShaderCache(shader_cache_path, shader_cache_version); OpenShaderCache(shader_cache_path, shader_cache_version);
@ -332,9 +332,9 @@ void GPUDevice::OpenShaderCache(std::string_view base_path, u32 version)
const std::string filename = Path::Combine(base_path, basename); const std::string filename = Path::Combine(base_path, basename);
if (!m_shader_cache.Open(filename.c_str(), version)) if (!m_shader_cache.Open(filename.c_str(), version))
{ {
Log_WarningPrintf("Failed to open shader cache. Creating new cache."); Log_WarningPrint("Failed to open shader cache. Creating new cache.");
if (!m_shader_cache.Create()) if (!m_shader_cache.Create())
Log_ErrorPrintf("Failed to create new shader cache."); Log_ErrorPrint("Failed to create new shader cache.");
// Squish the pipeline cache too, it's going to be stale. // Squish the pipeline cache too, it's going to be stale.
if (m_features.pipeline_cache) if (m_features.pipeline_cache)
@ -343,7 +343,7 @@ void GPUDevice::OpenShaderCache(std::string_view base_path, u32 version)
Path::Combine(base_path, TinyString::from_format("{}.bin", GetShaderCacheBaseName("pipelines"))); Path::Combine(base_path, TinyString::from_format("{}.bin", GetShaderCacheBaseName("pipelines")));
if (FileSystem::FileExists(pc_filename.c_str())) if (FileSystem::FileExists(pc_filename.c_str()))
{ {
Log_InfoPrintf("Removing old pipeline cache '%s'", pc_filename.c_str()); Log_InfoFmt("Removing old pipeline cache '{}'", Path::GetFileName(pc_filename));
FileSystem::DeleteFile(pc_filename.c_str()); FileSystem::DeleteFile(pc_filename.c_str());
} }
} }
@ -363,7 +363,7 @@ void GPUDevice::OpenShaderCache(std::string_view base_path, u32 version)
if (ReadPipelineCache(filename)) if (ReadPipelineCache(filename))
s_pipeline_cache_path = std::move(filename); s_pipeline_cache_path = std::move(filename);
else else
Log_WarningPrintf("Failed to read pipeline cache."); Log_WarningPrint("Failed to read pipeline cache.");
} }
} }
@ -380,13 +380,14 @@ void GPUDevice::CloseShaderCache()
FILESYSTEM_STAT_DATA sd; FILESYSTEM_STAT_DATA sd;
if (!FileSystem::StatFile(s_pipeline_cache_path.c_str(), &sd) || sd.Size != static_cast<s64>(data.size())) if (!FileSystem::StatFile(s_pipeline_cache_path.c_str(), &sd) || sd.Size != static_cast<s64>(data.size()))
{ {
Log_InfoPrintf("Writing %zu bytes to '%s'", data.size(), s_pipeline_cache_path.c_str()); Log_InfoFmt("Writing {} bytes to '{}'", data.size(), Path::GetFileName(s_pipeline_cache_path));
if (!FileSystem::WriteBinaryFile(s_pipeline_cache_path.c_str(), data.data(), data.size())) if (!FileSystem::WriteBinaryFile(s_pipeline_cache_path.c_str(), data.data(), data.size()))
Log_ErrorPrintf("Failed to write pipeline cache to '%s'", s_pipeline_cache_path.c_str()); Log_ErrorFmt("Failed to write pipeline cache to '{}'", Path::GetFileName(s_pipeline_cache_path));
} }
else else
{ {
Log_InfoPrintf("Skipping updating pipeline cache '%s' due to no changes.", s_pipeline_cache_path.c_str()); Log_InfoFmt("Skipping updating pipeline cache '{}' due to no changes.",
Path::GetFileName(s_pipeline_cache_path));
} }
} }
@ -454,7 +455,7 @@ bool GPUDevice::AcquireWindow(bool recreate_window)
if (!wi.has_value()) if (!wi.has_value())
return false; return false;
Log_InfoPrintf("Render window is %ux%u.", wi->surface_width, wi->surface_height); Log_InfoFmt("Render window is {}x{}.", wi->surface_width, wi->surface_height);
m_window_info = wi.value(); m_window_info = wi.value();
return true; return true;
} }
@ -505,7 +506,7 @@ bool GPUDevice::CreateResources()
m_imgui_pipeline = CreatePipeline(plconfig); m_imgui_pipeline = CreatePipeline(plconfig);
if (!m_imgui_pipeline) if (!m_imgui_pipeline)
{ {
Log_ErrorPrintf("Failed to compile ImGui pipeline."); Log_ErrorPrint("Failed to compile ImGui pipeline.");
return false; return false;
} }
GL_OBJECT_NAME(m_imgui_pipeline, "ImGui Pipeline"); GL_OBJECT_NAME(m_imgui_pipeline, "ImGui Pipeline");
@ -665,7 +666,7 @@ std::unique_ptr<GPUShader> GPUDevice::CreateShader(GPUShaderStage stage, std::st
if (shader) if (shader)
return shader; return shader;
Log_ErrorPrintf("Failed to create shader from binary (driver changed?). Clearing cache."); Log_ErrorPrint("Failed to create shader from binary (driver changed?). Clearing cache.");
m_shader_cache.Clear(); m_shader_cache.Clear();
} }

View File

@ -1,4 +1,4 @@
// SPDX-FileCopyrightText: 2023 Connor McLaughlin <stenzek@gmail.com> // SPDX-FileCopyrightText: 2023-2024 Connor McLaughlin <stenzek@gmail.com>
// SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0) // SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)
#include "gpu_shader_cache.h" #include "gpu_shader_cache.h"
@ -8,6 +8,7 @@
#include "common/heap_array.h" #include "common/heap_array.h"
#include "common/log.h" #include "common/log.h"
#include "common/md5_digest.h" #include "common/md5_digest.h"
#include "common/path.h"
#include "fmt/format.h" #include "fmt/format.h"
@ -97,7 +98,7 @@ void GPUShaderCache::Clear()
Close(); Close();
Log_WarningPrintf("Clearing shader cache at %s.", m_base_filename.c_str()); Log_WarningFmt("Clearing shader cache at {}.", Path::GetFileName(m_base_filename));
const std::string index_filename = fmt::format("{}.idx", m_base_filename); const std::string index_filename = fmt::format("{}.idx", m_base_filename);
const std::string blob_filename = fmt::format("{}.bin", m_base_filename); const std::string blob_filename = fmt::format("{}.bin", m_base_filename);
@ -108,25 +109,25 @@ bool GPUShaderCache::CreateNew(const std::string& index_filename, const std::str
{ {
if (FileSystem::FileExists(index_filename.c_str())) if (FileSystem::FileExists(index_filename.c_str()))
{ {
Log_WarningPrintf("Removing existing index file '%s'", index_filename.c_str()); Log_WarningFmt("Removing existing index file '{}'", Path::GetFileName(index_filename));
FileSystem::DeleteFile(index_filename.c_str()); FileSystem::DeleteFile(index_filename.c_str());
} }
if (FileSystem::FileExists(blob_filename.c_str())) if (FileSystem::FileExists(blob_filename.c_str()))
{ {
Log_WarningPrintf("Removing existing blob file '%s'", blob_filename.c_str()); Log_WarningFmt("Removing existing blob file '{}'", Path::GetFileName(blob_filename));
FileSystem::DeleteFile(blob_filename.c_str()); FileSystem::DeleteFile(blob_filename.c_str());
} }
m_index_file = FileSystem::OpenCFile(index_filename.c_str(), "wb"); m_index_file = FileSystem::OpenCFile(index_filename.c_str(), "wb");
if (!m_index_file) if (!m_index_file) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to open index file '%s' for writing", index_filename.c_str()); Log_ErrorFmt("Failed to open index file '{}' for writing", Path::GetFileName(index_filename));
return false; return false;
} }
if (std::fwrite(&m_version, sizeof(m_version), 1, m_index_file) != 1) if (std::fwrite(&m_version, sizeof(m_version), 1, m_index_file) != 1) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to write version to index file '%s'", index_filename.c_str()); Log_ErrorFmt("Failed to write version to index file '{}'", Path::GetFileName(index_filename));
std::fclose(m_index_file); std::fclose(m_index_file);
m_index_file = nullptr; m_index_file = nullptr;
FileSystem::DeleteFile(index_filename.c_str()); FileSystem::DeleteFile(index_filename.c_str());
@ -134,9 +135,9 @@ bool GPUShaderCache::CreateNew(const std::string& index_filename, const std::str
} }
m_blob_file = FileSystem::OpenCFile(blob_filename.c_str(), "w+b"); m_blob_file = FileSystem::OpenCFile(blob_filename.c_str(), "w+b");
if (!m_blob_file) if (!m_blob_file) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to open blob file '%s' for writing", blob_filename.c_str()); Log_ErrorFmt("Failed to open blob file '{}' for writing", Path::GetFileName(blob_filename));
std::fclose(m_index_file); std::fclose(m_index_file);
m_index_file = nullptr; m_index_file = nullptr;
FileSystem::DeleteFile(index_filename.c_str()); FileSystem::DeleteFile(index_filename.c_str());
@ -155,7 +156,7 @@ bool GPUShaderCache::ReadExisting(const std::string& index_filename, const std::
// we don't want to blow away the cache. so just continue without a cache. // we don't want to blow away the cache. so just continue without a cache.
if (errno == EACCES) if (errno == EACCES)
{ {
Log_WarningPrintf("Failed to open shader cache index with EACCES, are you running two instances?"); Log_WarningPrint("Failed to open shader cache index with EACCES, are you running two instances?");
return true; return true;
} }
@ -163,18 +164,18 @@ bool GPUShaderCache::ReadExisting(const std::string& index_filename, const std::
} }
u32 file_version = 0; u32 file_version = 0;
if (std::fread(&file_version, sizeof(file_version), 1, m_index_file) != 1 || file_version != m_version) if (std::fread(&file_version, sizeof(file_version), 1, m_index_file) != 1 || file_version != m_version) [[unlikely]]
{ {
Log_ErrorPrintf("Bad file/data version in '%s'", index_filename.c_str()); Log_ErrorFmt("Bad file/data version in '{}'", Path::GetFileName(index_filename));
std::fclose(m_index_file); std::fclose(m_index_file);
m_index_file = nullptr; m_index_file = nullptr;
return false; return false;
} }
m_blob_file = FileSystem::OpenCFile(blob_filename.c_str(), "a+b"); m_blob_file = FileSystem::OpenCFile(blob_filename.c_str(), "a+b");
if (!m_blob_file) if (!m_blob_file) [[unlikely]]
{ {
Log_ErrorPrintf("Blob file '%s' is missing", blob_filename.c_str()); Log_ErrorFmt("Blob file '{}' is missing", Path::GetFileName(blob_filename));
std::fclose(m_index_file); std::fclose(m_index_file);
m_index_file = nullptr; m_index_file = nullptr;
return false; return false;
@ -187,12 +188,12 @@ bool GPUShaderCache::ReadExisting(const std::string& index_filename, const std::
{ {
CacheIndexEntry entry; CacheIndexEntry entry;
if (std::fread(&entry, sizeof(entry), 1, m_index_file) != 1 || if (std::fread(&entry, sizeof(entry), 1, m_index_file) != 1 ||
(entry.file_offset + entry.compressed_size) > blob_file_size) (entry.file_offset + entry.compressed_size) > blob_file_size) [[unlikely]]
{ {
if (std::feof(m_index_file)) if (std::feof(m_index_file))
break; break;
Log_ErrorPrintf("Failed to read entry from '%s', corrupt file?", index_filename.c_str()); Log_ErrorFmt("Failed to read entry from '{}', corrupt file?", Path::GetFileName(index_filename));
m_index.clear(); m_index.clear();
std::fclose(m_blob_file); std::fclose(m_blob_file);
m_blob_file = nullptr; m_blob_file = nullptr;
@ -210,7 +211,7 @@ bool GPUShaderCache::ReadExisting(const std::string& index_filename, const std::
// ensure we don't write before seeking // ensure we don't write before seeking
std::fseek(m_index_file, 0, SEEK_END); std::fseek(m_index_file, 0, SEEK_END);
Log_DevPrintf("Read %zu entries from '%s'", m_index.size(), index_filename.c_str()); Log_DevFmt("Read {} entries from '{}'", m_index.size(), Path::GetFileName(index_filename));
return true; return true;
} }
@ -257,18 +258,18 @@ bool GPUShaderCache::Lookup(const CacheIndexKey& key, ShaderBinary* binary)
DynamicHeapArray<u8> compressed_data(iter->second.compressed_size); DynamicHeapArray<u8> compressed_data(iter->second.compressed_size);
if (std::fseek(m_blob_file, iter->second.file_offset, SEEK_SET) != 0 || if (std::fseek(m_blob_file, iter->second.file_offset, SEEK_SET) != 0 ||
std::fread(compressed_data.data(), iter->second.compressed_size, 1, m_blob_file) != 1) std::fread(compressed_data.data(), iter->second.compressed_size, 1, m_blob_file) != 1) [[unlikely]]
{ {
Log_ErrorPrintf("Read %u byte %s shader from file failed", iter->second.compressed_size, Log_ErrorFmt("Read {} byte {} shader from file failed", iter->second.compressed_size,
GPUShader::GetStageName(static_cast<GPUShaderStage>(key.shader_type))); GPUShader::GetStageName(static_cast<GPUShaderStage>(key.shader_type)));
return false; return false;
} }
const size_t decompress_result = const size_t decompress_result =
ZSTD_decompress(binary->data(), binary->size(), compressed_data.data(), compressed_data.size()); ZSTD_decompress(binary->data(), binary->size(), compressed_data.data(), compressed_data.size());
if (ZSTD_isError(decompress_result)) if (ZSTD_isError(decompress_result)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to decompress shader: %s", ZSTD_getErrorName(decompress_result)); Log_ErrorFmt("Failed to decompress shader: {}", ZSTD_getErrorName(decompress_result));
return false; return false;
} }
@ -279,9 +280,9 @@ bool GPUShaderCache::Insert(const CacheIndexKey& key, const void* data, u32 data
{ {
DynamicHeapArray<u8> compress_buffer(ZSTD_compressBound(data_size)); DynamicHeapArray<u8> compress_buffer(ZSTD_compressBound(data_size));
const size_t compress_result = ZSTD_compress(compress_buffer.data(), compress_buffer.size(), data, data_size, 0); const size_t compress_result = ZSTD_compress(compress_buffer.data(), compress_buffer.size(), data, data_size, 0);
if (ZSTD_isError(compress_result)) if (ZSTD_isError(compress_result)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to compress shader: %s", ZSTD_getErrorName(compress_result)); Log_ErrorFmt("Failed to compress shader: {}", ZSTD_getErrorName(compress_result));
return false; return false;
} }
@ -305,16 +306,15 @@ bool GPUShaderCache::Insert(const CacheIndexKey& key, const void* data, u32 data
entry.uncompressed_size = idata.uncompressed_size; entry.uncompressed_size = idata.uncompressed_size;
if (std::fwrite(compress_buffer.data(), compress_result, 1, m_blob_file) != 1 || std::fflush(m_blob_file) != 0 || if (std::fwrite(compress_buffer.data(), compress_result, 1, m_blob_file) != 1 || std::fflush(m_blob_file) != 0 ||
std::fwrite(&entry, sizeof(entry), 1, m_index_file) != 1 || std::fflush(m_index_file) != 0) std::fwrite(&entry, sizeof(entry), 1, m_index_file) != 1 || std::fflush(m_index_file) != 0) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to write %u byte %s shader blob to file", data_size, Log_ErrorFmt("Failed to write {} byte {} shader blob to file", data_size,
GPUShader::GetStageName(static_cast<GPUShaderStage>(key.shader_type))); GPUShader::GetStageName(static_cast<GPUShaderStage>(key.shader_type)));
return false; return false;
} }
Log_DevPrintf("Cached compressed %s shader: %u -> %u bytes", Log_DevFmt("Cached compressed {} shader: {} -> {} bytes",
GPUShader::GetStageName(static_cast<GPUShaderStage>(key.shader_type)), data_size, GPUShader::GetStageName(static_cast<GPUShaderStage>(key.shader_type)), data_size, compress_result);
static_cast<u32>(compress_result));
m_index.emplace(key, idata); m_index.emplace(key, idata);
return true; return true;
} }

View File

@ -190,40 +190,39 @@ bool GPUTexture::ValidateConfig(u32 width, u32 height, u32 layers, u32 levels, u
{ {
if (width > MAX_WIDTH || height > MAX_HEIGHT || layers > MAX_LAYERS || levels > MAX_LEVELS || samples > MAX_SAMPLES) if (width > MAX_WIDTH || height > MAX_HEIGHT || layers > MAX_LAYERS || levels > MAX_LEVELS || samples > MAX_SAMPLES)
{ {
Log_ErrorPrintf("Invalid dimensions: %ux%ux%u %u %u.", width, height, layers, levels, samples); Log_ErrorFmt("Invalid dimensions: {}x{}x{} {} {}.", width, height, layers, levels, samples);
return false; return false;
} }
const u32 max_texture_size = g_gpu_device->GetMaxTextureSize(); const u32 max_texture_size = g_gpu_device->GetMaxTextureSize();
if (width > max_texture_size || height > max_texture_size) if (width > max_texture_size || height > max_texture_size)
{ {
Log_ErrorPrintf("Texture width (%u) or height (%u) exceeds max texture size (%u).", width, height, Log_ErrorFmt("Texture width ({}) or height ({}) exceeds max texture size ({}).", width, height, max_texture_size);
max_texture_size);
return false; return false;
} }
const u32 max_samples = g_gpu_device->GetMaxMultisamples(); const u32 max_samples = g_gpu_device->GetMaxMultisamples();
if (samples > max_samples) if (samples > max_samples)
{ {
Log_ErrorPrintf("Texture samples (%u) exceeds max samples (%u).", samples, max_samples); Log_ErrorFmt("Texture samples ({}) exceeds max samples ({}).", samples, max_samples);
return false; return false;
} }
if (samples > 1 && levels > 1) if (samples > 1 && levels > 1)
{ {
Log_ErrorPrintf("Multisampled textures can't have mip levels."); Log_ErrorPrint("Multisampled textures can't have mip levels.");
return false; return false;
} }
if (layers > 1 && type != Type::Texture && type != Type::DynamicTexture) if (layers > 1 && type != Type::Texture && type != Type::DynamicTexture)
{ {
Log_ErrorPrintf("Texture arrays are not supported on targets."); Log_ErrorPrint("Texture arrays are not supported on targets.");
return false; return false;
} }
if (levels > 1 && type != Type::Texture && type != Type::DynamicTexture) if (levels > 1 && type != Type::Texture && type != Type::DynamicTexture)
{ {
Log_ErrorPrintf("Mipmaps are not supported on targets."); Log_ErrorPrint("Mipmaps are not supported on targets.");
return false; return false;
} }
@ -318,7 +317,7 @@ bool GPUTexture::ConvertTextureDataToRGBA8(u32 width, u32 height, std::vector<u3
} }
default: default:
Log_ErrorPrintf("Unknown pixel format %u", static_cast<u32>(format)); [[unlikely]] Log_ErrorFmt("Unknown pixel format {}", static_cast<u32>(format));
return false; return false;
} }
} }

View File

@ -179,7 +179,7 @@ bool HTTPDownloaderCurl::StartRequest(HTTPDownloader::Request* request)
curl_easy_setopt(req->handle, CURLOPT_POSTFIELDS, request->post_data.c_str()); curl_easy_setopt(req->handle, CURLOPT_POSTFIELDS, request->post_data.c_str());
} }
Log_DevPrintf("Started HTTP request for '%s'", req->url.c_str()); Log_DevFmt("Started HTTP request for '{}'", req->url);
req->state.store(Request::State::Started, std::memory_order_release); req->state.store(Request::State::Started, std::memory_order_release);
req->start_time = Common::Timer::GetCurrentValue(); req->start_time = Common::Timer::GetCurrentValue();

View File

@ -42,7 +42,7 @@ bool HTTPDownloaderWinHttp::Initialize(std::string user_agent)
WINHTTP_FLAG_ASYNC); WINHTTP_FLAG_ASYNC);
if (m_hSession == NULL) if (m_hSession == NULL)
{ {
Log_ErrorPrintf("WinHttpOpen() failed: %u", GetLastError()); Log_ErrorFmt("WinHttpOpen() failed: {}", GetLastError());
return false; return false;
} }
@ -51,7 +51,7 @@ bool HTTPDownloaderWinHttp::Initialize(std::string user_agent)
if (WinHttpSetStatusCallback(m_hSession, HTTPStatusCallback, notification_flags, NULL) == if (WinHttpSetStatusCallback(m_hSession, HTTPStatusCallback, notification_flags, NULL) ==
WINHTTP_INVALID_STATUS_CALLBACK) WINHTTP_INVALID_STATUS_CALLBACK)
{ {
Log_ErrorPrintf("WinHttpSetStatusCallback() failed: %u", GetLastError()); Log_ErrorFmt("WinHttpSetStatusCallback() failed: {}", GetLastError());
return false; return false;
} }
@ -89,17 +89,17 @@ void CALLBACK HTTPDownloaderWinHttp::HTTPStatusCallback(HINTERNET hRequest, DWOR
case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
{ {
const WINHTTP_ASYNC_RESULT* res = reinterpret_cast<const WINHTTP_ASYNC_RESULT*>(lpvStatusInformation); const WINHTTP_ASYNC_RESULT* res = reinterpret_cast<const WINHTTP_ASYNC_RESULT*>(lpvStatusInformation);
Log_ErrorPrintf("WinHttp async function %p returned error %u", res->dwResult, res->dwError); Log_ErrorFmt("WinHttp async function {} returned error {}", res->dwResult, res->dwError);
req->status_code = HTTP_STATUS_ERROR; req->status_code = HTTP_STATUS_ERROR;
req->state.store(Request::State::Complete); req->state.store(Request::State::Complete);
return; return;
} }
case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
{ {
Log_DevPrintf("SendRequest complete"); Log_DevPrint("SendRequest complete");
if (!WinHttpReceiveResponse(hRequest, nullptr)) if (!WinHttpReceiveResponse(hRequest, nullptr))
{ {
Log_ErrorPrintf("WinHttpReceiveResponse() failed: %u", GetLastError()); Log_ErrorFmt("WinHttpReceiveResponse() failed: {}", GetLastError());
req->status_code = HTTP_STATUS_ERROR; req->status_code = HTTP_STATUS_ERROR;
req->state.store(Request::State::Complete); req->state.store(Request::State::Complete);
} }
@ -108,13 +108,13 @@ void CALLBACK HTTPDownloaderWinHttp::HTTPStatusCallback(HINTERNET hRequest, DWOR
} }
case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
{ {
Log_DevPrintf("Headers available"); Log_DevPrint("Headers available");
DWORD buffer_size = sizeof(req->status_code); DWORD buffer_size = sizeof(req->status_code);
if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &req->status_code, &buffer_size, WINHTTP_NO_HEADER_INDEX)) WINHTTP_HEADER_NAME_BY_INDEX, &req->status_code, &buffer_size, WINHTTP_NO_HEADER_INDEX))
{ {
Log_ErrorPrintf("WinHttpQueryHeaders() for status code failed: %u", GetLastError()); Log_ErrorFmt("WinHttpQueryHeaders() for status code failed: {}", GetLastError());
req->status_code = HTTP_STATUS_ERROR; req->status_code = HTTP_STATUS_ERROR;
req->state.store(Request::State::Complete); req->state.store(Request::State::Complete);
return; return;
@ -126,7 +126,7 @@ void CALLBACK HTTPDownloaderWinHttp::HTTPStatusCallback(HINTERNET hRequest, DWOR
WINHTTP_NO_HEADER_INDEX)) WINHTTP_NO_HEADER_INDEX))
{ {
if (GetLastError() != ERROR_WINHTTP_HEADER_NOT_FOUND) if (GetLastError() != ERROR_WINHTTP_HEADER_NOT_FOUND)
Log_WarningPrintf("WinHttpQueryHeaders() for content length failed: %u", GetLastError()); Log_WarningFmt("WinHttpQueryHeaders() for content length failed: {}", GetLastError());
req->content_length = 0; req->content_length = 0;
} }
@ -145,14 +145,14 @@ void CALLBACK HTTPDownloaderWinHttp::HTTPStatusCallback(HINTERNET hRequest, DWOR
} }
} }
Log_DevPrintf("Status code %d, content-length is %u", req->status_code, req->content_length); Log_DevFmt("Status code {}, content-length is {}", req->status_code, req->content_length);
req->data.reserve(req->content_length); req->data.reserve(req->content_length);
req->state = Request::State::Receiving; req->state = Request::State::Receiving;
// start reading // start reading
if (!WinHttpQueryDataAvailable(hRequest, nullptr) && GetLastError() != ERROR_IO_PENDING) if (!WinHttpQueryDataAvailable(hRequest, nullptr) && GetLastError() != ERROR_IO_PENDING)
{ {
Log_ErrorPrintf("WinHttpQueryDataAvailable() failed: %u", GetLastError()); Log_ErrorFmt("WinHttpQueryDataAvailable() failed: {}", GetLastError());
req->status_code = HTTP_STATUS_ERROR; req->status_code = HTTP_STATUS_ERROR;
req->state.store(Request::State::Complete); req->state.store(Request::State::Complete);
} }
@ -166,19 +166,19 @@ void CALLBACK HTTPDownloaderWinHttp::HTTPStatusCallback(HINTERNET hRequest, DWOR
if (bytes_available == 0) if (bytes_available == 0)
{ {
// end of request // end of request
Log_DevPrintf("End of request '%s', %zu bytes received", req->url.c_str(), req->data.size()); Log_DevFmt("End of request '{}', {} bytes received", req->url, req->data.size());
req->state.store(Request::State::Complete); req->state.store(Request::State::Complete);
return; return;
} }
// start the transfer // start the transfer
Log_DevPrintf("%u bytes available", bytes_available); Log_DevFmt("{} bytes available", bytes_available);
req->io_position = static_cast<u32>(req->data.size()); req->io_position = static_cast<u32>(req->data.size());
req->data.resize(req->io_position + bytes_available); req->data.resize(req->io_position + bytes_available);
if (!WinHttpReadData(hRequest, req->data.data() + req->io_position, bytes_available, nullptr) && if (!WinHttpReadData(hRequest, req->data.data() + req->io_position, bytes_available, nullptr) &&
GetLastError() != ERROR_IO_PENDING) GetLastError() != ERROR_IO_PENDING)
{ {
Log_ErrorPrintf("WinHttpReadData() failed: %u", GetLastError()); Log_ErrorFmt("WinHttpReadData() failed: {}", GetLastError());
req->status_code = HTTP_STATUS_ERROR; req->status_code = HTTP_STATUS_ERROR;
req->state.store(Request::State::Complete); req->state.store(Request::State::Complete);
} }
@ -187,7 +187,7 @@ void CALLBACK HTTPDownloaderWinHttp::HTTPStatusCallback(HINTERNET hRequest, DWOR
} }
case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
{ {
Log_DevPrintf("Read of %u complete", dwStatusInformationLength); Log_DevFmt("Read of {} complete", dwStatusInformationLength);
const u32 new_size = req->io_position + dwStatusInformationLength; const u32 new_size = req->io_position + dwStatusInformationLength;
Assert(new_size <= req->data.size()); Assert(new_size <= req->data.size());
@ -196,7 +196,7 @@ void CALLBACK HTTPDownloaderWinHttp::HTTPStatusCallback(HINTERNET hRequest, DWOR
if (!WinHttpQueryDataAvailable(hRequest, nullptr) && GetLastError() != ERROR_IO_PENDING) if (!WinHttpQueryDataAvailable(hRequest, nullptr) && GetLastError() != ERROR_IO_PENDING)
{ {
Log_ErrorPrintf("WinHttpQueryDataAvailable() failed: %u", GetLastError()); Log_ErrorFmt("WinHttpQueryDataAvailable() failed: {}", GetLastError());
req->status_code = HTTP_STATUS_ERROR; req->status_code = HTTP_STATUS_ERROR;
req->state.store(Request::State::Complete); req->state.store(Request::State::Complete);
} }
@ -238,7 +238,7 @@ bool HTTPDownloaderWinHttp::StartRequest(HTTPDownloader::Request* request)
const std::wstring url_wide(StringUtil::UTF8StringToWideString(req->url)); const std::wstring url_wide(StringUtil::UTF8StringToWideString(req->url));
if (!WinHttpCrackUrl(url_wide.c_str(), static_cast<DWORD>(url_wide.size()), 0, &uc)) if (!WinHttpCrackUrl(url_wide.c_str(), static_cast<DWORD>(url_wide.size()), 0, &uc))
{ {
Log_ErrorPrintf("WinHttpCrackUrl() failed: %u", GetLastError()); Log_ErrorFmt("WinHttpCrackUrl() failed: {}", GetLastError());
req->callback(HTTP_STATUS_ERROR, std::string(), req->data); req->callback(HTTP_STATUS_ERROR, std::string(), req->data);
delete req; delete req;
return false; return false;
@ -250,7 +250,7 @@ bool HTTPDownloaderWinHttp::StartRequest(HTTPDownloader::Request* request)
req->hConnection = WinHttpConnect(m_hSession, host_name.c_str(), uc.nPort, 0); req->hConnection = WinHttpConnect(m_hSession, host_name.c_str(), uc.nPort, 0);
if (!req->hConnection) if (!req->hConnection)
{ {
Log_ErrorPrintf("Failed to start HTTP request for '%s': %u", req->url.c_str(), GetLastError()); Log_ErrorFmt("Failed to start HTTP request for '{}': {}", req->url, GetLastError());
req->callback(HTTP_STATUS_ERROR, std::string(), req->data); req->callback(HTTP_STATUS_ERROR, std::string(), req->data);
delete req; delete req;
return false; return false;
@ -262,7 +262,7 @@ bool HTTPDownloaderWinHttp::StartRequest(HTTPDownloader::Request* request)
req->object_name.c_str(), NULL, NULL, NULL, request_flags); req->object_name.c_str(), NULL, NULL, NULL, request_flags);
if (!req->hRequest) if (!req->hRequest)
{ {
Log_ErrorPrintf("WinHttpOpenRequest() failed: %u", GetLastError()); Log_ErrorFmt("WinHttpOpenRequest() failed: {}", GetLastError());
WinHttpCloseHandle(req->hConnection); WinHttpCloseHandle(req->hConnection);
return false; return false;
} }
@ -283,12 +283,12 @@ bool HTTPDownloaderWinHttp::StartRequest(HTTPDownloader::Request* request)
if (!result && GetLastError() != ERROR_IO_PENDING) if (!result && GetLastError() != ERROR_IO_PENDING)
{ {
Log_ErrorPrintf("WinHttpSendRequest() failed: %u", GetLastError()); Log_ErrorFmt("WinHttpSendRequest() failed: {}", GetLastError());
req->status_code = HTTP_STATUS_ERROR; req->status_code = HTTP_STATUS_ERROR;
req->state.store(Request::State::Complete); req->state.store(Request::State::Complete);
} }
Log_DevPrintf("Started HTTP request for '%s'", req->url.c_str()); Log_DevFmt("Started HTTP request for '{}'", req->url);
req->state = Request::State::Started; req->state = Request::State::Started;
req->start_time = Common::Timer::GetCurrentValue(); req->start_time = Common::Timer::GetCurrentValue();
return true; return true;

View File

@ -219,7 +219,7 @@ bool ImGuiFullscreen::Initialize(const char* placeholder_image_path)
s_placeholder_texture = LoadTexture(placeholder_image_path); s_placeholder_texture = LoadTexture(placeholder_image_path);
if (!s_placeholder_texture) if (!s_placeholder_texture)
{ {
Log_ErrorPrintf("Missing placeholder texture '%s', cannot continue", placeholder_image_path); Log_ErrorFmt("Missing placeholder texture '{}', cannot continue", placeholder_image_path);
return false; return false;
} }

View File

@ -686,9 +686,9 @@ void Host::AddOSDMessage(std::string message, float duration /*= 2.0f*/)
void Host::AddKeyedOSDMessage(std::string key, std::string message, float duration /* = 2.0f */) void Host::AddKeyedOSDMessage(std::string key, std::string message, float duration /* = 2.0f */)
{ {
if (!key.empty()) if (!key.empty())
Log_InfoPrintf("OSD [%s]: %s", key.c_str(), message.c_str()); Log_InfoFmt("OSD [{}]: {}", key, message);
else else
Log_InfoPrintf("OSD: %s", message.c_str()); Log_InfoFmt("OSD: {}", message);
if (!ImGuiManager::s_show_osd_messages) if (!ImGuiManager::s_show_osd_messages)
return; return;
@ -1045,7 +1045,7 @@ void ImGuiManager::UpdateSoftwareCursorTexture(u32 index)
RGBA8Image image; RGBA8Image image;
if (!image.LoadFromFile(sc.image_path.c_str())) if (!image.LoadFromFile(sc.image_path.c_str()))
{ {
Log_ErrorPrintf("Failed to load software cursor %u image '%s'", index, sc.image_path.c_str()); Log_ErrorFmt("Failed to load software cursor {} image '{}'", index, sc.image_path);
return; return;
} }
g_gpu_device->RecycleTexture(std::move(sc.texture)); g_gpu_device->RecycleTexture(std::move(sc.texture));
@ -1053,8 +1053,8 @@ void ImGuiManager::UpdateSoftwareCursorTexture(u32 index)
GPUTexture::Format::RGBA8, image.GetPixels(), image.GetPitch()); GPUTexture::Format::RGBA8, image.GetPixels(), image.GetPitch());
if (!sc.texture) if (!sc.texture)
{ {
Log_ErrorPrintf("Failed to upload %ux%u software cursor %u image '%s'", image.GetWidth(), image.GetHeight(), index, Log_ErrorFmt("Failed to upload {}x{} software cursor {} image '{}'", image.GetWidth(), image.GetHeight(), index,
sc.image_path.c_str()); sc.image_path);
return; return;
} }

View File

@ -114,7 +114,7 @@ bool INISettingsInterface::Save(Error* error /* = nullptr */)
} }
else if (!FileSystem::RenamePath(temp_filename.c_str(), m_filename.c_str(), error)) else if (!FileSystem::RenamePath(temp_filename.c_str(), m_filename.c_str(), error))
{ {
Log_ErrorPrintf("Failed to rename '%s' to '%s'", temp_filename.c_str(), m_filename.c_str()); Error::AddPrefixFmt(error, "Failed to rename '{}' to '{}': ", temp_filename, m_filename);
FileSystem::DeleteFile(temp_filename.c_str()); FileSystem::DeleteFile(temp_filename.c_str());
return false; return false;
} }
@ -122,7 +122,7 @@ bool INISettingsInterface::Save(Error* error /* = nullptr */)
if (err != SI_OK) if (err != SI_OK)
{ {
Log_WarningPrintf("Failed to save settings to '%s'.", m_filename.c_str()); Log_WarningFmt("Failed to save settings to '{}'.", m_filename);
return false; return false;
} }
@ -363,7 +363,7 @@ std::vector<std::pair<std::string, std::string>> INISettingsInterface::GetKeyVal
{ {
if (!m_ini.GetAllValues(section, key.pItem, values)) // [[unlikely]] if (!m_ini.GetAllValues(section, key.pItem, values)) // [[unlikely]]
{ {
Log_ErrorPrintf("Got no values for a key returned from GetAllKeys!"); Log_ErrorPrint("Got no values for a key returned from GetAllKeys!");
continue; continue;
} }
for (const Entry& value : values) for (const Entry& value : values)

View File

@ -222,7 +222,7 @@ bool InputManager::SplitBinding(std::string_view binding, std::string_view* sour
const std::string_view::size_type slash_pos = binding.find('/'); const std::string_view::size_type slash_pos = binding.find('/');
if (slash_pos == std::string_view::npos) if (slash_pos == std::string_view::npos)
{ {
Log_WarningPrintf("Malformed binding: '%.*s'", static_cast<int>(binding.size()), binding.data()); Log_WarningFmt("Malformed binding: '{}'", binding);
return false; return false;
} }
@ -493,7 +493,7 @@ void InputManager::AddBinding(std::string_view binding, const InputEventHandler&
std::optional<InputBindingKey> key = ParseInputBindingKey(chord_binding); std::optional<InputBindingKey> key = ParseInputBindingKey(chord_binding);
if (!key.has_value()) if (!key.has_value())
{ {
Log_ErrorPrintf("Invalid binding: '%.*s'", static_cast<int>(binding.size()), binding.data()); Log_ErrorFmt("Invalid binding: '{}'", binding);
ibinding.reset(); ibinding.reset();
break; break;
} }
@ -506,8 +506,7 @@ void InputManager::AddBinding(std::string_view binding, const InputEventHandler&
if (ibinding->num_keys == MAX_KEYS_PER_BINDING) if (ibinding->num_keys == MAX_KEYS_PER_BINDING)
{ {
Log_ErrorPrintf("Too many chord parts, max is %u (%.*s)", MAX_KEYS_PER_BINDING, static_cast<int>(binding.size()), Log_ErrorFmt("Too many chord parts, max is {} ({})", static_cast<unsigned>(MAX_KEYS_PER_BINDING), binding.size());
binding.data());
ibinding.reset(); ibinding.reset();
break; break;
} }
@ -862,7 +861,7 @@ void InputManager::AddPadBindings(SettingsInterface& si, const std::string& sect
break; break;
default: default:
Log_ErrorPrintf("Unhandled binding info type %u", static_cast<u32>(bi.type)); Log_ErrorFmt("Unhandled binding info type {}", static_cast<u32>(bi.type));
break; break;
} }
} }
@ -1379,7 +1378,7 @@ static u32 TryMapGenericMapping(SettingsInterface& si, const std::string& sectio
if (found_mapping) if (found_mapping)
{ {
Log_InfoPrintf("(MapController) Map %s/%s to '%s'", section.c_str(), bind_name, found_mapping->c_str()); Log_InfoFmt("Map {}/{} to '{}'", section, bind_name, *found_mapping);
si.SetStringValue(section.c_str(), bind_name, found_mapping->c_str()); si.SetStringValue(section.c_str(), bind_name, found_mapping->c_str());
return 1; return 1;
} }
@ -1606,8 +1605,7 @@ void InputManager::LoadMacroButtonConfig(SettingsInterface& si, const std::strin
} }
if (!binding) if (!binding)
{ {
Log_DevPrintf("Invalid bind '%.*s' in macro button %u for pad %u", static_cast<int>(button.size()), Log_DevFmt("Invalid bind '{}' in macro button {} for pad {}", button, pad, i);
button.data(), pad, i);
continue; continue;
} }
@ -1929,7 +1927,7 @@ void InputManager::UpdateInputSourceState(SettingsInterface& si, std::unique_loc
std::unique_ptr<InputSource> source(factory_function()); std::unique_ptr<InputSource> source(factory_function());
if (!source->Initialize(si, settings_lock)) if (!source->Initialize(si, settings_lock))
{ {
Log_ErrorPrintf("(InputManager) Source '%s' failed to initialize.", InputManager::InputSourceToString(type)); Log_ErrorFmt("Source '{}' failed to initialize.", InputManager::InputSourceToString(type));
return; return;
} }

View File

@ -104,7 +104,7 @@ bool JitCodeBuffer::TryAllocateAt(const void* addr)
if (!m_code_ptr) if (!m_code_ptr)
{ {
if (!addr) if (!addr)
Log_ErrorPrintf("VirtualAlloc(RWX, %u) for internal buffer failed: %u", m_total_size, GetLastError()); Log_ErrorFmt("VirtualAlloc(RWX, %u) for internal buffer failed: {}", m_total_size, GetLastError());
return false; return false;
} }
@ -134,14 +134,14 @@ bool JitCodeBuffer::TryAllocateAt(const void* addr)
if (!m_code_ptr) if (!m_code_ptr)
{ {
if (!addr) if (!addr)
Log_ErrorPrintf("mmap(RWX, %u) for internal buffer failed: %d", m_total_size, errno); Log_ErrorFmt("mmap(RWX, %u) for internal buffer failed: {}", m_total_size, errno);
return false; return false;
} }
else if (addr && m_code_ptr != addr) else if (addr && m_code_ptr != addr)
{ {
if (munmap(m_code_ptr, m_total_size) != 0) if (munmap(m_code_ptr, m_total_size) != 0)
Log_ErrorPrintf("Failed to munmap() incorrectly hinted allocation: %d", errno); Log_ErrorFmt("Failed to munmap() incorrectly hinted allocation: {}", errno);
m_code_ptr = nullptr; m_code_ptr = nullptr;
return false; return false;
} }
@ -163,7 +163,7 @@ bool JitCodeBuffer::Initialize(void* buffer, u32 size, u32 far_code_size /* = 0
DWORD old_protect = 0; DWORD old_protect = 0;
if (!VirtualProtect(buffer, size, PAGE_EXECUTE_READWRITE, &old_protect)) if (!VirtualProtect(buffer, size, PAGE_EXECUTE_READWRITE, &old_protect))
{ {
Log_ErrorPrintf("VirtualProtect(RWX) for external buffer failed: %u", GetLastError()); Log_ErrorFmt("VirtualProtect(RWX) for external buffer failed: {}", GetLastError());
return false; return false;
} }
@ -174,7 +174,7 @@ bool JitCodeBuffer::Initialize(void* buffer, u32 size, u32 far_code_size /* = 0
if (!VirtualProtect(buffer, guard_size, PAGE_NOACCESS, &old_guard_protect) || if (!VirtualProtect(buffer, guard_size, PAGE_NOACCESS, &old_guard_protect) ||
!VirtualProtect(guard_at_end, guard_size, PAGE_NOACCESS, &old_guard_protect)) !VirtualProtect(guard_at_end, guard_size, PAGE_NOACCESS, &old_guard_protect))
{ {
Log_ErrorPrintf("VirtualProtect(NOACCESS) for guard page failed: %u", GetLastError()); Log_ErrorFmt("VirtualProtect(NOACCESS) for guard page failed: {}", GetLastError());
return false; return false;
} }
} }
@ -184,7 +184,7 @@ bool JitCodeBuffer::Initialize(void* buffer, u32 size, u32 far_code_size /* = 0
#elif defined(__linux__) || defined(__ANDROID__) || defined(__APPLE__) || defined(__HAIKU__) || defined(__FreeBSD__) #elif defined(__linux__) || defined(__ANDROID__) || defined(__APPLE__) || defined(__HAIKU__) || defined(__FreeBSD__)
if (mprotect(buffer, size, PROT_READ | PROT_WRITE | PROT_EXEC) != 0) if (mprotect(buffer, size, PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
{ {
Log_ErrorPrintf("mprotect(RWX) for external buffer failed: %d", errno); Log_ErrorFmt("mprotect(RWX) for external buffer failed: {}", errno);
return false; return false;
} }
@ -193,7 +193,7 @@ bool JitCodeBuffer::Initialize(void* buffer, u32 size, u32 far_code_size /* = 0
u8* guard_at_end = (static_cast<u8*>(buffer) + size) - guard_size; u8* guard_at_end = (static_cast<u8*>(buffer) + size) - guard_size;
if (mprotect(buffer, guard_size, PROT_NONE) != 0 || mprotect(guard_at_end, guard_size, PROT_NONE) != 0) if (mprotect(buffer, guard_size, PROT_NONE) != 0 || mprotect(guard_at_end, guard_size, PROT_NONE) != 0)
{ {
Log_ErrorPrintf("mprotect(NONE) for guard page failed: %d", errno); Log_ErrorFmt("mprotect(NONE) for guard page failed: {}", errno);
return false; return false;
} }
} }
@ -229,10 +229,10 @@ void JitCodeBuffer::Destroy()
{ {
#if defined(_WIN32) #if defined(_WIN32)
if (!VirtualFree(m_code_ptr, 0, MEM_RELEASE)) if (!VirtualFree(m_code_ptr, 0, MEM_RELEASE))
Log_ErrorPrintf("Failed to free code pointer %p", m_code_ptr); Log_ErrorFmt("Failed to free code pointer %p", static_cast<void*>(m_code_ptr));
#elif defined(__linux__) || defined(__ANDROID__) || defined(__APPLE__) || defined(__HAIKU__) || defined(__FreeBSD__) #elif defined(__linux__) || defined(__ANDROID__) || defined(__APPLE__) || defined(__HAIKU__) || defined(__FreeBSD__)
if (munmap(m_code_ptr, m_total_size) != 0) if (munmap(m_code_ptr, m_total_size) != 0)
Log_ErrorPrintf("Failed to free code pointer %p", m_code_ptr); Log_ErrorFmt("Failed to free code pointer %p", static_cast<void*>(m_code_ptr));
#endif #endif
} }
else if (m_code_ptr) else if (m_code_ptr)
@ -240,10 +240,10 @@ void JitCodeBuffer::Destroy()
#if defined(_WIN32) #if defined(_WIN32)
DWORD old_protect = 0; DWORD old_protect = 0;
if (!VirtualProtect(m_code_ptr, m_total_size, m_old_protection, &old_protect)) if (!VirtualProtect(m_code_ptr, m_total_size, m_old_protection, &old_protect))
Log_ErrorPrintf("Failed to restore protection on %p", m_code_ptr); Log_ErrorFmt("Failed to restore protection on %p", static_cast<void*>(m_code_ptr));
#else #else
if (mprotect(m_code_ptr, m_total_size, m_old_protection) != 0) if (mprotect(m_code_ptr, m_total_size, m_old_protection) != 0)
Log_ErrorPrintf("Failed to restore protection on %p", m_code_ptr); Log_ErrorFmt("Failed to restore protection on %p", static_cast<void*>(m_code_ptr));
#endif #endif
} }

View File

@ -178,7 +178,7 @@ bool MetalDevice::CreateDevice(std::string_view adapter, bool threaded_presentat
m_device = [device retain]; m_device = [device retain];
m_queue = [queue retain]; m_queue = [queue retain];
Log_InfoPrintf("Metal Device: %s", [[m_device name] UTF8String]); Log_InfoFmt("Metal Device: {}", [[m_device name] UTF8String]);
SetFeatures(disabled_features); SetFeatures(disabled_features);
@ -469,7 +469,7 @@ bool MetalDevice::UpdateWindow()
if (m_window_info.type != WindowInfo::Type::Surfaceless && !CreateLayer()) if (m_window_info.type != WindowInfo::Type::Surfaceless && !CreateLayer())
{ {
Log_ErrorPrintf("Failed to create layer on updated window"); Log_ErrorPrint("Failed to create layer on updated window");
return false; return false;
} }
@ -515,7 +515,7 @@ bool MetalDevice::CreateBuffers()
!m_uniform_buffer.Create(m_device, UNIFORM_BUFFER_SIZE) || !m_uniform_buffer.Create(m_device, UNIFORM_BUFFER_SIZE) ||
!m_texture_upload_buffer.Create(m_device, TEXTURE_STREAM_BUFFER_SIZE)) !m_texture_upload_buffer.Create(m_device, TEXTURE_STREAM_BUFFER_SIZE))
{ {
Log_ErrorPrintf("Failed to create vertex/index/uniform buffers."); Log_ErrorPrint("Failed to create vertex/index/uniform buffers.");
return false; return false;
} }
@ -635,7 +635,7 @@ std::unique_ptr<GPUShader> MetalDevice::CreateShaderFromMSL(GPUShaderStage stage
id<MTLFunction> function = [library newFunctionWithName:StringViewToNSString(entry_point)]; id<MTLFunction> function = [library newFunctionWithName:StringViewToNSString(entry_point)];
if (!function) if (!function)
{ {
Log_ErrorPrintf("Failed to get main function in compiled library"); Log_ErrorPrint("Failed to get main function in compiled library");
return {}; return {};
} }
@ -834,8 +834,8 @@ id<MTLDepthStencilState> MetalDevice::GetDepthState(const GPUPipeline::DepthStat
id<MTLDepthStencilState> state = [m_device newDepthStencilStateWithDescriptor:desc]; id<MTLDepthStencilState> state = [m_device newDepthStencilStateWithDescriptor:desc];
m_depth_states.emplace(ds.key, state); m_depth_states.emplace(ds.key, state);
if (state == nil) if (state == nil) [[unlikely]]
Log_ErrorPrintf("Failed to create depth-stencil state."); Log_ErrorPrint("Failed to create depth-stencil state.");
return state; return state;
} }
@ -1216,7 +1216,7 @@ std::unique_ptr<GPUTexture> MetalDevice::CreateTexture(u32 width, u32 height, u3
id<MTLTexture> tex = [m_device newTextureWithDescriptor:desc]; id<MTLTexture> tex = [m_device newTextureWithDescriptor:desc];
if (tex == nil) if (tex == nil)
{ {
Log_ErrorPrintf("Failed to create %ux%u texture.", width, height); Log_ErrorFmt("Failed to create {}x{} texture.", width, height);
return {}; return {};
} }
@ -1460,7 +1460,7 @@ std::unique_ptr<GPUSampler> MetalDevice::CreateSampler(const GPUSampler::Config&
} }
if (i == std::size(border_color_mapping)) if (i == std::size(border_color_mapping))
{ {
Log_ErrorPrintf("Unsupported border color: %08X", config.border_color.GetValue()); Log_ErrorFmt("Unsupported border color: {:08X}", config.border_color.GetValue());
return {}; return {};
} }
@ -1471,7 +1471,7 @@ std::unique_ptr<GPUSampler> MetalDevice::CreateSampler(const GPUSampler::Config&
id<MTLSamplerState> ss = [m_device newSamplerStateWithDescriptor:desc]; id<MTLSamplerState> ss = [m_device newSamplerStateWithDescriptor:desc];
if (ss == nil) if (ss == nil)
{ {
Log_ErrorPrintf("Failed to create sampler state."); Log_ErrorPrint("Failed to create sampler state.");
return {}; return {};
} }
@ -2557,7 +2557,7 @@ void MetalDevice::SubmitCommandBuffer(bool wait_for_completion)
void MetalDevice::SubmitCommandBufferAndRestartRenderPass(const char* reason) void MetalDevice::SubmitCommandBufferAndRestartRenderPass(const char* reason)
{ {
Log_DevPrintf("Submitting command buffer and restarting render pass due to %s", reason); Log_DevFmt("Submitting command buffer and restarting render pass due to {}", reason);
const bool in_render_pass = InRenderPass(); const bool in_render_pass = InRenderPass();
SubmitCommandBuffer(); SubmitCommandBuffer();

View File

@ -27,7 +27,7 @@ bool MetalStreamBuffer::Create(id<MTLDevice> device, u32 size)
id<MTLBuffer> new_buffer = [device newBufferWithLength:size options:options]; id<MTLBuffer> new_buffer = [device newBufferWithLength:size options:options];
if (new_buffer == nil) if (new_buffer == nil)
{ {
Log_ErrorPrintf("Failed to create buffer."); Log_ErrorPrint("Failed to create buffer.");
return false; return false;
} }
@ -61,10 +61,9 @@ bool MetalStreamBuffer::ReserveMemory(u32 num_bytes, u32 alignment)
const u32 required_bytes = num_bytes + alignment; const u32 required_bytes = num_bytes + alignment;
// Check for sane allocations // Check for sane allocations
if (required_bytes > m_size) if (required_bytes > m_size) [[unlikely]]
{ {
Log_ErrorPrintf("Attempting to allocate %u bytes from a %u byte stream buffer", static_cast<u32>(num_bytes), Log_ErrorFmt("Attempting to allocate {} bytes from a {} byte stream buffer", num_bytes, m_size);
static_cast<u32>(m_size));
Panic("Stream buffer overflow"); Panic("Stream buffer overflow");
return false; return false;
} }

View File

@ -64,16 +64,16 @@ static void DisableBrokenExtensions(const char* gl_vendor, const char* gl_render
gl_major_version >= 3 && gl_minor_version >= 2 && major_version > 0)) gl_major_version >= 3 && gl_minor_version >= 2 && major_version > 0))
{ {
// r32p0 and beyond seem okay. // r32p0 and beyond seem okay.
// Log_VerbosePrintf("Keeping copy_image for driver version '%s'", gl_version); // Log_VerbosePrint("Keeping copy_image for driver version '%s'", gl_version);
// Framebuffer blits still end up faster. // Framebuffer blits still end up faster.
Log_VerbosePrintf("Newer Mali driver detected, disabling GL_{EXT,OES}_copy_image."); Log_VerbosePrint("Newer Mali driver detected, disabling GL_{EXT,OES}_copy_image.");
GLAD_GL_EXT_copy_image = 0; GLAD_GL_EXT_copy_image = 0;
GLAD_GL_OES_copy_image = 0; GLAD_GL_OES_copy_image = 0;
} }
else else
{ {
Log_VerbosePrintf("Older Mali driver detected, disabling GL_{EXT,OES}_copy_image, disjoint_timer_query."); Log_VerbosePrint("Older Mali driver detected, disabling GL_{EXT,OES}_copy_image, disjoint_timer_query.");
GLAD_GL_EXT_copy_image = 0; GLAD_GL_EXT_copy_image = 0;
GLAD_GL_OES_copy_image = 0; GLAD_GL_OES_copy_image = 0;
GLAD_GL_EXT_disjoint_timer_query = 0; GLAD_GL_EXT_disjoint_timer_query = 0;
@ -203,10 +203,10 @@ std::unique_ptr<OpenGLContext> OpenGLContext::Create(const WindowInfo& wi, Error
const char* gl_renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER)); const char* gl_renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
const char* gl_version = reinterpret_cast<const char*>(glGetString(GL_VERSION)); const char* gl_version = reinterpret_cast<const char*>(glGetString(GL_VERSION));
const char* gl_shading_language_version = reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION)); const char* gl_shading_language_version = reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
Log_InfoPrintf("GL_VENDOR: %s", gl_vendor); Log_InfoFmt("GL_VENDOR: {}", gl_vendor);
Log_InfoPrintf("GL_RENDERER: %s", gl_renderer); Log_InfoFmt("GL_RENDERER: {}", gl_renderer);
Log_InfoPrintf("GL_VERSION: %s", gl_version); Log_InfoFmt("GL_VERSION: {}", gl_version);
Log_InfoPrintf("GL_SHADING_LANGUAGE_VERSION: %s", gl_shading_language_version); Log_InfoFmt("GL_SHADING_LANGUAGE_VERSION: {}", gl_shading_language_version);
DisableBrokenExtensions(gl_vendor, gl_renderer, gl_version); DisableBrokenExtensions(gl_vendor, gl_renderer, gl_version);

View File

@ -257,7 +257,7 @@ bool OpenGLContextEGL::ChangeSurface(const WindowInfo& new_wi)
if (was_current && !eglMakeCurrent(m_display, m_surface, m_surface, m_context)) if (was_current && !eglMakeCurrent(m_display, m_surface, m_surface, m_context))
{ {
Log_ErrorPrintf("Failed to make context current again after surface change"); Log_ErrorPrint("Failed to make context current again after surface change");
return false; return false;
} }
@ -270,7 +270,7 @@ void OpenGLContextEGL::ResizeSurface(u32 new_surface_width /*= 0*/, u32 new_surf
{ {
EGLint surface_width, surface_height; EGLint surface_width, surface_height;
if (eglQuerySurface(m_display, m_surface, EGL_WIDTH, &surface_width) && if (eglQuerySurface(m_display, m_surface, EGL_WIDTH, &surface_width) &&
eglQuerySurface(m_display, m_surface, EGL_HEIGHT, &surface_height)) eglQuerySurface(m_display, m_surface, EGL_HEIGHT, &surface_height)) [[likely]]
{ {
m_wi.surface_width = static_cast<u32>(surface_width); m_wi.surface_width = static_cast<u32>(surface_width);
m_wi.surface_height = static_cast<u32>(surface_height); m_wi.surface_height = static_cast<u32>(surface_height);
@ -278,7 +278,7 @@ void OpenGLContextEGL::ResizeSurface(u32 new_surface_width /*= 0*/, u32 new_surf
} }
else else
{ {
Log_ErrorPrintf("eglQuerySurface() failed: %d", eglGetError()); Log_ErrorFmt("eglQuerySurface() failed: 0x{:X}", eglGetError());
} }
} }
@ -298,9 +298,9 @@ bool OpenGLContextEGL::IsCurrent() const
bool OpenGLContextEGL::MakeCurrent() bool OpenGLContextEGL::MakeCurrent()
{ {
if (!eglMakeCurrent(m_display, m_surface, m_surface, m_context)) if (!eglMakeCurrent(m_display, m_surface, m_surface, m_context)) [[unlikely]]
{ {
Log_ErrorPrintf("eglMakeCurrent() failed: %d", eglGetError()); Log_ErrorFmt("eglMakeCurrent() failed: 0x{:X}", eglGetError());
return false; return false;
} }
@ -364,7 +364,7 @@ bool OpenGLContextEGL::CreateSurface()
} }
else else
{ {
Log_ErrorPrintf("eglQuerySurface() failed: %d", eglGetError()); Log_ErrorFmt("eglQuerySurface() failed: 0x{:X}", eglGetError());
} }
m_wi.surface_format = GetSurfaceTextureFormat(); m_wi.surface_format = GetSurfaceTextureFormat();
@ -383,15 +383,15 @@ bool OpenGLContextEGL::CreatePBufferSurface()
}; };
m_surface = eglCreatePbufferSurface(m_display, m_config, attrib_list); m_surface = eglCreatePbufferSurface(m_display, m_config, attrib_list);
if (!m_surface) if (!m_surface) [[unlikely]]
{ {
Log_ErrorPrintf("eglCreatePbufferSurface() failed: %d", eglGetError()); Log_ErrorFmt("eglCreatePbufferSurface() failed: {}", eglGetError());
return false; return false;
} }
m_wi.surface_format = GetSurfaceTextureFormat(); m_wi.surface_format = GetSurfaceTextureFormat();
Log_DevPrintf("Created %ux%u pbuffer surface", width, height); Log_DevFmt("Created {}x{} pbuffer surface", width, height);
return true; return true;
} }
@ -447,7 +447,7 @@ GPUTexture::Format OpenGLContextEGL::GetSurfaceTextureFormat() const
} }
else else
{ {
Log_ErrorPrintf("Unknown surface format: R=%u, G=%u, B=%u, A=%u", red_size, green_size, blue_size, alpha_size); Log_ErrorFmt("Unknown surface format: R={}, G={}, B={}, A={}", red_size, green_size, blue_size, alpha_size);
return GPUTexture::Format::RGBA8; return GPUTexture::Format::RGBA8;
} }
} }
@ -618,7 +618,7 @@ bool OpenGLContextEGL::CreateContextAndSurface(const Version& version, EGLContex
if (!CreateSurface()) if (!CreateSurface())
{ {
Log_ErrorPrintf("Failed to create surface for context"); Log_ErrorPrint("Failed to create surface for context");
eglDestroyContext(m_display, m_context); eglDestroyContext(m_display, m_context);
m_context = EGL_NO_CONTEXT; m_context = EGL_NO_CONTEXT;
return false; return false;
@ -626,7 +626,7 @@ bool OpenGLContextEGL::CreateContextAndSurface(const Version& version, EGLContex
if (make_current && !eglMakeCurrent(m_display, m_surface, m_surface, m_context)) if (make_current && !eglMakeCurrent(m_display, m_surface, m_surface, m_context))
{ {
Log_ErrorPrintf("eglMakeCurrent() failed: %d", eglGetError()); Log_ErrorFmt("eglMakeCurrent() failed: 0x{:X}", eglGetError());
if (m_surface != EGL_NO_SURFACE) if (m_surface != EGL_NO_SURFACE)
{ {
eglDestroySurface(m_display, m_surface); eglDestroySurface(m_display, m_surface);

View File

@ -280,7 +280,7 @@ bool OpenGLDevice::CreateDevice(std::string_view adapter, bool threaded_presenta
m_gl_context = OpenGLContext::Create(m_window_info, error); m_gl_context = OpenGLContext::Create(m_window_info, error);
if (!m_gl_context) if (!m_gl_context)
{ {
Log_ErrorPrintf("Failed to create any GL context"); Log_ErrorPrint("Failed to create any GL context");
m_gl_context.reset(); m_gl_context.reset();
return false; return false;
} }
@ -496,8 +496,8 @@ bool OpenGLDevice::CheckFeatures(FeatureMask disabled_features)
if (!m_features.pipeline_cache) if (!m_features.pipeline_cache)
{ {
Log_WarningPrintf("Your GL driver does not support program binaries. Hopefully it has a built-in cache, otherwise " Log_WarningPrint("Your GL driver does not support program binaries. Hopefully it has a built-in cache, otherwise "
"startup will be slow due to compiling shaders."); "startup will be slow due to compiling shaders.");
} }
// Mobile drivers prefer textures to not be updated mid-frame. // Mobile drivers prefer textures to not be updated mid-frame.
@ -536,7 +536,7 @@ bool OpenGLDevice::UpdateWindow()
if (!m_gl_context->ChangeSurface(m_window_info)) if (!m_gl_context->ChangeSurface(m_window_info))
{ {
Log_ErrorPrintf("Failed to change surface"); Log_ErrorPrint("Failed to change surface");
return false; return false;
} }
@ -681,16 +681,16 @@ void OpenGLDevice::DestroySurface()
m_window_info.SetSurfaceless(); m_window_info.SetSurfaceless();
if (!m_gl_context->ChangeSurface(m_window_info)) if (!m_gl_context->ChangeSurface(m_window_info))
Log_ErrorPrintf("Failed to switch to surfaceless"); Log_ErrorPrint("Failed to switch to surfaceless");
} }
bool OpenGLDevice::CreateBuffers() bool OpenGLDevice::CreateBuffers()
{ {
if (!(m_vertex_buffer = OpenGLStreamBuffer::Create(GL_ARRAY_BUFFER, VERTEX_BUFFER_SIZE)) || if (!(m_vertex_buffer = OpenGLStreamBuffer::Create(GL_ARRAY_BUFFER, VERTEX_BUFFER_SIZE)) ||
!(m_index_buffer = OpenGLStreamBuffer::Create(GL_ELEMENT_ARRAY_BUFFER, INDEX_BUFFER_SIZE)) || !(m_index_buffer = OpenGLStreamBuffer::Create(GL_ELEMENT_ARRAY_BUFFER, INDEX_BUFFER_SIZE)) ||
!(m_uniform_buffer = OpenGLStreamBuffer::Create(GL_UNIFORM_BUFFER, UNIFORM_BUFFER_SIZE))) !(m_uniform_buffer = OpenGLStreamBuffer::Create(GL_UNIFORM_BUFFER, UNIFORM_BUFFER_SIZE))) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to create one or more device buffers."); Log_ErrorPrint("Failed to create one or more device buffers.");
return false; return false;
} }
@ -703,8 +703,9 @@ bool OpenGLDevice::CreateBuffers()
if (!m_disable_pbo) if (!m_disable_pbo)
{ {
if (!(m_texture_stream_buffer = OpenGLStreamBuffer::Create(GL_PIXEL_UNPACK_BUFFER, TEXTURE_STREAM_BUFFER_SIZE))) if (!(m_texture_stream_buffer = OpenGLStreamBuffer::Create(GL_PIXEL_UNPACK_BUFFER, TEXTURE_STREAM_BUFFER_SIZE)))
[[unlikely]]
{ {
Log_ErrorPrintf("Failed to create texture stream buffer"); Log_ErrorPrint("Failed to create texture stream buffer");
return false; return false;
} }
@ -717,9 +718,9 @@ bool OpenGLDevice::CreateBuffers()
GLuint fbos[2]; GLuint fbos[2];
glGetError(); glGetError();
glGenFramebuffers(static_cast<GLsizei>(std::size(fbos)), fbos); glGenFramebuffers(static_cast<GLsizei>(std::size(fbos)), fbos);
if (const GLenum err = glGetError(); err != GL_NO_ERROR) if (const GLenum err = glGetError(); err != GL_NO_ERROR) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to create framebuffers: %u", err); Log_ErrorFmt("Failed to create framebuffers: {}", err);
return false; return false;
} }
m_read_fbo = fbos[0]; m_read_fbo = fbos[0];
@ -838,7 +839,7 @@ void OpenGLDevice::PopTimestampQuery()
glGetIntegerv(GL_GPU_DISJOINT_EXT, &disjoint); glGetIntegerv(GL_GPU_DISJOINT_EXT, &disjoint);
if (disjoint) if (disjoint)
{ {
Log_VerbosePrintf("GPU timing disjoint, resetting."); Log_VerbosePrint("GPU timing disjoint, resetting.");
if (m_timestamp_query_started) if (m_timestamp_query_started)
glEndQueryEXT(GL_TIME_ELAPSED); glEndQueryEXT(GL_TIME_ELAPSED);

View File

@ -1,4 +1,4 @@
// SPDX-FileCopyrightText: 2019-2023 Connor McLaughlin <stenzek@gmail.com> // SPDX-FileCopyrightText: 2019-2024 Connor McLaughlin <stenzek@gmail.com>
// SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0) // SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)
#include "opengl_pipeline.h" #include "opengl_pipeline.h"
@ -7,6 +7,7 @@
#include "shadergen.h" #include "shadergen.h"
#include "common/assert.h" #include "common/assert.h"
#include "common/error.h"
#include "common/file_system.h" #include "common/file_system.h"
#include "common/hash_combine.h" #include "common/hash_combine.h"
#include "common/log.h" #include "common/log.h"
@ -109,7 +110,7 @@ bool OpenGLShader::Compile()
GLuint shader = glCreateShader(GetGLShaderType(m_stage)); GLuint shader = glCreateShader(GetGLShaderType(m_stage));
if (GLenum err = glGetError(); err != GL_NO_ERROR) if (GLenum err = glGetError(); err != GL_NO_ERROR)
{ {
Log_ErrorPrintf("glCreateShader() failed: %u", err); Log_ErrorFmt("glCreateShader() failed: {}", err);
return false; return false;
} }
@ -132,7 +133,7 @@ bool OpenGLShader::Compile()
if (status == GL_TRUE) if (status == GL_TRUE)
{ {
Log_ErrorPrintf("Shader compiled with warnings:\n%s", info_log.c_str()); Log_ErrorFmt("Shader compiled with warnings:\n{}", info_log);
} }
else else
{ {
@ -169,7 +170,7 @@ std::unique_ptr<GPUShader> OpenGLDevice::CreateShaderFromSource(GPUShaderStage s
{ {
if (std::strcmp(entry_point, "main") != 0) if (std::strcmp(entry_point, "main") != 0)
{ {
Log_ErrorPrintf("Entry point must be 'main', but got '%s' instead.", entry_point); Log_ErrorFmt("Entry point must be 'main', but got '{}' instead.", entry_point);
return {}; return {};
} }
@ -264,7 +265,7 @@ GLuint OpenGLDevice::LookupProgramCache(const OpenGLPipeline::ProgramCacheKey& k
it->second.program_id = CreateProgramFromPipelineCache(it->second, plconfig); it->second.program_id = CreateProgramFromPipelineCache(it->second, plconfig);
if (it->second.program_id == 0) if (it->second.program_id == 0)
{ {
Log_ErrorPrintf("Failed to create program from binary."); Log_ErrorPrint("Failed to create program from binary.");
m_program_cache.erase(it); m_program_cache.erase(it);
it = m_program_cache.end(); it = m_program_cache.end();
DiscardPipelineCache(); DiscardPipelineCache();
@ -306,17 +307,17 @@ GLuint OpenGLDevice::CompileProgram(const GPUPipeline::GraphicsConfig& plconfig)
OpenGLShader* fragment_shader = static_cast<OpenGLShader*>(plconfig.fragment_shader); OpenGLShader* fragment_shader = static_cast<OpenGLShader*>(plconfig.fragment_shader);
OpenGLShader* geometry_shader = static_cast<OpenGLShader*>(plconfig.geometry_shader); OpenGLShader* geometry_shader = static_cast<OpenGLShader*>(plconfig.geometry_shader);
if (!vertex_shader || !fragment_shader || !vertex_shader->Compile() || !fragment_shader->Compile() || if (!vertex_shader || !fragment_shader || !vertex_shader->Compile() || !fragment_shader->Compile() ||
(geometry_shader && !geometry_shader->Compile())) (geometry_shader && !geometry_shader->Compile())) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to compile shaders."); Log_ErrorPrint("Failed to compile shaders.");
return 0; return 0;
} }
glGetError(); glGetError();
const GLuint program_id = glCreateProgram(); const GLuint program_id = glCreateProgram();
if (glGetError() != GL_NO_ERROR) if (glGetError() != GL_NO_ERROR) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to create program object."); Log_ErrorPrint("Failed to create program object.");
return 0; return 0;
} }
@ -372,7 +373,7 @@ GLuint OpenGLDevice::CompileProgram(const GPUPipeline::GraphicsConfig& plconfig)
GLint info_log_length = 0; GLint info_log_length = 0;
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &info_log_length); glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &info_log_length);
if (status == GL_FALSE || info_log_length > 0) if (status == GL_FALSE || info_log_length > 0) [[unlikely]]
{ {
std::string info_log; std::string info_log;
info_log.resize(info_log_length + 1); info_log.resize(info_log_length + 1);
@ -380,11 +381,11 @@ GLuint OpenGLDevice::CompileProgram(const GPUPipeline::GraphicsConfig& plconfig)
if (status == GL_TRUE) if (status == GL_TRUE)
{ {
Log_ErrorPrintf("Program linked with warnings:\n%s", info_log.c_str()); Log_ErrorFmt("Program linked with warnings:\n{}", info_log.c_str());
} }
else else
{ {
Log_ErrorPrintf("Program failed to link:\n%s", info_log.c_str()); Log_ErrorFmt("Program failed to link:\n{}", info_log.c_str());
glDeleteProgram(program_id); glDeleteProgram(program_id);
return 0; return 0;
} }
@ -468,7 +469,7 @@ GLuint OpenGLDevice::CreateVAO(std::span<const GPUPipeline::VertexAttribute> att
glGenVertexArrays(1, &vao); glGenVertexArrays(1, &vao);
if (const GLenum err = glGetError(); err != GL_NO_ERROR) if (const GLenum err = glGetError(); err != GL_NO_ERROR)
{ {
Log_ErrorPrintf("Failed to create vertex array object: %u", vao); Log_ErrorFmt("Failed to create vertex array object: {}", err);
return 0; return 0;
} }
@ -720,7 +721,8 @@ bool OpenGLDevice::ReadPipelineCache(const std::string& filename)
{ {
DebugAssert(!m_pipeline_disk_cache_file); DebugAssert(!m_pipeline_disk_cache_file);
m_pipeline_disk_cache_file = FileSystem::OpenCFile(filename.c_str(), "r+b"); Error error;
m_pipeline_disk_cache_file = FileSystem::OpenCFile(filename.c_str(), "r+b", &error);
m_pipeline_disk_cache_filename = filename; m_pipeline_disk_cache_filename = filename;
if (!m_pipeline_disk_cache_file) if (!m_pipeline_disk_cache_file)
@ -735,12 +737,12 @@ bool OpenGLDevice::ReadPipelineCache(const std::string& filename)
// If it doesn't exist, we're going to create it. // If it doesn't exist, we're going to create it.
if (errno != ENOENT) if (errno != ENOENT)
{ {
Log_WarningPrintf("Failed to open shader cache: %d", errno); Log_WarningFmt("Failed to open shader cache: {}", error.GetDescription());
m_pipeline_disk_cache_filename = {}; m_pipeline_disk_cache_filename = {};
return false; return false;
} }
Log_WarningPrintf("Disk cache does not exist, creating."); Log_WarningPrint("Disk cache does not exist, creating.");
return DiscardPipelineCache(); return DiscardPipelineCache();
} }
@ -756,7 +758,7 @@ bool OpenGLDevice::ReadPipelineCache(const std::string& filename)
if (FileSystem::FSeek64(m_pipeline_disk_cache_file, size - sizeof(PipelineDiskCacheFooter), SEEK_SET) != 0 || if (FileSystem::FSeek64(m_pipeline_disk_cache_file, size - sizeof(PipelineDiskCacheFooter), SEEK_SET) != 0 ||
std::fread(&file_footer, sizeof(file_footer), 1, m_pipeline_disk_cache_file) != 1) std::fread(&file_footer, sizeof(file_footer), 1, m_pipeline_disk_cache_file) != 1)
{ {
Log_ErrorPrintf("Failed to read disk cache footer."); Log_ErrorPrint("Failed to read disk cache footer.");
return DiscardPipelineCache(); return DiscardPipelineCache();
} }
@ -771,7 +773,7 @@ bool OpenGLDevice::ReadPipelineCache(const std::string& filename)
std::strncmp(file_footer.driver_version, expected_footer.driver_version, std::size(file_footer.driver_version)) != std::strncmp(file_footer.driver_version, expected_footer.driver_version, std::size(file_footer.driver_version)) !=
0) 0)
{ {
Log_ErrorPrintf("Disk cache does not match expected driver/version."); Log_ErrorPrint("Disk cache does not match expected driver/version.");
return DiscardPipelineCache(); return DiscardPipelineCache();
} }
@ -780,7 +782,7 @@ bool OpenGLDevice::ReadPipelineCache(const std::string& filename)
if (m_pipeline_disk_cache_data_end < 0 || if (m_pipeline_disk_cache_data_end < 0 ||
FileSystem::FSeek64(m_pipeline_disk_cache_file, m_pipeline_disk_cache_data_end, SEEK_SET) != 0) FileSystem::FSeek64(m_pipeline_disk_cache_file, m_pipeline_disk_cache_data_end, SEEK_SET) != 0)
{ {
Log_ErrorPrintf("Failed to seek to start of index entries."); Log_ErrorPrint("Failed to seek to start of index entries.");
return DiscardPipelineCache(); return DiscardPipelineCache();
} }
@ -791,13 +793,13 @@ bool OpenGLDevice::ReadPipelineCache(const std::string& filename)
if (std::fread(&entry, sizeof(entry), 1, m_pipeline_disk_cache_file) != 1 || if (std::fread(&entry, sizeof(entry), 1, m_pipeline_disk_cache_file) != 1 ||
(static_cast<s64>(entry.offset) + static_cast<s64>(entry.compressed_size)) >= size) (static_cast<s64>(entry.offset) + static_cast<s64>(entry.compressed_size)) >= size)
{ {
Log_ErrorPrintf("Failed to read disk cache entry."); Log_ErrorPrint("Failed to read disk cache entry.");
return DiscardPipelineCache(); return DiscardPipelineCache();
} }
if (m_program_cache.find(entry.key) != m_program_cache.end()) if (m_program_cache.find(entry.key) != m_program_cache.end())
{ {
Log_ErrorPrintf("Duplicate program in disk cache."); Log_ErrorPrint("Duplicate program in disk cache.");
return DiscardPipelineCache(); return DiscardPipelineCache();
} }
@ -811,7 +813,7 @@ bool OpenGLDevice::ReadPipelineCache(const std::string& filename)
m_program_cache.emplace(entry.key, pitem); m_program_cache.emplace(entry.key, pitem);
} }
Log_VerbosePrintf("Read %zu programs from disk cache.", m_program_cache.size()); Log_VerboseFmt("Read {} programs from disk cache.", m_program_cache.size());
return true; return true;
} }
@ -828,26 +830,26 @@ GLuint OpenGLDevice::CreateProgramFromPipelineCache(const OpenGLPipeline::Progra
DynamicHeapArray<u8> compressed_data(it.file_compressed_size); DynamicHeapArray<u8> compressed_data(it.file_compressed_size);
if (FileSystem::FSeek64(m_pipeline_disk_cache_file, it.file_offset, SEEK_SET) != 0 || if (FileSystem::FSeek64(m_pipeline_disk_cache_file, it.file_offset, SEEK_SET) != 0 ||
std::fread(compressed_data.data(), it.file_compressed_size, 1, m_pipeline_disk_cache_file) != 1) std::fread(compressed_data.data(), it.file_compressed_size, 1, m_pipeline_disk_cache_file) != 1) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to read program from disk cache."); Log_ErrorPrint("Failed to read program from disk cache.");
return 0; return 0;
} }
const size_t decompress_result = const size_t decompress_result =
ZSTD_decompress(data.data(), data.size(), compressed_data.data(), compressed_data.size()); ZSTD_decompress(data.data(), data.size(), compressed_data.data(), compressed_data.size());
if (ZSTD_isError(decompress_result)) if (ZSTD_isError(decompress_result)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to decompress program from disk cache: %s", ZSTD_getErrorName(decompress_result)); Log_ErrorFmt("Failed to decompress program from disk cache: {}", ZSTD_getErrorName(decompress_result));
return 0; return 0;
} }
compressed_data.deallocate(); compressed_data.deallocate();
glGetError(); glGetError();
GLuint prog = glCreateProgram(); GLuint prog = glCreateProgram();
if (const GLenum err = glGetError(); err != GL_NO_ERROR) if (const GLenum err = glGetError(); err != GL_NO_ERROR) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to create program object: %u", err); Log_ErrorFmt("Failed to create program object: {}", err);
return 0; return 0;
} }
@ -855,9 +857,9 @@ GLuint OpenGLDevice::CreateProgramFromPipelineCache(const OpenGLPipeline::Progra
GLint link_status; GLint link_status;
glGetProgramiv(prog, GL_LINK_STATUS, &link_status); glGetProgramiv(prog, GL_LINK_STATUS, &link_status);
if (link_status != GL_TRUE) if (link_status != GL_TRUE) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to create GL program from binary: status %d, discarding cache.", link_status); Log_ErrorFmt("Failed to create GL program from binary: status {}, discarding cache.", link_status);
glDeleteProgram(prog); glDeleteProgram(prog);
return 0; return 0;
} }
@ -888,27 +890,27 @@ void OpenGLDevice::AddToPipelineCache(OpenGLPipeline::ProgramCacheItem* it)
Log_WarningPrint("glGetProgramBinary() failed"); Log_WarningPrint("glGetProgramBinary() failed");
return; return;
} }
else if (static_cast<size_t>(binary_size) != uncompressed_data.size()) else if (static_cast<size_t>(binary_size) != uncompressed_data.size()) [[unlikely]]
{ {
Log_WarningPrintf("Size changed from %zu to %d after glGetProgramBinary()", uncompressed_data.size(), binary_size); Log_WarningFmt("Size changed from {} to {} after glGetProgramBinary()", uncompressed_data.size(), binary_size);
} }
DynamicHeapArray<u8> compressed_data(ZSTD_compressBound(binary_size)); DynamicHeapArray<u8> compressed_data(ZSTD_compressBound(binary_size));
const size_t compress_result = const size_t compress_result =
ZSTD_compress(compressed_data.data(), compressed_data.size(), uncompressed_data.data(), binary_size, 0); ZSTD_compress(compressed_data.data(), compressed_data.size(), uncompressed_data.data(), binary_size, 0);
if (ZSTD_isError(compress_result)) if (ZSTD_isError(compress_result)) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to compress program: %s", ZSTD_getErrorName(compress_result)); Log_ErrorFmt("Failed to compress program: {}", ZSTD_getErrorName(compress_result));
return; return;
} }
Log_DevPrintf("Program binary retrieved and compressed, %zu -> %zu bytes, format %u", Log_DevFmt("Program binary retrieved and compressed, {} -> {} bytes, format {}", binary_size, compress_result,
static_cast<size_t>(binary_size), compress_result, format); format);
if (FileSystem::FSeek64(m_pipeline_disk_cache_file, m_pipeline_disk_cache_data_end, SEEK_SET) != 0 || if (FileSystem::FSeek64(m_pipeline_disk_cache_file, m_pipeline_disk_cache_data_end, SEEK_SET) != 0 ||
std::fwrite(compressed_data.data(), compress_result, 1, m_pipeline_disk_cache_file) != 1) std::fwrite(compressed_data.data(), compress_result, 1, m_pipeline_disk_cache_file) != 1)
{ {
Log_ErrorPrintf("Failed to write binary to disk cache."); Log_ErrorPrint("Failed to write binary to disk cache.");
} }
it->file_format = format; it->file_format = format;
@ -940,11 +942,12 @@ bool OpenGLDevice::DiscardPipelineCache()
if (m_pipeline_disk_cache_file) if (m_pipeline_disk_cache_file)
std::fclose(m_pipeline_disk_cache_file); std::fclose(m_pipeline_disk_cache_file);
Error error;
m_pipeline_disk_cache_data_end = 0; m_pipeline_disk_cache_data_end = 0;
m_pipeline_disk_cache_file = FileSystem::OpenCFile(m_pipeline_disk_cache_filename.c_str(), "w+b"); m_pipeline_disk_cache_file = FileSystem::OpenCFile(m_pipeline_disk_cache_filename.c_str(), "w+b", &error);
if (!m_pipeline_disk_cache_file) if (!m_pipeline_disk_cache_file) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to reopen pipeline cache: %d", errno); Log_ErrorFmt("Failed to reopen pipeline cache: {}", error.GetDescription());
m_pipeline_disk_cache_filename = {}; m_pipeline_disk_cache_filename = {};
return false; return false;
} }
@ -964,13 +967,13 @@ void OpenGLDevice::ClosePipelineCache()
if (!m_pipeline_disk_cache_changed) if (!m_pipeline_disk_cache_changed)
{ {
Log_VerbosePrintf("Not updating pipeline cache because it has not changed."); Log_VerbosePrint("Not updating pipeline cache because it has not changed.");
return; return;
} }
if (FileSystem::FSeek64(m_pipeline_disk_cache_file, m_pipeline_disk_cache_data_end, SEEK_SET) != 0) if (FileSystem::FSeek64(m_pipeline_disk_cache_file, m_pipeline_disk_cache_data_end, SEEK_SET) != 0) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to seek to data end."); Log_ErrorPrint("Failed to seek to data end.");
return; return;
} }
@ -988,9 +991,9 @@ void OpenGLDevice::ClosePipelineCache()
entry.compressed_size = it.second.file_compressed_size; entry.compressed_size = it.second.file_compressed_size;
entry.uncompressed_size = it.second.file_uncompressed_size; entry.uncompressed_size = it.second.file_uncompressed_size;
if (std::fwrite(&entry, sizeof(entry), 1, m_pipeline_disk_cache_file) != 1) if (std::fwrite(&entry, sizeof(entry), 1, m_pipeline_disk_cache_file) != 1) [[unlikely]]
{ {
Log_ErrorPrintf("Failed to write index entry."); Log_ErrorPrint("Failed to write index entry.");
return; return;
} }
@ -1001,6 +1004,6 @@ void OpenGLDevice::ClosePipelineCache()
FillFooter(&footer, m_shader_cache.GetVersion()); FillFooter(&footer, m_shader_cache.GetVersion());
footer.num_programs = count; footer.num_programs = count;
if (std::fwrite(&footer, sizeof(footer), 1, m_pipeline_disk_cache_file) != 1) if (std::fwrite(&footer, sizeof(footer), 1, m_pipeline_disk_cache_file) != 1) [[unlikely]]
Log_ErrorPrintf("Failed to write footer."); Log_ErrorPrint("Failed to write footer.");
} }

View File

@ -119,7 +119,7 @@ std::unique_ptr<OpenGLTexture> OpenGLTexture::Create(u32 width, u32 height, u32
if (layers > 1 && data) if (layers > 1 && data)
{ {
Log_ErrorPrintf("Loading texture array data not currently supported"); Log_ErrorPrint("Loading texture array data not currently supported");
return nullptr; return nullptr;
} }
@ -224,7 +224,7 @@ std::unique_ptr<OpenGLTexture> OpenGLTexture::Create(u32 width, u32 height, u32
GLenum error = glGetError(); GLenum error = glGetError();
if (error != GL_NO_ERROR) if (error != GL_NO_ERROR)
{ {
Log_ErrorPrintf("Failed to create texture: 0x%X", error); Log_ErrorFmt("Failed to create texture: 0x{:X}", error);
glDeleteTextures(1, &id); glDeleteTextures(1, &id);
return nullptr; return nullptr;
} }
@ -411,7 +411,7 @@ std::unique_ptr<GPUSampler> OpenGLDevice::CreateSampler(const GPUSampler::Config
glGenSamplers(1, &sampler); glGenSamplers(1, &sampler);
if (glGetError() != GL_NO_ERROR) if (glGetError() != GL_NO_ERROR)
{ {
Log_ErrorPrintf("Failed to create sampler: %u", sampler); Log_ErrorFmt("Failed to create sampler: {:X}", sampler);
return {}; return {};
} }
@ -630,7 +630,7 @@ bool OpenGLTextureBuffer::CreateBuffer()
glGenTextures(1, &m_texture_id); glGenTextures(1, &m_texture_id);
if (const GLenum err = glGetError(); err != GL_NO_ERROR) if (const GLenum err = glGetError(); err != GL_NO_ERROR)
{ {
Log_ErrorPrintf("Failed to create texture for buffer: %u", err); Log_ErrorFmt("Failed to create texture for buffer: 0x{:X}", err);
return false; return false;
} }
@ -683,7 +683,7 @@ std::unique_ptr<GPUTextureBuffer> OpenGLDevice::CreateTextureBuffer(GPUTextureBu
glGetInteger64v(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &max_ssbo_size); glGetInteger64v(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &max_ssbo_size);
if (static_cast<GLint64>(buffer_size) > max_ssbo_size) if (static_cast<GLint64>(buffer_size) > max_ssbo_size)
{ {
Log_ErrorPrintf("Buffer size of %u not supported, max is %" PRId64, buffer_size, max_ssbo_size); Log_ErrorFmt("Buffer size of {} not supported, max is {}", buffer_size, max_ssbo_size);
return {}; return {};
} }
} }
@ -701,7 +701,7 @@ std::unique_ptr<GPUTextureBuffer> OpenGLDevice::CreateTextureBuffer(GPUTextureBu
glGenTextures(1, &texture_id); glGenTextures(1, &texture_id);
if (const GLenum err = glGetError(); err != GL_NO_ERROR) if (const GLenum err = glGetError(); err != GL_NO_ERROR)
{ {
Log_ErrorPrintf("Failed to create texture for buffer: %u", err); Log_ErrorFmt("Failed to create texture for buffer: 0x{:X}", err);
return {}; return {};
} }

Some files were not shown because too many files have changed in this diff Show More