Fix merge conflicts

This commit is contained in:
halogen 2026-03-04 10:03:26 -05:00
commit 8434825dbb
119 changed files with 9672 additions and 8629 deletions

53
.clang-format Normal file
View file

@ -0,0 +1,53 @@
---
BasedOnStyle: Microsoft
AccessModifierOffset: -2
BraceWrapping:
AfterCaseLabel: false
AfterClass: true
AfterControlStatement: Always
AfterEnum: true
AfterExternBlock: true
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: true
AfterStruct: true
AfterUnion: false
BeforeCatch: true
BeforeElse: true
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
ColumnLimit: 0
IncludeBlocks: Preserve
IndentAccessModifiers: false
IndentCaseBlocks: true
IndentCaseLabels: false
IndentExportBlock: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: false
IndentPPDirectives: None
IndentWidth: 4
InsertBraces: true
InsertNewlineAtEOF: true
NamespaceIndentation: None
PointerAlignment: Right
RemoveParentheses: Leave
RemoveSemicolon: false
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes: CaseSensitive
SpacesInParens: Never
SpacesInParensOptions:
ExceptDoubleParentheses: false
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Latest
TabWidth: 4
UseTab: Never

View file

Before

Width:  |  Height:  |  Size: 952 KiB

After

Width:  |  Height:  |  Size: 952 KiB

View file

@ -1,23 +1,23 @@
# Pull Request
## Note: IF YOUR PR CHANGES THE GAME BEHAVIOR VISIBLY, REMEMBER TO ATTACH A GAMEPLAY FOOTAGE (or at least a screenshot) OF YOU *ACTUALLY* PLAYING THE GAME WITH YOUR CHANGES. Untested PRs are *NOT* welcome. Please don't forget to describe what did you do in each commit in your PR.
<!--
Note: IF YOUR PR CHANGES THE GAME BEHAVIOR VISIBLY, REMEMBER TO ATTACH A GAMEPLAY FOOTAGE (or at least a screenshot) OF YOU *ACTUALLY* PLAYING THE GAME WITH YOUR CHANGES. Untested PRs are *NOT* welcome. Please don't forget to describe what did you do in each commit in your PR.
-->
## Description
Briefly describe the changes this PR introduces.
<!-- Briefly describe the changes this PR introduces. -->
## Changes
### Previous Behavior
*Describe how the code behaved before this change.*
<!-- Describe how the code behaved before this change. -->
### Root Cause
*Explain the core reason behind the erroneous/old behavior (e.g., bug, design flaw, missing edge case).*
<!-- Explain the core reason behind the erroneous/old behavior (e.g., bug, design flaw, missing edge case). -->
### New Behavior
*Describe how the code behaves after this change.*
<!-- Describe how the code behaves after this change. -->
### Fix Implementation
*Detail exactly how the issue was resolved (specific code changes, algorithms, logic flows).*
<!-- Detail exactly how the issue was resolved (specific code changes, algorithms, logic flows). -->
## Related Issues
- Fixes #[issue-number]

View file

@ -5,6 +5,10 @@ on:
push:
branches:
- 'main'
paths-ignore:
- '.gitignore'
- '*.md'
- '.github/*.md'
jobs:
build:
@ -32,4 +36,8 @@ jobs:
with:
tag_name: nightly
name: Nightly Release
files: LCEWindows64.zip
body: Requires at least Windows 7 and DirectX 11 compatible GPU to run. Compiled with MSVC v14.44.35207 in Release mode with Whole Program Optimization, as well as `/O2 /Ot /Oi /Ob3 /GF /fp:precise`.
files: |
LCEWindows64.zip
./x64/Release/Minecraft.Client.exe
./x64/Release/Minecraft.Client.pdb

3
.gitignore vendored
View file

@ -430,3 +430,6 @@ build/*
!x64/**/iggy_w64.dll
!x64/**/mss64.dll
!x64/**/redist64/
# Local saves
Minecraft.Client/Saves/

View file

