Terraria 1.4.0.5 Source Code

This commit is contained in:
MikeyIsBaeYT 2021-10-26 12:45:26 -04:00
commit 05205f009e
1059 changed files with 563450 additions and 0 deletions

View file

@ -0,0 +1,108 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.AchievementsSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Terraria.Social.Steam
{
public class AchievementsSocialModule : Terraria.Social.Base.AchievementsSocialModule
{
private const string FILE_NAME = "/achievements-steam.dat";
private Callback<UserStatsReceived_t> _userStatsReceived;
private bool _areStatsReceived;
private Dictionary<string, int> _intStatCache = new Dictionary<string, int>();
private Dictionary<string, float> _floatStatCache = new Dictionary<string, float>();
public override void Initialize()
{
// ISSUE: method pointer
this._userStatsReceived = Callback<UserStatsReceived_t>.Create(new Callback<UserStatsReceived_t>.DispatchDelegate((object) this, __methodptr(OnUserStatsReceived)));
SteamUserStats.RequestCurrentStats();
while (!this._areStatsReceived)
{
CoreSocialModule.Pulse();
Thread.Sleep(10);
}
}
public override void Shutdown() => this.StoreStats();
public override bool IsAchievementCompleted(string name)
{
bool flag;
return SteamUserStats.GetAchievement(name, ref flag) & flag;
}
public override byte[] GetEncryptionKey()
{
byte[] numArray = new byte[16];
byte[] bytes = BitConverter.GetBytes((ulong) SteamUser.GetSteamID().m_SteamID);
Array.Copy((Array) bytes, (Array) numArray, 8);
Array.Copy((Array) bytes, 0, (Array) numArray, 8, 8);
return numArray;
}
public override string GetSavePath() => "/achievements-steam.dat";
private int GetIntStat(string name)
{
int num;
if (this._intStatCache.TryGetValue(name, out num) || !SteamUserStats.GetStat(name, ref num))
return num;
this._intStatCache.Add(name, num);
return num;
}
private float GetFloatStat(string name)
{
float num;
if (this._floatStatCache.TryGetValue(name, out num) || !SteamUserStats.GetStat(name, ref num))
return num;
this._floatStatCache.Add(name, num);
return num;
}
private bool SetFloatStat(string name, float value)
{
this._floatStatCache[name] = value;
return SteamUserStats.SetStat(name, value);
}
public override void UpdateIntStat(string name, int value)
{
if (this.GetIntStat(name) >= value)
return;
this.SetIntStat(name, value);
}
private bool SetIntStat(string name, int value)
{
this._intStatCache[name] = value;
return SteamUserStats.SetStat(name, value);
}
public override void UpdateFloatStat(string name, float value)
{
if ((double) this.GetFloatStat(name) >= (double) value)
return;
this.SetFloatStat(name, value);
}
public override void StoreStats() => SteamUserStats.StoreStats();
public override void CompleteAchievement(string name) => SteamUserStats.SetAchievement(name);
private void OnUserStatsReceived(UserStatsReceived_t results)
{
if (results.m_nGameID != 105600L || !CSteamID.op_Equality((CSteamID) results.m_steamIDUser, SteamUser.GetSteamID()))
return;
this._areStatsReceived = true;
}
}
}

View file

@ -0,0 +1,79 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.CloudSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
using System;
using System.Collections.Generic;
namespace Terraria.Social.Steam
{
public class CloudSocialModule : Terraria.Social.Base.CloudSocialModule
{
private const uint WRITE_CHUNK_SIZE = 1024;
private object ioLock = new object();
private byte[] writeBuffer = new byte[1024];
public override void Initialize() => base.Initialize();
public override void Shutdown()
{
}
public override IEnumerable<string> GetFiles()
{
lock (this.ioLock)
{
int fileCount = SteamRemoteStorage.GetFileCount();
List<string> stringList = new List<string>(fileCount);
for (int index = 0; index < fileCount; ++index)
{
int num;
stringList.Add(SteamRemoteStorage.GetFileNameAndSize(index, ref num));
}
return (IEnumerable<string>) stringList;
}
}
public override bool Write(string path, byte[] data, int length)
{
lock (this.ioLock)
{
UGCFileWriteStreamHandle_t writeStreamHandleT = SteamRemoteStorage.FileWriteStreamOpen(path);
for (uint index = 0; (long) index < (long) length; index += 1024U)
{
int num = (int) Math.Min(1024L, (long) length - (long) index);
Array.Copy((Array) data, (long) index, (Array) this.writeBuffer, 0L, (long) num);
SteamRemoteStorage.FileWriteStreamWriteChunk(writeStreamHandleT, this.writeBuffer, num);
}
return SteamRemoteStorage.FileWriteStreamClose(writeStreamHandleT);
}
}
public override int GetFileSize(string path)
{
lock (this.ioLock)
return SteamRemoteStorage.GetFileSize(path);
}
public override void Read(string path, byte[] buffer, int size)
{
lock (this.ioLock)
SteamRemoteStorage.FileRead(path, buffer, size);
}
public override bool HasFile(string path)
{
lock (this.ioLock)
return SteamRemoteStorage.FileExists(path);
}
public override bool Delete(string path)
{
lock (this.ioLock)
return SteamRemoteStorage.FileDelete(path);
}
}
}

View file

