Skip to content

Commit

Permalink
Merge pull request #14 from risk-of-thunder/master
Browse files Browse the repository at this point in the history
Update
  • Loading branch information
Reinms authored Aug 23, 2020
2 parents f6ba7d6 + 8c8475b commit a8407d8
Show file tree
Hide file tree
Showing 7 changed files with 173 additions and 50 deletions.
3 changes: 1 addition & 2 deletions R2API/EliteAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ private static void GetOriginalEliteCountHook(ILContext il) {
private static void AddEliteAction(List<EliteDef> eliteDefinitions) {
foreach (var customElite in EliteDefinitions) {
eliteDefinitions.Add(customElite.EliteDef);

var currentEliteTiers = GetCombatDirectorEliteTiers();
if (customElite.EliteTier == 1) {
var index = currentEliteTiers[1].eliteTypes.Length;
Expand All @@ -69,7 +68,7 @@ private static void AddEliteAction(List<EliteDef> eliteDefinitions) {
var eliteTierIndex = customElite.EliteTier + 1;
var eliteTypeIndex = currentEliteTiers[eliteTierIndex].eliteTypes.Length;
Array.Resize(ref currentEliteTiers[eliteTierIndex].eliteTypes, eliteTypeIndex + 1);
currentEliteTiers[1].eliteTypes[eliteTypeIndex] = customElite.EliteDef.eliteIndex;
currentEliteTiers[eliteTierIndex].eliteTypes[eliteTypeIndex] = customElite.EliteDef.eliteIndex;
}
OverrideCombatDirectorEliteTiers(currentEliteTiers);

Expand Down
21 changes: 15 additions & 6 deletions R2API/LanguageAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,23 @@ private static void LoadCustomTokensFromFile(string file) {
return;
}

var languageTokens = jsonNode.Keys;
foreach (var language in languageTokens) {
JSONNode generic = jsonNode[language];
if (generic == null) {
var genericsAdded = false;
var languages = jsonNode.Keys;
foreach (var language in languages) {
JSONNode languageTokens = jsonNode[language];
if (languageTokens == null) {
return;
}
foreach (string text in generic.Keys) {
Add(text, generic[text].Value);

if (!genericsAdded) {
foreach (string text in languageTokens.Keys) {
Add(text, languageTokens[text].Value);
}
genericsAdded = true;
}

foreach (string text in languageTokens.Keys) {
Add(text, languageTokens[text].Value, language);
}
}
}
Expand Down
37 changes: 28 additions & 9 deletions R2API/Networking/NetworkingAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,19 @@ public static bool Loaded {
private static readonly Dictionary<int, RequestPerformerBase> NetRequests = new Dictionary<int, RequestPerformerBase>();

public static bool RegisterMessageType<TMessage>() where TMessage : INetMessage, new() {
if(!Loaded) {
if (!Loaded) {
throw new InvalidOperationException($"{nameof(NetworkingAPI)} is not loaded. Please use [{nameof(R2APISubmoduleDependency)}(nameof({nameof(NetworkingAPI)})]");
}

return RegisterMessageTypeInternal<TMessage>();
}

internal static bool RegisterMessageTypeInternal<TMessage>() where TMessage : INetMessage, new () {
var inst = new TMessage();
var type = inst.GetType();

var type = inst.GetType();
int hash = GetNetworkHash(type);

if (NetMessages.ContainsKey(hash)) {
R2API.Logger.LogError("Tried to register a message type with a duplicate hash");
return false;
Expand All @@ -47,10 +53,16 @@ public static bool Loaded {
}

public static bool RegisterCommandType<TCommand>() where TCommand : INetCommand, new() {
if(!Loaded) {
if (!Loaded) {
throw new InvalidOperationException($"{nameof(NetworkingAPI)} is not loaded. Please use [{nameof(R2APISubmoduleDependency)}(nameof({nameof(NetworkingAPI)})]");
}

return RegisterCommandTypeInternal<TCommand>();
}

public static bool RegisterCommandTypeInternal<TCommand>() where TCommand : INetCommand, new() {
var inst = new TCommand();

var type = inst.GetType();
int hash = GetNetworkHash(type);

Expand All @@ -67,9 +79,16 @@ public static bool Loaded {
public static bool RegisterRequestTypes<TRequest, TReply>()
where TRequest : INetRequest<TRequest, TReply>, new()
where TReply : INetRequestReply<TRequest, TReply>, new() {
if(!Loaded) {
if (!Loaded) {
throw new InvalidOperationException($"{nameof(NetworkingAPI)} is not loaded. Please use [{nameof(R2APISubmoduleDependency)}(nameof({nameof(NetworkingAPI)})]");
}

return RegisterRequestTypesInternal<TRequest, TReply>();
}

internal static bool RegisterRequestTypesInternal<TRequest, TReply>()
where TRequest : INetRequest<TRequest, TReply>, new()
where TReply : INetRequestReply<TRequest, TReply>, new() {
var request = new TRequest();
var reply = new TReply();

Expand All @@ -86,12 +105,12 @@ public static bool RegisterRequestTypes<TRequest, TReply>()

[R2APISubmoduleInit(Stage = InitStage.SetHooks)]
internal static void SetHooks() {
RegisterMessageType<DamageMessage>();
RegisterMessageType<BuffMessage>();
RegisterMessageType<DotMessage>();
RegisterMessageTypeInternal<DamageMessage>();
RegisterMessageTypeInternal<BuffMessage>();
RegisterMessageTypeInternal<DotMessage>();

RegisterMessageType<ExampleMessage>();
RegisterRequestTypes<ExamplePing, ExamplePingReply>();
RegisterMessageTypeInternal<ExampleMessage>();
RegisterRequestTypesInternal<ExamplePing, ExamplePingReply>();

GameNetworkManager.onStartServerGlobal += RegisterServerHandlers;
GameNetworkManager.onStartClientGlobal += RegisterClientHandlers;
Expand Down
29 changes: 28 additions & 1 deletion R2API/R2API.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,36 @@ static GameNetworkManager.SimpleLocalizedKickReason SwapToStandardMessage(GameNe
{
reason.GetDisplayTokenAndFormatParams(out var token, out _);
return new GameNetworkManager.SimpleLocalizedKickReason(token,
"This information is not yet available, see below the list of all mods the server needs you to have : ",
"",
string.Join("\n", NetworkModCompatibilityHelper.networkModList));
}
c.Index++;
c.EmitDelegate<Func<GameNetworkManager.ModMismatchKickReason, GameNetworkManager.SimpleLocalizedKickReason>>(SwapToStandardMessage);
}
};

// Temporary fix for displaying correctly the mods that the user is missing when trying to connect
On.RoR2.Networking.GameNetworkManager.SimpleLocalizedKickReason.GetDisplayTokenAndFormatParams +=
(On.RoR2.Networking.GameNetworkManager.SimpleLocalizedKickReason.orig_GetDisplayTokenAndFormatParams orig,
GameNetworkManager.SimpleLocalizedKickReason self, out string token, out object[] formatArgs) => {
var baseToken = self.baseToken;
var args = self.formatArgs;
token = baseToken;
if (baseToken != "KICK_REASON_MOD_MISMATCH")
{
token = baseToken;
formatArgs = args;
return;
}
var mods = args[1].Split('\n');
var myMods = NetworkModCompatibilityHelper.networkModList;

var extraMods = string.Join("\n", myMods.Except(mods));
var missingMods = string.Join("\n", mods.Except(myMods));

formatArgs = new object[] { extraMods, missingMods };
};

// Temporary fix until the KVP Foreach properly check for null Value before calling Equals on them
IL.RoR2.SteamworksLobbyDataGenerator.RebuildLobbyData += il => {
var c = new ILCursor(il);
Expand Down Expand Up @@ -227,6 +249,11 @@ private static void CheckR2APIMonomodPatch() {
"Please make sure that a file called:",
"Assembly-CSharp.R2API.mm.dll",
"is present in the Risk of Rain 2\\BepInEx\\monomod\\ folder",
"or",
"You are missing the monomod loader that is normally located in,",
"the Risk of Rain 2\\BepInEx\\patchers\\BepInEx.MonoMod.Loader folder.",
"If you don't have this folder, please download BepInEx again from the",
"thunderstore and make sure to follow the installation instructions."
};
Logger.LogBlockError(message);
}
Expand Down
4 changes: 2 additions & 2 deletions R2API/Utils/APISubmodule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public class APISubmoduleHandler {
private readonly int _build;
private readonly ManualLogSource _logger;
private HashSet<string> _moduleSet;
private HashSet<string> LoadedModules;
private static HashSet<string> LoadedModules;

internal APISubmoduleHandler(int build, ManualLogSource logger = null) {
_build = build;
Expand All @@ -64,7 +64,7 @@ internal APISubmoduleHandler(int build, ManualLogSource logger = null) {
/// Return true if the specified submodule is loaded.
/// </summary>
/// <param name="submodule">nameof the submodule</param>
public bool IsLoaded(string submodule) => LoadedModules.Contains(submodule);
public static bool IsLoaded(string submodule) => LoadedModules.Contains(submodule);

internal HashSet<string> LoadRequested(PluginScanner pluginScanner) {
_moduleSet = new HashSet<string>();
Expand Down
40 changes: 29 additions & 11 deletions R2API/Utils/NetworkCompatibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@
using System.Linq;
using BepInEx;
using Mono.Cecil;
using R2API.Networking;
using RoR2;

namespace R2API.Utils {
/// <summary>
/// Enum used for telling whether or not the mod should be needed by everyone in multiplayer games.
/// Also can specify if the mod does not work in multiplayer.
/// </summary>
public enum CompatibilityLevel {
NoNeedForSync,
EveryoneMustHaveMod
EveryoneMustHaveMod,
//BreaksMultiplayer //todo
}

/// <summary>
Expand All @@ -29,7 +32,7 @@ public enum VersionStrictness {
/// you want to specify if the mod should be installed by everyone in multiplayer games or not.
/// If the mod is required to be installed by everyone, you'll need to also specify if the same mod version should be used by everyone or not.
/// By default, it's supposed that everyone needs the mod and the same version.
/// e.g: [NetworkCompatibility(CompatibilityLevel.NoNeedForSync, VersionStrictness.DifferentModVersionsAreOk)]
/// e.g: [NetworkCompatibility(CompatibilityLevel.NoNeedForSync)]
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)]
public class NetworkCompatibility : Attribute {
Expand Down Expand Up @@ -83,8 +86,13 @@ internal void BuildModList(PluginScanner pluginScanner) {
// By default, any plugins that don't have the NetworkCompatibility attribute and
// don't have the ManualNetworkRegistration attribute are added to the networked mod list
if (!haveNetworkCompatAttribute) {
if (bepinPluginAttribute != null && !haveManualRegistrationAttribute) {
modList.Add(modGuid + ModGuidAndModVersionSeparator + modVersion);
if (bepinPluginAttribute != null){
if (!haveManualRegistrationAttribute) {
modList.Add(modGuid + ModGuidAndModVersionSeparator + modVersion);
}
else {
R2API.Logger.LogDebug($"Found {nameof(ManualNetworkRegistrationAttribute)} type. Ignoring.");
}
}
else {
R2API.Logger.LogDebug($"Found {nameof(BaseUnityPlugin)} type but no {nameof(BepInPlugin)} attribute");
Expand Down Expand Up @@ -133,6 +141,9 @@ internal void BuildModList(PluginScanner pluginScanner) {

void CallWhenAssembliesAreScanned() {
if (modList.Count != 0) {
if (IsR2APIAffectingNetwork()) {
modList.Add(R2API.PluginGUID + ModGuidAndModVersionSeparator + R2API.PluginVersion);
}
var sortedModList = modList.ToList();
sortedModList.Sort();
R2API.Logger.LogInfo("[NetworkCompatibility] Adding to the networkModList : ");
Expand All @@ -144,15 +155,22 @@ void CallWhenAssembliesAreScanned() {
}
}

internal static bool IsR2APIAffectingNetwork() {
return APISubmoduleHandler.IsLoaded(nameof(NetworkingAPI));
}

private static void TryGetNetworkCompatibilityArguments(IList<CustomAttributeArgument> attributeArguments,
out CompatibilityLevel compatibilityLevel, out VersionStrictness versionStrictness) {
if (attributeArguments[0].Value is int && attributeArguments[1].Value is int) {
compatibilityLevel = (CompatibilityLevel)attributeArguments[0].Value;
versionStrictness = (VersionStrictness)attributeArguments[1].Value;
}
else {
compatibilityLevel = CompatibilityLevel.EveryoneMustHaveMod;
versionStrictness = VersionStrictness.EveryoneNeedSameModVersion;
compatibilityLevel = CompatibilityLevel.EveryoneMustHaveMod;
versionStrictness = VersionStrictness.EveryoneNeedSameModVersion;

if (attributeArguments != null && attributeArguments.Count > 0) {
if (attributeArguments[0].Value is int) {
compatibilityLevel = (CompatibilityLevel)attributeArguments[0].Value;
}
if (attributeArguments[1].Value is int) {
versionStrictness = (VersionStrictness)attributeArguments[1].Value;
}
}
}
}
Expand Down
Loading

0 comments on commit a8407d8

Please sign in to comment.