@ -8,11 +8,25 @@ endif()
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
function(configure_msvc_target target)
target_compile_options(${target} PRIVATE
$<$<AND:$<NOT:$<CONFIG:Release>>,$<COMPILE_LANGUAGE:C,CXX>>:/W3>
$<$<AND:$<CONFIG:Release>,$<COMPILE_LANGUAGE:C,CXX>>:/W0>
$<$<COMPILE_LANGUAGE:C,CXX>:/MP>
$<$<COMPILE_LANGUAGE:C,CXX>:/FS>
$<$<COMPILE_LANGUAGE:CXX>:/EHsc>
$<$<AND:$<CONFIG:Release>,$<COMPILE_LANGUAGE:C,CXX>>:/GL /O2 /Oi /GT /GF>
)
endfunction()
include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/WorldSources.cmake")
include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/ClientSources.cmake")
list(TRANSFORM MINECRAFT_WORLD_SOURCES PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.World/")
list(TRANSFORM MINECRAFT_CLIENT_SOURCES PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/")
list(APPEND MINECRAFT_CLIENT_SOURCES
"${CMAKE_CURRENT_SOURCE_DIR}/Minecraft.Client/Xbox/MinecraftWindows.rc"
)
add_library(MinecraftWorld STATIC ${MINECRAFT_WORLD_SOURCES})
target_include_directories(MinecraftWorld PRIVATE
@ -24,11 +38,7 @@ target_compile_definitions(MinecraftWorld PRIVATE
$<$<NOT:$<CONFIG:Debug>>:_LARGE_WORLDS;_DEBUG_MENUS_ENABLED;_LIB;_CRT_NON_CONFORMING_SWPRINTFS;_CRT_SECURE_NO_WARNINGS;_WINDOWS64>
)
if(MSVC)
target_compile_options(MinecraftWorld PRIVATE
$<$<COMPILE_LANGUAGE:C,CXX>:/W3>
$<$<COMPILE_LANGUAGE:C,CXX>:/MP>
$<$<COMPILE_LANGUAGE:CXX>:/EHsc>
)
configure_msvc_target(MinecraftWorld)
endif()
add_executable(MinecraftClient WIN32 ${MINECRAFT_CLIENT_SOURCES})
@ -43,10 +53,9 @@ target_compile_definitions(MinecraftClient PRIVATE
$<$<NOT:$<CONFIG:Debug>>:_LARGE_WORLDS;_DEBUG_MENUS_ENABLED;_CRT_NON_CONFORMING_SWPRINTFS;_CRT_SECURE_NO_WARNINGS;_WINDOWS64>
)
if(MSVC)
target_compile_options(MinecraftClient PRIVATE
$<$<COMPILE_LANGUAGE:C,CXX>:/W3>
$<$<COMPILE_LANGUAGE:C,CXX>:/MP>
$<$<COMPILE_LANGUAGE:CXX>:/EHsc>
configure_msvc_target(MinecraftClient)
target_link_options(MinecraftClient PRIVATE
$<$<CONFIG:Release>:/LTCG /INCREMENTAL:NO>
)
endif()

View file

@ -63,5 +63,6 @@ MinecraftConsoles/build $ wine MinecraftClient.exe
Notes:
- The CMake build will only compile a Windows binary, and non-win32 systems will cross-compile one.
- Contributors on macOS or Linux should be able to cross-compile a windows build. Running the game via Wine is separate from having a supported build environment.
- Post-build asset copy is automatic for `MinecraftClient` in CMake (Debug and Release variants).
- The game relies on relative paths (for example `Common\Media\...`), so launching from the output directory is required.

View file

@ -55,6 +55,12 @@
#endif
#include "DLCTexturePack.h"
#ifdef _WINDOWS64
#include "Xbox\Network\NetworkPlayerXbox.h"
#include "Common\Network\PlatformNetworkManagerStub.h"
#endif
#ifdef _DURANGO
#include "../Minecraft.World/DurangoStats.h"
#include "../Minecraft.World/GenericStats.h"
@ -421,7 +427,6 @@ void ClientConnection::handleAddEntity(shared_ptr<AddEntityPacket> packet)
{
case AddEntityPacket::MINECART:
e = Minecart::createMinecart(level, x, y, z, packet->data);
break;
case AddEntityPacket::FISH_HOOK:
{
// 4J Stu - Brought forward from 1.4 to be able to drop XP from fishing
@ -444,7 +449,7 @@ void ClientConnection::handleAddEntity(shared_ptr<AddEntityPacket> packet)
}
}
if (owner->instanceof(eTYPE_PLAYER))
if (owner != NULL && owner->instanceof(eTYPE_PLAYER))
{
shared_ptr<Player> player = dynamic_pointer_cast<Player>(owner);
shared_ptr<FishingHook> hook = shared_ptr<FishingHook>( new FishingHook(level, x, y, z, player) );
@ -757,7 +762,7 @@ void ClientConnection::handleAddPlayer(shared_ptr<AddPlayerPacket> packet)
return;
}
}
#ifdef _WINDOWS64
/*#ifdef _WINDOWS64
// On Windows64 all XUIDs are INVALID_XUID so the XUID check above never fires.
// packet->m_playerIndex is the server-assigned sequential index (set via LoginPacket),
// NOT the controller slot — so we must scan all local player slots and match by
@ -771,7 +776,7 @@ void ClientConnection::handleAddPlayer(shared_ptr<AddPlayerPacket> packet)
return;
}
}
#endif
#endif*/
double x = packet->x / 32.0;
double y = packet->y / 32.0;
@ -793,7 +798,28 @@ void ClientConnection::handleAddPlayer(shared_ptr<AddPlayerPacket> packet)
if (networkPlayer != NULL) player->m_displayName = networkPlayer->GetDisplayName();
#else
// On all other platforms display name is just gamertag so don't check with the network manager
player->m_displayName = player->name;
player->m_displayName = player->getName();
#endif
#ifdef _WINDOWS64
{
PlayerUID pktXuid = player->getXuid();
const PlayerUID WIN64_XUID_BASE = (PlayerUID)0xe000d45248242f2e;
if (pktXuid >= WIN64_XUID_BASE && pktXuid < WIN64_XUID_BASE + MINECRAFT_NET_MAX_PLAYERS)
{
BYTE smallId = (BYTE)(pktXuid - WIN64_XUID_BASE);
INetworkPlayer* np = g_NetworkManager.GetPlayerBySmallId(smallId);
if (np != NULL)
{
NetworkPlayerXbox* npx = (NetworkPlayerXbox*)np;
IQNetPlayer* qp = npx->GetQNetPlayer();
if (qp != NULL && qp->m_gamertag[0] == 0)
{
wcsncpy_s(qp->m_gamertag, 32, packet->name.c_str(), _TRUNCATE);
}
}
}
}
#endif
// printf("\t\t\t\t%d: Add player\n",packet->id,packet->yRot);
@ -938,6 +964,39 @@ void ClientConnection::handleMoveEntitySmall(shared_ptr<MoveEntityPacketSmall> p
void ClientConnection::handleRemoveEntity(shared_ptr<RemoveEntitiesPacket> packet)
{
#ifdef _WINDOWS64
if (!g_NetworkManager.IsHost())
{
for (int i = 0; i < packet->ids.length; i++)
{
shared_ptr<Entity> entity = getEntity(packet->ids[i]);
if (entity != NULL && entity->GetType() == eTYPE_PLAYER)
{
shared_ptr<Player> player = dynamic_pointer_cast<Player>(entity);
if (player != NULL)
{
PlayerUID xuid = player->getXuid();
INetworkPlayer* np = g_NetworkManager.GetPlayerByXuid(xuid);
if (np != NULL)
{
NetworkPlayerXbox* npx = (NetworkPlayerXbox*)np;
IQNetPlayer* qp = npx->GetQNetPlayer();
if (qp != NULL)
{
extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager;
g_pPlatformNetworkManager->NotifyPlayerLeaving(qp);
qp->m_smallId = 0;
qp->m_isRemote = false;
qp->m_isHostPlayer = false;
qp->m_gamertag[0] = 0;
qp->SetCustomDataValue(0);
}
}
}
}
}
}
#endif
for (int i = 0; i < packet->ids.length; i++)
{
level->removeEntity(packet->ids[i]);

View file

@ -829,6 +829,7 @@ enum EControllerActions
ACTION_MENU_OTHER_STICK_LEFT,
ACTION_MENU_OTHER_STICK_RIGHT,
ACTION_MENU_PAUSEMENU,
ACTION_MENU_QUICK_MOVE,
#ifdef _DURANGO
ACTION_MENU_GTC_PAUSE,

View file

@ -56,7 +56,7 @@ void SoundEngine::playMusicTick() {};
#else
#ifdef _WINDOWS64
char SoundEngine::m_szSoundPath[]={"Windows64\\Sound\\"};
char SoundEngine::m_szSoundPath[]={"Windows64Media\\Sound\\"};
char SoundEngine::m_szMusicPath[]={"music\\"};
char SoundEngine::m_szRedistName[]={"redist64"};
#elif defined _DURANGO

View file

@ -760,6 +760,43 @@ bool CMinecraftApp::LoadBeaconMenu(int iPad ,shared_ptr<Inventory> inventory, sh
//////////////////////////////////////////////
// GAME SETTINGS
//////////////////////////////////////////////
#ifdef _WINDOWS64
static void Win64_GetSettingsPath(char *outPath, DWORD size)
{
GetModuleFileNameA(NULL, outPath, size);
char *lastSlash = strrchr(outPath, '\\');
if (lastSlash) *(lastSlash + 1) = '\0';
strncat_s(outPath, size, "settings.dat", _TRUNCATE);
}
static void Win64_SaveSettings(GAME_SETTINGS *gs)
{
if (!gs) return;
char filePath[MAX_PATH] = {};
Win64_GetSettingsPath(filePath, MAX_PATH);
FILE *f = NULL;
if (fopen_s(&f, filePath, "wb") == 0 && f)
{
fwrite(gs, sizeof(GAME_SETTINGS), 1, f);
fclose(f);
}
}
static void Win64_LoadSettings(GAME_SETTINGS *gs)
{
if (!gs) return;
char filePath[MAX_PATH] = {};
Win64_GetSettingsPath(filePath, MAX_PATH);
FILE *f = NULL;
if (fopen_s(&f, filePath, "rb") == 0 && f)
{
GAME_SETTINGS temp = {};
if (fread(&temp, sizeof(GAME_SETTINGS), 1, f) == 1)
memcpy(gs, &temp, sizeof(GAME_SETTINGS));
fclose(f);
}
}
#endif
void CMinecraftApp::InitGameSettings()
{
for(int i=0;i<XUSER_MAX_COUNT;i++)
@ -780,6 +817,8 @@ void CMinecraftApp::InitGameSettings()
// clear this for now - it will come from reading the system values
memset(pProfileSettings,0,sizeof(C_4JProfile::PROFILESETTINGS));
SetDefaultOptions(pProfileSettings,i);
Win64_LoadSettings(GameSettingsA[i]);
ApplyGameSettingsChanged(i);
#elif defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__
C4JStorage::PROFILESETTINGS *pProfileSettings=StorageManager.GetDashboardProfileSettings(i);
// 4J-PB - don't cause an options write to happen here
@ -1342,9 +1381,13 @@ void CMinecraftApp::ActionGameSettings(int iPad,eGameSetting eVal)
case eGameSetting_Gamma:
if(iPad==ProfileManager.GetPrimaryPad())
{
#if defined(_WIN64) || defined(_WINDOWS64)
pMinecraft->options->set(Options::Option::GAMMA, ((float)GameSettingsA[iPad]->ucGamma) / 100.0f);
#else
// ucGamma range is 0-100, UpdateGamma is 0 - 32768
float fVal=((float)GameSettingsA[iPad]->ucGamma)*327.68f;
RenderManager.UpdateGamma((unsigned short)fVal);
#endif
}
break;
@ -2368,6 +2411,9 @@ void CMinecraftApp::CheckGameSettingsChanged(bool bOverride5MinuteTimer, int iPa
StorageManager.WriteToProfile(i,true, bOverride5MinuteTimer);
#else
ProfileManager.WriteToProfile(i,true, bOverride5MinuteTimer);
#ifdef _WINDOWS64
Win64_SaveSettings(GameSettingsA[i]);
#endif
#endif
GameSettingsA[i]->bSettingsChanged=false;
}
@ -2381,6 +2427,9 @@ void CMinecraftApp::CheckGameSettingsChanged(bool bOverride5MinuteTimer, int iPa
StorageManager.WriteToProfile(iPad,true, bOverride5MinuteTimer);
#else
ProfileManager.WriteToProfile(iPad,true, bOverride5MinuteTimer);
#ifdef _WINDOWS64
Win64_SaveSettings(GameSettingsA[iPad]);
#endif
#endif
GameSettingsA[iPad]->bSettingsChanged=false;
}
@ -3398,7 +3447,7 @@ void CMinecraftApp::HandleXuiActions(void)
bool gameStarted = false;
for(int j = 0; j < pMinecraft->levels.length; j++)
{
if (pMinecraft->levels.data[i] != NULL)
if (pMinecraft->levels.data[i] != nullptr)
{
gameStarted = true;
break;

View file

@ -167,6 +167,11 @@ bool CGameNetworkManager::_RunNetworkGame(LPVOID lpParameter)
return true;
}
}
else
{
// Client needs QNET_STATE_GAME_PLAY so that IsInGameplay() returns true
s_pPlatformNetworkManager->SetGamePlayState();
}
if( g_NetworkManager.IsLeavingGame() ) return false;
@ -1479,7 +1484,10 @@ void CGameNetworkManager::CreateSocket( INetworkPlayer *pNetworkPlayer, bool loc
Minecraft *pMinecraft = Minecraft::GetInstance();
Socket *socket = NULL;
shared_ptr<MultiplayerLocalPlayer> mpPlayer = pMinecraft->localplayers[pNetworkPlayer->GetUserIndex()];
shared_ptr<MultiplayerLocalPlayer> mpPlayer = nullptr;
int userIdx = pNetworkPlayer->GetUserIndex();
if (userIdx >= 0 && userIdx < XUSER_MAX_COUNT)
mpPlayer = pMinecraft->localplayers[userIdx];
if( localPlayer && mpPlayer != NULL && mpPlayer->connection != NULL)
{
// If we already have a MultiplayerLocalPlayer here then we are doing a session type change
@ -1970,7 +1978,7 @@ bool CGameNetworkManager::AllowedToPlayMultiplayer(int playerIdx)
return ProfileManager.AllowedToPlayMultiplayer(playerIdx);
}
char *CGameNetworkManager::GetOnlineName(int playerIdx)
const char *CGameNetworkManager::GetOnlineName(int playerIdx)
{
return ProfileManager.GetGamertag(playerIdx);
}

View file

@ -196,7 +196,7 @@ private:
int GetLockedProfile();
bool IsSignedInLive(int playerIdx);
bool AllowedToPlayMultiplayer(int playerIdx);
char *GetOnlineName(int playerIdx);
const char *GetOnlineName(int playerIdx);
C4JThread::Event* m_hServerStoppedEvent;
C4JThread::Event* m_hServerReadyEvent;

View file

@ -84,6 +84,7 @@ public:
virtual void HandleSignInChange() = 0;
virtual bool _RunNetworkGame() = 0;
virtual void SetGamePlayState() {}
private:
virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom) = 0;

View file

@ -2,7 +2,12 @@
#include "../../../Minecraft.World/Socket.h"
#include "../../../Minecraft.World/StringHelpers.h"
#include "PlatformNetworkManagerStub.h"
#include "../../Xbox/Network/NetworkPlayerXbox.h" // TODO - stub version of this?
#include "..\..\Xbox\Network\NetworkPlayerXbox.h" // TODO - stub version of this?
#ifdef _WINDOWS64
#include "..\..\Windows64\Network\WinsockNetLayer.h"
#include "..\..\Minecraft.h"
#include "..\..\User.h"
#endif
CPlatformNetworkManagerStub *g_pPlatformNetworkManager;
@ -114,10 +119,43 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer )
}
}
void CPlatformNetworkManagerStub::NotifyPlayerLeaving(IQNetPlayer* pQNetPlayer)
{
app.DebugPrintf("Player 0x%p \"%ls\" leaving.\n", pQNetPlayer, pQNetPlayer->GetGamertag());
INetworkPlayer* networkPlayer = getNetworkPlayer(pQNetPlayer);
if (networkPlayer == NULL)
return;
Socket* socket = networkPlayer->GetSocket();
if (socket != NULL)
{
if (m_pIQNet->IsHost())
g_NetworkManager.CloseConnection(networkPlayer);
}
if (m_pIQNet->IsHost())
{
SystemFlagRemovePlayer(networkPlayer);
}
g_NetworkManager.PlayerLeaving(networkPlayer);
for (int idx = 0; idx < XUSER_MAX_COUNT; ++idx)
{
if (playerChangedCallback[idx] != NULL)
playerChangedCallback[idx](playerChangedCallbackParam[idx], networkPlayer, true);
}
removeNetworkPlayer(pQNetPlayer);
}
bool CPlatformNetworkManagerStub::Initialise(CGameNetworkManager *pGameNetworkManager, int flagIndexSize)
{
m_pGameNetworkManager = pGameNetworkManager;
m_flagIndexSize = flagIndexSize;
m_pIQNet = new IQNet();
g_pPlatformNetworkManager = this;
for( int i = 0; i < XUSER_MAX_COUNT; i++ )
{
@ -174,6 +212,37 @@ bool CPlatformNetworkManagerStub::isSystemPrimaryPlayer(IQNetPlayer *pQNetPlayer
// We call this twice a frame, either side of the render call so is a good place to "tick" things
void CPlatformNetworkManagerStub::DoWork()
{
#ifdef _WINDOWS64
extern QNET_STATE _iQNetStubState;
if (_iQNetStubState == QNET_STATE_SESSION_STARTING && app.GetGameStarted())
{
_iQNetStubState = QNET_STATE_GAME_PLAY;
if (m_pIQNet->IsHost())
WinsockNetLayer::UpdateAdvertiseJoinable(true);
}
if (_iQNetStubState == QNET_STATE_IDLE)
TickSearch();
if (_iQNetStubState == QNET_STATE_GAME_PLAY && m_pIQNet->IsHost())
{
BYTE disconnectedSmallId;
while (WinsockNetLayer::PopDisconnectedSmallId(&disconnectedSmallId))
{
IQNetPlayer* qnetPlayer = m_pIQNet->GetPlayerBySmallId(disconnectedSmallId);
if (qnetPlayer != NULL && qnetPlayer->m_smallId == disconnectedSmallId)
{
NotifyPlayerLeaving(qnetPlayer);
qnetPlayer->m_smallId = 0;
qnetPlayer->m_isRemote = false;
qnetPlayer->m_isHostPlayer = false;
qnetPlayer->m_gamertag[0] = 0;
qnetPlayer->SetCustomDataValue(0);
WinsockNetLayer::PushFreeSmallId(disconnectedSmallId);
if (IQNet::s_playerCount > 1)
IQNet::s_playerCount--;
}
}
}
#endif
}
int CPlatformNetworkManagerStub::GetPlayerCount()
@ -232,6 +301,10 @@ bool CPlatformNetworkManagerStub::LeaveGame(bool bMigrateHost)
m_bLeavingGame = true;
#ifdef _WINDOWS64
WinsockNetLayer::StopAdvertising();
#endif
// If we are the host wait for the game server to end
if(m_pIQNet->IsHost() && g_NetworkManager.ServerStoppedValid())
{
@ -239,6 +312,22 @@ bool CPlatformNetworkManagerStub::LeaveGame(bool bMigrateHost)
g_NetworkManager.ServerStoppedWait();
g_NetworkManager.ServerStoppedDestroy();
}
else
{
m_pIQNet->EndGame();
}
for (AUTO_VAR(it, currentNetworkPlayers.begin()); it != currentNetworkPlayers.end(); it++)
delete* it;
currentNetworkPlayers.clear();
m_machineQNetPrimaryPlayers.clear();
SystemFlagReset();
#ifdef _WINDOWS64
WinsockNetLayer::Shutdown();
WinsockNetLayer::Initialize();
#endif
return true;
}
@ -262,7 +351,35 @@ void CPlatformNetworkManagerStub::HostGame(int localUsersMask, bool bOnlineGame,
m_pIQNet->HostGame();
#ifdef _WINDOWS64
IQNet::m_player[0].m_smallId = 0;
IQNet::m_player[0].m_isRemote = false;
IQNet::m_player[0].m_isHostPlayer = true;
IQNet::s_playerCount = 1;
#endif
_HostGame( localUsersMask, publicSlots, privateSlots );
#ifdef _WINDOWS64
int port = WIN64_NET_DEFAULT_PORT;
const char* bindIp = NULL;
if (g_Win64DedicatedServer)
{
if (g_Win64DedicatedServerPort > 0)
port = g_Win64DedicatedServerPort;
if (g_Win64DedicatedServerBindIP[0] != 0)
bindIp = g_Win64DedicatedServerBindIP;
}
if (!WinsockNetLayer::IsActive())
WinsockNetLayer::HostGame(port, bindIp);
if (WinsockNetLayer::IsActive())
{
const wchar_t* hostName = IQNet::m_player[0].m_gamertag;
unsigned int settings = app.GetGameHostOption(eGameHostOption_All);
WinsockNetLayer::StartAdvertising(port, hostName, settings, 0, 0, MINECRAFT_NET_VERSION);
}
#endif
//#endif
}
@ -275,9 +392,54 @@ bool CPlatformNetworkManagerStub::_StartGame()
return true;
}
int CPlatformNetworkManagerStub::JoinGame(FriendSessionInfo *searchResult, int localUsersMask, int primaryUserIndex)
int CPlatformNetworkManagerStub::JoinGame(FriendSessionInfo* searchResult, int localUsersMask, int primaryUserIndex)
{
#ifdef _WINDOWS64
if (searchResult == NULL)
return CGameNetworkManager::JOINGAME_FAIL_GENERAL;
const char* hostIP = searchResult->data.hostIP;
int hostPort = searchResult->data.hostPort;
if (hostPort <= 0 || hostIP[0] == 0)
return CGameNetworkManager::JOINGAME_FAIL_GENERAL;
m_bLeavingGame = false;
IQNet::s_isHosting = false;
m_pIQNet->ClientJoinGame();
IQNet::m_player[0].m_smallId = 0;
IQNet::m_player[0].m_isRemote = true;
IQNet::m_player[0].m_isHostPlayer = true;
wcsncpy_s(IQNet::m_player[0].m_gamertag, 32, searchResult->data.hostName, _TRUNCATE);
WinsockNetLayer::StopDiscovery();
if (!WinsockNetLayer::JoinGame(hostIP, hostPort))
{
app.DebugPrintf("Win64 LAN: Failed to connect to %s:%d\n", hostIP, hostPort);
return CGameNetworkManager::JOINGAME_FAIL_GENERAL;
}
BYTE localSmallId = WinsockNetLayer::GetLocalSmallId();
IQNet::m_player[localSmallId].m_smallId = localSmallId;
IQNet::m_player[localSmallId].m_isRemote = false;
IQNet::m_player[localSmallId].m_isHostPlayer = false;
Minecraft* pMinecraft = Minecraft::GetInstance();
wcscpy_s(IQNet::m_player[localSmallId].m_gamertag, 32, pMinecraft->user->name.c_str());
IQNet::s_playerCount = localSmallId + 1;
NotifyPlayerJoined(&IQNet::m_player[0]);
NotifyPlayerJoined(&IQNet::m_player[localSmallId]);
m_pGameNetworkManager->StateChange_AnyToStarting();
return CGameNetworkManager::JOINGAME_SUCCESS;
#else
return CGameNetworkManager::JOINGAME_SUCCESS;
#endif
}
bool CPlatformNetworkManagerStub::SetLocalGame(bool isLocal)
@ -315,6 +477,22 @@ void CPlatformNetworkManagerStub::HandleSignInChange()
bool CPlatformNetworkManagerStub::_RunNetworkGame()
{
#ifdef _WINDOWS64
extern QNET_STATE _iQNetStubState;
_iQNetStubState = QNET_STATE_GAME_PLAY;
for (DWORD i = 0; i < IQNet::s_playerCount; i++)
{
if (IQNet::m_player[i].m_isRemote)
{
INetworkPlayer* pNetworkPlayer = getNetworkPlayer(&IQNet::m_player[i]);
if (pNetworkPlayer != NULL && pNetworkPlayer->GetSocket() != NULL)
{
Socket::addIncomingSocket(pNetworkPlayer->GetSocket());
}
}
}
#endif
return true;
}
@ -503,10 +681,60 @@ wstring CPlatformNetworkManagerStub::GatherRTTStats()
void CPlatformNetworkManagerStub::TickSearch()
{
#ifdef _WINDOWS64
if (m_SessionsUpdatedCallback == NULL)
return;
static DWORD lastSearchTime = 0;
DWORD now = GetTickCount();
if (now - lastSearchTime < 2000)
return;
lastSearchTime = now;
SearchForGames();
#endif
}
void CPlatformNetworkManagerStub::SearchForGames()
{
#ifdef _WINDOWS64
std::vector<Win64LANSession> lanSessions = WinsockNetLayer::GetDiscoveredSessions();
for (size_t i = 0; i < friendsSessions[0].size(); i++)
delete friendsSessions[0][i];
friendsSessions[0].clear();
for (size_t i = 0; i < lanSessions.size(); i++)
{
FriendSessionInfo* info = new FriendSessionInfo();
size_t nameLen = wcslen(lanSessions[i].hostName);
info->displayLabel = new wchar_t[nameLen + 1];
wcscpy_s(info->displayLabel, nameLen + 1, lanSessions[i].hostName);
info->displayLabelLength = (unsigned char)nameLen;
info->displayLabelViewableStartIndex = 0;
info->data.netVersion = lanSessions[i].netVersion;
info->data.m_uiGameHostSettings = lanSessions[i].gameHostSettings;
info->data.texturePackParentId = lanSessions[i].texturePackParentId;
info->data.subTexturePackId = lanSessions[i].subTexturePackId;
info->data.isReadyToJoin = lanSessions[i].isJoinable;
info->data.isJoinable = lanSessions[i].isJoinable;
strncpy_s(info->data.hostIP, sizeof(info->data.hostIP), lanSessions[i].hostIP, _TRUNCATE);
info->data.hostPort = lanSessions[i].hostPort;
wcsncpy_s(info->data.hostName, XUSER_NAME_SIZE, lanSessions[i].hostName, _TRUNCATE);
info->data.playerCount = lanSessions[i].playerCount;
info->data.maxPlayers = lanSessions[i].maxPlayers;
info->sessionId = (SessionID)((unsigned __int64)inet_addr(lanSessions[i].hostIP) | ((unsigned __int64)lanSessions[i].hostPort << 32));
friendsSessions[0].push_back(info);
}
m_searchResultsCount[0] = (int)friendsSessions[0].size();
if (m_SessionsUpdatedCallback != NULL)
m_SessionsUpdatedCallback(m_pSearchParam);
#endif
}
int CPlatformNetworkManagerStub::SearchForGamesThreadProc( void* lpParameter )
@ -522,7 +750,9 @@ void CPlatformNetworkManagerStub::SetSearchResultsReady(int resultCount)
vector<FriendSessionInfo *> *CPlatformNetworkManagerStub::GetSessionList(int iPad, int localPlayers, bool partyOnly)
{
vector<FriendSessionInfo *> *filteredList = new vector<FriendSessionInfo *>();;
vector<FriendSessionInfo*>* filteredList = new vector<FriendSessionInfo*>();
for (size_t i = 0; i < friendsSessions[0].size(); i++)
filteredList->push_back(friendsSessions[0][i]);
return filteredList;
}

View file

@ -161,8 +161,9 @@ public:
virtual void GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam );
virtual void ForceFriendsSessionRefresh();
private:
public:
void NotifyPlayerJoined( IQNetPlayer *pQNetPlayer );
void NotifyPlayerLeaving(IQNetPlayer* pQNetPlayer);
#ifndef _XBOX
void FakeLocalPlayerJoined() { NotifyPlayerJoined(m_pIQNet->GetLocalPlayerByUserIndex(0)); }

View file

@ -23,9 +23,9 @@ typedef struct _GameSessionData
_GameSessionData()
{
netVersion = 0;
memset(hostName,0,XUSER_NAME_SIZE);
memset(players,0,MINECRAFT_NET_MAX_PLAYERS*sizeof(players[0]));
memset(szPlayers,0,MINECRAFT_NET_MAX_PLAYERS*XUSER_NAME_SIZE);
memset(hostName, 0, XUSER_NAME_SIZE);
memset(players, 0, MINECRAFT_NET_MAX_PLAYERS * sizeof(players[0]));
memset(szPlayers, 0, MINECRAFT_NET_MAX_PLAYERS * XUSER_NAME_SIZE);
isJoinable = true;
m_uiGameHostSettings = 0;
texturePackParentId = 0;
@ -50,7 +50,7 @@ typedef struct _GameSessionData
_GameSessionData()
{
netVersion = 0;
memset(players,0,MINECRAFT_NET_MAX_PLAYERS*sizeof(players[0]));
memset(players, 0, MINECRAFT_NET_MAX_PLAYERS * sizeof(players[0]));
isJoinable = true;
m_uiGameHostSettings = 0;
texturePackParentId = 0;
@ -63,12 +63,19 @@ typedef struct _GameSessionData
#else
typedef struct _GameSessionData
{
unsigned short netVersion; // 2 bytes
unsigned int m_uiGameHostSettings; // 4 bytes
unsigned int texturePackParentId; // 4 bytes
unsigned char subTexturePackId; // 1 byte
unsigned short netVersion;
unsigned int m_uiGameHostSettings;
unsigned int texturePackParentId;
unsigned char subTexturePackId;
bool isReadyToJoin; // 1 byte
bool isReadyToJoin;
bool isJoinable;
char hostIP[64];
int hostPort;
wchar_t hostName[XUSER_NAME_SIZE];
unsigned char playerCount;
unsigned char maxPlayers;
_GameSessionData()
{
@ -76,6 +83,13 @@ typedef struct _GameSessionData
m_uiGameHostSettings = 0;
texturePackParentId = 0;
subTexturePackId = 0;
isReadyToJoin = false;
isJoinable = true;
memset(hostIP, 0, sizeof(hostIP));
hostPort = 0;
memset(hostName, 0, sizeof(hostName));
playerCount = 0;
maxPlayers = MINECRAFT_NET_MAX_PLAYERS;
}
} GameSessionData;
#endif
@ -91,7 +105,7 @@ public:
#elif defined(_DURANGO)
DQRNetworkManager::SessionSearchResult searchResult;
#endif
wchar_t *displayLabel;
wchar_t* displayLabel;
unsigned char displayLabelLength;
unsigned char displayLabelViewableStartIndex;
GameSessionData data;
@ -107,7 +121,7 @@ public:
~FriendSessionInfo()
{
if(displayLabel!=NULL)
if (displayLabel != NULL)
delete displayLabel;
}
};

View file

@ -21,6 +21,7 @@ IUIScene_AbstractContainerMenu::IUIScene_AbstractContainerMenu()
m_pointerPos.x = 0.0f;
m_pointerPos.y = 0.0f;
m_bPointerDrivenByMouse = false;
}
@ -357,6 +358,7 @@ void IUIScene_AbstractContainerMenu::onMouseTick()
// If there is any input on sticks, move the pointer.
if ( ( fabs( fInputX ) >= 0.01f ) || ( fabs( fInputY ) >= 0.01f ) )
{
m_bPointerDrivenByMouse = false;
fInputDirX = ( fInputX > 0.0f ) ? 1.0f : ( fInputX < 0.0f )?-1.0f : 0.0f;
fInputDirY = ( fInputY > 0.0f ) ? 1.0f : ( fInputY < 0.0f )?-1.0f : 0.0f;
@ -692,7 +694,7 @@ void IUIScene_AbstractContainerMenu::onMouseTick()
// If there is no stick input, and we are over a slot, then snap pointer to slot centre.
// 4J - TomK - only if this particular component allows so!
if(CanHaveFocus(eSectionUnderPointer))
if(!m_bPointerDrivenByMouse && CanHaveFocus(eSectionUnderPointer))
{
vPointerPos.x = vSnapPos.x;
vPointerPos.y = vSnapPos.y;
@ -1302,42 +1304,60 @@ bool IUIScene_AbstractContainerMenu::handleKeyDown(int iPad, int iAction, bool b
#endif
int buttonNum=0; // 0 = LeftMouse, 1 = RightMouse
BOOL quickKeyHeld=FALSE; // Represents shift key on PC
BOOL validKeyPress = FALSE;
BOOL quickKeyHeld=false; // Represents shift key on PC
BOOL quickKeyDown = false; // Represents shift key on PC
BOOL validKeyPress = false;
bool itemEditorKeyPress = false;
// Ignore input from other players
//if(pMinecraft->player->GetXboxPad()!=pInputData->UserIndex) return S_OK;
switch(iAction)
{
#ifdef _DEBUG_MENUS_ENABLED
case ACTION_MENU_OTHER_STICK_PRESS:
itemEditorKeyPress = TRUE;
break;
#endif
#endif
case ACTION_MENU_A:
#ifdef __ORBIS__
case ACTION_MENU_TOUCHPAD_PRESS:
#endif
if(!bRepeat)
if (!bRepeat)
{
validKeyPress = TRUE;
// Standard left click
buttonNum = 0;
quickKeyHeld = FALSE;
if( IsSectionSlotList( m_eCurrSection ) )
if (KMInput.IsKeyDown(VK_SHIFT))
{
int currentIndex = getCurrentIndex( m_eCurrSection ) - getSectionStartOffset(m_eCurrSection);
{
validKeyPress = TRUE;
bool bSlotHasItem = !isSlotEmpty(m_eCurrSection, currentIndex);
if ( bSlotHasItem )
ui.PlayUISFX(eSFX_Press);
// Shift and left click
buttonNum = 0;
quickKeyHeld = TRUE;
if (IsSectionSlotList(m_eCurrSection))
{
int currentIndex = getCurrentIndex(m_eCurrSection) - getSectionStartOffset(m_eCurrSection);
bool bSlotHasItem = !isSlotEmpty(m_eCurrSection, currentIndex);
if (bSlotHasItem)
ui.PlayUISFX(eSFX_Press);
}
}
}
else {
if (IsSectionSlotList(m_eCurrSection))
{
int currentIndex = getCurrentIndex(m_eCurrSection) - getSectionStartOffset(m_eCurrSection);
bool bSlotHasItem = !isSlotEmpty(m_eCurrSection, currentIndex);
if (bSlotHasItem)
ui.PlayUISFX(eSFX_Press);
}
//
}
//
}
break;
case ACTION_MENU_X:
@ -1359,6 +1379,7 @@ bool IUIScene_AbstractContainerMenu::handleKeyDown(int iPad, int iAction, bool b
}
}
break;
case ACTION_MENU_Y:
if(!bRepeat)
{

View file

@ -125,6 +125,7 @@ protected:
eTutorial_State m_previousTutorialState;
UIVec2D m_pointerPos;
bool m_bPointerDrivenByMouse;
// Offset from pointer image top left to centre (we use the centre as the actual pointer).
float m_fPointerImageOffsetX;

View file

@ -210,7 +210,6 @@ void IUIScene_CreativeMenu::staticCtor()
ITEM_AUX(Tile::woolCarpet_Id,13) // Green
ITEM_AUX(Tile::woolCarpet_Id,12) // Brown
#if 0
ITEM_AUX(Tile::stained_glass_Id,14) // Red
ITEM_AUX(Tile::stained_glass_Id,1) // Orange
ITEM_AUX(Tile::stained_glass_Id,4) // Yellow
@ -244,7 +243,6 @@ void IUIScene_CreativeMenu::staticCtor()
ITEM_AUX(Tile::stained_glass_pane_Id,15) // Black
ITEM_AUX(Tile::stained_glass_pane_Id,13) // Green
ITEM_AUX(Tile::stained_glass_pane_Id,12) // Brown
#endif
#ifndef _CONTENT_PACKAGE
DEF(eCreativeInventory_ArtToolsDecorations)
@ -845,8 +843,9 @@ IUIScene_CreativeMenu::TabSpec::TabSpec(LPCWSTR icon, int descriptionId, int sta
}
}
m_staticPerPage = MAX_SIZE - dynamicItems;
m_pages = (int)ceil((float)m_staticItems / m_staticPerPage);
m_staticPerPage = columns;
const int totalRows = (m_staticItems + columns - 1) / columns;
m_pages = std::max<int>(1, totalRows - 5 + 1);
}
IUIScene_CreativeMenu::TabSpec::~TabSpec()
@ -881,7 +880,7 @@ void IUIScene_CreativeMenu::TabSpec::populateMenu(AbstractContainerMenu *menu, i
for(; currentGroup < m_staticGroupsCount; ++currentGroup)
{
int size = categoryGroups[m_staticGroupsA[currentGroup]].size();
if( currentIndex + size < startIndex)
if( currentIndex + size <= startIndex)
{
currentIndex += size;
continue;
@ -931,7 +930,7 @@ void IUIScene_CreativeMenu::TabSpec::populateMenu(AbstractContainerMenu *menu, i
for(; currentGroup < m_debugGroupsCount; ++currentGroup)
{
int size = categoryGroups[m_debugGroupsA[currentGroup]].size();
if( currentIndex + size < startIndex)
if( currentIndex + size <= startIndex)
{
currentIndex += size;
continue;
@ -972,7 +971,9 @@ unsigned int IUIScene_CreativeMenu::TabSpec::getPageCount()
#ifndef _CONTENT_PACKAGE
if(app.DebugArtToolsOn())
{
return (int)ceil((float)(m_staticItems + m_debugItems) / m_staticPerPage);
int totalItems = m_staticItems + m_debugItems;
const int totalRows = (totalItems + columns - 1) / columns;
return std::max<int>(1, totalRows - rows + 1);
}
else
#endif

View file

@ -1012,6 +1012,7 @@ void UIController::handleKeyPress(unsigned int iPad, unsigned int key)
case ACTION_MENU_PAUSEMENU: kbDown = KMInput.IsKeyDown(VK_ESCAPE); kbPressed = KMInput.IsKeyPressed(VK_ESCAPE); kbReleased = KMInput.IsKeyReleased(VK_ESCAPE); break;
case ACTION_MENU_LEFT_SCROLL: kbDown = KMInput.IsKeyDown('Q'); kbPressed = KMInput.IsKeyPressed('Q'); kbReleased = KMInput.IsKeyReleased('Q'); break;
case ACTION_MENU_RIGHT_SCROLL: kbDown = KMInput.IsKeyDown('E'); kbPressed = KMInput.IsKeyPressed('E'); kbReleased = KMInput.IsKeyReleased('E'); break;
case ACTION_MENU_QUICK_MOVE: kbDown = KMInput.IsKeyDown(VK_SHIFT); kbPressed = KMInput.IsKeyPressed(VK_SHIFT); kbReleased = KMInput.IsKeyReleased(VK_SHIFT); break;
}
pressed = pressed || kbPressed;
released = released || kbReleased;
@ -1444,7 +1445,7 @@ GDrawTexture * RADLINK UIController::TextureSubstitutionCreateCallback ( void *
// 4J Stu - All our flash controls that allow replacing textures use a special 64x64 symbol
// Force this size here so that our images don't get scaled wildly
#if (defined __ORBIS__ || defined _DURANGO )
#if (defined __ORBIS__ || defined _DURANGO || defined _WINDOWS64 )
*width = 96;
*height = 96;
#else

View file

@ -30,6 +30,14 @@ UIScene_AbstractContainerMenu::UIScene_AbstractContainerMenu(int iPad, UILayer *
m_bIgnoreInput=false;
#ifdef _WINDOWS64
m_bMouseDragSlider=false;
m_bHasMousePosition = false;
m_lastMouseX = 0;
m_lastMouseY = 0;
for (int btn = 0; btn < 3; btn++)
{
KMInput.ConsumeMousePress(btn);
}
#endif
}
@ -184,7 +192,9 @@ void UIScene_AbstractContainerMenu::tick()
#ifdef _WINDOWS64
bool mouseActive = (m_iPad == 0 && !KMInput.IsCaptured());
bool drivePointerFromMouse = false;
float rawMouseMovieX = 0, rawMouseMovieY = 0;
int scrollDelta = 0;
// Map Windows mouse position to the virtual pointer in movie coordinates
if (mouseActive)
{
@ -196,15 +206,30 @@ void UIScene_AbstractContainerMenu::tick()
{
int mouseX = KMInput.GetMouseX();
int mouseY = KMInput.GetMouseY();
bool mouseMoved = !m_bHasMousePosition || mouseX != m_lastMouseX || mouseY != m_lastMouseY;
m_bHasMousePosition = true;
m_lastMouseX = mouseX;
m_lastMouseY = mouseY;
scrollDelta = KMInput.ConsumeScrollDelta();
// Convert mouse position to movie coordinates using the movie/client ratio
float mx = (float)mouseX * ((float)m_movieWidth / (float)clientWidth);
float my = (float)mouseY * ((float)m_movieHeight / (float)clientHeight);
float mx = (float)mouseX * ((float)m_movieWidth / (float)clientWidth) - (float)m_controlMainPanel.getXPos();
float my = (float)mouseY * ((float)m_movieHeight / (float)clientHeight) - (float)m_controlMainPanel.getYPos();
m_pointerPos.x = mx;
m_pointerPos.y = my;
rawMouseMovieX = mx;
rawMouseMovieY = my;
// Once the mouse has taken over the container cursor, keep following the OS cursor
// until explicit controller input takes ownership back.
drivePointerFromMouse = m_bPointerDrivenByMouse || mouseMoved || KMInput.IsMouseDown(0) || KMInput.IsMouseDown(1) || KMInput.IsMouseDown(2) || scrollDelta != 0;
if (drivePointerFromMouse)
{
m_bPointerDrivenByMouse = true;
m_eCurrTapState = eTapStateNoInput;
m_pointerPos.x = mx;
m_pointerPos.y = my;
}
}
}
#endif
@ -251,7 +276,6 @@ void UIScene_AbstractContainerMenu::tick()
}
// Mouse scroll wheel for page scrolling
int scrollDelta = KMInput.ConsumeScrollDelta();
if (scrollDelta > 0)
{
handleKeyDown(m_iPad, ACTION_MENU_OTHER_STICK_UP, false);
@ -276,14 +300,19 @@ void UIScene_AbstractContainerMenu::tick()
#ifdef _WINDOWS64
S32 x, y;
if (mouseActive)
if (mouseActive && m_bPointerDrivenByMouse)
{
// Send raw mouse position directly as Iggy event to avoid coordinate round-trip errors
// Scale mouse client coords to the Iggy display space (which was set to getRenderDimensions())
RECT clientRect;
GetClientRect(KMInput.GetHWnd(), &clientRect);
x = (S32)((float)KMInput.GetMouseX() * ((float)width / (float)clientRect.right));
y = (S32)((float)KMInput.GetMouseY() * ((float)height / (float)clientRect.bottom));
float mouseMovieX = (float)KMInput.GetMouseX() * ((float)m_movieWidth / (float)clientRect.right);
float mouseMovieY = (float)KMInput.GetMouseY() * ((float)m_movieHeight / (float)clientRect.bottom);
float mouseLocalX = mouseMovieX - (float)m_controlMainPanel.getXPos();
float mouseLocalY = mouseMovieY - (float)m_controlMainPanel.getYPos();
x = (S32)(mouseLocalX * ((float)width / m_movieWidth));
y = (S32)(mouseLocalY * ((float)height / m_movieHeight));
}
else
{
@ -369,6 +398,7 @@ void UIScene_AbstractContainerMenu::handleInput(int iPad, int key, bool repeat,
if(pressed)
{
m_bPointerDrivenByMouse = false;
handled = handleKeyDown(m_iPad, key, repeat);
}
}

View file

@ -12,6 +12,9 @@ private:
bool m_bIgnoreInput;
#ifdef _WINDOWS64
bool m_bMouseDragSlider;
bool m_bHasMousePosition;
int m_lastMouseX;
int m_lastMouseY;
#endif
protected:

View file

@ -1085,6 +1085,7 @@ void UIScene_CreateWorldMenu::CreateGame(UIScene_CreateWorldMenu* pClass, DWORD
__int64 seedValue = 0;
NetworkGameInitData *param = new NetworkGameInitData();
param->levelName = wWorldName;
if (wSeed.length() != 0)
{

View file

@ -238,7 +238,7 @@ UIScene_LoadMenu::UIScene_LoadMenu(int iPad, void *initData, UILayer *parentLaye
#endif
m_bShowTimer = true;
}
#if defined(_DURANGO)
#if defined(_DURANGO)
m_labelGameName.init(params->saveDetails->UTF16SaveName);
#else
wchar_t wSaveName[128];
@ -246,6 +246,16 @@ UIScene_LoadMenu::UIScene_LoadMenu(int iPad, void *initData, UILayer *parentLaye
mbstowcs(wSaveName, params->saveDetails->UTF8SaveName, strlen(params->saveDetails->UTF8SaveName)+1); // plus null
m_labelGameName.init(wSaveName);
#endif
#endif
#ifdef _WINDOWS64
if (params->saveDetails != NULL && params->saveDetails->UTF8SaveName[0] != '\0')
{
wchar_t wSaveName[128];
ZeroMemory(wSaveName, sizeof(wSaveName));
mbstowcs(wSaveName, params->saveDetails->UTF8SaveName, 127);
m_levelName = wstring(wSaveName);
m_labelGameName.init(m_levelName);
}
#endif
}
@ -1574,6 +1584,7 @@ void UIScene_LoadMenu::StartGameFromSave(UIScene_LoadMenu* pClass, DWORD dwLocal
param->saveData = NULL;
param->levelGen = pClass->m_levelGen;
param->texturePackId = pClass->m_MoreOptionsParams.dwTexturePack;
param->levelName = pClass->m_levelName;
Minecraft *pMinecraft = Minecraft::GetInstance();
pMinecraft->skins->selectTexturePackById(pClass->m_MoreOptionsParams.dwTexturePack);

View file

@ -59,6 +59,7 @@ private:
bool m_bIsCorrupt;
bool m_bThumbnailGetFailed;
__int64 m_seed;
wstring m_levelName;
#ifdef __PS3__
std::vector<SonyCommerce::ProductInfo>*m_pvProductInfo;

View file

@ -25,6 +25,98 @@
#include "message_dialog.h"
#endif
#ifdef _WINDOWS64
#include "..\..\..\Minecraft.World\NbtIo.h"
#include "..\..\..\Minecraft.World\compression.h"
static wstring ReadLevelNameFromSaveFile(const wstring& filePath)
{
HANDLE hFile = CreateFileW(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (hFile == INVALID_HANDLE_VALUE) return L"";
DWORD fileSize = GetFileSize(hFile, NULL);
if (fileSize < 12 || fileSize == INVALID_FILE_SIZE) { CloseHandle(hFile); return L""; }
unsigned char *rawData = new unsigned char[fileSize];
DWORD bytesRead = 0;
if (!ReadFile(hFile, rawData, fileSize, &bytesRead, NULL) || bytesRead != fileSize)
{
CloseHandle(hFile);
delete[] rawData;
return L"";
}
CloseHandle(hFile);
unsigned char *saveData = NULL;
unsigned int saveSize = 0;
bool freeSaveData = false;
if (*(unsigned int*)rawData == 0)
{
// Compressed format: bytes 0-3=0, bytes 4-7=decompressed size, bytes 8+=compressed data
unsigned int decompSize = *(unsigned int*)(rawData + 4);
if (decompSize == 0 || decompSize > 128 * 1024 * 1024)
{
delete[] rawData;
return L"";
}
saveData = new unsigned char[decompSize];
Compression::getCompression()->Decompress(saveData, &decompSize, rawData + 8, fileSize - 8);
saveSize = decompSize;
freeSaveData = true;
}
else
{
saveData = rawData;
saveSize = fileSize;
}
wstring result = L"";
if (saveSize >= 12)
{
unsigned int headerOffset = *(unsigned int*)saveData;
unsigned int numEntries = *(unsigned int*)(saveData + 4);
const unsigned int entrySize = sizeof(FileEntrySaveData);
if (headerOffset < saveSize && numEntries > 0 && numEntries < 10000 &&
headerOffset + numEntries * entrySize <= saveSize)
{
FileEntrySaveData *table = (FileEntrySaveData *)(saveData + headerOffset);
for (unsigned int i = 0; i < numEntries; i++)
{
if (wcscmp(table[i].filename, L"level.dat") == 0)
{
unsigned int off = table[i].startOffset;
unsigned int len = table[i].length;
if (off >= 12 && off + len <= saveSize && len > 0 && len < 4 * 1024 * 1024)
{
byteArray ba;
ba.data = (byte*)(saveData + off);
ba.length = len;
CompoundTag *root = NbtIo::decompress(ba);
if (root != NULL)
{
CompoundTag *dataTag = root->getCompound(L"Data");
if (dataTag != NULL)
result = dataTag->getString(L"LevelName");
delete root;
}
}
break;
}
}
}
}
if (freeSaveData) delete[] saveData;
delete[] rawData;
// "world" is the engine default — it means no real name was ever set, so
// return empty to let the caller fall back to the save filename (timestamp).
if (result == L"world") result = L"";
return result;
}
#endif
#ifdef SONY_REMOTE_STORAGE_DOWNLOAD
unsigned long UIScene_LoadOrJoinMenu::m_ulFileSize=0L;
@ -159,7 +251,7 @@ UIScene_LoadOrJoinMenu::UIScene_LoadOrJoinMenu(int iPad, void *initData, UILayer
}
#endif
#if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) || defined(_DURANGO)
#if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) || defined(_DURANGO) || defined(_WINDOWS64)
// Always clear the saves when we enter this menu
StorageManager.ClearSavesInfo();
#endif
@ -284,13 +376,8 @@ UIScene_LoadOrJoinMenu::~UIScene_LoadOrJoinMenu()
g_NetworkManager.SetSessionsUpdatedCallback( NULL, NULL );
app.SetLiveLinkRequired( false );
if(m_currentSessions)
{
for(AUTO_VAR(it, m_currentSessions->begin()); it < m_currentSessions->end(); ++it)
{
delete (*it);
}
}
delete m_currentSessions;
m_currentSessions = NULL;
#if TO_BE_IMPLEMENTED
// Reset the background downloading, in case we changed it by attempting to download a texture pack
@ -619,6 +706,22 @@ void UIScene_LoadOrJoinMenu::tick()
m_saveDetails = new SaveListDetails[m_pSaveDetails->iSaveC];
m_iSaveDetailsCount = m_pSaveDetails->iSaveC;
#ifdef _WINDOWS64
// Build sorted index array (newest-first by filename timestamp YYYYMMDDHHMMSS)
int *sortedIdx = new int[m_pSaveDetails->iSaveC];
for (int si = 0; si < (int)m_pSaveDetails->iSaveC; ++si) sortedIdx[si] = si;
for (int si = 1; si < (int)m_pSaveDetails->iSaveC; ++si)
{
int key = sortedIdx[si];
int sj = si - 1;
while (sj >= 0 && strcmp(m_pSaveDetails->SaveInfoA[sortedIdx[sj]].UTF8SaveFilename, m_pSaveDetails->SaveInfoA[key].UTF8SaveFilename) < 0)
{
sortedIdx[sj + 1] = sortedIdx[sj];
--sj;
}
sortedIdx[sj + 1] = key;
}
#endif
for(unsigned int i = 0; i < m_pSaveDetails->iSaveC; ++i)
{
#if defined(_XBOX_ONE)
@ -632,14 +735,40 @@ void UIScene_LoadOrJoinMenu::tick()
m_saveDetails[i].saveId = i;
memcpy(m_saveDetails[i].UTF16SaveName, m_pSaveDetails->SaveInfoA[i].UTF16SaveTitle, 128);
memcpy(m_saveDetails[i].UTF16SaveFilename, m_pSaveDetails->SaveInfoA[i].UTF16SaveFilename, MAX_SAVEFILENAME_LENGTH);
#else
#ifdef _WINDOWS64
{
int origIdx = sortedIdx[i];
wchar_t wFilename[MAX_SAVEFILENAME_LENGTH];
ZeroMemory(wFilename, sizeof(wFilename));
mbstowcs(wFilename, m_pSaveDetails->SaveInfoA[origIdx].UTF8SaveFilename, MAX_SAVEFILENAME_LENGTH - 1);
wstring filePath = wstring(L"Windows64\\GameHDD\\") + wstring(wFilename) + wstring(L"\\saveData.ms");
wstring levelName = ReadLevelNameFromSaveFile(filePath);
if (!levelName.empty())
{
m_buttonListSaves.addItem(levelName, wstring(L""));
wcstombs(m_saveDetails[i].UTF8SaveName, levelName.c_str(), 127);
m_saveDetails[i].UTF8SaveName[127] = '\0';
}
else
{
m_buttonListSaves.addItem(m_pSaveDetails->SaveInfoA[origIdx].UTF8SaveTitle, L"");
memcpy(m_saveDetails[i].UTF8SaveName, m_pSaveDetails->SaveInfoA[origIdx].UTF8SaveTitle, 128);
}
m_saveDetails[i].saveId = origIdx;
memcpy(m_saveDetails[i].UTF8SaveFilename, m_pSaveDetails->SaveInfoA[origIdx].UTF8SaveFilename, MAX_SAVEFILENAME_LENGTH);
}
#else
m_buttonListSaves.addItem(m_pSaveDetails->SaveInfoA[i].UTF8SaveTitle, L"");
m_saveDetails[i].saveId = i;
memcpy(m_saveDetails[i].UTF8SaveName, m_pSaveDetails->SaveInfoA[i].UTF8SaveTitle, 128);
m_saveDetails[i].saveId = i;
memcpy(m_saveDetails[i].UTF8SaveFilename, m_pSaveDetails->SaveInfoA[i].UTF8SaveFilename, MAX_SAVEFILENAME_LENGTH);
#endif
#endif
}
#ifdef _WINDOWS64
delete[] sortedIdx;
#endif
m_controlSavesTimer.setVisible( false );
// set focus on the first button
@ -655,7 +784,11 @@ void UIScene_LoadOrJoinMenu::tick()
app.DebugPrintf("Requesting the first thumbnail\n");
// set the save to load
PSAVE_DETAILS pSaveDetails=StorageManager.ReturnSavesInfo();
#ifdef _WINDOWS64
C4JStorage::ESaveGameState eLoadStatus=StorageManager.LoadSaveDataThumbnail(&pSaveDetails->SaveInfoA[m_saveDetails[m_iRequestingThumbnailId].saveId],&LoadSaveDataThumbnailReturned,this);
#else
C4JStorage::ESaveGameState eLoadStatus=StorageManager.LoadSaveDataThumbnail(&pSaveDetails->SaveInfoA[(int)m_iRequestingThumbnailId],&LoadSaveDataThumbnailReturned,this);
#endif
if(eLoadStatus!=C4JStorage::ESaveGame_GetSaveThumbnail)
{
@ -718,7 +851,11 @@ void UIScene_LoadOrJoinMenu::tick()
app.DebugPrintf("Requesting another thumbnail\n");
// set the save to load
PSAVE_DETAILS pSaveDetails=StorageManager.ReturnSavesInfo();
#ifdef _WINDOWS64
C4JStorage::ESaveGameState eLoadStatus=StorageManager.LoadSaveDataThumbnail(&pSaveDetails->SaveInfoA[m_saveDetails[m_iRequestingThumbnailId].saveId],&LoadSaveDataThumbnailReturned,this);
#else
C4JStorage::ESaveGameState eLoadStatus=StorageManager.LoadSaveDataThumbnail(&pSaveDetails->SaveInfoA[(int)m_iRequestingThumbnailId],&LoadSaveDataThumbnailReturned,this);
#endif
if(eLoadStatus!=C4JStorage::ESaveGame_GetSaveThumbnail)
{
// something went wrong
@ -1328,7 +1465,7 @@ void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId)
LoadMenuInitData *params = new LoadMenuInitData();
params->iPad = m_iPad;
// need to get the iIndex from the list item, since the position in the list doesn't correspond to the GetSaveGameInfo list because of sorting
params->iSaveGameInfoIndex=((int)childId)-m_iDefaultButtonsC;
params->iSaveGameInfoIndex=m_saveDetails[((int)childId)-m_iDefaultButtonsC].saveId;
//params->pbSaveRenamed=&m_bSaveRenamed;
params->levelGen = NULL;
params->saveDetails = &m_saveDetails[ ((int)childId)-m_iDefaultButtonsC ];

View file

@ -1,11 +1,14 @@
#include "stdafx.h"
#include "UI.h"
#include "UIScene_SettingsGraphicsMenu.h"
#include "..\..\Minecraft.h"
#include "..\..\GameRenderer.h"
UIScene_SettingsGraphicsMenu::UIScene_SettingsGraphicsMenu(int iPad, void *initData, UILayer *parentLayer) : UIScene(iPad, parentLayer)
{
// Setup all the Iggy references we need for this scene
initialiseMovie();
Minecraft* pMinecraft = Minecraft::GetInstance();
m_bNotInGame=(Minecraft::GetInstance()->level==NULL);
@ -18,6 +21,9 @@ UIScene_SettingsGraphicsMenu::UIScene_SettingsGraphicsMenu(int iPad, void *initD
swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_GAMMA ),app.GetGameSettings(m_iPad,eGameSetting_Gamma));
m_sliderGamma.init(TempString,eControl_Gamma,0,100,app.GetGameSettings(m_iPad,eGameSetting_Gamma));
swprintf((WCHAR*)TempString, 256, L"FOV: %d%%", (int)pMinecraft->gameRenderer->GetFovVal());
m_sliderFOV.init(TempString, eControl_FOV, 70, 110, (int)pMinecraft->gameRenderer->GetFovVal());
swprintf( (WCHAR *)TempString, 256, L"%ls: %d%%", app.GetString( IDS_SLIDER_INTERFACEOPACITY ),app.GetGameSettings(m_iPad,eGameSetting_InterfaceOpacity));
m_sliderInterfaceOpacity.init(TempString,eControl_InterfaceOpacity,0,100,app.GetGameSettings(m_iPad,eGameSetting_InterfaceOpacity));
@ -141,6 +147,17 @@ void UIScene_SettingsGraphicsMenu::handleSliderMove(F64 sliderId, F64 currentVal
m_sliderGamma.setLabel(TempString);
break;
case eControl_FOV:
{
Minecraft* pMinecraft = Minecraft::GetInstance();
pMinecraft->gameRenderer->SetFovVal((float)currentValue);
WCHAR TempString[256];
swprintf((WCHAR*)TempString, 256, L"FOV: %d%%", (int)currentValue);
m_sliderFOV.setLabel(TempString);
}
break;
case eControl_InterfaceOpacity:
m_sliderInterfaceOpacity.handleSliderMove(value);

View file

@ -11,16 +11,18 @@ private:
eControl_BedrockFog,
eControl_CustomSkinAnim,
eControl_Gamma,
eControl_FOV,
eControl_InterfaceOpacity
};
UIControl_CheckBox m_checkboxClouds, m_checkboxBedrockFog, m_checkboxCustomSkinAnim; // Checkboxes
UIControl_Slider m_sliderGamma, m_sliderInterfaceOpacity; // Sliders
UIControl_Slider m_sliderGamma, m_sliderFOV, m_sliderInterfaceOpacity; // Sliders
UI_BEGIN_MAP_ELEMENTS_AND_NAMES(UIScene)
UI_MAP_ELEMENT( m_checkboxClouds, "Clouds")
UI_MAP_ELEMENT( m_checkboxBedrockFog, "BedrockFog")
UI_MAP_ELEMENT( m_checkboxCustomSkinAnim, "CustomSkinAnim")
UI_MAP_ELEMENT( m_sliderGamma, "Gamma")
UI_MAP_ELEMENT(m_sliderFOV, "FOV")
UI_MAP_ELEMENT( m_sliderInterfaceOpacity, "InterfaceOpacity")
UI_END_MAP_ELEMENTS_AND_NAMES()

View file

@ -77,12 +77,7 @@ void EnderDragonRenderer::renderModel(shared_ptr<LivingEntity> _mob, float wp, f
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(1, 0, 0, 0.5f);
#ifdef __PSVITA__
// AP - not sure that the usecompiled flag is supposed to be false. This makes it really slow on vita. Making it true still seems to look the same
model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true);
#else
model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, false);
#endif
glEnable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glDepthFunc(GL_LEQUAL);

View file

@ -20,6 +20,7 @@
#include "StatsCounter.h"
#include "Windows64/Social/SocialManager.h"
#include "Windows64/Sentient/DynamicConfigurations.h"
#include "Windows64/Network/WinsockNetLayer.h"
#elif defined __PSVITA__
#include "PSVita/Sentient/SentientManager.h"
#include "StatsCounter.h"
@ -46,63 +47,63 @@ CXuiStringTable StringTable;
#ifndef _XBOX_ONE
ATG::XMLParser::XMLParser() {}
ATG::XMLParser::~XMLParser() {}
HRESULT ATG::XMLParser::ParseXMLBuffer( CONST CHAR* strBuffer, UINT uBufferSize ) { return S_OK; }
VOID ATG::XMLParser::RegisterSAXCallbackInterface( ISAXCallback *pISAXCallback ) {}
HRESULT ATG::XMLParser::ParseXMLBuffer(CONST CHAR* strBuffer, UINT uBufferSize) { return S_OK; }
VOID ATG::XMLParser::RegisterSAXCallbackInterface(ISAXCallback* pISAXCallback) {}
#endif
bool CSocialManager::IsTitleAllowedToPostAnything() { return false; }
bool CSocialManager::AreAllUsersAllowedToPostImages() { return false; }
bool CSocialManager::IsTitleAllowedToPostImages() { return false; }
bool CSocialManager::PostLinkToSocialNetwork( ESocialNetwork eSocialNetwork, DWORD dwUserIndex, bool bUsingKinect ) { return false; }
bool CSocialManager::PostImageToSocialNetwork( ESocialNetwork eSocialNetwork, DWORD dwUserIndex, bool bUsingKinect ) { return false; }
CSocialManager *CSocialManager::Instance() { return NULL; }
bool CSocialManager::PostLinkToSocialNetwork(ESocialNetwork eSocialNetwork, DWORD dwUserIndex, bool bUsingKinect) { return false; }
bool CSocialManager::PostImageToSocialNetwork(ESocialNetwork eSocialNetwork, DWORD dwUserIndex, bool bUsingKinect) { return false; }
CSocialManager* CSocialManager::Instance() { return NULL; }
void CSocialManager::SetSocialPostText(LPCWSTR Title, LPCWSTR Caption, LPCWSTR Desc) {};
DWORD XShowPartyUI(DWORD dwUserIndex) { return 0; }
DWORD XShowFriendsUI(DWORD dwUserIndex) { return 0; }
HRESULT XPartyGetUserList(XPARTY_USER_LIST *pUserList) { return S_OK; }
DWORD XContentGetThumbnail(DWORD dwUserIndex, const XCONTENT_DATA *pContentData, PBYTE pbThumbnail, PDWORD pcbThumbnail, PXOVERLAPPED *pOverlapped) { return 0; }
HRESULT XPartyGetUserList(XPARTY_USER_LIST* pUserList) { return S_OK; }
DWORD XContentGetThumbnail(DWORD dwUserIndex, const XCONTENT_DATA* pContentData, PBYTE pbThumbnail, PDWORD pcbThumbnail, PXOVERLAPPED* pOverlapped) { return 0; }
void XShowAchievementsUI(int i) {}
DWORD XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE Mode) { return 0; }
#ifndef _DURANGO
void PIXAddNamedCounter(int a, char *b, ...) {}
void PIXAddNamedCounter(int a, char* b, ...) {}
//#define PS3_USE_PIX_EVENTS
//#define PS4_USE_PIX_EVENTS
void PIXBeginNamedEvent(int a, char *b, ...)
void PIXBeginNamedEvent(int a, char* b, ...)
{
#ifdef PS4_USE_PIX_EVENTS
char buf[512];
va_list args;
va_start(args,b);
vsprintf(buf,b,args);
va_list args;
va_start(args, b);
vsprintf(buf, b, args);
sceRazorCpuPushMarker(buf, 0xffffffff, SCE_RAZOR_MARKER_ENABLE_HUD);
#endif
#ifdef PS3_USE_PIX_EVENTS
char buf[256];
wchar_t wbuf[256];
va_list args;
va_start(args,b);
vsprintf(buf,b,args);
va_list args;
va_start(args, b);
vsprintf(buf, b, args);
snPushMarker(buf);
// mbstowcs(wbuf,buf,256);
// RenderManager.BeginEvent(wbuf);
va_end(args);
// mbstowcs(wbuf,buf,256);
// RenderManager.BeginEvent(wbuf);
va_end(args);
#endif
}
#if 0//__PSVITA__
if( PixDepth < 64 )
{
char buf[512];
va_list args;
va_start(args,b);
vsprintf(buf,b,args);
sceRazorCpuPushMarkerWithHud(buf, 0xffffffff, SCE_RAZOR_MARKER_ENABLE_HUD);
}
PixDepth += 1;
if (PixDepth < 64)
{
char buf[512];
va_list args;
va_start(args, b);
vsprintf(buf, b, args);
sceRazorCpuPushMarkerWithHud(buf, 0xffffffff, SCE_RAZOR_MARKER_ENABLE_HUD);
}
PixDepth += 1;
#endif
@ -113,17 +114,17 @@ void PIXEndNamedEvent()
#endif
#ifdef PS3_USE_PIX_EVENTS
snPopMarker();
// RenderManager.EndEvent();
// RenderManager.EndEvent();
#endif
#if 0//__PSVITA__
if( PixDepth <= 64 )
if (PixDepth <= 64)
{
sceRazorCpuPopMarker();
}
PixDepth -= 1;
#endif
}
void PIXSetMarkerDeprecated(int a, char *b, ...) {}
void PIXSetMarkerDeprecated(int a, char* b, ...) {}
#else
// 4J Stu - Removed this implementation in favour of a macro that will convert our string format
// conversion at compile time rather than at runtime
@ -175,38 +176,33 @@ bool IsEqualXUID(PlayerUID a, PlayerUID b)
#endif
}
void XMemCpy(void *a, const void *b, size_t s) { memcpy(a, b, s); }
void XMemSet(void *a, int t, size_t s) { memset(a, t, s); }
void XMemSet128(void *a, int t, size_t s) { memset(a, t, s); }
void *XPhysicalAlloc(SIZE_T a, ULONG_PTR b, ULONG_PTR c, DWORD d) { return malloc(a); }
void XPhysicalFree(void *a) { free(a); }
void XMemCpy(void* a, const void* b, size_t s) { memcpy(a, b, s); }
void XMemSet(void* a, int t, size_t s) { memset(a, t, s); }
void XMemSet128(void* a, int t, size_t s) { memset(a, t, s); }
void* XPhysicalAlloc(SIZE_T a, ULONG_PTR b, ULONG_PTR c, DWORD d) { return malloc(a); }
void XPhysicalFree(void* a) { free(a); }
D3DXVECTOR3::D3DXVECTOR3() {}
D3DXVECTOR3::D3DXVECTOR3(float x,float y,float z) : x(x), y(y), z(z) {}
D3DXVECTOR3& D3DXVECTOR3::operator += ( CONST D3DXVECTOR3& add ) { x += add.x; y += add.y; z += add.z; return *this; }
D3DXVECTOR3::D3DXVECTOR3(float x, float y, float z) : x(x), y(y), z(z) {}
D3DXVECTOR3& D3DXVECTOR3::operator += (CONST D3DXVECTOR3 & add) { x += add.x; y += add.y; z += add.z; return *this; }
BYTE IQNetPlayer::GetSmallId() { return 0; }
void IQNetPlayer::SendData(IQNetPlayer *player, const void *pvData, DWORD dwDataSize, DWORD dwFlags)
BYTE IQNetPlayer::GetSmallId() { return m_smallId; }
void IQNetPlayer::SendData(IQNetPlayer * player, const void* pvData, DWORD dwDataSize, DWORD dwFlags)
{
app.DebugPrintf("Sending from 0x%x to 0x%x %d bytes\n",this,player,dwDataSize);
if (WinsockNetLayer::IsActive())
{
WinsockNetLayer::SendToSmallId(player->m_smallId, pvData, dwDataSize);
}
}
bool IQNetPlayer::IsSameSystem(IQNetPlayer *player) { return true; }
DWORD IQNetPlayer::GetSendQueueSize( IQNetPlayer *player, DWORD dwFlags ) { return 0; }
bool IQNetPlayer::IsSameSystem(IQNetPlayer * player) { return (this == player) || (!m_isRemote && !player->m_isRemote); }
DWORD IQNetPlayer::GetSendQueueSize(IQNetPlayer * player, DWORD dwFlags) { return 0; }
DWORD IQNetPlayer::GetCurrentRtt() { return 0; }
bool IQNetPlayer::IsHost() { return this == &IQNet::m_player[0]; }
bool IQNetPlayer::IsHost() { return m_isHostPlayer; }
bool IQNetPlayer::IsGuest() { return false; }
bool IQNetPlayer::IsLocal() { return true; }
PlayerUID IQNetPlayer::GetXuid() { return INVALID_XUID; }
LPCWSTR IQNetPlayer::GetGamertag()
{
static wchar_t tags[4][16];
int idx = GetUserIndex();
if(idx < 0 || idx >= 4) idx = 0;
mbstowcs(tags[idx], ProfileManager.GetGamertag(idx), 15);
tags[idx][15] = L'\0';
return tags[idx];
}
int IQNetPlayer::GetSessionIndex() { return 0; }
bool IQNetPlayer::IsLocal() { return !m_isRemote; }
PlayerUID IQNetPlayer::GetXuid() { return (PlayerUID)(0xe000d45248242f2e + m_smallId); } // todo: restore to INVALID_XUID once saves support this
LPCWSTR IQNetPlayer::GetGamertag() { return m_gamertag; }
int IQNetPlayer::GetSessionIndex() { return m_smallId; }
bool IQNetPlayer::IsTalking() { return false; }
bool IQNetPlayer::IsMutedByLocalUser(DWORD dwUserIndex) { return false; }
bool IQNetPlayer::HasVoice() { return false; }
@ -219,22 +215,121 @@ ULONG_PTR IQNetPlayer::GetCustomDataValue() {
return m_customData;
}
IQNetPlayer IQNet::m_player[4];
IQNetPlayer IQNet::m_player[MINECRAFT_NET_MAX_PLAYERS];
DWORD IQNet::s_playerCount = 1;
bool IQNet::s_isHosting = true;
bool _bQNetStubGameRunning = false;
QNET_STATE _iQNetStubState = QNET_STATE_IDLE;
HRESULT IQNet::AddLocalPlayerByUserIndex(DWORD dwUserIndex){ return S_OK; }
IQNetPlayer *IQNet::GetHostPlayer() { return &m_player[0]; }
IQNetPlayer *IQNet::GetLocalPlayerByUserIndex(DWORD dwUserIndex) { return &m_player[dwUserIndex]; }
IQNetPlayer *IQNet::GetPlayerByIndex(DWORD dwPlayerIndex) { return &m_player[0]; }
IQNetPlayer *IQNet::GetPlayerBySmallId(BYTE SmallId){ return &m_player[0]; }
IQNetPlayer *IQNet::GetPlayerByXuid(PlayerUID xuid){ return &m_player[0]; }
DWORD IQNet::GetPlayerCount() { return 1; }
QNET_STATE IQNet::GetState() { return _bQNetStubGameRunning ? QNET_STATE_GAME_PLAY : QNET_STATE_IDLE; }
bool IQNet::IsHost() { return true; }
HRESULT IQNet::JoinGameFromInviteInfo(DWORD dwUserIndex, DWORD dwUserMask, const INVITE_INFO *pInviteInfo) { return S_OK; }
void IQNet::HostGame() { _bQNetStubGameRunning = true; }
void IQNet::EndGame() { _bQNetStubGameRunning = false; }
void Win64_SetupRemoteQNetPlayer(IQNetPlayer * player, BYTE smallId, bool isHost, bool isLocal)
{
player->m_smallId = smallId;
player->m_isRemote = !isLocal;
player->m_isHostPlayer = isHost;
swprintf_s(player->m_gamertag, 32, L"Player%d", smallId);
if (smallId >= IQNet::s_playerCount)
IQNet::s_playerCount = smallId + 1;
}
static bool Win64_IsActivePlayer(IQNetPlayer* p, DWORD index);
HRESULT IQNet::AddLocalPlayerByUserIndex(DWORD dwUserIndex) { return S_OK; }
IQNetPlayer* IQNet::GetHostPlayer() { return &m_player[0]; }
IQNetPlayer* IQNet::GetLocalPlayerByUserIndex(DWORD dwUserIndex)
{
if (s_isHosting)
{
if (dwUserIndex < MINECRAFT_NET_MAX_PLAYERS &&
!m_player[dwUserIndex].m_isRemote &&
Win64_IsActivePlayer(&m_player[dwUserIndex], dwUserIndex))
return &m_player[dwUserIndex];
return NULL;
}
if (dwUserIndex != 0)
return NULL;
for (DWORD i = 0; i < s_playerCount; i++)
{
if (!m_player[i].m_isRemote && Win64_IsActivePlayer(&m_player[i], i))
return &m_player[i];
}
return NULL;
}
static bool Win64_IsActivePlayer(IQNetPlayer * p, DWORD index)
{
if (index == 0) return true;
return (p->GetCustomDataValue() != 0);
}
IQNetPlayer* IQNet::GetPlayerByIndex(DWORD dwPlayerIndex)
{
DWORD found = 0;
for (DWORD i = 0; i < s_playerCount; i++)
{
if (Win64_IsActivePlayer(&m_player[i], i))
{
if (found == dwPlayerIndex) return &m_player[i];
found++;
}
}
return &m_player[0];
}
IQNetPlayer* IQNet::GetPlayerBySmallId(BYTE SmallId)
{
for (DWORD i = 0; i < s_playerCount; i++)
{
if (m_player[i].m_smallId == SmallId && Win64_IsActivePlayer(&m_player[i], i)) return &m_player[i];
}
return NULL;
}
IQNetPlayer* IQNet::GetPlayerByXuid(PlayerUID xuid)
{
for (DWORD i = 0; i < s_playerCount; i++)
{
if (Win64_IsActivePlayer(&m_player[i], i) && m_player[i].GetXuid() == xuid) return &m_player[i];
}
return &m_player[0];
}
DWORD IQNet::GetPlayerCount()
{
DWORD count = 0;
for (DWORD i = 0; i < s_playerCount; i++)
{
if (Win64_IsActivePlayer(&m_player[i], i)) count++;
}
return count;
}
QNET_STATE IQNet::GetState() { return _iQNetStubState; }
bool IQNet::IsHost() { return s_isHosting; }
HRESULT IQNet::JoinGameFromInviteInfo(DWORD dwUserIndex, DWORD dwUserMask, const INVITE_INFO * pInviteInfo) { return S_OK; }
void IQNet::HostGame() { _iQNetStubState = QNET_STATE_SESSION_STARTING; s_isHosting = true; }
void IQNet::ClientJoinGame()
{
_iQNetStubState = QNET_STATE_SESSION_STARTING;
s_isHosting = false;
for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++)
{
m_player[i].m_smallId = (BYTE)i;
m_player[i].m_isRemote = true;
m_player[i].m_isHostPlayer = false;
m_player[i].m_gamertag[0] = 0;
m_player[i].SetCustomDataValue(0);
}
}
void IQNet::EndGame()
{
_iQNetStubState = QNET_STATE_IDLE;
s_isHosting = false;
s_playerCount = 1;
for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++)
{
m_player[i].m_smallId = (BYTE)i;
m_player[i].m_isRemote = false;
m_player[i].m_isHostPlayer = false;
m_player[i].m_gamertag[0] = 0;
m_player[i].SetCustomDataValue(0);
}
}
DWORD MinecraftDynamicConfigurations::GetTrialTime() { return DYNAMIC_CONFIG_DEFAULT_TRIAL_TIME; }
@ -244,9 +339,9 @@ void XSetThreadProcessor(HANDLE a, int b) {}
// #endif // __PS3__
DWORD XUserGetSigninInfo(
DWORD dwUserIndex,
DWORD dwFlags,
PXUSER_SIGNIN_INFO pSigninInfo
DWORD dwUserIndex,
DWORD dwFlags,
PXUSER_SIGNIN_INFO pSigninInfo
)
{
return 0;
@ -257,16 +352,16 @@ LPCWSTR CXuiStringTable::Lookup(UINT nIndex) { return L"String"; }
void CXuiStringTable::Clear() {}
HRESULT CXuiStringTable::Load(LPCWSTR szId) { return S_OK; }
DWORD XUserAreUsersFriends( DWORD dwUserIndex, PPlayerUID pXuids, DWORD dwXuidCount, PBOOL pfResult, void *pOverlapped) { return 0; }
DWORD XUserAreUsersFriends(DWORD dwUserIndex, PPlayerUID pXuids, DWORD dwXuidCount, PBOOL pfResult, void* pOverlapped) { return 0; }
#if defined __ORBIS__ || defined __PS3__ || defined _XBOX_ONE
#else
HRESULT XMemDecompress(
XMEMDECOMPRESSION_CONTEXT Context,
VOID *pDestination,
SIZE_T *pDestSize,
CONST VOID *pSource,
SIZE_T SrcSize
XMEMDECOMPRESSION_CONTEXT Context,
VOID * pDestination,
SIZE_T * pDestSize,
CONST VOID * pSource,
SIZE_T SrcSize
)
{
memcpy(pDestination, pSource, SrcSize);
@ -276,12 +371,12 @@ HRESULT XMemDecompress(
/*
DECOMPRESSOR_HANDLE Decompressor = (DECOMPRESSOR_HANDLE)Context;
if( Decompress(
Decompressor, // Decompressor handle
(void *)pSource, // Compressed data
SrcSize, // Compressed data size
pDestination, // Decompressed buffer
*pDestSize, // Decompressed buffer size
pDestSize) ) // Decompressed data size
Decompressor, // Decompressor handle
(void *)pSource, // Compressed data
SrcSize, // Compressed data size
pDestination, // Decompressed buffer
*pDestSize, // Decompressed buffer size
pDestSize) ) // Decompressed data size
{
return S_OK;
}
@ -293,11 +388,11 @@ HRESULT XMemDecompress(
}
HRESULT XMemCompress(
XMEMCOMPRESSION_CONTEXT Context,
VOID *pDestination,
SIZE_T *pDestSize,
CONST VOID *pSource,
SIZE_T SrcSize
XMEMCOMPRESSION_CONTEXT Context,
VOID * pDestination,
SIZE_T * pDestSize,
CONST VOID * pSource,
SIZE_T SrcSize
)
{
memcpy(pDestination, pSource, SrcSize);
@ -324,10 +419,10 @@ HRESULT XMemCompress(
}
HRESULT XMemCreateCompressionContext(
XMEMCODEC_TYPE CodecType,
CONST VOID *pCodecParams,
DWORD Flags,
XMEMCOMPRESSION_CONTEXT *pContext
XMEMCODEC_TYPE CodecType,
CONST VOID * pCodecParams,
DWORD Flags,
XMEMCOMPRESSION_CONTEXT * pContext
)
{
/*
@ -345,10 +440,10 @@ HRESULT XMemCreateCompressionContext(
}
HRESULT XMemCreateDecompressionContext(
XMEMCODEC_TYPE CodecType,
CONST VOID *pCodecParams,
DWORD Flags,
XMEMDECOMPRESSION_CONTEXT *pContext
XMEMCODEC_TYPE CodecType,
CONST VOID * pCodecParams,
DWORD Flags,
XMEMDECOMPRESSION_CONTEXT * pContext
)
{
/*
@ -367,14 +462,14 @@ HRESULT XMemCreateDecompressionContext(
void XMemDestroyCompressionContext(XMEMCOMPRESSION_CONTEXT Context)
{
// COMPRESSOR_HANDLE Compressor = (COMPRESSOR_HANDLE)Context;
// CloseCompressor(Compressor);
// COMPRESSOR_HANDLE Compressor = (COMPRESSOR_HANDLE)Context;
// CloseCompressor(Compressor);
}
void XMemDestroyDecompressionContext(XMEMDECOMPRESSION_CONTEXT Context)
{
// DECOMPRESSOR_HANDLE Decompressor = (DECOMPRESSOR_HANDLE)Context;
// CloseDecompressor(Decompressor);
// DECOMPRESSOR_HANDLE Decompressor = (DECOMPRESSOR_HANDLE)Context;
// CloseDecompressor(Decompressor);
}
#endif
@ -389,62 +484,62 @@ DWORD XEnableGuestSignin(BOOL fEnable) { return 0; }
/////////////////////////////////////////////// Profile library
#ifdef _WINDOWS64
static void *profileData[4];
static void* profileData[4];
static bool s_bProfileIsFullVersion;
void C_4JProfile::Initialise( DWORD dwTitleID,
DWORD dwOfferID,
unsigned short usProfileVersion,
UINT uiProfileValuesC,
UINT uiProfileSettingsC,
DWORD *pdwProfileSettingsA,
int iGameDefinedDataSizeX4,
unsigned int *puiGameDefinedDataChangedBitmask)
void C_4JProfile::Initialise(DWORD dwTitleID,
DWORD dwOfferID,
unsigned short usProfileVersion,
UINT uiProfileValuesC,
UINT uiProfileSettingsC,
DWORD * pdwProfileSettingsA,
int iGameDefinedDataSizeX4,
unsigned int* puiGameDefinedDataChangedBitmask)
{
for( int i = 0; i < 4; i++ )
for (int i = 0; i < 4; i++)
{
profileData[i] = new byte[iGameDefinedDataSizeX4/4];
ZeroMemory(profileData[i],sizeof(byte)*iGameDefinedDataSizeX4/4);
profileData[i] = new byte[iGameDefinedDataSizeX4 / 4];
ZeroMemory(profileData[i], sizeof(byte) * iGameDefinedDataSizeX4 / 4);
// Set some sane initial values!
GAME_SETTINGS *pGameSettings = (GAME_SETTINGS *)profileData[i];
pGameSettings->ucMenuSensitivity=100; //eGameSetting_Sensitivity_InMenu
pGameSettings->ucInterfaceOpacity=80; //eGameSetting_Sensitivity_InMenu
pGameSettings->usBitmaskValues|=0x0200; //eGameSetting_DisplaySplitscreenGamertags - on
pGameSettings->usBitmaskValues|=0x0400; //eGameSetting_Hints - on
pGameSettings->usBitmaskValues|=0x1000; //eGameSetting_Autosave - 2
pGameSettings->usBitmaskValues|=0x8000; //eGameSetting_Tooltips - on
pGameSettings->uiBitmaskValues=0L; // reset
pGameSettings->uiBitmaskValues|=GAMESETTING_CLOUDS; //eGameSetting_Clouds - on
pGameSettings->uiBitmaskValues|=GAMESETTING_ONLINE; //eGameSetting_GameSetting_Online - on
pGameSettings->uiBitmaskValues|=GAMESETTING_FRIENDSOFFRIENDS; //eGameSetting_GameSetting_FriendsOfFriends - on
pGameSettings->uiBitmaskValues|=GAMESETTING_DISPLAYUPDATEMSG; //eGameSetting_DisplayUpdateMessage (counter)
pGameSettings->uiBitmaskValues&=~GAMESETTING_BEDROCKFOG; //eGameSetting_BedrockFog - off
pGameSettings->uiBitmaskValues|=GAMESETTING_DISPLAYHUD; //eGameSetting_DisplayHUD - on
pGameSettings->uiBitmaskValues|=GAMESETTING_DISPLAYHAND; //eGameSetting_DisplayHand - on
pGameSettings->uiBitmaskValues|=GAMESETTING_CUSTOMSKINANIM; //eGameSetting_CustomSkinAnim - on
pGameSettings->uiBitmaskValues|=GAMESETTING_DEATHMESSAGES; //eGameSetting_DeathMessages - on
pGameSettings->uiBitmaskValues|=(GAMESETTING_UISIZE&0x00000800); // uisize 2
pGameSettings->uiBitmaskValues|=(GAMESETTING_UISIZE_SPLITSCREEN&0x00004000); // splitscreen ui size 3
pGameSettings->uiBitmaskValues|=GAMESETTING_ANIMATEDCHARACTER; //eGameSetting_AnimatedCharacter - on
GAME_SETTINGS* pGameSettings = (GAME_SETTINGS*)profileData[i];
pGameSettings->ucMenuSensitivity = 100; //eGameSetting_Sensitivity_InMenu
pGameSettings->ucInterfaceOpacity = 80; //eGameSetting_Sensitivity_InMenu
pGameSettings->usBitmaskValues |= 0x0200; //eGameSetting_DisplaySplitscreenGamertags - on
pGameSettings->usBitmaskValues |= 0x0400; //eGameSetting_Hints - on
pGameSettings->usBitmaskValues |= 0x1000; //eGameSetting_Autosave - 2
pGameSettings->usBitmaskValues |= 0x8000; //eGameSetting_Tooltips - on
pGameSettings->uiBitmaskValues = 0L; // reset
pGameSettings->uiBitmaskValues |= GAMESETTING_CLOUDS; //eGameSetting_Clouds - on
pGameSettings->uiBitmaskValues |= GAMESETTING_ONLINE; //eGameSetting_GameSetting_Online - on
pGameSettings->uiBitmaskValues |= GAMESETTING_FRIENDSOFFRIENDS; //eGameSetting_GameSetting_FriendsOfFriends - on
pGameSettings->uiBitmaskValues |= GAMESETTING_DISPLAYUPDATEMSG; //eGameSetting_DisplayUpdateMessage (counter)
pGameSettings->uiBitmaskValues &= ~GAMESETTING_BEDROCKFOG; //eGameSetting_BedrockFog - off
pGameSettings->uiBitmaskValues |= GAMESETTING_DISPLAYHUD; //eGameSetting_DisplayHUD - on
pGameSettings->uiBitmaskValues |= GAMESETTING_DISPLAYHAND; //eGameSetting_DisplayHand - on
pGameSettings->uiBitmaskValues |= GAMESETTING_CUSTOMSKINANIM; //eGameSetting_CustomSkinAnim - on
pGameSettings->uiBitmaskValues |= GAMESETTING_DEATHMESSAGES; //eGameSetting_DeathMessages - on
pGameSettings->uiBitmaskValues |= (GAMESETTING_UISIZE & 0x00000800); // uisize 2
pGameSettings->uiBitmaskValues |= (GAMESETTING_UISIZE_SPLITSCREEN & 0x00004000); // splitscreen ui size 3
pGameSettings->uiBitmaskValues |= GAMESETTING_ANIMATEDCHARACTER; //eGameSetting_AnimatedCharacter - on
// TU12
// favorite skins added, but only set in TU12 - set to FFs
for(int i=0;i<MAX_FAVORITE_SKINS;i++)
for (int i = 0; i < MAX_FAVORITE_SKINS; i++)
{
pGameSettings->uiFavoriteSkinA[i]=0xFFFFFFFF;
pGameSettings->uiFavoriteSkinA[i] = 0xFFFFFFFF;
}
pGameSettings->ucCurrentFavoriteSkinPos=0;
pGameSettings->ucCurrentFavoriteSkinPos = 0;
// Added a bitmask in TU13 to enable/disable display of the Mash-up pack worlds in the saves list
pGameSettings->uiMashUpPackWorldsDisplay = 0xFFFFFFFF;
// PS3DEC13
pGameSettings->uiBitmaskValues&=~GAMESETTING_PS3EULAREAD; //eGameSetting_PS3_EULA_Read - off
pGameSettings->uiBitmaskValues &= ~GAMESETTING_PS3EULAREAD; //eGameSetting_PS3_EULA_Read - off
// PS3 1.05 - added Greek
pGameSettings->ucLanguage = MINECRAFT_LANGUAGE_DEFAULT; // use the system language
// PS Vita - network mode added
pGameSettings->uiBitmaskValues&=~GAMESETTING_PSVITANETWORKMODEADHOC; //eGameSetting_PSVita_NetworkModeAdhoc - off
pGameSettings->uiBitmaskValues &= ~GAMESETTING_PSVITANETWORKMODEADHOC; //eGameSetting_PSVita_NetworkModeAdhoc - off
// Tutorials for most menus, and a few other things
@ -453,90 +548,90 @@ void C_4JProfile::Initialise( DWORD dwTitleID,
pGameSettings->ucTutorialCompletion[2] = 0xF;
// Has gone halfway through the tutorial
pGameSettings->ucTutorialCompletion[28] |= 1<<0;
pGameSettings->ucTutorialCompletion[28] |= 1 << 0;
}
}
void C_4JProfile::SetTrialTextStringTable(CXuiStringTable *pStringTable,int iAccept,int iReject) {}
void C_4JProfile::SetTrialAwardText(eAwardType AwardType,int iTitle,int iText) {}
void C_4JProfile::SetTrialTextStringTable(CXuiStringTable * pStringTable, int iAccept, int iReject) {}
void C_4JProfile::SetTrialAwardText(eAwardType AwardType, int iTitle, int iText) {}
int C_4JProfile::GetLockedProfile() { return 0; }
void C_4JProfile::SetLockedProfile(int iProf) {}
bool C_4JProfile::IsSignedIn(int iQuadrant) { return ( iQuadrant == 0); }
bool C_4JProfile::IsSignedIn(int iQuadrant) { return (iQuadrant == 0); }
bool C_4JProfile::IsSignedInLive(int iProf) { return true; }
bool C_4JProfile::IsGuest(int iQuadrant) { return false; }
UINT C_4JProfile::RequestSignInUI(bool bFromInvite,bool bLocalGame,bool bNoGuestsAllowed,bool bMultiplayerSignIn,bool bAddUser, int( *Func)(LPVOID,const bool, const int iPad),LPVOID lpParam,int iQuadrant) { return 0; }
UINT C_4JProfile::DisplayOfflineProfile(int( *Func)(LPVOID,const bool, const int iPad),LPVOID lpParam,int iQuadrant) { return 0; }
UINT C_4JProfile::RequestConvertOfflineToGuestUI(int( *Func)(LPVOID,const bool, const int iPad),LPVOID lpParam,int iQuadrant) { return 0; }
UINT C_4JProfile::RequestSignInUI(bool bFromInvite, bool bLocalGame, bool bNoGuestsAllowed, bool bMultiplayerSignIn, bool bAddUser, int(*Func)(LPVOID, const bool, const int iPad), LPVOID lpParam, int iQuadrant) { return 0; }
UINT C_4JProfile::DisplayOfflineProfile(int(*Func)(LPVOID, const bool, const int iPad), LPVOID lpParam, int iQuadrant) { return 0; }
UINT C_4JProfile::RequestConvertOfflineToGuestUI(int(*Func)(LPVOID, const bool, const int iPad), LPVOID lpParam, int iQuadrant) { return 0; }
void C_4JProfile::SetPrimaryPlayerChanged(bool bVal) {}
bool C_4JProfile::QuerySigninStatus(void) { return true; }
void C_4JProfile::GetXUID(int iPad, PlayerUID *pXuid,bool bOnlineXuid) {*pXuid = 0xe000d45248242f2e; }
BOOL C_4JProfile::AreXUIDSEqual(PlayerUID xuid1,PlayerUID xuid2) { return false; }
void C_4JProfile::GetXUID(int iPad, PlayerUID * pXuid, bool bOnlineXuid)
{
#ifdef _WINDOWS64
if (iPad != 0)
{
*pXuid = INVALID_XUID;
return;
}
if (IQNet::s_isHosting)
*pXuid = 0xe000d45248242f2e;
else
*pXuid = 0xe000d45248242f2e + WinsockNetLayer::GetLocalSmallId();
#else
* pXuid = 0xe000d45248242f2e + iPad;
#endif
}
BOOL C_4JProfile::AreXUIDSEqual(PlayerUID xuid1, PlayerUID xuid2) { return xuid1 == xuid2; }
BOOL C_4JProfile::XUIDIsGuest(PlayerUID xuid) { return false; }
bool C_4JProfile::AllowedToPlayMultiplayer(int iProf) { return true; }
#if defined(__ORBIS__)
bool C_4JProfile::GetChatAndContentRestrictions(int iPad, bool thisQuadrantOnly, bool *pbChatRestricted,bool *pbContentRestricted,int *piAge)
bool C_4JProfile::GetChatAndContentRestrictions(int iPad, bool thisQuadrantOnly, bool* pbChatRestricted, bool* pbContentRestricted, int* piAge)
{
if(pbChatRestricted) *pbChatRestricted = false;
if(pbContentRestricted) *pbContentRestricted = false;
if(piAge) *piAge = 100;
if (pbChatRestricted) *pbChatRestricted = false;
if (pbContentRestricted) *pbContentRestricted = false;
if (piAge) *piAge = 100;
return true;
}
#endif
void C_4JProfile::StartTrialGame() {}
void C_4JProfile::AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly, BOOL *allAllowed, BOOL *friendsAllowed) {}
BOOL C_4JProfile::CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly, PPlayerUID pXuids, DWORD dwXuidCount ) { return true; }
bool C_4JProfile::GetProfileAvatar(int iPad,int( *Func)(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes), LPVOID lpParam) { return false; }
void C_4JProfile::AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly, BOOL * allAllowed, BOOL * friendsAllowed) {}
BOOL C_4JProfile::CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly, PPlayerUID pXuids, DWORD dwXuidCount) { return true; }
bool C_4JProfile::GetProfileAvatar(int iPad, int(*Func)(LPVOID lpParam, PBYTE pbThumbnail, DWORD dwThumbnailBytes), LPVOID lpParam) { return false; }
void C_4JProfile::CancelProfileAvatarRequest() {}
int C_4JProfile::GetPrimaryPad() { return 0; }
void C_4JProfile::SetPrimaryPad(int iPad) {}
#ifdef _DURANGO
char fakeGamerTag[32] = "PlayerName";
void SetFakeGamertag(char *name){ strcpy_s(fakeGamerTag, name); }
char* C_4JProfile::GetGamertag(int iPad){ return fakeGamerTag; }
void SetFakeGamertag(char* name) { strcpy_s(fakeGamerTag, name); }
#else
char* C_4JProfile::GetGamertag(int iPad)
{
static char tags[4][16] = { "Player 1", "Player 2", "Player 3", "Player 4" };
if(iPad >= 0 && iPad < 4) return tags[iPad];
return tags[0];
}
wstring C_4JProfile::GetDisplayName(int iPad)
{
switch(iPad)
{
case 1: return L"Player 2";
case 2: return L"Player 3";
case 3: return L"Player 4";
default: return L"Player 1";
}
}
char* C_4JProfile::GetGamertag(int iPad) { extern char g_Win64Username[17]; return g_Win64Username; }
wstring C_4JProfile::GetDisplayName(int iPad) { extern wchar_t g_Win64UsernameW[17]; return g_Win64UsernameW; }
#endif
bool C_4JProfile::IsFullVersion() { return s_bProfileIsFullVersion; }
void C_4JProfile::SetSignInChangeCallback(void ( *Func)(LPVOID, bool, unsigned int),LPVOID lpParam) {}
void C_4JProfile::SetNotificationsCallback(void ( *Func)(LPVOID, DWORD, unsigned int),LPVOID lpParam) {}
void C_4JProfile::SetSignInChangeCallback(void (*Func)(LPVOID, bool, unsigned int), LPVOID lpParam) {}
void C_4JProfile::SetNotificationsCallback(void (*Func)(LPVOID, DWORD, unsigned int), LPVOID lpParam) {}
bool C_4JProfile::RegionIsNorthAmerica(void) { return false; }
bool C_4JProfile::LocaleIsUSorCanada(void) { return false; }
HRESULT C_4JProfile::GetLiveConnectionStatus() { return S_OK; }
bool C_4JProfile::IsSystemUIDisplayed() { return false; }
void C_4JProfile::SetProfileReadErrorCallback(void ( *Func)(LPVOID), LPVOID lpParam) {}
int( *defaultOptionsCallback)(LPVOID,C_4JProfile::PROFILESETTINGS *, const int iPad) = NULL;
void C_4JProfile::SetProfileReadErrorCallback(void (*Func)(LPVOID), LPVOID lpParam) {}
int(*defaultOptionsCallback)(LPVOID, C_4JProfile::PROFILESETTINGS*, const int iPad) = NULL;
LPVOID lpProfileParam = NULL;
int C_4JProfile::SetDefaultOptionsCallback(int( *Func)(LPVOID,PROFILESETTINGS *, const int iPad),LPVOID lpParam)
int C_4JProfile::SetDefaultOptionsCallback(int(*Func)(LPVOID, PROFILESETTINGS*, const int iPad), LPVOID lpParam)
{
defaultOptionsCallback = Func;
lpProfileParam = lpParam;
return 0;
}
int C_4JProfile::SetOldProfileVersionCallback(int( *Func)(LPVOID,unsigned char *, const unsigned short,const int),LPVOID lpParam) { return 0; }
int C_4JProfile::SetOldProfileVersionCallback(int(*Func)(LPVOID, unsigned char*, const unsigned short, const int), LPVOID lpParam) { return 0; }
// To store the dashboard preferences for controller flipped, etc.
C_4JProfile::PROFILESETTINGS ProfileSettingsA[XUSER_MAX_COUNT];
C_4JProfile::PROFILESETTINGS * C_4JProfile::GetDashboardProfileSettings(int iPad) { return &ProfileSettingsA[iPad]; }
C_4JProfile::PROFILESETTINGS* C_4JProfile::GetDashboardProfileSettings(int iPad) { return &ProfileSettingsA[iPad]; }
void C_4JProfile::WriteToProfile(int iQuadrant, bool bGameDefinedDataChanged, bool bOverride5MinuteLimitOnProfileWrites) {}
void C_4JProfile::ForceQueuedProfileWrites(int iPad) {}
void *C_4JProfile::GetGameDefinedProfileData(int iQuadrant)
void* C_4JProfile::GetGameDefinedProfileData(int iQuadrant)
{
// 4J Stu - Don't reset the options when we call this!!
//defaultOptionsCallback(lpProfileParam, (C_4JProfile::PROFILESETTINGS *)profileData[iQuadrant], iQuadrant);
@ -545,9 +640,10 @@ void *C_4JProfile::GetGameDefinedProfileData(int iQuadrant)
return profileData[iQuadrant];
}
void C_4JProfile::ResetProfileProcessState() {}
void C_4JProfile::Tick( void ) {}
void C_4JProfile::RegisterAward(int iAwardNumber,int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected,
CXuiStringTable*pStringTable, int iTitleStr, int iTextStr, int iAcceptStr, char *pszThemeName, unsigned int ulThemeSize) {}
void C_4JProfile::Tick(void) {}
void C_4JProfile::RegisterAward(int iAwardNumber, int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected,
CXuiStringTable * pStringTable, int iTitleStr, int iTextStr, int iAcceptStr, char* pszThemeName, unsigned int ulThemeSize) {
}
int C_4JProfile::GetAwardId(int iAwardNumber) { return 0; }
eAwardType C_4JProfile::GetAwardType(int iAwardNumber) { return eAwardType_Achievement; }
bool C_4JProfile::CanBeAwarded(int iQuadrant, int iAwardNumber) { return false; }
@ -555,11 +651,11 @@ void C_4JProfile::Award(int iQuadrant, int iAwardNumber, bool bForce) {}
bool C_4JProfile::IsAwardsFlagSet(int iQuadrant, int iAward) { return false; }
void C_4JProfile::RichPresenceInit(int iPresenceCount, int iContextCount) {}
void C_4JProfile::RegisterRichPresenceContext(int iGameConfigContextID) {}
void C_4JProfile::SetRichPresenceContextValue(int iPad,int iContextID, int iVal) {}
void C_4JProfile::SetCurrentGameActivity(int iPad,int iNewPresence, bool bSetOthersToIdle) {}
void C_4JProfile::SetRichPresenceContextValue(int iPad, int iContextID, int iVal) {}
void C_4JProfile::SetCurrentGameActivity(int iPad, int iNewPresence, bool bSetOthersToIdle) {}
void C_4JProfile::DisplayFullVersionPurchase(bool bRequired, int iQuadrant, int iUpsellParam) {}
void C_4JProfile::SetUpsellCallback(void ( *Func)(LPVOID lpParam, eUpsellType type, eUpsellResponse response, int iUserData),LPVOID lpParam) {}
void C_4JProfile::SetDebugFullOverride(bool bVal) {s_bProfileIsFullVersion = bVal;}
void C_4JProfile::SetUpsellCallback(void (*Func)(LPVOID lpParam, eUpsellType type, eUpsellResponse response, int iUserData), LPVOID lpParam) {}
void C_4JProfile::SetDebugFullOverride(bool bVal) { s_bProfileIsFullVersion = bVal; }
void C_4JProfile::ShowProfileCard(int iPad, PlayerUID targetUid) {}
/////////////////////////////////////////////// Storage library
@ -567,60 +663,60 @@ void C_4JProfile::ShowProfileCard(int iPad, PlayerUID targetUid) {}
#if 0
C4JStorage::C4JStorage() {}
void C4JStorage::Tick() {}
C4JStorage::EMessageResult C4JStorage::RequestMessageBox(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad, int( *Func)(LPVOID,int,const C4JStorage::EMessageResult),LPVOID lpParam, C4JStringTable *pStringTable, WCHAR *pwchFormatString,DWORD dwFocusButton) { return C4JStorage::EMessage_Undefined; }
C4JStorage::EMessageResult C4JStorage::GetMessageBoxResult() { return C4JStorage::EMessage_Undefined; }
bool C4JStorage::SetSaveDevice(int( *Func)(LPVOID,const bool),LPVOID lpParam, bool bForceResetOfSaveDevice) { return true; }
void C4JStorage::Init(LPCWSTR pwchDefaultSaveName,char *pszSavePackName,int iMinimumSaveSize, int( *Func)(LPVOID, const ESavingMessage, int),LPVOID lpParam) {}
C4JStorage::EMessageResult C4JStorage::RequestMessageBox(UINT uiTitle, UINT uiText, UINT * uiOptionA, UINT uiOptionC, DWORD dwPad, int(*Func)(LPVOID, int, const C4JStorage::EMessageResult), LPVOID lpParam, C4JStringTable * pStringTable, WCHAR * pwchFormatString, DWORD dwFocusButton) { return C4JStorage::EMessage_Undefined; }
C4JStorage::EMessageResult C4JStorage::GetMessageBoxResult() { return C4JStorage::EMessage_Undefined; }
bool C4JStorage::SetSaveDevice(int(*Func)(LPVOID, const bool), LPVOID lpParam, bool bForceResetOfSaveDevice) { return true; }
void C4JStorage::Init(LPCWSTR pwchDefaultSaveName, char* pszSavePackName, int iMinimumSaveSize, int(*Func)(LPVOID, const ESavingMessage, int), LPVOID lpParam) {}
void C4JStorage::ResetSaveData() {}
void C4JStorage::SetDefaultSaveNameForKeyboardDisplay(LPCWSTR pwchDefaultSaveName) {}
void C4JStorage::SetSaveTitle(LPCWSTR pwchDefaultSaveName) {}
LPCWSTR C4JStorage::GetSaveTitle() { return L""; }
bool C4JStorage::GetSaveUniqueNumber(INT *piVal) { return true; }
bool C4JStorage::GetSaveUniqueFilename(char *pszName) { return true; }
void C4JStorage::SetSaveUniqueFilename(char *szFilename) { }
void C4JStorage::SetState(ESaveGameControlState eControlState,int( *Func)(LPVOID,const bool),LPVOID lpParam) {}
bool C4JStorage::GetSaveUniqueNumber(INT * piVal) { return true; }
bool C4JStorage::GetSaveUniqueFilename(char* pszName) { return true; }
void C4JStorage::SetSaveUniqueFilename(char* szFilename) {}
void C4JStorage::SetState(ESaveGameControlState eControlState, int(*Func)(LPVOID, const bool), LPVOID lpParam) {}
void C4JStorage::SetSaveDisabled(bool bDisable) {}
bool C4JStorage::GetSaveDisabled(void) { return false; }
unsigned int C4JStorage::GetSaveSize() { return 0; }
void C4JStorage::GetSaveData(void *pvData,unsigned int *pulBytes) {}
void C4JStorage::GetSaveData(void* pvData, unsigned int* pulBytes) {}
PVOID C4JStorage::AllocateSaveData(unsigned int ulBytes) { return new char[ulBytes]; }
void C4JStorage::SaveSaveData(unsigned int ulBytes,PBYTE pbThumbnail,DWORD cbThumbnail,PBYTE pbTextData, DWORD dwTextLen) {}
void C4JStorage::CopySaveDataToNewSave(PBYTE pbThumbnail,DWORD cbThumbnail,WCHAR *wchNewName,int ( *Func)(LPVOID lpParam, bool), LPVOID lpParam) {}
void C4JStorage::SetSaveDeviceSelected(unsigned int uiPad,bool bSelected) {}
void C4JStorage::SaveSaveData(unsigned int ulBytes, PBYTE pbThumbnail, DWORD cbThumbnail, PBYTE pbTextData, DWORD dwTextLen) {}
void C4JStorage::CopySaveDataToNewSave(PBYTE pbThumbnail, DWORD cbThumbnail, WCHAR * wchNewName, int (*Func)(LPVOID lpParam, bool), LPVOID lpParam) {}
void C4JStorage::SetSaveDeviceSelected(unsigned int uiPad, bool bSelected) {}
bool C4JStorage::GetSaveDeviceSelected(unsigned int iPad) { return true; }
C4JStorage::ELoadGameStatus C4JStorage::DoesSaveExist(bool *pbExists) { return C4JStorage::ELoadGame_Idle; }
C4JStorage::ELoadGameStatus C4JStorage::DoesSaveExist(bool* pbExists) { return C4JStorage::ELoadGame_Idle; }
bool C4JStorage::EnoughSpaceForAMinSaveGame() { return true; }
void C4JStorage::SetSaveMessageVPosition(float fY) {}
//C4JStorage::ESGIStatus C4JStorage::GetSavesInfo(int iPad,bool ( *Func)(LPVOID, int, CACHEINFOSTRUCT *, int, HRESULT),LPVOID lpParam,char *pszSavePackName) { return C4JStorage::ESGIStatus_Idle; }
C4JStorage::ESaveGameState C4JStorage::GetSavesInfo(int iPad,int ( *Func)(LPVOID lpParam,SAVE_DETAILS *pSaveDetails,const bool),LPVOID lpParam,char *pszSavePackName) { return C4JStorage::ESaveGame_Idle; }
C4JStorage::ESaveGameState C4JStorage::GetSavesInfo(int iPad, int (*Func)(LPVOID lpParam, SAVE_DETAILS * pSaveDetails, const bool), LPVOID lpParam, char* pszSavePackName) { return C4JStorage::ESaveGame_Idle; }
void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile,XCONTENT_DATA &xContentData) {}
void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, PBYTE *ppbImageData, DWORD *pdwImageBytes) {}
C4JStorage::ESaveGameState C4JStorage::LoadSaveData(PSAVE_INFO pSaveInfo,int( *Func)(LPVOID lpParam,const bool, const bool), LPVOID lpParam) {return C4JStorage::ESaveGame_Idle;}
C4JStorage::EDeleteGameStatus C4JStorage::DeleteSaveData(PSAVE_INFO pSaveInfo,int( *Func)(LPVOID lpParam,const bool), LPVOID lpParam) { return C4JStorage::EDeleteGame_Idle; }
PSAVE_DETAILS C4JStorage::ReturnSavesInfo() {return NULL;}
void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, XCONTENT_DATA & xContentData) {}
void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, PBYTE * ppbImageData, DWORD * pdwImageBytes) {}
C4JStorage::ESaveGameState C4JStorage::LoadSaveData(PSAVE_INFO pSaveInfo, int(*Func)(LPVOID lpParam, const bool, const bool), LPVOID lpParam) { return C4JStorage::ESaveGame_Idle; }
C4JStorage::EDeleteGameStatus C4JStorage::DeleteSaveData(PSAVE_INFO pSaveInfo, int(*Func)(LPVOID lpParam, const bool), LPVOID lpParam) { return C4JStorage::EDeleteGame_Idle; }
PSAVE_DETAILS C4JStorage::ReturnSavesInfo() { return NULL; }
void C4JStorage::RegisterMarketplaceCountsCallback(int ( *Func)(LPVOID lpParam, C4JStorage::DLC_TMS_DETAILS *, int), LPVOID lpParam ) {}
void C4JStorage::SetDLCPackageRoot(char *pszDLCRoot) {}
C4JStorage::EDLCStatus C4JStorage::GetDLCOffers(int iPad,int( *Func)(LPVOID, int, DWORD, int),LPVOID lpParam, DWORD dwOfferTypesBitmaskT) { return C4JStorage::EDLC_Idle; }
void C4JStorage::RegisterMarketplaceCountsCallback(int (*Func)(LPVOID lpParam, C4JStorage::DLC_TMS_DETAILS*, int), LPVOID lpParam) {}
void C4JStorage::SetDLCPackageRoot(char* pszDLCRoot) {}
C4JStorage::EDLCStatus C4JStorage::GetDLCOffers(int iPad, int(*Func)(LPVOID, int, DWORD, int), LPVOID lpParam, DWORD dwOfferTypesBitmaskT) { return C4JStorage::EDLC_Idle; }
DWORD C4JStorage::CancelGetDLCOffers() { return 0; }
void C4JStorage::ClearDLCOffers() {}
XMARKETPLACE_CONTENTOFFER_INFO& C4JStorage::GetOffer(DWORD dw) { static XMARKETPLACE_CONTENTOFFER_INFO retval = {0}; return retval; }
XMARKETPLACE_CONTENTOFFER_INFO& C4JStorage::GetOffer(DWORD dw) { static XMARKETPLACE_CONTENTOFFER_INFO retval = { 0 }; return retval; }
int C4JStorage::GetOfferCount() { return 0; }
DWORD C4JStorage::InstallOffer(int iOfferIDC,ULONGLONG *ullOfferIDA,int( *Func)(LPVOID, int, int),LPVOID lpParam, bool bTrial) { return 0; }
DWORD C4JStorage::GetAvailableDLCCount( int iPad) { return 0; }
XCONTENT_DATA& C4JStorage::GetDLC(DWORD dw) { static XCONTENT_DATA retval = {0}; return retval; }
C4JStorage::EDLCStatus C4JStorage::GetInstalledDLC(int iPad,int( *Func)(LPVOID, int, int),LPVOID lpParam) { return C4JStorage::EDLC_Idle; }
DWORD C4JStorage::MountInstalledDLC(int iPad,DWORD dwDLC,int( *Func)(LPVOID, int, DWORD,DWORD),LPVOID lpParam,LPCSTR szMountDrive) { return 0; }
DWORD C4JStorage::InstallOffer(int iOfferIDC, ULONGLONG * ullOfferIDA, int(*Func)(LPVOID, int, int), LPVOID lpParam, bool bTrial) { return 0; }
DWORD C4JStorage::GetAvailableDLCCount(int iPad) { return 0; }
XCONTENT_DATA& C4JStorage::GetDLC(DWORD dw) { static XCONTENT_DATA retval = { 0 }; return retval; }
C4JStorage::EDLCStatus C4JStorage::GetInstalledDLC(int iPad, int(*Func)(LPVOID, int, int), LPVOID lpParam) { return C4JStorage::EDLC_Idle; }
DWORD C4JStorage::MountInstalledDLC(int iPad, DWORD dwDLC, int(*Func)(LPVOID, int, DWORD, DWORD), LPVOID lpParam, LPCSTR szMountDrive) { return 0; }
DWORD C4JStorage::UnmountInstalledDLC(LPCSTR szMountDrive) { return 0; }
C4JStorage::ETMSStatus C4JStorage::ReadTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,C4JStorage::eTMS_FileType eFileType, WCHAR *pwchFilename,BYTE **ppBuffer,DWORD *pdwBufferSize,int( *Func)(LPVOID, WCHAR *,int, bool, int),LPVOID lpParam, int iAction) { return C4JStorage::ETMSStatus_Idle; }
bool C4JStorage::WriteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename,BYTE *pBuffer,DWORD dwBufferSize) { return true; }
bool C4JStorage::DeleteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename) { return true; }
void C4JStorage::StoreTMSPathName(WCHAR *pwchName) {}
unsigned int C4JStorage::CRC(unsigned char *buf, int len) { return 0; }
C4JStorage::ETMSStatus C4JStorage::ReadTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, C4JStorage::eTMS_FileType eFileType, WCHAR * pwchFilename, BYTE * *ppBuffer, DWORD * pdwBufferSize, int(*Func)(LPVOID, WCHAR*, int, bool, int), LPVOID lpParam, int iAction) { return C4JStorage::ETMSStatus_Idle; }
bool C4JStorage::WriteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, WCHAR * pwchFilename, BYTE * pBuffer, DWORD dwBufferSize) { return true; }
bool C4JStorage::DeleteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, WCHAR * pwchFilename) { return true; }
void C4JStorage::StoreTMSPathName(WCHAR * pwchName) {}
unsigned int C4JStorage::CRC(unsigned char* buf, int len) { return 0; }
struct PTMSPP_FILEDATA;
C4JStorage::ETMSStatus C4JStorage::TMSPP_ReadFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPCSTR szFilename,int( *Func)(LPVOID,int,int,PTMSPP_FILEDATA, LPCSTR)/*=NULL*/,LPVOID lpParam/*=NULL*/, int iUserData/*=0*/) {return C4JStorage::ETMSStatus_Idle;}
C4JStorage::ETMSStatus C4JStorage::TMSPP_ReadFile(int iPad, C4JStorage::eGlobalStorage eStorageFacility, C4JStorage::eTMS_FILETYPEVAL eFileTypeVal, LPCSTR szFilename, int(*Func)(LPVOID, int, int, PTMSPP_FILEDATA, LPCSTR)/*=NULL*/, LPVOID lpParam/*=NULL*/, int iUserData/*=0*/) { return C4JStorage::ETMSStatus_Idle; }
#endif // _WINDOWS64
#endif // __PS3__
@ -636,8 +732,8 @@ BOOL CSentientManager::RecordHeartBeat(DWORD dwUserId) { return true; }
BOOL CSentientManager::RecordLevelStart(DWORD dwUserId, ESen_FriendOrMatch friendsOrMatch, ESen_CompeteOrCoop competeOrCoop, int difficulty, DWORD numberOfLocalPlayers, DWORD numberOfOnlinePlayers) { return true; }
BOOL CSentientManager::RecordLevelExit(DWORD dwUserId, ESen_LevelExitStatus levelExitStatus) { return true; }
BOOL CSentientManager::RecordLevelSaveOrCheckpoint(DWORD dwUserId, INT saveOrCheckPointID, INT saveSizeInBytes) { return true; }
BOOL CSentientManager::RecordLevelResume(DWORD dwUserId, ESen_FriendOrMatch friendsOrMatch, ESen_CompeteOrCoop competeOrCoop, int difficulty, DWORD numberOfLocalPlayers, DWORD numberOfOnlinePlayers, INT saveOrCheckPointID) { return true; }
BOOL CSentientManager::RecordPauseOrInactive(DWORD dwUserId) { return true; }
BOOL CSentientManager::RecordLevelResume(DWORD dwUserId, ESen_FriendOrMatch friendsOrMatch, ESen_CompeteOrCoop competeOrCoop, int difficulty, DWORD numberOfLocalPlayers, DWORD numberOfOnlinePlayers, INT saveOrCheckPointID) { return true; }
BOOL CSentientManager::RecordPauseOrInactive(DWORD dwUserId) { return true; }
BOOL CSentientManager::RecordUnpauseOrActive(DWORD dwUserId) { return true; }
BOOL CSentientManager::RecordMenuShown(DWORD dwUserId, INT menuID, INT optionalMenuSubID) { return true; }
BOOL CSentientManager::RecordAchievementUnlocked(DWORD dwUserId, INT achievementID, INT achievementGamerscore) { return true; }

View file

@ -501,23 +501,26 @@ void GameRenderer::moveCameraToPlayer(float a)
else
{
// 4J - corrected bug where this used to just take player->xRot & yRot directly and so wasn't taking into account interpolation, allowing camera to go through walls
float playerYRot = player->yRotO + (player->yRot - player->yRotO) * a;
float playerXRot = player->xRotO + (player->xRot - player->xRotO) * a;
float yRot = playerYRot;
float xRot = playerXRot;
float yRot = player->yRotO + (player->yRot - player->yRotO) * a;
float xRot = player->xRotO + (player->xRot - player->xRotO) * a;
// Thirdperson view values are now 0 for disabled, 1 for original mode, 2 for reversed.
if( localplayer->ThirdPersonView() == 2 )
{
// Reverse x rotation - note that this is only used in doing collision to calculate our view
// Reverse y rotation - note that this is only used in doing collision to calculate our view
// distance, the actual rotation itself is just below this else {} block
xRot += 180.0f;
yRot += 180.0f;
}
double xd = -Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * cameraDist;
double zd = Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * cameraDist;
double yd = -Mth::sin(xRot / 180 * PI) * cameraDist;
if (localplayer->ThirdPersonView() == 2)
{
yd = Mth::sin(xRot / 180 * PI) * cameraDist;
}
for (int i = 0; i < 8; i++)
{
float xo = (float)((i & 1) * 2 - 1);
@ -538,16 +541,7 @@ void GameRenderer::moveCameraToPlayer(float a)
}
}
if ( localplayer->ThirdPersonView() == 2)
{
glRotatef(180, 0, 1, 0);
}
glRotatef(playerXRot - xRot, 1, 0, 0);
glRotatef(playerYRot - yRot, 0, 1, 0);
glTranslatef(0, 0, (float) -cameraDist);
glRotatef(yRot - playerYRot, 0, 1, 0);
glRotatef(xRot - playerXRot, 1, 0, 0);
}
}
else
@ -557,8 +551,21 @@ void GameRenderer::moveCameraToPlayer(float a)
if (!mc->options->fixedCamera)
{
glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, 1, 0, 0);
glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, 0, 1, 0);
float pitch = player->xRotO + (player->xRot - player->xRotO) * a;
if (localplayer->ThirdPersonView() == 2)
{
pitch = -pitch;
}
glRotatef(pitch, 1, 0, 0);
if (localplayer->ThirdPersonView() == 2)
{
glRotatef(player->yRotO + (player->yRot - player->yRotO) * a, 0, 1, 0);
}
else
{
glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, 0, 1, 0);
}
}
glTranslatef(0, heightOffset, 0);
@ -903,7 +910,7 @@ void GameRenderer::updateLightTexture(float a)
if (_g > 1) _g = 1;
if (_b > 1) _b = 1;
float brightness = 0.0f; // 4J - TODO - was mc->options->gamma;
float brightness = mc->options->gamma;
float ir = 1 - _r;
float ig = 1 - _g;

View file

@ -145,7 +145,7 @@ void Input::tick(LocalPlayer *player)
// Delta should normally be 0 since applyFrameMouseLook() already consumed it
if (rawDx != 0.0f || rawDy != 0.0f)
{
float mouseSensitivity = 0.5f;
float mouseSensitivity = ((float)app.GetGameSettings(iPad, eGameSetting_Sensitivity_InGame)) / 100.0f;
float mdx = rawDx * mouseSensitivity;
float mdy = -rawDy * mouseSensitivity;
if (app.GetGameSettings(iPad, eGameSetting_ControlInvertLook))

View file

@ -1964,8 +1964,8 @@ bool LevelRenderer::updateDirtyChunks()
{
if( (!onlyRebuild) ||
globalChunkFlags[ pClipChunk->globalIdx ] & CHUNK_FLAG_COMPILED ||
( distSq < 20 * 20 ) ) // Always rebuild really near things or else building (say) at tower up into empty blocks when we are low on memory will not create render data
{
( distSq < 96 * 96 ) ) // Always rebuild really near things or else building (say) at tower up into empty blocks when we are low on memory will not create render data
{ // distSq adjusted from 20 * 20 to 96 * 96 - updated by detectiveren
considered++;
// Is this chunk nearer than our nearest?
#ifdef _LARGE_WORLDS
@ -2557,13 +2557,19 @@ void LevelRenderer::cull(Culler *culler, float a)
{
unsigned char flags = pClipChunk->globalIdx == -1 ? 0 : globalChunkFlags[ pClipChunk->globalIdx ];
// Always perform frustum cull test
bool clipres = clip(pClipChunk->aabb, fdraw);
if ( (flags & CHUNK_FLAG_COMPILED ) && ( ( flags & CHUNK_FLAG_EMPTYBOTH ) != CHUNK_FLAG_EMPTYBOTH ) )
{
bool clipres = clip(pClipChunk->aabb, fdraw);
pClipChunk->visible = clipres;
if( pClipChunk->visible ) vis++;
total++;
}
else if (clipres)
{
pClipChunk->visible = true;
}
else
{
pClipChunk->visible = false;
@ -2572,6 +2578,7 @@ void LevelRenderer::cull(Culler *culler, float a)
}
}
void LevelRenderer::playStreamingMusic(const wstring& name, int x, int y, int z)
{
if (name != L"")

View file

@ -52,14 +52,16 @@ public:
static const int CHUNK_SIZE = 16;
#endif
static const int CHUNK_Y_COUNT = Level::maxBuildHeight / CHUNK_SIZE;
#if defined _XBOX_ONE
static const int MAX_COMMANDBUFFER_ALLOCATIONS = 2047 * 1024 * 1024; // Changed to 2047. 4J had set to 512.
#if defined _WINDOWS64
static const int MAX_COMMANDBUFFER_ALLOCATIONS = 2047 * 1024 * 1024; // Changed to 2047. 4J had set to 512.
#elif defined _XBOX_ONE
static const int MAX_COMMANDBUFFER_ALLOCATIONS = 512 * 1024 * 1024; // 4J - added
#elif defined __ORBIS__
static const int MAX_COMMANDBUFFER_ALLOCATIONS = 448 * 1024 * 1024; // 4J - added - hard limit is 512 so giving a lot of headroom here for fragmentation (have seen 16MB lost to fragmentation in multiplayer crash dump before)
#elif defined __PS3__
static const int MAX_COMMANDBUFFER_ALLOCATIONS = 110 * 1024 * 1024; // 4J - added
#else
static const int MAX_COMMANDBUFFER_ALLOCATIONS = 55 * 1024 * 1024; // 4J - added
static const int MAX_COMMANDBUFFER_ALLOCATIONS = 55 * 1024 * 1024; // 4J - added
#endif
public:
LevelRenderer(Minecraft *mc, Textures *textures);
@ -270,10 +272,10 @@ public:
bool dirtyChunkPresent;
__int64 lastDirtyChunkFound;
static const int FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS = 250;
static const int FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS = 125; // decreased from 250 to 125 - updated by detectiveren
#ifdef _LARGE_WORLDS
static const int MAX_CONCURRENT_CHUNK_REBUILDS = 4;
static const int MAX_CONCURRENT_CHUNK_REBUILDS = 8; // increased from 4 to 8 - updated by detectiveren
static const int MAX_CHUNK_REBUILD_THREADS = MAX_CONCURRENT_CHUNK_REBUILDS - 1;
static Chunk permaChunk[MAX_CONCURRENT_CHUNK_REBUILDS];
static C4JThread *rebuildThreads[MAX_CHUNK_REBUILD_THREADS];

File diff suppressed because it is too large Load diff

View file

@ -723,9 +723,12 @@
<Filter Include="PSVita\Miles Sound System\lib">
<UniqueIdentifier>{0061db22-43de-4b54-a161-c43958cdcd7e}</UniqueIdentifier>
</Filter>
<Filter Include="net\minecraft\client\resources">
<Filter Include="net\minecraft\client\resources">
<UniqueIdentifier>{889a84db-3009-4a7c-8234-4bf93d412690}</UniqueIdentifier>
</Filter>
<Filter Include="Windows64\Source Files\Network">
<UniqueIdentifier>{e5d7fb24-25b8-413c-84ec-974bf0d4a3d1}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="ReadMe.txt" />
@ -3769,6 +3772,9 @@
<ClInclude Include="Common\Leaderboards\LeaderboardInterface.h">
<Filter>Common\Source Files\Leaderboards</Filter>
</ClInclude>
<ClInclude Include="Windows64\Network\WinsockNetLayer.h">
<Filter>Windows64\Source Files\Network</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="stdafx.cpp">
@ -5916,6 +5922,9 @@
<ClCompile Include="compat_shims.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Windows64\Network\WinsockNetLayer.cpp">
<Filter>Windows64\Source Files\Network</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Library Include="Xbox\4JLibs\libs\4J_Render_d.lib">

View file

@ -7,8 +7,16 @@
<LocalDebuggerWorkingDirectory>$(SolutionDir)$(Platform)\$(Configuration)\</LocalDebuggerWorkingDirectory>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64EC'">
<LocalDebuggerWorkingDirectory>$(SolutionDir)$(Platform)\$(Configuration)\</LocalDebuggerWorkingDirectory>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LocalDebuggerWorkingDirectory>$(SolutionDir)$(Platform)\$(Configuration)\</LocalDebuggerWorkingDirectory>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64EC'">
<LocalDebuggerWorkingDirectory>$(SolutionDir)$(Platform)\$(Configuration)\</LocalDebuggerWorkingDirectory>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View file

@ -1191,7 +1191,7 @@ void Minecraft::applyFrameMouseLook()
KMInput.ConsumeMouseDelta(rawDx, rawDy);
if (rawDx == 0.0f && rawDy == 0.0f) continue;
float mouseSensitivity = 0.5f;
float mouseSensitivity = ((float)app.GetGameSettings(iPad, eGameSetting_Sensitivity_InGame)) / 100.0f;
float mdx = rawDx * mouseSensitivity;
float mdy = -rawDy * mouseSensitivity;
if (app.GetGameSettings(iPad, eGameSetting_ControlInvertLook))
@ -1456,7 +1456,7 @@ void Minecraft::run_middle()
if (KMInput.ConsumeKeyPress('C')) localplayers[i]->ullButtonsPressed |= 1LL<<MINECRAFT_ACTION_CRAFTING;
if (KMInput.ConsumeKeyPress(VK_F5)) localplayers[i]->ullButtonsPressed |= 1LL<<MINECRAFT_ACTION_RENDER_THIRD_PERSON;
// In flying mode, Shift held = sneak/descend
if (localplayers[i]->abilities.flying && KMInput.IsKeyDown(VK_SHIFT))
if (localplayers[i]->abilities.flying && KMInput.IsKeyDown(VK_SHIFT) && !ui.GetMenuDisplayed(i))
localplayers[i]->ullButtonsPressed |= 1LL<<MINECRAFT_ACTION_SNEAK_TOGGLE;
}
#endif
@ -3618,8 +3618,6 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures)
if((player->ullButtonsPressed&(1LL<<MINECRAFT_ACTION_RENDER_DEBUG)) )
{
#ifndef _CONTENT_PACKAGE
options->renderDebug = !options->renderDebug;
#ifdef _XBOX
app.EnableDebugOverlay(options->renderDebug,iPad);
#else
@ -3629,13 +3627,11 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures)
#endif
}
if((player->ullButtonsPressed&(1LL<<MINECRAFT_ACTION_SPAWN_CREEPER)) && app.GetMobsDontAttackEnabled())
{
//shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(Creeper::_class->newInstance( level ));
//shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(Wolf::_class->newInstance( level ));
shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(shared_ptr<Spider>(new Spider( level )));
mob->moveTo(player->x+1, player->y, player->z+1, level->random->nextFloat() * 360, 0);
level->addEntity(mob);
if((player->ullButtonsPressed&(1LL<<MINECRAFT_ACTION_SPAWN_CREEPER)))
{
#ifndef _CONTENT_PACKAGE
options->renderDebug = !options->renderDebug;
#endif
}
}

View file

@ -27,6 +27,11 @@
#include "../Minecraft.World/Pos.h"
#include "../Minecraft.World/System.h"
#include "../Minecraft.World/StringHelpers.h"
#include "../Minecraft.World/net.minecraft.world.entity.item.h"
#include "../Minecraft.World/net.minecraft.world.item.h"
#include "../Minecraft.World/net.minecraft.world.item.enchantment.h"
#include "../Minecraft.World/net.minecraft.world.damagesource.h"
#include <sstream>
#ifdef SPLIT_SAVES
#include "../Minecraft.World/ConsoleSaveFileSplit.h"
#endif
@ -78,6 +83,438 @@ bool MinecraftServer::s_slowQueuePacketSent = false;
unordered_map<wstring, int> MinecraftServer::ironTimers;
static void PrintConsoleLine(const wchar_t *prefix, const wstring &message)
{
wprintf(L"%ls%ls\n", prefix, message.c_str());
fflush(stdout);
}
static bool TryParseIntValue(const wstring &text, int &value)
{
std::wistringstream stream(text);
stream >> value;
return !stream.fail() && stream.eof();
}
static vector<wstring> SplitConsoleCommand(const wstring &command)
{
vector<wstring> tokens;
std::wistringstream stream(command);
wstring token;
while (stream >> token)
{
tokens.push_back(token);
}
return tokens;
}
static wstring JoinConsoleCommandTokens(const vector<wstring> &tokens, size_t startIndex)
{
wstring joined;
for (size_t i = startIndex; i < tokens.size(); ++i)
{
if (!joined.empty()) joined += L" ";
joined += tokens[i];
}
return joined;
}
static shared_ptr<ServerPlayer> FindPlayerByName(PlayerList *playerList, const wstring &name)
{
if (playerList == NULL) return nullptr;
for (size_t i = 0; i < playerList->players.size(); ++i)
{
shared_ptr<ServerPlayer> player = playerList->players[i];
if (player != NULL && equalsIgnoreCase(player->getName(), name))
{
return player;
}
}
return nullptr;
}
static void SetAllLevelTimes(MinecraftServer *server, int value)
{
for (unsigned int i = 0; i < server->levels.length; ++i)
{
if (server->levels[i] != NULL)
{
server->levels[i]->setDayTime(value);
}
}
}
static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCommand)
{
if (server == NULL)
return false;
wstring command = trimString(rawCommand);
if (command.empty())
return true;
if (command[0] == L'/')
{
command = trimString(command.substr(1));
}
vector<wstring> tokens = SplitConsoleCommand(command);
if (tokens.empty())
return true;
const wstring action = toLower(tokens[0]);
PlayerList *playerList = server->getPlayers();
if (action == L"help" || action == L"?")
{
server->info(L"Commands: help, stop, list, say <message>, save-all, time <set day|night|ticks|add ticks>, weather <clear|rain|thunder> [seconds], tp <player> <target>, give <player> <itemId> [amount] [aux], enchant <player> <enchantId> [level], kill <player>");
return true;
}
if (action == L"stop")
{
server->info(L"Stopping server...");
MinecraftServer::HaltServer();
return true;
}
if (action == L"list")
{
wstring playerNames = (playerList != NULL) ? playerList->getPlayerNames() : L"";
if (playerNames.empty()) playerNames = L"(none)";
server->info(L"Players (" + _toString((playerList != NULL) ? playerList->getPlayerCount() : 0) + L"): " + playerNames);
return true;
}
if (action == L"say")
{
if (tokens.size() < 2)
{
server->warn(L"Usage: say <message>");
return false;
}
wstring message = L"[Server] " + JoinConsoleCommandTokens(tokens, 1);
if (playerList != NULL)
{
playerList->broadcastAll(shared_ptr<ChatPacket>(new ChatPacket(message)));
}
server->info(message);
return true;
}
if (action == L"save-all")
{
if (playerList != NULL)
{
playerList->saveAll(NULL, false);
}
server->info(L"World saved.");
return true;
}
if (action == L"time")
{
if (tokens.size() < 2)
{
server->warn(L"Usage: time set <day|night|ticks> | time add <ticks>");
return false;
}
if (toLower(tokens[1]) == L"add")
{
if (tokens.size() < 3)
{
server->warn(L"Usage: time add <ticks>");
return false;
}
int delta = 0;
if (!TryParseIntValue(tokens[2], delta))
{
server->warn(L"Invalid tick value: " + tokens[2]);
return false;
}
for (unsigned int i = 0; i < server->levels.length; ++i)
{
if (server->levels[i] != NULL)
{
server->levels[i]->setDayTime(server->levels[i]->getDayTime() + delta);
}
}
server->info(L"Added " + _toString(delta) + L" ticks.");
return true;
}
wstring timeValue = toLower(tokens[1]);
if (timeValue == L"set")
{
if (tokens.size() < 3)
{
server->warn(L"Usage: time set <day|night|ticks>");
return false;
}
timeValue = toLower(tokens[2]);
}
int targetTime = 0;
if (timeValue == L"day")
{
targetTime = 0;
}
else if (timeValue == L"night")
{
targetTime = 12500;
}
else if (!TryParseIntValue(timeValue, targetTime))
{
server->warn(L"Invalid time value: " + timeValue);
return false;
}
SetAllLevelTimes(server, targetTime);
server->info(L"Time set to " + _toString(targetTime) + L".");
return true;
}
if (action == L"weather")
{
if (tokens.size() < 2)
{
server->warn(L"Usage: weather <clear|rain|thunder> [seconds]");
return false;
}
int durationSeconds = 600;
if (tokens.size() >= 3 && !TryParseIntValue(tokens[2], durationSeconds))
{
server->warn(L"Invalid duration: " + tokens[2]);
return false;
}
if (server->levels[0] == NULL)
{
server->warn(L"The overworld is not loaded.");
return false;
}
LevelData *levelData = server->levels[0]->getLevelData();
int duration = durationSeconds * SharedConstants::TICKS_PER_SECOND;
levelData->setRainTime(duration);
levelData->setThunderTime(duration);
wstring weather = toLower(tokens[1]);
if (weather == L"clear")
{
levelData->setRaining(false);
levelData->setThundering(false);
}
else if (weather == L"rain")
{
levelData->setRaining(true);
levelData->setThundering(false);
}
else if (weather == L"thunder")
{
levelData->setRaining(true);
levelData->setThundering(true);
}
else
{
server->warn(L"Usage: weather <clear|rain|thunder> [seconds]");
return false;
}
server->info(L"Weather set to " + weather + L".");
return true;
}
if (action == L"tp" || action == L"teleport")
{
if (tokens.size() < 3)
{
server->warn(L"Usage: tp <player> <target>");
return false;
}
shared_ptr<ServerPlayer> subject = FindPlayerByName(playerList, tokens[1]);
shared_ptr<ServerPlayer> destination = FindPlayerByName(playerList, tokens[2]);
if (subject == NULL)
{
server->warn(L"Unknown player: " + tokens[1]);
return false;
}
if (destination == NULL)
{
server->warn(L"Unknown player: " + tokens[2]);
return false;
}
if (subject->level->dimension->id != destination->level->dimension->id || !subject->isAlive())
{
server->warn(L"Teleport failed because the players are not in the same dimension or the source player is dead.");
return false;
}
subject->ride(nullptr);
subject->connection->teleport(destination->x, destination->y, destination->z, destination->yRot, destination->xRot);
server->info(L"Teleported " + subject->getName() + L" to " + destination->getName() + L".");
return true;
}
if (action == L"give")
{
if (tokens.size() < 3)
{
server->warn(L"Usage: give <player> <itemId> [amount] [aux]");
return false;
}
shared_ptr<ServerPlayer> player = FindPlayerByName(playerList, tokens[1]);
if (player == NULL)
{
server->warn(L"Unknown player: " + tokens[1]);
return false;
}
int itemId = 0;
int amount = 1;
int aux = 0;
if (!TryParseIntValue(tokens[2], itemId))
{
server->warn(L"Invalid item id: " + tokens[2]);
return false;
}
if (tokens.size() >= 4 && !TryParseIntValue(tokens[3], amount))
{
server->warn(L"Invalid amount: " + tokens[3]);
return false;
}
if (tokens.size() >= 5 && !TryParseIntValue(tokens[4], aux))
{
server->warn(L"Invalid aux value: " + tokens[4]);
return false;
}
if (itemId <= 0 || Item::items[itemId] == NULL)
{
server->warn(L"Unknown item id: " + _toString(itemId));
return false;
}
if (amount <= 0)
{
server->warn(L"Amount must be positive.");
return false;
}
shared_ptr<ItemInstance> itemInstance(new ItemInstance(itemId, amount, aux));
shared_ptr<ItemEntity> drop = player->drop(itemInstance);
if (drop != NULL)
{
drop->throwTime = 0;
}
server->info(L"Gave item " + _toString(itemId) + L" x" + _toString(amount) + L" to " + player->getName() + L".");
return true;
}
if (action == L"enchant")
{
if (tokens.size() < 3)
{
server->warn(L"Usage: enchant <player> <enchantId> [level]");
return false;
}
shared_ptr<ServerPlayer> player = FindPlayerByName(playerList, tokens[1]);
if (player == NULL)
{
server->warn(L"Unknown player: " + tokens[1]);
return false;
}
int enchantmentId = 0;
int enchantmentLevel = 1;
if (!TryParseIntValue(tokens[2], enchantmentId))
{
server->warn(L"Invalid enchantment id: " + tokens[2]);
return false;
}
if (tokens.size() >= 4 && !TryParseIntValue(tokens[3], enchantmentLevel))
{
server->warn(L"Invalid enchantment level: " + tokens[3]);
return false;
}
shared_ptr<ItemInstance> selectedItem = player->getSelectedItem();
if (selectedItem == NULL)
{
server->warn(L"The player is not holding an item.");
return false;
}
Enchantment *enchantment = Enchantment::enchantments[enchantmentId];
if (enchantment == NULL)
{
server->warn(L"Unknown enchantment id: " + _toString(enchantmentId));
return false;
}
if (!enchantment->canEnchant(selectedItem))
{
server->warn(L"That enchantment cannot be applied to the selected item.");
return false;
}
if (enchantmentLevel < enchantment->getMinLevel()) enchantmentLevel = enchantment->getMinLevel();
if (enchantmentLevel > enchantment->getMaxLevel()) enchantmentLevel = enchantment->getMaxLevel();
if (selectedItem->hasTag())
{
ListTag<CompoundTag> *enchantmentTags = selectedItem->getEnchantmentTags();
if (enchantmentTags != NULL)
{
for (int i = 0; i < enchantmentTags->size(); i++)
{
int type = enchantmentTags->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_ID);
if (Enchantment::enchantments[type] != NULL && !Enchantment::enchantments[type]->isCompatibleWith(enchantment))
{
server->warn(L"That enchantment conflicts with an existing enchantment on the selected item.");
return false;
}
}
}
}
selectedItem->enchant(enchantment, enchantmentLevel);
server->info(L"Enchanted " + player->getName() + L"'s held item with " + _toString(enchantmentId) + L" " + _toString(enchantmentLevel) + L".");
return true;
}
if (action == L"kill")
{
if (tokens.size() < 2)
{
server->warn(L"Usage: kill <player>");
return false;
}
shared_ptr<ServerPlayer> player = FindPlayerByName(playerList, tokens[1]);
if (player == NULL)
{
server->warn(L"Unknown player: " + tokens[1]);
return false;
}
player->hurt(DamageSource::outOfWorld, 3.4e38f);
server->info(L"Killed " + player->getName() + L".");
return true;
}
server->warn(L"Unknown command: " + command);
return false;
}
MinecraftServer::MinecraftServer()
{
// 4J - added initialisers
@ -107,12 +544,14 @@ MinecraftServer::MinecraftServer()
forceGameType = false;
commandDispatcher = new ServerCommandDispatcher();
InitializeCriticalSection(&m_consoleInputCS);
DispenserBootstrap::bootStrap();
}
MinecraftServer::~MinecraftServer()
{
DeleteCriticalSection(&m_consoleInputCS);
}
bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, DWORD initSettings, bool findSeed)
@ -150,6 +589,15 @@ bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, DW
#endif
settings = new Settings(new File(L"server.properties"));
app.SetGameHostOption(eGameHostOption_Difficulty, settings->getInt(L"difficulty", app.GetGameHostOption(eGameHostOption_Difficulty)));
app.SetGameHostOption(eGameHostOption_GameType, settings->getInt(L"gamemode", app.GetGameHostOption(eGameHostOption_GameType)));
app.SetGameHostOption(eGameHostOption_Structures, settings->getBoolean(L"generate-structures", app.GetGameHostOption(eGameHostOption_Structures) > 0) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_BonusChest, settings->getBoolean(L"bonus-chest", app.GetGameHostOption(eGameHostOption_BonusChest) > 0) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_PvP, settings->getBoolean(L"pvp", app.GetGameHostOption(eGameHostOption_PvP) > 0) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_TrustPlayers, settings->getBoolean(L"trust-players", app.GetGameHostOption(eGameHostOption_TrustPlayers) > 0) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_FireSpreads, settings->getBoolean(L"fire-spreads", app.GetGameHostOption(eGameHostOption_FireSpreads) > 0) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_TNT, settings->getBoolean(L"tnt", app.GetGameHostOption(eGameHostOption_TNT) > 0) ? 1 : 0);
app.DebugPrintf("\n*** SERVER SETTINGS ***\n");
app.DebugPrintf("ServerSettings: host-friends-only is %s\n",(app.GetGameHostOption(eGameHostOption_FriendsOfFriends)>0)?"on":"off");
app.DebugPrintf("ServerSettings: game-type is %s\n",(app.GetGameHostOption(eGameHostOption_GameType)==0)?"Survival Mode":"Creative Mode");
@ -165,15 +613,15 @@ bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, DW
//localIp = settings->getString(L"server-ip", L"");
//onlineMode = settings->getBoolean(L"online-mode", true);
//motd = settings->getString(L"motd", L"A Minecraft Server");
//motd.replace('§', '$');
//motd.replace('<EFBFBD>', '$');
setAnimals(settings->getBoolean(L"spawn-animals", true));
setNpcsEnabled(settings->getBoolean(L"spawn-npcs", true));
setPvpAllowed(app.GetGameHostOption( eGameHostOption_PvP )>0?true:false); // settings->getBoolean(L"pvp", true);
setPvpAllowed(app.GetGameHostOption( eGameHostOption_PvP )>0?true:false);
// 4J Stu - We should never have hacked clients flying when they shouldn't be like the PC version, so enable flying always
// Fix for #46612 - TU5: Code: Multiplayer: A client can be banned for flying when accidentaly being blown by dynamite
setFlightAllowed(true); //settings->getBoolean(L"allow-flight", false);
setFlightAllowed(settings->getBoolean(L"allow-flight", true));
// 4J Stu - Enabling flight to stop it kicking us when we use it
#ifdef _DEBUG_MENUS_ENABLED
@ -219,8 +667,8 @@ bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, DW
__int64 levelNanoTime = System::nanoTime();
wstring levelName = settings->getString(L"level-name", L"world");
wstring levelTypeString;
wstring levelName = (initData && !initData->levelName.empty()) ? initData->levelName : settings->getString(L"level-name", L"world");
wstring levelTypeString;
bool gameRuleUseFlatWorld = false;
if(app.getLevelGenerationOptions() != NULL)
@ -1707,17 +2155,23 @@ void MinecraftServer::tick()
void MinecraftServer::handleConsoleInput(const wstring& msg, ConsoleInputSource *source)
{
EnterCriticalSection(&m_consoleInputCS);
consoleInput.push_back(new ConsoleInput(msg, source));
LeaveCriticalSection(&m_consoleInputCS);
}
void MinecraftServer::handleConsoleInputs()
{
while (consoleInput.size() > 0)
vector<ConsoleInput *> pendingInputs;
EnterCriticalSection(&m_consoleInputCS);
pendingInputs.swap(consoleInput);
LeaveCriticalSection(&m_consoleInputCS);
for (size_t i = 0; i < pendingInputs.size(); ++i)
{
AUTO_VAR(it, consoleInput.begin());
ConsoleInput *input = *it;
consoleInput.erase(it);
// commands->handleCommand(input); // 4J - removed - TODO - do we want equivalent of console commands?
ConsoleInput *input = pendingInputs[i];
ExecuteConsoleCommand(this, input->msg);
delete input;
}
}
@ -1750,10 +2204,12 @@ File *MinecraftServer::getFile(const wstring& name)
void MinecraftServer::info(const wstring& string)
{
PrintConsoleLine(L"[INFO] ", string);
}
void MinecraftServer::warn(const wstring& string)
{
PrintConsoleLine(L"[WARN] ", string);
}
wstring MinecraftServer::getConsoleName()

View file

@ -43,6 +43,7 @@ typedef struct _NetworkGameInitData
unsigned int xzSize;
unsigned char hellScale;
ESavePlatform savePlatform;
wstring levelName;
_NetworkGameInitData()
{
@ -103,6 +104,7 @@ private:
// vector<Tickable *> tickables = new ArrayList<Tickable>(); // 4J - removed
CommandDispatcher *commandDispatcher;
vector<ConsoleInput *> consoleInput; // 4J - was synchronizedList - TODO - investigate
CRITICAL_SECTION m_consoleInputCS;
public:
bool onlineMode;
bool animals;

View file

@ -6,6 +6,7 @@
#include "Minecraft.h"
#include "ClientConnection.h"
#include "LevelRenderer.h"
#include "Common/Network/GameNetworkManager.h"
#include "../Minecraft.World/net.minecraft.world.level.h"
#include "../Minecraft.World/net.minecraft.world.item.h"
#include "../Minecraft.World/net.minecraft.world.entity.player.h"
@ -85,6 +86,14 @@ bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face)
if (oldTile == NULL) return false;
#ifdef _WINDOWS64
if (g_NetworkManager.IsHost())
{
level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT));
return true;
}
#endif
level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT));
int data = level->getData(x, y, z);

View file

@ -20,6 +20,10 @@
Random *PendingConnection::random = new Random();
#ifdef _WINDOWS64
bool g_bRejectDuplicateNames = true;
#endif
PendingConnection::PendingConnection(MinecraftServer *server, Socket *socket, const wstring& id)
{
// 4J - added initialisers
@ -166,6 +170,30 @@ void PendingConnection::handleLogin(shared_ptr<LoginPacket> packet)
{
disconnect(DisconnectPacket::eDisconnect_Banned);
}
#ifdef _WINDOWS64
else if (g_bRejectDuplicateNames)
{
bool nameTaken = false;
vector<shared_ptr<ServerPlayer> >& pl = server->getPlayers()->players;
for (unsigned int i = 0; i < pl.size(); i++)
{
if (pl[i] != NULL && pl[i]->name == name)
{
nameTaken = true;
break;
}
}
if (nameTaken)
{
app.DebugPrintf("Rejecting duplicate name: %ls\n", name.c_str());
disconnect(DisconnectPacket::eDisconnect_Banned);
}
else
{
handleAcceptedLogin(packet);
}
}
#endif
else
{
handleAcceptedLogin(packet);

View file

@ -25,7 +25,7 @@
#include "../Minecraft.World/net.minecraft.world.level.saveddata.h"
#include "../Minecraft.World/JavaMath.h"
#include "../Minecraft.World/EntityIO.h"
#ifdef _XBOX
#if defined(_XBOX) || defined(_WINDOWS64)
#include "Xbox/Network/NetworkPlayerXbox.h"
#elif defined(__PS3__) || defined(__ORBIS__)
#include "Common/Network/Sony/NetworkPlayerSony.h"
@ -56,6 +56,11 @@ PlayerList::PlayerList(MinecraftServer *server)
maxPlayers = server->settings->getInt(L"max-players", 20);
doWhiteList = false;
#ifdef _WINDOWS64
maxPlayers = MINECRAFT_NET_MAX_PLAYERS;
#else
maxPlayers = server->settings->getInt(L"max-players", 20);
#endif
InitializeCriticalSection(&m_kickPlayersCS);
InitializeCriticalSection(&m_closePlayersCS);
}
@ -100,7 +105,14 @@ void PlayerList::placeNewPlayer(Connection *connection, shared_ptr<ServerPlayer>
}
}
#endif
#ifdef _WINDOWS64
if (networkPlayer != NULL && !networkPlayer->IsLocal())
{
NetworkPlayerXbox* nxp = (NetworkPlayerXbox*)networkPlayer;
IQNetPlayer* qnp = nxp->GetQNetPlayer();
wcsncpy_s(qnp->m_gamertag, 32, player->name.c_str(), _TRUNCATE);
}
#endif
// 4J Stu - TU-1 hotfix
// Fix for #13150 - When a player loads/joins a game after saving/leaving in the nether, sometimes they are spawned on top of the nether and cannot mine down
validatePlayerSpawnPosition(player);
@ -227,7 +239,7 @@ void PlayerList::placeNewPlayer(Connection *connection, shared_ptr<ServerPlayer>
sendLevelInfo(player, level);
// 4J-PB - removed, since it needs to be localised in the language the client is in
//server->players->broadcastAll( shared_ptr<ChatPacket>( new ChatPacket(L"§e" + playerEntity->name + L" joined the game.") ) );
//server->players->broadcastAll( shared_ptr<ChatPacket>( new ChatPacket(L"<EFBFBD>e" + playerEntity->name + L" joined the game.") ) );
broadcastAll( shared_ptr<ChatPacket>( new ChatPacket(player->name, ChatPacket::e_ChatPlayerJoinedGame) ) );
MemSect(14);
@ -428,7 +440,7 @@ void PlayerList::add(shared_ptr<ServerPlayer> player)
// Some code from here has been moved to the above validatePlayerSpawnPosition function
// 4J Stu - Swapped these lines about so that we get the chunk visiblity packet way ahead of all the add tracked entity packets
// Fix for #9169 - ART : Sign text is replaced with the words “Awaiting approval”.
// Fix for #9169 - ART : Sign text is replaced with the words <EFBFBD>Awaiting approval<61>.
changeDimension(player, NULL);
level->addEntity(player);
@ -469,14 +481,12 @@ void PlayerList::remove(shared_ptr<ServerPlayer> player)
//4J Stu - We don't want to save the map data for guests, so when we are sure that the player is gone delete the map
if(player->isGuest()) playerIo->deleteMapFilesForPlayer(player);
ServerLevel *level = player->getLevel();
if (player->riding != NULL)
if (player->riding != NULL)
{
// remove mount first because the player unmounts when being
// removed, also remove mount because it's saved in the player's
// save tag
level->removeEntityImmediately(player->riding);
app.DebugPrintf("removing player mount");
}
level->getTracker()->removeEntity(player);
level->removeEntity(player);
level->getChunkMap()->remove(player);
AUTO_VAR(it, find(players.begin(),players.end(),player));
@ -497,17 +507,30 @@ void PlayerList::remove(shared_ptr<ServerPlayer> player)
shared_ptr<ServerPlayer> PlayerList::getPlayerForLogin(PendingConnection *pendingConnection, const wstring& userName, PlayerUID xuid, PlayerUID onlineXuid)
{
if (players.size() >= maxPlayers)
#ifdef _WINDOWS64
if (players.size() >= (unsigned int)MINECRAFT_NET_MAX_PLAYERS)
#else
if (players.size() >= (unsigned int)maxPlayers)
#endif
{
pendingConnection->disconnect(DisconnectPacket::eDisconnect_ServerFull);
return shared_ptr<ServerPlayer>();
}
shared_ptr<ServerPlayer> player = shared_ptr<ServerPlayer>(new ServerPlayer(server, server->getLevel(0), userName, new ServerPlayerGameMode(server->getLevel(0)) ));
player->gameMode->player = player; // 4J added as had to remove this assignment from ServerPlayer ctor
player->setXuid( xuid ); // 4J Added
player->setOnlineXuid( onlineXuid ); // 4J Added
#ifdef _WINDOWS64
{
INetworkPlayer* np = pendingConnection->connection->getSocket()->getPlayer();
if (np != NULL)
{
PlayerUID realXuid = np->GetUID();
player->setXuid(realXuid);
player->setOnlineXuid(realXuid);
}
}
#endif
// Work out the base server player settings
INetworkPlayer *networkPlayer = pendingConnection->connection->getSocket()->getPlayer();
if(networkPlayer != NULL && !networkPlayer->IsHost())

View file

@ -1,18 +1,90 @@
#include "stdafx.h"
#include "Settings.h"
#include "../Minecraft.World/File.h"
#include "../Minecraft.World/StringHelpers.h"
#include <fstream>
static wstring ParsePropertyText(const string &text)
{
return trimString(convStringToWstring(text));
}
static bool TryParseBoolean(const wstring &text, bool defaultValue)
{
wstring lowered = toLower(trimString(text));
if (lowered == L"true" || lowered == L"1" || lowered == L"yes" || lowered == L"on")
return true;
if (lowered == L"false" || lowered == L"0" || lowered == L"no" || lowered == L"off")
return false;
return defaultValue;
}
// 4J - TODO - serialise/deserialise from file
Settings::Settings(File *file)
{
if (file != NULL)
{
filePath = file->getPath();
}
if (filePath.empty())
return;
std::ifstream stream(wstringtofilename(filePath), std::ios::in | std::ios::binary);
if (!stream.is_open())
return;
string line;
while (std::getline(stream, line))
{
if (!line.empty() && line[line.size() - 1] == '\r')
line.erase(line.size() - 1);
if (line.size() >= 3 &&
(unsigned char)line[0] == 0xEF &&
(unsigned char)line[1] == 0xBB &&
(unsigned char)line[2] == 0xBF)
{
line.erase(0, 3);
}
size_t commentPos = line.find_first_of("#;");
if (commentPos != string::npos && line.find_first_not_of(" \t") == commentPos)
continue;
size_t separatorPos = line.find('=');
if (separatorPos == string::npos)
continue;
wstring key = ParsePropertyText(line.substr(0, separatorPos));
if (key.empty())
continue;
wstring value = ParsePropertyText(line.substr(separatorPos + 1));
properties[key] = value;
}
}
void Settings::generateNewProperties()
{
saveProperties();
}
void Settings::saveProperties()
{
if (filePath.empty())
return;
std::ofstream stream(wstringtofilename(filePath), std::ios::out | std::ios::binary | std::ios::trunc);
if (!stream.is_open())
return;
stream << "# MinecraftConsoles dedicated server properties\r\n";
for (unordered_map<wstring, wstring>::const_iterator it = properties.begin(); it != properties.end(); ++it)
{
string key = string(wstringtochararray(it->first));
string value = string(wstringtochararray(it->second));
stream << key << "=" << value << "\r\n";
}
}
wstring Settings::getString(const wstring& key, const wstring& defaultValue)
@ -39,17 +111,17 @@ bool Settings::getBoolean(const wstring& key, bool defaultValue)
{
if(properties.find(key) == properties.end())
{
properties[key] = _toString<bool>(defaultValue);
properties[key] = defaultValue ? L"true" : L"false";
saveProperties();
}
MemSect(35);
bool retval = _fromString<bool>(properties[key]);
bool retval = TryParseBoolean(properties[key], defaultValue);
MemSect(0);
return retval;
}
void Settings::setBooleanAndSave(const wstring& key, bool value)
{
properties[key] = _toString<bool>(value);
properties[key] = value ? L"true" : L"false";
saveProperties();
}
}

View file

@ -7,8 +7,8 @@ class Settings
// public static Logger logger = Logger.getLogger("Minecraft");
// private Properties properties = new Properties();
private:
unordered_map<wstring,wstring> properties; // 4J - TODO was Properties type, will need to implement something we can serialise/deserialise too
//File *file;
unordered_map<wstring,wstring> properties;
wstring filePath;
public:
Settings(File *file);
@ -18,4 +18,4 @@ public:
int getInt(const wstring& key, int defaultValue);
bool getBoolean(const wstring& key, bool defaultValue);
void setBooleanAndSave(const wstring& key, bool value);
};
};

View file

@ -424,12 +424,109 @@ void Textures::bindTextureLayers(ResourceLocation *resource)
{
assert(resource->isPreloaded());
// Hack: 4JLibs on Windows does not currently reproduce Minecraft's layered horse texture path reliably.
// Merge the layers on the CPU and bind the cached result as a normal single texture instead.
wstring cacheKey = L"%layered%";
int layers = resource->getTextureCount();
for( int i = 0; i < layers; i++ )
{
RenderManager.TextureBind(loadTexture(resource->getTexture(i)));
cacheKey += std::to_wstring(resource->getTexture(i));
cacheKey += L"/";
}
int id = -1;
bool inMap = ( idMap.find(cacheKey) != idMap.end() );
if( inMap )
{
id = idMap[cacheKey];
}
else
{
// Cache by layer signature so the merge cost is only paid once per horse texture combination.
intArray mergedPixels;
int mergedWidth = 0;
int mergedHeight = 0;
bool hasMergedPixels = false;
for( int i = 0; i < layers; i++ )
{
TEXTURE_NAME textureName = resource->getTexture(i);
if( textureName == (_TEXTURE_NAME)-1 )
{
continue;
}
wstring resourceName = wstring(preLoaded[textureName]) + L".png";
BufferedImage *image = readImage(textureName, resourceName);
if( image == NULL )
{
continue;
}
int width = image->getWidth();
int height = image->getHeight();
intArray layerPixels = loadTexturePixels(image);
delete image;
if( !hasMergedPixels )
{
mergedWidth = width;
mergedHeight = height;
mergedPixels = intArray(width * height);
memcpy(mergedPixels.data, layerPixels.data, width * height * sizeof(int));
hasMergedPixels = true;
}
else if( width == mergedWidth && height == mergedHeight )
{
for( int p = 0; p < width * height; p++ )
{
int dst = mergedPixels[p];
int src = layerPixels[p];
float srcAlpha = ((src >> 24) & 0xff) / 255.0f;
if( srcAlpha <= 0.0f )
{
continue;
}
float dstAlpha = ((dst >> 24) & 0xff) / 255.0f;
float outAlpha = srcAlpha + dstAlpha * (1.0f - srcAlpha);
if( outAlpha <= 0.0f )
{
mergedPixels[p] = 0;
continue;
}
float srcFactor = srcAlpha / outAlpha;
float dstFactor = (dstAlpha * (1.0f - srcAlpha)) / outAlpha;
int outA = (int)(outAlpha * 255.0f + 0.5f);
int outR = (int)((((src >> 16) & 0xff) * srcFactor) + (((dst >> 16) & 0xff) * dstFactor) + 0.5f);
int outG = (int)((((src >> 8) & 0xff) * srcFactor) + (((dst >> 8) & 0xff) * dstFactor) + 0.5f);
int outB = (int)(((src & 0xff) * srcFactor) + ((dst & 0xff) * dstFactor) + 0.5f);
mergedPixels[p] = (outA << 24) | (outR << 16) | (outG << 8) | outB;
}
}
delete[] layerPixels.data;
}
if( hasMergedPixels )
{
BufferedImage *mergedImage = new BufferedImage(mergedWidth, mergedHeight, BufferedImage::TYPE_INT_ARGB);
memcpy(mergedImage->getData(), mergedPixels.data, mergedWidth * mergedHeight * sizeof(int));
delete[] mergedPixels.data;
id = getTexture(mergedImage, C4JRender::TEXTURE_FORMAT_RxGyBzAw, false);
}
else
{
id = 0;
}
idMap[cacheKey] = id;
}
RenderManager.TextureBind(id);
}
void Textures::bind(int id)

View file

@ -103,6 +103,7 @@ void KeyboardMouseInput::OnRawMouseInput(LPARAM lParam)
void KeyboardMouseInput::OnMouseButton(int button, bool down)
{
if (ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad())) { return; }
if (button >= 0 && button < 3)
{
if (down && !m_mouseButtons[button]) m_mousePressedAccum[button] = true;

View file

@ -0,0 +1,920 @@
// Code implemented by LCEMP, credit if used on other repos
// https://github.com/LCEMP/LCEMP
#include "stdafx.h"
#ifdef _WINDOWS64
#include "WinsockNetLayer.h"
#include "..\..\Common\Network\PlatformNetworkManagerStub.h"
#include "..\..\..\Minecraft.World\Socket.h"
SOCKET WinsockNetLayer::s_listenSocket = INVALID_SOCKET;
SOCKET WinsockNetLayer::s_hostConnectionSocket = INVALID_SOCKET;
HANDLE WinsockNetLayer::s_acceptThread = NULL;
HANDLE WinsockNetLayer::s_clientRecvThread = NULL;
bool WinsockNetLayer::s_isHost = false;
bool WinsockNetLayer::s_connected = false;
bool WinsockNetLayer::s_active = false;
bool WinsockNetLayer::s_initialized = false;
BYTE WinsockNetLayer::s_localSmallId = 0;
BYTE WinsockNetLayer::s_hostSmallId = 0;
BYTE WinsockNetLayer::s_nextSmallId = 1;
CRITICAL_SECTION WinsockNetLayer::s_sendLock;
CRITICAL_SECTION WinsockNetLayer::s_connectionsLock;
std::vector<Win64RemoteConnection> WinsockNetLayer::s_connections;
SOCKET WinsockNetLayer::s_advertiseSock = INVALID_SOCKET;
HANDLE WinsockNetLayer::s_advertiseThread = NULL;
volatile bool WinsockNetLayer::s_advertising = false;
Win64LANBroadcast WinsockNetLayer::s_advertiseData = {};
CRITICAL_SECTION WinsockNetLayer::s_advertiseLock;
int WinsockNetLayer::s_hostGamePort = WIN64_NET_DEFAULT_PORT;
SOCKET WinsockNetLayer::s_discoverySock = INVALID_SOCKET;
HANDLE WinsockNetLayer::s_discoveryThread = NULL;
volatile bool WinsockNetLayer::s_discovering = false;
CRITICAL_SECTION WinsockNetLayer::s_discoveryLock;
std::vector<Win64LANSession> WinsockNetLayer::s_discoveredSessions;
CRITICAL_SECTION WinsockNetLayer::s_disconnectLock;
std::vector<BYTE> WinsockNetLayer::s_disconnectedSmallIds;
CRITICAL_SECTION WinsockNetLayer::s_freeSmallIdLock;
std::vector<BYTE> WinsockNetLayer::s_freeSmallIds;
bool g_Win64MultiplayerHost = false;
bool g_Win64MultiplayerJoin = false;
int g_Win64MultiplayerPort = WIN64_NET_DEFAULT_PORT;
char g_Win64MultiplayerIP[256] = "127.0.0.1";
bool g_Win64DedicatedServer = false;
int g_Win64DedicatedServerPort = WIN64_NET_DEFAULT_PORT;
char g_Win64DedicatedServerBindIP[256] = "";
bool WinsockNetLayer::Initialize()
{
if (s_initialized) return true;
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0)
{
app.DebugPrintf("WSAStartup failed: %d\n", result);
return false;
}
InitializeCriticalSection(&s_sendLock);
InitializeCriticalSection(&s_connectionsLock);
InitializeCriticalSection(&s_advertiseLock);
InitializeCriticalSection(&s_discoveryLock);
InitializeCriticalSection(&s_disconnectLock);
InitializeCriticalSection(&s_freeSmallIdLock);
s_initialized = true;
StartDiscovery();
return true;
}
void WinsockNetLayer::Shutdown()
{
StopAdvertising();
StopDiscovery();
s_active = false;
s_connected = false;
if (s_listenSocket != INVALID_SOCKET)
{
closesocket(s_listenSocket);
s_listenSocket = INVALID_SOCKET;
}
if (s_hostConnectionSocket != INVALID_SOCKET)
{
closesocket(s_hostConnectionSocket);
s_hostConnectionSocket = INVALID_SOCKET;
}
EnterCriticalSection(&s_connectionsLock);
for (size_t i = 0; i < s_connections.size(); i++)
{
s_connections[i].active = false;
if (s_connections[i].tcpSocket != INVALID_SOCKET)
{
closesocket(s_connections[i].tcpSocket);
}
}
s_connections.clear();
LeaveCriticalSection(&s_connectionsLock);
if (s_acceptThread != NULL)
{
WaitForSingleObject(s_acceptThread, 2000);
CloseHandle(s_acceptThread);
s_acceptThread = NULL;
}
if (s_clientRecvThread != NULL)
{
WaitForSingleObject(s_clientRecvThread, 2000);
CloseHandle(s_clientRecvThread);
s_clientRecvThread = NULL;
}
if (s_initialized)
{
DeleteCriticalSection(&s_sendLock);
DeleteCriticalSection(&s_connectionsLock);
DeleteCriticalSection(&s_advertiseLock);
DeleteCriticalSection(&s_discoveryLock);
DeleteCriticalSection(&s_disconnectLock);
s_disconnectedSmallIds.clear();
DeleteCriticalSection(&s_freeSmallIdLock);
s_freeSmallIds.clear();
WSACleanup();
s_initialized = false;
}
}
bool WinsockNetLayer::HostGame(int port, const char* bindIp)
{
if (!s_initialized && !Initialize()) return false;
s_isHost = true;
s_localSmallId = 0;
s_hostSmallId = 0;
s_nextSmallId = 1;
s_hostGamePort = port;
EnterCriticalSection(&s_freeSmallIdLock);
s_freeSmallIds.clear();
LeaveCriticalSection(&s_freeSmallIdLock);
struct addrinfo hints = {};
struct addrinfo* result = NULL;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = (bindIp == NULL || bindIp[0] == 0) ? AI_PASSIVE : 0;
char portStr[16];
sprintf_s(portStr, "%d", port);
const char* resolvedBindIp = (bindIp != NULL && bindIp[0] != 0) ? bindIp : NULL;
int iResult = getaddrinfo(resolvedBindIp, portStr, &hints, &result);
if (iResult != 0)
{
app.DebugPrintf("getaddrinfo failed for %s:%d - %d\n",
resolvedBindIp != NULL ? resolvedBindIp : "*",
port,
iResult);
return false;
}
s_listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (s_listenSocket == INVALID_SOCKET)
{
app.DebugPrintf("socket() failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
return false;
}
int opt = 1;
setsockopt(s_listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
iResult = ::bind(s_listenSocket, result->ai_addr, (int)result->ai_addrlen);
freeaddrinfo(result);
if (iResult == SOCKET_ERROR)
{
app.DebugPrintf("bind() failed: %d\n", WSAGetLastError());
closesocket(s_listenSocket);
s_listenSocket = INVALID_SOCKET;
return false;
}
iResult = listen(s_listenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR)
{
app.DebugPrintf("listen() failed: %d\n", WSAGetLastError());
closesocket(s_listenSocket);
s_listenSocket = INVALID_SOCKET;
return false;
}
s_active = true;
s_connected = true;
s_acceptThread = CreateThread(NULL, 0, AcceptThreadProc, NULL, 0, NULL);
app.DebugPrintf("Win64 LAN: Hosting on %s:%d\n",
resolvedBindIp != NULL ? resolvedBindIp : "*",
port);
return true;
}
bool WinsockNetLayer::JoinGame(const char* ip, int port)
{
if (!s_initialized && !Initialize()) return false;
s_isHost = false;
s_hostSmallId = 0;
s_connected = false;
s_active = false;
if (s_hostConnectionSocket != INVALID_SOCKET)
{
closesocket(s_hostConnectionSocket);
s_hostConnectionSocket = INVALID_SOCKET;
}
struct addrinfo hints = {};
struct addrinfo* result = NULL;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
char portStr[16];
sprintf_s(portStr, "%d", port);
int iResult = getaddrinfo(ip, portStr, &hints, &result);
if (iResult != 0)
{
app.DebugPrintf("getaddrinfo failed for %s:%d - %d\n", ip, port, iResult);
return false;
}
bool connected = false;
BYTE assignedSmallId = 0;
const int maxAttempts = 12;
for (int attempt = 0; attempt < maxAttempts; ++attempt)
{
s_hostConnectionSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (s_hostConnectionSocket == INVALID_SOCKET)
{
app.DebugPrintf("socket() failed: %d\n", WSAGetLastError());
break;
}
int noDelay = 1;
setsockopt(s_hostConnectionSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay));
iResult = connect(s_hostConnectionSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
int err = WSAGetLastError();
app.DebugPrintf("connect() to %s:%d failed (attempt %d/%d): %d\n", ip, port, attempt + 1, maxAttempts, err);
closesocket(s_hostConnectionSocket);
s_hostConnectionSocket = INVALID_SOCKET;
Sleep(200);
continue;
}
BYTE assignBuf[1];
int bytesRecv = recv(s_hostConnectionSocket, (char*)assignBuf, 1, 0);
if (bytesRecv != 1)
{
app.DebugPrintf("Failed to receive small ID assignment from host (attempt %d/%d)\n", attempt + 1, maxAttempts);
closesocket(s_hostConnectionSocket);
s_hostConnectionSocket = INVALID_SOCKET;
Sleep(200);
continue;
}
assignedSmallId = assignBuf[0];
connected = true;
break;
}
freeaddrinfo(result);
if (!connected)
{
return false;
}
s_localSmallId = assignedSmallId;
app.DebugPrintf("Win64 LAN: Connected to %s:%d, assigned smallId=%d\n", ip, port, s_localSmallId);
s_active = true;
s_connected = true;
s_clientRecvThread = CreateThread(NULL, 0, ClientRecvThreadProc, NULL, 0, NULL);
return true;
}
bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void* data, int dataSize)
{
if (sock == INVALID_SOCKET || dataSize <= 0) return false;
EnterCriticalSection(&s_sendLock);
BYTE header[4];
header[0] = (BYTE)((dataSize >> 24) & 0xFF);
header[1] = (BYTE)((dataSize >> 16) & 0xFF);
header[2] = (BYTE)((dataSize >> 8) & 0xFF);
header[3] = (BYTE)(dataSize & 0xFF);
int totalSent = 0;
int toSend = 4;
while (totalSent < toSend)
{
int sent = send(sock, (const char*)header + totalSent, toSend - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0)
{
LeaveCriticalSection(&s_sendLock);
return false;
}
totalSent += sent;
}
totalSent = 0;
while (totalSent < dataSize)
{
int sent = send(sock, (const char*)data + totalSent, dataSize - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0)
{
LeaveCriticalSection(&s_sendLock);
return false;
}
totalSent += sent;
}
LeaveCriticalSection(&s_sendLock);
return true;
}
bool WinsockNetLayer::SendToSmallId(BYTE targetSmallId, const void* data, int dataSize)
{
if (!s_active) return false;
if (s_isHost)
{
SOCKET sock = GetSocketForSmallId(targetSmallId);
if (sock == INVALID_SOCKET) return false;
return SendOnSocket(sock, data, dataSize);
}
else
{
return SendOnSocket(s_hostConnectionSocket, data, dataSize);
}
}
SOCKET WinsockNetLayer::GetSocketForSmallId(BYTE smallId)
{
EnterCriticalSection(&s_connectionsLock);
for (size_t i = 0; i < s_connections.size(); i++)
{
if (s_connections[i].smallId == smallId && s_connections[i].active)
{
SOCKET sock = s_connections[i].tcpSocket;
LeaveCriticalSection(&s_connectionsLock);
return sock;
}
}
LeaveCriticalSection(&s_connectionsLock);
return INVALID_SOCKET;
}
static bool RecvExact(SOCKET sock, BYTE* buf, int len)
{
int totalRecv = 0;
while (totalRecv < len)
{
int r = recv(sock, (char*)buf + totalRecv, len - totalRecv, 0);
if (r <= 0) return false;
totalRecv += r;
}
return true;
}
void WinsockNetLayer::HandleDataReceived(BYTE fromSmallId, BYTE toSmallId, unsigned char* data, unsigned int dataSize)
{
INetworkPlayer* pPlayerFrom = g_NetworkManager.GetPlayerBySmallId(fromSmallId);
INetworkPlayer* pPlayerTo = g_NetworkManager.GetPlayerBySmallId(toSmallId);
if (pPlayerFrom == NULL || pPlayerTo == NULL) return;
if (s_isHost)
{
::Socket* pSocket = pPlayerFrom->GetSocket();
if (pSocket != NULL)
pSocket->pushDataToQueue(data, dataSize, false);
}
else
{
::Socket* pSocket = pPlayerTo->GetSocket();
if (pSocket != NULL)
pSocket->pushDataToQueue(data, dataSize, true);
}
}
DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param)
{
while (s_active)
{
SOCKET clientSocket = accept(s_listenSocket, NULL, NULL);
if (clientSocket == INVALID_SOCKET)
{
if (s_active)
app.DebugPrintf("accept() failed: %d\n", WSAGetLastError());
break;
}
int noDelay = 1;
setsockopt(clientSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay));
extern QNET_STATE _iQNetStubState;
if (_iQNetStubState != QNET_STATE_GAME_PLAY)
{
app.DebugPrintf("Win64 LAN: Rejecting connection, game not ready\n");
closesocket(clientSocket);
continue;
}
BYTE assignedSmallId;
EnterCriticalSection(&s_freeSmallIdLock);
if (!s_freeSmallIds.empty())
{
assignedSmallId = s_freeSmallIds.back();
s_freeSmallIds.pop_back();
}
else if (s_nextSmallId < MINECRAFT_NET_MAX_PLAYERS)
{
assignedSmallId = s_nextSmallId++;
}
else
{
LeaveCriticalSection(&s_freeSmallIdLock);
app.DebugPrintf("Win64 LAN: Server full, rejecting connection\n");
closesocket(clientSocket);
continue;
}
LeaveCriticalSection(&s_freeSmallIdLock);
BYTE assignBuf[1] = { assignedSmallId };
int sent = send(clientSocket, (const char*)assignBuf, 1, 0);
if (sent != 1)
{
app.DebugPrintf("Failed to send small ID to client\n");
closesocket(clientSocket);
continue;
}
Win64RemoteConnection conn;
conn.tcpSocket = clientSocket;
conn.smallId = assignedSmallId;
conn.active = true;
conn.recvThread = NULL;
EnterCriticalSection(&s_connectionsLock);
s_connections.push_back(conn);
int connIdx = (int)s_connections.size() - 1;
LeaveCriticalSection(&s_connectionsLock);
app.DebugPrintf("Win64 LAN: Client connected, assigned smallId=%d\n", assignedSmallId);
IQNetPlayer* qnetPlayer = &IQNet::m_player[assignedSmallId];
extern void Win64_SetupRemoteQNetPlayer(IQNetPlayer * player, BYTE smallId, bool isHost, bool isLocal);
Win64_SetupRemoteQNetPlayer(qnetPlayer, assignedSmallId, false, false);
extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager;
g_pPlatformNetworkManager->NotifyPlayerJoined(qnetPlayer);
DWORD* threadParam = new DWORD;
*threadParam = connIdx;
HANDLE hThread = CreateThread(NULL, 0, RecvThreadProc, threadParam, 0, NULL);
EnterCriticalSection(&s_connectionsLock);
if (connIdx < (int)s_connections.size())
s_connections[connIdx].recvThread = hThread;
LeaveCriticalSection(&s_connectionsLock);
}
return 0;
}
DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param)
{
DWORD connIdx = *(DWORD*)param;
delete (DWORD*)param;
EnterCriticalSection(&s_connectionsLock);
if (connIdx >= (DWORD)s_connections.size())
{
LeaveCriticalSection(&s_connectionsLock);
return 0;
}
SOCKET sock = s_connections[connIdx].tcpSocket;
BYTE clientSmallId = s_connections[connIdx].smallId;
LeaveCriticalSection(&s_connectionsLock);
std::vector<BYTE> recvBuf;
recvBuf.resize(WIN64_NET_RECV_BUFFER_SIZE);
while (s_active)
{
BYTE header[4];
if (!RecvExact(sock, header, 4))
{
app.DebugPrintf("Win64 LAN: Client smallId=%d disconnected (header)\n", clientSmallId);
break;
}
int packetSize =
((uint32_t)header[0] << 24) |
((uint32_t)header[1] << 16) |
((uint32_t)header[2] << 8) |
((uint32_t)header[3]);
if (packetSize <= 0 || packetSize > WIN64_NET_MAX_PACKET_SIZE)
{
app.DebugPrintf("Win64 LAN: Invalid packet size %d from client smallId=%d (max=%d)\n",
packetSize,
clientSmallId,
(int)WIN64_NET_MAX_PACKET_SIZE);
break;
}
if ((int)recvBuf.size() < packetSize)
{
recvBuf.resize(packetSize);
app.DebugPrintf("Win64 LAN: Resized host recv buffer to %d bytes for client smallId=%d\n", packetSize, clientSmallId);
}
if (!RecvExact(sock, &recvBuf[0], packetSize))
{
app.DebugPrintf("Win64 LAN: Client smallId=%d disconnected (body)\n", clientSmallId);
break;
}
HandleDataReceived(clientSmallId, s_hostSmallId, &recvBuf[0], packetSize);
}
EnterCriticalSection(&s_connectionsLock);
for (size_t i = 0; i < s_connections.size(); i++)
{
if (s_connections[i].smallId == clientSmallId)
{
s_connections[i].active = false;
if (s_connections[i].tcpSocket != INVALID_SOCKET)
{
closesocket(s_connections[i].tcpSocket);
s_connections[i].tcpSocket = INVALID_SOCKET;
}
break;
}
}
LeaveCriticalSection(&s_connectionsLock);
EnterCriticalSection(&s_disconnectLock);
s_disconnectedSmallIds.push_back(clientSmallId);
LeaveCriticalSection(&s_disconnectLock);
return 0;
}
bool WinsockNetLayer::PopDisconnectedSmallId(BYTE* outSmallId)
{
bool found = false;
EnterCriticalSection(&s_disconnectLock);
if (!s_disconnectedSmallIds.empty())
{
*outSmallId = s_disconnectedSmallIds.back();
s_disconnectedSmallIds.pop_back();
found = true;
}
LeaveCriticalSection(&s_disconnectLock);
return found;
}
void WinsockNetLayer::PushFreeSmallId(BYTE smallId)
{
EnterCriticalSection(&s_freeSmallIdLock);
s_freeSmallIds.push_back(smallId);
LeaveCriticalSection(&s_freeSmallIdLock);
}
void WinsockNetLayer::CloseConnectionBySmallId(BYTE smallId)
{
EnterCriticalSection(&s_connectionsLock);
for (size_t i = 0; i < s_connections.size(); i++)
{
if (s_connections[i].smallId == smallId && s_connections[i].active && s_connections[i].tcpSocket != INVALID_SOCKET)
{
closesocket(s_connections[i].tcpSocket);
s_connections[i].tcpSocket = INVALID_SOCKET;
app.DebugPrintf("Win64 LAN: Force-closed TCP connection for smallId=%d\n", smallId);
break;
}
}
LeaveCriticalSection(&s_connectionsLock);
}
DWORD WINAPI WinsockNetLayer::ClientRecvThreadProc(LPVOID param)
{
std::vector<BYTE> recvBuf;
recvBuf.resize(WIN64_NET_RECV_BUFFER_SIZE);
while (s_active && s_hostConnectionSocket != INVALID_SOCKET)
{
BYTE header[4];
if (!RecvExact(s_hostConnectionSocket, header, 4))
{
app.DebugPrintf("Win64 LAN: Disconnected from host (header)\n");
break;
}
int packetSize = (header[0] << 24) | (header[1] << 16) | (header[2] << 8) | header[3];
if (packetSize <= 0 || packetSize > WIN64_NET_MAX_PACKET_SIZE)
{
app.DebugPrintf("Win64 LAN: Invalid packet size %d from host (max=%d)\n",
packetSize,
(int)WIN64_NET_MAX_PACKET_SIZE);
break;
}
if ((int)recvBuf.size() < packetSize)
{
recvBuf.resize(packetSize);
app.DebugPrintf("Win64 LAN: Resized client recv buffer to %d bytes\n", packetSize);
}
if (!RecvExact(s_hostConnectionSocket, &recvBuf[0], packetSize))
{
app.DebugPrintf("Win64 LAN: Disconnected from host (body)\n");
break;
}
HandleDataReceived(s_hostSmallId, s_localSmallId, &recvBuf[0], packetSize);
}
s_connected = false;
return 0;
}
bool WinsockNetLayer::StartAdvertising(int gamePort, const wchar_t* hostName, unsigned int gameSettings, unsigned int texPackId, unsigned char subTexId, unsigned short netVer)
{
if (s_advertising) return true;
if (!s_initialized) return false;
EnterCriticalSection(&s_advertiseLock);
memset(&s_advertiseData, 0, sizeof(s_advertiseData));
s_advertiseData.magic = WIN64_LAN_BROADCAST_MAGIC;
s_advertiseData.netVersion = netVer;
s_advertiseData.gamePort = (WORD)gamePort;
wcsncpy_s(s_advertiseData.hostName, 32, hostName, _TRUNCATE);
s_advertiseData.playerCount = 1;
s_advertiseData.maxPlayers = MINECRAFT_NET_MAX_PLAYERS;
s_advertiseData.gameHostSettings = gameSettings;
s_advertiseData.texturePackParentId = texPackId;
s_advertiseData.subTexturePackId = subTexId;
s_advertiseData.isJoinable = 0;
s_hostGamePort = gamePort;
LeaveCriticalSection(&s_advertiseLock);
s_advertiseSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s_advertiseSock == INVALID_SOCKET)
{
app.DebugPrintf("Win64 LAN: Failed to create advertise socket: %d\n", WSAGetLastError());
return false;
}
BOOL broadcast = TRUE;
setsockopt(s_advertiseSock, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast));
s_advertising = true;
s_advertiseThread = CreateThread(NULL, 0, AdvertiseThreadProc, NULL, 0, NULL);
app.DebugPrintf("Win64 LAN: Started advertising on UDP port %d\n", WIN64_LAN_DISCOVERY_PORT);
return true;
}
void WinsockNetLayer::StopAdvertising()
{
s_advertising = false;
if (s_advertiseSock != INVALID_SOCKET)
{
closesocket(s_advertiseSock);
s_advertiseSock = INVALID_SOCKET;
}
if (s_advertiseThread != NULL)
{
WaitForSingleObject(s_advertiseThread, 2000);
CloseHandle(s_advertiseThread);
s_advertiseThread = NULL;
}
}
void WinsockNetLayer::UpdateAdvertisePlayerCount(BYTE count)
{
EnterCriticalSection(&s_advertiseLock);
s_advertiseData.playerCount = count;
LeaveCriticalSection(&s_advertiseLock);
}
void WinsockNetLayer::UpdateAdvertiseJoinable(bool joinable)
{
EnterCriticalSection(&s_advertiseLock);
s_advertiseData.isJoinable = joinable ? 1 : 0;
LeaveCriticalSection(&s_advertiseLock);
}
DWORD WINAPI WinsockNetLayer::AdvertiseThreadProc(LPVOID param)
{
struct sockaddr_in broadcastAddr;
memset(&broadcastAddr, 0, sizeof(broadcastAddr));
broadcastAddr.sin_family = AF_INET;
broadcastAddr.sin_port = htons(WIN64_LAN_DISCOVERY_PORT);
broadcastAddr.sin_addr.s_addr = INADDR_BROADCAST;
while (s_advertising)
{
EnterCriticalSection(&s_advertiseLock);
Win64LANBroadcast data = s_advertiseData;
LeaveCriticalSection(&s_advertiseLock);
int sent = sendto(s_advertiseSock, (const char*)&data, sizeof(data), 0,
(struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr));
if (sent == SOCKET_ERROR && s_advertising)
{
app.DebugPrintf("Win64 LAN: Broadcast sendto failed: %d\n", WSAGetLastError());
}
Sleep(1000);
}
return 0;
}
bool WinsockNetLayer::StartDiscovery()
{
if (s_discovering) return true;
if (!s_initialized) return false;
s_discoverySock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s_discoverySock == INVALID_SOCKET)
{
app.DebugPrintf("Win64 LAN: Failed to create discovery socket: %d\n", WSAGetLastError());
return false;
}
BOOL reuseAddr = TRUE;
setsockopt(s_discoverySock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuseAddr, sizeof(reuseAddr));
struct sockaddr_in bindAddr;
memset(&bindAddr, 0, sizeof(bindAddr));
bindAddr.sin_family = AF_INET;
bindAddr.sin_port = htons(WIN64_LAN_DISCOVERY_PORT);
bindAddr.sin_addr.s_addr = INADDR_ANY;
if (::bind(s_discoverySock, (struct sockaddr*)&bindAddr, sizeof(bindAddr)) == SOCKET_ERROR)
{
app.DebugPrintf("Win64 LAN: Discovery bind failed: %d\n", WSAGetLastError());
closesocket(s_discoverySock);
s_discoverySock = INVALID_SOCKET;
return false;
}
DWORD timeout = 500;
setsockopt(s_discoverySock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
s_discovering = true;
s_discoveryThread = CreateThread(NULL, 0, DiscoveryThreadProc, NULL, 0, NULL);
app.DebugPrintf("Win64 LAN: Listening for LAN games on UDP port %d\n", WIN64_LAN_DISCOVERY_PORT);
return true;
}
void WinsockNetLayer::StopDiscovery()
{
s_discovering = false;
if (s_discoverySock != INVALID_SOCKET)
{
closesocket(s_discoverySock);
s_discoverySock = INVALID_SOCKET;
}
if (s_discoveryThread != NULL)
{
WaitForSingleObject(s_discoveryThread, 2000);
CloseHandle(s_discoveryThread);
s_discoveryThread = NULL;
}
EnterCriticalSection(&s_discoveryLock);
s_discoveredSessions.clear();
LeaveCriticalSection(&s_discoveryLock);
}
std::vector<Win64LANSession> WinsockNetLayer::GetDiscoveredSessions()
{
std::vector<Win64LANSession> result;
EnterCriticalSection(&s_discoveryLock);
result = s_discoveredSessions;
LeaveCriticalSection(&s_discoveryLock);
return result;
}
DWORD WINAPI WinsockNetLayer::DiscoveryThreadProc(LPVOID param)
{
char recvBuf[512];
while (s_discovering)
{
struct sockaddr_in senderAddr;
int senderLen = sizeof(senderAddr);
int recvLen = recvfrom(s_discoverySock, recvBuf, sizeof(recvBuf), 0,
(struct sockaddr*)&senderAddr, &senderLen);
if (recvLen == SOCKET_ERROR)
{
continue;
}
if (recvLen < (int)sizeof(Win64LANBroadcast))
continue;
Win64LANBroadcast* broadcast = (Win64LANBroadcast*)recvBuf;
if (broadcast->magic != WIN64_LAN_BROADCAST_MAGIC)
continue;
char senderIP[64];
inet_ntop(AF_INET, &senderAddr.sin_addr, senderIP, sizeof(senderIP));
DWORD now = GetTickCount();
EnterCriticalSection(&s_discoveryLock);
bool found = false;
for (size_t i = 0; i < s_discoveredSessions.size(); i++)
{
if (strcmp(s_discoveredSessions[i].hostIP, senderIP) == 0 &&
s_discoveredSessions[i].hostPort == (int)broadcast->gamePort)
{
s_discoveredSessions[i].netVersion = broadcast->netVersion;
wcsncpy_s(s_discoveredSessions[i].hostName, 32, broadcast->hostName, _TRUNCATE);
s_discoveredSessions[i].playerCount = broadcast->playerCount;
s_discoveredSessions[i].maxPlayers = broadcast->maxPlayers;
s_discoveredSessions[i].gameHostSettings = broadcast->gameHostSettings;
s_discoveredSessions[i].texturePackParentId = broadcast->texturePackParentId;
s_discoveredSessions[i].subTexturePackId = broadcast->subTexturePackId;
s_discoveredSessions[i].isJoinable = (broadcast->isJoinable != 0);
s_discoveredSessions[i].lastSeenTick = now;
found = true;
break;
}
}
if (!found)
{
Win64LANSession session;
memset(&session, 0, sizeof(session));
strncpy_s(session.hostIP, sizeof(session.hostIP), senderIP, _TRUNCATE);
session.hostPort = (int)broadcast->gamePort;
session.netVersion = broadcast->netVersion;
wcsncpy_s(session.hostName, 32, broadcast->hostName, _TRUNCATE);
session.playerCount = broadcast->playerCount;
session.maxPlayers = broadcast->maxPlayers;
session.gameHostSettings = broadcast->gameHostSettings;
session.texturePackParentId = broadcast->texturePackParentId;
session.subTexturePackId = broadcast->subTexturePackId;
session.isJoinable = (broadcast->isJoinable != 0);
session.lastSeenTick = now;
s_discoveredSessions.push_back(session);
app.DebugPrintf("Win64 LAN: Discovered game \"%ls\" at %s:%d\n",
session.hostName, session.hostIP, session.hostPort);
}
for (size_t i = s_discoveredSessions.size(); i > 0; i--)
{
if (now - s_discoveredSessions[i - 1].lastSeenTick > 5000)
{
app.DebugPrintf("Win64 LAN: Session \"%ls\" at %s timed out\n",
s_discoveredSessions[i - 1].hostName, s_discoveredSessions[i - 1].hostIP);
s_discoveredSessions.erase(s_discoveredSessions.begin() + (i - 1));
}
}
LeaveCriticalSection(&s_discoveryLock);
}
return 0;
}
#endif

