Reapply "Minecraft.World: C4JThread: Update Threader from Portable-LCE"

This reverts commit 6300671276.
This commit is contained in:
Anaël committed 2026-12-01 12:22:06 +01:00
1 parent e10f2859f4
commit 96a2beb04b
18 files changed
+843 -1369

No files matched your search

+38 -38
View File
@@ -34,10 +34,10 @@ constexpr float MUSIC_FADE_DURATION_SECONDS = 4.0f;
#ifdef __ORBIS__
#include <audioout.h>
//#define __DISABLE_MILES__ // MGH disabled for now as it crashes if we call sceNpMatching2Initialize
#endif
#endif
// take out Orbis until they are done
#if defined _XBOX
#if defined _XBOX
SoundEngine::SoundEngine() {}
void SoundEngine::init(Options *pOptions)
@@ -161,13 +161,13 @@ const char *SoundEngine::m_szStreamFileA[eStream_Max]=
// The End
"the_end_dragon_alive",
"the_end_end",
// Battle
"BattleMode1",
"BattleMode2",
"BattleMode3",
"BattleMode4",
// CDs
"11",
"13",
@@ -209,11 +209,11 @@ void SoundEngine::init(Options* pOptions)
m_MasterEffectsVolume = 1.0f;
m_validListenerCount = 1;
m_bSystemMusicPlaying = false;
app.DebugPrintf("---miniaudio initialized\n");
return;
}
@@ -402,7 +402,7 @@ void SoundEngine::tick(shared_ptr<Mob> *players, float a)
// store the listener positions for splitscreen
m_ListenerA[i].vPosition.x = x;
m_ListenerA[i].vPosition.y = y;
m_ListenerA[i].vPosition.z = z;
m_ListenerA[i].vPosition.z = z;
m_ListenerA[i].vOrientFront.x = -ySin;
m_ListenerA[i].vOrientFront.y = 0;
@@ -452,7 +452,7 @@ SoundEngine::SoundEngine()
m_musicStreamActive = false;
m_StreamState=eMusicStreamState_Idle;
m_iMusicDelay=0;
m_validListenerCount=0;
m_validListenerCount=0;
m_bHeardTrackA=nullptr;
@@ -542,7 +542,7 @@ void SoundEngine::play(int iSound, float x, float y, float z, float volume, floa
{
char basePlusExt[256];
sprintf_s(basePlusExt, "%s%s", basePath, extensions[extIdx]);
DWORD attr = GetFileAttributesA(basePlusExt);
if (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY))
{
@@ -562,7 +562,7 @@ void SoundEngine::play(int iSound, float x, float y, float z, float volume, floa
{
char numberedPath[256];
sprintf_s(numberedPath, "%s%d%s", basePath, i, extensions[extIdx]);
DWORD attr = GetFileAttributesA(numberedPath);
if (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY))
{
@@ -578,7 +578,7 @@ void SoundEngine::play(int iSound, float x, float y, float z, float volume, floa
{
char numberedPath[256];
sprintf_s(numberedPath, "%s%d%s", basePath, chosen, extensions[extIdx]);
DWORD attr = GetFileAttributesA(numberedPath);
if (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY))
{
@@ -600,7 +600,7 @@ void SoundEngine::play(int iSound, float x, float y, float z, float volume, floa
s->info.x = x;
s->info.y = y;
s->info.z = z;
s->info.volume = volume;
s->info.pitch = pitch;
s->info.bIs3D = true;
@@ -725,7 +725,7 @@ void SoundEngine::stopLoopingSound(MiniAudioSound* sound)
/////////////////////////////////////////////
//
//
//
// startElytraSound / stopElytraSound
// Manages a single persistent looping sound for elytra gliding.
// Call startElytraSound every tick while gliding (it no-ops if already running,
@@ -966,7 +966,7 @@ void SoundEngine::playStreaming(const wstring& name, float x, float y, float z,
m_bCurrentStreamIsMenuMusic = false;
m_musicID = getMusicID(name);
m_iMusicDelay = 0;
if (m_StreamState == eMusicStreamState_Playing || m_StreamState == eMusicStreamState_Opening || m_musicStreamActive)
{
m_StreamState = eMusicStreamState_Fading;
@@ -1061,7 +1061,7 @@ int SoundEngine::getMusicID(eMusicType iDomain)
return GetRandomishTrack(m_iStream_Overworld_Min,m_iStream_Overworld_Max);
}
}
switch(iDomain)
{
case eMusicType_Nether:
@@ -1154,7 +1154,7 @@ void SoundEngine::updateSystemMusicPlaying(bool isPlaying)
// updateSoundEffectVolume
//
/////////////////////////////////////////////
void SoundEngine::updateSoundEffectVolume(float fVal)
void SoundEngine::updateSoundEffectVolume(float fVal)
{
m_MasterEffectsVolume=fVal;
//AIL_set_variable_float(0,"UserEffectVol",fVal);
@@ -1170,7 +1170,7 @@ int SoundEngine::OpenStreamThreadProc(void* lpParameter)
SoundEngine* soundEngine = (SoundEngine*)lpParameter;
const char* ext = strrchr(soundEngine->m_szStreamName, '.');
if (soundEngine->m_musicStreamActive)
{
ma_sound_stop(&soundEngine->m_musicStream);
@@ -1205,7 +1205,7 @@ int SoundEngine::OpenStreamThreadProc(void* lpParameter)
// playMusicTick
//
/////////////////////////////////////////////
void SoundEngine::playMusicTick()
void SoundEngine::playMusicTick()
{
// AP - vita will update the music during the mixer callback
#ifndef __PSVITA__
@@ -1214,7 +1214,7 @@ void SoundEngine::playMusicTick()
}
// AP - moved to a separate function so it can be called from the mixer callback on Vita
void SoundEngine::playMusicUpdate()
void SoundEngine::playMusicUpdate()
{
static float fMusicVol = 0.0f;
fMusicVol = getMasterMusicVolume();
@@ -1248,7 +1248,7 @@ void SoundEngine::playMusicUpdate()
// 4J-PB - Need to check if we are a patched BD build
if(app.GetBootedFromDiscPatch())
{
sprintf(m_szStreamName,"%s/%s",app.GetBDUsrDirPath(m_szMusicPath), m_szMusicPath );
sprintf(m_szStreamName,"%s/%s",app.GetBDUsrDirPath(m_szMusicPath), m_szMusicPath );
app.DebugPrintf("SoundEngine::playMusicUpdate - (booted from disc patch) music path - %s",m_szStreamName);
}
else
@@ -1282,7 +1282,7 @@ void SoundEngine::playMusicUpdate()
SetIsPlayingStreamingGameMusic(true);
SetIsPlayingStreamingCDMusic(false);
m_StreamingAudioInfo.bIs3D=false;
#ifdef _XBOX_ONE
wstring &wstrSoundName=dlcAudioFile->GetSoundName(m_musicID);
wstring wstrFile=L"TPACK:\\Data\\" + wstrSoundName +L".wav";
@@ -1315,7 +1315,7 @@ void SoundEngine::playMusicUpdate()
}
}
else
{
{
// 4J-PB - if this is a PS3 disc patch, we have to check if the music file is in the patch data
#ifdef __PS3__
if(app.GetBootedFromDiscPatch() && (m_musicID<m_iStream_CD_1))
@@ -1327,7 +1327,7 @@ void SoundEngine::playMusicUpdate()
strcat((char *)m_szStreamName,".wav");
// check if this is in the patch data
sprintf(m_szStreamName,"%s/%s",app.GetBDUsrDirPath(m_szStreamName), m_szMusicPath );
sprintf(m_szStreamName,"%s/%s",app.GetBDUsrDirPath(m_szStreamName), m_szMusicPath );
strcat((char *)m_szStreamName,"music/");
strcat((char *)m_szStreamName,m_szStreamFileA[m_musicID]);
strcat((char *)m_szStreamName,".wav");
@@ -1357,7 +1357,7 @@ void SoundEngine::playMusicUpdate()
strcat((char *)m_szStreamName,m_szStreamFileA[m_musicID]);
strcat((char *)m_szStreamName,".wav");
}
#else
#else
if(m_musicID<m_iStream_CD_1)
{
SetIsPlayingStreamingGameMusic(true);
@@ -1376,7 +1376,7 @@ void SoundEngine::playMusicUpdate()
}
strcat((char *)m_szStreamName,m_szStreamFileA[m_musicID]);
strcat((char *)m_szStreamName,".wav");
#endif
}
@@ -1385,7 +1385,7 @@ void SoundEngine::playMusicUpdate()
// strcat((char *)szStreamName,SoundName);
FILE* pFile = nullptr;
if (fopen_s(&pFile, reinterpret_cast<char*>(m_szStreamName), "rb") == 0 && pFile)
{
fclose(pFile);
@@ -1402,7 +1402,7 @@ void SoundEngine::playMusicUpdate()
for (size_t i = 0; i < extCount; i++)
{
strcpy_s(dotPos, 5, extensions[i]);
if (fopen_s(&pFile, reinterpret_cast<char*>(m_szStreamName), "rb") == 0 && pFile)
{
fclose(pFile);
@@ -1431,7 +1431,7 @@ void SoundEngine::playMusicUpdate()
break;
case eMusicStreamState_Opening:
if( !m_openStreamThread->isRunning() )
if( !m_openStreamThread->IsRunning() )
{
delete m_openStreamThread;
m_openStreamThread = nullptr;
@@ -1445,27 +1445,27 @@ void SoundEngine::playMusicUpdate()
{
const bool isCD = (m_musicID >= m_iStream_CD_1);
const char* folder = isCD ? "cds/" : "music/";
int n = sprintf_s(reinterpret_cast<char*>(m_szStreamName), 512, "%s%s%s.wav", m_szMusicPath, folder, m_szStreamFileA[m_musicID]);
if (n > 0)
{
FILE* pFile = nullptr;
if (fopen_s(&pFile, reinterpret_cast<char*>(m_szStreamName), "rb") == 0 && pFile)
{
fclose(pFile);
m_openStreamThread = new C4JThread(OpenStreamThreadProc, this, "OpenStreamThreadProc");
m_openStreamThread->Run();
break;
}
}
}
m_StreamState = eMusicStreamState_Idle;
break;
}
if (m_StreamingAudioInfo.bIs3D)
{
ma_sound_set_spatialization_enabled(&m_musicStream, MA_TRUE);
@@ -1520,7 +1520,7 @@ void SoundEngine::playMusicUpdate()
}
break;
case eMusicStreamState_OpeningCancel:
if( !m_openStreamThread->isRunning() )
if( !m_openStreamThread->IsRunning() )
{
delete m_openStreamThread;
m_openStreamThread = nullptr;
@@ -1625,7 +1625,7 @@ void SoundEngine::playMusicUpdate()
// Set the end track
m_musicID = getMusicID(eMusicType_End);
SetIsPlayingEndMusic(true);
SetIsPlayingNetherMusic(false);
SetIsPlayingNetherMusic(false);
}
else if(!playerInEnd && GetIsPlayingEndMusic())
{
@@ -1636,7 +1636,7 @@ void SoundEngine::playMusicUpdate()
// Set the end track
m_musicID = getMusicID(eMusicType_Nether);
SetIsPlayingEndMusic(false);
SetIsPlayingNetherMusic(true);
SetIsPlayingNetherMusic(true);
}
else
{
@@ -1645,7 +1645,7 @@ void SoundEngine::playMusicUpdate()
// Set the end track
m_musicID = getMusicID(eMusicType_Overworld);
SetIsPlayingEndMusic(false);
SetIsPlayingNetherMusic(false);
SetIsPlayingNetherMusic(false);
}
}
else if (playerInNether && !GetIsPlayingNetherMusic())
@@ -1728,7 +1728,7 @@ void SoundEngine::playMusicUpdate()
break;
case eMusicStreamState_Completed:
{
{
// random delay of up to 3 minutes for music
m_iMusicDelay = random->nextInt(20 * 60 * 3);//random->nextInt(20 * 60 * 10) + 20 * 60 * 10;
// Check if we have a local player in The Nether or in The End, and play that music if they are
@@ -326,7 +326,6 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame
thread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL);
#endif //__PS3__
thread->SetProcessor(CPU_CORE_SERVER);
thread->Run();
ServerReadyWait();
@@ -2154,7 +2153,7 @@ void CGameNetworkManager::ServerStoppedWait()
// If this is called from the main thread, then this won't be ticking anything which can mean that the storage manager state can't progress.
// This means that the server thread we are waiting on won't ever finish, as it might be locked waiting for this to complete itself.
// Do some ticking here then if this is the case.
if( C4JThread::isMainThread() )
if( C4JThread::IsMainThread() )
{
int result = WAIT_TIMEOUT;
do
+5 -6
View File
@@ -231,7 +231,7 @@ static wstring GetControlTypeSkinPath(int controlType, bool hd)
{
return wstring(L"Graphics\\ControlType\\HD\\") + skinName + L"HD.swf";
}
return wstring(L"Graphics\\ControlType\\") + skinName + L".swf";
}
#endif
@@ -823,7 +823,6 @@ void UIController::ReloadSkin()
#else
m_reloadSkinThread = new C4JThread(reloadSkinThreadProc, (void*)this, "Reload skin thread");
m_reloadSkinThread->SetProcessor(CPU_CORE_UI_SCENE);
// Navigate to the timer scene so that we can display something while the loading is happening
ui.NavigateToScene(0,eUIScene_Timer,(void *)1,eUILayer_Tooltips,eUIGroup_Fullscreen);
@@ -939,7 +938,7 @@ int UIController::reloadSkinThreadProc(void* lpParam)
bool UIController::IsReloadingSkin()
{
return m_reloadSkinThread && (!m_reloadSkinThread->hasStarted() || m_reloadSkinThread->isRunning());
return m_reloadSkinThread && (!m_reloadSkinThread->HasStarted() || m_reloadSkinThread->IsRunning());
}
bool UIController::IsExpectingOrReloadingSkin()
@@ -2284,7 +2283,7 @@ GDrawTexture * RADLINK UIController::TextureSubstitutionCreateCallback ( void *
*height = 96;
}
}
#endif
*destroy_callback_data = (void *)id;
@@ -3031,7 +3030,7 @@ void UIController::SetSelectedItem(unsigned int iPad, const wstring &label1, con
group = eUIGroup_Fullscreen;
}
bool handled = false;
auto pHUD = m_groups[static_cast<int>(group)]->getHUD();
if(pHUD && pHUD->hasMovie())
{
@@ -3312,7 +3311,7 @@ void UIController::UpdateAutosaveCountdownTimer(unsigned int uiSeconds)
const int primaryPad = ProfileManager.GetPrimaryPad();
const int controlType = app.GetGameSettings(primaryPad, eGameSetting_ControlType);
const bool consoleAutosave = (controlType == 0 || controlType == 1 || controlType == 4);
if (!consoleAutosave)
if (!consoleAutosave)
{
WCHAR wcAutosaveCountdown[100];
swprintf( wcAutosaveCountdown, 100, app.GetString(IDS_AUTOSAVE_COUNTDOWN),uiSeconds);
@@ -60,7 +60,6 @@ UIScene_FullscreenProgress::UIScene_FullscreenProgress(int iPad, void *initData,
m_labelTip.setVisible( m_CompletionData->bShowTips );
thread = new C4JThread(params->func, params->lpParam, "FullscreenProgress");
thread->SetProcessor(CPU_CORE_UI_SCENE); // TODO 4J Stu - Make sure this is a good thread/core to use
m_threadCompleted = false;
thread->Run();
@@ -219,7 +218,7 @@ void UIScene_FullscreenProgress::tick()
else
{
if(( m_CompletionData->bRequiresUserAction == TRUE ) && (!m_bWasCancelled))
{
{
m_threadCompleted = true;
m_buttonConfirm.setVisible( true );
// 4J-TomK - rebuild touch after confirm button made visible again
@@ -239,7 +238,7 @@ void UIScene_FullscreenProgress::tick()
{
case e_ProgressCompletion_AutosaveNavigateBack:
app.DebugPrintf("e_ProgressCompletion_AutosaveNavigateBack\n");
{
{
// 4J Stu - Fix for #65437 - Customer Encountered: Code: Settings: Autosave option doesn't work when the Host goes into idle state during gameplay.
// Autosave obviously cannot occur if an ignore autosave menu is displayed, so even if we navigate back to a scene and not empty
// then we still want to reset this flag which was set true by the navigate to the fullscreen progress
@@ -285,7 +284,7 @@ void UIScene_FullscreenProgress::tick()
app.DebugPrintf("Default\n");
break;
}
}
}
}
}
}
@@ -309,7 +308,7 @@ void UIScene_FullscreenProgress::handleInput(int iPad, int key, bool repeat, boo
break;
case ACTION_MENU_B:
case ACTION_MENU_CANCEL:
if( pressed && m_cancelFunc != nullptr && !m_bWasCancelled )
if( pressed && m_cancelFunc != nullptr && !m_bWasCancelled )
{
m_cancelText = -1;
updateTooltips();
@@ -376,7 +375,7 @@ void UIScene_FullscreenProgress::handleTimerComplete(int id)
switch(id)
{
case TIMER_FULLSCREEN_TIPS:
{
{
// display the next tip
wstring wsText=app.FormatHTMLString(m_iPad,app.GetString(app.GetNextTip()));
wchar_t startTags[64];
@@ -385,7 +384,7 @@ void UIScene_FullscreenProgress::handleTimerComplete(int id)
m_labelTip.setLabel(wsText);
}
break;
}
}
}
void UIScene_FullscreenProgress::SetWasCancelled(bool wasCancelled)
@@ -397,10 +396,10 @@ bool UIScene_FullscreenProgress::isReadyToDelete()
{
if( m_bWaitForThreadToDelete )
{
return !thread->isRunning();
return !thread->IsRunning();
}
else
{
return true;
}
}
}
+1 -2
View File
@@ -183,7 +183,7 @@ GameRenderer::GameRenderer(Minecraft *mc)
#ifndef MINECRAFT_SERVER_BUILD
#ifdef MULTITHREAD_ENABLE
m_updateEvents = new C4JThread::EventArray(eUpdateEventCount, C4JThread::EventArray::e_modeAutoClear);
m_updateEvents = new C4JThread::EventArray(eUpdateEventCount, C4JThread::EventArray::Mode::AutoClear);
m_updateEvents->Set(eUpdateEventIsFinished);
InitializeCriticalSection(&m_csDeleteStack);
@@ -191,7 +191,6 @@ GameRenderer::GameRenderer(Minecraft *mc)
#ifdef __PS3__
m_updateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL);
#endif// __PS3__
m_updateThread->SetProcessor(CPU_CORE_CHUNK_UPDATE);
m_updateThread->Run();
#endif
#endif
-14
View File
@@ -4185,20 +4185,6 @@ void LevelRenderer::staticCtor()
rebuildThreads[i] = new C4JThread(rebuildChunkThreadProc,(void *)i,threadName);
s_activationEventA[i] = new C4JThread::Event();
// Threads 1,3 and 5 are generally idle so use them
if((i%3) == 0) rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_A);
else if((i%3) == 1)
{
rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_B);
#ifdef __ORBIS__
rebuildThreads[i]->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2.
#endif
}
else if((i%3) == 2) rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_C);
//ResumeThread( saveThreads[j] );
rebuildThreads[i]->Run();
}
}
@@ -1,17 +1,13 @@
#include "stdafx.h"
#include "Linux_UIController.h"
#define _ENABLEIGGY
ConsoleUIController ui;
void ConsoleUIController::init(S32 w, S32 h)
{
#ifdef _ENABLEIGGY
// Shared init
preInit(w,h);
postInit();
#endif
}
void ConsoleUIController::render()
@@ -51,4 +47,4 @@ void ConsoleUIController::destroySubstitutionTexture(void *destroyCallBackData,
void ConsoleUIController::shutdown()
{
}
}
+2 -3
View File
@@ -975,7 +975,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring
pSave->ConvertToLocalPlatform();
storage = std::make_shared<McRegionLevelStorage>(pSave, File(L"."), name, true);
#endif
}
@@ -1063,8 +1063,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring
m_postUpdateThread = new C4JThread(runPostUpdate, this, "Post processing", 256*1024);
m_postUpdateTerminate = false;
m_postUpdateThread->SetProcessor(CPU_CORE_POST_PROCESSING);
m_postUpdateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL);
m_postUpdateThread->SetPriority(static_cast<C4JThread::ThreadPriority>(THREAD_PRIORITY_ABOVE_NORMAL));
m_postUpdateThread->Run();
int64_t startTime = System::currentTimeMillis();
-8
View File
@@ -828,14 +828,6 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener)
//saveThreads[j] = CreateThread(nullptr,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]);
saveThreads[j] = new C4JThread(runSaveThreadProc,(void *)&threadData[j],threadName);
//app.DebugPrintf("Created new thread: %s\n",threadName);
// Threads 1,3 and 5 are generally idle so use them (this call waits on thread 2)
if(j == 0) saveThreads[j]->SetProcessor(CPU_CORE_SAVE_THREAD_A); //XSetThreadProcessor( saveThreads[j], 1);
else if(j == 1) saveThreads[j]->SetProcessor(CPU_CORE_SAVE_THREAD_B); //XSetThreadProcessor( saveThreads[j], 3);
else if(j == 2) saveThreads[j]->SetProcessor(CPU_CORE_SAVE_THREAD_C); //XSetThreadProcessor( saveThreads[j], 5);
//ResumeThread( saveThreads[j] );
saveThreads[j]->Run();
}
-1
View File
@@ -69,7 +69,6 @@ void ServerLevel::staticCtor()
InitializeCriticalSection(&m_updateCS[2]);
m_updateThread = new C4JThread(runUpdate, nullptr, "Tile update");
m_updateThread->SetProcessor(CPU_CORE_TILE_UPDATE);
#ifdef __ORBIS__
m_updateThread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2.
#endif
+5 -6
View File
@@ -624,7 +624,7 @@ int main(int argc, char **argv)
LogErrorf("world-io", "Failed to load configured world \"%s\".", WideToUtf8(targetWorldName).c_str());
g_NetworkManager.Terminate();
CleanupDevice();
return 4;
}
@@ -662,7 +662,7 @@ int main(int argc, char **argv)
C4JThread *startThread = new C4JThread(&CGameNetworkManager::RunNetworkGameThreadProc, (LPVOID)param, "RunNetworkGame");
startThread->Run();
while (startThread->isRunning() && !IsShutdownRequested())
while (startThread->IsRunning() && !IsShutdownRequested())
{
TickCoreSystems();
Sleep(10);
@@ -677,7 +677,7 @@ int main(int argc, char **argv)
LogErrorf("startup", "Failed to start dedicated server (code %d).", startupResult);
g_NetworkManager.Terminate();
CleanupDevice();
return 4;
}
@@ -788,7 +788,7 @@ int main(int argc, char **argv)
{
C4JThread waitThread(&WaitForServerStoppedThreadProc, NULL, "WaitServerStopped");
waitThread.Run();
while (waitThread.isRunning())
while (waitThread.IsRunning())
{
TickCoreSystems();
Sleep(10);
@@ -807,8 +807,7 @@ int main(int argc, char **argv)
LogDebugf("shutdown", "Network manager terminated.");
ServerRuntime::ServerLogManager::Shutdown();
CleanupDevice();
return 0;
}
File diff suppressed because it is too large. Load diff
+145 -206
View File
@@ -1,234 +1,173 @@
#pragma once
#include <queue>
typedef int (C4JThreadStartFunc)(void* lpThreadParameter);
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
using C4JThreadStartFunc = int(void* lpThreadParameter);
class Level;
#if defined(_XBOX_ONE) || defined(__ORBIS__)
#define CPU_CORE_MAIN_THREAD 0
#define CPU_CORE_SERVER 1
#define CPU_CORE_CHUNK_UPDATE 2
#define CPU_CORE_REMOVE_PLAYER 2
#define CPU_CORE_CHUNK_REBUILD_A 3
#define CPU_CORE_SAVE_THREAD_A 3
#define CPU_CORE_UI_SCENE 3
#define CPU_CORE_POST_PROCESSING 3
#define CPU_CORE_DQR_REALTIMESESSION 3
#define CPU_CORE_CHUNK_REBUILD_B 4
#define CPU_CORE_SAVE_THREAD_B 4
#define CPU_CORE_TILE_UPDATE 4
#define CPU_CORE_CONNECTIONS 4
#define CPU_CORE_CHUNK_REBUILD_C 5
#define CPU_CORE_SAVE_THREAD_C 5
#define CPU_CORE_LEADERBOARDS 5 // Orbis only
#else
#define CPU_CORE_MAIN_THREAD 0
#define CPU_CORE_CHUNK_REBUILD_A 1
#define CPU_CORE_SAVE_THREAD_A 1
#define CPU_CORE_TILE_UPDATE 1
#define CPU_CORE_CONNECTIONS 1
#define CPU_CORE_CHUNK_UPDATE 2
#define CPU_CORE_REMOVE_PLAYER 2
#define CPU_CORE_CHUNK_REBUILD_B 3
#define CPU_CORE_SAVE_THREAD_B 3
#define CPU_CORE_UI_SCENE 3
#define CPU_CORE_POST_PROCESSING 3
#define CPU_CORE_SERVER 4
#define CPU_CORE_CHUNK_REBUILD_C 5
#define CPU_CORE_SAVE_THREAD_C 5
#define CPU_CORE_LEADERBOARDS 5 // Sony only
#endif
class C4JThread
{
class C4JThread {
public:
struct WaitResult {
static constexpr std::uint32_t Signaled = 0;
static constexpr std::uint32_t Timeout = 258;
};
class Event
{
public:
enum EMode
{
e_modeAutoClear,
e_modeManualClear
};
Event(EMode mode = e_modeAutoClear);
~Event();
void Set();
void Clear();
DWORD WaitForSignal(int timeoutMs);
enum class ThreadPriority : int {
Idle = -15,
Lowest = -2,
BelowNormal = -1,
Normal = 0,
AboveNormal = 1,
Highest = 2,
TimeCritical = 15
};
private:
EMode m_mode;
#ifdef __PS3__
sys_event_flag_t m_event;
#elif defined __ORBIS__
SceKernelEventFlag m_event;
#elif defined __PSVITA__
SceUID m_event;
#else
HANDLE m_event;
#endif // __PS3__
};
static constexpr int kInfiniteTimeout = -1;
static constexpr int kStillActive = 259;
class EventArray
{
public:
enum EMode
{
e_modeAutoClear,
e_modeManualClear
};
class Event {
public:
enum class Mode { AutoClear, ManualClear };
EventArray(int size, EMode mode = e_modeAutoClear);
explicit Event(Mode mode = Mode::AutoClear);
~Event() = default;
void Set(int index);
void Clear(int index);
void SetAll();
void ClearAll();
DWORD WaitForAll(int timeoutMs);
DWORD WaitForAny(int timeoutMs);
DWORD WaitForSingle(int index, int timeoutMs);
#ifdef __PS3__
void Cancel();
#endif
void Set();
void Clear();
std::uint32_t WaitForSignal(int timeoutMs);
private:
int m_size;
EMode m_mode;
#ifdef __PS3__
sys_event_flag_t m_events;
#elif defined __ORBIS__
SceKernelEventFlag m_events;
#elif defined __PSVITA__
SceUID m_events;
#else
HANDLE* m_events;
#endif // __PS3__
};
private:
Mode m_mode;
std::mutex m_mutex;
std::condition_variable m_condition;
bool m_signaled;
};
// Lock-free bitmask of up to 32 events; waiters block via
// std::atomic::wait.
class EventArray {
public:
enum class Mode { AutoClear, ManualClear };
explicit EventArray(int size, Mode mode = Mode::AutoClear);
class EventQueue
{
typedef void (UpdateFunc)(void* lpParameter);
typedef void (ThreadInitFunc)();
void Set(int index);
void Clear(int index);
void SetAll();
void ClearAll();
std::uint32_t WaitForAll(int timeoutMs);
std::uint32_t WaitForAny(int timeoutMs);
std::uint32_t WaitForSingle(int index, int timeoutMs);
C4JThread* m_thread;
std::queue<void*> m_queue;
C4JThread::EventArray* m_startEvent;
C4JThread::Event* m_finishedEvent;
CRITICAL_SECTION m_critSect;
UpdateFunc* m_updateFunc;
ThreadInitFunc* m_threadInitFunc;
char m_threadName[64];
int m_processor;
int m_priority;
void init();
static int threadFunc(void* lpParam);
void threadPoll();
private:
int m_size;
Mode m_mode;
std::atomic<std::uint32_t> m_signaledMask;
};
public:
EventQueue(UpdateFunc* updateFunc, ThreadInitFunc threadInitFunc, const char* szThreadName);
void setProcessor(int proc) { m_processor = proc; if(m_thread) m_thread->SetProcessor(proc); }
void setPriority(int priority) { m_priority = priority; if(m_thread) m_thread->SetPriority(priority); }
void sendEvent(Level* pLevel);
void waitForFinish();
};
class EventQueue {
public:
using UpdateFunc = void(void* lpParameter);
using ThreadInitFunc = void();
EventQueue(UpdateFunc* updateFunc, ThreadInitFunc* threadInitFunc,
const char* threadName);
~EventQueue();
EventQueue(const EventQueue&) = delete;
EventQueue& operator=(const EventQueue&) = delete;
C4JThread(C4JThreadStartFunc* startFunc, void* param, const char* threadName, int stackSize = 0);
C4JThread( const char* mainThreadName ); // only used for the main thread
~C4JThread();
void SetPriority(ThreadPriority priority);
void SendEvent(Level* pLevel);
void WaitForFinish();
void Run();
bool isRunning() { return m_isRunning; }
bool hasStarted() { return m_hasStarted; }
void SetProcessor(int proc);
void SetPriority(int priority);
DWORD WaitForCompletion(int timeoutMs);
int GetExitCode();
char* getName() { return m_threadName; }
static void Sleep(int millisecs);
static C4JThread* getCurrentThread();
static bool isMainThread();
static char* getCurrentThreadName() { return getCurrentThread()->getName(); }
private:
void Init();
static int ThreadFunc(void* lpParam);
void ThreadPoll();
#ifdef __ORBIS__
static void PushAffinityAllCores(); // PS4 only
static void PopAffinity();
static __thread SceKernelCpumask m_oldAffinityMask;
#endif // __ORBIS__
std::unique_ptr<C4JThread> m_thread;
std::queue<void*> m_queue;
std::mutex m_mutex;
std::condition_variable m_queueCondition;
std::condition_variable m_drainedCondition;
UpdateFunc* m_updateFunc;
ThreadInitFunc* m_threadInitFunc;
std::string m_threadName;
ThreadPriority m_priority;
bool m_busy;
std::once_flag m_initOnce;
std::atomic<bool> m_stopRequested;
};
#ifdef _XBOX_ONE
static void StaticInit();
#endif
C4JThread(C4JThreadStartFunc* startFunc, void* param,
const char* threadName, int stackSize = 0);
explicit C4JThread(const char* mainThreadName);
~C4JThread();
C4JThread(const C4JThread&) = delete;
C4JThread& operator=(const C4JThread&) = delete;
void Run();
[[nodiscard]] bool IsRunning() const noexcept {
return m_isRunning.load(std::memory_order_acquire);
}
[[nodiscard]] bool HasStarted() const noexcept {
return m_hasStarted.load(std::memory_order_acquire);
}
void SetPriority(ThreadPriority priority);
std::uint32_t WaitForCompletion(int timeoutMs);
[[nodiscard]] int GetExitCode() const noexcept;
[[nodiscard]] const char* GetName() const noexcept {
return m_threadName.c_str();
}
static C4JThread* GetCurrentThread() noexcept;
static bool IsMainThread() noexcept;
static const char* GetCurrentThreadName() noexcept {
const C4JThread* pThread = GetCurrentThread();
return pThread ? pThread->GetName() : "(4J) Unknown thread";
}
static void SetThreadName(std::uint32_t threadId, const char* threadName);
static void SetCurrentThreadName(const char* threadName);
// TODO(C++26): When we switch to C++26, replace EventQueue with
// std::execution (senders/receivers) for structured concurrency.
// TODO(C++26): When we switch to C++26, use std::hazard_pointer / std::rcu
// for lock-free data structure reclamation.
private:
void* m_threadParam;
C4JThreadStartFunc* m_startFunc;
int m_stackSize;
char m_threadName[64];
bool m_isRunning;
bool m_hasStarted;
int m_exitCode;
int64_t m_lastSleepTime;
static std::vector<C4JThread*> ms_threadList;
static CRITICAL_SECTION ms_threadListCS;
static void EntryPoint(C4JThread* pThread);
static C4JThread& GetMainThreadInstance() noexcept;
#ifdef _XBOX_ONE
// 4J Stu - On XboxOne the main thread is not the one that does all the static init, so we have to set this up later
static C4JThread *m_mainThread;
#else
static C4JThread m_mainThread;
#endif
void* m_threadParam;
C4JThreadStartFunc* m_startFunc;
int m_stackSize;
std::string m_threadName;
std::atomic<bool> m_isRunning;
std::atomic<bool> m_hasStarted;
std::atomic<int> m_exitCode;
#ifdef __PS3__
sys_ppu_thread_t m_threadID;
Event *m_completionFlag;
int m_priority;
static void entryPoint(uint64_t);
#elif defined __ORBIS__
ScePthreadAttr m_threadAttr;
ScePthread m_threadID;
Event *m_completionFlag;
int m_priority;
static void *entryPoint(void *);
#elif defined __PSVITA__
SceUID m_threadID;
Event *m_completionFlag;
int m_priority;
static SceInt32 entryPoint(SceSize argSize, void *pArgBlock);
#else
DWORD m_threadID;
HANDLE m_threadHandle;
Event *m_completionFlag;
static DWORD WINAPI entryPoint(LPVOID lpParam);
#endif
std::thread::id m_threadID;
std::thread m_threadHandle;
std::unique_ptr<Event> m_completionFlag;
std::atomic<ThreadPriority> m_requestedPriority;
std::atomic<std::int64_t> m_nativeTid;
static thread_local C4JThread* ms_currentThread;
};
void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName );
class CriticalSectionScopeLock
{
CRITICAL_SECTION* m_pCS;
public:
CriticalSectionScopeLock(CRITICAL_SECTION* pCS) { m_pCS = pCS; EnterCriticalSection(m_pCS); }
~CriticalSectionScopeLock() { LeaveCriticalSection(m_pCS); }
};
+1 -2
View File
@@ -116,8 +116,7 @@ Connection::Connection(Socket *socket, const wstring& id, PacketListener *packet
readThread = new C4JThread(runRead, static_cast<void *>(this), readThreadName, READ_STACK_SIZE);
writeThread = new C4JThread(runWrite, this, writeThreadName, WRITE_STACK_SIZE);
readThread->SetProcessor(CPU_CORE_CONNECTIONS);
writeThread->SetProcessor(CPU_CORE_CONNECTIONS );
#ifdef __ORBIS__
readThread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2.
writeThread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2.
+13 -27
View File
@@ -320,36 +320,22 @@ void McRegionChunkStorage::flush()
}
void McRegionChunkStorage::staticCtor()
{
InitializeCriticalSectionAndSpinCount(&cs_memory,5120);
void McRegionChunkStorage::staticCtor() {
for (unsigned int i = 0; i < 3; ++i) {
char threadName[256];
sprintf(threadName, "McRegion Save thread %d\n", i);
C4JThread::SetThreadName(0, threadName);
for(unsigned int i = 0; i < 3; ++i)
{
char threadName[256];
sprintf(threadName,"McRegion Save thread %d\n",i);
SetThreadName(0, threadName);
// saveThreads[j] =
// CreateThread(nullptr,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]);
s_saveThreads[i] =
new C4JThread(runSaveThreadProc, nullptr, threadName);
//saveThreads[j] = CreateThread(nullptr,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]);
s_saveThreads[i] = new C4JThread(runSaveThreadProc,nullptr,threadName);
// Log::info("Created new thread: %s\n",threadName);
//app.DebugPrintf("Created new thread: %s\n",threadName);
// Threads 1,3 and 5 are generally idle so use them
if(i == 0) s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_A);
else if(i == 1)
{
s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_B);
#ifdef __ORBIS__
s_saveThreads[i]->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2.
#endif
}
else if(i == 2) s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_C);
//ResumeThread( saveThreads[j] );
s_saveThreads[i]->Run();
}
// ResumeThread( saveThreads[j] );
s_saveThreads[i]->Run();
}
}
int McRegionChunkStorage::runSaveThreadProc(LPVOID lpParam)
+17
View File
@@ -0,0 +1,17 @@
// Linux stub implementations for ShutdownManager
// The PS3/PSVita versions have full implementations; on Linux these are no-ops.
#include "ShutdownManager.h"
#include "C4JThread.h"
void ShutdownManager::Initialise() {}
void ShutdownManager::StartShutdown() {}
void ShutdownManager::MainThreadHandleShutdown() {}
void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/) {}
void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/,
C4JThread::EventArray* /*eventArray*/) {}
bool ShutdownManager::ShouldRun(ShutdownManager::EThreadId /*threadId*/) {
return true;
}
void ShutdownManager::HasFinished(ShutdownManager::EThreadId /*threadId*/) {}
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <array>
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <mutex>
#include "C4JThread.h"
class ShutdownManager {
public:
enum EThreadId {
eMainThread,
eLeaderboardThread,
eCommerceThread,
ePostProcessThread,
eRunUpdateThread,
eRenderChunkUpdateThread,
eServerThread,
ePlatformStorageThreads,
eConnectionReadThreads,
eConnectionWriteThreads,
eEventQueueThreads,
eThreadIdCount
};
static void Initialise();
static void StartShutdown();
static void MainThreadHandleShutdown();
static void HasStarted(EThreadId threadId);
static void HasStarted(EThreadId threadId,
C4JThread::EventArray* eventArray);
static bool ShouldRun(EThreadId threadId);
static void HasFinished(EThreadId threadId);
private:
struct GroupState {
std::size_t started = 0;
std::size_t running = 0;
};
struct State {
std::mutex mutex;
std::condition_variable condition;
std::array<GroupState, eThreadIdCount> groups{};
std::atomic<bool> shutdownRequested{false};
};
static State& GetState();
};
+7 -5
View File
@@ -7,6 +7,8 @@ set(_MINECRAFT_WORLD_COMMON_CONSOLEHELPERS
"${CMAKE_CURRENT_SOURCE_DIR}/ArrayWithLength.h"
"${CMAKE_CURRENT_SOURCE_DIR}/C4JThread.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/C4JThread.h"
"${CMAKE_CURRENT_SOURCE_DIR}/ShutdownManager.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/ShutdownManager.h"
"${CMAKE_CURRENT_SOURCE_DIR}/Definitions.h"
"${CMAKE_CURRENT_SOURCE_DIR}/HashExtension.h"
"${CMAKE_CURRENT_SOURCE_DIR}/PerformanceTimer.cpp"
@@ -443,7 +445,7 @@ set(_MINECRAFT_WORLD_COMMON_NET_MINECRAFT_NETWORK_PACKET
"${CMAKE_CURRENT_SOURCE_DIR}/UseItemPacket.h"
"${CMAKE_CURRENT_SOURCE_DIR}/XZPacket.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/XZPacket.h"
"${CMAKE_CURRENT_SOURCE_DIR}/net.minecraft.network.packet.h"
"${CMAKE_CURRENT_SOURCE_DIR}/net.minecraft.network.packet.h"
"${CMAKE_CURRENT_SOURCE_DIR}/../Minecraft.Client/ParticleType.h"
"${CMAKE_CURRENT_SOURCE_DIR}/../Minecraft.Client/ParticleType.cpp"
)
@@ -869,7 +871,7 @@ set(_MINECRAFT_WORLD_COMMON_NET_MINECRAFT_WORLD_ENTITY_ITEM
"${CMAKE_CURRENT_SOURCE_DIR}/MinecartTNT.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/MinecartTNT.h"
"${CMAKE_CURRENT_SOURCE_DIR}/PrimedTnt.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/PrimedTnt.h"
"${CMAKE_CURRENT_SOURCE_DIR}/PrimedTnt.h"
"${CMAKE_CURRENT_SOURCE_DIR}/ArmorStand.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/ArmorStand.h"
"${CMAKE_CURRENT_SOURCE_DIR}/net.minecraft.world.entity.item.h"
@@ -912,10 +914,10 @@ set(_MINECRAFT_WORLD_COMMON_NET_MINECRAFT_WORLD_ENTITY_MONSTER
"${CMAKE_CURRENT_SOURCE_DIR}/Witch.h"
"${CMAKE_CURRENT_SOURCE_DIR}/Zombie.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/Zombie.h"
"${CMAKE_CURRENT_SOURCE_DIR}/Endermite.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/Endermite.h"
"${CMAKE_CURRENT_SOURCE_DIR}/Guardian.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/Guardian.h"
"${CMAKE_CURRENT_SOURCE_DIR}/net.minecraft.world.entity.monster.h"
@@ -2135,7 +2137,7 @@ set(_MINECRAFT_WORLD_COMMON_NET_MINECRAFT_WORLD_LEVEL_TILE
"${CMAKE_CURRENT_SOURCE_DIR}/SeaLanternTile.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/PrismarineTile.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/TallGrass2.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/FishFoodItem.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/ArmorStandItem.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/SavannaTreeFeature.cpp"