@ -0,0 +1,109 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.CoreSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using ReLogic.OS;
using Steamworks;
using System;
using System.Threading;
using System.Windows.Forms;
using Terraria.Localization;
namespace Terraria.Social.Steam
{
public class CoreSocialModule : ISocialModule
{
private static CoreSocialModule _instance;
public const int SteamAppId = 105600;
private bool IsSteamValid;
private object _steamTickLock = new object();
private object _steamCallbackLock = new object();
private Callback<GameOverlayActivated_t> _onOverlayActivated;
public static event Action OnTick;
public void Initialize()
{
CoreSocialModule._instance = this;
if (SteamAPI.RestartAppIfNecessary(new AppId_t(105600U)))
{
Environment.Exit(1);
}
else
{
if (!SteamAPI.Init())
{
int num = (int) MessageBox.Show(Language.GetTextValue("Error.LaunchFromSteam"), Language.GetTextValue("Error.Error"));
Environment.Exit(1);
}
this.IsSteamValid = true;
new Thread(new ParameterizedThreadStart(this.SteamCallbackLoop))
{
IsBackground = true
}.Start();
new Thread(new ParameterizedThreadStart(this.SteamTickLoop))
{
IsBackground = true
}.Start();
Main.OnTickForThirdPartySoftwareOnly += new Action(this.PulseSteamTick);
Main.OnTickForThirdPartySoftwareOnly += new Action(this.PulseSteamCallback);
if (!Platform.IsOSX)
return;
// ISSUE: method pointer
this._onOverlayActivated = Callback<GameOverlayActivated_t>.Create(new Callback<GameOverlayActivated_t>.DispatchDelegate((object) this, __methodptr(OnOverlayActivated)));
}
}
public void PulseSteamTick()
{
if (!Monitor.TryEnter(this._steamTickLock))
return;
Monitor.Pulse(this._steamTickLock);
Monitor.Exit(this._steamTickLock);
}
public void PulseSteamCallback()
{
if (!Monitor.TryEnter(this._steamCallbackLock))
return;
Monitor.Pulse(this._steamCallbackLock);
Monitor.Exit(this._steamCallbackLock);
}
public static void Pulse()
{
CoreSocialModule._instance.PulseSteamTick();
CoreSocialModule._instance.PulseSteamCallback();
}
private void SteamTickLoop(object context)
{
Monitor.Enter(this._steamTickLock);
while (this.IsSteamValid)
{
if (CoreSocialModule.OnTick != null)
CoreSocialModule.OnTick();
Monitor.Wait(this._steamTickLock);
}
Monitor.Exit(this._steamTickLock);
}
private void SteamCallbackLoop(object context)
{
Monitor.Enter(this._steamCallbackLock);
while (this.IsSteamValid)
{
SteamAPI.RunCallbacks();
Monitor.Wait(this._steamCallbackLock);
}
Monitor.Exit(this._steamCallbackLock);
SteamAPI.Shutdown();
}
public void Shutdown() => Application.ApplicationExit += (EventHandler) ((obj, evt) => this.IsSteamValid = false);
public void OnOverlayActivated(GameOverlayActivated_t result) => Main.instance.IsMouseVisible = result.m_bActive == 1;
}
}

View file

@ -0,0 +1,25 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.FriendsSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
namespace Terraria.Social.Steam
{
public class FriendsSocialModule : Terraria.Social.Base.FriendsSocialModule
{
public override void Initialize()
{
}
public override void Shutdown()
{
}
public override string GetUsername() => SteamFriends.GetPersonaName();
public override void OpenJoinInterface() => SteamFriends.ActivateGameOverlay("Friends");
}
}

123
Social/Steam/Lobby.cs Normal file
View file