View file

@ -0,0 +1,154 @@
// Code implemented by LCEMP, credit if used on other repos
// https://github.com/LCEMP/LCEMP
#pragma once
#ifdef _WINDOWS64
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <vector>
#include "..\..\Common\Network\NetworkPlayerInterface.h"
#pragma comment(lib, "Ws2_32.lib")
#define WIN64_NET_DEFAULT_PORT 25565
#define WIN64_NET_MAX_CLIENTS 7
#define WIN64_NET_RECV_BUFFER_SIZE 65536
#define WIN64_NET_MAX_PACKET_SIZE (4 * 1024 * 1024)
#define WIN64_LAN_DISCOVERY_PORT 25566
#define WIN64_LAN_BROADCAST_MAGIC 0x4D434C4E
class Socket;
#pragma pack(push, 1)
struct Win64LANBroadcast
{
DWORD magic;
WORD netVersion;
WORD gamePort;
wchar_t hostName[32];
BYTE playerCount;
BYTE maxPlayers;
DWORD gameHostSettings;
DWORD texturePackParentId;
BYTE subTexturePackId;
BYTE isJoinable;
};
#pragma pack(pop)
struct Win64LANSession
{
char hostIP[64];
int hostPort;
wchar_t hostName[32];
unsigned short netVersion;
unsigned char playerCount;
unsigned char maxPlayers;
unsigned int gameHostSettings;
unsigned int texturePackParentId;
unsigned char subTexturePackId;
bool isJoinable;
DWORD lastSeenTick;
};
struct Win64RemoteConnection
{
SOCKET tcpSocket;
BYTE smallId;
HANDLE recvThread;
volatile bool active;
};
class WinsockNetLayer
{
public:
static bool Initialize();
static void Shutdown();
static bool HostGame(int port, const char* bindIp = NULL);
static bool JoinGame(const char* ip, int port);
static bool SendToSmallId(BYTE targetSmallId, const void* data, int dataSize);
static bool SendOnSocket(SOCKET sock, const void* data, int dataSize);
static bool IsHosting() { return s_isHost; }
static bool IsConnected() { return s_connected; }
static bool IsActive() { return s_active; }
static BYTE GetLocalSmallId() { return s_localSmallId; }
static BYTE GetHostSmallId() { return s_hostSmallId; }
static SOCKET GetSocketForSmallId(BYTE smallId);
static void HandleDataReceived(BYTE fromSmallId, BYTE toSmallId, unsigned char* data, unsigned int dataSize);
static bool PopDisconnectedSmallId(BYTE* outSmallId);
static void PushFreeSmallId(BYTE smallId);
static void CloseConnectionBySmallId(BYTE smallId);
static bool StartAdvertising(int gamePort, const wchar_t* hostName, unsigned int gameSettings, unsigned int texPackId, unsigned char subTexId, unsigned short netVer);
static void StopAdvertising();
static void UpdateAdvertisePlayerCount(BYTE count);
static void UpdateAdvertiseJoinable(bool joinable);
static bool StartDiscovery();
static void StopDiscovery();
static std::vector<Win64LANSession> GetDiscoveredSessions();
static int GetHostPort() { return s_hostGamePort; }
private:
static DWORD WINAPI AcceptThreadProc(LPVOID param);
static DWORD WINAPI RecvThreadProc(LPVOID param);
static DWORD WINAPI ClientRecvThreadProc(LPVOID param);
static DWORD WINAPI AdvertiseThreadProc(LPVOID param);
static DWORD WINAPI DiscoveryThreadProc(LPVOID param);
static SOCKET s_listenSocket;
static SOCKET s_hostConnectionSocket;
static HANDLE s_acceptThread;
static HANDLE s_clientRecvThread;
static bool s_isHost;
static bool s_connected;
static bool s_active;
static bool s_initialized;
static BYTE s_localSmallId;
static BYTE s_hostSmallId;
static BYTE s_nextSmallId;
static CRITICAL_SECTION s_sendLock;
static CRITICAL_SECTION s_connectionsLock;
static std::vector<Win64RemoteConnection> s_connections;
static SOCKET s_advertiseSock;
static HANDLE s_advertiseThread;
static volatile bool s_advertising;
static Win64LANBroadcast s_advertiseData;
static CRITICAL_SECTION s_advertiseLock;
static int s_hostGamePort;
static SOCKET s_discoverySock;
static HANDLE s_discoveryThread;
static volatile bool s_discovering;
static CRITICAL_SECTION s_discoveryLock;
static std::vector<Win64LANSession> s_discoveredSessions;
static CRITICAL_SECTION s_disconnectLock;
static std::vector<BYTE> s_disconnectedSmallIds;
static CRITICAL_SECTION s_freeSmallIdLock;
static std::vector<BYTE> s_freeSmallIds;
};
extern bool g_Win64MultiplayerHost;
extern bool g_Win64MultiplayerJoin;
extern int g_Win64MultiplayerPort;
extern char g_Win64MultiplayerIP[256];
extern bool g_Win64DedicatedServer;
extern int g_Win64DedicatedServerPort;
extern char g_Win64DedicatedServerBindIP[256];
#endif

