chore: fmt

This commit is contained in:
Tropical 2026-03-30 09:37:24 -05:00
parent e911e07a58
commit 1767c3f6e9
32 changed files with 2076 additions and 1896 deletions

View file

@ -929,8 +929,8 @@ void MultiPlayerLevel::removeUnusedTileEntitiesInRegion(int x0, int y0, int z0,
tileEntityList[i] = tileEntityList.back();
tileEntityList.pop_back();
// 4J Stu - Chests can create new tile entities when being
// removed, so disable this
// 4J Stu - Chests can create new tile entities when
// being removed, so disable this
m_bDisableAddNewTileEntities = true;
lc->removeTileEntity(te->x & 15, te->y, te->z & 15);
m_bDisableAddNewTileEntities = false;

View file

@ -192,15 +192,21 @@ ServerLevel::~ServerLevel() {
}
m_queuedSendTileUpdates.clear();
delete this->tracker; // MGH - added, we were losing about 500K going in
// and out the menus
delete this->tracker; // MGH - added, we were losing about 500K going
// in and out the menus
delete this->chunkMap;
}
// Make sure that the update thread isn't actually doing any updating
{ std::lock_guard<std::recursive_mutex> lock(m_updateCS[0]); }
{ std::lock_guard<std::recursive_mutex> lock(m_updateCS[1]); }
{ std::lock_guard<std::recursive_mutex> lock(m_updateCS[2]); }
{
std::lock_guard<std::recursive_mutex> lock(m_updateCS[0]);
}
{
std::lock_guard<std::recursive_mutex> lock(m_updateCS[1]);
}
{
std::lock_guard<std::recursive_mutex> lock(m_updateCS[2]);
}
m_updateTrigger->clearAll();
}
@ -441,8 +447,9 @@ void ServerLevel::tickTiles() {
{
std::lock_guard<std::recursive_mutex> lock(m_updateCS[iLev]);
// This section processes the tiles that need to be ticked, which we worked
// out in the previous tick (or haven't yet, if this is the first frame)
// This section processes the tiles that need to be ticked, which we
// worked out in the previous tick (or haven't yet, if this is the first
// frame)
/*int grassTicks = 0;
int lavaTicks = 0;
int otherTicks = 0;*/
@ -452,7 +459,8 @@ void ServerLevel::tickTiles() {
int z = m_updateTileZ[iLev][i];
if (hasChunkAt(x, y, z)) {
int id = getTile(x, y, z);
if (Tile::tiles[id] != nullptr && Tile::tiles[id]->isTicking()) {
if (Tile::tiles[id] != nullptr &&
Tile::tiles[id]->isTicking()) {
/*if(id == 2) ++grassTicks;
else if(id == 11) ++lavaTicks;
else ++otherTicks;*/
@ -461,7 +469,8 @@ void ServerLevel::tickTiles() {
}
}
// printf("Total ticks - Grass: %d, Lava: %d, Other: %d, Total: %d\n",
// grassTicks, lavaTicks, otherTicks, grassTicks + lavaTicks + otherTicks);
// grassTicks, lavaTicks, otherTicks, grassTicks + lavaTicks +
// otherTicks);
m_updateTileCount[iLev] = 0;
m_updateChunkCount[iLev] = 0;
}

File diff suppressed because it is too large Load diff

View file

@ -265,8 +265,9 @@ int MinecraftServer::runPostUpdate(void* lpParam) {
{
std::unique_lock<std::mutex> lock(server->m_postProcessCS);
int maxRequests = server->m_postProcessRequests.size();
while (server->m_postProcessRequests.size() &&
ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread)) {
while (
server->m_postProcessRequests.size() &&
ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread)) {
MinecraftServer::postProcessRequest request =
server->m_postProcessRequests.back();
server->m_postProcessRequests.pop_back();
@ -287,9 +288,10 @@ int MinecraftServer::runPostUpdate(void* lpParam) {
void MinecraftServer::addPostProcessRequest(ChunkSource* chunkSource, int x,
int z) {
{ std::lock_guard<std::mutex> lock(m_postProcessCS);
m_postProcessRequests.push_back(
MinecraftServer::postProcessRequest(x, z, chunkSource));
{
std::lock_guard<std::mutex> lock(m_postProcessCS);
m_postProcessRequests.push_back(
MinecraftServer::postProcessRequest(x, z, chunkSource));
}
}
@ -298,16 +300,17 @@ void MinecraftServer::postProcessTerminate(ProgressRenderer* mcprogress) {
size_t postProcessItemCount = 0;
size_t postProcessItemRemaining = 0;
{ std::lock_guard<std::mutex> lock(server->m_postProcessCS);
postProcessItemCount = server->m_postProcessRequests.size();
{
std::lock_guard<std::mutex> lock(server->m_postProcessCS);
postProcessItemCount = server->m_postProcessRequests.size();
}
do {
status = m_postUpdateThread->waitForCompletion(50);
if (status == C4JThread::WaitResult::Timeout) {
{ std::lock_guard<std::mutex> lock(server->m_postProcessCS);
postProcessItemRemaining =
server->m_postProcessRequests.size();
{
std::lock_guard<std::mutex> lock(server->m_postProcessCS);
postProcessItemRemaining = server->m_postProcessRequests.size();
}
if (postProcessItemCount) {

View file

@ -155,47 +155,51 @@ LevelChunk* MultiPlayerChunkCache::create(int x, int z) {
LevelChunk* lastChunk = chunk;
if (chunk == nullptr) {
{ std::unique_lock<std::mutex> lock(m_csLoadCreate);
// LevelChunk *chunk;
if (g_NetworkManager.IsHost()) // force here to disable sharing of data
{
// 4J-JEV: We are about to use shared data, abort if the server is
// stopped and the data is deleted.
if (MinecraftServer::getInstance()->serverHalted()) return nullptr;
std::unique_lock<std::mutex> lock(m_csLoadCreate);
// If we're the host, then don't create the chunk, share data from
// the server's copy
// LevelChunk *chunk;
if (g_NetworkManager
.IsHost()) // force here to disable sharing of data
{
// 4J-JEV: We are about to use shared data, abort if the server
// is stopped and the data is deleted.
if (MinecraftServer::getInstance()->serverHalted())
return nullptr;
// If we're the host, then don't create the chunk, share data
// from the server's copy
#ifdef _LARGE_WORLDS
LevelChunk* serverChunk =
MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunkLoadedOrUnloaded(x, z);
LevelChunk* serverChunk =
MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunkLoadedOrUnloaded(x, z);
#else
LevelChunk* serverChunk = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunk(x, z);
LevelChunk* serverChunk = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunk(x, z);
#endif
chunk = new LevelChunk(level, x, z, serverChunk);
// Let renderer know that this chunk has been created - it might
// have made render data from the EmptyChunk if it got to a chunk
// before the server sent it
level->setTilesDirty(x * 16, 0, z * 16, x * 16 + 15, 127,
z * 16 + 15);
hasData[idx] = true;
} else {
// Passing an empty array into the LevelChunk ctor, which it now
// detects and sets up the chunk as compressed & empty
byteArray bytes;
chunk = new LevelChunk(level, x, z, serverChunk);
// Let renderer know that this chunk has been created - it might
// have made render data from the EmptyChunk if it got to a
// chunk before the server sent it
level->setTilesDirty(x * 16, 0, z * 16, x * 16 + 15, 127,
z * 16 + 15);
hasData[idx] = true;
} else {
// Passing an empty array into the LevelChunk ctor, which it now
// detects and sets up the chunk as compressed & empty
byteArray bytes;
chunk = new LevelChunk(level, bytes, x, z);
chunk = new LevelChunk(level, bytes, x, z);
// 4J - changed to use new methods for lighting
chunk->setSkyLightDataAllBright();
// Arrays::fill(chunk->skyLight->data, (byte) 255);
}
// 4J - changed to use new methods for lighting
chunk->setSkyLightDataAllBright();
// Arrays::fill(chunk->skyLight->data,
//(byte) 255);
}
chunk->loaded = true;
chunk->loaded = true;
}
#if (defined _WIN64 || defined __LP64__)
@ -216,8 +220,9 @@ LevelChunk* MultiPlayerChunkCache::create(int x, int z) {
}
// Successfully updated the cache
{ std::lock_guard<std::mutex> lock(m_csLoadCreate);
loadedChunkList.push_back(chunk);
{
std::lock_guard<std::mutex> lock(m_csLoadCreate);
loadedChunkList.push_back(chunk);
}
} else {
// Something else must have updated the cache. Return that chunk and
@ -278,8 +283,9 @@ void MultiPlayerChunkCache::recreateLogicStructuresForChunk(int chunkX,
std::wstring MultiPlayerChunkCache::gatherStats() {
int size;
{ std::lock_guard<std::mutex> lock(m_csLoadCreate);
size = (int)loadedChunkList.size();
{
std::lock_guard<std::mutex> lock(m_csLoadCreate);
size = (int)loadedChunkList.size();
}
return L"MultiplayerChunkCache: " + _toString<int>(size);
}

View file

@ -69,9 +69,7 @@ PlayerConnection::PlayerConnection(MinecraftServer* server,
app.GetGameHostOption(eGameHostOption_Gamertags) != 0 ? true : false);
}
PlayerConnection::~PlayerConnection() {
delete connection;
}
PlayerConnection::~PlayerConnection() { delete connection; }
void PlayerConnection::tick() {
if (done) return;

View file

@ -48,7 +48,6 @@ PlayerList::PlayerList(MinecraftServer* server) {
maxPlayers = server->settings->getInt(L"max-players", 20);
doWhiteList = false;
}
PlayerList::~PlayerList() {
@ -59,7 +58,6 @@ PlayerList::~PlayerList() {
// back to this player
(*it)->gameMode = nullptr;
}
}
void PlayerList::placeNewPlayer(Connection* connection,
@ -991,73 +989,76 @@ void PlayerList::tick() {
}
}
{ std::lock_guard<std::mutex> lock(m_closePlayersCS);
while (!m_smallIdsToClose.empty()) {
std::uint8_t smallId = m_smallIdsToClose.front();
m_smallIdsToClose.pop_front();
{
std::lock_guard<std::mutex> lock(m_closePlayersCS);
while (!m_smallIdsToClose.empty()) {
std::uint8_t smallId = m_smallIdsToClose.front();
m_smallIdsToClose.pop_front();
std::shared_ptr<ServerPlayer> player = nullptr;
std::shared_ptr<ServerPlayer> player = nullptr;
for (unsigned int i = 0; i < players.size(); i++) {
std::shared_ptr<ServerPlayer> p = players.at(i);
// 4J Stu - May be being a bit overprotective with all the nullptr
// checks, but adding late in TU7 so want to be safe
if (p != nullptr && p->connection != nullptr &&
p->connection->connection != nullptr &&
p->connection->connection->getSocket() != nullptr &&
p->connection->connection->getSocket()->getSmallId() ==
smallId) {
player = p;
break;
for (unsigned int i = 0; i < players.size(); i++) {
std::shared_ptr<ServerPlayer> p = players.at(i);
// 4J Stu - May be being a bit overprotective with all the
// nullptr checks, but adding late in TU7 so want to be safe
if (p != nullptr && p->connection != nullptr &&
p->connection->connection != nullptr &&
p->connection->connection->getSocket() != nullptr &&
p->connection->connection->getSocket()->getSmallId() ==
smallId) {
player = p;
break;
}
}
if (player != nullptr) {
player->connection->disconnect(
DisconnectPacket::eDisconnect_Closed);
}
}
if (player != nullptr) {
player->connection->disconnect(
DisconnectPacket::eDisconnect_Closed);
}
}
}
{ std::lock_guard<std::mutex> lock(m_kickPlayersCS);
while (!m_smallIdsToKick.empty()) {
std::uint8_t smallId = m_smallIdsToKick.front();
m_smallIdsToKick.pop_front();
INetworkPlayer* selectedPlayer =
g_NetworkManager.GetPlayerBySmallId(smallId);
if (selectedPlayer != nullptr) {
if (selectedPlayer->IsLocal() != true) {
// #if 0
PlayerUID xuid = selectedPlayer->GetUID();
// Kick this player from the game
std::shared_ptr<ServerPlayer> player = nullptr;
{
std::lock_guard<std::mutex> lock(m_kickPlayersCS);
while (!m_smallIdsToKick.empty()) {
std::uint8_t smallId = m_smallIdsToKick.front();
m_smallIdsToKick.pop_front();
INetworkPlayer* selectedPlayer =
g_NetworkManager.GetPlayerBySmallId(smallId);
if (selectedPlayer != nullptr) {
if (selectedPlayer->IsLocal() != true) {
// #if 0
PlayerUID xuid = selectedPlayer->GetUID();
// Kick this player from the game
std::shared_ptr<ServerPlayer> player = nullptr;
for (unsigned int i = 0; i < players.size(); i++) {
std::shared_ptr<ServerPlayer> p = players.at(i);
PlayerUID playersXuid = p->getOnlineXuid();
if (p != nullptr &&
ProfileManager.AreXUIDSEqual(playersXuid, xuid)) {
player = p;
break;
for (unsigned int i = 0; i < players.size(); i++) {
std::shared_ptr<ServerPlayer> p = players.at(i);
PlayerUID playersXuid = p->getOnlineXuid();
if (p != nullptr &&
ProfileManager.AreXUIDSEqual(playersXuid, xuid)) {
player = p;
break;
}
}
}
if (player != nullptr) {
m_bannedXuids.push_back(player->getOnlineXuid());
// 4J Stu - If we have kicked a player, make sure that they
// have no privileges if they later try to join the world
// when trust players is off
player->enableAllPlayerPrivileges(false);
player->connection->setWasKicked();
player->connection->send(
std::shared_ptr<DisconnectPacket>(new DisconnectPacket(
DisconnectPacket::eDisconnect_Kicked)));
if (player != nullptr) {
m_bannedXuids.push_back(player->getOnlineXuid());
// 4J Stu - If we have kicked a player, make sure that
// they have no privileges if they later try to join the
// world when trust players is off
player->enableAllPlayerPrivileges(false);
player->connection->setWasKicked();
player->connection->send(
std::shared_ptr<DisconnectPacket>(
new DisconnectPacket(
DisconnectPacket::eDisconnect_Kicked)));
}
// #endif
}
// #endif
}
}
}
}
// Check our receiving players, and if they are dead see if we can replace
// them
@ -1624,14 +1625,16 @@ bool PlayerList::canReceiveAllPackets(std::shared_ptr<ServerPlayer> player) {
}
void PlayerList::kickPlayerByShortId(std::uint8_t networkSmallId) {
{ std::lock_guard<std::mutex> lock(m_kickPlayersCS);
m_smallIdsToKick.push_back(networkSmallId);
{
std::lock_guard<std::mutex> lock(m_kickPlayersCS);
m_smallIdsToKick.push_back(networkSmallId);
}
}
void PlayerList::closePlayerConnectionBySmallId(std::uint8_t networkSmallId) {
{ std::lock_guard<std::mutex> lock(m_closePlayersCS);
m_smallIdsToClose.push_back(networkSmallId);
{
std::lock_guard<std::mutex> lock(m_closePlayersCS);
m_smallIdsToClose.push_back(networkSmallId);
}
}

View file

@ -38,7 +38,6 @@ ServerChunkCache::ServerChunkCache(ServerLevel* level, ChunkStorage* storage,
m_unloadedCache = new LevelChunk*[XZSIZE * XZSIZE];
memset(m_unloadedCache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk*));
#endif
}
// 4J-PB added
@ -144,18 +143,19 @@ LevelChunk* ServerChunkCache::create(
LevelChunk* lastChunk = chunk;
if ((chunk == nullptr) || (chunk->x != x) || (chunk->z != z)) {
{ std::lock_guard<std::recursive_mutex> lock(m_csLoadCreate);
chunk = load(x, z);
if (chunk == nullptr) {
if (source == nullptr) {
chunk = emptyChunk;
} else {
chunk = source->getChunk(x, z);
{
std::lock_guard<std::recursive_mutex> lock(m_csLoadCreate);
chunk = load(x, z);
if (chunk == nullptr) {
if (source == nullptr) {
chunk = emptyChunk;
} else {
chunk = source->getChunk(x, z);
}
}
if (chunk != nullptr) {
chunk->load();
}
}
if (chunk != nullptr) {
chunk->load();
}
}
#if defined(_WIN64) || defined(__LP64__)
@ -649,11 +649,12 @@ bool ServerChunkCache::saveAllEntities() {
PIXBeginNamedEvent(0, "Save all entities");
PIXBeginNamedEvent(0, "saving to NBT");
{ std::lock_guard<std::recursive_mutex> lock(m_csLoadCreate);
for (auto it = m_loadedChunkList.begin(); it != m_loadedChunkList.end();
++it) {
storage->saveEntities(level, *it);
}
{
std::lock_guard<std::recursive_mutex> lock(m_csLoadCreate);
for (auto it = m_loadedChunkList.begin(); it != m_loadedChunkList.end();
++it) {
storage->saveEntities(level, *it);
}
}
PIXEndNamedEvent();
@ -860,7 +861,8 @@ int ServerChunkCache::runSaveThreadProc(void* lpParam) {
// Wait for the producer thread to tell us to start
params->wakeEvent->waitForSignal(
C4JThread::kInfiniteTimeout); // WaitForSingleObject(params->wakeEvent,INFINITE);
C4JThread::
kInfiniteTimeout); // WaitForSingleObject(params->wakeEvent,INFINITE);
// app.DebugPrintf("Save thread has started\n");
@ -887,7 +889,8 @@ int ServerChunkCache::runSaveThreadProc(void* lpParam) {
// Wait for the producer thread to tell us to go again
params->wakeEvent->waitForSignal(
C4JThread::kInfiniteTimeout); // WaitForSingleObject(params->wakeEvent,INFINITE);
C4JThread::
kInfiniteTimeout); // WaitForSingleObject(params->wakeEvent,INFINITE);
PIXEndNamedEvent();
}

View file

@ -34,17 +34,19 @@ void ServerConnection::addPlayerConnection(
}
void ServerConnection::handleConnection(std::shared_ptr<PendingConnection> uc) {
{ std::lock_guard<std::mutex> lock(pending_cs);
pending.push_back(uc);
{
std::lock_guard<std::mutex> lock(pending_cs);
pending.push_back(uc);
}
}
void ServerConnection::stop() {
{ std::lock_guard<std::mutex> lock(pending_cs);
for (unsigned int i = 0; i < pending.size(); i++) {
std::shared_ptr<PendingConnection> uc = pending[i];
uc->connection->close(DisconnectPacket::eDisconnect_Closed);
}
{
std::lock_guard<std::mutex> lock(pending_cs);
for (unsigned int i = 0; i < pending.size(); i++) {
std::shared_ptr<PendingConnection> uc = pending[i];
uc->connection->close(DisconnectPacket::eDisconnect_Closed);
}
}
for (unsigned int i = 0; i < players.size(); i++) {
@ -58,8 +60,9 @@ void ServerConnection::tick() {
// MGH - changed this so that the the CS lock doesn't cover the tick
// (was causing a lockup when 2 players tried to join)
std::vector<std::shared_ptr<PendingConnection> > tempPending;
{ std::lock_guard<std::mutex> lock(pending_cs);
tempPending = pending;
{
std::lock_guard<std::mutex> lock(pending_cs);
tempPending = pending;
}
for (unsigned int i = 0; i < tempPending.size(); i++) {
@ -76,12 +79,13 @@ void ServerConnection::tick() {
}
// now remove from the pending list
{ std::lock_guard<std::mutex> lock(pending_cs);
for (unsigned int i = 0; i < pending.size(); i++)
if (pending[i]->done) {
pending.erase(pending.begin() + i);
i--;
}
{
std::lock_guard<std::mutex> lock(pending_cs);
for (unsigned int i = 0; i < pending.size(); i++)
if (pending[i]->done) {
pending.erase(pending.begin() + i);
i--;
}
}
for (unsigned int i = 0; i < players.size(); i++) {

View file

@ -4613,9 +4613,10 @@ bool CMinecraftApp::DefaultCapeExists() {
std::wstring wTex = L"Special_Cape.png";
bool val = false;
{ std::lock_guard<std::mutex> lock(csMemFilesLock);
auto it = m_MEM_Files.find(wTex);
if (it != m_MEM_Files.end()) val = true;
{
std::lock_guard<std::mutex> lock(csMemFilesLock);
auto it = m_MEM_Files.find(wTex);
if (it != m_MEM_Files.end()) val = true;
}
return val;
@ -4624,9 +4625,10 @@ bool CMinecraftApp::DefaultCapeExists() {
bool CMinecraftApp::IsFileInMemoryTextures(const std::wstring& wName) {
bool val = false;
{ std::lock_guard<std::mutex> lock(csMemFilesLock);
auto it = m_MEM_Files.find(wName);
if (it != m_MEM_Files.end()) val = true;
{
std::lock_guard<std::mutex> lock(csMemFilesLock);
auto it = m_MEM_Files.find(wName);
if (it != m_MEM_Files.end()) val = true;
}
return val;
@ -4678,9 +4680,10 @@ int CMinecraftApp::GetTPConfigVal(wchar_t* pwchDataFile) { return -1; }
bool CMinecraftApp::IsFileInTPD(int iConfig) {
bool val = false;
{ std::lock_guard<std::mutex> lock(csMemTPDLock);
auto it = m_MEM_TPD.find(iConfig);
if (it != m_MEM_TPD.end()) val = true;
{
std::lock_guard<std::mutex> lock(csMemTPDLock);
auto it = m_MEM_TPD.find(iConfig);
if (it != m_MEM_TPD.end()) val = true;
}
return val;
@ -6607,41 +6610,42 @@ std::uint32_t CMinecraftApp::m_dwContentTypeA[e_Marketplace_MAX] = {
unsigned int CMinecraftApp::AddDLCRequest(eDLCMarketplaceType eType,
bool bPromote) {
// lock access
{ std::lock_guard<std::mutex> lock(csDLCDownloadQueue);
{
std::lock_guard<std::mutex> lock(csDLCDownloadQueue);
// If it's already in there, promote it to the top of the list
int iPosition = 0;
for (auto it = m_DLCDownloadQueue.begin(); it != m_DLCDownloadQueue.end();
++it) {
DLCRequest* pCurrent = *it;
// If it's already in there, promote it to the top of the list
int iPosition = 0;
for (auto it = m_DLCDownloadQueue.begin();
it != m_DLCDownloadQueue.end(); ++it) {
DLCRequest* pCurrent = *it;
if (pCurrent->dwType == m_dwContentTypeA[eType]) {
// already got this in the list
if (pCurrent->eState == e_DLC_ContentState_Retrieving ||
pCurrent->eState == e_DLC_ContentState_Retrieved) {
// already retrieved this
return 0;
} else {
// promote
if (bPromote) {
m_DLCDownloadQueue.erase(m_DLCDownloadQueue.begin() +
iPosition);
m_DLCDownloadQueue.insert(m_DLCDownloadQueue.begin(),
pCurrent);
if (pCurrent->dwType == m_dwContentTypeA[eType]) {
// already got this in the list
if (pCurrent->eState == e_DLC_ContentState_Retrieving ||
pCurrent->eState == e_DLC_ContentState_Retrieved) {
// already retrieved this
return 0;
} else {
// promote
if (bPromote) {
m_DLCDownloadQueue.erase(m_DLCDownloadQueue.begin() +
iPosition);
m_DLCDownloadQueue.insert(m_DLCDownloadQueue.begin(),
pCurrent);
}
return 0;
}
return 0;
}
iPosition++;
}
iPosition++;
}
DLCRequest* pDLCreq = new DLCRequest;
pDLCreq->dwType = m_dwContentTypeA[eType];
pDLCreq->eState = e_DLC_ContentState_Idle;
DLCRequest* pDLCreq = new DLCRequest;
pDLCreq->dwType = m_dwContentTypeA[eType];
pDLCreq->eState = e_DLC_ContentState_Idle;
m_DLCDownloadQueue.push_back(pDLCreq);
m_DLCDownloadQueue.push_back(pDLCreq);
m_bAllDLCContentRetrieved = false;
m_bAllDLCContentRetrieved = false;
}
app.DebugPrintf("[Consoles_App] Added DLC request.\n");
@ -6859,41 +6863,42 @@ bool CMinecraftApp::RetrieveNextDLCContent() {
// online.
}
{ std::lock_guard<std::mutex> lock(csDLCDownloadQueue);
for (auto it = m_DLCDownloadQueue.begin(); it != m_DLCDownloadQueue.end();
++it) {
DLCRequest* pCurrent = *it;
{
std::lock_guard<std::mutex> lock(csDLCDownloadQueue);
for (auto it = m_DLCDownloadQueue.begin();
it != m_DLCDownloadQueue.end(); ++it) {
DLCRequest* pCurrent = *it;
if (pCurrent->eState == e_DLC_ContentState_Retrieving) {
return true;
if (pCurrent->eState == e_DLC_ContentState_Retrieving) {
return true;
}
}
}
// Now look for the next retrieval
for (auto it = m_DLCDownloadQueue.begin(); it != m_DLCDownloadQueue.end();
++it) {
DLCRequest* pCurrent = *it;
// Now look for the next retrieval
for (auto it = m_DLCDownloadQueue.begin();
it != m_DLCDownloadQueue.end(); ++it) {
DLCRequest* pCurrent = *it;
if (pCurrent->eState == e_DLC_ContentState_Idle) {
if (pCurrent->eState == e_DLC_ContentState_Idle) {
#if defined(_DEBUG)
app.DebugPrintf("RetrieveNextDLCContent - type = %d\n",
pCurrent->dwType);
app.DebugPrintf("RetrieveNextDLCContent - type = %d\n",
pCurrent->dwType);
#endif
C4JStorage::EDLCStatus status = StorageManager.GetDLCOffers(
ProfileManager.GetPrimaryPad(),
&CMinecraftApp::DLCOffersReturned, this, pCurrent->dwType);
if (status == C4JStorage::EDLC_Pending) {
pCurrent->eState = e_DLC_ContentState_Retrieving;
} else {
// no content of this type, or some other problem
app.DebugPrintf("RetrieveNextDLCContent - PROBLEM\n");
pCurrent->eState = e_DLC_ContentState_Retrieved;
C4JStorage::EDLCStatus status = StorageManager.GetDLCOffers(
ProfileManager.GetPrimaryPad(),
&CMinecraftApp::DLCOffersReturned, this, pCurrent->dwType);
if (status == C4JStorage::EDLC_Pending) {
pCurrent->eState = e_DLC_ContentState_Retrieving;
} else {
// no content of this type, or some other problem
app.DebugPrintf("RetrieveNextDLCContent - PROBLEM\n");
pCurrent->eState = e_DLC_ContentState_Retrieved;
}
return true;
}
return true;
}
}
}
app.DebugPrintf("[Consoles_App] Finished downloading dlc content.\n");
return false;
@ -6905,46 +6910,48 @@ int CMinecraftApp::TMSPPFileReturned(void* pParam, int iPad, int iUserData,
CMinecraftApp* pClass = (CMinecraftApp*)pParam;
// find the right one in the vector
{ std::lock_guard<std::mutex> lock(pClass->csTMSPPDownloadQueue);
for (auto it = pClass->m_TMSPPDownloadQueue.begin();
it != pClass->m_TMSPPDownloadQueue.end(); ++it) {
TMSPPRequest* pCurrent = *it;
{
std::lock_guard<std::mutex> lock(pClass->csTMSPPDownloadQueue);
for (auto it = pClass->m_TMSPPDownloadQueue.begin();
it != pClass->m_TMSPPDownloadQueue.end(); ++it) {
TMSPPRequest* pCurrent = *it;
#if defined(_WINDOWS64)
char szFile[MAX_TMSFILENAME_SIZE];
wcstombs(szFile, pCurrent->wchFilename, MAX_TMSFILENAME_SIZE);
char szFile[MAX_TMSFILENAME_SIZE];
wcstombs(szFile, pCurrent->wchFilename, MAX_TMSFILENAME_SIZE);
if (strcmp(szFilename, szFile) == 0)
if (strcmp(szFilename, szFile) == 0)
#endif
{
// set this to retrieved whether it found it or not
pCurrent->eState = e_TMS_ContentState_Retrieved;
{
// set this to retrieved whether it found it or not
pCurrent->eState = e_TMS_ContentState_Retrieved;
if (pFileData != nullptr) {
switch (pCurrent->eType) {
case e_DLC_TexturePackData: {
app.DebugPrintf("--- Got texturepack data %ls\n",
pCurrent->wchFilename);
// get the config value for the texture pack
int iConfig = app.GetTPConfigVal(pCurrent->wchFilename);
app.AddMemoryTPDFile(iConfig, pFileData->pbData,
pFileData->size);
} break;
default:
app.DebugPrintf("--- Got image data - %ls\n",
pCurrent->wchFilename);
app.AddMemoryTextureFile(pCurrent->wchFilename,
pFileData->pbData,
if (pFileData != nullptr) {
switch (pCurrent->eType) {
case e_DLC_TexturePackData: {
app.DebugPrintf("--- Got texturepack data %ls\n",
pCurrent->wchFilename);
// get the config value for the texture pack
int iConfig =
app.GetTPConfigVal(pCurrent->wchFilename);
app.AddMemoryTPDFile(iConfig, pFileData->pbData,
pFileData->size);
break;
} break;
default:
app.DebugPrintf("--- Got image data - %ls\n",
pCurrent->wchFilename);
app.AddMemoryTextureFile(pCurrent->wchFilename,
pFileData->pbData,
pFileData->size);
break;
}
} else {
app.DebugPrintf("TMSImageReturned failed (%s)...\n",
szFilename);
}
} else {
app.DebugPrintf("TMSImageReturned failed (%s)...\n",
szFilename);
break;
}
break;
}
}
}
return 0;
}
@ -6963,16 +6970,17 @@ void CMinecraftApp::ClearAndResetDLCDownloadQueue() {
app.DebugPrintf("[Consoles_App] Clear and reset download queue.\n");
int iPosition = 0;
{ std::lock_guard<std::mutex> lock(csTMSPPDownloadQueue);
for (auto it = m_DLCDownloadQueue.begin(); it != m_DLCDownloadQueue.end();
++it) {
DLCRequest* pCurrent = *it;
{
std::lock_guard<std::mutex> lock(csTMSPPDownloadQueue);
for (auto it = m_DLCDownloadQueue.begin();
it != m_DLCDownloadQueue.end(); ++it) {
DLCRequest* pCurrent = *it;
delete pCurrent;
iPosition++;
}
m_DLCDownloadQueue.clear();
m_bAllDLCContentRetrieved = true;
delete pCurrent;
iPosition++;
}
m_DLCDownloadQueue.clear();
m_bAllDLCContentRetrieved = true;
}
}
@ -6985,16 +6993,17 @@ void CMinecraftApp::TickTMSPPFilesRetrieved() {
}
void CMinecraftApp::ClearTMSPPFilesRetrieved() {
int iPosition = 0;
{ std::lock_guard<std::mutex> lock(csTMSPPDownloadQueue);
for (auto it = m_TMSPPDownloadQueue.begin();
it != m_TMSPPDownloadQueue.end(); ++it) {
TMSPPRequest* pCurrent = *it;
{
std::lock_guard<std::mutex> lock(csTMSPPDownloadQueue);
for (auto it = m_TMSPPDownloadQueue.begin();
it != m_TMSPPDownloadQueue.end(); ++it) {
TMSPPRequest* pCurrent = *it;
delete pCurrent;
iPosition++;
}
m_TMSPPDownloadQueue.clear();
m_bAllTMSContentRetrieved = true;
delete pCurrent;
iPosition++;
}
m_TMSPPDownloadQueue.clear();
m_bAllTMSContentRetrieved = true;
}
}
@ -7003,24 +7012,25 @@ int CMinecraftApp::DLCOffersReturned(void* pParam, int iOfferC,
CMinecraftApp* pClass = (CMinecraftApp*)pParam;
// find the right one in the vector
{ std::lock_guard<std::mutex> lock(pClass->csTMSPPDownloadQueue);
for (auto it = pClass->m_DLCDownloadQueue.begin();
it != pClass->m_DLCDownloadQueue.end(); ++it) {
DLCRequest* pCurrent = *it;
{
std::lock_guard<std::mutex> lock(pClass->csTMSPPDownloadQueue);
for (auto it = pClass->m_DLCDownloadQueue.begin();
it != pClass->m_DLCDownloadQueue.end(); ++it) {
DLCRequest* pCurrent = *it;
// avatar items are coming back as type Content, so we can't trust the
// type setting
if (pCurrent->dwType == static_cast<std::uint32_t>(dwType)) {
pClass->m_iDLCOfferC = iOfferC;
app.DebugPrintf(
"DLCOffersReturned - type %u, count %d - setting to "
"retrieved\n",
dwType, iOfferC);
pCurrent->eState = e_DLC_ContentState_Retrieved;
break;
// avatar items are coming back as type Content, so we can't trust
// the type setting
if (pCurrent->dwType == static_cast<std::uint32_t>(dwType)) {
pClass->m_iDLCOfferC = iOfferC;
app.DebugPrintf(
"DLCOffersReturned - type %u, count %d - setting to "
"retrieved\n",
dwType, iOfferC);
pCurrent->eState = e_DLC_ContentState_Retrieved;
break;
}
}
}
}
return 0;
}
@ -7057,29 +7067,32 @@ void CMinecraftApp::SetAdditionalSkinBoxes(std::uint32_t dwSkinID,
std::vector<ModelPart*>* pvModelPart = new std::vector<ModelPart*>;
std::vector<SKIN_BOX*>* pvSkinBoxes = new std::vector<SKIN_BOX*>;
{ std::lock_guard<std::mutex> lock_mp(csAdditionalModelParts);
std::lock_guard<std::mutex> lock_sb(csAdditionalSkinBoxes);
{
std::lock_guard<std::mutex> lock_mp(csAdditionalModelParts);
std::lock_guard<std::mutex> lock_sb(csAdditionalSkinBoxes);
app.DebugPrintf(
"*** SetAdditionalSkinBoxes - Inserting model parts for skin %d from "
"array of Skin Boxes\n",
dwSkinID & 0x0FFFFFFF);
app.DebugPrintf(
"*** SetAdditionalSkinBoxes - Inserting model parts for skin %d "
"from "
"array of Skin Boxes\n",
dwSkinID & 0x0FFFFFFF);
// convert the skin boxes into model parts, and add to the humanoid model
for (unsigned int i = 0; i < dwSkinBoxC; i++) {
if (pModel) {
ModelPart* pModelPart = pModel->AddOrRetrievePart(&SkinBoxA[i]);
pvModelPart->push_back(pModelPart);
pvSkinBoxes->push_back(&SkinBoxA[i]);
// convert the skin boxes into model parts, and add to the humanoid
// model
for (unsigned int i = 0; i < dwSkinBoxC; i++) {
if (pModel) {
ModelPart* pModelPart = pModel->AddOrRetrievePart(&SkinBoxA[i]);
pvModelPart->push_back(pModelPart);
pvSkinBoxes->push_back(&SkinBoxA[i]);
}
}
}
m_AdditionalModelParts.insert(
std::pair<std::uint32_t, std::vector<ModelPart*>*>(dwSkinID,
pvModelPart));
m_AdditionalSkinBoxes.insert(
std::pair<std::uint32_t, std::vector<SKIN_BOX*>*>(dwSkinID,
pvSkinBoxes));
m_AdditionalModelParts.insert(
std::pair<std::uint32_t, std::vector<ModelPart*>*>(dwSkinID,
pvModelPart));
m_AdditionalSkinBoxes.insert(
std::pair<std::uint32_t, std::vector<SKIN_BOX*>*>(dwSkinID,
pvSkinBoxes));
}
}
@ -7090,27 +7103,30 @@ std::vector<ModelPart*>* CMinecraftApp::SetAdditionalSkinBoxes(
Model* pModel = renderer->getModel();
std::vector<ModelPart*>* pvModelPart = new std::vector<ModelPart*>;
{ std::lock_guard<std::mutex> lock_mp(csAdditionalModelParts);
std::lock_guard<std::mutex> lock_sb(csAdditionalSkinBoxes);
app.DebugPrintf(
"*** SetAdditionalSkinBoxes - Inserting model parts for skin %d from "
"array of Skin Boxes\n",
dwSkinID & 0x0FFFFFFF);
{
std::lock_guard<std::mutex> lock_mp(csAdditionalModelParts);
std::lock_guard<std::mutex> lock_sb(csAdditionalSkinBoxes);
app.DebugPrintf(
"*** SetAdditionalSkinBoxes - Inserting model parts for skin %d "
"from "
"array of Skin Boxes\n",
dwSkinID & 0x0FFFFFFF);
// convert the skin boxes into model parts, and add to the humanoid model
for (auto it = pvSkinBoxA->begin(); it != pvSkinBoxA->end(); ++it) {
if (pModel) {
ModelPart* pModelPart = pModel->AddOrRetrievePart(*it);
pvModelPart->push_back(pModelPart);
// convert the skin boxes into model parts, and add to the humanoid
// model
for (auto it = pvSkinBoxA->begin(); it != pvSkinBoxA->end(); ++it) {
if (pModel) {
ModelPart* pModelPart = pModel->AddOrRetrievePart(*it);
pvModelPart->push_back(pModelPart);
}
}
}
m_AdditionalModelParts.insert(
std::pair<std::uint32_t, std::vector<ModelPart*>*>(dwSkinID,
pvModelPart));
m_AdditionalSkinBoxes.insert(
std::pair<std::uint32_t, std::vector<SKIN_BOX*>*>(dwSkinID,
pvSkinBoxA));
m_AdditionalModelParts.insert(
std::pair<std::uint32_t, std::vector<ModelPart*>*>(dwSkinID,
pvModelPart));
m_AdditionalSkinBoxes.insert(
std::pair<std::uint32_t, std::vector<SKIN_BOX*>*>(dwSkinID,
pvSkinBoxA));
}
return pvModelPart;
}

View file

@ -33,7 +33,6 @@ SonyLeaderboardManager::SonyLeaderboardManager() {
m_openSessions = 0;
m_running = false;
m_threadScoreboard = nullptr;
}
@ -49,7 +48,6 @@ SonyLeaderboardManager::~SonyLeaderboardManager() {
}
delete m_threadScoreboard;
}
int SonyLeaderboardManager::scoreboardThreadEntry(void* lpParam) {
@ -66,8 +64,9 @@ int SonyLeaderboardManager::scoreboardThreadEntry(void* lpParam) {
self->scoreboardThreadInternal();
}
{ std::lock_guard<std::mutex> lock(self->m_csViewsLock);
needsWriting = self->m_views.size() > 0;
{
std::lock_guard<std::mutex> lock(self->m_csViewsLock);
needsWriting = self->m_views.size() > 0;
}
// 4J Stu - We can't write while we aren't signed in to live
@ -165,8 +164,9 @@ void SonyLeaderboardManager::scoreboardThreadInternal() {
// we'll manage the write queue seperately.
bool hasWork;
{ std::lock_guard<std::mutex> lock(m_csViewsLock);
hasWork = !m_views.empty();
{
std::lock_guard<std::mutex> lock(m_csViewsLock);
hasWork = !m_views.empty();
}
if (hasWork) {
@ -493,9 +493,10 @@ bool SonyLeaderboardManager::setScore() {
// Get next job.
RegisterScore rscore;
{ std::lock_guard<std::mutex> lock(m_csViewsLock);
rscore = m_views.front();
m_views.pop();
{
std::lock_guard<std::mutex> lock(m_csViewsLock);
rscore = m_views.front();
m_views.pop();
}
if (ProfileManager.IsGuest(rscore.m_iPad)) {
@ -641,7 +642,8 @@ bool SonyLeaderboardManager::OpenSession() {
m_threadScoreboard =
new C4JThread(&scoreboardThreadEntry, this, "4JScoreboard");
m_threadScoreboard->setProcessor(CPU_CORE_LEADERBOARDS);
m_threadScoreboard->setPriority(C4JThread::ThreadPriority::BelowNormal);
m_threadScoreboard->setPriority(
C4JThread::ThreadPriority::BelowNormal);
m_threadScoreboard->run();
}
@ -682,16 +684,18 @@ bool SonyLeaderboardManager::WriteStats(unsigned int viewCount, ViewIn views) {
// Write relevant parameters.
// RegisterScore *regScore = reinterpret_cast<RegisterScore *>(views);
{ std::lock_guard<std::mutex> lock(m_csViewsLock);
for (int i = 0; i < viewCount; i++) {
app.DebugPrintf(
"[SonyLeaderboardManager] WriteStats(), starting. difficulty=%i, "
"statsType=%i, score=%i\n",
views[i].m_difficulty, views[i].m_commentData.m_statsType,
views[i].m_score);
{
std::lock_guard<std::mutex> lock(m_csViewsLock);
for (int i = 0; i < viewCount; i++) {
app.DebugPrintf(
"[SonyLeaderboardManager] WriteStats(), starting. "
"difficulty=%i, "
"statsType=%i, score=%i\n",
views[i].m_difficulty, views[i].m_commentData.m_statsType,
views[i].m_score);
m_views.push(views[i]);
}
m_views.push(views[i]);
}
}
delete[] views; //*regScore;

View file

@ -616,8 +616,9 @@ void UIController::StartReloadSkinThread() {
int UIController::reloadSkinThreadProc(void* lpParam) {
{
std::lock_guard<std::mutex> lock(ms_reloadSkinCS); // MGH - added to prevent crash loading Iggy movies
// while the skins were being reloaded
std::lock_guard<std::mutex> lock(
ms_reloadSkinCS); // MGH - added to prevent crash loading Iggy
// movies while the skins were being reloaded
UIController* controller = (UIController*)lpParam;
// Load new skin
controller->loadSkins();
@ -1400,9 +1401,7 @@ UIScene* UIController::GetSceneFromCallbackId(size_t id) {
return scene;
}
void UIController::lockCallbackScenes() {
m_registeredCallbackScenesCS.lock();
}
void UIController::lockCallbackScenes() { m_registeredCallbackScenesCS.lock(); }
void UIController::unlockCallbackScenes() {
m_registeredCallbackScenesCS.unlock();

View file

@ -247,8 +247,8 @@ bool UIScene::mapElementsAndNames() {
extern std::mutex s_loadSkinCS;
void UIScene::loadMovie() {
UIController::ms_reloadSkinCS.lock(); // MGH - added to prevent crash
// loading Iggy movies while the skins
// were being reloaded
// loading Iggy movies while the
// skins were being reloaded
std::wstring moviePath = getMoviePath();
#if defined(_WINDOWS64)

View file

@ -93,8 +93,8 @@ void Chunk::reconcileRenderableTileEntities(
// TODO - 4J see how input entity vector is set up and decide what way is best
// to pass this to the function
Chunk::Chunk(Level* level, LevelRenderer::rteMap& globalRenderableTileEntities,
std::mutex& globalRenderableTileEntities_cs, int x, int y,
int z, ClipChunk* clipChunk)
std::mutex& globalRenderableTileEntities_cs, int x, int y, int z,
ClipChunk* clipChunk)
: globalRenderableTileEntities(&globalRenderableTileEntities),
globalRenderableTileEntities_cs(&globalRenderableTileEntities_cs) {
clipChunk->visible = false;
@ -151,25 +151,27 @@ void Chunk::setPos(int x, int y, int z) {
assigned = true;
{
std::lock_guard<std::recursive_mutex> lock(levelRenderer->m_csDirtyChunks);
std::lock_guard<std::recursive_mutex> lock(
levelRenderer->m_csDirtyChunks);
unsigned char refCount =
levelRenderer->incGlobalChunkRefCount(x, y, z, level);
// printf("\t\t [inc] refcount %d at %d, %d, %d\n",refCount,x,y,z);
// int idx = levelRenderer->getGlobalIndexForChunk(x, y, z, level);
// If we're the first thing to be referencing this, mark it up as dirty to
// get rebuilt
// If we're the first thing to be referencing this, mark it up as dirty
// to get rebuilt
if (refCount == 1) {
// printf("Setting %d %d %d dirty [%d]\n",x,y,z, idx);
// Chunks being made dirty in this way can be very numerous (eg the full
// visible area of the world at start up, or a whole edge of the world
// when moving). On account of this, don't want to stick them into our
// lock free queue that we would normally use for letting the render
// update thread know about this chunk. Instead, just set the flag to
// say this is dirty, and then pass a special value of 1 through to the
// lock free stack which lets that thread know that at least one chunk
// other than the ones in the stack itself have been made dirty.
// Chunks being made dirty in this way can be very numerous (eg the
// full visible area of the world at start up, or a whole edge of
// the world when moving). On account of this, don't want to stick
// them into our lock free queue that we would normally use for
// letting the render update thread know about this chunk. Instead,
// just set the flag to say this is dirty, and then pass a special
// value of 1 through to the lock free stack which lets that thread
// know that at least one chunk other than the ones in the stack
// itself have been made dirty.
levelRenderer->setGlobalChunkFlag(x, y, z, level,
LevelRenderer::CHUNK_FLAG_DIRTY);
PIXSetMarkerDeprecated(0, "Non-stack event pushed");
@ -722,7 +724,8 @@ void Chunk::reset() {
bool retireRenderableTileEntities = false;
{
std::lock_guard<std::recursive_mutex> lock(levelRenderer->m_csDirtyChunks);
std::lock_guard<std::recursive_mutex> lock(
levelRenderer->m_csDirtyChunks);
oldKey = levelRenderer->getGlobalIndexForChunk(x, y, z, level);
unsigned char refCount =
levelRenderer->decGlobalChunkRefCount(x, y, z, level);
@ -735,8 +738,8 @@ void Chunk::reset() {
if (lists >= 0) {
lists += levelRenderer->chunkLists;
for (int i = 0; i < 2; i++) {
// 4J - added - clear any renderer data associated with this
// unused list
// 4J - added - clear any renderer data associated with
// this unused list
RenderManager.CBuffClear(lists + i);
}
levelRenderer->setGlobalChunkFlags(x, y, z, level, 0);

View file

@ -61,8 +61,8 @@ private:
public:
Chunk(Level* level, LevelRenderer::rteMap& globalRenderableTileEntities,
std::mutex& globalRenderableTileEntities_cs, int x, int y,
int z, ClipChunk* clipChunk);
std::mutex& globalRenderableTileEntities_cs, int x, int y, int z,
ClipChunk* clipChunk);
Chunk();
void setPos(int x, int y, int z);

View file

@ -34,7 +34,8 @@ void ProgressRenderer::_progressStart(int title) {
}
{
std::lock_guard<std::recursive_mutex> lock(ProgressRenderer::s_progress);
std::lock_guard<std::recursive_mutex> lock(
ProgressRenderer::s_progress);
lastPercent = 0;
this->title = title;
}
@ -48,7 +49,8 @@ void ProgressRenderer::progressStage(int status) {
lastTime = 0;
{
std::lock_guard<std::recursive_mutex> lock(ProgressRenderer::s_progress);
std::lock_guard<std::recursive_mutex> lock(
ProgressRenderer::s_progress);
m_eType = eProgressStringType_ID;
this->status = status;
}
@ -60,7 +62,8 @@ void ProgressRenderer::progressStagePercentage(int i) {
// 4J Stu - Removing all progressRenderer rendering. This will be replaced
// on the xbox
{
std::lock_guard<std::recursive_mutex> lock(ProgressRenderer::s_progress);
std::lock_guard<std::recursive_mutex> lock(
ProgressRenderer::s_progress);
lastPercent = i;
}
}
@ -68,7 +71,8 @@ void ProgressRenderer::progressStagePercentage(int i) {
int ProgressRenderer::getCurrentPercent() {
int returnValue = 0;
{
std::lock_guard<std::recursive_mutex> lock(ProgressRenderer::s_progress);
std::lock_guard<std::recursive_mutex> lock(
ProgressRenderer::s_progress);
returnValue = lastPercent;
}
return returnValue;
@ -77,7 +81,8 @@ int ProgressRenderer::getCurrentPercent() {
int ProgressRenderer::getCurrentTitle() {
int returnValue;
{
std::lock_guard<std::recursive_mutex> lock(ProgressRenderer::s_progress);
std::lock_guard<std::recursive_mutex> lock(
ProgressRenderer::s_progress);
returnValue = title;
}
return returnValue;
@ -86,7 +91,8 @@ int ProgressRenderer::getCurrentTitle() {
int ProgressRenderer::getCurrentStatus() {
int returnValue;
{
std::lock_guard<std::recursive_mutex> lock(ProgressRenderer::s_progress);
std::lock_guard<std::recursive_mutex> lock(
ProgressRenderer::s_progress);
returnValue = status;
}
return returnValue;
@ -95,7 +101,8 @@ int ProgressRenderer::getCurrentStatus() {
ProgressRenderer::eProgressStringType ProgressRenderer::getType() {
eProgressStringType returnValue;
{
std::lock_guard<std::recursive_mutex> lock(ProgressRenderer::s_progress);
std::lock_guard<std::recursive_mutex> lock(
ProgressRenderer::s_progress);
returnValue = m_eType;
}
return returnValue;

View file

@ -1062,9 +1062,7 @@ void GameRenderer::AddForDelete(SparseDataStorage* deleteThis) {
m_deleteStackSparseDataStorage.push_back(deleteThis);
}
void GameRenderer::FinishedReassigning() {
m_csDeleteStack.unlock();
}
void GameRenderer::FinishedReassigning() { m_csDeleteStack.unlock(); }
int GameRenderer::runUpdate(void* lpParam) {
Minecraft* minecraft = Minecraft::GetInstance();
@ -1135,8 +1133,8 @@ int GameRenderer::runUpdate(void* lpParam) {
i < m_deleteStackCompressedTileStorage.size(); i++)
delete m_deleteStackCompressedTileStorage[i];
m_deleteStackCompressedTileStorage.clear();
for (unsigned int i = 0;
i < m_deleteStackSparseDataStorage.size(); i++)
for (unsigned int i = 0; i < m_deleteStackSparseDataStorage.size();
i++)
delete m_deleteStackSparseDataStorage[i];
m_deleteStackSparseDataStorage.clear();
}
@ -1175,7 +1173,8 @@ void GameRenderer::DisableUpdateThread() {
"------------------DisableUpdateThread--------------------\n");
updateRunning = false;
m_updateEvents->clear(eUpdateCanRun);
m_updateEvents->waitForSingle(eUpdateEventIsFinished, C4JThread::kInfiniteTimeout);
m_updateEvents->waitForSingle(eUpdateEventIsFinished,
C4JThread::kInfiniteTimeout);
#endif
}

View file

@ -513,7 +513,6 @@ void LevelRenderer::allChanged(int playerIndex) {
noEntityRenderFrames = 2;
Minecraft::GetInstance()->gameRenderer->EnableUpdateThread();
}
void LevelRenderer::renderEntities(Vec3* cam, Culler* culler, float a) {
@ -620,7 +619,8 @@ void LevelRenderer::renderEntities(Vec3* cam, Culler* culler, float a) {
it != renderableTileEntities.end(); it++) {
int idx = it->first;
// Don't render if it isn't in the same dimension as this player
if (!isGlobalIndexInSameDimension(idx, level[playerIndex])) continue;
if (!isGlobalIndexInSameDimension(idx, level[playerIndex]))
continue;
for (auto it2 = it->second.tiles.begin();
it2 != it->second.tiles.end(); it2++) {
@ -3973,7 +3973,6 @@ void LevelRenderer::DestroyedTileManager::addAABBs(Level* level, AABB* box,
}
}
}
}
void LevelRenderer::DestroyedTileManager::tick() {

View file

@ -774,13 +774,9 @@ int ConsoleSaveFileOriginal::getOriginalSaveVersion() {
return header.getOriginalSaveVersion();
}
void ConsoleSaveFileOriginal::LockSaveAccess() {
m_lock.lock();
}
void ConsoleSaveFileOriginal::LockSaveAccess() { m_lock.lock(); }
void ConsoleSaveFileOriginal::ReleaseSaveAccess() {
m_lock.unlock();
}
void ConsoleSaveFileOriginal::ReleaseSaveAccess() { m_lock.unlock(); }
ESavePlatform ConsoleSaveFileOriginal::getSavePlatform() {
return header.getSavePlatform();

View file

@ -396,7 +396,6 @@ ConsoleSaveFileSplit::ConsoleSaveFileSplit(ConsoleSaveFile* sourceSave,
void ConsoleSaveFileSplit::_init(const std::wstring& fileName, void* pvSaveData,
unsigned int fileSize, ESavePlatform plat) {
m_lastTickTime = 0;
// One time initialise of static stuff required for our storage
@ -1504,9 +1503,7 @@ int ConsoleSaveFileSplit::getOriginalSaveVersion() {
void ConsoleSaveFileSplit::LockSaveAccess() { m_lock.lock(); }
void ConsoleSaveFileSplit::ReleaseSaveAccess() {
m_lock.unlock();
}
void ConsoleSaveFileSplit::ReleaseSaveAccess() { m_lock.unlock(); }
ESavePlatform ConsoleSaveFileSplit::getSavePlatform() {
return header.getSavePlatform();

View file

@ -92,44 +92,46 @@ int32_t Compression::CompressLZXRLE(void* pDestination, unsigned int* pDestSize,
int32_t Compression::CompressRLE(void* pDestination, unsigned int* pDestSize,
void* pSource, unsigned int SrcSize) {
unsigned int rleSize;
{ std::lock_guard<std::mutex> lock(rleCompressLock);
// static unsigned char rleBuf[1024*100];
{
std::lock_guard<std::mutex> lock(rleCompressLock);
// static unsigned char rleBuf[1024*100];
unsigned char* pucIn = (unsigned char*)pSource;
unsigned char* pucEnd = pucIn + SrcSize;
unsigned char* pucOut = (unsigned char*)rleCompressBuf;
unsigned char* pucIn = (unsigned char*)pSource;
unsigned char* pucEnd = pucIn + SrcSize;
unsigned char* pucOut = (unsigned char*)rleCompressBuf;
// Compress with RLE first:
// 0 - 254 - encodes a single byte
// 255 followed by 0, 1, 2 - encodes a 1, 2, or 3 255s
// 255 followed by 3-255, followed by a byte - encodes a run of n + 1 bytes
PIXBeginNamedEvent(0, "RLE compression");
do {
unsigned char thisOne = *pucIn++;
// Compress with RLE first:
// 0 - 254 - encodes a single byte
// 255 followed by 0, 1, 2 - encodes a 1, 2, or 3 255s
// 255 followed by 3-255, followed by a byte - encodes a run of n + 1
// bytes
PIXBeginNamedEvent(0, "RLE compression");
do {
unsigned char thisOne = *pucIn++;
unsigned int count = 1;
while ((pucIn != pucEnd) && (*pucIn == thisOne) && (count < 256)) {
pucIn++;
count++;
}
unsigned int count = 1;
while ((pucIn != pucEnd) && (*pucIn == thisOne) && (count < 256)) {
pucIn++;
count++;
}
if (count <= 3) {
if (thisOne == 255) {
if (count <= 3) {
if (thisOne == 255) {
*pucOut++ = 255;
*pucOut++ = count - 1;
} else {
for (unsigned int i = 0; i < count; i++) {
*pucOut++ = thisOne;
}
}
} else {
*pucOut++ = 255;
*pucOut++ = count - 1;
} else {
for (unsigned int i = 0; i < count; i++) {
*pucOut++ = thisOne;
}
*pucOut++ = thisOne;
}
} else {
*pucOut++ = 255;
*pucOut++ = count - 1;
*pucOut++ = thisOne;
}
} while (pucIn != pucEnd);
rleSize = (unsigned int)(pucOut - rleCompressBuf);
PIXEndNamedEvent();
} while (pucIn != pucEnd);
rleSize = (unsigned int)(pucOut - rleCompressBuf);
PIXEndNamedEvent();
}
// Return

File diff suppressed because it is too large Load diff

View file

@ -109,8 +109,8 @@ protected:
std::vector<std::shared_ptr<Entity> > entitiesToRemove;
public:
bool hasEntitiesToRemove(); // 4J added
bool m_bDisableAddNewTileEntities; // 4J Added
bool hasEntitiesToRemove(); // 4J added
bool m_bDisableAddNewTileEntities; // 4J Added
std::recursive_mutex m_tileEntityListCS; // 4J added
std::vector<std::shared_ptr<TileEntity> > tileEntityList;

View file

@ -28,17 +28,17 @@ std::recursive_mutex LevelChunk::m_csEntities;
std::recursive_mutex LevelChunk::m_csTileEntities;
bool LevelChunk::touchedSky = false;
void LevelChunk::staticCtor() {
}
void LevelChunk::staticCtor() {}
void LevelChunk::init(Level* level, int x, int z) {
biomes = byteArray(16 * 16);
for (int i = 0; i < 16 * 16; i++) {
biomes[i] = 0xff;
}
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
entityBlocks =
new std::vector<std::shared_ptr<Entity> >*[ENTITY_BLOCKS_LENGTH];
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
entityBlocks =
new std::vector<std::shared_ptr<Entity> >*[ENTITY_BLOCKS_LENGTH];
}
terrainPopulated = 0;
@ -59,10 +59,11 @@ void LevelChunk::init(Level* level, int x, int z) {
this->z = z;
MemSect(1);
heightmap = byteArray(16 * 16);
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
entityBlocks[i] = new std::vector<std::shared_ptr<Entity> >();
}
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
entityBlocks[i] = new std::vector<std::shared_ptr<Entity> >();
}
}
MemSect(0);
@ -224,61 +225,63 @@ void LevelChunk::setUnsaved(bool unsaved) {
void LevelChunk::stopSharingTilesAndData() {
#if defined(SHARING_ENABLED)
{ std::lock_guard<std::recursive_mutex> lock(m_csSharing);
lastUnsharedTime = System::currentTimeMillis();
if (!sharingTilesAndData) {
return;
}
{
std::lock_guard<std::recursive_mutex> lock(m_csSharing);
lastUnsharedTime = System::currentTimeMillis();
if (!sharingTilesAndData) {
return;
}
// If we've got a reference to a server chunk's terrainPopulated flag that
// this LevelChunk is sharing with, then don't consider unsharing if it
// hasn't been set. This is because post-processing things that update the
// server chunks won't actually cause the server to send any updates to the
// tiles that they alter, so they completely depend on the data not being
// shared for it to get from the server to here
if ((serverTerrainPopulated) &&
(((*serverTerrainPopulated) & sTerrainPopulatedAllAffecting) !=
sTerrainPopulatedAllAffecting)) {
return;
}
// If we've got a reference to a server chunk's terrainPopulated flag
// that this LevelChunk is sharing with, then don't consider unsharing
// if it hasn't been set. This is because post-processing things that
// update the server chunks won't actually cause the server to send any
// updates to the tiles that they alter, so they completely depend on
// the data not being shared for it to get from the server to here
if ((serverTerrainPopulated) &&
(((*serverTerrainPopulated) & sTerrainPopulatedAllAffecting) !=
sTerrainPopulatedAllAffecting)) {
return;
}
// If this is the empty chunk, then it will have a x & z of 0,0 - if we
// don't drop out here we'll end up unsharing the chunk at this location for
// no reason
if (isEmpty()) {
return;
}
// If this is the empty chunk, then it will have a x & z of 0,0 - if we
// don't drop out here we'll end up unsharing the chunk at this location
// for no reason
if (isEmpty()) {
return;
}
MemSect(47);
MemSect(47);
// Changed to used compressed storage - these CTORs make deep copies of the
// storage passed as a parameter
lowerBlocks = new CompressedTileStorage(lowerBlocks);
// Changed to used compressed storage - these CTORs make deep copies of
// the storage passed as a parameter
lowerBlocks = new CompressedTileStorage(lowerBlocks);
// Changed to use new sparse data storage - this CTOR makes a deep copy of
// the storage passed as a parameter
lowerData = new SparseDataStorage(lowerData);
// Changed to use new sparse data storage - this CTOR makes a deep copy
// of the storage passed as a parameter
lowerData = new SparseDataStorage(lowerData);
if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) {
upperBlocks = new CompressedTileStorage(upperBlocks);
upperData = new SparseDataStorage(upperData);
} else {
upperBlocks = nullptr;
upperData = nullptr;
}
if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) {
upperBlocks = new CompressedTileStorage(upperBlocks);
upperData = new SparseDataStorage(upperData);
} else {
upperBlocks = nullptr;
upperData = nullptr;
}
/*
newDataLayer = new DataLayer(skyLight->data.length*2, level->depthBits);
XMemCpy(newDataLayer->data.data, skyLight->data.data,
skyLight->data.length); skyLight = newDataLayer;
/*
newDataLayer = new DataLayer(skyLight->data.length*2, level->depthBits);
XMemCpy(newDataLayer->data.data, skyLight->data.data,
skyLight->data.length); skyLight = newDataLayer;
newDataLayer = new DataLayer(blockLight->data.length*2, level->depthBits);
XMemCpy(newDataLayer->data.data, blockLight->data.data,
blockLight->data.length); blockLight = newDataLayer;
*/
newDataLayer = new DataLayer(blockLight->data.length*2,
level->depthBits); XMemCpy(newDataLayer->data.data,
blockLight->data.data, blockLight->data.length); blockLight =
newDataLayer;
*/
sharingTilesAndData = false;
MemSect(0);
sharingTilesAndData = false;
MemSect(0);
}
#endif
}
@ -290,108 +293,110 @@ void LevelChunk::stopSharingTilesAndData() {
// not sharing
void LevelChunk::reSyncLighting() {
#if defined(SHARING_ENABLED)
{ std::lock_guard<std::recursive_mutex> lock(m_csSharing);
{
std::lock_guard<std::recursive_mutex> lock(m_csSharing);
if (isEmpty()) {
return;
}
if (isEmpty()) {
return;
}
#if defined(_LARGE_WORLDS)
LevelChunk* lc = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunkLoadedOrUnloaded(x, z);
LevelChunk* lc = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunkLoadedOrUnloaded(x, z);
#else
LevelChunk* lc = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunk(x, z);
LevelChunk* lc = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunk(x, z);
#endif
GameRenderer::AddForDelete(lowerSkyLight);
lowerSkyLight = new SparseLightStorage(lc->lowerSkyLight);
GameRenderer::FinishedReassigning();
GameRenderer::AddForDelete(lowerBlockLight);
lowerBlockLight = new SparseLightStorage(lc->lowerBlockLight);
GameRenderer::FinishedReassigning();
GameRenderer::AddForDelete(lowerSkyLight);
lowerSkyLight = new SparseLightStorage(lc->lowerSkyLight);
GameRenderer::FinishedReassigning();
GameRenderer::AddForDelete(lowerBlockLight);
lowerBlockLight = new SparseLightStorage(lc->lowerBlockLight);
GameRenderer::FinishedReassigning();
if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) {
GameRenderer::AddForDelete(upperSkyLight);
upperSkyLight = new SparseLightStorage(lc->upperSkyLight);
GameRenderer::FinishedReassigning();
GameRenderer::AddForDelete(upperBlockLight);
upperBlockLight = new SparseLightStorage(lc->upperBlockLight);
GameRenderer::FinishedReassigning();
}
if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) {
GameRenderer::AddForDelete(upperSkyLight);
upperSkyLight = new SparseLightStorage(lc->upperSkyLight);
GameRenderer::FinishedReassigning();
GameRenderer::AddForDelete(upperBlockLight);
upperBlockLight = new SparseLightStorage(lc->upperBlockLight);
GameRenderer::FinishedReassigning();
}
}
#endif
}
void LevelChunk::startSharingTilesAndData(int forceMs) {
#if defined(SHARING_ENABLED)
{ std::lock_guard<std::recursive_mutex> lock(m_csSharing);
if (sharingTilesAndData) {
return;
}
{
std::lock_guard<std::recursive_mutex> lock(m_csSharing);
if (sharingTilesAndData) {
return;
}
// If this is the empty chunk, then it will have a x & z of 0,0 - we'll end
// up potentially loading the 0,0 block if we proceed. And it obviously
// doesn't make sense to go resharing the 0,0 block on behalf of an empty
// chunk either
if (isEmpty()) {
return;
}
// If this is the empty chunk, then it will have a x & z of 0,0 - we'll
// end up potentially loading the 0,0 block if we proceed. And it
// obviously doesn't make sense to go resharing the 0,0 block on behalf
// of an empty chunk either
if (isEmpty()) {
return;
}
#if defined(_LARGE_WORLDS)
LevelChunk* lc = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunkLoadedOrUnloaded(x, z);
LevelChunk* lc = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunkLoadedOrUnloaded(x, z);
#else
LevelChunk* lc = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunk(x, z);
LevelChunk* lc = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunk(x, z);
#endif
// In normal usage, chunks should only reshare if their local data matched
// that on the server. The forceMs parameter though can be used to force a
// share if resharing hasn't happened after a period of time
if (forceMs == 0) {
// Normal behaviour - just check that the data matches, and don't start
// sharing data if it doesn't (yet)
if (!lowerBlocks->isSameAs(lc->lowerBlocks) ||
(upperBlocks && lc->upperBlocks &&
!upperBlocks->isSameAs(lc->upperBlocks))) {
return;
// In normal usage, chunks should only reshare if their local data
// matched that on the server. The forceMs parameter though can be used
// to force a share if resharing hasn't happened after a period of time
if (forceMs == 0) {
// Normal behaviour - just check that the data matches, and don't
// start sharing data if it doesn't (yet)
if (!lowerBlocks->isSameAs(lc->lowerBlocks) ||
(upperBlocks && lc->upperBlocks &&
!upperBlocks->isSameAs(lc->upperBlocks))) {
return;
}
} else {
// Only force if it has been more than forceMs milliseconds since we
// last wanted to unshare this chunk
int64_t timenow = System::currentTimeMillis();
if ((timenow - lastUnsharedTime) < forceMs) {
return;
}
}
} else {
// Only force if it has been more than forceMs milliseconds since we
// last wanted to unshare this chunk
int64_t timenow = System::currentTimeMillis();
if ((timenow - lastUnsharedTime) < forceMs) {
return;
}
}
// Note - data that was shared isn't directly deleted here, as it might
// still be in use in the game render update thread. Let that thread delete
// it when it is safe to do so instead.
GameRenderer::AddForDelete(lowerBlocks);
lowerBlocks = lc->lowerBlocks;
GameRenderer::FinishedReassigning();
GameRenderer::AddForDelete(lowerData);
lowerData = lc->lowerData;
GameRenderer::FinishedReassigning();
if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) {
GameRenderer::AddForDelete(upperBlocks);
upperBlocks = lc->upperBlocks;
// Note - data that was shared isn't directly deleted here, as it might
// still be in use in the game render update thread. Let that thread
// delete it when it is safe to do so instead.
GameRenderer::AddForDelete(lowerBlocks);
lowerBlocks = lc->lowerBlocks;
GameRenderer::FinishedReassigning();
GameRenderer::AddForDelete(upperData);
upperData = lc->upperData;
GameRenderer::AddForDelete(lowerData);
lowerData = lc->lowerData;
GameRenderer::FinishedReassigning();
}
sharingTilesAndData = true;
if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) {
GameRenderer::AddForDelete(upperBlocks);
upperBlocks = lc->upperBlocks;
GameRenderer::FinishedReassigning();
GameRenderer::AddForDelete(upperData);
upperData = lc->upperData;
GameRenderer::FinishedReassigning();
}
sharingTilesAndData = true;
}
#endif
}
@ -1150,8 +1155,9 @@ void LevelChunk::addEntity(std::shared_ptr<Entity> e) {
e->yChunk = yc;
e->zChunk = z;
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
entityBlocks[yc]->push_back(e);
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
entityBlocks[yc]->push_back(e);
}
}
@ -1163,19 +1169,19 @@ void LevelChunk::removeEntity(std::shared_ptr<Entity> e, int yc) {
if (yc < 0) yc = 0;
if (yc >= ENTITY_BLOCKS_LENGTH) yc = ENTITY_BLOCKS_LENGTH - 1;
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
// 4J - was entityBlocks[yc]->remove(e);
auto it = find(entityBlocks[yc]->begin(), entityBlocks[yc]->end(), e);
if (it != entityBlocks[yc]->end()) {
entityBlocks[yc]->erase(it);
// 4J - we don't want storage creeping up here as thinkgs move round the
// world accumulating up spare space
MemSect(31);
entityBlocks[yc]->shrink_to_fit();
MemSect(0);
}
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
// 4J - was entityBlocks[yc]->remove(e);
auto it = find(entityBlocks[yc]->begin(), entityBlocks[yc]->end(), e);
if (it != entityBlocks[yc]->end()) {
entityBlocks[yc]->erase(it);
// 4J - we don't want storage creeping up here as thinkgs move round
// the world accumulating up spare space
MemSect(31);
entityBlocks[yc]->shrink_to_fit();
MemSect(0);
}
}
}
@ -1201,50 +1207,56 @@ std::shared_ptr<TileEntity> LevelChunk::getTileEntity(int x, int y, int z) {
// insert when we don't want one)
// shared_ptr<TileEntity> tileEntity = tileEntities[pos];
std::shared_ptr<TileEntity> tileEntity = nullptr;
{ std::unique_lock<std::recursive_mutex> lock(m_csTileEntities);
auto it = tileEntities.find(pos);
{
std::unique_lock<std::recursive_mutex> lock(m_csTileEntities);
auto it = tileEntities.find(pos);
if (it == tileEntities.end()) {
lock.unlock(); // Note: don't assume iterator is valid for
// tileEntities after this point
if (it == tileEntities.end()) {
lock.unlock(); // Note: don't assume iterator is valid for
// tileEntities after this point
// Fix for #48450 - All: Code Defect: Hang: Game hangs in tutorial, when
// player arrive at the particular coordinate 4J Stu - Chests try to get
// their neighbours when being destroyed, which then causes new tile
// entities to be created if the neighbour has already been destroyed
if (level->m_bDisableAddNewTileEntities) return nullptr;
// Fix for #48450 - All: Code Defect: Hang: Game hangs in tutorial,
// when player arrive at the particular coordinate 4J Stu - Chests
// try to get their neighbours when being destroyed, which then
// causes new tile entities to be created if the neighbour has
// already been destroyed
if (level->m_bDisableAddNewTileEntities) return nullptr;
int t = getTile(x, y, z);
if (t <= 0 || !Tile::tiles[t]->isEntityTile()) return nullptr;
int t = getTile(x, y, z);
if (t <= 0 || !Tile::tiles[t]->isEntityTile()) return nullptr;
// 4J-PB changed from this in 1.7.3
// EntityTile *et = (EntityTile *) Tile::tiles[t];
// et->onPlace(level, this->x * 16 + x, y, this->z * 16 + z);
// 4J-PB changed from this in 1.7.3
// EntityTile *et = (EntityTile *) Tile::tiles[t];
// et->onPlace(level, this->x * 16 + x, y, this->z * 16 + z);
// if (tileEntity == nullptr)
//{
tileEntity =
dynamic_cast<EntityTile*>(Tile::tiles[t])->newTileEntity(level);
level->setTileEntity(this->x * 16 + x, y, this->z * 16 + z, tileEntity);
//}
// if (tileEntity == nullptr)
//{
tileEntity =
dynamic_cast<EntityTile*>(Tile::tiles[t])->newTileEntity(level);
level->setTileEntity(this->x * 16 + x, y, this->z * 16 + z,
tileEntity);
//}
// tileEntity = tileEntities[pos]; // 4J - TODO - this
// doesn't seem right - assignment wrong way? Check
// tileEntity = tileEntities[pos]; // 4J - TODO - this
// doesn't seem right - assignment wrong way? Check
// 4J Stu - It should have been inserted by now, but check to be sure
{ std::lock_guard<std::recursive_mutex> lock2(m_csTileEntities);
auto newIt = tileEntities.find(pos);
if (newIt != tileEntities.end()) {
tileEntity = newIt->second;
// 4J Stu - It should have been inserted by now, but check to be
// sure
{
std::lock_guard<std::recursive_mutex> lock2(m_csTileEntities);
auto newIt = tileEntities.find(pos);
if (newIt != tileEntities.end()) {
tileEntity = newIt->second;
}
}
} else {
tileEntity = it->second;
}
}
} else {
tileEntity = it->second;
}
}
if (tileEntity != nullptr && tileEntity->isRemoved()) {
{ std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
tileEntities.erase(pos);
{
std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
tileEntities.erase(pos);
}
return nullptr;
}
@ -1259,7 +1271,8 @@ void LevelChunk::addTileEntity(std::shared_ptr<TileEntity> te) {
setTileEntity(xx, yy, zz, te);
if (loaded) {
{
std::lock_guard<std::recursive_mutex> lock(level->m_tileEntityListCS);
std::lock_guard<std::recursive_mutex> lock(
level->m_tileEntityListCS);
level->tileEntityList.push_back(te);
}
}
@ -1289,8 +1302,9 @@ void LevelChunk::setTileEntity(int x, int y, int z,
tileEntity->clearRemoved();
{ std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
tileEntities[pos] = tileEntity;
{
std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
tileEntities[pos] = tileEntity;
}
}
@ -1303,20 +1317,21 @@ void LevelChunk::removeTileEntity(int x, int y, int z) {
// if (removeThis != null) {
// removeThis.setRemoved();
// }
{ std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
auto it = tileEntities.find(pos);
if (it != tileEntities.end()) {
std::shared_ptr<TileEntity> te = tileEntities[pos];
tileEntities.erase(pos);
if (te != nullptr) {
if (level->isClientSide) {
app.DebugPrintf("Removing tile entity of type %d\n",
te->GetType());
{
std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
auto it = tileEntities.find(pos);
if (it != tileEntities.end()) {
std::shared_ptr<TileEntity> te = tileEntities[pos];
tileEntities.erase(pos);
if (te != nullptr) {
if (level->isClientSide) {
app.DebugPrintf("Removing tile entity of type %d\n",
te->GetType());
}
te->setRemoved();
}
te->setRemoved();
}
}
}
}
}
@ -1361,17 +1376,20 @@ void LevelChunk::load() {
#endif
std::vector<std::shared_ptr<TileEntity> > values;
{ std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
for (auto it = tileEntities.begin(); it != tileEntities.end(); it++) {
values.push_back(it->second);
}
{
std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
for (auto it = tileEntities.begin(); it != tileEntities.end();
it++) {
values.push_back(it->second);
}
}
level->addAllPendingTileEntities(values);
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
level->addEntities(entityBlocks[i]);
}
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
level->addEntities(entityBlocks[i]);
}
}
} else {
#if defined(_LARGE_WORLDS)
@ -1385,10 +1403,12 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter
loaded = false;
if (unloadTileEntities) {
std::vector<std::shared_ptr<TileEntity> > tileEntitiesToRemove;
{ std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
for (auto it = tileEntities.begin(); it != tileEntities.end(); it++) {
tileEntitiesToRemove.push_back(it->second);
}
{
std::lock_guard<std::recursive_mutex> lock(m_csTileEntities);
for (auto it = tileEntities.begin(); it != tileEntities.end();
it++) {
tileEntitiesToRemove.push_back(it->second);
}
}
auto itEnd = tileEntitiesToRemove.end();
@ -1398,10 +1418,11 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter
}
}
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
level->removeEntities(entityBlocks[i]);
}
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
level->removeEntities(entityBlocks[i]);
}
}
// app.DebugPrintf("Unloaded chunk %d, %d\n", x, z);
@ -1418,22 +1439,23 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter
PIXBeginNamedEvent(0, "Saving entities");
ListTag<CompoundTag>* entityTags = new ListTag<CompoundTag>();
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
auto itEnd = entityBlocks[i]->end();
for (std::vector<std::shared_ptr<Entity> >::iterator it =
entityBlocks[i]->begin();
it != itEnd; it++) {
std::shared_ptr<Entity> e = *it;
CompoundTag* teTag = new CompoundTag();
if (e->save(teTag)) {
entityTags->add(teTag);
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
auto itEnd = entityBlocks[i]->end();
for (std::vector<std::shared_ptr<Entity> >::iterator it =
entityBlocks[i]->begin();
it != itEnd; it++) {
std::shared_ptr<Entity> e = *it;
CompoundTag* teTag = new CompoundTag();
if (e->save(teTag)) {
entityTags->add(teTag);
}
}
}
// Clear out this list
entityBlocks[i]->clear();
}
// Clear out this list
entityBlocks[i]->clear();
}
}
m_unloadedEntitiesTag->put(L"Entities", entityTags);
@ -1463,16 +1485,17 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter
}
bool LevelChunk::containsPlayer() {
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
std::vector<std::shared_ptr<Entity> >* vecEntity = entityBlocks[i];
for (int j = 0; j < vecEntity->size(); j++) {
if (vecEntity->at(j)->GetType() == eTYPE_SERVERPLAYER) {
return true;
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) {
std::vector<std::shared_ptr<Entity> >* vecEntity = entityBlocks[i];
for (int j = 0; j < vecEntity->size(); j++) {
if (vecEntity->at(j)->GetType() == eTYPE_SERVERPLAYER) {
return true;
}
}
}
}
}
return false;
}
@ -1492,31 +1515,32 @@ void LevelChunk::getEntities(std::shared_ptr<Entity> except, AABB* bb,
// AP - locking is expensive so enter once in
// Level::getEntities
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int yc = yc0; yc <= yc1; yc++) {
std::vector<std::shared_ptr<Entity> >* entities = entityBlocks[yc];
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int yc = yc0; yc <= yc1; yc++) {
std::vector<std::shared_ptr<Entity> >* entities = entityBlocks[yc];
auto itEnd = entities->end();
for (auto it = entities->begin(); it != itEnd; it++) {
std::shared_ptr<Entity> e = *it; // entities->at(i);
if (e != except && e->bb.intersects(*bb) &&
(selector == nullptr || selector->matches(e))) {
es.push_back(e);
std::vector<std::shared_ptr<Entity> >* subs =
e->getSubEntities();
if (subs != nullptr) {
for (int j = 0; j < subs->size(); j++) {
e = subs->at(j);
if (e != except && e->bb.intersects(*bb) &&
(selector == nullptr || selector->matches(e))) {
es.push_back(e);
auto itEnd = entities->end();
for (auto it = entities->begin(); it != itEnd; it++) {
std::shared_ptr<Entity> e = *it; // entities->at(i);
if (e != except && e->bb.intersects(*bb) &&
(selector == nullptr || selector->matches(e))) {
es.push_back(e);
std::vector<std::shared_ptr<Entity> >* subs =
e->getSubEntities();
if (subs != nullptr) {
for (int j = 0; j < subs->size(); j++) {
e = subs->at(j);
if (e != except && e->bb.intersects(*bb) &&
(selector == nullptr || selector->matches(e))) {
es.push_back(e);
}
}
}
}
}
}
}
}
}
void LevelChunk::getEntitiesOfClass(const std::type_info& ec, AABB* bb,
@ -1538,55 +1562,57 @@ void LevelChunk::getEntitiesOfClass(const std::type_info& ec, AABB* bb,
// AP - locking is expensive so enter once in
// Level::getEntitiesOfClass
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int yc = yc0; yc <= yc1; yc++) {
std::vector<std::shared_ptr<Entity> >* entities = entityBlocks[yc];
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int yc = yc0; yc <= yc1; yc++) {
std::vector<std::shared_ptr<Entity> >* entities = entityBlocks[yc];
auto itEnd = entities->end();
for (auto it = entities->begin(); it != itEnd; it++) {
std::shared_ptr<Entity> e = *it; // entities->at(i);
auto itEnd = entities->end();
for (auto it = entities->begin(); it != itEnd; it++) {
std::shared_ptr<Entity> e = *it; // entities->at(i);
bool isAssignableFrom = false;
// Some special cases where the base class is a general type that
// our class may be derived from, otherwise do a direct comparison
// of type_info
if (ec == typeid(Player))
isAssignableFrom = e->instanceof(eTYPE_PLAYER);
else if (ec == typeid(Entity))
isAssignableFrom = e->instanceof(eTYPE_ENTITY);
else if (ec == typeid(Mob))
isAssignableFrom = e->instanceof(eTYPE_MOB);
else if (ec == typeid(LivingEntity))
isAssignableFrom = e->instanceof(eTYPE_LIVINGENTITY);
else if (ec == typeid(ItemEntity))
isAssignableFrom = e->instanceof(eTYPE_ITEMENTITY);
else if (ec == typeid(Minecart))
isAssignableFrom = e->instanceof(eTYPE_MINECART);
else if (ec == typeid(Monster))
isAssignableFrom = e->instanceof(eTYPE_MONSTER);
else if (ec == typeid(Zombie))
isAssignableFrom = e->instanceof(eTYPE_ZOMBIE);
else if (Entity* entity = e.get();
entity != nullptr && ec == typeid(*entity))
isAssignableFrom = true;
if (isAssignableFrom && e->bb.intersects(*bb)) {
if (selector == nullptr || selector->matches(e)) {
es.push_back(e);
bool isAssignableFrom = false;
// Some special cases where the base class is a general type
// that our class may be derived from, otherwise do a direct
// comparison of type_info
if (ec == typeid(Player))
isAssignableFrom = e->instanceof(eTYPE_PLAYER);
else if (ec == typeid(Entity))
isAssignableFrom = e->instanceof(eTYPE_ENTITY);
else if (ec == typeid(Mob))
isAssignableFrom = e->instanceof(eTYPE_MOB);
else if (ec == typeid(LivingEntity))
isAssignableFrom = e->instanceof(eTYPE_LIVINGENTITY);
else if (ec == typeid(ItemEntity))
isAssignableFrom = e->instanceof(eTYPE_ITEMENTITY);
else if (ec == typeid(Minecart))
isAssignableFrom = e->instanceof(eTYPE_MINECART);
else if (ec == typeid(Monster))
isAssignableFrom = e->instanceof(eTYPE_MONSTER);
else if (ec == typeid(Zombie))
isAssignableFrom = e->instanceof(eTYPE_ZOMBIE);
else if (Entity* entity = e.get();
entity != nullptr && ec == typeid(*entity))
isAssignableFrom = true;
if (isAssignableFrom && e->bb.intersects(*bb)) {
if (selector == nullptr || selector->matches(e)) {
es.push_back(e);
}
}
// 4J - note needs to be equivalent to
// baseClass.isAssignableFrom(e.getClass())
}
// 4J - note needs to be equivalent to
// baseClass.isAssignableFrom(e.getClass())
}
}
}
}
int LevelChunk::countEntities() {
int entityCount = 0;
{ std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int yc = 0; yc < ENTITY_BLOCKS_LENGTH; yc++) {
entityCount += (int)entityBlocks[yc]->size();
}
{
std::lock_guard<std::recursive_mutex> lock(m_csEntities);
for (int yc = 0; yc < ENTITY_BLOCKS_LENGTH; yc++) {
entityCount += (int)entityBlocks[yc]->size();
}
}
return entityCount;
}
@ -2131,11 +2157,12 @@ void LevelChunk::compressBlocks() {
// Note - only the extraction of the pointers needs to be done in the
// lock, since even if the data is unshared whilst we are
// processing this data is still valid (for the server)
{ std::lock_guard<std::recursive_mutex> lock(m_csSharing);
if (sharingTilesAndData) {
blocksToCompressLower = lowerBlocks;
blocksToCompressUpper = upperBlocks;
}
{
std::lock_guard<std::recursive_mutex> lock(m_csSharing);
if (sharingTilesAndData) {
blocksToCompressLower = lowerBlocks;
blocksToCompressUpper = upperBlocks;
}
}
} else {
// Not the host, simple case
@ -2230,11 +2257,12 @@ void LevelChunk::compressData() {
// Note - only the extraction of the pointers needs to be done in the
// lock, since even if the data is unshared whilst we are
// processing this data is still valid (for the server)
{ std::lock_guard<std::recursive_mutex> lock(m_csSharing);
if (sharingTilesAndData) {
dataToCompressLower = lowerData;
dataToCompressUpper = upperData;
}
{
std::lock_guard<std::recursive_mutex> lock(m_csSharing);
if (sharingTilesAndData) {
dataToCompressLower = lowerData;
dataToCompressUpper = upperData;
}
}
} else {
// Not the host, simple case

View file

@ -33,16 +33,17 @@ CompressedTileStorage::CompressedTileStorage() {
}
CompressedTileStorage::CompressedTileStorage(CompressedTileStorage* copyFrom) {
{ std::lock_guard<std::recursive_mutex> lock(cs_write);
allocatedSize = copyFrom->allocatedSize;
if (allocatedSize > 0) {
indicesAndData = (unsigned char*)XPhysicalAlloc(
allocatedSize, MAXULONG_PTR, 4096,
PAGE_READWRITE); //(unsigned char *)malloc(allocatedSize);
XMemCpy(indicesAndData, copyFrom->indicesAndData, allocatedSize);
} else {
indicesAndData = nullptr;
}
{
std::lock_guard<std::recursive_mutex> lock(cs_write);
allocatedSize = copyFrom->allocatedSize;
if (allocatedSize > 0) {
indicesAndData = (unsigned char*)XPhysicalAlloc(
allocatedSize, MAXULONG_PTR, 4096,
PAGE_READWRITE); //(unsigned char *)malloc(allocatedSize);
XMemCpy(indicesAndData, copyFrom->indicesAndData, allocatedSize);
} else {
indicesAndData = nullptr;
}
}
#if defined(PSVITA_PRECOMPUTED_TABLE)

View file

@ -184,8 +184,9 @@ void McRegionChunkStorage::save(Level* level, LevelChunk* levelChunk) {
// Note - have added use of a mutex round sections of code that
// do a lot of memory alloc/free operations. This is because when we are
// running saves on multiple threads these sections have a lot of contention.
// Better to let each thread have its turn at a higher level of granularity.
// running saves on multiple threads these sections have a lot of
// contention. Better to let each thread have its turn at a higher level of
// granularity.
MemSect(30);
PIXBeginNamedEvent(0, "Getting output stream\n");
DataOutputStream* output = RegionFileCache::getChunkDataOutputStream(
@ -199,22 +200,24 @@ void McRegionChunkStorage::save(Level* level, LevelChunk* levelChunk) {
PIXEndNamedEvent();
PIXBeginNamedEvent(0, "Updating chunk queue");
{ std::lock_guard<std::mutex> lock(cs_memory);
s_chunkDataQueue.push_back(output);
{
std::lock_guard<std::mutex> lock(cs_memory);
s_chunkDataQueue.push_back(output);
}
PIXEndNamedEvent();
} else {
CompoundTag* tag;
{ std::lock_guard<std::mutex> lock(cs_memory);
PIXBeginNamedEvent(0, "Creating tags\n");
tag = new CompoundTag();
CompoundTag* levelData = new CompoundTag();
tag->put(L"Level", levelData);
OldChunkStorage::save(levelChunk, level, levelData);
PIXEndNamedEvent();
PIXBeginNamedEvent(0, "NbtIo writing\n");
NbtIo::write(tag, output);
PIXEndNamedEvent();
{
std::lock_guard<std::mutex> lock(cs_memory);
PIXBeginNamedEvent(0, "Creating tags\n");
tag = new CompoundTag();
CompoundTag* levelData = new CompoundTag();
tag->put(L"Level", levelData);
OldChunkStorage::save(levelChunk, level, levelData);
PIXEndNamedEvent();
PIXBeginNamedEvent(0, "NbtIo writing\n");
NbtIo::write(tag, output);
PIXEndNamedEvent();
}
PIXBeginNamedEvent(0, "Output closing\n");
output->close();
@ -223,11 +226,12 @@ void McRegionChunkStorage::save(Level* level, LevelChunk* levelChunk) {
// 4J Stu - getChunkDataOutputStream makes a new DataOutputStream that
// points to a new ChunkBuffer( ByteArrayOutputStream ) We should clean
// these up when we are done
{ std::lock_guard<std::mutex> lock(cs_memory);
PIXBeginNamedEvent(0, "Cleaning up\n");
output->deleteChildStream();
delete output;
delete tag;
{
std::lock_guard<std::mutex> lock(cs_memory);
PIXBeginNamedEvent(0, "Cleaning up\n");
output->deleteChildStream();
delete output;
delete tag;
}
PIXEndNamedEvent();
}
@ -355,32 +359,34 @@ int McRegionChunkStorage::runSaveThreadProc(void* lpParam) {
DataOutputStream* dos = nullptr;
while (running) {
{ std::unique_lock<std::mutex> lock(cs_memory, std::try_to_lock);
if (lock.owns_lock()) {
lastQueueSize = s_chunkDataQueue.size();
if (lastQueueSize > 0) {
dos = s_chunkDataQueue.front();
s_chunkDataQueue.pop_front();
}
s_runningThreadCount++;
lock.unlock();
{
std::unique_lock<std::mutex> lock(cs_memory, std::try_to_lock);
if (lock.owns_lock()) {
lastQueueSize = s_chunkDataQueue.size();
if (lastQueueSize > 0) {
dos = s_chunkDataQueue.front();
s_chunkDataQueue.pop_front();
}
s_runningThreadCount++;
lock.unlock();
if (dos) {
PIXBeginNamedEvent(0, "Saving chunk");
// app.DebugPrintf("Compressing chunk data (%d left)\n",
// lastQueueSize - 1);
dos->close();
dos->deleteChildStream();
PIXEndNamedEvent();
}
delete dos;
dos = nullptr;
if (dos) {
PIXBeginNamedEvent(0, "Saving chunk");
// app.DebugPrintf("Compressing chunk data (%d left)\n",
// lastQueueSize - 1);
dos->close();
dos->deleteChildStream();
PIXEndNamedEvent();
}
delete dos;
dos = nullptr;
{ std::lock_guard<std::mutex> lock2(cs_memory);
s_runningThreadCount--;
{
std::lock_guard<std::mutex> lock2(cs_memory);
s_runningThreadCount--;
}
}
}
}
// If there was more than one thing in the queue last time we checked,
// then we want to spin round again soon Otherwise wait a bit longer
@ -404,30 +410,34 @@ void McRegionChunkStorage::WaitIfTooManyQueuedChunks() { WaitForSaves(); }
void McRegionChunkStorage::WaitForAllSaves() {
// Wait for there to be no more tasks to be processed...
size_t queueSize;
{ std::lock_guard<std::mutex> lock(cs_memory);
queueSize = s_chunkDataQueue.size();
{
std::lock_guard<std::mutex> lock(cs_memory);
queueSize = s_chunkDataQueue.size();
}
while (queueSize > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
{ std::lock_guard<std::mutex> lock(cs_memory);
queueSize = s_chunkDataQueue.size();
{
std::lock_guard<std::mutex> lock(cs_memory);
queueSize = s_chunkDataQueue.size();
}
}
// And then wait for there to be no running threads that are processing
// these tasks
int runningThreadCount;
{ std::lock_guard<std::mutex> lock(cs_memory);
runningThreadCount = s_runningThreadCount;
{
std::lock_guard<std::mutex> lock(cs_memory);
runningThreadCount = s_runningThreadCount;
}
while (runningThreadCount > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
{ std::lock_guard<std::mutex> lock(cs_memory);
runningThreadCount = s_runningThreadCount;
{
std::lock_guard<std::mutex> lock(cs_memory);
runningThreadCount = s_runningThreadCount;
}
}
}
@ -439,16 +449,18 @@ void McRegionChunkStorage::WaitForSaves() {
// Wait for the queue to reduce to a level where we should add more elements
size_t queueSize;
{ std::lock_guard<std::mutex> lock(cs_memory);
queueSize = s_chunkDataQueue.size();
{
std::lock_guard<std::mutex> lock(cs_memory);
queueSize = s_chunkDataQueue.size();
}
if (queueSize > MAX_QUEUE_SIZE) {
while (queueSize > DESIRED_QUEUE_SIZE) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
{ std::lock_guard<std::mutex> lock(cs_memory);
queueSize = s_chunkDataQueue.size();
{
std::lock_guard<std::mutex> lock(cs_memory);
queueSize = s_chunkDataQueue.size();
}
}
}

View file

@ -218,7 +218,8 @@ void ZonedChunkStorage::saveEntities(Level* level, LevelChunk* lc) {
{
std::lock_guard<std::mutex> lock(lc->m_csEntities);
for (int i = 0; i < LevelChunk::ENTITY_BLOCKS_LENGTH; i++) {
std::vector<std::shared_ptr<Entity> >* entities = lc->entityBlocks[i];
std::vector<std::shared_ptr<Entity> >* entities =
lc->entityBlocks[i];
auto itEndTags = entities->end();
for (auto it = entities->begin(); it != itEndTags; it++) {

View file

@ -462,7 +462,8 @@ void Connection::tick() {
{
std::lock_guard<std::mutex> lock(incoming_cs);
while (!disconnected && !g_NetworkManager.IsLeavingGame() &&
g_NetworkManager.IsInSession() && !incoming.empty() && max-- >= 0) {
g_NetworkManager.IsInSession() && !incoming.empty() &&
max-- >= 0) {
std::shared_ptr<Packet> packet = incoming.front();
packetsToHandle.push_back(packet);
incoming.pop();

View file

@ -55,7 +55,7 @@ private:
bool running;
std::queue<std::shared_ptr<Packet> >
incoming; // 4J - was using synchronizedList...
incoming; // 4J - was using synchronizedList...
std::mutex incoming_cs; // ... now has this mutex
std::queue<std::shared_ptr<Packet> >
outgoing; // 4J - was using synchronizedList - but don't think it is

View file

@ -47,7 +47,8 @@ void Socket::Initialise(ServerConnection* serverConnection) {
// Streams already exist just reset queue state and re-open streams.
for (int i = 0; i < 2; i++) {
{
std::unique_lock<std::mutex> lock(s_hostQueueLock[i], std::try_to_lock);
std::unique_lock<std::mutex> lock(s_hostQueueLock[i],
std::try_to_lock);
if (lock.owns_lock()) {
// Clear the queue
std::queue<std::uint8_t> empty;
@ -246,7 +247,8 @@ int Socket::SocketInputStreamLocal::read() {
while (m_streamOpen && ShutdownManager::ShouldRun(
ShutdownManager::eConnectionReadThreads)) {
{
std::unique_lock<std::mutex> lock(s_hostQueueLock[m_queueIdx], std::try_to_lock);
std::unique_lock<std::mutex> lock(s_hostQueueLock[m_queueIdx],
std::try_to_lock);
if (lock.owns_lock()) {
if (s_hostQueue[m_queueIdx].size()) {
std::uint8_t retval = s_hostQueue[m_queueIdx].front();
@ -272,7 +274,8 @@ int Socket::SocketInputStreamLocal::read(byteArray b, unsigned int offset,
unsigned int length) {
while (m_streamOpen) {
{
std::unique_lock<std::mutex> lock(s_hostQueueLock[m_queueIdx], std::try_to_lock);
std::unique_lock<std::mutex> lock(s_hostQueueLock[m_queueIdx],
std::try_to_lock);
if (lock.owns_lock()) {
if (s_hostQueue[m_queueIdx].size() >= length) {
for (unsigned int i = 0; i < length; i++) {
@ -356,7 +359,8 @@ int Socket::SocketInputStreamNetwork::read() {
while (m_streamOpen && ShutdownManager::ShouldRun(
ShutdownManager::eConnectionReadThreads)) {
{
std::unique_lock<std::mutex> lock(m_socket->m_queueLockNetwork[m_queueIdx], std::try_to_lock);
std::unique_lock<std::mutex> lock(
m_socket->m_queueLockNetwork[m_queueIdx], std::try_to_lock);
if (lock.owns_lock()) {
if (m_socket->m_queueNetwork[m_queueIdx].size()) {
std::uint8_t retval =
@ -383,7 +387,8 @@ int Socket::SocketInputStreamNetwork::read(byteArray b, unsigned int offset,
unsigned int length) {
while (m_streamOpen) {
{
std::unique_lock<std::mutex> lock(m_socket->m_queueLockNetwork[m_queueIdx], std::try_to_lock);
std::unique_lock<std::mutex> lock(
m_socket->m_queueLockNetwork[m_queueIdx], std::try_to_lock);
if (lock.owns_lock()) {
if (m_socket->m_queueNetwork[m_queueIdx].size() >= length) {
for (unsigned int i = 0; i < length; i++) {
@ -449,7 +454,8 @@ void Socket::SocketOutputStreamNetwork::writeWithFlags(byteArray b,
queueIdx = SOCKET_CLIENT_END;
{
std::lock_guard<std::mutex> lock(m_socket->m_queueLockNetwork[queueIdx]);
std::lock_guard<std::mutex> lock(
m_socket->m_queueLockNetwork[queueIdx]);
for (unsigned int i = 0; i < length; i++) {
m_socket->m_queueNetwork[queueIdx].push(b[offset + i]);
}

View file

@ -115,7 +115,7 @@ private:
// For network connections
std::queue<std::uint8_t> m_queueNetwork[2]; // For input data
std::mutex m_queueLockNetwork[2]; // For input data
std::mutex m_queueLockNetwork[2]; // For input data
SocketInputStreamNetwork* m_inputStream[2];
SocketOutputStreamNetwork* m_outputStream[2];
bool m_endClosed[2];

View file

@ -215,14 +215,30 @@ void setPriorityPlatform(std::thread& threadHandle, bool isSelf,
using enum C4JThread::ThreadPriority;
int niceValue = 0;
switch (priority) {
case TimeCritical: niceValue = -15; break;
case Highest: niceValue = -10; break;
case AboveNormal: niceValue = -5; break;
case Normal: niceValue = 0; break;
case BelowNormal: niceValue = 5; break;
case Lowest: niceValue = 10; break;
case Idle: niceValue = 19; break;
default: niceValue = 0; break;
case TimeCritical:
niceValue = -15;
break;
case Highest:
niceValue = -10;
break;
case AboveNormal:
niceValue = -5;
break;
case Normal:
niceValue = 0;
break;
case BelowNormal:
niceValue = 5;
break;
case Lowest:
niceValue = 10;
break;
case Idle:
niceValue = 19;
break;
default:
niceValue = 0;
break;
}
errno = 0;
@ -401,8 +417,8 @@ bool C4JThread::isMainThread() noexcept {
}
void C4JThread::setThreadName(std::uint32_t threadId, const char* threadName) {
const char* safe = (threadName && threadName[0] != '\0') ? threadName
: "(4J) Unnamed";
const char* safe =
(threadName && threadName[0] != '\0') ? threadName : "(4J) Unnamed";
setThreadNamePlatform(threadId, safe);
}
@ -477,10 +493,9 @@ std::uint32_t C4JThread::EventArray::waitForSingle(int index, int timeoutMs) {
const std::uint32_t bitMask = 1U << static_cast<std::uint32_t>(index);
std::unique_lock lock(m_mutex);
if (!waitForCondition(m_condition, lock, timeoutMs,
[this, bitMask] {
return (m_signaledMask & bitMask) != 0U;
})) {
if (!waitForCondition(m_condition, lock, timeoutMs, [this, bitMask] {
return (m_signaledMask & bitMask) != 0U;
})) {
return WaitResult::Timeout;
}
if (m_mode == Mode::AutoClear) m_signaledMask &= ~bitMask;
@ -491,10 +506,9 @@ std::uint32_t C4JThread::EventArray::waitForAll(int timeoutMs) {
const std::uint32_t bitMask = buildMaskForSize(m_size);
std::unique_lock lock(m_mutex);
if (!waitForCondition(m_condition, lock, timeoutMs,
[this, bitMask] {
return (m_signaledMask & bitMask) == bitMask;
})) {
if (!waitForCondition(m_condition, lock, timeoutMs, [this, bitMask] {
return (m_signaledMask & bitMask) == bitMask;
})) {
return WaitResult::Timeout;
}
if (m_mode == Mode::AutoClear) m_signaledMask &= ~bitMask;
@ -505,15 +519,13 @@ std::uint32_t C4JThread::EventArray::waitForAny(int timeoutMs) {
const std::uint32_t bitMask = buildMaskForSize(m_size);
std::unique_lock lock(m_mutex);
if (!waitForCondition(m_condition, lock, timeoutMs,
[this, bitMask] {
return (m_signaledMask & bitMask) != 0U;
})) {
if (!waitForCondition(m_condition, lock, timeoutMs, [this, bitMask] {
return (m_signaledMask & bitMask) != 0U;
})) {
return WaitResult::Timeout;
}
const std::uint32_t readyIndex =
firstSetBitIndex(m_signaledMask & bitMask);
const std::uint32_t readyIndex = firstSetBitIndex(m_signaledMask & bitMask);
if (m_mode == Mode::AutoClear) m_signaledMask &= ~(1U << readyIndex);
return WaitResult::Signaled + readyIndex;
}