@ -0,0 +1,123 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.Lobby
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
using System;
using System.Collections.Generic;
namespace Terraria.Social.Steam
{
public class Lobby
{
private HashSet<CSteamID> _usersSeen = new HashSet<CSteamID>();
private byte[] _messageBuffer = new byte[1024];
public CSteamID Id = (CSteamID) CSteamID.Nil;
public CSteamID Owner = (CSteamID) CSteamID.Nil;
public LobbyState State;
private CallResult<LobbyEnter_t> _lobbyEnter;
private CallResult<LobbyEnter_t>.APIDispatchDelegate _lobbyEnterExternalCallback;
private CallResult<LobbyCreated_t> _lobbyCreated;
private CallResult<LobbyCreated_t>.APIDispatchDelegate _lobbyCreatedExternalCallback;
public Lobby()
{
// ISSUE: method pointer
this._lobbyEnter = CallResult<LobbyEnter_t>.Create(new CallResult<LobbyEnter_t>.APIDispatchDelegate((object) this, __methodptr(OnLobbyEntered)));
// ISSUE: method pointer
this._lobbyCreated = CallResult<LobbyCreated_t>.Create(new CallResult<LobbyCreated_t>.APIDispatchDelegate((object) this, __methodptr(OnLobbyCreated)));
}
public void Create(
bool inviteOnly,
CallResult<LobbyCreated_t>.APIDispatchDelegate callResult)
{
SteamAPICall_t lobby = SteamMatchmaking.CreateLobby(inviteOnly ? (ELobbyType) 0 : (ELobbyType) 1, 256);
this._lobbyCreatedExternalCallback = callResult;
this._lobbyCreated.Set(lobby, (CallResult<LobbyCreated_t>.APIDispatchDelegate) null);
this.State = LobbyState.Creating;
}
public void OpenInviteOverlay()
{
if (this.State == LobbyState.Inactive)
SteamFriends.ActivateGameOverlayInviteDialog(new CSteamID(Main.LobbyId));
else
SteamFriends.ActivateGameOverlayInviteDialog(this.Id);
}
public void Join(
CSteamID lobbyId,
CallResult<LobbyEnter_t>.APIDispatchDelegate callResult)
{
if (this.State != LobbyState.Inactive)
return;
this.State = LobbyState.Connecting;
this._lobbyEnterExternalCallback = callResult;
this._lobbyEnter.Set(SteamMatchmaking.JoinLobby(lobbyId), (CallResult<LobbyEnter_t>.APIDispatchDelegate) null);
}
public byte[] GetMessage(int index)
{
CSteamID csteamId;
EChatEntryType echatEntryType;
int lobbyChatEntry = SteamMatchmaking.GetLobbyChatEntry(this.Id, index, ref csteamId, this._messageBuffer, this._messageBuffer.Length, ref echatEntryType);
byte[] numArray = new byte[lobbyChatEntry];
Array.Copy((Array) this._messageBuffer, (Array) numArray, lobbyChatEntry);
return numArray;
}
public int GetUserCount() => SteamMatchmaking.GetNumLobbyMembers(this.Id);
public CSteamID GetUserByIndex(int index) => SteamMatchmaking.GetLobbyMemberByIndex(this.Id, index);
public bool SendMessage(byte[] data) => this.SendMessage(data, data.Length);
public bool SendMessage(byte[] data, int length) => this.State == LobbyState.Active && SteamMatchmaking.SendLobbyChatMsg(this.Id, data, length);
public void Set(CSteamID lobbyId)
{
this.Id = lobbyId;
this.State = LobbyState.Active;
this.Owner = SteamMatchmaking.GetLobbyOwner(lobbyId);
}
public void SetPlayedWith(CSteamID userId)
{
if (this._usersSeen.Contains(userId))
return;
SteamFriends.SetPlayedWith(userId);
this._usersSeen.Add(userId);
}
public void Leave()
{
if (this.State == LobbyState.Active)
SteamMatchmaking.LeaveLobby(this.Id);
this.State = LobbyState.Inactive;
this._usersSeen.Clear();
}
private void OnLobbyEntered(LobbyEnter_t result, bool failure)
{
if (this.State != LobbyState.Connecting)
return;
this.State = !failure ? LobbyState.Active : LobbyState.Inactive;
this.Id = new CSteamID((ulong) result.m_ulSteamIDLobby);
this.Owner = SteamMatchmaking.GetLobbyOwner(this.Id);
this._lobbyEnterExternalCallback.Invoke(result, failure);
}
private void OnLobbyCreated(LobbyCreated_t result, bool failure)
{
if (this.State != LobbyState.Creating)
return;
this.State = !failure ? LobbyState.Active : LobbyState.Inactive;
this.Id = new CSteamID((ulong) result.m_ulSteamIDLobby);
this.Owner = SteamMatchmaking.GetLobbyOwner(this.Id);
this._lobbyCreatedExternalCallback.Invoke(result, failure);
}
}
}

View file

@ -0,0 +1,16 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.LobbyState
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
namespace Terraria.Social.Steam
{
public enum LobbyState
{
Inactive,
Connecting,
Creating,
Active,
}
}

View file