View file

@ -35,9 +35,27 @@ void CConsoleMinecraftApp::FatalLoadError()
void CConsoleMinecraftApp::CaptureSaveThumbnail()
{
RenderManager.CaptureThumbnail(&m_ThumbnailBuffer);
}
void CConsoleMinecraftApp::GetSaveThumbnail(PBYTE *pbData,DWORD *pdwSize)
{
// On a save caused by a create world, the thumbnail capture won't have happened
if (m_ThumbnailBuffer.Allocated())
{
if (pbData)
{
*pbData = new BYTE[m_ThumbnailBuffer.GetBufferSize()];
*pdwSize = m_ThumbnailBuffer.GetBufferSize();
memcpy(*pbData, m_ThumbnailBuffer.GetBufferPointer(), *pdwSize);
}
m_ThumbnailBuffer.Release();
}
else
{
// No capture happened (e.g. first save on world creation) leave thumbnail as NULL
if (pbData) *pbData = NULL;
if (pdwSize) *pdwSize = 0;
}
}
void CConsoleMinecraftApp::ReleaseSaveThumbnail()
{
@ -57,7 +75,8 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart()
Minecraft *pMinecraft=Minecraft::GetInstance();
app.ReleaseSaveThumbnail();
ProfileManager.SetLockedProfile(0);
pMinecraft->user->name = L"Windows";
extern wchar_t g_Win64UsernameW[17];
pMinecraft->user->name = g_Win64UsernameW;
app.ApplyGameSettingsChanged(0);
////////////////////////////////////////////////////////////////////////////////////////////// From CScene_MultiGameJoinLoad::OnInit

View file

@ -1,7 +1,9 @@
#pragma once
#include "4JLibs\inc\4J_Render.h"
class CConsoleMinecraftApp : public CMinecraftApp
{
ImageFileBuffer m_ThumbnailBuffer;
public:
CConsoleMinecraftApp();

View file

@ -4,7 +4,9 @@
#include "stdafx.h"
#include <assert.h>
#include <iostream>
#include <ShellScalingApi.h>
#include <shellapi.h>
#include "GameConfig/Minecraft.spa.h"
#include "../MinecraftServer.h"
#include "../LocalPlayer.h"
@ -34,9 +36,11 @@
#include "Sentient/SentientManager.h"
#include "../../Minecraft.World/IntCache.h"
#include "../Textures.h"
#include "../Settings.h"
#include "Resource.h"
#include "../../Minecraft.World/compression.h"
#include "../../Minecraft.World/OldChunkStorage.h"
#include "Network/WinsockNetLayer.h"
#include "Xbox/Resource.h"
@ -84,10 +88,158 @@ BOOL g_bWidescreen = TRUE;
int g_iScreenWidth = 1920;
int g_iScreenHeight = 1080;
UINT g_ScreenWidth = 1920;
UINT g_ScreenHeight = 1080;
char g_Win64Username[17] = { 0 };
wchar_t g_Win64UsernameW[17] = { 0 };
// Fullscreen toggle state
static bool g_isFullscreen = false;
static WINDOWPLACEMENT g_wpPrev = { sizeof(g_wpPrev) };
struct Win64LaunchOptions
{
int screenMode;
bool serverMode;
};
static void CopyWideArgToAnsi(LPCWSTR source, char* dest, size_t destSize)
{
if (destSize == 0)
return;
dest[0] = 0;
if (source == NULL)
return;
WideCharToMultiByte(CP_ACP, 0, source, -1, dest, (int)destSize, NULL, NULL);
dest[destSize - 1] = 0;
}
static void ApplyScreenMode(int screenMode)
{
switch (screenMode)
{
case 1:
g_iScreenWidth = 1280;
g_iScreenHeight = 720;
break;
case 2:
g_iScreenWidth = 640;
g_iScreenHeight = 480;
break;
case 3:
g_iScreenWidth = 720;
g_iScreenHeight = 408;
break;
default:
break;
}
}
static Win64LaunchOptions ParseLaunchOptions()
{
Win64LaunchOptions options = {};
options.screenMode = 0;
options.serverMode = false;
g_Win64MultiplayerJoin = false;
g_Win64MultiplayerPort = WIN64_NET_DEFAULT_PORT;
g_Win64DedicatedServer = false;
g_Win64DedicatedServerPort = WIN64_NET_DEFAULT_PORT;
g_Win64DedicatedServerBindIP[0] = 0;
int argc = 0;
LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL)
return options;
if (argc > 1 && lstrlenW(argv[1]) == 1)
{
if (argv[1][0] >= L'1' && argv[1][0] <= L'3')
options.screenMode = argv[1][0] - L'0';
}
for (int i = 1; i < argc; ++i)
{
if (_wcsicmp(argv[i], L"-server") == 0)
{
options.serverMode = true;
break;
}
}
g_Win64DedicatedServer = options.serverMode;
for (int i = 1; i < argc; ++i)
{
if (_wcsicmp(argv[i], L"-name") == 0 && (i + 1) < argc)
{
CopyWideArgToAnsi(argv[++i], g_Win64Username, sizeof(g_Win64Username));
}
else if (_wcsicmp(argv[i], L"-ip") == 0 && (i + 1) < argc)
{
char ipBuf[256];
CopyWideArgToAnsi(argv[++i], ipBuf, sizeof(ipBuf));
if (options.serverMode)
{
strncpy_s(g_Win64DedicatedServerBindIP, sizeof(g_Win64DedicatedServerBindIP), ipBuf, _TRUNCATE);
}
else
{
strncpy_s(g_Win64MultiplayerIP, sizeof(g_Win64MultiplayerIP), ipBuf, _TRUNCATE);
g_Win64MultiplayerJoin = true;
}
}
else if (_wcsicmp(argv[i], L"-port") == 0 && (i + 1) < argc)
{
wchar_t* endPtr = NULL;
long port = wcstol(argv[++i], &endPtr, 10);
if (endPtr != argv[i] && *endPtr == 0 && port > 0 && port <= 65535)
{
if (options.serverMode)
g_Win64DedicatedServerPort = (int)port;
else
g_Win64MultiplayerPort = (int)port;
}
}
}
LocalFree(argv);
return options;
}
static BOOL WINAPI HeadlessServerCtrlHandler(DWORD ctrlType)
{
switch (ctrlType)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
app.m_bShutdown = true;
MinecraftServer::HaltServer();
return TRUE;
default:
return FALSE;
}
}
static void SetupHeadlessServerConsole()
{
if (AllocConsole())
{
FILE* stream = NULL;
freopen_s(&stream, "CONIN$", "r", stdin);
freopen_s(&stream, "CONOUT$", "w", stdout);
freopen_s(&stream, "CONOUT$", "w", stderr);
SetConsoleTitleA("Minecraft Server");
}
SetConsoleCtrlHandler(HeadlessServerCtrlHandler, TRUE);
}
void DefineActions(void)
{
// The app needs to define the actions required, and the possible mappings for these
@ -403,6 +555,15 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
if (LOWORD(wParam) == WA_INACTIVE)
KMInput.SetCapture(false);
break;
case WM_SETFOCUS:
{
// Re-capture when window receives focus (e.g., after clicking on it)
Minecraft *pMinecraft = Minecraft::GetInstance();
bool shouldCapture = pMinecraft && app.GetGameStarted() && !ui.GetMenuDisplayed(0) && pMinecraft->screen == NULL;
if (shouldCapture)
KMInput.SetCapture(true);
}
break;
case WM_KILLFOCUS:
KMInput.SetCapture(false);
KMInput.ClearAllState();
@ -416,7 +577,6 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
return TRUE;
}
return DefWindowProc(hWnd, message, wParam, lParam);
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
@ -707,7 +867,224 @@ void CleanupDevice()
if( g_pd3dDevice ) g_pd3dDevice->Release();
}
static Minecraft* InitialiseMinecraftRuntime()
{
app.loadMediaArchive();
RenderManager.Initialise(g_pd3dDevice, g_pSwapChain);
app.loadStringTable();
ui.init(g_pd3dDevice, g_pImmediateContext, g_pRenderTargetView, g_pDepthStencilView, g_iScreenWidth, g_iScreenHeight);
InputManager.Initialise(1, 3, MINECRAFT_ACTION_MAX, ACTION_MAX_MENU);
KMInput.Init(g_hWnd);
DefineActions();
InputManager.SetJoypadMapVal(0, 0);
InputManager.SetKeyRepeatRate(0.3f, 0.2f);
ProfileManager.Initialise(TITLEID_MINECRAFT,
app.m_dwOfferID,
PROFILE_VERSION_10,
NUM_PROFILE_VALUES,
NUM_PROFILE_SETTINGS,
dwProfileSettingsA,
app.GAME_DEFINED_PROFILE_DATA_BYTES * XUSER_MAX_COUNT,
&app.uiGameDefinedDataChangedBitmask
);
ProfileManager.SetDefaultOptionsCallback(&CConsoleMinecraftApp::DefaultOptionsCallback, (LPVOID)&app);
g_NetworkManager.Initialise();
for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++)
{
IQNet::m_player[i].m_smallId = (BYTE)i;
IQNet::m_player[i].m_isRemote = false;
IQNet::m_player[i].m_isHostPlayer = (i == 0);
swprintf_s(IQNet::m_player[i].m_gamertag, 32, L"Player%d", i);
}
wcscpy_s(IQNet::m_player[0].m_gamertag, 32, g_Win64UsernameW);
WinsockNetLayer::Initialize();
ProfileManager.SetDebugFullOverride(true);
Tesselator::CreateNewThreadStorage(1024 * 1024);
AABB::CreateNewThreadStorage();
Vec3::CreateNewThreadStorage();
IntCache::CreateNewThreadStorage();
Compression::CreateNewThreadStorage();
OldChunkStorage::CreateNewThreadStorage();
Level::enableLightingCache();
Tile::CreateNewThreadStorage();
Minecraft::main();
Minecraft* pMinecraft = Minecraft::GetInstance();
if (pMinecraft == NULL)
return NULL;
app.InitGameSettings();
app.InitialiseTips();
pMinecraft->options->set(Options::Option::MUSIC, 1.0f);
pMinecraft->options->set(Options::Option::SOUND, 1.0f);
return pMinecraft;
}
static int HeadlessServerConsoleThreadProc(void* lpParameter)
{
UNREFERENCED_PARAMETER(lpParameter);
std::string line;
while (!app.m_bShutdown)
{
if (!std::getline(std::cin, line))
{
if (std::cin.eof())
{
break;
}
std::cin.clear();
Sleep(50);
continue;
}
wstring command = trimString(convStringToWstring(line));
if (command.empty())
continue;
MinecraftServer* server = MinecraftServer::getInstance();
if (server != NULL)
{
server->handleConsoleInput(command, server);
}
}
return 0;
}
static int RunHeadlessServer()
{
SetupHeadlessServerConsole();
Settings serverSettings(new File(L"server.properties"));
wstring configuredBindIp = serverSettings.getString(L"server-ip", L"");
const char* bindIp = "*";
if (g_Win64DedicatedServerBindIP[0] != 0)
{
bindIp = g_Win64DedicatedServerBindIP;
}
else if (!configuredBindIp.empty())
{
bindIp = wstringtochararray(configuredBindIp);
}
const int port = g_Win64DedicatedServerPort > 0 ? g_Win64DedicatedServerPort : serverSettings.getInt(L"server-port", WIN64_NET_DEFAULT_PORT);
printf("Starting headless server on %s:%d\n", bindIp, port);
fflush(stdout);
Minecraft* pMinecraft = InitialiseMinecraftRuntime();
if (pMinecraft == NULL)
{
fprintf(stderr, "Failed to initialise the Minecraft runtime.\n");
return 1;
}
app.SetGameHostOption(eGameHostOption_Difficulty, serverSettings.getInt(L"difficulty", 1));
app.SetGameHostOption(eGameHostOption_Gamertags, 1);
app.SetGameHostOption(eGameHostOption_GameType, serverSettings.getInt(L"gamemode", 0));
app.SetGameHostOption(eGameHostOption_LevelType, 0);
app.SetGameHostOption(eGameHostOption_Structures, serverSettings.getBoolean(L"generate-structures", true) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_BonusChest, serverSettings.getBoolean(L"bonus-chest", false) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_PvP, serverSettings.getBoolean(L"pvp", true) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_TrustPlayers, serverSettings.getBoolean(L"trust-players", true) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_FireSpreads, serverSettings.getBoolean(L"fire-spreads", true) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_TNT, serverSettings.getBoolean(L"tnt", true) ? 1 : 0);
app.SetGameHostOption(eGameHostOption_HostCanFly, 1);
app.SetGameHostOption(eGameHostOption_HostCanChangeHunger, 1);
app.SetGameHostOption(eGameHostOption_HostCanBeInvisible, 1);
app.SetGameHostOption(eGameHostOption_MobGriefing, 1);
app.SetGameHostOption(eGameHostOption_KeepInventory, 0);
app.SetGameHostOption(eGameHostOption_DoMobSpawning, 1);
app.SetGameHostOption(eGameHostOption_DoMobLoot, 1);
app.SetGameHostOption(eGameHostOption_DoTileDrops, 1);
app.SetGameHostOption(eGameHostOption_NaturalRegeneration, 1);
app.SetGameHostOption(eGameHostOption_DoDaylightCycle, 1);
MinecraftServer::resetFlags();
g_NetworkManager.HostGame(0, false, true, MINECRAFT_NET_MAX_PLAYERS, 0);
if (!WinsockNetLayer::IsActive())
{
fprintf(stderr, "Failed to bind the server socket on %s:%d.\n", bindIp, port);
return 1;
}
g_NetworkManager.FakeLocalPlayerJoined();
NetworkGameInitData* param = new NetworkGameInitData();
param->seed = 0;
param->settings = app.GetGameHostOption(eGameHostOption_All);
g_NetworkManager.ServerStoppedCreate(true);
g_NetworkManager.ServerReadyCreate(true);
C4JThread* thread = new C4JThread(&CGameNetworkManager::ServerThreadProc, param, "Server", 256 * 1024);
thread->SetProcessor(CPU_CORE_SERVER);
thread->Run();
g_NetworkManager.ServerReadyWait();
g_NetworkManager.ServerReadyDestroy();
if (MinecraftServer::serverHalted())
{
fprintf(stderr, "The server halted during startup.\n");
g_NetworkManager.LeaveGame(false);
return 1;
}
app.SetGameStarted(true);
g_NetworkManager.DoWork();
printf("Server ready on %s:%d\n", bindIp, port);
printf("Type 'help' for server commands.\n");
fflush(stdout);
C4JThread* consoleThread = new C4JThread(&HeadlessServerConsoleThreadProc, NULL, "Server console", 128 * 1024);
consoleThread->Run();
MSG msg = { 0 };
while (WM_QUIT != msg.message && !app.m_bShutdown && !MinecraftServer::serverHalted())
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
continue;
}
app.UpdateTime();
ProfileManager.Tick();
StorageManager.Tick();
RenderManager.Tick();
ui.tick();
g_NetworkManager.DoWork();
app.HandleXuiActions();
Sleep(10);
}
printf("Stopping server...\n");
fflush(stdout);
app.m_bShutdown = true;
MinecraftServer::HaltServer();
g_NetworkManager.LeaveGame(false);
return 0;
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
@ -717,40 +1094,69 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
// 4J-Win64: set CWD to exe dir so asset paths resolve correctly
{
char szExeDir[MAX_PATH] = {};
GetModuleFileNameA(NULL, szExeDir, MAX_PATH);
char *pSlash = strrchr(szExeDir, '\\');
if (pSlash) { *(pSlash + 1) = '\0'; SetCurrentDirectoryA(szExeDir); }
}
// Declare DPI awareness so GetSystemMetrics returns physical pixels
SetProcessDPIAware();
g_iScreenWidth = GetSystemMetrics(SM_CXSCREEN);
g_iScreenHeight = GetSystemMetrics(SM_CYSCREEN);
if(lpCmdLine)
{
if(lpCmdLine[0] == '1')
{
g_iScreenWidth = 1280;
g_iScreenHeight = 720;
}
else if(lpCmdLine[0] == '2')
{
g_iScreenWidth = 640;
g_iScreenHeight = 480;
}
else if(lpCmdLine[0] == '3')
{
// Vita
g_iScreenWidth = 720;
g_iScreenHeight = 408;
// Load username from username.txt
char exePath[MAX_PATH] = {};
GetModuleFileNameA(NULL, exePath, MAX_PATH);
char *lastSlash = strrchr(exePath, '\\');
if (lastSlash)
{
*(lastSlash + 1) = '\0';
}
// Vita native
//g_iScreenWidth = 960;
//g_iScreenHeight = 544;
}
char filePath[MAX_PATH] = {};
_snprintf_s(filePath, sizeof(filePath), _TRUNCATE, "%susername.txt", exePath);
FILE *f = nullptr;
if (fopen_s(&f, filePath, "r") == 0 && f)
{
char buf[128] = {};
if (fgets(buf, sizeof(buf), f))
{
int len = (int)strlen(buf);
while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r' || buf[len - 1] == ' '))
{
buf[--len] = '\0';
}
if (len > 0)
{
strncpy_s(g_Win64Username, sizeof(g_Win64Username), buf, _TRUNCATE);
}
}
fclose(f);
}
// Load stuff from launch options, including username
Win64LaunchOptions launchOptions = ParseLaunchOptions();
ApplyScreenMode(launchOptions.screenMode);
// If no username, let's fall back
if (g_Win64Username[0] == 0)
{
// Default username will be "Player"
strncpy_s(g_Win64Username, sizeof(g_Win64Username), "Player", _TRUNCATE);
}
MultiByteToWideChar(CP_ACP, 0, g_Win64Username, -1, g_Win64UsernameW, 17);
// Initialize global strings
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
if (!InitInstance (hInstance, launchOptions.serverMode ? SW_HIDE : nCmdShow))
{
return FALSE;
}
@ -763,6 +1169,13 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
return 0;
}
if (launchOptions.serverMode)
{
int serverResult = RunHeadlessServer();
CleanupDevice();
return serverResult;
}
#if 0
// Main message loop
MSG msg = {0};
@ -815,193 +1228,13 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
}
#endif
app.loadMediaArchive();
RenderManager.Initialise(g_pd3dDevice, g_pSwapChain);
app.loadStringTable();
ui.init(g_pd3dDevice,g_pImmediateContext,g_pRenderTargetView,g_pDepthStencilView,g_iScreenWidth,g_iScreenHeight);
////////////////
// Initialise //
////////////////
// Set the number of possible joypad layouts that the user can switch between, and the number of actions
InputManager.Initialise(1,3,MINECRAFT_ACTION_MAX, ACTION_MAX_MENU);
// Initialize keyboard/mouse input
KMInput.Init(g_hWnd);
// Set the default joypad action mappings for Minecraft
DefineActions();
InputManager.SetJoypadMapVal(0,0);
InputManager.SetKeyRepeatRate(0.3f,0.2f);
// Initialise the profile manager with the game Title ID, Offer ID, a profile version number, and the number of profile values and settings
ProfileManager.Initialise(TITLEID_MINECRAFT,
app.m_dwOfferID,
PROFILE_VERSION_10,
NUM_PROFILE_VALUES,
NUM_PROFILE_SETTINGS,
dwProfileSettingsA,
app.GAME_DEFINED_PROFILE_DATA_BYTES*XUSER_MAX_COUNT,
&app.uiGameDefinedDataChangedBitmask
);
#if 0
// register the awards
ProfileManager.RegisterAward(eAward_TakingInventory, ACHIEVEMENT_01, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_GettingWood, ACHIEVEMENT_02, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_Benchmarking, ACHIEVEMENT_03, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_TimeToMine, ACHIEVEMENT_04, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_HotTopic, ACHIEVEMENT_05, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_AquireHardware, ACHIEVEMENT_06, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_TimeToFarm, ACHIEVEMENT_07, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_BakeBread, ACHIEVEMENT_08, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_TheLie, ACHIEVEMENT_09, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_GettingAnUpgrade, ACHIEVEMENT_10, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_DeliciousFish, ACHIEVEMENT_11, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_OnARail, ACHIEVEMENT_12, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_TimeToStrike, ACHIEVEMENT_13, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_MonsterHunter, ACHIEVEMENT_14, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_CowTipper, ACHIEVEMENT_15, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_WhenPigsFly, ACHIEVEMENT_16, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_LeaderOfThePack, ACHIEVEMENT_17, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_MOARTools, ACHIEVEMENT_18, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_DispenseWithThis, ACHIEVEMENT_19, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_InToTheNether, ACHIEVEMENT_20, eAwardType_Achievement);
ProfileManager.RegisterAward(eAward_mine100Blocks, GAMER_PICTURE_GAMERPIC1, eAwardType_GamerPic,false,app.GetStringTable(),IDS_AWARD_TITLE,IDS_AWARD_GAMERPIC1,IDS_CONFIRM_OK);
ProfileManager.RegisterAward(eAward_kill10Creepers, GAMER_PICTURE_GAMERPIC2, eAwardType_GamerPic,false,app.GetStringTable(),IDS_AWARD_TITLE,IDS_AWARD_GAMERPIC2,IDS_CONFIRM_OK);
ProfileManager.RegisterAward(eAward_eatPorkChop, AVATARASSETAWARD_PORKCHOP_TSHIRT, eAwardType_AvatarItem,false,app.GetStringTable(),IDS_AWARD_TITLE,IDS_AWARD_AVATAR1,IDS_CONFIRM_OK);
ProfileManager.RegisterAward(eAward_play100Days, AVATARASSETAWARD_WATCH, eAwardType_AvatarItem,false,app.GetStringTable(),IDS_AWARD_TITLE,IDS_AWARD_AVATAR2,IDS_CONFIRM_OK);
ProfileManager.RegisterAward(eAward_arrowKillCreeper, AVATARASSETAWARD_CAP, eAwardType_AvatarItem,false,app.GetStringTable(),IDS_AWARD_TITLE,IDS_AWARD_AVATAR3,IDS_CONFIRM_OK);
ProfileManager.RegisterAward(eAward_socialPost, 0, eAwardType_Theme,false,app.GetStringTable(),IDS_AWARD_TITLE,IDS_AWARD_THEME,IDS_CONFIRM_OK,THEME_NAME,THEME_FILESIZE);
// Rich Presence init - number of presences, number of contexts
ProfileManager.RichPresenceInit(4,1);
ProfileManager.RegisterRichPresenceContext(CONTEXT_GAME_STATE);
// initialise the storage manager with a default save display name, a Minimum save size, and a callback for displaying the saving message
StorageManager.Init(app.GetString(IDS_DEFAULT_SAVENAME),"savegame.dat",FIFTY_ONE_MB,&CConsoleMinecraftApp::DisplaySavingMessage,(LPVOID)&app);
// Set up the global title storage path
StorageManager.StoreTMSPathName();
// set a function to be called when there's a sign in change, so we can exit a level if the primary player signs out
ProfileManager.SetSignInChangeCallback(&CConsoleMinecraftApp::SignInChangeCallback,(LPVOID)&app);
// set a function to be called when the ethernet is disconnected, so we can back out if required
ProfileManager.SetNotificationsCallback(&CConsoleMinecraftApp::NotificationsCallback,(LPVOID)&app);
#endif
// Set a callback for the default player options to be set - when there is no profile data for the player
ProfileManager.SetDefaultOptionsCallback(&CConsoleMinecraftApp::DefaultOptionsCallback,(LPVOID)&app);
#if 0
// Set a callback to deal with old profile versions needing updated to new versions
ProfileManager.SetOldProfileVersionCallback(&CConsoleMinecraftApp::OldProfileVersionCallback,(LPVOID)&app);
// Set a callback for when there is a read error on profile data
ProfileManager.SetProfileReadErrorCallback(&CConsoleMinecraftApp::ProfileReadErrorCallback,(LPVOID)&app);
#endif
// QNet needs to be setup after profile manager, as we do not want its Notify listener to handle
// XN_SYS_SIGNINCHANGED notifications. This does mean that we need to have a callback in the
// ProfileManager for XN_LIVE_INVITE_ACCEPTED for QNet.
g_NetworkManager.Initialise();
// 4J-PB moved further down
//app.InitGameSettings();
// debug switch to trial version
ProfileManager.SetDebugFullOverride(true);
#if 0
//ProfileManager.AddDLC(2);
StorageManager.SetDLCPackageRoot("DLCDrive");
StorageManager.RegisterMarketplaceCountsCallback(&CConsoleMinecraftApp::MarketplaceCountsCallback,(LPVOID)&app);
// Kinect !
if(XNuiGetHardwareStatus()!=0)
Minecraft *pMinecraft = InitialiseMinecraftRuntime();
if (pMinecraft == NULL)
{
// If the Kinect Sensor is not physically connected, this function returns 0.
NuiInitialize(NUI_INITIALIZE_FLAG_USES_HIGH_QUALITY_COLOR | NUI_INITIALIZE_FLAG_USES_DEPTH |
NUI_INITIALIZE_FLAG_EXTRAPOLATE_FLOOR_PLANE | NUI_INITIALIZE_FLAG_USES_FITNESS | NUI_INITIALIZE_FLAG_NUI_GUIDE_DISABLED | NUI_INITIALIZE_FLAG_SUPPRESS_AUTOMATIC_UI,NUI_INITIALIZE_DEFAULT_HARDWARE_THREAD );
CleanupDevice();
return 1;
}
// Sentient !
hr = TelemetryManager->Init();
#endif
// Initialise TLS for tesselator, for this main thread
Tesselator::CreateNewThreadStorage(1024*1024);
// Initialise TLS for AABB and Vec3 pools, for this main thread
AABB::CreateNewThreadStorage();
Vec3::CreateNewThreadStorage();
IntCache::CreateNewThreadStorage();
Compression::CreateNewThreadStorage();
OldChunkStorage::CreateNewThreadStorage();
Level::enableLightingCache();
Tile::CreateNewThreadStorage();
Minecraft::main();
Minecraft *pMinecraft=Minecraft::GetInstance();
app.InitGameSettings();
#if 0
//bool bDisplayPauseMenu=false;
// set the default gamma level
float fVal=50.0f*327.68f;
RenderManager.UpdateGamma((unsigned short)fVal);
// load any skins
//app.AddSkinsToMemoryTextureFiles();
// set the achievement text for a trial achievement, now we have the string table loaded
ProfileManager.SetTrialTextStringTable(app.GetStringTable(),IDS_CONFIRM_OK, IDS_CONFIRM_CANCEL);
ProfileManager.SetTrialAwardText(eAwardType_Achievement,IDS_UNLOCK_TITLE,IDS_UNLOCK_ACHIEVEMENT_TEXT);
ProfileManager.SetTrialAwardText(eAwardType_GamerPic,IDS_UNLOCK_TITLE,IDS_UNLOCK_GAMERPIC_TEXT);
ProfileManager.SetTrialAwardText(eAwardType_AvatarItem,IDS_UNLOCK_TITLE,IDS_UNLOCK_AVATAR_TEXT);
ProfileManager.SetTrialAwardText(eAwardType_Theme,IDS_UNLOCK_TITLE,IDS_UNLOCK_THEME_TEXT);
ProfileManager.SetUpsellCallback(&app.UpsellReturnedCallback,&app);
// Set up a debug character press sequence
#ifndef _FINAL_BUILD
app.SetDebugSequence("LRLRYYY");
#endif
// Initialise the social networking manager.
CSocialManager::Instance()->Initialise();
// Update the base scene quick selects now that the minecraft class exists
//CXuiSceneBase::UpdateScreenSettings(0);
#endif
app.InitialiseTips();
#if 0
DWORD initData=0;
#ifndef _FINAL_BUILD
#ifndef _DEBUG
#pragma message(__LOC__"Need to define the _FINAL_BUILD before submission")
#endif
#endif
// Set the default sound levels
pMinecraft->options->set(Options::Option::MUSIC,1.0f);
pMinecraft->options->set(Options::Option::SOUND,1.0f);
app.NavigateToScene(XUSER_INDEX_ANY,eUIScene_Intro,&initData);
#endif
// Set the default sound levels
pMinecraft->options->set(Options::Option::MUSIC,1.0f);
pMinecraft->options->set(Options::Option::SOUND,1.0f);
//app.TemporaryCreateGameStart();
//Sleep(10000);
@ -1082,7 +1315,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
PIXEndNamedEvent();
PIXBeginNamedEvent(0,"Network manager do work #1");
// g_NetworkManager.DoWork();
g_NetworkManager.DoWork();
PIXEndNamedEvent();
// LeaderboardManager::Instance()->Tick();
@ -1208,49 +1441,67 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
}
}
// F11 toggles fullscreen
if (KMInput.IsKeyPressed(VK_F11))
// F1 toggles the HUD
if (KMInput.IsKeyPressed(VK_F1))
{
ToggleFullscreen();
int primaryPad = ProfileManager.GetPrimaryPad();
unsigned char displayHud = app.GetGameSettings(primaryPad, eGameSetting_DisplayHUD);
app.SetGameSettings(primaryPad, eGameSetting_DisplayHUD, displayHud ? 0 : 1);
app.SetGameSettings(primaryPad, eGameSetting_DisplayHand, displayHud ? 0 : 1);
}
// TAB opens host options menu. - Vvis :3
if (KMInput.IsKeyPressed(VK_TAB) && !ui.GetMenuDisplayed(0))
{
if (Minecraft* pMinecraft = Minecraft::GetInstance())
{
{
ui.NavigateToScene(0, eUIScene_InGameHostOptionsMenu);
}
}
}
#ifdef _DEBUG_MENUS_ENABLED
// F3 toggles onscreen debug info
if (KMInput.IsKeyPressed(VK_F3))
{
if (Minecraft* pMinecraft = Minecraft::GetInstance())
{
if (pMinecraft->options && app.DebugSettingsOn())
if (pMinecraft->options)
{
pMinecraft->options->renderDebug = !pMinecraft->options->renderDebug;
}
}
}
// F4 opens debug overlay
if (KMInput.IsKeyPressed(VK_F4))
#ifdef _DEBUG_MENUS_ENABLED
// F4 Open debug overlay
if (KMInput.IsKeyPressed(VK_F4))
{
if (Minecraft *pMinecraft = Minecraft::GetInstance())
{
if (pMinecraft->options &&
app.GetGameStarted() && !ui.GetMenuDisplayed(0) && pMinecraft->screen == NULL)
{
ui.NavigateToScene(0, eUIScene_DebugOverlay, NULL, eUILayer_Debug);
}
}
}
// F6 Open debug console
if (KMInput.IsKeyPressed(VK_F6))
{
static bool s_debugConsole = false;
s_debugConsole = !s_debugConsole;
ui.ShowUIDebugConsole(s_debugConsole);
}
#endif
// F11 Toggle fullscreen
if (KMInput.IsKeyPressed(VK_F11))
{
ToggleFullscreen();
}
// TAB opens game info menu. - Vvis :3 - Updated by detectiveren
if (KMInput.IsKeyPressed(VK_TAB) && !ui.GetMenuDisplayed(0))
{
if (Minecraft* pMinecraft = Minecraft::GetInstance())
{
if (pMinecraft->options && app.DebugSettingsOn() &&
app.GetGameStarted() && !ui.GetMenuDisplayed(0) && pMinecraft->screen == NULL)
{
ui.NavigateToScene(0, eUIScene_DebugOverlay, NULL, eUILayer_Debug);
ui.NavigateToScene(0, eUIScene_InGameInfoMenu);
}
}
}
#endif
#if 0
// has the game defined profile data been changed (by a profile load)

