diff options
| author | daoge_cmd <3523206925@qq.com> | 2026-03-01 12:16:08 +0800 |
|---|---|---|
| committer | daoge_cmd <3523206925@qq.com> | 2026-03-01 12:16:08 +0800 |
| commit | b691c43c44ff180d10e7d4a9afc83b98551ff586 (patch) | |
| tree | 3e9849222cbc6ba49f2f1fc6e5fe7179632c7390 /Minecraft.Client/Common/Network/Sony | |
| parent | def8cb415354ac390b7e89052a50605285f1aca9 (diff) | |
Initial commit
Diffstat (limited to 'Minecraft.Client/Common/Network/Sony')
19 files changed, 5101 insertions, 0 deletions
diff --git a/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.cpp b/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.cpp new file mode 100644 index 00000000..9c750e95 --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.cpp @@ -0,0 +1,114 @@ +#include "stdafx.h" +#include "NetworkPlayerSony.h" + +NetworkPlayerSony::NetworkPlayerSony(SQRNetworkPlayer *qnetPlayer) +{ + m_sqrPlayer = qnetPlayer; + m_pSocket = NULL; +} + +unsigned char NetworkPlayerSony::GetSmallId() +{ + return m_sqrPlayer->GetSmallId(); +} + +void NetworkPlayerSony::SendData(INetworkPlayer *player, const void *pvData, int dataSize, bool lowPriority) +{ + // TODO - handle priority + m_sqrPlayer->SendData( ((NetworkPlayerSony *)player)->m_sqrPlayer, pvData, dataSize ); +} + +bool NetworkPlayerSony::IsSameSystem(INetworkPlayer *player) +{ + return m_sqrPlayer->IsSameSystem(((NetworkPlayerSony *)player)->m_sqrPlayer); +} + +int NetworkPlayerSony::GetSendQueueSizeBytes( INetworkPlayer *player, bool lowPriority ) +{ + return 0; // TODO +} + +int NetworkPlayerSony::GetSendQueueSizeMessages( INetworkPlayer *player, bool lowPriority ) +{ + return 0; // TODO +} + +int NetworkPlayerSony::GetCurrentRtt() +{ + return 0; // TODO +} + +bool NetworkPlayerSony::IsHost() +{ + return m_sqrPlayer->IsHost(); +} + +bool NetworkPlayerSony::IsGuest() +{ + return false; // TODO +} + +bool NetworkPlayerSony::IsLocal() +{ + return m_sqrPlayer->IsLocal(); +} + +int NetworkPlayerSony::GetSessionIndex() +{ + return m_sqrPlayer->GetSessionIndex(); +} + +bool NetworkPlayerSony::IsTalking() +{ + return m_sqrPlayer->IsTalking(); +} + +bool NetworkPlayerSony::IsMutedByLocalUser(int userIndex) +{ + return m_sqrPlayer->IsMutedByLocalUser(userIndex); +} + +bool NetworkPlayerSony::HasVoice() +{ + return m_sqrPlayer->HasVoice(); +} + +bool NetworkPlayerSony::HasCamera() +{ + return false; // TODO +} + +int NetworkPlayerSony::GetUserIndex() +{ + return m_sqrPlayer->GetLocalPlayerIndex(); +} + +void NetworkPlayerSony::SetSocket(Socket *pSocket) +{ + m_pSocket = pSocket; +} + +Socket *NetworkPlayerSony::GetSocket() +{ + return m_pSocket; +} + +const wchar_t *NetworkPlayerSony::GetOnlineName() +{ + return m_sqrPlayer->GetName(); +} + +wstring NetworkPlayerSony::GetDisplayName() +{ + return m_sqrPlayer->GetName(); +} + +PlayerUID NetworkPlayerSony::GetUID() +{ + return m_sqrPlayer->GetUID(); +} + +void NetworkPlayerSony::SetUID(PlayerUID UID) +{ + m_sqrPlayer->SetUID(UID); +} diff --git a/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.h b/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.h new file mode 100644 index 00000000..5c8605fb --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/NetworkPlayerSony.h @@ -0,0 +1,39 @@ +#pragma once + +#include "..\..\Common\Network\NetworkPlayerInterface.h" +#include "SQRNetworkPlayer.h" + +// This is an implementation of the INetworkPlayer interface, for Sony platforms. It effectively wraps the SQRNetworkPlayer class in a non-platform-specific way. + +class NetworkPlayerSony : public INetworkPlayer +{ +public: + // Common player interface + NetworkPlayerSony(SQRNetworkPlayer *sqrPlayer); + virtual unsigned char GetSmallId(); + virtual void SendData(INetworkPlayer *player, const void *pvData, int dataSize, bool lowPriority); + virtual bool IsSameSystem(INetworkPlayer *player); + virtual int GetSendQueueSizeBytes( INetworkPlayer *player, bool lowPriority ); + virtual int GetSendQueueSizeMessages( INetworkPlayer *player, bool lowPriority ); + virtual int GetCurrentRtt(); + virtual bool IsHost(); + virtual bool IsGuest(); + virtual bool IsLocal(); + virtual int GetSessionIndex(); + virtual bool IsTalking(); + virtual bool IsMutedByLocalUser(int userIndex); + virtual bool HasVoice(); + virtual bool HasCamera(); + virtual int GetUserIndex(); + virtual void SetSocket(Socket *pSocket); + virtual Socket *GetSocket(); + virtual const wchar_t *GetOnlineName(); + virtual wstring GetDisplayName(); + virtual PlayerUID GetUID(); + + void SetUID(PlayerUID UID); + +private: + SQRNetworkPlayer *m_sqrPlayer; + Socket *m_pSocket; +}; diff --git a/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp new file mode 100644 index 00000000..009993cb --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp @@ -0,0 +1,1462 @@ +#include "stdafx.h" +#include "..\..\..\Minecraft.World\Socket.h" +#include "..\..\..\Minecraft.World\StringHelpers.h" +#include "PlatformNetworkManagerSony.h" +#include "NetworkPlayerSony.h" +#include "..\..\Common\Network\GameNetworkManager.h" + +CPlatformNetworkManagerSony *g_pPlatformNetworkManager; + +bool CPlatformNetworkManagerSony::IsLocalGame() +{ + return m_bIsOfflineGame; +} +bool CPlatformNetworkManagerSony::IsPrivateGame() +{ + return m_bIsPrivateGame; +} +bool CPlatformNetworkManagerSony::IsLeavingGame() +{ + return m_bLeavingGame; +} +void CPlatformNetworkManagerSony::ResetLeavingGame() +{ + m_bLeavingGame = false; +} + + +void CPlatformNetworkManagerSony::HandleStateChange(SQRNetworkManager::eSQRNetworkManagerState oldState, SQRNetworkManager::eSQRNetworkManagerState newState, bool idleReasonIsSessionFull) +{ + static const char * c_apszStateNames[] = + { + "SNM_STATE_INITIALISING", + "SNM_STATE_INITIALISE_FAILED", + "SNM_STATE_IDLE", + "SNM_STATE_HOSTING", + "SNM_STATE_JOINING", + "SNM_STATE_STARTING", + "SNM_STATE_PLAYING", + "SNM_STATE_LEAVING", + "SNM_STATE_ENDING", + }; + + app.DebugPrintf( "Network State: %s ==> %s\n", + c_apszStateNames[ oldState ], + c_apszStateNames[ newState ] ); + + if( newState == SQRNetworkManager::SNM_STATE_HOSTING ) + { + m_bLeavingGame = false; + m_bLeaveGameOnTick = false; + m_bHostChanged = false; + g_NetworkManager.StateChange_AnyToHosting(); + } + else if( newState == SQRNetworkManager::SNM_STATE_JOINING ) + { + // 4J Stu - We may be accepting an invite from the DLC menu, so hide the icon +#ifdef __ORBIS__ + sceNpCommerceHidePsStoreIcon(); +#elif defined __PSVITA__ + sceNpCommerce2HidePsStoreIcon(); +#endif + m_bLeavingGame = false; + m_bLeaveGameOnTick = false; + m_bHostChanged = false; + g_NetworkManager.StateChange_AnyToJoining(); + } + else if( newState == SQRNetworkManager::SNM_STATE_IDLE && oldState == SQRNetworkManager::SNM_STATE_JOINING ) + { + if( idleReasonIsSessionFull ) + { + g_NetworkManager.StateChange_JoiningToIdle(JOIN_FAILED_SERVER_FULL); + } + else + { + g_NetworkManager.StateChange_JoiningToIdle(JOIN_FAILED_NONSPECIFIC); + } + } + else if( newState == SQRNetworkManager::SNM_STATE_IDLE && oldState == SQRNetworkManager::SNM_STATE_HOSTING ) + { + m_bLeavingGame = true; + } + else if( newState == SQRNetworkManager::SNM_STATE_STARTING ) + { + m_lastPlayerEventTimeStart = app.getAppTime(); + + g_NetworkManager.StateChange_AnyToStarting(); + } + // Fix for #93148 - TCR 001: BAS Game Stability: Title will crash for the multiplayer client if host of the game will exit during the clients loading to created world. + // 4J Stu - If the client joins just as the host is exiting, then they can skip to leaving without passing through ending + else if( newState == SQRNetworkManager::SNM_STATE_ENDING ) + { + g_NetworkManager.StateChange_AnyToEnding( oldState == SQRNetworkManager::SNM_STATE_PLAYING ); + + // 4J-PB - Only the host can leave here - the clients will hang if m_bLeavingGame is set to true here + if( m_pSQRNet->IsHost() ) + { + m_bLeavingGame = true; + } + } + + if( newState == SQRNetworkManager::SNM_STATE_IDLE ) + { + // On PS3, sometimes we're getting a SNM_STATE_ENDING transition to SNM_STATE_IDLE on joining, because the server context being deleted sets the state away from SNM_STATE_JOINING before we detect + // the cause for the disconnection. This means we don't pick up on the joining->idle transition. Set disconnection reason here too for this case. + if( idleReasonIsSessionFull ) + { + app.SetDisconnectReason( DisconnectPacket::eDisconnect_ServerFull ); + } + g_NetworkManager.StateChange_AnyToIdle(); + } +} + +void CPlatformNetworkManagerSony::HandleDataReceived(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, unsigned char *data, unsigned int dataSize) +{ + if(m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_ENDING) + { + return; + } + + if( playerTo->IsHost() ) + { + // If we are the host we care who this came from + //app.DebugPrintf( "Pushing data into host read queue for user \"%ls\"\n", pPlayerFrom->GetGamertag()); + // Push this data into the read queue for the player that sent it + INetworkPlayer *pPlayerFrom = getNetworkPlayer(playerFrom); + Socket *socket = pPlayerFrom->GetSocket(); + + if(socket != NULL) + socket->pushDataToQueue(data, dataSize, false); + } + else + { + // If we are not the host the message must have come from the host, so we care more about who it is addressed to + INetworkPlayer *pPlayerTo = getNetworkPlayer(playerTo); + Socket *socket = pPlayerTo->GetSocket(); + //app.DebugPrintf( "Pushing data into read queue for user \"%ls\"\n", apPlayersTo[dwPlayer]->GetGamertag()); + if(socket != NULL) + socket->pushDataToQueue(data, dataSize); + } +} + +void CPlatformNetworkManagerSony::HandlePlayerJoined(SQRNetworkPlayer * pSQRPlayer) +{ + const char * pszDescription; + + // 4J Stu - We create a fake socket for every where that we need an INBOUND queue of game data. Outbound + // is all handled by QNet so we don't need that. Therefore each client player has one, and the host has one + // for each client player. + bool createFakeSocket = false; + bool localPlayer = false; + + NetworkPlayerSony *networkPlayer = (NetworkPlayerSony *)addNetworkPlayer(pSQRPlayer); + + if( pSQRPlayer->IsLocal() ) + { + localPlayer = true; + if( pSQRPlayer->IsHost() ) + { + pszDescription = "local host"; + // 4J Stu - No socket for the localhost as it uses a special loopback queue + + m_machineSQRPrimaryPlayers.push_back( pSQRPlayer ); + } + else + { + pszDescription = "local"; + + // We need an inbound queue on all local players to receive data from the host + createFakeSocket = true; + } + } + else + { + if( pSQRPlayer->IsHost() ) + { + pszDescription = "remote host"; + } + else + { + pszDescription = "remote"; + + // If we are the host, then create a fake socket for every remote player + if( m_pSQRNet->IsHost() ) + { + createFakeSocket = true; + } + } + + if( m_pSQRNet->IsHost() && !m_bHostChanged ) + { + // Do we already have a primary player for this system? + bool systemHasPrimaryPlayer = false; + for(AUTO_VAR(it, m_machineSQRPrimaryPlayers.begin()); it < m_machineSQRPrimaryPlayers.end(); ++it) + { + SQRNetworkPlayer *pQNetPrimaryPlayer = *it; + if( pSQRPlayer->IsSameSystem(pQNetPrimaryPlayer) ) + { + systemHasPrimaryPlayer = true; + break; + } + } + if( !systemHasPrimaryPlayer ) + m_machineSQRPrimaryPlayers.push_back( pSQRPlayer ); + } + } + g_NetworkManager.PlayerJoining( networkPlayer ); + + if( createFakeSocket == true && !m_bHostChanged ) + { + g_NetworkManager.CreateSocket( networkPlayer, localPlayer ); + } + +#if 0 + app.DebugPrintf( "Player 0x%p \"%ls\" joined; %s; voice %i; camera %i.\n", + pSQRPlayer, + pSQRPlayer->GetGamertag(), + pszDescription, + (int) pSQRPlayer->HasVoice(), + (int) pSQRPlayer->HasCamera() ); +#endif + + + if( m_pSQRNet->IsHost() ) + { + // 4J-PB - only the host should do this + g_NetworkManager.UpdateAndSetGameSessionData(); + SystemFlagAddPlayer( networkPlayer ); + } + + for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) + { + if(playerChangedCallback[idx] != NULL) + playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, false ); + } + + if(true) // TODO m_pSQRNet->GetState() == QNET_STATE_GAME_PLAY) + { + int localPlayerCount = 0; + for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) + { + if( m_pSQRNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; + } + + float appTime = app.getAppTime(); + + // Only record stats for the primary player here + m_lastPlayerEventTimeStart = appTime; + } +} + +void CPlatformNetworkManagerSony::HandlePlayerLeaving(SQRNetworkPlayer *pSQRPlayer) +{ + //__debugbreak(); + + app.DebugPrintf( "Player 0x%p leaving.\n", + pSQRPlayer ); + + INetworkPlayer *networkPlayer = getNetworkPlayer(pSQRPlayer); + + if( networkPlayer ) + { + // Get our wrapper object associated with this player. + Socket *socket = networkPlayer->GetSocket(); + if( socket != NULL ) + { + // If we are in game then remove this player from the game as well. + // We may get here either from the player requesting to exit the game, + // in which case we they will already have left the game server, or from a disconnection + // where we then have to remove them from the game server + if( m_pSQRNet->IsHost() && !m_bHostChanged ) + { + g_NetworkManager.CloseConnection(networkPlayer); + } + + // Free the wrapper object memory. + // TODO 4J Stu - We may still be using this at the point that the player leaves the session. + // We need this as long as the game server still needs to communicate with the player + //delete socket; + + networkPlayer->SetSocket( NULL ); + } + + if( m_pSQRNet->IsHost() && !m_bHostChanged ) + { + if( isSystemPrimaryPlayer(pSQRPlayer) ) + { + SQRNetworkPlayer *pNewSQRPrimaryPlayer = NULL; + for(unsigned int i = 0; i < m_pSQRNet->GetPlayerCount(); ++i ) + { + SQRNetworkPlayer *pSQRPlayer2 = m_pSQRNet->GetPlayerByIndex( i ); + + if ( pSQRPlayer2 != NULL && pSQRPlayer2 != pSQRPlayer && pSQRPlayer2->IsSameSystem( pSQRPlayer ) ) + { + pNewSQRPrimaryPlayer = pSQRPlayer2; + break; + } + } + AUTO_VAR(it, find( m_machineSQRPrimaryPlayers.begin(), m_machineSQRPrimaryPlayers.end(), pSQRPlayer)); + if( it != m_machineSQRPrimaryPlayers.end() ) + { + m_machineSQRPrimaryPlayers.erase( it ); + } + + if( pNewSQRPrimaryPlayer != NULL ) + m_machineSQRPrimaryPlayers.push_back( pNewSQRPrimaryPlayer ); + } + + g_NetworkManager.UpdateAndSetGameSessionData( networkPlayer ); + 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 ); + } + + if(m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_PLAYING) + { + int localPlayerCount = 0; + for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) + { + if( m_pSQRNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; + } + + float appTime = app.getAppTime(); + m_lastPlayerEventTimeStart = appTime; + } + + removeNetworkPlayer(pSQRPlayer); + } +} + +// Update our external data to match the current internal player slots, and resync back out (host only) +void CPlatformNetworkManagerSony::HandleResyncPlayerRequest(SQRNetworkPlayer **aPlayers) +{ + m_hostGameSessionData.playerCount = 0; + for(int i = 0; i < SQRNetworkManager::MAX_ONLINE_PLAYER_COUNT; i++ ) + { + if( aPlayers[i] ) + { + m_hostGameSessionData.players[i] = aPlayers[i]->GetUID(); + m_hostGameSessionData.playerCount++; + } + else + { + memset(&m_hostGameSessionData.players[i],0,sizeof(m_hostGameSessionData.players[i])); + } + } + m_pSQRNet->UpdateExternalRoomData(); +} + +void CPlatformNetworkManagerSony::HandleAddLocalPlayerFailed(int idx) +{ + g_NetworkManager.AddLocalPlayerFailed(idx); +} + +void CPlatformNetworkManagerSony::HandleDisconnect(bool bLostRoomOnly,bool bPSNSignOut) +{ + g_NetworkManager.HandleDisconnect(bLostRoomOnly,bPSNSignOut); +} + +void CPlatformNetworkManagerSony::HandleInviteReceived( int userIndex, const SQRNetworkManager::PresenceSyncInfo *pInviteInfo) +{ + g_NetworkManager.GameInviteReceived( userIndex, pInviteInfo ); +} + +extern SQRNetworkManager *testSQRNetworkManager; + +bool CPlatformNetworkManagerSony::Initialise(CGameNetworkManager *pGameNetworkManager, int flagIndexSize) +{ + // Create a sony network manager, and go online +#ifdef __ORBIS__ + m_pSQRNet = new SQRNetworkManager_Orbis(this); + m_pSQRNet->Initialise(); +#elif defined __PS3__ + m_pSQRNet = new SQRNetworkManager_PS3(this); + m_pSQRNet->Initialise(); +#else // __PSVITA__ + // m_pSQRNet = new SQRNetworkManager_Vita(this); + m_bUsingAdhocMode = false; + m_pSQRNet_Vita_Adhoc = new SQRNetworkManager_AdHoc_Vita(this); + m_pSQRNet_Vita = new SQRNetworkManager_Vita(this); + + m_pSQRNet = m_pSQRNet_Vita; + + // 4J-PB - seems we can't initialise both adhoc and psn comms - from Rohan - "having adhoc matching and matching2 library initialised together results in undesired behaviour", but probably having other parts initialised also is 'undesirable' + + m_pSQRNet_Vita->Initialise(); + + if(ProfileManager.IsSignedInPSN(ProfileManager.GetPrimaryPad())) + { + // we're signed into the PSN, but we won't be online yet, force a sign-in online here + m_pSQRNet_Vita->AttemptPSNSignIn(NULL, NULL); + } + + +#endif + + m_pGameNetworkManager = pGameNetworkManager; + m_flagIndexSize = flagIndexSize; + g_pPlatformNetworkManager = this; + for( int i = 0; i < XUSER_MAX_COUNT; i++ ) + { + playerChangedCallback[ i ] = NULL; + } + + m_bLeavingGame = false; + m_bLeaveGameOnTick = false; + m_bHostChanged = false; + m_bLeaveRoomWhenLeavingGame = true; + + m_bSearchPending = false; + + m_bIsOfflineGame = false; + m_pSearchParam = NULL; + m_SessionsUpdatedCallback = NULL; + + m_searchResultsCount = 0; + m_pSearchResults = NULL; + + m_lastSearchStartTime = 0; + + // Success! + return true; +} + +void CPlatformNetworkManagerSony::Terminate() +{ + m_pSQRNet->Terminate(); +} + +int CPlatformNetworkManagerSony::GetJoiningReadyPercentage() +{ + return m_pSQRNet->GetJoiningReadyPercentage(); +} + +int CPlatformNetworkManagerSony::CorrectErrorIDS(int IDS) +{ + // Attempts to remap the following messages to provide something that PS3 TCRs are happier with + // + // IDS_CONNECTION_LOST - "Connection lost" + // IDS_CONNECTION_FAILED - "Connection failed" + // IDS_CONNECTION_LOST_LIVE - "Connection to "PSN" was lost. Exiting to the main menu." + // IDS_CONNECTION_LOST_LIVE_NO_EXIT - "Connection to "PSN" was lost." + // IDS_CONNECTION_LOST_SERVER - "Connection to the server was lost. Exiting to the main menu." + // + // Map to: + // + // IDS_ERROR_NETWORK - "A network error has occurred" + // IDS_ERROR_NETWORK_TITLE - "Network Error" + // IDS_ERROR_NETWORK_EXIT - "A network error has occurred. Exiting to Main Menu." + // IDS_ERROR_PSN_SIGN_OUT - You have been signed out from the "PSN". + // IDS_ERROR_PSN_SIGN_OUT_EXIT - You have been signed out from the "PSN". Exiting to Main Menu + + // Determine if we'd prefer to present errors as a signing out issue, rather than a network issue, based on whether we have a network connection at all or not + bool preferSignoutError = false; + int state; +#ifdef __PS3__ + int ret = cellNetCtlGetState( &state ); + int IPObtainedState = CELL_NET_CTL_STATE_IPObtained; +#elif defined __ORBIS__ + int ret = sceNetCtlGetState( &state ); + int IPObtainedState = SCE_NET_CTL_STATE_IPOBTAINED; +#elif defined __PSVITA__ + int ret = sceNetCtlInetGetState( &state ); + int IPObtainedState = SCE_NET_CTL_STATE_IPOBTAINED; +#endif + if( ret == 0 ) + { + if( state == IPObtainedState ) + { + preferSignoutError = true; + } + } + +#ifdef __PSVITA__ + // If we're in ad-hoc mode this problem definitely wasn't PSN related + if (usingAdhocMode()) preferSignoutError = false; +#endif + + // If we're the host we haven't lost connection to the server + if (IDS == IDS_CONNECTION_LOST_SERVER && g_NetworkManager.IsHost()) + { + IDS = IDS_CONNECTION_LOST_LIVE; + } + + switch(IDS) + { + case IDS_CONNECTION_LOST: + case IDS_CONNECTION_FAILED: + return IDS_ERROR_NETWORK_TITLE; + case IDS_CONNECTION_LOST_LIVE: + if( preferSignoutError ) + { + return IDS_ERROR_PSN_SIGN_OUT_EXIT; + } + else + { + return IDS_ERROR_NETWORK_EXIT; + } + case IDS_CONNECTION_LOST_LIVE_NO_EXIT: + if( preferSignoutError ) + { + return IDS_ERROR_PSN_SIGN_OUT; + } + else + { + return IDS_ERROR_NETWORK_TITLE; + } + break; +#ifdef __PSVITA__ + case IDS_CONNECTION_LOST_SERVER: + if(preferSignoutError) + { + if(ProfileManager.IsSignedInPSN(ProfileManager.GetPrimaryPad()) == false) + return IDS_ERROR_PSN_SIGN_OUT_EXIT; + } +#endif + default: + return IDS; + } + + +} + +bool CPlatformNetworkManagerSony::isSystemPrimaryPlayer(SQRNetworkPlayer *pSQRPlayer) +{ + bool playerIsSystemPrimary = false; + for(AUTO_VAR(it, m_machineSQRPrimaryPlayers.begin()); it < m_machineSQRPrimaryPlayers.end(); ++it) + { + SQRNetworkPlayer *pSQRPrimaryPlayer = *it; + if( pSQRPrimaryPlayer == pSQRPlayer ) + { + playerIsSystemPrimary = true; + break; + } + } + return playerIsSystemPrimary; +} + +// We call this twice a frame, either side of the render call so is a good place to "tick" things +void CPlatformNetworkManagerSony::DoWork() +{ +#if 0 + DWORD dwNotifyId; + ULONG_PTR ulpNotifyParam; + + while( XNotifyGetNext( + m_notificationListener, + 0, // Any notification + &dwNotifyId, + &ulpNotifyParam) + ) + { + + switch(dwNotifyId) + { + + case XN_SYS_SIGNINCHANGED: + app.DebugPrintf("Signinchanged - %d\n", ulpNotifyParam); + break; + case XN_LIVE_INVITE_ACCEPTED: + // ignore these - we're catching them from the game listener, so we can get the one from the dashboard + break; + default: + m_pIQNet->Notify(dwNotifyId,ulpNotifyParam); + break; + } + + } + + TickSearch(); + + if( m_bLeaveGameOnTick ) + { + m_pIQNet->LeaveGame(m_migrateHostOnLeave); + m_bLeaveGameOnTick = false; + } + + m_pIQNet->DoWork(); +#else + TickSearch(); + + if( m_bLeaveGameOnTick ) + { + m_pSQRNet->LeaveRoom(m_bLeaveRoomWhenLeavingGame); + m_bLeaveGameOnTick = false; + } + + m_pSQRNet->Tick(); +#endif +} + +int CPlatformNetworkManagerSony::GetPlayerCount() +{ + return m_pSQRNet->GetPlayerCount(); +} + +bool CPlatformNetworkManagerSony::ShouldMessageForFullSession() +{ + return false; +} + +int CPlatformNetworkManagerSony::GetOnlinePlayerCount() +{ + return m_pSQRNet->GetOnlinePlayerCount(); +} + +int CPlatformNetworkManagerSony::GetLocalPlayerMask(int playerIndex) +{ + return 1 << playerIndex; +} + +bool CPlatformNetworkManagerSony::AddLocalPlayerByUserIndex( int userIndex ) +{ + return m_pSQRNet->AddLocalPlayerByUserIndex(userIndex); +} + +bool CPlatformNetworkManagerSony::RemoveLocalPlayerByUserIndex( int userIndex ) +{ + SQRNetworkPlayer *pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex(userIndex); + INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pSQRPlayer); + + if(pNetworkPlayer != NULL) + { + Socket *socket = pNetworkPlayer->GetSocket(); + + if( socket != NULL ) + { + // We can't remove the player from qnet until we have stopped using it to communicate + C4JThread* thread = new C4JThread(&CPlatformNetworkManagerSony::RemovePlayerOnSocketClosedThreadProc, pNetworkPlayer, "RemovePlayerOnSocketClosed"); + thread->SetProcessor( CPU_CORE_REMOVE_PLAYER ); + thread->Run(); + } + else + { + // Safe to remove the player straight away + return m_pSQRNet->RemoveLocalPlayerByUserIndex(userIndex); + } + } + return true; +} + +bool CPlatformNetworkManagerSony::IsInStatsEnabledSession() +{ +#if 0 + DWORD dataSize = sizeof(QNET_LIVE_STATS_MODE); + QNET_LIVE_STATS_MODE statsMode; + m_pIQNet->GetOpt(QNET_OPTION_LIVE_STATS_MODE, &statsMode , &dataSize ); + + // Use QNET_LIVE_STATS_MODE_AUTO if there is another way to check if stats are enabled or not + bool statsEnabled = statsMode == QNET_LIVE_STATS_MODE_ENABLED; + return m_pIQNet->GetState() != QNET_STATE_IDLE && statsEnabled; +#endif + return true; +} + +bool CPlatformNetworkManagerSony::SessionHasSpace(unsigned int spaceRequired /*= 1*/) +{ + return m_pSQRNet->SessionHasSpace(spaceRequired); +#if 0 + // This function is used while a session is running, so all players trying to join + // should use public slots, + DWORD publicSlots = 0; + DWORD filledPublicSlots = 0; + DWORD privateSlots = 0; + DWORD filledPrivateSlots = 0; + + DWORD dataSize = sizeof(DWORD); + m_pIQNet->GetOpt(QNET_OPTION_TOTAL_PUBLIC_SLOTS, &publicSlots, &dataSize ); + m_pIQNet->GetOpt(QNET_OPTION_FILLED_PUBLIC_SLOTS, &filledPublicSlots, &dataSize ); + m_pIQNet->GetOpt(QNET_OPTION_TOTAL_PRIVATE_SLOTS, &privateSlots, &dataSize ); + m_pIQNet->GetOpt(QNET_OPTION_FILLED_PRIVATE_SLOTS, &filledPrivateSlots, &dataSize ); + + DWORD spaceLeft = (publicSlots - filledPublicSlots) + (privateSlots - filledPrivateSlots); + + return spaceLeft >= spaceRequired; +#else + return true; +#endif +} + +void CPlatformNetworkManagerSony::SendInviteGUI(int quadrant) +{ + m_pSQRNet->SendInviteGUI(); +} + +bool CPlatformNetworkManagerSony::IsAddingPlayer() +{ + return false; +} + +bool CPlatformNetworkManagerSony::LeaveGame(bool bMigrateHost) +{ + if( m_bLeavingGame ) return true; + + m_bLeavingGame = true; + + // If we are a client, wait for all client connections to close + // TODO Possibly need to do multiple objects depending on how split screen online works + SQRNetworkPlayer *pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex(g_NetworkManager.GetPrimaryPad()); + INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pSQRPlayer); + + if(pNetworkPlayer != NULL) + { + Socket *socket = pNetworkPlayer->GetSocket(); + + if( socket != NULL ) + { + //printf("Waiting for socket closed event\n"); + DWORD result = socket->m_socketClosedEvent->WaitForSignal(INFINITE); + + // The session might be gone once the socket releases + if( IsInSession() ) + { + //printf("Socket closed event has fired\n"); + // 4J Stu - Clear our reference to this socket + pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex(g_NetworkManager.GetPrimaryPad()); + pNetworkPlayer = getNetworkPlayer(pSQRPlayer); + pNetworkPlayer->SetSocket( NULL ); + } + delete socket; + } + else + { + //printf("Socket is already NULL\n"); + } + } + + // If we are the host wait for the game server to end + if(m_pSQRNet->IsHost() && g_NetworkManager.ServerStoppedValid()) + { + m_pSQRNet->EndGame(); + g_NetworkManager.ServerStoppedWait(); + g_NetworkManager.ServerStoppedDestroy(); + } + + return _LeaveGame(bMigrateHost, true); +} + +bool CPlatformNetworkManagerSony::_LeaveGame(bool bMigrateHost, bool bLeaveRoom) +{ + // 4J Stu - Fix for #10490 - TCR 001 BAS Game Stability: When a party of four players leave a world to join another world without saving the title will crash. + // Changed this to make it threadsafe + m_bLeavingGame = true; // Added for Sony platforms but unsure why the 360 doesn't need it - without this, the leaving triggered by this causes the game to respond by leaving again when it transitions to the SNM_STATE_ENDING state + m_bLeaveRoomWhenLeavingGame = bLeaveRoom; + m_bLeaveGameOnTick = true; + m_migrateHostOnLeave = bMigrateHost; + + return true; +} + +void CPlatformNetworkManagerSony::HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, unsigned char privateSlots /*= 0*/) +{ +// #ifdef _XBOX + // 4J Stu - We probably did this earlier as well, but just to be sure! + SetLocalGame( !bOnlineGame ); + SetPrivateGame( bIsPrivate ); + SystemFlagReset(); + + // Make sure that the Primary Pad is in by default + localUsersMask |= GetLocalPlayerMask( g_NetworkManager.GetPrimaryPad() ); + + _HostGame( localUsersMask, publicSlots, privateSlots ); +//#endif +} + +void CPlatformNetworkManagerSony::_HostGame(int usersMask, unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, unsigned char privateSlots /*= 0*/) +{ + // Start hosting a new game + + memset(&m_hostGameSessionData,0,sizeof(m_hostGameSessionData)); + m_hostGameSessionData.netVersion = MINECRAFT_NET_VERSION; + m_hostGameSessionData.isJoinable = !IsPrivateGame(); + m_hostGameSessionData.isReadyToJoin = false; + m_hostGameSessionData.playerCount = 0; + m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); + for( int i = 0; i < SQRNetworkManager::MAX_LOCAL_PLAYER_COUNT; i++ ) + { + if( usersMask & ( 1 << i ) ) + { + m_hostGameSessionData.playerCount++; + } + } + + m_pSQRNet->CreateAndJoinRoom(g_NetworkManager.GetPrimaryPad(),usersMask, &m_hostGameSessionData, sizeof(m_hostGameSessionData), IsLocalGame()); // Should be using: g_NetworkManager.GetLockedProfile() but that isn't being set currently +} + +bool CPlatformNetworkManagerSony::_StartGame() +{ +#if 0 + // Set the options that now allow players to join this game + BOOL enableJip = TRUE; // Must always be true othewise nobody can join the game while in the PLAY state + m_pIQNet->SetOpt( QNET_OPTION_JOIN_IN_PROGRESS_ALLOWED, &enableJip, sizeof BOOL ); + BOOL enableInv = !IsLocalGame(); + m_pIQNet->SetOpt( QNET_OPTION_INVITES_ALLOWED, &enableInv, sizeof BOOL ); + BOOL enablePres = !IsPrivateGame() && !IsLocalGame(); + m_pIQNet->SetOpt( QNET_OPTION_PRESENCE_JOIN_MODE, &enablePres, sizeof BOOL ); + + return ( m_pIQNet->StartGame() == S_OK ); +#else + m_pSQRNet->StartGame(); + return true; +#endif +} + +int CPlatformNetworkManagerSony::JoinGame(FriendSessionInfo *searchResult, int localUsersMask, int primaryUserIndex) +{ + int joinPlayerCount = 0; + for( int i = 0; i < SQRNetworkManager::MAX_LOCAL_PLAYER_COUNT; i++ ) + { + if( localUsersMask & ( 1 << i ) ) + { + joinPlayerCount++; + } + } + GameSessionData *gameSession = (GameSessionData *)(&searchResult->data); + if( ( gameSession->playerCount + joinPlayerCount ) > SQRNetworkManager::MAX_ONLINE_PLAYER_COUNT ) + { + return CGameNetworkManager::JOINGAME_FAIL_SERVER_FULL; + } + + if( m_pSQRNet->JoinRoom(&searchResult->searchResult, localUsersMask) ) + { + return CGameNetworkManager::JOINGAME_SUCCESS; + } + else + { + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } +} + +bool CPlatformNetworkManagerSony::SetLocalGame(bool isLocal) +{ + if( m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_IDLE) + { +#if 0 + QNET_SESSIONTYPE sessionType = isLocal ? QNET_SESSIONTYPE_LOCAL : QNET_SESSIONTYPE_LIVE_STANDARD; + m_pIQNet->SetOpt(QNET_OPTION_TYPE_SESSIONTYPE, &sessionType , sizeof QNET_SESSIONTYPE); + + // The default value for this is QNET_LIVE_STATS_MODE_AUTO, but that decides based on the players + // in when the game starts. As we may want a non-live player to join the game we cannot have stats enabled + // when we create the sessions. As a result of this, the NotifyWriteStats callback will not be called for + // LIVE players that are connected to LIVE so we write their stats data on a state change. + QNET_LIVE_STATS_MODE statsMode = isLocal ? QNET_LIVE_STATS_MODE_DISABLED : QNET_LIVE_STATS_MODE_ENABLED; + m_pIQNet->SetOpt(QNET_OPTION_LIVE_STATS_MODE, &statsMode , sizeof QNET_LIVE_STATS_MODE); + + // Also has a default of QNET_LIVE_PRESENCE_MODE_AUTO as above, although the effects are less of an issue + QNET_LIVE_PRESENCE_MODE presenceMode = isLocal ? QNET_LIVE_PRESENCE_MODE_NOT_ADVERTISED : QNET_LIVE_PRESENCE_MODE_ADVERTISED; + m_pIQNet->SetOpt(QNET_OPTION_LIVE_PRESENCE_MODE, &presenceMode , sizeof QNET_LIVE_PRESENCE_MODE); +#endif + + m_bIsOfflineGame = isLocal; + app.DebugPrintf("Setting as local game: %s\n", isLocal ? "yes" : "no" ); + } + else + { + app.DebugPrintf("Tried to change session type while not in idle or offline state\n"); + } + + return true; +} + +void CPlatformNetworkManagerSony::SetPrivateGame(bool isPrivate) +{ + app.DebugPrintf("Setting as private game: %s\n", isPrivate ? "yes" : "no" ); + m_bIsPrivateGame = isPrivate; +} + +void CPlatformNetworkManagerSony::RegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) +{ + playerChangedCallback[iPad] = callback; + playerChangedCallbackParam[iPad] = callbackParam; +} + +void CPlatformNetworkManagerSony::UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) +{ + if(playerChangedCallbackParam[iPad] == callbackParam) + { + playerChangedCallback[iPad] = NULL; + playerChangedCallbackParam[iPad] = NULL; + } +} + +void CPlatformNetworkManagerSony::HandleSignInChange() +{ + return; +} + +bool CPlatformNetworkManagerSony::_RunNetworkGame() +{ +#if 0 + // We delay actually starting the session so that we know the game server is running by the time the clients try to join + // This does result in a host advantage + HRESULT hr = m_pIQNet->StartGame(); + if(FAILED(hr)) return false; + + // Set the options that now allow players to join this game + BOOL enableJip = TRUE; // Must always be true othewise nobody can join the game while in the PLAY state + m_pIQNet->SetOpt( QNET_OPTION_JOIN_IN_PROGRESS_ALLOWED, &enableJip, sizeof BOOL ); + BOOL enableInv = !IsLocalGame(); + m_pIQNet->SetOpt( QNET_OPTION_INVITES_ALLOWED, &enableInv, sizeof BOOL ); + BOOL enablePres = !IsPrivateGame() && !IsLocalGame(); + m_pIQNet->SetOpt( QNET_OPTION_PRESENCE_JOIN_MODE, &enablePres, sizeof BOOL ); +#endif + if( IsHost() ) + { + m_pSQRNet->StartGame(); + m_hostGameSessionData.isReadyToJoin = true; + m_pSQRNet->UpdateExternalRoomData(); + m_pSQRNet->SetPresenceDataStartHostingGame(); + } + + return true; +} + +// Note that this does less than the xbox equivalent as we have HandleResyncPlayerRequest that is called by the underlying SQRNetworkManager when players are added/removed etc., so this +// call is only used to update the game host settings & then do the final push out of the data. +void CPlatformNetworkManagerSony::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= NULL*/) +{ + if( this->m_bLeavingGame ) + return; + + m_hostGameSessionData.hostPlayerUID = GetHostPlayer()->GetUID(); +#ifdef __PSVITA__ + if(usingAdhocMode()) + { + m_hostGameSessionData.hostPlayerUID.setForAdhoc(); + } +#endif + + m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); + + // If this is called With a pNetworkPlayerLeaving, then the call has ultimately started within SQRNetworkManager::RemoveRemotePlayersAndSync, so we don't need to sync each change + // as that function does a sync at the end of all changes. + if( pNetworkPlayerLeaving == NULL ) + { + m_pSQRNet->UpdateExternalRoomData(); + } +} + +int CPlatformNetworkManagerSony::RemovePlayerOnSocketClosedThreadProc( void* lpParam ) +{ + INetworkPlayer *pNetworkPlayer = (INetworkPlayer *)lpParam; + + Socket *socket = pNetworkPlayer->GetSocket(); + + if( socket != NULL ) + { + //printf("Waiting for socket closed event\n"); + socket->m_socketClosedEvent->WaitForSignal(INFINITE); + + //printf("Socket closed event has fired\n"); + // 4J Stu - Clear our reference to this socket + pNetworkPlayer->SetSocket( NULL ); + delete socket; + } + + return g_pPlatformNetworkManager->RemoveLocalPlayer( pNetworkPlayer ); +} + +bool CPlatformNetworkManagerSony::RemoveLocalPlayer( INetworkPlayer *pNetworkPlayer ) +{ + if( pNetworkPlayer->IsLocal() ) + { + return m_pSQRNet->RemoveLocalPlayerByUserIndex( pNetworkPlayer->GetUserIndex() ); + } + + return true; +} + +CPlatformNetworkManagerSony::PlayerFlags::PlayerFlags(INetworkPlayer *pNetworkPlayer, unsigned int count) +{ + // 4J Stu - Don't assert, just make it a multiple of 8! This count is calculated from a load of separate values, + // and makes tweaking world/render sizes a pain if we hit an assert here + count = (count + 8 - 1) & ~(8 - 1); + //assert( ( count % 8 ) == 0 ); + this->m_pNetworkPlayer = pNetworkPlayer; + this->flags = new unsigned char [ count / 8 ]; + memset( this->flags, 0, count / 8 ); + this->count = count; +} +CPlatformNetworkManagerSony::PlayerFlags::~PlayerFlags() +{ + delete [] flags; +} + +// Add a player to the per system flag storage - if we've already got a player from that system, copy its flags over +void CPlatformNetworkManagerSony::SystemFlagAddPlayer(INetworkPlayer *pNetworkPlayer) +{ + PlayerFlags *newPlayerFlags = new PlayerFlags( pNetworkPlayer, m_flagIndexSize); + // If any of our existing players are on the same system, then copy over flags from that one + for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) + { + if( pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer) ) + { + memcpy( newPlayerFlags->flags, m_playerFlags[i]->flags, m_playerFlags[i]->count / 8 ); + break; + } + } + m_playerFlags.push_back(newPlayerFlags); +} + +// Remove a player from the per system flag storage - just maintains the m_playerFlags vector without any gaps in it +void CPlatformNetworkManagerSony::SystemFlagRemovePlayer(INetworkPlayer *pNetworkPlayer) +{ + for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) + { + if( m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer ) + { + delete m_playerFlags[i]; + m_playerFlags[i] = m_playerFlags.back(); + m_playerFlags.pop_back(); + return; + } + } +} + +void CPlatformNetworkManagerSony::SystemFlagReset() +{ + for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) + { + delete m_playerFlags[i]; + } + m_playerFlags.clear(); +} + +// Set a per system flag - this is done by setting the flag on every player that shares that system +void CPlatformNetworkManagerSony::SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index) +{ + if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return; + if( pNetworkPlayer == NULL ) return; + + for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) + { + if( pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer) ) + { + m_playerFlags[i]->flags[ index / 8 ] |= ( 128 >> ( index % 8 ) ); + } + } +} + +// Get value of a per system flag - can be read from the flags of the passed in player as anything else sent to that +// system should also have been duplicated here +bool CPlatformNetworkManagerSony::SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index) +{ + if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return false; + if( pNetworkPlayer == NULL ) + { + return false; + } + + for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) + { + if( m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer ) + { + return ( ( m_playerFlags[i]->flags[ index / 8 ] & ( 128 >> ( index % 8 ) ) ) != 0 ); + } + } + return false; +} + +wstring CPlatformNetworkManagerSony::GatherStats() +{ +#if 0 + return L"Queue messages: " + _toString(((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_MESSAGES ) ) + + L" Queue bytes: " + _toString( ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_BYTES ) ); +#else + return L""; +#endif +} + +wstring CPlatformNetworkManagerSony::GatherRTTStats() +{ +#if 0 + wstring stats(L"Rtt: "); + + wchar_t stat[32]; + + for(unsigned int i = 0; i < GetPlayerCount(); ++i) + { + SQRNetworkPlayer *pSQRPlayer = ((NetworkPlayerXbox *)GetPlayerByIndex( i ))->GetQNetPlayer(); + + if(!pSQRPlayer->IsLocal()) + { + ZeroMemory(stat,32); + swprintf(stat, 32, L"%d: %d/", i, pSQRPlayer->GetCurrentRtt() ); + stats.append(stat); + } + } + return stats; +#else + return L""; +#endif +} + +void CPlatformNetworkManagerSony::TickSearch() +{ + if( m_bSearchPending ) + { + if( !m_pSQRNet->FriendRoomManagerIsBusy() ) + { + m_searchResultsCount = m_pSQRNet->FriendRoomManagerGetCount(); + delete m_pSearchResults; + m_pSearchResults = new SQRNetworkManager::SessionSearchResult[m_searchResultsCount]; + + for( int i = 0; i < m_searchResultsCount; i++ ) + { + m_pSQRNet->FriendRoomManagerGetRoomInfo(i, &m_pSearchResults[i] ); + } + m_bSearchPending = false; + + if( m_SessionsUpdatedCallback != NULL ) m_SessionsUpdatedCallback(m_pSearchParam); + } + } + else + { + if( !m_pSQRNet->FriendRoomManagerIsBusy() ) + { + // Don't start searches unless we have registered a callback + int searchDelay = MINECRAFT_PS3ROOM_SEARCH_DELAY_MILLISECONDS; +#ifdef __PSVITA__ + // in adhoc mode we can keep searching, as the friend list is populated in callbacks + // 4J Stu - Every second seems a bit much as it makes the friend list flash every time it updates. Changed this to 5 seconds. + if( usingAdhocMode()) + searchDelay = 5000; +#endif + if( m_SessionsUpdatedCallback != NULL && (m_lastSearchStartTime + searchDelay) < GetTickCount() ) + { + if( m_pSQRNet->FriendRoomManagerSearch() ) + { + m_bSearchPending = true; + m_lastSearchStartTime = GetTickCount(); + } + } + } + } +} + +vector<FriendSessionInfo *> *CPlatformNetworkManagerSony::GetSessionList(int iPad, int localPlayers, bool partyOnly) +{ + vector<FriendSessionInfo *> *filteredList = new vector<FriendSessionInfo *>(); + for( int i = 0; i < m_searchResultsCount; i++ ) + { + if( m_pSearchResults[i].m_extData ) + { + FriendSessionInfo *newInfo = new FriendSessionInfo(); + newInfo->displayLabel = new wchar_t[17]; + ZeroMemory(newInfo->displayLabel, sizeof(wchar_t)*17); + // TODO - this mbstowcs shouldn't encounter any non-ascii characters, but I imagine we'll want to actually use the online name here which is UTF-8 + mbstowcs(newInfo->displayLabel, m_pSearchResults[i].m_NpId.handle.data, 17); + newInfo->displayLabelLength = strlen(m_pSearchResults[i].m_NpId.handle.data); + newInfo->hasPartyMember = false; + newInfo->searchResult = m_pSearchResults[i]; + newInfo->sessionId = m_pSearchResults[i].m_sessionId; + memcpy(&newInfo->data, m_pSearchResults[i].m_extData, sizeof(GameSessionData)); + if( ( newInfo->data.isReadyToJoin ) && + ( newInfo->data.isJoinable ) && + ( newInfo->data.netVersion == MINECRAFT_NET_VERSION ) ) + { + filteredList->push_back(newInfo); + } + else + { + delete newInfo; + } + } + } + + return filteredList; +} + +bool CPlatformNetworkManagerSony::GetGameSessionInfo(int iPad, SessionID sessionId, FriendSessionInfo *foundSessionInfo) +{ +#if 0 + HRESULT hr = E_FAIL; + + const XSESSION_SEARCHRESULT *pSearchResult; + const XNQOSINFO * pxnqi; + + if( m_currentSearchResultsCount[iPad] > 0 ) + { + // Loop through all the results. + for( DWORD dwResult = 0; dwResult < m_currentSearchResultsCount[iPad]; dwResult++ ) + { + pSearchResult = &m_pCurrentSearchResults[iPad]->pResults[dwResult]; + + if(memcmp( &pSearchResult->info.sessionID, &sessionId, sizeof(SessionID) ) != 0) continue; + + bool foundSession = false; + FriendSessionInfo *sessionInfo = NULL; + AUTO_VAR(itFriendSession, friendsSessions[iPad].begin()); + for(itFriendSession = friendsSessions[iPad].begin(); itFriendSession < friendsSessions[iPad].end(); ++itFriendSession) + { + sessionInfo = *itFriendSession; + if(memcmp( &pSearchResult->info.sessionID, &sessionInfo->sessionId, sizeof(SessionID) ) == 0) + { + sessionInfo->searchResult = *pSearchResult; + sessionInfo->displayLabel = new wchar_t[100]; + ZeroMemory( sessionInfo->displayLabel, 100 * sizeof(wchar_t) ); + foundSession = true; + break; + } + } + + // We received a search result for a session no longer in our list of friends sessions + if(!foundSession) break; + + // See if this result was contacted successfully via QoS probes. + pxnqi = &m_pCurrentQoSResult[iPad]->axnqosinfo[dwResult]; + if( pxnqi->bFlags & XNET_XNQOSINFO_TARGET_CONTACTED ) + { + + if(pxnqi->cbData > 0) + { + sessionInfo->data = *(GameSessionData *)pxnqi->pbData; + + wstring gamerName = convStringToWstring(sessionInfo->data.hostName); + swprintf(sessionInfo->displayLabel,app.GetString(IDS_GAME_HOST_NAME),L"MWWWWWWWWWWWWWWM");// gamerName.c_str() ); + } + else + { + swprintf(sessionInfo->displayLabel,app.GetString(IDS_GAME_HOST_NAME_UNKNOWN)); + } + sessionInfo->displayLabelLength = wcslen( sessionInfo->displayLabel ); + + // If this host wasn't disabled use this one. + if( !( pxnqi->bFlags & XNET_XNQOSINFO_TARGET_DISABLED ) && + sessionInfo->data.netVersion == MINECRAFT_NET_VERSION && + sessionInfo->data.isJoinable) + { + foundSessionInfo->data = sessionInfo->data; + if(foundSessionInfo->displayLabel != NULL) delete [] foundSessionInfo->displayLabel; + foundSessionInfo->displayLabel = new wchar_t[100]; + memcpy(foundSessionInfo->displayLabel, sessionInfo->displayLabel, 100 * sizeof(wchar_t) ); + foundSessionInfo->displayLabelLength = sessionInfo->displayLabelLength; + foundSessionInfo->hasPartyMember = sessionInfo->hasPartyMember; + foundSessionInfo->searchResult = sessionInfo->searchResult; + foundSessionInfo->sessionId = sessionInfo->sessionId; + + hr = S_OK; + } + } + } + } + + return ( hr == S_OK ); +#else + return false; +#endif +} + +void CPlatformNetworkManagerSony::SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(LPVOID pParam), LPVOID pSearchParam ) +{ + m_SessionsUpdatedCallback = SessionsUpdatedCallback; m_pSearchParam = pSearchParam; +} + +void CPlatformNetworkManagerSony::GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ) +{ + m_pSQRNet->GetExtDataForRoom( foundSession->sessionId.m_RoomId, &foundSession->data, FriendSessionUpdatedFn, pParam); +} + +void CPlatformNetworkManagerSony::ForceFriendsSessionRefresh() +{ + app.DebugPrintf("Resetting friends session search data\n"); + m_lastSearchStartTime = 0; + m_searchResultsCount = 0; + delete m_pSearchResults; + m_pSearchResults = NULL; +} + +INetworkPlayer *CPlatformNetworkManagerSony::addNetworkPlayer(SQRNetworkPlayer *pSQRPlayer) +{ + NetworkPlayerSony *pNetworkPlayer = new NetworkPlayerSony(pSQRPlayer); + pSQRPlayer->SetCustomDataValue((ULONG_PTR)pNetworkPlayer); + currentNetworkPlayers.push_back( pNetworkPlayer ); + return pNetworkPlayer; +} + +void CPlatformNetworkManagerSony::removeNetworkPlayer(SQRNetworkPlayer *pSQRPlayer) +{ + INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pSQRPlayer); + for( AUTO_VAR(it, currentNetworkPlayers.begin()); it != currentNetworkPlayers.end(); it++ ) + { + if( *it == pNetworkPlayer ) + { + currentNetworkPlayers.erase(it); + return; + } + } +} + +INetworkPlayer *CPlatformNetworkManagerSony::getNetworkPlayer(SQRNetworkPlayer *pSQRPlayer) +{ + return pSQRPlayer ? (INetworkPlayer *)(pSQRPlayer->GetCustomDataValue()) : NULL; +} + + +INetworkPlayer *CPlatformNetworkManagerSony::GetLocalPlayerByUserIndex(int userIndex ) +{ + return getNetworkPlayer(m_pSQRNet->GetLocalPlayerByUserIndex(userIndex)); +} + +INetworkPlayer *CPlatformNetworkManagerSony::GetPlayerByIndex(int playerIndex) +{ + return getNetworkPlayer(m_pSQRNet->GetPlayerByIndex(playerIndex)); +} + +INetworkPlayer * CPlatformNetworkManagerSony::GetPlayerByXuid(PlayerUID xuid) +{ + return getNetworkPlayer(m_pSQRNet->GetPlayerByXuid(xuid)); +} + +INetworkPlayer * CPlatformNetworkManagerSony::GetPlayerBySmallId(unsigned char smallId) +{ + return getNetworkPlayer(m_pSQRNet->GetPlayerBySmallId(smallId)); +} + +INetworkPlayer *CPlatformNetworkManagerSony::GetHostPlayer() +{ + return getNetworkPlayer(m_pSQRNet->GetHostPlayer()); +} + +bool CPlatformNetworkManagerSony::IsHost() +{ + return m_pSQRNet->IsHost() && !m_bHostChanged; +} + +bool CPlatformNetworkManagerSony::JoinGameFromInviteInfo( int userIndex, int userMask, const INVITE_INFO *pInviteInfo) +{ + return m_pSQRNet->JoinRoom( pInviteInfo->m_RoomId, pInviteInfo->m_ServerId, userMask, pInviteInfo ); +} + +void CPlatformNetworkManagerSony::SetSessionTexturePackParentId( int id ) +{ + m_hostGameSessionData.texturePackParentId = id; +} + +void CPlatformNetworkManagerSony::SetSessionSubTexturePackId( int id ) +{ + m_hostGameSessionData.subTexturePackId = id; +} + +void CPlatformNetworkManagerSony::Notify(int ID, ULONG_PTR Param) +{ +#if 0 + m_pSQRNet->Notify( ID, Param ); +#endif +} + +bool CPlatformNetworkManagerSony::IsInSession() +{ + return m_pSQRNet->IsInSession(); +} + +bool CPlatformNetworkManagerSony::IsInGameplay() +{ + return m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_PLAYING; +} + +bool CPlatformNetworkManagerSony::IsReadyToPlayOrIdle() +{ + return m_pSQRNet->IsReadyToPlayOrIdle(); +} + +void CPlatformNetworkManagerSony::SetSQRPresenceInfoFromExtData(SQRNetworkManager::PresenceSyncInfo *presence, void *pExtData, SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId) +{ + GameSessionData *gsd = (GameSessionData *)pExtData; + + memcpy(&presence->hostPlayerUID, &gsd->hostPlayerUID, sizeof(GameSessionUID) ); + presence->m_RoomId = roomId; + presence->m_ServerId = serverId; + presence->texturePackParentId = gsd->texturePackParentId; + presence->subTexturePackId = gsd->subTexturePackId; + presence->netVersion = gsd->netVersion; + presence->inviteOnly = !gsd->isJoinable; +} + +void CPlatformNetworkManagerSony::MallocAndSetExtDataFromSQRPresenceInfo(void **pExtData, SQRNetworkManager::PresenceSyncInfo *presence) +{ + GameSessionData *gsd = (GameSessionData *)malloc(sizeof(GameSessionData)); + memset(gsd, 0, sizeof(GameSessionData)); + if( presence->netVersion != 0 ) + { + memcpy(&gsd->hostPlayerUID, &presence->hostPlayerUID, sizeof(GameSessionUID) ); + gsd->texturePackParentId = presence->texturePackParentId; + gsd->subTexturePackId = presence->subTexturePackId; + gsd->netVersion = presence->netVersion; + gsd->isJoinable = !presence->inviteOnly; + gsd->isReadyToJoin = true; + } + *pExtData = gsd; +} + +#ifdef __PSVITA__ +bool CPlatformNetworkManagerSony::setAdhocMode( bool bAdhoc ) +{ + if(m_bUsingAdhocMode != bAdhoc) + { + m_bUsingAdhocMode = bAdhoc; + if(m_bUsingAdhocMode) + { + // uninit the PSN, and init adhoc + if(m_pSQRNet_Vita->IsInitialised()) + { + m_pSQRNet_Vita->UnInitialise(); + } + + if(m_pSQRNet_Vita_Adhoc->IsInitialised()==false) + { + m_pSQRNet_Vita_Adhoc->Initialise(); + } + + m_pSQRNet = m_pSQRNet_Vita_Adhoc; + } + else + { + if(m_pSQRNet_Vita_Adhoc->IsInitialised()) + { + int ret = sceNetCtlAdhocDisconnect(); + // uninit the adhoc, and init psn + m_pSQRNet_Vita_Adhoc->UnInitialise(); + } + + if(m_pSQRNet_Vita->IsInitialised()==false) + { + m_pSQRNet_Vita->Initialise(); + } + + m_pSQRNet = m_pSQRNet_Vita; + } + } + + return true; +} + +void CPlatformNetworkManagerSony::startAdhocMatching( ) +{ + assert(m_pSQRNet == m_pSQRNet_Vita_Adhoc); + ((SQRNetworkManager_AdHoc_Vita*)m_pSQRNet_Vita_Adhoc)->startMatching(); +} + +bool CPlatformNetworkManagerSony::checkValidInviteData(const INVITE_INFO* pInviteInfo) +{ + if(((SQRNetworkManager_Vita*)m_pSQRNet_Vita)->GetHostUID() == pInviteInfo->hostPlayerUID) + { + // we're trying to join a game we're already in, so we just ignore this + return false; + } + else + { + return true; + } +} + + + +#endif // __PSVITA__ diff --git a/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.h b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.h new file mode 100644 index 00000000..258acd83 --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.h @@ -0,0 +1,187 @@ +#pragma once +using namespace std; +#include <vector> +#include "..\..\..\Minecraft.World\C4JThread.h" +#include "..\..\Common\Network\NetworkPlayerInterface.h" +#include "..\..\Common\Network\PlatformNetworkManagerInterface.h" +#include "..\..\Common\Network\SessionInfo.h" +#include "SQRNetworkPlayer.h" + +// This is how often we allow a search for new games +#define MINECRAFT_PS3ROOM_SEARCH_DELAY_MILLISECONDS 30000 + +// This is the Sony platform specific implementation of CPlatformNetworkManager. It is implemented using SQRNetworkManager/SQRNetworkPlayer. There shouldn't be any general game code in here, +// this class is for providing a bridge between the common game-side network implementation, and the lowest level platform specific libraries. + +class CPlatformNetworkManagerSony : public CPlatformNetworkManager, ISQRNetworkManagerListener +{ + friend class CGameNetworkManager; +public: + virtual bool Initialise(CGameNetworkManager *pGameNetworkManager, int flagIndexSize); + virtual void Terminate(); + virtual int GetJoiningReadyPercentage(); + virtual int CorrectErrorIDS(int IDS); + + virtual void DoWork(); + virtual int GetPlayerCount(); + virtual int GetOnlinePlayerCount(); + virtual int GetLocalPlayerMask(int playerIndex); + virtual bool AddLocalPlayerByUserIndex( int userIndex ); + virtual bool RemoveLocalPlayerByUserIndex( int userIndex ); + virtual INetworkPlayer *GetLocalPlayerByUserIndex( int userIndex ); + virtual INetworkPlayer *GetPlayerByIndex(int playerIndex); + virtual INetworkPlayer * GetPlayerByXuid(PlayerUID xuid); + virtual INetworkPlayer * GetPlayerBySmallId(unsigned char smallId); + virtual bool ShouldMessageForFullSession(); + + virtual INetworkPlayer *GetHostPlayer(); + virtual bool IsHost(); + virtual bool JoinGameFromInviteInfo( int userIndex, int userMask, const INVITE_INFO *pInviteInfo); + virtual bool LeaveGame(bool bMigrateHost); + + virtual bool IsInSession(); + virtual bool IsInGameplay(); + virtual bool IsReadyToPlayOrIdle(); + virtual bool IsInStatsEnabledSession(); + virtual bool SessionHasSpace(unsigned int spaceRequired = 1); + + virtual void SendInviteGUI(int quadrant); + virtual bool IsAddingPlayer(); + + virtual void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0); + virtual int JoinGame(FriendSessionInfo *searchResult, int localUsersMask, int primaryUserIndex ); + virtual bool SetLocalGame(bool isLocal); + virtual bool IsLocalGame(); + virtual void SetPrivateGame(bool isPrivate); + virtual bool IsPrivateGame(); + virtual bool IsLeavingGame(); + virtual void ResetLeavingGame(); + + virtual void RegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam); + virtual void UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam); + + virtual void HandleSignInChange(); + + virtual bool _RunNetworkGame(); + +#ifdef __PSVITA__ + bool usingAdhocMode() { return m_bUsingAdhocMode; } + bool setAdhocMode(bool bAdhoc); + void startAdhocMatching(); + bool checkValidInviteData(const INVITE_INFO* pInviteInfo); +#endif + +private: + bool isSystemPrimaryPlayer(SQRNetworkPlayer *pQNetPlayer); + virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom); + virtual void _HostGame(int dwUsersMask, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0); + virtual bool _StartGame(); + +#ifdef __PSVITA__ + bool m_bUsingAdhocMode; + SQRNetworkManager_Vita* m_pSQRNet_Vita; + SQRNetworkManager_AdHoc_Vita* m_pSQRNet_Vita_Adhoc; +#endif + SQRNetworkManager * m_pSQRNet; // pointer to SQRNetworkManager interface + + HANDLE m_notificationListener; + + vector<SQRNetworkPlayer *> m_machineSQRPrimaryPlayers; // collection of players that we deem to be the main one for that system + + bool m_bLeavingGame; + bool m_bLeaveGameOnTick; + bool m_migrateHostOnLeave; + bool m_bHostChanged; + bool m_bLeaveRoomWhenLeavingGame; + + bool m_bIsOfflineGame; + bool m_bIsPrivateGame; + int m_flagIndexSize; + + // This is only maintained by the host, and is not valid on client machines + GameSessionData m_hostGameSessionData; + CGameNetworkManager *m_pGameNetworkManager; +public: + virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL); + +private: + // TODO 4J Stu - Do we need to be able to have more than one of these? + void (*playerChangedCallback[XUSER_MAX_COUNT])(void *callbackParam, INetworkPlayer *pPlayer, bool leaving); + void *playerChangedCallbackParam[XUSER_MAX_COUNT]; + + static int RemovePlayerOnSocketClosedThreadProc( void* lpParam ); + virtual bool RemoveLocalPlayer( INetworkPlayer *pNetworkPlayer ); + + // Things for handling per-system flags + class PlayerFlags + { + public: + INetworkPlayer *m_pNetworkPlayer; + unsigned char *flags; + unsigned int count; + PlayerFlags(INetworkPlayer *pNetworkPlayer, unsigned int count); + ~PlayerFlags(); + }; + vector<PlayerFlags *> m_playerFlags; + void SystemFlagAddPlayer(INetworkPlayer *pNetworkPlayer); + void SystemFlagRemovePlayer(INetworkPlayer *pNetworkPlayer); + void SystemFlagReset(); +public: + virtual void SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index); + virtual bool SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index); + + // For telemetry +private: + float m_lastPlayerEventTimeStart; + +public: + wstring GatherStats(); + wstring GatherRTTStats(); + +private: + vector<FriendSessionInfo *> friendsSessions; + + int m_lastSearchStartTime; + + // The results that will be filled in with the current search + int m_searchResultsCount; + SQRNetworkManager::SessionSearchResult *m_pSearchResults; + + int m_lastSearchPad; + bool m_bSearchPending; + LPVOID m_pSearchParam; + void (*m_SessionsUpdatedCallback)(LPVOID pParam); + + C4JThread* m_SearchingThread; + + void TickSearch(); + + vector<INetworkPlayer *>currentNetworkPlayers; + INetworkPlayer *addNetworkPlayer(SQRNetworkPlayer *pSQRPlayer); + void removeNetworkPlayer(SQRNetworkPlayer *pSQRPlayer); + static INetworkPlayer *getNetworkPlayer(SQRNetworkPlayer *pSQRPlayer); + + virtual void SetSessionTexturePackParentId( int id ); + virtual void SetSessionSubTexturePackId( int id ); + virtual void Notify(int ID, ULONG_PTR Param); + +public: + virtual vector<FriendSessionInfo *> *GetSessionList(int iPad, int localPlayers, bool partyOnly); + virtual bool GetGameSessionInfo(int iPad, SessionID sessionId,FriendSessionInfo *foundSession); + virtual void SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(LPVOID pParam), LPVOID pSearchParam ); + virtual void GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ); + virtual void ForceFriendsSessionRefresh(); + + // ... and the new ones that have been converted to ISQRNetworkManagerListener + virtual void HandleDataReceived(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, unsigned char *data, unsigned int dataSize); + virtual void HandlePlayerJoined(SQRNetworkPlayer *player); + virtual void HandlePlayerLeaving(SQRNetworkPlayer *player); + virtual void HandleStateChange(SQRNetworkManager::eSQRNetworkManagerState oldState, SQRNetworkManager::eSQRNetworkManagerState newState, bool idleReasonIsSessionFull); + virtual void HandleResyncPlayerRequest(SQRNetworkPlayer **aPlayers); + virtual void HandleAddLocalPlayerFailed(int idx); + virtual void HandleDisconnect(bool bLostRoomOnly,bool bPSNSignOut=false); + virtual void HandleInviteReceived( int userIndex, const SQRNetworkManager::PresenceSyncInfo *pInviteInfo); + + static void SetSQRPresenceInfoFromExtData(SQRNetworkManager::PresenceSyncInfo *presence, void *pExtData, SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId); + static void MallocAndSetExtDataFromSQRPresenceInfo(void **pExtData, SQRNetworkManager::PresenceSyncInfo *presence); +}; diff --git a/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.cpp b/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.cpp new file mode 100644 index 00000000..20f2641c --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.cpp @@ -0,0 +1,10 @@ +#include "stdafx.h" + +#include "SQRNetworkManager.h" + +bool SQRNetworkManager::s_safeToRespondToGameBootInvite = false; + +void SQRNetworkManager::SafeToRespondToGameBootInvite() +{ + s_safeToRespondToGameBootInvite = true; +} diff --git a/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.h b/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.h new file mode 100644 index 00000000..c93368d8 --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SQRNetworkManager.h @@ -0,0 +1,313 @@ +#pragma once +#include <np.h> +#ifdef __PS3__ +#include <netex\libnetctl.h> +#include <netex\net.h> +#else +#include <libnetctl.h> +#include <net.h> +#include <np_toolkit.h> +#endif +#include <queue> + +#include <unordered_map> + +class SQRNetworkPlayer; +class ISQRNetworkManagerListener; +class SonyVoiceChat; +class C4JThread; + +// This is the lowest level manager for providing network functionality on Sony platforms. This manages various network activities including the players within a gaming session. +// The game shouldn't directly use this class, it is here to provide functionality required by PlatformNetworkManagerSony. + +class SQRNetworkManager +{ +public: + static const int MAX_LOCAL_PLAYER_COUNT = XUSER_MAX_COUNT; + static const int MAX_ONLINE_PLAYER_COUNT = MINECRAFT_NET_MAX_PLAYERS; + + static const int NP_POOL_SIZE = 128 * 1024; +protected: + friend class SQRNetworkPlayer; + friend class SonyVoiceChat; + + + static const int MAX_FRIENDS = 100; +#ifdef __PS3__ + static const int RUDP_THREAD_PRIORITY = 999; +#else // __ORBIS_ + static const int RUDP_THREAD_PRIORITY = 500; +#endif + static const int RUDP_THREAD_STACK_SIZE = 32878; + static const int MAX_SIMULTANEOUS_INVITES = 10; + + + // This class stores everything about a player that must be synchronised between machines. This syncing is carried out + // by the Matching2 lib by using internal room binary data (ie data that is only visible to current members of a room) + class PlayerSyncData + { + public: + PlayerUID m_UID; // Assigned by the associated player->GetUID() + SceNpMatching2RoomMemberId m_roomMemberId; // Assigned by Matching2 lib, we can use to indicate which machine this player belongs to (note - 16 bits) + unsigned char m_smallId; // Assigned by SQRNetworkManager, to attach a permanent id to this player (until we have to wrap round), to match a similar concept in qnet + unsigned char m_localIdx : 4; // Which local player (by controller index) this represents + unsigned char m_playerCount : 4; + }; + + class RoomSyncData + { + public: + PlayerSyncData players[MAX_ONLINE_PLAYER_COUNT]; + void setPlayerCount(int c) { players[0].m_playerCount = c;} + int getPlayerCount() { return players[0].m_playerCount;} + }; + +public: + class PresenceSyncInfo + { + public: + GameSessionUID hostPlayerUID; + SceNpMatching2RoomId m_RoomId; + SceNpMatching2ServerId m_ServerId; + unsigned int texturePackParentId; + unsigned short netVersion; + unsigned char subTexturePackId; + bool inviteOnly; + }; + + + // Externally exposed state. All internal states are mapped to one of these broader states. + typedef enum + { + SNM_STATE_INITIALISING, + SNM_STATE_INITIALISE_FAILED, + SNM_STATE_IDLE, + + SNM_STATE_HOSTING, + SNM_STATE_JOINING, + + SNM_STATE_STARTING, + SNM_STATE_PLAYING, + + SNM_STATE_LEAVING, + SNM_STATE_ENDING, + } eSQRNetworkManagerState; + + struct SessionID + { + SceNpMatching2RoomId m_RoomId; + SceNpMatching2ServerId m_ServerId; + }; + + struct SessionSearchResult + { + SceNpId m_NpId; + SessionID m_sessionId; + void *m_extData; +#ifdef __PSVITA__ + SceNetInAddr m_netAddr; +#endif + }; + +protected: + + // On initialisation, state should transition from SNM_INT_STATE_UNINITIALISED -> SNM_INT_STATE_SIGNING_IN -> SNM_INT_STATE_SIGNED_IN -> SNM_INT_STATE_STARTING_CONTEXT -> SNM_INT_STATE_IDLE. + // Error indicated if we transition at any point to SNM_INT_STATE_INITIALISE_FAILED. + + // NOTE: If anything changes in here, then the mapping from internal -> external state needs to be updated (m_INTtoEXTStateMappings, defined in the cpp file) + typedef enum + { + SNM_INT_STATE_UNINITIALISED, + SNM_INT_STATE_SIGNING_IN, + SNM_INT_STATE_STARTING_CONTEXT, + SNM_INT_STATE_INITIALISE_FAILED, + + SNM_INT_STATE_IDLE, + SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT, + + SNM_INT_STATE_HOSTING_STARTING_MATCHING_CONTEXT, + SNM_INT_STATE_HOSTING_SEARCHING_FOR_SERVER, + SNM_INT_STATE_HOSTING_SERVER_SEARCH_SERVER_ERROR, + SNM_INT_STATE_HOSTING_SERVER_FOUND, + SNM_INT_STATE_HOSTING_SERVER_SEARCH_CREATING_CONTEXT, + SNM_INT_STATE_HOSTING_SERVER_SEARCH_FAILED, + + SNM_INT_STATE_HOSTING_CREATE_ROOM_SEARCHING_FOR_WORLD, + SNM_INT_STATE_HOSTING_CREATE_ROOM_WORLD_FOUND, + SNM_INT_STATE_HOSTING_CREATE_ROOM_CREATING_ROOM, + SNM_INT_STATE_HOSTING_CREATE_ROOM_SUCCESS, + SNM_INT_STATE_HOSTING_CREATE_ROOM_FAILED, + SNM_INT_STATE_HOSTING_CREATE_ROOM_RESTART_MATCHING_CONTEXT, + SNM_INT_STATE_HOSTING_WAITING_TO_PLAY, + + SNM_INT_STATE_JOINING_STARTING_MATCHING_CONTEXT, + SNM_INT_STATE_JOINING_SEARCHING_FOR_SERVER, + SNM_INT_STATE_JOINING_SERVER_SEARCH_SERVER_ERROR, + SNM_INT_STATE_JOINING_SERVER_FOUND, + SNM_INT_STATE_JOINING_SERVER_SEARCH_CREATING_CONTEXT, + SNM_INT_STATE_JOINING_SERVER_SEARCH_FAILED, + + SNM_INT_STATE_JOINING_JOIN_ROOM, + SNM_INT_STATE_JOINING_JOIN_ROOM_FAILED, + + SNM_INT_STATE_JOINING_WAITING_FOR_LOCAL_PLAYERS, + + SNM_INT_STATE_SERVER_DELETING_CONTEXT, + + SNM_INT_STATE_STARTING, + SNM_INT_STATE_PLAYING, + + SNM_INT_STATE_LEAVING, + SNM_INT_STATE_LEAVING_FAILED, + + SNM_INT_STATE_ENDING, + + SNM_INT_STATE_COUNT + + } eSQRNetworkManagerInternalState; + + typedef enum + { + SNM_FORCE_ERROR_NP2_INIT, + SNM_FORCE_ERROR_NET_INITIALIZE_NETWORK, + SNM_FORCE_ERROR_NET_CTL_INIT, + SNM_FORCE_ERROR_RUDP_INIT, + SNM_FORCE_ERROR_NET_START_DIALOG, + SNM_FORCE_ERROR_MATCHING2_INIT, + SNM_FORCE_ERROR_REGISTER_NP_CALLBACK, + SNM_FORCE_ERROR_GET_NPID, + SNM_FORCE_ERROR_CREATE_MATCHING_CONTEXT, + SNM_FORCE_ERROR_REGISTER_CALLBACKS, + SNM_FORCE_ERROR_CONTEXT_START_ASYNC, + SNM_FORCE_ERROR_SET_EXTERNAL_ROOM_DATA, + SNM_FORCE_ERROR_GET_FRIEND_LIST_ENTRY_COUNT, + SNM_FORCE_ERROR_GET_FRIEND_LIST_ENTRY, + SNM_FORCE_ERROR_GET_USER_INFO_LIST, + SNM_FORCE_ERROR_LEAVE_ROOM, + SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL, + SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL2, + SNM_FORCE_ERROR_CREATE_SERVER_CONTEXT, + SNM_FORCE_ERROR_CREATE_JOIN_ROOM, + SNM_FORCE_ERROR_GET_SERVER_INFO, + SNM_FORCE_ERROR_DELETE_SERVER_CONTEXT, + SNM_FORCE_ERROR_SETSOCKOPT_0, + SNM_FORCE_ERROR_SETSOCKOPT_1, + SNM_FORCE_ERROR_SETSOCKOPT_2, + SNM_FORCE_ERROR_SOCK_BIND, + SNM_FORCE_ERROR_CREATE_RUDP_CONTEXT, + SNM_FORCE_ERROR_RUDP_BIND, + SNM_FORCE_ERROR_RUDP_INIT2, + SNM_FORCE_ERROR_GET_ROOM_EXTERNAL_DATA, + SNM_FORCE_ERROR_GET_SERVER_INFO_DATA, + SNM_FORCE_ERROR_GET_WORLD_INFO_DATA, + SNM_FORCE_ERROR_GET_CREATE_JOIN_ROOM_DATA, + SNM_FORCE_ERROR_GET_USER_INFO_LIST_DATA, + SNM_FORCE_ERROR_GET_JOIN_ROOM_DATA, + SNM_FORCE_ERROR_GET_ROOM_MEMBER_DATA_INTERNAL, + SNM_FORCE_ERROR_GET_ROOM_EXTERNAL_DATA2, + SNM_FORCE_ERROR_CREATE_SERVER_CONTEXT_CALLBACK, + SNM_FORCE_ERROR_SET_ROOM_DATA_CALLBACK, + SNM_FORCE_ERROR_UPDATED_ROOM_DATA, + SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL1, + SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL2, + SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL3, + SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL4, + SNM_FORCE_ERROR_GET_WORLD_INFO_LIST, + SNM_FORCE_ERROR_JOIN_ROOM, + + SNM_FORCE_ERROR_COUNT, + } eSQRForceError; + + + class StateChangeInfo + { + public: + eSQRNetworkManagerState m_oldState; + eSQRNetworkManagerState m_newState; + bool m_idleReasonIsSessionFull; + StateChangeInfo(eSQRNetworkManagerState oldState, eSQRNetworkManagerState newState,bool idleReasonIsSessionFull) : m_oldState(oldState), m_newState(newState), m_idleReasonIsSessionFull(idleReasonIsSessionFull) {} + }; + + std::queue<StateChangeInfo> m_stateChangeQueue; + CRITICAL_SECTION m_csStateChangeQueue; + CRITICAL_SECTION m_csMatching; + + typedef enum + { + SNM_FRIEND_SEARCH_STATE_IDLE, // Idle - search result will be valid (although it may not have any entries) + SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_COUNT, // Getting count of friends in friend list + SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_INFO, // Getting presence/NpId info for each friend + } eSQRNetworkManagerFriendSearchState; + + typedef void (*ServerContextValidCallback)(SQRNetworkManager *manager); + + static bool s_safeToRespondToGameBootInvite; + +public: + + // General + virtual void Tick() = 0; + virtual void Initialise() = 0; +#ifdef __PSVITA__ + virtual void UnInitialise() = 0; // to switch from PSN to Adhoc + virtual bool IsInitialised() = 0; +#endif + virtual void Terminate() = 0; + virtual eSQRNetworkManagerState GetState() = 0; + virtual bool IsHost() = 0; + virtual bool IsReadyToPlayOrIdle() = 0; + virtual bool IsInSession() = 0; + + // Session management + virtual void CreateAndJoinRoom(int hostIndex, int localPlayerMask, void *extData, int extDataSize, bool offline) = 0; + virtual void UpdateExternalRoomData() = 0; + virtual bool FriendRoomManagerIsBusy() = 0; + virtual bool FriendRoomManagerSearch() = 0; + virtual bool FriendRoomManagerSearch2() = 0; + virtual int FriendRoomManagerGetCount() = 0; + virtual void FriendRoomManagerGetRoomInfo(int idx, SessionSearchResult *searchResult) = 0; + virtual bool JoinRoom(SessionSearchResult *searchResult, int localPlayerMask) = 0; + virtual bool JoinRoom(SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId, int localPlayerMask, const SQRNetworkManager::PresenceSyncInfo *presence) = 0; + virtual void StartGame() = 0; + virtual void LeaveRoom(bool bActuallyLeaveRoom) = 0; + virtual void EndGame() = 0; + virtual bool SessionHasSpace(int spaceRequired) = 0; + virtual bool AddLocalPlayerByUserIndex(int idx) = 0; + virtual bool RemoveLocalPlayerByUserIndex(int idx) = 0; + virtual void SendInviteGUI() = 0; + + virtual void GetExtDataForRoom( SceNpMatching2RoomId roomId, void *extData, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ) = 0; + + // Player retrieval + virtual int GetPlayerCount() = 0; + virtual int GetOnlinePlayerCount() = 0; + virtual SQRNetworkPlayer *GetPlayerByIndex(int idx) = 0; + virtual SQRNetworkPlayer *GetPlayerBySmallId(int idx) = 0; + virtual SQRNetworkPlayer *GetPlayerByXuid(PlayerUID xuid) = 0; + virtual SQRNetworkPlayer *GetLocalPlayerByUserIndex(int idx) = 0; + virtual SQRNetworkPlayer *GetHostPlayer() = 0; + + virtual void SetPresenceDataStartHostingGame() = 0; + virtual int GetJoiningReadyPercentage() = 0; + + virtual void LocalDataSend(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, const void *data, unsigned int dataSize) = 0; + virtual int GetSessionIndex(SQRNetworkPlayer *player) = 0; + + static void SafeToRespondToGameBootInvite(); + +}; + + +// Class defining interface to be implemented for class that handles callbacks +class ISQRNetworkManagerListener +{ +public: + virtual void HandleDataReceived(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, unsigned char *data, unsigned int dataSize) = 0; + virtual void HandlePlayerJoined(SQRNetworkPlayer *player) = 0; + virtual void HandlePlayerLeaving(SQRNetworkPlayer *player) = 0; + virtual void HandleStateChange(SQRNetworkManager::eSQRNetworkManagerState oldState, SQRNetworkManager::eSQRNetworkManagerState newState, bool idleReasonIsSessionFull) = 0; + virtual void HandleResyncPlayerRequest(SQRNetworkPlayer **aPlayers) = 0; + virtual void HandleAddLocalPlayerFailed(int idx) = 0; + virtual void HandleDisconnect(bool bLostRoomOnly,bool bPSNSignOut=false) = 0; + virtual void HandleInviteReceived( int userIndex, const SQRNetworkManager::PresenceSyncInfo *pInviteInfo) = 0; +}; diff --git a/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.cpp b/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.cpp new file mode 100644 index 00000000..e244b34c --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.cpp @@ -0,0 +1,399 @@ +#include "stdafx.h" +#include "SQRNetworkPlayer.h" + +#ifdef __PS3__ +#include <cell/rudp.h> +#include "PS3/Network/SonyVoiceChat.h" + +#elif defined __ORBIS__ +#include <rudp.h> +#include "Orbis/Network/SonyVoiceChat_Orbis.h" + +#else // __PSVITA__ +#include <rudp.h> +#include <adhoc_matching.h> +#include "PSVita/Network/SonyVoiceChat_Vita.h" + +#endif + + +static const bool sc_verbose = false; + +int SQRNetworkPlayer::GetSmallId() +{ + return m_ISD.m_smallId; +} + +wchar_t *SQRNetworkPlayer::GetName() +{ + return m_name; +} + +bool SQRNetworkPlayer::IsRemote() +{ + return !IsLocal(); +} + +bool SQRNetworkPlayer::IsHost() +{ + return (m_type == SNP_TYPE_HOST); +} + +bool SQRNetworkPlayer::IsLocal() +{ + // m_host determines whether this *machine* is hosting the game, not this player (which is determined by m_type) + if( m_host ) + { + // If we are the hosting machine, then both the host & local players are local to this machine + return (m_type == SNP_TYPE_HOST) || (m_type == SNP_TYPE_LOCAL); + } + else + { + // Not hosting, just local players are actually physically local + return (m_type == SNP_TYPE_LOCAL) ; + } +} + +int SQRNetworkPlayer::GetLocalPlayerIndex() +{ + return m_localPlayerIdx; +} + +bool SQRNetworkPlayer::IsSameSystem(SQRNetworkPlayer *other) +{ + return (m_roomMemberId == other->m_roomMemberId); +} + +uintptr_t SQRNetworkPlayer::GetCustomDataValue() +{ + return m_customData; +} + +void SQRNetworkPlayer::SetCustomDataValue(uintptr_t data) +{ + m_customData = data; +} + +SQRNetworkPlayer::SQRNetworkPlayer(SQRNetworkManager *manager, eSQRNetworkPlayerType playerType, bool onHost, SceNpMatching2RoomMemberId roomMemberId, int localPlayerIdx, int rudpCtx, PlayerUID *pUID) +{ + m_roomMemberId = roomMemberId; + m_localPlayerIdx = localPlayerIdx; + m_rudpCtx = rudpCtx; + m_flags = 0; + m_type = playerType; + m_host = onHost; + m_manager = manager; + m_customData = 0; + if( pUID ) + { + memcpy(&m_ISD.m_UID,pUID,sizeof(PlayerUID)); +#ifdef __PSVITA__ + if(CGameNetworkManager::usingAdhocMode() && pUID->getOnlineID()[0] == 0) + { + assert(localPlayerIdx == 0); + // player doesn't have an online UID, set it from the player name + m_ISD.m_UID.setForAdhoc(); + } +#endif // __PSVITA__ + } + else + { + memset(&m_ISD.m_UID,0,sizeof(PlayerUID)); + } + SetNameFromUID(); + InitializeCriticalSection(&m_csQueue); +#ifdef __ORBIS__ + if(IsLocal()) + { + SonyVoiceChat_Orbis::initLocalPlayer(m_localPlayerIdx); + } +#endif + +} + +SQRNetworkPlayer::~SQRNetworkPlayer() +{ +#ifdef __ORBIS__ + SQRNetworkManager_Orbis* pMan = (SQRNetworkManager_Orbis*)m_manager; +// pMan->removePlayerFromVoiceChat(this); +// m_roomMemberId = -1; +#endif + DeleteCriticalSection(&m_csQueue); +} + +bool SQRNetworkPlayer::IsReady() +{ + return ( ( m_flags & SNP_FLAG_READY_MASK ) == SNP_FLAG_READY_MASK ); +} + +PlayerUID SQRNetworkPlayer::GetUID() +{ + return m_ISD.m_UID; +} + +void SQRNetworkPlayer::SetUID(PlayerUID UID) +{ + m_ISD.m_UID = UID; + SetNameFromUID(); +} + +bool SQRNetworkPlayer::HasConnectionAndSmallId() +{ + const int reqFlags = ( SNP_FLAG_CONNECTION_COMPLETE | SNP_FLAG_SMALLID_ALLOCATED ); + return (( m_flags & reqFlags) == reqFlags); +} + +void SQRNetworkPlayer::ConnectionComplete() +{ + m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ConnectionComplete\n"); + m_flags |= SNP_FLAG_CONNECTION_COMPLETE; +} + +void SQRNetworkPlayer::SmallIdAllocated(unsigned char smallId) +{ + m_ISD.m_smallId = smallId; + m_flags |= SNP_FLAG_SMALLID_ALLOCATED; + m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Small ID allocated\n"); + + + // If this is a non-network sort of player then flag now as having its small id confirmed + if( ( m_type == SNP_TYPE_HOST ) || + ( m_host && ( m_type == SNP_TYPE_LOCAL ) ) || + ( !m_host && ( m_type == SNP_TYPE_REMOTE ) ) ) + { + m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Small ID confirmed\n"); + + m_flags |= SNP_FLAG_SMALLID_CONFIRMED; + } +} + +void SQRNetworkPlayer::InitialDataReceived(SQRNetworkPlayer::InitSendData *ISD) +{ + assert(m_ISD.m_smallId == ISD->m_smallId); + memcpy(&m_ISD, ISD, sizeof(InitSendData) ); +#ifdef __PSVITA__ + SetNameFromUID(); +#endif + m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Small ID confirmed\n"); + m_flags |= SNP_FLAG_SMALLID_CONFIRMED; +} + +bool SQRNetworkPlayer::HasSmallIdConfirmed() +{ + return ( m_flags & SNP_FLAG_SMALLID_CONFIRMED ); +} + +// To confirm to the host that we are ready, send a single byte with our small id. +void SQRNetworkPlayer::ConfirmReady() +{ +#ifdef __PS3__ + int ret = cellRudpWrite( m_rudpCtx, &m_ISD, sizeof(InitSendData), CELL_RUDP_MSG_LATENCY_CRITICAL ); +#else //__ORBIS__ + int ret = sceRudpWrite( m_rudpCtx, &m_ISD, sizeof(InitSendData), SCE_RUDP_MSG_LATENCY_CRITICAL ); +#endif + // TODO - error handling here? + assert ( ret == sizeof(InitSendData) ); + // Final flag for a local player on the client, as we are now safe to send data on to the host + m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Small ID confirmed\n"); + m_flags |= SNP_FLAG_SMALLID_CONFIRMED; +} + +// Attempt to send data, of any size, from this player to that specified by pPlayerTarget. This may not be possible depending on the two players, due to +// our star shaped network connectivity. Data may be any size, and is copied so on returning from this method it does not need to be preserved. +void SQRNetworkPlayer::SendData( SQRNetworkPlayer *pPlayerTarget, const void *data, unsigned int dataSize ) +{ + // Our network is connected as a star. If we are the host, then we can send to any remote player. If we're a client, we can send only to the host. + // The host can also send to other local players, but this doesn't need to go through Rudp. + if( m_host ) + { + if( ( m_type == SNP_TYPE_HOST ) && ( pPlayerTarget->m_type == SNP_TYPE_LOCAL ) ) + { + // Special internal communication from host to local player + m_manager->LocalDataSend( this, pPlayerTarget, data, dataSize ); + } + else if( ( m_type == SNP_TYPE_LOCAL ) && ( pPlayerTarget->m_type == SNP_TYPE_HOST ) ) + { + // Special internal communication from local player to host + m_manager->LocalDataSend( this, pPlayerTarget, data, dataSize ); + } + else if( ( m_type == SNP_TYPE_HOST ) && ( pPlayerTarget->m_type == SNP_TYPE_REMOTE ) ) + { + // Rudp communication from host to remote player - handled by remote player instance + pPlayerTarget->SendInternal(data,dataSize); + } + else + { + // Can't do any other types of communications + assert(false); + } + } + else + { + if( ( m_type == SNP_TYPE_LOCAL ) && ( pPlayerTarget->m_type == SNP_TYPE_HOST ) ) + { + // Rudp communication from client to host - handled by this player instace + SendInternal(data, dataSize); + } + else + { + // Can't do any other types of communications + assert(false); + } + } +} + +// Internal send function - to simplify the number of mechanisms we have for sending data, this method just adds the data to be send to the player's internal queue, +// and then calls SendMoreInternal. This method can take any size of data, which it will split up into payload size chunks before sending. All input data is copied +// into internal buffers. +void SQRNetworkPlayer::SendInternal(const void *data, unsigned int dataSize) +{ + EnterCriticalSection(&m_csQueue); + + QueuedSendBlock sendBlock; + + unsigned char *dataCurrent = (unsigned char *)data; + unsigned int dataRemaining = dataSize; + + while( dataRemaining ) + { + int dataSize = dataRemaining; + if( dataSize > SNP_MAX_PAYLOAD ) dataSize = SNP_MAX_PAYLOAD; + sendBlock.start = new unsigned char [dataSize]; + sendBlock.end = sendBlock.start + dataSize; + sendBlock.current = sendBlock.start; + memcpy( sendBlock.start, dataCurrent, dataSize); + m_sendQueue.push(sendBlock); + dataRemaining -= dataSize; + dataCurrent += dataSize; + } + + // Now try and send as much as we can + SendMoreInternal(); + + LeaveCriticalSection(&m_csQueue); +} + + + + +// Internal send function. This attempts to send as many elements in the queue as possible until the write function tells us that we can't send any more. This way, +// we are guaranteed that if there *is* anything more in the queue left to send, we'll get a CELL_RUDP_CONTEXT_EVENT_WRITABLE event when whatever we've managed to +// send here is complete, and can continue on. +void SQRNetworkPlayer::SendMoreInternal() +{ + EnterCriticalSection(&m_csQueue); + bool keepSending; + do + { + keepSending = false; + if( m_sendQueue.size() > 0) + { + // Attempt to send the full data in the first element in our queue + unsigned char *data= m_sendQueue.front().current; + int dataSize = m_sendQueue.front().end - m_sendQueue.front().current; +#ifdef __PS3__ + int ret = cellRudpWrite( m_rudpCtx, data, dataSize, 0);//CELL_RUDP_MSG_LATENCY_CRITICAL ); + int wouldBlockFlag = CELL_RUDP_ERROR_WOULDBLOCK; + +#else // __ORBIS__ + int ret = sceRudpWrite( m_rudpCtx, data, dataSize, 0);//CELL_RUDP_MSG_LATENCY_CRITICAL ); + int wouldBlockFlag = SCE_RUDP_ERROR_WOULDBLOCK; +#endif + if( ret == dataSize ) + { + // Fully sent, remove from queue - will loop in the while loop to see if there's anything else in the queue we could send + delete [] m_sendQueue.front().start; + m_sendQueue.pop(); + if( m_sendQueue.size() ) + { + keepSending = true; + } + } + else if( ( ret >= 0 ) || ( ret == wouldBlockFlag ) ) + { + + + // Things left to send - adjust this element in the queue + int remainingBytes; + if( ret >= 0 ) + { + // Only ret bytes sent so far + remainingBytes = dataSize - ret; + assert(remainingBytes > 0 ); + } + else + { + // Is CELL_RUDP_ERROR_WOULDBLOCK, nothing has yet been sent + remainingBytes = dataSize; + } + m_sendQueue.front().current = m_sendQueue.front().end - remainingBytes; + } + } + } while (keepSending); + LeaveCriticalSection(&m_csQueue); +} + +void SQRNetworkPlayer::SetNameFromUID() +{ + mbstowcs(m_name, m_ISD.m_UID.getOnlineID(), 16); + m_name[16] = 0; +#ifdef __PS3__ // only 1 player on vita, and they have to be online (or adhoc), and with PS4 all local players need to be signed in + // Not an online player? Add a suffix with the controller ID on + if( m_ISD.m_UID.isSignedIntoPSN() == 0) + { + int pos = wcslen(m_name); + swprintf(&m_name[pos], 5, L" (%d)", m_ISD.m_UID.getQuadrant() + 1 ); + } +#endif +} + +void SQRNetworkPlayer::SetName(char *name) +{ + mbstowcs(m_name, name, 20); + m_name[20] = 0; +} + +int SQRNetworkPlayer::GetSessionIndex() +{ + return m_manager->GetSessionIndex(this); +} + +bool SQRNetworkPlayer::HasVoice() +{ +#ifdef __ORBIS__ + return SonyVoiceChat_Orbis::hasMicConnected(this); +#elif defined __PSVITA__ + return SonyVoiceChat_Vita::hasMicConnected(this); +#else + return SonyVoiceChat::hasMicConnected(&m_roomMemberId); +#endif +} + +bool SQRNetworkPlayer::IsTalking() +{ +#ifdef __ORBIS__ + return SonyVoiceChat_Orbis::isTalking(this); +#elif defined __PSVITA__ + return SonyVoiceChat_Vita::isTalking(this); +#else + return SonyVoiceChat::isTalking(&m_roomMemberId); +#endif +} + +bool SQRNetworkPlayer::IsMutedByLocalUser(int userIndex) +{ +#ifdef __ORBIS__ +// assert(0); // this is never called, so isn't implemented in the PS4 voice stuff at the moment + return false; +#elif defined __PSVITA__ + return false;// this is never called, so isn't implemented in the Vita voice stuff at the moment +#else + SQRNetworkManager_PS3* pMan = (SQRNetworkManager_PS3*)m_manager; + return SonyVoiceChat::isMutedPlayer(pMan->m_roomSyncData.players[userIndex].m_roomMemberId); +#endif +} diff --git a/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.h b/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.h new file mode 100644 index 00000000..0cd56e8d --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SQRNetworkPlayer.h @@ -0,0 +1,103 @@ +#pragma once +#include "SQRNetworkManager.h" +#include <queue> + +// This is the lowest level class for handling the concept of a player on Sony platforms. This is managed by SQRNetworkManager. The game shouldn't directly communicate +// with this class, as it is wrapped by NetworkPlayerSony which is an implementation of a platform-independent interface INetworkPlayer. + +class SQRNetworkPlayer +{ +#ifdef __ORBIS__ + friend class SQRNetworkManager_Orbis; + friend class SonyVoiceChat_Orbis; +#elif defined __PS3__ + friend class SQRNetworkManager_PS3; +#else // __PSVITA__ + friend class SQRNetworkManager_Vita; + friend class SQRNetworkManager_AdHoc_Vita; + friend class SonyVoiceChat_Vita; +#endif + friend class SQRNetworkManager; + friend class NetworkPlayerSony; + friend class CPlatformNetworkManagerSony; + + int GetSmallId(); + wchar_t *GetName(); + bool IsRemote(); + bool IsHost(); + bool IsLocal(); + int GetLocalPlayerIndex(); + bool IsSameSystem(SQRNetworkPlayer *other); + uintptr_t GetCustomDataValue(); + void SetCustomDataValue(uintptr_t data); + bool HasVoice(); + bool IsTalking(); + bool IsMutedByLocalUser(int userIndex); + + static const int SNP_FLAG_CONNECTION_COMPLETE = 1; // This player has a fully connected Rudp or other local link established (to a remote player if this is on the host, to the host if this is a client) - or isn't expected to have one + static const int SNP_FLAG_SMALLID_ALLOCATED = 2; // This player has a small id allocated + static const int SNP_FLAG_SMALLID_CONFIRMED = 4; // This player's small id has been confirmed as received by the client (only relevant for players using network communications, others set at the same time as allocating) + static const int SNP_FLAG_READY_MASK = 7; // Mask indicated all bits which must be set in the flags for this player to be considered "ready" + + static const int SNP_MAX_PAYLOAD = 1346; // This is the default RUDP payload size - if we want to change this we'll need to use cellRudpSetOption to set something else & adjust segment size + + typedef enum + { + SNP_TYPE_HOST, // This player represents the host + SNP_TYPE_LOCAL, // On host - this player is a local player that needs communicated with specially not using rudp. On clients - this is a local player, where m_rudpCtx is the context used to communicate from this player to/from the host + SNP_TYPE_REMOTE, // On host - this player's m_rupdCtx can be used to communicate from between the host and this player. On clients - this is a remote player that cannot be communicated with + } eSQRNetworkPlayerType; + + class QueuedSendBlock + { + public: + unsigned char *start; + unsigned char *end; + unsigned char *current; + }; + + class InitSendData + { + public: + unsigned char m_smallId; // Id to uniquely and permanently identify this player between machines - assigned by the server + PlayerUID m_UID; + }; + + SQRNetworkPlayer(SQRNetworkManager *manager, eSQRNetworkPlayerType playerType, bool onHost, SceNpMatching2RoomMemberId roomMemberId, int localPlayerIdx, int rudpCtx, PlayerUID *pUID); + ~SQRNetworkPlayer(); + + PlayerUID GetUID(); + void SetUID(PlayerUID UID); + bool HasConnectionAndSmallId(); + bool IsReady(); + void ConnectionComplete(); + void SmallIdAllocated(unsigned char smallId); + void InitialDataReceived(InitSendData *ISD); // Only for remote players as viewed from the host, this is set when the host has received confirmation that the client has received the small id for this player, ie it is now safe to send data to + bool HasSmallIdConfirmed(); + + void SendData( SQRNetworkPlayer *pPlayerTarget, const void *data, unsigned int dataSize ); + + void ConfirmReady(); + void SendInternal(const void *data, unsigned int dataSize); + void SendMoreInternal(); +#ifdef __PSVITA__ + void SendInternal_VitaAdhoc(const void *data, unsigned int dataSize, EAdhocDataTag tag = e_dataTag_Normal); + void SendMoreInternal_VitaAdhoc(); +#endif + void SetNameFromUID(); + void SetName(char *name); + int GetSessionIndex(); + + eSQRNetworkPlayerType m_type; // The player type + bool m_host; // Whether this actual player class is stored on a host (not whether it represents the host, or a player on the host machine) + int m_flags; // Flags reflecting current state of this player + int m_rudpCtx; // Rudp context that can be used to communicate between this player & the host (see comments for eSQRNetworkPlayerType above) + int m_localPlayerIdx; // Index of this player on the machine to which it belongs + SceNpMatching2RoomMemberId m_roomMemberId; // The room member id, effectively a per machine id + InitSendData m_ISD; // Player UID & ID that get sent together to the host when connection is established + SQRNetworkManager *m_manager; // Pointer back to the manager that is managing this player + wchar_t m_name[21]; + uintptr_t m_customData; + CRITICAL_SECTION m_csQueue; + std::queue<QueuedSendBlock> m_sendQueue; +}; diff --git a/Minecraft.Client/Common/Network/Sony/SonyCommerce.cpp b/Minecraft.Client/Common/Network/Sony/SonyCommerce.cpp new file mode 100644 index 00000000..8435cd56 --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SonyCommerce.cpp @@ -0,0 +1,1492 @@ +#include "stdafx.h" + +#include "SonyCommerce.h" +#include "..\PS3Extras\ShutdownManager.h" +#include <sys/event.h> + + +bool SonyCommerce::m_bCommerceInitialised = false; +SceNpCommerce2SessionInfo SonyCommerce::m_sessionInfo; +SonyCommerce::State SonyCommerce::m_state = e_state_noSession; +int SonyCommerce::m_errorCode = 0; +LPVOID SonyCommerce::m_callbackParam = NULL; + +void* SonyCommerce::m_receiveBuffer = NULL; +SonyCommerce::Event SonyCommerce::m_event; +std::queue<SonyCommerce::Message> SonyCommerce::m_messageQueue; +std::vector<SonyCommerce::ProductInfo>* SonyCommerce::m_pProductInfoList = NULL; +SonyCommerce::ProductInfoDetailed* SonyCommerce::m_pProductInfoDetailed = NULL; +SonyCommerce::ProductInfo* SonyCommerce::m_pProductInfo = NULL; + +SonyCommerce::CategoryInfo* SonyCommerce::m_pCategoryInfo = NULL; +const char* SonyCommerce::m_pProductID = NULL; +char* SonyCommerce::m_pCategoryID = NULL; +SonyCommerce::CheckoutInputParams SonyCommerce::m_checkoutInputParams; +SonyCommerce::DownloadListInputParams SonyCommerce::m_downloadInputParams; + +SonyCommerce::CallbackFunc SonyCommerce::m_callbackFunc = NULL; +sys_memory_container_t SonyCommerce::m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; +bool SonyCommerce::m_bUpgradingTrial = false; + +SonyCommerce::CallbackFunc SonyCommerce::m_trialUpgradeCallbackFunc; +LPVOID SonyCommerce::m_trialUpgradeCallbackParam; + +CRITICAL_SECTION SonyCommerce::m_queueLock; + + + +uint32_t SonyCommerce::m_contextId=0; ///< The npcommerce2 context ID +bool SonyCommerce::m_contextCreated=false; ///< npcommerce2 context ID created? +SonyCommerce::Phase SonyCommerce::m_currentPhase = e_phase_stopped; ///< Current commerce2 util +char SonyCommerce::m_commercebuffer[SCE_NP_COMMERCE2_RECV_BUF_SIZE]; + +C4JThread* SonyCommerce::m_tickThread = NULL; +bool SonyCommerce::m_bLicenseChecked=false; // Check the trial/full license for the game + + +SonyCommerce::ProductInfoDetailed s_trialUpgradeProductInfoDetailed; +void SonyCommerce::Delete() +{ + m_pProductInfoList=NULL; + m_pProductInfoDetailed=NULL; + m_pProductInfo=NULL; + m_pCategoryInfo = NULL; + m_pProductID = NULL; + m_pCategoryID = NULL; +} +void SonyCommerce::Init() +{ + int ret; + + assert(m_state == e_state_noSession); + if(!m_bCommerceInitialised) + { + ret = sceNpCommerce2Init(); + if (ret < 0) + { + app.DebugPrintf(4,"sceNpCommerce2Init failed (0x%x)\n", ret); + return; + } + else + { + m_bCommerceInitialised = true; + } + m_pCategoryID=(char *)malloc(sizeof(char) * 100); + InitializeCriticalSection(&m_queueLock); + } + + return ; + +} + + + +void SonyCommerce::CheckForTrialUpgradeKey_Callback(LPVOID param, bool bFullVersion) +{ + ProfileManager.SetFullVersion(bFullVersion); + if(ProfileManager.IsFullVersion()) + { + StorageManager.SetSaveDisabled(false); + ConsoleUIController::handleUnlockFullVersionCallback(); + // licence has been checked, so we're ok to install the trophies now + ProfileManager.InitialiseTrophies( SQRNetworkManager_PS3::GetSceNpCommsId(), + SQRNetworkManager_PS3::GetSceNpCommsSig()); + + } + m_bLicenseChecked=true; +} + +bool SonyCommerce::LicenseChecked() +{ + return m_bLicenseChecked; +} + +void SonyCommerce::CheckForTrialUpgradeKey() +{ + StorageManager.CheckForTrialUpgradeKey(CheckForTrialUpgradeKey_Callback, NULL); +} + +int SonyCommerce::Shutdown() +{ + int ret=0; + if (m_contextCreated) + { + ret = sceNpCommerce2DestroyCtx(m_contextId); + if (ret != 0) + { + return ret; + } + + m_contextId = 0; + m_contextCreated = false; + } + + ret = sceNpCommerce2Term(); + m_bCommerceInitialised = false; + if (ret != 0) + { + return ret; + } + delete m_pCategoryID; + DeleteCriticalSection(&m_queueLock); + + return ret; +} + + + +int SonyCommerce::TickLoop(void* lpParam) +{ + ShutdownManager::HasStarted(ShutdownManager::eCommerceThread); + while( (m_currentPhase != e_phase_stopped) && ShutdownManager::ShouldRun(ShutdownManager::eCommerceThread) ) + { + processEvent(); + processMessage(); + Sleep(16); // sleep for a frame + } + + ShutdownManager::HasFinished(ShutdownManager::eCommerceThread); + + return 0; +} + +int SonyCommerce::getProductList(std::vector<ProductInfo>* productList, char *categoryId) +{ + int ret = 0; + uint32_t requestId; + size_t bufSize = sizeof(m_commercebuffer); + size_t fillSize = 0; + SceNpCommerce2GetCategoryContentsResult result; + SceNpCommerce2CategoryInfo categoryInfo; + SceNpCommerce2ContentInfo contentInfo; + SceNpCommerce2GameProductInfo productInfo; + SceNpCommerce2GameSkuInfo skuInfo; + ProductInfo tempInfo; + std::vector<ProductInfo> tempProductVec; + + if (!m_contextCreated) + { + ret = createContext(); + if (ret < 0) + { + setError(ret); + return ret; + } + } + + // Create request ID + ret = sceNpCommerce2GetCategoryContentsCreateReq(m_contextId, &requestId); + if (ret < 0) + { + setError(ret); + return ret; + } + + // Obtain category content data + ret = sceNpCommerce2GetCategoryContentsStart(requestId, categoryId, 0, SCE_NP_COMMERCE2_GETCAT_MAX_COUNT); + if (ret < 0) + { + sceNpCommerce2DestroyReq(requestId); + setError(ret); + return ret; + } + + ret = sceNpCommerce2GetCategoryContentsGetResult(requestId, m_commercebuffer, bufSize, &fillSize); + if (ret < 0) + { + sceNpCommerce2DestroyReq(requestId); + setError(ret); + return ret; + } + + ret = sceNpCommerce2DestroyReq(requestId); + if (ret < 0) + { + setError(ret); + return ret; + } + + // We have the initial category content data, + // now to take out the category content information. + ret = sceNpCommerce2InitGetCategoryContentsResult(&result, m_commercebuffer, fillSize); + if (ret < 0) + { + setError(ret); + return ret; + } + + // Get the category information + ret = sceNpCommerce2GetCategoryInfo(&result, &categoryInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } + + if(categoryInfo.countOfProduct==0) + { + // There is no DLC + return 0; + } + + // Reserve some space + tempProductVec.reserve(categoryInfo.countOfProduct); + + // For each product, obtain information + for (int i = 0; i < result.rangeOfContents.count; i++) + { + ret = sceNpCommerce2GetContentInfo(&result, i, &contentInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } + + // Only process if it is a product + if (contentInfo.contentType == SCE_NP_COMMERCE2_CONTENT_TYPE_PRODUCT) + { + + // reset tempInfo + memset(&tempInfo, 0x0, sizeof(tempInfo)); + + // Get product info + ret = sceNpCommerce2GetGameProductInfoFromContentInfo(&contentInfo, &productInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } + + // populate our temp struct + + strncpy(tempInfo.productId, productInfo.productId, SCE_NP_COMMERCE2_PRODUCT_ID_LEN); + strncpy(tempInfo.productName, productInfo.productName, SCE_NP_COMMERCE2_PRODUCT_NAME_LEN); + strncpy(tempInfo.shortDescription, productInfo.productShortDescription, SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN); + if(tempInfo.longDescription[0]!=0) + { + strncpy(tempInfo.longDescription, productInfo.productLongDescription, SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN); + } + else + { +#ifdef _DEBUG + strcpy(tempInfo.longDescription,"Missing long description"); +#endif + } + strncpy(tempInfo.spName, productInfo.spName, SCE_NP_COMMERCE2_SP_NAME_LEN); + strncpy(tempInfo.imageUrl, productInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); + tempInfo.releaseDate = productInfo.releaseDate; + + if (productInfo.countOfSku == 1) + { + // Get SKU info + ret = sceNpCommerce2GetGameSkuInfoFromGameProductInfo(&productInfo, 0, &skuInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } + tempInfo.purchasabilityFlag = skuInfo.purchasabilityFlag; + + // Take out the price. Nicely formatted + // but also keep the price as a value in case it's 0 - we need to show "free" for that + tempInfo.ui32Price= skuInfo.price; + ret = sceNpCommerce2GetPrice(m_contextId, tempInfo.price, sizeof(tempInfo.price), skuInfo.price); + + if (ret < 0) + { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } + } + tempProductVec.push_back(tempInfo); + } + } + + // Set our result + *productList = tempProductVec; + + // Destroy the category contents result + ret = sceNpCommerce2DestroyGetCategoryContentsResult(&result); + if (ret < 0) + { + return ret; + } + + return ret; +} + +int SonyCommerce::getCategoryInfo(CategoryInfo *pInfo, char *categoryId) +{ + int ret = 0; + uint32_t requestId; + size_t bufSize = sizeof(m_commercebuffer); + size_t fillSize = 0; + SceNpCommerce2GetCategoryContentsResult result; + SceNpCommerce2CategoryInfo categoryInfo; + SceNpCommerce2ContentInfo contentInfo; + //CategoryInfo tempCatInfo; + CategoryInfoSub tempSubCatInfo; + + if (!m_contextCreated) + { + ret = createContext(); + if (ret < 0) + { + m_errorCode = ret; + return ret; + } + } + + // Create request ID + ret = sceNpCommerce2GetCategoryContentsCreateReq(m_contextId, &requestId); + if (ret < 0) + { + m_errorCode = ret; + return ret; + } + + // Obtain category content data + if (categoryId) + { + ret = sceNpCommerce2GetCategoryContentsStart(requestId, categoryId, 0, SCE_NP_COMMERCE2_GETCAT_MAX_COUNT); + } + else + { + ret = sceNpCommerce2GetCategoryContentsStart(requestId,categoryId, + 0, SCE_NP_COMMERCE2_GETCAT_MAX_COUNT); + } + if (ret < 0) + { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } + + ret = sceNpCommerce2GetCategoryContentsGetResult(requestId, m_commercebuffer, bufSize, &fillSize); + if (ret < 0) + { + if(ret==SCE_NP_COMMERCE2_ERROR_SERVER_MAINTENANCE) + { + app.DebugPrintf(4,"\n--- SCE_NP_COMMERCE2_ERROR_SERVER_MAINTENANCE ---\n\n"); + } + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } + + ret = sceNpCommerce2DestroyReq(requestId); + if (ret < 0) + { + m_errorCode = ret; + return ret; + } + + // We have the initial category content data, + // now to take out the category content information. + ret = sceNpCommerce2InitGetCategoryContentsResult(&result, m_commercebuffer, fillSize); + if (ret < 0) { + m_errorCode = ret; + return ret; + } + + // Get the category information + ret = sceNpCommerce2GetCategoryInfo(&result, &categoryInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + m_errorCode = ret; + return ret; + } + + strcpy(pInfo->current.categoryId, categoryInfo.categoryId); + strcpy(pInfo->current.categoryName, categoryInfo.categoryName); + strcpy(pInfo->current.categoryDescription, categoryInfo.categoryDescription); + strcpy(pInfo->current.imageUrl, categoryInfo.imageUrl); + pInfo->countOfProducts = categoryInfo.countOfProduct; + pInfo->countOfSubCategories = categoryInfo.countOfSubCategory; + + if (categoryInfo.countOfSubCategory > 0) + { + // For each sub category, obtain information + for (int i = 0; i < result.rangeOfContents.count; i++) + { + + ret = sceNpCommerce2GetContentInfo(&result, i, &contentInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + m_errorCode = ret; + return ret; + } + + // Only process if it is a category + if (contentInfo.contentType == SCE_NP_COMMERCE2_CONTENT_TYPE_CATEGORY) + { + + ret = sceNpCommerce2GetCategoryInfoFromContentInfo(&contentInfo, &categoryInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + m_errorCode = ret; + return ret; + } + + strcpy(tempSubCatInfo.categoryId, categoryInfo.categoryId); + strcpy(tempSubCatInfo.categoryName, categoryInfo.categoryName); + strcpy(tempSubCatInfo.categoryDescription, categoryInfo.categoryDescription); + strcpy(tempSubCatInfo.imageUrl, categoryInfo.imageUrl); + + // Add to the list + pInfo->subCategories.push_back(tempSubCatInfo); + } + } + } + + // Set our result + //*info = tempCatInfo; + + // Destroy the category contents result + ret = sceNpCommerce2DestroyGetCategoryContentsResult(&result); + if (ret < 0) { + return ret; + } + + return ret; +} + + +int SonyCommerce::getDetailedProductInfo(ProductInfoDetailed *pInfo, const char *productId, char *categoryId) +{ + int ret = 0; + uint32_t requestId; + size_t bufSize = sizeof(m_commercebuffer); + size_t fillSize = 0; + std::list<SceNpCommerce2ContentRatingDescriptor> ratingDescList; + SceNpCommerce2GetProductInfoResult result; + SceNpCommerce2ContentRatingInfo ratingInfo; + SceNpCommerce2GameProductInfo productInfo; + SceNpCommerce2GameSkuInfo skuInfo; + //ProductInfoDetailed tempInfo; + + if (!m_contextCreated) { + ret = createContext(); + if (ret < 0) { + m_errorCode = ret; + return ret; + } + } + + // Obtain product data + ret = sceNpCommerce2GetProductInfoCreateReq(m_contextId, &requestId); + if (ret < 0) { + m_errorCode = ret; + return ret; + } + + if (categoryId && categoryId[0] != 0) { + ret = sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); + } else { + ret = sceNpCommerce2GetProductInfoStart(requestId, NULL, productId); + } + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } + + ret = sceNpCommerce2GetProductInfoGetResult(requestId, m_commercebuffer, bufSize, &fillSize); + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } + + ret = sceNpCommerce2DestroyReq(requestId); + if (ret < 0) + { + m_errorCode = ret; + return ret; + } + + // Take Out Game Product Information + ret = sceNpCommerce2InitGetProductInfoResult(&result, m_commercebuffer, fillSize); + if (ret < 0) + { + m_errorCode = ret; + return ret; + } + + ret = sceNpCommerce2GetGameProductInfo(&result, &productInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + + // Get rating info + ret = sceNpCommerce2GetContentRatingInfoFromGameProductInfo(&productInfo, &ratingInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + + for (int index = 0; index < ratingInfo.countOfContentRatingDescriptor; index++) + { + SceNpCommerce2ContentRatingDescriptor desc; + sceNpCommerce2GetContentRatingDescriptor(&ratingInfo, index, &desc); + ratingDescList.push_back(desc); + } + + // populate our temp struct + pInfo->ratingDescriptors = ratingDescList; + strncpy(pInfo->productId, productInfo.productId, SCE_NP_COMMERCE2_PRODUCT_ID_LEN); + strncpy(pInfo->productName, productInfo.productName, SCE_NP_COMMERCE2_PRODUCT_NAME_LEN); + strncpy(pInfo->shortDescription, productInfo.productShortDescription, SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN); + strncpy(pInfo->longDescription, productInfo.productLongDescription, SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN); + strncpy(pInfo->legalDescription, productInfo.legalDescription, SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN); + strncpy(pInfo->spName, productInfo.spName, SCE_NP_COMMERCE2_SP_NAME_LEN); + strncpy(pInfo->imageUrl, productInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); + pInfo->releaseDate = productInfo.releaseDate; + strncpy(pInfo->ratingSystemId, ratingInfo.ratingSystemId, SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN); + strncpy(pInfo->ratingImageUrl, ratingInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); + + // Get SKU info + if (productInfo.countOfSku == 1) + { + ret = sceNpCommerce2GetGameSkuInfoFromGameProductInfo(&productInfo, 0, &skuInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + strncpy(pInfo->skuId, skuInfo.skuId, SCE_NP_COMMERCE2_SKU_ID_LEN); + pInfo->purchasabilityFlag = skuInfo.purchasabilityFlag; + + // Take out the price. Nicely formatted + // but also keep the price as a value in case it's 0 - we need to show "free" for that + pInfo->ui32Price= skuInfo.price; + ret = sceNpCommerce2GetPrice(m_contextId, pInfo->price, sizeof(pInfo->price), skuInfo.price); + if (ret < 0) + { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + } + + // Set our result + //*info = tempInfo; + + ret = sceNpCommerce2DestroyGetProductInfoResult(&result); + if (ret < 0) + { + return ret; + } + + return ret; +} + + +int SonyCommerce::addDetailedProductInfo(ProductInfo *info, const char *productId, char *categoryId) +{ + int ret = 0; + uint32_t requestId; + size_t bufSize = sizeof(m_commercebuffer); + size_t fillSize = 0; + std::list<SceNpCommerce2ContentRatingDescriptor> ratingDescList; + SceNpCommerce2GetProductInfoResult result; + SceNpCommerce2ContentRatingInfo ratingInfo; + SceNpCommerce2GameProductInfo productInfo; + SceNpCommerce2GameSkuInfo skuInfo; + //ProductInfoDetailed tempInfo; + + if (!m_contextCreated) + { + ret = createContext(); + if (ret < 0) + { + m_errorCode = ret; + return ret; + } + } + + // Obtain product data + ret = sceNpCommerce2GetProductInfoCreateReq(m_contextId, &requestId); + if (ret < 0) + { + m_errorCode = ret; + return ret; + } + + if (categoryId && categoryId[0] != 0) + { + ret = sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); + } + else + { + ret = sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); + } + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } + + ret = sceNpCommerce2GetProductInfoGetResult(requestId, m_commercebuffer, bufSize, &fillSize); + if (ret < 0) + { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } + + ret = sceNpCommerce2DestroyReq(requestId); + if (ret < 0) + { + m_errorCode = ret; + return ret; + } + + // Take Out Game Product Information + ret = sceNpCommerce2InitGetProductInfoResult(&result, m_commercebuffer, fillSize); + if (ret < 0) + { + m_errorCode = ret; + return ret; + } + + ret = sceNpCommerce2GetGameProductInfo(&result, &productInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + + // Get rating info + ret = sceNpCommerce2GetContentRatingInfoFromGameProductInfo(&productInfo, &ratingInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + + for (int index = 0; index < ratingInfo.countOfContentRatingDescriptor; index++) + { + SceNpCommerce2ContentRatingDescriptor desc; + sceNpCommerce2GetContentRatingDescriptor(&ratingInfo, index, &desc); + ratingDescList.push_back(desc); + } + + // populate our temp struct +// tempInfo.ratingDescriptors = ratingDescList; +// strncpy(tempInfo.productId, productInfo.productId, SCE_NP_COMMERCE2_PRODUCT_ID_LEN); +// strncpy(tempInfo.productName, productInfo.productName, SCE_NP_COMMERCE2_PRODUCT_NAME_LEN); +// strncpy(tempInfo.shortDescription, productInfo.productShortDescription, SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN); + strncpy(info->longDescription, productInfo.productLongDescription, SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN); +// strncpy(tempInfo.legalDescription, productInfo.legalDescription, SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN); +// strncpy(tempInfo.spName, productInfo.spName, SCE_NP_COMMERCE2_SP_NAME_LEN); +// strncpy(tempInfo.imageUrl, productInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); +// tempInfo.releaseDate = productInfo.releaseDate; +// strncpy(tempInfo.ratingSystemId, ratingInfo.ratingSystemId, SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN); +// strncpy(tempInfo.ratingImageUrl, ratingInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); + + // Get SKU info + if (productInfo.countOfSku == 1) + { + ret = sceNpCommerce2GetGameSkuInfoFromGameProductInfo(&productInfo, 0, &skuInfo); + if (ret < 0) + { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + strncpy(info->skuId, skuInfo.skuId, SCE_NP_COMMERCE2_SKU_ID_LEN); + info->purchasabilityFlag = skuInfo.purchasabilityFlag; + info->annotation = skuInfo.annotation; + + // Take out the price. Nicely formatted + // but also keep the price as a value in case it's 0 - we need to show "free" for that + info->ui32Price= skuInfo.price; + ret = sceNpCommerce2GetPrice(m_contextId, info->price, sizeof(info->price), skuInfo.price); + if (ret < 0) + { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + } + else + { + // 4J-PB - more than one sku id! We have to be able to use the sku id returned for a product, so there is not supposed to be more than 1 + app.DebugPrintf("MORE THAN 1 SKU ID FOR %s\n",info->productName); + } + + // Set our result + //*info = tempInfo; + + ret = sceNpCommerce2DestroyGetProductInfoResult(&result); + if (ret < 0) + { + return ret; + } + + return ret; +} + + +int SonyCommerce::checkout(CheckoutInputParams ¶ms) +{ + int ret = 0; + const char *skuIdsTemp[SCE_NP_COMMERCE2_SKU_CHECKOUT_MAX]; + std::list<const char *>::iterator iter = params.skuIds.begin(); + std::list<const char *>::iterator iterEnd = params.skuIds.end(); + + if (!m_contextCreated) { + ret = createContext(); + if (ret < 0) { + return ret; + } + } + + for (int i = 0; i < params.skuIds.size(); i++) { + skuIdsTemp[i] = (const char *)(*iter); + iter++; + } + + ret = sceNpCommerce2DoCheckoutStartAsync(m_contextId, skuIdsTemp, params.skuIds.size(), *params.memContainer); + if (ret < 0) { + return ret; + } + + return CELL_OK; +} + + +int SonyCommerce::downloadList(DownloadListInputParams ¶ms) +{ + int ret = 0; + const char *skuIdsTemp[SCE_NP_COMMERCE2_SKU_CHECKOUT_MAX]; + std::list<const char *>::iterator iter = params.skuIds.begin(); + std::list<const char *>::iterator iterEnd = params.skuIds.end(); + + if (!m_contextCreated) { + ret = createContext(); + if (ret < 0) { + return ret; + } + } + + for (int i = 0; i < params.skuIds.size(); i++) { + skuIdsTemp[i] = (const char *)(*iter); + iter++; + } + ret = sceNpCommerce2DoDlListStartAsync(m_contextId, app.GetCommerceCategory(), skuIdsTemp, params.skuIds.size(), *params.memContainer); + if (ret < 0) { + return ret; + } + + return CELL_OK; +} + +void SonyCommerce::UpgradeTrialCallback2(LPVOID lpParam,int err) +{ + app.DebugPrintf(4,"SonyCommerce_UpgradeTrialCallback2 : err : 0x%08x\n", err); + SonyCommerce::CheckForTrialUpgradeKey(); + if(err != CELL_OK) + { + UINT uiIDA[1]; + uiIDA[0]=IDS_CONFIRM_OK; + C4JStorage::EMessageResult result = ui.RequestMessageBox( IDS_PRO_UNLOCKGAME_TITLE, IDS_NO_DLCOFFERS, uiIDA,1,ProfileManager.GetPrimaryPad()); + } + m_trialUpgradeCallbackFunc(m_trialUpgradeCallbackParam, m_errorCode); +} + +void SonyCommerce::UpgradeTrialCallback1(LPVOID lpParam,int err) +{ + + app.DebugPrintf(4,"SonyCommerce_UpgradeTrialCallback1 : err : 0x%08x\n", err); + if(err == CELL_OK) + { + const char* skuID = s_trialUpgradeProductInfoDetailed.skuId; + if(s_trialUpgradeProductInfoDetailed.purchasabilityFlag == SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_OFF) + { + app.DebugPrintf(4,"UpgradeTrialCallback1 - DownloadAlreadyPurchased\n"); + SonyCommerce::DownloadAlreadyPurchased( UpgradeTrialCallback2, NULL, skuID); + } + else + { + app.DebugPrintf(4,"UpgradeTrialCallback1 - Checkout\n"); + SonyCommerce::Checkout( UpgradeTrialCallback2, NULL, skuID); + } + } + else + { + UINT uiIDA[1]; + uiIDA[0]=IDS_CONFIRM_OK; + C4JStorage::EMessageResult result = ui.RequestMessageBox( IDS_PRO_UNLOCKGAME_TITLE, IDS_NO_DLCOFFERS, uiIDA,1,ProfileManager.GetPrimaryPad()); + m_trialUpgradeCallbackFunc(m_trialUpgradeCallbackParam, m_errorCode); + } +} + + + +// global func, so we can call from the profile lib +void SonyCommerce_UpgradeTrial() +{ + // we're now calling the app function here, which manages pending requests + app.UpgradeTrial(); +} + +void SonyCommerce::UpgradeTrial(CallbackFunc cb, LPVOID lpParam) +{ + m_trialUpgradeCallbackFunc = cb; + m_trialUpgradeCallbackParam = lpParam; + +// static char szTrialUpgradeSkuID[64]; +// sprintf(szTrialUpgradeSkuID, "%s-TRIALUPGRADE0001", app.GetCommerceCategory());//, szSKUSuffix); + GetDetailedProductInfo(UpgradeTrialCallback1, NULL, &s_trialUpgradeProductInfoDetailed, app.GetUpgradeKey(), app.GetCommerceCategory()); +} + + +int SonyCommerce::createContext() +{ + SceNpId npId; + int ret = sceNpManagerGetNpId(&npId); + if(ret < 0) + { + app.DebugPrintf(4,"createContext sceNpManagerGetNpId problem\n"); + return ret; + } + + if (m_contextCreated) { + ret = sceNpCommerce2DestroyCtx(m_contextId); + if (ret < 0) + { + app.DebugPrintf(4,"createContext sceNpCommerce2DestroyCtx problem\n"); + return ret; + } + } + + // Create commerce2 context + ret = sceNpCommerce2CreateCtx(SCE_NP_COMMERCE2_VERSION, &npId, commerce2Handler, NULL, &m_contextId); + if (ret < 0) + { + app.DebugPrintf(4,"createContext sceNpCommerce2CreateCtx problem\n"); + return ret; + } + + m_contextCreated = true; + + return CELL_OK; +} + +int SonyCommerce::createSession() +{ + int ret = createContext(); + if (ret < 0) { + return ret; + } + + m_currentPhase = e_phase_creatingSessionPhase; + ret = sceNpCommerce2CreateSessionStart(m_contextId); + if (ret < 0) { + return ret; + } + return ret; +} + + +void SonyCommerce::commerce2Handler(uint32_t contextId, uint32_t subjectId, int event, int errorCode, void *arg) +{ +// Event reply; +// reply.service = Toolkit::NP::commerce; +// + EnterCriticalSection(&m_queueLock); + + switch (event) { + case SCE_NP_COMMERCE2_EVENT_REQUEST_ERROR: + { + m_messageQueue.push(e_message_commerceEnd); + m_errorCode = errorCode; + break; + } + case SCE_NP_COMMERCE2_EVENT_CREATE_SESSION_DONE: + { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceSessionCreated; + break; + } + case SCE_NP_COMMERCE2_EVENT_CREATE_SESSION_ABORT: + { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceSessionAborted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_STARTED: + { + m_currentPhase = e_phase_checkoutPhase; + m_event = e_event_commerceCheckoutStarted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_SUCCESS: + { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceCheckoutSuccess; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_BACK: + { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceCheckoutAborted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_FINISHED: + { + m_event = e_event_commerceCheckoutFinished; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_DL_LIST_STARTED: + { + m_currentPhase = e_phase_downloadListPhase; + m_event = e_event_commerceDownloadListStarted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_DL_LIST_SUCCESS: + { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceDownloadListSuccess; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_DL_LIST_FINISHED: + { + m_event = e_event_commerceDownloadListFinished; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_STARTED: + m_currentPhase = e_phase_productBrowsePhase; + m_event = e_event_commerceProductBrowseStarted; + break; + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_SUCCESS: + { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceProductBrowseSuccess; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_BACK: + { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceProductBrowseAborted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_FINISHED: + { + m_event = e_event_commerceProductBrowseFinished; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_OPENED: + break; + case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_STARTED: + { + m_currentPhase = e_phase_voucherRedeemPhase; + m_event = e_event_commerceVoucherInputStarted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_SUCCESS: + { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceVoucherInputSuccess; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_BACK: + { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceVoucherInputAborted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_FINISHED: + { + m_event = e_event_commerceVoucherInputFinished; + break; + } + default: + break; + }; + + LeaveCriticalSection(&m_queueLock); +} + + + +void SonyCommerce::processMessage() +{ + EnterCriticalSection(&m_queueLock); + int ret; + if(m_messageQueue.empty()) + { + LeaveCriticalSection(&m_queueLock); + return; + } + Message msg = m_messageQueue.front(); + m_messageQueue.pop(); + + switch (msg) + { + + case e_message_commerceCreateSession: + ret = createSession(); + if (ret < 0) + { + m_event = e_event_commerceError; + m_errorCode = ret; + } + break; + + case e_message_commerceGetCategoryInfo: + { + ret = getCategoryInfo(m_pCategoryInfo, m_pCategoryID); + if (ret < 0) + { + m_event = e_event_commerceError; + app.DebugPrintf(4,"ERROR - e_event_commerceGotCategoryInfo - %s\n",m_pCategoryID); + m_errorCode = ret; + } + else + { + m_event = e_event_commerceGotCategoryInfo; + app.DebugPrintf(4,"e_event_commerceGotCategoryInfo - %s\n",m_pCategoryID); + } + break; + } + + case e_message_commerceGetProductList: + { + ret = getProductList(m_pProductInfoList, m_pCategoryID); + if (ret < 0) + { + m_event = e_event_commerceError; + } + else + { + m_event = e_event_commerceGotProductList; + app.DebugPrintf(4,"e_event_commerceGotProductList - %s\n",m_pCategoryID); + } + break; + } + + case e_message_commerceGetDetailedProductInfo: + { + ret = getDetailedProductInfo(m_pProductInfoDetailed, m_pProductID, m_pCategoryID); + if (ret < 0) + { + m_event = e_event_commerceError; + m_errorCode = ret; + } + else + { + m_event = e_event_commerceGotDetailedProductInfo; + app.DebugPrintf(4,"e_event_commerceGotDetailedProductInfo - %s\n",m_pCategoryID); + } + break; + } + case e_message_commerceAddDetailedProductInfo: + { + ret = addDetailedProductInfo(m_pProductInfo, m_pProductID, m_pCategoryID); + if (ret < 0) + { + m_event = e_event_commerceError; + m_errorCode = ret; + } + else + { + m_event = e_event_commerceAddedDetailedProductInfo; + } + break; + } + +// +// case e_message_commerceStoreProductBrowse: +// { +// ret = productBrowse(*(ProductBrowseParams *)msg.inputArgs); +// if (ret < 0) { +// m_event = e_event_commerceError; +// m_errorCode = ret; +// } +// _TOOLKIT_NP_DEL (ProductBrowseParams *)msg.inputArgs; +// break; +// } +// +// case e_message_commerceUpgradeTrial: +// { +// ret = upgradeTrial(); +// if (ret < 0) { +// m_event = e_event_commerceError; +// m_errorCode = ret; +// } +// break; +// } +// +// case e_message_commerceRedeemVoucher: +// { +// ret = voucherCodeInput(*(VoucherInputParams *)msg.inputArgs); +// if (ret < 0) { +// m_event = e_event_commerceError; +// m_errorCode = ret; +// } +// _TOOLKIT_NP_DEL (VoucherInputParams *)msg.inputArgs; +// break; +// } +// +// case e_message_commerceGetEntitlementList: +// { +// Job<std::vector<SceNpEntitlement> > tmpJob(static_cast<Future<std::vector<SceNpEntitlement> > *>(msg.output)); +// +// int state = 0; +// int ret = sceNpManagerGetStatus(&state); +// +// // We don't want to process this if we are offline +// if (ret < 0 || state != SCE_NP_MANAGER_STATUS_ONLINE) { +// m_event = e_event_commerceError; +// reply.returnCode = SCE_TOOLKIT_NP_OFFLINE; +// tmpJob.setError(SCE_TOOLKIT_NP_OFFLINE); +// } else { +// getEntitlementList(&tmpJob); +// } +// break; +// } +// +// case e_message_commerceConsumeEntitlement: +// { +// int state = 0; +// int ret = sceNpManagerGetStatus(&state); +// +// // We don't want to process this if we are offline +// if (ret < 0 || state != SCE_NP_MANAGER_STATUS_ONLINE) { +// m_event = e_event_commerceError; +// reply.returnCode = SCE_TOOLKIT_NP_OFFLINE; +// } else { +// +// ret = consumeEntitlement(*(EntitlementToConsume *)msg.inputArgs); +// if (ret < 0) { +// m_event = e_event_commerceError; +// m_errorCode = ret; +// } else { +// m_event = e_event_commerceConsumedEntitlement; +// } +// } +// _TOOLKIT_NP_DEL (EntitlementToConsume *)msg.inputArgs; +// +// break; +// } +// + case e_message_commerceCheckout: + { + ret = checkout(m_checkoutInputParams); + if (ret < 0) { + m_event = e_event_commerceError; + m_errorCode = ret; + } + break; + } + + case e_message_commerceDownloadList: + { + ret = downloadList(m_downloadInputParams); + if (ret < 0) { + m_event = e_event_commerceError; + m_errorCode = ret; + } + break; + } + + case e_message_commerceEnd: + app.DebugPrintf("XXX - e_message_commerceEnd!\n"); + ret = commerceEnd(); + if (ret < 0) + { + m_event = e_event_commerceError; + m_errorCode = ret; + } + // 4J-PB - we don't seem to handle the error code here + else if(m_errorCode!=0) + { + m_event = e_event_commerceError; + } + break; + + default: + break; + } + + LeaveCriticalSection(&m_queueLock); +} + + +void SonyCommerce::processEvent() +{ + int ret = 0; + + switch (m_event) + { + case e_event_none: + break; + case e_event_commerceSessionCreated: + app.DebugPrintf(4,"Commerce Session Created.\n"); + runCallback(); + break; + case e_event_commerceSessionAborted: + app.DebugPrintf(4,"Commerce Session aborted.\n"); + runCallback(); + break; + case e_event_commerceGotProductList: + app.DebugPrintf(4,"Got product list.\n"); + runCallback(); + break; + case e_event_commerceGotCategoryInfo: + app.DebugPrintf(4,"Got category info\n"); + runCallback(); + break; + case e_event_commerceGotDetailedProductInfo: + app.DebugPrintf(4,"Got detailed product info.\n"); + runCallback(); + break; + case e_event_commerceAddedDetailedProductInfo: + app.DebugPrintf(4,"Added detailed product info.\n"); + runCallback(); + break; + case e_event_commerceProductBrowseStarted: + break; + case e_event_commerceProductBrowseSuccess: + break; + case e_event_commerceProductBrowseAborted: + break; + case e_event_commerceProductBrowseFinished: + assert(0); +// ret = sys_memory_container_destroy(s_memContainer); +// if (ret < 0) { +// printf("Failed to destroy memory container"); +// } +// s_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + break; + case e_event_commerceVoucherInputStarted: + break; + case e_event_commerceVoucherInputSuccess: + break; + case e_event_commerceVoucherInputAborted: + break; + case e_event_commerceVoucherInputFinished: + assert(0); +// ret = sys_memory_container_destroy(s_memContainer); +// if (ret < 0) { +// printf("Failed to destroy memory container"); +// } +// s_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + break; + case e_event_commerceGotEntitlementList: + break; + case e_event_commerceConsumedEntitlement: + break; + case e_event_commerceCheckoutStarted: + app.DebugPrintf(4,"Checkout Started\n"); + break; + case e_event_commerceCheckoutSuccess: + app.DebugPrintf(4,"Checkout succeeded: 0x%x\n", m_errorCode); + // clear the DLC installed and check again + app.ClearDLCInstalled(); + ui.HandleDLCInstalled(0); + break; + case e_event_commerceCheckoutAborted: + app.DebugPrintf(4,"Checkout aborted: 0x%x\n", m_errorCode); + break; + case e_event_commerceCheckoutFinished: + app.DebugPrintf(4,"Checkout Finished: 0x%x\n", m_errorCode); + ret = sys_memory_container_destroy(m_memContainer); + if (ret < 0) { + app.DebugPrintf(4,"Failed to destroy memory container"); + } + + m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time + if(m_callbackFunc!=NULL) + { + runCallback(); + } + break; + case e_event_commerceDownloadListStarted: + app.DebugPrintf(4,"Download List Started\n"); + break; + case e_event_commerceDownloadListSuccess: + app.DebugPrintf(4,"Download succeeded: 0x%x\n", m_errorCode); + break; + case e_event_commerceDownloadListFinished: + app.DebugPrintf(4,"Download Finished: 0x%x\n", m_errorCode); + ret = sys_memory_container_destroy(m_memContainer); + if (ret < 0) { + app.DebugPrintf(4,"Failed to destroy memory container"); + } + + m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time + if(m_callbackFunc!=NULL) + { + runCallback(); + } + break; + case e_event_commerceError: + app.DebugPrintf(4,"Commerce Error 0x%x\n", m_errorCode); + + if(m_memContainer != SYS_MEMORY_CONTAINER_ID_INVALID) + { + ret = sys_memory_container_destroy(m_memContainer); + if (ret < 0) { + app.DebugPrintf(4,"Failed to destroy memory container"); + } + + m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + } + + runCallback(); + break; + default: + break; + } + m_event = e_event_none; +} + + +int SonyCommerce::commerceEnd() +{ + int ret = 0; + + if (m_currentPhase == e_phase_voucherRedeemPhase) + ret = sceNpCommerce2DoProductCodeFinishAsync(m_contextId); + else if (m_currentPhase == e_phase_productBrowsePhase) + ret = sceNpCommerce2DoProductBrowseFinishAsync(m_contextId); + else if (m_currentPhase == e_phase_creatingSessionPhase) + ret = sceNpCommerce2CreateSessionFinish(m_contextId, &m_sessionInfo); + else if (m_currentPhase == e_phase_checkoutPhase) + ret = sceNpCommerce2DoCheckoutFinishAsync(m_contextId); + else if (m_currentPhase == e_phase_downloadListPhase) + ret = sceNpCommerce2DoDlListFinishAsync(m_contextId); + + m_currentPhase = e_phase_idle; + + return ret; +} + +void SonyCommerce::CreateSession( CallbackFunc cb, LPVOID lpParam ) +{ + Init(); + EnterCriticalSection(&m_queueLock); + setCallback(cb,lpParam); + m_messageQueue.push(e_message_commerceCreateSession); + if(m_tickThread == NULL) + m_tickThread = new C4JThread(TickLoop, NULL, "SonyCommerce tick"); + if(m_tickThread->isRunning() == false) + { + m_currentPhase = e_phase_idle; + m_tickThread->Run(); + } + LeaveCriticalSection(&m_queueLock); +} + +void SonyCommerce::CloseSession() +{ + assert(m_currentPhase == e_phase_idle); + m_currentPhase = e_phase_stopped; + Shutdown(); +} + +void SonyCommerce::GetProductList( CallbackFunc cb, LPVOID lpParam, std::vector<ProductInfo>* productList, const char *categoryId) +{ + EnterCriticalSection(&m_queueLock); + setCallback(cb,lpParam); + m_pProductInfoList = productList; + strcpy(m_pCategoryID,categoryId); + m_messageQueue.push(e_message_commerceGetProductList); + LeaveCriticalSection(&m_queueLock); +} + +void SonyCommerce::GetDetailedProductInfo( CallbackFunc cb, LPVOID lpParam, ProductInfoDetailed* productInfo, const char *productId, const char *categoryId ) +{ + EnterCriticalSection(&m_queueLock); + setCallback(cb,lpParam); + m_pProductInfoDetailed = productInfo; + m_pProductID = productId; + strcpy(m_pCategoryID,categoryId); + m_messageQueue.push(e_message_commerceGetDetailedProductInfo); + LeaveCriticalSection(&m_queueLock); +} + +// 4J-PB - fill out the long description and the price for the product +void SonyCommerce::AddDetailedProductInfo( CallbackFunc cb, LPVOID lpParam, ProductInfo* productInfo, const char *productId, const char *categoryId ) +{ + EnterCriticalSection(&m_queueLock); + setCallback(cb,lpParam); + m_pProductInfo = productInfo; + m_pProductID = productId; + strcpy(m_pCategoryID,categoryId); + m_messageQueue.push(e_message_commerceAddDetailedProductInfo); + LeaveCriticalSection(&m_queueLock); +} +void SonyCommerce::GetCategoryInfo( CallbackFunc cb, LPVOID lpParam, CategoryInfo *info, const char *categoryId ) +{ + EnterCriticalSection(&m_queueLock); + setCallback(cb,lpParam); + m_pCategoryInfo = info; + strcpy(m_pCategoryID,categoryId); + m_messageQueue.push(e_message_commerceGetCategoryInfo); + LeaveCriticalSection(&m_queueLock); +} + +void SonyCommerce::Checkout( CallbackFunc cb, LPVOID lpParam, const char* skuID ) +{ + if(m_memContainer != SYS_MEMORY_CONTAINER_ID_INVALID) + { + return; + } + EnterCriticalSection(&m_queueLock); + setCallback(cb,lpParam); + int ret = sys_memory_container_create(&m_memContainer, SCE_NP_COMMERCE2_DO_CHECKOUT_MEMORY_CONTAINER_SIZE); + if (ret < 0) + { + app.DebugPrintf(4,"sys_memory_container_create() failed. ret = 0x%x\n", ret); + } + + m_checkoutInputParams.memContainer = &m_memContainer; + m_checkoutInputParams.skuIds.clear(); + m_checkoutInputParams.skuIds.push_back(skuID); + m_messageQueue.push(e_message_commerceCheckout); + LeaveCriticalSection(&m_queueLock); +} + +void SonyCommerce::DownloadAlreadyPurchased( CallbackFunc cb, LPVOID lpParam, const char* skuID ) +{ + if(m_memContainer != SYS_MEMORY_CONTAINER_ID_INVALID) + return; + EnterCriticalSection(&m_queueLock); + setCallback(cb,lpParam); + int ret = sys_memory_container_create(&m_memContainer, SCE_NP_COMMERCE2_DO_CHECKOUT_MEMORY_CONTAINER_SIZE); + if (ret < 0) + { + app.DebugPrintf(4,"sys_memory_container_create() failed. ret = 0x%x\n", ret); + } + + m_downloadInputParams.memContainer = &m_memContainer; + m_downloadInputParams.skuIds.clear(); + m_downloadInputParams.skuIds.push_back(skuID); + m_messageQueue.push(e_message_commerceDownloadList); + LeaveCriticalSection(&m_queueLock); +} + + + diff --git a/Minecraft.Client/Common/Network/Sony/SonyCommerce.h b/Minecraft.Client/Common/Network/Sony/SonyCommerce.h new file mode 100644 index 00000000..6df04947 --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SonyCommerce.h @@ -0,0 +1,173 @@ +#pragma once + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#ifdef __PS3__ +#include <np.h> +#include <np/drm.h> +#include <np/commerce2.h> +#elif defined __PSVITA__ +#include <np.h> +#include <np_toolkit.h> +#else // __ORBIS__ + +#define SCE_NP_COMMERCE2_CATEGORY_ID_LEN SCE_TOOLKIT_NP_COMMERCE_CATEGORY_ID_LEN ///< The size of the category ID. +#define SCE_NP_COMMERCE2_PRODUCT_ID_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_ID_LEN ///< The size of the product ID. +#define SCE_NP_COMMERCE2_CATEGORY_NAME_LEN SCE_TOOLKIT_NP_COMMERCE_CATEGORY_NAME_LEN ///< The size of the category name. +#define SCE_NP_COMMERCE2_CATEGORY_DESCRIPTION_LEN SCE_TOOLKIT_NP_COMMERCE_CATEGORY_DESCRIPTION_LEN ///< The size of the category description. +#define SCE_NP_COMMERCE2_URL_LEN SCE_TOOLKIT_NP_COMMERCE_URL_LEN ///< The size of the URL. +#define SCE_NP_COMMERCE2_PRODUCT_NAME_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_NAME_LEN ///< The size of the product name. +#define SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_SHORT_DESCRIPTION_LEN ///< The size of the product short description. +#define SCE_NP_COMMERCE2_SP_NAME_LEN SCE_TOOLKIT_NP_COMMERCE_SP_NAME_LEN ///< The size of the licensee (publisher) name. +#define SCE_NP_COMMERCE2_CURRENCY_CODE_LEN SCE_TOOLKIT_NP_COMMERCE_CURRENCY_CODE_LEN ///< The size of currency code. +#define SCE_NP_COMMERCE2_CURRENCY_CODE_LEN SCE_TOOLKIT_NP_COMMERCE_CURRENCY_CODE_LEN +#define SCE_NP_COMMERCE2_CURRENCY_SYMBOL_LEN SCE_TOOLKIT_NP_COMMERCE_CURRENCY_SYMBOL_LEN ///< The size of currency symbol. +#define SCE_NP_COMMERCE2_THOUSAND_SEPARATOR_LEN SCE_TOOLKIT_NP_COMMERCE_THOUSAND_SEPARATOR_LEN ///< The size of the character separating every 3 digits of the price. +#define SCE_NP_COMMERCE2_DECIMAL_LETTER_LEN SCE_TOOLKIT_NP_COMMERCE_DECIMAL_LETTER_LEN ///< The size of the character indicating the decimal point in the price. +#define SCE_NP_COMMERCE2_SKU_ID_LEN SCE_TOOLKIT_NP_COMMERCE_SKU_ID_LEN ///< The size of the SKU ID. +#define SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_LONG_DESCRIPTION_LEN ///< The size of the product long description. +#define SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_LEGAL_DESCRIPTION_LEN ///< The size of the product legal description. +#define SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN SCE_TOOLKIT_NP_COMMERCE_RATING_SYSTEM_ID_LEN ///< The size of the rating system ID. +#define SCE_NP_ENTITLEMENT_ID_SIZE SCE_TOOLKIT_NP_COMMERCE_ENTITLEMENT_ID_LEN ///< The size of entitlement ID. +#endif + +#ifndef __PSVITA__ +#define SCE_TOOLKIT_NP_SKU_PRICE_LEN (SCE_NP_COMMERCE2_CURRENCY_CODE_LEN \ + + SCE_NP_COMMERCE2_CURRENCY_SYMBOL_LEN \ + + SCE_NP_COMMERCE2_THOUSAND_SEPARATOR_LEN \ + + SCE_NP_COMMERCE2_DECIMAL_LETTER_LEN) ///< The maximum length of a price in characters. +#endif + +class SonyCommerce +{ + +public: + typedef void (*CallbackFunc)(LPVOID lpParam, int error_code); + + + /// @brief + /// Contains information about a subcategory on the PlayStation(R)Store. + /// + /// Contains information about a subcategory on the PlayStation(R)Store. + typedef struct CategoryInfoSub + { + char categoryId[SCE_NP_COMMERCE2_CATEGORY_ID_LEN]; ///< The ID of the subcategory. + char categoryName[SCE_NP_COMMERCE2_CATEGORY_NAME_LEN]; ///< The name of the subcategory. + char categoryDescription[SCE_NP_COMMERCE2_CATEGORY_DESCRIPTION_LEN]; ///< The detailed description of the subcategory. + char imageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The image URL of the subcategory. + } + CategoryInfoSub; + + /// @brief + /// Current category information + /// + /// This structure contains information about a category on the PlayStation(R)Store + typedef struct CategoryInfo + { + CategoryInfoSub current; ///< The currently selected subcategory. + std::list<CategoryInfoSub> subCategories; ///< Information about the subcategories in this category. + uint32_t countOfProducts; ///< The number of products in the category. + uint32_t countOfSubCategories; ///< The number of subcategories. + } + CategoryInfo; + + /// Contains information about a product in the PlayStation(R)Store. + typedef struct ProductInfo + { + uint32_t purchasabilityFlag; ///< A flag that indicates whether the product can be purchased (<c>SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_XXX</c>). + uint32_t annotation; // SCE_NP_COMMERCE2_SKU_ANN_PURCHASED_CANNOT_PURCHASE_AGAIN or SCE_NP_COMMERCE2_SKU_ANN_PURCHASED_CAN_PURCHASE_AGAIN + uint32_t ui32Price; + char productId[SCE_NP_COMMERCE2_PRODUCT_ID_LEN]; ///< The product ID. + char productName[SCE_NP_COMMERCE2_PRODUCT_NAME_LEN]; ///< The name of the product. + char shortDescription[SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN]; ///< A short description of the product. + char longDescription[SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN]; ///< A long description of the product. + char skuId[SCE_NP_COMMERCE2_SKU_ID_LEN]; ///< The SKU ID + char spName[SCE_NP_COMMERCE2_SP_NAME_LEN]; ///< The service provider name. + char imageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The product image URL. + char price[SCE_TOOLKIT_NP_SKU_PRICE_LEN]; ///< The price of the product. This is formatted to include the currency code. + char padding[6]; ///< Padding. +#ifdef __PS3__ + CellRtcTick releaseDate; ///< The product release date. +#else + SceRtcTick releaseDate; +#endif + } + ProductInfo; + + /// @brief + /// Contains detailed information about a product on the PlayStation(R)Store. + /// + /// Contains detailed information about a product on the PlayStation(R)Store. + typedef struct ProductInfoDetailed + { + uint32_t purchasabilityFlag; ///< A flag that indicates whether the product can be purchased (<c>SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_XXX</c>). + uint32_t ui32Price; + char skuId[SCE_NP_COMMERCE2_SKU_ID_LEN]; ///< The SKU ID + char productId[SCE_NP_COMMERCE2_PRODUCT_ID_LEN]; ///< The product ID. + char productName[SCE_NP_COMMERCE2_PRODUCT_NAME_LEN]; ///< The name of the product. + char shortDescription[SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN]; ///< A short description of the product. + char longDescription[SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN]; ///< A long description of the product. + char legalDescription[SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN]; ///< The legal description for the product. + char spName[SCE_NP_COMMERCE2_SP_NAME_LEN]; ///< The service provider name. + char imageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The product image URL. + char price[SCE_TOOLKIT_NP_SKU_PRICE_LEN]; ///< The price of the product. This is formatted to include the currency code. + char ratingSystemId[SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN]; ///< The ID of the rating system (for example: PEGI, ESRB). + char ratingImageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The URL of the rating icon. + char padding[2]; ///< Padding. +#ifdef __PS3__ + std::list<SceNpCommerce2ContentRatingDescriptor> ratingDescriptors; ///< The list of rating descriptors. + CellRtcTick releaseDate; ///< The product release date. +#else + SceRtcTick releaseDate; ///< The product release date. +#endif + } + ProductInfoDetailed; + + /// @brief + /// Checkout parameters + /// + /// This structure contains list of SKUs to checkout to and a memory container + typedef struct CheckoutInputParams + { + std::list<const char *> skuIds; ///< List of SKU IDs +#ifdef __PS3__ + sys_memory_container_t *memContainer; ///< Memory container for checkout overlay +#endif + } + CheckoutInputParams; + + /// @brief + /// Contains download list parameters. + /// + /// Contains download list parameters. + typedef struct DownloadListInputParams + { + std::list<const char *> skuIds; ///< The list of SKU IDs +#ifdef __PS3__ + sys_memory_container_t *memContainer; ///< A memory container for checkout overlay. +#endif + const char* categoryID; + } + DownloadListInputParams; + + +public: + virtual void CreateSession(CallbackFunc cb, LPVOID lpParam) = 0; + virtual void CloseSession() = 0; + + virtual void GetCategoryInfo(CallbackFunc cb, LPVOID lpParam, CategoryInfo *info, const char *categoryId) = 0; + virtual void GetProductList(CallbackFunc cb, LPVOID lpParam, std::vector<ProductInfo>* productList, const char *categoryId) = 0; + virtual void GetDetailedProductInfo(CallbackFunc cb, LPVOID lpParam, ProductInfoDetailed* productInfoDetailed, const char *productId, const char *categoryId) = 0; + virtual void AddDetailedProductInfo( CallbackFunc cb, LPVOID lpParam, ProductInfo* productInfo, const char *productId, const char *categoryId ) = 0; + virtual void Checkout(CallbackFunc cb, LPVOID lpParam, const char* skuID) = 0; + virtual void DownloadAlreadyPurchased(CallbackFunc cb, LPVOID lpParam, const char* skuID) = 0; +#if defined(__ORBIS__) || defined( __PSVITA__) + virtual void Checkout_Game(CallbackFunc cb, LPVOID lpParam, const char* skuID) = 0; + virtual void DownloadAlreadyPurchased_Game(CallbackFunc cb, LPVOID lpParam, const char* skuID) = 0; +#endif + virtual void UpgradeTrial(CallbackFunc cb, LPVOID lpParam) = 0; + virtual void CheckForTrialUpgradeKey() = 0; + virtual bool LicenseChecked() = 0; + +}; diff --git a/Minecraft.Client/Common/Network/Sony/SonyHttp.cpp b/Minecraft.Client/Common/Network/Sony/SonyHttp.cpp new file mode 100644 index 00000000..f0095885 --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SonyHttp.cpp @@ -0,0 +1,34 @@ +#include "stdafx.h" +#include "SonyHttp.h" + + +#ifdef __PS3__ +#include "PS3\Network\SonyHttp_PS3.h" +SonyHttp_PS3 g_SonyHttp; + +#elif defined __ORBIS__ +#include "Orbis\Network\SonyHttp_Orbis.h" +SonyHttp_Orbis g_SonyHttp; + +#elif defined __PSVITA__ +#include "PSVita\Network\SonyHttp_Vita.h" +SonyHttp_Vita g_SonyHttp; + +#endif + + + +bool SonyHttp::init() +{ + return g_SonyHttp.init(); +} + +void SonyHttp::shutdown() +{ + g_SonyHttp.shutdown(); +} + +bool SonyHttp::getDataFromURL(const char* szURL, void** ppOutData, int* pDataSize) +{ + return g_SonyHttp.getDataFromURL(szURL, ppOutData, pDataSize); +} diff --git a/Minecraft.Client/Common/Network/Sony/SonyHttp.h b/Minecraft.Client/Common/Network/Sony/SonyHttp.h new file mode 100644 index 00000000..3fa526b0 --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SonyHttp.h @@ -0,0 +1,11 @@ +#pragma once + + + +class SonyHttp +{ +public: + static bool init(); + static void shutdown(); + static bool getDataFromURL(const char* szURL, void** ppOutData, int* pDataSize); +};
\ No newline at end of file diff --git a/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.cpp b/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.cpp new file mode 100644 index 00000000..ccb1957d --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.cpp @@ -0,0 +1,340 @@ + + +#include "stdafx.h" +#include "SonyRemoteStorage.h" + + +static const char sc_remoteSaveFilename[] = "/minecraft_save/gamedata.rs"; +#ifdef __PSVITA__ +static const char sc_localSaveFilename[] = "CloudSave_Vita.bin"; +static const char sc_localSaveFullPath[] = "savedata0:CloudSave_Vita.bin"; +#elif defined __PS3__ +static const char sc_localSaveFilename[] = "CloudSave_PS3.bin"; +static const char sc_localSaveFullPath[] = "NPEB01899--140720203552"; +#else +static const char sc_localSaveFilename[] = "CloudSave_Orbis.bin"; +static const char sc_localSaveFullPath[] = "/app0/CloudSave_Orbis.bin"; +#endif + +static SceRemoteStorageStatus statParams; + + + + +// void remoteStorageGetCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int error_code) +// { +// app.DebugPrintf("remoteStorageGetCallback err : 0x%08x\n"); +// } +// +// void remoteStorageCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int error_code) +// { +// app.DebugPrintf("remoteStorageCallback err : 0x%08x\n"); +// +// app.getRemoteStorage()->getRemoteFileInfo(&statParams, remoteStorageGetInfoCallback, NULL); +// } + + + + + + + + +void getSaveInfoReturnCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int error_code) +{ + SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; + app.DebugPrintf("remoteStorageGetInfoCallback err : 0x%08x\n", error_code); + if(error_code == 0) + { + for(int i=0;i<statParams.numFiles;i++) + { + if(strcmp(statParams.data[i].fileName, sc_remoteSaveFilename) == 0) + { + // found the file we need in the cloud + pRemoteStorage->m_getInfoStatus = SonyRemoteStorage::e_infoFound; + pRemoteStorage->m_remoteFileInfo = &statParams.data[i]; + } + } + } + if(pRemoteStorage->m_getInfoStatus != SonyRemoteStorage::e_infoFound) + pRemoteStorage->m_getInfoStatus = SonyRemoteStorage::e_noInfoFound; +} + + + + + + +static void getSaveInfoInitCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int error_code) +{ + SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; + if(error_code != 0) + { + app.DebugPrintf("getSaveInfoInitCallback err : 0x%08x\n", error_code); + pRemoteStorage->m_getInfoStatus = SonyRemoteStorage::e_noInfoFound; + } + else + { + app.DebugPrintf("getSaveInfoInitCallback calling getRemoteFileInfo\n"); + app.getRemoteStorage()->getRemoteFileInfo(&statParams, getSaveInfoReturnCallback, pRemoteStorage); + } +} + +void SonyRemoteStorage::getSaveInfo() +{ + if(m_getInfoStatus == e_gettingInfo) + { + app.DebugPrintf("SonyRemoteStorage::getSaveInfo already running!!!\n"); + return; + } + + m_getInfoStatus = e_gettingInfo; + if(!ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) + { + m_getInfoStatus = e_noInfoFound; + return; + } + app.DebugPrintf("SonyRemoteStorage::getSaveInfo calling init\n"); + + bool bOK = init(getSaveInfoInitCallback, this); + if(!bOK) + m_getInfoStatus = e_noInfoFound; +} + +bool SonyRemoteStorage::getSaveData( const char* localDirname, CallbackFunc cb, LPVOID lpParam ) +{ + m_startTime = System::currentTimeMillis(); + m_dataProgress = 0; + return getData(sc_remoteSaveFilename, localDirname, cb, lpParam); +} + + +static void setSaveDataInitCallback(LPVOID lpParam, SonyRemoteStorage::Status s, int error_code) +{ + SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; + if(error_code != 0) + { + app.DebugPrintf("setSaveDataInitCallback err : 0x%08x\n", error_code); + pRemoteStorage->m_setDataStatus = SonyRemoteStorage::e_settingDataFailed; + if(pRemoteStorage->m_initCallbackFunc) + pRemoteStorage->m_initCallbackFunc(pRemoteStorage->m_initCallbackParam, s, error_code); + } + else + { + app.getRemoteStorage()->setData(pRemoteStorage->m_setSaveDataInfo, pRemoteStorage->m_initCallbackFunc, pRemoteStorage->m_initCallbackParam); + } + +} +bool SonyRemoteStorage::setSaveData(PSAVE_INFO info, CallbackFunc cb, void* lpParam) +{ + m_setSaveDataInfo = info; + m_setDataStatus = e_settingData; + m_initCallbackFunc = cb; + m_initCallbackParam = lpParam; + m_dataProgress = 0; + bool bOK = init(setSaveDataInitCallback, this); + if(!bOK) + m_setDataStatus = e_settingDataFailed; + + return bOK; +} + +const char* SonyRemoteStorage::getLocalFilename() +{ + return sc_localSaveFullPath; +} + +const char* SonyRemoteStorage::getSaveNameUTF8() +{ + if(m_getInfoStatus != e_infoFound) + return NULL; + DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; + return pDescData->m_saveNameUTF8; +} + +ESavePlatform SonyRemoteStorage::getSavePlatform() +{ + if(m_getInfoStatus != e_infoFound) + return SAVE_FILE_PLATFORM_NONE; + DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; + return (ESavePlatform)MAKE_FOURCC(pDescData->m_platform[0], pDescData->m_platform[1], pDescData->m_platform[2], pDescData->m_platform[3]); + +} + +__int64 SonyRemoteStorage::getSaveSeed() +{ + if(m_getInfoStatus != e_infoFound) + return 0; + DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; + + char seedString[17]; + ZeroMemory(seedString,17); + memcpy(seedString, pDescData->m_seed,16); + + __uint64 seed = 0; + std::stringstream ss; + ss << seedString; + ss >> std::hex >> seed; + return seed; +} + +unsigned int SonyRemoteStorage::getSaveHostOptions() +{ + if(m_getInfoStatus != e_infoFound) + return 0; + DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; + + char optionsString[9]; + ZeroMemory(optionsString,9); + memcpy(optionsString, pDescData->m_hostOptions,8); + + unsigned int uiHostOptions = 0; + std::stringstream ss; + ss << optionsString; + ss >> std::hex >> uiHostOptions; + return uiHostOptions; +} + +unsigned int SonyRemoteStorage::getSaveTexturePack() +{ + if(m_getInfoStatus != e_infoFound) + return 0; + DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; + + char textureString[9]; + ZeroMemory(textureString,9); + memcpy(textureString, pDescData->m_texturePack,8); + + unsigned int uiTexturePack = 0; + std::stringstream ss; + ss << textureString; + ss >> std::hex >> uiTexturePack; + return uiTexturePack; +} + +const char* SonyRemoteStorage::getRemoteSaveFilename() +{ + return sc_remoteSaveFilename; +} + +int SonyRemoteStorage::getSaveFilesize() +{ + if(m_getInfoStatus == e_infoFound) + { + return m_remoteFileInfo->fileSize; + } + return 0; +} + + +bool SonyRemoteStorage::setData( PSAVE_INFO info, CallbackFunc cb, LPVOID lpParam ) +{ + m_setDataSaveInfo = info; + m_callbackFunc = cb; + m_callbackParam = lpParam; + m_status = e_setDataInProgress; + + C4JStorage::ESaveGameState eLoadStatus=StorageManager.LoadSaveDataThumbnail(info,&LoadSaveDataThumbnailReturned,this); + return true; +} + +int SonyRemoteStorage::LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes) +{ + SonyRemoteStorage *pClass= (SonyRemoteStorage *)lpParam; + + if(pClass->m_bAborting) + { + pClass->runCallback(); + return 0; + } + + app.DebugPrintf("Received data for a thumbnail\n"); + + if(pbThumbnail && dwThumbnailBytes) + { + pClass->m_thumbnailData = pbThumbnail; + pClass->m_thumbnailDataSize = dwThumbnailBytes; + } + else + { + app.DebugPrintf("Thumbnail data is NULL, or has size 0\n"); + pClass->m_thumbnailData = NULL; + pClass->m_thumbnailDataSize = 0; + } + + if(pClass->m_SetDataThread != NULL) + delete pClass->m_SetDataThread; + + pClass->m_SetDataThread = new C4JThread(setDataThread, pClass, "setDataThread"); + pClass->m_SetDataThread->Run(); + + return 0; +} + +int SonyRemoteStorage::setDataThread(void* lpParam) +{ + SonyRemoteStorage* pClass = (SonyRemoteStorage*)lpParam; + pClass->m_startTime = System::currentTimeMillis(); + pClass->setDataInternal(); + return 0; +} + +bool SonyRemoteStorage::saveIsAvailable() +{ + if(m_getInfoStatus != e_infoFound) + return false; +#ifdef __PS3__ + return (getSavePlatform() == SAVE_FILE_PLATFORM_PSVITA); +#elif defined __PSVITA__ + return (getSavePlatform() == SAVE_FILE_PLATFORM_PS3); +#else // __ORBIS__ + return true; +#endif +} + +int SonyRemoteStorage::getDataProgress() +{ + __int64 time = System::currentTimeMillis(); + int elapsedSecs = (time - m_startTime) / 1000; + int progVal = m_dataProgress + (elapsedSecs/3); + if(progVal > 95) + { + return m_dataProgress; + } + return progVal; +} + + +bool SonyRemoteStorage::shutdown() +{ + if(m_bInitialised) + { + int ret = sceRemoteStorageTerm(); + if(ret >= 0) + { + app.DebugPrintf("Term request done \n"); + m_bInitialised = false; + free(m_memPoolBuffer); + m_memPoolBuffer = NULL; + return true; + } + else + { + app.DebugPrintf("Error in Term request: 0x%x \n", ret); + return false; + } + } + return true; +} + + +void SonyRemoteStorage::waitForStorageManagerIdle() +{ + C4JStorage::ESaveGameState storageState = StorageManager.GetSaveState(); + while(storageState != C4JStorage::ESaveGame_Idle) + { + Sleep(10); +// app.DebugPrintf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>> storageState = %d\n", storageState); + storageState = StorageManager.GetSaveState(); + } +} diff --git a/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.h b/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.h new file mode 100644 index 00000000..f435848e --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/SonyRemoteStorage.h @@ -0,0 +1,120 @@ +#pragma once + + +#include "..\..\Common\Network\Sony\sceRemoteStorage\header\sceRemoteStorage.h" + +class SonyRemoteStorage +{ +public: + enum Status + { + e_idle, + e_accountLinked, + e_error, + e_signInRequired, + e_compressInProgress, + e_setDataInProgress, + e_setDataSucceeded, + e_getDataInProgress, + e_getDataSucceeded, + e_getStatusInProgress, + e_getStatusSucceeded + }; + typedef void (*CallbackFunc)(LPVOID lpParam, Status s, int error_code); + + enum GetInfoStatus + { + e_gettingInfo, + e_infoFound, + e_noInfoFound + }; + GetInfoStatus m_getInfoStatus; + + enum SetDataStatus + { + e_settingData, + e_settingDataFailed, + e_settingDataSucceeded + }; + SetDataStatus m_setDataStatus; + + PSAVE_INFO m_setSaveDataInfo; + SceRemoteStorageData* m_remoteFileInfo; + + class DescriptionData + { + // this stuff is read from a JSON query, so it all has to be text based, max 256 bytes + public: + char m_platform[4]; + char m_seed[16]; // 8 bytes as hex + char m_hostOptions[8]; // 4 bytes as hex + char m_texturePack[8]; // 4 bytes as hex + char m_saveNameUTF8[128]; + }; + + CallbackFunc m_callbackFunc; + void* m_callbackParam; + + + CallbackFunc m_initCallbackFunc; + void* m_initCallbackParam; + + void getSaveInfo(); + bool waitingForSaveInfo() { return (m_getInfoStatus == e_gettingInfo); } + bool saveIsAvailable(); + + int getSaveFilesize(); + bool getSaveData(const char* localDirname, CallbackFunc cb, LPVOID lpParam); + + bool setSaveData(PSAVE_INFO info, CallbackFunc cb, void* lpParam); + bool waitingForSetData() { return (m_setDataStatus == e_settingData); } + + const char* getLocalFilename(); + const char* getSaveNameUTF8(); + ESavePlatform getSavePlatform(); + __int64 getSaveSeed(); + unsigned int getSaveHostOptions(); + unsigned int getSaveTexturePack(); + + void SetServiceID(char *pchServiceID) { m_pchServiceID=pchServiceID; } + + virtual bool init(CallbackFunc cb, LPVOID lpParam) = 0; + virtual bool getRemoteFileInfo(SceRemoteStorageStatus* pInfo, CallbackFunc cb, LPVOID lpParam) = 0; + virtual bool getData(const char* remotePath, const char* localPath, CallbackFunc cb, LPVOID lpParam) = 0; + virtual void abort() = 0; + virtual bool shutdown(); + virtual bool setDataInternal() = 0; + virtual void runCallback() = 0; + + + Status getStatus() { return m_status; } + int getDataProgress(); + void waitForStorageManagerIdle(); + + + + bool setData( PSAVE_INFO info, CallbackFunc cb, LPVOID lpParam ); + static int LoadSaveDataThumbnailReturned(LPVOID lpParam,PBYTE pbThumbnail,DWORD dwThumbnailBytes); + static int setDataThread(void* lpParam); + + SonyRemoteStorage() : m_memPoolBuffer(NULL), m_bInitialised(false),m_getInfoStatus(e_noInfoFound) {} + +protected: + const char* getRemoteSaveFilename(); + bool m_bInitialised; + void* m_memPoolBuffer; + Status m_status; + int m_dataProgress; + char *m_pchServiceID; + + PBYTE m_thumbnailData; + unsigned int m_thumbnailDataSize; + C4JThread* m_SetDataThread; + PSAVE_INFO m_setDataSaveInfo; + __int64 m_startTime; + + bool m_bAborting; + bool m_bTransferStarted; + +}; + diff --git a/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorage.h b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorage.h new file mode 100644 index 00000000..de70398d --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorage.h @@ -0,0 +1,137 @@ + +#ifndef SCE_REMOTE_STORAGE_H +#define SCE_REMOTE_STORAGE_H + +#include "sceRemoteStorageDefines.h" + +/// @brief +/// Initialises the RemoteStorage library. +/// +/// Initialises the RemoteStorage library, creates a session on the server and starts the Thread to process requests. +/// This method must be executed to start the RemoteStorage library or none of its functionality will be available. +/// This method will block while it initializes its thread and will return an error if it is +/// unable to do so. The session will be created on the thread once this is created and it won't be a blocking operation. +/// +/// It is important to note that HTTP, SSL and NET libraries are not being initialised by the library and should be initialised outside of it. +/// +/// @param params The structure of type <>SceRemoteStorageInitParams</c> that contains necessary information to start the library. +/// +/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_INVALID_ARGUMENT At least one of the arguments passed in the input structure is not valid. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. +/// @retval USER_ACCOUNT_LINKED This event will be sent to the event callback when the session is created and linked to PSN on the server +/// @retval PSN_SIGN_IN_REQUIRED This event will be sent to the event callback when the session is created but not linked to PSN on the server. +/// This will only happen on the PC version and requires to call <c>sceRemoteStorageOpenWebBrowser()</c> function. +/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// +/// @note System errors may be returned. Design your code so it does expect other errors. +int32_t sceRemoteStorageInit(const SceRemoteStorageInitParams & params); + +/// @brief +/// Terminates the RemoteStorage library. +/// +/// Terminates the RemoteStorage library and deletes the thread that process requests. +/// This method must be executed to terminate the RemoteStorage library to prevent leaks in memory and resources. +/// This method will abort any other pending requests and terminate the library. It won't wait for requests to finish. +/// This method is synchronous and does not make use of the callback to inform the user of success termination. It is executed on the calling thread. +/// +/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successful. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. +/// +/// @note System errors may be returned. Design your code so it does expect other errors. +int32_t sceRemoteStorageTerm(); + +/// @brief +/// Aborts a request sent to the RemoteStorage library. +/// +/// Aborts a request being processed or pending to be processed by the RemoteStorage library. +/// This method is synchronous and does not make use of the callback to inform the user of success termination. It is executed on the calling thread. +/// +/// @param param A structure containing the request Id to be aborted. +/// This request Id is provided by other functions (get/setData, getStatus and OpenWebBrowser) so they can be referenced. +/// +/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successful. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_REQ_ID_NOT_FOUND The request Id sent is not found. +/// +/// @note System errors may be returned. Design your code so it does expect other errors. +int32_t sceRemoteStorageAbort(const SceRemoteStorageAbortReqParams & params); + +/// @brief +/// Opens the default web browser to sign in to PSN on PC. +/// +/// Opens the default web browser to sign in to PSN on PC. This function does not have any functionality on other platforms. +/// This method does make use of the callback to inform the user of success termination. This function has priority over other functions on the thread (as getData(), getStatus() +/// and setData()) and it will be executed as soon as the thread finishes processing a pending request. +/// +/// @param param The structure containing extra parameters to be passed in. This structure does only exist for future expansions. +/// +/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. +/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// +/// @note System errors may be returned. Design your code so it does expect other errors. +int32_t sceRemoteStorageOpenWebBrowser(const SceRemoteStorageWebBrowserReqParams & params); + +/// @brief +/// Gives details for all files of a user. +/// +/// Gives details for all files of a user. It provides generic information (remaining bandwidth per day, HDD space per user, number of files) as well as +/// specific file information (number of bytes, file name, file description, MD5 checksum, timestamp and file visibility). File data is not provided. +/// This method does make use of the callback to inform the user of success termination. The SceRemoteStorageStatus pointer must be pointer a to a valid +/// location in memory until the callback is called as the output information will be stored in such location. +/// +/// @param params The structure containing extra parameters to be passed in. This structure does only exist for future expansions. +/// @param status The structure where the output information will be stored. The memory location being pointed must be valid until the callback gets called. +/// +/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. +/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// +/// @note System errors may be returned. Design your code so it does expect other errors. +int32_t sceRemoteStorageGetStatus(const SceRemoteStorageStatusReqParams & params, SceRemoteStorageStatus * status); + +/// @brief +/// Gets section of data from a file specified. +/// +/// Gets section of data from a file specified. The amount of data requested can be of any size. To request this information the name of file, the number of bytes and +/// the byte to start reading along with a buffer to store such data must be provided. +/// Metadata information of the file, as description or visibility, will be provided only in the case the first amount of bytes for the file are requested (offset = 0). +/// This method does make use of the callback to inform the user of success termination. The SceRemoteStorageData pointer must be a pointer to a valid +/// location in memory until the callback is called as the output information will be stored in such location. +/// +/// @param params The structure containing the file name to read, the start byte to start reading and the amount of bytes to read. +/// @param status The structure where the output information will be stored. The memory location being pointed must be valid until the callback gets called. +/// +/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. +/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// +/// @note System errors may be returned. Design your code so it does expect other errors. +int32_t sceRemoteStorageGetData(const SceRemoteStorageGetDataReqParams & params, SceRemoteStorageData * data); + +/// @brief +/// Sets chunk of data to a file specified. +/// +/// Sets chunk of data to a file specified. The amount of data sent must be of, at least, 5 Megabytes per chunk excepts +/// in the case of the last chunk of the file (or the only one if that is the case) as it can be smaller. +/// The information provided regarding the chunk as the chunk number, total number of chunks, data buffer and its size should be provided in every call. +/// The information provided regarding the file as its name, description and visibility should be provided in the last chunk only (this is, when +/// chunk number = number of chunks). +/// This method does make use of the callback to inform the user of success termination. The data attribute of the SceRemoteStorageSetDataReqParams pointer +/// must be a pointer to a valid location in memory until the callback is called as the buffer won't be copied internally. +/// +/// @param data The structure containing the chunk information. +/// +/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. +/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// +/// @note System errors may be returned. Design your code so it does expect other errors. +int32_t sceRemoteStorageSetData(const SceRemoteStorageSetDataReqParams & data); + +#endif
\ No newline at end of file diff --git a/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorageDefines.h b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorageDefines.h new file mode 100644 index 00000000..b3c8f5cc --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorageDefines.h @@ -0,0 +1,167 @@ + +#ifndef SCE_REMOTE_STORAGE_DEFINES_H +#define SCE_REMOTE_STORAGE_DEFINES_H + +#ifdef __psp2__ +#include <stddef.h> +#include <apputil.h> +#elif __ORBIS__ +#include <stddef.h> +#define SceAppUtilSaveDataDataSlot int +#elif __PS3__ +#define SceAppUtilSaveDataDataSlot int +#endif + +#include <stdint.h> + +// Macros +#define SCE_REMOTE_STORAGE_MAX_FILES 16 +#define SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN 64 +#define SCE_REMOTE_STORAGE_CLIENT_ID_MAX_LEN 64 +#define SCE_REMOTE_STORAGE_PLATFORM_NAME_MAX_LEN 16 +#define SCE_REMOTE_STORAGE_MD5_STRING_LENGTH 33 +#define SCE_REMOTE_STORAGE_RFC2822_LENGTH 32 +#define SCE_REMOTE_STORAGE_DATA_DESCRIPTION_MAX_LEN 256 +#define SCE_REMOTE_STORAGE_DATA_LOCATION_MAX_LEN 256 +#define SCE_REMOTE_STORAGE_PS3_SAVEDATA_SECUREFILEID_SIZE 16 +#define SCE_REMOTE_STORAGE_PS3_SAVEDATA_FILENAME_SIZE 13 +#define SCE_REMOTE_STORAGE_AUTH_CODE_MAX_LEN 128 + +// Return values +#define SCE_REMOTE_STORAGE_SUCCESS 0 + +// Error codes +#define SCE_REMOTE_STORAGE_ERROR_INVALID_ARGUMENT 0x80001001 +#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_CREATE_THREAD 0x80001002 +#define SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED 0x80001003 +#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_OPEN_WEB_BROWSER 0x80001004 +#define SCE_REMOTE_STORAGE_ERROR_PSN_ACCOUNT_NOT_LINKED 0x80001005 +#define SCE_REMOTE_STORAGE_ERROR_COULD_NOT_CREATE_SESSION 0x80001006 +#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE 0x80001007 +#define SCE_REMOTE_STORAGE_ERROR_SESSION_DOES_NOT_EXIST 0x80001008 +#define SCE_REMOTE_STORAGE_ERROR_REQ_ID_NOT_FOUND 0x80001009 +#define SCE_REMOTE_STORAGE_ERROR_MAX_NUMBER_FILES_REACHED 0x8000100A +#define SCE_REMOTE_STORAGE_ERROR_NO_MORE_SYNCS 0x8000100B +#define SCE_REMOTE_STORAGE_ERROR_ALREADY_INITIALISED 0x8000100C +#define SCE_REMOTE_STORAGE_ERROR_INVALID_UPLOADID 0x8000100D +#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_OPEN_FILE 0x8000100E +#define SCE_REMOTE_STORAGE_ERROR_CLOUD_DATA_CORRUPTED 0x8000100F +#define SCE_REMOTE_STORAGE_ERROR_INVALID_CHAR_IN_FILE_NAME 0x80001010 +#define SCE_REMOTE_STORAGE_ERROR_INVALID_JSON_RESPONSE 0x80001011 +#define SCE_REMOTE_STORAGE_ERROR_REQUEST_ABORTED 0x80001012 +#define SCE_REMOTE_STORAGE_ERROR_SERVER_ERROR 0x80002000 // Server errors can be between 0x80002064 to 0x800022BB both included + + +typedef enum SceRemoteStorageDataVisibility +{ + PRIVATE = 0, // Only data owner can read and write data + PUBLIC_READ_ONLY, // Everyone can read this data. Owner can write to it + PUBLIC_READ_WRITE // Everyone can read and write data +} SceRemoteStorageDataVisibility; + +typedef enum SceRemoteStorageEvent +{ + USER_ACCOUNT_LINKED = 0, // User's account has been linked with PSN + PSN_SIGN_IN_REQUIRED, // User's PSN sign-in through web browser is required + WEB_BROWSER_RESULT, // Result of sceRemoteStorageOpenWebBrowser(). Please check retCode + GET_DATA_RESULT, // Result of sceRemoteStorageGetData(). Please check retCode + GET_DATA_PROGRESS, // Progress of sceRemoteStorageGetData() completion as a percentage. Please check retCode + SET_DATA_RESULT, // Result of sceRemoteStorageSetData(). Please check retCode + SET_DATA_PROGRESS, // Progress of sceRemoteStorageSetData() completion as a percentage. Please check retCode + GET_STATUS_RESULT, // Result of sceRemoteStorageGetStatus(). Please check retCode + ERROR_OCCURRED // A generic error has occurred. Please check retCode +} SceRemoteStorageEvent; + +typedef enum SceRemoteStorageEnvironment +{ + DEVELOPMENT = 0, + PRODUCTION +}SceRemoteStorageEnvironment; + +typedef void (*sceRemoteStorageCallback)(const SceRemoteStorageEvent event, int32_t retCode, void * userData); + +typedef struct SceRemoteStorageInitParamsThread +{ + int32_t threadAffinity; // Thread affinity + int32_t threadPriority; // Priority that the thread runs out +} SceRemoteStorageInitParamsThread; + +typedef struct SceRemoteStorageInitParamsPool +{ + void * memPoolBuffer; // Memory pool used by sceRemoteStorage library + size_t memPoolSize; // Size of memPoolBuffer +} SceRemoteStorageInitParamsPool; + +typedef struct SceRemoteStorageInitTimeout +{ + uint32_t resolveMs; //Timeout for DNS resolution in milliseconds. Defaults to 30 seconds + uint32_t connectMs; //Timeout for first connection between client and server. Defaults to 30 seconds + uint32_t sendMs; //Timeout to send request to server. Defaults to 120 seconds + uint32_t receiveMs; //Timeout to receive information from server. Defaults to 120 seconds + + SceRemoteStorageInitTimeout() : resolveMs(30 * 1000), connectMs(30 * 1000), sendMs(120 * 1000), receiveMs(120 * 1000) {} +}SceRemoteStorageInitTimeout; + +typedef struct SceRemoteStorageInitParams +{ + sceRemoteStorageCallback callback; // Event callback + void * userData; // Application defined data for callback + int32_t httpContextId; // PS4 only: Http context ID that was returned from sceHttpInit() + int32_t userId; // PS4 only: Current user, see SceUserServiceUserId + void * psnTicket; // PS3 only: The PSN ticket used to authenticate the user + size_t psnTicketSize; // PS3 only: The size of the PSN ticket in bytes + char clientId[SCE_REMOTE_STORAGE_CLIENT_ID_MAX_LEN]; // This represents your application on PSN, used to sign PSN user in for your title + SceRemoteStorageInitTimeout timeout; // Timeout for network transactions + SceRemoteStorageInitParamsPool pool; // Memory pool parameters + SceRemoteStorageInitParamsThread thread; // Thread creation parameters + SceRemoteStorageEnvironment environment; // Only used on non-PlayStation platforms: PSN Environment used by the library +} SceRemoteStorageInitParams; + +typedef struct SceRemoteStorageGetDataReqParams +{ + char fileName[SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN]; // Name of file on remote storage server + char pathLocation[SCE_REMOTE_STORAGE_DATA_LOCATION_MAX_LEN]; // File location on the HDD + char secureFileId[SCE_REMOTE_STORAGE_PS3_SAVEDATA_SECUREFILEID_SIZE]; // PS3 only. ID used for save data encryption + char ps3DataFilename[SCE_REMOTE_STORAGE_PS3_SAVEDATA_FILENAME_SIZE]; // PS3 only. Name of data file in save data + uint32_t ps3FileType; // PS3 only. Type of file, CELL_SAVEDATA_FILETYPE_XXX + SceAppUtilSaveDataDataSlot psVitaSaveDataSlot; // PS Vita only. Save data slot information +} SceRemoteStorageGetDataReqParams; + +typedef struct SceRemoteStorageSetDataReqParams +{ + char fileName[SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN]; // Name of file on remote storage server + char fileDescription[SCE_REMOTE_STORAGE_DATA_DESCRIPTION_MAX_LEN]; // Description of file on remote storage server + char pathLocation[SCE_REMOTE_STORAGE_DATA_LOCATION_MAX_LEN]; // File location on the HDD + char secureFileId[SCE_REMOTE_STORAGE_PS3_SAVEDATA_SECUREFILEID_SIZE]; // PS3 only. ID used for save data encryption + char ps3DataFilename[SCE_REMOTE_STORAGE_PS3_SAVEDATA_FILENAME_SIZE]; // PS3 only. Name of data file in save data + uint32_t ps3FileType; // PS3 only. Type of file, CELL_SAVEDATA_FILETYPE_XXX + SceRemoteStorageDataVisibility visibility; // Visibility of data +} SceRemoteStorageSetDataReqParams; + +typedef struct SceRemoteStorageData +{ + char fileName[SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN]; // Name of file on remote storage server + char fileDescription[SCE_REMOTE_STORAGE_DATA_DESCRIPTION_MAX_LEN]; // Description of file on remote storage server + size_t fileSize; // Size of file in bytes + char md5Checksum[SCE_REMOTE_STORAGE_MD5_STRING_LENGTH]; // File MD5 checksum + char timeStamp[SCE_REMOTE_STORAGE_RFC2822_LENGTH]; // Time that data was written on the server. Format is RFC2822 + SceRemoteStorageDataVisibility visibility; // Visibility of data +} SceRemoteStorageData; + +typedef struct SceRemoteStorageWebBrowserReqParams { } SceRemoteStorageWebBrowseReqParams; + +typedef struct SceRemoteStorageStatusReqParams { } SceRemoteStorageStatusReqParams; + +typedef struct SceRemoteStorageAbortReqParams +{ + uint32_t requestId; // The request Id to be aborted +} SceRemoteStorageAbortReqParams; + +typedef struct SceRemoteStorageStatus +{ + uint32_t numFiles; // Number of files user has on remote storage server + SceRemoteStorageData data[SCE_REMOTE_STORAGE_MAX_FILES]; // Details about data if available. Data buffer will not be retrieved + uint64_t remainingSyncs; // Remaining syncs. the user has for upload/download +} SceRemoteStorageStatus; + +#endif diff --git a/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/ps3/lib/sceRemoteStorage.a b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/ps3/lib/sceRemoteStorage.a Binary files differnew file mode 100644 index 00000000..1b2eb640 --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/ps3/lib/sceRemoteStorage.a diff --git a/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/ps4/lib/sceRemoteStorage.a b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/ps4/lib/sceRemoteStorage.a Binary files differnew file mode 100644 index 00000000..2e667e20 --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/ps4/lib/sceRemoteStorage.a diff --git a/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/psvita/lib/sceRemoteStorage.a b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/psvita/lib/sceRemoteStorage.a Binary files differnew file mode 100644 index 00000000..f8568afd --- /dev/null +++ b/Minecraft.Client/Common/Network/Sony/sceRemoteStorage/psvita/lib/sceRemoteStorage.a |