@ -0,0 +1,243 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.NetClientSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
using System;
using System.Diagnostics;
using Terraria.Localization;
using Terraria.Net;
using Terraria.Net.Sockets;
using Terraria.Social.WeGame;
namespace Terraria.Social.Steam
{
public class NetClientSocialModule : NetSocialModule
{
private Callback<GameLobbyJoinRequested_t> _gameLobbyJoinRequested;
private Callback<P2PSessionRequest_t> _p2pSessionRequest;
private Callback<P2PSessionConnectFail_t> _p2pSessionConnectfail;
private HAuthTicket _authTicket = (HAuthTicket) HAuthTicket.Invalid;
private byte[] _authData = new byte[1021];
private uint _authDataLength;
private bool _hasLocalHost;
public NetClientSocialModule()
: base(2, 1)
{
}
public override void Initialize()
{
base.Initialize();
// ISSUE: method pointer
this._gameLobbyJoinRequested = Callback<GameLobbyJoinRequested_t>.Create(new Callback<GameLobbyJoinRequested_t>.DispatchDelegate((object) this, __methodptr(OnLobbyJoinRequest)));
// ISSUE: method pointer
this._p2pSessionRequest = Callback<P2PSessionRequest_t>.Create(new Callback<P2PSessionRequest_t>.DispatchDelegate((object) this, __methodptr(OnP2PSessionRequest)));
// ISSUE: method pointer
this._p2pSessionConnectfail = Callback<P2PSessionConnectFail_t>.Create(new Callback<P2PSessionConnectFail_t>.DispatchDelegate((object) this, __methodptr(OnSessionConnectFail)));
Main.OnEngineLoad += new Action(this.CheckParameters);
}
private void CheckParameters()
{
ulong result;
if (!Program.LaunchParameters.ContainsKey("+connect_lobby") || !ulong.TryParse(Program.LaunchParameters["+connect_lobby"], out result))
return;
this.ConnectToLobby(result);
}
public void ConnectToLobby(ulong lobbyId)
{
CSteamID lobbySteamId = new CSteamID(lobbyId);
if (!((CSteamID) ref lobbySteamId).IsValid())
return;
Main.OpenPlayerSelect((Main.OnPlayerSelected) (playerData =>
{
Main.ServerSideCharacter = false;
playerData.SetAsActive();
Main.menuMode = 882;
Main.statusText = Language.GetTextValue("Social.Joining");
WeGameHelper.WriteDebugString(" CheckParameters lobby.join");
// ISSUE: method pointer
this._lobby.Join(lobbySteamId, new CallResult<LobbyEnter_t>.APIDispatchDelegate((object) this, __methodptr(OnLobbyEntered)));
}));
}
public override void LaunchLocalServer(Process process, ServerMode mode)
{
WeGameHelper.WriteDebugString(nameof (LaunchLocalServer));
if (this._lobby.State != LobbyState.Inactive)
this._lobby.Leave();
ProcessStartInfo startInfo = process.StartInfo;
startInfo.Arguments = startInfo.Arguments + " -steam -localsteamid " + (object) (ulong) SteamUser.GetSteamID().m_SteamID;
if (mode.HasFlag((Enum) ServerMode.Lobby))
{
this._hasLocalHost = true;
if (mode.HasFlag((Enum) ServerMode.FriendsCanJoin))
process.StartInfo.Arguments += " -lobby friends";
else
process.StartInfo.Arguments += " -lobby private";
if (mode.HasFlag((Enum) ServerMode.FriendsOfFriends))
process.StartInfo.Arguments += " -friendsoffriends";
}
SteamFriends.SetRichPresence("status", Language.GetTextValue("Social.StatusInGame"));
Netplay.OnDisconnect += new Action(this.OnDisconnect);
process.Start();
}
public override ulong GetLobbyId() => 0;
public override bool StartListening(SocketConnectionAccepted callback) => false;
public override void StopListening()
{
}
public override void Close(RemoteAddress address)
{
SteamFriends.ClearRichPresence();
this.Close(this.RemoteAddressToSteamId(address));
}
public override bool CanInvite() => (this._hasLocalHost || this._lobby.State == LobbyState.Active || Main.LobbyId != 0UL) && (uint) Main.netMode > 0U;
public override void OpenInviteInterface() => this._lobby.OpenInviteOverlay();
private void Close(CSteamID user)
{
if (!this._connectionStateMap.ContainsKey(user))
return;
SteamNetworking.CloseP2PSessionWithUser(user);
this.ClearAuthTicket();
this._connectionStateMap[user] = NetSocialModule.ConnectionState.Inactive;
this._lobby.Leave();
this._reader.ClearUser(user);
this._writer.ClearUser(user);
}
public override void Connect(RemoteAddress address)
{
}
public override void CancelJoin()
{
if (this._lobby.State == LobbyState.Inactive)
return;
this._lobby.Leave();
}
private void OnLobbyJoinRequest(GameLobbyJoinRequested_t result)
{
WeGameHelper.WriteDebugString(" OnLobbyJoinRequest");
if (this._lobby.State != LobbyState.Inactive)
this._lobby.Leave();
string friendName = SteamFriends.GetFriendPersonaName((CSteamID) result.m_steamIDFriend);
Main.QueueMainThreadAction((Action) (() => Main.OpenPlayerSelect((Main.OnPlayerSelected) (playerData =>
{
Main.ServerSideCharacter = false;
playerData.SetAsActive();
Main.menuMode = 882;
Main.statusText = Language.GetTextValue("Social.JoiningFriend", (object) friendName);
// ISSUE: method pointer
this._lobby.Join((CSteamID) result.m_steamIDLobby, new CallResult<LobbyEnter_t>.APIDispatchDelegate((object) this, __methodptr(OnLobbyEntered)));
}))));
}
private void OnLobbyEntered(LobbyEnter_t result, bool failure)
{
WeGameHelper.WriteDebugString(" OnLobbyEntered");
SteamNetworking.AllowP2PPacketRelay(true);
this.SendAuthTicket(this._lobby.Owner);
int num = 0;
P2PSessionState_t p2PsessionStateT;
while (SteamNetworking.GetP2PSessionState(this._lobby.Owner, ref p2PsessionStateT) && p2PsessionStateT.m_bConnectionActive != 1)
{
switch ((byte) p2PsessionStateT.m_eP2PSessionError)
{
case 1:
this.ClearAuthTicket();
return;
case 2:
this.ClearAuthTicket();
return;
case 3:
this.ClearAuthTicket();
return;
case 4:
if (++num > 5)
{
this.ClearAuthTicket();
return;
}
SteamNetworking.CloseP2PSessionWithUser(this._lobby.Owner);
this.SendAuthTicket(this._lobby.Owner);
continue;
case 5:
this.ClearAuthTicket();
return;
default:
continue;
}
}
this._connectionStateMap[this._lobby.Owner] = NetSocialModule.ConnectionState.Connected;
SteamFriends.SetPlayedWith(this._lobby.Owner);
SteamFriends.SetRichPresence("status", Language.GetTextValue("Social.StatusInGame"));
Main.clrInput();
Netplay.ServerPassword = "";
Main.GetInputText("");
Main.autoPass = false;
Main.netMode = 1;
Netplay.OnConnectedToSocialServer((ISocket) new SocialSocket((RemoteAddress) new SteamAddress(this._lobby.Owner)));
}
private void SendAuthTicket(CSteamID address)
{
WeGameHelper.WriteDebugString(" SendAuthTicket");
if (HAuthTicket.op_Equality(this._authTicket, (HAuthTicket) HAuthTicket.Invalid))
this._authTicket = SteamUser.GetAuthSessionTicket(this._authData, this._authData.Length, ref this._authDataLength);
int length = (int) this._authDataLength + 3;
byte[] numArray = new byte[length];
numArray[0] = (byte) (length & (int) byte.MaxValue);
numArray[1] = (byte) (length >> 8 & (int) byte.MaxValue);
numArray[2] = (byte) 93;
for (int index = 0; (long) index < (long) this._authDataLength; ++index)
numArray[index + 3] = this._authData[index];
SteamNetworking.SendP2PPacket(address, numArray, (uint) length, (EP2PSend) 2, 1);
}
private void ClearAuthTicket()
{
if (HAuthTicket.op_Inequality(this._authTicket, (HAuthTicket) HAuthTicket.Invalid))
SteamUser.CancelAuthTicket(this._authTicket);
this._authTicket = (HAuthTicket) HAuthTicket.Invalid;
for (int index = 0; index < this._authData.Length; ++index)
this._authData[index] = (byte) 0;
this._authDataLength = 0U;
}
private void OnDisconnect()
{
SteamFriends.ClearRichPresence();
this._hasLocalHost = false;
Netplay.OnDisconnect -= new Action(this.OnDisconnect);
}
private void OnSessionConnectFail(P2PSessionConnectFail_t result)
{
WeGameHelper.WriteDebugString(" OnSessionConnectFail");
this.Close((CSteamID) result.m_steamIDRemote);
}
private void OnP2PSessionRequest(P2PSessionRequest_t result)
{
WeGameHelper.WriteDebugString(" OnP2PSessionRequest");
CSteamID steamIdRemote = (CSteamID) result.m_steamIDRemote;
if (!this._connectionStateMap.ContainsKey(steamIdRemote) || this._connectionStateMap[steamIdRemote] == NetSocialModule.ConnectionState.Inactive)
return;
SteamNetworking.AcceptP2PSessionWithUser(steamIdRemote);
}
}
}