View file

@ -1658,7 +1658,8 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in
// If you're navigating to the multigamejoinload, and the player hasn't seen the updates message yet, display it now
// display this message the first 3 times
if((eScene==eUIScene_LoadOrJoinMenu) && (bSeenUpdateTextThisSession==false) && ( app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_DisplayUpdateMessage)!=0))
// todo: re-enable if we fix this menu, for now its just blank!
if(false && (eScene==eUIScene_LoadOrJoinMenu) && (bSeenUpdateTextThisSession==false) && ( app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_DisplayUpdateMessage)!=0))
{
eScene=eUIScene_NewUpdateMessage;
bSeenUpdateTextThisSession=true;

View file

@ -48,9 +48,13 @@ void glLoadIdentity()
RenderManager.MatrixSetIdentity();
}
extern int g_iScreenWidth;
extern int g_iScreenHeight;
void gluPerspective(float fovy, float aspect, float zNear, float zFar)
{
RenderManager.MatrixPerspective(fovy,aspect,zNear,zFar);
float dynamicAspect = (float)g_iScreenWidth / (float)g_iScreenHeight;
RenderManager.MatrixPerspective(fovy, dynamicAspect, zNear, zFar);
}
void glOrtho(float left,float right,float bottom,float top,float zNear,float zFar)