View file

@ -0,0 +1,197 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.NetServerSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Terraria.Localization;
using Terraria.Net;
using Terraria.Net.Sockets;
namespace Terraria.Social.Steam
{
public class NetServerSocialModule : NetSocialModule
{
private ServerMode _mode;
private Callback<P2PSessionRequest_t> _p2pSessionRequest;
private bool _acceptingClients;
private SocketConnectionAccepted _connectionAcceptedCallback;
public NetServerSocialModule()
: base(1, 2)
{
}
private void BroadcastConnectedUsers()
{
List<ulong> ulongList = new List<ulong>();
foreach (KeyValuePair<CSteamID, NetSocialModule.ConnectionState> connectionState in this._connectionStateMap)
{
if (connectionState.Value == NetSocialModule.ConnectionState.Connected)
ulongList.Add((ulong) connectionState.Key.m_SteamID);
}
byte[] numArray = new byte[ulongList.Count * 8 + 1];
using (MemoryStream memoryStream = new MemoryStream(numArray))
{
using (BinaryWriter binaryWriter = new BinaryWriter((Stream) memoryStream))
{
binaryWriter.Write((byte) 1);
foreach (ulong num in ulongList)
binaryWriter.Write(num);
}
}
this._lobby.SendMessage(numArray);
}
public override void Initialize()
{
base.Initialize();
this._reader.SetReadEvent(new SteamP2PReader.OnReadEvent(this.OnPacketRead));
// ISSUE: method pointer
this._p2pSessionRequest = Callback<P2PSessionRequest_t>.Create(new Callback<P2PSessionRequest_t>.DispatchDelegate((object) this, __methodptr(OnP2PSessionRequest)));
if (Program.LaunchParameters.ContainsKey("-lobby"))
{
this._mode |= ServerMode.Lobby;
string launchParameter = Program.LaunchParameters["-lobby"];
if (!(launchParameter == "private"))
{
if (launchParameter == "friends")
{
this._mode |= ServerMode.FriendsCanJoin;
// ISSUE: method pointer
this._lobby.Create(false, new CallResult<LobbyCreated_t>.APIDispatchDelegate((object) this, __methodptr(OnLobbyCreated)));
}
else
Console.WriteLine(Language.GetTextValue("Error.InvalidLobbyFlag", (object) "private", (object) "friends"));
}
else
{
// ISSUE: method pointer
this._lobby.Create(true, new CallResult<LobbyCreated_t>.APIDispatchDelegate((object) this, __methodptr(OnLobbyCreated)));
}
}
if (!Program.LaunchParameters.ContainsKey("-friendsoffriends"))
return;
this._mode |= ServerMode.FriendsOfFriends;
}
public override ulong GetLobbyId() => (ulong) this._lobby.Id.m_SteamID;
public override void OpenInviteInterface()
{
}
public override void CancelJoin()
{
}
public override bool CanInvite() => false;
public override void LaunchLocalServer(Process process, ServerMode mode)
{
}
public override bool StartListening(SocketConnectionAccepted callback)
{
this._acceptingClients = true;
this._connectionAcceptedCallback = callback;
return true;
}
public override void StopListening() => this._acceptingClients = false;
public override void Connect(RemoteAddress address)
{
}
public override void Close(RemoteAddress address) => this.Close(this.RemoteAddressToSteamId(address));
private void Close(CSteamID user)
{
if (!this._connectionStateMap.ContainsKey(user))
return;
SteamUser.EndAuthSession(user);
SteamNetworking.CloseP2PSessionWithUser(user);
this._connectionStateMap[user] = NetSocialModule.ConnectionState.Inactive;
this._reader.ClearUser(user);
this._writer.ClearUser(user);
}
private void OnLobbyCreated(LobbyCreated_t result, bool failure)
{
if (failure)
return;
SteamFriends.SetRichPresence("status", Language.GetTextValue("Social.StatusInGame"));
}
private bool OnPacketRead(byte[] data, int length, CSteamID userId)
{
if (!this._connectionStateMap.ContainsKey(userId) || this._connectionStateMap[userId] == NetSocialModule.ConnectionState.Inactive)
{
P2PSessionRequest_t result;
result.m_steamIDRemote = (__Null) userId;
this.OnP2PSessionRequest(result);
if (!this._connectionStateMap.ContainsKey(userId) || this._connectionStateMap[userId] == NetSocialModule.ConnectionState.Inactive)
return false;
}
NetSocialModule.ConnectionState connectionState = this._connectionStateMap[userId];
if (connectionState != NetSocialModule.ConnectionState.Authenticating)
return connectionState == NetSocialModule.ConnectionState.Connected;
if (length < 3 || ((int) data[1] << 8 | (int) data[0]) != length || data[2] != (byte) 93)
return false;
byte[] numArray = new byte[data.Length - 3];
Array.Copy((Array) data, 3, (Array) numArray, 0, numArray.Length);
switch ((int) SteamUser.BeginAuthSession(numArray, numArray.Length, userId))
{
case 0:
this._connectionStateMap[userId] = NetSocialModule.ConnectionState.Connected;
this.BroadcastConnectedUsers();
break;
case 1:
this.Close(userId);
break;
case 2:
this.Close(userId);
break;
case 3:
this.Close(userId);
break;
case 4:
this.Close(userId);
break;
case 5:
this.Close(userId);
break;
}
return false;
}
private void OnP2PSessionRequest(P2PSessionRequest_t result)
{
CSteamID steamIdRemote = (CSteamID) result.m_steamIDRemote;
if (this._connectionStateMap.ContainsKey(steamIdRemote) && this._connectionStateMap[steamIdRemote] != NetSocialModule.ConnectionState.Inactive)
{
SteamNetworking.AcceptP2PSessionWithUser(steamIdRemote);
}
else
{
if (!this._acceptingClients || !this._mode.HasFlag((Enum) ServerMode.FriendsOfFriends) && SteamFriends.GetFriendRelationship(steamIdRemote) != 3)
return;
SteamNetworking.AcceptP2PSessionWithUser(steamIdRemote);
P2PSessionState_t p2PsessionStateT;
do
;
while (SteamNetworking.GetP2PSessionState(steamIdRemote, ref p2PsessionStateT) && p2PsessionStateT.m_bConnecting == 1);
if (p2PsessionStateT.m_bConnectionActive == null)
this.Close(steamIdRemote);
this._connectionStateMap[steamIdRemote] = NetSocialModule.ConnectionState.Authenticating;
this._connectionAcceptedCallback((ISocket) new SocialSocket((RemoteAddress) new SteamAddress(steamIdRemote)));
}
}
}
}

View file

@ -0,0 +1,126 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.NetSocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
using System;
using System.Collections.Concurrent;
using System.IO;
using Terraria.Net;
namespace Terraria.Social.Steam
{
public abstract class NetSocialModule : Terraria.Social.Base.NetSocialModule
{
protected const int ServerReadChannel = 1;
protected const int ClientReadChannel = 2;
protected const int LobbyMessageJoin = 1;
protected const ushort GamePort = 27005;
protected const ushort SteamPort = 27006;
protected const ushort QueryPort = 27007;
protected static readonly byte[] _handshake = new byte[10]
{
(byte) 10,
(byte) 0,
(byte) 93,
(byte) 114,
(byte) 101,
(byte) 108,
(byte) 111,
(byte) 103,
(byte) 105,
(byte) 99
};
protected SteamP2PReader _reader;
protected SteamP2PWriter _writer;
protected Lobby _lobby = new Lobby();
protected ConcurrentDictionary<CSteamID, NetSocialModule.ConnectionState> _connectionStateMap = new ConcurrentDictionary<CSteamID, NetSocialModule.ConnectionState>();
protected object _steamLock = new object();
private Callback<LobbyChatMsg_t> _lobbyChatMessage;
protected NetSocialModule(int readChannel, int writeChannel)
{
this._reader = new SteamP2PReader(readChannel);
this._writer = new SteamP2PWriter(writeChannel);
}
public override void Initialize()
{
CoreSocialModule.OnTick += new Action(this._reader.ReadTick);
CoreSocialModule.OnTick += new Action(this._writer.SendAll);
NetSocialModule netSocialModule = this;
// ISSUE: virtual method pointer
this._lobbyChatMessage = Callback<LobbyChatMsg_t>.Create(new Callback<LobbyChatMsg_t>.DispatchDelegate((object) netSocialModule, __vmethodptr(netSocialModule, OnLobbyChatMessage)));
}
public override void Shutdown() => this._lobby.Leave();
public override bool IsConnected(RemoteAddress address)
{
if (address == null)
return false;
CSteamID steamId = this.RemoteAddressToSteamId(address);
if (!this._connectionStateMap.ContainsKey(steamId) || this._connectionStateMap[steamId] != NetSocialModule.ConnectionState.Connected)
return false;
if (this.GetSessionState(steamId).m_bConnectionActive == 1)
return true;
this.Close(address);
return false;
}
protected virtual void OnLobbyChatMessage(LobbyChatMsg_t result)
{
if (result.m_ulSteamIDLobby != this._lobby.Id.m_SteamID || result.m_eChatEntryType != 1 || result.m_ulSteamIDUser != this._lobby.Owner.m_SteamID)
return;
byte[] message = this._lobby.GetMessage((int) result.m_iChatID);
if (message.Length == 0)
return;
using (MemoryStream memoryStream = new MemoryStream(message))
{
using (BinaryReader binaryReader = new BinaryReader((Stream) memoryStream))
{
if (binaryReader.ReadByte() != (byte) 1)
return;
while ((long) message.Length - memoryStream.Position >= 8L)
{
CSteamID userId;
// ISSUE: explicit constructor call
((CSteamID) ref userId).\u002Ector(binaryReader.ReadUInt64());
if (CSteamID.op_Inequality(userId, SteamUser.GetSteamID()))
this._lobby.SetPlayedWith(userId);
}
}
}
}
protected P2PSessionState_t GetSessionState(CSteamID userId)
{
P2PSessionState_t p2PsessionStateT;
SteamNetworking.GetP2PSessionState(userId, ref p2PsessionStateT);
return p2PsessionStateT;
}
protected CSteamID RemoteAddressToSteamId(RemoteAddress address) => ((SteamAddress) address).SteamId;
public override bool Send(RemoteAddress address, byte[] data, int length)
{
this._writer.QueueSend(this.RemoteAddressToSteamId(address), data, length);
return true;
}
public override int Receive(RemoteAddress address, byte[] data, int offset, int length) => address == null ? 0 : this._reader.Receive(this.RemoteAddressToSteamId(address), data, offset, length);
public override bool IsDataAvailable(RemoteAddress address) => this._reader.IsDataAvailable(this.RemoteAddressToSteamId(address));
public enum ConnectionState
{
Inactive,
Authenticating,
Connected,
}
protected delegate void AsyncHandshake(CSteamID client);
}
}