View file

@ -0,0 +1 @@
C:\Users\manea\Documents\MinecraftConsoles\Minecraft.World\ARM64EC_Debug\Minecraft.World.lib

View file

@ -12,7 +12,7 @@ ArmorSlot::ArmorSlot(int slotNum, shared_ptr<Container> container, int id, int x
{
}
int ArmorSlot::getMaxStackSize()
int ArmorSlot::getMaxStackSize() const
{
return 1;
}

View file

@ -16,7 +16,7 @@ public:
ArmorSlot(int slotNum, shared_ptr<Container> container, int id, int x, int y);
virtual ~ArmorSlot() {}
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual bool mayPlace(shared_ptr<ItemInstance> item);
Icon *getNoItemIcon();
//virtual bool mayCombine(shared_ptr<ItemInstance> item); // 4J Added

View file

@ -134,7 +134,7 @@ bool BeaconMenu::PaymentSlot::mayPlace(shared_ptr<ItemInstance> item)
return false;
}
int BeaconMenu::PaymentSlot::getMaxStackSize()
int BeaconMenu::PaymentSlot::getMaxStackSize() const
{
return 1;
}

View file

@ -14,7 +14,7 @@ private:
PaymentSlot(shared_ptr<Container> container, int slot, int x, int y);
bool mayPlace(shared_ptr<ItemInstance> item);
int getMaxStackSize();
int getMaxStackSize() const;
};
public:

View file

@ -346,7 +346,7 @@ void BeaconTileEntity::setCustomName(const wstring &name)
this->name = name;
}
int BeaconTileEntity::getMaxStackSize()
int BeaconTileEntity::getMaxStackSize() const
{
return 1;
}

View file

@ -64,7 +64,7 @@ public:
wstring getCustomName();
bool hasCustomName();
void setCustomName(const wstring &name);
int getMaxStackSize();
int getMaxStackSize() const;
bool stillValid(shared_ptr<Player> player);
void startOpen();
void stopOpen();

View file

@ -101,7 +101,7 @@ shared_ptr<ItemInstance> BrewingStandMenu::quickMoveStack(shared_ptr<Player> pla
else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END)
{
// 4J-PB - if the item is an ingredient, quickmove it into the ingredient slot
if( (Item::items[stack->id]->hasPotionBrewingFormula() || (stack->id == Item::netherwart_seeds_Id) ) &&
if( (Item::items[stack->id]->hasPotionBrewingFormula() || (stack->id == Item::netherwart_seeds_Id) ) &&
(!IngredientSlot->hasItem() || (stack->id==IngredientSlot->getItem()->id) ) )
{
if(!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT+1, false))
@ -125,7 +125,7 @@ shared_ptr<ItemInstance> BrewingStandMenu::quickMoveStack(shared_ptr<Player> pla
else if (slotIndex >= USE_ROW_SLOT_START && slotIndex < USE_ROW_SLOT_END)
{
// 4J-PB - if the item is an ingredient, quickmove it into the ingredient slot
if((Item::items[stack->id]->hasPotionBrewingFormula() || (stack->id == Item::netherwart_seeds_Id)) &&
if((Item::items[stack->id]->hasPotionBrewingFormula() || (stack->id == Item::netherwart_seeds_Id)) &&
(!IngredientSlot->hasItem() || (stack->id==IngredientSlot->getItem()->id) ))
{
if(!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT+1, false))
@ -140,7 +140,7 @@ shared_ptr<ItemInstance> BrewingStandMenu::quickMoveStack(shared_ptr<Player> pla
{
return nullptr;
}
}
}
else if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false))
{
return nullptr;
@ -183,7 +183,7 @@ bool BrewingStandMenu::PotionSlot::mayPlace(shared_ptr<ItemInstance> item)
return mayPlaceItem(item);
}
int BrewingStandMenu::PotionSlot::getMaxStackSize()
int BrewingStandMenu::PotionSlot::getMaxStackSize() const
{
return 1;
}
@ -231,7 +231,7 @@ bool BrewingStandMenu::IngredientsSlot::mayCombine(shared_ptr<ItemInstance> seco
return false;
}
int BrewingStandMenu::IngredientsSlot::getMaxStackSize()
int BrewingStandMenu::IngredientsSlot::getMaxStackSize() const
{
return 64;
}

View file

@ -47,7 +47,7 @@ private:
PotionSlot(shared_ptr<Player> player, shared_ptr<Container> container, int slot, int x, int y);
virtual bool mayPlace(shared_ptr<ItemInstance> item);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual void onTake(shared_ptr<Player> player, shared_ptr<ItemInstance> carried);
static bool mayPlaceItem(shared_ptr<ItemInstance> item);
virtual bool mayCombine(shared_ptr<ItemInstance> item); // 4J Added
@ -59,7 +59,7 @@ private:
IngredientsSlot(shared_ptr<Container> container, int slot, int x, int y);
virtual bool mayPlace(shared_ptr<ItemInstance> item);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual bool mayCombine(shared_ptr<ItemInstance> item); // 4J Added
};
};

View file

@ -10,7 +10,7 @@
int slotsForUp [] = { BrewingStandTileEntity::INGREDIENT_SLOT };
int slotsForOtherFaces [] = { 0, 1, 2 };
intArray BrewingStandTileEntity::SLOTS_FOR_UP = intArray(slotsForUp, 1);
intArray BrewingStandTileEntity::SLOTS_FOR_UP = intArray(slotsForUp, 1);
intArray BrewingStandTileEntity::SLOTS_FOR_OTHER_FACES = intArray(slotsForOtherFaces, 3);
BrewingStandTileEntity::BrewingStandTileEntity()
@ -156,7 +156,7 @@ bool BrewingStandTileEntity::isBrewable()
}
else
{
if (!Item::items[ingredient->id]->hasPotionBrewingFormula() && ingredient->id != Item::bucket_water_Id && ingredient->id != Item::netherwart_seeds_Id)
if (!Item::items[ingredient->id]->hasPotionBrewingFormula() && ingredient->id != Item::bucket_water_Id && ingredient->id != Item::netherwart_seeds_Id)
{
return false;
}
@ -327,7 +327,7 @@ void BrewingStandTileEntity::save(CompoundTag *base)
for (int i = 0; i < items.length; i++)
{
if (items[i] != NULL)
if (items[i] != NULL)
{
CompoundTag *tag = new CompoundTag();
tag->putByte(L"Slot", (byte) i);
@ -356,7 +356,7 @@ shared_ptr<ItemInstance> BrewingStandTileEntity::removeItem(unsigned int slot, i
if (slot >= 0 && slot < items.length && items[slot] != NULL)
{
if (items[slot]->count <= count)
if (items[slot]->count <= count)
{
shared_ptr<ItemInstance> item = items[slot];
items[slot] = nullptr;
@ -364,8 +364,8 @@ shared_ptr<ItemInstance> BrewingStandTileEntity::removeItem(unsigned int slot, i
// 4J Stu - Fix for duplication glitch
if(item->count <= 0) return nullptr;
return item;
}
else
}
else
{
shared_ptr<ItemInstance> i = items[slot]->remove(count);
if (items[slot]->count == 0) items[slot] = nullptr;
@ -397,7 +397,7 @@ void BrewingStandTileEntity::setItem(unsigned int slot, shared_ptr<ItemInstance>
}
}
int BrewingStandTileEntity::getMaxStackSize()
int BrewingStandTileEntity::getMaxStackSize() const
{
// this value is not used for the potion slots
return 64;

View file

@ -12,7 +12,7 @@ public:
private:
ItemInstanceArray items;
static intArray SLOTS_FOR_UP;
static intArray SLOTS_FOR_UP;
static intArray SLOTS_FOR_OTHER_FACES;
int brewTime;
@ -37,7 +37,7 @@ private:
void doBrew();
int applyIngredient(int currentBrew, shared_ptr<ItemInstance> ingredient);
public:
virtual void load(CompoundTag *base);
virtual void save(CompoundTag *base);
@ -45,7 +45,7 @@ public:
virtual shared_ptr<ItemInstance> removeItem(unsigned int slot, int i);
virtual shared_ptr<ItemInstance> removeItemNoUpdate(int slot);
virtual void setItem(unsigned int slot, shared_ptr<ItemInstance> item);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual bool stillValid(shared_ptr<Player> player);
virtual void startOpen();
virtual void stopOpen();

View file

@ -53,7 +53,7 @@ ChestTileEntity::~ChestTileEntity()
delete items;
}
unsigned int ChestTileEntity::getContainerSize()
unsigned int ChestTileEntity::getContainerSize()
{
return 9 * 3;
}
@ -63,11 +63,11 @@ shared_ptr<ItemInstance> ChestTileEntity::getItem(unsigned int slot)
return items->data[slot];
}
shared_ptr<ItemInstance> ChestTileEntity::removeItem(unsigned int slot, int count)
shared_ptr<ItemInstance> ChestTileEntity::removeItem(unsigned int slot, int count)
{
if (items->data[slot] != NULL)
{
if (items->data[slot]->count <= count)
if (items->data[slot]->count <= count)
{
shared_ptr<ItemInstance> item = items->data[slot];
items->data[slot] = nullptr;
@ -75,8 +75,8 @@ shared_ptr<ItemInstance> ChestTileEntity::removeItem(unsigned int slot, int coun
// 4J Stu - Fix for duplication glitch
if(item->count <= 0) return nullptr;
return item;
}
else
}
else
{
shared_ptr<ItemInstance> i = items->data[slot]->remove(count);
if (items->data[slot]->count == 0) items->data[slot] = nullptr;
@ -154,7 +154,7 @@ void ChestTileEntity::save(CompoundTag *base)
for (unsigned int i = 0; i < items->length; i++)
{
if (items->data[i] != NULL)
if (items->data[i] != NULL)
{
CompoundTag *tag = new CompoundTag();
tag->putByte(L"Slot", (byte) i);
@ -167,7 +167,7 @@ void ChestTileEntity::save(CompoundTag *base)
base->putBoolean(L"bonus", isBonusChest);
}
int ChestTileEntity::getMaxStackSize()
int ChestTileEntity::getMaxStackSize() const
{
return Container::LARGE_MAX_STACK_SIZE;
}
@ -179,7 +179,7 @@ bool ChestTileEntity::stillValid(shared_ptr<Player> player)
return true;
}
void ChestTileEntity::setChanged()
void ChestTileEntity::setChanged()
{
TileEntity::setChanged();
}
@ -302,7 +302,7 @@ void ChestTileEntity::tick()
if (s.lock() != NULL) zc += 0.5;
if (e.lock() != NULL) xc += 0.5;
// 4J-PB - Seems the chest open volume is much louder than other sounds from user reports. We'll tone it down a bit
// 4J-PB - Seems the chest open volume is much louder than other sounds from user reports. We'll tone it down a bit
level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_OPEN, 0.2f, level->random->nextFloat() * 0.1f + 0.9f);
}
}
@ -327,7 +327,7 @@ void ChestTileEntity::tick()
if (s.lock() != NULL) zc += 0.5;
if (e.lock() != NULL) xc += 0.5;
// 4J-PB - Seems the chest open volume is much louder than other sounds from user reports. We'll tone it down a bit
// 4J-PB - Seems the chest open volume is much louder than other sounds from user reports. We'll tone it down a bit
level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_CLOSE, 0.2f, level->random->nextFloat() * 0.1f + 0.9f);
}
}

View file

@ -59,7 +59,7 @@ public:
virtual void setCustomName(const wstring &name);
virtual void load(CompoundTag *base);
virtual void save(CompoundTag *base);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual bool stillValid(shared_ptr<Player> player);
virtual void setChanged();
virtual void clearCache();

View file

@ -70,7 +70,7 @@ void CompoundContainer::setItem(unsigned int slot, shared_ptr<ItemInstance> item
else c1->setItem(slot, item);
}
int CompoundContainer::getMaxStackSize()
int CompoundContainer::getMaxStackSize() const
{
return c1->getMaxStackSize();
}

View file

@ -24,7 +24,7 @@ public:
virtual shared_ptr<ItemInstance> removeItem(unsigned int slot, int i);
virtual shared_ptr<ItemInstance> removeItemNoUpdate(int slot);
virtual void setItem(unsigned int slot, shared_ptr<ItemInstance> item);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual void setChanged();
virtual bool stillValid(shared_ptr<Player> player);

View file

@ -749,7 +749,7 @@ void ConsoleSaveFileOriginal::Flush(bool autosave, bool updateThumbnail )
PBYTE pbDataSaveImage=NULL;
DWORD dwDataSizeSaveImage=0;
#if ( defined _XBOX || defined _DURANGO )
#if ( defined _XBOX || defined _DURANGO || defined _WINDOWS64 )
app.GetSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize);
#elif ( defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ )
app.GetSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize,&pbDataSaveImage,&dwDataSizeSaveImage);

View file

@ -20,7 +20,7 @@ public:
virtual wstring getName() = 0;
virtual wstring getCustomName() = 0; // 4J Stu added for sending over the network
virtual bool hasCustomName() = 0;
virtual int getMaxStackSize() = 0;
virtual int getMaxStackSize() const = 0;
virtual void setChanged() = 0;
virtual bool stillValid(shared_ptr<Player> player) = 0;
virtual void startOpen() = 0;

View file

@ -95,7 +95,7 @@ void CraftingContainer::setItem(unsigned int slot, shared_ptr<ItemInstance> item
if(menu) menu->slotsChanged();
}
int CraftingContainer::getMaxStackSize()
int CraftingContainer::getMaxStackSize() const
{
return Container::LARGE_MAX_STACK_SIZE;
}

View file

@ -24,7 +24,7 @@ public:
virtual shared_ptr<ItemInstance> removeItemNoUpdate(int slot);
virtual shared_ptr<ItemInstance> removeItem(unsigned int slot, int count);
virtual void setItem(unsigned int slot, shared_ptr<ItemInstance> item);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual void setChanged();
bool stillValid(shared_ptr<Player> player);

View file