View file

@ -0,0 +1,50 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.OverlaySocialModule
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
namespace Terraria.Social.Steam
{
public class OverlaySocialModule : Terraria.Social.Base.OverlaySocialModule
{
private Callback<GamepadTextInputDismissed_t> _gamepadTextInputDismissed;
private bool _gamepadTextInputActive;
public override void Initialize() => this._gamepadTextInputDismissed = Callback<GamepadTextInputDismissed_t>.Create(new Callback<GamepadTextInputDismissed_t>.DispatchDelegate((object) this, __methodptr(OnGamepadTextInputDismissed)));
public override void Shutdown()
{
}
public override bool IsGamepadTextInputActive() => this._gamepadTextInputActive;
public override bool ShowGamepadTextInput(
string description,
uint maxLength,
bool multiLine = false,
string existingText = "",
bool password = false)
{
if (this._gamepadTextInputActive)
return false;
int num = SteamUtils.ShowGamepadTextInput(password ? (EGamepadTextInputMode) 1 : (EGamepadTextInputMode) 0, multiLine ? (EGamepadTextInputLineMode) 1 : (EGamepadTextInputLineMode) 0, description, maxLength, existingText) ? 1 : 0;
if (num == 0)
return num != 0;
this._gamepadTextInputActive = true;
return num != 0;
}
public override string GetGamepadText()
{
uint gamepadTextLength = SteamUtils.GetEnteredGamepadTextLength();
string str;
SteamUtils.GetEnteredGamepadTextInput(ref str, gamepadTextLength);
return str;
}
private void OnGamepadTextInputDismissed(GamepadTextInputDismissed_t result) => this._gamepadTextInputActive = false;
}
}

View file

@ -0,0 +1,121 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.SteamP2PReader
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
using System;
using System.Collections.Generic;
namespace Terraria.Social.Steam
{
public class SteamP2PReader
{
public object SteamLock = new object();
private const int BUFFER_SIZE = 4096;
private Dictionary<CSteamID, Queue<SteamP2PReader.ReadResult>> _pendingReadBuffers = new Dictionary<CSteamID, Queue<SteamP2PReader.ReadResult>>();
private Queue<CSteamID> _deletionQueue = new Queue<CSteamID>();
private Queue<byte[]> _bufferPool = new Queue<byte[]>();
private int _channel;
private SteamP2PReader.OnReadEvent _readEvent;
public SteamP2PReader(int channel) => this._channel = channel;
public void ClearUser(CSteamID id)
{
lock (this._pendingReadBuffers)
this._deletionQueue.Enqueue(id);
}
public bool IsDataAvailable(CSteamID id)
{
lock (this._pendingReadBuffers)
{
if (!this._pendingReadBuffers.ContainsKey(id))
return false;
Queue<SteamP2PReader.ReadResult> pendingReadBuffer = this._pendingReadBuffers[id];
return pendingReadBuffer.Count != 0 && pendingReadBuffer.Peek().Size != 0U;
}
}
public void SetReadEvent(SteamP2PReader.OnReadEvent method) => this._readEvent = method;
private bool IsPacketAvailable(out uint size)
{
lock (this.SteamLock)
return SteamNetworking.IsP2PPacketAvailable(ref size, this._channel);
}
public void ReadTick()
{
lock (this._pendingReadBuffers)
{
while (this._deletionQueue.Count > 0)
this._pendingReadBuffers.Remove(this._deletionQueue.Dequeue());
uint size1;
while (this.IsPacketAvailable(out size1))
{
byte[] data = this._bufferPool.Count != 0 ? this._bufferPool.Dequeue() : new byte[(int) Math.Max(size1, 4096U)];
uint size2;
CSteamID csteamId;
bool flag;
lock (this.SteamLock)
flag = SteamNetworking.ReadP2PPacket(data, (uint) data.Length, ref size2, ref csteamId, this._channel);
if (flag)
{
if (this._readEvent == null || this._readEvent(data, (int) size2, csteamId))
{
if (!this._pendingReadBuffers.ContainsKey(csteamId))
this._pendingReadBuffers[csteamId] = new Queue<SteamP2PReader.ReadResult>();
this._pendingReadBuffers[csteamId].Enqueue(new SteamP2PReader.ReadResult(data, size2));
}
else
this._bufferPool.Enqueue(data);
}
}
}
}
public int Receive(CSteamID user, byte[] buffer, int bufferOffset, int bufferSize)
{
uint num1 = 0;
lock (this._pendingReadBuffers)
{
if (!this._pendingReadBuffers.ContainsKey(user))
return 0;
Queue<SteamP2PReader.ReadResult> pendingReadBuffer = this._pendingReadBuffers[user];
while (pendingReadBuffer.Count > 0)
{
SteamP2PReader.ReadResult readResult = pendingReadBuffer.Peek();
uint num2 = Math.Min((uint) bufferSize - num1, readResult.Size - readResult.Offset);
if (num2 == 0U)
return (int) num1;
Array.Copy((Array) readResult.Data, (long) readResult.Offset, (Array) buffer, (long) bufferOffset + (long) num1, (long) num2);
if ((int) num2 == (int) readResult.Size - (int) readResult.Offset)
this._bufferPool.Enqueue(pendingReadBuffer.Dequeue().Data);
else
readResult.Offset += num2;
num1 += num2;
}
}
return (int) num1;
}
public class ReadResult
{
public byte[] Data;
public uint Size;
public uint Offset;
public ReadResult(byte[] data, uint size)
{
this.Data = data;
this.Size = size;
this.Offset = 0U;
}
}
public delegate bool OnReadEvent(byte[] data, int size, CSteamID user);
}
}