@ -23,7 +23,7 @@ DispenserTileEntity::~DispenserTileEntity()
delete random;
}
unsigned int DispenserTileEntity::getContainerSize()
unsigned int DispenserTileEntity::getContainerSize()
{
return 9;
}
@ -33,7 +33,7 @@ shared_ptr<ItemInstance> DispenserTileEntity::getItem(unsigned int slot)
return items[slot];
}
shared_ptr<ItemInstance> DispenserTileEntity::removeItem(unsigned int slot, int count)
shared_ptr<ItemInstance> DispenserTileEntity::removeItem(unsigned int slot, int count)
{
if (items[slot] != NULL)
{
@ -45,8 +45,8 @@ shared_ptr<ItemInstance> DispenserTileEntity::removeItem(unsigned int slot, int
// 4J Stu - Fix for duplication glitch
if(item->count <= 0) return nullptr;
return item;
}
else
}
else
{
shared_ptr<ItemInstance> i = items[slot]->remove(count);
if (items[slot]->count == 0) items[slot] = nullptr;
@ -71,7 +71,7 @@ shared_ptr<ItemInstance> DispenserTileEntity::removeItemNoUpdate(int slot)
}
// 4J-PB added for spawn eggs not being useable due to limits, so add them in again
void DispenserTileEntity::AddItemBack(shared_ptr<ItemInstance>item, unsigned int slot)
void DispenserTileEntity::AddItemBack(shared_ptr<ItemInstance>item, unsigned int slot)
{
if (items[slot] != NULL)
{
@ -80,7 +80,7 @@ void DispenserTileEntity::AddItemBack(shared_ptr<ItemInstance>item, unsigned int
{
items[slot]->count++;
setChanged();
}
}
}
else
{
@ -91,7 +91,7 @@ void DispenserTileEntity::AddItemBack(shared_ptr<ItemInstance>item, unsigned int
}
/**
* Removes an item with the given id and returns true if one was found.
*
*
* @param itemId
* @return
*/
@ -114,7 +114,7 @@ int DispenserTileEntity::getRandomSlot()
int replaceOdds = 1;
for (unsigned int i = 0; i < items.length; i++)
{
if (items[i] != NULL && random->nextInt(replaceOdds++) == 0)
if (items[i] != NULL && random->nextInt(replaceOdds++) == 0)
{
replaceSlot = i;
}
@ -123,7 +123,7 @@ int DispenserTileEntity::getRandomSlot()
return replaceSlot;
}
void DispenserTileEntity::setItem(unsigned int slot, shared_ptr<ItemInstance> item)
void DispenserTileEntity::setItem(unsigned int slot, shared_ptr<ItemInstance> item)
{
items[slot] = item;
if (item != NULL && item->count > getMaxStackSize()) item->count = getMaxStackSize();
@ -144,7 +144,7 @@ int DispenserTileEntity::addItem(shared_ptr<ItemInstance> item)
return -1;
}
wstring DispenserTileEntity::getName()
wstring DispenserTileEntity::getName()
{
return hasCustomName() ? name : app.GetString(IDS_TILE_DISPENSER);
}
@ -184,7 +184,7 @@ void DispenserTileEntity::save(CompoundTag *base)
TileEntity::save(base);
ListTag<CompoundTag> *listTag = new ListTag<CompoundTag>;
for (unsigned int i = 0; i < items.length; i++)
for (unsigned int i = 0; i < items.length; i++)
{
if (items[i] != NULL)
{
@ -198,7 +198,7 @@ void DispenserTileEntity::save(CompoundTag *base)
if (hasCustomName()) base->putString(L"CustomName", name);
}
int DispenserTileEntity::getMaxStackSize()
int DispenserTileEntity::getMaxStackSize() const
{
return Container::LARGE_MAX_STACK_SIZE;
}

View file

@ -45,7 +45,7 @@ public:
virtual bool hasCustomName();
virtual void load(CompoundTag *base);
virtual void save(CompoundTag *base);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual bool stillValid(shared_ptr<Player> player);
virtual void setChanged();
@ -55,5 +55,5 @@ public:
// 4J Added
virtual shared_ptr<TileEntity> clone();
void AddItemBack(shared_ptr<ItemInstance>item, unsigned int slot);
void AddItemBack(shared_ptr<ItemInstance>item, unsigned int slot);
};

View file

@ -6,7 +6,7 @@ EnchantmentContainer::EnchantmentContainer(EnchantmentMenu *menu) : SimpleContai
{
}
int EnchantmentContainer::getMaxStackSize()
int EnchantmentContainer::getMaxStackSize() const
{
return 1;
}

View file

@ -13,7 +13,7 @@ private:
EnchantmentMenu *m_menu;
public:
EnchantmentContainer(EnchantmentMenu *menu);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual void setChanged();
virtual bool canPlaceItem(int slot, shared_ptr<ItemInstance> item);
};

View file

@ -420,7 +420,7 @@ void Entity::remove()
void Entity::setSize(float w, float h)
{
if (w != bbWidth || h != bbHeight)
if (w != bbWidth || h != bbHeight)
{
float oldW = bbWidth;
@ -431,7 +431,7 @@ void Entity::setSize(float w, float h)
bb->z1 = bb->z0 + bbWidth;
bb->y1 = bb->y0 + bbHeight;
if (bbWidth > oldW && !firstTick && !level->isClientSide)
if (bbWidth > oldW && !firstTick && !level->isClientSide)
{
move(oldW - bbWidth, 0, oldW - bbWidth);
}
@ -449,7 +449,7 @@ void Entity::setPos(EntityPos *pos)
void Entity::setRot(float yRot, float xRot)
{
/* JAVA:
/* JAVA:
this->yRot = yRot % 360.0f;
this->xRot = xRot % 360.0f;
@ -585,7 +585,7 @@ void Entity::baseTick()
{
onFire = 0;
}
else
else
{
if (onFire > 0)
{
@ -1031,7 +1031,7 @@ void Entity::checkFallDamage(double ya, bool onGround)
causeFallDamage(fallDistance);
fallDistance = 0;
}
}
}
else
{
if (ya < 0) fallDistance -= (float) ya;
@ -1100,7 +1100,7 @@ bool Entity::updateInWaterState()
fallDistance = 0;
wasInWater = true;
onFire = 0;
}
}
else
{
wasInWater = false;
@ -1468,25 +1468,17 @@ void Entity::onLoadedFromSave()
}
ListTag<DoubleTag> *Entity::newDoubleList(unsigned int number, double firstValue, ...)
template<typename ...Args>
ListTag<DoubleTag> *Entity::newDoubleList(unsigned int, double firstValue, Args... args)
{
ListTag<DoubleTag> *res = new ListTag<DoubleTag>();
// Add the first parameter to the ListTag
res->add( new DoubleTag(L"", firstValue ) );
va_list vl;
va_start(vl,firstValue);
double val;
for (unsigned int i=1;i<number;i++)
{
val=va_arg(vl,double);
res->add(new DoubleTag(L"", val));
}
va_end(vl);
// use pre-C++17 fold trick (TODO: once we drop C++14 support, use C++14 fold expression)
using expander = int[];
(void)expander{0, (res->add(new DoubleTag(L"", static_cast<double>(args))), 0)...};
return res;
}
@ -1573,7 +1565,7 @@ bool Entity::interact(shared_ptr<Player> player)
return false;
}
AABB *Entity::getCollideAgainstBox(shared_ptr<Entity> entity)
AABB *Entity::getCollideAgainstBox(shared_ptr<Entity> entity)
{
return NULL;
}
@ -1842,7 +1834,7 @@ void Entity::setSharedFlag(int flag, bool value)
if( entityData )
{
byte currentValue = entityData->getByte(DATA_SHARED_FLAGS_ID);
if (value)
if (value)
{
entityData->set(DATA_SHARED_FLAGS_ID, (byte) (currentValue | (1 << flag)));
}
@ -2121,13 +2113,13 @@ wstring Entity::getNetworkName()
return getDisplayName();
}
void Entity::setAnimOverrideBitmask(unsigned int uiBitmask)
void Entity::setAnimOverrideBitmask(unsigned int uiBitmask)
{
m_uiAnimOverrideBitmask=uiBitmask;
app.DebugPrintf("!!! Setting anim override bitmask to %d\n",uiBitmask);
}
unsigned int Entity::getAnimOverrideBitmask()
{
unsigned int Entity::getAnimOverrideBitmask()
{
if(app.GetGameSettings(eGameSetting_CustomSkinAnim)==0 )
{
// We have a force animation for some skins (claptrap)

View file

@ -304,7 +304,8 @@ public:
virtual void onLoadedFromSave();
protected:
ListTag<DoubleTag> *newDoubleList(unsigned int number, double firstValue, ...);
template<typename ...Args>
ListTag<DoubleTag> *newDoubleList(unsigned int, double firstValue, Args... args);
ListTag<FloatTag> *newFloatList(unsigned int number, float firstValue, float secondValue);
public:

View file

@ -160,7 +160,7 @@ void FurnaceTileEntity::save(CompoundTag *base)
}
int FurnaceTileEntity::getMaxStackSize()
int FurnaceTileEntity::getMaxStackSize() const
{
return Container::LARGE_MAX_STACK_SIZE;
}
@ -205,7 +205,7 @@ void FurnaceTileEntity::tick()
if (items[SLOT_FUEL] != NULL)
{
// 4J Added: Keep track of whether charcoal was used in production of current stack.
if ( items[SLOT_FUEL]->getItem()->id == Item::coal_Id
if ( items[SLOT_FUEL]->getItem()->id == Item::coal_Id
&& items[SLOT_FUEL]->getAuxValue() == CoalItem::CHAR_COAL)
{
m_charcoalUsed = true;
@ -250,7 +250,7 @@ void FurnaceTileEntity::tick()
bool FurnaceTileEntity::canBurn()
{
if (items[SLOT_INPUT] == NULL) return false;
ItemInstance *burnResult = FurnaceRecipes::getInstance()->getResult(items[SLOT_INPUT]->getItem()->id);
const ItemInstance *burnResult = FurnaceRecipes::getInstance()->getResult(items[SLOT_INPUT]->getItem()->id);
if (burnResult == NULL) return false;
if (items[SLOT_RESULT] == NULL) return true;
if (!items[SLOT_RESULT]->sameItem_not_shared(burnResult)) return false;
@ -264,7 +264,7 @@ void FurnaceTileEntity::burn()
{
if (!canBurn()) return;
ItemInstance *result = FurnaceRecipes::getInstance()->getResult(items[SLOT_INPUT]->getItem()->id);
const ItemInstance *result = FurnaceRecipes::getInstance()->getResult(items[SLOT_INPUT]->getItem()->id);
if (items[SLOT_RESULT] == NULL) items[SLOT_RESULT] = result->copy();
else if (items[SLOT_RESULT]->id == result->id) items[SLOT_RESULT]->count++;

View file

@ -57,7 +57,7 @@ public:
virtual void setCustomName(const wstring &name);
virtual void load(CompoundTag *base);
virtual void save(CompoundTag *base);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
int getBurnProgress(int max);
int getLitProgress(int max);
bool isLit();

View file

@ -131,7 +131,7 @@ void HopperTileEntity::setCustomName(const wstring &name)
this->name = name;
}
int HopperTileEntity::getMaxStackSize()
int HopperTileEntity::getMaxStackSize() const
{
return Container::LARGE_MAX_STACK_SIZE;
}

View file

@ -35,7 +35,7 @@ public:
virtual wstring getCustomName();
virtual bool hasCustomName();
virtual void setCustomName(const wstring &name);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual bool stillValid(shared_ptr<Player> player);
virtual void startOpen();
virtual void stopOpen();

View file

@ -3,20 +3,3 @@
#include "I18n.h"
Language *I18n::lang = Language::getInstance();
wstring I18n::get(const wstring& id, ...)
{
#ifdef __PSVITA__ // 4J - vita doesn't like having a reference type as the last parameter passed to va_start - we shouldn't need this method anyway
return L"";
#elif _MSC_VER >= 1930 // VS2022+ also disallows va_start with reference types
return id;
#else
va_list va;
va_start(va, id);
return I18n::get(id, va);
#endif
}
wstring I18n::get(const wstring& id, va_list args)
{
return lang->getElement(id, args);
}

View file

@ -10,6 +10,9 @@ private:
static Language *lang;
public:
static wstring get(const wstring& id, ...);
static wstring get(const wstring& id, va_list args);
template<typename ...Args>
static wstring get(Args... args)
{
return lang->getElement(std::forward<Args>(args)...);
}
};

View file

@ -87,7 +87,7 @@ int Inventory::getSlotWithRemainingSpace(shared_ptr<ItemInstance> item)
{
for (unsigned int i = 0; i < items.length; i++)
{
if (items[i] != NULL && items[i]->id == item->id && items[i]->isStackable()
if (items[i] != NULL && items[i]->id == item->id && items[i]->isStackable()
&& items[i]->count < items[i]->getMaxStackSize() && items[i]->count < getMaxStackSize()
&& (!items[i]->isStackedByData() || items[i]->getAuxValue() == item->getAuxValue())
&& ItemInstance::tagMatches(items[i], item))
@ -228,7 +228,7 @@ int Inventory::addResource(shared_ptr<ItemInstance> itemInstance)
if (slot < 0) return count;
if (items[slot] == NULL)
{
items[slot] = ItemInstance::clone(itemInstance);
items[slot] = ItemInstance::clone(itemInstance);
player->handleCollectItem(itemInstance);
}
return 0;
@ -299,14 +299,14 @@ bool Inventory::removeResource(int type,int iAuxVal)
void Inventory::removeResources(shared_ptr<ItemInstance> item)
{
if(item == NULL) return;
if(item == NULL) return;
int countToRemove = item->count;
for (unsigned int i = 0; i < items.length; i++)
{
if (items[i] != NULL && items[i]->sameItemWithTags(item))
{
int slotCount = items[i]->count;
int slotCount = items[i]->count;
items[i]->count -= countToRemove;
if(slotCount < countToRemove)
{
@ -387,7 +387,7 @@ bool Inventory::add(shared_ptr<ItemInstance> item)
{
player->handleCollectItem(item);
player->awardStat(
player->awardStat(
GenericStats::itemsCollected(item->id, item->getAuxValue()),
GenericStats::param_itemsCollected(item->id, item->getAuxValue(), item->GetCount()));
@ -475,7 +475,7 @@ void Inventory::setItem(unsigned int slot, shared_ptr<ItemInstance> item)
else
{
items[slot] = item;
}
}
player->handleCollectItem(item);
/*
ItemInstanceArray& pile = items;
@ -592,7 +592,7 @@ bool Inventory::hasCustomName()
return false;
}
int Inventory::getMaxStackSize()
int Inventory::getMaxStackSize() const
{
return MAX_INVENTORY_STACK_SIZE;
}

View file

@ -81,7 +81,7 @@ public:
wstring getName();
wstring getCustomName();
bool hasCustomName();
int getMaxStackSize();
int getMaxStackSize() const;
bool canDestroy(Tile *tile);
shared_ptr<ItemInstance> getArmor(int layer);
int getArmorValue();

View file

@ -291,12 +291,12 @@ void Item::staticCtor()
Item::helmet_iron = (ArmorItem *) ( ( new ArmorItem(50, ArmorItem::ArmorMaterial::IRON, 2, ArmorItem::SLOT_HEAD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, eMaterial_iron) ->setIconName(L"helmetIron")->setDescriptionId(IDS_ITEM_HELMET_IRON)->setUseDescriptionId(IDS_DESC_HELMET_IRON) );
Item::helmet_diamond = (ArmorItem *) ( ( new ArmorItem(54, ArmorItem::ArmorMaterial::DIAMOND, 3, ArmorItem::SLOT_HEAD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, eMaterial_diamond) ->setIconName(L"helmetDiamond")->setDescriptionId(IDS_ITEM_HELMET_DIAMOND)->setUseDescriptionId(IDS_DESC_HELMET_DIAMOND) );
Item::helmet_gold = (ArmorItem *) ( ( new ArmorItem(58, ArmorItem::ArmorMaterial::GOLD, 4, ArmorItem::SLOT_HEAD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, eMaterial_gold) ->setIconName(L"helmetGold")->setDescriptionId(IDS_ITEM_HELMET_GOLD)->setUseDescriptionId(IDS_DESC_HELMET_GOLD) );
Item::chestplate_leather = (ArmorItem *) ( ( new ArmorItem(43, ArmorItem::ArmorMaterial::CLOTH, 0, ArmorItem::SLOT_TORSO) ) ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, eMaterial_cloth) ->setIconName(L"chestplateCloth")->setDescriptionId(IDS_ITEM_CHESTPLATE_CLOTH)->setUseDescriptionId(IDS_DESC_CHESTPLATE_LEATHER) );
Item::chestplate_iron = (ArmorItem *) ( ( new ArmorItem(51, ArmorItem::ArmorMaterial::IRON, 2, ArmorItem::SLOT_TORSO) ) ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, eMaterial_iron) ->setIconName(L"chestplateIron")->setDescriptionId(IDS_ITEM_CHESTPLATE_IRON)->setUseDescriptionId(IDS_DESC_CHESTPLATE_IRON) );
Item::chestplate_diamond = (ArmorItem *) ( ( new ArmorItem(55, ArmorItem::ArmorMaterial::DIAMOND, 3, ArmorItem::SLOT_TORSO) ) ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, eMaterial_diamond) ->setIconName(L"chestplateDiamond")->setDescriptionId(IDS_ITEM_CHESTPLATE_DIAMOND)->setUseDescriptionId(IDS_DESC_CHESTPLATE_DIAMOND) );
Item::chestplate_gold = (ArmorItem *) ( ( new ArmorItem(59, ArmorItem::ArmorMaterial::GOLD, 4, ArmorItem::SLOT_TORSO) ) ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, eMaterial_gold) ->setIconName(L"chestplateGold")->setDescriptionId(IDS_ITEM_CHESTPLATE_GOLD)->setUseDescriptionId(IDS_DESC_CHESTPLATE_GOLD) );
Item::leggings_leather = (ArmorItem *) ( ( new ArmorItem(44, ArmorItem::ArmorMaterial::CLOTH, 0, ArmorItem::SLOT_LEGS) ) ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, eMaterial_cloth) ->setIconName(L"leggingsCloth")->setDescriptionId(IDS_ITEM_LEGGINGS_CLOTH)->setUseDescriptionId(IDS_DESC_LEGGINGS_LEATHER) );
Item::leggings_iron = (ArmorItem *) ( ( new ArmorItem(52, ArmorItem::ArmorMaterial::IRON, 2, ArmorItem::SLOT_LEGS) ) ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, eMaterial_iron) ->setIconName(L"leggingsIron")->setDescriptionId(IDS_ITEM_LEGGINGS_IRON)->setUseDescriptionId(IDS_DESC_LEGGINGS_IRON) );
Item::leggings_diamond = (ArmorItem *) ( ( new ArmorItem(56, ArmorItem::ArmorMaterial::DIAMOND, 3, ArmorItem::SLOT_LEGS) ) ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, eMaterial_diamond) ->setIconName(L"leggingsDiamond")->setDescriptionId(IDS_ITEM_LEGGINGS_DIAMOND)->setUseDescriptionId(IDS_DESC_LEGGINGS_DIAMOND) );
@ -319,14 +319,14 @@ void Item::staticCtor()
// 4J-PB - todo - add materials and base types to the ones below
Item::bucket_empty = ( new BucketItem(69, 0) ) ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_water)->setIconName(L"bucket")->setDescriptionId(IDS_ITEM_BUCKET)->setUseDescriptionId(IDS_DESC_BUCKET)->setMaxStackSize(16);
Item::bowl = ( new Item(25) ) ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_wood)->setIconName(L"bowl")->setDescriptionId(IDS_ITEM_BOWL)->setUseDescriptionId(IDS_DESC_BOWL)->setMaxStackSize(64);
Item::bucket_water = ( new BucketItem(70, Tile::water_Id) ) ->setIconName(L"bucketWater")->setDescriptionId(IDS_ITEM_BUCKET_WATER)->setCraftingRemainingItem(Item::bucket_empty)->setUseDescriptionId(IDS_DESC_BUCKET_WATER);
Item::bucket_lava = ( new BucketItem(71, Tile::lava_Id) ) ->setIconName(L"bucketLava")->setDescriptionId(IDS_ITEM_BUCKET_LAVA)->setCraftingRemainingItem(Item::bucket_empty)->setUseDescriptionId(IDS_DESC_BUCKET_LAVA);
Item::bucket_milk = ( new MilkBucketItem(79) )->setIconName(L"milk")->setDescriptionId(IDS_ITEM_BUCKET_MILK)->setCraftingRemainingItem(Item::bucket_empty)->setUseDescriptionId(IDS_DESC_BUCKET_MILK);
Item::bow = (BowItem *)( new BowItem(5) ) ->setIconName(L"bow")->setBaseItemTypeAndMaterial(eBaseItemType_bow, eMaterial_bow) ->setDescriptionId(IDS_ITEM_BOW)->setUseDescriptionId(IDS_DESC_BOW);
Item::arrow = ( new Item(6) ) ->setIconName(L"arrow")->setBaseItemTypeAndMaterial(eBaseItemType_bow, eMaterial_arrow) ->setDescriptionId(IDS_ITEM_ARROW)->setUseDescriptionId(IDS_DESC_ARROW);
Item::compass = ( new CompassItem(89) ) ->setIconName(L"compass")->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, eMaterial_compass) ->setDescriptionId(IDS_ITEM_COMPASS)->setUseDescriptionId(IDS_DESC_COMPASS);
Item::clock = ( new ClockItem(91) ) ->setIconName(L"clock")->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, eMaterial_clock) ->setDescriptionId(IDS_ITEM_CLOCK)->setUseDescriptionId(IDS_DESC_CLOCK);
Item::map = (MapItem *) ( new MapItem(102) ) ->setIconName(L"map")->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, eMaterial_map) ->setDescriptionId(IDS_ITEM_MAP)->setUseDescriptionId(IDS_DESC_MAP);
@ -357,7 +357,7 @@ void Item::staticCtor()
->setBaseItemTypeAndMaterial(eBaseItemType_giltFruit,eMaterial_apple)->setIconName(L"appleGold")->setDescriptionId(IDS_ITEM_APPLE_GOLD);//->setUseDescriptionId(IDS_DESC_GOLDENAPPLE);
Item::sign = ( new SignItem(67) ) ->setBaseItemTypeAndMaterial(eBaseItemType_HangingItem, eMaterial_wood)->setIconName(L"sign")->setDescriptionId(IDS_ITEM_SIGN)->setUseDescriptionId(IDS_DESC_SIGN);
Item::minecart = ( new MinecartItem(72, Minecart::TYPE_RIDEABLE) ) ->setIconName(L"minecart")->setDescriptionId(IDS_ITEM_MINECART)->setUseDescriptionId(IDS_DESC_MINECART);
@ -396,7 +396,7 @@ void Item::staticCtor()
Item::cookie = ( new FoodItem(101, 2, FoodConstants::FOOD_SATURATION_POOR, false) ) ->setIconName(L"cookie")->setDescriptionId(IDS_ITEM_COOKIE)->setUseDescriptionId(IDS_DESC_COOKIE);
Item::shears = (ShearsItem *)( new ShearsItem(103) ) ->setIconName(L"shears")->setBaseItemTypeAndMaterial(eBaseItemType_devicetool, eMaterial_shears)->setDescriptionId(IDS_ITEM_SHEARS)->setUseDescriptionId(IDS_DESC_SHEARS);
Item::shears = (ShearsItem *)( new ShearsItem(103) ) ->setIconName(L"shears")->setBaseItemTypeAndMaterial(eBaseItemType_devicetool, eMaterial_shears)->setDescriptionId(IDS_ITEM_SHEARS)->setUseDescriptionId(IDS_DESC_SHEARS);
Item::melon = (new FoodItem(104, 2, FoodConstants::FOOD_SATURATION_LOW, false)) ->setIconName(L"melon")->setDescriptionId(IDS_ITEM_MELON_SLICE)->setUseDescriptionId(IDS_DESC_MELON_SLICE);
@ -455,7 +455,7 @@ void Item::staticCtor()
// putting the fire charge in as a torch, so that it stacks without being near the middle of the selection boxes
Item::fireball = (new FireChargeItem(129)) ->setBaseItemTypeAndMaterial(eBaseItemType_torch, eMaterial_setfire)->setIconName(L"fireball")->setDescriptionId(IDS_ITEM_FIREBALL)->setUseDescriptionId(IDS_DESC_FIREBALL);
Item::frame = (new HangingEntityItem(133,eTYPE_ITEM_FRAME)) ->setBaseItemTypeAndMaterial(eBaseItemType_HangingItem, eMaterial_glass)->setIconName(L"frame")->setDescriptionId(IDS_ITEM_ITEMFRAME)->setUseDescriptionId(IDS_DESC_ITEMFRAME);
// TU12
Item::skull = (new SkullItem(141)) ->setIconName(L"skull")->setDescriptionId(IDS_ITEM_SKULL)->setUseDescriptionId(IDS_DESC_SKULL);
@ -501,7 +501,7 @@ void Item::staticCtor()
void Item::staticInit()
{
Stats::buildItemStats();
}
}
_Tier::Tier(int level, int uses, float speed, float damage, int enchantmentValue) :
@ -668,7 +668,7 @@ shared_ptr<ItemInstance> Item::useTimeDepleted(shared_ptr<ItemInstance> itemInst
return itemInstance;
}
int Item::getMaxStackSize()
int Item::getMaxStackSize() const
{
return maxStackSize;
}
@ -711,7 +711,7 @@ bool Item::canBeDepleted()
/**
* Returns true when the item was used to deal more than default damage
*
*
* @param itemInstance
* @param mob
* @param attacker
@ -724,7 +724,7 @@ bool Item::hurtEnemy(shared_ptr<ItemInstance> itemInstance, shared_ptr<LivingEnt
/**
* Returns true when the item was used to mine more efficiently
*
*
* @param itemInstance
* @param tile
* @param x

View file

@ -72,8 +72,8 @@ public:
eMaterial_stoneSmooth,
eMaterial_netherbrick,
eMaterial_ender,
eMaterial_glass,
eMaterial_blaze,
eMaterial_glass,
eMaterial_blaze,
eMaterial_magic,
eMaterial_melon,
eMaterial_setfire,
@ -421,13 +421,13 @@ public:
static const int bow_Id = 261;
static const int arrow_Id = 262;
static const int coal_Id = 263;
static const int diamond_Id = 264;
static const int diamond_Id = 264;
static const int ironIngot_Id = 265;
static const int goldIngot_Id = 266;
static const int sword_iron_Id = 267;
static const int sword_wood_Id = 268;
static const int sword_wood_Id = 268;
static const int shovel_wood_Id = 269;
static const int pickAxe_wood_Id = 270;
static const int pickAxe_wood_Id = 270;
static const int hatchet_wood_Id = 271;
static const int sword_stone_Id = 272;
static const int shovel_stone_Id = 273;
@ -437,7 +437,7 @@ public:
static const int shovel_diamond_Id = 277;
static const int pickAxe_diamond_Id = 278;
static const int hatchet_diamond_Id = 279;
static const int stick_Id = 280;
static const int stick_Id = 280;
static const int bowl_Id = 281;
static const int mushroomStew_Id = 282;
static const int sword_gold_Id = 283;
@ -452,7 +452,7 @@ public:
static const int hoe_iron_Id = 292;
static const int hoe_diamond_Id = 293;
static const int hoe_gold_Id = 294;
static const int seeds_wheat_Id = 295;
static const int seeds_wheat_Id = 295;
static const int wheat_Id = 296;
static const int bread_Id = 297;
@ -485,7 +485,7 @@ public:
static const int porkChop_raw_Id = 319;
static const int porkChop_cooked_Id = 320;
static const int painting_Id = 321;
static const int apple_gold_Id = 322;
static const int apple_gold_Id = 322;
static const int sign_Id = 323;
static const int door_wood_Id = 324;
static const int bucket_empty_Id = 325;
@ -501,7 +501,7 @@ public:
static const int bucket_milk_Id = 335;
static const int brick_Id = 336;
static const int clay_Id = 337;
static const int reeds_Id = 338;
static const int reeds_Id = 338;
static const int paper_Id = 339;
static const int book_Id = 340;
static const int slimeBall_Id = 341;
@ -514,7 +514,7 @@ public:
static const int yellowDust_Id = 348;
static const int fish_raw_Id = 349;
static const int fish_cooked_Id = 350;
static const int dye_powder_Id = 351;
static const int dye_powder_Id = 351;
static const int bone_Id = 352;
static const int sugar_Id = 353;
static const int cake_Id = 354;
@ -574,7 +574,7 @@ public:
static const int record_12_Id = 2266;
// 4J-PB - this one isn't playable in the PC game, but is fine in ours
static const int record_08_Id = 2267;
static const int record_08_Id = 2267;
// TU9
static const int fireball_Id = 385;
@ -668,7 +668,7 @@ public:
virtual bool TestUse(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player);
virtual shared_ptr<ItemInstance> use(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player);
virtual shared_ptr<ItemInstance> useTimeDepleted(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player);
virtual int getMaxStackSize();
virtual int getMaxStackSize() const;
virtual int getLevelDataForAuxValue(int auxValue);
bool isStackedByData();
@ -686,7 +686,7 @@ public:
/**
* Returns true when the item was used to deal more than default damage
*
*
* @param itemInstance
* @param mob
* @param attacker
@ -696,7 +696,7 @@ public:
/**
* Returns true when the item was used to mine more efficiently
*
*
* @param itemInstance
* @param tile
* @param x

View file

@ -31,17 +31,17 @@ void ItemInstance::_init(int id, int count, int auxValue)
this->m_bForceNumberDisplay=false;
}
ItemInstance::ItemInstance(Tile *tile)
ItemInstance::ItemInstance(Tile *tile)
{
_init(tile->id, 1, 0);
}
ItemInstance::ItemInstance(Tile *tile, int count)
ItemInstance::ItemInstance(Tile *tile, int count)
{
_init(tile->id, count, 0);
}
// 4J-PB - added
ItemInstance::ItemInstance(MapItem *item, int count)
ItemInstance::ItemInstance(MapItem *item, int count)
{
_init(item->id, count, 0);
}
@ -51,19 +51,19 @@ ItemInstance::ItemInstance(Tile *tile, int count, int auxValue)
_init(tile->id, count, auxValue);
}
ItemInstance::ItemInstance(Item *item)
ItemInstance::ItemInstance(Item *item)
{
_init(item->id, 1, 0);
}
ItemInstance::ItemInstance(Item *item, int count)
ItemInstance::ItemInstance(Item *item, int count)
{
_init(item->id, count, 0);
}
ItemInstance::ItemInstance(Item *item, int count, int auxValue)
ItemInstance::ItemInstance(Item *item, int count, int auxValue)
{
_init(item->id, count, auxValue);
}
@ -89,7 +89,7 @@ ItemInstance::~ItemInstance()
if(tag != NULL) delete tag;
}
shared_ptr<ItemInstance> ItemInstance::remove(int count)
shared_ptr<ItemInstance> ItemInstance::remove(int count)
{
shared_ptr<ItemInstance> ii = shared_ptr<ItemInstance>( new ItemInstance(id, count, auxValue) );
if (tag != NULL) ii->tag = (CompoundTag *) tag->copy();
@ -123,17 +123,17 @@ bool ItemInstance::useOn(shared_ptr<Player> player, Level *level, int x, int y,
return getItem()->useOn(shared_from_this(), player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnOnly);
}
float ItemInstance::getDestroySpeed(Tile *tile)
float ItemInstance::getDestroySpeed(Tile *tile)
{
return getItem()->getDestroySpeed(shared_from_this(), tile);
}
bool ItemInstance::TestUse(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player)
bool ItemInstance::TestUse(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player)
{
return getItem()->TestUse( itemInstance, level, player);
}
shared_ptr<ItemInstance> ItemInstance::use(Level *level, shared_ptr<Player> player)
shared_ptr<ItemInstance> ItemInstance::use(Level *level, shared_ptr<Player> player)
{
return getItem()->use(shared_from_this(), level, player);
}
@ -143,7 +143,7 @@ shared_ptr<ItemInstance> ItemInstance::useTimeDepleted(Level *level, shared_ptr<
return getItem()->useTimeDepleted(shared_from_this(), level, player);
}
CompoundTag *ItemInstance::save(CompoundTag *compoundTag)
CompoundTag *ItemInstance::save(CompoundTag *compoundTag)
{
compoundTag->putShort(L"id", (short) id);
compoundTag->putByte(L"Count", (byte) count);
@ -169,7 +169,7 @@ void ItemInstance::load(CompoundTag *compoundTag)
}
}
int ItemInstance::getMaxStackSize()
int ItemInstance::getMaxStackSize() const
{
return getItem()->getMaxStackSize();
}
@ -179,7 +179,7 @@ bool ItemInstance::isStackable()
return getMaxStackSize() > 1 && (!isDamageableItem() || !isDamaged());
}
bool ItemInstance::isDamageableItem()
bool ItemInstance::isDamageableItem()
{
return Item::items[id]->getMaxDamage() > 0;
}
@ -187,7 +187,7 @@ bool ItemInstance::isDamageableItem()
/**
* Returns true if this item type only can be stacked with items that have
* the same auxValue data.
*
*
* @return
*/
@ -196,7 +196,7 @@ bool ItemInstance::isStackedByData()
return Item::items[id]->isStackedByData();
}
bool ItemInstance::isDamaged()
bool ItemInstance::isDamaged()
{
return isDamageableItem() && auxValue > 0;
}
@ -280,13 +280,13 @@ void ItemInstance::hurtAndBreak(int dmg, shared_ptr<LivingEntity> owner)
void ItemInstance::hurtEnemy(shared_ptr<LivingEntity> mob, shared_ptr<Player> attacker)
{
//bool used =
//bool used =
Item::items[id]->hurtEnemy(shared_from_this(), mob, attacker);
}
void ItemInstance::mineBlock(Level *level, int tile, int x, int y, int z, shared_ptr<Player> owner)
void ItemInstance::mineBlock(Level *level, int tile, int x, int y, int z, shared_ptr<Player> owner)
{
//bool used =
//bool used =
Item::items[id]->mineBlock( shared_from_this(), level, tile, x, y, z, owner);
}
@ -342,7 +342,7 @@ bool ItemInstance::tagMatches(shared_ptr<ItemInstance> a, shared_ptr<ItemInstanc
return true;
}
bool ItemInstance::matches(shared_ptr<ItemInstance> a, shared_ptr<ItemInstance> b)
bool ItemInstance::matches(shared_ptr<ItemInstance> a, shared_ptr<ItemInstance> b)
{
if (a == NULL && b == NULL) return true;
if (a == NULL || b == NULL) return false;
@ -368,7 +368,7 @@ bool ItemInstance::matches(shared_ptr<ItemInstance> b)
/**
* Checks if this item is the same item as the other one, disregarding the
* 'count' value.
*
*
* @param b
* @return
*/
@ -393,17 +393,17 @@ bool ItemInstance::sameItemWithTags(shared_ptr<ItemInstance> b)
}
// 4J Stu - Added this for the one time when we compare with a non-shared pointer
bool ItemInstance::sameItem_not_shared(ItemInstance *b)
bool ItemInstance::sameItem_not_shared(const ItemInstance *b)
{
return id == b->id && auxValue == b->auxValue;
}
unsigned int ItemInstance::getUseDescriptionId()
unsigned int ItemInstance::getUseDescriptionId()
{
return Item::items[id]->getUseDescriptionId(shared_from_this());
}
unsigned int ItemInstance::getDescriptionId(int iData /*= -1*/)
unsigned int ItemInstance::getDescriptionId(int iData /*= -1*/)
{
return Item::items[id]->getDescriptionId(shared_from_this());
}
@ -420,7 +420,7 @@ shared_ptr<ItemInstance> ItemInstance::clone(shared_ptr<ItemInstance> item)
return item == NULL ? nullptr : item->copy();
}
wstring ItemInstance::toString()
wstring ItemInstance::toString()
{
//return count + "x" + Item::items[id]->getDescriptionId() + "@" + auxValue;
@ -661,7 +661,7 @@ vector<HtmlString> *ItemInstance::getHoverText(shared_ptr<Player> player, bool a
lines->push_back(it->second->getHoverText(it->first));
}
}
// Delete modifiers map
for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it)
{
@ -760,17 +760,17 @@ bool ItemInstance::mayBePlacedInAdventureMode()
return getItem()->mayBePlacedInAdventureMode();
}
bool ItemInstance::isFramed()
bool ItemInstance::isFramed()
{
return frame != NULL;
}
void ItemInstance::setFramed(shared_ptr<ItemFrame> frame)
void ItemInstance::setFramed(shared_ptr<ItemFrame> frame)
{
this->frame = frame;
}
shared_ptr<ItemFrame> ItemInstance::getFrame()
shared_ptr<ItemFrame> ItemInstance::getFrame()
{
return frame;
}
@ -807,8 +807,8 @@ attrAttrModMap *ItemInstance::getAttributeModifiers()
CompoundTag *entry = entries->get(i);
AttributeModifier *attribute = SharedMonsterAttributes::loadAttributeModifier(entry);
// 4J Not sure why but this is a check that the attribute ID is not empty
/*if (attribute->getId()->getLeastSignificantBits() != 0 && attribute->getId()->getMostSignificantBits() != 0)
// 4J Not sure why but this is a check that the attribute ID is not empty
/*if (attribute->getId()->getLeastSignificantBits() != 0 && attribute->getId()->getMostSignificantBits() != 0)
{*/
result->insert(std::pair<eATTRIBUTE_ID, AttributeModifier *>(static_cast<eATTRIBUTE_ID>(entry->getInt(L"ID")), attribute));
/*}*/
@ -848,7 +848,7 @@ int ItemInstance::get4JData()
}
}
// 4J Added - to show strength on potions
bool ItemInstance::hasPotionStrengthBar()
bool ItemInstance::hasPotionStrengthBar()
{
// exclude a bottle of water from this
if((id==Item::potion_Id) && (auxValue !=0))// && (!MACRO_POTION_IS_AKWARD(auxValue))) 4J-PB leaving the bar on an awkward potion so we can differentiate it from a water bottle
@ -859,7 +859,7 @@ bool ItemInstance::hasPotionStrengthBar()
return false;
}
int ItemInstance::GetPotionStrength()
int ItemInstance::GetPotionStrength()
{
if(MACRO_POTION_IS_INSTANTDAMAGE(auxValue) || MACRO_POTION_IS_INSTANTHEALTH(auxValue) )
{

View file

@ -77,12 +77,12 @@ public:
int getIconType();
bool useOn(shared_ptr<Player> player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false);
float getDestroySpeed(Tile *tile);
bool TestUse(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player);
bool TestUse(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player);
shared_ptr<ItemInstance> use(Level *level, shared_ptr<Player> player);
shared_ptr<ItemInstance> useTimeDepleted(Level *level, shared_ptr<Player> player);
CompoundTag *save(CompoundTag *compoundTag);
void load(CompoundTag *compoundTag);
int getMaxStackSize();
int getMaxStackSize() const;
bool isStackable();
bool isDamageableItem();
bool isStackedByData();
@ -113,7 +113,7 @@ private:
public:
bool sameItem(shared_ptr<ItemInstance> b);
bool sameItemWithTags(shared_ptr<ItemInstance> b); //4J Added
bool sameItem_not_shared(ItemInstance *b); // 4J Stu - Added this for the one time I need it
bool sameItem_not_shared(const ItemInstance *b); // 4J Stu - Added this for the one time I need it
virtual unsigned int getUseDescriptionId(); // 4J Added
virtual unsigned int getDescriptionId(int iData = -1);
virtual ItemInstance *setDescriptionId(unsigned int id);

View file

@ -14,37 +14,12 @@ Language *Language::getInstance()
return singleton;
}
/* 4J Jev, creates 2 identical functions.
wstring Language::getElement(const wstring& elementId)
{
return elementId;
} */
wstring Language::getElement(const wstring& elementId, ...)
{
#ifdef __PSVITA__ // 4J - vita doesn't like having a reference type as the last parameter passed to va_start - we shouldn't need this method anyway
return L"";
#elif _MSC_VER >= 1930 // VS2022+ also disallows va_start with reference types
return elementId;
#else
va_list args;
va_start(args, elementId);
return getElement(elementId, args);
#endif
}
wstring Language::getElement(const wstring& elementId, va_list args)
{
// 4J TODO
return elementId;
}
wstring Language::getElementName(const wstring& elementId)
std::wstring Language::getElementName(const std::wstring& elementId)
{
return elementId;
}
wstring Language::getElementDescription(const wstring& elementId)
std::wstring Language::getElementDescription(const std::wstring& elementId)
{
return elementId;
}

View file

@ -1,5 +1,7 @@
#pragma once
#include <string>
class Language
{
private:
@ -7,8 +9,11 @@ private:
public:
Language();
static Language *getInstance();
wstring getElement(const wstring& elementId, ...);
wstring getElement(const wstring& elementId, va_list args);
wstring getElementName(const wstring& elementId);
wstring getElementDescription(const wstring& elementId);
template<typename...Args>
inline std::wstring getElement(const std::wstring& elementId, Args...)
{
return elementId;
}
std::wstring getElementName(const std::wstring& elementId);
std::wstring getElementDescription(const std::wstring& elementId);
};

View file

@ -596,7 +596,14 @@ void MapItemSavedData::mergeInMapData(shared_ptr<MapItemSavedData> dataToAdd)
void MapItemSavedData::removeItemFrameDecoration(shared_ptr<ItemInstance> item)
{
AUTO_VAR(frameDecoration, nonPlayerDecorations.find( item->getFrame()->entityId ) );
if ( !item )
return;
std::shared_ptr<ItemFrame> frame = item->getFrame();
if ( !frame )
return;
auto frameDecoration = nonPlayerDecorations.find(frame->entityId);
if ( frameDecoration != nonPlayerDecorations.end() )
{
delete frameDecoration->second;

View file

@ -105,7 +105,7 @@ bool MerchantContainer::hasCustomName()
return false;
}
int MerchantContainer::getMaxStackSize()
int MerchantContainer::getMaxStackSize() const
{
return Container::LARGE_MAX_STACK_SIZE;
}

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