View file

@ -0,0 +1,106 @@
// Decompiled with JetBrains decompiler
// Type: Terraria.Social.Steam.SteamP2PWriter
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Users\mikeyisbaeyt\Downloads\depotdownloader-2.4.5\depots\105601\6707058\Terraria.exe
using Steamworks;
using System;
using System.Collections.Generic;
namespace Terraria.Social.Steam
{
public class SteamP2PWriter
{
private const int BUFFER_SIZE = 1024;
private Dictionary<CSteamID, Queue<SteamP2PWriter.WriteInformation>> _pendingSendData = new Dictionary<CSteamID, Queue<SteamP2PWriter.WriteInformation>>();
private Dictionary<CSteamID, Queue<SteamP2PWriter.WriteInformation>> _pendingSendDataSwap = new Dictionary<CSteamID, Queue<SteamP2PWriter.WriteInformation>>();
private Queue<byte[]> _bufferPool = new Queue<byte[]>();
private int _channel;
private object _lock = new object();
public SteamP2PWriter(int channel) => this._channel = channel;
public void QueueSend(CSteamID user, byte[] data, int length)
{
lock (this._lock)
{
Queue<SteamP2PWriter.WriteInformation> writeInformationQueue;
if (this._pendingSendData.ContainsKey(user))
writeInformationQueue = this._pendingSendData[user];
else
this._pendingSendData[user] = writeInformationQueue = new Queue<SteamP2PWriter.WriteInformation>();
int val1 = length;
int sourceIndex = 0;
while (val1 > 0)
{
SteamP2PWriter.WriteInformation writeInformation;
if (writeInformationQueue.Count == 0 || 1024 - writeInformationQueue.Peek().Size == 0)
{
writeInformation = this._bufferPool.Count <= 0 ? new SteamP2PWriter.WriteInformation() : new SteamP2PWriter.WriteInformation(this._bufferPool.Dequeue());
writeInformationQueue.Enqueue(writeInformation);
}
else
writeInformation = writeInformationQueue.Peek();
int length1 = Math.Min(val1, 1024 - writeInformation.Size);
Array.Copy((Array) data, sourceIndex, (Array) writeInformation.Data, writeInformation.Size, length1);
writeInformation.Size += length1;
val1 -= length1;
sourceIndex += length1;
}
}
}
public void ClearUser(CSteamID user)
{
lock (this._lock)
{
if (this._pendingSendData.ContainsKey(user))
{
Queue<SteamP2PWriter.WriteInformation> writeInformationQueue = this._pendingSendData[user];
while (writeInformationQueue.Count > 0)
this._bufferPool.Enqueue(writeInformationQueue.Dequeue().Data);
}
if (!this._pendingSendDataSwap.ContainsKey(user))
return;
Queue<SteamP2PWriter.WriteInformation> writeInformationQueue1 = this._pendingSendDataSwap[user];
while (writeInformationQueue1.Count > 0)
this._bufferPool.Enqueue(writeInformationQueue1.Dequeue().Data);
}
}
public void SendAll()
{
lock (this._lock)
Utils.Swap<Dictionary<CSteamID, Queue<SteamP2PWriter.WriteInformation>>>(ref this._pendingSendData, ref this._pendingSendDataSwap);
foreach (KeyValuePair<CSteamID, Queue<SteamP2PWriter.WriteInformation>> keyValuePair in this._pendingSendDataSwap)
{
Queue<SteamP2PWriter.WriteInformation> writeInformationQueue = keyValuePair.Value;
while (writeInformationQueue.Count > 0)
{
SteamP2PWriter.WriteInformation writeInformation = writeInformationQueue.Dequeue();
SteamNetworking.SendP2PPacket(keyValuePair.Key, writeInformation.Data, (uint) writeInformation.Size, (EP2PSend) 2, this._channel);
this._bufferPool.Enqueue(writeInformation.Data);
}
}
}
public class WriteInformation
{
public byte[] Data;
public int Size;
public WriteInformation()
{
this.Data = new byte[1024];
this.Size = 0;
}
public WriteInformation(byte[] data)
{
this.Data = data;
this.Size = 0;
}
}
}
}