From e4be608b9501b485628b6ddaeb5fa79ccbd3c786 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Sun, 3 Dec 2023 05:20:12 +0800 Subject: [PATCH 01/29] Update --- .../Attributes/Il2CppRegisterAttribute.cs | 2 +- .../Attributes/LoadAttribute.cs | 0 .../Attributes/OptionLoadAttribute.cs | 2 +- .../Attributes/PluginCompatibility.cs | 14 ++ NextShip.Api/Attributes/ShipPluginInfo.cs | 16 ++ .../Attributes/TranslateTag.cs | 2 +- .../Manager => NextShip.Api/Bases}/Manager.cs | 4 +- NextShip.Api/Bases/ShipPlugin.cs | 19 ++ .../Config/AddonsData.cs | 3 +- NextShip.Api/Config/CosmeticsConfig.cs | 21 +++ NextShip.Api/Config/NextPaths.cs | 5 + NextShip.Api/Enums/CompatibilityLevel.cs | 10 + NextShip.Api/Enums/CosmeticTypes.cs | 24 +++ NextShip.Api/Enums/FileType.cs | 9 + NextShip.Api/GlobalUsing.cs | 4 +- NextShip.Api/Interfaces/IEventManager.cs | 10 + NextShip.Api/Interfaces/ILang.cs | 6 + NextShip.Api/Interfaces/ILangManager.cs | 5 + NextShip.Api/Interfaces/INextEvent.cs | 10 + NextShip.Api/Interfaces/INextService.cs | 10 + NextShip.Api/Interfaces/IRole.cs | 20 ++ NextShip.Api/Interfaces/IRoleCreator.cs | 6 + NextShip.Api/Logs/Log.cs | 32 +++- NextShip.Api/NextShip.Api.csproj | 11 +- NextShip.Api/Plugins/INextPlugin.cs | 12 ++ NextShip.Api/Roles/Role.cs | 27 --- NextShip.Api/Roles/RoleBase.cs | 3 +- NextShip.Api/Roles/RoleManager.Assaign.cs | 24 +-- NextShip.Api/Roles/RoleManager.cs | 11 -- NextShip.Api/Roles/SimpleRoleInfo.cs | 9 +- .../SourceGenerators/LangSourceGenerator.cs | 12 ++ NextShip.Api/Utils/StreamUtils.cs | 1 + NextShip/Api/Role/RoleCreater.cs | 5 - NextShip/Chat/Command.cs | 96 ---------- NextShip/Chat/Commands.cs | 45 ----- NextShip/Chat/Patches/ChatPatch.cs | 130 ------------- NextShip/Chat/VoiceChatManager.cs | 28 --- NextShip/Chat/VoiceClient.cs | 27 --- NextShip/Config/CosmeticsConfig.cs | 12 -- NextShip/Cosmetics/CosmeticsManager.cs | 8 - NextShip/Cosmetics/CustomCosmeticsManager.cs | 28 +-- NextShip/Cosmetics/Loaders/CosmeticsLoader.cs | 3 +- .../Cosmetics/Loaders/TORCosmeticsLoader.cs | 5 +- NextShip/DIY/Addons/AddonsManager.cs | 1 + NextShip/DIY/Plugins/PluginBase.cs | 58 ------ NextShip/DIY/Plugins/PluginManager.cs | 15 +- NextShip/Game/GameEvents/GameEvent.cs | 23 --- NextShip/Game/GameEvents/GameState.cs | 38 ---- NextShip/Game/GameEvents/IGameEvent.cs | 32 ---- NextShip/Game/GameModes/GameModeManager.cs | 34 ---- NextShip/Game/Info/HostInfo.cs | 5 - NextShip/Game/Info/ShipInfo.cs | 14 -- NextShip/Game/Tasks/Task.cs | 48 ----- NextShip/GlobalUsing.cs | 2 +- NextShip/Languages/LanguagePack.cs | 13 +- .../Listeners/Attributes/EventListener.cs | 36 ---- NextShip/Listeners/ListenerManager.cs | 63 ------- NextShip/Manager/BanManager.cs | 5 - NextShip/Manager/EventManager.cs | 45 +++++ NextShip/Manager/FilesManager.cs | 19 +- NextShip/Manager/HistoryInfoManager.cs | 5 - NextShip/Manager/HistoryManager.cs | 5 - NextShip/Manager/PlayerManager.cs | 5 - NextShip/Manager/PositionManager.cs | 25 --- NextShip/Manager/RegisterManager.cs | 8 +- NextShip/Manager/VanillaManager.cs | 11 -- NextShip/Manager/VersionManager.cs | 5 - NextShip/NextService.cs | 60 ++++++ NextShip/NextShip.csproj | 8 +- NextShip/Options/DefaultOption.cs | 3 +- NextShip/Options/OptionManager.cs | 1 + NextShip/Patches/CheckGameEndPatch.cs | 28 --- NextShip/Patches/CredentialsPatch.cs | 108 ----------- NextShip/Patches/EndGamePatch.cs | 115 ------------ NextShip/Patches/PlayerControlPatch.cs | 167 ----------------- NextShip/Patches/ServerPath.cs | 21 +-- NextShip/RPC/RPC.cs | 173 ------------------ NextShip/RPC/RPCPatch.cs | 2 +- NextShip/RPC/RPCUtils.cs | 13 +- NextShip/Roles/Court/judge.cs | 5 - NextShip/Roles/Crewmate/Mayor.cs | 5 - NextShip/Roles/Crewmate/Postman.cs | 20 -- NextShip/Roles/Cult/CultPreacher.cs | 5 - NextShip/Roles/Cult/Cultist.cs | 5 - NextShip/Roles/Impostor/Camouflager.cs | 29 --- NextShip/Roles/Impostor/Illusory.cs | 28 --- NextShip/Roles/Modifier/Flash.cs | 19 -- NextShip/Roles/Modifier/Lover.cs | 21 --- NextShip/Roles/Neutral/Jester.cs | 20 -- NextShip/Roles/Neutral/SchrodingersCat.cs | 20 -- NextShip/Roles/PoliceStation/Sheriff.cs | 24 --- NextShip/UI/Components/DownMenu.cs | 3 +- NextShip/UI/Components/NextMenuOption.cs | 3 +- NextShip/UI/Components/ShipOptionBehaviour.cs | 1 + NextShip/UI/UIManager/NextUIManager.cs | 1 + NextShip/UI/VoiceChatHud.cs | 80 -------- NextShip/main.cs | 113 +++--------- 97 files changed, 446 insertions(+), 1901 deletions(-) rename NextShip.Api/{Utilities => }/Attributes/Il2CppRegisterAttribute.cs (97%) rename NextShip.Api/{Utilities => }/Attributes/LoadAttribute.cs (100%) rename NextShip.Api/{Utilities => }/Attributes/OptionLoadAttribute.cs (95%) create mode 100644 NextShip.Api/Attributes/PluginCompatibility.cs create mode 100644 NextShip.Api/Attributes/ShipPluginInfo.cs rename NextShip.Api/{Utilities => }/Attributes/TranslateTag.cs (94%) rename {NextShip/Manager => NextShip.Api/Bases}/Manager.cs (68%) create mode 100644 NextShip.Api/Bases/ShipPlugin.cs rename {NextShip => NextShip.Api}/Config/AddonsData.cs (84%) create mode 100644 NextShip.Api/Config/CosmeticsConfig.cs create mode 100644 NextShip.Api/Config/NextPaths.cs create mode 100644 NextShip.Api/Enums/CompatibilityLevel.cs create mode 100644 NextShip.Api/Enums/CosmeticTypes.cs create mode 100644 NextShip.Api/Enums/FileType.cs create mode 100644 NextShip.Api/Interfaces/IEventManager.cs create mode 100644 NextShip.Api/Interfaces/ILang.cs create mode 100644 NextShip.Api/Interfaces/ILangManager.cs create mode 100644 NextShip.Api/Interfaces/INextEvent.cs create mode 100644 NextShip.Api/Interfaces/INextService.cs create mode 100644 NextShip.Api/Interfaces/IRole.cs create mode 100644 NextShip.Api/Interfaces/IRoleCreator.cs create mode 100644 NextShip.Api/Plugins/INextPlugin.cs delete mode 100644 NextShip.Api/Roles/Role.cs create mode 100644 NextShip.Api/SourceGenerators/LangSourceGenerator.cs delete mode 100644 NextShip/Api/Role/RoleCreater.cs delete mode 100644 NextShip/Chat/Command.cs delete mode 100644 NextShip/Chat/Commands.cs delete mode 100644 NextShip/Chat/Patches/ChatPatch.cs delete mode 100644 NextShip/Chat/VoiceChatManager.cs delete mode 100644 NextShip/Chat/VoiceClient.cs delete mode 100644 NextShip/Config/CosmeticsConfig.cs delete mode 100644 NextShip/DIY/Plugins/PluginBase.cs delete mode 100644 NextShip/Game/GameEvents/GameEvent.cs delete mode 100644 NextShip/Game/GameEvents/GameState.cs delete mode 100644 NextShip/Game/GameEvents/IGameEvent.cs delete mode 100644 NextShip/Game/GameModes/GameModeManager.cs delete mode 100644 NextShip/Game/Info/HostInfo.cs delete mode 100644 NextShip/Game/Info/ShipInfo.cs delete mode 100644 NextShip/Game/Tasks/Task.cs delete mode 100644 NextShip/Listeners/Attributes/EventListener.cs delete mode 100644 NextShip/Listeners/ListenerManager.cs delete mode 100644 NextShip/Manager/BanManager.cs create mode 100644 NextShip/Manager/EventManager.cs delete mode 100644 NextShip/Manager/HistoryInfoManager.cs delete mode 100644 NextShip/Manager/HistoryManager.cs delete mode 100644 NextShip/Manager/PlayerManager.cs delete mode 100644 NextShip/Manager/PositionManager.cs delete mode 100644 NextShip/Manager/VanillaManager.cs delete mode 100644 NextShip/Manager/VersionManager.cs create mode 100644 NextShip/NextService.cs delete mode 100644 NextShip/Patches/CheckGameEndPatch.cs delete mode 100644 NextShip/Patches/CredentialsPatch.cs delete mode 100644 NextShip/Patches/EndGamePatch.cs delete mode 100644 NextShip/Patches/PlayerControlPatch.cs delete mode 100644 NextShip/RPC/RPC.cs delete mode 100644 NextShip/Roles/Court/judge.cs delete mode 100644 NextShip/Roles/Crewmate/Mayor.cs delete mode 100644 NextShip/Roles/Crewmate/Postman.cs delete mode 100644 NextShip/Roles/Cult/CultPreacher.cs delete mode 100644 NextShip/Roles/Cult/Cultist.cs delete mode 100644 NextShip/Roles/Impostor/Camouflager.cs delete mode 100644 NextShip/Roles/Impostor/Illusory.cs delete mode 100644 NextShip/Roles/Modifier/Flash.cs delete mode 100644 NextShip/Roles/Modifier/Lover.cs delete mode 100644 NextShip/Roles/Neutral/Jester.cs delete mode 100644 NextShip/Roles/Neutral/SchrodingersCat.cs delete mode 100644 NextShip/Roles/PoliceStation/Sheriff.cs delete mode 100644 NextShip/UI/VoiceChatHud.cs diff --git a/NextShip.Api/Utilities/Attributes/Il2CppRegisterAttribute.cs b/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs similarity index 97% rename from NextShip.Api/Utilities/Attributes/Il2CppRegisterAttribute.cs rename to NextShip.Api/Attributes/Il2CppRegisterAttribute.cs index 767cb70..ae6a2b1 100644 --- a/NextShip.Api/Utilities/Attributes/Il2CppRegisterAttribute.cs +++ b/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs @@ -2,7 +2,7 @@ using HarmonyLib; using Il2CppInterop.Runtime.Injection; -namespace NextShip.Api.Utilities.Attributes; +namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Class)] public sealed class Il2CppRegisterAttribute : Attribute diff --git a/NextShip.Api/Utilities/Attributes/LoadAttribute.cs b/NextShip.Api/Attributes/LoadAttribute.cs similarity index 100% rename from NextShip.Api/Utilities/Attributes/LoadAttribute.cs rename to NextShip.Api/Attributes/LoadAttribute.cs diff --git a/NextShip.Api/Utilities/Attributes/OptionLoadAttribute.cs b/NextShip.Api/Attributes/OptionLoadAttribute.cs similarity index 95% rename from NextShip.Api/Utilities/Attributes/OptionLoadAttribute.cs rename to NextShip.Api/Attributes/OptionLoadAttribute.cs index 9b7eddf..236db95 100644 --- a/NextShip.Api/Utilities/Attributes/OptionLoadAttribute.cs +++ b/NextShip.Api/Attributes/OptionLoadAttribute.cs @@ -1,7 +1,7 @@ using System.Reflection; using HarmonyLib; -namespace NextShip.Api.Utilities.Attributes; +namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Method)] public sealed class OptionLoad : Attribute diff --git a/NextShip.Api/Attributes/PluginCompatibility.cs b/NextShip.Api/Attributes/PluginCompatibility.cs new file mode 100644 index 0000000..8d602a7 --- /dev/null +++ b/NextShip.Api/Attributes/PluginCompatibility.cs @@ -0,0 +1,14 @@ +namespace NextShip.Api.Attributes; + +[AttributeUsage(AttributeTargets.Class)] +public sealed class PluginCompatibility : Attribute +{ + public CompatibilityLevel Compatibility; + public string PluginName; + + public PluginCompatibility(string pluginName, CompatibilityLevel compatibility = CompatibilityLevel.Compatible) + { + PluginName = pluginName; + Compatibility = compatibility; + } +} \ No newline at end of file diff --git a/NextShip.Api/Attributes/ShipPluginInfo.cs b/NextShip.Api/Attributes/ShipPluginInfo.cs new file mode 100644 index 0000000..4a506fb --- /dev/null +++ b/NextShip.Api/Attributes/ShipPluginInfo.cs @@ -0,0 +1,16 @@ +namespace NextShip.Api.Attributes; + +[AttributeUsage(AttributeTargets.Class)] +public sealed class ShipPluginInfo : Attribute +{ + public ShipPluginInfo(string Id, ShipVersion Version, string Name) + { + this.Id = Id; + this.Version = Version; + this.Name = Name; + } + + public string Id { get; } + public ShipVersion Version { get; } + public string Name { get; } +} \ No newline at end of file diff --git a/NextShip.Api/Utilities/Attributes/TranslateTag.cs b/NextShip.Api/Attributes/TranslateTag.cs similarity index 94% rename from NextShip.Api/Utilities/Attributes/TranslateTag.cs rename to NextShip.Api/Attributes/TranslateTag.cs index 44aced5..3e4bf71 100644 --- a/NextShip.Api/Utilities/Attributes/TranslateTag.cs +++ b/NextShip.Api/Attributes/TranslateTag.cs @@ -1,4 +1,4 @@ -namespace NextShip.Api.Utilities.Attributes; +namespace NextShip.Api.Attributes; public class TranslateTag : Attribute { diff --git a/NextShip/Manager/Manager.cs b/NextShip.Api/Bases/Manager.cs similarity index 68% rename from NextShip/Manager/Manager.cs rename to NextShip.Api/Bases/Manager.cs index 3065ded..e32df58 100644 --- a/NextShip/Manager/Manager.cs +++ b/NextShip.Api/Bases/Manager.cs @@ -1,8 +1,8 @@ -namespace NextShip.Manager; +namespace NextShip.Api.Bases; public class Manager where T : new() { - protected static T _instance; + protected static T _instance = default!; public static T Instance => Get(); diff --git a/NextShip.Api/Bases/ShipPlugin.cs b/NextShip.Api/Bases/ShipPlugin.cs new file mode 100644 index 0000000..c686a4c --- /dev/null +++ b/NextShip.Api/Bases/ShipPlugin.cs @@ -0,0 +1,19 @@ +namespace NextShip.Api.Bases; + + +public abstract class ShipPlugin +{ + public List PluginCompatibilities = new(); + public ShipPluginInfo ShipPluginInfo = null!; + + public ShipPlugin() + { + } + + public ShipPlugin(ShipPluginInfo pluginInfo) + { + ShipPluginInfo = pluginInfo; + } + + public abstract void Load(); +} \ No newline at end of file diff --git a/NextShip/Config/AddonsData.cs b/NextShip.Api/Config/AddonsData.cs similarity index 84% rename from NextShip/Config/AddonsData.cs rename to NextShip.Api/Config/AddonsData.cs index f10be22..ae657ad 100644 --- a/NextShip/Config/AddonsData.cs +++ b/NextShip.Api/Config/AddonsData.cs @@ -1,5 +1,4 @@ -#nullable enable -namespace NextShip.Config; +namespace NextShip.Api.Config; public class AddonsInfo { diff --git a/NextShip.Api/Config/CosmeticsConfig.cs b/NextShip.Api/Config/CosmeticsConfig.cs new file mode 100644 index 0000000..4e44d78 --- /dev/null +++ b/NextShip.Api/Config/CosmeticsConfig.cs @@ -0,0 +1,21 @@ +using NextShip.Api.Enums; + +namespace NextShip.Api.Config; + +public class CosmeticsConfig +{ + public CosmeticsConfig(CosmeticRepoType cosmeticRepoType, CosmeticType cosmeticType, CosmeticLoadType cosmeticLoadType, string repoName, string repoURL) + { + CosmeticRepoType = cosmeticRepoType; + CosmeticType = cosmeticType; + CosmeticLoadType = cosmeticLoadType; + RepoName = repoName; + RepoURL = repoURL; + } + + public CosmeticRepoType CosmeticRepoType { get; set; } + public CosmeticType CosmeticType { get; set; } + public CosmeticLoadType CosmeticLoadType { get; set; } + public string RepoName { get; set; } + public string RepoURL { get; set; } +} \ No newline at end of file diff --git a/NextShip.Api/Config/NextPaths.cs b/NextShip.Api/Config/NextPaths.cs new file mode 100644 index 0000000..3d7582c --- /dev/null +++ b/NextShip.Api/Config/NextPaths.cs @@ -0,0 +1,5 @@ +namespace NextShip.Api.Config; + +public class NextPaths +{ +} \ No newline at end of file diff --git a/NextShip.Api/Enums/CompatibilityLevel.cs b/NextShip.Api/Enums/CompatibilityLevel.cs new file mode 100644 index 0000000..6335292 --- /dev/null +++ b/NextShip.Api/Enums/CompatibilityLevel.cs @@ -0,0 +1,10 @@ +namespace NextShip.Api.Enums; + +public enum CompatibilityLevel +{ + Unknown = 0, + Compatible = 1, + Incompatible = 2, + Dependency = 3, + Need = 4 +} \ No newline at end of file diff --git a/NextShip.Api/Enums/CosmeticTypes.cs b/NextShip.Api/Enums/CosmeticTypes.cs new file mode 100644 index 0000000..962922b --- /dev/null +++ b/NextShip.Api/Enums/CosmeticTypes.cs @@ -0,0 +1,24 @@ +namespace NextShip.Api.Enums; + +public enum CosmeticRepoType +{ + TOR, + EXR, + NOS, + TIS +} + +public enum CosmeticsTypes +{ + Hat, + NamePlate, + Visor, + Skin +} + +public enum CosmeticLoadType +{ + Repo, + Disk, + Resources +} \ No newline at end of file diff --git a/NextShip.Api/Enums/FileType.cs b/NextShip.Api/Enums/FileType.cs new file mode 100644 index 0000000..10be172 --- /dev/null +++ b/NextShip.Api/Enums/FileType.cs @@ -0,0 +1,9 @@ +namespace NextShip.Api.Enums; + +public enum FileType +{ + Csv, + Json, + Yaml, + Txt +} \ No newline at end of file diff --git a/NextShip.Api/GlobalUsing.cs b/NextShip.Api/GlobalUsing.cs index fa1701c..f91427b 100644 --- a/NextShip.Api/GlobalUsing.cs +++ b/NextShip.Api/GlobalUsing.cs @@ -2,5 +2,7 @@ global using NextShip.Api.Roles; global using NextShip.Api.Utils; global using NextShip.Api.Utilities; -global using NextShip.Api.Utilities.Attributes; +global using NextShip.Api.Enums; +global using NextShip.Api.Bases; +global using NextShip.Api.Attributes; global using static NextShip.Api.Logs.log; \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IEventManager.cs b/NextShip.Api/Interfaces/IEventManager.cs new file mode 100644 index 0000000..15846ba --- /dev/null +++ b/NextShip.Api/Interfaces/IEventManager.cs @@ -0,0 +1,10 @@ +namespace NextShip.Api.Interfaces; + +public interface IEventManager +{ + // 注册事件 + public void RegisterEvent(INextEvent @event); + + + public void UnRegisterEvent(INextEvent @event); +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILang.cs b/NextShip.Api/Interfaces/ILang.cs new file mode 100644 index 0000000..ce934ce --- /dev/null +++ b/NextShip.Api/Interfaces/ILang.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public class ILang +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILangManager.cs b/NextShip.Api/Interfaces/ILangManager.cs new file mode 100644 index 0000000..fe11d06 --- /dev/null +++ b/NextShip.Api/Interfaces/ILangManager.cs @@ -0,0 +1,5 @@ +namespace NextShip.Api.Interfaces; + +public class ILangManager +{ +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextEvent.cs b/NextShip.Api/Interfaces/INextEvent.cs new file mode 100644 index 0000000..6a416c3 --- /dev/null +++ b/NextShip.Api/Interfaces/INextEvent.cs @@ -0,0 +1,10 @@ +namespace NextShip.Api.Interfaces; + +public interface INextEvent +{ + public string EventName { get; set; } + + public void OnRegister(IEventManager @eventManager); + + public void OnUnRegister(IEventManager @eventManager); +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextService.cs b/NextShip.Api/Interfaces/INextService.cs new file mode 100644 index 0000000..0fd23f8 --- /dev/null +++ b/NextShip.Api/Interfaces/INextService.cs @@ -0,0 +1,10 @@ +namespace NextShip.Api.Interfaces; + +public interface INextService +{ + public void Build(); + + public void Rebuild(); + + public void Reset(); +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IRole.cs b/NextShip.Api/Interfaces/IRole.cs new file mode 100644 index 0000000..b6f836e --- /dev/null +++ b/NextShip.Api/Interfaces/IRole.cs @@ -0,0 +1,20 @@ +namespace NextShip.Api.Interfaces; + +public interface IRole +{ + public Type RoleBaseType { get; set; } + public Type RoleType { get; set; } + + public SimpleRoleInfo SimpleRoleInfo { get; set; } + + public List RoleBase { get; set; } + + public List Players { get; set; } + + + public bool EnableAssign { get; set; } + + public Func CreateRoleBase { get; set; } + + public bool CanCreate(IRole role, PlayerControl player); +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IRoleCreator.cs b/NextShip.Api/Interfaces/IRoleCreator.cs new file mode 100644 index 0000000..11851f6 --- /dev/null +++ b/NextShip.Api/Interfaces/IRoleCreator.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public interface IRoleCreator +{ + public T Create(IRole role) where T : RoleBase; +} \ No newline at end of file diff --git a/NextShip.Api/Logs/Log.cs b/NextShip.Api/Logs/Log.cs index f097c59..d1c2654 100644 --- a/NextShip.Api/Logs/Log.cs +++ b/NextShip.Api/Logs/Log.cs @@ -3,26 +3,44 @@ namespace NextShip.Api.Logs; -public abstract class log +public sealed class log { - public readonly ManualLogSource LogSource; + public ManualLogSource LogSource { get; private set; } + + public readonly TextWriter Writer = null!; + + public static bool CreateEd; static log() { - ConsoleTextFC(); + System.Console.OutputEncoding = Encoding.UTF8; } - public log(ManualLogSource logSource) + private log(ManualLogSource logSource) { LogSource = logSource; Instance = this; } - public static log? Instance { get; set; } + public static log Instance { get; set; } + + public static log Get(ManualLogSource logSource) + { + if (CreateEd) + { + Instance.Set(logSource); + return Instance; + } + + var _log = new log(logSource); + CreateEd = true; + return _log; + } - public static void ConsoleTextFC() + private void Set(ManualLogSource logSource) { - if (!System.Console.OutputEncoding.Equals(Encoding.UTF8)) System.Console.OutputEncoding = Encoding.UTF8; + if (logSource != LogSource) + LogSource = logSource; } private void SendToFile(string? tag, string? filename, string text, LogLevel level = LogLevel.Info) diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index c3df230..3915853 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -8,12 +8,21 @@ 1.0.0 APIReadme.md true + true - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + diff --git a/NextShip.Api/Plugins/INextPlugin.cs b/NextShip.Api/Plugins/INextPlugin.cs new file mode 100644 index 0000000..44a92a7 --- /dev/null +++ b/NextShip.Api/Plugins/INextPlugin.cs @@ -0,0 +1,12 @@ +namespace NextShip.Api.Plugins; + +public interface INextPlugin +{ + public void OnLoad() {} + + public virtual bool OnEnable() => true; + + public virtual bool OnDisable() => true; + + public void OnUnload() {} +} \ No newline at end of file diff --git a/NextShip.Api/Roles/Role.cs b/NextShip.Api/Roles/Role.cs deleted file mode 100644 index a46dd0d..0000000 --- a/NextShip.Api/Roles/Role.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace NextShip.Api.Roles; - -public abstract class Role -{ - protected Type RoleBaseType = null!; - protected Type RoleType = null!; - - public SimpleRoleInfo SimpleRoleInfo { get; protected set; } = null!; - - public List RoleBase { get; set; } = null!; - - public List PlayerControls { get; set; } = null!; - - - public bool EnableAssign { get; set; } - - public Func CreateRoleBase { get; set; } = null!; - - public virtual void OptionLoad() - { - } - - public virtual bool CanCreate() - { - return true; - } -} \ No newline at end of file diff --git a/NextShip.Api/Roles/RoleBase.cs b/NextShip.Api/Roles/RoleBase.cs index a479b1b..08ef05d 100644 --- a/NextShip.Api/Roles/RoleBase.cs +++ b/NextShip.Api/Roles/RoleBase.cs @@ -13,8 +13,7 @@ protected RoleBase(PlayerControl? player) Active = true; RoleManager.Get().AllRoleBases.Add(this); } - - public Role ParentRole { get; protected set; } = null!; + public PlayerControl? Player { get; private set; } public Func WinCheck { get; } diff --git a/NextShip.Api/Roles/RoleManager.Assaign.cs b/NextShip.Api/Roles/RoleManager.Assaign.cs index 75c20bb..03e7184 100644 --- a/NextShip.Api/Roles/RoleManager.Assaign.cs +++ b/NextShip.Api/Roles/RoleManager.Assaign.cs @@ -7,7 +7,6 @@ public partial class RoleManager public IEnumerator GetAssignRole(PlayerControl player) { Assign: - Assigner.AssignRole(); if (!Assigner.Get(player, out var role)) goto Assign; @@ -35,28 +34,7 @@ public bool Get(PlayerControl player, out RoleBase? role) return role != null; } - - public void AssignRole() - { - var Roles = RoleManager.Get().Roles.Where(n => n.EnableAssign).ToList(); - - foreach (var @base in from player in CachedPlayer.AllPlayers - where - player.CanAssaign() - && - Get(player, out _) - let role = Roles[GetValue()] - select - role.CreateRoleBase(player)) - AllAssigns.Add(@base); - - return; - - int GetValue() - { - return Random.Next(0, Roles.Count - 1); - } - } + public void Restore() { diff --git a/NextShip.Api/Roles/RoleManager.cs b/NextShip.Api/Roles/RoleManager.cs index bd1c786..d73cf43 100644 --- a/NextShip.Api/Roles/RoleManager.cs +++ b/NextShip.Api/Roles/RoleManager.cs @@ -5,7 +5,6 @@ namespace NextShip.Api.Roles; public partial class RoleManager { public static RoleManager Instance; - public readonly List Roles = new(); public List AllRoleBases = new(); public List AllSimpleRoleInfos = new(); @@ -21,16 +20,6 @@ public List GetActiveRole() return AllRoleBases.Where(n => n.Active).ToList(); } - public void RegisterRole(Role role) - { - Roles.Add(role); - } - - public void RegisterRole(IEnumerable roles) - { - roles.Do(RegisterRole); - } - public T GetRole(PlayerControl playerControl) where T : RoleBase { diff --git a/NextShip.Api/Roles/SimpleRoleInfo.cs b/NextShip.Api/Roles/SimpleRoleInfo.cs index 5897ec6..6a449dc 100644 --- a/NextShip.Api/Roles/SimpleRoleInfo.cs +++ b/NextShip.Api/Roles/SimpleRoleInfo.cs @@ -12,10 +12,6 @@ public sealed class SimpleRoleInfo public RoleTeam roleTeam; public RoleType roleType; - public SimpleRoleInfo() - { - } - public SimpleRoleInfo ( RoleId id, @@ -24,7 +20,8 @@ public SimpleRoleInfo RoleType type, string roleStringId, string roleName, - int roleIntId) + int roleIntId + ) { RoleColor = color; Name = roleName; @@ -59,6 +56,4 @@ string roleName ) : this(RoleId.none, color, team, type, "", roleName, -1) { } - - public Role ParentRole { get; } } \ No newline at end of file diff --git a/NextShip.Api/SourceGenerators/LangSourceGenerator.cs b/NextShip.Api/SourceGenerators/LangSourceGenerator.cs new file mode 100644 index 0000000..e32afe6 --- /dev/null +++ b/NextShip.Api/SourceGenerators/LangSourceGenerator.cs @@ -0,0 +1,12 @@ +using Microsoft.CodeAnalysis; + +namespace NextShip.Api.SourceGenerators; + + +/*[Generator(LanguageNames.CSharp)] +public class LangSourceGenerator : IIncrementalGenerator +{ + public void Initialize(IncrementalGeneratorInitializationContext context) + { + } +}*/ \ No newline at end of file diff --git a/NextShip.Api/Utils/StreamUtils.cs b/NextShip.Api/Utils/StreamUtils.cs index 033ac30..7a7cf29 100644 --- a/NextShip.Api/Utils/StreamUtils.cs +++ b/NextShip.Api/Utils/StreamUtils.cs @@ -4,6 +4,7 @@ using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; +using NextShip.Api.Attributes; using SeekOrigin = Il2CppSystem.IO.SeekOrigin; namespace NextShip.Api.Utils; diff --git a/NextShip/Api/Role/RoleCreater.cs b/NextShip/Api/Role/RoleCreater.cs deleted file mode 100644 index 6a99563..0000000 --- a/NextShip/Api/Role/RoleCreater.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Api.ShipApi.Roles; - -public class RoleCreater -{ -} \ No newline at end of file diff --git a/NextShip/Chat/Command.cs b/NextShip/Chat/Command.cs deleted file mode 100644 index f92e980..0000000 --- a/NextShip/Chat/Command.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NextShip.Chat.Patches; - -namespace NextShip.Chat; - -public class Command -{ - public static readonly List AllCommand; - public Action CommandEvent; - public int count; - - public string[] key; - - static Command() - { - AllCommand = new List(); - } - - public Command(string[] key, Action CommandEvent) - { - this.CommandEvent = CommandEvent; - count = AllCommand.Count; - this.key = key; - - AllCommand!.Add(this); - } - - private int KeyCount => key.Length; - - public string GetText() - { - var text = "/"; - foreach (var k in key) - { - text += k; - if (k == key.Last()) continue; - text += " "; - } - - return text; - } - - public static bool TryGetCommandEvent(string text, out Action action) - { - action = null; - var command = AllCommand.Find(n => n.Compare(text)); - if (command == null) return false; - action = command.CommandEvent; - return true; - } - - private bool Compare(string text) - { - return GetText() == text; - } - - private bool Compare(IReadOnlyCollection keys) - { - if (ChatPatch.CurrentText == "/") return true; - Info($"compare {keys.ToText()}"); - if (keys.Count > key.Length) return false; - Info("keys.Count > key.Length"); - if (keys == key) return false; - Info("keys == key"); - if (GetText() == ChatPatch.CurrentText) return false; - Info("GetText() == ChatPatch.CurrentText"); - - var Is = true; - for (var i = 0; i < keys.Count; i++) - { - var TKey = keys.ElementAt(i); - var VKey = key.ElementAt(i); - if (TKey != VKey) Is = Compare(TKey, VKey); - if (!Is) break; - } - - return Is; - } - - private static bool Compare(string TKey, string VKey) - { - Info($"{"Compare: " + TKey + " - " + VKey}"); - return VKey.Contains(TKey); - } - - public static List GetCommands(string[] keys) - { - var Commands = AllCommand.Where(n => n.Compare(keys)).ToList(); - Commands.Sort((x, y) => x.KeyCount.CompareTo(y.KeyCount)); - /*if (Commands.First().KeyCount > Commands.Last().KeyCount) Commands.Reverse();*/ - - return Commands; - } -} \ No newline at end of file diff --git a/NextShip/Chat/Commands.cs b/NextShip/Chat/Commands.cs deleted file mode 100644 index cb294ae..0000000 --- a/NextShip/Chat/Commands.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using HarmonyLib; - -namespace NextShip.Chat; - -[HarmonyPatch] -public static class Commands -{ - [HarmonyPatch(typeof(ChatController), nameof(ChatController.SendChat))] - [HarmonyPrefix] - public static bool SendChatPatch_Prefix(ChatController __instance) - { - __instance.timeSinceLastMessage = 3f; - var text = __instance.freeChatField.Text; - var args = text.Split(' '); - var canceled = false; - var cancelVal = ""; - switch (args[0]) - { - case "e": - break; - } - - if (Command.TryGetCommandEvent(text, out var action)) - { - canceled = true; - action(); - } - - - if (!CheckChat(text, out var checkAction)) checkAction.Invoke(__instance); - - if (!canceled) return true; - __instance.freeChatField.Clear(); - __instance.freeChatField.textArea.SetText(cancelVal); - - return false; - } - - private static bool CheckChat(string text, out Action action) - { - action = null; - return true; - } -} \ No newline at end of file diff --git a/NextShip/Chat/Patches/ChatPatch.cs b/NextShip/Chat/Patches/ChatPatch.cs deleted file mode 100644 index cfd6e55..0000000 --- a/NextShip/Chat/Patches/ChatPatch.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System.Collections.Generic; -using HarmonyLib; -using Il2CppSystem; -using TMPro; -using UnityEngine; - -namespace NextShip.Chat.Patches; - -[HarmonyPatch] -public static class ChatPatch -{ - private static GameObject CommandPromptBox; - private static readonly List AllButton = new(); - public static string CurrentText; - - [HarmonyPatch(typeof(ChatController), nameof(ChatController.Awake))] - [HarmonyPostfix] - public static void ChatController_Awake_Postfix(ChatController __instance) - { - __instance.freeChatField.OnChangedEvent += (Action)(() => OnChatChanged(__instance)); - new Command(new[] { "h" }, () => Info("h")); - new Command(new[] { "abab", "text" }, () => Info("ababaa")); - } - - - private static void OnChatChanged(ChatController __instance) - { - InitCommandPromptBox(__instance); - var text = __instance.freeChatField.Text; - CurrentText = text; - CommandPromptBox.SetActive(text.StartsWith("/")); - if (text.StartsWith("/")) UpdateCommandPromptBox(GetText(text), __instance); - } - - private static string[] GetText(string text) - { - var strings = new List(); - var AllStrings = new List(); - foreach (var c in text) - switch (c) - { - case '/': - continue; - case ' ': - AllStrings.Add(strings.ToText()); - Info($"Add {strings.ToText()}"); - strings = new List(); - continue; - default: - Info($"add {c}"); - strings.Add(c.ToStringText()); - break; - } - - Info($"GetString : {AllStrings.ToText()}"); - return AllStrings.ToArray(); - } - - private static void InitCommandPromptBox(ChatController __instance) - { - if (CommandPromptBox) return; - - CommandPromptBox = new GameObject("CommandPromptBox"); - CommandPromptBox.transform.SetParent(__instance.freeChatField.transform); - CommandPromptBox.transform.localPosition = new Vector3(0.0031f, 0.559f, -1); - var border = ObjetUtils.Find("smallButtonBorder"); - Sprite.Create(border.texture, new Rect(383, 272, 64, 64), new Vector2(0.5f, 0.5f), border.pixelsPerUnit, 0, - SpriteMeshType.FullRect, border.border).CaChe("PromptBorder"); - - var background = ObjetUtils.Find("blank"); - var SR = CommandPromptBox.AddComponent(); - SR.drawMode = SpriteDrawMode.Sliced; - SR.sprite = background; - SR.size = new Vector2(6.4f, 0.5f); - SR.color = new Color(0.962f, 1, 1, 0.298f); - } - - - private static void UpdateCommandPromptBox(string[] text, ChatController __instance) - { - var BoxSR = CommandPromptBox.GetComponent(); - AllButton.Do(n => n.Destroy()); - var list = Command.GetCommands(text); - if (list == null || list.Count == 0) - { - BoxSR.size = new Vector2(6.4f, 0.5f); - return; - } - - var count = 1; - Vector3 vector3 = new(-0.0017f, -0.12f, -1); - foreach (var command in Command.GetCommands(text)) - { - if (count == 5) break; - var button = new GameObject($"Button {count} : {text.ToText()}"); - button.transform.SetParent(CommandPromptBox.transform); - var SR = button.AddComponent(); - SR.sprite = SpriteUtils.GetCache("PromptBorder"); - SR.drawMode = SpriteDrawMode.Sliced; - SR.size = new Vector2(6.4f, 0.25f); - SR.color = new Color(0, 0, 0, 0); - button.transform.localPosition = vector3; - ; - vector3.y += 0.2f; - - var ButtonText = new GameObject("text"); - ButtonText.transform.SetParent(button.transform); - ButtonText.transform.localPosition = new Vector3(6.85f, -2.34f, -1); - var TMP = ButtonText.AddComponent(); - TMP.text = command.GetText(); - TMP.fontSize = 3; - TMP.color = new Color(0.962f, 1, 1, 0.298f); - - button.CreatePassiveButton(() => __instance.freeChatField.textArea.SetText(command.GetText()), - OnMouseOut: () => - { - TMP.color = new Color(0.962f, 1, 1, 0.298f); - SR.color = new Color(0, 0, 0, 0); - }, - OnMouseOver: () => - SR.color = TMP.color = Palette.White - ); - - count++; - AllButton.Add(button); - } - - CommandPromptBox.AllGameObjectDo(n => n.layer = LayerUtils.GetUILayer()); - } -} \ No newline at end of file diff --git a/NextShip/Chat/VoiceChatManager.cs b/NextShip/Chat/VoiceChatManager.cs deleted file mode 100644 index 6d98083..0000000 --- a/NextShip/Chat/VoiceChatManager.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Collections.Generic; -using System.Net.Sockets; - -namespace NextShip.Chat; - -public sealed class VoiceChatManager -{ - private static VoiceChatManager Instance; - - public List AllClient = new(); - public PlayerControl LocalPlayer = CachedPlayer.LocalPlayer; - - public TcpClient TcpClient; - public UdpClient UdpClient; - public VoiceConnectType VoiceConnectType; - - public static VoiceChatManager Get() - { - return Instance ??= new VoiceChatManager(); - } -} - -public enum VoiceConnectType -{ - RPCConnect, // RPC连接 - ServerConnect, // 额外服务器连接 - LocalConnect // 本地连接 -} \ No newline at end of file diff --git a/NextShip/Chat/VoiceClient.cs b/NextShip/Chat/VoiceClient.cs deleted file mode 100644 index 72c9856..0000000 --- a/NextShip/Chat/VoiceClient.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using NextShip.Game.Info; - -namespace NextShip.Chat; - -public class VoiceClient : IDisposable -{ - public PlayerControl Player; - public ShipInfo PlayerInfo; - public VoiceStatus Status; - - public void Dispose() - { - } - - public void Start() - { - } - - public void Update() - { - } -} - -public enum VoiceStatus -{ -} \ No newline at end of file diff --git a/NextShip/Config/CosmeticsConfig.cs b/NextShip/Config/CosmeticsConfig.cs deleted file mode 100644 index 8150f58..0000000 --- a/NextShip/Config/CosmeticsConfig.cs +++ /dev/null @@ -1,12 +0,0 @@ -using NextShip.Cosmetics; - -namespace NextShip.Config; - -public class CosmeticsConfig -{ - public CosmeticRepoType CosmeticRepoType { get; set; } - public CosmeticType CosmeticType { get; set; } - public CosmeticLoadType CosmeticLoadType { get; set; } - public string RepoName { get; set; } - public string RepoURL { get; set; } -} \ No newline at end of file diff --git a/NextShip/Cosmetics/CosmeticsManager.cs b/NextShip/Cosmetics/CosmeticsManager.cs index db1cd03..b775438 100644 --- a/NextShip/Cosmetics/CosmeticsManager.cs +++ b/NextShip/Cosmetics/CosmeticsManager.cs @@ -1,16 +1,8 @@ -using System.Collections.Generic; using HarmonyLib; -using NextShip.Game.Info; -using NextShip.Manager; using UnityEngine; namespace NextShip.Cosmetics; -public class ShipCosmeticsManager : Manager -{ - public List ShipInfos = new(); -} - [HarmonyPatch] internal static class ShipCosmeticsCache { diff --git a/NextShip/Cosmetics/CustomCosmeticsManager.cs b/NextShip/Cosmetics/CustomCosmeticsManager.cs index 175ec96..46e82e5 100644 --- a/NextShip/Cosmetics/CustomCosmeticsManager.cs +++ b/NextShip/Cosmetics/CustomCosmeticsManager.cs @@ -5,7 +5,8 @@ using System.Text.Json; using System.Text.RegularExpressions; using HarmonyLib; -using NextShip.Config; +using NextShip.Api.Config; +using NextShip.Api.Enums; using NextShip.Cosmetics.Loaders; using NextShip.Manager; using UnityEngine; @@ -31,7 +32,7 @@ public static class CustomCosmeticsManager public static List AllLoaders = new(); internal static readonly string RepoFilePath = - Path.Combine(FilesManager.CreativityPath, RepoFile.Is(FilesManager.FileType.Json)); + Path.Combine(FilesManager.CreativityPath, RepoFile.Is(FileType.Json)); private static readonly CosmeticsConfig[] ModConfig = { @@ -112,26 +113,3 @@ public static void AddToList(HatManager __instance) } } } - -public enum CosmeticRepoType -{ - TOR, - EXR, - NOS, - TIS -} - -public enum CosmeticType -{ - Hat, - NamePlate, - Visor, - Skin -} - -public enum CosmeticLoadType -{ - Repo, - Disk, - Resources -} \ No newline at end of file diff --git a/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs b/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs index 8875c1c..c2b06d8 100644 --- a/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs +++ b/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Threading.Tasks; -using NextShip.Config; +using NextShip.Api.Config; +using NextShip.Api.Enums; using UnityEngine; namespace NextShip.Cosmetics.Loaders; diff --git a/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs b/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs index 2bf21e3..9126d3a 100644 --- a/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs +++ b/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs @@ -8,7 +8,8 @@ using System.Threading.Tasks; using HarmonyLib; using Newtonsoft.Json.Linq; -using NextShip.Config; +using NextShip.Api.Config; +using NextShip.Api.Enums; using NextShip.Manager; using UnityEngine; @@ -120,7 +121,7 @@ private async void DownLoadSprites(HttpClient httpClient, string url, List(); var md5 = MD5.Create(); - var directoryPath = FilesManager.GetCosmeticsCacheDirectory(CosmeticType.Hat).FullName; + var directoryPath = FilesManager.GetCosmeticsCacheDirectory(CosmeticsTypes.Hat).FullName; foreach (var info in infos) { diff --git a/NextShip/DIY/Addons/AddonsManager.cs b/NextShip/DIY/Addons/AddonsManager.cs index 82b4abc..d850612 100644 --- a/NextShip/DIY/Addons/AddonsManager.cs +++ b/NextShip/DIY/Addons/AddonsManager.cs @@ -1,3 +1,4 @@ +using NextShip.Api.Bases; using NextShip.Manager; namespace NextShip.Addons; diff --git a/NextShip/DIY/Plugins/PluginBase.cs b/NextShip/DIY/Plugins/PluginBase.cs deleted file mode 100644 index aff1721..0000000 --- a/NextShip/DIY/Plugins/PluginBase.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace NextShip.Plugins; - -public abstract class ShipPlugin -{ - public List PluginCompatibilities = new(); - public ShipPluginInfo ShipPluginInfo; - - public ShipPlugin() - { - } - - public ShipPlugin(ShipPluginInfo pluginInfo) - { - ShipPluginInfo = pluginInfo; - } - - public abstract void Load(); -} - -[AttributeUsage(AttributeTargets.Class)] -public sealed class PluginCompatibility : Attribute -{ - public CompatibilityLevel Compatibility; - public string PluginName; - - public PluginCompatibility(string pluginName, CompatibilityLevel compatibility = CompatibilityLevel.Compatible) - { - PluginName = pluginName; - Compatibility = compatibility; - } -} - -public enum CompatibilityLevel -{ - Unknown = 0, - Compatible = 1, - Incompatible = 2, - Dependency = 3, - Need = 4 -} - -[AttributeUsage(AttributeTargets.Class)] -public sealed class ShipPluginInfo : Attribute -{ - public ShipPluginInfo(string Id, ShipVersion Version, string Name) - { - this.Id = Id; - this.Version = Version; - this.Name = Name; - } - - public string Id { get; } - public ShipVersion Version { get; } - public string Name { get; } -} \ No newline at end of file diff --git a/NextShip/DIY/Plugins/PluginManager.cs b/NextShip/DIY/Plugins/PluginManager.cs index 50ffd2c..90308f0 100644 --- a/NextShip/DIY/Plugins/PluginManager.cs +++ b/NextShip/DIY/Plugins/PluginManager.cs @@ -4,10 +4,12 @@ using System.Linq; using System.Reflection; using HarmonyLib; +using NextShip.Api.Attributes; +using NextShip.Api.Bases; using NextShip.Api.Utilities.Attributes; using NextShip.Manager; -namespace NextShip.Plugins; +namespace NextShip.DIY.Plugins; public class PluginManager : Manager { @@ -61,11 +63,12 @@ private void Load(string path) has = true; var plugin = (ShipPlugin)assembly.CreateInstance(n.FullName!); - if (plugin?.ShipPluginInfo == null) - { - var shipPluginInfo = n.GetCustomAttribute(); - plugin!.ShipPluginInfo = shipPluginInfo; - } + if (plugin == null) + return; + + var shipPluginInfo = n.GetCustomAttribute(); + if (shipPluginInfo != null) + plugin.ShipPluginInfo = shipPluginInfo; var Compatibilities = n.GetCustomAttributes(); plugin.PluginCompatibilities = Compatibilities.ToList(); diff --git a/NextShip/Game/GameEvents/GameEvent.cs b/NextShip/Game/GameEvents/GameEvent.cs deleted file mode 100644 index cb73e0b..0000000 --- a/NextShip/Game/GameEvents/GameEvent.cs +++ /dev/null @@ -1,23 +0,0 @@ -using HarmonyLib; -using NextShip.Listeners; - -namespace NextShip.Game.GameEvents; - -[HarmonyPatch] -public class GameEvent -{ - [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnGameEnd))] - [HarmonyPostfix] - public static void AmongUsClient_OnGameEnd(AmongUsClient __instance, - [HarmonyArgument(0)] EndGameResult endGameResult) - { - ListenerManager.Get().allGameEvents.Do(n => n.OnGameEnd(__instance, endGameResult)); - } - - [HarmonyPatch(typeof(GameStartManager), nameof(GameStartManager.Start))] - [HarmonyPostfix] - public static void GameStartManager_OnGameStart(GameStartManager __instance) - { - ListenerManager.Get().allGameEvents.Do(n => n.OnGameStart(__instance)); - } -} \ No newline at end of file diff --git a/NextShip/Game/GameEvents/GameState.cs b/NextShip/Game/GameEvents/GameState.cs deleted file mode 100644 index ccc6d72..0000000 --- a/NextShip/Game/GameEvents/GameState.cs +++ /dev/null @@ -1,38 +0,0 @@ -using HarmonyLib; -using InnerNet; - -namespace NextShip.Game.GameEvents; - -[HarmonyPatch] -public static class GameState -{ - public static bool InGame; - public static bool IsLobby => AmongUsClient.Instance.GameState == InnerNetClient.GameStates.Joined; - public static bool IsInGame => InGame; - public static bool IsEnded => AmongUsClient.Instance.GameState == InnerNetClient.GameStates.Ended; - public static bool IsOnlineGame => AmongUsClient.Instance.NetworkMode == NetworkModes.OnlineGame; - public static bool IsLocalGame => AmongUsClient.Instance.NetworkMode == NetworkModes.LocalGame; - public static bool IsFreePlay => AmongUsClient.Instance.NetworkMode == NetworkModes.FreePlay; - public static bool IsMeeting => InGame && MeetingHud.Instance; - - [HarmonyPatch(typeof(IntroCutscene), nameof(IntroCutscene.CoBegin))] - [HarmonyPostfix] - public static void CoBeginPatch() - { - InGame = true; - } - - [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnGameJoined))] - [HarmonyPostfix] - public static void OnGameJoinedPatch() - { - InGame = false; - } - - [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnGameEnd))] - [HarmonyPostfix] - public static void OnGameEndPatch() - { - InGame = false; - } -} \ No newline at end of file diff --git a/NextShip/Game/GameEvents/IGameEvent.cs b/NextShip/Game/GameEvents/IGameEvent.cs deleted file mode 100644 index e08916e..0000000 --- a/NextShip/Game/GameEvents/IGameEvent.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace NextShip.Game.GameEvents; - -public interface IGameEvent -{ - public void OnPlayerJoined(AmongUsClient _amongUsClient) - { - } - - public void OnPlayerLeft(AmongUsClient _amongUsClient) - { - } - - public void OnGameStart(GameStartManager _gameStartManager) - { - } - - public void OnCoBegin() - { - } - - public void OnPlayerKill(PlayerControl murderer, PlayerControl target) - { - } - - public void OnGameEnd(AmongUsClient __instance, EndGameResult endGameResult) - { - } - - public void OnIntroCutscene(IntroCutscene _introCutscene) - { - } -} \ No newline at end of file diff --git a/NextShip/Game/GameModes/GameModeManager.cs b/NextShip/Game/GameModes/GameModeManager.cs deleted file mode 100644 index 6ae7650..0000000 --- a/NextShip/Game/GameModes/GameModeManager.cs +++ /dev/null @@ -1,34 +0,0 @@ -using NextShip.Api.Utilities.Attributes; -using NextShip.Options; - -namespace NextShip.Game.GameModes; - -[Load] -public class GameModeManager -{ - public static OptionBase GameModeOption; - - public static void CreateOption() - { - /*var stringvalue = new StringOptionValue(new[] - { - GameMode.Vanilla.ToString(), GameMode.HideAndSeek.ToString(), GameMode.Normal.ToString(), - GameMode.PropHunter.ToString(), - GameMode.ResidentEvil.ToString(), - GameMode.BattleRoyale.ToString(), GameMode.RacingMode.ToString(), GameMode.RunForTime.ToString() - }); - GameModeOption = CStringOption.Create("Game Mode", stringvalue, optionTab.GameSettings);*/ - } -} - -public enum GameMode -{ - Vanilla = -2, // 原版 - HideAndSeek = -1, // 躲猫猫 - Normal = 0, // 一般 - PropHunter = 3, //道具猎手 - ResidentEvil = 4, //生化危机 - BattleRoyale = 5, //大逃杀 - RacingMode = 6, //竞速模式 - RunForTime = 7 //全员加速中 -} \ No newline at end of file diff --git a/NextShip/Game/Info/HostInfo.cs b/NextShip/Game/Info/HostInfo.cs deleted file mode 100644 index 5341ede..0000000 --- a/NextShip/Game/Info/HostInfo.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Game.Info; - -public sealed class HostInfo : ShipInfo -{ -} \ No newline at end of file diff --git a/NextShip/Game/Info/ShipInfo.cs b/NextShip/Game/Info/ShipInfo.cs deleted file mode 100644 index a7b575a..0000000 --- a/NextShip/Game/Info/ShipInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using UnityEngine; - -namespace NextShip.Game.Info; - -public abstract class ShipInfo -{ - public Color BodyBackGroundColor; - public Color BodyColor; - public Color BodyVisorColor; - public GameData Data; - public int id; - public string Name; - public PlayerControl Player; -} \ No newline at end of file diff --git a/NextShip/Game/Tasks/Task.cs b/NextShip/Game/Tasks/Task.cs deleted file mode 100644 index 8cb64bb..0000000 --- a/NextShip/Game/Tasks/Task.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using HarmonyLib; - -namespace NextShip.Game.Tasks; - -[HarmonyPatch] -public static class TasksHandler -{ - public static Tuple taskInfo(GameData.PlayerInfo playerInfo) - { - var TotalTasks = 0; - var CompletedTasks = 0; - if (!playerInfo.Disconnected && - playerInfo.Tasks != null && - playerInfo.Object && - playerInfo.Role && - playerInfo.Role.TasksCountTowardProgress - ) - foreach (var playerInfoTask in playerInfo.Tasks.GetFastEnumerator()) - { - if (playerInfoTask.Complete) CompletedTasks++; - TotalTasks++; - } - - return Tuple.Create(CompletedTasks, TotalTasks); - } - - [HarmonyPatch(typeof(GameData), nameof(GameData.RecomputeTaskCounts))] - private static class GameDataRecomputeTaskCountsPatch - { - private static bool Prefix(GameData __instance) - { - var totalTasks = 0; - var completedTasks = 0; - - foreach (var playerInfo in GameData.Instance.AllPlayers.GetFastEnumerator()) - { - var (playerCompleted, playerTotal) = taskInfo(playerInfo); - totalTasks += playerTotal; - completedTasks += playerCompleted; - } - - __instance.TotalTasks = totalTasks; - __instance.CompletedTasks = completedTasks; - return false; - } - } -} \ No newline at end of file diff --git a/NextShip/GlobalUsing.cs b/NextShip/GlobalUsing.cs index 0a60638..03350c6 100644 --- a/NextShip/GlobalUsing.cs +++ b/NextShip/GlobalUsing.cs @@ -3,4 +3,4 @@ global using NextShip.Api.Roles; global using NextShip.Api.Utilities; global using static NextShip.Api.Logs.log; -global using Main = NextShip.Main; \ No newline at end of file +global using Main = NextShip.NextShip; \ No newline at end of file diff --git a/NextShip/Languages/LanguagePack.cs b/NextShip/Languages/LanguagePack.cs index 9e6d886..b3cfc44 100644 --- a/NextShip/Languages/LanguagePack.cs +++ b/NextShip/Languages/LanguagePack.cs @@ -31,12 +31,7 @@ public class LanguagePack private static readonly Dictionary defaultLanguageSet = new(); public Dictionary languageSet; - - - public LanguagePack() - { - languageSet = new Dictionary(defaultLanguageSet); - } + //初始化 public static void Init() @@ -126,10 +121,8 @@ public static void Load() public void deserialize(string path) { - using (var sr = new StreamReader(path, Encoding.GetEncoding("utf-8"))) - { - deserialize(sr); - } + using var sr = new StreamReader(path, Encoding.GetEncoding("utf-8")); + deserialize(sr); } public void deserialize(StreamReader reader) diff --git a/NextShip/Listeners/Attributes/EventListener.cs b/NextShip/Listeners/Attributes/EventListener.cs deleted file mode 100644 index 7c9242d..0000000 --- a/NextShip/Listeners/Attributes/EventListener.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Reflection; -using NextShip.Game.GameEvents; - -namespace NextShip.Listeners.Attributes; - -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] -public class EventListener : Attribute -{ - public static void Registration(Type type) - { - var methodInfos = type.GetMethods(); - foreach (var MethodInfo in methodInfos) - { - if (MethodInfo.GetCustomAttribute() == null) continue; - if (MethodInfo.ReturnType == typeof(IGameEvent)) - { - ListenerManager.Get().RegisterGameEvent(MethodInfo.Invoke(null, null) as IGameEvent); - continue; - } - - if (!MethodInfo.Name.Contains("On")) continue; - - ListenerManager.Get().RegisterMethod(MethodInfo); - } - - if (type.GetCustomAttribute() == null) return; - foreach (var variableInterface in type.GetInterfaces()) - { - if (variableInterface != typeof(IGameEvent)) continue; - - var gameEvent = type.Assembly.CreateInstance(type.FullName!) as IGameEvent; - ListenerManager.Get().RegisterGameEvent(gameEvent); - } - } -} \ No newline at end of file diff --git a/NextShip/Listeners/ListenerManager.cs b/NextShip/Listeners/ListenerManager.cs deleted file mode 100644 index 6295ae4..0000000 --- a/NextShip/Listeners/ListenerManager.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using HarmonyLib; -using NextShip.Game.GameEvents; - -namespace NextShip.Listeners; - -public class ListenerManager -{ - private static ListenerManager _ListenerManager; - public readonly List allGameEvents = new(); - private readonly List allMethodInfos = new(); - - private ListenerManager() - { - _ListenerManager = this; - } - - internal void RegisterMethod(MethodInfo methodInfo) - { - allMethodInfos.Add(methodInfo); - } - - internal void RegisterGameEvent(IGameEvent gameEvent) - { - allGameEvents.Add(gameEvent); - } - - internal void URegisterGameEvent(IGameEvent gameEvent) - { - allGameEvents.Remove(gameEvent); - } - - internal bool Start(string name, object Target, params object[] objects) - { - var method = allMethodInfos.Find(n => n.Name == name); - if (method == null) return false; - - var list = new List(); - foreach (var varMethod in allMethodInfos.Where(n => - n.Name == name && n.GetGenericArguments().Contains((Type[])objects))) list.Add(varMethod); - - if (list.Count == 0) return false; - - try - { - list.Do(n => n.Invoke(Target, objects)); - return true; - } - catch (Exception e) - { - Exception(e); - return false; - } - } - - public static ListenerManager Get() - { - return _ListenerManager ?? new ListenerManager(); - } -} \ No newline at end of file diff --git a/NextShip/Manager/BanManager.cs b/NextShip/Manager/BanManager.cs deleted file mode 100644 index 28070c4..0000000 --- a/NextShip/Manager/BanManager.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Manager; - -public class BanManager : Manager -{ -} \ No newline at end of file diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs new file mode 100644 index 0000000..c4bd0bf --- /dev/null +++ b/NextShip/Manager/EventManager.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public class EventManager : IEventManager +{ + private readonly List RegisterEvents = new(); + + public void RegisterEvent(INextEvent @event) + { + @event.OnRegister(this); + RegisterEvents.Add(@event); + } + + public void UnRegisterEvent(INextEvent @event) + { + @event.OnUnRegister(this); + RegisterEvents.Remove(@event); + } + + public bool TryGetEvent(string eventName, out INextEvent @event) + { + if (RegisterEvents.Any(n => n.EventName == eventName)) + { + @event = RegisterEvents.FirstOrDefault(n => n.EventName == eventName); + return true; + } + + @event = null; + return false; + } + + public T GetEvent() where T : INextEvent + { + return (T)RegisterEvents.FirstOrDefault(n => n is T); + } + + public INextEvent GetEvent(Type type) + { + return RegisterEvents.FirstOrDefault(n => n.GetType() == type); + } +} \ No newline at end of file diff --git a/NextShip/Manager/FilesManager.cs b/NextShip/Manager/FilesManager.cs index 3953dd7..778ae02 100644 --- a/NextShip/Manager/FilesManager.cs +++ b/NextShip/Manager/FilesManager.cs @@ -1,17 +1,10 @@ using System.IO; +using NextShip.Api.Enums; namespace NextShip.Manager; public static class FilesManager { - public enum FileType - { - Csv, - Json, - Yaml, - Txt - } - public const string TIS_DataPath = "./TIS_Data"; public const string CreativityPath = "./Creativity"; public const string TIS_TempPath = "./TIS_Data/TEMP"; @@ -64,14 +57,14 @@ public static DirectoryInfo GetConfigDirectory(string name) return CreateDirectory(Path.Combine(CreativityPath, "Config", name)); } - public static DirectoryInfo GetCosmeticsCacheDirectory(Cosmetics.CosmeticType type) + public static DirectoryInfo GetCosmeticsCacheDirectory(CosmeticsTypes type) { var directoryName = type switch { - Cosmetics.CosmeticType.NamePlate => "CacheNamePlate", - Cosmetics.CosmeticType.Visor => "CacheVisor", - Cosmetics.CosmeticType.Skin => "CacheSkin", - Cosmetics.CosmeticType.Hat => "CacheHat", + CosmeticsTypes.NamePlate => "CacheNamePlate", + CosmeticsTypes.Visor => "CacheVisor", + CosmeticsTypes.Skin => "CacheSkin", + CosmeticsTypes.Hat => "CacheHat", _ => string.Empty }; return CreateDirectory(Path.Combine(CreativityPath, directoryName)); diff --git a/NextShip/Manager/HistoryInfoManager.cs b/NextShip/Manager/HistoryInfoManager.cs deleted file mode 100644 index 9630ab2..0000000 --- a/NextShip/Manager/HistoryInfoManager.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Manager; - -public class HistoryInfoManager : Manager -{ -} \ No newline at end of file diff --git a/NextShip/Manager/HistoryManager.cs b/NextShip/Manager/HistoryManager.cs deleted file mode 100644 index 57a5a57..0000000 --- a/NextShip/Manager/HistoryManager.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Manager; - -public class HistoryManager : Manager -{ -} \ No newline at end of file diff --git a/NextShip/Manager/PlayerManager.cs b/NextShip/Manager/PlayerManager.cs deleted file mode 100644 index 230f52f..0000000 --- a/NextShip/Manager/PlayerManager.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Manager; - -public class PlayerManager -{ -} \ No newline at end of file diff --git a/NextShip/Manager/PositionManager.cs b/NextShip/Manager/PositionManager.cs deleted file mode 100644 index cee6de8..0000000 --- a/NextShip/Manager/PositionManager.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace NextShip.Manager; - -public static class PositionManager -{ - public static readonly List AllGameObjects = AllGameObjectsPosition.Keys.ToList(); - public static Dictionary> AllGameObjectsPosition = new(); - - public static Vector3 Left = new(); - - public static void Set(this GameObject objet, Vector3 vector3) - { - objet.transform.position = vector3; - if (AllGameObjectsPosition.ContainsKey(objet)) - { - AllGameObjectsPosition[objet].Add(vector3); - return; - } - - AllGameObjectsPosition.Add(objet, new List { vector3 }); - } -} \ No newline at end of file diff --git a/NextShip/Manager/RegisterManager.cs b/NextShip/Manager/RegisterManager.cs index f8344c6..9f7b03a 100644 --- a/NextShip/Manager/RegisterManager.cs +++ b/NextShip/Manager/RegisterManager.cs @@ -1,18 +1,17 @@ using System; using System.Reflection; using HarmonyLib; +using NextShip.Api.Attributes; using NextShip.Api.Utilities.Attributes; -using NextShip.Listeners.Attributes; namespace NextShip.Manager; public static class RegisterManager { -/* public static List> registerList = new(); */ - public static void Registration(Assembly dll) + public static void Registration() { Info("Register: Start Registration(开始注册)", filename: "RegisterManager"); - dll.GetTypes().Do(StartRegistrations); + Assembly.GetExecutingAssembly().GetTypes().Do(StartRegistrations); } private static void StartRegistrations(Type type) @@ -20,7 +19,6 @@ private static void StartRegistrations(Type type) Il2CppRegisterAttribute.Registration(type); LoadAttribute.Registration(type); OptionLoad.Registration(type); - EventListener.Registration(type); TranslateTag.Registration(type); } } \ No newline at end of file diff --git a/NextShip/Manager/VanillaManager.cs b/NextShip/Manager/VanillaManager.cs deleted file mode 100644 index b8e199b..0000000 --- a/NextShip/Manager/VanillaManager.cs +++ /dev/null @@ -1,11 +0,0 @@ -using NextShip.Api.Utilities.Attributes; - -namespace NextShip.Manager; - -public static class VanillaManager -{ - [Load] - public static void Load() - { - } -} \ No newline at end of file diff --git a/NextShip/Manager/VersionManager.cs b/NextShip/Manager/VersionManager.cs deleted file mode 100644 index 779eee9..0000000 --- a/NextShip/Manager/VersionManager.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Manager; - -public class VersionManager : Manager -{ -} \ No newline at end of file diff --git a/NextShip/NextService.cs b/NextShip/NextService.cs new file mode 100644 index 0000000..d302308 --- /dev/null +++ b/NextShip/NextService.cs @@ -0,0 +1,60 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using NextShip.Api.Interfaces; + +namespace NextShip; + +public class NextService : INextService +{ + public IServiceProvider _Provider { get; private set; } + + private ServiceCollection _collection = new (); + + private bool BuildCompleted { get; set; } + + public NextService Set(ServiceCollection collection) + { + _collection = collection; + return this; + } + + public T Get() => _Provider.GetService(); + + public object Get(Type type) => _Provider.GetService(type); + + public void Build() + { + if(BuildCompleted) return; + + if (_collection.Count != 0) + { + _Provider = _collection.BuildServiceProvider(); + return; + } + + var collection = new ServiceCollection(); + + _Provider = collection.BuildServiceProvider(); + } + + + public void Rebuild() + { + Reset(); + Build(); + } + + public void Reset() + { + _collection.Clear(); + _Provider = null; + BuildCompleted = false; + } + + public static NextService Build(ServiceCollection collection) + { + var _Service = new NextService().Set(collection); + _Service.Build(); + return _Service; + } +} \ No newline at end of file diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index 5d38c0e..9cf75e8 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -10,6 +10,7 @@ true false false + true @@ -28,7 +29,7 @@ - + @@ -36,6 +37,11 @@ + + + + + diff --git a/NextShip/Options/DefaultOption.cs b/NextShip/Options/DefaultOption.cs index 7cd09a8..d915d2b 100644 --- a/NextShip/Options/DefaultOption.cs +++ b/NextShip/Options/DefaultOption.cs @@ -1,4 +1,5 @@ -using NextShip.Api.Utilities.Attributes; +using NextShip.Api.Attributes; +using NextShip.Api.Utilities.Attributes; namespace NextShip.Options; diff --git a/NextShip/Options/OptionManager.cs b/NextShip/Options/OptionManager.cs index 9c918a7..c02b492 100644 --- a/NextShip/Options/OptionManager.cs +++ b/NextShip/Options/OptionManager.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using HarmonyLib; +using NextShip.Api.Attributes; using NextShip.Api.Utilities.Attributes; namespace NextShip.Options; diff --git a/NextShip/Patches/CheckGameEndPatch.cs b/NextShip/Patches/CheckGameEndPatch.cs deleted file mode 100644 index 6ccdaca..0000000 --- a/NextShip/Patches/CheckGameEndPatch.cs +++ /dev/null @@ -1,28 +0,0 @@ -using HarmonyLib; -using NextShip.Roles; - -namespace NextShip.Patches; - -[HarmonyPatch(typeof(LogicGameFlowNormal), nameof(LogicGameFlowNormal.CheckEndCriteria))] -internal class CheckGameEndPatch -{ - public static bool Prefix(ShipStatus __instance) - { - return false; - if (!GameData.Instance) return false; - if (CheckAndEndGameForJesterWin(__instance)) return false; - return true; - } - - private static bool CheckAndEndGameForJesterWin(ShipStatus __instance) - { - if (Jester.triggerJesterWin) - { - //__instance.enabled = false; - GameManager.Instance.RpcEndGame((GameOverReason)CustomGameOverReason.JesterWin, false); - return true; - } - - return false; - } -} \ No newline at end of file diff --git a/NextShip/Patches/CredentialsPatch.cs b/NextShip/Patches/CredentialsPatch.cs deleted file mode 100644 index 437b63f..0000000 --- a/NextShip/Patches/CredentialsPatch.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System.Text; -using HarmonyLib; -using Il2CppSystem; -using InnerNet; -using UnityEngine; - -//using static NextShip.Languages.LanguageCSV; - -namespace NextShip.Patches; - -[HarmonyPatch] -public static class CredentialsPatch -{ - public static PingText pingText = new(); - - [HarmonyPatch(typeof(VersionShower), nameof(VersionShower.Start))] - private static class VersionShowerPatch - { - private static string stringText; - - private static void Postfix(VersionShower __instance) - { - stringText = __instance.text.text; -#if DEBUG - stringText += " " + $"{ThisAssembly.Git.Branch} {ThisAssembly.Git.Commit}"; -#endif - - stringText += "" + $"作者:天寸梦初 ver{Main.SupportVersion}"; - - __instance.text.text = stringText; - } - } - - [HarmonyPatch(typeof(PingTracker), nameof(PingTracker.Update))] - public static class PingTrackerPatch - { - private static void Postfix(PingTracker __instance) - { - pingText.Update(); - - StringBuilder stringBuilder = new(); - stringBuilder.AppendLine(TextUtils.cs(pingText.GetPingColor(), __instance.text.text)); - if (AmongUsClient.Instance.GameState == InnerNetClient.GameStates.Started) - stringBuilder.AppendLine( - $"The Ideal Ship \n - Next Ship v{Main.Version.ToString()}\n"); - - stringBuilder.AppendLine(TextUtils.cs(pingText.GetFPSColor(), $"FPS: {pingText.GetFPS()}")); - - __instance.text.text = stringBuilder.ToString(); - } - } - - public class PingText - { - private readonly int frequency = 30; - private readonly int ping = AmongUsClient.Instance.Ping; - private float deltaTime; - - private int FPS; - private Color FPSColor; - private Color PingColor; - private int time; - - public void Update() - { - deltaTime += Time.deltaTime; - - if (time == frequency) - { - FPS = (int)Mathf.Ceil(frequency / deltaTime); - deltaTime = 0; - time = 0; - } - - time++; - - PingColor = Color.cyan; - if (ping > 120) PingColor = Color.green; - if (ping > 180) PingColor = Color.blue; - if (ping > 240) PingColor = Color.white; - if (ping > 300) PingColor = Color.white; - if (ping > 500) PingColor = Color.red; - - if (FPS > 200) FPSColor = new Color32(255, 255, 0, Byte.MaxValue); - if (FPS <= 200) FPSColor = new Color32(99, 184, 255, Byte.MaxValue); - if (FPS <= 120) FPSColor = new Color32(205, 201, 201, Byte.MaxValue); - if (FPS <= 90) FPSColor = new Color32(84, 255, 159, Byte.MaxValue); - if (FPS <= 60) FPSColor = new Color32(240, 248, 255, Byte.MaxValue); - if (FPS <= 30) FPSColor = new Color32(255, 222, 173, Byte.MaxValue); - if (FPS <= 15) FPSColor = Color.red; - } - - public Color GetPingColor() - { - return PingColor; - } - - public Color GetFPSColor() - { - return FPSColor; - } - - public int GetFPS() - { - return FPS; - } - } -} \ No newline at end of file diff --git a/NextShip/Patches/EndGamePatch.cs b/NextShip/Patches/EndGamePatch.cs deleted file mode 100644 index 856e4ec..0000000 --- a/NextShip/Patches/EndGamePatch.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using HarmonyLib; -using NextShip.Roles; -using TMPro; -using UnityEngine; - -namespace NextShip.Patches; - -internal enum CustomGameOverReason -{ - forcedEnd = 10, - JesterWin -} - -internal enum WinCondition -{ - Default, - JesterWin -} - -internal static class AdditionalTempData -{ - // Should be implemented using a proper GameOverReason in the future - public static WinCondition winCondition = WinCondition.Default; - public static List additionalWinConditions = new(); - public static List playerRoles = new(); - public static float timer; - - public static void clear() - { - playerRoles.Clear(); - additionalWinConditions.Clear(); - winCondition = WinCondition.Default; - timer = 0; - } - - internal class PlayerRoleInfo - { - public string PlayerName { get; set; } - -/* public List Roles { get; set; } */ - public int TasksCompleted { get; set; } - public int TasksTotal { get; set; } - public bool IsGuesser { get; set; } - public int? Kills { get; set; } - } -} - -[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnGameEnd))] -public class OnGameEndPatch -{ - public static void Postfix(AmongUsClient __instance, [HarmonyArgument(0)] ref EndGameResult endGameResult) - { - /* AdditionalTempData.clear(); - - foreach(var player in CachedPlayer.AllPlayers) - { - var roles = RoleInfo.getRoleInfoForPlayer(player); - /* int? killCount = GameHistory.deadPlayers.FindAll(x => x.killerIfExisting != null && x.killerIfExisting.PlayerId == playerControl.PlayerId).Count; - if (killCount == 0 && !(new List() { RoleInfo.sheriff, RoleInfo.jackal, RoleInfo.sidekick, RoleInfo.thief }.Contains(RoleInfo.getRoleInfoForPlayer(playerControl, false).FirstOrDefault()) || playerControl.Data.Role.IsImpostor)) - { - killCount = null; - } - AdditionalTempData.playerRoles.Add(new AdditionalTempData.PlayerRoleInfo() { PlayerName = playerControl.Data.PlayerName, Roles = roles, TasksTotal = tasksTotal, TasksCompleted = tasksCompleted, IsGuesser = isGuesser, Kills = killCount }); - } */ - - var notWinners = new List(); - if (Jester.jester != null) notWinners.Add(Jester.jester); - var winnersToRemove = new List(); - foreach (var winner in TempData.winners.GetFastEnumerator()) - if (notWinners.Any(x => x.Data.PlayerName == winner.PlayerName)) - winnersToRemove.Add(winner); - - foreach (var winner in winnersToRemove) TempData.winners.Remove(winner); - var jesterWin = Jester.jester != null && - endGameResult.GameOverReason == (GameOverReason)CustomGameOverReason.JesterWin; - if (jesterWin) - { - TempData.winners = new Il2CppSystem.Collections.Generic.List(); - var wpd = new WinningPlayerData(Jester.jester.Data); - TempData.winners.Add(wpd); - AdditionalTempData.winCondition = WinCondition.JesterWin; - } -/* if (TempData.winners[0].IsImpostor && SchrodingersCat.team == RoleInfo.RoleTeam.Impostor) TempData.winners.Add(new WinningPlayerData(SchrodingersCat.schrodingersCat.Data)); - if (!TempData.winners[0].IsImpostor && SchrodingersCat.team == RoleInfo.RoleTeam.Crewmate) TempData.winners.Add(new WinningPlayerData(SchrodingersCat.schrodingersCat.Data)); */ - } -} - -[HarmonyPatch(typeof(EndGameManager), nameof(EndGameManager.SetEverythingUp))] -public class EndGameManagerSetUpPatch -{ - public static void Postfix(EndGameManager __instance) - { - var bonusText = Object.Instantiate(__instance.WinText.gameObject); - bonusText.transform.position = new Vector3(__instance.WinText.transform.position.x, - __instance.WinText.transform.position.y - 0.5f, __instance.WinText.transform.position.z); - bonusText.transform.localScale = new Vector3(0.7f, 0.7f, 1f); - var textRenderer = bonusText.GetComponent(); - textRenderer.text = ""; - - if (TempData.EndReason == (GameOverReason)CustomGameOverReason.JesterWin) - { - __instance.WinText.text = GetString("JesterWinText"); - __instance.WinText.color = Jester.color; - textRenderer.text = GetString("JesterWinSubText"); - textRenderer.color = Jester.color; - } - else if (TempData.EndReason == (GameOverReason)CustomGameOverReason.forcedEnd) - { - __instance.WinText.text = GetString("forcedEndWinText"); - __instance.WinText.color = Palette.AcceptedGreen; - } - } -} \ No newline at end of file diff --git a/NextShip/Patches/PlayerControlPatch.cs b/NextShip/Patches/PlayerControlPatch.cs deleted file mode 100644 index 3974894..0000000 --- a/NextShip/Patches/PlayerControlPatch.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using AmongUs.GameOptions; -using HarmonyLib; -using InnerNet; -using NextShip.Roles; -using TMPro; -using UnityEngine; - -namespace NextShip.Patches; - -[HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.FixedUpdate))] -public static class PlayerControlFixedUpdatePatch -{ - private static PlayerControl setTarget(bool onlyCrewmates = false, bool targetPlayersInVents = false, - List untargetablePlayers = null, PlayerControl targetingPlayer = null) - { - var go = GameOptionsManager.Instance.currentGameOptions; - var NGO = GameOptionsManager.Instance.currentNormalGameOptions; - PlayerControl result = null; - var num = GameOptionsData.KillDistances[Mathf.Clamp(NGO.KillDistance, 0, 2)]; - if (!ShipStatus.Instance) return result; - if (targetingPlayer == null) targetingPlayer = CachedPlayer.LocalPlayer.PlayerControl; - if (targetingPlayer.Data.IsDead) return result; - - var truePosition = targetingPlayer.GetTruePosition(); - foreach (var playerInfo in GameData.Instance.AllPlayers.GetFastEnumerator()) - if (!playerInfo.Disconnected && playerInfo.PlayerId != targetingPlayer.PlayerId && !playerInfo.IsDead && - (!onlyCrewmates || !playerInfo.Role.IsImpostor)) - { - var @object = playerInfo.Object; - if (untargetablePlayers != null && untargetablePlayers.Any(x => x == @object)) - // if that player is not targetable: skip check - continue; - - if (@object && (!@object.inVent || targetPlayersInVents)) - { - var vector = @object.GetTruePosition() - truePosition; - var magnitude = vector.magnitude; - if (magnitude <= num && !PhysicsHelpers.AnyNonTriggersBetween(truePosition, vector.normalized, - magnitude, Constants.ShipAndObjectsMask)) - { - result = @object; - num = magnitude; - } - } - } - - return result; - } - - private static void setPlayerOutline(PlayerControl target, Color color) - { - if (target == null || target.cosmetics?.currentBodySprite?.BodySprite == null) return; - - target.cosmetics.currentBodySprite.BodySprite.material.SetFloat("_Outline", 1f); - target.cosmetics.currentBodySprite.BodySprite.material.SetColor("_OutlineColor", color); - } - - private static void setBasePlayerOutlines() - { - foreach (var target in PlayerControl.AllPlayerControls) - { - if (target == null || target.cosmetics?.currentBodySprite?.BodySprite.material == null) - continue; - target.cosmetics?.currentBodySprite?.BodySprite.material.SetFloat("_Outline", 0f); - } - } - - private static void sheriffSetTarget() - { - if (Sheriff.sheriff == null || Sheriff.sheriff != CachedPlayer.LocalPlayer.PlayerControl) - return; - Sheriff.currentTarget = setTarget(); - setPlayerOutline(Sheriff.currentTarget, Sheriff.color); - } - - private static void impostorSetTarget() - { - if (!CachedPlayer.LocalPlayer.Data.Role.IsImpostor || !CachedPlayer.LocalPlayer.PlayerControl.CanMove || - CachedPlayer.LocalPlayer.Data.IsDead) - { - FastDestroyableSingleton.Instance.KillButton.SetTarget(null); - return; - } - - PlayerControl target = null; - target = setTarget(true, true); - - FastDestroyableSingleton.Instance.KillButton - .SetTarget(target); // Includes setPlayerOutline(target, Palette.ImpstorRed); - } - - public static void updatePlayerInfo() - { - foreach (PlayerControl p in CachedPlayer.AllPlayers) - { - if (p != CachedPlayer.LocalPlayer.PlayerControl && !CachedPlayer.LocalPlayer.Data.IsDead && - !p.isDummy) continue; - var playerInfoTransform = p.cosmetics.nameText.transform.parent.FindChild("Info"); - var playerInfo = playerInfoTransform != null - ? playerInfoTransform.GetComponent() - : null; - if (playerInfo == null) - { - playerInfo = Object.Instantiate(p.cosmetics.nameText, - p.cosmetics.nameText.transform.parent); - playerInfo.transform.localPosition += Vector3.up * 0.225f; - playerInfo.fontSize *= 0.75f; - playerInfo.gameObject.name = "Info"; - playerInfo.color = playerInfo.color.SetAlpha(1f); - } - - var playerVoteArea = MeetingHud.Instance?.playerStates?.FirstOrDefault(x => x.TargetPlayerId == p.PlayerId); - var meetingInfoTransform = playerVoteArea != null - ? playerVoteArea.NameText.transform.parent.FindChild("Info") - : null; - var meetingInfo = meetingInfoTransform != null ? meetingInfoTransform.GetComponent() : null; - if (meetingInfo == null && playerVoteArea != null) - { - meetingInfo = Object.Instantiate(playerVoteArea.NameText, playerVoteArea.NameText.transform.parent); - meetingInfo.transform.localPosition += Vector3.down * 0.20f; - meetingInfo.fontSize *= 0.75f; - meetingInfo.gameObject.name = "Info"; - } - -/* string roleNames = RoleHelpers.GetRolesString(p, true); - string modifierName = RoleHelpers.GetRolesString(p, true, true); */ - - var playerInfoText = ""; - var meetingInfoText = ""; -/* if (p == CachedPlayer.LocalPlayer.PlayerControl || p.isDummy) - { - playerInfoText = $"{roleNames}"; - meetingInfoText = $"{roleNames}\n{modifierName}".Trim(); - } */ - - playerInfo.text = playerInfoText; - playerInfo.gameObject.SetActive(p.Visible); - if (meetingInfo != null) - meetingInfo.text = MeetingHud.Instance.state == MeetingHud.VoteStates.Results ? "" : meetingInfoText; - } - } - - public static void speedUpdate() - { - var p = CachedPlayer.LocalPlayer.PlayerControl; - if (p == Flash.flash && Flash.flash != null) p.MyPhysics.Speed = Flash.speed; - } - - public static void Postfix(PlayerControl __instance) - { - if (AmongUsClient.Instance.GameState != InnerNetClient.GameStates.Started) return; - if (CachedPlayer.LocalPlayer.PlayerControl == __instance) - { - setBasePlayerOutlines(); - - updatePlayerInfo(); - - sheriffSetTarget(); - - impostorSetTarget(); - - speedUpdate(); - } - } -} \ No newline at end of file diff --git a/NextShip/Patches/ServerPath.cs b/NextShip/Patches/ServerPath.cs index c59d584..03a852c 100644 --- a/NextShip/Patches/ServerPath.cs +++ b/NextShip/Patches/ServerPath.cs @@ -1,5 +1,4 @@ -using System.Linq; -using HarmonyLib; +using HarmonyLib; namespace NextShip.Patches; @@ -17,16 +16,15 @@ public static void autoAddServer() createHttp("www.aumods.xyz", "Modded NA (MNA)", 443, true), createHttp("au-eu.duikbo.at", "Modded EU (MEU)", 443, true) }; - - if (!Main.isChinese) regionInfos.ToList().RemoveAt(0); + + foreach (var r in regionInfos) { if (Main.serverManager.AvailableRegions.Contains(r)) continue; Main.serverManager.AddOrUpdateRegion(r); } - - if (Main.IsDev) Main.serverManager.SetRegion(regionInfos[0]); + } public static IRegionInfo createHttp(string ip, string name, ushort port, bool ishttps) @@ -36,16 +34,7 @@ public static IRegionInfo createHttp(string ip, string name, ushort port, bool i ServerInfo[] ServerInfo = { serverInfo }; return new StaticHttpRegionInfo(name, StringNames.NoTranslation, ip, ServerInfo).CastFast(); } - - [HarmonyPatch(typeof(Constants), nameof(Constants.GetBroadcastVersion))] - [HarmonyPrefix] - public static bool ConstantsGetBroadcastVersionPatch(ref int __result) - { - if (!CurrentVanillaServer) return true; - - __result = Constants.GetVersion(2222, 0, 0, 0); - return false; - } + private static bool IsVanilla(this IRegionInfo regionInfo) { diff --git a/NextShip/RPC/RPC.cs b/NextShip/RPC/RPC.cs deleted file mode 100644 index 8862feb..0000000 --- a/NextShip/RPC/RPC.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System; -using Hazel; -using NextShip.Roles; -using static NextShip.Api.Roles.RoleEnum; - -namespace NextShip.RPC; - -internal enum CustomRPC -{ - // Main 主要 - ResetVariables, - ShareOptions, - WorkaroundSetRoles, - SetRole, - SetModifier, - setDead, - RestoreRole, - ChangeRole, - RestorePlayerLook, - customrpc, - VersionShakehand, - HistorySynchronization, - RpcValueHandshake, - - // Role 职业相关 - SheriffKill, - Camouflager, - Illusory, - SchrodingerSCatTeamChange, - LoverSendChat -} - -public static class RPCProcedure -{ - public static void ResetVariables() - { - } - - public static void WorkaroundSetRoles(byte numberOfRoles, MessageReader reader) - { - for (var i = 0; i < numberOfRoles; i++) - { - var playerId = (byte)reader.ReadPackedUInt32(); - var roleId = (byte)reader.ReadPackedUInt32(); - try - { - setRole(roleId, playerId); - } - catch (Exception e) - { - Error("Error while deserializing roles: " + e.Message); - } - } - } - - public static void setRole(byte roleId, byte playerId) - { - var player = PlayerUtils.GetPlayerForId(playerId); - switch ((RoleId)roleId) - { - case RoleId.Sheriff: - Sheriff.sheriff = player; - break; - - case RoleId.Jester: - Jester.jester = player; - break; - - case RoleId.Camouflager: - Roles.Camouflager.camouflager = player; - break; - - case RoleId.Illusory: - Roles.Illusory.illusory = player; - break; - } - } - - public static void setModifier(byte modifierId, byte playerId, byte flag) - { - var player = PlayerUtils.GetPlayerForId(playerId); - switch ((RoleId)modifierId) - { - case RoleId.Flash: - Flash.flash = player; - break; - - case RoleId.Lover: - if (flag == 0) - Lover.lover1 = player; - else - Lover.lover2 = player; - break; - } - } - - public static void setDead(byte id, bool isDead) - { - var player = PlayerUtils.GetPlayerForId(id); - player.Data.IsDead = isDead; - } - - public static void SheriffKill(byte targetId) - { - var player = PlayerUtils.GetPlayerForId(targetId); - Sheriff.sheriff.MurderPlayer(player, MurderResultFlags.Succeeded); - } - - public static void RestoreRole(byte id) - { - switch ((RoleId)id) - { - case RoleId.Sheriff: - Sheriff.sheriff = null; - break; - case RoleId.Flash: - Flash.flash = null; - break; - case RoleId.Jester: - Jester.jester = null; - break; - } - } - - public static void ChangeRole(byte playerId, byte targetRoleId) - { - var player = PlayerUtils.GetPlayerForId(playerId); - setRole(targetRoleId, playerId); - } - - public static void RestorePlayerLook() - { - foreach (var player in CachedPlayer.AllPlayers) player.PlayerControl.setDefaultLook(); - } - - public static void Camouflager() - { - foreach (var player in CachedPlayer.AllPlayers) player.PlayerControl.setLook("", 6, "", "", "", ""); - } - - public static void Illusory() - { - if (CachedPlayer.LocalPlayer.PlayerControl.Data.Role.IsImpostor) return; - for (var i = 0; i < CachedPlayer.AllPlayers.Count; i++) - { - var rndPlayer = CachedPlayer.AllPlayers[rnd.Next(0, CachedPlayer.AllPlayers.Count)].PlayerControl; - CachedPlayer.AllPlayers[i].PlayerControl.setLook(rndPlayer.Data.PlayerName, - rndPlayer.Data.DefaultOutfit.ColorId, rndPlayer.Data.DefaultOutfit.HatId, - rndPlayer.Data.DefaultOutfit.VisorId, rndPlayer.Data.DefaultOutfit.SkinId, - rndPlayer.Data.DefaultOutfit.PetId); - } - } - - /*public static void LoverSendChat(PlayerControl player, string text, bool isSend = false) - { - if (!isSend) - { - LoveChatPatch.LoverChat.AddChat(player, text); - return; - } - - if (isSend) - { - text = Regex.Replace(text, "<.*?>", string.Empty); - var messageWriter = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, - (byte)CustomRPC.LoverSendChat, SendOption.Reliable); - messageWriter.Write(player.PlayerId); - messageWriter.Write(text); - AmongUsClient.Instance.FinishRpcImmediately(messageWriter); - LoveChatPatch.LoverChat.AddChat(PlayerControl.LocalPlayer, text); - } - }*/ -} \ No newline at end of file diff --git a/NextShip/RPC/RPCPatch.cs b/NextShip/RPC/RPCPatch.cs index b28f4d6..455d2a1 100644 --- a/NextShip/RPC/RPCPatch.cs +++ b/NextShip/RPC/RPCPatch.cs @@ -11,7 +11,7 @@ public class RPCHandlerPatch { private static void Postfix([HarmonyArgument(0)] byte callId, [HarmonyArgument(1)] MessageReader reader) { - RPCUtils.StartRPC(callId, reader); + /*RPCUtils.StartRPC(callId, reader);*/ } private static bool Prefix(PlayerControl __instance, [HarmonyArgument(0)] byte callId, diff --git a/NextShip/RPC/RPCUtils.cs b/NextShip/RPC/RPCUtils.cs index 529c74c..35b27b2 100644 --- a/NextShip/RPC/RPCUtils.cs +++ b/NextShip/RPC/RPCUtils.cs @@ -29,8 +29,6 @@ public static void Create(byte rpc, byte[] bytes = null, int[] ints = null, floa foreach (var str in strings) rpcStart.Write(str); - SendValueLength(bytes.Length, ints.Length, bools.Length, floats.Length, strings.Length); - AmongUsClient.Instance.FinishRpcImmediately(rpcStart); } @@ -100,17 +98,14 @@ public static void ReadValueLength(MessageReader reader) ReadValue(reader); } - public static void SendValueLength(int byteL = 0, int intL = 0, int boolL = 0, int FloatL = 0, int StringL = 0) + /*public static void SendValueLength(int byteL = 0, int intL = 0, int boolL = 0, int FloatL = 0, int StringL = 0) { - var rpcStart = AmongUsClient.Instance.StartRpcImmediately(CachedPlayer.LocalPlayer.PlayerControl.NetId, - (byte)CustomRPC.RpcValueHandshake, SendOption.Reliable); var Length = 0; if (byteL != 0) Length++; if (intL != 0) Length++; if (boolL != 0) Length++; if (FloatL != 0) Length++; if (StringL != 0) Length++; - rpcStart.Write(Length); if (byteL != 0) { @@ -143,9 +138,9 @@ public static void SendValueLength(int byteL = 0, int intL = 0, int boolL = 0, i } AmongUsClient.Instance.FinishRpcImmediately(rpcStart); - } + }*/ - public static void StartRPC(byte rpc, MessageReader reader) + /*public static void StartRPC(byte rpc, MessageReader reader) { switch (rpc) { @@ -194,7 +189,7 @@ public static void StartRPC(byte rpc, MessageReader reader) RPCProcedure.Illusory(); break; } - } + }*/ } public static class ReadRPCValue diff --git a/NextShip/Roles/Court/judge.cs b/NextShip/Roles/Court/judge.cs deleted file mode 100644 index c60e9ee..0000000 --- a/NextShip/Roles/Court/judge.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Roles; - -public class judge -{ -} \ No newline at end of file diff --git a/NextShip/Roles/Crewmate/Mayor.cs b/NextShip/Roles/Crewmate/Mayor.cs deleted file mode 100644 index 803ddb7..0000000 --- a/NextShip/Roles/Crewmate/Mayor.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Roles; - -public class Mayor -{ -} \ No newline at end of file diff --git a/NextShip/Roles/Crewmate/Postman.cs b/NextShip/Roles/Crewmate/Postman.cs deleted file mode 100644 index b1051c7..0000000 --- a/NextShip/Roles/Crewmate/Postman.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace NextShip.Roles; - -public class Postman : Role -{ - private static readonly SimpleRoleInfo PostmanRoleInfo = new(); - - - public Postman() - { - CreateRoleBase = n => new PostmanBase(n); - SimpleRoleInfo = PostmanRoleInfo; - } - - private class PostmanBase : RoleBase - { - public PostmanBase(PlayerControl player) : base(player) - { - } - } -} \ No newline at end of file diff --git a/NextShip/Roles/Cult/CultPreacher.cs b/NextShip/Roles/Cult/CultPreacher.cs deleted file mode 100644 index b4803f6..0000000 --- a/NextShip/Roles/Cult/CultPreacher.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Roles; - -public class CultPreacher -{ -} \ No newline at end of file diff --git a/NextShip/Roles/Cult/Cultist.cs b/NextShip/Roles/Cult/Cultist.cs deleted file mode 100644 index df2239f..0000000 --- a/NextShip/Roles/Cult/Cultist.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Roles; - -public class Cultist -{ -} \ No newline at end of file diff --git a/NextShip/Roles/Impostor/Camouflager.cs b/NextShip/Roles/Impostor/Camouflager.cs deleted file mode 100644 index 8224053..0000000 --- a/NextShip/Roles/Impostor/Camouflager.cs +++ /dev/null @@ -1,29 +0,0 @@ -using UnityEngine; - -namespace NextShip.Roles; - -public class Camouflager -{ - public static PlayerControl camouflager; - public static Color color = Palette.ImpostorRed; - public static float cooldown = 30f; - public static float duration = 10f; - public static Sprite ButtonSprite; - - - public static Sprite getButtonSprite() - { - if (ButtonSprite) return ButtonSprite; - ButtonSprite = SpriteUtils.LoadSpriteFromResources("NextShip.Resources.CamouflagerButton.png", 115f); - return ButtonSprite; - } - - public static void clearAndReload() - { - camouflager = null; - } - - public static void OptionLoad() - { - } -} \ No newline at end of file diff --git a/NextShip/Roles/Impostor/Illusory.cs b/NextShip/Roles/Impostor/Illusory.cs deleted file mode 100644 index aabb364..0000000 --- a/NextShip/Roles/Impostor/Illusory.cs +++ /dev/null @@ -1,28 +0,0 @@ -using UnityEngine; - -namespace NextShip.Roles; - -public class Illusory -{ - public static PlayerControl illusory; - public static Color color = Palette.ImpostorRed; - public static float cooldown = 30f; - public static float duration = 10f; - public static Sprite ButtonSprite; - - public static Sprite getButtonSprite() - { - if (ButtonSprite) return ButtonSprite; - ButtonSprite = SpriteUtils.LoadSpriteFromResources("NextShip.Resources.Illusory.png", 115f); - return ButtonSprite; - } - - public static void clearAndReload() - { - illusory = null; - } - - public static void OptionLoad() - { - } -} \ No newline at end of file diff --git a/NextShip/Roles/Modifier/Flash.cs b/NextShip/Roles/Modifier/Flash.cs deleted file mode 100644 index b436b5c..0000000 --- a/NextShip/Roles/Modifier/Flash.cs +++ /dev/null @@ -1,19 +0,0 @@ -using UnityEngine; - -namespace NextShip.Roles; - -public static class Flash -{ - public static PlayerControl flash; - public static Color color = new Color32(248, 205, 70, byte.MaxValue); - public static float speed = 5f; - - public static void clearAndReload() - { - flash = null; - } - - public static void OptionLoad() - { - } -} \ No newline at end of file diff --git a/NextShip/Roles/Modifier/Lover.cs b/NextShip/Roles/Modifier/Lover.cs deleted file mode 100644 index 64ae7f8..0000000 --- a/NextShip/Roles/Modifier/Lover.cs +++ /dev/null @@ -1,21 +0,0 @@ -using UnityEngine; - -namespace NextShip.Roles; - -public class Lover -{ - public static PlayerControl lover1, lover2; - public static Color Color = new Color32(255, 105, 180, byte.MaxValue); - public static bool suicide; - - public static void clearAndReload() - { - lover1 = null; - lover2 = null; - suicide = false; - } - - public static void OptionLoad() - { - } -} \ No newline at end of file diff --git a/NextShip/Roles/Neutral/Jester.cs b/NextShip/Roles/Neutral/Jester.cs deleted file mode 100644 index 3a79e43..0000000 --- a/NextShip/Roles/Neutral/Jester.cs +++ /dev/null @@ -1,20 +0,0 @@ -using UnityEngine; - -namespace NextShip.Roles; - -public class Jester -{ - public static PlayerControl jester; - public static Color color = new Color32(255, 105, 180, byte.MaxValue); - public static bool triggerJesterWin = false; - public static bool CanCallEmergency = true; - - public static void clearAndReload() - { - jester = null; - } - - public static void OptionLoad() - { - } -} \ No newline at end of file diff --git a/NextShip/Roles/Neutral/SchrodingersCat.cs b/NextShip/Roles/Neutral/SchrodingersCat.cs deleted file mode 100644 index 46a68a6..0000000 --- a/NextShip/Roles/Neutral/SchrodingersCat.cs +++ /dev/null @@ -1,20 +0,0 @@ -using UnityEngine; - -namespace NextShip.Roles; - -public class SchrodingersCat -{ - public static PlayerControl schrodingersCat; - public static Color color = new(130, 130, 130); - public static RoleTeam team = RoleTeam.Neutral; - - public static void clearAndReload() - { - schrodingersCat = null; - team = RoleTeam.Neutral; - } - - public static void OptionLoad() - { - } -} \ No newline at end of file diff --git a/NextShip/Roles/PoliceStation/Sheriff.cs b/NextShip/Roles/PoliceStation/Sheriff.cs deleted file mode 100644 index f43d7b7..0000000 --- a/NextShip/Roles/PoliceStation/Sheriff.cs +++ /dev/null @@ -1,24 +0,0 @@ -using UnityEngine; - -namespace NextShip.Roles; - -public class Sheriff : RoleBase -{ - public static PlayerControl sheriff; - public static Color color = new Color32(248, 205, 70, byte.MaxValue); - public static float shootNumber = 5f; - public static float cooldown = 30f; - public static PlayerControl currentTarget; - - - public Sheriff(PlayerControl player) : base(player) - { - } - - - public static void clearAndReload() - { - sheriff = null; - currentTarget = null; - } -} \ No newline at end of file diff --git a/NextShip/UI/Components/DownMenu.cs b/NextShip/UI/Components/DownMenu.cs index 1c635b8..5c606c4 100644 --- a/NextShip/UI/Components/DownMenu.cs +++ b/NextShip/UI/Components/DownMenu.cs @@ -1,4 +1,5 @@ -using NextShip.Api.Utilities.Attributes; +using NextShip.Api.Attributes; +using NextShip.Api.Utilities.Attributes; using UnityEngine; namespace NextShip.UI.Components; diff --git a/NextShip/UI/Components/NextMenuOption.cs b/NextShip/UI/Components/NextMenuOption.cs index fc320e0..f89f943 100644 --- a/NextShip/UI/Components/NextMenuOption.cs +++ b/NextShip/UI/Components/NextMenuOption.cs @@ -1,4 +1,5 @@ -using NextShip.Api.Utilities.Attributes; +using NextShip.Api.Attributes; +using NextShip.Api.Utilities.Attributes; using NextShip.Options; using UnityEngine; diff --git a/NextShip/UI/Components/ShipOptionBehaviour.cs b/NextShip/UI/Components/ShipOptionBehaviour.cs index 30511a4..343b8b9 100644 --- a/NextShip/UI/Components/ShipOptionBehaviour.cs +++ b/NextShip/UI/Components/ShipOptionBehaviour.cs @@ -1,4 +1,5 @@ using System; +using NextShip.Api.Attributes; using NextShip.Api.Utilities.Attributes; using NextShip.Options; using TMPro; diff --git a/NextShip/UI/UIManager/NextUIManager.cs b/NextShip/UI/UIManager/NextUIManager.cs index 9756e21..14047a2 100644 --- a/NextShip/UI/UIManager/NextUIManager.cs +++ b/NextShip/UI/UIManager/NextUIManager.cs @@ -1,3 +1,4 @@ +using NextShip.Api.Attributes; using NextShip.Api.Utilities.Attributes; using UnityEngine; diff --git a/NextShip/UI/VoiceChatHud.cs b/NextShip/UI/VoiceChatHud.cs deleted file mode 100644 index 8881e14..0000000 --- a/NextShip/UI/VoiceChatHud.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using HarmonyLib; -using UnityEngine; - -namespace NextShip.UI; - -[HarmonyPatch] -public class VoiceChatHud -{ - private static readonly List AllPlayer = new(); - private static GameObject VCHud; - private static GameObject VCClinetTem; - private static Vector3 POS; - private static GameObject AllPlayerList; - - [HarmonyPatch(typeof(HudManager), nameof(HudManager.Start))] - [HarmonyPostfix] - public static void HudManager_Start_Postfix(HudManager __instance) - { - return; - if (VCHud) return; - VCHud = new GameObject("VoiceChatHud") - { - transform = - { - localPosition = new Vector3(5, 0, -500) - } - }; - VCHud.transform.SetParent(Camera.main!.transform); - var HeadBackGround = new GameObject("HeadBackGround"); - HeadBackGround.transform.SetParent(VCHud.transform); - var BackGroundSprite = HeadBackGround.AddComponent(); - BackGroundSprite.sprite = SpriteUtils.LoadSpriteFromResources("NextShip.Resources.HeadBackGround.png", 150f); - BackGroundSprite.size = new Vector2(0.8f, 12); - BackGroundSprite.drawMode = SpriteDrawMode.Sliced; - BackGroundSprite.color = new Color(1, 1, 1, 0.399f); - BackGroundSprite.transform.localPosition = new Vector3(0, 0, 0); - - AllPlayerList = new GameObject("AllPlayer"); - AllPlayerList.transform.SetParent(VCHud.transform); - AllPlayerList.transform.localPosition = new Vector3(0, 0, -5); - POS = new Vector3(0, 0, -5); - - VCHud.AllGameObjectDo(n => n.layer = LayerUtils.GetUILayer()); - - var chatButton = GameObject.Find("ChatButton"); - chatButton.transform.localPosition = new Vector3(3.7f, 2.6f, -100); - var Buttons = GameObject.Find("Buttons"); - Buttons.transform.localPosition = new Vector3(-0.5f, 0, 0); - Buttons.transform.Find("BottomRight").localPosition = new Vector3(4.85f, -2.3f, -9); - } - - [HarmonyPatch(typeof(HudManager), nameof(HudManager.Update))] - [HarmonyPostfix] - public static void HudManagerUpdatePatch_Postfix(HudManager __instance) - { - if (!VCClinetTem) return; - - - UpdatePlayer(__instance); - } - - private static void UpdatePlayer(HudManager __instance) - { - foreach (var avatar in CachedPlayer.AllPlayers.Select(_ => new GameObject("Avatar"))) - { - avatar.transform.SetParent(AllPlayerList.transform); - /*avatar.transform.localPosition = Pos;*/ - var Border = new GameObject("Border"); - Border.transform.SetParent(avatar.transform); - Border.transform.localPosition = new Vector3(0, 0, 0); - var BorderSprite = Border.AddComponent(); - BorderSprite.sprite = SpriteUtils.LoadSpriteFromResources("NextShip.Resources.HeadBorder.png", 500f); - - AllPlayer.Add(avatar); - /*Pos.y -= 2;*/ - } - } -} \ No newline at end of file diff --git a/NextShip/main.cs b/NextShip/main.cs index 2557018..443d053 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -1,4 +1,3 @@ -using System; using System.Globalization; using System.Reflection; using BepInEx; @@ -9,10 +8,9 @@ using NextShip.Languages; using NextShip.Manager; using NextShip.Patches; -using NextShip.Roles; -using NextShip.UI.Components; using NextShip.UI.UIManager; -using UnityEngine; + +using BepInExLogger = BepInEx.Logging.Logger; [assembly: AssemblyFileVersion(Main.VersionString)] [assembly: AssemblyInformationalVersion(Main.VersionString)] @@ -21,7 +19,7 @@ namespace NextShip; [BepInPlugin(Id, ModName, VersionString)] [BepInProcess("Among Us.exe")] -public sealed class Main : BasePlugin +public sealed class NextShip : BasePlugin { // 模组名称 public const string ModName = "NextShip"; @@ -30,110 +28,51 @@ public sealed class Main : BasePlugin public const string Id = "cn.MengChu.NextShip"; // 模组版本 - public const string VersionString = "0.5.0"; - - // bilibili链接 - public const string bilibiliURL = "https://space.bilibili.com/394107547"; - - public const string QQURL = - "http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=OqTfMLjm7lMD5OMV68Rs9JLnbcXc-fDR&authKey=8tt0sNVVsfsGvOBFLNmtDA8CD7fweh%2Bbe1%2FMq2j62zGNWJ17Q%2FNXfG4c7r6JlN1S&noverify=0&group_code=815101721"; - - public const string QQNumber = "815101721"; + public const string VersionString = "100.0"; // Among Us游玩版本 - public static readonly AmongUsVersion SupportVersion = new(2023, 7, 21); - - public static readonly AmongUsVersion[] AmongUsSupportVersions = - { - SupportVersion - }; - - public static readonly string HashCode = HashUtils.GetFileMD5Hash(Paths.PluginPath.CombinePath($"{ModName}.dll")); - - // 模组构建时间 - public static string BuildTime = ""; - - // 是否为开发版本 - public static bool IsDev = true; - - internal static bool isCn; - internal static bool isChinese; - - public static readonly ShipVersion ShipVersion = new ShipVersion().Parse(VersionString); - public static Version Version = Version.Parse(VersionString); + public static readonly AmongUsVersion SupportVersion = new(2023, 10, 24); + + internal static ManualLogSource TISLog; - public static Main Instance; - - internal static UpdateTask UpdateTask; - internal static readonly ServerManager serverManager = DestroyableSingleton.Instance; - - // 模组主颜色 - public readonly Color ModColor = "#90c2f4".HTMLColorTo32(); - internal Harmony Harmony { get; } = new(Id); + + public static NextShip Instance; + + internal static readonly ServerManager serverManager = FastDestroyableSingleton.Instance; + private Harmony Harmony { get; } = new(Id); public override void Load() { - if (IsDev) - ConsoleTextFC(); - ConsoleManager.SetConsoleTitle("Among Us " + ModName + " Game"); - TISLog = BepInEx.Logging.Logger.CreateLogSource(ModName.RemoveBlank()); + TISLog = BepInExLogger.CreateLogSource(ModName.RemoveBlank()); - constInit(); + Init(); + Get(TISLog); Instance = this; Harmony.PatchAll(); FilesManager.Init(); ServerPath.autoAddServer(); - - var _Assembly = Assembly.GetExecutingAssembly(); - RegisterManager.Registration(_Assembly); - - UpdateTask = AddComponent(); + + RegisterManager.Registration(); + AddComponent(); - - Init(); + LanguagePack.Init(); - - UpdateTask.DontDestroyOnLoad(); - + CustomCosmeticsManager.LoadHat(); - - RegisterRoles(); - - VanillaManager.Load(); } - - private static void RegisterRoles() + private static void Init() { - var roles = new Role[] - { - new Postman() - }; - - Api.Roles.RoleManager.Get().RegisterRole(roles); - } - - private static void constInit() - { -#if RELEASE - IsDev = false; -#endif - var CountryName = RegionInfo.CurrentRegion.EnglishName; - isCn = CountryName.Contains("China"); //|| CountryName.Contains("Hong Kong") || CountryName.Contains("Taiwan"); - isChinese = (TranslationController.InstanceExists - ? TranslationController.Instance.currentLanguage.languageID - : SupportedLangs.English) is SupportedLangs.SChinese or SupportedLangs.TChinese; - - Info($"IsDev:{IsDev.ToString()}", "Const"); - Info($"CountryName:{CountryName} | {RegionInfo.CurrentRegion.DisplayName}", "Const"); - Info($"isCn:{isCn.ToString()}", "Const"); - Info($"IsChinese:{isChinese.ToString()}", "Const"); + Info("IsDev:{}", "Const"); + Info($"CountryName:| {RegionInfo.CurrentRegion.DisplayName}", "Const"); + Info("isCn:", "Const"); + Info($"IsChinese:", "Const"); Info($"Support Among Us Version {SupportVersion}", "Info"); - Info($"Hash: {HashCode}", "Info"); + Info($"Hash: ", "Info"); Info($"欢迎游玩{ModName} | Welcome to{ModName}", "Info"); } } \ No newline at end of file From 4691d6c9106f11dbf0d791f7d4ef6852346e2801 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Sun, 3 Dec 2023 05:21:00 +0800 Subject: [PATCH 02/29] =?UTF-8?q?IDE=E6=A0=BC=E5=BC=8F=E5=8C=96=E6=B8=85?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NextShip.Api/Bases/ShipPlugin.cs | 1 - NextShip.Api/Config/CosmeticsConfig.cs | 5 ++- NextShip.Api/Interfaces/IEventManager.cs | 4 +-- NextShip.Api/Interfaces/ILang.cs | 1 - NextShip.Api/Interfaces/INextEvent.cs | 4 +-- NextShip.Api/Interfaces/INextService.cs | 4 +-- NextShip.Api/Logs/Log.cs | 8 ++--- NextShip.Api/NextShip.Api.csproj | 12 +++---- NextShip.Api/Plugins/INextPlugin.cs | 20 ++++++++--- NextShip.Api/Roles/RoleBase.cs | 2 +- NextShip.Api/Roles/RoleManager.Assaign.cs | 2 +- NextShip.Api/Roles/RoleManager.cs | 2 -- NextShip.Api/Roles/SimpleRoleInfo.cs | 2 +- .../SourceGenerators/LangSourceGenerator.cs | 3 -- NextShip.Api/Utils/StreamUtils.cs | 1 - NextShip/Cosmetics/CustomCosmeticsManager.cs | 2 +- NextShip/DIY/Addons/AddonsManager.cs | 1 - NextShip/DIY/Plugins/PluginManager.cs | 4 +-- NextShip/Languages/LanguagePack.cs | 2 +- NextShip/Manager/EventManager.cs | 4 +-- NextShip/NextService.cs | 33 +++++++++++-------- NextShip/NextShip.csproj | 4 +-- NextShip/Options/DefaultOption.cs | 1 - NextShip/Options/OptionManager.cs | 1 - NextShip/Patches/ServerPath.cs | 6 ++-- NextShip/UI/Components/DownMenu.cs | 1 - NextShip/UI/Components/NextMenuOption.cs | 1 - NextShip/UI/Components/ShipOptionBehaviour.cs | 1 - NextShip/UI/UIManager/NextUIManager.cs | 1 - NextShip/main.cs | 21 ++++++------ 30 files changed, 75 insertions(+), 79 deletions(-) diff --git a/NextShip.Api/Bases/ShipPlugin.cs b/NextShip.Api/Bases/ShipPlugin.cs index c686a4c..d08326d 100644 --- a/NextShip.Api/Bases/ShipPlugin.cs +++ b/NextShip.Api/Bases/ShipPlugin.cs @@ -1,6 +1,5 @@ namespace NextShip.Api.Bases; - public abstract class ShipPlugin { public List PluginCompatibilities = new(); diff --git a/NextShip.Api/Config/CosmeticsConfig.cs b/NextShip.Api/Config/CosmeticsConfig.cs index 4e44d78..1e87532 100644 --- a/NextShip.Api/Config/CosmeticsConfig.cs +++ b/NextShip.Api/Config/CosmeticsConfig.cs @@ -1,10 +1,9 @@ -using NextShip.Api.Enums; - namespace NextShip.Api.Config; public class CosmeticsConfig { - public CosmeticsConfig(CosmeticRepoType cosmeticRepoType, CosmeticType cosmeticType, CosmeticLoadType cosmeticLoadType, string repoName, string repoURL) + public CosmeticsConfig(CosmeticRepoType cosmeticRepoType, CosmeticType cosmeticType, + CosmeticLoadType cosmeticLoadType, string repoName, string repoURL) { CosmeticRepoType = cosmeticRepoType; CosmeticType = cosmeticType; diff --git a/NextShip.Api/Interfaces/IEventManager.cs b/NextShip.Api/Interfaces/IEventManager.cs index 15846ba..aa83608 100644 --- a/NextShip.Api/Interfaces/IEventManager.cs +++ b/NextShip.Api/Interfaces/IEventManager.cs @@ -4,7 +4,7 @@ public interface IEventManager { // 注册事件 public void RegisterEvent(INextEvent @event); - - + + public void UnRegisterEvent(INextEvent @event); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILang.cs b/NextShip.Api/Interfaces/ILang.cs index ce934ce..9c49236 100644 --- a/NextShip.Api/Interfaces/ILang.cs +++ b/NextShip.Api/Interfaces/ILang.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public class ILang { - } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextEvent.cs b/NextShip.Api/Interfaces/INextEvent.cs index 6a416c3..fa4cb85 100644 --- a/NextShip.Api/Interfaces/INextEvent.cs +++ b/NextShip.Api/Interfaces/INextEvent.cs @@ -4,7 +4,7 @@ public interface INextEvent { public string EventName { get; set; } - public void OnRegister(IEventManager @eventManager); + public void OnRegister(IEventManager eventManager); - public void OnUnRegister(IEventManager @eventManager); + public void OnUnRegister(IEventManager eventManager); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextService.cs b/NextShip.Api/Interfaces/INextService.cs index 0fd23f8..ac0406d 100644 --- a/NextShip.Api/Interfaces/INextService.cs +++ b/NextShip.Api/Interfaces/INextService.cs @@ -3,8 +3,8 @@ namespace NextShip.Api.Interfaces; public interface INextService { public void Build(); - + public void Rebuild(); - + public void Reset(); } \ No newline at end of file diff --git a/NextShip.Api/Logs/Log.cs b/NextShip.Api/Logs/Log.cs index d1c2654..4f8078e 100644 --- a/NextShip.Api/Logs/Log.cs +++ b/NextShip.Api/Logs/Log.cs @@ -5,12 +5,10 @@ namespace NextShip.Api.Logs; public sealed class log { - public ManualLogSource LogSource { get; private set; } + public static bool CreateEd; public readonly TextWriter Writer = null!; - public static bool CreateEd; - static log() { System.Console.OutputEncoding = Encoding.UTF8; @@ -22,6 +20,8 @@ private log(ManualLogSource logSource) Instance = this; } + public ManualLogSource LogSource { get; private set; } + public static log Instance { get; set; } public static log Get(ManualLogSource logSource) @@ -31,7 +31,7 @@ public static log Get(ManualLogSource logSource) Instance.Set(logSource); return Instance; } - + var _log = new log(logSource); CreateEd = true; return _log; diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index 3915853..b024820 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -16,13 +16,13 @@ - all - runtime; build; native; contentfiles; analyzers; buildtransitive + all + runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + + diff --git a/NextShip.Api/Plugins/INextPlugin.cs b/NextShip.Api/Plugins/INextPlugin.cs index 44a92a7..6d09398 100644 --- a/NextShip.Api/Plugins/INextPlugin.cs +++ b/NextShip.Api/Plugins/INextPlugin.cs @@ -2,11 +2,21 @@ namespace NextShip.Api.Plugins; public interface INextPlugin { - public void OnLoad() {} + public void OnLoad() + { + } - public virtual bool OnEnable() => true; - - public virtual bool OnDisable() => true; + public bool OnEnable() + { + return true; + } - public void OnUnload() {} + public bool OnDisable() + { + return true; + } + + public void OnUnload() + { + } } \ No newline at end of file diff --git a/NextShip.Api/Roles/RoleBase.cs b/NextShip.Api/Roles/RoleBase.cs index 08ef05d..365bc40 100644 --- a/NextShip.Api/Roles/RoleBase.cs +++ b/NextShip.Api/Roles/RoleBase.cs @@ -13,7 +13,7 @@ protected RoleBase(PlayerControl? player) Active = true; RoleManager.Get().AllRoleBases.Add(this); } - + public PlayerControl? Player { get; private set; } public Func WinCheck { get; } diff --git a/NextShip.Api/Roles/RoleManager.Assaign.cs b/NextShip.Api/Roles/RoleManager.Assaign.cs index 03e7184..6971beb 100644 --- a/NextShip.Api/Roles/RoleManager.Assaign.cs +++ b/NextShip.Api/Roles/RoleManager.Assaign.cs @@ -34,7 +34,7 @@ public bool Get(PlayerControl player, out RoleBase? role) return role != null; } - + public void Restore() { diff --git a/NextShip.Api/Roles/RoleManager.cs b/NextShip.Api/Roles/RoleManager.cs index d73cf43..55332e7 100644 --- a/NextShip.Api/Roles/RoleManager.cs +++ b/NextShip.Api/Roles/RoleManager.cs @@ -1,5 +1,3 @@ -using HarmonyLib; - namespace NextShip.Api.Roles; public partial class RoleManager diff --git a/NextShip.Api/Roles/SimpleRoleInfo.cs b/NextShip.Api/Roles/SimpleRoleInfo.cs index 6a449dc..6ee1e25 100644 --- a/NextShip.Api/Roles/SimpleRoleInfo.cs +++ b/NextShip.Api/Roles/SimpleRoleInfo.cs @@ -21,7 +21,7 @@ public SimpleRoleInfo string roleStringId, string roleName, int roleIntId - ) + ) { RoleColor = color; Name = roleName; diff --git a/NextShip.Api/SourceGenerators/LangSourceGenerator.cs b/NextShip.Api/SourceGenerators/LangSourceGenerator.cs index e32afe6..28949ea 100644 --- a/NextShip.Api/SourceGenerators/LangSourceGenerator.cs +++ b/NextShip.Api/SourceGenerators/LangSourceGenerator.cs @@ -1,8 +1,5 @@ -using Microsoft.CodeAnalysis; - namespace NextShip.Api.SourceGenerators; - /*[Generator(LanguageNames.CSharp)] public class LangSourceGenerator : IIncrementalGenerator { diff --git a/NextShip.Api/Utils/StreamUtils.cs b/NextShip.Api/Utils/StreamUtils.cs index 7a7cf29..033ac30 100644 --- a/NextShip.Api/Utils/StreamUtils.cs +++ b/NextShip.Api/Utils/StreamUtils.cs @@ -4,7 +4,6 @@ using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; -using NextShip.Api.Attributes; using SeekOrigin = Il2CppSystem.IO.SeekOrigin; namespace NextShip.Api.Utils; diff --git a/NextShip/Cosmetics/CustomCosmeticsManager.cs b/NextShip/Cosmetics/CustomCosmeticsManager.cs index 46e82e5..2217eb1 100644 --- a/NextShip/Cosmetics/CustomCosmeticsManager.cs +++ b/NextShip/Cosmetics/CustomCosmeticsManager.cs @@ -112,4 +112,4 @@ public static void AddToList(HatManager __instance) __instance.allHats = list.ToArray(); } } -} +} \ No newline at end of file diff --git a/NextShip/DIY/Addons/AddonsManager.cs b/NextShip/DIY/Addons/AddonsManager.cs index d850612..ff00e72 100644 --- a/NextShip/DIY/Addons/AddonsManager.cs +++ b/NextShip/DIY/Addons/AddonsManager.cs @@ -1,5 +1,4 @@ using NextShip.Api.Bases; -using NextShip.Manager; namespace NextShip.Addons; diff --git a/NextShip/DIY/Plugins/PluginManager.cs b/NextShip/DIY/Plugins/PluginManager.cs index 90308f0..4cc5bca 100644 --- a/NextShip/DIY/Plugins/PluginManager.cs +++ b/NextShip/DIY/Plugins/PluginManager.cs @@ -65,9 +65,9 @@ private void Load(string path) var plugin = (ShipPlugin)assembly.CreateInstance(n.FullName!); if (plugin == null) return; - + var shipPluginInfo = n.GetCustomAttribute(); - if (shipPluginInfo != null) + if (shipPluginInfo != null) plugin.ShipPluginInfo = shipPluginInfo; var Compatibilities = n.GetCustomAttributes(); diff --git a/NextShip/Languages/LanguagePack.cs b/NextShip/Languages/LanguagePack.cs index b3cfc44..307b3ce 100644 --- a/NextShip/Languages/LanguagePack.cs +++ b/NextShip/Languages/LanguagePack.cs @@ -31,7 +31,7 @@ public class LanguagePack private static readonly Dictionary defaultLanguageSet = new(); public Dictionary languageSet; - + //初始化 public static void Init() diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs index c4bd0bf..73c86c7 100644 --- a/NextShip/Manager/EventManager.cs +++ b/NextShip/Manager/EventManager.cs @@ -8,7 +8,7 @@ namespace NextShip.Manager; public class EventManager : IEventManager { private readonly List RegisterEvents = new(); - + public void RegisterEvent(INextEvent @event) { @event.OnRegister(this); @@ -37,7 +37,7 @@ public T GetEvent() where T : INextEvent { return (T)RegisterEvents.FirstOrDefault(n => n is T); } - + public INextEvent GetEvent(Type type) { return RegisterEvents.FirstOrDefault(n => n.GetType() == type); diff --git a/NextShip/NextService.cs b/NextShip/NextService.cs index d302308..94729a4 100644 --- a/NextShip/NextService.cs +++ b/NextShip/NextService.cs @@ -6,25 +6,14 @@ namespace NextShip; public class NextService : INextService { + private ServiceCollection _collection = new(); public IServiceProvider _Provider { get; private set; } - private ServiceCollection _collection = new (); - private bool BuildCompleted { get; set; } - public NextService Set(ServiceCollection collection) - { - _collection = collection; - return this; - } - - public T Get() => _Provider.GetService(); - - public object Get(Type type) => _Provider.GetService(type); - public void Build() { - if(BuildCompleted) return; + if (BuildCompleted) return; if (_collection.Count != 0) { @@ -36,7 +25,7 @@ public void Build() _Provider = collection.BuildServiceProvider(); } - + public void Rebuild() { @@ -51,6 +40,22 @@ public void Reset() BuildCompleted = false; } + public NextService Set(ServiceCollection collection) + { + _collection = collection; + return this; + } + + public T Get() + { + return _Provider.GetService(); + } + + public object Get(Type type) + { + return _Provider.GetService(type); + } + public static NextService Build(ServiceCollection collection) { var _Service = new NextService().Set(collection); diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index 9cf75e8..98354ce 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -38,8 +38,8 @@ - - + + diff --git a/NextShip/Options/DefaultOption.cs b/NextShip/Options/DefaultOption.cs index d915d2b..5923e69 100644 --- a/NextShip/Options/DefaultOption.cs +++ b/NextShip/Options/DefaultOption.cs @@ -1,5 +1,4 @@ using NextShip.Api.Attributes; -using NextShip.Api.Utilities.Attributes; namespace NextShip.Options; diff --git a/NextShip/Options/OptionManager.cs b/NextShip/Options/OptionManager.cs index c02b492..8df2a5b 100644 --- a/NextShip/Options/OptionManager.cs +++ b/NextShip/Options/OptionManager.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using HarmonyLib; using NextShip.Api.Attributes; -using NextShip.Api.Utilities.Attributes; namespace NextShip.Options; diff --git a/NextShip/Patches/ServerPath.cs b/NextShip/Patches/ServerPath.cs index 03a852c..fd1353c 100644 --- a/NextShip/Patches/ServerPath.cs +++ b/NextShip/Patches/ServerPath.cs @@ -16,15 +16,13 @@ public static void autoAddServer() createHttp("www.aumods.xyz", "Modded NA (MNA)", 443, true), createHttp("au-eu.duikbo.at", "Modded EU (MEU)", 443, true) }; - - + foreach (var r in regionInfos) { if (Main.serverManager.AvailableRegions.Contains(r)) continue; Main.serverManager.AddOrUpdateRegion(r); } - } public static IRegionInfo createHttp(string ip, string name, ushort port, bool ishttps) @@ -34,7 +32,7 @@ public static IRegionInfo createHttp(string ip, string name, ushort port, bool i ServerInfo[] ServerInfo = { serverInfo }; return new StaticHttpRegionInfo(name, StringNames.NoTranslation, ip, ServerInfo).CastFast(); } - + private static bool IsVanilla(this IRegionInfo regionInfo) { diff --git a/NextShip/UI/Components/DownMenu.cs b/NextShip/UI/Components/DownMenu.cs index 5c606c4..5467ac2 100644 --- a/NextShip/UI/Components/DownMenu.cs +++ b/NextShip/UI/Components/DownMenu.cs @@ -1,5 +1,4 @@ using NextShip.Api.Attributes; -using NextShip.Api.Utilities.Attributes; using UnityEngine; namespace NextShip.UI.Components; diff --git a/NextShip/UI/Components/NextMenuOption.cs b/NextShip/UI/Components/NextMenuOption.cs index f89f943..a2cffe8 100644 --- a/NextShip/UI/Components/NextMenuOption.cs +++ b/NextShip/UI/Components/NextMenuOption.cs @@ -1,5 +1,4 @@ using NextShip.Api.Attributes; -using NextShip.Api.Utilities.Attributes; using NextShip.Options; using UnityEngine; diff --git a/NextShip/UI/Components/ShipOptionBehaviour.cs b/NextShip/UI/Components/ShipOptionBehaviour.cs index 343b8b9..8152a93 100644 --- a/NextShip/UI/Components/ShipOptionBehaviour.cs +++ b/NextShip/UI/Components/ShipOptionBehaviour.cs @@ -1,6 +1,5 @@ using System; using NextShip.Api.Attributes; -using NextShip.Api.Utilities.Attributes; using NextShip.Options; using TMPro; using UnityEngine; diff --git a/NextShip/UI/UIManager/NextUIManager.cs b/NextShip/UI/UIManager/NextUIManager.cs index 14047a2..50aaf7d 100644 --- a/NextShip/UI/UIManager/NextUIManager.cs +++ b/NextShip/UI/UIManager/NextUIManager.cs @@ -1,5 +1,4 @@ using NextShip.Api.Attributes; -using NextShip.Api.Utilities.Attributes; using UnityEngine; namespace NextShip.UI.UIManager; diff --git a/NextShip/main.cs b/NextShip/main.cs index 443d053..7c68e8e 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -9,7 +9,6 @@ using NextShip.Manager; using NextShip.Patches; using NextShip.UI.UIManager; - using BepInExLogger = BepInEx.Logging.Logger; [assembly: AssemblyFileVersion(Main.VersionString)] @@ -32,12 +31,12 @@ public sealed class NextShip : BasePlugin // Among Us游玩版本 public static readonly AmongUsVersion SupportVersion = new(2023, 10, 24); - - + + internal static ManualLogSource TISLog; - + public static NextShip Instance; - + internal static readonly ServerManager serverManager = FastDestroyableSingleton.Instance; private Harmony Harmony { get; } = new(Id); @@ -55,13 +54,13 @@ public override void Load() FilesManager.Init(); ServerPath.autoAddServer(); - + RegisterManager.Registration(); - + AddComponent(); - + LanguagePack.Init(); - + CustomCosmeticsManager.LoadHat(); } @@ -70,9 +69,9 @@ private static void Init() Info("IsDev:{}", "Const"); Info($"CountryName:| {RegionInfo.CurrentRegion.DisplayName}", "Const"); Info("isCn:", "Const"); - Info($"IsChinese:", "Const"); + Info("IsChinese:", "Const"); Info($"Support Among Us Version {SupportVersion}", "Info"); - Info($"Hash: ", "Info"); + Info("Hash: ", "Info"); Info($"欢迎游玩{ModName} | Welcome to{ModName}", "Info"); } } \ No newline at end of file From 527014f39bce28c8a4da686730819c3bb524f93d Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Tue, 5 Dec 2023 21:07:54 +0800 Subject: [PATCH 03/29] Update --- NextShip.Api/Attributes/LoadAttribute.cs | 9 +- NextShip.Api/Enums/LoadMode.cs | 10 ++ NextShip.Api/GlobalUsing.cs | 3 +- NextShip.Api/Interfaces/ILang.cs | 11 +- NextShip.Api/Interfaces/ILangManager.cs | 7 +- NextShip.Api/Interfaces/ILoadManager.cs | 6 ++ NextShip.Api/Logs/FastLog.cs | 63 +++++++++++ NextShip.Api/Logs/Log.cs | 131 ++++++++++++----------- NextShip.Api/Managers/PatchManager.cs | 6 ++ NextShip.Api/Services/DownloadService.cs | 6 ++ NextShip/Cosmetics/CosmeticsChecks.cs | 2 +- NextShip/DIY/Plugins/PluginManager.cs | 1 - NextShip/GlobalUsing.cs | 1 + NextShip/Manager/RegisterManager.cs | 1 - NextShip/Updates/DownLoadManager.cs | 21 ---- NextShip/Updates/ModUpdater.cs | 13 +-- NextShip/Updates/VersionManager.cs | 12 +-- 17 files changed, 192 insertions(+), 111 deletions(-) create mode 100644 NextShip.Api/Enums/LoadMode.cs create mode 100644 NextShip.Api/Interfaces/ILoadManager.cs create mode 100644 NextShip.Api/Logs/FastLog.cs create mode 100644 NextShip.Api/Managers/PatchManager.cs create mode 100644 NextShip.Api/Services/DownloadService.cs delete mode 100644 NextShip/Updates/DownLoadManager.cs diff --git a/NextShip.Api/Attributes/LoadAttribute.cs b/NextShip.Api/Attributes/LoadAttribute.cs index b446f50..8ff4406 100644 --- a/NextShip.Api/Attributes/LoadAttribute.cs +++ b/NextShip.Api/Attributes/LoadAttribute.cs @@ -1,11 +1,18 @@ using System.Collections; using System.Reflection; -namespace NextShip.Api.Utilities.Attributes; +namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor)] public sealed class LoadAttribute : Attribute { + public readonly LoadMode Mode; + + public LoadAttribute(LoadMode mode = LoadMode.Load) + { + Mode = mode; + } + public static void Registration(Type type) { Info("Start Registration", filename: MethodUtils.GetClassName()); diff --git a/NextShip.Api/Enums/LoadMode.cs b/NextShip.Api/Enums/LoadMode.cs new file mode 100644 index 0000000..0e28176 --- /dev/null +++ b/NextShip.Api/Enums/LoadMode.cs @@ -0,0 +1,10 @@ +namespace NextShip.Api.Enums; + +public enum LoadMode +{ + PreLoad, + FastLoad, + Load, + LastLoad, + CompleteLoad +} \ No newline at end of file diff --git a/NextShip.Api/GlobalUsing.cs b/NextShip.Api/GlobalUsing.cs index f91427b..e64e86c 100644 --- a/NextShip.Api/GlobalUsing.cs +++ b/NextShip.Api/GlobalUsing.cs @@ -5,4 +5,5 @@ global using NextShip.Api.Enums; global using NextShip.Api.Bases; global using NextShip.Api.Attributes; -global using static NextShip.Api.Logs.log; \ No newline at end of file +global using NextShip.Api.Logs; +global using static NextShip.Api.Logs.FastLog; \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILang.cs b/NextShip.Api/Interfaces/ILang.cs index 9c49236..ffdb1b7 100644 --- a/NextShip.Api/Interfaces/ILang.cs +++ b/NextShip.Api/Interfaces/ILang.cs @@ -1,5 +1,14 @@ namespace NextShip.Api.Interfaces; -public class ILang +public interface ILang { + public SupportedLangs LangId { get; protected set; } + + public string LangName { get; set; } + + public string GetString(string Key); + + public string GetStringOfIndex(int Index); + + public void Init(); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILangManager.cs b/NextShip.Api/Interfaces/ILangManager.cs index fe11d06..a23e29c 100644 --- a/NextShip.Api/Interfaces/ILangManager.cs +++ b/NextShip.Api/Interfaces/ILangManager.cs @@ -1,5 +1,10 @@ namespace NextShip.Api.Interfaces; -public class ILangManager +public interface ILangManager { + public void RegisterLang(ILang lang); + + public void UnRegisterLang(ILang lang); + + public void SetLang(SupportedLangs langId, ILang lang); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILoadManager.cs b/NextShip.Api/Interfaces/ILoadManager.cs new file mode 100644 index 0000000..c2c8f1a --- /dev/null +++ b/NextShip.Api/Interfaces/ILoadManager.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public interface ILoadManager +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Logs/FastLog.cs b/NextShip.Api/Logs/FastLog.cs new file mode 100644 index 0000000..54853a3 --- /dev/null +++ b/NextShip.Api/Logs/FastLog.cs @@ -0,0 +1,63 @@ +using BepInEx.Logging; + +namespace NextShip.Api.Logs; + +public static class FastLog +{ + /* + 各消息作用: + + 发生了致命错误,无法从中恢复 : A fatal error has occurred, which cannot be recovered from + Fatal + + 发生错误,但可以从中恢复 : An error has occured, but can be recovered from + Error + + 已发出警告,但并不一定意味着发生了错误 : A warning has been produced, but does not necessarily mean that something wrong has happened + Warning + + 应向用户显示的重要消息 : An important message that should be displayed to the user + Message + + 重要性较低的消息 : A message of low importance + Info + + 可能只有开发人员感兴趣的消息 : A message that would likely only interest a developer + Debug, + */ + + public static void Info(string text, string? tag = null, string? filename = null) + { + log.Instance?.SendToFile(tag, filename, text); + } + + public static void Warn(string text, string? tag = null, string? filename = null) + { + log.Instance?.SendToFile(tag, filename, text, LogLevel.Warning); + } + + public static void Error(string text, string? tag = null, string? filename = null) + { + log.Instance?.SendToFile(tag, filename, text, LogLevel.Error); + } + + public static void Fatal(string text, string? tag = null, string? filename = null) + { + log.Instance?.SendToFile(tag, filename, text, LogLevel.Fatal); + } + + public static void Msg(string text, string? tag = null, string? filename = null) + { + log.Instance?.SendToFile(tag, filename, text, LogLevel.Message); + } + + public static void Exception(Exception ex, string? tag = null, string? filename = null) + { + log.Instance?.SendToFile(tag, filename, ex.ToString(), LogLevel.Error); + } + + public static void Debug(string text, string? tag = null, string? filename = null) + { + log.Instance?.SendToFile(tag, filename, text, LogLevel.Debug); + } +} \ No newline at end of file diff --git a/NextShip.Api/Logs/Log.cs b/NextShip.Api/Logs/Log.cs index 4f8078e..9a6a9bd 100644 --- a/NextShip.Api/Logs/Log.cs +++ b/NextShip.Api/Logs/Log.cs @@ -1,4 +1,5 @@ using System.Text; +using BepInEx; using BepInEx.Logging; namespace NextShip.Api.Logs; @@ -7,7 +8,9 @@ public sealed class log { public static bool CreateEd; - public readonly TextWriter Writer = null!; + public StreamWriter? DiskWriter; + + public TextWriter? ConsoleWriter; static log() { @@ -17,18 +20,67 @@ static log() private log(ManualLogSource logSource) { LogSource = logSource; + ConsoleWriter = ConsoleManager.ConsoleStream; Instance = this; } + + public void CreateDiskLog(string name, string? path = null) + { + var stream = GetDiskLogStream(name, path); + DiskWriter = new StreamWriter(stream); + DiskWriter.AutoFlush = true; + + DiskWriter.WriteLine($"Next Ship Api Disk Log OutTime:{DateTime.Now:g}"); + } + + public Stream GetDiskLogStream(string name, string? path = null, bool outTime = false) + { + if (outTime) + { + var timeString = DateTime.Now.ToString("g") + .Replace("/", "-").Replace(" ", "-").Trim(); + name = $"{name}_{timeString}.log"; + } + + path ??= string.Empty; + + var FilePath = path + name; + + if (!File.Exists(FilePath)) + return File.Create(FilePath); + + Stream stream; + var count = 0; + + while (true) + { + count++; + FilePath = path + name + $"_{count}"; + + if (!File.Exists(FilePath)) + { + stream = File.Create(FilePath); + break; + } + + stream = File.Open(FilePath, FileMode.Open); + if (stream.Length == 0) + break; + } + + return stream; + } + public ManualLogSource LogSource { get; private set; } - public static log Instance { get; set; } + public static log? Instance { get; set; } - public static log Get(ManualLogSource logSource) + public static log? Get(ManualLogSource logSource) { if (CreateEd) { - Instance.Set(logSource); + Instance?.Set(logSource); return Instance; } @@ -43,14 +95,22 @@ private void Set(ManualLogSource logSource) LogSource = logSource; } - private void SendToFile(string? tag, string? filename, string text, LogLevel level = LogLevel.Info) + internal void SendToFile(string? tag, string? filename, string text, LogLevel level = LogLevel.Info) { var logger = Instance?.LogSource; + var t = DateTime.Now.ToString("HH:mm:ss"); + var log_text = $"[{t}]"; - if (tag != null) log_text += $"[{tag}]"; - if (filename != null) log_text += $"[{filename}]"; + + if (tag != null) + log_text += $"[{tag}]"; + + if (filename != null) + log_text += $"[{filename}]"; + log_text += text; + switch (level) { case LogLevel.Info: @@ -82,61 +142,4 @@ private void SendToFile(string? tag, string? filename, string text, LogLevel lev break; } } - - /* - 各消息作用: - - 发生了致命错误,无法从中恢复 : A fatal error has occurred, which cannot be recovered from - Fatal - - 发生错误,但可以从中恢复 : An error has occured, but can be recovered from - Error - - 已发出警告,但并不一定意味着发生了错误 : A warning has been produced, but does not necessarily mean that something wrong has happened - Warning - - 应向用户显示的重要消息 : An important message that should be displayed to the user - Message - - 重要性较低的消息 : A message of low importance - Info - - 可能只有开发人员感兴趣的消息 : A message that would likely only interest a developer - Debug, - */ - - public static void Info(string text, string? tag = null, string? filename = null) - { - Instance?.SendToFile(tag, filename, text); - } - - public static void Warn(string text, string? tag = null, string? filename = null) - { - Instance?.SendToFile(tag, filename, text, LogLevel.Warning); - } - - public static void Error(string text, string? tag = null, string? filename = null) - { - Instance?.SendToFile(tag, filename, text, LogLevel.Error); - } - - public static void Fatal(string text, string? tag = null, string? filename = null) - { - Instance?.SendToFile(tag, filename, text, LogLevel.Fatal); - } - - public static void Msg(string text, string? tag = null, string? filename = null) - { - Instance?.SendToFile(tag, filename, text, LogLevel.Message); - } - - public static void Exception(Exception ex, string? tag = null, string? filename = null) - { - Instance?.SendToFile(tag, filename, ex.ToString(), LogLevel.Error); - } - - public static void Debug(string text, string? tag = null, string? filename = null) - { - Instance?.SendToFile(tag, filename, text, LogLevel.Debug); - } } \ No newline at end of file diff --git a/NextShip.Api/Managers/PatchManager.cs b/NextShip.Api/Managers/PatchManager.cs new file mode 100644 index 0000000..3cabb0a --- /dev/null +++ b/NextShip.Api/Managers/PatchManager.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Managers; + +public class PatchManager +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Services/DownloadService.cs b/NextShip.Api/Services/DownloadService.cs new file mode 100644 index 0000000..6c76054 --- /dev/null +++ b/NextShip.Api/Services/DownloadService.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Services; + +public class DownloadService +{ + +} \ No newline at end of file diff --git a/NextShip/Cosmetics/CosmeticsChecks.cs b/NextShip/Cosmetics/CosmeticsChecks.cs index 798615f..0e0be10 100644 --- a/NextShip/Cosmetics/CosmeticsChecks.cs +++ b/NextShip/Cosmetics/CosmeticsChecks.cs @@ -1,6 +1,6 @@ using System.Collections; using System.IO; -using NextShip.Api.Utilities.Attributes; +using NextShip.Api.Attributes; namespace NextShip.Cosmetics; diff --git a/NextShip/DIY/Plugins/PluginManager.cs b/NextShip/DIY/Plugins/PluginManager.cs index 4cc5bca..fb02544 100644 --- a/NextShip/DIY/Plugins/PluginManager.cs +++ b/NextShip/DIY/Plugins/PluginManager.cs @@ -6,7 +6,6 @@ using HarmonyLib; using NextShip.Api.Attributes; using NextShip.Api.Bases; -using NextShip.Api.Utilities.Attributes; using NextShip.Manager; namespace NextShip.DIY.Plugins; diff --git a/NextShip/GlobalUsing.cs b/NextShip/GlobalUsing.cs index 03350c6..10c855b 100644 --- a/NextShip/GlobalUsing.cs +++ b/NextShip/GlobalUsing.cs @@ -3,4 +3,5 @@ global using NextShip.Api.Roles; global using NextShip.Api.Utilities; global using static NextShip.Api.Logs.log; +global using static NextShip.Api.Logs.FastLog; global using Main = NextShip.NextShip; \ No newline at end of file diff --git a/NextShip/Manager/RegisterManager.cs b/NextShip/Manager/RegisterManager.cs index 9f7b03a..b25e7c8 100644 --- a/NextShip/Manager/RegisterManager.cs +++ b/NextShip/Manager/RegisterManager.cs @@ -2,7 +2,6 @@ using System.Reflection; using HarmonyLib; using NextShip.Api.Attributes; -using NextShip.Api.Utilities.Attributes; namespace NextShip.Manager; diff --git a/NextShip/Updates/DownLoadManager.cs b/NextShip/Updates/DownLoadManager.cs deleted file mode 100644 index 3987fc2..0000000 --- a/NextShip/Updates/DownLoadManager.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace NextShip.Updates; - -public class DownLoadManager -{ - public static DownLoadManager Instance { get; private set; } - - public static DownLoadManager Get() - { - return Instance ??= new DownLoadManager(); - } - - public void Download(string url, string fileName, string filePath, DownLoadMode mode = DownLoadMode.Http) - { - } -} - -public enum DownLoadMode -{ - Http, - Downloader -} \ No newline at end of file diff --git a/NextShip/Updates/ModUpdater.cs b/NextShip/Updates/ModUpdater.cs index 6c24989..5222977 100644 --- a/NextShip/Updates/ModUpdater.cs +++ b/NextShip/Updates/ModUpdater.cs @@ -1,4 +1,3 @@ -global using NextShip.Updates; using System.Threading.Tasks; using BepInEx.Configuration; @@ -7,20 +6,14 @@ namespace NextShip.Updates; public class ModUpdater { // HUdate=HasUpdate 判断是否有更新 - public static bool HUpdate = VersionManager.HUpdate; + public static bool HUpdate = VersionManager.HasUpdate; + public static ConfigEntry AutoUpdate; // 模组下载链接 public string ModDownloadURL; - - public ModUpdater(string modDownloadURL) - { - ModDownloadURL = modDownloadURL; - } - - public Task UpdateMod() + public async Task UpdateMod() { - return Task.FromResult(true); } } \ No newline at end of file diff --git a/NextShip/Updates/VersionManager.cs b/NextShip/Updates/VersionManager.cs index 36a5959..7d238fc 100644 --- a/NextShip/Updates/VersionManager.cs +++ b/NextShip/Updates/VersionManager.cs @@ -10,8 +10,7 @@ public enum Download Github, Gitee, Jsdelivr, - Nightly, - Alist + Nightly } // Github链接 @@ -26,24 +25,20 @@ public enum Download // 构建件存放 public const string nightlyUrl = "https://nightly.link/NextShipAU/NextShip/workflows/Build-Release/main"; - // 服务器alist - public const string alistUrl = "http://pan.pafyx.top/TIS"; - // 2018k.cnAPI public const string KApiUrl = "http://api.2018k.cn"; public const string KApiId = "FC912F87DE524E5393F6F35B66B8ACEB"; // HUdate=HasUpdate 判断是否有更新 - public static bool HUpdate; + public static bool HasUpdate; public static readonly List<(string, Download)> URLs = new() { (GithubUrl, Download.Github), (GiteeUrl, Download.Gitee), (jsdelivrUrl, Download.Jsdelivr), - (nightlyUrl, Download.Nightly), - (alistUrl, Download.Alist) + (nightlyUrl, Download.Nightly) }; public static ShipVersion lastVersion; @@ -109,7 +104,6 @@ public static Dictionary GetDownLoadUrlPingInfo() { { Download.Github, PingUtils.Ping("github.com") }, { Download.Gitee, PingUtils.Ping("Gitee.com") }, - { Download.Alist, PingUtils.Ping("pan.pafyx.top") }, { Download.Nightly, PingUtils.Ping("nightly.link") }, { Download.Jsdelivr, PingUtils.Ping("jsdelivr.net") } }; From 1e51d2c61f87f3e26be7873ced481f60f370cdb0 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Tue, 5 Dec 2023 21:08:21 +0800 Subject: [PATCH 04/29] =?UTF-8?q?=E5=B0=9D=E8=AF=95=E6=9B=B4=E6=94=B9?= =?UTF-8?q?=E4=B8=BAnet8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NextShip.Api/NextShip.Api.csproj | 2 +- NextShip/NextShip.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index b024820..b0cc4f2 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -1,7 +1,7 @@ - net6.0 + net8.0 enable enable NextShip.Api diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index 98354ce..949636d 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -1,6 +1,6 @@ - net6.0 + net8.0 1.0.0 latest embedded From 424e4dc274527ac01272f61763fc02158029d86f Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Tue, 5 Dec 2023 21:16:22 +0800 Subject: [PATCH 05/29] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=8C=85=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NextShip.Api/NextShip.Api.csproj | 12 ++++++------ NextShip/NextShip.csproj | 8 +------- global.json | 7 +++++++ 3 files changed, 14 insertions(+), 13 deletions(-) create mode 100644 global.json diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index b0cc4f2..d3d0982 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -8,22 +8,22 @@ 1.0.0 APIReadme.md true - true - + - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index 949636d..45df0b7 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -28,7 +28,7 @@ - + @@ -37,12 +37,6 @@ - - - - - - diff --git a/global.json b/global.json new file mode 100644 index 0000000..dad2db5 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "8.0.0", + "rollForward": "latestMajor", + "allowPrerelease": true + } +} \ No newline at end of file From ff6d45fa95078fc5ac2e9ff1f01a75a839171d0f Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Wed, 6 Dec 2023 01:16:08 +0800 Subject: [PATCH 06/29] Update --- NextShip.Api/APIHarmony.cs | 13 ++ .../Attributes/ReactorModFlagsAttribute.cs | 38 +++++ NextShip.Api/Config/Mod.cs | 27 ++++ NextShip.Api/Enums/ModFlags.cs | 37 +++++ NextShip.Api/Extension/ReactorExtension.cs | 150 ++++++++++++++++++ NextShip.Api/Extension/SteamExtension.cs | 17 ++ NextShip.Api/GlobalUsing.cs | 1 + NextShip.Api/Interfaces/INextScreenManager.cs | 6 + NextShip.Api/Interfaces/IPatchManager.cs | 6 + NextShip.Api/Managers/PatchManager.cs | 6 - NextShip.Api/Utilities/CachedPlayer.cs | 37 +++-- NextShip.Api/Utilities/EnumHelper.cs | 2 +- .../Utilities/FastDestroyableSingIeton.cs | 3 +- NextShip.Api/Utilities/StackFullCoroutine.cs | 6 - NextShip.Api/Utilities/YamlLoader.cs | 26 ++- NextShip.Api/Utils/AssetUtils.cs | 10 +- NextShip.Api/Utils/ColorUtils.cs | 11 +- NextShip.Api/Utils/GameObjectUtils.cs | 58 +++---- NextShip.Api/Utils/InputKeyUtils.cs | 10 +- NextShip.Api/Utils/JsonUtils.cs | 2 +- NextShip.Api/Utils/LayerUtils.cs | 12 +- NextShip.Api/Utils/MethodUtils.cs | 2 +- NextShip.Api/Utils/PingUtils.cs | 43 ++--- NextShip.Api/Utils/SpriteUtils.cs | 12 +- NextShip.Api/Utils/StreamUtils.cs | 2 +- NextShip.Api/Utils/TaskUtils.cs | 5 +- NextShip.Api/Utils/TextUtils.cs | 22 ++- NextShip/NextShip.csproj | 1 - NextShip/nuget.config => nuget.config | 0 29 files changed, 414 insertions(+), 151 deletions(-) create mode 100644 NextShip.Api/APIHarmony.cs create mode 100644 NextShip.Api/Attributes/ReactorModFlagsAttribute.cs create mode 100644 NextShip.Api/Config/Mod.cs create mode 100644 NextShip.Api/Enums/ModFlags.cs create mode 100644 NextShip.Api/Extension/ReactorExtension.cs create mode 100644 NextShip.Api/Extension/SteamExtension.cs create mode 100644 NextShip.Api/Interfaces/INextScreenManager.cs create mode 100644 NextShip.Api/Interfaces/IPatchManager.cs delete mode 100644 NextShip.Api/Managers/PatchManager.cs rename NextShip/nuget.config => nuget.config (100%) diff --git a/NextShip.Api/APIHarmony.cs b/NextShip.Api/APIHarmony.cs new file mode 100644 index 0000000..3e39062 --- /dev/null +++ b/NextShip.Api/APIHarmony.cs @@ -0,0 +1,13 @@ +using HarmonyLib; + +namespace NextShip.Api; + +internal static class APIHarmony +{ + internal static Harmony _Harmony { get; set; } + + static APIHarmony() + { + _Harmony = new Harmony("net.NextShip.Api"); + } +} \ No newline at end of file diff --git a/NextShip.Api/Attributes/ReactorModFlagsAttribute.cs b/NextShip.Api/Attributes/ReactorModFlagsAttribute.cs new file mode 100644 index 0000000..4e43f46 --- /dev/null +++ b/NextShip.Api/Attributes/ReactorModFlagsAttribute.cs @@ -0,0 +1,38 @@ +using System.Reflection; + +namespace NextShip.Api.Attributes; + +// form https://github.com/NuclearPowered/Reactor/blob/master/Reactor/Networking/Attributes/ReactorModFlagsAttribute.cs + +/// +/// Describes the of the annotated plugin class. +/// +[AttributeUsage(AttributeTargets.Class)] +public sealed class ReactorModFlagsAttribute : Attribute +{ + /// + /// Gets flags of the mod. + /// + public ModFlags Flags { get; } + + /// + /// Initializes a new instance of the class. + /// + /// Flags of the mod. + public ReactorModFlagsAttribute(ModFlags flags) + { + Flags = flags; + } + + internal static ModFlags GetModFlags(Type type) + { + var attribute = type.GetCustomAttribute(); + if (attribute != null) + { + return attribute.Flags; + } + + var metadataAttribute = type.Assembly.GetCustomAttributes().SingleOrDefault(x => x.Key == "Reactor.ModFlags"); + return metadataAttribute is { Value: not null } ? Enum.Parse(metadataAttribute.Value) : ModFlags.None; + } +} \ No newline at end of file diff --git a/NextShip.Api/Config/Mod.cs b/NextShip.Api/Config/Mod.cs new file mode 100644 index 0000000..324b690 --- /dev/null +++ b/NextShip.Api/Config/Mod.cs @@ -0,0 +1,27 @@ +namespace NextShip.Api.Config; + +/* + * form https://github.com/NuclearPowered/Reactor/blob/master/Reactor.Networking.Shared/Mod.cs + */ +public class Mod(string id, string version, ModFlags flags, string? name) +{ + /// + /// Gets the id of the mod. + /// + public string Id { get; } = id; + + /// + /// Gets the version of the mod. + /// + public string Version { get; } = version; + + /// + /// Gets the flags of the mod. + /// + public ModFlags Flags { get; } = flags; + + /// + /// Gets the name of the mod. + /// + public string? Name { get; } = name; +} \ No newline at end of file diff --git a/NextShip.Api/Enums/ModFlags.cs b/NextShip.Api/Enums/ModFlags.cs new file mode 100644 index 0000000..a73dce0 --- /dev/null +++ b/NextShip.Api/Enums/ModFlags.cs @@ -0,0 +1,37 @@ +namespace NextShip.Api.Enums; + +/* + * form https://github.com/NuclearPowered/Reactor/blob/master/Reactor.Networking.Shared/ModFlags.cs + */ + +/// +/// Represents flags of the mod. +/// 模组使用兼容 +/// +[Flags] +public enum ModFlags : ushort +{ + /// + /// No flags. + /// 没有 + /// + None = 0, + + /// + /// Requires all clients in a lobby to have the mod. + /// 所有人都拥有 + /// + RequireOnAllClients = 1 << 0, + + /// + /// Requires the server to have a plugin that handles the mod. + /// 在服务器需要 + /// + RequireOnServer = 1 << 1, + + /// + /// Requires the host of the lobby to have the mod. + /// 仅房主需要 + /// + RequireOnHost = 1 << 2, +} \ No newline at end of file diff --git a/NextShip.Api/Extension/ReactorExtension.cs b/NextShip.Api/Extension/ReactorExtension.cs new file mode 100644 index 0000000..8992665 --- /dev/null +++ b/NextShip.Api/Extension/ReactorExtension.cs @@ -0,0 +1,150 @@ +using BepInEx; +using BepInEx.Unity.IL2CPP; +using HarmonyLib; +using Hazel; +using Il2CppInterop.Runtime.InteropTypes.Arrays; +using InnerNet; +using NextShip.Api.Config; + +namespace NextShip.Api.Extension; + +/* + * form https://github.com/NuclearPowered/Reactor + */ + +[Harmony] +public static class ReactorExtension +{ + public static readonly HashSet HashSet_Mods = new (); + + public static readonly Dictionary> All_Mod = new (); + + public static bool ReactorHandshake; + + public static void UseReactorHandshake() + { + ReactorHandshake = true; + UseModList(); + _Harmony.PatchAll(typeof(ReactorExtension)); + } + + public static void DisableReactorHandshake() => ReactorHandshake = false; + + public static void GetHandshakeInfo() + { + + } + + private static void OnPluginLoad(PluginInfo pluginInfo, BasePlugin plugin) + { + var pluginType = plugin.GetType(); + + var mod = new Mod( + pluginInfo.Metadata.GUID, + pluginInfo.Metadata.Version.Clean(), + ReactorModFlagsAttribute.GetModFlags(pluginType), + pluginInfo.Metadata.Name + ); + + HashSet_Mods.Add(mod); + } + + public static void UseModList() + { + foreach (var existingPlugin in IL2CPPChainloader.Instance.Plugins.Values.Where(existingPlugin => existingPlugin.Instance != null)) + { + OnPluginLoad(existingPlugin, (BasePlugin) existingPlugin.Instance); + } + + IL2CPPChainloader.Instance.PluginLoad += (pluginInfo, _, plugin) => OnPluginLoad(pluginInfo, plugin); + } + + [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.GetConnectionData)), HarmonyPostfix] + public static void GetConnectionData_Postfix(ref Il2CppStructArray __result) + { + if (!ReactorHandshake) return; + var handshakeWriter = new MessageWriter(1000); + + // 写入原本握手内容 + handshakeWriter.Write(__result); + + // 写入反应堆握手版本 + handshakeWriter.Write(((ulong)0x72656163746f72 << 8) | 2); + + // 写入握手模组信息 + handshakeWriter.WritePacked(HashSet_Mods.Count); + foreach (var varMod in HashSet_Mods) + { + handshakeWriter.Write(varMod.Id); + handshakeWriter.Write(varMod.Version); + handshakeWriter.Write((ushort) varMod.Flags); + if (varMod.Flags.HasFlag(ModFlags.RequireOnAllClients)) + handshakeWriter.Write(varMod.Name); + } + + __result = handshakeWriter.ToByteArray(true); + handshakeWriter.Recycle(); + } + + [HarmonyPatch(typeof(InnerNetClient._HandleGameDataInner_d__39), nameof(InnerNetClient._HandleGameDataInner_d__39.MoveNext)), HarmonyPrefix] + public static bool _HandleGameDataInner_d__39_Prefix(InnerNetClient._HandleGameDataInner_d__39 __instance, ref bool __result) + { + if (!ReactorHandshake) return true; + + var innerNetClient = __instance.__4__this; + var reader = __instance.reader; + + if (__instance.__1__state != 0 || reader.Tag != InnerNetClient.SceneChangeFlag) return true; + + var clientId = reader.ReadPackedInt32(); + var clientData = innerNetClient.FindClientById(clientId); + var sceneName = reader.ReadString(); + + if (clientData == null || string.IsNullOrWhiteSpace(sceneName)) return true; + + if (reader.BytesRemaining >= sizeof(ulong) && Read(reader)) + { + var modCount = reader.ReadPackedInt32(); + var mods = new HashSet(modCount); + + for (var i = 0; i < modCount; i++) + { + var id = reader.ReadString(); + var version = reader.ReadString(); + var flags = (ModFlags) reader.ReadUInt16(); + var name = (flags & ModFlags.RequireOnAllClients) != 0 ? reader.ReadString() : null; + + mods.Add(new Mod(id, version, flags, name)); + } + + All_Mod[clientId] = mods; + } + + if (innerNetClient.AmHost) + { + innerNetClient.StartCoroutine(innerNetClient.CoOnPlayerChangedScene(clientData, sceneName)); + } + else + { + reader.Recycle(); + } + + __result = false; + return false; + + bool Read(MessageReader _reader) + { + var value = _reader.ReadUInt64(); + var magic = value >> 8; + var version = (byte) (value & 0xFF); + return magic == 0x72656163746f72 && version == 2; + } + } + + [ + HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.DisconnectInternal)), + HarmonyPatch(typeof(EndGameResult), nameof(EndGameResult.Create)), + HarmonyPostfix + ] + public static void Clear_Postfix() => All_Mod.Clear(); +} \ No newline at end of file diff --git a/NextShip.Api/Extension/SteamExtension.cs b/NextShip.Api/Extension/SteamExtension.cs new file mode 100644 index 0000000..2274138 --- /dev/null +++ b/NextShip.Api/Extension/SteamExtension.cs @@ -0,0 +1,17 @@ +using BepInEx; + +namespace NextShip.Api.Extension; + +public static class SteamExtension +{ + public const string file_Name = "steam_appid.txt"; + + public const string Among_Us_SteamId = "945360"; + + public static void UseSteamIdFile() + { + var path = Paths.GameRootPath.CombinePath(file_Name); + if (!File.Exists(path)) + File.WriteAllText(path, Among_Us_SteamId); + } +} \ No newline at end of file diff --git a/NextShip.Api/GlobalUsing.cs b/NextShip.Api/GlobalUsing.cs index e64e86c..be1d99e 100644 --- a/NextShip.Api/GlobalUsing.cs +++ b/NextShip.Api/GlobalUsing.cs @@ -6,4 +6,5 @@ global using NextShip.Api.Bases; global using NextShip.Api.Attributes; global using NextShip.Api.Logs; +global using static NextShip.Api.APIHarmony; global using static NextShip.Api.Logs.FastLog; \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextScreenManager.cs b/NextShip.Api/Interfaces/INextScreenManager.cs new file mode 100644 index 0000000..812be9c --- /dev/null +++ b/NextShip.Api/Interfaces/INextScreenManager.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public class INextScreenManager +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IPatchManager.cs b/NextShip.Api/Interfaces/IPatchManager.cs new file mode 100644 index 0000000..d077980 --- /dev/null +++ b/NextShip.Api/Interfaces/IPatchManager.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public interface IPatchManager +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Managers/PatchManager.cs b/NextShip.Api/Managers/PatchManager.cs deleted file mode 100644 index 3cabb0a..0000000 --- a/NextShip.Api/Managers/PatchManager.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace NextShip.Api.Managers; - -public class PatchManager -{ - -} \ No newline at end of file diff --git a/NextShip.Api/Utilities/CachedPlayer.cs b/NextShip.Api/Utilities/CachedPlayer.cs index a72d017..670c081 100644 --- a/NextShip.Api/Utilities/CachedPlayer.cs +++ b/NextShip.Api/Utilities/CachedPlayer.cs @@ -8,18 +8,18 @@ namespace NextShip.Api.Utilities; // from TheOtherRole public class CachedPlayer { - public static readonly Dictionary PlayerPtrs = new(); + public static readonly Dictionary PlayerIntPtrS = new(); public static readonly List AllPlayers = new(); - public static CachedPlayer LocalPlayer; - public GameData.PlayerInfo Data; - public CustomNetworkTransform NetTransform; - public PlayerControl PlayerControl; + public static CachedPlayer? LocalPlayer; + public GameData.PlayerInfo Data = null!; + public CustomNetworkTransform NetTransform = null!; + public PlayerControl PlayerControl = null!; public byte PlayerId; - public PlayerPhysics PlayerPhysics; + public PlayerPhysics PlayerPhysics = null!; - public Transform transform; + public Transform transform = null!; - public static implicit operator bool(CachedPlayer player) + public static implicit operator bool(CachedPlayer? player) { return player != null && player.PlayerControl; } @@ -38,9 +38,9 @@ public static implicit operator PlayerPhysics(CachedPlayer player) [HarmonyPatch] public static class CachedPlayerPatches { - public static bool CanAssaign(this CachedPlayer player) + public static bool CanAssign(this CachedPlayer? player) { - return player != null && player.Data != null; + return player is { Data: not null }; } [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.Awake))] @@ -56,13 +56,12 @@ public static void CachePlayerPatch(PlayerControl __instance) NetTransform = __instance.NetTransform }; CachedPlayer.AllPlayers.Add(player); - CachedPlayer.PlayerPtrs[__instance.Pointer] = player; + CachedPlayer.PlayerIntPtrS[__instance.Pointer] = player; #if DEBUG - foreach (var cachedPlayer in CachedPlayer.AllPlayers) - if (!cachedPlayer.PlayerControl || !cachedPlayer.PlayerPhysics || !cachedPlayer.NetTransform || - !cachedPlayer.transform) - Error($"CachedPlayer {cachedPlayer.PlayerControl.name} has null fields"); + foreach (var cachedPlayer in CachedPlayer.AllPlayers.Where(cachedPlayer => !cachedPlayer?.PlayerControl || !cachedPlayer.PlayerPhysics || !cachedPlayer.NetTransform || + !cachedPlayer.transform)) + Error($"CachedPlayer {cachedPlayer?.PlayerControl.name} has null fields"); #endif } @@ -72,7 +71,7 @@ public static void RemoveCachedPlayerPatch(PlayerControl __instance) { if (__instance.notRealPlayer) return; CachedPlayer.AllPlayers.RemoveAll(p => p.PlayerControl.Pointer == __instance.Pointer); - CachedPlayer.PlayerPtrs.Remove(__instance.Pointer); + CachedPlayer.PlayerIntPtrS.Remove(__instance.Pointer); } [HarmonyPatch(typeof(GameData), nameof(GameData.Deserialize))] @@ -81,7 +80,7 @@ public static void AddCachedDataOnDeserialize() { foreach (var cachedPlayer in CachedPlayer.AllPlayers) { - cachedPlayer.Data = cachedPlayer.PlayerControl.Data; + cachedPlayer!.Data = cachedPlayer.PlayerControl.Data; cachedPlayer.PlayerId = cachedPlayer.PlayerControl.PlayerId; } } @@ -92,7 +91,7 @@ public static void AddCachedDataOnAddPlayer() { foreach (var cachedPlayer in CachedPlayer.AllPlayers) { - cachedPlayer.Data = cachedPlayer.PlayerControl.Data; + cachedPlayer!.Data = cachedPlayer.PlayerControl.Data; cachedPlayer.PlayerId = cachedPlayer.PlayerControl.PlayerId; } } @@ -101,7 +100,7 @@ public static void AddCachedDataOnAddPlayer() [HarmonyPostfix] public static void SetCachedPlayerId(PlayerControl __instance) { - CachedPlayer.PlayerPtrs[__instance.Pointer].PlayerId = __instance.PlayerId; + CachedPlayer.PlayerIntPtrS[__instance.Pointer]!.PlayerId = __instance.PlayerId; } [HarmonyPatch] diff --git a/NextShip.Api/Utilities/EnumHelper.cs b/NextShip.Api/Utilities/EnumHelper.cs index 093c7c6..23afa1d 100644 --- a/NextShip.Api/Utilities/EnumHelper.cs +++ b/NextShip.Api/Utilities/EnumHelper.cs @@ -8,7 +8,7 @@ public static class EnumHelper /// /// 取得したいenumの型 /// Tのすべての値 - public static T[] GetAllValues() where T : Enum + public static T[]? GetAllValues() where T : Enum { return Enum.GetValues(typeof(T)) as T[]; } diff --git a/NextShip.Api/Utilities/FastDestroyableSingIeton.cs b/NextShip.Api/Utilities/FastDestroyableSingIeton.cs index c5c74b0..abd329c 100644 --- a/NextShip.Api/Utilities/FastDestroyableSingIeton.cs +++ b/NextShip.Api/Utilities/FastDestroyableSingIeton.cs @@ -27,8 +27,7 @@ public static T Instance { IntPtr objectPointer; IL2CPP.il2cpp_field_static_get_value(_fieldPtr, &objectPointer); - if (objectPointer == IntPtr.Zero) return DestroyableSingleton.Instance; - return _createObject(objectPointer); + return objectPointer == IntPtr.Zero ? DestroyableSingleton.Instance : _createObject(objectPointer); } } } \ No newline at end of file diff --git a/NextShip.Api/Utilities/StackFullCoroutine.cs b/NextShip.Api/Utilities/StackFullCoroutine.cs index 6117dcd..3f77aba 100644 --- a/NextShip.Api/Utilities/StackFullCoroutine.cs +++ b/NextShip.Api/Utilities/StackFullCoroutine.cs @@ -27,10 +27,4 @@ public void MoveNext() else if (current.Current is IEnumerator child) stack.Add(child); } - - public bool Move() - { - Move(); - return CanMove(); - } } \ No newline at end of file diff --git a/NextShip.Api/Utilities/YamlLoader.cs b/NextShip.Api/Utilities/YamlLoader.cs index f8b8514..20b0693 100644 --- a/NextShip.Api/Utilities/YamlLoader.cs +++ b/NextShip.Api/Utilities/YamlLoader.cs @@ -84,13 +84,12 @@ public YamlLoader LoadFromString(string yamlString) foreach (var loc in locations) try { - if (valueNode is YamlMappingNode mappingNode) - { - var keyNode = new YamlScalarNode(loc); - if (mappingNode.Children.TryGetValue(keyNode, out valueNode)) - // 继续向下查找 - continue; - } + if (valueNode is not YamlMappingNode mappingNode) return null; + + var keyNode = new YamlScalarNode(loc); + if (mappingNode.Children.TryGetValue(keyNode, out valueNode)) + // 继续向下查找 + continue; // 如果找不到对应的键或节点不是一个映射节点,则返回空列表 return null; @@ -131,13 +130,12 @@ public YamlLoader LoadFromString(string yamlString) foreach (var loc in locations) try { - if (valueNode is YamlMappingNode mappingNode) - { - var keyNode = new YamlScalarNode(loc); - if (mappingNode.Children.TryGetValue(keyNode, out valueNode)) - // 继续向下查找 - continue; - } + if (valueNode is not YamlMappingNode mappingNode) return null; + + var keyNode = new YamlScalarNode(loc); + if (mappingNode.Children.TryGetValue(keyNode, out valueNode)) + // 继续向下查找 + continue; // 如果找不到对应的键或节点不是一个映射节点,则返回 null return null; diff --git a/NextShip.Api/Utils/AssetUtils.cs b/NextShip.Api/Utils/AssetUtils.cs index 1408bd1..6df2a3d 100644 --- a/NextShip.Api/Utils/AssetUtils.cs +++ b/NextShip.Api/Utils/AssetUtils.cs @@ -12,11 +12,11 @@ public static class AssetUtils public static PetBehaviour GetPetBehaviour(this string id) { var asset = _CosmeticsCache.GetPet(id); - if (asset.Data.ProdId == "pet_EmptyPet" && _hatManager.allPets.FirstOrDefault(n => n.ProdId == id) != null) - { - var Asset = _hatManager.GetPetById(id).CreateAddressableAsset(); - Asset.LoadAsync((Action)(() => asset = Asset.GetAsset())); - } + if (asset.Data.ProdId != "pet_EmptyPet" || + _hatManager.allPets.FirstOrDefault(n => n.ProdId == id) == null) return asset; + + var Asset = _hatManager.GetPetById(id).CreateAddressableAsset(); + Asset.LoadAsync((Action)(() => asset = Asset.GetAsset())); return asset; } diff --git a/NextShip.Api/Utils/ColorUtils.cs b/NextShip.Api/Utils/ColorUtils.cs index bf529bb..c17e935 100644 --- a/NextShip.Api/Utils/ColorUtils.cs +++ b/NextShip.Api/Utils/ColorUtils.cs @@ -3,13 +3,16 @@ namespace NextShip.Api.Utils; -public static class ColorUtils +public static partial class ColorUtils { - public static Color32 HTMLColorTo32(this string HTMLcolor) + public static Color32 HTMLColorTo32(this string HTML_Color) { - Regex regex = new("^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$"); - if (ColorUtility.TryParseHtmlString(HTMLcolor, out var color) && regex.IsMatch(HTMLcolor)) return color; + var regex = MyRegex(); + if (ColorUtility.TryParseHtmlString(HTML_Color, out var color) && regex.IsMatch(HTML_Color)) return color; return new Color32(255, 255, 255, byte.MinValue); } + + [GeneratedRegex("^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$")] + private static partial Regex MyRegex(); } \ No newline at end of file diff --git a/NextShip.Api/Utils/GameObjectUtils.cs b/NextShip.Api/Utils/GameObjectUtils.cs index dc3275b..81a7ed1 100644 --- a/NextShip.Api/Utils/GameObjectUtils.cs +++ b/NextShip.Api/Utils/GameObjectUtils.cs @@ -17,7 +17,7 @@ public static class GameObjectUtils public static void DestroyTranslator(this GameObject obj) { TextTranslatorTMP[] translatorTMPs = obj.GetComponentsInChildren(true); - if (translatorTMPs != null) translatorTMPs.Do(n => Object.Destroy(n)); + translatorTMPs?.Do(Object.Destroy); } /// @@ -34,30 +34,30 @@ public static void DestroyTranslator(this MonoBehaviour obj) public static void DestroyAspectPosition(this GameObject gameObject) { AspectPosition[] aspectPositions = gameObject.GetComponentsInChildren(true); - if (aspectPositions != null) aspectPositions.Do(n => Object.Destroy(n)); + aspectPositions?.Do(Object.Destroy); } public static void DestroyComponents(this GameObject gameObject) where T : Object { T[] components = gameObject.GetComponentsInChildren(true); - if (components != null) components.Do(n => Object.Destroy(n)); + components?.Do(Object.Destroy); } - public static (GameObject, T) CreateGameObject(string name = null, Transform parent = null, + public static (GameObject, T) CreateGameObject(string? name = null, Transform? parent = null, Vector3 vector3 = default) where T : Component { var gameObject = CreateGameObject(name, parent, vector3); return (gameObject, gameObject.AddComponent()); } - public static GameObject CreateGGameObject(string name = null, Transform parent = null, + public static GameObject CreateGGameObject(string? name = null, Transform? parent = null, Vector3 vector3 = default) where T : Component { return CreateGameObject(name, parent, vector3).Item1; } - public static T CreateCGameObject(string name = null, Transform parent = null, Vector3 vector3 = default) + public static T CreateCGameObject(string? name = null, Transform? parent = null, Vector3 vector3 = default) where T : Component { return CreateGameObject(name, parent, vector3).Item2; @@ -66,14 +66,14 @@ public static T CreateCGameObject(string name = null, Transform parent = null public static PassiveButton CreatePassiveButton ( this GameObject @object, - Action onClick = null, - GameObject activeSprite = null, - GameObject inactiveSprite = null, - GameObject disabledSprite = null, - AudioClip ClickSound = null, - AudioClip HoverSound = null, - Action OnMouseOut = null, - Action OnMouseOver = null + Action? onClick = null, + GameObject? activeSprite = null, + GameObject? inactiveSprite = null, + GameObject? disabledSprite = null, + AudioClip? ClickSound = null, + AudioClip? HoverSound = null, + Action? OnMouseOut = null, + Action? OnMouseOver = null ) { var button = @object.AddComponent(); @@ -98,7 +98,7 @@ public static PassiveButton CreatePassiveButton return button; } - public static GameObject CreateGameObject(string name = null, Transform parent = null, Vector3 position = default) + public static GameObject CreateGameObject(string? name = null, Transform? parent = null, Vector3 position = default) { var gameObject = new GameObject { @@ -125,19 +125,19 @@ public static void AllGameObjectDo(this GameObject gameObject, Action allTransform, - out List bools, bool test = false, params string[] stings) + public static bool GetGameObjetWithCondition(out GameObject LastGameObject, out List allTransform, + out List Bools, bool test = false, params string[] stings) { - bools = new List(); + Bools = new List(); allTransform = new List(); - LastgameObject = null; + LastGameObject = null!; for (var i = 0; i < stings.Length; i++) { if (i == 0) { - LastgameObject = GameObject.Find(stings[i]); - bools.Add(LastgameObject); - if (LastgameObject) allTransform.Add(LastgameObject.transform); + LastGameObject = GameObject.Find(stings[i]); + Bools.Add(LastGameObject); + if (LastGameObject) allTransform.Add(LastGameObject.transform); if (test) { @@ -147,10 +147,10 @@ public static bool GetGameObjetWithCondition(out GameObject LastgameObject, out } else { - if (!LastgameObject) return false; - var transform = LastgameObject.transform.Find(stings[i]); - bools.Add(transform); - LastgameObject = transform.gameObject; + if (!LastGameObject) return false; + var transform = LastGameObject.transform.Find(stings[i]); + Bools.Add(transform); + LastGameObject = transform.gameObject; allTransform.Add(transform); if (test) @@ -160,13 +160,13 @@ public static bool GetGameObjetWithCondition(out GameObject LastgameObject, out } } - Info($"i:{i} name:{stings[i]} bool:{bools.Last()}"); + Info($"i:{i} name:{stings[i]} bool:{Bools.Last()}"); } - return bools.Last(); + return Bools.Last(); } - public static GameObject GetGameObjetFormAll(string name, string[] OptionPaths = null) + public static GameObject? GetGameObjetFormAll(string name, string[]? OptionPaths = null) { var RootGameObjects = SceneManager.GetActiveScene().GetRootGameObjects(); diff --git a/NextShip.Api/Utils/InputKeyUtils.cs b/NextShip.Api/Utils/InputKeyUtils.cs index e673e50..127b35b 100644 --- a/NextShip.Api/Utils/InputKeyUtils.cs +++ b/NextShip.Api/Utils/InputKeyUtils.cs @@ -6,13 +6,9 @@ public static class InputKeyUtils { public static bool GetKeysDown(params KeyCode[] keys) { - if (keys.Any(k => Input.GetKeyDown(k)) && keys.All(k => Input.GetKey(k))) - { - Warn($"KeyDown:{keys.Where(k => Input.GetKeyDown(k)).First()} in [{string.Join(",", keys)}]"); - return true; - } - - return false; + if (!keys.Any(Input.GetKeyDown) || !keys.All(Input.GetKey)) return false; + Warn($"KeyDown:{keys.First(Input.GetKeyDown)} in [{string.Join(",", keys)}]"); + return true; } public static bool GetKeyDown(KeyCode key) diff --git a/NextShip.Api/Utils/JsonUtils.cs b/NextShip.Api/Utils/JsonUtils.cs index 370f812..73a74bb 100644 --- a/NextShip.Api/Utils/JsonUtils.cs +++ b/NextShip.Api/Utils/JsonUtils.cs @@ -4,7 +4,7 @@ namespace NextShip.Api.Utils; public static class JsonUtils { - public static string GetString(this JToken token, string key) + public static string? GetString(this JToken token, string key) { return token[key]?.ToString(); } diff --git a/NextShip.Api/Utils/LayerUtils.cs b/NextShip.Api/Utils/LayerUtils.cs index f00f0ac..94a21e2 100644 --- a/NextShip.Api/Utils/LayerUtils.cs +++ b/NextShip.Api/Utils/LayerUtils.cs @@ -25,37 +25,37 @@ public static string GetName(this int layer) public static int GetDefaultLayer() { - if (defaultLayer == null) defaultLayer = LayerMask.NameToLayer("Default"); + defaultLayer ??= LayerMask.NameToLayer("Default"); return defaultLayer.Value; } public static int GetShortObjectsLayer() { - if (shortObjectsLayer == null) shortObjectsLayer = LayerMask.NameToLayer("ShortObjects"); + shortObjectsLayer ??= LayerMask.NameToLayer("ShortObjects"); return shortObjectsLayer.Value; } public static int GetObjectsLayer() { - if (objectsLayer == null) objectsLayer = LayerMask.NameToLayer("Objects"); + objectsLayer ??= LayerMask.NameToLayer("Objects"); return objectsLayer.Value; } public static int GetUILayer() { - if (uiLayer == null) uiLayer = LayerMask.NameToLayer("UI"); + uiLayer ??= LayerMask.NameToLayer("UI"); return uiLayer.Value; } public static int GetShipLayer() { - if (shipLayer == null) shipLayer = LayerMask.NameToLayer("Ship"); + shipLayer ??= LayerMask.NameToLayer("Ship"); return shipLayer.Value; } public static int GetShadowLayer() { - if (shadowLayer == null) shadowLayer = LayerMask.NameToLayer("Shadow"); + shadowLayer ??= LayerMask.NameToLayer("Shadow"); return shadowLayer.Value; } diff --git a/NextShip.Api/Utils/MethodUtils.cs b/NextShip.Api/Utils/MethodUtils.cs index 3648fe1..1ccb3d4 100644 --- a/NextShip.Api/Utils/MethodUtils.cs +++ b/NextShip.Api/Utils/MethodUtils.cs @@ -9,7 +9,7 @@ public class MethodUtils /// public static string GetNamespace() { - return MethodBase.GetCurrentMethod()?.DeclaringType?.Namespace; + return MethodBase.GetCurrentMethod()?.DeclaringType?.Namespace ?? string.Empty; } /// diff --git a/NextShip.Api/Utils/PingUtils.cs b/NextShip.Api/Utils/PingUtils.cs index 34b1407..a07c1c4 100644 --- a/NextShip.Api/Utils/PingUtils.cs +++ b/NextShip.Api/Utils/PingUtils.cs @@ -13,43 +13,34 @@ public static PingInfo Ping(string url) var reply = ping.Send(url); var stringB = new StringBuilder(); - string status; - status = reply.Status switch + var status = reply.Status switch { IPStatus.Success => "成功", IPStatus.TimedOut => "超时", _ => "失败" }; + stringB.AppendLine("状态:" + status); - if (reply.Status == IPStatus.Success) - { - stringB.AppendLine(string.Format("Ip地址: {0} ", reply.Address)); - stringB.AppendLine(string.Format("ping时间: {0} ", reply.Options.Ttl)); - stringB.AppendLine(string.Format("ping包大小: {0} ", reply.Buffer.Length)); - stringB.AppendLine(string.Format("往返时间: {0} ", reply.RoundtripTime)); - } + if (reply.Status != IPStatus.Success) + return new PingInfo(reply.Address.ToString(), reply.Options!.Ttl, reply.Buffer.Length, + reply.RoundtripTime, stringB); + + stringB.AppendLine($"Ip地址: {reply.Address} "); + stringB.AppendLine($"ping时间: {reply.Options!.Ttl} "); + stringB.AppendLine($"ping包大小: {reply.Buffer.Length} "); + stringB.AppendLine($"往返时间: {reply.RoundtripTime} "); - return new PingInfo(reply.Address.ToString(), reply.Options.Ttl, reply.Buffer.Length, + return new PingInfo(reply.Address.ToString(), reply.Options!.Ttl, reply.Buffer.Length, reply.RoundtripTime, stringB); } } -public class PingInfo +public class PingInfo(string ip, int pingTime, int size = -1, long roundTripTime = -1, StringBuilder? stringB = null) { - public string ip; - public int pingTime; - public long roundTripTime; - public int size; - public StringBuilder stringB; - - public PingInfo - (string ip, int pingTime, int size = -1, long roundTripTime = -1, StringBuilder stringB = null) - { - this.ip = ip; - this.pingTime = pingTime; - this.size = size; - this.roundTripTime = roundTripTime; - this.stringB = stringB; - } + public string ip = ip; + public readonly int pingTime = pingTime; + public long roundTripTime = roundTripTime; + public int size = size; + public StringBuilder? stringB = stringB; } \ No newline at end of file diff --git a/NextShip.Api/Utils/SpriteUtils.cs b/NextShip.Api/Utils/SpriteUtils.cs index 1cb08c0..fe446be 100644 --- a/NextShip.Api/Utils/SpriteUtils.cs +++ b/NextShip.Api/Utils/SpriteUtils.cs @@ -50,7 +50,7 @@ public static Sprite GetCache(string name, bool NoCache = false) return null; } - public static Sprite LoadSpriteFromResources(string path, float pixelsPerUnit, Vector2 pivot, uint extrude, + public static Sprite? LoadSpriteFromResources(string path, float pixelsPerUnit, Vector2 pivot, uint extrude, SpriteMeshType meshType, Vector4 border) { try @@ -78,7 +78,7 @@ public static Sprite ToFullRect(this Sprite sprite, string name = "") return FullRectSprite; } - public static unsafe Texture2D LoadTextureFromResources(string path) + public static unsafe Texture2D? LoadTextureFromResources(string path) { try { @@ -102,7 +102,7 @@ public static unsafe Texture2D LoadTextureFromResources(string path) return null; } - public static Texture2D LoadTextureFromByte(Il2CppStructArray bytes) + public static Texture2D? LoadTextureFromByte(Il2CppStructArray bytes) { var texture = new Texture2D(2, 2, TextureFormat.ARGB32, true); var byteTexture = bytes; @@ -110,7 +110,7 @@ public static Texture2D LoadTextureFromByte(Il2CppStructArray bytes) return texture; } - public static Texture2D LoadTextureFromDisk(string path) + public static Texture2D? LoadTextureFromDisk(string path) { try { @@ -125,7 +125,7 @@ public static Texture2D LoadTextureFromDisk(string path) return null; } - public static Sprite LoadSpriteFromDisk(string path, float pixelsPerUnit) + public static Sprite? LoadSpriteFromDisk(string path, float pixelsPerUnit) { try { @@ -144,7 +144,7 @@ public static Sprite LoadSpriteFromDisk(string path, float pixelsPerUnit) return null; } - public static Sprite LoadSpriteFromResources(string FileName) + public static Sprite? LoadSpriteFromResources(string FileName) { var TheAssembly = Assembly.GetExecutingAssembly(); var names = TheAssembly.GetManifestResourceNames(); diff --git a/NextShip.Api/Utils/StreamUtils.cs b/NextShip.Api/Utils/StreamUtils.cs index 033ac30..e192cc0 100644 --- a/NextShip.Api/Utils/StreamUtils.cs +++ b/NextShip.Api/Utils/StreamUtils.cs @@ -17,7 +17,7 @@ public static class StreamUtils // form reactor - public static byte[] ReadFully(this Stream input) + public static byte[] ReadFully(this Stream? input) { using var ms = new MemoryStream(); input.CopyTo(ms); diff --git a/NextShip.Api/Utils/TaskUtils.cs b/NextShip.Api/Utils/TaskUtils.cs index a5b1679..47e1a0b 100644 --- a/NextShip.Api/Utils/TaskUtils.cs +++ b/NextShip.Api/Utils/TaskUtils.cs @@ -4,10 +4,9 @@ namespace NextShip.Api.Utils; public static class TaskUtils { - public static void StartTask(Action[] actions) + public static void StartTask(IEnumerable actions) { - actions.Do( - StartTask); + actions.Do(StartTask); } public static void StartTask(Action action) diff --git a/NextShip.Api/Utils/TextUtils.cs b/NextShip.Api/Utils/TextUtils.cs index c8f3cd5..06c4fe0 100644 --- a/NextShip.Api/Utils/TextUtils.cs +++ b/NextShip.Api/Utils/TextUtils.cs @@ -6,21 +6,19 @@ namespace NextShip.Api.Utils; public static class TextUtils { - public static string TextRemove(this string Otext, string targetText) + public static string TextRemove(this string OldText, string targetText) { - return Otext.Replace(targetText, ""); + return OldText.Replace(targetText, ""); } - public static string TextRemove(this string Otext, string[] targetText) + public static string TextRemove(this string OldText, IEnumerable targetText) { - foreach (var tt in targetText) Otext = Otext.Replace(tt, ""); - return Otext; + return targetText.Aggregate(OldText, (current, tt) => current.Replace(tt, "")); } public static string cs(Color c, string s) { - return string.Format("{4}", ToByte(c.r), ToByte(c.g), ToByte(c.b), - ToByte(c.a), s); + return $"{s}"; } public static byte ToByte(float f) @@ -37,22 +35,20 @@ public static string RemoveBlank(this string s) public static string clearColor(this string str) { var s = str.Replace("", ""); - var found = s.IndexOf(">", StringComparison.Ordinal); - s = s.Substring(found + 1); + var found = s.IndexOf('>'); + s = s[(found + 1)..]; return s; } public static string ToColorString(this string text, Color color) { - string colorString; - colorString = "" + text + ""; + var colorString = "" + text + ""; return colorString; } public static string ToColorString(this string text, System.Drawing.Color color) { - string colorString; - colorString = "" + text + ""; + var colorString = "" + text + ""; return colorString; } diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index 45df0b7..565af6c 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -19,7 +19,6 @@ - all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/NextShip/nuget.config b/nuget.config similarity index 100% rename from NextShip/nuget.config rename to nuget.config From d00cb79d8c0ad5c6bb2f5074908b6a6aa75c2b88 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Wed, 6 Dec 2023 01:17:06 +0800 Subject: [PATCH 07/29] =?UTF-8?q?IDE=E6=A0=BC=E5=BC=8F=E5=B9=B6=E6=B8=85?= =?UTF-8?q?=E7=90=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NextShip.Api/APIHarmony.cs | 4 +- NextShip.Api/Attributes/LoadAttribute.cs | 4 +- .../Attributes/ReactorModFlagsAttribute.cs | 22 +++--- NextShip.Api/Config/Mod.cs | 8 +- NextShip.Api/Enums/ModFlags.cs | 22 +++--- NextShip.Api/Extension/ReactorExtension.cs | 76 ++++++++++--------- NextShip.Api/Extension/SteamExtension.cs | 2 +- NextShip.Api/Interfaces/ILoadManager.cs | 1 - NextShip.Api/Interfaces/INextScreenManager.cs | 1 - NextShip.Api/Interfaces/IPatchManager.cs | 1 - NextShip.Api/Services/DownloadService.cs | 1 - NextShip.Api/Utilities/YamlLoader.cs | 4 +- NextShip.Api/Utils/PingUtils.cs | 6 +- NextShip/Updates/ModUpdater.cs | 2 +- 14 files changed, 75 insertions(+), 79 deletions(-) diff --git a/NextShip.Api/APIHarmony.cs b/NextShip.Api/APIHarmony.cs index 3e39062..d4fdc9e 100644 --- a/NextShip.Api/APIHarmony.cs +++ b/NextShip.Api/APIHarmony.cs @@ -4,10 +4,10 @@ namespace NextShip.Api; internal static class APIHarmony { - internal static Harmony _Harmony { get; set; } - static APIHarmony() { _Harmony = new Harmony("net.NextShip.Api"); } + + internal static Harmony _Harmony { get; set; } } \ No newline at end of file diff --git a/NextShip.Api/Attributes/LoadAttribute.cs b/NextShip.Api/Attributes/LoadAttribute.cs index 8ff4406..fca9296 100644 --- a/NextShip.Api/Attributes/LoadAttribute.cs +++ b/NextShip.Api/Attributes/LoadAttribute.cs @@ -7,12 +7,12 @@ namespace NextShip.Api.Attributes; public sealed class LoadAttribute : Attribute { public readonly LoadMode Mode; - + public LoadAttribute(LoadMode mode = LoadMode.Load) { Mode = mode; } - + public static void Registration(Type type) { Info("Start Registration", filename: MethodUtils.GetClassName()); diff --git a/NextShip.Api/Attributes/ReactorModFlagsAttribute.cs b/NextShip.Api/Attributes/ReactorModFlagsAttribute.cs index 4e43f46..392281e 100644 --- a/NextShip.Api/Attributes/ReactorModFlagsAttribute.cs +++ b/NextShip.Api/Attributes/ReactorModFlagsAttribute.cs @@ -5,18 +5,13 @@ namespace NextShip.Api.Attributes; // form https://github.com/NuclearPowered/Reactor/blob/master/Reactor/Networking/Attributes/ReactorModFlagsAttribute.cs /// -/// Describes the of the annotated plugin class. +/// Describes the of the annotated plugin class. /// [AttributeUsage(AttributeTargets.Class)] public sealed class ReactorModFlagsAttribute : Attribute { /// - /// Gets flags of the mod. - /// - public ModFlags Flags { get; } - - /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Flags of the mod. public ReactorModFlagsAttribute(ModFlags flags) @@ -24,15 +19,18 @@ public ReactorModFlagsAttribute(ModFlags flags) Flags = flags; } + /// + /// Gets flags of the mod. + /// + public ModFlags Flags { get; } + internal static ModFlags GetModFlags(Type type) { var attribute = type.GetCustomAttribute(); - if (attribute != null) - { - return attribute.Flags; - } + if (attribute != null) return attribute.Flags; - var metadataAttribute = type.Assembly.GetCustomAttributes().SingleOrDefault(x => x.Key == "Reactor.ModFlags"); + var metadataAttribute = type.Assembly.GetCustomAttributes() + .SingleOrDefault(x => x.Key == "Reactor.ModFlags"); return metadataAttribute is { Value: not null } ? Enum.Parse(metadataAttribute.Value) : ModFlags.None; } } \ No newline at end of file diff --git a/NextShip.Api/Config/Mod.cs b/NextShip.Api/Config/Mod.cs index 324b690..4b3e4c0 100644 --- a/NextShip.Api/Config/Mod.cs +++ b/NextShip.Api/Config/Mod.cs @@ -6,22 +6,22 @@ namespace NextShip.Api.Config; public class Mod(string id, string version, ModFlags flags, string? name) { /// - /// Gets the id of the mod. + /// Gets the id of the mod. /// public string Id { get; } = id; /// - /// Gets the version of the mod. + /// Gets the version of the mod. /// public string Version { get; } = version; /// - /// Gets the flags of the mod. + /// Gets the flags of the mod. /// public ModFlags Flags { get; } = flags; /// - /// Gets the name of the mod. + /// Gets the name of the mod. /// public string? Name { get; } = name; } \ No newline at end of file diff --git a/NextShip.Api/Enums/ModFlags.cs b/NextShip.Api/Enums/ModFlags.cs index a73dce0..fd9da47 100644 --- a/NextShip.Api/Enums/ModFlags.cs +++ b/NextShip.Api/Enums/ModFlags.cs @@ -5,33 +5,33 @@ namespace NextShip.Api.Enums; */ /// -/// Represents flags of the mod. -/// 模组使用兼容 +/// Represents flags of the mod. +/// 模组使用兼容 /// [Flags] public enum ModFlags : ushort { /// - /// No flags. - /// 没有 + /// No flags. + /// 没有 /// None = 0, /// - /// Requires all clients in a lobby to have the mod. - /// 所有人都拥有 + /// Requires all clients in a lobby to have the mod. + /// 所有人都拥有 /// RequireOnAllClients = 1 << 0, /// - /// Requires the server to have a plugin that handles the mod. - /// 在服务器需要 + /// Requires the server to have a plugin that handles the mod. + /// 在服务器需要 /// RequireOnServer = 1 << 1, /// - /// Requires the host of the lobby to have the mod. - /// 仅房主需要 + /// Requires the host of the lobby to have the mod. + /// 仅房主需要 /// - RequireOnHost = 1 << 2, + RequireOnHost = 1 << 2 } \ No newline at end of file diff --git a/NextShip.Api/Extension/ReactorExtension.cs b/NextShip.Api/Extension/ReactorExtension.cs index 8992665..f3a3764 100644 --- a/NextShip.Api/Extension/ReactorExtension.cs +++ b/NextShip.Api/Extension/ReactorExtension.cs @@ -15,12 +15,12 @@ namespace NextShip.Api.Extension; [Harmony] public static class ReactorExtension { - public static readonly HashSet HashSet_Mods = new (); + public static readonly HashSet HashSet_Mods = new(); - public static readonly Dictionary> All_Mod = new (); + public static readonly Dictionary> All_Mod = new(); public static bool ReactorHandshake; - + public static void UseReactorHandshake() { ReactorHandshake = true; @@ -28,13 +28,15 @@ public static void UseReactorHandshake() _Harmony.PatchAll(typeof(ReactorExtension)); } - public static void DisableReactorHandshake() => ReactorHandshake = false; - + public static void DisableReactorHandshake() + { + ReactorHandshake = false; + } + public static void GetHandshakeInfo() { - } - + private static void OnPluginLoad(PluginInfo pluginInfo, BasePlugin plugin) { var pluginType = plugin.GetType(); @@ -48,18 +50,18 @@ private static void OnPluginLoad(PluginInfo pluginInfo, BasePlugin plugin) HashSet_Mods.Add(mod); } - + public static void UseModList() { - foreach (var existingPlugin in IL2CPPChainloader.Instance.Plugins.Values.Where(existingPlugin => existingPlugin.Instance != null)) - { - OnPluginLoad(existingPlugin, (BasePlugin) existingPlugin.Instance); - } + foreach (var existingPlugin in IL2CPPChainloader.Instance.Plugins.Values.Where(existingPlugin => + existingPlugin.Instance != null)) + OnPluginLoad(existingPlugin, (BasePlugin)existingPlugin.Instance); IL2CPPChainloader.Instance.PluginLoad += (pluginInfo, _, plugin) => OnPluginLoad(pluginInfo, plugin); } - - [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.GetConnectionData)), HarmonyPostfix] + + [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.GetConnectionData))] + [HarmonyPostfix] public static void GetConnectionData_Postfix(ref Il2CppStructArray __result) { if (!ReactorHandshake) return; @@ -67,7 +69,7 @@ public static void GetConnectionData_Postfix(ref Il2CppStructArray __resul // 写入原本握手内容 handshakeWriter.Write(__result); - + // 写入反应堆握手版本 handshakeWriter.Write(((ulong)0x72656163746f72 << 8) | 2); @@ -77,31 +79,34 @@ public static void GetConnectionData_Postfix(ref Il2CppStructArray __resul { handshakeWriter.Write(varMod.Id); handshakeWriter.Write(varMod.Version); - handshakeWriter.Write((ushort) varMod.Flags); - if (varMod.Flags.HasFlag(ModFlags.RequireOnAllClients)) + handshakeWriter.Write((ushort)varMod.Flags); + if (varMod.Flags.HasFlag(ModFlags.RequireOnAllClients)) handshakeWriter.Write(varMod.Name); } __result = handshakeWriter.ToByteArray(true); handshakeWriter.Recycle(); } - - [HarmonyPatch(typeof(InnerNetClient._HandleGameDataInner_d__39), nameof(InnerNetClient._HandleGameDataInner_d__39.MoveNext)), HarmonyPrefix] - public static bool _HandleGameDataInner_d__39_Prefix(InnerNetClient._HandleGameDataInner_d__39 __instance, ref bool __result) + + [HarmonyPatch(typeof(InnerNetClient._HandleGameDataInner_d__39), + nameof(InnerNetClient._HandleGameDataInner_d__39.MoveNext))] + [HarmonyPrefix] + public static bool _HandleGameDataInner_d__39_Prefix(InnerNetClient._HandleGameDataInner_d__39 __instance, + ref bool __result) { if (!ReactorHandshake) return true; - + var innerNetClient = __instance.__4__this; var reader = __instance.reader; if (__instance.__1__state != 0 || reader.Tag != InnerNetClient.SceneChangeFlag) return true; - + var clientId = reader.ReadPackedInt32(); var clientData = innerNetClient.FindClientById(clientId); var sceneName = reader.ReadString(); if (clientData == null || string.IsNullOrWhiteSpace(sceneName)) return true; - + if (reader.BytesRemaining >= sizeof(ulong) && Read(reader)) { var modCount = reader.ReadPackedInt32(); @@ -111,7 +116,7 @@ public static bool _HandleGameDataInner_d__39_Prefix(InnerNetClient._HandleGameD { var id = reader.ReadString(); var version = reader.ReadString(); - var flags = (ModFlags) reader.ReadUInt16(); + var flags = (ModFlags)reader.ReadUInt16(); var name = (flags & ModFlags.RequireOnAllClients) != 0 ? reader.ReadString() : null; mods.Add(new Mod(id, version, flags, name)); @@ -119,32 +124,29 @@ public static bool _HandleGameDataInner_d__39_Prefix(InnerNetClient._HandleGameD All_Mod[clientId] = mods; } - + if (innerNetClient.AmHost) - { innerNetClient.StartCoroutine(innerNetClient.CoOnPlayerChangedScene(clientData, sceneName)); - } else - { reader.Recycle(); - } __result = false; return false; - + bool Read(MessageReader _reader) { var value = _reader.ReadUInt64(); var magic = value >> 8; - var version = (byte) (value & 0xFF); + var version = (byte)(value & 0xFF); return magic == 0x72656163746f72 && version == 2; } } - [ - HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.DisconnectInternal)), - HarmonyPatch(typeof(EndGameResult), nameof(EndGameResult.Create)), - HarmonyPostfix - ] - public static void Clear_Postfix() => All_Mod.Clear(); + [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.DisconnectInternal))] + [HarmonyPatch(typeof(EndGameResult), nameof(EndGameResult.Create))] + [HarmonyPostfix] + public static void Clear_Postfix() + { + All_Mod.Clear(); + } } \ No newline at end of file diff --git a/NextShip.Api/Extension/SteamExtension.cs b/NextShip.Api/Extension/SteamExtension.cs index 2274138..18e7062 100644 --- a/NextShip.Api/Extension/SteamExtension.cs +++ b/NextShip.Api/Extension/SteamExtension.cs @@ -7,7 +7,7 @@ public static class SteamExtension public const string file_Name = "steam_appid.txt"; public const string Among_Us_SteamId = "945360"; - + public static void UseSteamIdFile() { var path = Paths.GameRootPath.CombinePath(file_Name); diff --git a/NextShip.Api/Interfaces/ILoadManager.cs b/NextShip.Api/Interfaces/ILoadManager.cs index c2c8f1a..9516124 100644 --- a/NextShip.Api/Interfaces/ILoadManager.cs +++ b/NextShip.Api/Interfaces/ILoadManager.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public interface ILoadManager { - } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextScreenManager.cs b/NextShip.Api/Interfaces/INextScreenManager.cs index 812be9c..aba2f2a 100644 --- a/NextShip.Api/Interfaces/INextScreenManager.cs +++ b/NextShip.Api/Interfaces/INextScreenManager.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public class INextScreenManager { - } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IPatchManager.cs b/NextShip.Api/Interfaces/IPatchManager.cs index d077980..4c44533 100644 --- a/NextShip.Api/Interfaces/IPatchManager.cs +++ b/NextShip.Api/Interfaces/IPatchManager.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public interface IPatchManager { - } \ No newline at end of file diff --git a/NextShip.Api/Services/DownloadService.cs b/NextShip.Api/Services/DownloadService.cs index 6c76054..3ce73b5 100644 --- a/NextShip.Api/Services/DownloadService.cs +++ b/NextShip.Api/Services/DownloadService.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Services; public class DownloadService { - } \ No newline at end of file diff --git a/NextShip.Api/Utilities/YamlLoader.cs b/NextShip.Api/Utilities/YamlLoader.cs index 20b0693..2302481 100644 --- a/NextShip.Api/Utilities/YamlLoader.cs +++ b/NextShip.Api/Utilities/YamlLoader.cs @@ -85,7 +85,7 @@ public YamlLoader LoadFromString(string yamlString) try { if (valueNode is not YamlMappingNode mappingNode) return null; - + var keyNode = new YamlScalarNode(loc); if (mappingNode.Children.TryGetValue(keyNode, out valueNode)) // 继续向下查找 @@ -131,7 +131,7 @@ public YamlLoader LoadFromString(string yamlString) try { if (valueNode is not YamlMappingNode mappingNode) return null; - + var keyNode = new YamlScalarNode(loc); if (mappingNode.Children.TryGetValue(keyNode, out valueNode)) // 继续向下查找 diff --git a/NextShip.Api/Utils/PingUtils.cs b/NextShip.Api/Utils/PingUtils.cs index a07c1c4..1e89b46 100644 --- a/NextShip.Api/Utils/PingUtils.cs +++ b/NextShip.Api/Utils/PingUtils.cs @@ -19,13 +19,13 @@ public static PingInfo Ping(string url) IPStatus.TimedOut => "超时", _ => "失败" }; - + stringB.AppendLine("状态:" + status); if (reply.Status != IPStatus.Success) return new PingInfo(reply.Address.ToString(), reply.Options!.Ttl, reply.Buffer.Length, reply.RoundtripTime, stringB); - + stringB.AppendLine($"Ip地址: {reply.Address} "); stringB.AppendLine($"ping时间: {reply.Options!.Ttl} "); stringB.AppendLine($"ping包大小: {reply.Buffer.Length} "); @@ -38,8 +38,8 @@ public static PingInfo Ping(string url) public class PingInfo(string ip, int pingTime, int size = -1, long roundTripTime = -1, StringBuilder? stringB = null) { - public string ip = ip; public readonly int pingTime = pingTime; + public string ip = ip; public long roundTripTime = roundTripTime; public int size = size; public StringBuilder? stringB = stringB; diff --git a/NextShip/Updates/ModUpdater.cs b/NextShip/Updates/ModUpdater.cs index 5222977..5a93c7a 100644 --- a/NextShip/Updates/ModUpdater.cs +++ b/NextShip/Updates/ModUpdater.cs @@ -7,7 +7,7 @@ public class ModUpdater { // HUdate=HasUpdate 判断是否有更新 public static bool HUpdate = VersionManager.HasUpdate; - + public static ConfigEntry AutoUpdate; // 模组下载链接 From dc33b500649f9a22d9a37f972c9b4e7875ba8831 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Wed, 6 Dec 2023 01:17:24 +0800 Subject: [PATCH 08/29] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=B9=B6=E6=B8=85?= =?UTF-8?q?=E7=90=86=E4=BB=A3=E7=A0=81=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NextShip.Api/Interfaces/ILang.cs | 4 +-- NextShip.Api/Interfaces/ILangManager.cs | 2 +- NextShip.Api/Logs/Log.cs | 40 ++++++++++++------------- NextShip.Api/Utilities/CachedPlayer.cs | 3 +- NextShip.Api/Utils/AssetUtils.cs | 2 +- 5 files changed, 26 insertions(+), 25 deletions(-) diff --git a/NextShip.Api/Interfaces/ILang.cs b/NextShip.Api/Interfaces/ILang.cs index ffdb1b7..3545917 100644 --- a/NextShip.Api/Interfaces/ILang.cs +++ b/NextShip.Api/Interfaces/ILang.cs @@ -3,11 +3,11 @@ namespace NextShip.Api.Interfaces; public interface ILang { public SupportedLangs LangId { get; protected set; } - + public string LangName { get; set; } public string GetString(string Key); - + public string GetStringOfIndex(int Index); public void Init(); diff --git a/NextShip.Api/Interfaces/ILangManager.cs b/NextShip.Api/Interfaces/ILangManager.cs index a23e29c..bdee486 100644 --- a/NextShip.Api/Interfaces/ILangManager.cs +++ b/NextShip.Api/Interfaces/ILangManager.cs @@ -3,7 +3,7 @@ namespace NextShip.Api.Interfaces; public interface ILangManager { public void RegisterLang(ILang lang); - + public void UnRegisterLang(ILang lang); public void SetLang(SupportedLangs langId, ILang lang); diff --git a/NextShip.Api/Logs/Log.cs b/NextShip.Api/Logs/Log.cs index 9a6a9bd..8701c72 100644 --- a/NextShip.Api/Logs/Log.cs +++ b/NextShip.Api/Logs/Log.cs @@ -8,10 +8,10 @@ public sealed class log { public static bool CreateEd; - public StreamWriter? DiskWriter; - public TextWriter? ConsoleWriter; + public StreamWriter? DiskWriter; + static log() { System.Console.OutputEncoding = Encoding.UTF8; @@ -24,6 +24,10 @@ private log(ManualLogSource logSource) Instance = this; } + public ManualLogSource LogSource { get; private set; } + + public static log? Instance { get; set; } + public void CreateDiskLog(string name, string? path = null) { @@ -44,38 +48,34 @@ public Stream GetDiskLogStream(string name, string? path = null, bool outTime = } path ??= string.Empty; - + var FilePath = path + name; - + if (!File.Exists(FilePath)) return File.Create(FilePath); Stream stream; var count = 0; - + while (true) { count++; FilePath = path + name + $"_{count}"; - + if (!File.Exists(FilePath)) { stream = File.Create(FilePath); break; } - + stream = File.Open(FilePath, FileMode.Open); if (stream.Length == 0) break; } - + return stream; } - public ManualLogSource LogSource { get; private set; } - - public static log? Instance { get; set; } - public static log? Get(ManualLogSource logSource) { if (CreateEd) @@ -98,19 +98,19 @@ private void Set(ManualLogSource logSource) internal void SendToFile(string? tag, string? filename, string text, LogLevel level = LogLevel.Info) { var logger = Instance?.LogSource; - + var t = DateTime.Now.ToString("HH:mm:ss"); - + var log_text = $"[{t}]"; - - if (tag != null) + + if (tag != null) log_text += $"[{tag}]"; - - if (filename != null) + + if (filename != null) log_text += $"[{filename}]"; - + log_text += text; - + switch (level) { case LogLevel.Info: diff --git a/NextShip.Api/Utilities/CachedPlayer.cs b/NextShip.Api/Utilities/CachedPlayer.cs index 670c081..a4cf135 100644 --- a/NextShip.Api/Utilities/CachedPlayer.cs +++ b/NextShip.Api/Utilities/CachedPlayer.cs @@ -59,7 +59,8 @@ public static void CachePlayerPatch(PlayerControl __instance) CachedPlayer.PlayerIntPtrS[__instance.Pointer] = player; #if DEBUG - foreach (var cachedPlayer in CachedPlayer.AllPlayers.Where(cachedPlayer => !cachedPlayer?.PlayerControl || !cachedPlayer.PlayerPhysics || !cachedPlayer.NetTransform || + foreach (var cachedPlayer in CachedPlayer.AllPlayers.Where(cachedPlayer => !cachedPlayer?.PlayerControl || + !cachedPlayer.PlayerPhysics || !cachedPlayer.NetTransform || !cachedPlayer.transform)) Error($"CachedPlayer {cachedPlayer?.PlayerControl.name} has null fields"); #endif diff --git a/NextShip.Api/Utils/AssetUtils.cs b/NextShip.Api/Utils/AssetUtils.cs index 6df2a3d..d2bae36 100644 --- a/NextShip.Api/Utils/AssetUtils.cs +++ b/NextShip.Api/Utils/AssetUtils.cs @@ -14,7 +14,7 @@ public static PetBehaviour GetPetBehaviour(this string id) var asset = _CosmeticsCache.GetPet(id); if (asset.Data.ProdId != "pet_EmptyPet" || _hatManager.allPets.FirstOrDefault(n => n.ProdId == id) == null) return asset; - + var Asset = _hatManager.GetPetById(id).CreateAddressableAsset(); Asset.LoadAsync((Action)(() => asset = Asset.GetAsset())); From fde7f7b65521963149c4c1be48f245a59cb43092 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Sat, 9 Dec 2023 12:25:16 +0800 Subject: [PATCH 09/29] Update --- NextShip.Api/Bases/HostInfo.cs | 5 + NextShip.Api/Bases/NextInfo.cs | 16 +++ NextShip.Api/Bases/ShipTask.cs | 53 +++++++ .../Bases}/TaskState.cs | 29 +--- NextShip.Api/Bases/UpdateTasker.cs | 46 ++++++ NextShip.Api/Config/NextPaths.cs | 5 - NextShip.Api/Enums/TaskPriority.cs | 8 ++ NextShip.Api/Enums/TaskStateEnum.cs | 10 ++ NextShip.Api/Interfaces/INextEvent.cs | 2 + NextShip.Api/Interfaces/INextService.cs | 1 + NextShip.Api/Interfaces/IRoleCreator.cs | 6 +- NextShip.Api/Interfaces/IRoleManager.cs | 12 ++ NextShip.Api/Interfaces/IServiceBuilder.cs | 16 +++ NextShip.Api/NextShip.Api.csproj | 1 + NextShip.Api/Roles/RoleBase.cs | 27 +--- NextShip.Api/Roles/RoleManager.Assaign.cs | 44 ------ NextShip.Api/Roles/RoleManager.Restore.cs | 19 --- NextShip.Api/Roles/RoleManager.cs | 26 ---- NextShip.Api/Roles/SimpleRoleInfo.cs | 46 ++---- NextShip.Api/Services/DownloadService.cs | 11 +- NextShip.Api/Services/MetadataService.cs | 6 + NextShip/GlobalUsing.cs | 1 + NextShip/Manager/EventManager.cs | 10 ++ NextShip/Manager/LoadManager.cs | 8 +- NextShip/Manager/NextPatchManager.cs | 8 ++ NextShip/Manager/RoleManager.cs | 33 +++++ NextShip/NextManager.cs | 37 +++++ NextShip/NextPaths.cs | 15 ++ NextShip/NextService.cs | 40 +++--- NextShip/ServiceBuilder.cs | 71 +++++++++ NextShip/UI/Components/UpdateTask.cs | 136 ------------------ NextShip/main.cs | 52 ++++--- 32 files changed, 457 insertions(+), 343 deletions(-) create mode 100644 NextShip.Api/Bases/HostInfo.cs create mode 100644 NextShip.Api/Bases/NextInfo.cs create mode 100644 NextShip.Api/Bases/ShipTask.cs rename {NextShip/UI/Components => NextShip.Api/Bases}/TaskState.cs (50%) create mode 100644 NextShip.Api/Bases/UpdateTasker.cs delete mode 100644 NextShip.Api/Config/NextPaths.cs create mode 100644 NextShip.Api/Enums/TaskPriority.cs create mode 100644 NextShip.Api/Enums/TaskStateEnum.cs create mode 100644 NextShip.Api/Interfaces/IRoleManager.cs create mode 100644 NextShip.Api/Interfaces/IServiceBuilder.cs delete mode 100644 NextShip.Api/Roles/RoleManager.Assaign.cs delete mode 100644 NextShip.Api/Roles/RoleManager.Restore.cs delete mode 100644 NextShip.Api/Roles/RoleManager.cs create mode 100644 NextShip.Api/Services/MetadataService.cs create mode 100644 NextShip/Manager/NextPatchManager.cs create mode 100644 NextShip/Manager/RoleManager.cs create mode 100644 NextShip/NextManager.cs create mode 100644 NextShip/NextPaths.cs create mode 100644 NextShip/ServiceBuilder.cs delete mode 100644 NextShip/UI/Components/UpdateTask.cs diff --git a/NextShip.Api/Bases/HostInfo.cs b/NextShip.Api/Bases/HostInfo.cs new file mode 100644 index 0000000..24e3296 --- /dev/null +++ b/NextShip.Api/Bases/HostInfo.cs @@ -0,0 +1,5 @@ +namespace NextShip.Api.Bases; + +public record HostInfo : NextInfo +{ +} \ No newline at end of file diff --git a/NextShip.Api/Bases/NextInfo.cs b/NextShip.Api/Bases/NextInfo.cs new file mode 100644 index 0000000..dc7fa87 --- /dev/null +++ b/NextShip.Api/Bases/NextInfo.cs @@ -0,0 +1,16 @@ +namespace NextShip.Api.Bases; + +public record NextInfo +{ + public int clientId; + + public RoleBase Role; + + public PlayerControl PlayerControl; + + public GameData.PlayerInfo PlayerInfo; + + public string PUID; + + public string FriendCode; +} \ No newline at end of file diff --git a/NextShip.Api/Bases/ShipTask.cs b/NextShip.Api/Bases/ShipTask.cs new file mode 100644 index 0000000..d9d4a6b --- /dev/null +++ b/NextShip.Api/Bases/ShipTask.cs @@ -0,0 +1,53 @@ +namespace NextShip.Api.Bases; + +public class ShipTask +{ + + public readonly TaskPriority TaskPriority; + private readonly TaskState TaskState; + public bool Loop; + public Func LoopEndConditions; + public Action Task; + public float Time; + public bool Update; + public Func UpdateConditions; + + public ShipTask(float time, Action task, TaskPriority taskPriority = TaskPriority.Low) + { + Task = task; + Time = time; + TaskState = new TaskState(); + Task += () => TaskState.Completed(); + TaskPriority = taskPriority; + } + + public TaskStateEnum GetState => TaskState.Get(); + + public void StartLoop(Func conditions = null) + { + Loop = true; + LoopEndConditions = conditions; + StartUpdate(); + } + + public void StopLoop() + { + Loop = false; + LoopEndConditions = null; + RemoveUpdate(); + } + + public void StartUpdate(Func conditions = null) + { + Update = true; + UpdateConditions = conditions; + Task -= () => TaskState.Completed(); + } + + public void RemoveUpdate() + { + Update = false; + UpdateConditions = null; + Task += () => TaskState.Completed(); + } +} \ No newline at end of file diff --git a/NextShip/UI/Components/TaskState.cs b/NextShip.Api/Bases/TaskState.cs similarity index 50% rename from NextShip/UI/Components/TaskState.cs rename to NextShip.Api/Bases/TaskState.cs index 7b204a8..e1ff294 100644 --- a/NextShip/UI/Components/TaskState.cs +++ b/NextShip.Api/Bases/TaskState.cs @@ -1,18 +1,11 @@ -using System; +namespace NextShip.Api.Bases; -namespace NextShip.UI.Components; - -public class TaskState +public sealed class TaskState { - private Action Action; - private TaskStateEnum StateEnum; - - public TaskState() - { - StateEnum = TaskStateEnum.None; - } + private Action? Action; + private TaskStateEnum StateEnum = TaskStateEnum.None; - public virtual TaskStateEnum Get() + public TaskStateEnum Get() { return StateEnum; } @@ -25,7 +18,7 @@ public void set(TaskStateEnum @enum) public void Completed() { StateEnum = TaskStateEnum.Completed; - Action(); + Action?.Invoke(); } public void AddAction(Action action) @@ -35,15 +28,7 @@ public void AddAction(Action action) public void RemoverAction(Action action) { + if (Action == null) return; Action -= action; } -} - -public enum TaskStateEnum -{ - None, - Waiting, - Processing, - Completed, - Failed } \ No newline at end of file diff --git a/NextShip.Api/Bases/UpdateTasker.cs b/NextShip.Api/Bases/UpdateTasker.cs new file mode 100644 index 0000000..1b4c22b --- /dev/null +++ b/NextShip.Api/Bases/UpdateTasker.cs @@ -0,0 +1,46 @@ +using HarmonyLib; + +namespace NextShip.Api.Bases; + +public class UpdateTasker +{ + public readonly List Tasks = new (); + + public void FixedUpdate() + { ; + if (Tasks == null) return; + + Tasks.Do(UpdateTaskTime); + Tasks.Where(n => n.TaskPriority == TaskPriority.High).Do(StartTask); + } + + public void LateUpdate() + { + Tasks.Do(StartTask); + Tasks.Do(CheckTask); + } + + private void StartTask(ShipTask task) + { + if (task.Time > 0) return; + + task.Task.Invoke(); + } + + private void CheckTask(ShipTask task) + { + if (task.LoopEndConditions != null && task.LoopEndConditions.Invoke()) task.StopLoop(); + + if (task.UpdateConditions != null && !task.UpdateConditions.Invoke()) task.RemoveUpdate(); + + if (task.GetState == TaskStateEnum.Completed) Tasks.Remove(task); + } + + private void UpdateTaskTime(ShipTask Task) + { + if (Task.Time > 1) + Task.Time -= 1; + else + Task.Time = 0; + } +} \ No newline at end of file diff --git a/NextShip.Api/Config/NextPaths.cs b/NextShip.Api/Config/NextPaths.cs deleted file mode 100644 index 3d7582c..0000000 --- a/NextShip.Api/Config/NextPaths.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Api.Config; - -public class NextPaths -{ -} \ No newline at end of file diff --git a/NextShip.Api/Enums/TaskPriority.cs b/NextShip.Api/Enums/TaskPriority.cs new file mode 100644 index 0000000..bee05aa --- /dev/null +++ b/NextShip.Api/Enums/TaskPriority.cs @@ -0,0 +1,8 @@ +namespace NextShip.Api.Enums; + +public enum TaskPriority +{ + High = 0, + Medium = 1, + Low = 2 +} \ No newline at end of file diff --git a/NextShip.Api/Enums/TaskStateEnum.cs b/NextShip.Api/Enums/TaskStateEnum.cs new file mode 100644 index 0000000..e4e5060 --- /dev/null +++ b/NextShip.Api/Enums/TaskStateEnum.cs @@ -0,0 +1,10 @@ +namespace NextShip.Api.Enums; + +public enum TaskStateEnum +{ + None, + Waiting, + Processing, + Completed, + Failed +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextEvent.cs b/NextShip.Api/Interfaces/INextEvent.cs index fa4cb85..f855402 100644 --- a/NextShip.Api/Interfaces/INextEvent.cs +++ b/NextShip.Api/Interfaces/INextEvent.cs @@ -7,4 +7,6 @@ public interface INextEvent public void OnRegister(IEventManager eventManager); public void OnUnRegister(IEventManager eventManager); + + public void Call(INextEvent @event); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextService.cs b/NextShip.Api/Interfaces/INextService.cs index ac0406d..41c8743 100644 --- a/NextShip.Api/Interfaces/INextService.cs +++ b/NextShip.Api/Interfaces/INextService.cs @@ -2,6 +2,7 @@ namespace NextShip.Api.Interfaces; public interface INextService { + public void Build(); public void Rebuild(); diff --git a/NextShip.Api/Interfaces/IRoleCreator.cs b/NextShip.Api/Interfaces/IRoleCreator.cs index 11851f6..354e1fe 100644 --- a/NextShip.Api/Interfaces/IRoleCreator.cs +++ b/NextShip.Api/Interfaces/IRoleCreator.cs @@ -1,6 +1,10 @@ namespace NextShip.Api.Interfaces; -public interface IRoleCreator +public interface IRoleCreator : IDisposable { public T Create(IRole role) where T : RoleBase; + + public T GetRole(PlayerControl player); + + public void Clear(); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IRoleManager.cs b/NextShip.Api/Interfaces/IRoleManager.cs new file mode 100644 index 0000000..f980761 --- /dev/null +++ b/NextShip.Api/Interfaces/IRoleManager.cs @@ -0,0 +1,12 @@ +namespace NextShip.Api.Interfaces; + +public interface IRoleManager +{ + public void Register(IRole role); + + public void UnRegister(IRole role); + + public void AddCreator(IRoleCreator creator); + + public void RemoveCreator(IRoleCreator creator); +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IServiceBuilder.cs b/NextShip.Api/Interfaces/IServiceBuilder.cs new file mode 100644 index 0000000..2fdd214 --- /dev/null +++ b/NextShip.Api/Interfaces/IServiceBuilder.cs @@ -0,0 +1,16 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace NextShip.Api.Interfaces; + +public interface IServiceBuilder +{ + public IServiceBuilder CreateService(); + + public IServiceBuilder Add() where T : class; + + public IServiceBuilder Add(Type type); + + public INextService Build(); + + public IServiceBuilder Set(ServiceCollection collection); +} \ No newline at end of file diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index d3d0982..9e434e4 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -4,6 +4,7 @@ net8.0 enable enable + embedded NextShip.Api 1.0.0 APIReadme.md diff --git a/NextShip.Api/Roles/RoleBase.cs b/NextShip.Api/Roles/RoleBase.cs index 365bc40..c906210 100644 --- a/NextShip.Api/Roles/RoleBase.cs +++ b/NextShip.Api/Roles/RoleBase.cs @@ -1,33 +1,20 @@ namespace NextShip.Api.Roles; -public abstract class RoleBase : IDisposable +public abstract class RoleBase(PlayerControl? player) : IDisposable { - protected RoleBase(PlayerControl? player) - { - CanKill = false; - CanVent = false; - HasTask = true; - WinCheck = () => false; - Player = player; - - Active = true; - RoleManager.Get().AllRoleBases.Add(this); - } - - public PlayerControl? Player { get; private set; } + public PlayerControl? Player { get; private set; } = player; - public Func WinCheck { get; } - public bool CanKill { get; } - public bool CanVent { get; } - public bool HasTask { get; } + public Func WinCheck { get; } = () => false; + public bool CanKill { get; } = false; + public bool CanVent { get; } = false; + public bool HasTask { get; } = true; - public bool Active { get; protected set; } + public bool Active { get; protected set; } = true; public void Dispose() { OnDestroy(); Player = null; - RoleManager.Get().AllRoleBases.Remove(this); } public virtual void RpcSyncWriter() diff --git a/NextShip.Api/Roles/RoleManager.Assaign.cs b/NextShip.Api/Roles/RoleManager.Assaign.cs deleted file mode 100644 index 6971beb..0000000 --- a/NextShip.Api/Roles/RoleManager.Assaign.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace NextShip.Api.Roles; - -public partial class RoleManager -{ - private RoleAssigner Assigner => RoleAssigner.Get(); - - public IEnumerator GetAssignRole(PlayerControl player) - { - Assign: - - if (!Assigner.Get(player, out var role)) - goto Assign; - - yield return role; - } -} - -public class RoleAssigner -{ - private static RoleAssigner Instance; - - private Random Random = new(); - - public List AllAssigns { private set; get; } = new(); - - public static RoleAssigner Get() - { - return Instance ??= new RoleAssigner(); - } - - public bool Get(PlayerControl player, out RoleBase? role) - { - role = AllAssigns.FirstOrDefault(n => n?.Player == player); - - return role != null; - } - - - public void Restore() - { - AllAssigns = new List(); - Random = new Random(); - } -} \ No newline at end of file diff --git a/NextShip.Api/Roles/RoleManager.Restore.cs b/NextShip.Api/Roles/RoleManager.Restore.cs deleted file mode 100644 index 640f51d..0000000 --- a/NextShip.Api/Roles/RoleManager.Restore.cs +++ /dev/null @@ -1,19 +0,0 @@ -using HarmonyLib; - -namespace NextShip.Api.Roles; - -public partial class RoleManager -{ - public void OnGameEnd(AmongUsClient __instance, EndGameResult endGameResult) - { - Restore(); - } - - public void Restore() - { - Assigner.Restore(); - - AllRoleBases.Do(n => n.Dispose()); - AllRoleBases.Clear(); - } -} \ No newline at end of file diff --git a/NextShip.Api/Roles/RoleManager.cs b/NextShip.Api/Roles/RoleManager.cs deleted file mode 100644 index 55332e7..0000000 --- a/NextShip.Api/Roles/RoleManager.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace NextShip.Api.Roles; - -public partial class RoleManager -{ - public static RoleManager Instance; - - public List AllRoleBases = new(); - public List AllSimpleRoleInfos = new(); - - - public static RoleManager Get() - { - return Instance ??= new RoleManager(); - } - - public List GetActiveRole() - { - return AllRoleBases.Where(n => n.Active).ToList(); - } - - - public T GetRole(PlayerControl playerControl) where T : RoleBase - { - return (T)AllRoleBases.FirstOrDefault(n => n.Player == playerControl)!; - } -} \ No newline at end of file diff --git a/NextShip.Api/Roles/SimpleRoleInfo.cs b/NextShip.Api/Roles/SimpleRoleInfo.cs index 6ee1e25..cbada02 100644 --- a/NextShip.Api/Roles/SimpleRoleInfo.cs +++ b/NextShip.Api/Roles/SimpleRoleInfo.cs @@ -2,39 +2,21 @@ namespace NextShip.Api.Roles; -public sealed class SimpleRoleInfo +public sealed class SimpleRoleInfo(RoleId id, + Color color, + RoleTeam team, + RoleType type, + string roleStringId, + string roleName, + int roleIntId) { - public string Name; - public Color RoleColor; - public RoleId roleId; - public int roleIntId; - public string RoleStringId; - public RoleTeam roleTeam; - public RoleType roleType; - - public SimpleRoleInfo - ( - RoleId id, - Color color, - RoleTeam team, - RoleType type, - string roleStringId, - string roleName, - int roleIntId - ) - { - RoleColor = color; - Name = roleName; - roleId = id; - this.roleIntId = roleIntId; - RoleStringId = roleStringId; - roleTeam = team; - roleType = type; - - // Add to RoleManager - - RoleManager.Get().AllSimpleRoleInfos.Add(this); - } + public string Name = roleName; + public Color RoleColor = color; + public RoleId roleId = id; + public int roleIntId = roleIntId; + public string RoleStringId = roleStringId; + public RoleTeam roleTeam = team; + public RoleType roleType = type; public SimpleRoleInfo ( diff --git a/NextShip.Api/Services/DownloadService.cs b/NextShip.Api/Services/DownloadService.cs index 3ce73b5..bcb39ac 100644 --- a/NextShip.Api/Services/DownloadService.cs +++ b/NextShip.Api/Services/DownloadService.cs @@ -1,5 +1,14 @@ +using Microsoft.Extensions.Logging; + namespace NextShip.Api.Services; -public class DownloadService +public abstract class DownloadService(ILogger logger,HttpClient httpClient) { + private readonly HttpClient _httpClient = httpClient; + private readonly ILogger _logger = logger; + + public void Download(Uri uri) + { + + } } \ No newline at end of file diff --git a/NextShip.Api/Services/MetadataService.cs b/NextShip.Api/Services/MetadataService.cs new file mode 100644 index 0000000..e792341 --- /dev/null +++ b/NextShip.Api/Services/MetadataService.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Services; + +public class MetadataService +{ + +} \ No newline at end of file diff --git a/NextShip/GlobalUsing.cs b/NextShip/GlobalUsing.cs index 10c855b..6a2e149 100644 --- a/NextShip/GlobalUsing.cs +++ b/NextShip/GlobalUsing.cs @@ -4,4 +4,5 @@ global using NextShip.Api.Utilities; global using static NextShip.Api.Logs.log; global using static NextShip.Api.Logs.FastLog; +global using static NextShip.Manager.EventManager; global using Main = NextShip.NextShip; \ No newline at end of file diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs index 73c86c7..9edce09 100644 --- a/NextShip/Manager/EventManager.cs +++ b/NextShip/Manager/EventManager.cs @@ -7,6 +7,8 @@ namespace NextShip.Manager; public class EventManager : IEventManager { + public static EventManager _eventManager = Main._Service.Get(); + private readonly List RegisterEvents = new(); public void RegisterEvent(INextEvent @event) @@ -21,6 +23,14 @@ public void UnRegisterEvent(INextEvent @event) RegisterEvents.Remove(@event); } + public void Call(INextEvent @event) + { + foreach (var _event in RegisterEvents.FindAll(n => n.EventName == @event.EventName)) + { + @event.Call(_event); + } + } + public bool TryGetEvent(string eventName, out INextEvent @event) { if (RegisterEvents.Any(n => n.EventName == eventName)) diff --git a/NextShip/Manager/LoadManager.cs b/NextShip/Manager/LoadManager.cs index 1f9b08c..9824432 100644 --- a/NextShip/Manager/LoadManager.cs +++ b/NextShip/Manager/LoadManager.cs @@ -53,8 +53,6 @@ public static IEnumerator Load(SplashManager __instance) logo.gameObject.transform.localPosition = new Vector3(0, 0, -5); text.gameObject.transform.localPosition = new Vector3(0.2f, -0.9f, -5); - /*logo.sprite = SpriteUtils.NextShipText_Sprite;*/ - text.text = "Loading....."; text.alignment = TextAlignmentOptions.Center; text.fontSize = 4.5f; @@ -108,8 +106,10 @@ private static void StartErrorScreen(Exception exception) public static void AccountManager_Awake_Patch() { var fill = GameObject.Find("BlockFill"); - var color = new Color(0, 0, 0); - color.a = 0.9f; + var color = new Color(0, 0, 0) + { + a = 0.9f + }; fill.GetComponent().color = color; var text = new GameObject("Text"); diff --git a/NextShip/Manager/NextPatchManager.cs b/NextShip/Manager/NextPatchManager.cs new file mode 100644 index 0000000..975f659 --- /dev/null +++ b/NextShip/Manager/NextPatchManager.cs @@ -0,0 +1,8 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public class NextPatchManager : IPatchManager +{ + public static NextPatchManager _NextPatchManager = Main._Service.Get(); +} \ No newline at end of file diff --git a/NextShip/Manager/RoleManager.cs b/NextShip/Manager/RoleManager.cs new file mode 100644 index 0000000..cddeee0 --- /dev/null +++ b/NextShip/Manager/RoleManager.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; +using System.Linq; +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public sealed class NextRoleManager : IRoleManager +{ + public readonly List Roles = new(); + + public readonly HashSet RoleCreators = new(); + + + public void Register(IRole role) => + Roles.Add(role); + + public void UnRegister(IRole role) + { + Roles.Remove(role); + } + + public void AddCreator(IRoleCreator creator) => + RoleCreators.Add(creator); + + public void RemoveCreator(IRoleCreator creator) => + RoleCreators.Remove(creator); + + public T GetRole() where T : IRole => (T)Roles.FirstOrDefault(n => n is T); + + public IEnumerable GetRoles() where T : IRole => Roles.FindAll(n => n is T).Select(n => (T)n); + + public T GetCreator() where T : IRoleCreator => (T)RoleCreators.FirstOrDefault(n => n is T); +} \ No newline at end of file diff --git a/NextShip/NextManager.cs b/NextShip/NextManager.cs new file mode 100644 index 0000000..31e2259 --- /dev/null +++ b/NextShip/NextManager.cs @@ -0,0 +1,37 @@ +using System; +using NextShip.Api.Attributes; +using NextShip.Api.Bases; +using UnityEngine; + +namespace NextShip; + +[Il2CppRegister] +public class NextManager : MonoBehaviour +{ + private static NextManager _instance; + + public static NextManager Instance => _instance ??= Main.Instance.AddComponent(); + + public UpdateTasker _Tasker; + + public NextManager() + { + _Tasker = new UpdateTasker(); + _instance = this; + } + + public void Update() + { + + } + + public void FixedUpdate() + { + _Tasker.FixedUpdate(); + } + + public void LateUpdate() + { + _Tasker.LateUpdate(); + } +} \ No newline at end of file diff --git a/NextShip/NextPaths.cs b/NextShip/NextPaths.cs new file mode 100644 index 0000000..09a6aeb --- /dev/null +++ b/NextShip/NextPaths.cs @@ -0,0 +1,15 @@ +using System.Collections; +using NextShip.Api.Attributes; +using NextShip.Api.Enums; + +namespace NextShip; + +[Load(LoadMode.PreLoad)] +public class NextPaths +{ + [Load] + public static IEnumerator PreLoad() + { + yield return null; + } +} \ No newline at end of file diff --git a/NextShip/NextService.cs b/NextShip/NextService.cs index 94729a4..93bb19d 100644 --- a/NextShip/NextService.cs +++ b/NextShip/NextService.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using NextShip.Api.Interfaces; @@ -6,21 +7,35 @@ namespace NextShip; public class NextService : INextService { - private ServiceCollection _collection = new(); + public static readonly HashSet Services = new (); + + public NextService() + { + Services.Add(this); + } + + public NextService(IServiceProvider provider) : this() + { + _Provider = provider; + BuildCompleted = true; + } + public IServiceProvider _Provider { get; private set; } private bool BuildCompleted { get; set; } + public static NextService Build(IServiceBuilder builder) + { + var service = builder.Build(); + service.Build(); + + return (NextService)service; + } + public void Build() { if (BuildCompleted) return; - if (_collection.Count != 0) - { - _Provider = _collection.BuildServiceProvider(); - return; - } - var collection = new ServiceCollection(); _Provider = collection.BuildServiceProvider(); @@ -35,17 +50,10 @@ public void Rebuild() public void Reset() { - _collection.Clear(); _Provider = null; BuildCompleted = false; } - public NextService Set(ServiceCollection collection) - { - _collection = collection; - return this; - } - public T Get() { return _Provider.GetService(); @@ -58,8 +66,6 @@ public object Get(Type type) public static NextService Build(ServiceCollection collection) { - var _Service = new NextService().Set(collection); - _Service.Build(); - return _Service; + return (NextService)new ServiceBuilder().Set(collection).Build(); } } \ No newline at end of file diff --git a/NextShip/ServiceBuilder.cs b/NextShip/ServiceBuilder.cs new file mode 100644 index 0000000..f667df8 --- /dev/null +++ b/NextShip/ServiceBuilder.cs @@ -0,0 +1,71 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using JetBrains.Annotations; +using Microsoft.Extensions.DependencyInjection; +using NextShip.Api.Interfaces; + +namespace NextShip; + +public class ServiceBuilder : IServiceBuilder +{ + public ServiceCollection _collection { get; private set; } + + public IServiceBuilder CreateService() + { + _collection = new ServiceCollection(); + return this; + } + + public IServiceBuilder AddLogging() + { + _collection.AddLogging(); + return this; + } + + public IServiceBuilder Add() where T : class + { + _collection.AddSingleton(); + return this; + } + + public IServiceBuilder Add(Type type) + { + _collection.AddSingleton(type); + return this; + } + + public IServiceBuilder AddScoped() where T : class + { + _collection.AddScoped(); + return this; + } + + public IServiceBuilder AddScoped(Type type) + { + _collection.AddScoped(type); + return this; + } + + public IServiceBuilder AddTransient() where T : class + { + _collection.AddTransient(); + return this; + } + + public IServiceBuilder AddTransient(Type type) + { + _collection.AddTransient(type); + return this; + } + + public INextService Build() + { + return new NextService(provider: _collection.BuildServiceProvider()); + } + + public IServiceBuilder Set(ServiceCollection collection) + { + _collection = collection; + return this; + } +} \ No newline at end of file diff --git a/NextShip/UI/Components/UpdateTask.cs b/NextShip/UI/Components/UpdateTask.cs deleted file mode 100644 index 8e327e8..0000000 --- a/NextShip/UI/Components/UpdateTask.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using HarmonyLib; -using UnityEngine; - -namespace NextShip.UI.Components; - -public class UpdateTask : MonoBehaviour -{ - public static List Tasks; - public bool startd; - - public UpdateTask() - { - Start(); - } - - public void Start() - { - Tasks = new List(); - startd = true; - } - - public void FixedUpdate() - { - if (!startd) return; - if (Tasks == null) return; - - Tasks.Do(UpdateTaskTime); - Tasks.Where(n => n.Priority == ShipTask.priority.High).Do(StartTask); - } - - public void LateUpdate() - { - if (!startd) return; - if (Tasks == null) return; - - Tasks.Do(StartTask); - Tasks.Do(CheckTask); - } - - private void StartTask(ShipTask task) - { - if (task.Time > 0) return; - - task.Task.Invoke(); - } - - private void CheckTask(ShipTask task) - { - if (task.LoopEndConditions != null && task.LoopEndConditions.Invoke()) task.StopLoop(); - - if (task.UpdateConditions != null && !task.UpdateConditions.Invoke()) task.RemoveUpdate(); - - if (task.GetState == TaskStateEnum.Completed) Tasks.Remove(task); - } - - private void UpdateTaskTime(ShipTask Task) - { - if (Task.Time > 1) - Task.Time -= 1; - else - Task.Time = 0; - } -} - -public class ShipTask -{ - public enum priority - { - High = 0, - Medium = 1, - Low = 2 - } - - public readonly priority Priority; - private readonly TaskState TaskState; - public bool Loop; - public Func LoopEndConditions; - public Action Task; - public float Time; - public bool Update; - public Func UpdateConditions; - - public ShipTask(float time, Action task, priority priority = priority.Low) - { - Task = task; - Time = time; - TaskState = new TaskState(); - Task += () => TaskState.Completed(); - Priority = priority; - } - - public TaskStateEnum GetState => TaskState.Get(); - - public void StartLoop(Func conditions = null) - { - Loop = true; - LoopEndConditions = conditions; - StartUpdate(); - } - - public void StopLoop() - { - Loop = false; - LoopEndConditions = null; - RemoveUpdate(); - } - - public void StartUpdate(Func conditions = null) - { - Update = true; - UpdateConditions = conditions; - Task -= () => TaskState.Completed(); - } - - public void RemoveUpdate() - { - Update = false; - UpdateConditions = null; - Task += () => TaskState.Completed(); - } - - public void register() - { - UpdateTask.Tasks.Add(this); - } -} - -public class LastShipTask : ShipTask -{ - public LastShipTask(float time, Action task) : base(time, task, priority.High) - { - } -} \ No newline at end of file diff --git a/NextShip/main.cs b/NextShip/main.cs index 7c68e8e..2ef5f2e 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -1,9 +1,13 @@ using System.Globalization; +using System.Net.Http; using System.Reflection; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using HarmonyLib; +using Microsoft.Extensions.DependencyInjection; +using NextShip.Api.Interfaces; +using NextShip.Api.Services; using NextShip.Cosmetics; using NextShip.Languages; using NextShip.Manager; @@ -27,40 +31,40 @@ public sealed class NextShip : BasePlugin public const string Id = "cn.MengChu.NextShip"; // 模组版本 - public const string VersionString = "100.0"; + public const string VersionString = "1.0.0"; // Among Us游玩版本 public static readonly AmongUsVersion SupportVersion = new(2023, 10, 24); + + public static NextService _Service { get; private set; } - - internal static ManualLogSource TISLog; - - public static NextShip Instance; + public static NextShip Instance { get; private set; } internal static readonly ServerManager serverManager = FastDestroyableSingleton.Instance; + + private ManualLogSource TISLog; + private Harmony Harmony { get; } = new(Id); public override void Load() { - ConsoleManager.SetConsoleTitle("Among Us " + ModName + " Game"); + Instance = this; TISLog = BepInExLogger.CreateLogSource(ModName.RemoveBlank()); - + Harmony.PatchAll(); + Init(); Get(TISLog); + CreateService(); + + ConsoleManager.SetConsoleTitle("Among Us " + ModName + " Game"); + RegisterManager.Registration(); - Instance = this; - Harmony.PatchAll(); - + AddComponent().DontDestroyOnLoad(); + FilesManager.Init(); ServerPath.autoAddServer(); - - RegisterManager.Registration(); - - AddComponent(); - LanguagePack.Init(); - CustomCosmeticsManager.LoadHat(); } @@ -74,4 +78,20 @@ private static void Init() Info("Hash: ", "Info"); Info($"欢迎游玩{ModName} | Welcome to{ModName}", "Info"); } + + + private static void CreateService() + { + var builder = new ServiceBuilder(); + builder.CreateService(); + builder._collection.AddLogging(); + builder._collection.AddSingleton(); + builder._collection.AddSingleton(); + builder._collection.AddSingleton(); + builder.AddTransient(); + builder.Add(); + builder.Add(); + + _Service = NextService.Build(builder); + } } \ No newline at end of file From 784b219e9473d56f179a16e1f088b1533045434a Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Sat, 9 Dec 2023 12:26:43 +0800 Subject: [PATCH 10/29] =?UTF-8?q?IDE=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E5=8C=96=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NextShip.Api/Bases/NextInfo.cs | 4 +-- NextShip.Api/Bases/ShipTask.cs | 1 - NextShip.Api/Bases/UpdateTasker.cs | 23 ++++++------- NextShip.Api/Interfaces/INextService.cs | 1 - NextShip.Api/Interfaces/IRoleManager.cs | 4 +-- NextShip.Api/Services/DownloadService.cs | 3 +- NextShip.Api/Services/MetadataService.cs | 1 - NextShip/Manager/EventManager.cs | 7 ++-- NextShip/Manager/RoleManager.cs | 36 +++++++++++++------- NextShip/NextManager.cs | 6 ++-- NextShip/NextService.cs | 20 +++++------ NextShip/ServiceBuilder.cs | 42 +++++++++++------------- NextShip/main.cs | 21 ++++++------ 13 files changed, 86 insertions(+), 83 deletions(-) diff --git a/NextShip.Api/Bases/NextInfo.cs b/NextShip.Api/Bases/NextInfo.cs index dc7fa87..70effb2 100644 --- a/NextShip.Api/Bases/NextInfo.cs +++ b/NextShip.Api/Bases/NextInfo.cs @@ -4,7 +4,7 @@ public record NextInfo { public int clientId; - public RoleBase Role; + public string FriendCode; public PlayerControl PlayerControl; @@ -12,5 +12,5 @@ public record NextInfo public string PUID; - public string FriendCode; + public RoleBase Role; } \ No newline at end of file diff --git a/NextShip.Api/Bases/ShipTask.cs b/NextShip.Api/Bases/ShipTask.cs index d9d4a6b..79a6ee9 100644 --- a/NextShip.Api/Bases/ShipTask.cs +++ b/NextShip.Api/Bases/ShipTask.cs @@ -2,7 +2,6 @@ namespace NextShip.Api.Bases; public class ShipTask { - public readonly TaskPriority TaskPriority; private readonly TaskState TaskState; public bool Loop; diff --git a/NextShip.Api/Bases/UpdateTasker.cs b/NextShip.Api/Bases/UpdateTasker.cs index 1b4c22b..76fca95 100644 --- a/NextShip.Api/Bases/UpdateTasker.cs +++ b/NextShip.Api/Bases/UpdateTasker.cs @@ -4,38 +4,39 @@ namespace NextShip.Api.Bases; public class UpdateTasker { - public readonly List Tasks = new (); - + public readonly List Tasks = new(); + public void FixedUpdate() - { ; + { + ; if (Tasks == null) return; - + Tasks.Do(UpdateTaskTime); Tasks.Where(n => n.TaskPriority == TaskPriority.High).Do(StartTask); } - + public void LateUpdate() { Tasks.Do(StartTask); Tasks.Do(CheckTask); } - + private void StartTask(ShipTask task) { if (task.Time > 0) return; - + task.Task.Invoke(); } - + private void CheckTask(ShipTask task) { if (task.LoopEndConditions != null && task.LoopEndConditions.Invoke()) task.StopLoop(); - + if (task.UpdateConditions != null && !task.UpdateConditions.Invoke()) task.RemoveUpdate(); - + if (task.GetState == TaskStateEnum.Completed) Tasks.Remove(task); } - + private void UpdateTaskTime(ShipTask Task) { if (Task.Time > 1) diff --git a/NextShip.Api/Interfaces/INextService.cs b/NextShip.Api/Interfaces/INextService.cs index 41c8743..ac0406d 100644 --- a/NextShip.Api/Interfaces/INextService.cs +++ b/NextShip.Api/Interfaces/INextService.cs @@ -2,7 +2,6 @@ namespace NextShip.Api.Interfaces; public interface INextService { - public void Build(); public void Rebuild(); diff --git a/NextShip.Api/Interfaces/IRoleManager.cs b/NextShip.Api/Interfaces/IRoleManager.cs index f980761..187e2e2 100644 --- a/NextShip.Api/Interfaces/IRoleManager.cs +++ b/NextShip.Api/Interfaces/IRoleManager.cs @@ -3,9 +3,9 @@ namespace NextShip.Api.Interfaces; public interface IRoleManager { public void Register(IRole role); - + public void UnRegister(IRole role); - + public void AddCreator(IRoleCreator creator); public void RemoveCreator(IRoleCreator creator); diff --git a/NextShip.Api/Services/DownloadService.cs b/NextShip.Api/Services/DownloadService.cs index bcb39ac..d88dd80 100644 --- a/NextShip.Api/Services/DownloadService.cs +++ b/NextShip.Api/Services/DownloadService.cs @@ -2,13 +2,12 @@ namespace NextShip.Api.Services; -public abstract class DownloadService(ILogger logger,HttpClient httpClient) +public abstract class DownloadService(ILogger logger, HttpClient httpClient) { private readonly HttpClient _httpClient = httpClient; private readonly ILogger _logger = logger; public void Download(Uri uri) { - } } \ No newline at end of file diff --git a/NextShip.Api/Services/MetadataService.cs b/NextShip.Api/Services/MetadataService.cs index e792341..47c8416 100644 --- a/NextShip.Api/Services/MetadataService.cs +++ b/NextShip.Api/Services/MetadataService.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Services; public class MetadataService { - } \ No newline at end of file diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs index 9edce09..97c3f59 100644 --- a/NextShip/Manager/EventManager.cs +++ b/NextShip/Manager/EventManager.cs @@ -8,7 +8,7 @@ namespace NextShip.Manager; public class EventManager : IEventManager { public static EventManager _eventManager = Main._Service.Get(); - + private readonly List RegisterEvents = new(); public void RegisterEvent(INextEvent @event) @@ -25,10 +25,7 @@ public void UnRegisterEvent(INextEvent @event) public void Call(INextEvent @event) { - foreach (var _event in RegisterEvents.FindAll(n => n.EventName == @event.EventName)) - { - @event.Call(_event); - } + foreach (var _event in RegisterEvents.FindAll(n => n.EventName == @event.EventName)) @event.Call(_event); } public bool TryGetEvent(string eventName, out INextEvent @event) diff --git a/NextShip/Manager/RoleManager.cs b/NextShip/Manager/RoleManager.cs index cddeee0..598130f 100644 --- a/NextShip/Manager/RoleManager.cs +++ b/NextShip/Manager/RoleManager.cs @@ -6,28 +6,42 @@ namespace NextShip.Manager; public sealed class NextRoleManager : IRoleManager { + public readonly HashSet RoleCreators = new(); public readonly List Roles = new(); - public readonly HashSet RoleCreators = new(); - - - public void Register(IRole role) => + + public void Register(IRole role) + { Roles.Add(role); + } public void UnRegister(IRole role) { Roles.Remove(role); } - public void AddCreator(IRoleCreator creator) => + public void AddCreator(IRoleCreator creator) + { RoleCreators.Add(creator); + } - public void RemoveCreator(IRoleCreator creator) => + public void RemoveCreator(IRoleCreator creator) + { RoleCreators.Remove(creator); + } - public T GetRole() where T : IRole => (T)Roles.FirstOrDefault(n => n is T); - - public IEnumerable GetRoles() where T : IRole => Roles.FindAll(n => n is T).Select(n => (T)n); - - public T GetCreator() where T : IRoleCreator => (T)RoleCreators.FirstOrDefault(n => n is T); + public T GetRole() where T : IRole + { + return (T)Roles.FirstOrDefault(n => n is T); + } + + public IEnumerable GetRoles() where T : IRole + { + return Roles.FindAll(n => n is T).Select(n => (T)n); + } + + public T GetCreator() where T : IRoleCreator + { + return (T)RoleCreators.FirstOrDefault(n => n is T); + } } \ No newline at end of file diff --git a/NextShip/NextManager.cs b/NextShip/NextManager.cs index 31e2259..3ee267c 100644 --- a/NextShip/NextManager.cs +++ b/NextShip/NextManager.cs @@ -1,4 +1,3 @@ -using System; using NextShip.Api.Attributes; using NextShip.Api.Bases; using UnityEngine; @@ -9,8 +8,6 @@ namespace NextShip; public class NextManager : MonoBehaviour { private static NextManager _instance; - - public static NextManager Instance => _instance ??= Main.Instance.AddComponent(); public UpdateTasker _Tasker; @@ -20,9 +17,10 @@ public NextManager() _instance = this; } + public static NextManager Instance => _instance ??= Main.Instance.AddComponent(); + public void Update() { - } public void FixedUpdate() diff --git a/NextShip/NextService.cs b/NextShip/NextService.cs index 93bb19d..b095ffb 100644 --- a/NextShip/NextService.cs +++ b/NextShip/NextService.cs @@ -7,13 +7,13 @@ namespace NextShip; public class NextService : INextService { - public static readonly HashSet Services = new (); + public static readonly HashSet Services = new(); public NextService() { Services.Add(this); } - + public NextService(IServiceProvider provider) : this() { _Provider = provider; @@ -24,14 +24,6 @@ public NextService(IServiceProvider provider) : this() private bool BuildCompleted { get; set; } - public static NextService Build(IServiceBuilder builder) - { - var service = builder.Build(); - service.Build(); - - return (NextService)service; - } - public void Build() { if (BuildCompleted) return; @@ -54,6 +46,14 @@ public void Reset() BuildCompleted = false; } + public static NextService Build(IServiceBuilder builder) + { + var service = builder.Build(); + service.Build(); + + return (NextService)service; + } + public T Get() { return _Provider.GetService(); diff --git a/NextShip/ServiceBuilder.cs b/NextShip/ServiceBuilder.cs index f667df8..7087975 100644 --- a/NextShip/ServiceBuilder.cs +++ b/NextShip/ServiceBuilder.cs @@ -1,6 +1,4 @@ using System; -using System.Diagnostics.CodeAnalysis; -using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using NextShip.Api.Interfaces; @@ -9,19 +7,13 @@ namespace NextShip; public class ServiceBuilder : IServiceBuilder { public ServiceCollection _collection { get; private set; } - + public IServiceBuilder CreateService() { _collection = new ServiceCollection(); return this; } - public IServiceBuilder AddLogging() - { - _collection.AddLogging(); - return this; - } - public IServiceBuilder Add() where T : class { _collection.AddSingleton(); @@ -34,18 +26,35 @@ public IServiceBuilder Add(Type type) return this; } + public INextService Build() + { + return new NextService(_collection.BuildServiceProvider()); + } + + public IServiceBuilder Set(ServiceCollection collection) + { + _collection = collection; + return this; + } + + public IServiceBuilder AddLogging() + { + _collection.AddLogging(); + return this; + } + public IServiceBuilder AddScoped() where T : class { _collection.AddScoped(); return this; } - + public IServiceBuilder AddScoped(Type type) { _collection.AddScoped(type); return this; } - + public IServiceBuilder AddTransient() where T : class { _collection.AddTransient(); @@ -57,15 +66,4 @@ public IServiceBuilder AddTransient(Type type) _collection.AddTransient(type); return this; } - - public INextService Build() - { - return new NextService(provider: _collection.BuildServiceProvider()); - } - - public IServiceBuilder Set(ServiceCollection collection) - { - _collection = collection; - return this; - } } \ No newline at end of file diff --git a/NextShip/main.cs b/NextShip/main.cs index 2ef5f2e..8a88dea 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -12,7 +12,6 @@ using NextShip.Languages; using NextShip.Manager; using NextShip.Patches; -using NextShip.UI.UIManager; using BepInExLogger = BepInEx.Logging.Logger; [assembly: AssemblyFileVersion(Main.VersionString)] @@ -35,15 +34,15 @@ public sealed class NextShip : BasePlugin // Among Us游玩版本 public static readonly AmongUsVersion SupportVersion = new(2023, 10, 24); - - public static NextService _Service { get; private set; } - - public static NextShip Instance { get; private set; } internal static readonly ServerManager serverManager = FastDestroyableSingleton.Instance; - + private ManualLogSource TISLog; - + + public static NextService _Service { get; private set; } + + public static NextShip Instance { get; private set; } + private Harmony Harmony { get; } = new(Id); @@ -52,16 +51,16 @@ public override void Load() Instance = this; TISLog = BepInExLogger.CreateLogSource(ModName.RemoveBlank()); Harmony.PatchAll(); - + Init(); Get(TISLog); CreateService(); - + ConsoleManager.SetConsoleTitle("Among Us " + ModName + " Game"); RegisterManager.Registration(); AddComponent().DontDestroyOnLoad(); - + FilesManager.Init(); ServerPath.autoAddServer(); LanguagePack.Init(); @@ -91,7 +90,7 @@ private static void CreateService() builder.AddTransient(); builder.Add(); builder.Add(); - + _Service = NextService.Build(builder); } } \ No newline at end of file From d5a478e861a1a885b9a4d21b3311c644bcf751cc Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Sun, 10 Dec 2023 15:41:48 +0800 Subject: [PATCH 11/29] Update --- NextShip.Api/Extension/DevExtension.cs | 36 +++++++++++++++ NextShip.Api/Extension/NextUIExtension.cs | 11 +++++ NextShip.Api/GlobalUsing.cs | 1 + NextShip.Api/Managers/AssetManager.cs | 46 +++++++++++++++++++ NextShip.Api/UI/NextUI.cs | 34 ++++++++++++++ NextShip.Api/UI/NextUIManager.cs | 29 ++++++++++++ NextShip.Api/Utilities/AssetLoader.cs | 56 +++-------------------- NextShip.Api/Utils/StreamUtils.cs | 8 +++- NextShip/NextManager.cs | 2 + NextShip/main.cs | 4 ++ 10 files changed, 177 insertions(+), 50 deletions(-) create mode 100644 NextShip.Api/Extension/DevExtension.cs create mode 100644 NextShip.Api/Extension/NextUIExtension.cs create mode 100644 NextShip.Api/Managers/AssetManager.cs create mode 100644 NextShip.Api/UI/NextUI.cs create mode 100644 NextShip.Api/UI/NextUIManager.cs diff --git a/NextShip.Api/Extension/DevExtension.cs b/NextShip.Api/Extension/DevExtension.cs new file mode 100644 index 0000000..9932597 --- /dev/null +++ b/NextShip.Api/Extension/DevExtension.cs @@ -0,0 +1,36 @@ +namespace NextShip.Api.Extension; + +public static class DevExtension +{ + private static bool Start; + + public static void UseDevExtension() + { + if (Start) + return; + + try + { + Start = true; + } + catch (Exception e) + { + Exception(e); + } + + } + + public static void DisableDev() + { + try + { + + } + catch (Exception e) + { + Exception(e); + } + + Start = false; + } +} \ No newline at end of file diff --git a/NextShip.Api/Extension/NextUIExtension.cs b/NextShip.Api/Extension/NextUIExtension.cs new file mode 100644 index 0000000..d88469a --- /dev/null +++ b/NextShip.Api/Extension/NextUIExtension.cs @@ -0,0 +1,11 @@ +using NextShip.Api.UI; + +namespace NextShip.Api.Extension; + +public static class NextUIExtension +{ + public static NextUI UseTextBox(this NextUI nextUI) + { + return nextUI; + } +} \ No newline at end of file diff --git a/NextShip.Api/GlobalUsing.cs b/NextShip.Api/GlobalUsing.cs index be1d99e..c3fde4c 100644 --- a/NextShip.Api/GlobalUsing.cs +++ b/NextShip.Api/GlobalUsing.cs @@ -6,5 +6,6 @@ global using NextShip.Api.Bases; global using NextShip.Api.Attributes; global using NextShip.Api.Logs; +global using static NextShip.Api.Utils.StreamUtils; global using static NextShip.Api.APIHarmony; global using static NextShip.Api.Logs.FastLog; \ No newline at end of file diff --git a/NextShip.Api/Managers/AssetManager.cs b/NextShip.Api/Managers/AssetManager.cs new file mode 100644 index 0000000..c192f71 --- /dev/null +++ b/NextShip.Api/Managers/AssetManager.cs @@ -0,0 +1,46 @@ +using UnityEngine; + +namespace NextShip.Api.Managers; + +public class AssetManager +{ + public static AssetManager? Instance; + private readonly List _assetBundles = new(); + + private readonly List _assetLoaders = new(); + + public static AssetManager Get() + { + return Instance ??= new AssetManager(); + } + + public IReadOnlyList GetLoaders() + { + return _assetLoaders; + } + + public IReadOnlyList GetAssetS() + { + return _assetBundles; + } + + public void Add(AssetLoader? assetLoader) + { + _assetLoaders.Add(assetLoader); + } + + public void Add(AssetBundle? assetBundle) + { + _assetBundles.Add(assetBundle); + } + + public void Remove(AssetLoader? assetLoader) + { + _assetLoaders.Remove(assetLoader); + } + + public AssetLoader? GetLoader(string name) + { + return _assetLoaders.Find(n => name == n?.FileName || name == n?.LoaderName); + } +} \ No newline at end of file diff --git a/NextShip.Api/UI/NextUI.cs b/NextShip.Api/UI/NextUI.cs new file mode 100644 index 0000000..5995f79 --- /dev/null +++ b/NextShip.Api/UI/NextUI.cs @@ -0,0 +1,34 @@ +using UnityEngine; + +namespace NextShip.Api.UI; + +public class NextUI : IDisposable +{ + public string UIName { get; set; } = "NoName"; + + public int IntId; + + public TaskStateEnum State; + + public NextUI() + { + State = TaskStateEnum.None; + IntId = NextUIManager.Instance.AllCount; + NextUIManager.Instance.Add(this); + } + + public static NextUI StartUI(GameObject gameObject) + { + return new NextUI(); + } + + public void Update() + { + + } + + public void Dispose() + { + State = TaskStateEnum.Completed; + } +} \ No newline at end of file diff --git a/NextShip.Api/UI/NextUIManager.cs b/NextShip.Api/UI/NextUIManager.cs new file mode 100644 index 0000000..bde4a24 --- /dev/null +++ b/NextShip.Api/UI/NextUIManager.cs @@ -0,0 +1,29 @@ +namespace NextShip.Api.UI; + +public class NextUIManager +{ + private static NextUIManager? _instance; + + public static NextUIManager Instance => _instance ??= new NextUIManager(); + + + private readonly HashSet UIs = new(); + + private readonly Queue UIsQueue = new(); + + public int AllCount => UIs.Count; + + public void Add(NextUI nextUI) => UIs.Add(nextUI); + + public void Start(NextUI ui) => UIsQueue.Enqueue(ui); + + public void Update() + { + var ui = UIsQueue.Dequeue(); + + ui.Update(); + + if (ui.State != TaskStateEnum.Completed) + UIsQueue.Enqueue(ui); + } +} \ No newline at end of file diff --git a/NextShip.Api/Utilities/AssetLoader.cs b/NextShip.Api/Utilities/AssetLoader.cs index d7ace5e..7173ffe 100644 --- a/NextShip.Api/Utilities/AssetLoader.cs +++ b/NextShip.Api/Utilities/AssetLoader.cs @@ -1,5 +1,6 @@ using System.Reflection; using Il2CppInterop.Runtime.InteropTypes; +using NextShip.Api.Managers; using UnityEngine; using SystemFile = System.IO; using Il2cppFile = Il2CppSystem.IO.File; @@ -37,17 +38,17 @@ public List LoadAll() where T : Il2CppObjectBase return Asset.LoadAllAsset().ToList(); } - /*public AssetLoader LoadFromDisk() + public AssetLoader LoadFromDisk() { if (FileName is "" or null) return this; - - var directory = FilesManager.GetDataDirectory("/Assets"); - var bytes = Il2cppFile.ReadAllBytes(SystemFile.Path.Combine(directory.FullName, "Assets", FileName)); + + var directory = GetDir("Assets"); + var bytes = Il2cppFile.ReadAllBytes(Path.Combine(directory.FullName, FileName)); Asset = AssetBundle.LoadFromMemory(bytes); loaded = true; AssetManager.Get().Add(Asset); return this; - }*/ + } public AssetLoader LoadFromResources(Assembly assembly) { @@ -62,7 +63,7 @@ public AssetLoader LoadFromResources(Assembly assembly) return this; } - public void Add() + private void Add() { AssetManager.Get().Add(this); } @@ -72,46 +73,3 @@ public void Remove() AssetManager.Get().Remove(this); } } - -public class AssetManager -{ - public static AssetManager? Instance; - private readonly List _assetBundles = new(); - - private readonly List _assetLoaders = new(); - - public static AssetManager Get() - { - return Instance ??= new AssetManager(); - } - - public IReadOnlyList GetLoaders() - { - return _assetLoaders; - } - - public IReadOnlyList GetAssetS() - { - return _assetBundles; - } - - public void Add(AssetLoader? assetLoader) - { - _assetLoaders.Add(assetLoader); - } - - public void Add(AssetBundle? assetBundle) - { - _assetBundles.Add(assetBundle); - } - - public void Remove(AssetLoader? assetLoader) - { - _assetLoaders.Remove(assetLoader); - } - - public AssetLoader? GetLoader(string name) - { - return _assetLoaders.Find(n => name == n.FileName || name == n.LoaderName); - } -} \ No newline at end of file diff --git a/NextShip.Api/Utils/StreamUtils.cs b/NextShip.Api/Utils/StreamUtils.cs index e192cc0..176360a 100644 --- a/NextShip.Api/Utils/StreamUtils.cs +++ b/NextShip.Api/Utils/StreamUtils.cs @@ -10,6 +10,12 @@ namespace NextShip.Api.Utils; public static class StreamUtils { + public static DirectoryInfo GetDir(string name) + { + var path = $"./{name}"; + return Directory.Exists(path) ? new DirectoryInfo(path) : Directory.CreateDirectory(path); + } + public static Stream? GetStreamFormRes(this Assembly assembly, params string[] path) { return assembly.GetManifestResourceStream(string.Join(".", path)); @@ -20,7 +26,7 @@ public static class StreamUtils public static byte[] ReadFully(this Stream? input) { using var ms = new MemoryStream(); - input.CopyTo(ms); + input?.CopyTo(ms); return ms.ToArray(); } diff --git a/NextShip/NextManager.cs b/NextShip/NextManager.cs index 3ee267c..2b9f281 100644 --- a/NextShip/NextManager.cs +++ b/NextShip/NextManager.cs @@ -1,5 +1,6 @@ using NextShip.Api.Attributes; using NextShip.Api.Bases; +using NextShip.Api.UI; using UnityEngine; namespace NextShip; @@ -21,6 +22,7 @@ public NextManager() public void Update() { + NextUIManager.Instance.Update(); } public void FixedUpdate() diff --git a/NextShip/main.cs b/NextShip/main.cs index 8a88dea..1625991 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -6,6 +6,7 @@ using BepInEx.Unity.IL2CPP; using HarmonyLib; using Microsoft.Extensions.DependencyInjection; +using NextShip.Api.Extension; using NextShip.Api.Interfaces; using NextShip.Api.Services; using NextShip.Cosmetics; @@ -55,6 +56,9 @@ public override void Load() Init(); Get(TISLog); CreateService(); + + SteamExtension.UseSteamIdFile(); + ReactorExtension.UseReactorHandshake(); ConsoleManager.SetConsoleTitle("Among Us " + ModName + " Game"); RegisterManager.Registration(); From 62f4af8134e89ee40b0a90c412b899bbf49b2c26 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Sun, 10 Dec 2023 15:42:54 +0800 Subject: [PATCH 12/29] =?UTF-8?q?IDE=E6=A0=BC=E5=BC=8F=E5=8C=96=E6=B8=85?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NextShip.Api/Extension/DevExtension.cs | 6 ++---- NextShip.Api/UI/NextUI.cs | 17 ++++++++--------- NextShip.Api/UI/NextUIManager.cs | 20 +++++++++++++------- NextShip.Api/Utilities/AssetLoader.cs | 4 ++-- NextShip.Api/Utils/StreamUtils.cs | 2 +- NextShip/main.cs | 2 +- 6 files changed, 27 insertions(+), 24 deletions(-) diff --git a/NextShip.Api/Extension/DevExtension.cs b/NextShip.Api/Extension/DevExtension.cs index 9932597..1bbd9be 100644 --- a/NextShip.Api/Extension/DevExtension.cs +++ b/NextShip.Api/Extension/DevExtension.cs @@ -3,7 +3,7 @@ namespace NextShip.Api.Extension; public static class DevExtension { private static bool Start; - + public static void UseDevExtension() { if (Start) @@ -17,20 +17,18 @@ public static void UseDevExtension() { Exception(e); } - } public static void DisableDev() { try { - } catch (Exception e) { Exception(e); } - + Start = false; } } \ No newline at end of file diff --git a/NextShip.Api/UI/NextUI.cs b/NextShip.Api/UI/NextUI.cs index 5995f79..fb9bdb3 100644 --- a/NextShip.Api/UI/NextUI.cs +++ b/NextShip.Api/UI/NextUI.cs @@ -4,8 +4,6 @@ namespace NextShip.Api.UI; public class NextUI : IDisposable { - public string UIName { get; set; } = "NoName"; - public int IntId; public TaskStateEnum State; @@ -16,7 +14,14 @@ public NextUI() IntId = NextUIManager.Instance.AllCount; NextUIManager.Instance.Add(this); } - + + public string UIName { get; set; } = "NoName"; + + public void Dispose() + { + State = TaskStateEnum.Completed; + } + public static NextUI StartUI(GameObject gameObject) { return new NextUI(); @@ -24,11 +29,5 @@ public static NextUI StartUI(GameObject gameObject) public void Update() { - - } - - public void Dispose() - { - State = TaskStateEnum.Completed; } } \ No newline at end of file diff --git a/NextShip.Api/UI/NextUIManager.cs b/NextShip.Api/UI/NextUIManager.cs index bde4a24..9a6ccca 100644 --- a/NextShip.Api/UI/NextUIManager.cs +++ b/NextShip.Api/UI/NextUIManager.cs @@ -3,26 +3,32 @@ namespace NextShip.Api.UI; public class NextUIManager { private static NextUIManager? _instance; - - public static NextUIManager Instance => _instance ??= new NextUIManager(); private readonly HashSet UIs = new(); - + private readonly Queue UIsQueue = new(); + public static NextUIManager Instance => _instance ??= new NextUIManager(); + public int AllCount => UIs.Count; - public void Add(NextUI nextUI) => UIs.Add(nextUI); + public void Add(NextUI nextUI) + { + UIs.Add(nextUI); + } - public void Start(NextUI ui) => UIsQueue.Enqueue(ui); + public void Start(NextUI ui) + { + UIsQueue.Enqueue(ui); + } public void Update() { var ui = UIsQueue.Dequeue(); - + ui.Update(); - + if (ui.State != TaskStateEnum.Completed) UIsQueue.Enqueue(ui); } diff --git a/NextShip.Api/Utilities/AssetLoader.cs b/NextShip.Api/Utilities/AssetLoader.cs index 7173ffe..f6e0872 100644 --- a/NextShip.Api/Utilities/AssetLoader.cs +++ b/NextShip.Api/Utilities/AssetLoader.cs @@ -41,7 +41,7 @@ public List LoadAll() where T : Il2CppObjectBase public AssetLoader LoadFromDisk() { if (FileName is "" or null) return this; - + var directory = GetDir("Assets"); var bytes = Il2cppFile.ReadAllBytes(Path.Combine(directory.FullName, FileName)); Asset = AssetBundle.LoadFromMemory(bytes); @@ -72,4 +72,4 @@ public void Remove() { AssetManager.Get().Remove(this); } -} +} \ No newline at end of file diff --git a/NextShip.Api/Utils/StreamUtils.cs b/NextShip.Api/Utils/StreamUtils.cs index 176360a..ec6958b 100644 --- a/NextShip.Api/Utils/StreamUtils.cs +++ b/NextShip.Api/Utils/StreamUtils.cs @@ -15,7 +15,7 @@ public static DirectoryInfo GetDir(string name) var path = $"./{name}"; return Directory.Exists(path) ? new DirectoryInfo(path) : Directory.CreateDirectory(path); } - + public static Stream? GetStreamFormRes(this Assembly assembly, params string[] path) { return assembly.GetManifestResourceStream(string.Join(".", path)); diff --git a/NextShip/main.cs b/NextShip/main.cs index 1625991..e6b9b91 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -56,7 +56,7 @@ public override void Load() Init(); Get(TISLog); CreateService(); - + SteamExtension.UseSteamIdFile(); ReactorExtension.UseReactorHandshake(); From 76fdfd03ea80b1b6cae8a858f22753ef47aac086 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Tue, 12 Dec 2023 14:39:41 +0800 Subject: [PATCH 13/29] Update --- .../Attributes/Il2CppRegisterAttribute.cs | 30 ++++----- NextShip.Api/Attributes/LoadAttribute.cs | 65 ++++++++++--------- NextShip.Api/Attributes/ServiceAdd.cs | 21 ++++++ NextShip.Api/Interfaces/IKeyBindManager.cs | 6 ++ NextShip.Api/UI/CommonScreenCreator.cs | 8 +++ NextShip.Api/Utils/ListUtils.cs | 1 + NextShip.Api/Utils/MethodUtils.cs | 22 ++++++- NextShip/Manager/LoadManager.cs | 2 +- NextShip/main.cs | 5 ++ 9 files changed, 111 insertions(+), 49 deletions(-) create mode 100644 NextShip.Api/Attributes/ServiceAdd.cs create mode 100644 NextShip.Api/Interfaces/IKeyBindManager.cs create mode 100644 NextShip.Api/UI/CommonScreenCreator.cs diff --git a/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs b/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs index ae6a2b1..65e98e5 100644 --- a/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs +++ b/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs @@ -5,40 +5,38 @@ namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Class)] -public sealed class Il2CppRegisterAttribute : Attribute +public sealed class Il2CppRegisterAttribute(params Type[] interfaces) : Attribute { - public Il2CppRegisterAttribute(params Type[] interfaces) + public Il2CppRegisterAttribute() : this(Type.EmptyTypes) { - Interfaces = interfaces; } + - public Il2CppRegisterAttribute() - { - Interfaces = Type.EmptyTypes; - } - - public Type[] Interfaces { get; } + public Type[] Interfaces { get; } = interfaces; - public static void Registration(Type type) + public static void Registration(Type? type) { Info("Start Registration", "Il2CppRegister"); var attribute = - type.GetCustomAttribute(); + type?.GetCustomAttribute(); + if (attribute != null) registrationForTarget(type, attribute.Interfaces); Info("Complete Registration", "Il2CppRegister"); } - private static void registrationForTarget(Type targetType, Type[] interfaces) + private static void registrationForTarget(Type? targetType, Type[] interfaces) { - var targetBase = targetType.BaseType; + var targetBase = targetType?.BaseType; - Il2CppRegisterAttribute baseAttribute = null; + Il2CppRegisterAttribute? baseAttribute = null; - if (targetBase != null) baseAttribute = targetBase.GetCustomAttribute(); + if (targetBase != null) + baseAttribute = targetBase.GetCustomAttribute(); - if (baseAttribute != null) registrationForTarget(targetBase, baseAttribute.Interfaces); + if (baseAttribute != null) + registrationForTarget(targetBase, baseAttribute.Interfaces); Debug($"Registration {targetType}", "Register"); diff --git a/NextShip.Api/Attributes/LoadAttribute.cs b/NextShip.Api/Attributes/LoadAttribute.cs index fca9296..b942846 100644 --- a/NextShip.Api/Attributes/LoadAttribute.cs +++ b/NextShip.Api/Attributes/LoadAttribute.cs @@ -4,23 +4,26 @@ namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor)] -public sealed class LoadAttribute : Attribute +public sealed class LoadAttribute(LoadMode mode = LoadMode.Load) : Attribute { - public readonly LoadMode Mode; + public LoadMode Mode = mode; - public LoadAttribute(LoadMode mode = LoadMode.Load) - { - Mode = mode; - } + public IEnumerator? Enumerator; + + public static List Loads = new(); + public static string[] MethodNames = EnumHelper.GetAllNames(); + public static void Registration(Type type) { Info("Start Registration", filename: MethodUtils.GetClassName()); + + if (type.GetCustomAttribute() == null) return; + ConstructorInfo? constructor; if ( - type.GetCustomAttribute() != null - && - (constructor = type.GetConstructor + ( + constructor = type.GetConstructor ( BindingFlags.Public | BindingFlags.Static | @@ -28,34 +31,34 @@ public static void Registration(Type type) Array.Empty() ) ) - != null) + != null && constructor.Is()) constructor.Invoke(null, null); - foreach (var variableMethodInfo in type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | - BindingFlags.Public)) + foreach (var MethodInfo in type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)) { - if (variableMethodInfo.Name is "CoLoad" or "Load") + if (MethodInfo.ReturnType != typeof(IEnumerator)) + continue; + + var load = MethodInfo.GetCustomAttribute(); + LoadMode? mode = null; + if (Enum.TryParse(MethodInfo.Name, out LoadMode OutMode)) + mode = OutMode; + + if (load != null) { - if - ( - ( - type.IsDefined(typeof(LoadAttribute)) - || - variableMethodInfo.IsDefined(typeof(LoadAttribute)) - ) - && - variableMethodInfo.ReturnType == typeof(IEnumerator)) - /*LoadManager.AllLoad.Add(variableMethodInfo.Invoke(null, null) as IEnumerator);*/ - continue; - - if (type.IsDefined(typeof(LoadAttribute))) - { - variableMethodInfo.Invoke(null, null); - continue; - } + load.Enumerator = MethodInfo.Invoke(null, null) as IEnumerator; + Loads.Add(load); + continue; } - if (variableMethodInfo.GetCustomAttribute() != null) variableMethodInfo.Invoke(null, null); + if (mode != null ) + { + Loads.Add(new LoadAttribute + { + Mode = (LoadMode)mode, + Enumerator = MethodInfo.Invoke(null, null) as IEnumerator + }); + } } Info($"Statically Initialized Class {type}", "LoadAttribute"); diff --git a/NextShip.Api/Attributes/ServiceAdd.cs b/NextShip.Api/Attributes/ServiceAdd.cs new file mode 100644 index 0000000..e6bd59d --- /dev/null +++ b/NextShip.Api/Attributes/ServiceAdd.cs @@ -0,0 +1,21 @@ +using System.Reflection; + +namespace NextShip.Api.Attributes; + +[AttributeUsage(AttributeTargets.Field )] +public sealed class ServiceAddAttribute : Attribute +{ + public static void Registration(IServiceProvider provider, Assembly assembly) + { + var Fields = assembly.GetFieldInfos(); + + foreach (var VarField in Fields.Where(n => n.Is())) + { + if (!VarField.IsStatic) continue; + + var type = VarField.FieldType; + var value = provider.GetService(type); + VarField.SetValue(null, value); + } + } +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IKeyBindManager.cs b/NextShip.Api/Interfaces/IKeyBindManager.cs new file mode 100644 index 0000000..06a600e --- /dev/null +++ b/NextShip.Api/Interfaces/IKeyBindManager.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public interface IKeyBindManager +{ + +} \ No newline at end of file diff --git a/NextShip.Api/UI/CommonScreenCreator.cs b/NextShip.Api/UI/CommonScreenCreator.cs new file mode 100644 index 0000000..c0e2988 --- /dev/null +++ b/NextShip.Api/UI/CommonScreenCreator.cs @@ -0,0 +1,8 @@ +namespace NextShip.Api.UI; + +public static class CommonScreenCreator +{ + public static void StartErrorScreen(Exception exception) + { + } +} \ No newline at end of file diff --git a/NextShip.Api/Utils/ListUtils.cs b/NextShip.Api/Utils/ListUtils.cs index e212e98..d080a30 100644 --- a/NextShip.Api/Utils/ListUtils.cs +++ b/NextShip.Api/Utils/ListUtils.cs @@ -2,6 +2,7 @@ public static class ListUtils { + public static List GetLists(this List list, int count) { var l = new List(); diff --git a/NextShip.Api/Utils/MethodUtils.cs b/NextShip.Api/Utils/MethodUtils.cs index 1ccb3d4..7ea33f0 100644 --- a/NextShip.Api/Utils/MethodUtils.cs +++ b/NextShip.Api/Utils/MethodUtils.cs @@ -2,7 +2,7 @@ namespace NextShip.Api.Utils; -public class MethodUtils +public static class MethodUtils { /// /// 获取运行方法命名空间 @@ -28,4 +28,24 @@ public static string GetNamespace() { return MethodBase.GetCurrentMethod()?.DeclaringType?.Name; } + + public static bool Is(this MemberInfo info) where T : Attribute => info.GetCustomAttribute() != null; + + public static bool IsD(this MemberInfo info, Type type) => info.IsDefined(type); + + public static bool IsD(this MemberInfo info) => info.IsD(typeof(T)); + + public static IEnumerable GetMembers(this Type type, Func? Is) + { + var memberInfos = type.GetMembers(); + + return Is == null ? memberInfos.OfType() : memberInfos.OfType().Where(Is); + } + + public static List GetFieldInfos(this Assembly assembly) + { + var types = assembly.GetTypes(); + + return types.SelectMany(varType => varType.GetFields()).ToList(); + } } \ No newline at end of file diff --git a/NextShip/Manager/LoadManager.cs b/NextShip/Manager/LoadManager.cs index 9824432..84f0f77 100644 --- a/NextShip/Manager/LoadManager.cs +++ b/NextShip/Manager/LoadManager.cs @@ -15,7 +15,7 @@ public static class LoadManager private static bool Started; private static bool HasError; - public static List AllLoad = new(); + public static readonly List AllLoad = new(); [HarmonyPatch(typeof(SplashManager), nameof(SplashManager.Update))] [HarmonyPrefix] diff --git a/NextShip/main.cs b/NextShip/main.cs index e6b9b91..96ba7ac 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -6,6 +6,7 @@ using BepInEx.Unity.IL2CPP; using HarmonyLib; using Microsoft.Extensions.DependencyInjection; +using NextShip.Api.Attributes; using NextShip.Api.Extension; using NextShip.Api.Interfaces; using NextShip.Api.Services; @@ -43,6 +44,8 @@ public sealed class NextShip : BasePlugin public static NextService _Service { get; private set; } public static NextShip Instance { get; private set; } + + public static Assembly RootAssembly { get; private set; } private Harmony Harmony { get; } = new(Id); @@ -50,6 +53,7 @@ public sealed class NextShip : BasePlugin public override void Load() { Instance = this; + RootAssembly = Assembly.GetExecutingAssembly(); TISLog = BepInExLogger.CreateLogSource(ModName.RemoveBlank()); Harmony.PatchAll(); @@ -96,5 +100,6 @@ private static void CreateService() builder.Add(); _Service = NextService.Build(builder); + ServiceAddAttribute.Registration(_Service._Provider, RootAssembly); } } \ No newline at end of file From 3fe3e0b550636b747d83f94bedc580cd7954f516 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Tue, 12 Dec 2023 14:40:41 +0800 Subject: [PATCH 14/29] =?UTF-8?q?IDE=E6=A0=BC=E5=BC=8F=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Attributes/Il2CppRegisterAttribute.cs | 8 ++++---- NextShip.Api/Attributes/LoadAttribute.cs | 17 +++++++---------- NextShip.Api/Attributes/ServiceAdd.cs | 8 ++++---- NextShip.Api/Interfaces/IKeyBindManager.cs | 1 - NextShip.Api/Utils/ListUtils.cs | 1 - NextShip.Api/Utils/MethodUtils.cs | 17 +++++++++++++---- NextShip/main.cs | 2 +- 7 files changed, 29 insertions(+), 25 deletions(-) diff --git a/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs b/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs index 65e98e5..0948561 100644 --- a/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs +++ b/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs @@ -10,7 +10,7 @@ public sealed class Il2CppRegisterAttribute(params Type[] interfaces) : Attribut public Il2CppRegisterAttribute() : this(Type.EmptyTypes) { } - + public Type[] Interfaces { get; } = interfaces; @@ -20,7 +20,7 @@ public static void Registration(Type? type) var attribute = type?.GetCustomAttribute(); - + if (attribute != null) registrationForTarget(type, attribute.Interfaces); Info("Complete Registration", "Il2CppRegister"); @@ -32,10 +32,10 @@ private static void registrationForTarget(Type? targetType, Type[] interfaces) Il2CppRegisterAttribute? baseAttribute = null; - if (targetBase != null) + if (targetBase != null) baseAttribute = targetBase.GetCustomAttribute(); - if (baseAttribute != null) + if (baseAttribute != null) registrationForTarget(targetBase, baseAttribute.Interfaces); Debug($"Registration {targetType}", "Register"); diff --git a/NextShip.Api/Attributes/LoadAttribute.cs b/NextShip.Api/Attributes/LoadAttribute.cs index b942846..8b1c83c 100644 --- a/NextShip.Api/Attributes/LoadAttribute.cs +++ b/NextShip.Api/Attributes/LoadAttribute.cs @@ -6,20 +6,19 @@ namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor)] public sealed class LoadAttribute(LoadMode mode = LoadMode.Load) : Attribute { - public LoadMode Mode = mode; - - public IEnumerator? Enumerator; - public static List Loads = new(); public static string[] MethodNames = EnumHelper.GetAllNames(); - + + public IEnumerator? Enumerator; + public LoadMode Mode = mode; + public static void Registration(Type type) { Info("Start Registration", filename: MethodUtils.GetClassName()); if (type.GetCustomAttribute() == null) return; - + ConstructorInfo? constructor; if ( ( @@ -38,7 +37,7 @@ public static void Registration(Type type) { if (MethodInfo.ReturnType != typeof(IEnumerator)) continue; - + var load = MethodInfo.GetCustomAttribute(); LoadMode? mode = null; if (Enum.TryParse(MethodInfo.Name, out LoadMode OutMode)) @@ -51,14 +50,12 @@ public static void Registration(Type type) continue; } - if (mode != null ) - { + if (mode != null) Loads.Add(new LoadAttribute { Mode = (LoadMode)mode, Enumerator = MethodInfo.Invoke(null, null) as IEnumerator }); - } } Info($"Statically Initialized Class {type}", "LoadAttribute"); diff --git a/NextShip.Api/Attributes/ServiceAdd.cs b/NextShip.Api/Attributes/ServiceAdd.cs index e6bd59d..7600373 100644 --- a/NextShip.Api/Attributes/ServiceAdd.cs +++ b/NextShip.Api/Attributes/ServiceAdd.cs @@ -2,17 +2,17 @@ namespace NextShip.Api.Attributes; -[AttributeUsage(AttributeTargets.Field )] +[AttributeUsage(AttributeTargets.Field)] public sealed class ServiceAddAttribute : Attribute { public static void Registration(IServiceProvider provider, Assembly assembly) { var Fields = assembly.GetFieldInfos(); - - foreach (var VarField in Fields.Where(n => n.Is())) + + foreach (var VarField in Fields.Where(n => n.Is())) { if (!VarField.IsStatic) continue; - + var type = VarField.FieldType; var value = provider.GetService(type); VarField.SetValue(null, value); diff --git a/NextShip.Api/Interfaces/IKeyBindManager.cs b/NextShip.Api/Interfaces/IKeyBindManager.cs index 06a600e..d6f9994 100644 --- a/NextShip.Api/Interfaces/IKeyBindManager.cs +++ b/NextShip.Api/Interfaces/IKeyBindManager.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public interface IKeyBindManager { - } \ No newline at end of file diff --git a/NextShip.Api/Utils/ListUtils.cs b/NextShip.Api/Utils/ListUtils.cs index d080a30..e212e98 100644 --- a/NextShip.Api/Utils/ListUtils.cs +++ b/NextShip.Api/Utils/ListUtils.cs @@ -2,7 +2,6 @@ public static class ListUtils { - public static List GetLists(this List list, int count) { var l = new List(); diff --git a/NextShip.Api/Utils/MethodUtils.cs b/NextShip.Api/Utils/MethodUtils.cs index 7ea33f0..765d622 100644 --- a/NextShip.Api/Utils/MethodUtils.cs +++ b/NextShip.Api/Utils/MethodUtils.cs @@ -29,16 +29,25 @@ public static string GetNamespace() return MethodBase.GetCurrentMethod()?.DeclaringType?.Name; } - public static bool Is(this MemberInfo info) where T : Attribute => info.GetCustomAttribute() != null; + public static bool Is(this MemberInfo info) where T : Attribute + { + return info.GetCustomAttribute() != null; + } - public static bool IsD(this MemberInfo info, Type type) => info.IsDefined(type); + public static bool IsD(this MemberInfo info, Type type) + { + return info.IsDefined(type); + } - public static bool IsD(this MemberInfo info) => info.IsD(typeof(T)); + public static bool IsD(this MemberInfo info) + { + return info.IsD(typeof(T)); + } public static IEnumerable GetMembers(this Type type, Func? Is) { var memberInfos = type.GetMembers(); - + return Is == null ? memberInfos.OfType() : memberInfos.OfType().Where(Is); } diff --git a/NextShip/main.cs b/NextShip/main.cs index 96ba7ac..4bbcdb8 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -44,7 +44,7 @@ public sealed class NextShip : BasePlugin public static NextService _Service { get; private set; } public static NextShip Instance { get; private set; } - + public static Assembly RootAssembly { get; private set; } private Harmony Harmony { get; } = new(Id); From 1a8cf6309b1d04152c7d12a295883487798ce66c Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Tue, 19 Dec 2023 16:29:04 +0800 Subject: [PATCH 15/29] Update --- .github/workflows/Build-Release.yml | 64 ++++++++++++++++++++ NextShip.Api/Bases/NKeyBind.cs | 6 ++ NextShip.Api/Bases/NextInfo.cs | 4 ++ NextShip.Api/Interfaces/IEventListener.cs | 8 +++ NextShip.Api/Interfaces/IEventManager.cs | 4 +- NextShip.Api/Interfaces/IKeyBindManager.cs | 3 + NextShip.Api/Interfaces/IPlayerManager.cs | 6 ++ NextShip/Languages/Language.cs | 22 ++----- NextShip/Manager/EventManager.cs | 18 +++++- NextShip/{ => Manager}/NextManager.cs | 2 +- NextShip/Manager/NextPlayerManager.cs | 26 ++++++++ NextShip/NextShip.csproj | 2 +- NextShip/Patches/HauntMenuMiniGamePatch.cs | 70 ---------------------- NextShip/Patches/KillButtonPatch.cs | 33 ---------- NextShip/Patches/PlayerPatch.cs | 13 ++++ NextShip/Patches/PlayerPhysicsPatch.cs | 23 ++++--- NextShip/{ => Services}/NextService.cs | 2 +- NextShip/{ => Services}/ServiceBuilder.cs | 2 +- NextShip/main.cs | 1 + 19 files changed, 168 insertions(+), 141 deletions(-) create mode 100644 .github/workflows/Build-Release.yml create mode 100644 NextShip.Api/Bases/NKeyBind.cs create mode 100644 NextShip.Api/Interfaces/IEventListener.cs create mode 100644 NextShip.Api/Interfaces/IPlayerManager.cs rename NextShip/{ => Manager}/NextManager.cs (95%) create mode 100644 NextShip/Manager/NextPlayerManager.cs delete mode 100644 NextShip/Patches/HauntMenuMiniGamePatch.cs delete mode 100644 NextShip/Patches/KillButtonPatch.cs create mode 100644 NextShip/Patches/PlayerPatch.cs rename NextShip/{ => Services}/NextService.cs (97%) rename NextShip/{ => Services}/ServiceBuilder.cs (98%) diff --git a/.github/workflows/Build-Release.yml b/.github/workflows/Build-Release.yml new file mode 100644 index 0000000..7125874 --- /dev/null +++ b/.github/workflows/Build-Release.yml @@ -0,0 +1,64 @@ +name: Build-Release + +on: + push: + branches: [ "main" ] + +jobs: + build: + runs-on: ubuntu-latest + + if: ${{ github.repository_owner == 'TheIdealShipAU' }} + steps: + - uses: actions/cache@v2 + with: + path: | + ~/.nuget/packages + ~/.cache/bepinex + key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }} + restore-keys: | + ${{ runner.os }}-nuget- + + - uses: actions/checkout@v2 + with: + submodules: true + + - name: Collect build info + id: info + uses: actions/github-script@v6 + with: + script: | + let version = "1.0.0"; + core.setOutput(ReleaseVersion, version); + + - name: install wget + run: sudo apt install wget + + - name: download BepInEx + run: wget https://builds.bepinex.dev/projects/bepinex_be/672/BepInEx-Unity.IL2CPP-win-x86-6.0.0-be.672%2B472e950.zip + + - name: BepInEx + run: unzip BepInEx-Unity.IL2CPP-win-x86-6.0.0-be.672+422e950.zip -d ./NextShipRelease/ + + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 8.x + + - name: build + run: dotnet build NextShip/NextShip.csproj --configuration Release + + - name: path + run: sudo chmod -R 777 ./NextShipRelease + + - name: upload NextShip + uses: actions/upload-artifact@v3 + with: + name: NextShip.dll + path: NextShip/bin/Release/net8.0/NextShip.dll + + - name: upload TheIdealShip + uses: actions/upload-artifact@v3 + with: + name: NextShip + path: ./NextShipRelease \ No newline at end of file diff --git a/NextShip.Api/Bases/NKeyBind.cs b/NextShip.Api/Bases/NKeyBind.cs new file mode 100644 index 0000000..fb98fba --- /dev/null +++ b/NextShip.Api/Bases/NKeyBind.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Bases; + +public class NKeyBind +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Bases/NextInfo.cs b/NextShip.Api/Bases/NextInfo.cs index 70effb2..7eab276 100644 --- a/NextShip.Api/Bases/NextInfo.cs +++ b/NextShip.Api/Bases/NextInfo.cs @@ -13,4 +13,8 @@ public record NextInfo public string PUID; public RoleBase Role; + + public float GhostSpeed; + + public float BodySpeed; } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IEventListener.cs b/NextShip.Api/Interfaces/IEventListener.cs new file mode 100644 index 0000000..83cc51d --- /dev/null +++ b/NextShip.Api/Interfaces/IEventListener.cs @@ -0,0 +1,8 @@ +namespace NextShip.Api.Interfaces; + +public interface IEventListener +{ + public void On(string name); + + public void On(INextEvent @event); +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IEventManager.cs b/NextShip.Api/Interfaces/IEventManager.cs index aa83608..b6b1e86 100644 --- a/NextShip.Api/Interfaces/IEventManager.cs +++ b/NextShip.Api/Interfaces/IEventManager.cs @@ -4,7 +4,7 @@ public interface IEventManager { // 注册事件 public void RegisterEvent(INextEvent @event); - - + + // 卸载事件 public void UnRegisterEvent(INextEvent @event); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IKeyBindManager.cs b/NextShip.Api/Interfaces/IKeyBindManager.cs index d6f9994..805c796 100644 --- a/NextShip.Api/Interfaces/IKeyBindManager.cs +++ b/NextShip.Api/Interfaces/IKeyBindManager.cs @@ -2,4 +2,7 @@ namespace NextShip.Api.Interfaces; public interface IKeyBindManager { + public void AddBind(NKeyBind bind); + + public void RemoveBind(NKeyBind bind); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IPlayerManager.cs b/NextShip.Api/Interfaces/IPlayerManager.cs new file mode 100644 index 0000000..edb1e3f --- /dev/null +++ b/NextShip.Api/Interfaces/IPlayerManager.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public interface IPlayerManager +{ + +} \ No newline at end of file diff --git a/NextShip/Languages/Language.cs b/NextShip/Languages/Language.cs index df4d71c..d030306 100644 --- a/NextShip/Languages/Language.cs +++ b/NextShip/Languages/Language.cs @@ -1,6 +1,7 @@ global using static NextShip.Languages.Language; using System.Collections.Generic; using System.IO; +using System.Linq; using csv = NextShip.Languages.LanguageCSV; using pack = NextShip.Languages.LanguagePack; @@ -8,35 +9,22 @@ namespace NextShip.Languages; public static class Language { - public static string GetString(string s, Dictionary replacementDic = null) + public static string GetString(string s, Dictionary? replacementDic = null) { var langId = TranslationController.InstanceExists ? TranslationController.Instance.currentLanguage.languageID : SupportedLangs.English; var str = ""; - if (File.Exists(@"Language\" + LanguagePack.languageName + ".dat")) - str = LanguagePack.GetPString(s); - else - str = csv.GetCString(s, langId); - if (replacementDic != null) - foreach (var rd in replacementDic) - str = str.Replace(rd.Key, rd.Value); - return str; + str = File.Exists(@"Language\" + pack.languageName + ".dat") ? pack.GetPString(s) : csv.GetCString(s, langId); + return replacementDic == null ? str : replacementDic.Aggregate(str, (current, rd) => current.Replace(rd.Key, rd.Value)); } public static void Init() { - if (!File.Exists(@"Language\" + LanguagePack.languageName + ".dat")) + if (!File.Exists(@"Language\" + pack.languageName + ".dat")) csv.LoadCSV(); else pack.Load(); } } -public enum OutputType -{ - Csv, - Yaml, - Json, - Txt -} \ No newline at end of file diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs index 97c3f59..0f34263 100644 --- a/NextShip/Manager/EventManager.cs +++ b/NextShip/Manager/EventManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using HarmonyLib; using NextShip.Api.Interfaces; namespace NextShip.Manager; @@ -9,7 +10,9 @@ public class EventManager : IEventManager { public static EventManager _eventManager = Main._Service.Get(); - private readonly List RegisterEvents = new(); + private readonly List RegisterEvents = []; + + private readonly HashSet EventListeners = []; public void RegisterEvent(INextEvent @event) { @@ -23,11 +26,20 @@ public void UnRegisterEvent(INextEvent @event) RegisterEvents.Remove(@event); } - public void Call(INextEvent @event) + public void RegisterListener(IEventListener listener) => EventListeners.Add(listener); + + public void UnRegisterListener(IEventListener listener) => EventListeners.Remove(listener); + + public void CallEvent(INextEvent @event) { - foreach (var _event in RegisterEvents.FindAll(n => n.EventName == @event.EventName)) @event.Call(_event); + foreach (var _event in RegisterEvents.FindAll(n => n.EventName == @event.EventName)) + @event.Call(_event); } + public void CallListener(string name) => EventListeners.Do(n => n.On(name)); + + public void CallListener(INextEvent @event) => EventListeners.Do(n => n.On(@event)); + public bool TryGetEvent(string eventName, out INextEvent @event) { if (RegisterEvents.Any(n => n.EventName == eventName)) diff --git a/NextShip/NextManager.cs b/NextShip/Manager/NextManager.cs similarity index 95% rename from NextShip/NextManager.cs rename to NextShip/Manager/NextManager.cs index 2b9f281..4092337 100644 --- a/NextShip/NextManager.cs +++ b/NextShip/Manager/NextManager.cs @@ -3,7 +3,7 @@ using NextShip.Api.UI; using UnityEngine; -namespace NextShip; +namespace NextShip.Manager; [Il2CppRegister] public class NextManager : MonoBehaviour diff --git a/NextShip/Manager/NextPlayerManager.cs b/NextShip/Manager/NextPlayerManager.cs new file mode 100644 index 0000000..60bc964 --- /dev/null +++ b/NextShip/Manager/NextPlayerManager.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using NextShip.Api.Bases; +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public class NextPlayerManager : IPlayerManager +{ + private static NextPlayerManager? _nextPlayerManager; + + public static NextPlayerManager Instance => _nextPlayerManager ??= new NextPlayerManager(); + + private readonly List PlayerInfos = new(); + + public NextInfo GetPlayerInfo(PlayerControl player) + { + return PlayerInfos.Find(n => n.PlayerControl == player)!; + } + + public void CreatePlayerInfo() + { + + } + + +} \ No newline at end of file diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index 565af6c..fc60f83 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -10,7 +10,7 @@ true false false - true + enable diff --git a/NextShip/Patches/HauntMenuMiniGamePatch.cs b/NextShip/Patches/HauntMenuMiniGamePatch.cs deleted file mode 100644 index d20e97d..0000000 --- a/NextShip/Patches/HauntMenuMiniGamePatch.cs +++ /dev/null @@ -1,70 +0,0 @@ -using HarmonyLib; - -namespace NextShip.Patches; -/* public class HauntMenuMiniGamePatch -{ - [HarmonyPatch(typeof(HauntMenuMinigame), nameof(HauntMenuMinigame.Start))] - public static bool Prefix(HauntMenuMinigame __instance) - { - if (CustomOptionHolder.disableHauntMenu.getBool()) return false; - - return true; - } -} -[HarmonyPatch(typeof(HauntMenuMinigame), nameof(HauntMenuMinigame.FixedUpdate))] -class HauntMenuMiniGameFixedUpdatePatch -{ - public static bool Prefix(HauntMenuMinigame __instance) - { - if (CustomOptionHolder.disableHauntMenu.getBool()) return false; - - return false; - } - - public static void Postfix(HauntMenuMinigame __instance) - { - if (CustomOptionHolder.disableHauntMenu.getBool()) - { - __instance.gameObject.SetActive(false); - return; - } - if (CachedPlayer.LocalPlayer.PlayerControl.IsSurvival()) - { - __instance.gameObject.SetActive(false); - } - else - { - __instance.gameObject.SetActive(true); - } - foreach (var b in __instance.FilterButtons) - { - b.gameObject.SetActive(false); - } - } -} */ - -/*[HarmonyPatch(typeof(AbilityButton), nameof(AbilityButton.Refresh))] -public static class AbilityButtonRefreshPatch -{ - public static void Postfix(AbilityButton __instance) - { - if (!disableHauntMenu.getBool()) return; - __instance.gameObject.SetActive(false); - } -}*/ - -[HarmonyPatch(typeof(HauntMenuMinigame), nameof(HauntMenuMinigame.SetFilterText))] -public static class HauntMenuMinigameSetFilterTextPatch -{ -/* public static bool Prefix(HauntMenuMinigame __instance) - { - if (GameOptionsManager.Instance.CurrentGameOptions.GameMode == GameModes.HideNSeek) return true; - var roleText = RoleHelpers.GetRoleInfo(__instance.HauntTarget,false).name; - var modifierText = RoleHelpers.GetRoleInfo(__instance.HauntTarget, true).name; - - string FilterText = roleText; - if (modifierText != null) FilterText += ("\n" + modifierText); - __instance.FilterText.text = FilterText; - return false; - } */ -} \ No newline at end of file diff --git a/NextShip/Patches/KillButtonPatch.cs b/NextShip/Patches/KillButtonPatch.cs deleted file mode 100644 index 784c5da..0000000 --- a/NextShip/Patches/KillButtonPatch.cs +++ /dev/null @@ -1,33 +0,0 @@ -/*using HarmonyLib; -using NextShip.Roles; - -namespace NextShip.Patches; - -internal class KillButtonPatch -{ - [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.MurderPlayer))] - public static class PlayerControlMurderPlayerPatch - { - public static bool Prefix(PlayerControl __instance, [HarmonyArgument(0)] PlayerControl target) - { - if (Lover.lover1 != null && Lover.lover2 != null && (target == Lover.lover1 || target == Lover.lover2) && - LoverDieForLove.getBool() && !Lover.suicide) - { - Lover.suicide = true; - if (target == Lover.lover1) Lover.lover2.Suicide(); - - if (target == Lover.lover2) Lover.lover1.Suicide(); - } - -/* if (SchrodingersCat.schrodingersCat != null && target == SchrodingersCat.schrodingersCat) - { - RoleInfo.RoleTeam STeam = RoleHelpers.GetRoleInfo(__instance).team; - RPCHelpers.Create((byte)CustomRPC.SchrodingerSCatTeamChange, bytes: new []{ (byte)STeam }); - return false; - } - #1# - return true; - } - } -}*/ - diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs new file mode 100644 index 0000000..4f6912b --- /dev/null +++ b/NextShip/Patches/PlayerPatch.cs @@ -0,0 +1,13 @@ +using HarmonyLib; + +namespace NextShip.Patches; + +[Harmony] +public static class PlayerPatch +{ + [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.Awake))] + public static void PlayerControlAwake_PostfixPatch(PlayerControl __instance) + { + + } +} \ No newline at end of file diff --git a/NextShip/Patches/PlayerPhysicsPatch.cs b/NextShip/Patches/PlayerPhysicsPatch.cs index 7d3340d..4643f23 100644 --- a/NextShip/Patches/PlayerPhysicsPatch.cs +++ b/NextShip/Patches/PlayerPhysicsPatch.cs @@ -1,18 +1,17 @@ +using HarmonyLib; +using NextShip.Manager; + namespace NextShip.Patches; -/* class PlayerPhysicsPatch +[Harmony] +public static class PlayerPhysicsPatch { // 运行后修改幽灵移速 - [HarmonyPatch(typeof(PlayerPhysics),nameof(PlayerPhysics.FixedUpdate))] - public static void Prefix (PlayerPhysics __instance) + [HarmonyPatch(typeof(PlayerPhysics),nameof(PlayerPhysics.FixedUpdate)), HarmonyPostfix] + public static void Update_Postfix(PlayerPhysics __instance) { - if (CustomOptionHolder.PlayerOption.getBool()) - { - __instance.GhostSpeed = CustomOptionHolder.PlayerGhostSpeed.getFloat(); - for (var i = 0 ; i < PlayerControl.AllPlayerControls.Count ; i++) - { - PlayerControl.AllPlayerControls[i].MyPhysics.GhostSpeed = CustomOptionHolder.PlayerGhostSpeed.getFloat(); - } - } + var playerInfo = NextPlayerManager.Instance.GetPlayerInfo(__instance.myPlayer); + __instance.GhostSpeed = playerInfo.GhostSpeed; + __instance.Speed = playerInfo.BodySpeed; } -} */ \ No newline at end of file +} \ No newline at end of file diff --git a/NextShip/NextService.cs b/NextShip/Services/NextService.cs similarity index 97% rename from NextShip/NextService.cs rename to NextShip/Services/NextService.cs index b095ffb..d4b08b5 100644 --- a/NextShip/NextService.cs +++ b/NextShip/Services/NextService.cs @@ -3,7 +3,7 @@ using Microsoft.Extensions.DependencyInjection; using NextShip.Api.Interfaces; -namespace NextShip; +namespace NextShip.Services; public class NextService : INextService { diff --git a/NextShip/ServiceBuilder.cs b/NextShip/Services/ServiceBuilder.cs similarity index 98% rename from NextShip/ServiceBuilder.cs rename to NextShip/Services/ServiceBuilder.cs index 7087975..3c8da21 100644 --- a/NextShip/ServiceBuilder.cs +++ b/NextShip/Services/ServiceBuilder.cs @@ -2,7 +2,7 @@ using Microsoft.Extensions.DependencyInjection; using NextShip.Api.Interfaces; -namespace NextShip; +namespace NextShip.Services; public class ServiceBuilder : IServiceBuilder { diff --git a/NextShip/main.cs b/NextShip/main.cs index 4bbcdb8..1f106c4 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -14,6 +14,7 @@ using NextShip.Languages; using NextShip.Manager; using NextShip.Patches; +using NextShip.Services; using BepInExLogger = BepInEx.Logging.Logger; [assembly: AssemblyFileVersion(Main.VersionString)] From f43e98304de4729c1fd67a38cb269af0de9b0cfe Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Tue, 19 Dec 2023 16:31:00 +0800 Subject: [PATCH 16/29] =?UTF-8?q?IDE=E6=A0=BC=E5=BC=8F=E5=8C=96=E6=B8=85?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NextShip.Api/Bases/NKeyBind.cs | 1 - NextShip.Api/Bases/NextInfo.cs | 7 +++--- NextShip.Api/Interfaces/IEventManager.cs | 2 +- NextShip.Api/Interfaces/IKeyBindManager.cs | 2 +- NextShip.Api/Interfaces/IPlayerManager.cs | 1 - NextShip.Api/Roles/SimpleRoleInfo.cs | 3 ++- NextShip.Api/Utilities/AssetLoader.cs | 1 - NextShip/Languages/Language.cs | 7 +++--- NextShip/Manager/EventManager.cs | 26 ++++++++++++++++------ NextShip/Manager/NextPlayerManager.cs | 11 ++++----- NextShip/Patches/PlayerPatch.cs | 1 - NextShip/Patches/PlayerPhysicsPatch.cs | 5 +++-- 12 files changed, 37 insertions(+), 30 deletions(-) diff --git a/NextShip.Api/Bases/NKeyBind.cs b/NextShip.Api/Bases/NKeyBind.cs index fb98fba..3d3c4d6 100644 --- a/NextShip.Api/Bases/NKeyBind.cs +++ b/NextShip.Api/Bases/NKeyBind.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Bases; public class NKeyBind { - } \ No newline at end of file diff --git a/NextShip.Api/Bases/NextInfo.cs b/NextShip.Api/Bases/NextInfo.cs index 7eab276..c2133c9 100644 --- a/NextShip.Api/Bases/NextInfo.cs +++ b/NextShip.Api/Bases/NextInfo.cs @@ -2,10 +2,13 @@ namespace NextShip.Api.Bases; public record NextInfo { + public float BodySpeed; public int clientId; public string FriendCode; + public float GhostSpeed; + public PlayerControl PlayerControl; public GameData.PlayerInfo PlayerInfo; @@ -13,8 +16,4 @@ public record NextInfo public string PUID; public RoleBase Role; - - public float GhostSpeed; - - public float BodySpeed; } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IEventManager.cs b/NextShip.Api/Interfaces/IEventManager.cs index b6b1e86..7ac9011 100644 --- a/NextShip.Api/Interfaces/IEventManager.cs +++ b/NextShip.Api/Interfaces/IEventManager.cs @@ -4,7 +4,7 @@ public interface IEventManager { // 注册事件 public void RegisterEvent(INextEvent @event); - + // 卸载事件 public void UnRegisterEvent(INextEvent @event); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IKeyBindManager.cs b/NextShip.Api/Interfaces/IKeyBindManager.cs index 805c796..63ac863 100644 --- a/NextShip.Api/Interfaces/IKeyBindManager.cs +++ b/NextShip.Api/Interfaces/IKeyBindManager.cs @@ -3,6 +3,6 @@ namespace NextShip.Api.Interfaces; public interface IKeyBindManager { public void AddBind(NKeyBind bind); - + public void RemoveBind(NKeyBind bind); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IPlayerManager.cs b/NextShip.Api/Interfaces/IPlayerManager.cs index edb1e3f..d913726 100644 --- a/NextShip.Api/Interfaces/IPlayerManager.cs +++ b/NextShip.Api/Interfaces/IPlayerManager.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public interface IPlayerManager { - } \ No newline at end of file diff --git a/NextShip.Api/Roles/SimpleRoleInfo.cs b/NextShip.Api/Roles/SimpleRoleInfo.cs index cbada02..4978a7c 100644 --- a/NextShip.Api/Roles/SimpleRoleInfo.cs +++ b/NextShip.Api/Roles/SimpleRoleInfo.cs @@ -2,7 +2,8 @@ namespace NextShip.Api.Roles; -public sealed class SimpleRoleInfo(RoleId id, +public sealed class SimpleRoleInfo( + RoleId id, Color color, RoleTeam team, RoleType type, diff --git a/NextShip.Api/Utilities/AssetLoader.cs b/NextShip.Api/Utilities/AssetLoader.cs index f6e0872..7fe50ab 100644 --- a/NextShip.Api/Utilities/AssetLoader.cs +++ b/NextShip.Api/Utilities/AssetLoader.cs @@ -2,7 +2,6 @@ using Il2CppInterop.Runtime.InteropTypes; using NextShip.Api.Managers; using UnityEngine; -using SystemFile = System.IO; using Il2cppFile = Il2CppSystem.IO.File; namespace NextShip.Api.Utilities; diff --git a/NextShip/Languages/Language.cs b/NextShip/Languages/Language.cs index d030306..2460baa 100644 --- a/NextShip/Languages/Language.cs +++ b/NextShip/Languages/Language.cs @@ -16,7 +16,9 @@ public static string GetString(string s, Dictionary? replacement : SupportedLangs.English; var str = ""; str = File.Exists(@"Language\" + pack.languageName + ".dat") ? pack.GetPString(s) : csv.GetCString(s, langId); - return replacementDic == null ? str : replacementDic.Aggregate(str, (current, rd) => current.Replace(rd.Key, rd.Value)); + return replacementDic == null + ? str + : replacementDic.Aggregate(str, (current, rd) => current.Replace(rd.Key, rd.Value)); } public static void Init() @@ -26,5 +28,4 @@ public static void Init() else pack.Load(); } -} - +} \ No newline at end of file diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs index 0f34263..dc693e1 100644 --- a/NextShip/Manager/EventManager.cs +++ b/NextShip/Manager/EventManager.cs @@ -10,10 +10,10 @@ public class EventManager : IEventManager { public static EventManager _eventManager = Main._Service.Get(); - private readonly List RegisterEvents = []; - private readonly HashSet EventListeners = []; + private readonly List RegisterEvents = []; + public void RegisterEvent(INextEvent @event) { @event.OnRegister(this); @@ -26,9 +26,15 @@ public void UnRegisterEvent(INextEvent @event) RegisterEvents.Remove(@event); } - public void RegisterListener(IEventListener listener) => EventListeners.Add(listener); + public void RegisterListener(IEventListener listener) + { + EventListeners.Add(listener); + } - public void UnRegisterListener(IEventListener listener) => EventListeners.Remove(listener); + public void UnRegisterListener(IEventListener listener) + { + EventListeners.Remove(listener); + } public void CallEvent(INextEvent @event) { @@ -36,9 +42,15 @@ public void CallEvent(INextEvent @event) @event.Call(_event); } - public void CallListener(string name) => EventListeners.Do(n => n.On(name)); - - public void CallListener(INextEvent @event) => EventListeners.Do(n => n.On(@event)); + public void CallListener(string name) + { + EventListeners.Do(n => n.On(name)); + } + + public void CallListener(INextEvent @event) + { + EventListeners.Do(n => n.On(@event)); + } public bool TryGetEvent(string eventName, out INextEvent @event) { diff --git a/NextShip/Manager/NextPlayerManager.cs b/NextShip/Manager/NextPlayerManager.cs index 60bc964..8280de5 100644 --- a/NextShip/Manager/NextPlayerManager.cs +++ b/NextShip/Manager/NextPlayerManager.cs @@ -7,11 +7,11 @@ namespace NextShip.Manager; public class NextPlayerManager : IPlayerManager { private static NextPlayerManager? _nextPlayerManager; - - public static NextPlayerManager Instance => _nextPlayerManager ??= new NextPlayerManager(); - + private readonly List PlayerInfos = new(); - + + public static NextPlayerManager Instance => _nextPlayerManager ??= new NextPlayerManager(); + public NextInfo GetPlayerInfo(PlayerControl player) { return PlayerInfos.Find(n => n.PlayerControl == player)!; @@ -19,8 +19,5 @@ public NextInfo GetPlayerInfo(PlayerControl player) public void CreatePlayerInfo() { - } - - } \ No newline at end of file diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs index 4f6912b..3bfca56 100644 --- a/NextShip/Patches/PlayerPatch.cs +++ b/NextShip/Patches/PlayerPatch.cs @@ -8,6 +8,5 @@ public static class PlayerPatch [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.Awake))] public static void PlayerControlAwake_PostfixPatch(PlayerControl __instance) { - } } \ No newline at end of file diff --git a/NextShip/Patches/PlayerPhysicsPatch.cs b/NextShip/Patches/PlayerPhysicsPatch.cs index 4643f23..d37779c 100644 --- a/NextShip/Patches/PlayerPhysicsPatch.cs +++ b/NextShip/Patches/PlayerPhysicsPatch.cs @@ -7,11 +7,12 @@ namespace NextShip.Patches; public static class PlayerPhysicsPatch { // 运行后修改幽灵移速 - [HarmonyPatch(typeof(PlayerPhysics),nameof(PlayerPhysics.FixedUpdate)), HarmonyPostfix] + [HarmonyPatch(typeof(PlayerPhysics), nameof(PlayerPhysics.FixedUpdate))] + [HarmonyPostfix] public static void Update_Postfix(PlayerPhysics __instance) { var playerInfo = NextPlayerManager.Instance.GetPlayerInfo(__instance.myPlayer); __instance.GhostSpeed = playerInfo.GhostSpeed; __instance.Speed = playerInfo.BodySpeed; } -} \ No newline at end of file +} \ No newline at end of file From 71661a37097dc6c720c7317b2a7c2f52ba568bc7 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Wed, 3 Jan 2024 21:40:17 +0800 Subject: [PATCH 17/29] E --- NextShip.Api/Enums/CosmeticsInfo.cs | 29 ++ .../Extension/PasswordVerification.cs | 24 + NextShip.Api/Extension/ReactorExtension.cs | 51 +-- NextShip.Api/Interfaces/INextServiceAdd.cs | 6 + NextShip.Api/Interfaces/IRoleCreator.cs | 4 +- NextShip.Api/Interfaces/IRoleManager.cs | 6 +- NextShip.Api/NextPaths.cs | 50 ++ NextShip.Api/NextShip.Api.csproj | 3 +- NextShip.Api/Patches/InnerNetClientPatch.cs | 32 ++ NextShip.Api/Services/DownloadService.cs | 10 +- NextShip.Api/Utils/DirectoryUtils.cs | 14 + NextShip.Api/Utils/TextUtils.cs | 12 + NextShip/Cosmetics/AllCosmeticsCache.cs | 70 +++ NextShip/Cosmetics/CosmeticsChecks.cs | 4 +- NextShip/Cosmetics/CosmeticsCreator.cs | 47 +- NextShip/Cosmetics/CustomCosmeticsManager.cs | 38 +- NextShip/Cosmetics/Loaders/CosmeticsLoader.cs | 55 +-- .../Cosmetics/Loaders/TORCosmeticsLoader.cs | 8 +- NextShip/Cosmetics/Patches/HatManagerPatch.cs | 79 +--- NextShip/DIY/Plugins/PluginManager.cs | 21 +- NextShip/Languages/LanguagePack.cs | 11 +- NextShip/Manager/FilesManager.cs | 84 ---- NextShip/Manager/NextPlayerManager.cs | 24 +- NextShip/Manager/RoleManager.cs | 42 +- NextShip/NextPaths.cs | 15 - NextShip/NextShip.csproj | 3 +- NextShip/Patches/JoinGameButtonPatch.cs | 7 +- NextShip/Patches/PlayerPatch.cs | 3 + NextShip/Patches/RegionPatch.cs | 73 ++- NextShip/Patches/RoleAssignmentPatch.cs | 432 +----------------- NextShip/Patches/SaveManagerPatch.cs | 5 +- NextShip/Roles/FastCreator.cs | 39 ++ NextShip/Services/DataService.cs | 6 + NextShip/Services/HatService.cs | 6 + NextShip/main.cs | 20 +- 35 files changed, 548 insertions(+), 785 deletions(-) create mode 100644 NextShip.Api/Enums/CosmeticsInfo.cs create mode 100644 NextShip.Api/Extension/PasswordVerification.cs create mode 100644 NextShip.Api/Interfaces/INextServiceAdd.cs create mode 100644 NextShip.Api/NextPaths.cs create mode 100644 NextShip.Api/Patches/InnerNetClientPatch.cs create mode 100644 NextShip.Api/Utils/DirectoryUtils.cs create mode 100644 NextShip/Cosmetics/AllCosmeticsCache.cs delete mode 100644 NextShip/Manager/FilesManager.cs delete mode 100644 NextShip/NextPaths.cs create mode 100644 NextShip/Roles/FastCreator.cs create mode 100644 NextShip/Services/DataService.cs create mode 100644 NextShip/Services/HatService.cs diff --git a/NextShip.Api/Enums/CosmeticsInfo.cs b/NextShip.Api/Enums/CosmeticsInfo.cs new file mode 100644 index 0000000..fa3d2f4 --- /dev/null +++ b/NextShip.Api/Enums/CosmeticsInfo.cs @@ -0,0 +1,29 @@ +namespace NextShip.Api.Enums; + +public record CosmeticsInfo +{ + public CosmeticType CosmeticType { get; set; } + public string Name { get; init; } + public string Author { get; set; } + + + public string Id { get; set; } + public string Package { get; set; } + public string Condition { get; set; } + + public string Resource { get; init; } + public string FlipResource { get; set; } + public string BackFlipResource { get; set; } + public string BackResource { get; set; } + public string ClimbResource { get; set; } + + public string ResHash { get; set; } + public string ResHashBack { get; set; } + public string ResHashClimb { get; set; } + public string ResHashFlip { get; set; } + public string ResHashBackFlip { get; set; } + + public bool Bounce { get; set; } + public bool Adaptive { get; set; } + public bool Behind { get; set; } +} \ No newline at end of file diff --git a/NextShip.Api/Extension/PasswordVerification.cs b/NextShip.Api/Extension/PasswordVerification.cs new file mode 100644 index 0000000..19b5e98 --- /dev/null +++ b/NextShip.Api/Extension/PasswordVerification.cs @@ -0,0 +1,24 @@ +using Hazel; +using NextShip.Api.Patches; + +namespace NextShip.Api.Extension; + +public class PasswordVerification +{ + public static bool Enable { get; private set; } + + public static int Password; + + public static void UseVerification() + { + Enable = true; + _Harmony.PatchAll(typeof(InnerNetClientPatch)); + } + + public static void Write(ref MessageWriter writer) + { + if (Password == 0) return; + var messageString = $"Password:{Password.ToString()}"; + writer.Write(messageString); + } +} \ No newline at end of file diff --git a/NextShip.Api/Extension/ReactorExtension.cs b/NextShip.Api/Extension/ReactorExtension.cs index f3a3764..ac789bd 100644 --- a/NextShip.Api/Extension/ReactorExtension.cs +++ b/NextShip.Api/Extension/ReactorExtension.cs @@ -2,9 +2,9 @@ using BepInEx.Unity.IL2CPP; using HarmonyLib; using Hazel; -using Il2CppInterop.Runtime.InteropTypes.Arrays; using InnerNet; using NextShip.Api.Config; +using NextShip.Api.Patches; namespace NextShip.Api.Extension; @@ -19,12 +19,13 @@ public static class ReactorExtension public static readonly Dictionary> All_Mod = new(); - public static bool ReactorHandshake; + public static bool ReactorHandshake { get; private set; } public static void UseReactorHandshake() { ReactorHandshake = true; UseModList(); + _Harmony.PatchAll(typeof(InnerNetClientPatch)); _Harmony.PatchAll(typeof(ReactorExtension)); } @@ -37,6 +38,22 @@ public static void GetHandshakeInfo() { } + public static void MessageWrite(ref MessageWriter handshakeWriter) + { + handshakeWriter.Write(((ulong)0x72656163746f72 << 8) | 2); + + // 写入握手模组信息 + handshakeWriter.WritePacked(HashSet_Mods.Count); + foreach (var varMod in HashSet_Mods) + { + handshakeWriter.Write(varMod.Id); + handshakeWriter.Write(varMod.Version); + handshakeWriter.Write((ushort)varMod.Flags); + if (varMod.Flags.HasFlag(ModFlags.RequireOnAllClients)) + handshakeWriter.Write(varMod.Name); + } + } + private static void OnPluginLoad(PluginInfo pluginInfo, BasePlugin plugin) { var pluginType = plugin.GetType(); @@ -51,7 +68,7 @@ private static void OnPluginLoad(PluginInfo pluginInfo, BasePlugin plugin) HashSet_Mods.Add(mod); } - public static void UseModList() + private static void UseModList() { foreach (var existingPlugin in IL2CPPChainloader.Instance.Plugins.Values.Where(existingPlugin => existingPlugin.Instance != null)) @@ -60,34 +77,6 @@ public static void UseModList() IL2CPPChainloader.Instance.PluginLoad += (pluginInfo, _, plugin) => OnPluginLoad(pluginInfo, plugin); } - [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.GetConnectionData))] - [HarmonyPostfix] - public static void GetConnectionData_Postfix(ref Il2CppStructArray __result) - { - if (!ReactorHandshake) return; - var handshakeWriter = new MessageWriter(1000); - - // 写入原本握手内容 - handshakeWriter.Write(__result); - - // 写入反应堆握手版本 - handshakeWriter.Write(((ulong)0x72656163746f72 << 8) | 2); - - // 写入握手模组信息 - handshakeWriter.WritePacked(HashSet_Mods.Count); - foreach (var varMod in HashSet_Mods) - { - handshakeWriter.Write(varMod.Id); - handshakeWriter.Write(varMod.Version); - handshakeWriter.Write((ushort)varMod.Flags); - if (varMod.Flags.HasFlag(ModFlags.RequireOnAllClients)) - handshakeWriter.Write(varMod.Name); - } - - __result = handshakeWriter.ToByteArray(true); - handshakeWriter.Recycle(); - } - [HarmonyPatch(typeof(InnerNetClient._HandleGameDataInner_d__39), nameof(InnerNetClient._HandleGameDataInner_d__39.MoveNext))] [HarmonyPrefix] diff --git a/NextShip.Api/Interfaces/INextServiceAdd.cs b/NextShip.Api/Interfaces/INextServiceAdd.cs new file mode 100644 index 0000000..503e4b1 --- /dev/null +++ b/NextShip.Api/Interfaces/INextServiceAdd.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public interface INextServiceAdd +{ + public void ServiceAdd(IServiceBuilder serviceBuilder); +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IRoleCreator.cs b/NextShip.Api/Interfaces/IRoleCreator.cs index 354e1fe..57066d3 100644 --- a/NextShip.Api/Interfaces/IRoleCreator.cs +++ b/NextShip.Api/Interfaces/IRoleCreator.cs @@ -4,7 +4,9 @@ public interface IRoleCreator : IDisposable { public T Create(IRole role) where T : RoleBase; - public T GetRole(PlayerControl player); + public T GetRole(PlayerControl player) where T : class; public void Clear(); + + public IRole GetAssign(); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IRoleManager.cs b/NextShip.Api/Interfaces/IRoleManager.cs index 187e2e2..478b01b 100644 --- a/NextShip.Api/Interfaces/IRoleManager.cs +++ b/NextShip.Api/Interfaces/IRoleManager.cs @@ -6,7 +6,9 @@ public interface IRoleManager public void UnRegister(IRole role); - public void AddCreator(IRoleCreator creator); + public void AssignRole(PlayerControl player, IRole role); - public void RemoveCreator(IRoleCreator creator); + public void Clear(); + + public void SetCreator(IRoleCreator creator); } \ No newline at end of file diff --git a/NextShip.Api/NextPaths.cs b/NextShip.Api/NextPaths.cs new file mode 100644 index 0000000..95413ee --- /dev/null +++ b/NextShip.Api/NextPaths.cs @@ -0,0 +1,50 @@ +namespace NextShip.Api; + +public static class NextPaths +{ + static NextPaths() + { + GetPaths(); + CreateDirectory(); + } + + private static void GetPaths() + { + RootDirectory = BepInEx.Paths.GameRootPath; + TIS_DataPath = $"{RootDirectory}/TIS_Data"; + CreativityPath = $"{RootDirectory}/Creativity"; + TIS_TempPath = $"{TIS_DataPath}/TEMP"; + TIS_ConfigPath = $"{TIS_DataPath}/Config"; + TIS_PluginsPath = $"{CreativityPath}/Plugins"; + TIS_TORHats = $"{CreativityPath}/TOR"; + } + + + private static void CreateDirectory() + { + var paths = typeof(NextPaths).GetFields(). + Where(n => n.IsStatic && n.IsPublic && n.FieldType == typeof(string)). + Select(n => n.GetValue(null)). + Select(n => (string)n); + + foreach (var Path in paths) + { + if (Directory.Exists(Path)) continue; + Directory.CreateDirectory(Path!); + } + } + + public static string RootDirectory; + + public static string TIS_DataPath { get; private set; } + + public static string CreativityPath { get; private set; } + + public static string TIS_TempPath { get; private set; } + + public static string TIS_ConfigPath { get; private set; } + + public static string TIS_PluginsPath { get; private set; } + + public static string TIS_TORHats { get; private set; } +} \ No newline at end of file diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index 9e434e4..6400a94 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -3,7 +3,6 @@ net8.0 enable - enable embedded NextShip.Api 1.0.0 @@ -15,7 +14,7 @@ - + diff --git a/NextShip.Api/Patches/InnerNetClientPatch.cs b/NextShip.Api/Patches/InnerNetClientPatch.cs new file mode 100644 index 0000000..51c706e --- /dev/null +++ b/NextShip.Api/Patches/InnerNetClientPatch.cs @@ -0,0 +1,32 @@ +using HarmonyLib; +using Hazel; +using Il2CppInterop.Runtime.InteropTypes.Arrays; +using InnerNet; +using NextShip.Api.Extension; + +namespace NextShip.Api.Patches; + +[Harmony] +public static class InnerNetClientPatch +{ + public static Il2CppStructArray GetDataByte(Il2CppStructArray original) + { + var Writer = new MessageWriter(1000); + Writer.Write(original); + + if (ReactorExtension.ReactorHandshake) + ReactorExtension.MessageWrite(ref Writer); + + if (PasswordVerification.Enable) + PasswordVerification.Write(ref Writer); + + var bytes = Writer.ToByteArray(true); + Writer.Recycle(); + return bytes; + } + + [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.GetConnectionData))] + [HarmonyPostfix] + public static void GetConnectionData_Postfix(ref Il2CppStructArray __result) => + __result = GetDataByte(__result); +} \ No newline at end of file diff --git a/NextShip.Api/Services/DownloadService.cs b/NextShip.Api/Services/DownloadService.cs index d88dd80..2f0db79 100644 --- a/NextShip.Api/Services/DownloadService.cs +++ b/NextShip.Api/Services/DownloadService.cs @@ -2,12 +2,18 @@ namespace NextShip.Api.Services; -public abstract class DownloadService(ILogger logger, HttpClient httpClient) +public class DownloadService(ILogger logger, HttpClient httpClient) { private readonly HttpClient _httpClient = httpClient; private readonly ILogger _logger = logger; - public void Download(Uri uri) + public Task Download(Uri uri) { + return Task.CompletedTask; + } + + public Task Download(string url) + { + return Download(new Uri(url)); } } \ No newline at end of file diff --git a/NextShip.Api/Utils/DirectoryUtils.cs b/NextShip.Api/Utils/DirectoryUtils.cs new file mode 100644 index 0000000..95137aa --- /dev/null +++ b/NextShip.Api/Utils/DirectoryUtils.cs @@ -0,0 +1,14 @@ +namespace NextShip.Api.Utils; + +public static class DirectoryUtils +{ + public static string GetDirectory(this string path) + { + if (Directory.Exists(path)) + return path; + + Directory.CreateDirectory(path!); + + return path; + } +} \ No newline at end of file diff --git a/NextShip.Api/Utils/TextUtils.cs b/NextShip.Api/Utils/TextUtils.cs index 06c4fe0..320f4fa 100644 --- a/NextShip.Api/Utils/TextUtils.cs +++ b/NextShip.Api/Utils/TextUtils.cs @@ -92,4 +92,16 @@ public static string ToText(this IEnumerable chars) { return chars.Aggregate("", (current, c) => current + c); } + + public static string Is(this string text, FileType type) + { + return text += type switch + { + FileType.Csv => ".csv", + FileType.Json => ".json", + FileType.Yaml => ".yaml", + FileType.Txt => ".txt", + _ => "" + }; + } } \ No newline at end of file diff --git a/NextShip/Cosmetics/AllCosmeticsCache.cs b/NextShip/Cosmetics/AllCosmeticsCache.cs new file mode 100644 index 0000000..d50dfb8 --- /dev/null +++ b/NextShip/Cosmetics/AllCosmeticsCache.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; + +namespace NextShip.Cosmetics; + +public static class AllCosmeticsCache +{ + public static readonly List AllHatViewDatasCache = []; + public static readonly List AllNamePlateViewDatasCache = []; + public static readonly List AllSkinViewDatasCache = []; + public static readonly List AllVisorViewDatasCache = []; + public static readonly List AllPetBehavioursCache = new(); + + + public static bool StartCache(HatManager __instance) + { + try + { + __instance.allHats.Do(n => n.AddToCache()); + __instance.allSkins.Do(n => n.AddToCache()); + __instance.allVisors.Do(n => n.AddToCache()); + __instance.allNamePlates.Do(n => n.AddToCache()); + __instance.allPets.Do(n => n.AddToCache()); + Info("缓存成功"); + return true; + } + catch (Exception e) + { + Exception(e); + Error("缓存失败"); + return false; + } + } + + private static void AddToCache(this HatData data) + { + var Asset = data.CreateAddressableAsset(); + Asset.LoadAsync(); + AllHatViewDatasCache.Add(Asset.GetAsset()); + } + + private static void AddToCache(this NamePlateData data) + { + var Asset = data.CreateAddressableAsset(); + Asset.LoadAsync(); + AllNamePlateViewDatasCache.Add(Asset.GetAsset()); + } + + private static void AddToCache(this VisorData data) + { + var Asset = data.CreateAddressableAsset(); + Asset.LoadAsync(); + AllVisorViewDatasCache.Add(Asset.GetAsset()); + } + + private static void AddToCache(this SkinData data) + { + var Asset = data.CreateAddressableAsset(); + Asset.LoadAsync(); + AllSkinViewDatasCache.Add(Asset.GetAsset()); + } + + private static void AddToCache(this PetData data) + { + var Asset = data.CreateAddressableAsset(); + Asset.LoadAsync(); + AllPetBehavioursCache.Add(Asset.GetAsset()); + } +} \ No newline at end of file diff --git a/NextShip/Cosmetics/CosmeticsChecks.cs b/NextShip/Cosmetics/CosmeticsChecks.cs index 0e0be10..3e61662 100644 --- a/NextShip/Cosmetics/CosmeticsChecks.cs +++ b/NextShip/Cosmetics/CosmeticsChecks.cs @@ -7,10 +7,10 @@ namespace NextShip.Cosmetics; [Load] public static class CosmeticsChecks { - private static readonly string TORFolderName = "TheOtherHats"; + private const string TORFolderName = "TheOtherHats"; public static string[] TORHatStrings; - private static readonly string ExtremeHatFolderName = "ExtremeHat"; + private const string ExtremeHatFolderName = "ExtremeHat"; public static IEnumerator CheckCosmetics() { diff --git a/NextShip/Cosmetics/CosmeticsCreator.cs b/NextShip/Cosmetics/CosmeticsCreator.cs index 66c7454..da59dfe 100644 --- a/NextShip/Cosmetics/CosmeticsCreator.cs +++ b/NextShip/Cosmetics/CosmeticsCreator.cs @@ -1,21 +1,18 @@ using System.Collections.Generic; using System.Linq; +using NextShip.Api.Enums; using NextShip.Cosmetics.Loaders; +using PowerTools; using UnityEngine; using UnityEngine.AddressableAssets; namespace NextShip.Cosmetics; -public class CosmeticsCreator +public class CosmeticsCreator(List allSprites) { private static Material hatShader; - public List AllSprites; - - public CosmeticsCreator(List allSprites) - { - AllSprites = allSprites; - } + public readonly List AllSprites = allSprites; private Sprite Get(string name) { @@ -50,6 +47,8 @@ private Sprite Get(string name) hatData.ViewDataRef = assetRef; hatData.CreateAddressableAsset(); + + AllCosmeticsCache.AllHatViewDatasCache.Add(hatView); return (hatView, hatData); } @@ -69,6 +68,8 @@ private Sprite Get(string name) namePlateData.ViewDataRef = assetRef; namePlateData.CreateAddressableAsset(); + + AllCosmeticsCache.AllNamePlateViewDatasCache.Add(namePlateView); return (namePlateView, namePlateData); } @@ -90,6 +91,9 @@ private Sprite Get(string name) skinData.ViewDataRef = assetRef; skinData.CreateAddressableAsset(); + + AllCosmeticsCache.AllSkinViewDatasCache.Add(skinView); + return (skinView, skinData); } @@ -112,6 +116,35 @@ private Sprite Get(string name) visorData.ViewDataRef = assetRef; visorData.CreateAddressableAsset(); + + AllCosmeticsCache.AllVisorViewDatasCache.Add(visorView); + return (visorView, visorData); } + + public (PetBehaviour, PetData) CreatePet(CosmeticsInfo info) + { + var petData = ScriptableObject.CreateInstance(); + var Behaviour = new GameObject(info.Name).AddComponent(); + + Behaviour.data = petData; + /*visorView.FloorFrame = Get(info.Resource); + visorView.ClimbFrame = Get(info.ClimbResource); + visorView.IdleFrame = Get(info.FlipResource); + visorView.LeftIdleFrame = Get(info.BackFlipResource);*/ + + petData.name = info.Name; + petData.displayOrder = 99; + petData.ProductId = info.Id; + petData.Free = true; + + var assetRef = new AssetReference(petData.Pointer); + + petData.PetPrefabRef = assetRef; + petData.CreateAddressableAsset(); + + AllCosmeticsCache.AllPetBehavioursCache.Add(Behaviour); + + return (Behaviour, petData); + } } \ No newline at end of file diff --git a/NextShip/Cosmetics/CustomCosmeticsManager.cs b/NextShip/Cosmetics/CustomCosmeticsManager.cs index 2217eb1..c29bc8f 100644 --- a/NextShip/Cosmetics/CustomCosmeticsManager.cs +++ b/NextShip/Cosmetics/CustomCosmeticsManager.cs @@ -13,30 +13,30 @@ namespace NextShip.Cosmetics; -public static class CustomCosmeticsManager +public static partial class CustomCosmeticsManager { public const string RepoFile = "CosmeticRepo"; - public static Dictionary AllCustomCosmeticNameAndInfo = new(); - public static Dictionary AllCosmeticRepoRepo = new(); + + public static readonly Dictionary AllCustomCosmeticNameAndInfo = new(); + public static readonly Dictionary AllCosmeticRepoRepo = new(); - public static HashSet AllCustomCosmeticSprites = new(); - public static HashSet AllCosmeticId = new(); + public static readonly HashSet AllCustomCosmeticSprites = []; + public static readonly HashSet AllCosmeticId = []; - public static Dictionary AllCustomHatViewData = new(); - public static List AllCustomSkinViewData = new(); - public static List AllCustomVisorViewData = new(); - public static List AllCustomNamePlateViewData = new(); + public static readonly Dictionary AllCustomHatViewData = new(); + public static readonly List AllCustomSkinViewData = []; + public static readonly List AllCustomVisorViewData = []; + public static readonly List AllCustomNamePlateViewData = []; private static CosmeticsLoader _Loaders; - public static List AllLoaders = new(); + public static readonly List AllLoaders = []; - internal static readonly string RepoFilePath = - Path.Combine(FilesManager.CreativityPath, RepoFile.Is(FileType.Json)); + private static readonly string RepoFilePath = + Path.Combine(NextPaths.CreativityPath, RepoFile.Is(FileType.Json)); private static readonly CosmeticsConfig[] ModConfig = - { - }; + Array.Empty(); public static Sprite GetSprite(string name) { @@ -54,9 +54,8 @@ public static void LoadHat() { foreach (var config in from config in configs let regex = - new Regex( - @"/https?\/\/:[-a-z0-9]+(\.[-a-z0-9])*\.(com|cn|edu|uk)\/[-a-z0-9_:@&?=+,.!/~*'%$]*/ig") - where regex.IsMatch(config.RepoURL) + MyRegex() + where regex.IsMatch(config.RepoURL) select config) { Load(config.CosmeticRepoType); @@ -69,7 +68,7 @@ where regex.IsMatch(config.RepoURL) } } - public static List ReadRepoFile() + public static IEnumerable ReadRepoFile() { using TextReader textReader = new StreamReader(RepoFilePath); return JsonSerializer.Deserialize>(textReader.ReadToEnd()); @@ -112,4 +111,7 @@ public static void AddToList(HatManager __instance) __instance.allHats = list.ToArray(); } } + + [GeneratedRegex(@"/https?\/\/:[-a-z0-9]+(\.[-a-z0-9])*\.(com|cn|edu|uk)\/[-a-z0-9_:@&?=+,.!/~*'%$]*/ig")] + private static partial Regex MyRegex(); } \ No newline at end of file diff --git a/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs b/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs index c2b06d8..0f9051e 100644 --- a/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs +++ b/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs @@ -8,25 +8,30 @@ namespace NextShip.Cosmetics.Loaders; public abstract class CosmeticsLoader { - public List AllCosmeticsInfo; - public List AllHat; - public List AllNamePlate; - public List AllSprite; + public readonly List AllCosmeticsInfo; + public readonly List AllHat; + public readonly List AllNamePlate; + public readonly List AllSprite; public List AllVisor; - public string HatJsonName = "CustomHats.json"; - public Dictionary> Hats = new(); + public const string HatJsonName = "CustomHats.json"; + public readonly Dictionary> Hats = new(); protected CosmeticsLoader() { CustomCosmeticsManager.AllLoaders.Add(this); - AllHat = new List(); - AllVisor = new List(); - AllNamePlate = new List(); - AllSprite = new List(); - AllCosmeticsInfo = new List(); + AllHat = []; + AllVisor = []; + AllNamePlate = []; + AllSprite = []; + AllCosmeticsInfo = []; + } + + protected CosmeticsLoader(List allHat) + { + AllHat = allHat; } public bool Loaded { get; protected set; } @@ -56,31 +61,3 @@ public virtual Task LoadFormOnRepo(CosmeticsConfig cosmeticsConfig) return Task.CompletedTask; } } - -public record CosmeticsInfo -{ - public CosmeticType CosmeticType { get; set; } - public string Name { get; set; } - public string Author { get; set; } - - - public string Id { get; set; } - public string Package { get; set; } - public string Condition { get; set; } - - public string Resource { get; set; } - public string FlipResource { get; set; } - public string BackFlipResource { get; set; } - public string BackResource { get; set; } - public string ClimbResource { get; set; } - - public string ResHash { get; set; } - public string ResHashBack { get; set; } - public string ResHashClimb { get; set; } - public string ResHashFlip { get; set; } - public string ResHashBackFlip { get; set; } - - public bool Bounce { get; set; } - public bool Adaptive { get; set; } - public bool Behind { get; set; } -} \ No newline at end of file diff --git a/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs b/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs index 9126d3a..1882b7c 100644 --- a/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs +++ b/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs @@ -18,7 +18,7 @@ namespace NextShip.Cosmetics.Loaders; public class TORCosmeticsLoader : CosmeticsLoader { private readonly CosmeticType CosmeticType = CosmeticType.Hat; - private readonly string HatDirectoryName = "hats"; + private const string HatDirectoryName = "hats"; public override CosmeticType GetCosmeticType() { @@ -58,7 +58,7 @@ private async Task Download(string Url) var jsonString = await response.Content.ReadAsStringAsync(); var JObj = JObject.Parse(jsonString)["hats"]; - var jsonFile = File.CreateText(FilesManager.CreativityPath + $"/{HatJsonName}"); + var jsonFile = File.CreateText(NextPaths.TIS_TORHats + $"/{HatJsonName}"); await jsonFile.WriteAsync(jsonString); if (!JObj.HasValues) return HttpStatusCode.ExpectationFailed; @@ -80,7 +80,7 @@ private async Task Download(string Url) private static void AddCosmeticInfoFromJson(JToken JObj, out List cosmeticsInfos) { - cosmeticsInfos = new List(); + cosmeticsInfos = []; for (var current = JObj.First; current != null; current = current.Next) { if (!current.HasValues) continue; @@ -121,7 +121,7 @@ private async void DownLoadSprites(HttpClient httpClient, string url, List(); var md5 = MD5.Create(); - var directoryPath = FilesManager.GetCosmeticsCacheDirectory(CosmeticsTypes.Hat).FullName; + var directoryPath = $"{NextPaths.TIS_TORHats}/Cache".GetDirectory(); foreach (var info in infos) { diff --git a/NextShip/Cosmetics/Patches/HatManagerPatch.cs b/NextShip/Cosmetics/Patches/HatManagerPatch.cs index 042d4a4..fa67c14 100644 --- a/NextShip/Cosmetics/Patches/HatManagerPatch.cs +++ b/NextShip/Cosmetics/Patches/HatManagerPatch.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using HarmonyLib; +using HarmonyLib; namespace NextShip.Cosmetics.Patches; @@ -16,79 +14,6 @@ public static void InitHatCache(HatManager __instance) if (initialized) return; TaskUtils.StartTask(() => initialized = AllCosmeticsCache.StartCache(__instance)); - /*CustomCosmeticsManager.AddToList(__instance);*/ - } - - /*[HarmonyPatch(nameof(HatManager.GetHatById))] - [HarmonyPatch(nameof(HatManager.GetUnlocked))] - [HarmonyPrefix] - public static void AddToListPatch_HatManager(HatManager __instance) - { - CustomCosmeticsManager.AddToList(__instance); - }*/ -} - -public static class AllCosmeticsCache -{ - public static List AllHatViewDatasCache = new(); - public static List AllNamePlateViewDatasCache = new(); - public static List AllSkinViewDatasCache = new(); - public static List AllVisorViewDatasCache = new(); - public static List AllPetBehavioursCache = new(); - - - public static bool StartCache(HatManager __instance) - { - try - { - __instance.allHats.Do(n => n.AddToCache()); - __instance.allSkins.Do(n => n.AddToCache()); - __instance.allVisors.Do(n => n.AddToCache()); - __instance.allNamePlates.Do(n => n.AddToCache()); - __instance.allPets.Do(n => n.AddToCache()); - Info("缓存成功"); - return true; - } - catch (Exception e) - { - Exception(e); - Error("缓存失败"); - return false; - } - } - - private static void AddToCache(this HatData data) - { - var Asset = data.CreateAddressableAsset(); - Asset.LoadAsync(); - AllHatViewDatasCache.Add(Asset.GetAsset()); - } - - private static void AddToCache(this NamePlateData data) - { - var Asset = data.CreateAddressableAsset(); - Asset.LoadAsync(); - AllNamePlateViewDatasCache.Add(Asset.GetAsset()); - } - - private static void AddToCache(this VisorData data) - { - var Asset = data.CreateAddressableAsset(); - Asset.LoadAsync(); - AllVisorViewDatasCache.Add(Asset.GetAsset()); - } - - private static void AddToCache(this SkinData data) - { - var Asset = data.CreateAddressableAsset(); - Asset.LoadAsync(); - AllSkinViewDatasCache.Add(Asset.GetAsset()); - } - - private static void AddToCache(this PetData data) - { - var Asset = data.CreateAddressableAsset(); - Asset.LoadAsync(); - AllPetBehavioursCache.Add(Asset.GetAsset()); } + } \ No newline at end of file diff --git a/NextShip/DIY/Plugins/PluginManager.cs b/NextShip/DIY/Plugins/PluginManager.cs index fb02544..8522c99 100644 --- a/NextShip/DIY/Plugins/PluginManager.cs +++ b/NextShip/DIY/Plugins/PluginManager.cs @@ -12,24 +12,13 @@ namespace NextShip.DIY.Plugins; public class PluginManager : Manager { - private readonly List<(Assembly, Type, ShipPlugin)> PluginCreateS = new(); - public bool existDirectory; - private List PluginPathS = new(); + private readonly List<(Assembly, Type, ShipPlugin)> PluginCreateS = []; + private List PluginPathS = []; - public List Plugins = new(); - private string PluginsPath; + public List Plugins = []; - [Load] - public static void Init() + public void Load() { - Get().Load(); - } - - private void Load() - { - PluginsPath = FilesManager.GetCreativityDirectory("Plugins").FullName; - existDirectory = Directory.Exists(PluginsPath); - LoadPlugins(); } @@ -98,7 +87,7 @@ private static void Load((Assembly, Type, ShipPlugin) pluginTuple) private List FindPlugins() { var pluginPaths = new List(); - var plugins = new DirectoryInfo(PluginsPath); + var plugins = new DirectoryInfo(NextPaths.TIS_PluginsPath); var fileInfos = plugins.GetFiles(); fileInfos.Do(n => pluginPaths.Add(n.FullName)); return pluginPaths; diff --git a/NextShip/Languages/LanguagePack.cs b/NextShip/Languages/LanguagePack.cs index 307b3ce..47b5266 100644 --- a/NextShip/Languages/LanguagePack.cs +++ b/NextShip/Languages/LanguagePack.cs @@ -78,13 +78,10 @@ public static string GetLname(int id) // 创建文件夹 private static void CTT() { - FilesManager.CreateDirectory(FPath); - if (!(Directory.GetDirectories(FPath).Length > 0 || Directory.GetFiles(FPath).Length > 0) || - !File.Exists(LPath) || !File.Exists(PPath)) - { - CreateTT(); - Msg("正在创建语言模板", "Language Pack"); - } + if ((Directory.GetDirectories(FPath).Length > 0 || Directory.GetFiles(FPath).Length > 0) && + File.Exists(LPath) && File.Exists(PPath)) return; + CreateTT(); + Msg("正在创建语言模板", "Language Pack"); } // 创建语言模板 diff --git a/NextShip/Manager/FilesManager.cs b/NextShip/Manager/FilesManager.cs deleted file mode 100644 index 778ae02..0000000 --- a/NextShip/Manager/FilesManager.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System.IO; -using NextShip.Api.Enums; - -namespace NextShip.Manager; - -public static class FilesManager -{ - public const string TIS_DataPath = "./TIS_Data"; - public const string CreativityPath = "./Creativity"; - public const string TIS_TempPath = "./TIS_Data/TEMP"; - public const string TIS_ConfigPath = TIS_DataPath + "/Config"; - - - public static void Init() - { - CreateDirectory(TIS_DataPath); - CreateDirectory(CreativityPath); - CreateDirectory(TIS_TempPath); - CreateDirectory(TIS_ConfigPath); - } - - public static DirectoryInfo CreateDirectory(string path) - { - DirectoryInfo directoryInfo; - if (!Directory.Exists(path)) - { - directoryInfo = Directory.CreateDirectory(path!); - Msg("创建文件夹:" + path.TextRemove("./") + "成功", filename: "FilesManager"); - } - else - { - directoryInfo = new DirectoryInfo(path); - Msg("文件夹已存在", filename: "FilesManager"); - } - - - return directoryInfo; - } - - public static DirectoryInfo GetDataDirectory(string name) - { - return CreateDirectory(Path.Combine(TIS_DataPath, name)); - } - - public static DirectoryInfo GetRootDirectory(string name) - { - return CreateDirectory($"./{name}"); - } - - public static DirectoryInfo GetCreativityDirectory(string name) - { - return CreateDirectory(Path.Combine(CreativityPath, name)); - } - - public static DirectoryInfo GetConfigDirectory(string name) - { - return CreateDirectory(Path.Combine(CreativityPath, "Config", name)); - } - - public static DirectoryInfo GetCosmeticsCacheDirectory(CosmeticsTypes type) - { - var directoryName = type switch - { - CosmeticsTypes.NamePlate => "CacheNamePlate", - CosmeticsTypes.Visor => "CacheVisor", - CosmeticsTypes.Skin => "CacheSkin", - CosmeticsTypes.Hat => "CacheHat", - _ => string.Empty - }; - return CreateDirectory(Path.Combine(CreativityPath, directoryName)); - } - - public static string Is(this string text, FileType type) - { - return text += type switch - { - FileType.Csv => ".csv", - FileType.Json => ".json", - FileType.Yaml => ".yaml", - FileType.Txt => ".txt", - _ => "" - }; - } -} \ No newline at end of file diff --git a/NextShip/Manager/NextPlayerManager.cs b/NextShip/Manager/NextPlayerManager.cs index 8280de5..a6e71f4 100644 --- a/NextShip/Manager/NextPlayerManager.cs +++ b/NextShip/Manager/NextPlayerManager.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using NextShip.Api.Bases; using NextShip.Api.Interfaces; @@ -6,11 +7,10 @@ namespace NextShip.Manager; public class NextPlayerManager : IPlayerManager { - private static NextPlayerManager? _nextPlayerManager; - private readonly List PlayerInfos = new(); - public static NextPlayerManager Instance => _nextPlayerManager ??= new NextPlayerManager(); + + public static NextPlayerManager Instance => Main._Service.Get(); public NextInfo GetPlayerInfo(PlayerControl player) { @@ -20,4 +20,22 @@ public NextInfo GetPlayerInfo(PlayerControl player) public void CreatePlayerInfo() { } + + public bool TryGetPlayer(PlayerControl player, out NextInfo? info) + { + if (PlayerInfos.Exists(n => n.PlayerControl == player)) + { + info = PlayerInfos.First(n => n.PlayerControl == player); + return true; + } + + info = null; + return false; + } + + + public void Clear() + { + PlayerInfos.Clear(); + } } \ No newline at end of file diff --git a/NextShip/Manager/RoleManager.cs b/NextShip/Manager/RoleManager.cs index 598130f..293e19b 100644 --- a/NextShip/Manager/RoleManager.cs +++ b/NextShip/Manager/RoleManager.cs @@ -1,15 +1,17 @@ using System.Collections.Generic; using System.Linq; using NextShip.Api.Interfaces; +using NextShip.Roles; namespace NextShip.Manager; +#nullable enable public sealed class NextRoleManager : IRoleManager { - public readonly HashSet RoleCreators = new(); - public readonly List Roles = new(); - - + public IRoleCreator? CurrentCreator { get; private set; } + + public readonly List Roles = []; + public void Register(IRole role) { Roles.Add(role); @@ -20,28 +22,40 @@ public void UnRegister(IRole role) Roles.Remove(role); } - public void AddCreator(IRoleCreator creator) + public FastCreator FastGetCreator() { - RoleCreators.Add(creator); + if (CurrentCreator is FastCreator creator) + return creator; + + var newCreator = new FastCreator(); + SetCreator(newCreator); + + return newCreator; } + - public void RemoveCreator(IRoleCreator creator) + public void AssignRole(PlayerControl player, IRole role) { - RoleCreators.Remove(creator); } - public T GetRole() where T : IRole + public void Clear() { - return (T)Roles.FirstOrDefault(n => n is T); } - public IEnumerable GetRoles() where T : IRole + public void SetCreator(IRoleCreator creator) { - return Roles.FindAll(n => n is T).Select(n => (T)n); + CurrentCreator?.Dispose(); + CurrentCreator = null; + CurrentCreator = creator; } - public T GetCreator() where T : IRoleCreator + public T? GetRole() where T : class, IRole { - return (T)RoleCreators.FirstOrDefault(n => n is T); + return Roles.FirstOrDefault(n => n is T) as T; + } + + public IEnumerable GetRoles() where T : IRole + { + return Roles.FindAll(n => n is T).Select(n => (T)n); } } \ No newline at end of file diff --git a/NextShip/NextPaths.cs b/NextShip/NextPaths.cs deleted file mode 100644 index 09a6aeb..0000000 --- a/NextShip/NextPaths.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections; -using NextShip.Api.Attributes; -using NextShip.Api.Enums; - -namespace NextShip; - -[Load(LoadMode.PreLoad)] -public class NextPaths -{ - [Load] - public static IEnumerator PreLoad() - { - yield return null; - } -} \ No newline at end of file diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index fc60f83..70c351d 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -10,7 +10,6 @@ true false false - enable @@ -27,7 +26,7 @@ - + diff --git a/NextShip/Patches/JoinGameButtonPatch.cs b/NextShip/Patches/JoinGameButtonPatch.cs index 4bdd40d..30a7389 100644 --- a/NextShip/Patches/JoinGameButtonPatch.cs +++ b/NextShip/Patches/JoinGameButtonPatch.cs @@ -5,13 +5,16 @@ namespace NextShip.Patches; [HarmonyPatch(typeof(JoinGameButton), nameof(JoinGameButton.OnClick))] -internal class JoinGameButtonPatch +internal partial class JoinGameButtonPatch { public static void Prefix(JoinGameButton __instance) { if (__instance.GameIdText == null) return; if (__instance.GameIdText.text == "" && - Regex.IsMatch(GUIUtility.systemCopyBuffer.Trim('\r', '\n'), @"^[a-zA-Z]{6}$")) + MyRegex().IsMatch(GUIUtility.systemCopyBuffer.Trim('\r', '\n'))) __instance.GameIdText.SetText(GUIUtility.systemCopyBuffer.Trim('\r', '\n')); } + + [GeneratedRegex(@"^[a-zA-Z]{6}$")] + private static partial Regex MyRegex(); } \ No newline at end of file diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs index 3bfca56..0a44a00 100644 --- a/NextShip/Patches/PlayerPatch.cs +++ b/NextShip/Patches/PlayerPatch.cs @@ -1,4 +1,5 @@ using HarmonyLib; +using NextShip.Manager; namespace NextShip.Patches; @@ -8,5 +9,7 @@ public static class PlayerPatch [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.Awake))] public static void PlayerControlAwake_PostfixPatch(PlayerControl __instance) { + if (NextPlayerManager.Instance.TryGetPlayer(__instance, out _)) + return; } } \ No newline at end of file diff --git a/NextShip/Patches/RegionPatch.cs b/NextShip/Patches/RegionPatch.cs index 1c23685..db75bd6 100644 --- a/NextShip/Patches/RegionPatch.cs +++ b/NextShip/Patches/RegionPatch.cs @@ -30,39 +30,33 @@ public static void Postfix(RegionMenu __instance) __instance.transform, () => { - if (ye < maxye) - { - ye++; - Menu.shuaXing(__instance); - } + if (ye >= maxye) return; + ye++; + Menu.Update(__instance); } ); xiaButton.gameObject.SetActive(!(Main.serverManager.AvailableRegions.Count <= 6)); } - if (shangButton == null || shangButton.gameObject == null) - { - shangButton = template.CreateButton( - "shangButton", - "上一页", - pos - new Vector3(0f, 2.5f, 0f), - __instance.transform, - () => - { - if (ye > 1) - { - ye--; - Menu.shuaXing(__instance); - } - } - ); + if (shangButton != null && shangButton.gameObject != null) return; + shangButton = template.CreateButton( + "shangButton", + "上一页", + pos - new Vector3(0f, 2.5f, 0f), + __instance.transform, + () => + { + if (ye <= 1) return; + ye--; + Menu.Update(__instance); + } + ); - xiaButton.gameObject.SetActive(!(Main.serverManager.AvailableRegions.Count <= 6)); - } + xiaButton.gameObject.SetActive(!(Main.serverManager.AvailableRegions.Count <= 6)); } - public static GameObject CreateButton(this GameObject template, string name, string text, Vector3 Position, + private static GameObject CreateButton(this GameObject template, string name, string text, Vector3 Position, Transform Preant, Action action) { var Button = Object.Instantiate(template, Preant); @@ -110,25 +104,14 @@ private static void CreateServerOption(RegionMenu __instance) { RegionMenuOpenPatch.maxye = serverManager.AvailableRegions.Count / 3 + (serverManager.AvailableRegions.Count % 3 == 0 ? 0 : 1); - var regionInfos = new IRegionInfo[1]; + var regionInfos = Array.Empty(); if (serverManager.AvailableRegions.Count < 6) regionInfos = serverManager.AvailableRegions; else - updateyer(); - - void updateyer() - { - var rlist = new List(); - for (var i = 0; i < 3; i++) - { - var s = RegionMenuOpenPatch.ye * 3 - i; - if (s <= serverManager.AvailableRegions.Count) rlist.Add(serverManager.AvailableRegions[s - 1]); - regionInfos = rlist.ToArray(); - } - } + UpdateYer(); __instance.controllerSelectable.Clear(); - List List = new(); + List List = []; var num = 0; foreach (var regionInfo in regionInfos) { @@ -148,9 +131,21 @@ void updateyer() } List.Do(n => __instance.controllerSelectable.Add(n)); + return; + + void UpdateYer() + { + var list = new List(); + for (var i = 0; i < 3; i++) + { + var s = RegionMenuOpenPatch.ye * 3 - i; + if (s <= serverManager.AvailableRegions.Count) list.Add(serverManager.AvailableRegions[s - 1]); + regionInfos = list.ToArray(); + } + } } - public static void shuaXing(RegionMenu __instance) + public static void Update(RegionMenu __instance) { __instance.ButtonPool.ReclaimAll(); CreateServerOption(__instance); diff --git a/NextShip/Patches/RoleAssignmentPatch.cs b/NextShip/Patches/RoleAssignmentPatch.cs index 772b9b4..524bb0c 100644 --- a/NextShip/Patches/RoleAssignmentPatch.cs +++ b/NextShip/Patches/RoleAssignmentPatch.cs @@ -1,435 +1,43 @@ -/*using System; -using System.Collections.Generic; -using System.Linq; using AmongUs.GameOptions; using HarmonyLib; -using Hazel; -using NextShip.Roles; -using NextShip.RPC; -using NextShip.Utilities; +using NextShip.Api.Attributes; +using NextShip.Manager; using UnityEngine; -using static NextShip.Roles.Core.RoleEnum; namespace NextShip.Patches; -public class RoleAssignmentData +[Harmony] +internal class GameOptionsDataPatch { - public Dictionary crewSettings = new(); - public Dictionary impSettings = new(); - public Dictionary neutralSettings = new(); - public List crewmates { get; set; } - public List impostors { get; set; } - public int maxCrewmateRoles { get; set; } - public int maxNeutralRoles { get; set; } - public int maxImpostorRoles { get; set; } -} - -[HarmonyPatch(typeof(RoleOptionsData), nameof(RoleOptionsData.GetNumPerGame))] -internal class RoleOptionsDataGetNumPerGamePatch -{ - public static void Postfix(ref int __result) - { - } -} - -[HarmonyPatch(typeof(IGameOptionsExtensions), nameof(IGameOptionsExtensions.GetAdjustedNumImpostors))] -internal class GameOptionsDataGetAdjustedNumImpostorsPatch -{ - public static void Postfix(ref int __result) + [HarmonyPatch(typeof(IGameOptionsExtensions), nameof(IGameOptionsExtensions.GetAdjustedNumImpostors))] + [HarmonyPostfix] + public static void GetAdjustedNumImpostorsPatch_Postfix(ref int __result) { __result = Mathf.Clamp(GameOptionsManager.Instance.CurrentGameOptions.NumImpostors, 1, 3); } -} -[HarmonyPatch(typeof(GameOptionsData), nameof(GameOptionsData.Validate))] -internal class GameOptionsDataValidatePatch -{ - public static void Postfix(GameOptionsData __instance) + [HarmonyPatch(typeof(GameOptionsData), nameof(GameOptionsData.Validate))] + [HarmonyPostfix] + public static void ValidatePatch_Postfix(GameOptionsData __instance) { __instance.NumImpostors = GameOptionsManager.Instance.CurrentGameOptions.NumImpostors; } } -[HarmonyPatch(typeof(RoleManager), nameof(RoleManager.SelectRoles))] -internal class RoleManagerSelectRolesPatch +[Harmony] +internal class RoleManagerPatch { - private static int crewValues; - private static int impValues; - private static readonly List> playerRoleMap = new(); - - public static RoleAssignmentData GetRoleAssignmentData() - { - var crewmates = PlayerControl.AllPlayerControls.ToArray().ToList().OrderBy(x => Guid.NewGuid()).ToList(); - crewmates.RemoveAll(x => x.Data.Role.IsImpostor); - var impostors = PlayerControl.AllPlayerControls.ToArray().ToList().OrderBy(x => Guid.NewGuid()).ToList(); - impostors.RemoveAll(x => !x.Data.Role.IsImpostor); - - var crewmateMin = crewmateRolesCountMin.getSelection(); - var crewmateMax = crewmateRolesCountMax.getSelection(); - var neutralMin = neutralRolesCountMin.getSelection(); - var neutralMax = neutralRolesCountMax.getSelection(); - var impostorMin = impostorRolesCountMin.getSelection(); - var impostorMax = impostorRolesCountMax.getSelection(); - - if (crewmateMin > crewmateMax) crewmateMin = crewmateMax; - if (neutralMin > neutralMax) neutralMin = neutralMax; - if (impostorMin > impostorMax) impostorMin = impostorMax; - - var crewCountSettings = rnd.Next(crewmateMin, crewmateMax + 1); - var neutralCountSettings = rnd.Next(neutralMin, neutralMax + 1); - var impCountSettings = rnd.Next(impostorMin, impostorMax + 1); - - var maxCrewmateRoles = Mathf.Min(crewmates.Count, crewCountSettings); - var maxNeutralRoles = Mathf.Min(crewmates.Count, neutralCountSettings); - var maxImpostorRoles = Mathf.Min(impostors.Count, impCountSettings); - - var impSettings = new Dictionary(); - var neutralSettings = new Dictionary(); - var crewSettings = new Dictionary(); - - impSettings.Add((byte)RoleId.Camouflager, Camouflager.camouflagerSpawnRate.getSelection()); - impSettings.Add((byte)RoleId.Illusory, illusorySpawnRate.getSelection()); - - crewSettings.Add((byte)RoleId.Sheriff, sheriffSpawnRate.getSelection()); + [ServiceAdd] private static readonly NextRoleManager _nextRoleManager; - neutralSettings.Add((byte)RoleId.Jester, jesterSpawnRate.getSelection()); - neutralSettings.Add((byte)RoleId.SchrodingersCats, SchrodingersCatRate.getSelection()); - - return new RoleAssignmentData - { - crewmates = crewmates, - impostors = impostors, - crewSettings = crewSettings, - neutralSettings = neutralSettings, - impSettings = impSettings, - maxCrewmateRoles = maxCrewmateRoles, - maxNeutralRoles = maxNeutralRoles, - maxImpostorRoles = maxImpostorRoles - }; - } - - public static void Postfix() + [HarmonyPatch(typeof(RoleManager), nameof(RoleManager.SelectRoles))] + public static void SelectRoles_Postfix(RoleManager __instance) { - var writer = AmongUsClient.Instance.StartRpcImmediately(CachedPlayer.LocalPlayer.PlayerControl.NetId, - (byte)CustomRPC.ResetVariables, SendOption.Reliable); - AmongUsClient.Instance.FinishRpcImmediately(writer); - RPCProcedure.ResetVariables(); - if (activateRoles.getBool()) assignRoles(); } - - private static void assignRoles() + [HarmonyPatch(typeof(GameManager), nameof(GameManager.EndGame))] + public static void OnGameEnd_Postfix(GameManager __instance) { - var data = GetRoleAssignmentData(); - assignEnsuredRoles(data); // Assign roles that should always be in the game next - assignChanceRoles(data); // Assign roles that may or may not be in the game last - assignModifiers(); // Assign modifier - setRolesAgain(); + NextPlayerManager.Instance.Clear(); + _nextRoleManager.Clear(); } - - private static void assignEnsuredRoles(RoleAssignmentData data) - { - var ensuredCrewmateRoles = data.crewSettings.Where(x => x.Value == 10).Select(x => x.Key).ToList(); - var ensuredNeutralRoles = data.neutralSettings.Where(x => x.Value == 10).Select(x => x.Key).ToList(); - var ensuredImpostorRoles = data.impSettings.Where(x => x.Value == 10).Select(x => x.Key).ToList(); - - while - ( - ( - data.impostors.Count > 0 - && - data.maxImpostorRoles > 0 - && - ensuredImpostorRoles.Count > 0 - ) - || - ( - data.crewmates.Count > 0 - && - ( - ( - data.maxCrewmateRoles > 0 - && - ensuredCrewmateRoles.Count > 0 - ) - || - ( - data.maxNeutralRoles > 0 - && - ensuredNeutralRoles.Count > 0 - ) - ) - ) - ) - { - var rolesToAssign = new Dictionary>(); - if - ( - data.crewmates.Count > 0 - && - ensuredCrewmateRoles.Count > 0 - ) - rolesToAssign.Add(RoleType.Crewmate, ensuredCrewmateRoles); - - if - ( - data.crewmates.Count > 0 - && - data.maxNeutralRoles > 0 - && - ensuredNeutralRoles.Count > 0 - ) - rolesToAssign.Add(RoleType.Neutral, ensuredNeutralRoles); - - if - ( - data.impostors.Count > 0 - && - data.maxImpostorRoles > 0 - && ensuredImpostorRoles.Count > 0 - ) - rolesToAssign.Add(RoleType.Impostor, ensuredImpostorRoles); - - var roleType = rolesToAssign.Keys.ElementAt(rnd.Next(0, rolesToAssign.Keys.Count())); - var players = roleType == RoleType.Crewmate || roleType == RoleType.Neutral - ? data.crewmates - : data.impostors; - var index = rnd.Next(0, rolesToAssign[roleType].Count); - var roleId = rolesToAssign[roleType][index]; - setRoleToRandomPlayer(rolesToAssign[roleType][index], players); - rolesToAssign[roleType].RemoveAt(index); - switch (roleType) - { - case RoleType.Crewmate: - data.maxCrewmateRoles--; - crewValues -= 10; - break; - case RoleType.Neutral: - data.maxNeutralRoles--; - break; - case RoleType.Impostor: - data.maxImpostorRoles--; - impValues -= 10; - break; - } - } - } - - private static void assignChanceRoles(RoleAssignmentData data) - { - // Get all roles where the chance to occur is set grater than 0% but not 100% and build a ticket pool based on their weight - var crewmateTickets = data.crewSettings.Where(x => x.Value > 0 && x.Value < 10) - .Select(x => Enumerable.Repeat(x.Key, x.Value)).SelectMany(x => x).ToList(); - var neutralTickets = data.neutralSettings.Where(x => x.Value > 0 && x.Value < 10) - .Select(x => Enumerable.Repeat(x.Key, x.Value)).SelectMany(x => x).ToList(); - var impostorTickets = data.impSettings.Where(x => x.Value > 0 && x.Value < 10) - .Select(x => Enumerable.Repeat(x.Key, x.Value)).SelectMany(x => x).ToList(); - - // Assign roles until we run out of either players we can assign roles to or run out of roles we can assign to players - while ( - (data.impostors.Count > 0 && data.maxImpostorRoles > 0 && impostorTickets.Count > 0) || - (data.crewmates.Count > 0 && ( - (data.maxCrewmateRoles > 0 && crewmateTickets.Count > 0) || - (data.maxNeutralRoles > 0 && neutralTickets.Count > 0) - ))) - { - var rolesToAssign = new Dictionary>(); - if (data.crewmates.Count > 0 && data.maxCrewmateRoles > 0 && crewmateTickets.Count > 0) - rolesToAssign.Add(RoleType.Crewmate, crewmateTickets); - if (data.crewmates.Count > 0 && data.maxNeutralRoles > 0 && neutralTickets.Count > 0) - rolesToAssign.Add(RoleType.Neutral, neutralTickets); - if (data.impostors.Count > 0 && data.maxImpostorRoles > 0 && impostorTickets.Count > 0) - rolesToAssign.Add(RoleType.Impostor, impostorTickets); - - // Randomly select a pool of role tickets to assign a role from next (Crewmate role, Neutral role or Impostor role) - // then select one of the roles from the selected pool to a player - // and remove all tickets of this role (and any potentially blocked role pairings) from the pool(s) - var roleType = rolesToAssign.Keys.ElementAt(rnd.Next(0, rolesToAssign.Keys.Count())); - var players = roleType == RoleType.Crewmate || roleType == RoleType.Neutral - ? data.crewmates - : data.impostors; - var index = rnd.Next(0, rolesToAssign[roleType].Count); - var roleId = rolesToAssign[roleType][index]; - setRoleToRandomPlayer(roleId, players); - rolesToAssign[roleType].RemoveAll(x => x == roleId); - - // Adjust the role limit - switch (roleType) - { - case RoleType.Crewmate: - data.maxCrewmateRoles--; - break; - case RoleType.Neutral: - data.maxNeutralRoles--; - break; - case RoleType.Impostor: - data.maxImpostorRoles--; - break; - } - } - } - - private static void assignModifiers() - { - var modifierMin = modifierRolesCountMin.getSelection(); - var modifierMax = modifierRolesCountMax.getSelection(); - if (modifierMin > modifierMax) modifierMin = modifierMax; - var modifierCountSettings = rnd.Next(modifierMin, modifierMax + 1); - var players = PlayerControl.AllPlayerControls.ToArray().ToList(); - var modifierCount = Mathf.Min(players.Count, modifierCountSettings); - if (modifierCount == 0) return; - - var allModifiers = new List(); - var ensuredModifiers = new List(); - var chanceModifiers = new List(); - allModifiers.AddRange - ( - new List - { - RoleId.Flash - } - ); - - if (rnd.Next(1, 101) <= LoverSpawnRate.getSelection() * 10 && CachedPlayer.AllPlayers.Count >= 2) - { - // 分配恋人 - var isEvilLover = rnd.Next(1, 101) <= LoverIsEvilProbability.getSelection() * 10; - byte firstLoverId; - var impPlayer = new List(players); - var crewPlayer = new List(players); - impPlayer.RemoveAll(x => !x.Data.Role.IsImpostor); - crewPlayer.RemoveAll(x => x.Data.Role.IsImpostor); - - if (isEvilLover) firstLoverId = setModifierToRandomPlayer((byte)RoleId.Lover, impPlayer); - else firstLoverId = setModifierToRandomPlayer((byte)RoleId.Lover, crewPlayer); - var secondLoverId = setModifierToRandomPlayer((byte)RoleId.Lover, crewPlayer, 1); - - players.RemoveAll(x => x.PlayerId == firstLoverId || x.PlayerId == secondLoverId); - modifierCount--; - } - - foreach (var m in allModifiers) - if (getSelectionForRoleId(m) == 10) - ensuredModifiers.AddRange(Enumerable.Repeat(m, getSelectionForRoleId(m) / 10)); - else chanceModifiers.AddRange(Enumerable.Repeat(m, getSelectionForRoleId(m))); - - assignModifiersToPlayers(ensuredModifiers, players, modifierCount); // Assign ensured modifier - - modifierCount -= ensuredModifiers.Count; - if (modifierCount <= 0) return; - var chanceModifierCount = Mathf.Min(modifierCount, chanceModifiers.Count); - var chanceModifierToAssign = new List(); - while (chanceModifierCount > 0 && chanceModifiers.Count > 0) - { - var index = rnd.Next(0, chanceModifiers.Count); - var modifierId = chanceModifiers[index]; - chanceModifierToAssign.Add(modifierId); - - var modifierSelection = getSelectionForRoleId(modifierId); - while (modifierSelection > 0) - { - chanceModifiers.Remove(modifierId); - modifierSelection--; - } - - chanceModifierCount--; - } - } - - private static byte setRoleToRandomPlayer(byte roleId, List playerList) - { - var index = rnd.Next(0, playerList.Count); - var playerId = playerList[index].PlayerId; - - playerRoleMap.Add(new Tuple(playerId, roleId)); - var writer = AmongUsClient.Instance.StartRpcImmediately(CachedPlayer.LocalPlayer.PlayerControl.NetId, - (byte)CustomRPC.SetRole, SendOption.Reliable); - writer.Write(roleId); - writer.Write(playerId); - AmongUsClient.Instance.FinishRpcImmediately(writer); - RPCProcedure.setRole(roleId, playerId); - return playerId; - } - - private static void setRolesAgain() - { - while (playerRoleMap.Any()) - { - var amount = (byte)Math.Min(playerRoleMap.Count, 20); - var writer = AmongUsClient.Instance!.StartRpcImmediately(CachedPlayer.LocalPlayer.PlayerControl.NetId, - (byte)CustomRPC.WorkaroundSetRoles, SendOption.Reliable); - writer.Write(amount); - for (var i = 0; i < amount; i++) - { - var option = playerRoleMap[0]; - playerRoleMap.RemoveAt(0); - writer.WritePacked((uint)option.Item1); - writer.WritePacked((uint)option.Item2); - } - - AmongUsClient.Instance.FinishRpcImmediately(writer); - } - } - - private static int getSelectionForRoleId(RoleId roleId) - { - var selection = 0; - switch (roleId) - { - case RoleId.Flash: - selection = flashSpawnRate.getSelection(); - break; - } - - return selection; - } - - private static byte setModifierToRandomPlayer(byte modifierId, List playerList, byte flag = 0) - { - if (playerList.Count == 0) return byte.MaxValue; - var index = rnd.Next(0, playerList.Count); - var playerId = playerList[index].PlayerId; - playerList.RemoveAt(index); - - var writer = AmongUsClient.Instance.StartRpcImmediately(CachedPlayer.LocalPlayer.PlayerControl.NetId, - (byte)CustomRPC.SetModifier, SendOption.Reliable); - writer.Write(modifierId); - writer.Write(playerId); - writer.Write(flag); - AmongUsClient.Instance.FinishRpcImmediately(writer); - RPCProcedure.setModifier(modifierId, playerId, flag); - return playerId; - } - - private static void assignModifiersToPlayers(List modifiers, List playerList, - int modifierCount) - { - modifiers = modifiers.OrderBy(x => rnd.Next()).ToList(); // randomize list - - while (modifierCount < modifiers.Count) - { - var index = rnd.Next(0, modifiers.Count); - modifiers.RemoveAt(index); - } - - byte playerId; - - var crewPlayer = new List(playerList); - /* crewPlayer.RemoveAll(x => x.Data.Role.IsImpostor || RoleInfo.getRoleInfoForPlayer(x).Any(r => r.type == RoleInfo.RoleType.Neutral)); #1# - - foreach (var modifier in modifiers) - { - if (playerList.Count == 0) break; - playerId = setModifierToRandomPlayer((byte)modifier, playerList); - playerList.RemoveAll(x => x.PlayerId == playerId); - } - } - - private enum RoleType - { - Crewmate = 0, - Neutral = 1, - Impostor = 2 - } -}*/ - +} \ No newline at end of file diff --git a/NextShip/Patches/SaveManagerPatch.cs b/NextShip/Patches/SaveManagerPatch.cs index 3e807b0..db8e85a 100644 --- a/NextShip/Patches/SaveManagerPatch.cs +++ b/NextShip/Patches/SaveManagerPatch.cs @@ -4,7 +4,6 @@ using AmongUs.Data.Legacy; using AmongUs.Data.Player; using HarmonyLib; -using NextShip.Manager; namespace NextShip.Patches; @@ -38,7 +37,7 @@ public static void LegacySaveManagerPatch_Postfix(ref string __result) [HarmonyPostfix] public static void OnJsonSaveDPatch([HarmonyArgument(1)] string filename) { - var path = FilesManager.CreateDirectory(FilesManager.TIS_ConfigPath).FullName + $"/{filename}"; + var path = NextPaths.TIS_ConfigPath + $"/{filename}"; var sourcePath = AUDataPath.CombinePath(filename); Info($"name {filename} path1 {sourcePath}, path2 {path}"); if (!File.Exists(path)) File.Create(path); @@ -50,7 +49,7 @@ public static void OnJsonSaveDPatch([HarmonyArgument(1)] string filename) public static void OnJsonLoadPatch(AbstractUserSaveData __instance) { var filename = __instance.GetFileName(); - var sourcePath = FilesManager.TIS_ConfigPath + $"/{filename}"; + var sourcePath = NextPaths.TIS_ConfigPath + $"/{filename}"; var DestPath = AUDataPath.CombinePath(filename); if (!File.Exists(sourcePath) || !File.Exists(DestPath)) return; Info($"name {filename} path1 {sourcePath}, path2 {DestPath}"); diff --git a/NextShip/Roles/FastCreator.cs b/NextShip/Roles/FastCreator.cs new file mode 100644 index 0000000..6da1d00 --- /dev/null +++ b/NextShip/Roles/FastCreator.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NextShip.Api.Interfaces; +using NextShip.Manager; + +namespace NextShip.Roles; + +public class FastCreator : IRoleCreator +{ + public readonly List AllRole = []; + + public void Dispose() + { + Clear(); + } + + public T Create(IRole role) where T : RoleBase + { + return (T)role.RoleBase[0]; + } + + public T GetRole(PlayerControl player) where T : class + { + return (AllRole.FirstOrDefault(n => n.Players.Contains(player)) as T)!; + } + + public void Clear() + { + AllRole.Clear(); + } + + public IRole GetAssign() + { + var random = new Random(); + var list = Main._Service.Get().Roles.Where(n => n.EnableAssign).ToList(); + return list[random.Next(list.Count)]; + } +} \ No newline at end of file diff --git a/NextShip/Services/DataService.cs b/NextShip/Services/DataService.cs new file mode 100644 index 0000000..09d6051 --- /dev/null +++ b/NextShip/Services/DataService.cs @@ -0,0 +1,6 @@ +namespace NextShip.Services; + +public class DataService +{ + +} \ No newline at end of file diff --git a/NextShip/Services/HatService.cs b/NextShip/Services/HatService.cs new file mode 100644 index 0000000..a8b0bcc --- /dev/null +++ b/NextShip/Services/HatService.cs @@ -0,0 +1,6 @@ +namespace NextShip.Services; + +public class HatService +{ + +} \ No newline at end of file diff --git a/NextShip/main.cs b/NextShip/main.cs index 1f106c4..c0ab86e 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Linq; using System.Net.Http; using System.Reflection; using BepInEx; @@ -11,6 +12,7 @@ using NextShip.Api.Interfaces; using NextShip.Api.Services; using NextShip.Cosmetics; +using NextShip.DIY.Plugins; using NextShip.Languages; using NextShip.Manager; using NextShip.Patches; @@ -44,7 +46,7 @@ public sealed class NextShip : BasePlugin public static NextService _Service { get; private set; } - public static NextShip Instance { get; private set; } + public static Main Instance { get; private set; } public static Assembly RootAssembly { get; private set; } @@ -58,6 +60,8 @@ public override void Load() TISLog = BepInExLogger.CreateLogSource(ModName.RemoveBlank()); Harmony.PatchAll(); + PluginManager.Get().Load(); + Init(); Get(TISLog); CreateService(); @@ -69,8 +73,7 @@ public override void Load() RegisterManager.Registration(); AddComponent().DontDestroyOnLoad(); - - FilesManager.Init(); + ServerPath.autoAddServer(); LanguagePack.Init(); CustomCosmeticsManager.LoadHat(); @@ -96,11 +99,22 @@ private static void CreateService() builder._collection.AddSingleton(); builder._collection.AddSingleton(); builder._collection.AddSingleton(); + builder._collection.AddSingleton(); builder.AddTransient(); builder.Add(); builder.Add(); + builder.Add(); + builder.Add(); + ServiceAdd(builder, RootAssembly); _Service = NextService.Build(builder); ServiceAddAttribute.Registration(_Service._Provider, RootAssembly); } + + private static void ServiceAdd(IServiceBuilder builder, Assembly addAssembly) + { + var types = addAssembly.GetTypes().Where(n => n.IsDefined(typeof(INextServiceAdd))) + .Select(AccessTools.CreateInstance).Select(n => (INextServiceAdd)n); + foreach (var varType in types) varType.ServiceAdd(builder); + } } \ No newline at end of file From 7f7c1b859ee69cdabcdc4b543aaa98da13a8d912 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Thu, 4 Jan 2024 21:12:29 +0800 Subject: [PATCH 18/29] E --- NextShip.Api/Extension/RPCExtension.cs | 9 +++ NextShip.Api/Interfaces/INextOptionManager.cs | 6 ++ NextShip.Api/Interfaces/IPatchManager.cs | 5 ++ NextShip.Api/Plugins/IPluginManager.cs | 6 ++ NextShip.Api/Plugins/IPluginStartup.cs | 6 ++ NextShip.Api/RPCS/FastRpcWriter.cs | 49 +++++++++++++++ NextShip.Api/Services/DependentService.cs | 16 +++++ NextShip.Api/ShipVersion.cs | 4 +- NextShip/Cosmetics/AllCosmeticsCache.cs | 2 +- NextShip/Manager/NextOptionManager.cs | 8 +++ NextShip/Manager/NextPatchManager.cs | 63 ++++++++++++++++++- NextShip/RPC/FastRPC.cs | 49 +-------------- NextShip/main.cs | 3 +- 13 files changed, 173 insertions(+), 53 deletions(-) create mode 100644 NextShip.Api/Extension/RPCExtension.cs create mode 100644 NextShip.Api/Interfaces/INextOptionManager.cs create mode 100644 NextShip.Api/Plugins/IPluginManager.cs create mode 100644 NextShip.Api/Plugins/IPluginStartup.cs create mode 100644 NextShip.Api/RPCS/FastRpcWriter.cs create mode 100644 NextShip.Api/Services/DependentService.cs create mode 100644 NextShip/Manager/NextOptionManager.cs diff --git a/NextShip.Api/Extension/RPCExtension.cs b/NextShip.Api/Extension/RPCExtension.cs new file mode 100644 index 0000000..1243973 --- /dev/null +++ b/NextShip.Api/Extension/RPCExtension.cs @@ -0,0 +1,9 @@ +namespace NextShip.Api.Extension; + +public class RPCExtension +{ + public static void UseFastRPC() + { + + } +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextOptionManager.cs b/NextShip.Api/Interfaces/INextOptionManager.cs new file mode 100644 index 0000000..78f18a6 --- /dev/null +++ b/NextShip.Api/Interfaces/INextOptionManager.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public class INextOptionManager +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IPatchManager.cs b/NextShip.Api/Interfaces/IPatchManager.cs index 4c44533..6b9db40 100644 --- a/NextShip.Api/Interfaces/IPatchManager.cs +++ b/NextShip.Api/Interfaces/IPatchManager.cs @@ -1,5 +1,10 @@ +using HarmonyLib; + namespace NextShip.Api.Interfaces; public interface IPatchManager { + public Harmony Create(string id); + + public void Register(Harmony harmony); } \ No newline at end of file diff --git a/NextShip.Api/Plugins/IPluginManager.cs b/NextShip.Api/Plugins/IPluginManager.cs new file mode 100644 index 0000000..6cc062c --- /dev/null +++ b/NextShip.Api/Plugins/IPluginManager.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Plugins; + +public class IPluginManager +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Plugins/IPluginStartup.cs b/NextShip.Api/Plugins/IPluginStartup.cs new file mode 100644 index 0000000..60944a8 --- /dev/null +++ b/NextShip.Api/Plugins/IPluginStartup.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Plugins; + +public class IPluginStartup +{ + +} \ No newline at end of file diff --git a/NextShip.Api/RPCS/FastRpcWriter.cs b/NextShip.Api/RPCS/FastRpcWriter.cs new file mode 100644 index 0000000..6dc75fe --- /dev/null +++ b/NextShip.Api/RPCS/FastRpcWriter.cs @@ -0,0 +1,49 @@ +using Hazel; + +namespace NextShip.Api.RPCs; + +public class FastRpcWriter(MessageWriter writer) +{ + private FastRpcWriter() : this(MessageWriter.Get()) { } + + public static FastRpcWriter StartNew() => + new FastRpcWriter(); + + public static FastRpcWriter StartNew(byte call, SendOption option = SendOption.None) => + new(AmongUsClient.Instance.StartRpcImmediately(CachedPlayer.LocalPlayer!.PlayerId, call, option)); + + public void Write(bool value) + { + writer.Write(value); + } + + public void Write(int value) + { + writer.Write(value); + } + + public void Write(float value) + { + writer.Write(value); + } + + public void Write(string value) + { + writer.Write(value); + } + + public void Write(byte value) + { + writer.Write(value); + } + + public void Finish() + { + AmongUsClient.Instance.FinishRpcImmediately(writer); + } + + public void Send() + { + AmongUsClient.Instance.connection.SendDisconnect(writer); + } +} \ No newline at end of file diff --git a/NextShip.Api/Services/DependentService.cs b/NextShip.Api/Services/DependentService.cs new file mode 100644 index 0000000..9842b88 --- /dev/null +++ b/NextShip.Api/Services/DependentService.cs @@ -0,0 +1,16 @@ +namespace NextShip.Api.Services; + +public class DependentService(DownloadService service) +{ + public string RootPath; + + public void SetPath(DirectoryInfo directoryInfo) + { + RootPath = directoryInfo.FullName; + } + + public void Init() + { + + } +} \ No newline at end of file diff --git a/NextShip.Api/ShipVersion.cs b/NextShip.Api/ShipVersion.cs index 189fb9f..74cc8be 100644 --- a/NextShip.Api/ShipVersion.cs +++ b/NextShip.Api/ShipVersion.cs @@ -19,7 +19,7 @@ public ShipVersion(int major, int minor, int info) public int Minor { get; protected set; } public int Info { get; protected set; } - public string? StringText { get; protected set; } + public string StringText { get; protected set; } public void set(int major, int minor, int info) { @@ -41,7 +41,7 @@ public AmongUsVersion(int major, int minor, int info) : base(major, minor, info) { } - internal AmongUsVersion() + private AmongUsVersion() { } diff --git a/NextShip/Cosmetics/AllCosmeticsCache.cs b/NextShip/Cosmetics/AllCosmeticsCache.cs index d50dfb8..8a7202d 100644 --- a/NextShip/Cosmetics/AllCosmeticsCache.cs +++ b/NextShip/Cosmetics/AllCosmeticsCache.cs @@ -10,7 +10,7 @@ public static class AllCosmeticsCache public static readonly List AllNamePlateViewDatasCache = []; public static readonly List AllSkinViewDatasCache = []; public static readonly List AllVisorViewDatasCache = []; - public static readonly List AllPetBehavioursCache = new(); + public static readonly List AllPetBehavioursCache = []; public static bool StartCache(HatManager __instance) diff --git a/NextShip/Manager/NextOptionManager.cs b/NextShip/Manager/NextOptionManager.cs new file mode 100644 index 0000000..5aa4860 --- /dev/null +++ b/NextShip/Manager/NextOptionManager.cs @@ -0,0 +1,8 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public class NextOptionManager : INextOptionManager +{ + +} \ No newline at end of file diff --git a/NextShip/Manager/NextPatchManager.cs b/NextShip/Manager/NextPatchManager.cs index 975f659..9380c3b 100644 --- a/NextShip/Manager/NextPatchManager.cs +++ b/NextShip/Manager/NextPatchManager.cs @@ -1,8 +1,69 @@ +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using HarmonyLib; using NextShip.Api.Interfaces; namespace NextShip.Manager; public class NextPatchManager : IPatchManager { - public static NextPatchManager _NextPatchManager = Main._Service.Get(); + public Harmony RootHarmony { get; private set; } + + private List _HarmonyS = []; + + private HashSet _Patches = []; + + public Harmony Create(string id) + { + if (_HarmonyS.Exists(n => n.Id == id)) + return _HarmonyS.First(n => n.Id == id); + + var Harmony = new Harmony(id); + _HarmonyS.Add(Harmony); + return Harmony; + } + + public void Register(Harmony harmony) + { + if (_HarmonyS.Exists(n => n.Id == harmony.Id)) + { + var old = _HarmonyS.Where(n => n.Id == harmony.Id); + old.Do(n => + { + var methods = n.GetPatchedMethods(); + foreach (var method in methods) + { + n.Unpatch(method, HarmonyPatchType.All); + } + + _HarmonyS.Remove(n); + }); + } + + _HarmonyS.Add(harmony); + } + + public void SetRoot(Harmony harmony) => RootHarmony = harmony; + + public void Patch(MethodBase @base, HarmonyMethod method = null,pathType type = pathType.None) + { + var prefix = type == pathType.Prefix ? method : null; + var postfix = type == pathType.Postfix ? method : null; + var transpiler = type == pathType.Transpiler ? method : null; + var finalizer = type == pathType.Finalizer ? method : null; + var ilmanipulator = type == pathType.Ilmanipulator ? method : null; + var info = RootHarmony.Patch(@base,prefix,postfix, transpiler, finalizer, ilmanipulator); + _Patches.Add(info); + } +} + +public enum pathType +{ + None, + Prefix, + Postfix, + Transpiler, + Finalizer, + Ilmanipulator } \ No newline at end of file diff --git a/NextShip/RPC/FastRPC.cs b/NextShip/RPC/FastRPC.cs index b731f43..e44f115 100644 --- a/NextShip/RPC/FastRPC.cs +++ b/NextShip/RPC/FastRPC.cs @@ -9,54 +9,7 @@ namespace NextShip.RPC; public class FastRPC { - public readonly FastReader Reader; - public readonly FastWriter Writer; - - public FastRPC() - { - Writer = new FastWriter(); - Reader = new FastReader(); - } - - public class FastWriter - { - private readonly MessageWriter _writer; - - public FastWriter() - { - _writer = MessageWriter.Get(); - } - - public FastWriter(MessageWriter writer) - { - _writer = writer; - } - - public void Write(bool value) - { - _writer.Write(value); - } - - public void Write(int value) - { - _writer.Write(value); - } - - public void Write(float value) - { - _writer.Write(value); - } - - public void Write(string value) - { - _writer.Write(value); - } - - public void Write(byte value) - { - _writer.Write(value); - } - } + public readonly FastReader Reader = new(); [HarmonyPatch] public class FastReader diff --git a/NextShip/main.cs b/NextShip/main.cs index c0ab86e..a64c3b9 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -99,15 +99,16 @@ private static void CreateService() builder._collection.AddSingleton(); builder._collection.AddSingleton(); builder._collection.AddSingleton(); - builder._collection.AddSingleton(); builder.AddTransient(); builder.Add(); builder.Add(); builder.Add(); builder.Add(); + builder.Add(); ServiceAdd(builder, RootAssembly); _Service = NextService.Build(builder); + _Service.Get().Init(); ServiceAddAttribute.Registration(_Service._Provider, RootAssembly); } From 9fd8e3e6e3db74f9a83847ed8df6de685859d89b Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Fri, 5 Jan 2024 00:09:41 +0800 Subject: [PATCH 19/29] e --- NextShip.Api/Enums/DataFlags.cs | 14 ++++ NextShip.Api/Enums/MessageFlags.cs | 28 +++++++ NextShip.Api/Enums/SystemRPCFlag.cs | 6 ++ NextShip.Api/RPCS/FastRpcWriter.cs | 111 ++++++++++++++++++++++++++-- NextShip/Patches/PlayerPatch.cs | 11 ++- 5 files changed, 162 insertions(+), 8 deletions(-) create mode 100644 NextShip.Api/Enums/DataFlags.cs create mode 100644 NextShip.Api/Enums/MessageFlags.cs create mode 100644 NextShip.Api/Enums/SystemRPCFlag.cs diff --git a/NextShip.Api/Enums/DataFlags.cs b/NextShip.Api/Enums/DataFlags.cs new file mode 100644 index 0000000..b2e88e2 --- /dev/null +++ b/NextShip.Api/Enums/DataFlags.cs @@ -0,0 +1,14 @@ +namespace NextShip.Api.Enums; +// from https://github.com/Impostor/Impostor/blob/master/src/Impostor.Server/Net/Inner/GameDataTag.cs +public enum DataFlags : byte +{ + Data = 1, + Rpc = 2, + Spawn = 4, + Despawn = 5, + SceneChange = 6, + Ready = 7, + ChangeSettings = 8, + ConsoleDeclareClientPlatform = 205, + PS4RoomRequest = 206 +} \ No newline at end of file diff --git a/NextShip.Api/Enums/MessageFlags.cs b/NextShip.Api/Enums/MessageFlags.cs new file mode 100644 index 0000000..6ac6bb0 --- /dev/null +++ b/NextShip.Api/Enums/MessageFlags.cs @@ -0,0 +1,28 @@ +namespace NextShip.Api.Enums; + +// form Impostor https://github.com/Impostor/Impostor/blob/master/src/Impostor.Api/Net/Messages/MessageFlags.cs +public enum MessageFlags : byte +{ + HostGame = 0, + JoinGame, + StartGame, + RemoveGame, + RemovePlayer, + DataAll, + DataToPlayer, + JoinedGame, + EndGame, + AlterGame = 10, + KickPlayer, + WaitForHost, + Redirect, + ReselectServer, + GetGameListV2 = 16, + ReportPlayer, + QuickMatch, + QuickMatchHost, + SetGameSession, + SetActivePodType, + QueryPlatformIds, + QueryLobbyInfo +} \ No newline at end of file diff --git a/NextShip.Api/Enums/SystemRPCFlag.cs b/NextShip.Api/Enums/SystemRPCFlag.cs new file mode 100644 index 0000000..1743835 --- /dev/null +++ b/NextShip.Api/Enums/SystemRPCFlag.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Enums; + +public enum SystemRPCFlag : byte +{ + VersionCheck = 210, +} \ No newline at end of file diff --git a/NextShip.Api/RPCS/FastRpcWriter.cs b/NextShip.Api/RPCS/FastRpcWriter.cs index 6dc75fe..8759f0b 100644 --- a/NextShip.Api/RPCS/FastRpcWriter.cs +++ b/NextShip.Api/RPCS/FastRpcWriter.cs @@ -2,39 +2,136 @@ namespace NextShip.Api.RPCs; -public class FastRpcWriter(MessageWriter writer) +#nullable enable +public class FastRpcWriter(MessageWriter? writer) { private FastRpcWriter() : this(MessageWriter.Get()) { } + private FastRpcWriter(SendOption option) : this(MessageWriter.Get(option)) { } + + private List targetIds; + + private int targetObjectId; + + private SendOption Option = SendOption.None; + + private int msgCount = 0; + + private byte CallId; + public static FastRpcWriter StartNew() => new FastRpcWriter(); public static FastRpcWriter StartNew(byte call, SendOption option = SendOption.None) => new(AmongUsClient.Instance.StartRpcImmediately(CachedPlayer.LocalPlayer!.PlayerId, call, option)); + + public void StartSendAllRPCWriter() + { + Clear(); + writer = MessageWriter.Get(Option); + StartDataAllMessage(); + StartRPCMessage(); + } + + public void Set(SendOption option) => Option = option; + + public void SetTargetObjectId(int id) => targetObjectId = id; + + public void SetRpcCallId(byte id) => CallId = id; + + public void Clear() + { + if (writer == null) return; + Recycle(); + writer = null; + } public void Write(bool value) { - writer.Write(value); + writer?.Write(value); } public void Write(int value) { - writer.Write(value); + writer?.Write(value); } public void Write(float value) { - writer.Write(value); + writer?.Write(value); } public void Write(string value) { - writer.Write(value); + writer?.Write(value); } public void Write(byte value) { - writer.Write(value); + writer?.Write(value); + } + + public void WritePacked(int value) + { + writer?.WritePacked(value); + } + + public void WritePacked(uint value) + { + writer?.WritePacked(value); + } + + private void StartDataAllMessage() + { + StartMessage((byte)MessageFlags.DataAll); + Write(AmongUsClient.Instance.GameId); + } + + private void StartDataToPlayerMessage() + { + StartMessage((byte)MessageFlags.DataToPlayer); + Write(AmongUsClient.Instance.GameId); + WritePacked(targetIds[0]); + targetIds.RemoveAt(0); + } + + private void StartRPCMessage() + { + StartMessage((byte)DataFlags.Rpc); + WritePacked(targetObjectId); + Write(CallId); + } + + public void StartMessage(byte flag) + { + writer?.StartMessage(flag); + msgCount++; + } + + public void EndMessage() + { + writer?.EndMessage(); + msgCount--; + } + + public void EndAllMessage() + { + while (msgCount > 0) + { + EndMessage(); + } + } + + public void Recycle() + { + writer?.Recycle(); + } + + public void RPCSend() + { + EndAllMessage(); + AmongUsClient.Instance.SendOrDisconnect(writer); + Recycle(); } public void Finish() @@ -44,6 +141,6 @@ public void Finish() public void Send() { - AmongUsClient.Instance.connection.SendDisconnect(writer); + AmongUsClient.Instance.connection.Send(writer); } } \ No newline at end of file diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs index 0a44a00..348b361 100644 --- a/NextShip/Patches/PlayerPatch.cs +++ b/NextShip/Patches/PlayerPatch.cs @@ -1,4 +1,7 @@ using HarmonyLib; +using Hazel; +using NextShip.Api.Enums; +using NextShip.Api.RPCs; using NextShip.Manager; namespace NextShip.Patches; @@ -6,10 +9,16 @@ namespace NextShip.Patches; [Harmony] public static class PlayerPatch { - [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.Awake))] + [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.Awake)), HarmonyPostfix] public static void PlayerControlAwake_PostfixPatch(PlayerControl __instance) { if (NextPlayerManager.Instance.TryGetPlayer(__instance, out _)) return; } + + [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerJoined)), HarmonyPostfix] + public static void OnPlayerJoined() + { + FastRpcWriter.StartNew((byte)SystemRPCFlag.VersionCheck, SendOption.Reliable); + } } \ No newline at end of file From a83bb4f896a31cdc989b0206205cc6e95e503dd2 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Fri, 5 Jan 2024 23:46:41 +0800 Subject: [PATCH 20/29] Update --- .../Attributes/Il2CppRegisterAttribute.cs | 1 + NextShip.Api/Attributes/LoadAttribute.cs | 6 +- .../Attributes/OptionLoadAttribute.cs | 2 +- .../Attributes/PluginCompatibility.cs | 15 +- NextShip.Api/Attributes/ShipPluginInfo.cs | 15 +- NextShip.Api/Attributes/TranslateTag.cs | 4 +- NextShip.Api/Bases/NextClientObject.cs | 7 + NextShip.Api/Bases/OptionBase.cs | 60 ++++++ NextShip.Api/Bases/OptionValueBase.cs | 18 ++ NextShip.Api/Bases/ShipPlugin.cs | 8 +- NextShip.Api/Enums/DataFlags.cs | 4 + NextShip.Api/Enums/MessageFlags.cs | 4 +- NextShip.Api/Enums/OptionTypes.cs | 11 ++ NextShip.Api/Enums/SystemRPCFlag.cs | 2 +- .../Extension/PasswordVerification.cs | 3 +- NextShip.Api/Extension/RPCExtension.cs | 1 - NextShip.Api/Interfaces/INextAdd.cs | 33 ++++ NextShip.Api/Interfaces/INextOptionManager.cs | 1 - NextShip.Api/Interfaces/INextServiceAdd.cs | 6 - NextShip.Api/Interfaces/IOptionInfo.cs | 27 +++ NextShip.Api/NextPaths.cs | 45 +++-- NextShip.Api/NextShip.Api.csproj | 9 +- NextShip.Api/Patches/InnerNetClientPatch.cs | 8 +- NextShip.Api/Plugins/IPluginManager.cs | 1 - NextShip.Api/Plugins/IPluginStartup.cs | 1 - NextShip.Api/RPCS/FastRpcWriter.cs | 113 ++++++++--- NextShip.Api/Services/DependentService.cs | 47 ++++- NextShip.Api/Utils/TextUtils.cs | 2 +- .../LangSourceGenerator.cs | 8 +- .../NextShip.SourceGenerator.csproj | 15 ++ NextShip.sln | 6 + NextShip/Cosmetics/CosmeticsChecks.cs | 2 +- NextShip/Cosmetics/CosmeticsCreator.cs | 22 +-- NextShip/Cosmetics/CustomCosmeticsManager.cs | 7 +- NextShip/Cosmetics/Loaders/CosmeticsLoader.cs | 7 +- .../Cosmetics/Loaders/TORCosmeticsLoader.cs | 3 +- NextShip/Cosmetics/Patches/HatManagerPatch.cs | 1 - NextShip/DIY/Addons/AddonsManager.cs | 2 +- NextShip/DIY/Plugins/PluginManager.cs | 2 +- NextShip/Languages/LanguagePack.cs | 1 - NextShip/Manager/NextOptionManager.cs | 1 - NextShip/Manager/NextPatchManager.cs | 33 ++-- NextShip/Manager/RoleManager.cs | 27 ++- NextShip/NextShip.csproj | 4 +- NextShip/Options/DefaultOption.cs | 11 -- NextShip/Options/Interface/IOptionInfo.cs | 14 -- .../Options/OptionBases/BooleanOptionBase.cs | 19 -- .../Options/OptionBases/FloatOptionBase.cs | 45 ----- NextShip/Options/OptionBases/IntOptionBase.cs | 42 ---- NextShip/Options/OptionBases/OptionBase.cs | 182 ------------------ .../Options/OptionBases/RoleOptionBase.cs | 30 --- .../Options/OptionBases/StringOptionBase.cs | 48 ----- NextShip/Options/OptionInfo.cs | 41 ++++ NextShip/Options/OptionManager.cs | 73 ------- ...OptionValue.cs => FloatOptionValueBase.cs} | 9 +- ...ntOptionValue.cs => IntOptionValueBase.cs} | 9 +- NextShip/Options/OptionValue/OptionValue.cs | 34 ---- NextShip/Options/Options/BooleanOptionBase.cs | 19 ++ NextShip/Options/Options/FloatOptionBase.cs | 44 +++++ NextShip/Options/Options/IntOptionBase.cs | 43 +++++ NextShip/Options/Options/RoleOptionBase.cs | 19 ++ NextShip/Options/Options/StringOptionBase.cs | 49 +++++ NextShip/Options/Patches/StringOptionPath.cs | 54 ------ NextShip/Options/VanillaOptionManager.cs | 20 -- NextShip/Patches/PlayerPatch.cs | 6 +- NextShip/Roles/FastCreator.cs | 2 +- NextShip/Services/DataService.cs | 1 - NextShip/Services/HatService.cs | 1 - NextShip/UI/Components/NextMenuOption.cs | 3 - NextShip/UI/Components/ShipOptionBehaviour.cs | 2 +- NextShip/main.cs | 42 ++-- 71 files changed, 688 insertions(+), 769 deletions(-) create mode 100644 NextShip.Api/Bases/NextClientObject.cs create mode 100644 NextShip.Api/Bases/OptionBase.cs create mode 100644 NextShip.Api/Bases/OptionValueBase.cs create mode 100644 NextShip.Api/Enums/OptionTypes.cs create mode 100644 NextShip.Api/Interfaces/INextAdd.cs delete mode 100644 NextShip.Api/Interfaces/INextServiceAdd.cs create mode 100644 NextShip.Api/Interfaces/IOptionInfo.cs rename {NextShip.Api/SourceGenerators => NextShip.SourceGenerator}/LangSourceGenerator.cs (59%) create mode 100644 NextShip.SourceGenerator/NextShip.SourceGenerator.csproj delete mode 100644 NextShip/Options/DefaultOption.cs delete mode 100644 NextShip/Options/Interface/IOptionInfo.cs delete mode 100644 NextShip/Options/OptionBases/BooleanOptionBase.cs delete mode 100644 NextShip/Options/OptionBases/FloatOptionBase.cs delete mode 100644 NextShip/Options/OptionBases/IntOptionBase.cs delete mode 100644 NextShip/Options/OptionBases/OptionBase.cs delete mode 100644 NextShip/Options/OptionBases/RoleOptionBase.cs delete mode 100644 NextShip/Options/OptionBases/StringOptionBase.cs create mode 100644 NextShip/Options/OptionInfo.cs delete mode 100644 NextShip/Options/OptionManager.cs rename NextShip/Options/OptionValue/{FloatOptionValue.cs => FloatOptionValueBase.cs} (58%) rename NextShip/Options/OptionValue/{IntOptionValue.cs => IntOptionValueBase.cs} (60%) delete mode 100644 NextShip/Options/OptionValue/OptionValue.cs create mode 100644 NextShip/Options/Options/BooleanOptionBase.cs create mode 100644 NextShip/Options/Options/FloatOptionBase.cs create mode 100644 NextShip/Options/Options/IntOptionBase.cs create mode 100644 NextShip/Options/Options/RoleOptionBase.cs create mode 100644 NextShip/Options/Options/StringOptionBase.cs delete mode 100644 NextShip/Options/Patches/StringOptionPath.cs delete mode 100644 NextShip/Options/VanillaOptionManager.cs diff --git a/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs b/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs index 0948561..3e352b0 100644 --- a/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs +++ b/NextShip.Api/Attributes/Il2CppRegisterAttribute.cs @@ -1,3 +1,4 @@ +#nullable enable using System.Reflection; using HarmonyLib; using Il2CppInterop.Runtime.Injection; diff --git a/NextShip.Api/Attributes/LoadAttribute.cs b/NextShip.Api/Attributes/LoadAttribute.cs index 8b1c83c..f93119a 100644 --- a/NextShip.Api/Attributes/LoadAttribute.cs +++ b/NextShip.Api/Attributes/LoadAttribute.cs @@ -6,11 +6,11 @@ namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor)] public sealed class LoadAttribute(LoadMode mode = LoadMode.Load) : Attribute { - public static List Loads = new(); + public static readonly List Loads = []; public static string[] MethodNames = EnumHelper.GetAllNames(); - public IEnumerator? Enumerator; + public IEnumerator Enumerator; public LoadMode Mode = mode; public static void Registration(Type type) @@ -19,7 +19,7 @@ public static void Registration(Type type) if (type.GetCustomAttribute() == null) return; - ConstructorInfo? constructor; + ConstructorInfo constructor; if ( ( constructor = type.GetConstructor diff --git a/NextShip.Api/Attributes/OptionLoadAttribute.cs b/NextShip.Api/Attributes/OptionLoadAttribute.cs index 236db95..2c8cadd 100644 --- a/NextShip.Api/Attributes/OptionLoadAttribute.cs +++ b/NextShip.Api/Attributes/OptionLoadAttribute.cs @@ -6,7 +6,7 @@ namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Method)] public sealed class OptionLoad : Attribute { - public static List MethodInfos = new(); + public static readonly List MethodInfos = []; public static void Registration(Type type) { diff --git a/NextShip.Api/Attributes/PluginCompatibility.cs b/NextShip.Api/Attributes/PluginCompatibility.cs index 8d602a7..6ad380f 100644 --- a/NextShip.Api/Attributes/PluginCompatibility.cs +++ b/NextShip.Api/Attributes/PluginCompatibility.cs @@ -1,14 +1,11 @@ namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Class)] -public sealed class PluginCompatibility : Attribute +public sealed class PluginCompatibility( + string pluginName, + CompatibilityLevel compatibility = CompatibilityLevel.Compatible) + : Attribute { - public CompatibilityLevel Compatibility; - public string PluginName; - - public PluginCompatibility(string pluginName, CompatibilityLevel compatibility = CompatibilityLevel.Compatible) - { - PluginName = pluginName; - Compatibility = compatibility; - } + public CompatibilityLevel Compatibility = compatibility; + public string PluginName = pluginName; } \ No newline at end of file diff --git a/NextShip.Api/Attributes/ShipPluginInfo.cs b/NextShip.Api/Attributes/ShipPluginInfo.cs index 4a506fb..51888fe 100644 --- a/NextShip.Api/Attributes/ShipPluginInfo.cs +++ b/NextShip.Api/Attributes/ShipPluginInfo.cs @@ -1,16 +1,9 @@ namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Class)] -public sealed class ShipPluginInfo : Attribute +public sealed class ShipPluginInfo(string Id, ShipVersion Version, string Name) : Attribute { - public ShipPluginInfo(string Id, ShipVersion Version, string Name) - { - this.Id = Id; - this.Version = Version; - this.Name = Name; - } - - public string Id { get; } - public ShipVersion Version { get; } - public string Name { get; } + public string Id { get; } = Id; + public ShipVersion Version { get; } = Version; + public string Name { get; } = Name; } \ No newline at end of file diff --git a/NextShip.Api/Attributes/TranslateTag.cs b/NextShip.Api/Attributes/TranslateTag.cs index 3e4bf71..c56df5c 100644 --- a/NextShip.Api/Attributes/TranslateTag.cs +++ b/NextShip.Api/Attributes/TranslateTag.cs @@ -7,8 +7,8 @@ public class TranslateTag : Attribute public readonly string Tag; - public Dictionary Translate = new(); - public SupportedLangs VanillaLang; + public readonly Dictionary Translate = new(); + public readonly SupportedLangs VanillaLang; public TranslateTag(string tag = "None", SupportedLangs Lang = 0, string VanillaText = "") diff --git a/NextShip.Api/Bases/NextClientObject.cs b/NextShip.Api/Bases/NextClientObject.cs new file mode 100644 index 0000000..647c7cc --- /dev/null +++ b/NextShip.Api/Bases/NextClientObject.cs @@ -0,0 +1,7 @@ +using InnerNet; + +namespace NextShip.Api.Bases; + +public class NextClientObject : InnerNetObject +{ +} \ No newline at end of file diff --git a/NextShip.Api/Bases/OptionBase.cs b/NextShip.Api/Bases/OptionBase.cs new file mode 100644 index 0000000..247e051 --- /dev/null +++ b/NextShip.Api/Bases/OptionBase.cs @@ -0,0 +1,60 @@ +using NextShip.Api.Interfaces; +using UnityEngine; + +namespace NextShip.Api.Bases; + +public abstract class OptionBase( + bool enableTranslation, + OptionBehaviour optionBehaviour, + IOptionInfo optionInfo, + string title) +{ + public readonly bool EnableTranslation = enableTranslation; + public readonly OptionBehaviour OptionBehaviour = optionBehaviour; + public readonly IOptionInfo optionInfo = optionInfo; + public readonly string Title = title; + public int id; + public Color nameColor; + public string StringId; + + public void AddChildren(IOptionInfo info) + { + optionInfo.AddChildren(info); + } + + public void RemoveChildren(IOptionInfo info) + { + optionInfo.RemoveChildren(info); + } + + public void SetParent(IOptionInfo info) + { + optionInfo.setParent(info); + } + + public abstract void Increase(); + + public abstract void Decrease(); + + public abstract int GetInt(); + public abstract float GetFloat(); + public abstract string GetValueString(); + public abstract OptionBase GetBase(); + + // 设置OptionBehaviour隐性转换 + public static explicit operator OptionBehaviour(OptionBase @base) + { + return @base.OptionBehaviour; + } + + public static explicit operator string(OptionBase @base) + { + return @base.GetValueString(); + } + + + public string GetTitleString() + { + return Title; + } +} \ No newline at end of file diff --git a/NextShip.Api/Bases/OptionValueBase.cs b/NextShip.Api/Bases/OptionValueBase.cs new file mode 100644 index 0000000..1b02448 --- /dev/null +++ b/NextShip.Api/Bases/OptionValueBase.cs @@ -0,0 +1,18 @@ +namespace NextShip.Options.OptionValue; + +public abstract class OptionValueBase( + T defaultValue, + T min, + T step, + T max) +{ + public readonly T Max = max; + public readonly T Min = min; + public readonly T Step = step; + public T DefaultValue = defaultValue; + public T Value = defaultValue; + + public abstract T GetValue(); + public abstract void increase(); + public abstract void decrease(); +} \ No newline at end of file diff --git a/NextShip.Api/Bases/ShipPlugin.cs b/NextShip.Api/Bases/ShipPlugin.cs index d08326d..c7b6f33 100644 --- a/NextShip.Api/Bases/ShipPlugin.cs +++ b/NextShip.Api/Bases/ShipPlugin.cs @@ -1,8 +1,10 @@ +using NextShip.Api.Interfaces; + namespace NextShip.Api.Bases; public abstract class ShipPlugin { - public List PluginCompatibilities = new(); + public List PluginCompatibilities = []; public ShipPluginInfo ShipPluginInfo = null!; public ShipPlugin() @@ -15,4 +17,8 @@ public ShipPlugin(ShipPluginInfo pluginInfo) } public abstract void Load(); + + public virtual void NextAdd(List adds) + { + } } \ No newline at end of file diff --git a/NextShip.Api/Enums/DataFlags.cs b/NextShip.Api/Enums/DataFlags.cs index b2e88e2..b93786e 100644 --- a/NextShip.Api/Enums/DataFlags.cs +++ b/NextShip.Api/Enums/DataFlags.cs @@ -1,4 +1,5 @@ namespace NextShip.Api.Enums; + // from https://github.com/Impostor/Impostor/blob/master/src/Impostor.Server/Net/Inner/GameDataTag.cs public enum DataFlags : byte { @@ -9,6 +10,9 @@ public enum DataFlags : byte SceneChange = 6, Ready = 7, ChangeSettings = 8, + + FastRPC = 50, + ConsoleDeclareClientPlatform = 205, PS4RoomRequest = 206 } \ No newline at end of file diff --git a/NextShip.Api/Enums/MessageFlags.cs b/NextShip.Api/Enums/MessageFlags.cs index 6ac6bb0..76d4be4 100644 --- a/NextShip.Api/Enums/MessageFlags.cs +++ b/NextShip.Api/Enums/MessageFlags.cs @@ -24,5 +24,7 @@ public enum MessageFlags : byte SetGameSession, SetActivePodType, QueryPlatformIds, - QueryLobbyInfo + QueryLobbyInfo, + + NextContact = 51 } \ No newline at end of file diff --git a/NextShip.Api/Enums/OptionTypes.cs b/NextShip.Api/Enums/OptionTypes.cs new file mode 100644 index 0000000..48f343d --- /dev/null +++ b/NextShip.Api/Enums/OptionTypes.cs @@ -0,0 +1,11 @@ +namespace NextShip.Api.Enums; + +public enum OptionTypes +{ + None, + Boolean, + Float, + String, + Int, + Role +} \ No newline at end of file diff --git a/NextShip.Api/Enums/SystemRPCFlag.cs b/NextShip.Api/Enums/SystemRPCFlag.cs index 1743835..2bfaa18 100644 --- a/NextShip.Api/Enums/SystemRPCFlag.cs +++ b/NextShip.Api/Enums/SystemRPCFlag.cs @@ -2,5 +2,5 @@ namespace NextShip.Api.Enums; public enum SystemRPCFlag : byte { - VersionCheck = 210, + VersionCheck = 210 } \ No newline at end of file diff --git a/NextShip.Api/Extension/PasswordVerification.cs b/NextShip.Api/Extension/PasswordVerification.cs index 19b5e98..a032d48 100644 --- a/NextShip.Api/Extension/PasswordVerification.cs +++ b/NextShip.Api/Extension/PasswordVerification.cs @@ -5,9 +5,8 @@ namespace NextShip.Api.Extension; public class PasswordVerification { - public static bool Enable { get; private set; } - public static int Password; + public static bool Enable { get; private set; } public static void UseVerification() { diff --git a/NextShip.Api/Extension/RPCExtension.cs b/NextShip.Api/Extension/RPCExtension.cs index 1243973..3733676 100644 --- a/NextShip.Api/Extension/RPCExtension.cs +++ b/NextShip.Api/Extension/RPCExtension.cs @@ -4,6 +4,5 @@ public class RPCExtension { public static void UseFastRPC() { - } } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextAdd.cs b/NextShip.Api/Interfaces/INextAdd.cs new file mode 100644 index 0000000..b70f0aa --- /dev/null +++ b/NextShip.Api/Interfaces/INextAdd.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using BepInEx.Configuration; +using HarmonyLib; +using NextShip.Api.Services; + +namespace NextShip.Api.Interfaces; + +public interface INextAdd +{ + public void ServiceAdd(IServiceBuilder serviceBuilder) + { + } + + public void DependentAdd(DependentService dependentService) + { + } + + public void ConfigBind(ConfigFile config) + { + } + + public static List GetAdds(Assembly assembly) + { + var list = new List(); + + assembly.GetTypes().Where(n => n.IsDefined(typeof(INextAdd))) + .Select(AccessTools.CreateInstance) + .Select(n => (INextAdd)n) + .Do(list.Add); + + return list; + } +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextOptionManager.cs b/NextShip.Api/Interfaces/INextOptionManager.cs index 78f18a6..4a5143d 100644 --- a/NextShip.Api/Interfaces/INextOptionManager.cs +++ b/NextShip.Api/Interfaces/INextOptionManager.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public class INextOptionManager { - } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextServiceAdd.cs b/NextShip.Api/Interfaces/INextServiceAdd.cs deleted file mode 100644 index 503e4b1..0000000 --- a/NextShip.Api/Interfaces/INextServiceAdd.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace NextShip.Api.Interfaces; - -public interface INextServiceAdd -{ - public void ServiceAdd(IServiceBuilder serviceBuilder); -} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IOptionInfo.cs b/NextShip.Api/Interfaces/IOptionInfo.cs new file mode 100644 index 0000000..cc66afa --- /dev/null +++ b/NextShip.Api/Interfaces/IOptionInfo.cs @@ -0,0 +1,27 @@ +namespace NextShip.Api.Interfaces; + +public interface IOptionInfo +{ + public bool enable { get; set; } + public string optionName { get; } + public int optionId { get; } + public int hierarchy { get; } + public IOptionInfo parent { get; set; } + public HashSet children { get; set; } + public OptionBase option { get; } + + public void setParent(IOptionInfo optionInfo) + { + parent = optionInfo; + } + + public void AddChildren(IOptionInfo optionInfo) + { + children.Add(optionInfo); + } + + public void RemoveChildren(IOptionInfo optionInfo) + { + children.Remove(optionInfo); + } +} \ No newline at end of file diff --git a/NextShip.Api/NextPaths.cs b/NextShip.Api/NextPaths.cs index 95413ee..b6b25b1 100644 --- a/NextShip.Api/NextPaths.cs +++ b/NextShip.Api/NextPaths.cs @@ -1,31 +1,48 @@ +using BepInEx; + namespace NextShip.Api; public static class NextPaths { + public static string RootDirectory; + static NextPaths() { GetPaths(); CreateDirectory(); } + public static string TIS_DataPath { get; private set; } + + public static string CreativityPath { get; private set; } + + public static string TIS_TempPath { get; private set; } + + public static string TIS_ConfigPath { get; private set; } + + public static string TIS_PluginsPath { get; private set; } + + public static string TIS_TORHats { get; private set; } + + public static string TIS_Lib { get; private set; } + private static void GetPaths() { - RootDirectory = BepInEx.Paths.GameRootPath; + RootDirectory = Paths.GameRootPath; TIS_DataPath = $"{RootDirectory}/TIS_Data"; CreativityPath = $"{RootDirectory}/Creativity"; TIS_TempPath = $"{TIS_DataPath}/TEMP"; TIS_ConfigPath = $"{TIS_DataPath}/Config"; TIS_PluginsPath = $"{CreativityPath}/Plugins"; TIS_TORHats = $"{CreativityPath}/TOR"; + TIS_Lib = $"{CreativityPath}/Dependents"; } - - + + private static void CreateDirectory() { - var paths = typeof(NextPaths).GetFields(). - Where(n => n.IsStatic && n.IsPublic && n.FieldType == typeof(string)). - Select(n => n.GetValue(null)). - Select(n => (string)n); + var paths = typeof(NextPaths).GetFields().Where(n => n.IsStatic && n.IsPublic && n.FieldType == typeof(string)) + .Select(n => n.GetValue(null)).Select(n => (string)n); foreach (var Path in paths) { @@ -33,18 +50,4 @@ private static void CreateDirectory() Directory.CreateDirectory(Path!); } } - - public static string RootDirectory; - - public static string TIS_DataPath { get; private set; } - - public static string CreativityPath { get; private set; } - - public static string TIS_TempPath { get; private set; } - - public static string TIS_ConfigPath { get; private set; } - - public static string TIS_PluginsPath { get; private set; } - - public static string TIS_TORHats { get; private set; } } \ No newline at end of file diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index 6400a94..624d970 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -11,19 +11,16 @@ - + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + + diff --git a/NextShip.Api/Patches/InnerNetClientPatch.cs b/NextShip.Api/Patches/InnerNetClientPatch.cs index 51c706e..a3c3c0f 100644 --- a/NextShip.Api/Patches/InnerNetClientPatch.cs +++ b/NextShip.Api/Patches/InnerNetClientPatch.cs @@ -19,14 +19,16 @@ public static Il2CppStructArray GetDataByte(Il2CppStructArray origin if (PasswordVerification.Enable) PasswordVerification.Write(ref Writer); - + var bytes = Writer.ToByteArray(true); Writer.Recycle(); return bytes; } - + [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.GetConnectionData))] [HarmonyPostfix] - public static void GetConnectionData_Postfix(ref Il2CppStructArray __result) => + public static void GetConnectionData_Postfix(ref Il2CppStructArray __result) + { __result = GetDataByte(__result); + } } \ No newline at end of file diff --git a/NextShip.Api/Plugins/IPluginManager.cs b/NextShip.Api/Plugins/IPluginManager.cs index 6cc062c..d371c0a 100644 --- a/NextShip.Api/Plugins/IPluginManager.cs +++ b/NextShip.Api/Plugins/IPluginManager.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Plugins; public class IPluginManager { - } \ No newline at end of file diff --git a/NextShip.Api/Plugins/IPluginStartup.cs b/NextShip.Api/Plugins/IPluginStartup.cs index 60944a8..ffb4158 100644 --- a/NextShip.Api/Plugins/IPluginStartup.cs +++ b/NextShip.Api/Plugins/IPluginStartup.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Plugins; public class IPluginStartup { - } \ No newline at end of file diff --git a/NextShip.Api/RPCS/FastRpcWriter.cs b/NextShip.Api/RPCS/FastRpcWriter.cs index 8759f0b..3009aac 100644 --- a/NextShip.Api/RPCS/FastRpcWriter.cs +++ b/NextShip.Api/RPCS/FastRpcWriter.cs @@ -5,25 +5,36 @@ namespace NextShip.Api.RPCs; #nullable enable public class FastRpcWriter(MessageWriter? writer) { - private FastRpcWriter() : this(MessageWriter.Get()) { } - - private FastRpcWriter(SendOption option) : this(MessageWriter.Get(option)) { } + private byte CallId; + + private int msgCount; + + private SendOption Option = SendOption.None; + + private int SendTargetId; private List targetIds; private int targetObjectId; - private SendOption Option = SendOption.None; + private FastRpcWriter() : this(MessageWriter.Get()) + { + } - private int msgCount = 0; + private FastRpcWriter(SendOption option) : this(MessageWriter.Get(option)) + { + } - private byte CallId; - - public static FastRpcWriter StartNew() => - new FastRpcWriter(); + public static FastRpcWriter StartNew() + { + return new FastRpcWriter(); + } - public static FastRpcWriter StartNew(byte call, SendOption option = SendOption.None) => - new(AmongUsClient.Instance.StartRpcImmediately(CachedPlayer.LocalPlayer!.PlayerId, call, option)); + public static FastRpcWriter StartNew(byte call, SendOption option = SendOption.None) + { + return new FastRpcWriter( + AmongUsClient.Instance.StartRpcImmediately(CachedPlayer.LocalPlayer!.PlayerId, call, option)); + } public void StartSendAllRPCWriter() { @@ -33,11 +44,69 @@ public void StartSendAllRPCWriter() StartRPCMessage(); } - public void Set(SendOption option) => Option = option; + public void StartSendToPlayerRPCWriter() + { + Clear(); + writer = MessageWriter.Get(Option); + StartDataToPlayerMessage(); + StartRPCMessage(); + } + + private void StartNextContactWriter(params PlayerControl[] targetPlayers) + { + Clear(); + + writer = MessageWriter.Get(Option = SendOption.Reliable); + + StartMessage((byte)MessageFlags.NextContact); + + Write(PlayerControl.LocalPlayer.PlayerId); - public void SetTargetObjectId(int id) => targetObjectId = id; + var players = targetPlayers.ToList(); + players.Remove(PlayerControl.LocalPlayer); - public void SetRpcCallId(byte id) => CallId = id; + WritePacked(players.Count); + + if (players.Count == PlayerControl.AllPlayerControls.Count - 1) + return; + + foreach (var player in targetPlayers) Write(player.PlayerId); + } + + public void SetSendOption(SendOption option) + { + Option = option; + } + + public void SetTargetObjectId(int id) + { + targetObjectId = id; + } + + public void SetRpcCallId(byte id) + { + CallId = id; + } + + public void SetTargetId(int id) + { + SendTargetId = id; + } + + public void Set(SendOption option = SendOption.None, byte callId = byte.MaxValue, int targetId = -1, + int? objId = null) + { + Option = option; + + if (callId != byte.MaxValue) + CallId = callId; + + if (targetId != -1) + SendTargetId = targetId; + + if (objId != null) + targetObjectId = (int)objId; + } public void Clear() { @@ -45,7 +114,7 @@ public void Clear() Recycle(); writer = null; } - + public void Write(bool value) { writer?.Write(value); @@ -75,7 +144,7 @@ public void WritePacked(int value) { writer?.WritePacked(value); } - + public void WritePacked(uint value) { writer?.WritePacked(value); @@ -91,8 +160,7 @@ private void StartDataToPlayerMessage() { StartMessage((byte)MessageFlags.DataToPlayer); Write(AmongUsClient.Instance.GameId); - WritePacked(targetIds[0]); - targetIds.RemoveAt(0); + WritePacked(SendTargetId); } private void StartRPCMessage() @@ -107,7 +175,7 @@ public void StartMessage(byte flag) writer?.StartMessage(flag); msgCount++; } - + public void EndMessage() { writer?.EndMessage(); @@ -116,10 +184,7 @@ public void EndMessage() public void EndAllMessage() { - while (msgCount > 0) - { - EndMessage(); - } + while (msgCount > 0) EndMessage(); } public void Recycle() @@ -138,7 +203,7 @@ public void Finish() { AmongUsClient.Instance.FinishRpcImmediately(writer); } - + public void Send() { AmongUsClient.Instance.connection.Send(writer); diff --git a/NextShip.Api/Services/DependentService.cs b/NextShip.Api/Services/DependentService.cs index 9842b88..feecb00 100644 --- a/NextShip.Api/Services/DependentService.cs +++ b/NextShip.Api/Services/DependentService.cs @@ -1,16 +1,53 @@ +using System.Reflection; + namespace NextShip.Api.Services; -public class DependentService(DownloadService service) +public class DependentService(HttpClient _client) { - public string RootPath; - + public readonly HashSet<(Assembly, FileInfo)> Dlls = []; + + public readonly Queue<(Uri, string)> DownloadDependents = new(); + + public readonly Queue<(Stream, string)> GenerateDependents = new(); + + private DirectoryInfo Directory; + private string RootPath; + public void SetPath(DirectoryInfo directoryInfo) { RootPath = directoryInfo.FullName; + Directory = directoryInfo; } - public void Init() + public void BuildDependent() { - + while (DownloadDependents.Count > 0) + { + var (url, name) = DownloadDependents.Dequeue(); + var stream = _client.GetStreamAsync(url).Result; + GenerateDependents.Enqueue((stream, name)); + } + + while (GenerateDependents.Count > 0) + { + var (stream, name) = GenerateDependents.Dequeue(); + var generateFile = File.Create(Directory.FullName + "/" + name); + stream.CopyToAsync(generateFile); + } + } + + public void LoadDependent() + { + var files = Directory.GetFiles(); + foreach (var file in files) + { + if (file.Extension == ".dll") + { + Dlls.Add((Assembly.LoadFile(file.FullName), file)); + continue; + } + + file.Delete(); + } } } \ No newline at end of file diff --git a/NextShip.Api/Utils/TextUtils.cs b/NextShip.Api/Utils/TextUtils.cs index 320f4fa..855bebd 100644 --- a/NextShip.Api/Utils/TextUtils.cs +++ b/NextShip.Api/Utils/TextUtils.cs @@ -92,7 +92,7 @@ public static string ToText(this IEnumerable chars) { return chars.Aggregate("", (current, c) => current + c); } - + public static string Is(this string text, FileType type) { return text += type switch diff --git a/NextShip.Api/SourceGenerators/LangSourceGenerator.cs b/NextShip.SourceGenerator/LangSourceGenerator.cs similarity index 59% rename from NextShip.Api/SourceGenerators/LangSourceGenerator.cs rename to NextShip.SourceGenerator/LangSourceGenerator.cs index 28949ea..2b85a36 100644 --- a/NextShip.Api/SourceGenerators/LangSourceGenerator.cs +++ b/NextShip.SourceGenerator/LangSourceGenerator.cs @@ -1,9 +1,11 @@ -namespace NextShip.Api.SourceGenerators; +using Microsoft.CodeAnalysis; -/*[Generator(LanguageNames.CSharp)] +namespace NextShip.SourceGenerator; + +[Generator(LanguageNames.CSharp)] public class LangSourceGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { } -}*/ \ No newline at end of file +} \ No newline at end of file diff --git a/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj b/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj new file mode 100644 index 0000000..91dfa8e --- /dev/null +++ b/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + NextShip.SourceGenerator + true + + + + + + + diff --git a/NextShip.sln b/NextShip.sln index 95dc779..f59ab8e 100644 --- a/NextShip.sln +++ b/NextShip.sln @@ -4,6 +4,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NextShip", "NextShip\NextSh EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NextShip.Api", "NextShip.Api\NextShip.Api.csproj", "{500593FE-0616-405F-B3E9-321C28A922E0}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NextShip.SourceGenerator", "NextShip.SourceGenerator\NextShip.SourceGenerator.csproj", "{68A4C610-376B-41F6-B242-DC13499BE7F8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -18,5 +20,9 @@ Global {500593FE-0616-405F-B3E9-321C28A922E0}.Debug|Any CPU.Build.0 = Debug|Any CPU {500593FE-0616-405F-B3E9-321C28A922E0}.Release|Any CPU.ActiveCfg = Release|Any CPU {500593FE-0616-405F-B3E9-321C28A922E0}.Release|Any CPU.Build.0 = Release|Any CPU + {68A4C610-376B-41F6-B242-DC13499BE7F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {68A4C610-376B-41F6-B242-DC13499BE7F8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {68A4C610-376B-41F6-B242-DC13499BE7F8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {68A4C610-376B-41F6-B242-DC13499BE7F8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/NextShip/Cosmetics/CosmeticsChecks.cs b/NextShip/Cosmetics/CosmeticsChecks.cs index 3e61662..7075f34 100644 --- a/NextShip/Cosmetics/CosmeticsChecks.cs +++ b/NextShip/Cosmetics/CosmeticsChecks.cs @@ -8,9 +8,9 @@ namespace NextShip.Cosmetics; public static class CosmeticsChecks { private const string TORFolderName = "TheOtherHats"; - public static string[] TORHatStrings; private const string ExtremeHatFolderName = "ExtremeHat"; + public static string[] TORHatStrings; public static IEnumerator CheckCosmetics() { diff --git a/NextShip/Cosmetics/CosmeticsCreator.cs b/NextShip/Cosmetics/CosmeticsCreator.cs index da59dfe..7e6e704 100644 --- a/NextShip/Cosmetics/CosmeticsCreator.cs +++ b/NextShip/Cosmetics/CosmeticsCreator.cs @@ -1,8 +1,6 @@ using System.Collections.Generic; using System.Linq; using NextShip.Api.Enums; -using NextShip.Cosmetics.Loaders; -using PowerTools; using UnityEngine; using UnityEngine.AddressableAssets; @@ -47,7 +45,7 @@ private Sprite Get(string name) hatData.ViewDataRef = assetRef; hatData.CreateAddressableAsset(); - + AllCosmeticsCache.AllHatViewDatasCache.Add(hatView); return (hatView, hatData); @@ -68,7 +66,7 @@ private Sprite Get(string name) namePlateData.ViewDataRef = assetRef; namePlateData.CreateAddressableAsset(); - + AllCosmeticsCache.AllNamePlateViewDatasCache.Add(namePlateView); return (namePlateView, namePlateData); @@ -91,9 +89,9 @@ private Sprite Get(string name) skinData.ViewDataRef = assetRef; skinData.CreateAddressableAsset(); - + AllCosmeticsCache.AllSkinViewDatasCache.Add(skinView); - + return (skinView, skinData); } @@ -116,12 +114,12 @@ private Sprite Get(string name) visorData.ViewDataRef = assetRef; visorData.CreateAddressableAsset(); - + AllCosmeticsCache.AllVisorViewDatasCache.Add(visorView); - + return (visorView, visorData); } - + public (PetBehaviour, PetData) CreatePet(CosmeticsInfo info) { var petData = ScriptableObject.CreateInstance(); @@ -132,7 +130,7 @@ private Sprite Get(string name) visorView.ClimbFrame = Get(info.ClimbResource); visorView.IdleFrame = Get(info.FlipResource); visorView.LeftIdleFrame = Get(info.BackFlipResource);*/ - + petData.name = info.Name; petData.displayOrder = 99; petData.ProductId = info.Id; @@ -142,9 +140,9 @@ private Sprite Get(string name) petData.PetPrefabRef = assetRef; petData.CreateAddressableAsset(); - + AllCosmeticsCache.AllPetBehavioursCache.Add(Behaviour); - + return (Behaviour, petData); } } \ No newline at end of file diff --git a/NextShip/Cosmetics/CustomCosmeticsManager.cs b/NextShip/Cosmetics/CustomCosmeticsManager.cs index c29bc8f..a6e8298 100644 --- a/NextShip/Cosmetics/CustomCosmeticsManager.cs +++ b/NextShip/Cosmetics/CustomCosmeticsManager.cs @@ -8,7 +8,6 @@ using NextShip.Api.Config; using NextShip.Api.Enums; using NextShip.Cosmetics.Loaders; -using NextShip.Manager; using UnityEngine; namespace NextShip.Cosmetics; @@ -16,7 +15,7 @@ namespace NextShip.Cosmetics; public static partial class CustomCosmeticsManager { public const string RepoFile = "CosmeticRepo"; - + public static readonly Dictionary AllCustomCosmeticNameAndInfo = new(); public static readonly Dictionary AllCosmeticRepoRepo = new(); @@ -36,7 +35,7 @@ public static partial class CustomCosmeticsManager Path.Combine(NextPaths.CreativityPath, RepoFile.Is(FileType.Json)); private static readonly CosmeticsConfig[] ModConfig = - Array.Empty(); + Array.Empty(); public static Sprite GetSprite(string name) { @@ -55,7 +54,7 @@ public static void LoadHat() foreach (var config in from config in configs let regex = MyRegex() - where regex.IsMatch(config.RepoURL) + where regex.IsMatch(config.RepoURL) select config) { Load(config.CosmeticRepoType); diff --git a/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs b/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs index 0f9051e..bed539f 100644 --- a/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs +++ b/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs @@ -8,17 +8,16 @@ namespace NextShip.Cosmetics.Loaders; public abstract class CosmeticsLoader { + public const string HatJsonName = "CustomHats.json"; public readonly List AllCosmeticsInfo; public readonly List AllHat; public readonly List AllNamePlate; public readonly List AllSprite; + public readonly Dictionary> Hats = new(); public List AllVisor; - public const string HatJsonName = "CustomHats.json"; - public readonly Dictionary> Hats = new(); - protected CosmeticsLoader() { CustomCosmeticsManager.AllLoaders.Add(this); @@ -60,4 +59,4 @@ public virtual Task LoadFormOnRepo(CosmeticsConfig cosmeticsConfig) { return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs b/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs index 1882b7c..1dcd94f 100644 --- a/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs +++ b/NextShip/Cosmetics/Loaders/TORCosmeticsLoader.cs @@ -10,15 +10,14 @@ using Newtonsoft.Json.Linq; using NextShip.Api.Config; using NextShip.Api.Enums; -using NextShip.Manager; using UnityEngine; namespace NextShip.Cosmetics.Loaders; public class TORCosmeticsLoader : CosmeticsLoader { - private readonly CosmeticType CosmeticType = CosmeticType.Hat; private const string HatDirectoryName = "hats"; + private readonly CosmeticType CosmeticType = CosmeticType.Hat; public override CosmeticType GetCosmeticType() { diff --git a/NextShip/Cosmetics/Patches/HatManagerPatch.cs b/NextShip/Cosmetics/Patches/HatManagerPatch.cs index fa67c14..a5bc890 100644 --- a/NextShip/Cosmetics/Patches/HatManagerPatch.cs +++ b/NextShip/Cosmetics/Patches/HatManagerPatch.cs @@ -15,5 +15,4 @@ public static void InitHatCache(HatManager __instance) TaskUtils.StartTask(() => initialized = AllCosmeticsCache.StartCache(__instance)); } - } \ No newline at end of file diff --git a/NextShip/DIY/Addons/AddonsManager.cs b/NextShip/DIY/Addons/AddonsManager.cs index ff00e72..d49f44b 100644 --- a/NextShip/DIY/Addons/AddonsManager.cs +++ b/NextShip/DIY/Addons/AddonsManager.cs @@ -1,6 +1,6 @@ using NextShip.Api.Bases; -namespace NextShip.Addons; +namespace NextShip.DIY.Addons; public class AddonsManager : Manager { diff --git a/NextShip/DIY/Plugins/PluginManager.cs b/NextShip/DIY/Plugins/PluginManager.cs index 8522c99..b94bd32 100644 --- a/NextShip/DIY/Plugins/PluginManager.cs +++ b/NextShip/DIY/Plugins/PluginManager.cs @@ -6,7 +6,6 @@ using HarmonyLib; using NextShip.Api.Attributes; using NextShip.Api.Bases; -using NextShip.Manager; namespace NextShip.DIY.Plugins; @@ -75,6 +74,7 @@ private static void Load((Assembly, Type, ShipPlugin) pluginTuple) try { pluginTuple.Item3.Load(); + pluginTuple.Item3.NextAdd(Main.Adds); Info($"Name:{shipPluginInfo.Name} . Version:{shipPluginInfo.Version} . Id:{shipPluginInfo.Id} 运行成功 ", filename: MethodUtils.GetClassName()); } diff --git a/NextShip/Languages/LanguagePack.cs b/NextShip/Languages/LanguagePack.cs index 47b5266..d8e15af 100644 --- a/NextShip/Languages/LanguagePack.cs +++ b/NextShip/Languages/LanguagePack.cs @@ -6,7 +6,6 @@ using System.Text.Json; using System.Text.Unicode; using AmongUs.Data; -using NextShip.Manager; using csv = NextShip.Languages.LanguageCSV; namespace NextShip.Languages; diff --git a/NextShip/Manager/NextOptionManager.cs b/NextShip/Manager/NextOptionManager.cs index 5aa4860..191b107 100644 --- a/NextShip/Manager/NextOptionManager.cs +++ b/NextShip/Manager/NextOptionManager.cs @@ -4,5 +4,4 @@ namespace NextShip.Manager; public class NextOptionManager : INextOptionManager { - } \ No newline at end of file diff --git a/NextShip/Manager/NextPatchManager.cs b/NextShip/Manager/NextPatchManager.cs index 9380c3b..e388525 100644 --- a/NextShip/Manager/NextPatchManager.cs +++ b/NextShip/Manager/NextPatchManager.cs @@ -8,17 +8,16 @@ namespace NextShip.Manager; public class NextPatchManager : IPatchManager { - public Harmony RootHarmony { get; private set; } + private readonly List _HarmonyS = []; - private List _HarmonyS = []; + private readonly HashSet _Patches = []; + public Harmony RootHarmony { get; private set; } - private HashSet _Patches = []; - public Harmony Create(string id) { if (_HarmonyS.Exists(n => n.Id == id)) return _HarmonyS.First(n => n.Id == id); - + var Harmony = new Harmony(id); _HarmonyS.Add(Harmony); return Harmony; @@ -32,28 +31,28 @@ public void Register(Harmony harmony) old.Do(n => { var methods = n.GetPatchedMethods(); - foreach (var method in methods) - { - n.Unpatch(method, HarmonyPatchType.All); - } + foreach (var method in methods) n.Unpatch(method, HarmonyPatchType.All); _HarmonyS.Remove(n); }); } - + _HarmonyS.Add(harmony); } - public void SetRoot(Harmony harmony) => RootHarmony = harmony; + public void SetRoot(Harmony harmony) + { + RootHarmony = harmony; + } - public void Patch(MethodBase @base, HarmonyMethod method = null,pathType type = pathType.None) + public void Patch(MethodBase @base, HarmonyMethod method = null, pathType type = pathType.None) { var prefix = type == pathType.Prefix ? method : null; var postfix = type == pathType.Postfix ? method : null; var transpiler = type == pathType.Transpiler ? method : null; var finalizer = type == pathType.Finalizer ? method : null; var ilmanipulator = type == pathType.Ilmanipulator ? method : null; - var info = RootHarmony.Patch(@base,prefix,postfix, transpiler, finalizer, ilmanipulator); + var info = RootHarmony.Patch(@base, prefix, postfix, transpiler, finalizer, ilmanipulator); _Patches.Add(info); } } @@ -61,9 +60,9 @@ public void Patch(MethodBase @base, HarmonyMethod method = null,pathType type = public enum pathType { None, - Prefix, - Postfix, - Transpiler, - Finalizer, + Prefix, + Postfix, + Transpiler, + Finalizer, Ilmanipulator } \ No newline at end of file diff --git a/NextShip/Manager/RoleManager.cs b/NextShip/Manager/RoleManager.cs index 293e19b..c2dbc52 100644 --- a/NextShip/Manager/RoleManager.cs +++ b/NextShip/Manager/RoleManager.cs @@ -8,10 +8,9 @@ namespace NextShip.Manager; #nullable enable public sealed class NextRoleManager : IRoleManager { - public IRoleCreator? CurrentCreator { get; private set; } - public readonly List Roles = []; - + public IRoleCreator? CurrentCreator { get; private set; } + public void Register(IRole role) { Roles.Add(role); @@ -22,17 +21,6 @@ public void UnRegister(IRole role) Roles.Remove(role); } - public FastCreator FastGetCreator() - { - if (CurrentCreator is FastCreator creator) - return creator; - - var newCreator = new FastCreator(); - SetCreator(newCreator); - - return newCreator; - } - public void AssignRole(PlayerControl player, IRole role) { @@ -49,6 +37,17 @@ public void SetCreator(IRoleCreator creator) CurrentCreator = creator; } + public FastCreator FastGetCreator() + { + if (CurrentCreator is FastCreator creator) + return creator; + + var newCreator = new FastCreator(); + SetCreator(newCreator); + + return newCreator; + } + public T? GetRole() where T : class, IRole { return Roles.FirstOrDefault(n => n is T) as T; diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index 70c351d..04d75d8 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -22,9 +22,11 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + - + + diff --git a/NextShip/Options/DefaultOption.cs b/NextShip/Options/DefaultOption.cs deleted file mode 100644 index 5923e69..0000000 --- a/NextShip/Options/DefaultOption.cs +++ /dev/null @@ -1,11 +0,0 @@ -using NextShip.Api.Attributes; - -namespace NextShip.Options; - -public class DefaultOption -{ - [OptionLoad] - public static void OptionLoad() - { - } -} \ No newline at end of file diff --git a/NextShip/Options/Interface/IOptionInfo.cs b/NextShip/Options/Interface/IOptionInfo.cs deleted file mode 100644 index 2992521..0000000 --- a/NextShip/Options/Interface/IOptionInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.Generic; - -namespace NextShip.Options; - -public interface IOptionInfo -{ - public bool enable { get; set; } - public string optionName { get; } - public int optionId { get; } - public int hierarchy { get; } - public OptionInfo parent { get; set; } - public List children { get; set; } - public OptionBase option { get; } -} \ No newline at end of file diff --git a/NextShip/Options/OptionBases/BooleanOptionBase.cs b/NextShip/Options/OptionBases/BooleanOptionBase.cs deleted file mode 100644 index b7a688c..0000000 --- a/NextShip/Options/OptionBases/BooleanOptionBase.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace NextShip.Options; - -public class BooleanOptionBase : StringOptionBase -{ - private static readonly string[] BooleanValueSelection = { "false", "true" }; - public bool BooleanValue; - - public BooleanOptionBase(string Title, int id, optionTab tab, bool Translation = true) : base(Title, id, - BooleanValueSelection, tab) - { - type = optionType.Boolean; - IntOptionValue = new IntOptionValue(0, 0, 1, 1); - } - - public override BooleanOptionBase GetBase() - { - return this; - } -} \ No newline at end of file diff --git a/NextShip/Options/OptionBases/FloatOptionBase.cs b/NextShip/Options/OptionBases/FloatOptionBase.cs deleted file mode 100644 index d324939..0000000 --- a/NextShip/Options/OptionBases/FloatOptionBase.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Globalization; - -namespace NextShip.Options; - -public class FloatOptionBase : OptionBase -{ - private readonly FloatOptionValue _floatOptionValue; - - public FloatOptionBase(string Title, int id, optionTab tab, FloatOptionValue floatOptionValue, - bool Translation = true) : base(Title, id, tab, optionType.Float, Translation) - { - _floatOptionValue = floatOptionValue; - } - - - public override void Increase() - { - _floatOptionValue.increase(); - } - - public override void Decrease() - { - _floatOptionValue.decrease(); - } - - public override int GetInt() - { - return (int)_floatOptionValue.GetValue(); - } - - public override float GetFloat() - { - return _floatOptionValue.GetValue(); - } - - public override string GetValueString() - { - return _floatOptionValue.GetValue().ToString(CultureInfo.CurrentCulture); - } - - public override OptionBase GetBase() - { - return this; - } -} \ No newline at end of file diff --git a/NextShip/Options/OptionBases/IntOptionBase.cs b/NextShip/Options/OptionBases/IntOptionBase.cs deleted file mode 100644 index b75df0d..0000000 --- a/NextShip/Options/OptionBases/IntOptionBase.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace NextShip.Options; - -public class IntOptionBase : OptionBase -{ - private readonly IntOptionValue _intOptionValue; - - public IntOptionBase(string Title, int id, optionTab tab, IntOptionValue intOptionValue, bool Translation = true) : - base(Title, id, tab, optionType.Int, Translation) - { - _intOptionValue = intOptionValue; - } - - public override void Increase() - { - _intOptionValue.GetValue(); - } - - public override void Decrease() - { - _intOptionValue.GetValue(); - } - - public override int GetInt() - { - return _intOptionValue.GetValue(); - } - - public override float GetFloat() - { - return _intOptionValue.GetValue(); - } - - public override string GetValueString() - { - return _intOptionValue.GetValue().ToString(); - } - - public override OptionBase GetBase() - { - return this; - } -} \ No newline at end of file diff --git a/NextShip/Options/OptionBases/OptionBase.cs b/NextShip/Options/OptionBases/OptionBase.cs deleted file mode 100644 index 2c2830b..0000000 --- a/NextShip/Options/OptionBases/OptionBase.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace NextShip.Options; - -public abstract class OptionBase -{ - public bool EnableTranslation; - public int id; - public Color nameColor; - public OptionBehaviour OptionBehaviour; - public OptionInfo optionInfo; - public string StringId; - public optionTab tab; - public string Title; - public optionType type; - - - public OptionBase - ( - string Title, - int id, - optionTab tab, - optionType type, - bool Translation = true - ) - { - this.Title = Title; - this.id = GetId(id); - this.tab = tab; - this.type = type; - EnableTranslation = Translation; - - optionInfo = new OptionInfo(Title, string.Empty, id, this); - OptionManager.AllOption.Add(this); - } - - public OptionBase - ( - string Title, - string stringId, - optionTab tab, - optionType type, - bool Translation = true - ) - { - this.Title = Title; - this.tab = tab; - this.type = type; - StringId = stringId; - EnableTranslation = Translation; - - optionInfo = new OptionInfo(Title, StringId, id, this); - OptionManager.AllOption.Add(this); - } - - public int GetId(int Id) - { - if (Id != -1) return id; - - var optionid = 0; - while (OptionManager.AllOption.FirstOrDefault(n => n.id == optionid) != null) optionid += 1; - - return optionid; - } - - public void SetId(int Id = -1, string stringId = "") - { - id = Id; - StringId = stringId; - } - - public void AddChildren(OptionInfo info) - { - optionInfo.AddChildren(info); - } - - public void RemoveChildren(OptionInfo info) - { - optionInfo.RemoveChildren(info); - } - - public void SetParent(OptionInfo info) - { - optionInfo.setParent(info); - } - - public abstract void Increase(); - - public abstract void Decrease(); - - public abstract int GetInt(); - public abstract float GetFloat(); - public abstract string GetValueString(); - public abstract OptionBase GetBase(); - - // 设置OptionBehaviour隐性转换 - public static explicit operator OptionBehaviour(OptionBase @base) - { - return @base.OptionBehaviour; - } - - public static explicit operator string(OptionBase @base) - { - return @base.GetValueString(); - } - - - public string GetTitleString() - { - return EnableTranslation ? GetString(Title) : Title; - } -} - -public class OptionInfo : IOptionInfo -{ - public OptionInfo - ( - string Name, - string stringId, - int Id, - OptionBase optionBase, - int Hierarchy = 0, - OptionInfo Parent = null, - List Children = null - ) - { - optionName = Name; - this.stringId = stringId; - optionId = Id; - option = optionBase; - hierarchy = Hierarchy; - parent = Parent; - children = Children; - OptionManager.AllOptionInfo.Add(this); - } - - public string stringId { get; } - - public bool enable { get; set; } - public string optionName { get; } - public int optionId { get; } - public int hierarchy { get; } - public OptionInfo parent { get; set; } - public List children { get; set; } - public OptionBase option { get; } - - public void setParent(OptionInfo optionInfo) - { - parent = optionInfo; - } - - public void AddChildren(OptionInfo optionInfo) - { - children.Add(optionInfo); - } - - public void RemoveChildren(OptionInfo optionInfo) - { - children.Remove(optionInfo); - } -} - -public enum optionTab -{ - GameSettings, - Impostor, - Crewmate, - Neutral, - other -} - -public enum optionType -{ - none, - Boolean, - Float, - String, - Int, - Role -} \ No newline at end of file diff --git a/NextShip/Options/OptionBases/RoleOptionBase.cs b/NextShip/Options/OptionBases/RoleOptionBase.cs deleted file mode 100644 index ba939fa..0000000 --- a/NextShip/Options/OptionBases/RoleOptionBase.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace NextShip.Options; - -public class RoleOptionBase : StringOptionBase -{ - public static string[] defaultChances = - { "0% ", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%" }; - - public RoleOptionBase(SimpleRoleInfo simpleRoleInfo, int id, optionTab RoleTab = default, string[] chances = null) : - base(simpleRoleInfo.Name, id, defaultChances, - optionTab.other) - { - type = optionType.Role; - if (chances != null) Selection = chances; - if (RoleTab != default) - tab = RoleTab; - else - tab = simpleRoleInfo.roleTeam switch - { - RoleTeam.Crewmate => optionTab.Crewmate, - RoleTeam.Impostor => optionTab.Impostor, - RoleTeam.Neutral => optionTab.Neutral, - _ => optionTab.other - }; - } - - public override RoleOptionBase GetBase() - { - return this; - } -} \ No newline at end of file diff --git a/NextShip/Options/OptionBases/StringOptionBase.cs b/NextShip/Options/OptionBases/StringOptionBase.cs deleted file mode 100644 index 2738ca8..0000000 --- a/NextShip/Options/OptionBases/StringOptionBase.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace NextShip.Options; - -public class StringOptionBase : OptionBase -{ - public IntOptionValue IntOptionValue; - public string[] Selection; - - public bool StringTranslation; - public string StringValue; - - public StringOptionBase(string name, int id, string[] selection, optionTab tab) : base(name, id, tab, - optionType.String) - { - IntOptionValue = new IntOptionValue(0, 0, 1, selection.Length); - Selection = selection; - } - - public override int GetInt() - { - return IntOptionValue.GetValue(); - } - - public override float GetFloat() - { - return IntOptionValue.GetValue(); - } - - - public override string GetValueString() - { - return Selection[IntOptionValue.GetValue()]; - } - - public override void Increase() - { - IntOptionValue.increase(); - } - - public override void Decrease() - { - IntOptionValue.decrease(); - } - - public override StringOptionBase GetBase() - { - return this; - } -} \ No newline at end of file diff --git a/NextShip/Options/OptionInfo.cs b/NextShip/Options/OptionInfo.cs new file mode 100644 index 0000000..b1af33d --- /dev/null +++ b/NextShip/Options/OptionInfo.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using NextShip.Api.Bases; +using NextShip.Api.Interfaces; + +namespace NextShip.Options; + +public class OptionInfo( + string Name, + string stringId, + int Id, + OptionBase optionBase, + int Hierarchy = 0, + IOptionInfo Parent = null, + HashSet Children = null) + : IOptionInfo +{ + public string stringId { get; } = stringId; + + public bool enable { get; set; } + public string optionName { get; } = Name; + public int optionId { get; } = Id; + public int hierarchy { get; } = Hierarchy; + public IOptionInfo parent { get; set; } = Parent; + public HashSet children { get; set; } = Children; + public OptionBase option { get; } = optionBase; + + public void setParent(OptionInfo optionInfo) + { + parent = optionInfo; + } + + public void AddChildren(OptionInfo optionInfo) + { + children.Add(optionInfo); + } + + public void RemoveChildren(OptionInfo optionInfo) + { + children.Remove(optionInfo); + } +} \ No newline at end of file diff --git a/NextShip/Options/OptionManager.cs b/NextShip/Options/OptionManager.cs deleted file mode 100644 index 8df2a5b..0000000 --- a/NextShip/Options/OptionManager.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Collections.Generic; -using HarmonyLib; -using NextShip.Api.Attributes; - -namespace NextShip.Options; - -public class OptionManager -{ - public static OptionManager _OptionManager; - - public static List AllOption = new(); - public static List AllOptionInfo = new(); - public List AllBooleanOption = new(); - public List AllFloatOption = new(); - public List AllIntOption = new(); - public List AllRoleOption = new(); - public List AllStringOption = new(); - - public OptionManager() - { - if ((AllBooleanOption.Count | AllRoleOption.Count | AllStringOption.Count | AllIntOption.Count | - AllFloatOption.Count) != 0) return; - foreach (var optionBase in AllOption) - switch (optionBase.type) - { - case optionType.none: - continue; - case optionType.Boolean: - AllBooleanOption.Add(optionBase as BooleanOptionBase); - break; - case optionType.Float: - AllFloatOption.Add(optionBase as FloatOptionBase); - break; - case optionType.String: - AllStringOption.Add(optionBase as StringOptionBase); - break; - case optionType.Int: - AllIntOption.Add(optionBase as IntOptionBase); - break; - case optionType.Role: - AllRoleOption.Add(optionBase as RoleOptionBase); - break; - default: - continue; - } - } - - public static OptionManager Get() - { - return _OptionManager ?? new OptionManager(); - } - - public static void Load() - { - OptionLoad.StartOptionLoad(); - Check(); - } - - private static void Check() - { - var e = new List(); - AllOption.Do(check); - return; - - void check(OptionBase @base) - { - if (e.Contains(@base.id)) - Warn($"选项id冲突 id: {@base.id} name: {@base.Title}"); - else - e.Add(@base.id); - } - } -} \ No newline at end of file diff --git a/NextShip/Options/OptionValue/FloatOptionValue.cs b/NextShip/Options/OptionValue/FloatOptionValueBase.cs similarity index 58% rename from NextShip/Options/OptionValue/FloatOptionValue.cs rename to NextShip/Options/OptionValue/FloatOptionValueBase.cs index 41cc21e..203fadf 100644 --- a/NextShip/Options/OptionValue/FloatOptionValue.cs +++ b/NextShip/Options/OptionValue/FloatOptionValueBase.cs @@ -1,11 +1,8 @@ -namespace NextShip.Options; +namespace NextShip.Options.OptionValue; -public class FloatOptionValue : OptionValue +public class FloatOptionValueBase(float defaultValue, float min, float step, float max) + : OptionValueBase(defaultValue, min, step, max) { - public FloatOptionValue(float defaultValue, float min, float step, float max) : base(defaultValue, min, step, max) - { - } - public override void decrease() { if (Value - Step < Min) return; diff --git a/NextShip/Options/OptionValue/IntOptionValue.cs b/NextShip/Options/OptionValue/IntOptionValueBase.cs similarity index 60% rename from NextShip/Options/OptionValue/IntOptionValue.cs rename to NextShip/Options/OptionValue/IntOptionValueBase.cs index 68ac9cb..95cf19d 100644 --- a/NextShip/Options/OptionValue/IntOptionValue.cs +++ b/NextShip/Options/OptionValue/IntOptionValueBase.cs @@ -1,11 +1,8 @@ -namespace NextShip.Options; +namespace NextShip.Options.OptionValue; -public class IntOptionValue : OptionValue +public class IntOptionValueBase(int defaultValue, int min, int step, int max) + : OptionValueBase(defaultValue, min, step, max) { - public IntOptionValue(int defaultValue, int min, int step, int max) : base(defaultValue, min, step, max) - { - } - public override void decrease() { if (Value - Step < Min) return; diff --git a/NextShip/Options/OptionValue/OptionValue.cs b/NextShip/Options/OptionValue/OptionValue.cs deleted file mode 100644 index 7df25ba..0000000 --- a/NextShip/Options/OptionValue/OptionValue.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace NextShip.Options; - -public abstract class OptionValue -{ - public T DefaultValue; - public T Max; - public T Min; - public T Step; - public T Value; - - public OptionValue - ( - T defaultValue, - T min, - T step, - T max - ) - { - DefaultValue = defaultValue; - Min = min; - Step = step; - Max = max; - - Value = defaultValue; - } - - public OptionValue((T, T, T, T) tuple) : this(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4) - { - } - - public abstract T GetValue(); - public abstract void increase(); - public abstract void decrease(); -} \ No newline at end of file diff --git a/NextShip/Options/Options/BooleanOptionBase.cs b/NextShip/Options/Options/BooleanOptionBase.cs new file mode 100644 index 0000000..aba71e1 --- /dev/null +++ b/NextShip/Options/Options/BooleanOptionBase.cs @@ -0,0 +1,19 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.Options.Options; + +public class BooleanOptionBase( + bool enableTranslation, + OptionBehaviour optionBehaviour, + IOptionInfo optionInfo, + string title) : StringOptionBase(enableTranslation, optionBehaviour, optionInfo, title) +{ + private static readonly string[] BooleanValueSelection = { "false", "true" }; + public bool BooleanValue; + + + public override BooleanOptionBase GetBase() + { + return this; + } +} \ No newline at end of file diff --git a/NextShip/Options/Options/FloatOptionBase.cs b/NextShip/Options/Options/FloatOptionBase.cs new file mode 100644 index 0000000..cc01de3 --- /dev/null +++ b/NextShip/Options/Options/FloatOptionBase.cs @@ -0,0 +1,44 @@ +using System.Globalization; +using NextShip.Api.Bases; +using NextShip.Api.Interfaces; +using NextShip.Options.OptionValue; + +namespace NextShip.Options.Options; + +public class FloatOptionBase( + bool enableTranslation, + OptionBehaviour optionBehaviour, + IOptionInfo optionInfo, + string title, + FloatOptionValueBase floatOptionValueBase) : OptionBase(enableTranslation, optionBehaviour, optionInfo, title) +{ + public override void Increase() + { + floatOptionValueBase.increase(); + } + + public override void Decrease() + { + floatOptionValueBase.decrease(); + } + + public override int GetInt() + { + return (int)floatOptionValueBase.GetValue(); + } + + public override float GetFloat() + { + return floatOptionValueBase.GetValue(); + } + + public override string GetValueString() + { + return floatOptionValueBase.GetValue().ToString(CultureInfo.CurrentCulture); + } + + public override OptionBase GetBase() + { + return this; + } +} \ No newline at end of file diff --git a/NextShip/Options/Options/IntOptionBase.cs b/NextShip/Options/Options/IntOptionBase.cs new file mode 100644 index 0000000..5509dce --- /dev/null +++ b/NextShip/Options/Options/IntOptionBase.cs @@ -0,0 +1,43 @@ +using NextShip.Api.Bases; +using NextShip.Api.Interfaces; +using NextShip.Options.OptionValue; + +namespace NextShip.Options.Options; + +public class IntOptionBase( + bool enableTranslation, + OptionBehaviour optionBehaviour, + IOptionInfo optionInfo, + string title, + IntOptionValueBase intOptionValueBase) : OptionBase(enableTranslation, optionBehaviour, optionInfo, title) +{ + public override void Increase() + { + intOptionValueBase.GetValue(); + } + + public override void Decrease() + { + intOptionValueBase.GetValue(); + } + + public override int GetInt() + { + return intOptionValueBase.GetValue(); + } + + public override float GetFloat() + { + return intOptionValueBase.GetValue(); + } + + public override string GetValueString() + { + return intOptionValueBase.GetValue().ToString(); + } + + public override OptionBase GetBase() + { + return this; + } +} \ No newline at end of file diff --git a/NextShip/Options/Options/RoleOptionBase.cs b/NextShip/Options/Options/RoleOptionBase.cs new file mode 100644 index 0000000..e469216 --- /dev/null +++ b/NextShip/Options/Options/RoleOptionBase.cs @@ -0,0 +1,19 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.Options.Options; + +public class RoleOptionBase( + bool enableTranslation, + OptionBehaviour optionBehaviour, + IOptionInfo optionInfo, + string title) : StringOptionBase(enableTranslation, optionBehaviour, optionInfo, title) +{ + public static string[] defaultChances = + { "0% ", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%" }; + + + public override RoleOptionBase GetBase() + { + return this; + } +} \ No newline at end of file diff --git a/NextShip/Options/Options/StringOptionBase.cs b/NextShip/Options/Options/StringOptionBase.cs new file mode 100644 index 0000000..2d75ac5 --- /dev/null +++ b/NextShip/Options/Options/StringOptionBase.cs @@ -0,0 +1,49 @@ +using NextShip.Api.Bases; +using NextShip.Api.Interfaces; +using NextShip.Options.OptionValue; + +namespace NextShip.Options.Options; + +public class StringOptionBase( + bool enableTranslation, + OptionBehaviour optionBehaviour, + IOptionInfo optionInfo, + string title) : OptionBase(enableTranslation, optionBehaviour, optionInfo, title) +{ + public IntOptionValueBase IntOptionValueBase; + public string[] Selection; + + public bool StringTranslation; + public string StringValue; + + public override int GetInt() + { + return IntOptionValueBase.GetValue(); + } + + public override float GetFloat() + { + return IntOptionValueBase.GetValue(); + } + + + public override string GetValueString() + { + return Selection[IntOptionValueBase.GetValue()]; + } + + public override void Increase() + { + IntOptionValueBase.increase(); + } + + public override void Decrease() + { + IntOptionValueBase.decrease(); + } + + public override StringOptionBase GetBase() + { + return this; + } +} \ No newline at end of file diff --git a/NextShip/Options/Patches/StringOptionPath.cs b/NextShip/Options/Patches/StringOptionPath.cs deleted file mode 100644 index 0c48b72..0000000 --- a/NextShip/Options/Patches/StringOptionPath.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Linq; -using HarmonyLib; - -namespace NextShip.Options.Patches; - -[HarmonyPatch(typeof(StringOption))] -public class StringOptionPath -{ - [HarmonyPatch(nameof(StringOption.OnEnable))] - [HarmonyPrefix] - public static bool StringOptionEnablePatch_Prefix(StringOption __instance) - { - if (OptionsConsolePatch.IsNextMenu) return false; - var option = OptionManager.AllOption.FirstOrDefault(option => option.OptionBehaviour == __instance); - if (option == null) return true; - - __instance.OnValueChanged = null; - OnOptionUpdate(__instance, option); - return false; - } - - - [HarmonyPatch(nameof(StringOption.Increase))] - [HarmonyPrefix] - public static bool StringOptionIncreasePatch_Prefix(StringOption __instance) - { - if (OptionsConsolePatch.IsNextMenu) return false; - var option = OptionManager.AllOption.FirstOrDefault(option => option.OptionBehaviour == __instance); - if (option == null) return true; - - option.Increase(); - OnOptionUpdate(__instance, option); - return false; - } - - [HarmonyPatch(typeof(StringOption), nameof(StringOption.Decrease))] - public static bool StringOptionDecreasePatch_Prefix(StringOption __instance) - { - if (OptionsConsolePatch.IsNextMenu) return false; - var option = OptionManager.AllOption.FirstOrDefault(option => option.OptionBehaviour == __instance); - if (option == null) return true; - - option.Decrease(); - OnOptionUpdate(__instance, option); - return false; - } - - private static void OnOptionUpdate(StringOption __instance, OptionBase option) - { - __instance.TitleText.text = option.GetTitleString(); - __instance.Value = __instance.oldValue = option.GetInt(); - __instance.ValueText.text = option.GetValueString(); - } -} \ No newline at end of file diff --git a/NextShip/Options/VanillaOptionManager.cs b/NextShip/Options/VanillaOptionManager.cs deleted file mode 100644 index 68c078b..0000000 --- a/NextShip/Options/VanillaOptionManager.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using AmongUs.GameOptions; - -namespace NextShip; - -public class VanillaOptionManager -{ - public static IGameOptions VanillaSettings => GameManager.Instance.LogicOptions.currentGameOptions; - - public static string Get(IGameOptions data) - { - return Convert.ToBase64String( - GameOptionsManager.Instance.gameOptionsFactory.ToBytes(GameManager.Instance.LogicOptions - .currentGameOptions)); - } - - public static void InitVanillaOptions() - { - } -} \ No newline at end of file diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs index 348b361..1af59eb 100644 --- a/NextShip/Patches/PlayerPatch.cs +++ b/NextShip/Patches/PlayerPatch.cs @@ -9,14 +9,16 @@ namespace NextShip.Patches; [Harmony] public static class PlayerPatch { - [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.Awake)), HarmonyPostfix] + [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.Awake))] + [HarmonyPostfix] public static void PlayerControlAwake_PostfixPatch(PlayerControl __instance) { if (NextPlayerManager.Instance.TryGetPlayer(__instance, out _)) return; } - [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerJoined)), HarmonyPostfix] + [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerJoined))] + [HarmonyPostfix] public static void OnPlayerJoined() { FastRpcWriter.StartNew((byte)SystemRPCFlag.VersionCheck, SendOption.Reliable); diff --git a/NextShip/Roles/FastCreator.cs b/NextShip/Roles/FastCreator.cs index 6da1d00..df3de77 100644 --- a/NextShip/Roles/FastCreator.cs +++ b/NextShip/Roles/FastCreator.cs @@ -9,7 +9,7 @@ namespace NextShip.Roles; public class FastCreator : IRoleCreator { public readonly List AllRole = []; - + public void Dispose() { Clear(); diff --git a/NextShip/Services/DataService.cs b/NextShip/Services/DataService.cs index 09d6051..4db2905 100644 --- a/NextShip/Services/DataService.cs +++ b/NextShip/Services/DataService.cs @@ -2,5 +2,4 @@ namespace NextShip.Services; public class DataService { - } \ No newline at end of file diff --git a/NextShip/Services/HatService.cs b/NextShip/Services/HatService.cs index a8b0bcc..2fe86c0 100644 --- a/NextShip/Services/HatService.cs +++ b/NextShip/Services/HatService.cs @@ -2,5 +2,4 @@ namespace NextShip.Services; public class HatService { - } \ No newline at end of file diff --git a/NextShip/UI/Components/NextMenuOption.cs b/NextShip/UI/Components/NextMenuOption.cs index a2cffe8..d114b40 100644 --- a/NextShip/UI/Components/NextMenuOption.cs +++ b/NextShip/UI/Components/NextMenuOption.cs @@ -1,5 +1,4 @@ using NextShip.Api.Attributes; -using NextShip.Options; using UnityEngine; namespace NextShip.UI.Components; @@ -9,12 +8,10 @@ public class NextMenuOption : MonoBehaviour { public Transform List; public bool Open; - public OptionManager __OptionManager; public NextOptionMenu __OptionMenu; public void Awake() { - __OptionManager = OptionManager.Get(); } public void Start() diff --git a/NextShip/UI/Components/ShipOptionBehaviour.cs b/NextShip/UI/Components/ShipOptionBehaviour.cs index 8152a93..8f7292c 100644 --- a/NextShip/UI/Components/ShipOptionBehaviour.cs +++ b/NextShip/UI/Components/ShipOptionBehaviour.cs @@ -1,6 +1,6 @@ using System; using NextShip.Api.Attributes; -using NextShip.Options; +using NextShip.Api.Bases; using TMPro; using UnityEngine; diff --git a/NextShip/main.cs b/NextShip/main.cs index a64c3b9..4fa7e68 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -1,5 +1,6 @@ +using System.Collections.Generic; using System.Globalization; -using System.Linq; +using System.IO; using System.Net.Http; using System.Reflection; using BepInEx; @@ -37,11 +38,15 @@ public sealed class NextShip : BasePlugin // 模组版本 public const string VersionString = "1.0.0"; + public const string BepInExVersion = "682"; + // Among Us游玩版本 - public static readonly AmongUsVersion SupportVersion = new(2023, 10, 24); + public static readonly AmongUsVersion SupportVersion = new(2023, 11, 28); internal static readonly ServerManager serverManager = FastDestroyableSingleton.Instance; + public static List Adds; + private ManualLogSource TISLog; public static NextService _Service { get; private set; } @@ -60,11 +65,13 @@ public override void Load() TISLog = BepInExLogger.CreateLogSource(ModName.RemoveBlank()); Harmony.PatchAll(); - PluginManager.Get().Load(); - - Init(); Get(TISLog); + Init(); + + PluginManager.Get().Load(); + CreateService(); + LoadDependent(); SteamExtension.UseSteamIdFile(); ReactorExtension.UseReactorHandshake(); @@ -73,7 +80,7 @@ public override void Load() RegisterManager.Registration(); AddComponent().DontDestroyOnLoad(); - + ServerPath.autoAddServer(); LanguagePack.Init(); CustomCosmeticsManager.LoadHat(); @@ -88,6 +95,10 @@ private static void Init() Info($"Support Among Us Version {SupportVersion}", "Info"); Info("Hash: ", "Info"); Info($"欢迎游玩{ModName} | Welcome to{ModName}", "Info"); + + Adds = INextAdd.GetAdds(RootAssembly); + foreach (var varType in Adds) + varType.ConfigBind(Instance.Config); } @@ -99,23 +110,30 @@ private static void CreateService() builder._collection.AddSingleton(); builder._collection.AddSingleton(); builder._collection.AddSingleton(); + builder._collection.AddSingleton(); builder.AddTransient(); builder.Add(); builder.Add(); builder.Add(); builder.Add(); builder.Add(); - ServiceAdd(builder, RootAssembly); + + foreach (var varType in Adds) + varType.ServiceAdd(builder); _Service = NextService.Build(builder); - _Service.Get().Init(); ServiceAddAttribute.Registration(_Service._Provider, RootAssembly); } - private static void ServiceAdd(IServiceBuilder builder, Assembly addAssembly) + private static void LoadDependent() { - var types = addAssembly.GetTypes().Where(n => n.IsDefined(typeof(INextServiceAdd))) - .Select(AccessTools.CreateInstance).Select(n => (INextServiceAdd)n); - foreach (var varType in types) varType.ServiceAdd(builder); + var service = _Service.Get(); + service.SetPath(new DirectoryInfo(NextPaths.TIS_Lib)); + + foreach (var varType in Adds) + varType.DependentAdd(service); + + service.BuildDependent(); + service.LoadDependent(); } } \ No newline at end of file From e0363648bf5e28172112eff14da0ad8b50947ea8 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Sun, 7 Jan 2024 13:37:59 +0800 Subject: [PATCH 21/29] E --- NextShip.Api/Enums/SystemRPCFlag.cs | 2 +- NextShip.Api/Extension/ModStampExtension.cs | 23 ++++++ NextShip.Api/NextShip.Api.csproj | 4 ++ NextShip.Api/RPCS/FastRPCExtension.cs | 9 +++ NextShip.Api/RPCS/FastRpcReader.cs | 75 ++++++++++++++++++++ NextShip.Api/RPCS/FastRpcWriter.cs | 8 +-- NextShip.Api/Services/DependentService.cs | 14 ++++ NextShip.Api/Services/EACService.cs | 6 ++ NextShip.Api/Services/MetadataService.cs | 11 ++- NextShip.Api/ShipVersion.cs | 24 +++++++ NextShip.Api/Utilities/GithubAnalyzer.cs | 6 ++ NextShip/Buttons/ButtonsManager.cs | 4 +- NextShip/Config/BepInExConfig.cs | 11 +++ NextShip/Cosmetics/Patches/HatPatch.cs | 4 +- NextShip/{GlobalUsing.cs => GlobalUsings.cs} | 0 NextShip/Languages/Language.cs | 1 - NextShip/Patches/ModManagerPatch.cs | 13 ---- NextShip/Patches/PlayerPatch.cs | 28 +++++++- NextShip/RPC/FastRPC.cs | 26 +------ NextShip/Services/HatService.cs | 5 -- NextShip/main.cs | 9 ++- 21 files changed, 224 insertions(+), 59 deletions(-) create mode 100644 NextShip.Api/Extension/ModStampExtension.cs create mode 100644 NextShip.Api/RPCS/FastRPCExtension.cs create mode 100644 NextShip.Api/RPCS/FastRpcReader.cs create mode 100644 NextShip.Api/Services/EACService.cs create mode 100644 NextShip.Api/Utilities/GithubAnalyzer.cs create mode 100644 NextShip/Config/BepInExConfig.cs rename NextShip/{GlobalUsing.cs => GlobalUsings.cs} (100%) delete mode 100644 NextShip/Patches/ModManagerPatch.cs delete mode 100644 NextShip/Services/HatService.cs diff --git a/NextShip.Api/Enums/SystemRPCFlag.cs b/NextShip.Api/Enums/SystemRPCFlag.cs index 2bfaa18..a2a0a5f 100644 --- a/NextShip.Api/Enums/SystemRPCFlag.cs +++ b/NextShip.Api/Enums/SystemRPCFlag.cs @@ -2,5 +2,5 @@ namespace NextShip.Api.Enums; public enum SystemRPCFlag : byte { - VersionCheck = 210 + VersionShare = 210 } \ No newline at end of file diff --git a/NextShip.Api/Extension/ModStampExtension.cs b/NextShip.Api/Extension/ModStampExtension.cs new file mode 100644 index 0000000..2187566 --- /dev/null +++ b/NextShip.Api/Extension/ModStampExtension.cs @@ -0,0 +1,23 @@ +using UnityEngine.SceneManagement; + +namespace NextShip.Api.Extension; + +public static class ModStampExtension +{ + private static bool Added = false; + public static void UseModStamp() + { + if (Added) + return; + + SceneManager.add_sceneLoaded((Action) ((scene, _) => + { + if (scene.name == "MainMenu") + { + ModManager.Instance.ShowModStamp(); + } + })); + + Added = true; + } +} \ No newline at end of file diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index 624d970..05a1bd7 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -6,7 +6,11 @@ embedded NextShip.Api 1.0.0 + NextShip.Api + GPL-3.0 + https://github.com/TheIdealShipAU/NextShip APIReadme.md + true true diff --git a/NextShip.Api/RPCS/FastRPCExtension.cs b/NextShip.Api/RPCS/FastRPCExtension.cs new file mode 100644 index 0000000..07f8fa5 --- /dev/null +++ b/NextShip.Api/RPCS/FastRPCExtension.cs @@ -0,0 +1,9 @@ +namespace NextShip.Api.RPCs; + +public static class FastRPCExtension +{ + public static void UseFastRPC() + { + _Harmony.PatchAll(typeof(FastRpcReaderPatch)); + } +} \ No newline at end of file diff --git a/NextShip.Api/RPCS/FastRpcReader.cs b/NextShip.Api/RPCS/FastRpcReader.cs new file mode 100644 index 0000000..a0111de --- /dev/null +++ b/NextShip.Api/RPCS/FastRpcReader.cs @@ -0,0 +1,75 @@ +using System.Reflection; +using HarmonyLib; +using Hazel; +using InnerNet; + +namespace NextShip.Api.RPCs; + +public class FastRpcReader +{ + public byte CallId; + public Action HandleRpc; +} + +[Harmony] +public static class FastRpcReaderPatch +{ + public static List AllFastRpcReader = []; + + [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.HandleGameDataInner))] + [HarmonyPrefix] + public static void InnerNet_ReaderPath([HarmonyArgument(0)] MessageReader reader) + { + if (AllFastRpcReader.Count <= 0) return; + var HandleReader = MessageReader.Get(reader); + HandleReader.Position = 0; + var tag = reader.Tag; + if (reader.Tag != (int)DataFlags.Rpc) + return; + try + { + var TargetObjectId = HandleReader.ReadPackedUInt32(); + var callId = HandleReader.ReadByte(); + AllFastRpcReader.Where(n => n.CallId == callId).Do(n => n.HandleRpc(MessageReader.Get(HandleReader))); + } + catch (Exception e) + { + Exception(e); + } + + finally + { + reader.Recycle(); + } + } + + public static void AddFormAssembly(Assembly assembly) + { + var types = assembly.GetTypes(); + foreach (var type in types) + { + var methods = type.GetMethods().Where(n => n.IsDefined(typeof(FastReadAdd)) && n.IsStatic).ToList(); + foreach (var method in methods) + { + var FastReadAdd = method.GetCustomAttribute(); + if (FastReadAdd == null) + continue; + + if (method.GetGenericArguments()[0] == typeof(MessageReader)) + { + AllFastRpcReader.Add(new FastRpcReader + { + CallId = FastReadAdd.CallId, + HandleRpc = n => method.Invoke(null, [n]) + }); + } + } + } + } +} + +[AttributeUsage(AttributeTargets.Method)] +public class FastReadAdd(byte callId) : Attribute +{ + public byte CallId = callId; +} \ No newline at end of file diff --git a/NextShip.Api/RPCS/FastRpcWriter.cs b/NextShip.Api/RPCS/FastRpcWriter.cs index 3009aac..f1ccba9 100644 --- a/NextShip.Api/RPCS/FastRpcWriter.cs +++ b/NextShip.Api/RPCS/FastRpcWriter.cs @@ -15,7 +15,7 @@ public class FastRpcWriter(MessageWriter? writer) private List targetIds; - private int targetObjectId; + private uint targetObjectId; private FastRpcWriter() : this(MessageWriter.Get()) { @@ -78,7 +78,7 @@ public void SetSendOption(SendOption option) Option = option; } - public void SetTargetObjectId(int id) + public void SetTargetObjectId(uint id) { targetObjectId = id; } @@ -94,7 +94,7 @@ public void SetTargetId(int id) } public void Set(SendOption option = SendOption.None, byte callId = byte.MaxValue, int targetId = -1, - int? objId = null) + uint? objId = null) { Option = option; @@ -105,7 +105,7 @@ public void Set(SendOption option = SendOption.None, byte callId = byte.MaxValue SendTargetId = targetId; if (objId != null) - targetObjectId = (int)objId; + targetObjectId = (uint)objId; } public void Clear() diff --git a/NextShip.Api/Services/DependentService.cs b/NextShip.Api/Services/DependentService.cs index feecb00..3a70eb7 100644 --- a/NextShip.Api/Services/DependentService.cs +++ b/NextShip.Api/Services/DependentService.cs @@ -5,22 +5,36 @@ namespace NextShip.Api.Services; public class DependentService(HttpClient _client) { public readonly HashSet<(Assembly, FileInfo)> Dlls = []; + + public readonly Queue RepoDownloadDependents = new(); public readonly Queue<(Uri, string)> DownloadDependents = new(); public readonly Queue<(Stream, string)> GenerateDependents = new(); private DirectoryInfo Directory; + private string RootPath; + private string RepoURL; + public void SetPath(DirectoryInfo directoryInfo) { RootPath = directoryInfo.FullName; Directory = directoryInfo; } + public void SetRepoURL(string uri) => RepoURL = uri; + public void BuildDependent() { + while (RepoDownloadDependents.Count > 0) + { + var name = RepoDownloadDependents.Dequeue(); + var url = RepoURL + $"/{name}"; + DownloadDependents.Enqueue((new Uri(url), name)); + } + while (DownloadDependents.Count > 0) { var (url, name) = DownloadDependents.Dequeue(); diff --git a/NextShip.Api/Services/EACService.cs b/NextShip.Api/Services/EACService.cs new file mode 100644 index 0000000..98c69a0 --- /dev/null +++ b/NextShip.Api/Services/EACService.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Services; + +public class EACService +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Services/MetadataService.cs b/NextShip.Api/Services/MetadataService.cs index 47c8416..4959223 100644 --- a/NextShip.Api/Services/MetadataService.cs +++ b/NextShip.Api/Services/MetadataService.cs @@ -1,5 +1,14 @@ +using Microsoft.Extensions.Logging; + namespace NextShip.Api.Services; -public class MetadataService +public class MetadataService(DownloadService _downloadService, ILogger _logger, GithubAnalyzer analyzer) { + private string Url; + public void SetRepo(string url) => Url = url; + + public void GetMetadataInfo() + { + + } } \ No newline at end of file diff --git a/NextShip.Api/ShipVersion.cs b/NextShip.Api/ShipVersion.cs index 74cc8be..659c6de 100644 --- a/NextShip.Api/ShipVersion.cs +++ b/NextShip.Api/ShipVersion.cs @@ -1,3 +1,5 @@ +using Hazel; +using NextShip.Api.RPCs; using UnityEngine; namespace NextShip.Api; @@ -33,6 +35,28 @@ public ShipVersion Parse(string str) var strings = str.Split('.'); return new ShipVersion(int.Parse(strings[0]), int.Parse(strings[1]), int.Parse(strings[2])); } + + public void Write(MessageWriter writer) + { + writer.Write(Major); + writer.Write(Minor); + writer.Write(Info); + } + + public void Write(FastRpcWriter writer) + { + writer.Write(Major); + writer.Write(Minor); + writer.Write(Info); + } + + public ShipVersion Read(MessageReader reader) + { + var major = reader.ReadInt32(); + var minor = reader.ReadInt32(); + var info = reader.ReadInt32(); + return new ShipVersion(major, minor, info); + } } public class AmongUsVersion : ShipVersion diff --git a/NextShip.Api/Utilities/GithubAnalyzer.cs b/NextShip.Api/Utilities/GithubAnalyzer.cs new file mode 100644 index 0000000..cff2495 --- /dev/null +++ b/NextShip.Api/Utilities/GithubAnalyzer.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Utilities; + +public class GithubAnalyzer +{ + +} \ No newline at end of file diff --git a/NextShip/Buttons/ButtonsManager.cs b/NextShip/Buttons/ButtonsManager.cs index bda16c4..02c6677 100644 --- a/NextShip/Buttons/ButtonsManager.cs +++ b/NextShip/Buttons/ButtonsManager.cs @@ -4,8 +4,8 @@ namespace NextShip.Buttons; public class ButtonsManager { - public List _AllButtons = new(); - public List _AllRoleButton = new(); + public List _AllButtons = []; + public List _AllRoleButton = []; public static ButtonsManager Instance { get; private set; } public static ButtonsManager Get() diff --git a/NextShip/Config/BepInExConfig.cs b/NextShip/Config/BepInExConfig.cs new file mode 100644 index 0000000..46f8f0b --- /dev/null +++ b/NextShip/Config/BepInExConfig.cs @@ -0,0 +1,11 @@ +using BepInEx.Configuration; +using NextShip.Api.Interfaces; + +namespace NextShip.Config; + +public class BepInExConfig : INextAdd +{ + public void ConfigBind(ConfigFile config) + { + } +} \ No newline at end of file diff --git a/NextShip/Cosmetics/Patches/HatPatch.cs b/NextShip/Cosmetics/Patches/HatPatch.cs index 712da54..1d9a96c 100644 --- a/NextShip/Cosmetics/Patches/HatPatch.cs +++ b/NextShip/Cosmetics/Patches/HatPatch.cs @@ -9,9 +9,7 @@ public static class HatPatch [HarmonyPrefix] public static bool HatParent_SetHat_PrefixPatch(HatParent __instance, int color) { - if (!CustomCosmeticsManager.AllCustomCosmeticNameAndInfo.ContainsKey(__instance.Hat.name)) return true; - - return false; + return !CustomCosmeticsManager.AllCustomCosmeticNameAndInfo.ContainsKey(__instance.Hat.name); } [HarmonyPatch(typeof(CosmeticsCache), nameof(CosmeticsCache.GetHat))] diff --git a/NextShip/GlobalUsing.cs b/NextShip/GlobalUsings.cs similarity index 100% rename from NextShip/GlobalUsing.cs rename to NextShip/GlobalUsings.cs diff --git a/NextShip/Languages/Language.cs b/NextShip/Languages/Language.cs index 2460baa..cf3aed6 100644 --- a/NextShip/Languages/Language.cs +++ b/NextShip/Languages/Language.cs @@ -1,4 +1,3 @@ -global using static NextShip.Languages.Language; using System.Collections.Generic; using System.IO; using System.Linq; diff --git a/NextShip/Patches/ModManagerPatch.cs b/NextShip/Patches/ModManagerPatch.cs deleted file mode 100644 index bd69388..0000000 --- a/NextShip/Patches/ModManagerPatch.cs +++ /dev/null @@ -1,13 +0,0 @@ -using HarmonyLib; - -namespace NextShip.Patches; - -public static class ModManagerPatch -{ - [HarmonyPatch(typeof(ModManager), nameof(ModManager.Awake))] - [HarmonyPostfix] - public static void ModManager_AwakePatch(ModManager __instance) - { - __instance.ShowModStamp(); - } -} \ No newline at end of file diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs index 1af59eb..82e035f 100644 --- a/NextShip/Patches/PlayerPatch.cs +++ b/NextShip/Patches/PlayerPatch.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using HarmonyLib; using Hazel; using NextShip.Api.Enums; @@ -17,10 +19,30 @@ public static void PlayerControlAwake_PostfixPatch(PlayerControl __instance) return; } + public static readonly List AllPlayerVersionInfos = []; + [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerJoined))] [HarmonyPostfix] - public static void OnPlayerJoined() + public static void OnPlayerJoined(AmongUsClient __instance) { - FastRpcWriter.StartNew((byte)SystemRPCFlag.VersionCheck, SendOption.Reliable); + var writer = FastRpcWriter.StartNew(); + writer.SetRpcCallId((byte)SystemRPCFlag.VersionShare); + writer.SetTargetObjectId(PlayerControl.LocalPlayer.NetId); + writer.SetSendOption(SendOption.Reliable); + writer.StartSendAllRPCWriter(); + writer.Write(PlayerControl.LocalPlayer.PlayerId); + Main.Version.Write(writer); + writer.Write(Main.BepInExVersion); } -} \ No newline at end of file + + [FastReadAdd((byte)SystemRPCFlag.VersionShare)] + public static void OnVersionShare(MessageReader reader) + { + var player = PlayerUtils.GetPlayerForId(reader.ReadByte()); + var version = new ShipVersion().Read(reader); + var BepInExVersion = reader.ReadString(); + AllPlayerVersionInfos.Add(new PlayerVersionInfo(player, version, BepInExVersion)); + } +} + +public record PlayerVersionInfo(PlayerControl Player,ShipVersion Version,string BepInExVersion); \ No newline at end of file diff --git a/NextShip/RPC/FastRPC.cs b/NextShip/RPC/FastRPC.cs index e44f115..15e009e 100644 --- a/NextShip/RPC/FastRPC.cs +++ b/NextShip/RPC/FastRPC.cs @@ -65,30 +65,6 @@ public byte ReadByte() { return _Reader.ReadByte(); } - - [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.HandleGameDataInner))] - [HarmonyPostfix] - public static void InnerNet_ReaderPath([HarmonyArgument(0)] MessageReader reader) - { - if (AllReader.Count <= 0) return; - var HandleReader = MessageReader.Get(reader); - if (reader.Tag == 2) - AllReader.Do(n => n.ParentReader = HandleReader); - try - { - var id = HandleReader.ReadByte(); - AllReader.Where(n => n.TargetId != null && n.TargetId == id && n.HandleRpc != null) - .Do(n => n.HandleRpc(id, HandleReader)); - } - catch (Exception e) - { - Exception(e); - } - - finally - { - reader.Recycle(); - } - } + } } \ No newline at end of file diff --git a/NextShip/Services/HatService.cs b/NextShip/Services/HatService.cs deleted file mode 100644 index 2fe86c0..0000000 --- a/NextShip/Services/HatService.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Services; - -public class HatService -{ -} \ No newline at end of file diff --git a/NextShip/main.cs b/NextShip/main.cs index 4fa7e68..de38ead 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -8,9 +8,11 @@ using BepInEx.Unity.IL2CPP; using HarmonyLib; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using NextShip.Api.Attributes; using NextShip.Api.Extension; using NextShip.Api.Interfaces; +using NextShip.Api.RPCs; using NextShip.Api.Services; using NextShip.Cosmetics; using NextShip.DIY.Plugins; @@ -43,6 +45,8 @@ public sealed class NextShip : BasePlugin // Among Us游玩版本 public static readonly AmongUsVersion SupportVersion = new(2023, 11, 28); + public static readonly ShipVersion Version = new ShipVersion().Parse(VersionString); + internal static readonly ServerManager serverManager = FastDestroyableSingleton.Instance; public static List Adds; @@ -75,6 +79,8 @@ public override void Load() SteamExtension.UseSteamIdFile(); ReactorExtension.UseReactorHandshake(); + FastRPCExtension.UseFastRPC(); + FastRpcReaderPatch.AddFormAssembly(RootAssembly); ConsoleManager.SetConsoleTitle("Among Us " + ModName + " Game"); RegisterManager.Registration(); @@ -112,11 +118,12 @@ private static void CreateService() builder._collection.AddSingleton(); builder._collection.AddSingleton(); builder.AddTransient(); + builder.AddTransient(); builder.Add(); builder.Add(); - builder.Add(); builder.Add(); builder.Add(); + builder.Add(); foreach (var varType in Adds) varType.ServiceAdd(builder); From 8cacbe8d3a1761edab88c6975d454de01d665949 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Thu, 11 Jan 2024 00:11:08 +0800 Subject: [PATCH 22/29] Update --- NextShip.Api/APIReadme.md | 0 NextShip.Api/Attributes/TranslateTag.cs | 2 +- NextShip.Api/Bases/HostInfo.cs | 5 - NextShip.Api/Bases/NKeyBind.cs | 4 +- NextShip.Api/Bases/NextClientObject.cs | 4 +- NextShip.Api/Bases/NextInfo.cs | 22 +++- NextShip.Api/Bases/OptionValueBase.cs | 2 +- NextShip.Api/Bases/ShipPlugin.cs | 4 +- NextShip.Api/Bases/TaskState.cs | 1 + NextShip.Api/Bases/UpdateTasker.cs | 1 - NextShip.Api/Config/AddonsData.cs | 10 +- NextShip.Api/Config/Mod.cs | 1 + NextShip.Api/Enums/RPCReadType.cs | 10 ++ NextShip.Api/Extension/ModStampExtension.cs | 2 +- NextShip.Api/Interfaces/ILoadManager.cs | 4 +- NextShip.Api/Interfaces/INextOptionManager.cs | 4 +- NextShip.Api/Interfaces/INextScreenManager.cs | 4 +- NextShip.Api/Interfaces/IPlayerManager.cs | 4 +- NextShip.Api/Interfaces/IServiceBuilder.cs | 14 +++ NextShip.Api/Logs/FastLog.cs | 15 +-- NextShip.Api/Logs/Log.cs | 13 +- NextShip.Api/Managers/AssetManager.cs | 1 + NextShip.Api/NextShip.Api.csproj | 11 +- NextShip.Api/Plugins/IPluginManager.cs | 4 +- NextShip.Api/Plugins/IPluginStartup.cs | 4 +- .../{RPCS => RPCs}/FastRPCExtension.cs | 0 NextShip.Api/{RPCS => RPCs}/FastRpcReader.cs | 4 +- NextShip.Api/{RPCS => RPCs}/FastRpcWriter.cs | 2 +- NextShip.Api/RPCs/RPCConnectProject.cs | 17 +++ NextShip.Api/RPCs/RPCProjectManager.cs | 20 +++ NextShip.Api/Readme.md | 1 + NextShip.Api/Roles/RoleBase.cs | 4 +- NextShip.Api/Services/DependentService.cs | 2 +- NextShip.Api/Services/EACService.cs | 6 - NextShip.Api/UI/NextUIManager.cs | 1 + NextShip.Api/Utilities/AssetLoader.cs | 7 +- NextShip.Api/Utilities/CachedPlayer.cs | 5 +- NextShip.Api/Utilities/EnumHelper.cs | 1 + NextShip.Api/Utilities/GithubAnalyzer.cs | 5 +- NextShip.Api/Utilities/YamlLoader.cs | 3 +- NextShip.Api/Utils/AssetUtils.cs | 9 +- NextShip.Api/Utils/GameObjectUtils.cs | 1 + NextShip.Api/Utils/JsonUtils.cs | 1 + NextShip.Api/Utils/MethodUtils.cs | 1 + NextShip.Api/Utils/ObjetUtils.cs | 7 +- NextShip.Api/Utils/PingUtils.cs | 5 +- .../RPC => NextShip.Api/Utils}/RPCUtils.cs | 114 +----------------- NextShip.Api/Utils/SpriteUtils.cs | 19 +-- NextShip.Api/Utils/StreamUtils.cs | 1 + NextShip.Api/Utils/TextUtils.cs | 2 +- .../NextShip.SourceGenerator.csproj | 2 +- NextShip.sln.DotSettings.user | 1 + NextShip/Buttons/ButtonBase.cs | 8 +- NextShip/Cosmetics/CosmeticsManager.cs | 5 - NextShip/DIY/Addons/AddonsManager.cs | 4 +- NextShip/DIY/Plugins/PluginLoadInfo.cs | 21 ++++ NextShip/DIY/Plugins/PluginLoadService.cs | 41 +++++++ NextShip/DIY/Plugins/PluginManager.cs | 58 ++++++--- NextShip/GlobalUsings.cs | 1 - NextShip/Languages/Language.cs | 13 +- NextShip/Languages/LanguagePack.cs | 3 +- NextShip/Manager/LoadManager.cs | 3 +- NextShip/Manager/NextOptionManager.cs | 4 +- NextShip/Manager/NextPlayerManager.cs | 40 +++++- .../{RoleManager.cs => NextRoleManager.cs} | 5 + NextShip/NextShip.csproj | 8 +- .../OptionValue/FloatOptionValueBase.cs | 2 + .../Options/OptionValue/IntOptionValueBase.cs | 2 + .../Options/Patches/OptionsConsolePatch.cs | 3 +- NextShip/Patches/PlayerPatch.cs | 13 +- NextShip/Patches/RoleAssignmentPatch.cs | 20 +++ NextShip/RPC/FastRPC.cs | 70 ----------- NextShip/RPC/RPCCheck.cs | 11 -- NextShip/RPC/RPCConnectProject.cs | 39 ------ NextShip/RPC/RPCPatch.cs | 23 ---- NextShip/Roles/FastCreator.cs | 12 +- NextShip/Services/DataService.cs | 4 +- NextShip/Services/ServiceBuilder.cs | 10 +- NextShip/UI/Components/DownMenu.cs | 7 +- NextShip/UI/Components/NextMenuOption.cs | 9 +- NextShip/UI/Components/ShipOptionBehaviour.cs | 4 - NextShip/UI/Module/FastScreen.cs | 2 +- NextShip/UI/Module/NextOptionMenu.cs | 2 +- NextShip/UI/Patches/GameStartManagerButton.cs | 4 +- NextShip/Updates/ModUpdater.cs | 3 +- NextShip/main.cs | 23 ++-- nuget.config | 8 +- 87 files changed, 428 insertions(+), 444 deletions(-) delete mode 100644 NextShip.Api/APIReadme.md delete mode 100644 NextShip.Api/Bases/HostInfo.cs create mode 100644 NextShip.Api/Enums/RPCReadType.cs rename NextShip.Api/{RPCS => RPCs}/FastRPCExtension.cs (100%) rename NextShip.Api/{RPCS => RPCs}/FastRpcReader.cs (94%) rename NextShip.Api/{RPCS => RPCs}/FastRpcWriter.cs (99%) create mode 100644 NextShip.Api/RPCs/RPCConnectProject.cs create mode 100644 NextShip.Api/RPCs/RPCProjectManager.cs create mode 100644 NextShip.Api/Readme.md delete mode 100644 NextShip.Api/Services/EACService.cs rename {NextShip/RPC => NextShip.Api/Utils}/RPCUtils.cs (51%) create mode 100644 NextShip/DIY/Plugins/PluginLoadInfo.cs create mode 100644 NextShip/DIY/Plugins/PluginLoadService.cs rename NextShip/Manager/{RoleManager.cs => NextRoleManager.cs} (96%) delete mode 100644 NextShip/RPC/FastRPC.cs delete mode 100644 NextShip/RPC/RPCCheck.cs delete mode 100644 NextShip/RPC/RPCConnectProject.cs delete mode 100644 NextShip/RPC/RPCPatch.cs diff --git a/NextShip.Api/APIReadme.md b/NextShip.Api/APIReadme.md deleted file mode 100644 index e69de29..0000000 diff --git a/NextShip.Api/Attributes/TranslateTag.cs b/NextShip.Api/Attributes/TranslateTag.cs index c56df5c..6071b22 100644 --- a/NextShip.Api/Attributes/TranslateTag.cs +++ b/NextShip.Api/Attributes/TranslateTag.cs @@ -14,7 +14,7 @@ public class TranslateTag : Attribute public TranslateTag(string tag = "None", SupportedLangs Lang = 0, string VanillaText = "") { Tag = tag; - VanillaLang = 0; + VanillaLang = Lang; Count = AllCount; AllCount++; diff --git a/NextShip.Api/Bases/HostInfo.cs b/NextShip.Api/Bases/HostInfo.cs deleted file mode 100644 index 24e3296..0000000 --- a/NextShip.Api/Bases/HostInfo.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace NextShip.Api.Bases; - -public record HostInfo : NextInfo -{ -} \ No newline at end of file diff --git a/NextShip.Api/Bases/NKeyBind.cs b/NextShip.Api/Bases/NKeyBind.cs index 3d3c4d6..656ef1c 100644 --- a/NextShip.Api/Bases/NKeyBind.cs +++ b/NextShip.Api/Bases/NKeyBind.cs @@ -1,5 +1,3 @@ namespace NextShip.Api.Bases; -public class NKeyBind -{ -} \ No newline at end of file +public class NKeyBind; \ No newline at end of file diff --git a/NextShip.Api/Bases/NextClientObject.cs b/NextShip.Api/Bases/NextClientObject.cs index 647c7cc..9ffb85d 100644 --- a/NextShip.Api/Bases/NextClientObject.cs +++ b/NextShip.Api/Bases/NextClientObject.cs @@ -2,6 +2,4 @@ namespace NextShip.Api.Bases; -public class NextClientObject : InnerNetObject -{ -} \ No newline at end of file +public class NextClientObject : InnerNetObject; \ No newline at end of file diff --git a/NextShip.Api/Bases/NextInfo.cs b/NextShip.Api/Bases/NextInfo.cs index c2133c9..cb85aac 100644 --- a/NextShip.Api/Bases/NextInfo.cs +++ b/NextShip.Api/Bases/NextInfo.cs @@ -1,19 +1,39 @@ +using InnerNet; +using NextShip.Api.Interfaces; + namespace NextShip.Api.Bases; public record NextInfo { public float BodySpeed; + public int clientId; + public byte PlayerId; + public string FriendCode; + public string PlayerName; + + public uint PlayerLevel; + + public int ColorId; + public float GhostSpeed; public PlayerControl PlayerControl; + public ClientData ClientData; + public GameData.PlayerInfo PlayerInfo; public string PUID; - public RoleBase Role; + public RoleBase RoleBase; + + public IRole Role; + + public bool IsHost; + + public bool IsLocal; } \ No newline at end of file diff --git a/NextShip.Api/Bases/OptionValueBase.cs b/NextShip.Api/Bases/OptionValueBase.cs index 1b02448..8b4067c 100644 --- a/NextShip.Api/Bases/OptionValueBase.cs +++ b/NextShip.Api/Bases/OptionValueBase.cs @@ -1,4 +1,4 @@ -namespace NextShip.Options.OptionValue; +namespace NextShip.Api.Bases; public abstract class OptionValueBase( T defaultValue, diff --git a/NextShip.Api/Bases/ShipPlugin.cs b/NextShip.Api/Bases/ShipPlugin.cs index c7b6f33..f03abdf 100644 --- a/NextShip.Api/Bases/ShipPlugin.cs +++ b/NextShip.Api/Bases/ShipPlugin.cs @@ -18,7 +18,5 @@ public ShipPlugin(ShipPluginInfo pluginInfo) public abstract void Load(); - public virtual void NextAdd(List adds) - { - } + public abstract List NextAdd(); } \ No newline at end of file diff --git a/NextShip.Api/Bases/TaskState.cs b/NextShip.Api/Bases/TaskState.cs index e1ff294..9877ac4 100644 --- a/NextShip.Api/Bases/TaskState.cs +++ b/NextShip.Api/Bases/TaskState.cs @@ -1,3 +1,4 @@ +#nullable enable namespace NextShip.Api.Bases; public sealed class TaskState diff --git a/NextShip.Api/Bases/UpdateTasker.cs b/NextShip.Api/Bases/UpdateTasker.cs index 76fca95..005c2b8 100644 --- a/NextShip.Api/Bases/UpdateTasker.cs +++ b/NextShip.Api/Bases/UpdateTasker.cs @@ -8,7 +8,6 @@ public class UpdateTasker public void FixedUpdate() { - ; if (Tasks == null) return; Tasks.Do(UpdateTaskTime); diff --git a/NextShip.Api/Config/AddonsData.cs b/NextShip.Api/Config/AddonsData.cs index ae657ad..fa8b8ec 100644 --- a/NextShip.Api/Config/AddonsData.cs +++ b/NextShip.Api/Config/AddonsData.cs @@ -2,9 +2,9 @@ namespace NextShip.Api.Config; public class AddonsInfo { - public string? name { get; set; } - public string? description { get; set; } - public string? version { get; set; } - public string? author { get; set; } - public string? RepoUrl { get; set; } + public string name { get; set; } + public string description { get; set; } + public string version { get; set; } + public string author { get; set; } + public string RepoUrl { get; set; } } \ No newline at end of file diff --git a/NextShip.Api/Config/Mod.cs b/NextShip.Api/Config/Mod.cs index 4b3e4c0..a508a3a 100644 --- a/NextShip.Api/Config/Mod.cs +++ b/NextShip.Api/Config/Mod.cs @@ -1,3 +1,4 @@ +#nullable enable namespace NextShip.Api.Config; /* diff --git a/NextShip.Api/Enums/RPCReadType.cs b/NextShip.Api/Enums/RPCReadType.cs new file mode 100644 index 0000000..1536205 --- /dev/null +++ b/NextShip.Api/Enums/RPCReadType.cs @@ -0,0 +1,10 @@ +namespace NextShip.Api.Enums; + +public enum RPCReadType +{ + Byte, + Int, + Bool, + Float, + String +} \ No newline at end of file diff --git a/NextShip.Api/Extension/ModStampExtension.cs b/NextShip.Api/Extension/ModStampExtension.cs index 2187566..d8c178b 100644 --- a/NextShip.Api/Extension/ModStampExtension.cs +++ b/NextShip.Api/Extension/ModStampExtension.cs @@ -4,7 +4,7 @@ namespace NextShip.Api.Extension; public static class ModStampExtension { - private static bool Added = false; + private static bool Added; public static void UseModStamp() { if (Added) diff --git a/NextShip.Api/Interfaces/ILoadManager.cs b/NextShip.Api/Interfaces/ILoadManager.cs index 9516124..8033f9e 100644 --- a/NextShip.Api/Interfaces/ILoadManager.cs +++ b/NextShip.Api/Interfaces/ILoadManager.cs @@ -1,5 +1,3 @@ namespace NextShip.Api.Interfaces; -public interface ILoadManager -{ -} \ No newline at end of file +public interface ILoadManager; \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextOptionManager.cs b/NextShip.Api/Interfaces/INextOptionManager.cs index 4a5143d..8bd7fbc 100644 --- a/NextShip.Api/Interfaces/INextOptionManager.cs +++ b/NextShip.Api/Interfaces/INextOptionManager.cs @@ -1,5 +1,3 @@ namespace NextShip.Api.Interfaces; -public class INextOptionManager -{ -} \ No newline at end of file +public class INextOptionManager; \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextScreenManager.cs b/NextShip.Api/Interfaces/INextScreenManager.cs index aba2f2a..69eedd4 100644 --- a/NextShip.Api/Interfaces/INextScreenManager.cs +++ b/NextShip.Api/Interfaces/INextScreenManager.cs @@ -1,5 +1,3 @@ namespace NextShip.Api.Interfaces; -public class INextScreenManager -{ -} \ No newline at end of file +public class INextScreenManager; \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IPlayerManager.cs b/NextShip.Api/Interfaces/IPlayerManager.cs index d913726..8c64d1c 100644 --- a/NextShip.Api/Interfaces/IPlayerManager.cs +++ b/NextShip.Api/Interfaces/IPlayerManager.cs @@ -1,5 +1,3 @@ namespace NextShip.Api.Interfaces; -public interface IPlayerManager -{ -} \ No newline at end of file +public interface IPlayerManager; \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IServiceBuilder.cs b/NextShip.Api/Interfaces/IServiceBuilder.cs index 2fdd214..9be1004 100644 --- a/NextShip.Api/Interfaces/IServiceBuilder.cs +++ b/NextShip.Api/Interfaces/IServiceBuilder.cs @@ -4,13 +4,27 @@ namespace NextShip.Api.Interfaces; public interface IServiceBuilder { + public ServiceCollection _collection { get; set; } + public IServiceBuilder CreateService(); public IServiceBuilder Add() where T : class; + public IServiceBuilder Add(Func func) where TService : class; + public IServiceBuilder Add(Type type); public INextService Build(); public IServiceBuilder Set(ServiceCollection collection); + + public IServiceBuilder AddLogging(); + + public IServiceBuilder AddScoped() where T : class; + + public IServiceBuilder AddScoped(Type type); + + public IServiceBuilder AddTransient() where T : class; + + public IServiceBuilder AddTransient(Type type); } \ No newline at end of file diff --git a/NextShip.Api/Logs/FastLog.cs b/NextShip.Api/Logs/FastLog.cs index 54853a3..066ecb5 100644 --- a/NextShip.Api/Logs/FastLog.cs +++ b/NextShip.Api/Logs/FastLog.cs @@ -1,3 +1,4 @@ +#nullable enable using BepInEx.Logging; namespace NextShip.Api.Logs; @@ -28,36 +29,36 @@ public static class FastLog public static void Info(string text, string? tag = null, string? filename = null) { - log.Instance?.SendToFile(tag, filename, text); + Log.Instance?.SendToFile(tag, filename, text); } public static void Warn(string text, string? tag = null, string? filename = null) { - log.Instance?.SendToFile(tag, filename, text, LogLevel.Warning); + Log.Instance?.SendToFile(tag, filename, text, LogLevel.Warning); } public static void Error(string text, string? tag = null, string? filename = null) { - log.Instance?.SendToFile(tag, filename, text, LogLevel.Error); + Log.Instance?.SendToFile(tag, filename, text, LogLevel.Error); } public static void Fatal(string text, string? tag = null, string? filename = null) { - log.Instance?.SendToFile(tag, filename, text, LogLevel.Fatal); + Log.Instance?.SendToFile(tag, filename, text, LogLevel.Fatal); } public static void Msg(string text, string? tag = null, string? filename = null) { - log.Instance?.SendToFile(tag, filename, text, LogLevel.Message); + Log.Instance?.SendToFile(tag, filename, text, LogLevel.Message); } public static void Exception(Exception ex, string? tag = null, string? filename = null) { - log.Instance?.SendToFile(tag, filename, ex.ToString(), LogLevel.Error); + Log.Instance?.SendToFile(tag, filename, ex.ToString(), LogLevel.Error); } public static void Debug(string text, string? tag = null, string? filename = null) { - log.Instance?.SendToFile(tag, filename, text, LogLevel.Debug); + Log.Instance?.SendToFile(tag, filename, text, LogLevel.Debug); } } \ No newline at end of file diff --git a/NextShip.Api/Logs/Log.cs b/NextShip.Api/Logs/Log.cs index 8701c72..3484886 100644 --- a/NextShip.Api/Logs/Log.cs +++ b/NextShip.Api/Logs/Log.cs @@ -1,10 +1,11 @@ +#nullable enable using System.Text; using BepInEx; using BepInEx.Logging; namespace NextShip.Api.Logs; -public sealed class log +public sealed class Log { public static bool CreateEd; @@ -12,12 +13,12 @@ public sealed class log public StreamWriter? DiskWriter; - static log() + static Log() { System.Console.OutputEncoding = Encoding.UTF8; } - private log(ManualLogSource logSource) + private Log(ManualLogSource logSource) { LogSource = logSource; ConsoleWriter = ConsoleManager.ConsoleStream; @@ -26,7 +27,7 @@ private log(ManualLogSource logSource) public ManualLogSource LogSource { get; private set; } - public static log? Instance { get; set; } + public static Log? Instance { get; set; } public void CreateDiskLog(string name, string? path = null) @@ -76,7 +77,7 @@ public Stream GetDiskLogStream(string name, string? path = null, bool outTime = return stream; } - public static log? Get(ManualLogSource logSource) + public static Log? Get(ManualLogSource logSource) { if (CreateEd) { @@ -84,7 +85,7 @@ public Stream GetDiskLogStream(string name, string? path = null, bool outTime = return Instance; } - var _log = new log(logSource); + var _log = new Log(logSource); CreateEd = true; return _log; } diff --git a/NextShip.Api/Managers/AssetManager.cs b/NextShip.Api/Managers/AssetManager.cs index c192f71..c471d89 100644 --- a/NextShip.Api/Managers/AssetManager.cs +++ b/NextShip.Api/Managers/AssetManager.cs @@ -1,3 +1,4 @@ +#nullable enable using UnityEngine; namespace NextShip.Api.Managers; diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index 05a1bd7..ec4fbbf 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -7,9 +7,13 @@ NextShip.Api 1.0.0 NextShip.Api - GPL-3.0 + @2024 MengChu + NextShip的API + MengChu + https://github.com/TheIdealShipAU/NextShip + https://github.com/TheIdealShipAU/NextShip/blob/main/LICENSE https://github.com/TheIdealShipAU/NextShip - APIReadme.md + Readme.md true true @@ -23,7 +27,8 @@ - + + diff --git a/NextShip.Api/Plugins/IPluginManager.cs b/NextShip.Api/Plugins/IPluginManager.cs index d371c0a..11bab52 100644 --- a/NextShip.Api/Plugins/IPluginManager.cs +++ b/NextShip.Api/Plugins/IPluginManager.cs @@ -1,5 +1,3 @@ namespace NextShip.Api.Plugins; -public class IPluginManager -{ -} \ No newline at end of file +public class IPluginManager; \ No newline at end of file diff --git a/NextShip.Api/Plugins/IPluginStartup.cs b/NextShip.Api/Plugins/IPluginStartup.cs index ffb4158..1c53fa2 100644 --- a/NextShip.Api/Plugins/IPluginStartup.cs +++ b/NextShip.Api/Plugins/IPluginStartup.cs @@ -1,5 +1,3 @@ namespace NextShip.Api.Plugins; -public class IPluginStartup -{ -} \ No newline at end of file +public class IPluginStartup; \ No newline at end of file diff --git a/NextShip.Api/RPCS/FastRPCExtension.cs b/NextShip.Api/RPCs/FastRPCExtension.cs similarity index 100% rename from NextShip.Api/RPCS/FastRPCExtension.cs rename to NextShip.Api/RPCs/FastRPCExtension.cs diff --git a/NextShip.Api/RPCS/FastRpcReader.cs b/NextShip.Api/RPCs/FastRpcReader.cs similarity index 94% rename from NextShip.Api/RPCS/FastRpcReader.cs rename to NextShip.Api/RPCs/FastRpcReader.cs index a0111de..d7a8112 100644 --- a/NextShip.Api/RPCS/FastRpcReader.cs +++ b/NextShip.Api/RPCs/FastRpcReader.cs @@ -24,11 +24,11 @@ public static void InnerNet_ReaderPath([HarmonyArgument(0)] MessageReader reader var HandleReader = MessageReader.Get(reader); HandleReader.Position = 0; var tag = reader.Tag; - if (reader.Tag != (int)DataFlags.Rpc) + if (tag != (int)DataFlags.Rpc) return; try { - var TargetObjectId = HandleReader.ReadPackedUInt32(); + HandleReader.ReadPackedUInt32(); var callId = HandleReader.ReadByte(); AllFastRpcReader.Where(n => n.CallId == callId).Do(n => n.HandleRpc(MessageReader.Get(HandleReader))); } diff --git a/NextShip.Api/RPCS/FastRpcWriter.cs b/NextShip.Api/RPCs/FastRpcWriter.cs similarity index 99% rename from NextShip.Api/RPCS/FastRpcWriter.cs rename to NextShip.Api/RPCs/FastRpcWriter.cs index f1ccba9..4a4bb1b 100644 --- a/NextShip.Api/RPCS/FastRpcWriter.cs +++ b/NextShip.Api/RPCs/FastRpcWriter.cs @@ -13,7 +13,7 @@ public class FastRpcWriter(MessageWriter? writer) private int SendTargetId; - private List targetIds; + private List targetIds = new (); private uint targetObjectId; diff --git a/NextShip.Api/RPCs/RPCConnectProject.cs b/NextShip.Api/RPCs/RPCConnectProject.cs new file mode 100644 index 0000000..13c9d2a --- /dev/null +++ b/NextShip.Api/RPCs/RPCConnectProject.cs @@ -0,0 +1,17 @@ +namespace NextShip.Api.RPCs; + +public abstract class RPCConnectProject +{ + public string ID; + + protected RPCConnectProject() + { + RPCProjectManager.Instance.AllProjects.Add(this); + } + + public abstract void OnStart(); + + public virtual void OnEnd() + { + } +} \ No newline at end of file diff --git a/NextShip.Api/RPCs/RPCProjectManager.cs b/NextShip.Api/RPCs/RPCProjectManager.cs new file mode 100644 index 0000000..0ce4053 --- /dev/null +++ b/NextShip.Api/RPCs/RPCProjectManager.cs @@ -0,0 +1,20 @@ +namespace NextShip.Api.RPCs; + + +public sealed class RPCProjectManager +{ + private static RPCProjectManager Current; + + public readonly List AllProjects = new(); + + public RPCProjectManager() + { + Current = this; + } + + public static RPCProjectManager Instance + { + get { return Current ??= new RPCProjectManager(); } + set => Current = value; + } +} \ No newline at end of file diff --git a/NextShip.Api/Readme.md b/NextShip.Api/Readme.md new file mode 100644 index 0000000..d61d3e9 --- /dev/null +++ b/NextShip.Api/Readme.md @@ -0,0 +1 @@ +This Is Among Us Mod Api \ No newline at end of file diff --git a/NextShip.Api/Roles/RoleBase.cs b/NextShip.Api/Roles/RoleBase.cs index c906210..f25f5de 100644 --- a/NextShip.Api/Roles/RoleBase.cs +++ b/NextShip.Api/Roles/RoleBase.cs @@ -1,8 +1,8 @@ namespace NextShip.Api.Roles; -public abstract class RoleBase(PlayerControl? player) : IDisposable +public abstract class RoleBase(PlayerControl player) : IDisposable { - public PlayerControl? Player { get; private set; } = player; + public PlayerControl Player { get; private set; } = player; public Func WinCheck { get; } = () => false; public bool CanKill { get; } = false; diff --git a/NextShip.Api/Services/DependentService.cs b/NextShip.Api/Services/DependentService.cs index 3a70eb7..3871286 100644 --- a/NextShip.Api/Services/DependentService.cs +++ b/NextShip.Api/Services/DependentService.cs @@ -45,7 +45,7 @@ public void BuildDependent() while (GenerateDependents.Count > 0) { var (stream, name) = GenerateDependents.Dequeue(); - var generateFile = File.Create(Directory.FullName + "/" + name); + var generateFile = File.Create(RootPath + "/" + name); stream.CopyToAsync(generateFile); } } diff --git a/NextShip.Api/Services/EACService.cs b/NextShip.Api/Services/EACService.cs deleted file mode 100644 index 98c69a0..0000000 --- a/NextShip.Api/Services/EACService.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace NextShip.Api.Services; - -public class EACService -{ - -} \ No newline at end of file diff --git a/NextShip.Api/UI/NextUIManager.cs b/NextShip.Api/UI/NextUIManager.cs index 9a6ccca..cdad51d 100644 --- a/NextShip.Api/UI/NextUIManager.cs +++ b/NextShip.Api/UI/NextUIManager.cs @@ -1,3 +1,4 @@ +#nullable enable namespace NextShip.Api.UI; public class NextUIManager diff --git a/NextShip.Api/Utilities/AssetLoader.cs b/NextShip.Api/Utilities/AssetLoader.cs index 7fe50ab..5e5fad0 100644 --- a/NextShip.Api/Utilities/AssetLoader.cs +++ b/NextShip.Api/Utilities/AssetLoader.cs @@ -1,4 +1,5 @@ -using System.Reflection; +#nullable enable +using System.Reflection; using Il2CppInterop.Runtime.InteropTypes; using NextShip.Api.Managers; using UnityEngine; @@ -27,14 +28,14 @@ public AssetLoader LoadFile(string fileName) return this; } - public T Load(string name) where T : Il2CppObjectBase + public T? Load(string name) where T : Il2CppObjectBase { return Asset.LoadAsset(name); } public List LoadAll() where T : Il2CppObjectBase { - return Asset.LoadAllAsset().ToList(); + return Asset!.LoadAllAsset().ToList(); } public AssetLoader LoadFromDisk() diff --git a/NextShip.Api/Utilities/CachedPlayer.cs b/NextShip.Api/Utilities/CachedPlayer.cs index a4cf135..a1f40f6 100644 --- a/NextShip.Api/Utilities/CachedPlayer.cs +++ b/NextShip.Api/Utilities/CachedPlayer.cs @@ -1,3 +1,4 @@ +#nullable enable using System.Collections; using System.Reflection; using HarmonyLib; @@ -71,7 +72,7 @@ public static void CachePlayerPatch(PlayerControl __instance) public static void RemoveCachedPlayerPatch(PlayerControl __instance) { if (__instance.notRealPlayer) return; - CachedPlayer.AllPlayers.RemoveAll(p => p.PlayerControl.Pointer == __instance.Pointer); + CachedPlayer.AllPlayers.RemoveAll(p => p!.PlayerControl.Pointer == __instance.Pointer); CachedPlayer.PlayerIntPtrS.Remove(__instance.Pointer); } @@ -125,7 +126,7 @@ public static void SetLocalPlayer() return; } - var cached = CachedPlayer.AllPlayers.FirstOrDefault(p => p.PlayerControl.Pointer == localPlayer.Pointer); + var cached = CachedPlayer.AllPlayers.FirstOrDefault(p => p!.PlayerControl.Pointer == localPlayer.Pointer); if (cached != null) CachedPlayer.LocalPlayer = cached; } } diff --git a/NextShip.Api/Utilities/EnumHelper.cs b/NextShip.Api/Utilities/EnumHelper.cs index 23afa1d..2b9fa3e 100644 --- a/NextShip.Api/Utilities/EnumHelper.cs +++ b/NextShip.Api/Utilities/EnumHelper.cs @@ -1,3 +1,4 @@ +#nullable enable namespace NextShip.Api.Utilities; // https://github.com/tukasa0001/TownOfHost/blob/main/Helpers/EnumHelper.cs# diff --git a/NextShip.Api/Utilities/GithubAnalyzer.cs b/NextShip.Api/Utilities/GithubAnalyzer.cs index cff2495..3712367 100644 --- a/NextShip.Api/Utilities/GithubAnalyzer.cs +++ b/NextShip.Api/Utilities/GithubAnalyzer.cs @@ -1,6 +1,3 @@ namespace NextShip.Api.Utilities; -public class GithubAnalyzer -{ - -} \ No newline at end of file +public class GithubAnalyzer; \ No newline at end of file diff --git a/NextShip.Api/Utilities/YamlLoader.cs b/NextShip.Api/Utilities/YamlLoader.cs index 2302481..6d260f0 100644 --- a/NextShip.Api/Utilities/YamlLoader.cs +++ b/NextShip.Api/Utilities/YamlLoader.cs @@ -1,4 +1,5 @@ -using System.Reflection; +#nullable enable +using System.Reflection; using YamlDotNet.RepresentationModel; namespace NextShip.Api.Utilities; diff --git a/NextShip.Api/Utils/AssetUtils.cs b/NextShip.Api/Utils/AssetUtils.cs index d2bae36..2f15a22 100644 --- a/NextShip.Api/Utils/AssetUtils.cs +++ b/NextShip.Api/Utils/AssetUtils.cs @@ -1,3 +1,4 @@ +#nullable enable using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.InteropTypes; using UnityEngine; @@ -46,15 +47,15 @@ public static NamePlateViewData GetNamePlateViewData(this string id) } - public static T LoadAsset(this AssetBundle? bundle, string name) where T : Il2CppObjectBase + public static T? LoadAsset(this AssetBundle? bundle, string name) where T : Il2CppObjectBase { - return bundle.LoadAsset(name, Il2CppType.Of()).Cast(); + return bundle != null ? bundle.LoadAsset(name, Il2CppType.Of()).Cast() : null; } - public static T[] LoadAllAsset(this AssetBundle? bundle) where T : Il2CppObjectBase + public static T[] LoadAllAsset(this AssetBundle bundle) where T : Il2CppObjectBase { var assets = bundle.LoadAllAssets(Il2CppType.Of()); - var assetArray = new T[assets.Length]; + var assetArray = new T[assets!.Length]; var count = 0; foreach (var asset in assets) { diff --git a/NextShip.Api/Utils/GameObjectUtils.cs b/NextShip.Api/Utils/GameObjectUtils.cs index 81a7ed1..2b6d49e 100644 --- a/NextShip.Api/Utils/GameObjectUtils.cs +++ b/NextShip.Api/Utils/GameObjectUtils.cs @@ -1,3 +1,4 @@ +#nullable enable using HarmonyLib; using UnityEngine; using UnityEngine.Events; diff --git a/NextShip.Api/Utils/JsonUtils.cs b/NextShip.Api/Utils/JsonUtils.cs index 73a74bb..b5a8386 100644 --- a/NextShip.Api/Utils/JsonUtils.cs +++ b/NextShip.Api/Utils/JsonUtils.cs @@ -1,3 +1,4 @@ +#nullable enable using Newtonsoft.Json.Linq; namespace NextShip.Api.Utils; diff --git a/NextShip.Api/Utils/MethodUtils.cs b/NextShip.Api/Utils/MethodUtils.cs index 765d622..0d82c72 100644 --- a/NextShip.Api/Utils/MethodUtils.cs +++ b/NextShip.Api/Utils/MethodUtils.cs @@ -1,3 +1,4 @@ +#nullable enable using System.Reflection; namespace NextShip.Api.Utils; diff --git a/NextShip.Api/Utils/ObjetUtils.cs b/NextShip.Api/Utils/ObjetUtils.cs index 70e74fc..7d0f109 100644 --- a/NextShip.Api/Utils/ObjetUtils.cs +++ b/NextShip.Api/Utils/ObjetUtils.cs @@ -1,4 +1,5 @@ -using HarmonyLib; +#nullable enable +using HarmonyLib; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.InteropTypes; using UnityEngine; @@ -42,7 +43,7 @@ public static class ObjetUtils return find ? GetObject.CastFast() : null; } - public static List FindAll(string name) where T : Il2CppObjectBase + public static List? FindAll(string name) where T : Il2CppObjectBase { var find = false; var list = new List(); @@ -59,7 +60,7 @@ public static List FindAll(string name) where T : Il2CppObjectBase return find ? list : null; } - public static GameObject Get(this Object obj, string name, Transform Preant = null) + public static GameObject Get(this Object obj, string name, Transform? Preant = null) { var Obj = Object.Instantiate(obj) as GameObject; Obj!.name = name; diff --git a/NextShip.Api/Utils/PingUtils.cs b/NextShip.Api/Utils/PingUtils.cs index 1e89b46..28dbf56 100644 --- a/NextShip.Api/Utils/PingUtils.cs +++ b/NextShip.Api/Utils/PingUtils.cs @@ -1,3 +1,4 @@ +#nullable enable using System.Net.NetworkInformation; using System.Text; @@ -11,9 +12,9 @@ public static PingInfo Ping(string url) var ping = new Ping(); var reply = ping.Send(url); - + var stringB = new StringBuilder(); - var status = reply.Status switch + var status = reply.Status switch { IPStatus.Success => "成功", IPStatus.TimedOut => "超时", diff --git a/NextShip/RPC/RPCUtils.cs b/NextShip.Api/Utils/RPCUtils.cs similarity index 51% rename from NextShip/RPC/RPCUtils.cs rename to NextShip.Api/Utils/RPCUtils.cs index 35b27b2..b775e06 100644 --- a/NextShip/RPC/RPCUtils.cs +++ b/NextShip.Api/Utils/RPCUtils.cs @@ -1,6 +1,6 @@ using Hazel; -namespace NextShip.RPC; +namespace NextShip.Api.Utils; public static class RPCUtils { @@ -73,23 +73,23 @@ public static void ReadValueLength(MessageReader reader) var type = reader.ReadByte(); switch (type) { - case (byte)ReadType.Byte: + case (byte)RPCReadType.Byte: ReadRPCValue.byteL = reader.ReadInt32(); break; - case (byte)ReadType.Int: + case (byte)RPCReadType.Int: ReadRPCValue.intL = reader.ReadInt32(); break; - case (byte)ReadType.Bool: + case (byte)RPCReadType.Bool: ReadRPCValue.boolL = reader.ReadInt32(); break; - case (byte)ReadType.Float: + case (byte)RPCReadType.Float: ReadRPCValue.floatL = reader.ReadInt32(); break; - case (byte)ReadType.String: + case (byte)RPCReadType.String: ReadRPCValue.stringL = reader.ReadInt32(); break; } @@ -97,99 +97,6 @@ public static void ReadValueLength(MessageReader reader) ReadValue(reader); } - - /*public static void SendValueLength(int byteL = 0, int intL = 0, int boolL = 0, int FloatL = 0, int StringL = 0) - { - var Length = 0; - if (byteL != 0) Length++; - if (intL != 0) Length++; - if (boolL != 0) Length++; - if (FloatL != 0) Length++; - if (StringL != 0) Length++; - - if (byteL != 0) - { - rpcStart.Write((byte)ReadType.Byte); - rpcStart.Write(byteL); - } - - if (intL != 0) - { - rpcStart.Write((byte)ReadType.Int); - rpcStart.Write(intL); - } - - if (boolL != 0) - { - rpcStart.Write((byte)ReadType.Bool); - rpcStart.Write(boolL); - } - - if (FloatL != 0) - { - rpcStart.Write((byte)ReadType.Float); - rpcStart.Write(FloatL); - } - - if (StringL != 0) - { - rpcStart.Write((byte)ReadType.String); - rpcStart.Write(StringL); - } - - AmongUsClient.Instance.FinishRpcImmediately(rpcStart); - }*/ - - /*public static void StartRPC(byte rpc, MessageReader reader) - { - switch (rpc) - { - case (byte)CustomRPC.ResetVariables: - RPCProcedure.ResetVariables(); - break; - - case (byte)CustomRPC.WorkaroundSetRoles: - RPCProcedure.WorkaroundSetRoles(reader.ReadByte(), reader); - break; - - case (byte)CustomRPC.SetRole: - RPCProcedure.setRole(reader.ReadByte(), reader.ReadByte()); - break; - - case (byte)CustomRPC.SetModifier: - RPCProcedure.setModifier(reader.ReadByte(), reader.ReadByte(), reader.ReadByte()); - break; - - case (byte)CustomRPC.setDead: - RPCProcedure.setDead(reader.ReadByte(), reader.ReadBoolean()); - break; - - case (byte)CustomRPC.SheriffKill: - RPCProcedure.SheriffKill(reader.ReadByte()); - break; - - case (byte)CustomRPC.RestoreRole: - var RestoreRoleId = reader.ReadByte(); - RPCProcedure.RestoreRole(RestoreRoleId); - break; - - case (byte)CustomRPC.RestorePlayerLook: - RPCProcedure.RestorePlayerLook(); - break; - - case (byte)CustomRPC.ChangeRole: - RPCProcedure.ChangeRole(reader.ReadByte(), reader.ReadByte()); - break; - - case (byte)CustomRPC.Camouflager: - RPCProcedure.Camouflager(); - break; - - case (byte)CustomRPC.Illusory: - RPCProcedure.Illusory(); - break; - } - }*/ } public static class ReadRPCValue @@ -218,13 +125,4 @@ public static void ClearAll() floatL = 0; stringL = 0; } -} - -public enum ReadType -{ - Byte, - Int, - Bool, - Float, - String } \ No newline at end of file diff --git a/NextShip.Api/Utils/SpriteUtils.cs b/NextShip.Api/Utils/SpriteUtils.cs index fe446be..6d78002 100644 --- a/NextShip.Api/Utils/SpriteUtils.cs +++ b/NextShip.Api/Utils/SpriteUtils.cs @@ -1,3 +1,4 @@ +#nullable enable using System.Reflection; using Il2CppInterop.Runtime.InteropTypes.Arrays; using UnityEngine; @@ -17,7 +18,7 @@ public static void CaChe(this Sprite sprite, string name = "") CacheSprite.Add(sprite); } - public static Sprite GetCache(string name, bool NoCache = false) + public static Sprite? GetCache(string name, bool NoCache = false) { var sprite = CacheSprite.FirstOrDefault(n => n.name == name); if (sprite == null || sprite == default) @@ -37,7 +38,7 @@ public static Sprite GetCache(string name, bool NoCache = false) { if (CachedSprites.TryGetValue(path + pixelsPerUnit, out var sprite)) return sprite; var texture = LoadTextureFromResources(path); - sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), + sprite = Sprite.Create(texture, new Rect(0, 0, texture!.width, texture.height), new Vector2(0.5f, 0.5f), pixelsPerUnit); sprite.hideFlags |= HideFlags.HideAndDontSave | HideFlags.DontSaveInEditor; return CachedSprites[path + pixelsPerUnit] = sprite; @@ -57,7 +58,7 @@ public static Sprite GetCache(string name, bool NoCache = false) { if (CachedSprites.TryGetValue(path + pixelsPerUnit, out var sprite)) return sprite; var texture = LoadTextureFromResources(path); - sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), pivot, + sprite = Sprite.Create(texture, new Rect(0, 0, texture!.width, texture.height), pivot, pixelsPerUnit, extrude, meshType, border); sprite.hideFlags |= HideFlags.HideAndDontSave | HideFlags.DontSaveInEditor; return CachedSprites[path + pixelsPerUnit] = sprite; @@ -102,7 +103,7 @@ public static Sprite ToFullRect(this Sprite sprite, string name = "") return null; } - public static Texture2D? LoadTextureFromByte(Il2CppStructArray bytes) + public static Texture2D LoadTextureFromByte(Il2CppStructArray bytes) { var texture = new Texture2D(2, 2, TextureFormat.ARGB32, true); var byteTexture = bytes; @@ -131,7 +132,7 @@ public static Sprite ToFullRect(this Sprite sprite, string name = "") { if (CachedSprites.TryGetValue(path + pixelsPerUnit, out var sprite)) return sprite; var texture = LoadTextureFromDisk(path); - sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), + sprite = Sprite.Create(texture, new Rect(0, 0, texture!.width, texture.height), new Vector2(0.5f, 0.5f), pixelsPerUnit); sprite.hideFlags |= HideFlags.HideAndDontSave | HideFlags.DontSaveInEditor; return CachedSprites[path + pixelsPerUnit] = sprite; @@ -155,13 +156,13 @@ public static Sprite ToFullRect(this Sprite sprite, string name = "") return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100f); - bool isFile(string name) + bool isFile(string _name) { - if (name.EndsWith(FileName)) return true; + if (_name.EndsWith(FileName)) return true; - var strings = name.Split("."); + var strings = _name.Split("."); var str = names[strings.Length - 2]; - var n = name.Replace(".png", ""); + var n = _name.Replace(".png", ""); return n == str; } } diff --git a/NextShip.Api/Utils/StreamUtils.cs b/NextShip.Api/Utils/StreamUtils.cs index ec6958b..0739ef3 100644 --- a/NextShip.Api/Utils/StreamUtils.cs +++ b/NextShip.Api/Utils/StreamUtils.cs @@ -1,3 +1,4 @@ +#nullable enable using System.Reflection; using System.Runtime.CompilerServices; using Il2CppInterop.Runtime.Attributes; diff --git a/NextShip.Api/Utils/TextUtils.cs b/NextShip.Api/Utils/TextUtils.cs index 855bebd..723067d 100644 --- a/NextShip.Api/Utils/TextUtils.cs +++ b/NextShip.Api/Utils/TextUtils.cs @@ -95,7 +95,7 @@ public static string ToText(this IEnumerable chars) public static string Is(this string text, FileType type) { - return text += type switch + return text + type switch { FileType.Csv => ".csv", FileType.Json => ".json", diff --git a/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj b/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj index 91dfa8e..cf7d711 100644 --- a/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj +++ b/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj @@ -9,7 +9,7 @@ - + diff --git a/NextShip.sln.DotSettings.user b/NextShip.sln.DotSettings.user index 09de27c..65767c8 100644 --- a/NextShip.sln.DotSettings.user +++ b/NextShip.sln.DotSettings.user @@ -1,4 +1,5 @@  + ShowAndRun <AssemblyExplorer> <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.il2cpp.msbuild\2.0.1" Loaded="True" /> <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.il2cpp.msbuild\2.1.0-rc.1" Loaded="True" /> diff --git a/NextShip/Buttons/ButtonBase.cs b/NextShip/Buttons/ButtonBase.cs index ba9931b..f4d0d44 100644 --- a/NextShip/Buttons/ButtonBase.cs +++ b/NextShip/Buttons/ButtonBase.cs @@ -17,15 +17,15 @@ public ButtonBase() ButtonGameObject = new GameObject(base.ToString()); } - public ButtonBase Create(string name = "", GameObject clonetarget = null, ActionButton ActionButton = null, + public ButtonBase Create(string _name = "", GameObject cloneTarget = null, ActionButton _ActionButton = null, Action action = null) { - this.name = name; - if (clonetarget != null) ButtonGameObject = Object.Instantiate(clonetarget); + this.name = _name; + if (cloneTarget != null) ButtonGameObject = Object.Instantiate(cloneTarget); if (action != null) Action = action; - if (ActionButton != null) this.ActionButton = ActionButton; + if (_ActionButton != null) this.ActionButton = _ActionButton; return this; } } \ No newline at end of file diff --git a/NextShip/Cosmetics/CosmeticsManager.cs b/NextShip/Cosmetics/CosmeticsManager.cs index b775438..0ba78f2 100644 --- a/NextShip/Cosmetics/CosmeticsManager.cs +++ b/NextShip/Cosmetics/CosmeticsManager.cs @@ -3,11 +3,6 @@ namespace NextShip.Cosmetics; -[HarmonyPatch] -internal static class ShipCosmeticsCache -{ -} - [HarmonyPatch] internal static class ShipCosmeticsSet { diff --git a/NextShip/DIY/Addons/AddonsManager.cs b/NextShip/DIY/Addons/AddonsManager.cs index d49f44b..c9ce54f 100644 --- a/NextShip/DIY/Addons/AddonsManager.cs +++ b/NextShip/DIY/Addons/AddonsManager.cs @@ -2,6 +2,4 @@ namespace NextShip.DIY.Addons; -public class AddonsManager : Manager -{ -} \ No newline at end of file +public class AddonsManager : Manager; \ No newline at end of file diff --git a/NextShip/DIY/Plugins/PluginLoadInfo.cs b/NextShip/DIY/Plugins/PluginLoadInfo.cs new file mode 100644 index 0000000..44e6790 --- /dev/null +++ b/NextShip/DIY/Plugins/PluginLoadInfo.cs @@ -0,0 +1,21 @@ +using System; +using System.Reflection; +using NextShip.Api.Attributes; +using NextShip.Api.Bases; + +namespace NextShip.DIY.Plugins; + +internal class PluginLoadInfo +{ + public string _path { get; set; } + public Assembly _Assembly { get; set; } + public Type _Type { get; set; } + public ShipPlugin Plugin { get; set; } + + public ShipPluginInfo PluginInfo { get; set; } + + internal void Load() + { + Plugin.Load(); + } +} \ No newline at end of file diff --git a/NextShip/DIY/Plugins/PluginLoadService.cs b/NextShip/DIY/Plugins/PluginLoadService.cs new file mode 100644 index 0000000..3fcf74d --- /dev/null +++ b/NextShip/DIY/Plugins/PluginLoadService.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using Microsoft.Extensions.DependencyInjection; +using NextShip.Api.Attributes; +using NextShip.Api.Bases; + +namespace NextShip.DIY.Plugins; + +public class PluginLoadService +{ + + private readonly List _pluginLoadInfos; + private readonly PluginManager _pluginManager; + private readonly IServiceProvider _serviceProvider; + + public PluginLoadService(PluginManager manager, IServiceProvider serviceProvider) + { + _pluginLoadInfos = manager.PluginLoadInfos; + _pluginManager = manager; + _serviceProvider = serviceProvider; + Load(); + } + + public void Load() + { + Info("开始加载插件"); + foreach (var plugin in _pluginLoadInfos) + { + plugin.Plugin = (ShipPlugin)ActivatorUtilities.CreateInstance(_serviceProvider, plugin._Type); + plugin.PluginInfo = plugin._Type.GetCustomAttribute(); + plugin.Load(); + + ServiceAddAttribute.Registration(_serviceProvider, plugin._Assembly); + _pluginManager.Plugins.Add(plugin.Plugin); + Info($"加载插件 {plugin._Assembly.GetName().Name} {plugin._Type.Name} {plugin._path}"); + } + + _pluginManager.PluginLoadInfos = _pluginLoadInfos; + } +} \ No newline at end of file diff --git a/NextShip/DIY/Plugins/PluginManager.cs b/NextShip/DIY/Plugins/PluginManager.cs index b94bd32..c5f11f1 100644 --- a/NextShip/DIY/Plugins/PluginManager.cs +++ b/NextShip/DIY/Plugins/PluginManager.cs @@ -4,8 +4,12 @@ using System.Linq; using System.Reflection; using HarmonyLib; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.FileSystemGlobbing; using NextShip.Api.Attributes; using NextShip.Api.Bases; +using NextShip.Api.Interfaces; +using NextShip.Services; namespace NextShip.DIY.Plugins; @@ -13,21 +17,26 @@ public class PluginManager : Manager { private readonly List<(Assembly, Type, ShipPlugin)> PluginCreateS = []; private List PluginPathS = []; + internal List PluginLoadInfos = []; public List Plugins = []; + - public void Load() + public void InitPlugins() { - LoadPlugins(); + FindPlugins(); + LoadAssemblyFormPath(); } - private void LoadPlugins() + public void OnServiceBuild(ServiceBuilder serviceBuilder) { - PluginPathS = FindPlugins(); - if (PluginPathS == null) return; - - PluginPathS.Do(Load); - PluginCreateS.Do(Load); + foreach (var plugin in PluginLoadInfos) + { + INextAdd.GetAdds(plugin._Assembly).Do(n => n.ServiceAdd(serviceBuilder)); + } + + serviceBuilder._collection.AddActivatedSingleton(provider => + ActivatorUtilities.CreateInstance(provider, this)); } private void Load(string path) @@ -49,9 +58,7 @@ private void Load(string path) IsInherit = true; has = true; - var plugin = (ShipPlugin)assembly.CreateInstance(n.FullName!); - if (plugin == null) - return; + var plugin = (ShipPlugin)ActivatorUtilities.CreateInstance(Main._Service._Provider, n); var shipPluginInfo = n.GetCustomAttribute(); if (shipPluginInfo != null) @@ -74,7 +81,7 @@ private static void Load((Assembly, Type, ShipPlugin) pluginTuple) try { pluginTuple.Item3.Load(); - pluginTuple.Item3.NextAdd(Main.Adds); + Main.Adds.AddRange(pluginTuple.Item3.NextAdd()); Info($"Name:{shipPluginInfo.Name} . Version:{shipPluginInfo.Version} . Id:{shipPluginInfo.Id} 运行成功 ", filename: MethodUtils.GetClassName()); } @@ -84,12 +91,27 @@ private static void Load((Assembly, Type, ShipPlugin) pluginTuple) } } - private List FindPlugins() + private void FindPlugins() { - var pluginPaths = new List(); - var plugins = new DirectoryInfo(NextPaths.TIS_PluginsPath); - var fileInfos = plugins.GetFiles(); - fileInfos.Do(n => pluginPaths.Add(n.FullName)); - return pluginPaths; + var matcher = new Matcher(); + matcher.AddInclude(".dll"); + PluginPathS.AddRange(matcher.GetResultsInFullPath(NextPaths.TIS_PluginsPath).ToList()); + } + + private void LoadAssemblyFormPath() + { + foreach (var varPath in PluginPathS) + { + var assembly = Assembly.LoadFile(varPath); + var type = assembly.GetTypes().FirstOrDefault(n => n.BaseType == typeof(ShipPlugin)); + if (type == null) continue; + var LoadInfo = new PluginLoadInfo + { + _path = varPath, + _Assembly = assembly, + _Type = type + }; + Info($"初始化插件 path:{varPath} type:{type}"); + } } } \ No newline at end of file diff --git a/NextShip/GlobalUsings.cs b/NextShip/GlobalUsings.cs index 6a2e149..2a353db 100644 --- a/NextShip/GlobalUsings.cs +++ b/NextShip/GlobalUsings.cs @@ -2,7 +2,6 @@ global using NextShip.Api.Utils; global using NextShip.Api.Roles; global using NextShip.Api.Utilities; -global using static NextShip.Api.Logs.log; global using static NextShip.Api.Logs.FastLog; global using static NextShip.Manager.EventManager; global using Main = NextShip.NextShip; \ No newline at end of file diff --git a/NextShip/Languages/Language.cs b/NextShip/Languages/Language.cs index cf3aed6..ebd36f5 100644 --- a/NextShip/Languages/Language.cs +++ b/NextShip/Languages/Language.cs @@ -1,20 +1,17 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using csv = NextShip.Languages.LanguageCSV; -using pack = NextShip.Languages.LanguagePack; namespace NextShip.Languages; public static class Language { - public static string GetString(string s, Dictionary? replacementDic = null) + public static string GetString(string s, Dictionary replacementDic = null) { var langId = TranslationController.InstanceExists ? TranslationController.Instance.currentLanguage.languageID : SupportedLangs.English; - var str = ""; - str = File.Exists(@"Language\" + pack.languageName + ".dat") ? pack.GetPString(s) : csv.GetCString(s, langId); + var str = File.Exists(@"Language\" + LanguagePack.languageName + ".dat") ? LanguagePack.GetPString(s) : LanguageCSV.GetCString(s, langId); return replacementDic == null ? str : replacementDic.Aggregate(str, (current, rd) => current.Replace(rd.Key, rd.Value)); @@ -22,9 +19,9 @@ public static string GetString(string s, Dictionary? replacement public static void Init() { - if (!File.Exists(@"Language\" + pack.languageName + ".dat")) - csv.LoadCSV(); + if (!File.Exists(@"Language\" + LanguagePack.languageName + ".dat")) + LanguageCSV.LoadCSV(); else - pack.Load(); + LanguagePack.Load(); } } \ No newline at end of file diff --git a/NextShip/Languages/LanguagePack.cs b/NextShip/Languages/LanguagePack.cs index d8e15af..8fc7f17 100644 --- a/NextShip/Languages/LanguagePack.cs +++ b/NextShip/Languages/LanguagePack.cs @@ -6,7 +6,6 @@ using System.Text.Json; using System.Text.Unicode; using AmongUs.Data; -using csv = NextShip.Languages.LanguageCSV; namespace NextShip.Languages; @@ -87,7 +86,7 @@ private static void CTT() private static void CreateTT() { var text = ""; - foreach (var title in csv.translateMaps) + foreach (var title in LanguageCSV.translateMaps) { text += '"' + $"{title.Key}" + '"' + " : " + '"' + LanguageCSV.GetCString(title.Key, 0) + '"' + "\n"; File.WriteAllText(LPath, text); diff --git a/NextShip/Manager/LoadManager.cs b/NextShip/Manager/LoadManager.cs index 84f0f77..22647bd 100644 --- a/NextShip/Manager/LoadManager.cs +++ b/NextShip/Manager/LoadManager.cs @@ -64,7 +64,8 @@ public static IEnumerator Load(SplashManager __instance) yield return null; } - var Co = new StackFullCoroutine(AllLoad.GetEnumerator()); + using var enumerator = AllLoad.GetEnumerator(); + var Co = new StackFullCoroutine(enumerator); while (Co.CanMove()) { diff --git a/NextShip/Manager/NextOptionManager.cs b/NextShip/Manager/NextOptionManager.cs index 191b107..58f87bd 100644 --- a/NextShip/Manager/NextOptionManager.cs +++ b/NextShip/Manager/NextOptionManager.cs @@ -2,6 +2,4 @@ namespace NextShip.Manager; -public class NextOptionManager : INextOptionManager -{ -} \ No newline at end of file +public class NextOptionManager : INextOptionManager; \ No newline at end of file diff --git a/NextShip/Manager/NextPlayerManager.cs b/NextShip/Manager/NextPlayerManager.cs index a6e71f4..111c212 100644 --- a/NextShip/Manager/NextPlayerManager.cs +++ b/NextShip/Manager/NextPlayerManager.cs @@ -1,5 +1,7 @@ +#nullable enable using System.Collections.Generic; using System.Linq; +using InnerNet; using NextShip.Api.Bases; using NextShip.Api.Interfaces; @@ -7,20 +9,50 @@ namespace NextShip.Manager; public class NextPlayerManager : IPlayerManager { - private readonly List PlayerInfos = new(); + private readonly List PlayerInfos = []; public static NextPlayerManager Instance => Main._Service.Get(); - public NextInfo GetPlayerInfo(PlayerControl player) + public NextInfo CreateOrGetSetPlayerInfo(PlayerControl player) { - return PlayerInfos.Find(n => n.PlayerControl == player)!; + var info = PlayerInfos.Exists(IsInfo) ? PlayerInfos.First(IsInfo) : new NextInfo(); + + info.PlayerControl = player; + info.PlayerId = player.PlayerId; + info.PlayerInfo = player.Data; + info.IsHost = AmongUsClient.Instance.HostId == info.clientId; + info.IsLocal = CachedPlayer.LocalPlayer?.PlayerControl == player; + return info; + bool IsInfo(NextInfo nextInfo) => nextInfo.PlayerControl == player || nextInfo.PlayerId == player.PlayerId; } + + public NextInfo CreateOrGetSetPlayerInfo(ClientData data) + { + var info = PlayerInfos.Exists(IsInfo) ? PlayerInfos.First(IsInfo) : new NextInfo(); - public void CreatePlayerInfo() + info.ClientData = data; + info.clientId = data.Id; + info.FriendCode = data.FriendCode; + info.PUID = data.ProductUserId; + info.PlayerLevel = data.PlayerLevel; + info.PlayerName = data.PlayerName; + info.PlayerControl = data.Character; + info.ColorId = data.ColorId; + info.IsHost = AmongUsClient.Instance.HostId == data.Id; + info.IsLocal = CachedPlayer.LocalPlayer?.PlayerControl == data.Character; + return info; + bool IsInfo(NextInfo nextInfo) => nextInfo.clientId == data.Id || nextInfo.PlayerControl == data.Character; + } + + public void InitPlayer(PlayerControl player) { + } + public bool IsHost(PlayerControl player) => PlayerInfos.First(n => n.PlayerControl == player).IsHost; + + public bool TryGetPlayer(PlayerControl player, out NextInfo? info) { if (PlayerInfos.Exists(n => n.PlayerControl == player)) diff --git a/NextShip/Manager/RoleManager.cs b/NextShip/Manager/NextRoleManager.cs similarity index 96% rename from NextShip/Manager/RoleManager.cs rename to NextShip/Manager/NextRoleManager.cs index c2dbc52..9cac9bc 100644 --- a/NextShip/Manager/RoleManager.cs +++ b/NextShip/Manager/NextRoleManager.cs @@ -26,6 +26,11 @@ public void AssignRole(PlayerControl player, IRole role) { } + public void CheckRoles() + { + + } + public void Clear() { } diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index 04d75d8..f938fab 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -22,10 +22,12 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + + + @@ -37,6 +39,10 @@ + + + + diff --git a/NextShip/Options/OptionValue/FloatOptionValueBase.cs b/NextShip/Options/OptionValue/FloatOptionValueBase.cs index 203fadf..3128c87 100644 --- a/NextShip/Options/OptionValue/FloatOptionValueBase.cs +++ b/NextShip/Options/OptionValue/FloatOptionValueBase.cs @@ -1,3 +1,5 @@ +using NextShip.Api.Bases; + namespace NextShip.Options.OptionValue; public class FloatOptionValueBase(float defaultValue, float min, float step, float max) diff --git a/NextShip/Options/OptionValue/IntOptionValueBase.cs b/NextShip/Options/OptionValue/IntOptionValueBase.cs index 95cf19d..c9554fb 100644 --- a/NextShip/Options/OptionValue/IntOptionValueBase.cs +++ b/NextShip/Options/OptionValue/IntOptionValueBase.cs @@ -1,3 +1,5 @@ +using NextShip.Api.Bases; + namespace NextShip.Options.OptionValue; public class IntOptionValueBase(int defaultValue, int min, int step, int max) diff --git a/NextShip/Options/Patches/OptionsConsolePatch.cs b/NextShip/Options/Patches/OptionsConsolePatch.cs index 50cbeeb..5e1b1f3 100644 --- a/NextShip/Options/Patches/OptionsConsolePatch.cs +++ b/NextShip/Options/Patches/OptionsConsolePatch.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using HarmonyLib; -using NextShip.UI; + +using NextShip.UI.Module; using UnityEngine; namespace NextShip.Options.Patches; diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs index 82e035f..8969d2d 100644 --- a/NextShip/Patches/PlayerPatch.cs +++ b/NextShip/Patches/PlayerPatch.cs @@ -1,7 +1,7 @@ -using System; using System.Collections.Generic; using HarmonyLib; using Hazel; +using InnerNet; using NextShip.Api.Enums; using NextShip.Api.RPCs; using NextShip.Manager; @@ -17,8 +17,19 @@ public static void PlayerControlAwake_PostfixPatch(PlayerControl __instance) { if (NextPlayerManager.Instance.TryGetPlayer(__instance, out _)) return; + NextPlayerManager.Instance.InitPlayer(__instance); } + [HarmonyPatch(typeof(GameData), nameof(GameData.AddPlayer))] + [HarmonyPostfix] + public static void GameDataAddPlayer_Postfix([HarmonyArgument(0)] PlayerControl pc) => + NextPlayerManager.Instance.CreateOrGetSetPlayerInfo(pc); + + [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.GetOrCreateClient))] + [HarmonyPostfix] + public static void GetOrCreateClient_Postfix(ClientData __result) => + NextPlayerManager.Instance.CreateOrGetSetPlayerInfo(__result); + public static readonly List AllPlayerVersionInfos = []; [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerJoined))] diff --git a/NextShip/Patches/RoleAssignmentPatch.cs b/NextShip/Patches/RoleAssignmentPatch.cs index 524bb0c..1ef2522 100644 --- a/NextShip/Patches/RoleAssignmentPatch.cs +++ b/NextShip/Patches/RoleAssignmentPatch.cs @@ -1,3 +1,5 @@ +using System.Collections.Generic; +using System.Linq; using AmongUs.GameOptions; using HarmonyLib; using NextShip.Api.Attributes; @@ -32,6 +34,24 @@ internal class RoleManagerPatch [HarmonyPatch(typeof(RoleManager), nameof(RoleManager.SelectRoles))] public static void SelectRoles_Postfix(RoleManager __instance) { + GetPlayerRoleS(out var C, out var I); + var CAssign = new Queue(C); + var IAssign = new Queue(I); + _StartAssign: + var player = (CAssign.Count > 0 ? CAssign : IAssign).Dequeue(); + var _creator = _nextRoleManager.FastGetCreator(); + var role = _creator.GetAssign(); + _nextRoleManager.AssignRole(player, role); + if (IAssign.Count > 0) + goto _StartAssign; + } + + private static void GetPlayerRoleS(out PlayerControl[] C, out PlayerControl[] I) + { + var ListC = CachedPlayer.AllPlayers.Where(n => n?.Data.Role.Role == RoleTypes.Crewmate).Select(n =>n.PlayerControl); + var ListI = CachedPlayer.AllPlayers.Where(n => n?.Data.Role.Role == RoleTypes.Impostor).Select(n => n.PlayerControl); + C = ListC.ToArray(); + I = ListI.ToArray(); } [HarmonyPatch(typeof(GameManager), nameof(GameManager.EndGame))] diff --git a/NextShip/RPC/FastRPC.cs b/NextShip/RPC/FastRPC.cs deleted file mode 100644 index 15e009e..0000000 --- a/NextShip/RPC/FastRPC.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using HarmonyLib; -using Hazel; -using InnerNet; - -namespace NextShip.RPC; - -public class FastRPC -{ - public readonly FastReader Reader = new(); - - [HarmonyPatch] - public class FastReader - { - public static List AllReader = new(); - public MessageReader _Reader; - - public Action HandleRpc = null; - public MessageReader ParentReader = new(); - private byte? TargetId; - - public FastReader() - { - _Reader = MessageReader.Get(ParentReader); - - AllReader.Add(this); - } - - public FastReader(MessageReader reader) - { - _Reader = reader; - - AllReader.Add(this); - } - - public void SetTarget(byte id) - { - TargetId = id; - } - - - public bool ReadBool() - { - return _Reader.ReadBoolean(); - } - - public int ReadInt() - { - return _Reader.ReadInt32(); - } - - public float ReadFloat() - { - return _Reader.ReadSingle(); - } - - public string ReadString() - { - return _Reader.ReadString(); - } - - public byte ReadByte() - { - return _Reader.ReadByte(); - } - - } -} \ No newline at end of file diff --git a/NextShip/RPC/RPCCheck.cs b/NextShip/RPC/RPCCheck.cs deleted file mode 100644 index af65fcb..0000000 --- a/NextShip/RPC/RPCCheck.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Hazel; - -namespace NextShip.RPC; - -public class RPCCheck -{ - public static bool CheckRpc(PlayerControl player, byte callId, MessageReader reader) - { - return true; - } -} \ No newline at end of file diff --git a/NextShip/RPC/RPCConnectProject.cs b/NextShip/RPC/RPCConnectProject.cs deleted file mode 100644 index 157fbb3..0000000 --- a/NextShip/RPC/RPCConnectProject.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Collections.Generic; - -namespace NextShip.RPC; - -public abstract class RPCConnectProject -{ - public string ID; - - protected RPCConnectProject() - { - RPCProjectManager.Instance.AllProjects.Add(this); - } - - public abstract void OnStart(); - - public virtual void OnEnd() - { - } -} - -public sealed class RPCProjectManager -{ - private static RPCProjectManager Current; - - private readonly RPCProjectManager _instance; - public List AllProjects = new(); - - public RPCProjectManager() - { - _instance = this; - Current = this; - } - - public static RPCProjectManager Instance - { - get { return Current ??= new RPCProjectManager(); } - set => Current = value; - } -} \ No newline at end of file diff --git a/NextShip/RPC/RPCPatch.cs b/NextShip/RPC/RPCPatch.cs deleted file mode 100644 index 455d2a1..0000000 --- a/NextShip/RPC/RPCPatch.cs +++ /dev/null @@ -1,23 +0,0 @@ -using HarmonyLib; -using Hazel; - -namespace NextShip.RPC; - -[HarmonyPatch] -public class RPCPatch -{ - [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.HandleRpc))] - public class RPCHandlerPatch - { - private static void Postfix([HarmonyArgument(0)] byte callId, [HarmonyArgument(1)] MessageReader reader) - { - /*RPCUtils.StartRPC(callId, reader);*/ - } - - private static bool Prefix(PlayerControl __instance, [HarmonyArgument(0)] byte callId, - [HarmonyArgument(1)] MessageReader reader) - { - return RPCCheck.CheckRpc(__instance, callId, reader); - } - } -} \ No newline at end of file diff --git a/NextShip/Roles/FastCreator.cs b/NextShip/Roles/FastCreator.cs index df3de77..591e67f 100644 --- a/NextShip/Roles/FastCreator.cs +++ b/NextShip/Roles/FastCreator.cs @@ -10,6 +10,10 @@ public class FastCreator : IRoleCreator { public readonly List AllRole = []; + private readonly NextRoleManager _RoleManager = Main._Service.Get(); + + private List enableRoles = []; + public void Dispose() { Clear(); @@ -32,8 +36,14 @@ public void Clear() public IRole GetAssign() { + SetList(); var random = new Random(); - var list = Main._Service.Get().Roles.Where(n => n.EnableAssign).ToList(); + var list = enableRoles; return list[random.Next(list.Count)]; } + + private void SetList() + { + enableRoles= _RoleManager.Roles.Where(n => n.EnableAssign).ToList(); + } } \ No newline at end of file diff --git a/NextShip/Services/DataService.cs b/NextShip/Services/DataService.cs index 4db2905..50a9921 100644 --- a/NextShip/Services/DataService.cs +++ b/NextShip/Services/DataService.cs @@ -1,5 +1,3 @@ namespace NextShip.Services; -public class DataService -{ -} \ No newline at end of file +public class DataService; \ No newline at end of file diff --git a/NextShip/Services/ServiceBuilder.cs b/NextShip/Services/ServiceBuilder.cs index 3c8da21..c6498d4 100644 --- a/NextShip/Services/ServiceBuilder.cs +++ b/NextShip/Services/ServiceBuilder.cs @@ -6,11 +6,11 @@ namespace NextShip.Services; public class ServiceBuilder : IServiceBuilder { - public ServiceCollection _collection { get; private set; } + public ServiceCollection _collection { get; set; } public IServiceBuilder CreateService() { - _collection = new ServiceCollection(); + _collection = []; return this; } @@ -26,6 +26,12 @@ public IServiceBuilder Add(Type type) return this; } + public IServiceBuilder Add(Func func) where TService : class + { + _collection.AddSingleton(func); + return this; + } + public INextService Build() { return new NextService(_collection.BuildServiceProvider()); diff --git a/NextShip/UI/Components/DownMenu.cs b/NextShip/UI/Components/DownMenu.cs index 5467ac2..703c1e2 100644 --- a/NextShip/UI/Components/DownMenu.cs +++ b/NextShip/UI/Components/DownMenu.cs @@ -4,9 +4,4 @@ namespace NextShip.UI.Components; [Il2CppRegister] -public class DownMenu : MonoBehaviour -{ - public void Start() - { - } -} \ No newline at end of file +public class DownMenu : MonoBehaviour; \ No newline at end of file diff --git a/NextShip/UI/Components/NextMenuOption.cs b/NextShip/UI/Components/NextMenuOption.cs index d114b40..2b4f725 100644 --- a/NextShip/UI/Components/NextMenuOption.cs +++ b/NextShip/UI/Components/NextMenuOption.cs @@ -1,4 +1,5 @@ using NextShip.Api.Attributes; +using NextShip.UI.Module; using UnityEngine; namespace NextShip.UI.Components; @@ -10,19 +11,11 @@ public class NextMenuOption : MonoBehaviour public bool Open; public NextOptionMenu __OptionMenu; - public void Awake() - { - } - public void Start() { CreateOption(); } - public void Update() - { - } - public void OnDestroy() { diff --git a/NextShip/UI/Components/ShipOptionBehaviour.cs b/NextShip/UI/Components/ShipOptionBehaviour.cs index 8f7292c..46ce0b5 100644 --- a/NextShip/UI/Components/ShipOptionBehaviour.cs +++ b/NextShip/UI/Components/ShipOptionBehaviour.cs @@ -18,10 +18,6 @@ public class ShipOptionBehaviour : MonoBehaviour public Action OnOptionValueChanged; public OptionBase OptionBase { private set; get; } - public void FixedUpdate() - { - } - public void OnEnable() { if (OptionBase == null) return; diff --git a/NextShip/UI/Module/FastScreen.cs b/NextShip/UI/Module/FastScreen.cs index 676c5b8..5297e31 100644 --- a/NextShip/UI/Module/FastScreen.cs +++ b/NextShip/UI/Module/FastScreen.cs @@ -3,7 +3,7 @@ using Twitch; using UnityEngine; -namespace NextShip.UI; +namespace NextShip.UI.Module; public class FastScreen { diff --git a/NextShip/UI/Module/NextOptionMenu.cs b/NextShip/UI/Module/NextOptionMenu.cs index dbdd2e1..5971cb7 100644 --- a/NextShip/UI/Module/NextOptionMenu.cs +++ b/NextShip/UI/Module/NextOptionMenu.cs @@ -7,7 +7,7 @@ using UnityEngine.Events; using Object = UnityEngine.Object; -namespace NextShip.UI; +namespace NextShip.UI.Module; [HarmonyPatch] public class NextOptionMenu diff --git a/NextShip/UI/Patches/GameStartManagerButton.cs b/NextShip/UI/Patches/GameStartManagerButton.cs index 571698f..70fab82 100644 --- a/NextShip/UI/Patches/GameStartManagerButton.cs +++ b/NextShip/UI/Patches/GameStartManagerButton.cs @@ -1,5 +1,3 @@ namespace NextShip.UI.Patches; -public class GameStartManagerButton -{ -} \ No newline at end of file +public class GameStartManagerButton; \ No newline at end of file diff --git a/NextShip/Updates/ModUpdater.cs b/NextShip/Updates/ModUpdater.cs index 5a93c7a..c62e8b3 100644 --- a/NextShip/Updates/ModUpdater.cs +++ b/NextShip/Updates/ModUpdater.cs @@ -13,7 +13,8 @@ public class ModUpdater // 模组下载链接 public string ModDownloadURL; - public async Task UpdateMod() + public Task UpdateMod() { + return Task.CompletedTask; } } \ No newline at end of file diff --git a/NextShip/main.cs b/NextShip/main.cs index de38ead..33e4976 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -1,14 +1,13 @@ +using System; using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Net.Http; using System.Reflection; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using HarmonyLib; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using NextShip.Api.Attributes; using NextShip.Api.Extension; using NextShip.Api.Interfaces; @@ -61,6 +60,8 @@ public sealed class NextShip : BasePlugin private Harmony Harmony { get; } = new(Id); + private static event Action OnBuilder; + public override void Load() { @@ -69,11 +70,9 @@ public override void Load() TISLog = BepInExLogger.CreateLogSource(ModName.RemoveBlank()); Harmony.PatchAll(); - Get(TISLog); + Api.Logs.Log.Get(TISLog); Init(); - PluginManager.Get().Load(); - CreateService(); LoadDependent(); @@ -107,6 +106,15 @@ private static void Init() varType.ConfigBind(Instance.Config); } + private static void InitPlugins() + { + var manager = PluginManager.Get(); + manager.InitPlugins(); + OnBuilder += manager.OnServiceBuild; + } + + public static void AddOnBuild() + {} private static void CreateService() { @@ -117,13 +125,14 @@ private static void CreateService() builder._collection.AddSingleton(); builder._collection.AddSingleton(); builder._collection.AddSingleton(); - builder.AddTransient(); + builder._collection.AddHttpClient(); builder.AddTransient(); builder.Add(); builder.Add(); builder.Add(); builder.Add(); - builder.Add(); + + OnBuilder?.Invoke(builder); foreach (var varType in Adds) varType.ServiceAdd(builder); diff --git a/nuget.config b/nuget.config index 9e5b163..4d24d61 100644 --- a/nuget.config +++ b/nuget.config @@ -1,9 +1,9 @@ - + - - - + + + From 79ba401dd9efaabfec54a6e4be60115d5058945a Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Thu, 11 Jan 2024 00:13:06 +0800 Subject: [PATCH 23/29] =?UTF-8?q?IDE=E6=A0=BC=E5=BC=8F=E5=8C=96=E6=B8=85?= =?UTF-8?q?=E7=90=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NextShip.Api/Bases/NextInfo.cs | 28 ++++++++--------- NextShip.Api/Extension/ModStampExtension.cs | 12 ++++---- NextShip.Api/Interfaces/IServiceBuilder.cs | 2 +- NextShip.Api/NextShip.Api.csproj | 2 +- NextShip.Api/RPCs/FastRpcReader.cs | 4 +-- NextShip.Api/RPCs/FastRpcWriter.cs | 2 +- NextShip.Api/RPCs/RPCProjectManager.cs | 3 +- NextShip.Api/Services/DependentService.cs | 17 ++++++----- NextShip.Api/Services/MetadataService.cs | 12 ++++++-- NextShip.Api/Utils/PingUtils.cs | 4 +-- NextShip/Buttons/ButtonBase.cs | 4 +-- NextShip/DIY/Plugins/PluginLoadInfo.cs | 4 +-- NextShip/DIY/Plugins/PluginLoadService.cs | 5 ++-- NextShip/DIY/Plugins/PluginManager.cs | 10 +++---- NextShip/Languages/Language.cs | 4 ++- NextShip/Manager/NextPlayerManager.cs | 22 ++++++++++---- NextShip/Manager/NextRoleManager.cs | 9 +++--- NextShip/NextShip.csproj | 4 +-- .../Options/Patches/OptionsConsolePatch.cs | 1 - NextShip/Patches/PlayerPatch.cs | 30 +++++++++++-------- NextShip/Patches/RoleAssignmentPatch.cs | 20 +++++++------ NextShip/Roles/FastCreator.cs | 7 ++--- NextShip/main.cs | 6 ++-- 23 files changed, 115 insertions(+), 97 deletions(-) diff --git a/NextShip.Api/Bases/NextInfo.cs b/NextShip.Api/Bases/NextInfo.cs index cb85aac..2df4f69 100644 --- a/NextShip.Api/Bases/NextInfo.cs +++ b/NextShip.Api/Bases/NextInfo.cs @@ -6,34 +6,34 @@ namespace NextShip.Api.Bases; public record NextInfo { public float BodySpeed; - + + public ClientData ClientData; + public int clientId; - public byte PlayerId; + public int ColorId; public string FriendCode; - public string PlayerName; - - public uint PlayerLevel; - - public int ColorId; - public float GhostSpeed; + public bool IsHost; + + public bool IsLocal; + public PlayerControl PlayerControl; - public ClientData ClientData; + public byte PlayerId; public GameData.PlayerInfo PlayerInfo; - public string PUID; + public uint PlayerLevel; - public RoleBase RoleBase; + public string PlayerName; - public IRole Role; + public string PUID; - public bool IsHost; + public IRole Role; - public bool IsLocal; + public RoleBase RoleBase; } \ No newline at end of file diff --git a/NextShip.Api/Extension/ModStampExtension.cs b/NextShip.Api/Extension/ModStampExtension.cs index d8c178b..3c6ff83 100644 --- a/NextShip.Api/Extension/ModStampExtension.cs +++ b/NextShip.Api/Extension/ModStampExtension.cs @@ -5,19 +5,17 @@ namespace NextShip.Api.Extension; public static class ModStampExtension { private static bool Added; + public static void UseModStamp() { if (Added) return; - - SceneManager.add_sceneLoaded((Action) ((scene, _) => + + SceneManager.add_sceneLoaded((Action)((scene, _) => { - if (scene.name == "MainMenu") - { - ModManager.Instance.ShowModStamp(); - } + if (scene.name == "MainMenu") ModManager.Instance.ShowModStamp(); })); - + Added = true; } } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IServiceBuilder.cs b/NextShip.Api/Interfaces/IServiceBuilder.cs index 9be1004..5ced91d 100644 --- a/NextShip.Api/Interfaces/IServiceBuilder.cs +++ b/NextShip.Api/Interfaces/IServiceBuilder.cs @@ -5,7 +5,7 @@ namespace NextShip.Api.Interfaces; public interface IServiceBuilder { public ServiceCollection _collection { get; set; } - + public IServiceBuilder CreateService(); public IServiceBuilder Add() where T : class; diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index ec4fbbf..167db34 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -28,7 +28,7 @@ - + diff --git a/NextShip.Api/RPCs/FastRpcReader.cs b/NextShip.Api/RPCs/FastRpcReader.cs index d7a8112..6552555 100644 --- a/NextShip.Api/RPCs/FastRpcReader.cs +++ b/NextShip.Api/RPCs/FastRpcReader.cs @@ -15,7 +15,7 @@ public class FastRpcReader public static class FastRpcReaderPatch { public static List AllFastRpcReader = []; - + [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.HandleGameDataInner))] [HarmonyPrefix] public static void InnerNet_ReaderPath([HarmonyArgument(0)] MessageReader reader) @@ -56,13 +56,11 @@ public static void AddFormAssembly(Assembly assembly) continue; if (method.GetGenericArguments()[0] == typeof(MessageReader)) - { AllFastRpcReader.Add(new FastRpcReader { CallId = FastReadAdd.CallId, HandleRpc = n => method.Invoke(null, [n]) }); - } } } } diff --git a/NextShip.Api/RPCs/FastRpcWriter.cs b/NextShip.Api/RPCs/FastRpcWriter.cs index 4a4bb1b..f5ae6e9 100644 --- a/NextShip.Api/RPCs/FastRpcWriter.cs +++ b/NextShip.Api/RPCs/FastRpcWriter.cs @@ -13,7 +13,7 @@ public class FastRpcWriter(MessageWriter? writer) private int SendTargetId; - private List targetIds = new (); + private List targetIds = new(); private uint targetObjectId; diff --git a/NextShip.Api/RPCs/RPCProjectManager.cs b/NextShip.Api/RPCs/RPCProjectManager.cs index 0ce4053..42b476c 100644 --- a/NextShip.Api/RPCs/RPCProjectManager.cs +++ b/NextShip.Api/RPCs/RPCProjectManager.cs @@ -1,10 +1,9 @@ namespace NextShip.Api.RPCs; - public sealed class RPCProjectManager { private static RPCProjectManager Current; - + public readonly List AllProjects = new(); public RPCProjectManager() diff --git a/NextShip.Api/Services/DependentService.cs b/NextShip.Api/Services/DependentService.cs index 3871286..0376ad7 100644 --- a/NextShip.Api/Services/DependentService.cs +++ b/NextShip.Api/Services/DependentService.cs @@ -5,26 +5,29 @@ namespace NextShip.Api.Services; public class DependentService(HttpClient _client) { public readonly HashSet<(Assembly, FileInfo)> Dlls = []; - - public readonly Queue RepoDownloadDependents = new(); public readonly Queue<(Uri, string)> DownloadDependents = new(); public readonly Queue<(Stream, string)> GenerateDependents = new(); + public readonly Queue RepoDownloadDependents = new(); + private DirectoryInfo Directory; - - private string RootPath; private string RepoURL; - + + private string RootPath; + public void SetPath(DirectoryInfo directoryInfo) { RootPath = directoryInfo.FullName; Directory = directoryInfo; } - public void SetRepoURL(string uri) => RepoURL = uri; + public void SetRepoURL(string uri) + { + RepoURL = uri; + } public void BuildDependent() { @@ -34,7 +37,7 @@ public void BuildDependent() var url = RepoURL + $"/{name}"; DownloadDependents.Enqueue((new Uri(url), name)); } - + while (DownloadDependents.Count > 0) { var (url, name) = DownloadDependents.Dequeue(); diff --git a/NextShip.Api/Services/MetadataService.cs b/NextShip.Api/Services/MetadataService.cs index 4959223..f590d85 100644 --- a/NextShip.Api/Services/MetadataService.cs +++ b/NextShip.Api/Services/MetadataService.cs @@ -2,13 +2,19 @@ namespace NextShip.Api.Services; -public class MetadataService(DownloadService _downloadService, ILogger _logger, GithubAnalyzer analyzer) +public class MetadataService( + DownloadService _downloadService, + ILogger _logger, + GithubAnalyzer analyzer) { private string Url; - public void SetRepo(string url) => Url = url; + + public void SetRepo(string url) + { + Url = url; + } public void GetMetadataInfo() { - } } \ No newline at end of file diff --git a/NextShip.Api/Utils/PingUtils.cs b/NextShip.Api/Utils/PingUtils.cs index 28dbf56..29f4702 100644 --- a/NextShip.Api/Utils/PingUtils.cs +++ b/NextShip.Api/Utils/PingUtils.cs @@ -12,9 +12,9 @@ public static PingInfo Ping(string url) var ping = new Ping(); var reply = ping.Send(url); - + var stringB = new StringBuilder(); - var status = reply.Status switch + var status = reply.Status switch { IPStatus.Success => "成功", IPStatus.TimedOut => "超时", diff --git a/NextShip/Buttons/ButtonBase.cs b/NextShip/Buttons/ButtonBase.cs index f4d0d44..448a2f3 100644 --- a/NextShip/Buttons/ButtonBase.cs +++ b/NextShip/Buttons/ButtonBase.cs @@ -20,12 +20,12 @@ public ButtonBase() public ButtonBase Create(string _name = "", GameObject cloneTarget = null, ActionButton _ActionButton = null, Action action = null) { - this.name = _name; + name = _name; if (cloneTarget != null) ButtonGameObject = Object.Instantiate(cloneTarget); if (action != null) Action = action; - if (_ActionButton != null) this.ActionButton = _ActionButton; + if (_ActionButton != null) ActionButton = _ActionButton; return this; } } \ No newline at end of file diff --git a/NextShip/DIY/Plugins/PluginLoadInfo.cs b/NextShip/DIY/Plugins/PluginLoadInfo.cs index 44e6790..615010e 100644 --- a/NextShip/DIY/Plugins/PluginLoadInfo.cs +++ b/NextShip/DIY/Plugins/PluginLoadInfo.cs @@ -11,9 +11,9 @@ internal class PluginLoadInfo public Assembly _Assembly { get; set; } public Type _Type { get; set; } public ShipPlugin Plugin { get; set; } - + public ShipPluginInfo PluginInfo { get; set; } - + internal void Load() { Plugin.Load(); diff --git a/NextShip/DIY/Plugins/PluginLoadService.cs b/NextShip/DIY/Plugins/PluginLoadService.cs index 3fcf74d..e0b37fd 100644 --- a/NextShip/DIY/Plugins/PluginLoadService.cs +++ b/NextShip/DIY/Plugins/PluginLoadService.cs @@ -9,11 +9,10 @@ namespace NextShip.DIY.Plugins; public class PluginLoadService { - private readonly List _pluginLoadInfos; private readonly PluginManager _pluginManager; private readonly IServiceProvider _serviceProvider; - + public PluginLoadService(PluginManager manager, IServiceProvider serviceProvider) { _pluginLoadInfos = manager.PluginLoadInfos; @@ -30,7 +29,7 @@ public void Load() plugin.Plugin = (ShipPlugin)ActivatorUtilities.CreateInstance(_serviceProvider, plugin._Type); plugin.PluginInfo = plugin._Type.GetCustomAttribute(); plugin.Load(); - + ServiceAddAttribute.Registration(_serviceProvider, plugin._Assembly); _pluginManager.Plugins.Add(plugin.Plugin); Info($"加载插件 {plugin._Assembly.GetName().Name} {plugin._Type.Name} {plugin._path}"); diff --git a/NextShip/DIY/Plugins/PluginManager.cs b/NextShip/DIY/Plugins/PluginManager.cs index c5f11f1..6943223 100644 --- a/NextShip/DIY/Plugins/PluginManager.cs +++ b/NextShip/DIY/Plugins/PluginManager.cs @@ -16,11 +16,11 @@ namespace NextShip.DIY.Plugins; public class PluginManager : Manager { private readonly List<(Assembly, Type, ShipPlugin)> PluginCreateS = []; - private List PluginPathS = []; internal List PluginLoadInfos = []; + private readonly List PluginPathS = []; public List Plugins = []; - + public void InitPlugins() { @@ -30,11 +30,9 @@ public void InitPlugins() public void OnServiceBuild(ServiceBuilder serviceBuilder) { - foreach (var plugin in PluginLoadInfos) - { + foreach (var plugin in PluginLoadInfos) INextAdd.GetAdds(plugin._Assembly).Do(n => n.ServiceAdd(serviceBuilder)); - } - + serviceBuilder._collection.AddActivatedSingleton(provider => ActivatorUtilities.CreateInstance(provider, this)); } diff --git a/NextShip/Languages/Language.cs b/NextShip/Languages/Language.cs index ebd36f5..402f964 100644 --- a/NextShip/Languages/Language.cs +++ b/NextShip/Languages/Language.cs @@ -11,7 +11,9 @@ public static string GetString(string s, Dictionary replacementD var langId = TranslationController.InstanceExists ? TranslationController.Instance.currentLanguage.languageID : SupportedLangs.English; - var str = File.Exists(@"Language\" + LanguagePack.languageName + ".dat") ? LanguagePack.GetPString(s) : LanguageCSV.GetCString(s, langId); + var str = File.Exists(@"Language\" + LanguagePack.languageName + ".dat") + ? LanguagePack.GetPString(s) + : LanguageCSV.GetCString(s, langId); return replacementDic == null ? str : replacementDic.Aggregate(str, (current, rd) => current.Replace(rd.Key, rd.Value)); diff --git a/NextShip/Manager/NextPlayerManager.cs b/NextShip/Manager/NextPlayerManager.cs index 111c212..35eff9f 100644 --- a/NextShip/Manager/NextPlayerManager.cs +++ b/NextShip/Manager/NextPlayerManager.cs @@ -24,9 +24,13 @@ public NextInfo CreateOrGetSetPlayerInfo(PlayerControl player) info.IsHost = AmongUsClient.Instance.HostId == info.clientId; info.IsLocal = CachedPlayer.LocalPlayer?.PlayerControl == player; return info; - bool IsInfo(NextInfo nextInfo) => nextInfo.PlayerControl == player || nextInfo.PlayerId == player.PlayerId; + + bool IsInfo(NextInfo nextInfo) + { + return nextInfo.PlayerControl == player || nextInfo.PlayerId == player.PlayerId; + } } - + public NextInfo CreateOrGetSetPlayerInfo(ClientData data) { var info = PlayerInfos.Exists(IsInfo) ? PlayerInfos.First(IsInfo) : new NextInfo(); @@ -42,16 +46,22 @@ public NextInfo CreateOrGetSetPlayerInfo(ClientData data) info.IsHost = AmongUsClient.Instance.HostId == data.Id; info.IsLocal = CachedPlayer.LocalPlayer?.PlayerControl == data.Character; return info; - bool IsInfo(NextInfo nextInfo) => nextInfo.clientId == data.Id || nextInfo.PlayerControl == data.Character; + + bool IsInfo(NextInfo nextInfo) + { + return nextInfo.clientId == data.Id || nextInfo.PlayerControl == data.Character; + } } public void InitPlayer(PlayerControl player) { - } - public bool IsHost(PlayerControl player) => PlayerInfos.First(n => n.PlayerControl == player).IsHost; - + public bool IsHost(PlayerControl player) + { + return PlayerInfos.First(n => n.PlayerControl == player).IsHost; + } + public bool TryGetPlayer(PlayerControl player, out NextInfo? info) { diff --git a/NextShip/Manager/NextRoleManager.cs b/NextShip/Manager/NextRoleManager.cs index 9cac9bc..83c1eab 100644 --- a/NextShip/Manager/NextRoleManager.cs +++ b/NextShip/Manager/NextRoleManager.cs @@ -26,11 +26,6 @@ public void AssignRole(PlayerControl player, IRole role) { } - public void CheckRoles() - { - - } - public void Clear() { } @@ -42,6 +37,10 @@ public void SetCreator(IRoleCreator creator) CurrentCreator = creator; } + public void CheckRoles() + { + } + public FastCreator FastGetCreator() { if (CurrentCreator is FastCreator creator) diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index f938fab..eb69218 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -25,7 +25,7 @@ - + @@ -40,7 +40,7 @@ - + diff --git a/NextShip/Options/Patches/OptionsConsolePatch.cs b/NextShip/Options/Patches/OptionsConsolePatch.cs index 5e1b1f3..a9978f2 100644 --- a/NextShip/Options/Patches/OptionsConsolePatch.cs +++ b/NextShip/Options/Patches/OptionsConsolePatch.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using HarmonyLib; - using NextShip.UI.Module; using UnityEngine; diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs index 8969d2d..5766e6b 100644 --- a/NextShip/Patches/PlayerPatch.cs +++ b/NextShip/Patches/PlayerPatch.cs @@ -11,6 +11,8 @@ namespace NextShip.Patches; [Harmony] public static class PlayerPatch { + public static readonly List AllPlayerVersionInfos = []; + [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.Awake))] [HarmonyPostfix] public static void PlayerControlAwake_PostfixPatch(PlayerControl __instance) @@ -22,28 +24,30 @@ public static void PlayerControlAwake_PostfixPatch(PlayerControl __instance) [HarmonyPatch(typeof(GameData), nameof(GameData.AddPlayer))] [HarmonyPostfix] - public static void GameDataAddPlayer_Postfix([HarmonyArgument(0)] PlayerControl pc) => + public static void GameDataAddPlayer_Postfix([HarmonyArgument(0)] PlayerControl pc) + { NextPlayerManager.Instance.CreateOrGetSetPlayerInfo(pc); + } [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.GetOrCreateClient))] [HarmonyPostfix] - public static void GetOrCreateClient_Postfix(ClientData __result) => + public static void GetOrCreateClient_Postfix(ClientData __result) + { NextPlayerManager.Instance.CreateOrGetSetPlayerInfo(__result); + } - public static readonly List AllPlayerVersionInfos = []; - [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerJoined))] [HarmonyPostfix] public static void OnPlayerJoined(AmongUsClient __instance) { - var writer = FastRpcWriter.StartNew(); - writer.SetRpcCallId((byte)SystemRPCFlag.VersionShare); - writer.SetTargetObjectId(PlayerControl.LocalPlayer.NetId); - writer.SetSendOption(SendOption.Reliable); - writer.StartSendAllRPCWriter(); - writer.Write(PlayerControl.LocalPlayer.PlayerId); - Main.Version.Write(writer); - writer.Write(Main.BepInExVersion); + var writer = FastRpcWriter.StartNew(); + writer.SetRpcCallId((byte)SystemRPCFlag.VersionShare); + writer.SetTargetObjectId(PlayerControl.LocalPlayer.NetId); + writer.SetSendOption(SendOption.Reliable); + writer.StartSendAllRPCWriter(); + writer.Write(PlayerControl.LocalPlayer.PlayerId); + Main.Version.Write(writer); + writer.Write(Main.BepInExVersion); } [FastReadAdd((byte)SystemRPCFlag.VersionShare)] @@ -56,4 +60,4 @@ public static void OnVersionShare(MessageReader reader) } } -public record PlayerVersionInfo(PlayerControl Player,ShipVersion Version,string BepInExVersion); \ No newline at end of file +public record PlayerVersionInfo(PlayerControl Player, ShipVersion Version, string BepInExVersion); \ No newline at end of file diff --git a/NextShip/Patches/RoleAssignmentPatch.cs b/NextShip/Patches/RoleAssignmentPatch.cs index 1ef2522..6f34bf4 100644 --- a/NextShip/Patches/RoleAssignmentPatch.cs +++ b/NextShip/Patches/RoleAssignmentPatch.cs @@ -36,20 +36,22 @@ public static void SelectRoles_Postfix(RoleManager __instance) { GetPlayerRoleS(out var C, out var I); var CAssign = new Queue(C); - var IAssign = new Queue(I); + var IAssign = new Queue(I); _StartAssign: - var player = (CAssign.Count > 0 ? CAssign : IAssign).Dequeue(); - var _creator = _nextRoleManager.FastGetCreator(); - var role = _creator.GetAssign(); - _nextRoleManager.AssignRole(player, role); - if (IAssign.Count > 0) - goto _StartAssign; + var player = (CAssign.Count > 0 ? CAssign : IAssign).Dequeue(); + var _creator = _nextRoleManager.FastGetCreator(); + var role = _creator.GetAssign(); + _nextRoleManager.AssignRole(player, role); + if (IAssign.Count > 0) + goto _StartAssign; } private static void GetPlayerRoleS(out PlayerControl[] C, out PlayerControl[] I) { - var ListC = CachedPlayer.AllPlayers.Where(n => n?.Data.Role.Role == RoleTypes.Crewmate).Select(n =>n.PlayerControl); - var ListI = CachedPlayer.AllPlayers.Where(n => n?.Data.Role.Role == RoleTypes.Impostor).Select(n => n.PlayerControl); + var ListC = CachedPlayer.AllPlayers.Where(n => n?.Data.Role.Role == RoleTypes.Crewmate) + .Select(n => n.PlayerControl); + var ListI = CachedPlayer.AllPlayers.Where(n => n?.Data.Role.Role == RoleTypes.Impostor) + .Select(n => n.PlayerControl); C = ListC.ToArray(); I = ListI.ToArray(); } diff --git a/NextShip/Roles/FastCreator.cs b/NextShip/Roles/FastCreator.cs index 591e67f..5814c3d 100644 --- a/NextShip/Roles/FastCreator.cs +++ b/NextShip/Roles/FastCreator.cs @@ -8,12 +8,11 @@ namespace NextShip.Roles; public class FastCreator : IRoleCreator { - public readonly List AllRole = []; - private readonly NextRoleManager _RoleManager = Main._Service.Get(); + public readonly List AllRole = []; private List enableRoles = []; - + public void Dispose() { Clear(); @@ -44,6 +43,6 @@ public IRole GetAssign() private void SetList() { - enableRoles= _RoleManager.Roles.Where(n => n.EnableAssign).ToList(); + enableRoles = _RoleManager.Roles.Where(n => n.EnableAssign).ToList(); } } \ No newline at end of file diff --git a/NextShip/main.cs b/NextShip/main.cs index 33e4976..ddf8872 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -78,6 +78,7 @@ public override void Load() SteamExtension.UseSteamIdFile(); ReactorExtension.UseReactorHandshake(); + ModStampExtension.UseModStamp(); FastRPCExtension.UseFastRPC(); FastRpcReaderPatch.AddFormAssembly(RootAssembly); @@ -112,9 +113,10 @@ private static void InitPlugins() manager.InitPlugins(); OnBuilder += manager.OnServiceBuild; } - + public static void AddOnBuild() - {} + { + } private static void CreateService() { From aaa5cf93c3c63f6f012d7cdeae928284a2f70894 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Sat, 17 Feb 2024 21:45:58 +0800 Subject: [PATCH 24/29] E --- NSLangAnalyzer/Constants.cs | 14 +++ NSLangAnalyzer/FileFinder.cs | 77 +++++++++++++ NSLangAnalyzer/MainAnalyzer.cs | 14 +++ NSLangAnalyzer/NSLException.cs | 16 +++ NSLangAnalyzer/NSLangAnalyzer.csproj | 9 ++ NextShip.Api/Attributes/FastAddRole.cs | 22 ++++ NextShip.Api/Attributes/NextEventListener.cs | 19 ++++ NextShip.Api/Attributes/ServiceAdd.cs | 43 +++++++- NextShip.Api/Bases/NKeyBind.cs | 21 +++- NextShip.Api/Bases/NextInfo.cs | 2 + NextShip.Api/Extension/CrowdedExtension.cs | 13 +++ NextShip.Api/Extension/ModStampExtension.cs | 2 +- .../Extension/PasswordVerification.cs | 1 + NextShip.Api/Extension/SteamExtension.cs | 7 +- .../{ILoadManager.cs => IBotManager.cs} | 5 +- NextShip.Api/Interfaces/IEventListener.cs | 4 +- NextShip.Api/Interfaces/ILang.cs | 2 + NextShip.Api/Interfaces/ILangManager.cs | 4 +- NextShip.Api/Interfaces/INextButton.cs | 6 + NextShip.Api/Interfaces/INextButtonManager.cs | 6 + NextShip.Api/Interfaces/INextEvent.cs | 2 + NextShip.Api/Interfaces/IRole.cs | 2 +- NextShip.Api/Logs/Log.cs | 32 +++--- NextShip.Api/NextShip.Api.csproj | 3 +- NextShip.Api/RPCs/FastRpcWriter.cs | 22 ++++ NextShip.Api/Roles/SimpleRoleInfo.cs | 57 +++++++--- NextShip.Api/Services/DependentService.cs | 3 +- NextShip.Api/Utilities/CachedPlayer.cs | 10 +- NextShip.Api/Utilities/GithubAnalyzer.cs | 17 ++- NextShip.Api/Utils/ListUtils.cs | 6 + NextShip.Api/Utils/MethodUtils.cs | 21 ++++ NextShip.Api/Utils/ServerUtils.cs | 31 ++++++ .../BuildInfoGenerator.cs | 13 +++ ...angSourceGenerator.cs => LangGenerator.cs} | 2 +- .../NextShip.SourceGenerator.csproj | 5 + NextShip.sln | 6 + NextShip/Buttons/ButtonBase.cs | 31 ------ NextShip/Buttons/ButtonsManager.cs | 15 --- NextShip/Buttons/RoleButtonBase.cs | 9 -- NextShip/DIY/Plugins/PluginLoadService.cs | 2 +- NextShip/DIY/Plugins/PluginManager.cs | 2 +- NextShip/Manager/EventManager.cs | 6 + NextShip/Manager/InstanceManager.cs | 30 +++++ NextShip/Manager/NextBotManager.cs | 8 ++ NextShip/Manager/NextButtonsManager.cs | 7 ++ NextShip/Manager/NextKeyBindManager.cs | 104 ++++++++++++++++++ NextShip/Manager/NextLangManager.cs | 23 ++++ NextShip/Manager/NextManager.cs | 14 +-- NextShip/Manager/NextScreenManager.cs | 8 ++ NextShip/NextEvents/HudManagerUpdateEvent.cs | 22 ++++ NextShip/Patches/AnnouncementPatch.cs | 4 +- NextShip/Patches/EmergencyMinigamePatch.cs | 36 ------ NextShip/Patches/ExileControllPatch.cs | 55 --------- NextShip/Patches/GameStartManagerPatch.cs | 41 ------- NextShip/Patches/IntroPatch.cs | 55 ++------- NextShip/Patches/PlayerPhysicsPatch.cs | 2 +- NextShip/Patches/ServerPath.cs | 42 ------- NextShip/Patches/UpdatePatch.cs | 11 +- NextShip/Roles/Crewmate/Sheriff.cs | 44 ++++++++ NextShip/main.cs | 29 +++-- 60 files changed, 765 insertions(+), 354 deletions(-) create mode 100644 NSLangAnalyzer/Constants.cs create mode 100644 NSLangAnalyzer/FileFinder.cs create mode 100644 NSLangAnalyzer/MainAnalyzer.cs create mode 100644 NSLangAnalyzer/NSLException.cs create mode 100644 NSLangAnalyzer/NSLangAnalyzer.csproj create mode 100644 NextShip.Api/Attributes/FastAddRole.cs create mode 100644 NextShip.Api/Attributes/NextEventListener.cs create mode 100644 NextShip.Api/Extension/CrowdedExtension.cs rename NextShip.Api/Interfaces/{ILoadManager.cs => IBotManager.cs} (52%) create mode 100644 NextShip.Api/Interfaces/INextButton.cs create mode 100644 NextShip.Api/Interfaces/INextButtonManager.cs create mode 100644 NextShip.Api/Utils/ServerUtils.cs create mode 100644 NextShip.SourceGenerator/BuildInfoGenerator.cs rename NextShip.SourceGenerator/{LangSourceGenerator.cs => LangGenerator.cs} (77%) delete mode 100644 NextShip/Buttons/ButtonBase.cs delete mode 100644 NextShip/Buttons/ButtonsManager.cs delete mode 100644 NextShip/Buttons/RoleButtonBase.cs create mode 100644 NextShip/Manager/InstanceManager.cs create mode 100644 NextShip/Manager/NextBotManager.cs create mode 100644 NextShip/Manager/NextButtonsManager.cs create mode 100644 NextShip/Manager/NextKeyBindManager.cs create mode 100644 NextShip/Manager/NextLangManager.cs create mode 100644 NextShip/Manager/NextScreenManager.cs create mode 100644 NextShip/NextEvents/HudManagerUpdateEvent.cs delete mode 100644 NextShip/Patches/EmergencyMinigamePatch.cs delete mode 100644 NextShip/Patches/ExileControllPatch.cs delete mode 100644 NextShip/Patches/GameStartManagerPatch.cs delete mode 100644 NextShip/Patches/ServerPath.cs create mode 100644 NextShip/Roles/Crewmate/Sheriff.cs diff --git a/NSLangAnalyzer/Constants.cs b/NSLangAnalyzer/Constants.cs new file mode 100644 index 0000000..b861dfc --- /dev/null +++ b/NSLangAnalyzer/Constants.cs @@ -0,0 +1,14 @@ +global using static NSLangAnalyzer.Constants; + +namespace NSLangAnalyzer; + +public static class Constants +{ + public const string FileSuffix = "NS"; + + public const string FileSuffix2 = "NSL"; + + public const string FileSuffix3 = "ns"; + + public const string FileSuffix4 = "nsl"; +} \ No newline at end of file diff --git a/NSLangAnalyzer/FileFinder.cs b/NSLangAnalyzer/FileFinder.cs new file mode 100644 index 0000000..0725ef0 --- /dev/null +++ b/NSLangAnalyzer/FileFinder.cs @@ -0,0 +1,77 @@ +namespace NSLangAnalyzer; + +internal class FileFinder +{ + private static string[] Extensions = [FileSuffix, FileSuffix2, FileSuffix3 , FileSuffix4]; + private readonly List _fileInfos = []; + private readonly List _readInfos = []; + + public FileFinder ReadFiles() + { + if (_fileInfos.Count == 0) + { + throw new NSLException("FileInfo = 0"); + } + + foreach (var info in _fileInfos) + { + using var readStream = info.OpenRead(); + using var reader = new StreamReader(readStream); + var strings = string.Empty; + + var OneLine = reader.ReadLine(); + if (OneLine == null || !OneLine.StartsWith('[') || !OneLine.EndsWith(']')) + { + continue; + } + + var texts = OneLine + .Replace("[", string.Empty) + .Replace("]", string.Empty) + .Split(":"); + + var name = texts[0]; + var author = texts[1]; + + var line = reader.ReadLine(); + while (line != null) + { + strings += line; + line = reader.ReadLine(); + } + + _readInfos.Add(new ReadInfo + { + Info = info, + ReadStrings = strings, + name = name, + author = author + }); + } + + return this; + } + + public FileFinder Get(DirectoryInfo directory) + { + _readInfos.Clear(); + _fileInfos.AddRange(directory.GetFiles().Where(isFile)); + return this; + } + + private static bool isFile(FileInfo fileInfo) + { + return Extensions.Any(varExtension => fileInfo.Extension == "." + varExtension); + } + + private class ReadInfo + { + public string? ReadStrings { get; set; } + + public FileInfo? Info { get; set; } + + public string? name { get; set; } + + public string? author { get; set; } + } +} \ No newline at end of file diff --git a/NSLangAnalyzer/MainAnalyzer.cs b/NSLangAnalyzer/MainAnalyzer.cs new file mode 100644 index 0000000..e69ea15 --- /dev/null +++ b/NSLangAnalyzer/MainAnalyzer.cs @@ -0,0 +1,14 @@ +namespace NSLangAnalyzer; + +public class MainAnalyzer +{ + private readonly FileFinder _Finder = new(); + + public void Find(string path) + { + if (!Directory.Exists(path)) + throw new NSLException("不存在指定文件夹"); + + var finder = _Finder.Get(new DirectoryInfo(path)).ReadFiles(); + } +} \ No newline at end of file diff --git a/NSLangAnalyzer/NSLException.cs b/NSLangAnalyzer/NSLException.cs new file mode 100644 index 0000000..5f5b199 --- /dev/null +++ b/NSLangAnalyzer/NSLException.cs @@ -0,0 +1,16 @@ +namespace NSLangAnalyzer; + +public class NSLException : Exception +{ + public NSLException() : base() + { + } + + public NSLException(string message) : base(message) + { + } + + public NSLException(string message, Exception exception) : base(message, exception) + { + } +} \ No newline at end of file diff --git a/NSLangAnalyzer/NSLangAnalyzer.csproj b/NSLangAnalyzer/NSLangAnalyzer.csproj new file mode 100644 index 0000000..3a63532 --- /dev/null +++ b/NSLangAnalyzer/NSLangAnalyzer.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/NextShip.Api/Attributes/FastAddRole.cs b/NextShip.Api/Attributes/FastAddRole.cs new file mode 100644 index 0000000..bd493fe --- /dev/null +++ b/NextShip.Api/Attributes/FastAddRole.cs @@ -0,0 +1,22 @@ +using System.Reflection; +using NextShip.Api.Interfaces; + +namespace NextShip.Api.Attributes; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor)] +public class FastAddRole : Attribute +{ + public static void Registration(IRoleManager _roleManager, Assembly assembly) + { + var Types = assembly.GetTypes(); + + foreach (var VarType in Types.Where(n => n.Is() && n.GetInterface(nameof(IRole)) != null)) + { + var constructorInfos = VarType.GetConstructors().Where(n => n.Is()); + foreach (var variableConstructorInfo in constructorInfos) + { + _roleManager.Register(variableConstructorInfo.Invoke(null, null) as IRole); + } + } + } +} \ No newline at end of file diff --git a/NextShip.Api/Attributes/NextEventListener.cs b/NextShip.Api/Attributes/NextEventListener.cs new file mode 100644 index 0000000..d7cd092 --- /dev/null +++ b/NextShip.Api/Attributes/NextEventListener.cs @@ -0,0 +1,19 @@ +using System.Reflection; +using NextShip.Api.Interfaces; + +namespace NextShip.Api.Attributes; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] +public sealed class NextEventListener : Attribute +{ + + public static void RegisterFormAssembly(Assembly assembly, IEventManager manager) + { + + } + + public static void RegisterFormService(IServiceProvider provider, IEventManager manager) + { + + } +} \ No newline at end of file diff --git a/NextShip.Api/Attributes/ServiceAdd.cs b/NextShip.Api/Attributes/ServiceAdd.cs index 7600373..0af7c91 100644 --- a/NextShip.Api/Attributes/ServiceAdd.cs +++ b/NextShip.Api/Attributes/ServiceAdd.cs @@ -1,21 +1,52 @@ using System.Reflection; +using HarmonyLib; namespace NextShip.Api.Attributes; -[AttributeUsage(AttributeTargets.Field)] +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Class | AttributeTargets.Method)] public sealed class ServiceAddAttribute : Attribute { + private readonly object _instance; + + public ServiceAddAttribute() + { + } + + public ServiceAddAttribute(object instance) + { + _instance = instance; + } + + public static void Registration(IServiceProvider provider, Assembly assembly) { var Fields = assembly.GetFieldInfos(); - - foreach (var VarField in Fields.Where(n => n.Is())) + var methods = assembly.GetMethodInfos(); + var constructors = assembly.GetConstructorInfos(); + + foreach (var Var in Fields.Where(n => n.Is())) { - if (!VarField.IsStatic) continue; + var instance = Var.GetCustomAttribute()?._instance; + if (!Var.IsStatic && instance == null) continue; - var type = VarField.FieldType; + var type = Var.FieldType; var value = provider.GetService(type); - VarField.SetValue(null, value); + Var.SetValue(null, value); + } + + foreach (var Var in methods.Where(n => n.Is())) + { + var instance = Var.GetCustomAttribute()?._instance; + if (!Var.IsStatic && instance == null) continue; + + var arguments = Var.GetGenericArguments().Select(provider.GetService).ToArray(); + _ = Var.Invoke(instance, arguments); + } + + foreach (var Var in constructors.Where(n => n.Is())) + { + var arguments = Var.GetGenericArguments().Select(provider.GetService).ToArray(); + _ = Var.Invoke(null, arguments); } } } \ No newline at end of file diff --git a/NextShip.Api/Bases/NKeyBind.cs b/NextShip.Api/Bases/NKeyBind.cs index 656ef1c..27f7f5a 100644 --- a/NextShip.Api/Bases/NKeyBind.cs +++ b/NextShip.Api/Bases/NKeyBind.cs @@ -1,3 +1,22 @@ +using UnityEngine; + namespace NextShip.Api.Bases; -public class NKeyBind; \ No newline at end of file +public class NKeyBind +{ + /// + /// 0 last + /// + public int Priority; + + /// + /// 1 key or 2 keys or 3 + /// + public int Mode; + + public KeyCode[] keys; + + public int KeyCount; + + public Action _Action; +} \ No newline at end of file diff --git a/NextShip.Api/Bases/NextInfo.cs b/NextShip.Api/Bases/NextInfo.cs index 2df4f69..e68883b 100644 --- a/NextShip.Api/Bases/NextInfo.cs +++ b/NextShip.Api/Bases/NextInfo.cs @@ -23,6 +23,8 @@ public record NextInfo public PlayerControl PlayerControl; + public PlayerPhysics PlayerPhysics; + public byte PlayerId; public GameData.PlayerInfo PlayerInfo; diff --git a/NextShip.Api/Extension/CrowdedExtension.cs b/NextShip.Api/Extension/CrowdedExtension.cs new file mode 100644 index 0000000..478ed22 --- /dev/null +++ b/NextShip.Api/Extension/CrowdedExtension.cs @@ -0,0 +1,13 @@ +namespace NextShip.Api.Extension; + +public static class CrowdedExtension +{ + private static bool Started; + + public static void UseCrowded() + { + if (Started) return; + + Started = true; + } +} \ No newline at end of file diff --git a/NextShip.Api/Extension/ModStampExtension.cs b/NextShip.Api/Extension/ModStampExtension.cs index 3c6ff83..9d05663 100644 --- a/NextShip.Api/Extension/ModStampExtension.cs +++ b/NextShip.Api/Extension/ModStampExtension.cs @@ -15,7 +15,7 @@ public static void UseModStamp() { if (scene.name == "MainMenu") ModManager.Instance.ShowModStamp(); })); - + Info(MethodUtils.GetVoidName()!); Added = true; } } \ No newline at end of file diff --git a/NextShip.Api/Extension/PasswordVerification.cs b/NextShip.Api/Extension/PasswordVerification.cs index a032d48..c58536d 100644 --- a/NextShip.Api/Extension/PasswordVerification.cs +++ b/NextShip.Api/Extension/PasswordVerification.cs @@ -18,6 +18,7 @@ public static void Write(ref MessageWriter writer) { if (Password == 0) return; var messageString = $"Password:{Password.ToString()}"; + Info(messageString); writer.Write(messageString); } } \ No newline at end of file diff --git a/NextShip.Api/Extension/SteamExtension.cs b/NextShip.Api/Extension/SteamExtension.cs index 18e7062..6e9a964 100644 --- a/NextShip.Api/Extension/SteamExtension.cs +++ b/NextShip.Api/Extension/SteamExtension.cs @@ -12,6 +12,11 @@ public static void UseSteamIdFile() { var path = Paths.GameRootPath.CombinePath(file_Name); if (!File.Exists(path)) - File.WriteAllText(path, Among_Us_SteamId); + File.WriteAllText(path!, Among_Us_SteamId); + else + { + return; + } + Info("Use steam_appid.txt"); } } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILoadManager.cs b/NextShip.Api/Interfaces/IBotManager.cs similarity index 52% rename from NextShip.Api/Interfaces/ILoadManager.cs rename to NextShip.Api/Interfaces/IBotManager.cs index 8033f9e..f622618 100644 --- a/NextShip.Api/Interfaces/ILoadManager.cs +++ b/NextShip.Api/Interfaces/IBotManager.cs @@ -1,3 +1,6 @@ namespace NextShip.Api.Interfaces; -public interface ILoadManager; \ No newline at end of file +public class IBotManager +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IEventListener.cs b/NextShip.Api/Interfaces/IEventListener.cs index 83cc51d..1dbccb2 100644 --- a/NextShip.Api/Interfaces/IEventListener.cs +++ b/NextShip.Api/Interfaces/IEventListener.cs @@ -2,7 +2,7 @@ namespace NextShip.Api.Interfaces; public interface IEventListener { - public void On(string name); + public void On(string name) {} - public void On(INextEvent @event); + public void On(INextEvent @event) {} } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILang.cs b/NextShip.Api/Interfaces/ILang.cs index 3545917..87e3acf 100644 --- a/NextShip.Api/Interfaces/ILang.cs +++ b/NextShip.Api/Interfaces/ILang.cs @@ -5,6 +5,8 @@ public interface ILang public SupportedLangs LangId { get; protected set; } public string LangName { get; set; } + + public string Author { get; set; } public string GetString(string Key); diff --git a/NextShip.Api/Interfaces/ILangManager.cs b/NextShip.Api/Interfaces/ILangManager.cs index bdee486..5bc0a08 100644 --- a/NextShip.Api/Interfaces/ILangManager.cs +++ b/NextShip.Api/Interfaces/ILangManager.cs @@ -6,5 +6,7 @@ public interface ILangManager public void UnRegisterLang(ILang lang); - public void SetLang(SupportedLangs langId, ILang lang); + public void Set(SupportedLangs langId, ILang lang); + + public void SetCurrentLang(SupportedLangs langId); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextButton.cs b/NextShip.Api/Interfaces/INextButton.cs new file mode 100644 index 0000000..eda903b --- /dev/null +++ b/NextShip.Api/Interfaces/INextButton.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public class INextButton +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextButtonManager.cs b/NextShip.Api/Interfaces/INextButtonManager.cs new file mode 100644 index 0000000..fbc67f0 --- /dev/null +++ b/NextShip.Api/Interfaces/INextButtonManager.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public class INextButtonManager +{ + +} \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextEvent.cs b/NextShip.Api/Interfaces/INextEvent.cs index f855402..1ca8331 100644 --- a/NextShip.Api/Interfaces/INextEvent.cs +++ b/NextShip.Api/Interfaces/INextEvent.cs @@ -3,6 +3,8 @@ namespace NextShip.Api.Interfaces; public interface INextEvent { public string EventName { get; set; } + + public int Id { get; set; } public void OnRegister(IEventManager eventManager); diff --git a/NextShip.Api/Interfaces/IRole.cs b/NextShip.Api/Interfaces/IRole.cs index b6f836e..73cf174 100644 --- a/NextShip.Api/Interfaces/IRole.cs +++ b/NextShip.Api/Interfaces/IRole.cs @@ -1,6 +1,6 @@ namespace NextShip.Api.Interfaces; -public interface IRole +public interface IRole : IDisposable { public Type RoleBaseType { get; set; } public Type RoleType { get; set; } diff --git a/NextShip.Api/Logs/Log.cs b/NextShip.Api/Logs/Log.cs index 3484886..a5c8e4f 100644 --- a/NextShip.Api/Logs/Log.cs +++ b/NextShip.Api/Logs/Log.cs @@ -22,12 +22,18 @@ private Log(ManualLogSource logSource) { LogSource = logSource; ConsoleWriter = ConsoleManager.ConsoleStream; - Instance = this; + _Instance = this; + } + + private Log() : this(new ManualLogSource("NextShip.Api")) + { } public ManualLogSource LogSource { get; private set; } - public static Log? Instance { get; set; } + private static Log? _Instance; + + public static Log Instance => _Instance ?? new Log(); public void CreateDiskLog(string name, string? path = null) @@ -81,7 +87,7 @@ public Stream GetDiskLogStream(string name, string? path = null, bool outTime = { if (CreateEd) { - Instance?.Set(logSource); + _Instance?.Set(logSource); return Instance; } @@ -98,7 +104,7 @@ private void Set(ManualLogSource logSource) internal void SendToFile(string? tag, string? filename, string text, LogLevel level = LogLevel.Info) { - var logger = Instance?.LogSource; + var logger = Instance.LogSource; var t = DateTime.Now.ToString("HH:mm:ss"); @@ -115,31 +121,31 @@ internal void SendToFile(string? tag, string? filename, string text, LogLevel le switch (level) { case LogLevel.Info: - logger?.LogInfo(log_text); + logger.LogInfo(log_text); break; case LogLevel.Warning: - logger?.LogWarning(log_text); + logger.LogWarning(log_text); break; case LogLevel.Error: - logger?.LogError(log_text); + logger.LogError(log_text); break; case LogLevel.Fatal: - logger?.LogFatal(log_text); + logger.LogFatal(log_text); break; case LogLevel.Message: - logger?.LogMessage(log_text); + logger.LogMessage(log_text); break; case LogLevel.Debug: - logger?.LogDebug(log_text); + logger.LogDebug(log_text); break; case LogLevel.None: - logger?.LogInfo(log_text); + logger.LogInfo(log_text); break; case LogLevel.All: break; default: - logger?.LogWarning("Error:Invalid LogLevel"); - logger?.LogInfo(log_text); + logger.LogWarning("Error:Invalid LogLevel"); + logger.LogInfo(log_text); break; } } diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index 167db34..0dbc5fb 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -28,7 +28,8 @@ - + + diff --git a/NextShip.Api/RPCs/FastRpcWriter.cs b/NextShip.Api/RPCs/FastRpcWriter.cs index f5ae6e9..35ae800 100644 --- a/NextShip.Api/RPCs/FastRpcWriter.cs +++ b/NextShip.Api/RPCs/FastRpcWriter.cs @@ -106,6 +106,8 @@ public void Set(SendOption option = SendOption.None, byte callId = byte.MaxValue if (objId != null) targetObjectId = (uint)objId; + + DebugInfo($"Set CallId{CallId} SendTargetId{targetId} TargetObjectId{targetObjectId}"); } public void Clear() @@ -113,47 +115,56 @@ public void Clear() if (writer == null) return; Recycle(); writer = null; + DebugInfo("Clear"); } public void Write(bool value) { writer?.Write(value); + DebugInfo($"Write bool {value}"); } public void Write(int value) { writer?.Write(value); + DebugInfo($"Write int {value}"); } public void Write(float value) { writer?.Write(value); + DebugInfo($"Write float {value}"); } public void Write(string value) { writer?.Write(value); + DebugInfo($"Write string {value}"); } public void Write(byte value) { writer?.Write(value); + DebugInfo($"Write byte {value}"); } public void WritePacked(int value) { writer?.WritePacked(value); + DebugInfo($"WritePacked int {value}"); } public void WritePacked(uint value) { writer?.WritePacked(value); + DebugInfo($"WritePacked uint {value}"); } private void StartDataAllMessage() { StartMessage((byte)MessageFlags.DataAll); Write(AmongUsClient.Instance.GameId); + DebugInfo("StartToALLMessage"); } private void StartDataToPlayerMessage() @@ -161,6 +172,7 @@ private void StartDataToPlayerMessage() StartMessage((byte)MessageFlags.DataToPlayer); Write(AmongUsClient.Instance.GameId); WritePacked(SendTargetId); + DebugInfo("StartToPlayerMessage"); } private void StartRPCMessage() @@ -168,28 +180,33 @@ private void StartRPCMessage() StartMessage((byte)DataFlags.Rpc); WritePacked(targetObjectId); Write(CallId); + DebugInfo("StartRpcMessage"); } public void StartMessage(byte flag) { writer?.StartMessage(flag); msgCount++; + DebugInfo($"StartMessage {flag}"); } public void EndMessage() { writer?.EndMessage(); msgCount--; + DebugInfo("EndMessage"); } public void EndAllMessage() { while (msgCount > 0) EndMessage(); + DebugInfo("EndAllMessage"); } public void Recycle() { writer?.Recycle(); + DebugInfo("Recycle"); } public void RPCSend() @@ -208,4 +225,9 @@ public void Send() { AmongUsClient.Instance.connection.Send(writer); } + + private void DebugInfo(string info) + { + Debug($"[FastWriter] CallId{CallId} sendOption{Option} msgCout{msgCount} || [FastWriterInfo]:{info}"); + } } \ No newline at end of file diff --git a/NextShip.Api/Roles/SimpleRoleInfo.cs b/NextShip.Api/Roles/SimpleRoleInfo.cs index 4978a7c..4719870 100644 --- a/NextShip.Api/Roles/SimpleRoleInfo.cs +++ b/NextShip.Api/Roles/SimpleRoleInfo.cs @@ -1,24 +1,51 @@ +using System.Text.Json.Serialization; using UnityEngine; namespace NextShip.Api.Roles; -public sealed class SimpleRoleInfo( - RoleId id, - Color color, - RoleTeam team, - RoleType type, - string roleStringId, - string roleName, - int roleIntId) +public sealed class SimpleRoleInfo { - public string Name = roleName; - public Color RoleColor = color; - public RoleId roleId = id; - public int roleIntId = roleIntId; - public string RoleStringId = roleStringId; - public RoleTeam roleTeam = team; - public RoleType roleType = type; + [JsonPropertyName("Name"), JsonInclude] + public string Name { get; set; } + + [JsonPropertyName("Color"), JsonInclude] + public Color RoleColor { get; set; } + + [JsonPropertyName("EnumId"), JsonInclude] + public RoleId roleId { get; set; } + + [JsonPropertyName("IntId"), JsonInclude] + public int RoleIntId { get; set; } + + [JsonPropertyName("StringId"), JsonInclude] + public string RoleStringId { get; set; } + + [JsonPropertyName("Team"), JsonInclude] + public RoleTeam roleTeam { get; set; } + + [JsonPropertyName("Type"), JsonInclude] + public RoleType roleType { get; set; } + public SimpleRoleInfo() {} + + public SimpleRoleInfo( + RoleId id, + Color color, + RoleTeam team, + RoleType type, + string roleStringId, + string roleName, + int roleIntId) + { + Name = roleName; + RoleColor = color; + roleId = id; + roleTeam = team; + roleType = type; + RoleStringId = roleStringId; + RoleIntId = roleIntId; + } + public SimpleRoleInfo ( RoleId id, diff --git a/NextShip.Api/Services/DependentService.cs b/NextShip.Api/Services/DependentService.cs index 0376ad7..5858add 100644 --- a/NextShip.Api/Services/DependentService.cs +++ b/NextShip.Api/Services/DependentService.cs @@ -60,7 +60,8 @@ public void LoadDependent() { if (file.Extension == ".dll") { - Dlls.Add((Assembly.LoadFile(file.FullName), file)); + var assembly = Assembly.LoadFile(file.FullName); + Dlls.Add((assembly, file)); continue; } diff --git a/NextShip.Api/Utilities/CachedPlayer.cs b/NextShip.Api/Utilities/CachedPlayer.cs index a1f40f6..1aab9aa 100644 --- a/NextShip.Api/Utilities/CachedPlayer.cs +++ b/NextShip.Api/Utilities/CachedPlayer.cs @@ -9,9 +9,9 @@ namespace NextShip.Api.Utilities; // from TheOtherRole public class CachedPlayer { - public static readonly Dictionary PlayerIntPtrS = new(); - public static readonly List AllPlayers = new(); - public static CachedPlayer? LocalPlayer; + public static readonly Dictionary PlayerIntPtrS = new(); + public static readonly List AllPlayers = []; + public static CachedPlayer LocalPlayer = null!; public GameData.PlayerInfo Data = null!; public CustomNetworkTransform NetTransform = null!; public PlayerControl PlayerControl = null!; @@ -82,7 +82,7 @@ public static void AddCachedDataOnDeserialize() { foreach (var cachedPlayer in CachedPlayer.AllPlayers) { - cachedPlayer!.Data = cachedPlayer.PlayerControl.Data; + cachedPlayer.Data = cachedPlayer.PlayerControl.Data; cachedPlayer.PlayerId = cachedPlayer.PlayerControl.PlayerId; } } @@ -122,7 +122,7 @@ public static void SetLocalPlayer() var localPlayer = PlayerControl.LocalPlayer; if (!localPlayer) { - CachedPlayer.LocalPlayer = null; + CachedPlayer.LocalPlayer = null!; return; } diff --git a/NextShip.Api/Utilities/GithubAnalyzer.cs b/NextShip.Api/Utilities/GithubAnalyzer.cs index 3712367..5d57ec9 100644 --- a/NextShip.Api/Utilities/GithubAnalyzer.cs +++ b/NextShip.Api/Utilities/GithubAnalyzer.cs @@ -1,3 +1,18 @@ +#nullable enable namespace NextShip.Api.Utilities; -public class GithubAnalyzer; \ No newline at end of file +public class GithubAnalyzer(string RepoUrl) +{ + public GithubData GetData() + { + return new GithubData(); + } +} + +public class GithubData +{ + public T? Get(string key, T? def) where T : class + { + return null; + } +} \ No newline at end of file diff --git a/NextShip.Api/Utils/ListUtils.cs b/NextShip.Api/Utils/ListUtils.cs index e212e98..2052303 100644 --- a/NextShip.Api/Utils/ListUtils.cs +++ b/NextShip.Api/Utils/ListUtils.cs @@ -2,6 +2,12 @@ public static class ListUtils { + public static List GetSortList(this List list, Comparison comparison) + { + list.Sort(comparison); + return list; + } + public static List GetLists(this List list, int count) { var l = new List(); diff --git a/NextShip.Api/Utils/MethodUtils.cs b/NextShip.Api/Utils/MethodUtils.cs index 0d82c72..d9b6a56 100644 --- a/NextShip.Api/Utils/MethodUtils.cs +++ b/NextShip.Api/Utils/MethodUtils.cs @@ -58,4 +58,25 @@ public static List GetFieldInfos(this Assembly assembly) return types.SelectMany(varType => varType.GetFields()).ToList(); } + + public static List GetMethodInfos(this Assembly assembly) + { + var types = assembly.GetTypes(); + + return types.SelectMany(varType => varType.GetMethods()).ToList(); + } + + public static List GetConstructorInfos(this Assembly assembly) + { + var types = assembly.GetTypes(); + + return types.SelectMany(varType => varType.GetConstructors()).ToList(); + } + + public static List GetMemberInfos(this Assembly assembly) + { + var types = assembly.GetTypes(); + + return types.SelectMany(varType => varType.GetMembers()).ToList(); + } } \ No newline at end of file diff --git a/NextShip.Api/Utils/ServerUtils.cs b/NextShip.Api/Utils/ServerUtils.cs new file mode 100644 index 0000000..7f759e1 --- /dev/null +++ b/NextShip.Api/Utils/ServerUtils.cs @@ -0,0 +1,31 @@ +using HarmonyLib; + +namespace NextShip.Api.Utils; + +public static class ServerUtils +{ + public static void AddServer(IRegionInfo region) => + ServerManager.Instance.AddOrUpdateRegion(region); + + public static void AddServers(IEnumerable regionInfos) => + regionInfos.Do(ServerManager.Instance.AddOrUpdateRegion); + + public static List CreateHttpInfos(params (string ip, string name, ushort port, bool isHttps)[] Infos) + { + return Infos.Select(tuple => createHttpInfo(tuple.ip, tuple.name, tuple.port, tuple.isHttps)).ToList(); + } + + public static IRegionInfo createHttpInfo(string ip, string name, ushort port, bool isHttps = false) + { + var serverIp = isHttps ? "https://" : "http://" + ip; + var serverInfo = new ServerInfo(name, serverIp, port, false); + ServerInfo[] ServerInfo = [serverInfo]; + return new StaticHttpRegionInfo(name, StringNames.NoTranslation, ip, ServerInfo).CastFast(); + } + + public static bool IsVanilla(this IRegionInfo regionInfo) + { + return regionInfo.TranslateName is StringNames.ServerAS or StringNames.ServerEU or StringNames.ServerNA + or StringNames.ServerSA; + } +} \ No newline at end of file diff --git a/NextShip.SourceGenerator/BuildInfoGenerator.cs b/NextShip.SourceGenerator/BuildInfoGenerator.cs new file mode 100644 index 0000000..5de5940 --- /dev/null +++ b/NextShip.SourceGenerator/BuildInfoGenerator.cs @@ -0,0 +1,13 @@ +using Microsoft.CodeAnalysis; + +namespace NextShip.SourceGenerator; + +[Generator(LanguageNames.CSharp)] +public class BuildInfoGenerator : IIncrementalGenerator +{ + + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var Time = DateTime.Now.ToString("G").Replace(" ", "-").Replace("/", "-"); + } +} \ No newline at end of file diff --git a/NextShip.SourceGenerator/LangSourceGenerator.cs b/NextShip.SourceGenerator/LangGenerator.cs similarity index 77% rename from NextShip.SourceGenerator/LangSourceGenerator.cs rename to NextShip.SourceGenerator/LangGenerator.cs index 2b85a36..72d4137 100644 --- a/NextShip.SourceGenerator/LangSourceGenerator.cs +++ b/NextShip.SourceGenerator/LangGenerator.cs @@ -3,7 +3,7 @@ namespace NextShip.SourceGenerator; [Generator(LanguageNames.CSharp)] -public class LangSourceGenerator : IIncrementalGenerator +public class LangGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { diff --git a/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj b/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj index cf7d711..ed903e9 100644 --- a/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj +++ b/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj @@ -10,6 +10,11 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/NextShip.sln b/NextShip.sln index f59ab8e..4363a81 100644 --- a/NextShip.sln +++ b/NextShip.sln @@ -6,6 +6,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NextShip.Api", "NextShip.Ap EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NextShip.SourceGenerator", "NextShip.SourceGenerator\NextShip.SourceGenerator.csproj", "{68A4C610-376B-41F6-B242-DC13499BE7F8}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NSLangAnalyzer", "NSLangAnalyzer\NSLangAnalyzer.csproj", "{81EC6168-530F-45B4-92A5-5FFEB719C0A7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -24,5 +26,9 @@ Global {68A4C610-376B-41F6-B242-DC13499BE7F8}.Debug|Any CPU.Build.0 = Debug|Any CPU {68A4C610-376B-41F6-B242-DC13499BE7F8}.Release|Any CPU.ActiveCfg = Release|Any CPU {68A4C610-376B-41F6-B242-DC13499BE7F8}.Release|Any CPU.Build.0 = Release|Any CPU + {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/NextShip/Buttons/ButtonBase.cs b/NextShip/Buttons/ButtonBase.cs deleted file mode 100644 index 448a2f3..0000000 --- a/NextShip/Buttons/ButtonBase.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using UnityEngine; -using Object = UnityEngine.Object; - -namespace NextShip.Buttons; - -public class ButtonBase -{ - public Action Action; - public ActionButton ActionButton; - public GameObject ButtonGameObject; - public string name; - public string text; - - public ButtonBase() - { - ButtonGameObject = new GameObject(base.ToString()); - } - - public ButtonBase Create(string _name = "", GameObject cloneTarget = null, ActionButton _ActionButton = null, - Action action = null) - { - name = _name; - if (cloneTarget != null) ButtonGameObject = Object.Instantiate(cloneTarget); - - if (action != null) Action = action; - - if (_ActionButton != null) ActionButton = _ActionButton; - return this; - } -} \ No newline at end of file diff --git a/NextShip/Buttons/ButtonsManager.cs b/NextShip/Buttons/ButtonsManager.cs deleted file mode 100644 index 02c6677..0000000 --- a/NextShip/Buttons/ButtonsManager.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections.Generic; - -namespace NextShip.Buttons; - -public class ButtonsManager -{ - public List _AllButtons = []; - public List _AllRoleButton = []; - public static ButtonsManager Instance { get; private set; } - - public static ButtonsManager Get() - { - return Instance ??= new ButtonsManager(); - } -} \ No newline at end of file diff --git a/NextShip/Buttons/RoleButtonBase.cs b/NextShip/Buttons/RoleButtonBase.cs deleted file mode 100644 index dbc6d42..0000000 --- a/NextShip/Buttons/RoleButtonBase.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace NextShip.Buttons; - -public abstract class RoleButton : ButtonBase -{ - protected RoleButton() - { - Create(); - } -} \ No newline at end of file diff --git a/NextShip/DIY/Plugins/PluginLoadService.cs b/NextShip/DIY/Plugins/PluginLoadService.cs index e0b37fd..c1bc4bc 100644 --- a/NextShip/DIY/Plugins/PluginLoadService.cs +++ b/NextShip/DIY/Plugins/PluginLoadService.cs @@ -21,7 +21,7 @@ public PluginLoadService(PluginManager manager, IServiceProvider serviceProvider Load(); } - public void Load() + private void Load() { Info("开始加载插件"); foreach (var plugin in _pluginLoadInfos) diff --git a/NextShip/DIY/Plugins/PluginManager.cs b/NextShip/DIY/Plugins/PluginManager.cs index 6943223..e7ae1d2 100644 --- a/NextShip/DIY/Plugins/PluginManager.cs +++ b/NextShip/DIY/Plugins/PluginManager.cs @@ -19,7 +19,7 @@ public class PluginManager : Manager internal List PluginLoadInfos = []; private readonly List PluginPathS = []; - public List Plugins = []; + public readonly List Plugins = []; public void InitPlugins() diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs index dc693e1..fba74aa 100644 --- a/NextShip/Manager/EventManager.cs +++ b/NextShip/Manager/EventManager.cs @@ -14,6 +14,12 @@ public class EventManager : IEventManager private readonly List RegisterEvents = []; + public void CallEvent(T @event) where T : INextEvent + { + foreach (var _event in RegisterEvents.FindAll(n => n.EventName == @event.EventName && n is T)) + @event.Call(_event); + } + public void RegisterEvent(INextEvent @event) { @event.OnRegister(this); diff --git a/NextShip/Manager/InstanceManager.cs b/NextShip/Manager/InstanceManager.cs new file mode 100644 index 0000000..036c2e4 --- /dev/null +++ b/NextShip/Manager/InstanceManager.cs @@ -0,0 +1,30 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; + +namespace NextShip.Manager; + +public class InstanceManager +{ + public Dictionary Instances = new(); + + public void RegisterInstance(T instance) + { + if (instance != null) + RegisterInstance(typeof(T), instance); + else + { + Error("实例添加失败为空"); + } + } + + public void RegisterInstance(Type type, object obj) => Instances[type] = obj; + + public T? Get() where T : class => Get(typeof(T)) as T; + + public object? Get(Type type) + { + return Instances.FirstOrDefault(n => n.Key == type).Value; + } +} \ No newline at end of file diff --git a/NextShip/Manager/NextBotManager.cs b/NextShip/Manager/NextBotManager.cs new file mode 100644 index 0000000..d181405 --- /dev/null +++ b/NextShip/Manager/NextBotManager.cs @@ -0,0 +1,8 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public class NextBotManager : IBotManager +{ + +} \ No newline at end of file diff --git a/NextShip/Manager/NextButtonsManager.cs b/NextShip/Manager/NextButtonsManager.cs new file mode 100644 index 0000000..9aa95ce --- /dev/null +++ b/NextShip/Manager/NextButtonsManager.cs @@ -0,0 +1,7 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public class NextButtonsManager : INextButtonManager +{ +} \ No newline at end of file diff --git a/NextShip/Manager/NextKeyBindManager.cs b/NextShip/Manager/NextKeyBindManager.cs new file mode 100644 index 0000000..55584ac --- /dev/null +++ b/NextShip/Manager/NextKeyBindManager.cs @@ -0,0 +1,104 @@ +using System.Collections.Generic; +using System.Linq; +using NextShip.Api.Bases; +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public class NextKeyBindManager : IKeyBindManager +{ + private readonly List _keyBinds = []; + + private int CurrentPriority; + + private int CurrentMode; + + private int MaxPriority; + + private int MaxMode; + + public NextKeyBindManager(NextManager _nextManager) + { + _nextManager.OnUpdate += OnUpdate; + } + + public void AddBind(NKeyBind bind) + { + _keyBinds.Add(bind); + if (bind.Priority > MaxPriority) + { + MaxPriority = bind.Priority; + } + + if (bind.Mode > MaxMode) + { + MaxMode = bind.Mode; + } + } + + public void RemoveBind(NKeyBind bind) + { + _keyBinds.Remove(bind); +get: + if (_keyBinds.All(n => n.Priority != MaxPriority) && MaxPriority > 0) + { + MaxPriority--; + goto get; + } + + if (_keyBinds.All(n => n.Mode != MaxMode) && MaxMode > 1) + { + MaxMode--; + goto get; + } + } + + private void OnUpdate() + { + Start: + var binds = getNKeyBinds(); + foreach (var varBind in binds) + { + if (!InputKeyUtils.GetKeysDown(varBind.keys)) continue; + StartBind(varBind); + break; + } + + if (CanGet()) + { + goto Start; + } + } + + private List getNKeyBinds() + { + return _keyBinds.FindAll(n => n.Mode == CurrentMode).GetSortList((x, y) => sort(x.Priority, x.Priority)).FindAll(n => n.Priority == CurrentPriority); + + int sort(int x, int y) + { + return x.CompareTo(y); + } + } + + private bool CanGet() + { + if (CurrentMode < MaxMode) + { + CurrentMode++; + return true; + } + + if (CurrentPriority < MaxPriority) + { + CurrentPriority++; + return true; + } + + return false; + } + + private void StartBind(NKeyBind bind) + { + bind._Action.Invoke(); + } +} \ No newline at end of file diff --git a/NextShip/Manager/NextLangManager.cs b/NextShip/Manager/NextLangManager.cs new file mode 100644 index 0000000..f62ba6c --- /dev/null +++ b/NextShip/Manager/NextLangManager.cs @@ -0,0 +1,23 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public class NextLangManager : ILangManager +{ + public void RegisterLang(ILang lang) + { + } + + public void UnRegisterLang(ILang lang) + { + } + + public void Set(SupportedLangs langId, ILang lang) + { + } + + public void SetCurrentLang(SupportedLangs langId) + { + + } +} \ No newline at end of file diff --git a/NextShip/Manager/NextManager.cs b/NextShip/Manager/NextManager.cs index 4092337..4428fed 100644 --- a/NextShip/Manager/NextManager.cs +++ b/NextShip/Manager/NextManager.cs @@ -1,3 +1,4 @@ +using System; using NextShip.Api.Attributes; using NextShip.Api.Bases; using NextShip.Api.UI; @@ -8,21 +9,14 @@ namespace NextShip.Manager; [Il2CppRegister] public class NextManager : MonoBehaviour { - private static NextManager _instance; + public readonly UpdateTasker _Tasker = new(); - public UpdateTasker _Tasker; - - public NextManager() - { - _Tasker = new UpdateTasker(); - _instance = this; - } - - public static NextManager Instance => _instance ??= Main.Instance.AddComponent(); + public event Action OnUpdate; public void Update() { NextUIManager.Instance.Update(); + OnUpdate?.Invoke(); } public void FixedUpdate() diff --git a/NextShip/Manager/NextScreenManager.cs b/NextShip/Manager/NextScreenManager.cs new file mode 100644 index 0000000..7cfc18b --- /dev/null +++ b/NextShip/Manager/NextScreenManager.cs @@ -0,0 +1,8 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.Manager; + +public class NextScreenManager : INextScreenManager +{ + +} \ No newline at end of file diff --git a/NextShip/NextEvents/HudManagerUpdateEvent.cs b/NextShip/NextEvents/HudManagerUpdateEvent.cs new file mode 100644 index 0000000..e88fecc --- /dev/null +++ b/NextShip/NextEvents/HudManagerUpdateEvent.cs @@ -0,0 +1,22 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.NextEvents; + +public class HudManagerUpdateEvent(HudManager Instance) : INextEvent +{ + public string EventName { get; set; } + + public int Id { get; set; } + + public void OnRegister(IEventManager eventManager) + { + } + + public void OnUnRegister(IEventManager eventManager) + { + } + + public void Call(INextEvent @event) + { + } +} \ No newline at end of file diff --git a/NextShip/Patches/AnnouncementPatch.cs b/NextShip/Patches/AnnouncementPatch.cs index dd37a43..a40b7da 100644 --- a/NextShip/Patches/AnnouncementPatch.cs +++ b/NextShip/Patches/AnnouncementPatch.cs @@ -11,7 +11,7 @@ namespace NextShip.Patches; public class AnnouncementPatch { //https://github.com/Dolly1016/Nebula/blob/master/Nebula/Module/ModUpdater.cs - public static List ModUpdateAnnouncements = new(); + public static readonly List ModUpdateAnnouncements = []; [HarmonyPatch(typeof(PlayerAnnouncementData), nameof(PlayerAnnouncementData.SetAnnouncements))] [HarmonyPrefix] @@ -19,7 +19,7 @@ public static void SetModAnnouncements(PlayerAnnouncementData __instance, [HarmonyArgument(0)] ref Il2CppReferenceArray aRange) { if (ModUpdateAnnouncements == null || ModUpdateAnnouncements.Count == 0) return; - List list = new(aRange.ToList()); + List list = [..aRange.ToList()]; list.AddRange(ModUpdateAnnouncements); list.Sort(AnCompare); aRange = list.ToArray(); diff --git a/NextShip/Patches/EmergencyMinigamePatch.cs b/NextShip/Patches/EmergencyMinigamePatch.cs deleted file mode 100644 index cbcf32b..0000000 --- a/NextShip/Patches/EmergencyMinigamePatch.cs +++ /dev/null @@ -1,36 +0,0 @@ -using HarmonyLib; - -namespace NextShip.Patches; - -[HarmonyPatch(typeof(EmergencyMinigame), nameof(EmergencyMinigame.Update))] -internal class EmergencyMinigameUpdatePatch -{ - public static void Postfix(EmergencyMinigame __instance) - { - var roleCanCallEmergency = true; - var statusText = ""; - - var player = CachedPlayer.LocalPlayer.PlayerControl; -/* var info = RoleHelpers.GetRoleInfo(player); */ -/* var id = info.roleId; - - if (id == RoleId.Jester) - { - roleCanCallEmergency = Jester.CanCallEmergency; - if (!roleCanCallEmergency) - { - statusText = "小丑达咩拍灯"; - } - } */ - - if (!roleCanCallEmergency) - { - __instance.StatusText.text = statusText; - __instance.NumberText.text = string.Empty; - __instance.ClosedLid.gameObject.SetActive(true); - __instance.OpenLid.gameObject.SetActive(false); - __instance.ButtonActive = false; - __instance.enabled = false; - } - } -} \ No newline at end of file diff --git a/NextShip/Patches/ExileControllPatch.cs b/NextShip/Patches/ExileControllPatch.cs deleted file mode 100644 index 79dd67c..0000000 --- a/NextShip/Patches/ExileControllPatch.cs +++ /dev/null @@ -1,55 +0,0 @@ -using HarmonyLib; - -namespace NextShip.Patches; - -[HarmonyPatch(typeof(ExileController), nameof(ExileController.Begin))] -internal class ExileControllerBeginPatch -{ -/* public static void Postfix(ExileController __instance, [HarmonyArgument(0)] ref GameData.PlayerInfo exiled, [HarmonyArgument(1)] bool tie) - { - if (exiled != null) - { - var player = exiled.GetPlayerForExile(); -/* var info = RoleHelpers.GetRoleInfo(player); - var eText = "\n" + string.Format(GetString("exileText"),exiled.PlayerName,info.name); - if (CustomOptionHolder.showExilePlayerConcreteRoleTeam.getBool()) - { - eText += "\n" + string.Format(GetString("exileTeamText"),RoleHelpers.GetRoleTeam(player)); - } - if (__instance.ImpostorText.text != null) - { - eText = eText + "\n" + __instance.ImpostorText.text; - __instance.ImpostorText.text = ""; - } - if (CustomOptionHolder.showExilePlayerRole.getBool() && GameManager.Instance.LogicOptions.GetConfirmImpostor()) - { - if (info != null) - { - if (__instance.completeString != "TestPlayer was not The Impostor") - { - __instance.completeString += eText; - } - } - } - } - } */ -} - -[HarmonyPatch] -internal class ExileControllerWrapUp -{ - [HarmonyPatch(typeof(ExileController), nameof(ExileController.WrapUp))] - private class ExileControllerWrapUpPatch - { - public static void Postfix(ExileController __instance) - { - if (__instance.exiled != null) - { -/* if(__instance.exiled.GetPlayerForExile().Is(RoleId.Jester)) - { - Jester.triggerJesterWin = true; - } */ - } - } - } -} \ No newline at end of file diff --git a/NextShip/Patches/GameStartManagerPatch.cs b/NextShip/Patches/GameStartManagerPatch.cs deleted file mode 100644 index ddabcdf..0000000 --- a/NextShip/Patches/GameStartManagerPatch.cs +++ /dev/null @@ -1,41 +0,0 @@ -using HarmonyLib; - -namespace NextShip.Patches; - -[HarmonyPatch(typeof(GameStartManager), nameof(GameStartManager.Update))] -internal class GameStartManagerUpdatePatch -{ - public static void Prefix(GameStartManager __instance) - { - __instance.MinPlayers = 1; - __instance.countDownTimer = 0; - } -} - -/*[HarmonyPatch(typeof(GameStartManager), nameof(GameStartManager.BeginGame))] -internal class GameStartManagerBeginGamePatch -{ - public static void Prefix() - { - /*if (noGameEnd.getBool() && dummynumber.getSelection() != 0) - { - var num = dummynumber.getSelection(); - for (var n = 1; n < num; n++) - { - var playerControl = Object.Instantiate(AmongUsClient.Instance.PlayerPrefab); - var i = playerControl.PlayerId = (byte)GameData.Instance.GetAvailableId(); - - GameData.Instance.AddPlayer(playerControl); - AmongUsClient.Instance.Spawn(playerControl); - - playerControl.transform.position = PlayerControl.LocalPlayer.transform.position; - playerControl.GetComponent().enabled = true; - playerControl.isDummy = true; - playerControl.SetName("假人" + n); - playerControl.SetColor(i); - - GameData.Instance.RpcSetTasks(playerControl.PlayerId, new byte[0]); - } - }#1# - } -}*/ \ No newline at end of file diff --git a/NextShip/Patches/IntroPatch.cs b/NextShip/Patches/IntroPatch.cs index a2c1a0e..bf7e287 100644 --- a/NextShip/Patches/IntroPatch.cs +++ b/NextShip/Patches/IntroPatch.cs @@ -2,52 +2,21 @@ namespace NextShip.Patches; -[HarmonyPatch(typeof(IntroCutscene), nameof(IntroCutscene.ShowRole))] +[Harmony] internal class ShowRolePatch { - public static void SetRoleTexts(IntroCutscene __instance) + + [HarmonyPatch(typeof(IntroCutscene), nameof(IntroCutscene.ShowRole))] + [HarmonyPrefix] + public static void OnShouRolePatch(IntroCutscene __instance) { -/* var LocalP = CachedPlayer.LocalPlayer.PlayerControl; -// 获取本地玩家角色信息 - RoleInfo roleInfo = RoleHelpers.GetRoleInfo(LocalP, false); - RoleInfo modifierInfo = RoleHelpers.GetRoleInfo(LocalP, true); - if (roleInfo != null) - { - __instance.YouAreText.color = roleInfo.color; - __instance.RoleText.text = roleInfo.name; - __instance.RoleText.color = roleInfo.color; - __instance.RoleBlurbText.text = roleInfo.IntroD; - __instance.RoleBlurbText.color = roleInfo.color; - } - if (modifierInfo != null) - { - __instance.RoleText.text += Helpers.cs(modifierInfo.color, $" {modifierInfo.name}"); - __instance.RoleBlurbText.text += "\n" + Helpers.cs(modifierInfo.color, modifierInfo.roleId == RoleId.Lover && RoleHelpers.getLover2() != null ? string.Format(modifierInfo.IntroD, RoleHelpers.getLover2().name) : modifierInfo.IntroD); - } */ + } - - /*public static bool Prefix(IntroCutscene __instance) + + [HarmonyPatch(typeof(IntroCutscene), nameof(IntroCutscene.ShowTeam))] + [HarmonyPrefix] + public static void OnShouTeamPatch(IntroCutscene __instance) { - if (!activateRoles.getBool()) return true; - FastDestroyableSingleton.Instance.StartCoroutine(Effects.Lerp(1f, - new Action(p => { SetRoleTexts(__instance); }))); - return true; - }*/ -} - -[HarmonyPatch(typeof(IntroCutscene), nameof(IntroCutscene.ShowTeam))] -internal class ShowTeamPatch -{ -/* public static void setRoleTeamText(IntroCutscene __instance) - { - var LocalP = CachedPlayer.LocalPlayer.PlayerControl; - var teamText = RoleHelpers.GetRoleTeam(LocalP); - __instance.TeamTitle.text = teamText; - } */ /* - public static bool Prefix(IntroCutscene __instance) - { - if (!CustomOptionHolder.activateRoles.getBool()) return true; - FastDestroyableSingleton.Instance.StartCoroutine(Effects.Lerp(1f, new Action((p) => { setRoleTeamText(__instance); }))); - return true; - } */ + + } } \ No newline at end of file diff --git a/NextShip/Patches/PlayerPhysicsPatch.cs b/NextShip/Patches/PlayerPhysicsPatch.cs index d37779c..ff2aed7 100644 --- a/NextShip/Patches/PlayerPhysicsPatch.cs +++ b/NextShip/Patches/PlayerPhysicsPatch.cs @@ -11,7 +11,7 @@ public static class PlayerPhysicsPatch [HarmonyPostfix] public static void Update_Postfix(PlayerPhysics __instance) { - var playerInfo = NextPlayerManager.Instance.GetPlayerInfo(__instance.myPlayer); + var playerInfo = NextPlayerManager.Instance.CreateOrGetSetPlayerInfo(__instance.myPlayer); __instance.GhostSpeed = playerInfo.GhostSpeed; __instance.Speed = playerInfo.BodySpeed; } diff --git a/NextShip/Patches/ServerPath.cs b/NextShip/Patches/ServerPath.cs deleted file mode 100644 index fd1353c..0000000 --- a/NextShip/Patches/ServerPath.cs +++ /dev/null @@ -1,42 +0,0 @@ -using HarmonyLib; - -namespace NextShip.Patches; - -[HarmonyPatch] -public static class ServerPath -{ - public static bool CurrentVanillaServer => Main.serverManager.CurrentRegion.IsVanilla(); - - public static void autoAddServer() - { - IRegionInfo[] regionInfos = - { - createHttp("au-sh.pafyx.top", "梦服上海(新)", 22000, false), - createHttp("au-as.duikbo.at", "Modded Asia (MAS)", 443, true), - createHttp("www.aumods.xyz", "Modded NA (MNA)", 443, true), - createHttp("au-eu.duikbo.at", "Modded EU (MEU)", 443, true) - }; - - - foreach (var r in regionInfos) - { - if (Main.serverManager.AvailableRegions.Contains(r)) continue; - Main.serverManager.AddOrUpdateRegion(r); - } - } - - public static IRegionInfo createHttp(string ip, string name, ushort port, bool ishttps) - { - var serverIp = ishttps ? "https://" : "http://" + ip; - var serverInfo = new ServerInfo(name, serverIp, port, false); - ServerInfo[] ServerInfo = { serverInfo }; - return new StaticHttpRegionInfo(name, StringNames.NoTranslation, ip, ServerInfo).CastFast(); - } - - - private static bool IsVanilla(this IRegionInfo regionInfo) - { - return regionInfo.TranslateName is StringNames.ServerAS or StringNames.ServerEU or StringNames.ServerNA - or StringNames.ServerSA; - } -} \ No newline at end of file diff --git a/NextShip/Patches/UpdatePatch.cs b/NextShip/Patches/UpdatePatch.cs index ffd1f79..7c53178 100644 --- a/NextShip/Patches/UpdatePatch.cs +++ b/NextShip/Patches/UpdatePatch.cs @@ -10,17 +10,16 @@ internal class HudManagerUpdatePatch private static void setPlayerNameColor(PlayerControl p, Color color) { p.cosmetics.nameText.color = color; - if (MeetingHud.Instance != null) - foreach (var player in MeetingHud.Instance.playerStates) - if (player.NameText != null && p.PlayerId == player.TargetPlayerId) - player.NameText.color = color; + if (MeetingHud.Instance == null) return; + foreach (var player in MeetingHud.Instance.playerStates) + if (player.NameText != null && p.PlayerId == player.TargetPlayerId) + player.NameText.color = color; } private static void SetNameColors() { var localPlayer = CachedPlayer.LocalPlayer.PlayerControl; -/* var localRoleInfo = RoleHelpers.GetRoleInfo(localPlayer, false); */ -/* setPlayerNameColor(localPlayer, localRoleInfo.color); */ + } private static void updateVentButton(HudManager __instance) diff --git a/NextShip/Roles/Crewmate/Sheriff.cs b/NextShip/Roles/Crewmate/Sheriff.cs new file mode 100644 index 0000000..7c8a9aa --- /dev/null +++ b/NextShip/Roles/Crewmate/Sheriff.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using NextShip.Api.Attributes; +using NextShip.Api.Interfaces; +using UnityEngine; + +namespace NextShip.Roles.Crewmate; + +[FastAddRole] +public class Sheriff : IRole +{ + public Type RoleBaseType { get; set; } = typeof(SheriffBase); + + public Type RoleType { get; set; } = typeof(Sheriff); + public List RoleBase { get; set; } + public List Players { get; set; } = []; + public bool EnableAssign { get; set; } = true; + + public Func CreateRoleBase { get; set; } + + public SimpleRoleInfo SimpleRoleInfo { get; set; } = new() + { + RoleColor = Color.yellow, + roleTeam = RoleTeam.Crewmate, + roleType = Api.Roles.RoleType.MainRole, + Name = nameof(Sheriff), + RoleStringId = nameof(Sheriff) + + }; + + public bool CanCreate(IRole role, PlayerControl player) + { + return true; + } + + public class SheriffBase(PlayerControl player) : RoleBase(player) + { + + } + + public void Dispose() + { + } +} \ No newline at end of file diff --git a/NextShip/main.cs b/NextShip/main.cs index ddf8872..cadd182 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.IO; using System.Reflection; +using System.Threading.Tasks; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; @@ -17,7 +18,6 @@ using NextShip.DIY.Plugins; using NextShip.Languages; using NextShip.Manager; -using NextShip.Patches; using NextShip.Services; using BepInExLogger = BepInEx.Logging.Logger; @@ -62,6 +62,8 @@ public sealed class NextShip : BasePlugin private static event Action OnBuilder; + private NextManager _nextManager; + public override void Load() { @@ -69,12 +71,18 @@ public override void Load() RootAssembly = Assembly.GetExecutingAssembly(); TISLog = BepInExLogger.CreateLogSource(ModName.RemoveBlank()); Harmony.PatchAll(); + _nextManager = AddComponent().DontDestroyOnLoad(); Api.Logs.Log.Get(TISLog); Init(); CreateService(); LoadDependent(); + Task.Run(() => + { + var roleManager = _Service.Get(); + FastAddRole.Registration(roleManager, RootAssembly); + }); SteamExtension.UseSteamIdFile(); ReactorExtension.UseReactorHandshake(); @@ -84,10 +92,7 @@ public override void Load() ConsoleManager.SetConsoleTitle("Among Us " + ModName + " Game"); RegisterManager.Registration(); - - AddComponent().DontDestroyOnLoad(); - - ServerPath.autoAddServer(); + LanguagePack.Init(); CustomCosmeticsManager.LoadHat(); } @@ -114,11 +119,7 @@ private static void InitPlugins() OnBuilder += manager.OnServiceBuild; } - public static void AddOnBuild() - { - } - - private static void CreateService() + private void CreateService() { var builder = new ServiceBuilder(); builder.CreateService(); @@ -126,13 +127,21 @@ private static void CreateService() builder._collection.AddSingleton(); builder._collection.AddSingleton(); builder._collection.AddSingleton(); + builder._collection.AddSingleton(); builder._collection.AddSingleton(); + builder._collection.AddSingleton(); + builder._collection.AddSingleton(); + builder._collection.AddSingleton(); + builder._collection.AddSingleton(); + builder._collection.AddSingleton(); + builder._collection.AddSingleton(_nextManager); builder._collection.AddHttpClient(); builder.AddTransient(); builder.Add(); builder.Add(); builder.Add(); builder.Add(); + builder.Add(); OnBuilder?.Invoke(builder); From fea973ef5a37834e7d26f70aec1d653357a1fbb2 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Tue, 20 Feb 2024 14:38:15 +0800 Subject: [PATCH 25/29] az --- NextShip.Api/Enums/SystemRPCFlag.cs | 3 +- NextShip.Api/NextShip.Api.csproj | 3 +- NextShip.Api/RPCs/FastRpcReader.cs | 8 ++--- NextShip.sln | 6 ++++ NextShip.sln.DotSettings.user | 16 ++++++++++ NextShip/LogInfos/RPCInfoLog.cs | 26 ++++++++++++++++ NextShip/Manager/InstanceManager.cs | 36 +++++++++++++++++++++-- NextShip/NextShip.csproj | 2 +- NextShip/Patches/GameStartManagerPatch.cs | 15 ++++++++++ NextShip/Patches/PlayerPatch.cs | 5 ++++ NextShip/UI/Components/NextMenuOption.cs | 3 +- OtherAttribute/FastReadAdd.cs | 9 ++++++ OtherAttribute/OtherAttribute.csproj | 13 ++++++++ 13 files changed, 133 insertions(+), 12 deletions(-) create mode 100644 NextShip/LogInfos/RPCInfoLog.cs create mode 100644 NextShip/Patches/GameStartManagerPatch.cs create mode 100644 OtherAttribute/FastReadAdd.cs create mode 100644 OtherAttribute/OtherAttribute.csproj diff --git a/NextShip.Api/Enums/SystemRPCFlag.cs b/NextShip.Api/Enums/SystemRPCFlag.cs index a2a0a5f..ddc4450 100644 --- a/NextShip.Api/Enums/SystemRPCFlag.cs +++ b/NextShip.Api/Enums/SystemRPCFlag.cs @@ -2,5 +2,6 @@ namespace NextShip.Api.Enums; public enum SystemRPCFlag : byte { - VersionShare = 210 + VersionShare = 210, + VersionShareAgain = 211, } \ No newline at end of file diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index 0dbc5fb..177bf98 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -19,7 +19,7 @@ - + @@ -31,6 +31,7 @@ + diff --git a/NextShip.Api/RPCs/FastRpcReader.cs b/NextShip.Api/RPCs/FastRpcReader.cs index 6552555..83af159 100644 --- a/NextShip.Api/RPCs/FastRpcReader.cs +++ b/NextShip.Api/RPCs/FastRpcReader.cs @@ -2,6 +2,8 @@ using HarmonyLib; using Hazel; using InnerNet; +using JetBrains.Annotations; +using OtherAttribute; namespace NextShip.Api.RPCs; @@ -65,9 +67,3 @@ public static void AddFormAssembly(Assembly assembly) } } } - -[AttributeUsage(AttributeTargets.Method)] -public class FastReadAdd(byte callId) : Attribute -{ - public byte CallId = callId; -} \ No newline at end of file diff --git a/NextShip.sln b/NextShip.sln index 4363a81..446ab8b 100644 --- a/NextShip.sln +++ b/NextShip.sln @@ -8,6 +8,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NextShip.SourceGenerator", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NSLangAnalyzer", "NSLangAnalyzer\NSLangAnalyzer.csproj", "{81EC6168-530F-45B4-92A5-5FFEB719C0A7}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OtherAttribute", "OtherAttribute\OtherAttribute.csproj", "{5E9827F3-7B33-4FB0-A0E5-C95677F66F49}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -30,5 +32,9 @@ Global {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Debug|Any CPU.Build.0 = Debug|Any CPU {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Release|Any CPU.ActiveCfg = Release|Any CPU {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Release|Any CPU.Build.0 = Release|Any CPU + {5E9827F3-7B33-4FB0-A0E5-C95677F66F49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5E9827F3-7B33-4FB0-A0E5-C95677F66F49}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5E9827F3-7B33-4FB0-A0E5-C95677F66F49}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5E9827F3-7B33-4FB0-A0E5-C95677F66F49}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/NextShip.sln.DotSettings.user b/NextShip.sln.DotSettings.user index 65767c8..cdba38c 100644 --- a/NextShip.sln.DotSettings.user +++ b/NextShip.sln.DotSettings.user @@ -3,4 +3,20 @@ <AssemblyExplorer> <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.il2cpp.msbuild\2.0.1" Loaded="True" /> <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.il2cpp.msbuild\2.1.0-rc.1" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.common\6.0.0-be.662" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.common\6.0.0-be.668" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.common\6.0.0-be.671" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.common\6.0.0-be.672" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.common\6.0.0-be.674" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.common\6.0.0-be.679" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.common\6.0.0-be.682" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.common\6.0.0-be.688" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.il2cpp\6.0.0-be.662" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.il2cpp\6.0.0-be.668" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.il2cpp\6.0.0-be.671" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.il2cpp\6.0.0-be.672" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.il2cpp\6.0.0-be.674" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.il2cpp\6.0.0-be.679" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.il2cpp\6.0.0-be.682" Loaded="True" /> + <PhysicalFolder Path="C:\Users\Huier\.nuget\packages\bepinex.unity.il2cpp\6.0.0-be.688" Loaded="True" /> </AssemblyExplorer> \ No newline at end of file diff --git a/NextShip/LogInfos/RPCInfoLog.cs b/NextShip/LogInfos/RPCInfoLog.cs new file mode 100644 index 0000000..e757bd4 --- /dev/null +++ b/NextShip/LogInfos/RPCInfoLog.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using HarmonyLib; +using Hazel; +using InnerNet; + +namespace NextShip.LogInfos; + +public class RPCInfoLog +{ + [HarmonyPatch] + internal static class RPCInfoLogPatch + { + private static IEnumerable InnerNetObjectTypes { get; } = typeof(InnerNetObject).Assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(InnerNetObject))).ToList(); + + public static IEnumerable TargetMethods() + { + return InnerNetObjectTypes.Select(x => x.GetMethod(nameof(InnerNetObject.HandleRpc), AccessTools.allDeclared)).Where(m => m != null)!; + } + + public static void Prefix(InnerNetObject __instance, [HarmonyArgument(0)] byte callId, [HarmonyArgument(1)] MessageReader reader) + => Info($"RPCHandle {nameof(__instance)} CallId{callId} Length:{reader.Length} Pos:{reader.Position} Tag:{reader.Tag}", "RPCInfoLog"); + } +} \ No newline at end of file diff --git a/NextShip/Manager/InstanceManager.cs b/NextShip/Manager/InstanceManager.cs index 036c2e4..620f642 100644 --- a/NextShip/Manager/InstanceManager.cs +++ b/NextShip/Manager/InstanceManager.cs @@ -2,12 +2,16 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; +using HarmonyLib; +using InnerNet; +using UnityEngine; namespace NextShip.Manager; public class InstanceManager { - public Dictionary Instances = new(); + public readonly Dictionary?> Instances = new(); public void RegisterInstance(T instance) { @@ -19,12 +23,40 @@ public void RegisterInstance(T instance) } } - public void RegisterInstance(Type type, object obj) => Instances[type] = obj; + public void RegisterInstance(Type type, object obj) => (Instances[type] ??= []).Add(obj); public T? Get() where T : class => Get(typeof(T)) as T; + + public List? Gets() where T : class => Gets(typeof(T)) as List; public object? Get(Type type) + { + return Instances.FirstOrDefault(n => n.Key == type).Value?.FirstOrDefault(); + } + + public IEnumerable? Gets(Type type) { return Instances.FirstOrDefault(n => n.Key == type).Value; } +} + +[HarmonyPatch] +internal static class InstanceManagerPatch +{ + private static IEnumerable InnerNetObjectTypes { get; } = typeof(InnerNetObject).Assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(MonoBehaviour))).ToList(); + + public static IEnumerable TargetMethods() + { + return InnerNetObjectTypes.Select(x => x.GetMethod("Awake", AccessTools.allDeclared)).Where(m => m != null)!; + } + + public static void Postfix(MonoBehaviour __instance) + { + var manager = Main._Service.Get(); + foreach (var (key, value) in manager.Instances) + { + value?.RemoveAll(n => n == null); + } + manager.RegisterInstance(__instance); + } } \ No newline at end of file diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index eb69218..6fe9795 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -30,7 +30,7 @@ - + diff --git a/NextShip/Patches/GameStartManagerPatch.cs b/NextShip/Patches/GameStartManagerPatch.cs new file mode 100644 index 0000000..2e4a7de --- /dev/null +++ b/NextShip/Patches/GameStartManagerPatch.cs @@ -0,0 +1,15 @@ +using System.Linq; +using HarmonyLib; + +namespace NextShip.Patches; + +[Harmony] +public static class GameStartManagerPatch +{ + [HarmonyPatch(typeof(GameStartManager), nameof(GameStartManager.Update))] + [HarmonyPostfix] + public static void OnGameStartManagerUpdatePatch() + { + + } +} \ No newline at end of file diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs index 5766e6b..59ab2a3 100644 --- a/NextShip/Patches/PlayerPatch.cs +++ b/NextShip/Patches/PlayerPatch.cs @@ -2,9 +2,11 @@ using HarmonyLib; using Hazel; using InnerNet; +using JetBrains.Annotations; using NextShip.Api.Enums; using NextShip.Api.RPCs; using NextShip.Manager; +using OtherAttribute; namespace NextShip.Patches; @@ -48,6 +50,9 @@ public static void OnPlayerJoined(AmongUsClient __instance) writer.Write(PlayerControl.LocalPlayer.PlayerId); Main.Version.Write(writer); writer.Write(Main.BepInExVersion); + + if (!AllPlayerVersionInfos.Exists(n => n.Player == CachedPlayer.LocalPlayer.PlayerControl)) + AllPlayerVersionInfos.Add(new PlayerVersionInfo(CachedPlayer.LocalPlayer.PlayerControl, Main.Version, Main.BepInExVersion)); } [FastReadAdd((byte)SystemRPCFlag.VersionShare)] diff --git a/NextShip/UI/Components/NextMenuOption.cs b/NextShip/UI/Components/NextMenuOption.cs index 2b4f725..d91631f 100644 --- a/NextShip/UI/Components/NextMenuOption.cs +++ b/NextShip/UI/Components/NextMenuOption.cs @@ -1,4 +1,5 @@ -using NextShip.Api.Attributes; +using System; +using NextShip.Api.Attributes; using NextShip.UI.Module; using UnityEngine; diff --git a/OtherAttribute/FastReadAdd.cs b/OtherAttribute/FastReadAdd.cs new file mode 100644 index 0000000..06e976a --- /dev/null +++ b/OtherAttribute/FastReadAdd.cs @@ -0,0 +1,9 @@ +using JetBrains.Annotations; + +namespace OtherAttribute; + +[MeansImplicitUse, AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] +public class FastReadAdd(byte callId) : Attribute +{ + public readonly byte CallId = callId; +} \ No newline at end of file diff --git a/OtherAttribute/OtherAttribute.csproj b/OtherAttribute/OtherAttribute.csproj new file mode 100644 index 0000000..f8aeaad --- /dev/null +++ b/OtherAttribute/OtherAttribute.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + From f6c49d4169273a41b25a8d7000c25b26aeec8e43 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Wed, 21 Feb 2024 13:29:25 +0800 Subject: [PATCH 26/29] abab --- NextShip.Api/Attributes/FastAddRole.cs | 4 +- NextShip.Api/Interfaces/ILangLoader.cs | 6 +++ NextShip.Api/RPCs/FastRpcReader.cs | 6 +-- NextShip.Api/Utils/SpriteUtils.cs | 3 +- NextShip.Api/Utils/StreamUtils.cs | 5 +++ NextShip/Roles/Crewmate/Sheriff.cs | 5 +-- NextShip/Roles/Impostor/Illusory.cs | 9 ++++ NextShip/Roles/Modifier/Bait.cs | 9 ++++ NextShip/Roles/Neutral/Schrodinger'sCat.cs | 49 ++++++++++++++++++++++ NextShip/main.cs | 2 +- OtherAttribute/FastAddRole.cs | 7 ++++ 11 files changed, 93 insertions(+), 12 deletions(-) create mode 100644 NextShip.Api/Interfaces/ILangLoader.cs create mode 100644 NextShip/Roles/Impostor/Illusory.cs create mode 100644 NextShip/Roles/Modifier/Bait.cs create mode 100644 NextShip/Roles/Neutral/Schrodinger'sCat.cs create mode 100644 OtherAttribute/FastAddRole.cs diff --git a/NextShip.Api/Attributes/FastAddRole.cs b/NextShip.Api/Attributes/FastAddRole.cs index bd493fe..6d6a2ee 100644 --- a/NextShip.Api/Attributes/FastAddRole.cs +++ b/NextShip.Api/Attributes/FastAddRole.cs @@ -1,10 +1,10 @@ using System.Reflection; using NextShip.Api.Interfaces; +using OtherAttribute; namespace NextShip.Api.Attributes; -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor)] -public class FastAddRole : Attribute +public static class FastAddRoleExt { public static void Registration(IRoleManager _roleManager, Assembly assembly) { diff --git a/NextShip.Api/Interfaces/ILangLoader.cs b/NextShip.Api/Interfaces/ILangLoader.cs new file mode 100644 index 0000000..549824c --- /dev/null +++ b/NextShip.Api/Interfaces/ILangLoader.cs @@ -0,0 +1,6 @@ +namespace NextShip.Api.Interfaces; + +public interface ILangLoader +{ + +} \ No newline at end of file diff --git a/NextShip.Api/RPCs/FastRpcReader.cs b/NextShip.Api/RPCs/FastRpcReader.cs index 83af159..368f796 100644 --- a/NextShip.Api/RPCs/FastRpcReader.cs +++ b/NextShip.Api/RPCs/FastRpcReader.cs @@ -1,8 +1,6 @@ using System.Reflection; using HarmonyLib; using Hazel; -using InnerNet; -using JetBrains.Annotations; using OtherAttribute; namespace NextShip.Api.RPCs; @@ -16,9 +14,9 @@ public class FastRpcReader [Harmony] public static class FastRpcReaderPatch { - public static List AllFastRpcReader = []; + public static readonly List AllFastRpcReader = []; - [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.HandleGameDataInner))] + [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.HandleGameDataInner))] [HarmonyPrefix] public static void InnerNet_ReaderPath([HarmonyArgument(0)] MessageReader reader) { diff --git a/NextShip.Api/Utils/SpriteUtils.cs b/NextShip.Api/Utils/SpriteUtils.cs index 6d78002..519e202 100644 --- a/NextShip.Api/Utils/SpriteUtils.cs +++ b/NextShip.Api/Utils/SpriteUtils.cs @@ -89,8 +89,7 @@ public static Sprite ToFullRect(this Sprite sprite, string name = "") if (stream == null) return texture; var length = stream.Length; var byteTexture = new Il2CppStructArray(length); - var _ = stream.Read(new Span(IntPtr.Add(byteTexture.Pointer, IntPtr.Size * 4).ToPointer(), - (int)length)); + var _ = stream.Read(byteTexture.ToSpan()); ImageConversion.LoadImage(texture, byteTexture, false); return texture; diff --git a/NextShip.Api/Utils/StreamUtils.cs b/NextShip.Api/Utils/StreamUtils.cs index 0739ef3..2557c00 100644 --- a/NextShip.Api/Utils/StreamUtils.cs +++ b/NextShip.Api/Utils/StreamUtils.cs @@ -21,6 +21,11 @@ public static DirectoryInfo GetDir(string name) { return assembly.GetManifestResourceStream(string.Join(".", path)); } + + public static unsafe Span ToSpan(this Il2CppStructArray array) where T : unmanaged + { + return new Span(IntPtr.Add(array.Pointer, IntPtr.Size * 4).ToPointer(), array.Length); + } // form reactor diff --git a/NextShip/Roles/Crewmate/Sheriff.cs b/NextShip/Roles/Crewmate/Sheriff.cs index 7c8a9aa..ada61c2 100644 --- a/NextShip/Roles/Crewmate/Sheriff.cs +++ b/NextShip/Roles/Crewmate/Sheriff.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using NextShip.Api.Attributes; using NextShip.Api.Interfaces; +using OtherAttribute; using UnityEngine; namespace NextShip.Roles.Crewmate; @@ -12,7 +12,7 @@ public class Sheriff : IRole public Type RoleBaseType { get; set; } = typeof(SheriffBase); public Type RoleType { get; set; } = typeof(Sheriff); - public List RoleBase { get; set; } + public List RoleBase { get; set; } = []; public List Players { get; set; } = []; public bool EnableAssign { get; set; } = true; @@ -25,7 +25,6 @@ public class Sheriff : IRole roleType = Api.Roles.RoleType.MainRole, Name = nameof(Sheriff), RoleStringId = nameof(Sheriff) - }; public bool CanCreate(IRole role, PlayerControl player) diff --git a/NextShip/Roles/Impostor/Illusory.cs b/NextShip/Roles/Impostor/Illusory.cs new file mode 100644 index 0000000..5ff1a0a --- /dev/null +++ b/NextShip/Roles/Impostor/Illusory.cs @@ -0,0 +1,9 @@ +using OtherAttribute; + +namespace NextShip.Roles.Impostor; + +[FastAddRole] +public class Illusory +{ + +} \ No newline at end of file diff --git a/NextShip/Roles/Modifier/Bait.cs b/NextShip/Roles/Modifier/Bait.cs new file mode 100644 index 0000000..b268c75 --- /dev/null +++ b/NextShip/Roles/Modifier/Bait.cs @@ -0,0 +1,9 @@ +using OtherAttribute; + +namespace NextShip.Roles.Modifier; + +[FastAddRole] +public class Bait +{ + +} \ No newline at end of file diff --git a/NextShip/Roles/Neutral/Schrodinger'sCat.cs b/NextShip/Roles/Neutral/Schrodinger'sCat.cs new file mode 100644 index 0000000..a100e91 --- /dev/null +++ b/NextShip/Roles/Neutral/Schrodinger'sCat.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using NextShip.Api.Interfaces; +using OtherAttribute; +using UnityEngine; + +namespace NextShip.Roles.Neutral; + +[FastAddRole] +public class SchrodingerCat : IRole +{ + public SchrodingerCat() + { + + } + + public void Dispose() + { + } + + public Type RoleBaseType { get; set; } = typeof(SchrodingerCatBase); + + public Type RoleType { get; set; } = typeof(SchrodingerCat); + + public SimpleRoleInfo SimpleRoleInfo { get; set; } = new() + { + RoleColor = Color.gray, + roleTeam = RoleTeam.Neutral, + roleType = Api.Roles.RoleType.MainRole, + Name = nameof(SchrodingerCat), + RoleStringId = nameof(SchrodingerCat) + }; + public List RoleBase { get; set; } = []; + public List Players { get; set; } = []; + + public bool EnableAssign { get; set; } = true; + + public Func CreateRoleBase { get; set; } + + public bool CanCreate(IRole role, PlayerControl player) + { + return true; + } + + public class SchrodingerCatBase(PlayerControl player) : RoleBase(player) + { + + } +} \ No newline at end of file diff --git a/NextShip/main.cs b/NextShip/main.cs index cadd182..d920bbf 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -81,7 +81,7 @@ public override void Load() Task.Run(() => { var roleManager = _Service.Get(); - FastAddRole.Registration(roleManager, RootAssembly); + FastAddRoleExt.Registration(roleManager, RootAssembly); }); SteamExtension.UseSteamIdFile(); diff --git a/OtherAttribute/FastAddRole.cs b/OtherAttribute/FastAddRole.cs new file mode 100644 index 0000000..871a8a4 --- /dev/null +++ b/OtherAttribute/FastAddRole.cs @@ -0,0 +1,7 @@ +using JetBrains.Annotations; + +namespace OtherAttribute; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor)] +[MeansImplicitUse] +public class FastAddRole : Attribute; \ No newline at end of file From 3ccf9d8496c3836b11bc7ac34aeb554fba3b4718 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Wed, 21 Feb 2024 17:58:01 +0800 Subject: [PATCH 27/29] Update --- NextShip.Api/Bases/OptionBase.cs | 2 ++ NextShip.Api/Interfaces/IEventListener.cs | 2 ++ NextShip/Manager/EventManager.cs | 7 +++- NextShip/Manager/NextOptionManager.cs | 5 ++- NextShip/Manager/NextRoleManager.cs | 2 ++ NextShip/Options/Options/RoleOptionBase.cs | 2 +- NextShip/Patches/RoleAssignmentPatch.cs | 2 +- NextShip/Roles/Crewmate/Sheriff.cs | 33 +++++++++++++++++-- ...{Schrodinger'sCat.cs => SchrodingerCat.cs} | 0 NextShip/Services/NextService.cs | 23 +++++++++++-- 10 files changed, 68 insertions(+), 10 deletions(-) rename NextShip/Roles/Neutral/{Schrodinger'sCat.cs => SchrodingerCat.cs} (100%) diff --git a/NextShip.Api/Bases/OptionBase.cs b/NextShip.Api/Bases/OptionBase.cs index 247e051..61b0e25 100644 --- a/NextShip.Api/Bases/OptionBase.cs +++ b/NextShip.Api/Bases/OptionBase.cs @@ -41,6 +41,8 @@ public void SetParent(IOptionInfo info) public abstract string GetValueString(); public abstract OptionBase GetBase(); + public T GetBase() where T : OptionBase => GetBase() as T; + // 设置OptionBehaviour隐性转换 public static explicit operator OptionBehaviour(OptionBase @base) { diff --git a/NextShip.Api/Interfaces/IEventListener.cs b/NextShip.Api/Interfaces/IEventListener.cs index 1dbccb2..bc97fda 100644 --- a/NextShip.Api/Interfaces/IEventListener.cs +++ b/NextShip.Api/Interfaces/IEventListener.cs @@ -3,6 +3,8 @@ namespace NextShip.Api.Interfaces; public interface IEventListener { public void On(string name) {} + + public void On(string name, object[] Instances) {} public void On(INextEvent @event) {} } \ No newline at end of file diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs index fba74aa..aa15eaf 100644 --- a/NextShip/Manager/EventManager.cs +++ b/NextShip/Manager/EventManager.cs @@ -8,7 +8,7 @@ namespace NextShip.Manager; public class EventManager : IEventManager { - public static EventManager _eventManager = Main._Service.Get(); + public static readonly EventManager _eventManager = Main._Service.Get(); private readonly HashSet EventListeners = []; @@ -52,6 +52,11 @@ public void CallListener(string name) { EventListeners.Do(n => n.On(name)); } + + public void CallListener(string name, object[] Instances) + { + EventListeners.Do(n => n.On(name, Instances)); + } public void CallListener(INextEvent @event) { diff --git a/NextShip/Manager/NextOptionManager.cs b/NextShip/Manager/NextOptionManager.cs index 58f87bd..5aa4860 100644 --- a/NextShip/Manager/NextOptionManager.cs +++ b/NextShip/Manager/NextOptionManager.cs @@ -2,4 +2,7 @@ namespace NextShip.Manager; -public class NextOptionManager : INextOptionManager; \ No newline at end of file +public class NextOptionManager : INextOptionManager +{ + +} \ No newline at end of file diff --git a/NextShip/Manager/NextRoleManager.cs b/NextShip/Manager/NextRoleManager.cs index 83c1eab..6cb32f0 100644 --- a/NextShip/Manager/NextRoleManager.cs +++ b/NextShip/Manager/NextRoleManager.cs @@ -41,6 +41,8 @@ public void CheckRoles() { } + public IRoleCreator GetCreator() => CurrentCreator ?? FastGetCreator(); + public FastCreator FastGetCreator() { if (CurrentCreator is FastCreator creator) diff --git a/NextShip/Options/Options/RoleOptionBase.cs b/NextShip/Options/Options/RoleOptionBase.cs index e469216..ea9e898 100644 --- a/NextShip/Options/Options/RoleOptionBase.cs +++ b/NextShip/Options/Options/RoleOptionBase.cs @@ -9,7 +9,7 @@ public class RoleOptionBase( string title) : StringOptionBase(enableTranslation, optionBehaviour, optionInfo, title) { public static string[] defaultChances = - { "0% ", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%" }; + ["0% ", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"]; public override RoleOptionBase GetBase() diff --git a/NextShip/Patches/RoleAssignmentPatch.cs b/NextShip/Patches/RoleAssignmentPatch.cs index 6f34bf4..6b56977 100644 --- a/NextShip/Patches/RoleAssignmentPatch.cs +++ b/NextShip/Patches/RoleAssignmentPatch.cs @@ -37,9 +37,9 @@ public static void SelectRoles_Postfix(RoleManager __instance) GetPlayerRoleS(out var C, out var I); var CAssign = new Queue(C); var IAssign = new Queue(I); + var _creator = _nextRoleManager.GetCreator(); _StartAssign: var player = (CAssign.Count > 0 ? CAssign : IAssign).Dequeue(); - var _creator = _nextRoleManager.FastGetCreator(); var role = _creator.GetAssign(); _nextRoleManager.AssignRole(player, role); if (IAssign.Count > 0) diff --git a/NextShip/Roles/Crewmate/Sheriff.cs b/NextShip/Roles/Crewmate/Sheriff.cs index ada61c2..8ca80eb 100644 --- a/NextShip/Roles/Crewmate/Sheriff.cs +++ b/NextShip/Roles/Crewmate/Sheriff.cs @@ -1,6 +1,9 @@ using System; using System.Collections.Generic; +using NextShip.Api.Bases; using NextShip.Api.Interfaces; +using NextShip.Manager; +using NextShip.Services; using OtherAttribute; using UnityEngine; @@ -18,6 +21,8 @@ public class Sheriff : IRole public Func CreateRoleBase { get; set; } + public List AllOption = []; + public SimpleRoleInfo SimpleRoleInfo { get; set; } = new() { RoleColor = Color.yellow, @@ -26,18 +31,40 @@ public class Sheriff : IRole Name = nameof(Sheriff), RoleStringId = nameof(Sheriff) }; + + public Sheriff() + { + var manager = Main._Service.Get(); + + } public bool CanCreate(IRole role, PlayerControl player) { return true; } - public class SheriffBase(PlayerControl player) : RoleBase(player) + public void Dispose() { - } + +} - public void Dispose() +public class SheriffBase : RoleBase +{ + public SheriffBase(PlayerControl player) : base(player) { + _eventManager.RegisterListener(new EventListener()); + } + + private class EventListener : IEventListener + { + public void On(string name) + { + } + + public void On(INextEvent @event) + { + + } } } \ No newline at end of file diff --git a/NextShip/Roles/Neutral/Schrodinger'sCat.cs b/NextShip/Roles/Neutral/SchrodingerCat.cs similarity index 100% rename from NextShip/Roles/Neutral/Schrodinger'sCat.cs rename to NextShip/Roles/Neutral/SchrodingerCat.cs diff --git a/NextShip/Services/NextService.cs b/NextShip/Services/NextService.cs index d4b08b5..d96923a 100644 --- a/NextShip/Services/NextService.cs +++ b/NextShip/Services/NextService.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Microsoft.Extensions.DependencyInjection; using NextShip.Api.Interfaces; @@ -7,11 +8,14 @@ namespace NextShip.Services; public class NextService : INextService { - public static readonly HashSet Services = new(); + private static readonly HashSet Services = []; + + public int id; public NextService() { Services.Add(this); + id = Services.Count == 0 ? 0 : Services.Last().id++; } public NextService(IServiceProvider provider) : this() @@ -54,18 +58,31 @@ public static NextService Build(IServiceBuilder builder) return (NextService)service; } + public static NextService Get(int id) => Services.FirstOrDefault(n => n.id == id); + public T Get() { - return _Provider.GetService(); + return _Provider!.GetService(); } public object Get(Type type) { - return _Provider.GetService(type); + return _Provider!.GetService(type); } public static NextService Build(ServiceCollection collection) { return (NextService)new ServiceBuilder().Set(collection).Build(); } +} + +internal static class ServiceExt +{ + internal static T ServiceGet() => Main._Service.Get(); + + internal static object ServiceGet(this Type type) => Main._Service.Get(type); + + internal static IEnumerable ServiceGets() => Main._Service._Provider.GetServices(); + + internal static IEnumerable ServiceGets(this Type type) => Main._Service._Provider.GetServices(type); } \ No newline at end of file From 633904934f478d75c3e9672ef1368b2390c0c5f0 Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Fri, 23 Feb 2024 20:34:23 +0800 Subject: [PATCH 28/29] abab --- NextShip/Manager/EventManager.cs | 24 +++++++++++++++ NextShip/Manager/NextOptionManager.cs | 32 ++++++++++++++++++++ NextShip/NextEvents/HudManagerUpdateEvent.cs | 4 +++ NextShip/Patches/HudPatch.cs | 17 ++++++++--- NextShip/Roles/Crewmate/Sheriff.cs | 14 ++++----- 5 files changed, 78 insertions(+), 13 deletions(-) diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs index aa15eaf..7dbb753 100644 --- a/NextShip/Manager/EventManager.cs +++ b/NextShip/Manager/EventManager.cs @@ -14,6 +14,10 @@ public class EventManager : IEventManager private readonly List RegisterEvents = []; + private FastListener _listener; + + public FastListener GetFastListener() => _listener ??= new FastListener(); + public void CallEvent(T @event) where T : INextEvent { foreach (var _event in RegisterEvents.FindAll(n => n.EventName == @event.EventName && n is T)) @@ -84,4 +88,24 @@ public INextEvent GetEvent(Type type) { return RegisterEvents.FirstOrDefault(n => n.GetType() == type); } +} + +public class FastListener +{ + private readonly List> AllListener = []; + + public void Register(Action action) + { + AllListener.Add(action); + } + + public void UnRegister(Action action) + { + AllListener.Remove(action); + } + + public void Call(string name, object[] instances = null) + { + AllListener.Do(n => n.Invoke(name, instances)); + } } \ No newline at end of file diff --git a/NextShip/Manager/NextOptionManager.cs b/NextShip/Manager/NextOptionManager.cs index 5aa4860..f100151 100644 --- a/NextShip/Manager/NextOptionManager.cs +++ b/NextShip/Manager/NextOptionManager.cs @@ -1,8 +1,40 @@ +using System.Collections.Generic; +using System.Linq; +using NextShip.Api.Bases; using NextShip.Api.Interfaces; namespace NextShip.Manager; public class NextOptionManager : INextOptionManager { + public List AllOptionBases = []; + + public void RegisterOptions(IEnumerable options) + { + var optionBases = options.ToList(); + foreach (var option in optionBases) + { + Register(option); + } + AllOptionBases.AddRange(optionBases); + } + + public void RegisterOption(T option) where T : OptionBase + { + + } + + private void Register(OptionBase option) + { + } + + public void GetOption(int id) where T : OptionBase + { + + } + public void GetOption(string Title) where T : OptionBase + { + + } } \ No newline at end of file diff --git a/NextShip/NextEvents/HudManagerUpdateEvent.cs b/NextShip/NextEvents/HudManagerUpdateEvent.cs index e88fecc..7d98f7b 100644 --- a/NextShip/NextEvents/HudManagerUpdateEvent.cs +++ b/NextShip/NextEvents/HudManagerUpdateEvent.cs @@ -8,6 +8,9 @@ public class HudManagerUpdateEvent(HudManager Instance) : INextEvent public int Id { get; set; } + public HudManager _HudManager = Instance; + + public void OnRegister(IEventManager eventManager) { } @@ -18,5 +21,6 @@ public void OnUnRegister(IEventManager eventManager) public void Call(INextEvent @event) { + } } \ No newline at end of file diff --git a/NextShip/Patches/HudPatch.cs b/NextShip/Patches/HudPatch.cs index 0f49bb8..7c2ea70 100644 --- a/NextShip/Patches/HudPatch.cs +++ b/NextShip/Patches/HudPatch.cs @@ -1,11 +1,8 @@ -/*using AmongUs.Data; using HarmonyLib; -using NextShip.RPC; -using NextShip.Utilities; -using UnityEngine; +using NextShip.NextEvents; namespace NextShip.Patches; - +/* [HarmonyPatch] public static class LoveChatPatch { @@ -94,3 +91,13 @@ private static bool CheckForModification(ChatController __instance, PlayerContro } }*/ +[Harmony] +public static class OnHudManagerUpdatePatch +{ + [HarmonyPatch(typeof(HudManager), nameof(HudManager.Update)), HarmonyPostfix] + public static void OnHudManagerUpdate(HudManager __instance) + { + _eventManager.CallEvent(new HudManagerUpdateEvent(__instance)); + } +} + diff --git a/NextShip/Roles/Crewmate/Sheriff.cs b/NextShip/Roles/Crewmate/Sheriff.cs index 8ca80eb..c91b1ce 100644 --- a/NextShip/Roles/Crewmate/Sheriff.cs +++ b/NextShip/Roles/Crewmate/Sheriff.cs @@ -36,6 +36,12 @@ public Sheriff() { var manager = Main._Service.Get(); + OptionCreate(); + } + + public void OptionCreate() + { + var OptionManager = ServiceExt.ServiceGet(); } public bool CanCreate(IRole role, PlayerControl player) @@ -58,13 +64,5 @@ public SheriffBase(PlayerControl player) : base(player) private class EventListener : IEventListener { - public void On(string name) - { - } - - public void On(INextEvent @event) - { - - } } } \ No newline at end of file From 93424b657f5324dabfe4125132fc33846fa320ab Mon Sep 17 00:00:00 2001 From: Bilibili_MengChu <2133404320@qq.com> Date: Thu, 11 Apr 2024 22:25:09 +0800 Subject: [PATCH 29/29] =?UTF-8?q?IDE=E6=A0=BC=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NSLangAnalyzer/Constants.cs | 6 +- NSLangAnalyzer/FileFinder.cs | 24 +++--- NSLangAnalyzer/NSLException.cs | 6 +- NextShip.Api/Attributes/FastAddRole.cs | 7 +- NextShip.Api/Attributes/FastReadAdd.cs | 8 ++ NextShip.Api/Attributes/NextEventListener.cs | 5 +- NextShip.Api/Attributes/ServiceAdd.cs | 13 ++-- NextShip.Api/Bases/ButtonBase.cs | 30 ++++++++ NextShip.Api/Bases/FastEventArgs.cs | 34 +++++++++ NextShip.Api/Bases/FastListener.cs | 38 ++++++++++ NextShip.Api/Bases/NKeyBind.cs | 14 ++-- NextShip.Api/Bases/NextInfo.cs | 4 +- NextShip.Api/Bases/OptionBase.cs | 5 +- NextShip.Api/Enums/SystemRPCFlag.cs | 4 + NextShip.Api/Extension/CrowdedExtension.cs | 4 +- NextShip.Api/Extension/SteamExtension.cs | 2 - NextShip.Api/GlobalUsing.cs | 2 + NextShip.Api/Interfaces/IBotManager.cs | 1 - NextShip.Api/Interfaces/IEventListener.cs | 14 +++- NextShip.Api/Interfaces/ILang.cs | 4 +- NextShip.Api/Interfaces/ILangLoader.cs | 1 - NextShip.Api/Interfaces/ILangManager.cs | 10 +++ NextShip.Api/Interfaces/INextButton.cs | 12 ++- NextShip.Api/Interfaces/INextButtonManager.cs | 1 - NextShip.Api/Interfaces/INextEvent.cs | 2 +- NextShip.Api/Interfaces/IRole.cs | 2 + NextShip.Api/Logs/Log.cs | 4 +- NextShip.Api/NextShip.Api.csproj | 8 +- NextShip.Api/RPCs/FastRpcReader.cs | 5 +- NextShip.Api/RPCs/FastRpcWriter.cs | 18 ++++- NextShip.Api/Roles/SimpleRoleInfo.cs | 55 ++++++++------ NextShip.Api/Utils/ListUtils.cs | 4 +- NextShip.Api/Utils/MethodUtils.cs | 6 +- NextShip.Api/Utils/ServerUtils.cs | 14 ++-- NextShip.Api/Utils/SpriteUtils.cs | 2 +- NextShip.Api/Utils/StreamUtils.cs | 2 +- .../BuildInfoGenerator.cs | 3 +- .../NextShip.SourceGenerator.csproj | 6 +- NextShip.sln | 6 -- NextShip/Buttons/NextButton.cs | 9 +++ NextShip/Cosmetics/CosmeticsChecks.cs | 1 - NextShip/Cosmetics/CosmeticsCreator.cs | 11 ++- NextShip/Cosmetics/Loaders/CosmeticsLoader.cs | 3 +- NextShip/DIY/Plugins/PluginLoadInfo.cs | 1 - NextShip/DIY/Plugins/PluginLoadService.cs | 1 - NextShip/DIY/Plugins/PluginManager.cs | 3 +- NextShip/GlobalUsings.cs | 1 + NextShip/LogInfos/RPCInfoLog.cs | 16 +++- NextShip/Manager/EventManager.cs | 62 ++++++++------- NextShip/Manager/InstanceManager.cs | 31 ++++---- NextShip/Manager/NextBotManager.cs | 1 - NextShip/Manager/NextButtonsManager.cs | 37 ++++++++- NextShip/Manager/NextKeyBindManager.cs | 30 +++----- NextShip/Manager/NextLangManager.cs | 57 +++++++++++++- NextShip/Manager/NextManager.cs | 5 +- NextShip/Manager/NextOptionManager.cs | 39 +++++++--- NextShip/Manager/NextRoleManager.cs | 7 +- NextShip/Manager/NextScreenManager.cs | 1 - NextShip/Manager/RegisterManager.cs | 1 - NextShip/NextEvents/HudManagerUpdateEvent.cs | 6 +- NextShip/NextShip.csproj | 4 +- NextShip/Options/DefOption.cs | 10 +++ .../Options/Patches/OptionsConsolePatch.cs | 14 ++-- NextShip/Patches/GameStartManagerPatch.cs | 2 - NextShip/Patches/HudPatch.cs | 6 +- NextShip/Patches/IntroPatch.cs | 5 +- NextShip/Patches/PlayerPatch.cs | 7 +- NextShip/Patches/RPCSyncPatch.cs | 61 +++++++++++++++ NextShip/Patches/RoleAssignmentPatch.cs | 1 - NextShip/Patches/UpdatePatch.cs | 7 -- NextShip/Roles/Crewmate/Sheriff.cs | 32 ++++---- NextShip/Roles/Impostor/Illusory.cs | 3 - NextShip/Roles/Modifier/Bait.cs | 3 - NextShip/Roles/Neutral/SchrodingerCat.cs | 20 +++-- NextShip/Services/NextService.cs | 29 +++++-- NextShip/UI/Components/DownMenu.cs | 3 +- NextShip/UI/Components/NextMenuOption.cs | 5 +- NextShip/UI/Components/ShipOptionBehaviour.cs | 5 +- NextShip/UI/Patches/OptionMenuPatch.cs | 75 ------------------- NextShip/UI/UIManager/NextUIManager.cs | 1 - NextShip/main.cs | 22 +++--- OtherAttribute/FastAddRole.cs | 7 -- OtherAttribute/FastReadAdd.cs | 9 --- OtherAttribute/OtherAttribute.csproj | 13 ---- 84 files changed, 637 insertions(+), 416 deletions(-) create mode 100644 NextShip.Api/Attributes/FastReadAdd.cs create mode 100644 NextShip.Api/Bases/ButtonBase.cs create mode 100644 NextShip.Api/Bases/FastEventArgs.cs create mode 100644 NextShip.Api/Bases/FastListener.cs create mode 100644 NextShip/Buttons/NextButton.cs create mode 100644 NextShip/Options/DefOption.cs create mode 100644 NextShip/Patches/RPCSyncPatch.cs delete mode 100644 NextShip/UI/Patches/OptionMenuPatch.cs delete mode 100644 OtherAttribute/FastAddRole.cs delete mode 100644 OtherAttribute/FastReadAdd.cs delete mode 100644 OtherAttribute/OtherAttribute.csproj diff --git a/NSLangAnalyzer/Constants.cs b/NSLangAnalyzer/Constants.cs index b861dfc..9f80ef9 100644 --- a/NSLangAnalyzer/Constants.cs +++ b/NSLangAnalyzer/Constants.cs @@ -5,10 +5,10 @@ namespace NSLangAnalyzer; public static class Constants { public const string FileSuffix = "NS"; - + public const string FileSuffix2 = "NSL"; - + public const string FileSuffix3 = "ns"; - + public const string FileSuffix4 = "nsl"; } \ No newline at end of file diff --git a/NSLangAnalyzer/FileFinder.cs b/NSLangAnalyzer/FileFinder.cs index 0725ef0..770ae9b 100644 --- a/NSLangAnalyzer/FileFinder.cs +++ b/NSLangAnalyzer/FileFinder.cs @@ -2,16 +2,13 @@ namespace NSLangAnalyzer; internal class FileFinder { - private static string[] Extensions = [FileSuffix, FileSuffix2, FileSuffix3 , FileSuffix4]; + private static readonly string[] Extensions = [FileSuffix, FileSuffix2, FileSuffix3, FileSuffix4]; private readonly List _fileInfos = []; private readonly List _readInfos = []; public FileFinder ReadFiles() { - if (_fileInfos.Count == 0) - { - throw new NSLException("FileInfo = 0"); - } + if (_fileInfos.Count == 0) throw new NSLException("FileInfo = 0"); foreach (var info in _fileInfos) { @@ -20,10 +17,7 @@ public FileFinder ReadFiles() var strings = string.Empty; var OneLine = reader.ReadLine(); - if (OneLine == null || !OneLine.StartsWith('[') || !OneLine.EndsWith(']')) - { - continue; - } + if (OneLine == null || !OneLine.StartsWith('[') || !OneLine.EndsWith(']')) continue; var texts = OneLine .Replace("[", string.Empty) @@ -32,14 +26,14 @@ public FileFinder ReadFiles() var name = texts[0]; var author = texts[1]; - + var line = reader.ReadLine(); while (line != null) { strings += line; line = reader.ReadLine(); } - + _readInfos.Add(new ReadInfo { Info = info, @@ -48,10 +42,10 @@ public FileFinder ReadFiles() author = author }); } - + return this; } - + public FileFinder Get(DirectoryInfo directory) { _readInfos.Clear(); @@ -69,9 +63,9 @@ private class ReadInfo public string? ReadStrings { get; set; } public FileInfo? Info { get; set; } - + public string? name { get; set; } - + public string? author { get; set; } } } \ No newline at end of file diff --git a/NSLangAnalyzer/NSLException.cs b/NSLangAnalyzer/NSLException.cs index 5f5b199..13a8826 100644 --- a/NSLangAnalyzer/NSLException.cs +++ b/NSLangAnalyzer/NSLException.cs @@ -2,14 +2,14 @@ namespace NSLangAnalyzer; public class NSLException : Exception { - public NSLException() : base() + public NSLException() { } - + public NSLException(string message) : base(message) { } - + public NSLException(string message, Exception exception) : base(message, exception) { } diff --git a/NextShip.Api/Attributes/FastAddRole.cs b/NextShip.Api/Attributes/FastAddRole.cs index 6d6a2ee..9d9f211 100644 --- a/NextShip.Api/Attributes/FastAddRole.cs +++ b/NextShip.Api/Attributes/FastAddRole.cs @@ -1,10 +1,11 @@ using System.Reflection; using NextShip.Api.Interfaces; -using OtherAttribute; namespace NextShip.Api.Attributes; -public static class FastAddRoleExt +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor)] +[MeansImplicitUse] +public class FastAddRole : Attribute { public static void Registration(IRoleManager _roleManager, Assembly assembly) { @@ -14,9 +15,7 @@ public static void Registration(IRoleManager _roleManager, Assembly assembly) { var constructorInfos = VarType.GetConstructors().Where(n => n.Is()); foreach (var variableConstructorInfo in constructorInfos) - { _roleManager.Register(variableConstructorInfo.Invoke(null, null) as IRole); - } } } } \ No newline at end of file diff --git a/NextShip.Api/Attributes/FastReadAdd.cs b/NextShip.Api/Attributes/FastReadAdd.cs new file mode 100644 index 0000000..02cdc26 --- /dev/null +++ b/NextShip.Api/Attributes/FastReadAdd.cs @@ -0,0 +1,8 @@ +namespace NextShip.Api.Attributes; + +[MeansImplicitUse] +[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] +public class FastReadAdd(byte callId) : Attribute +{ + public readonly byte CallId = callId; +} \ No newline at end of file diff --git a/NextShip.Api/Attributes/NextEventListener.cs b/NextShip.Api/Attributes/NextEventListener.cs index d7cd092..8b076f1 100644 --- a/NextShip.Api/Attributes/NextEventListener.cs +++ b/NextShip.Api/Attributes/NextEventListener.cs @@ -6,14 +6,11 @@ namespace NextShip.Api.Attributes; [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public sealed class NextEventListener : Attribute { - public static void RegisterFormAssembly(Assembly assembly, IEventManager manager) { - } - + public static void RegisterFormService(IServiceProvider provider, IEventManager manager) { - } } \ No newline at end of file diff --git a/NextShip.Api/Attributes/ServiceAdd.cs b/NextShip.Api/Attributes/ServiceAdd.cs index 0af7c91..58476f3 100644 --- a/NextShip.Api/Attributes/ServiceAdd.cs +++ b/NextShip.Api/Attributes/ServiceAdd.cs @@ -1,5 +1,4 @@ using System.Reflection; -using HarmonyLib; namespace NextShip.Api.Attributes; @@ -7,7 +6,7 @@ namespace NextShip.Api.Attributes; public sealed class ServiceAddAttribute : Attribute { private readonly object _instance; - + public ServiceAddAttribute() { } @@ -16,14 +15,14 @@ public ServiceAddAttribute(object instance) { _instance = instance; } - - + + public static void Registration(IServiceProvider provider, Assembly assembly) { var Fields = assembly.GetFieldInfos(); var methods = assembly.GetMethodInfos(); var constructors = assembly.GetConstructorInfos(); - + foreach (var Var in Fields.Where(n => n.Is())) { var instance = Var.GetCustomAttribute()?._instance; @@ -33,7 +32,7 @@ public static void Registration(IServiceProvider provider, Assembly assembly) var value = provider.GetService(type); Var.SetValue(null, value); } - + foreach (var Var in methods.Where(n => n.Is())) { var instance = Var.GetCustomAttribute()?._instance; @@ -42,7 +41,7 @@ public static void Registration(IServiceProvider provider, Assembly assembly) var arguments = Var.GetGenericArguments().Select(provider.GetService).ToArray(); _ = Var.Invoke(instance, arguments); } - + foreach (var Var in constructors.Where(n => n.Is())) { var arguments = Var.GetGenericArguments().Select(provider.GetService).ToArray(); diff --git a/NextShip.Api/Bases/ButtonBase.cs b/NextShip.Api/Bases/ButtonBase.cs new file mode 100644 index 0000000..b67244d --- /dev/null +++ b/NextShip.Api/Bases/ButtonBase.cs @@ -0,0 +1,30 @@ +using UnityEngine; + +namespace NextShip.Api.Bases; + +[Il2CppRegister] +public abstract class ButtonBase : MonoBehaviour +{ + public NKeyBind KeyBind; + public Action OnClick { get; set; } + + public void Start() + { + } + + public void Update() + { + } + + public void OnEnable() + { + } + + public void OnDisable() + { + } + + public void OnDestroy() + { + } +} \ No newline at end of file diff --git a/NextShip.Api/Bases/FastEventArgs.cs b/NextShip.Api/Bases/FastEventArgs.cs new file mode 100644 index 0000000..bff0520 --- /dev/null +++ b/NextShip.Api/Bases/FastEventArgs.cs @@ -0,0 +1,34 @@ +#nullable enable +namespace NextShip.Api.Bases; + +public struct FastEventArgs +{ + public string Name { get; set; } + + public string EventName { get; set; } + + public object[] Instances { get; set; } + + public FastListener _FastListener { get; set; } + + public T? Get() where T : class + { + return TryGet(out var instance) ? instance : null; + } + + public bool TryGet(out T? instance) where T : class + { + instance = null; + if (!TryGet(typeof(T), out var inGet)) return false; + instance = inGet as T; + return true; + } + + public bool TryGet(Type type, out object? instance) + { + instance = null; + if (!_FastListener.EventInstanceTypes.TryGetValue(EventName, out List? value)) return false; + instance = Instances[value.IndexOf(type)]; + return true; + } +} \ No newline at end of file diff --git a/NextShip.Api/Bases/FastListener.cs b/NextShip.Api/Bases/FastListener.cs new file mode 100644 index 0000000..5d67ec4 --- /dev/null +++ b/NextShip.Api/Bases/FastListener.cs @@ -0,0 +1,38 @@ +using HarmonyLib; + +namespace NextShip.Api.Bases; + +public class FastListener +{ + private readonly List> AllListener = []; + + public readonly Dictionary> EventInstanceTypes = new(); + + public int Register(Action action) + { + AllListener.Add(action); + return AllListener.IndexOf(action); + } + + public void UnRegister(int id) + { + AllListener.RemoveAt(id); + } + + public void Call(string eventName, object[] instances = null, string name = null) + { + if (instances != null) + { + EventInstanceTypes[eventName] = []; + foreach (var tp in instances) EventInstanceTypes[eventName].Add(tp.GetType()); + } + + AllListener.Do(n => n.Invoke(new FastEventArgs + { + Name = name, + EventName = eventName, + Instances = instances, + _FastListener = this + })); + } +} \ No newline at end of file diff --git a/NextShip.Api/Bases/NKeyBind.cs b/NextShip.Api/Bases/NKeyBind.cs index 27f7f5a..442d115 100644 --- a/NextShip.Api/Bases/NKeyBind.cs +++ b/NextShip.Api/Bases/NKeyBind.cs @@ -5,18 +5,18 @@ namespace NextShip.Api.Bases; public class NKeyBind { /// - /// 0 last + /// 0 last /// - public int Priority; + public int Priority { get; set; } /// - /// 1 key or 2 keys or 3 + /// 1 key or 2 keys or 3 /// - public int Mode; + public int Mode { get; set; } - public KeyCode[] keys; + public KeyCode[] keys { get; set; } - public int KeyCount; + public int KeyCount { get; set; } - public Action _Action; + public Action _Action { get; set; } } \ No newline at end of file diff --git a/NextShip.Api/Bases/NextInfo.cs b/NextShip.Api/Bases/NextInfo.cs index e68883b..8d28eac 100644 --- a/NextShip.Api/Bases/NextInfo.cs +++ b/NextShip.Api/Bases/NextInfo.cs @@ -23,8 +23,6 @@ public record NextInfo public PlayerControl PlayerControl; - public PlayerPhysics PlayerPhysics; - public byte PlayerId; public GameData.PlayerInfo PlayerInfo; @@ -33,6 +31,8 @@ public record NextInfo public string PlayerName; + public PlayerPhysics PlayerPhysics; + public string PUID; public IRole Role; diff --git a/NextShip.Api/Bases/OptionBase.cs b/NextShip.Api/Bases/OptionBase.cs index 61b0e25..f90bb0a 100644 --- a/NextShip.Api/Bases/OptionBase.cs +++ b/NextShip.Api/Bases/OptionBase.cs @@ -41,7 +41,10 @@ public void SetParent(IOptionInfo info) public abstract string GetValueString(); public abstract OptionBase GetBase(); - public T GetBase() where T : OptionBase => GetBase() as T; + public T GetBase() where T : OptionBase + { + return GetBase() as T; + } // 设置OptionBehaviour隐性转换 public static explicit operator OptionBehaviour(OptionBase @base) diff --git a/NextShip.Api/Enums/SystemRPCFlag.cs b/NextShip.Api/Enums/SystemRPCFlag.cs index ddc4450..08da009 100644 --- a/NextShip.Api/Enums/SystemRPCFlag.cs +++ b/NextShip.Api/Enums/SystemRPCFlag.cs @@ -4,4 +4,8 @@ public enum SystemRPCFlag : byte { VersionShare = 210, VersionShareAgain = 211, + + RpcConnectProject = 215, + + EventMessage = 220 } \ No newline at end of file diff --git a/NextShip.Api/Extension/CrowdedExtension.cs b/NextShip.Api/Extension/CrowdedExtension.cs index 478ed22..b7b2cfb 100644 --- a/NextShip.Api/Extension/CrowdedExtension.cs +++ b/NextShip.Api/Extension/CrowdedExtension.cs @@ -3,11 +3,11 @@ namespace NextShip.Api.Extension; public static class CrowdedExtension { private static bool Started; - + public static void UseCrowded() { if (Started) return; - + Started = true; } } \ No newline at end of file diff --git a/NextShip.Api/Extension/SteamExtension.cs b/NextShip.Api/Extension/SteamExtension.cs index 6e9a964..7002a06 100644 --- a/NextShip.Api/Extension/SteamExtension.cs +++ b/NextShip.Api/Extension/SteamExtension.cs @@ -14,9 +14,7 @@ public static void UseSteamIdFile() if (!File.Exists(path)) File.WriteAllText(path!, Among_Us_SteamId); else - { return; - } Info("Use steam_appid.txt"); } } \ No newline at end of file diff --git a/NextShip.Api/GlobalUsing.cs b/NextShip.Api/GlobalUsing.cs index c3fde4c..f0b99ef 100644 --- a/NextShip.Api/GlobalUsing.cs +++ b/NextShip.Api/GlobalUsing.cs @@ -1,3 +1,5 @@ +extern alias JetBrainsRoot; +global using MeansImplicitUse = MeansImplicitUseAttribute; global using NextShip.Api; global using NextShip.Api.Roles; global using NextShip.Api.Utils; diff --git a/NextShip.Api/Interfaces/IBotManager.cs b/NextShip.Api/Interfaces/IBotManager.cs index f622618..4148d62 100644 --- a/NextShip.Api/Interfaces/IBotManager.cs +++ b/NextShip.Api/Interfaces/IBotManager.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public class IBotManager { - } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/IEventListener.cs b/NextShip.Api/Interfaces/IEventListener.cs index bc97fda..fa1fe0f 100644 --- a/NextShip.Api/Interfaces/IEventListener.cs +++ b/NextShip.Api/Interfaces/IEventListener.cs @@ -2,9 +2,15 @@ namespace NextShip.Api.Interfaces; public interface IEventListener { - public void On(string name) {} - - public void On(string name, object[] Instances) {} + public void On(string name) + { + } - public void On(INextEvent @event) {} + public void On(string name, object[] Instances) + { + } + + public void On(INextEvent @event) + { + } } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILang.cs b/NextShip.Api/Interfaces/ILang.cs index 87e3acf..8f15a8f 100644 --- a/NextShip.Api/Interfaces/ILang.cs +++ b/NextShip.Api/Interfaces/ILang.cs @@ -5,7 +5,7 @@ public interface ILang public SupportedLangs LangId { get; protected set; } public string LangName { get; set; } - + public string Author { get; set; } public string GetString(string Key); @@ -13,4 +13,6 @@ public interface ILang public string GetStringOfIndex(int Index); public void Init(); + + public void Clear(); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILangLoader.cs b/NextShip.Api/Interfaces/ILangLoader.cs index 549824c..fb498ba 100644 --- a/NextShip.Api/Interfaces/ILangLoader.cs +++ b/NextShip.Api/Interfaces/ILangLoader.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public interface ILangLoader { - } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/ILangManager.cs b/NextShip.Api/Interfaces/ILangManager.cs index 5bc0a08..f29939c 100644 --- a/NextShip.Api/Interfaces/ILangManager.cs +++ b/NextShip.Api/Interfaces/ILangManager.cs @@ -9,4 +9,14 @@ public interface ILangManager public void Set(SupportedLangs langId, ILang lang); public void SetCurrentLang(SupportedLangs langId); + + public ILang GetCurrentLang(); + + public ILang GetLang(SupportedLangs langId); + + public ILang GetLang(string LangNameOrAuthor); + + public ILang[] GetLangS(SupportedLangs langId); + + public ILang[] GetLangS(string name); } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextButton.cs b/NextShip.Api/Interfaces/INextButton.cs index eda903b..410c066 100644 --- a/NextShip.Api/Interfaces/INextButton.cs +++ b/NextShip.Api/Interfaces/INextButton.cs @@ -1,6 +1,14 @@ namespace NextShip.Api.Interfaces; -public class INextButton +public interface INextButton { - + public ButtonBase Base { get; set; } + + public void OnRegister(INextButtonManager _nextButtonManager) + { + } + + public void OnUnRegister(INextButtonManager _nextButtonManager) + { + } } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextButtonManager.cs b/NextShip.Api/Interfaces/INextButtonManager.cs index fbc67f0..f0fb0a1 100644 --- a/NextShip.Api/Interfaces/INextButtonManager.cs +++ b/NextShip.Api/Interfaces/INextButtonManager.cs @@ -2,5 +2,4 @@ namespace NextShip.Api.Interfaces; public class INextButtonManager { - } \ No newline at end of file diff --git a/NextShip.Api/Interfaces/INextEvent.cs b/NextShip.Api/Interfaces/INextEvent.cs index 1ca8331..04110c8 100644 --- a/NextShip.Api/Interfaces/INextEvent.cs +++ b/NextShip.Api/Interfaces/INextEvent.cs @@ -3,7 +3,7 @@ namespace NextShip.Api.Interfaces; public interface INextEvent { public string EventName { get; set; } - + public int Id { get; set; } public void OnRegister(IEventManager eventManager); diff --git a/NextShip.Api/Interfaces/IRole.cs b/NextShip.Api/Interfaces/IRole.cs index 73cf174..b2c5f60 100644 --- a/NextShip.Api/Interfaces/IRole.cs +++ b/NextShip.Api/Interfaces/IRole.cs @@ -17,4 +17,6 @@ public interface IRole : IDisposable public Func CreateRoleBase { get; set; } public bool CanCreate(IRole role, PlayerControl player); + + public void OptionCreate(INextOptionManager _nextOptionManager); } \ No newline at end of file diff --git a/NextShip.Api/Logs/Log.cs b/NextShip.Api/Logs/Log.cs index a5c8e4f..35fc510 100644 --- a/NextShip.Api/Logs/Log.cs +++ b/NextShip.Api/Logs/Log.cs @@ -9,6 +9,8 @@ public sealed class Log { public static bool CreateEd; + private static Log? _Instance; + public TextWriter? ConsoleWriter; public StreamWriter? DiskWriter; @@ -31,8 +33,6 @@ private Log() : this(new ManualLogSource("NextShip.Api")) public ManualLogSource LogSource { get; private set; } - private static Log? _Instance; - public static Log Instance => _Instance ?? new Log(); diff --git a/NextShip.Api/NextShip.Api.csproj b/NextShip.Api/NextShip.Api.csproj index 177bf98..81faac0 100644 --- a/NextShip.Api/NextShip.Api.csproj +++ b/NextShip.Api/NextShip.Api.csproj @@ -19,19 +19,19 @@ - - + + + - + - diff --git a/NextShip.Api/RPCs/FastRpcReader.cs b/NextShip.Api/RPCs/FastRpcReader.cs index 368f796..a0dd965 100644 --- a/NextShip.Api/RPCs/FastRpcReader.cs +++ b/NextShip.Api/RPCs/FastRpcReader.cs @@ -1,7 +1,6 @@ using System.Reflection; using HarmonyLib; using Hazel; -using OtherAttribute; namespace NextShip.Api.RPCs; @@ -39,7 +38,7 @@ public static void InnerNet_ReaderPath([HarmonyArgument(0)] MessageReader reader finally { - reader.Recycle(); + HandleReader.Recycle(); } } @@ -64,4 +63,4 @@ public static void AddFormAssembly(Assembly assembly) } } } -} +} \ No newline at end of file diff --git a/NextShip.Api/RPCs/FastRpcWriter.cs b/NextShip.Api/RPCs/FastRpcWriter.cs index 35ae800..131bb11 100644 --- a/NextShip.Api/RPCs/FastRpcWriter.cs +++ b/NextShip.Api/RPCs/FastRpcWriter.cs @@ -30,6 +30,17 @@ public static FastRpcWriter StartNew() return new FastRpcWriter(); } + public static FastRpcWriter StartNewRpcWriter(SystemRPCFlag rpc) + { + var writer = StartNew(); + writer.SetRpcCallId(rpc); + writer.SetSendOption(SendOption.Reliable); + writer.SetTargetObjectId(PlayerControl.LocalPlayer.NetId); + writer.StartDataAllMessage(); + writer.StartRPCMessage(); + return writer; + } + public static FastRpcWriter StartNew(byte call, SendOption option = SendOption.None) { return new FastRpcWriter( @@ -83,6 +94,11 @@ public void SetTargetObjectId(uint id) targetObjectId = id; } + public void SetRpcCallId(SystemRPCFlag id) + { + CallId = (byte)id; + } + public void SetRpcCallId(byte id) { CallId = id; @@ -106,7 +122,7 @@ public void Set(SendOption option = SendOption.None, byte callId = byte.MaxValue if (objId != null) targetObjectId = (uint)objId; - + DebugInfo($"Set CallId{CallId} SendTargetId{targetId} TargetObjectId{targetObjectId}"); } diff --git a/NextShip.Api/Roles/SimpleRoleInfo.cs b/NextShip.Api/Roles/SimpleRoleInfo.cs index 4719870..73fd47b 100644 --- a/NextShip.Api/Roles/SimpleRoleInfo.cs +++ b/NextShip.Api/Roles/SimpleRoleInfo.cs @@ -5,28 +5,9 @@ namespace NextShip.Api.Roles; public sealed class SimpleRoleInfo { - [JsonPropertyName("Name"), JsonInclude] - public string Name { get; set; } - - [JsonPropertyName("Color"), JsonInclude] - public Color RoleColor { get; set; } - - [JsonPropertyName("EnumId"), JsonInclude] - public RoleId roleId { get; set; } - - [JsonPropertyName("IntId"), JsonInclude] - public int RoleIntId { get; set; } - - [JsonPropertyName("StringId"), JsonInclude] - public string RoleStringId { get; set; } - - [JsonPropertyName("Team"), JsonInclude] - public RoleTeam roleTeam { get; set; } - - [JsonPropertyName("Type"), JsonInclude] - public RoleType roleType { get; set; } - - public SimpleRoleInfo() {} + public SimpleRoleInfo() + { + } public SimpleRoleInfo( RoleId id, @@ -45,7 +26,7 @@ public SimpleRoleInfo( RoleStringId = roleStringId; RoleIntId = roleIntId; } - + public SimpleRoleInfo ( RoleId id, @@ -66,4 +47,32 @@ string roleName ) : this(RoleId.none, color, team, type, "", roleName, -1) { } + + [JsonPropertyName("Name")] + [JsonInclude] + public string Name { get; set; } + + [JsonPropertyName("Color")] + [JsonInclude] + public Color RoleColor { get; set; } + + [JsonPropertyName("EnumId")] + [JsonInclude] + public RoleId roleId { get; set; } + + [JsonPropertyName("IntId")] + [JsonInclude] + public int RoleIntId { get; set; } + + [JsonPropertyName("StringId")] + [JsonInclude] + public string RoleStringId { get; set; } + + [JsonPropertyName("Team")] + [JsonInclude] + public RoleTeam roleTeam { get; set; } + + [JsonPropertyName("Type")] + [JsonInclude] + public RoleType roleType { get; set; } } \ No newline at end of file diff --git a/NextShip.Api/Utils/ListUtils.cs b/NextShip.Api/Utils/ListUtils.cs index 2052303..17efffd 100644 --- a/NextShip.Api/Utils/ListUtils.cs +++ b/NextShip.Api/Utils/ListUtils.cs @@ -2,12 +2,12 @@ public static class ListUtils { - public static List GetSortList(this List list, Comparison comparison) + public static List GetSortList(this List list, Comparison comparison) { list.Sort(comparison); return list; } - + public static List GetLists(this List list, int count) { var l = new List(); diff --git a/NextShip.Api/Utils/MethodUtils.cs b/NextShip.Api/Utils/MethodUtils.cs index d9b6a56..f2236c1 100644 --- a/NextShip.Api/Utils/MethodUtils.cs +++ b/NextShip.Api/Utils/MethodUtils.cs @@ -58,21 +58,21 @@ public static List GetFieldInfos(this Assembly assembly) return types.SelectMany(varType => varType.GetFields()).ToList(); } - + public static List GetMethodInfos(this Assembly assembly) { var types = assembly.GetTypes(); return types.SelectMany(varType => varType.GetMethods()).ToList(); } - + public static List GetConstructorInfos(this Assembly assembly) { var types = assembly.GetTypes(); return types.SelectMany(varType => varType.GetConstructors()).ToList(); } - + public static List GetMemberInfos(this Assembly assembly) { var types = assembly.GetTypes(); diff --git a/NextShip.Api/Utils/ServerUtils.cs b/NextShip.Api/Utils/ServerUtils.cs index 7f759e1..ecb024f 100644 --- a/NextShip.Api/Utils/ServerUtils.cs +++ b/NextShip.Api/Utils/ServerUtils.cs @@ -4,17 +4,21 @@ namespace NextShip.Api.Utils; public static class ServerUtils { - public static void AddServer(IRegionInfo region) => + public static void AddServer(IRegionInfo region) + { ServerManager.Instance.AddOrUpdateRegion(region); + } - public static void AddServers(IEnumerable regionInfos) => + public static void AddServers(IEnumerable regionInfos) + { regionInfos.Do(ServerManager.Instance.AddOrUpdateRegion); - + } + public static List CreateHttpInfos(params (string ip, string name, ushort port, bool isHttps)[] Infos) { return Infos.Select(tuple => createHttpInfo(tuple.ip, tuple.name, tuple.port, tuple.isHttps)).ToList(); } - + public static IRegionInfo createHttpInfo(string ip, string name, ushort port, bool isHttps = false) { var serverIp = isHttps ? "https://" : "http://" + ip; @@ -22,7 +26,7 @@ public static IRegionInfo createHttpInfo(string ip, string name, ushort port, bo ServerInfo[] ServerInfo = [serverInfo]; return new StaticHttpRegionInfo(name, StringNames.NoTranslation, ip, ServerInfo).CastFast(); } - + public static bool IsVanilla(this IRegionInfo regionInfo) { return regionInfo.TranslateName is StringNames.ServerAS or StringNames.ServerEU or StringNames.ServerNA diff --git a/NextShip.Api/Utils/SpriteUtils.cs b/NextShip.Api/Utils/SpriteUtils.cs index 519e202..a818f84 100644 --- a/NextShip.Api/Utils/SpriteUtils.cs +++ b/NextShip.Api/Utils/SpriteUtils.cs @@ -79,7 +79,7 @@ public static Sprite ToFullRect(this Sprite sprite, string name = "") return FullRectSprite; } - public static unsafe Texture2D? LoadTextureFromResources(string path) + public static Texture2D? LoadTextureFromResources(string path) { try { diff --git a/NextShip.Api/Utils/StreamUtils.cs b/NextShip.Api/Utils/StreamUtils.cs index 2557c00..77eb0db 100644 --- a/NextShip.Api/Utils/StreamUtils.cs +++ b/NextShip.Api/Utils/StreamUtils.cs @@ -21,7 +21,7 @@ public static DirectoryInfo GetDir(string name) { return assembly.GetManifestResourceStream(string.Join(".", path)); } - + public static unsafe Span ToSpan(this Il2CppStructArray array) where T : unmanaged { return new Span(IntPtr.Add(array.Pointer, IntPtr.Size * 4).ToPointer(), array.Length); diff --git a/NextShip.SourceGenerator/BuildInfoGenerator.cs b/NextShip.SourceGenerator/BuildInfoGenerator.cs index 5de5940..2776be0 100644 --- a/NextShip.SourceGenerator/BuildInfoGenerator.cs +++ b/NextShip.SourceGenerator/BuildInfoGenerator.cs @@ -5,9 +5,8 @@ namespace NextShip.SourceGenerator; [Generator(LanguageNames.CSharp)] public class BuildInfoGenerator : IIncrementalGenerator { - public void Initialize(IncrementalGeneratorInitializationContext context) { - var Time = DateTime.Now.ToString("G").Replace(" ", "-").Replace("/", "-"); + var Time = DateTime.Now.ToString("G").Replace(" ", "-").Replace("/", "-"); } } \ No newline at end of file diff --git a/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj b/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj index ed903e9..e71a964 100644 --- a/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj +++ b/NextShip.SourceGenerator/NextShip.SourceGenerator.csproj @@ -10,10 +10,10 @@ - + - all - runtime; build; native; contentfiles; analyzers; buildtransitive + all + runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/NextShip.sln b/NextShip.sln index 446ab8b..4363a81 100644 --- a/NextShip.sln +++ b/NextShip.sln @@ -8,8 +8,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NextShip.SourceGenerator", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NSLangAnalyzer", "NSLangAnalyzer\NSLangAnalyzer.csproj", "{81EC6168-530F-45B4-92A5-5FFEB719C0A7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OtherAttribute", "OtherAttribute\OtherAttribute.csproj", "{5E9827F3-7B33-4FB0-A0E5-C95677F66F49}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -32,9 +30,5 @@ Global {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Debug|Any CPU.Build.0 = Debug|Any CPU {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Release|Any CPU.ActiveCfg = Release|Any CPU {81EC6168-530F-45B4-92A5-5FFEB719C0A7}.Release|Any CPU.Build.0 = Release|Any CPU - {5E9827F3-7B33-4FB0-A0E5-C95677F66F49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5E9827F3-7B33-4FB0-A0E5-C95677F66F49}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5E9827F3-7B33-4FB0-A0E5-C95677F66F49}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5E9827F3-7B33-4FB0-A0E5-C95677F66F49}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/NextShip/Buttons/NextButton.cs b/NextShip/Buttons/NextButton.cs new file mode 100644 index 0000000..a2e96f9 --- /dev/null +++ b/NextShip/Buttons/NextButton.cs @@ -0,0 +1,9 @@ +using NextShip.Api.Bases; +using NextShip.Api.Interfaces; + +namespace NextShip.Buttons; + +public class NextButton : INextButton +{ + public ButtonBase Base { get; set; } +} \ No newline at end of file diff --git a/NextShip/Cosmetics/CosmeticsChecks.cs b/NextShip/Cosmetics/CosmeticsChecks.cs index 7075f34..6fac541 100644 --- a/NextShip/Cosmetics/CosmeticsChecks.cs +++ b/NextShip/Cosmetics/CosmeticsChecks.cs @@ -1,6 +1,5 @@ using System.Collections; using System.IO; -using NextShip.Api.Attributes; namespace NextShip.Cosmetics; diff --git a/NextShip/Cosmetics/CosmeticsCreator.cs b/NextShip/Cosmetics/CosmeticsCreator.cs index 7e6e704..5c24046 100644 --- a/NextShip/Cosmetics/CosmeticsCreator.cs +++ b/NextShip/Cosmetics/CosmeticsCreator.cs @@ -8,8 +8,6 @@ namespace NextShip.Cosmetics; public class CosmeticsCreator(List allSprites) { - private static Material hatShader; - public readonly List AllSprites = allSprites; private Sprite Get(string name) @@ -19,14 +17,15 @@ private Sprite Get(string name) public (HatViewData, HatData) CreateHat(CosmeticsInfo info) { - if (hatShader == null) hatShader = FastDestroyableSingleton.Instance.PlayerMaterial; - var hatData = ScriptableObject.CreateInstance(); var hatView = ScriptableObject.CreateInstance(); + hatView.MatchPlayerColor = info.Adaptive; hatView.MainImage = hatView.FloorImage = Get(info.Resource); - if (info.ClimbResource != null) hatView.LeftClimbImage = hatView.ClimbImage = Get(info.ClimbResource); - if (info.Adaptive && hatShader != null) hatView.AltShader = hatShader; + + if (info.ClimbResource != null) + hatView.LeftClimbImage = hatView.ClimbImage = Get(info.ClimbResource); + if (info.BackResource != null) { hatView.BackImage = Get(info.BackResource); diff --git a/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs b/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs index bed539f..fd045f7 100644 --- a/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs +++ b/NextShip/Cosmetics/Loaders/CosmeticsLoader.cs @@ -13,11 +13,10 @@ public abstract class CosmeticsLoader public readonly List AllHat; public readonly List AllNamePlate; public readonly List AllSprite; + public readonly List AllVisor; public readonly Dictionary> Hats = new(); - public List AllVisor; - protected CosmeticsLoader() { CustomCosmeticsManager.AllLoaders.Add(this); diff --git a/NextShip/DIY/Plugins/PluginLoadInfo.cs b/NextShip/DIY/Plugins/PluginLoadInfo.cs index 615010e..0eef87c 100644 --- a/NextShip/DIY/Plugins/PluginLoadInfo.cs +++ b/NextShip/DIY/Plugins/PluginLoadInfo.cs @@ -1,6 +1,5 @@ using System; using System.Reflection; -using NextShip.Api.Attributes; using NextShip.Api.Bases; namespace NextShip.DIY.Plugins; diff --git a/NextShip/DIY/Plugins/PluginLoadService.cs b/NextShip/DIY/Plugins/PluginLoadService.cs index c1bc4bc..ee71011 100644 --- a/NextShip/DIY/Plugins/PluginLoadService.cs +++ b/NextShip/DIY/Plugins/PluginLoadService.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Reflection; using Microsoft.Extensions.DependencyInjection; -using NextShip.Api.Attributes; using NextShip.Api.Bases; namespace NextShip.DIY.Plugins; diff --git a/NextShip/DIY/Plugins/PluginManager.cs b/NextShip/DIY/Plugins/PluginManager.cs index e7ae1d2..d32f498 100644 --- a/NextShip/DIY/Plugins/PluginManager.cs +++ b/NextShip/DIY/Plugins/PluginManager.cs @@ -6,7 +6,6 @@ using HarmonyLib; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileSystemGlobbing; -using NextShip.Api.Attributes; using NextShip.Api.Bases; using NextShip.Api.Interfaces; using NextShip.Services; @@ -16,10 +15,10 @@ namespace NextShip.DIY.Plugins; public class PluginManager : Manager { private readonly List<(Assembly, Type, ShipPlugin)> PluginCreateS = []; - internal List PluginLoadInfos = []; private readonly List PluginPathS = []; public readonly List Plugins = []; + internal List PluginLoadInfos = []; public void InitPlugins() diff --git a/NextShip/GlobalUsings.cs b/NextShip/GlobalUsings.cs index 2a353db..b9d746a 100644 --- a/NextShip/GlobalUsings.cs +++ b/NextShip/GlobalUsings.cs @@ -2,6 +2,7 @@ global using NextShip.Api.Utils; global using NextShip.Api.Roles; global using NextShip.Api.Utilities; +global using NextShip.Api.Attributes; global using static NextShip.Api.Logs.FastLog; global using static NextShip.Manager.EventManager; global using Main = NextShip.NextShip; \ No newline at end of file diff --git a/NextShip/LogInfos/RPCInfoLog.cs b/NextShip/LogInfos/RPCInfoLog.cs index e757bd4..f3b59c0 100644 --- a/NextShip/LogInfos/RPCInfoLog.cs +++ b/NextShip/LogInfos/RPCInfoLog.cs @@ -13,14 +13,22 @@ public class RPCInfoLog [HarmonyPatch] internal static class RPCInfoLogPatch { - private static IEnumerable InnerNetObjectTypes { get; } = typeof(InnerNetObject).Assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(InnerNetObject))).ToList(); + private static IEnumerable InnerNetObjectTypes { get; } = typeof(InnerNetObject).Assembly.GetTypes() + .Where(x => x.IsSubclassOf(typeof(InnerNetObject))).ToList(); public static IEnumerable TargetMethods() { - return InnerNetObjectTypes.Select(x => x.GetMethod(nameof(InnerNetObject.HandleRpc), AccessTools.allDeclared)).Where(m => m != null)!; + return InnerNetObjectTypes + .Select(x => x.GetMethod(nameof(InnerNetObject.HandleRpc), AccessTools.allDeclared)) + .Where(m => m != null)!; } - public static void Prefix(InnerNetObject __instance, [HarmonyArgument(0)] byte callId, [HarmonyArgument(1)] MessageReader reader) - => Info($"RPCHandle {nameof(__instance)} CallId{callId} Length:{reader.Length} Pos:{reader.Position} Tag:{reader.Tag}", "RPCInfoLog"); + public static void Prefix(InnerNetObject __instance, [HarmonyArgument(0)] byte callId, + [HarmonyArgument(1)] MessageReader reader) + { + Info( + $"RPCHandle {nameof(__instance)} CallId{callId} Length:{reader.Length} Pos:{reader.Position} Tag:{reader.Tag}", + "RPCInfoLog"); + } } } \ No newline at end of file diff --git a/NextShip/Manager/EventManager.cs b/NextShip/Manager/EventManager.cs index 7dbb753..4f01249 100644 --- a/NextShip/Manager/EventManager.cs +++ b/NextShip/Manager/EventManager.cs @@ -2,28 +2,28 @@ using System.Collections.Generic; using System.Linq; using HarmonyLib; +using NextShip.Api.Bases; +using NextShip.Api.Enums; using NextShip.Api.Interfaces; +using NextShip.Api.RPCs; namespace NextShip.Manager; public class EventManager : IEventManager { - public static readonly EventManager _eventManager = Main._Service.Get(); - private readonly HashSet EventListeners = []; private readonly List RegisterEvents = []; private FastListener _listener; - public FastListener GetFastListener() => _listener ??= new FastListener(); - - public void CallEvent(T @event) where T : INextEvent + public EventManager() { - foreach (var _event in RegisterEvents.FindAll(n => n.EventName == @event.EventName && n is T)) - @event.Call(_event); + _eventManager = this; } - + + public static EventManager _eventManager { get; private set; } + public void RegisterEvent(INextEvent @event) { @event.OnRegister(this); @@ -36,6 +36,17 @@ public void UnRegisterEvent(INextEvent @event) RegisterEvents.Remove(@event); } + public FastListener GetFastListener() + { + return _listener ??= new FastListener(); + } + + public void CallEvent(T @event) where T : INextEvent + { + foreach (var _event in RegisterEvents.FindAll(n => n.EventName == @event.EventName && n is T)) + @event.Call(_event); + } + public void RegisterListener(IEventListener listener) { EventListeners.Add(listener); @@ -56,7 +67,20 @@ public void CallListener(string name) { EventListeners.Do(n => n.On(name)); } - + + public void CallListenerToRPC(string name, object[] instances = null) + { + var writer = FastRpcWriter.StartNewRpcWriter(SystemRPCFlag.EventMessage); + writer.Write(name); + if (instances != null) + { + writer.WritePacked(instances.Length); + foreach (var obj in instances) writer.Write(obj.GetType().Name); + } + + writer.RPCSend(); + } + public void CallListener(string name, object[] Instances) { EventListeners.Do(n => n.On(name, Instances)); @@ -88,24 +112,4 @@ public INextEvent GetEvent(Type type) { return RegisterEvents.FirstOrDefault(n => n.GetType() == type); } -} - -public class FastListener -{ - private readonly List> AllListener = []; - - public void Register(Action action) - { - AllListener.Add(action); - } - - public void UnRegister(Action action) - { - AllListener.Remove(action); - } - - public void Call(string name, object[] instances = null) - { - AllListener.Do(n => n.Invoke(name, instances)); - } } \ No newline at end of file diff --git a/NextShip/Manager/InstanceManager.cs b/NextShip/Manager/InstanceManager.cs index 620f642..49b3c61 100644 --- a/NextShip/Manager/InstanceManager.cs +++ b/NextShip/Manager/InstanceManager.cs @@ -15,25 +15,32 @@ public class InstanceManager public void RegisterInstance(T instance) { - if (instance != null) + if (instance != null) RegisterInstance(typeof(T), instance); else - { Error("实例添加失败为空"); - } } - public void RegisterInstance(Type type, object obj) => (Instances[type] ??= []).Add(obj); + public void RegisterInstance(Type type, object obj) + { + (Instances[type] ??= []).Add(obj); + } + + public T? Get() where T : class + { + return Get(typeof(T)) as T; + } - public T? Get() where T : class => Get(typeof(T)) as T; - - public List? Gets() where T : class => Gets(typeof(T)) as List; + public List? Gets() where T : class + { + return Gets(typeof(T)) as List; + } public object? Get(Type type) { return Instances.FirstOrDefault(n => n.Key == type).Value?.FirstOrDefault(); } - + public IEnumerable? Gets(Type type) { return Instances.FirstOrDefault(n => n.Key == type).Value; @@ -43,7 +50,8 @@ public void RegisterInstance(T instance) [HarmonyPatch] internal static class InstanceManagerPatch { - private static IEnumerable InnerNetObjectTypes { get; } = typeof(InnerNetObject).Assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(MonoBehaviour))).ToList(); + private static IEnumerable InnerNetObjectTypes { get; } = typeof(InnerNetObject).Assembly.GetTypes() + .Where(x => x.IsSubclassOf(typeof(MonoBehaviour))).ToList(); public static IEnumerable TargetMethods() { @@ -53,10 +61,7 @@ public static IEnumerable TargetMethods() public static void Postfix(MonoBehaviour __instance) { var manager = Main._Service.Get(); - foreach (var (key, value) in manager.Instances) - { - value?.RemoveAll(n => n == null); - } + foreach (var (key, value) in manager.Instances) value?.RemoveAll(n => n == null); manager.RegisterInstance(__instance); } } \ No newline at end of file diff --git a/NextShip/Manager/NextBotManager.cs b/NextShip/Manager/NextBotManager.cs index d181405..94dfef1 100644 --- a/NextShip/Manager/NextBotManager.cs +++ b/NextShip/Manager/NextBotManager.cs @@ -4,5 +4,4 @@ namespace NextShip.Manager; public class NextBotManager : IBotManager { - } \ No newline at end of file diff --git a/NextShip/Manager/NextButtonsManager.cs b/NextShip/Manager/NextButtonsManager.cs index 9aa95ce..981f5ab 100644 --- a/NextShip/Manager/NextButtonsManager.cs +++ b/NextShip/Manager/NextButtonsManager.cs @@ -1,7 +1,42 @@ -using NextShip.Api.Interfaces; +using System; +using System.Collections.Generic; +using System.Linq; +using HarmonyLib; +using NextShip.Api.Interfaces; namespace NextShip.Manager; +[Harmony] public class NextButtonsManager : INextButtonManager { + private readonly List allButtons = []; + + + public void RegisterButton(INextButton button) + { + allButtons.Add(button); + } + + public void UnRegisterButton(INextButton button) + { + allButtons.Remove(button); + } + + public INextButton GetButton(Func Finer) + { + return allButtons.FirstOrDefault(Finer); + } + + [HarmonyPatch(typeof(HudManager), nameof(HudManager.Start))] + [HarmonyPostfix] + public static void OnHudManagerStart(HudManager __instance) + { + } + + + [HarmonyPatch(typeof(HudManager), nameof(HudManager.OnGameStart))] + [HarmonyPostfix] + public static void OnHudManagerGameStart(HudManager __instance) + { + } } \ No newline at end of file diff --git a/NextShip/Manager/NextKeyBindManager.cs b/NextShip/Manager/NextKeyBindManager.cs index 55584ac..4610335 100644 --- a/NextShip/Manager/NextKeyBindManager.cs +++ b/NextShip/Manager/NextKeyBindManager.cs @@ -9,43 +9,37 @@ public class NextKeyBindManager : IKeyBindManager { private readonly List _keyBinds = []; - private int CurrentPriority; - private int CurrentMode; - private int MaxPriority; + private int CurrentPriority; private int MaxMode; + private int MaxPriority; + public NextKeyBindManager(NextManager _nextManager) { _nextManager.OnUpdate += OnUpdate; } - + public void AddBind(NKeyBind bind) { _keyBinds.Add(bind); - if (bind.Priority > MaxPriority) - { - MaxPriority = bind.Priority; - } + if (bind.Priority > MaxPriority) MaxPriority = bind.Priority; - if (bind.Mode > MaxMode) - { - MaxMode = bind.Mode; - } + if (bind.Mode > MaxMode) MaxMode = bind.Mode; } public void RemoveBind(NKeyBind bind) { _keyBinds.Remove(bind); -get: + get: if (_keyBinds.All(n => n.Priority != MaxPriority) && MaxPriority > 0) { MaxPriority--; goto get; } - + if (_keyBinds.All(n => n.Mode != MaxMode) && MaxMode > 1) { MaxMode--; @@ -64,15 +58,13 @@ private void OnUpdate() break; } - if (CanGet()) - { - goto Start; - } + if (CanGet()) goto Start; } private List getNKeyBinds() { - return _keyBinds.FindAll(n => n.Mode == CurrentMode).GetSortList((x, y) => sort(x.Priority, x.Priority)).FindAll(n => n.Priority == CurrentPriority); + return _keyBinds.FindAll(n => n.Mode == CurrentMode).GetSortList((x, y) => sort(x.Priority, x.Priority)) + .FindAll(n => n.Priority == CurrentPriority); int sort(int x, int y) { diff --git a/NextShip/Manager/NextLangManager.cs b/NextShip/Manager/NextLangManager.cs index f62ba6c..ab9ed68 100644 --- a/NextShip/Manager/NextLangManager.cs +++ b/NextShip/Manager/NextLangManager.cs @@ -1,23 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using AmongUs.Data; using NextShip.Api.Interfaces; namespace NextShip.Manager; +#nullable enable public class NextLangManager : ILangManager { + private readonly List AllLang = []; + + private readonly Dictionary Current = new(); + + public NextLangManager() + { + DataManager.Settings.Language.OnLanguageChanged += (Action)(() => + { + SetCurrentLang(DataManager.Settings.Language.CurrentLanguage); + }); + } + + public SupportedLangs CurrentLang { get; private set; } + public void RegisterLang(ILang lang) { + if (!Current.ContainsKey(lang.LangId)) + Set(lang.LangId, lang); + + AllLang.Add(lang); + lang.Init(); } public void UnRegisterLang(ILang lang) { + if (Current[lang.LangId] == lang) + Current.Remove(lang.LangId); + + AllLang.Remove(lang); + lang.Clear(); } public void Set(SupportedLangs langId, ILang lang) { + Current[langId] = lang; } public void SetCurrentLang(SupportedLangs langId) { - + CurrentLang = langId; + } + + public ILang GetCurrentLang() + { + return Current[CurrentLang]; + } + + public ILang GetLang(SupportedLangs langId) + { + return Current[langId]; + } + + public ILang GetLang(string LangNameOrAuthor) + { + return AllLang.FirstOrDefault(n => n.LangName == LangNameOrAuthor || n.Author == LangNameOrAuthor)!; + } + + public ILang[] GetLangS(SupportedLangs langId) + { + return AllLang.FindAll(n => n.LangId == langId).ToArray(); + } + + public ILang[] GetLangS(string name) + { + return AllLang.FindAll(n => n.LangName == name || n.Author == name).ToArray(); } } \ No newline at end of file diff --git a/NextShip/Manager/NextManager.cs b/NextShip/Manager/NextManager.cs index 4428fed..b1f3b66 100644 --- a/NextShip/Manager/NextManager.cs +++ b/NextShip/Manager/NextManager.cs @@ -1,5 +1,4 @@ using System; -using NextShip.Api.Attributes; using NextShip.Api.Bases; using NextShip.Api.UI; using UnityEngine; @@ -11,8 +10,6 @@ public class NextManager : MonoBehaviour { public readonly UpdateTasker _Tasker = new(); - public event Action OnUpdate; - public void Update() { NextUIManager.Instance.Update(); @@ -28,4 +25,6 @@ public void LateUpdate() { _Tasker.LateUpdate(); } + + public event Action OnUpdate; } \ No newline at end of file diff --git a/NextShip/Manager/NextOptionManager.cs b/NextShip/Manager/NextOptionManager.cs index f100151..524e132 100644 --- a/NextShip/Manager/NextOptionManager.cs +++ b/NextShip/Manager/NextOptionManager.cs @@ -1,40 +1,57 @@ using System.Collections.Generic; using System.Linq; +using HarmonyLib; using NextShip.Api.Bases; using NextShip.Api.Interfaces; +using NextShip.Options; +using NextShip.UI.Components; +using NextShip.UI.Module; namespace NextShip.Manager; public class NextOptionManager : INextOptionManager { - public List AllOptionBases = []; + private readonly NextRoleManager _RoleManager; + public readonly List AllOptionBases = []; - public void RegisterOptions(IEnumerable options) + public NextOptionManager(NextRoleManager roleManager, EventManager eventManager) { - var optionBases = options.ToList(); - foreach (var option in optionBases) + _RoleManager = roleManager; + + eventManager.GetFastListener().Register(OnFastListener); + } + + private void OnFastListener(FastEventArgs args) + { + if (args.EventName == "OptionCreate") { - Register(option); + var _optionMenu = args.Get(); + var _MenuOption = args.Get(); + DefOption.OptionCreate(this); + _RoleManager.Roles.Do(n => n.OptionCreate(this)); } + } + + public void RegisterOptions(IEnumerable options) + { + var optionBases = options.ToList(); + foreach (var option in optionBases) Register(option); AllOptionBases.AddRange(optionBases); } - + public void RegisterOption(T option) where T : OptionBase { - } private void Register(OptionBase option) { } - + public void GetOption(int id) where T : OptionBase { - } - + public void GetOption(string Title) where T : OptionBase { - } } \ No newline at end of file diff --git a/NextShip/Manager/NextRoleManager.cs b/NextShip/Manager/NextRoleManager.cs index 6cb32f0..f4e947a 100644 --- a/NextShip/Manager/NextRoleManager.cs +++ b/NextShip/Manager/NextRoleManager.cs @@ -41,8 +41,11 @@ public void CheckRoles() { } - public IRoleCreator GetCreator() => CurrentCreator ?? FastGetCreator(); - + public IRoleCreator GetCreator() + { + return CurrentCreator ?? FastGetCreator(); + } + public FastCreator FastGetCreator() { if (CurrentCreator is FastCreator creator) diff --git a/NextShip/Manager/NextScreenManager.cs b/NextShip/Manager/NextScreenManager.cs index 7cfc18b..92e6be0 100644 --- a/NextShip/Manager/NextScreenManager.cs +++ b/NextShip/Manager/NextScreenManager.cs @@ -4,5 +4,4 @@ namespace NextShip.Manager; public class NextScreenManager : INextScreenManager { - } \ No newline at end of file diff --git a/NextShip/Manager/RegisterManager.cs b/NextShip/Manager/RegisterManager.cs index b25e7c8..861f501 100644 --- a/NextShip/Manager/RegisterManager.cs +++ b/NextShip/Manager/RegisterManager.cs @@ -1,7 +1,6 @@ using System; using System.Reflection; using HarmonyLib; -using NextShip.Api.Attributes; namespace NextShip.Manager; diff --git a/NextShip/NextEvents/HudManagerUpdateEvent.cs b/NextShip/NextEvents/HudManagerUpdateEvent.cs index 7d98f7b..91a952f 100644 --- a/NextShip/NextEvents/HudManagerUpdateEvent.cs +++ b/NextShip/NextEvents/HudManagerUpdateEvent.cs @@ -4,11 +4,10 @@ namespace NextShip.NextEvents; public class HudManagerUpdateEvent(HudManager Instance) : INextEvent { + public HudManager _HudManager = Instance; public string EventName { get; set; } - - public int Id { get; set; } - public HudManager _HudManager = Instance; + public int Id { get; set; } public void OnRegister(IEventManager eventManager) @@ -21,6 +20,5 @@ public void OnUnRegister(IEventManager eventManager) public void Call(INextEvent @event) { - } } \ No newline at end of file diff --git a/NextShip/NextShip.csproj b/NextShip/NextShip.csproj index 6fe9795..4d94cbe 100644 --- a/NextShip/NextShip.csproj +++ b/NextShip/NextShip.csproj @@ -30,8 +30,8 @@ - - + + diff --git a/NextShip/Options/DefOption.cs b/NextShip/Options/DefOption.cs new file mode 100644 index 0000000..341b3f7 --- /dev/null +++ b/NextShip/Options/DefOption.cs @@ -0,0 +1,10 @@ +using NextShip.Api.Interfaces; + +namespace NextShip.Options; + +public static class DefOption +{ + public static void OptionCreate(INextOptionManager _nextOptionManager) + { + } +} \ No newline at end of file diff --git a/NextShip/Options/Patches/OptionsConsolePatch.cs b/NextShip/Options/Patches/OptionsConsolePatch.cs index a9978f2..c356be1 100644 --- a/NextShip/Options/Patches/OptionsConsolePatch.cs +++ b/NextShip/Options/Patches/OptionsConsolePatch.cs @@ -20,8 +20,6 @@ public class OptionsConsolePatch [HarmonyPrefix] public static bool OptionsConsoleUsePatch(OptionsConsole __instance) { - /*if (!AllowNoHostUse) return true;*/ - var @object = PlayerControl.LocalPlayer; var couldUse = @object.CanMove; var canUse = @@ -36,17 +34,16 @@ public static bool OptionsConsoleUsePatch(OptionsConsole __instance) nextOptionMenu ??= new NextOptionMenu(__instance, NextMenuParent); nextOptionMenu.__instance = __instance; - if (!nextOptionMenu.Initd) nextOptionMenu.Init(); + if (!nextOptionMenu.Initd) + nextOptionMenu.Init(); if (nextOptionMenu.Initd) OpenNextOptionMenu(__instance); - else - OpenVanillaOptionMenu(__instance); return false; } - public static void OpenVanillaOptionMenu(OptionsConsole __instance) + /*public static void OpenVanillaOptionMenu(OptionsConsole __instance) { if (!Camera.main) return; PlayerControl.LocalPlayer.NetTransform.Halt(); @@ -54,14 +51,15 @@ public static void OpenVanillaOptionMenu(OptionsConsole __instance) optionMenu.transform.localPosition = __instance.CustomPosition; FastDestroyableSingleton.Instance.DoTransitionFade(null, optionMenu.gameObject, null); IsNextMenu = false; - } + }*/ private static void OpenNextOptionMenu(OptionsConsole __instance) { if (!Camera.main) return; IsNextMenu = NextOptionMenu.Instance.OpenMenu(__instance.CustomPosition); - if (!IsNextMenu) OpenVanillaOptionMenu(__instance); + /*if (!IsNextMenu) + OpenVanillaOptionMenu(__instance);*/ } [HarmonyPatch(typeof(HudManager), nameof(HudManager.Start))] diff --git a/NextShip/Patches/GameStartManagerPatch.cs b/NextShip/Patches/GameStartManagerPatch.cs index 2e4a7de..0012474 100644 --- a/NextShip/Patches/GameStartManagerPatch.cs +++ b/NextShip/Patches/GameStartManagerPatch.cs @@ -1,4 +1,3 @@ -using System.Linq; using HarmonyLib; namespace NextShip.Patches; @@ -10,6 +9,5 @@ public static class GameStartManagerPatch [HarmonyPostfix] public static void OnGameStartManagerUpdatePatch() { - } } \ No newline at end of file diff --git a/NextShip/Patches/HudPatch.cs b/NextShip/Patches/HudPatch.cs index 7c2ea70..4aafd06 100644 --- a/NextShip/Patches/HudPatch.cs +++ b/NextShip/Patches/HudPatch.cs @@ -94,10 +94,10 @@ private static bool CheckForModification(ChatController __instance, PlayerContro [Harmony] public static class OnHudManagerUpdatePatch { - [HarmonyPatch(typeof(HudManager), nameof(HudManager.Update)), HarmonyPostfix] + [HarmonyPatch(typeof(HudManager), nameof(HudManager.Update))] + [HarmonyPostfix] public static void OnHudManagerUpdate(HudManager __instance) { _eventManager.CallEvent(new HudManagerUpdateEvent(__instance)); } -} - +} \ No newline at end of file diff --git a/NextShip/Patches/IntroPatch.cs b/NextShip/Patches/IntroPatch.cs index bf7e287..2918998 100644 --- a/NextShip/Patches/IntroPatch.cs +++ b/NextShip/Patches/IntroPatch.cs @@ -5,18 +5,15 @@ namespace NextShip.Patches; [Harmony] internal class ShowRolePatch { - [HarmonyPatch(typeof(IntroCutscene), nameof(IntroCutscene.ShowRole))] [HarmonyPrefix] public static void OnShouRolePatch(IntroCutscene __instance) { - } - + [HarmonyPatch(typeof(IntroCutscene), nameof(IntroCutscene.ShowTeam))] [HarmonyPrefix] public static void OnShouTeamPatch(IntroCutscene __instance) { - } } \ No newline at end of file diff --git a/NextShip/Patches/PlayerPatch.cs b/NextShip/Patches/PlayerPatch.cs index 59ab2a3..0a5fbc9 100644 --- a/NextShip/Patches/PlayerPatch.cs +++ b/NextShip/Patches/PlayerPatch.cs @@ -2,11 +2,9 @@ using HarmonyLib; using Hazel; using InnerNet; -using JetBrains.Annotations; using NextShip.Api.Enums; using NextShip.Api.RPCs; using NextShip.Manager; -using OtherAttribute; namespace NextShip.Patches; @@ -50,9 +48,10 @@ public static void OnPlayerJoined(AmongUsClient __instance) writer.Write(PlayerControl.LocalPlayer.PlayerId); Main.Version.Write(writer); writer.Write(Main.BepInExVersion); - + if (!AllPlayerVersionInfos.Exists(n => n.Player == CachedPlayer.LocalPlayer.PlayerControl)) - AllPlayerVersionInfos.Add(new PlayerVersionInfo(CachedPlayer.LocalPlayer.PlayerControl, Main.Version, Main.BepInExVersion)); + AllPlayerVersionInfos.Add(new PlayerVersionInfo(CachedPlayer.LocalPlayer.PlayerControl, Main.Version, + Main.BepInExVersion)); } [FastReadAdd((byte)SystemRPCFlag.VersionShare)] diff --git a/NextShip/Patches/RPCSyncPatch.cs b/NextShip/Patches/RPCSyncPatch.cs new file mode 100644 index 0000000..3b24194 --- /dev/null +++ b/NextShip/Patches/RPCSyncPatch.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using Hazel; +using NextShip.Api.Enums; + +namespace NextShip.Patches; + +[HarmonyPatch] +public static class RPCSyncPatch +{ + public static readonly List AllDefRpcS = []; + + + [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.HandleGameDataInner))] + [HarmonyPrefix] + public static bool OnHandleGameDataInnerPreFix(AmongUsClient __instance, [HarmonyArgument(0)] MessageReader reader) + { + var Has = false; + var HandleReader = MessageReader.Get(reader); + HandleReader.Position = 0; + var tag = reader.Tag; + if (tag != (byte)DataFlags.Rpc) + return true; + try + { + HandleReader.ReadPackedUInt32(); + var callId = HandleReader.ReadByte(); + Has = AllDefRpcS.Exists(n => n.HasRPC(callId)); + AllDefRpcS.Do(n => + { + var read = MessageReader.Get(HandleReader); + n.OnRPC(ref read); + read.Recycle(); + }); + } + catch (Exception e) + { + Exception(e); + } + + finally + { + HandleReader.Recycle(); + } + + return !Has; + } +} + +public abstract class DefRPC +{ + protected DefRPC() + { + RPCSyncPatch.AllDefRpcS.Add(this); + } + + public abstract bool HasRPC(byte rpcFlag); + + public abstract void OnRPC(ref MessageReader reader); +} \ No newline at end of file diff --git a/NextShip/Patches/RoleAssignmentPatch.cs b/NextShip/Patches/RoleAssignmentPatch.cs index 6b56977..7d3c6f0 100644 --- a/NextShip/Patches/RoleAssignmentPatch.cs +++ b/NextShip/Patches/RoleAssignmentPatch.cs @@ -2,7 +2,6 @@ using System.Linq; using AmongUs.GameOptions; using HarmonyLib; -using NextShip.Api.Attributes; using NextShip.Manager; using UnityEngine; diff --git a/NextShip/Patches/UpdatePatch.cs b/NextShip/Patches/UpdatePatch.cs index 7c53178..d9b2dba 100644 --- a/NextShip/Patches/UpdatePatch.cs +++ b/NextShip/Patches/UpdatePatch.cs @@ -16,12 +16,6 @@ private static void setPlayerNameColor(PlayerControl p, Color color) player.NameText.color = color; } - private static void SetNameColors() - { - var localPlayer = CachedPlayer.LocalPlayer.PlayerControl; - - } - private static void updateVentButton(HudManager __instance) { if (MeetingHud.Instance || CachedPlayer.LocalPlayer.Data.IsDead) __instance.ImpostorVentButton.Hide(); @@ -48,7 +42,6 @@ private static void updateMapButton(HudManager __instance) private static void Postfix(HudManager __instance) { if (AmongUsClient.Instance.GameState != InnerNetClient.GameStates.Started) return; - SetNameColors(); updateVentButton(__instance); updateSabotageButton(__instance); updateUseButton(__instance); diff --git a/NextShip/Roles/Crewmate/Sheriff.cs b/NextShip/Roles/Crewmate/Sheriff.cs index c91b1ce..b270606 100644 --- a/NextShip/Roles/Crewmate/Sheriff.cs +++ b/NextShip/Roles/Crewmate/Sheriff.cs @@ -3,8 +3,6 @@ using NextShip.Api.Bases; using NextShip.Api.Interfaces; using NextShip.Manager; -using NextShip.Services; -using OtherAttribute; using UnityEngine; namespace NextShip.Roles.Crewmate; @@ -12,16 +10,21 @@ namespace NextShip.Roles.Crewmate; [FastAddRole] public class Sheriff : IRole { + public List AllOption = []; + + public Sheriff() + { + var manager = Main._Service.Get(); + } + public Type RoleBaseType { get; set; } = typeof(SheriffBase); - + public Type RoleType { get; set; } = typeof(Sheriff); public List RoleBase { get; set; } = []; public List Players { get; set; } = []; public bool EnableAssign { get; set; } = true; - - public Func CreateRoleBase { get; set; } - public List AllOption = []; + public Func CreateRoleBase { get; set; } public SimpleRoleInfo SimpleRoleInfo { get; set; } = new() { @@ -32,27 +35,18 @@ public class Sheriff : IRole RoleStringId = nameof(Sheriff) }; - public Sheriff() + public bool CanCreate(IRole role, PlayerControl player) { - var manager = Main._Service.Get(); - - OptionCreate(); + return true; } - public void OptionCreate() + public void OptionCreate(INextOptionManager _nextOptionManager) { - var OptionManager = ServiceExt.ServiceGet(); - } - - public bool CanCreate(IRole role, PlayerControl player) - { - return true; } public void Dispose() { } - } public class SheriffBase : RoleBase @@ -61,7 +55,7 @@ public SheriffBase(PlayerControl player) : base(player) { _eventManager.RegisterListener(new EventListener()); } - + private class EventListener : IEventListener { } diff --git a/NextShip/Roles/Impostor/Illusory.cs b/NextShip/Roles/Impostor/Illusory.cs index 5ff1a0a..0cd399f 100644 --- a/NextShip/Roles/Impostor/Illusory.cs +++ b/NextShip/Roles/Impostor/Illusory.cs @@ -1,9 +1,6 @@ -using OtherAttribute; - namespace NextShip.Roles.Impostor; [FastAddRole] public class Illusory { - } \ No newline at end of file diff --git a/NextShip/Roles/Modifier/Bait.cs b/NextShip/Roles/Modifier/Bait.cs index b268c75..b22c978 100644 --- a/NextShip/Roles/Modifier/Bait.cs +++ b/NextShip/Roles/Modifier/Bait.cs @@ -1,9 +1,6 @@ -using OtherAttribute; - namespace NextShip.Roles.Modifier; [FastAddRole] public class Bait { - } \ No newline at end of file diff --git a/NextShip/Roles/Neutral/SchrodingerCat.cs b/NextShip/Roles/Neutral/SchrodingerCat.cs index a100e91..4d2ed68 100644 --- a/NextShip/Roles/Neutral/SchrodingerCat.cs +++ b/NextShip/Roles/Neutral/SchrodingerCat.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using NextShip.Api.Interfaces; -using OtherAttribute; using UnityEngine; namespace NextShip.Roles.Neutral; @@ -9,11 +8,6 @@ namespace NextShip.Roles.Neutral; [FastAddRole] public class SchrodingerCat : IRole { - public SchrodingerCat() - { - - } - public void Dispose() { } @@ -21,7 +15,7 @@ public void Dispose() public Type RoleBaseType { get; set; } = typeof(SchrodingerCatBase); public Type RoleType { get; set; } = typeof(SchrodingerCat); - + public SimpleRoleInfo SimpleRoleInfo { get; set; } = new() { RoleColor = Color.gray, @@ -30,20 +24,24 @@ public void Dispose() Name = nameof(SchrodingerCat), RoleStringId = nameof(SchrodingerCat) }; + public List RoleBase { get; set; } = []; public List Players { get; set; } = []; public bool EnableAssign { get; set; } = true; - + public Func CreateRoleBase { get; set; } - + public bool CanCreate(IRole role, PlayerControl player) { return true; } - + + public void OptionCreate(INextOptionManager _nextOptionManager) + { + } + public class SchrodingerCatBase(PlayerControl player) : RoleBase(player) { - } } \ No newline at end of file diff --git a/NextShip/Services/NextService.cs b/NextShip/Services/NextService.cs index d96923a..ac609e8 100644 --- a/NextShip/Services/NextService.cs +++ b/NextShip/Services/NextService.cs @@ -58,7 +58,10 @@ public static NextService Build(IServiceBuilder builder) return (NextService)service; } - public static NextService Get(int id) => Services.FirstOrDefault(n => n.id == id); + public static NextService Get(int id) + { + return Services.FirstOrDefault(n => n.id == id); + } public T Get() { @@ -78,11 +81,23 @@ public static NextService Build(ServiceCollection collection) internal static class ServiceExt { - internal static T ServiceGet() => Main._Service.Get(); + internal static T ServiceGet() + { + return Main._Service.Get(); + } + + internal static object ServiceGet(this Type type) + { + return Main._Service.Get(type); + } + + internal static IEnumerable ServiceGets() + { + return Main._Service._Provider.GetServices(); + } - internal static object ServiceGet(this Type type) => Main._Service.Get(type); - - internal static IEnumerable ServiceGets() => Main._Service._Provider.GetServices(); - - internal static IEnumerable ServiceGets(this Type type) => Main._Service._Provider.GetServices(type); + internal static IEnumerable ServiceGets(this Type type) + { + return Main._Service._Provider.GetServices(type); + } } \ No newline at end of file diff --git a/NextShip/UI/Components/DownMenu.cs b/NextShip/UI/Components/DownMenu.cs index 703c1e2..c0824cc 100644 --- a/NextShip/UI/Components/DownMenu.cs +++ b/NextShip/UI/Components/DownMenu.cs @@ -1,5 +1,4 @@ -using NextShip.Api.Attributes; -using UnityEngine; +using UnityEngine; namespace NextShip.UI.Components; diff --git a/NextShip/UI/Components/NextMenuOption.cs b/NextShip/UI/Components/NextMenuOption.cs index d91631f..17ec518 100644 --- a/NextShip/UI/Components/NextMenuOption.cs +++ b/NextShip/UI/Components/NextMenuOption.cs @@ -1,6 +1,4 @@ -using System; -using NextShip.Api.Attributes; -using NextShip.UI.Module; +using NextShip.UI.Module; using UnityEngine; namespace NextShip.UI.Components; @@ -14,6 +12,7 @@ public class NextMenuOption : MonoBehaviour public void Start() { + _eventManager.GetFastListener().Call("OptionCreate", [__OptionMenu, this]); CreateOption(); } diff --git a/NextShip/UI/Components/ShipOptionBehaviour.cs b/NextShip/UI/Components/ShipOptionBehaviour.cs index 46ce0b5..d5b7e9d 100644 --- a/NextShip/UI/Components/ShipOptionBehaviour.cs +++ b/NextShip/UI/Components/ShipOptionBehaviour.cs @@ -1,5 +1,4 @@ using System; -using NextShip.Api.Attributes; using NextShip.Api.Bases; using TMPro; using UnityEngine; @@ -30,7 +29,7 @@ public void SetOptionBase(OptionBase optionBase) OptionBase = optionBase; } - /*internal static GameObject GenerateOption(Transform Parent, string Name = "Temp") + internal static GameObject GenerateOption(Transform Parent, string Name = "Temp") { var Option = new GameObject(Name); Option.transform.SetParent(Parent); @@ -75,5 +74,5 @@ public void SetOptionBase(OptionBase optionBase) }); return Option; - }*/ + } } \ No newline at end of file diff --git a/NextShip/UI/Patches/OptionMenuPatch.cs b/NextShip/UI/Patches/OptionMenuPatch.cs deleted file mode 100644 index 206ead2..0000000 --- a/NextShip/UI/Patches/OptionMenuPatch.cs +++ /dev/null @@ -1,75 +0,0 @@ -/*using System; -using System.Collections.Generic; -using System.Linq; -using HarmonyLib; -using Il2CppInterop.Runtime.InteropTypes.Arrays; -using TMPro; -using UnityEngine; -using UnityEngine.UI; -using Object = UnityEngine.Object; - -namespace NextShip.Patches; - -[HarmonyPatch(typeof(OptionsMenuBehaviour), nameof(OptionsMenuBehaviour.Start))] -internal class OptionMenuPatch -{ - public static TabGroup TISTabButton; - public static GameObject DownloadS; - public static GameObject TISTabContent; - - public static void Postfix(OptionsMenuBehaviour __instance) - { - var tabs = new List(__instance.Tabs.ToArray()); - if (tabs.Count() < 4) return; - if (TISTabContent == null) - { - TISTabContent = new GameObject("TISTabContent"); - TISTabContent.transform.SetParent(__instance.transform); - TISTabContent.transform.localScale = new Vector3(1f, 1f, 1f); - } - - if (DownloadS == null) - { - for (var i = 0; i < tabs[2].Content.transform.childCount; i++) - if (tabs[2].Content.transform.GetChild(i).name == "Languages" && - tabs[2].Content.transform.GetChild(i).transform.GetChild(0).name == "TitleText_TMP") - DownloadS = Object.Instantiate(tabs[2].Content.transform.GetChild(i).gameObject, - TISTabContent.transform); - - DownloadS.DestroyTranslator(); - DownloadS.transform.GetChild(0).GetComponent().text = "下载源"; - var Dropdown1 = DownloadS.AddComponent(); -/* Dropdown1.image.sprite #1# - DownloadS.SetActive(TISTabContent.active); - } - - if (TISTabButton == null) - { - TISTabButton = Object.Instantiate(tabs[0], tabs[0].transform.parent); - TISTabButton.name = "NextShipTab"; - TISTabButton.Content = TISTabContent; -// TISTabButton.Content = null; - TISTabButton.transform.localPosition += new Vector3(4f, 0, 0); - var text = TISTabButton.transform.FindChild("Text_TMP").gameObject; - text.GetComponent().enabled = false; - text.GetComponent().text = "TIS"; - var passiveButton = TISTabButton.GetComponent(); - passiveButton.OnClick = new Button.ButtonClickedEvent(); - passiveButton.OnClick.AddListener((Action)(() => - { - for (var i = 0; i < tabs.Count; i++) - if (tabs[i].Content == TISTabContent) - __instance.OpenTabGroup(i); - - passiveButton.OnMouseOver.Invoke(); - })); - tabs.Add(TISTabButton); - } - - var x = -2.25f; - for (var i = 0; i < tabs.Count - 1; i++) tabs[i].transform.localPosition = new Vector3(x + 1.5f * i, 0, 0); - for (var i = 0; i < tabs.Count; i++) tabs[i].transform.localScale = new Vector3(0.9f, 1, 1); - __instance.Tabs = new Il2CppReferenceArray(tabs.ToArray()); - } -}*/ - diff --git a/NextShip/UI/UIManager/NextUIManager.cs b/NextShip/UI/UIManager/NextUIManager.cs index 50aaf7d..990a15f 100644 --- a/NextShip/UI/UIManager/NextUIManager.cs +++ b/NextShip/UI/UIManager/NextUIManager.cs @@ -1,4 +1,3 @@ -using NextShip.Api.Attributes; using UnityEngine; namespace NextShip.UI.UIManager; diff --git a/NextShip/main.cs b/NextShip/main.cs index d920bbf..0f1de1d 100644 --- a/NextShip/main.cs +++ b/NextShip/main.cs @@ -9,7 +9,6 @@ using BepInEx.Unity.IL2CPP; using HarmonyLib; using Microsoft.Extensions.DependencyInjection; -using NextShip.Api.Attributes; using NextShip.Api.Extension; using NextShip.Api.Interfaces; using NextShip.Api.RPCs; @@ -50,6 +49,8 @@ public sealed class NextShip : BasePlugin public static List Adds; + private NextManager _nextManager; + private ManualLogSource TISLog; public static NextService _Service { get; private set; } @@ -62,8 +63,6 @@ public sealed class NextShip : BasePlugin private static event Action OnBuilder; - private NextManager _nextManager; - public override void Load() { @@ -78,11 +77,7 @@ public override void Load() CreateService(); LoadDependent(); - Task.Run(() => - { - var roleManager = _Service.Get(); - FastAddRoleExt.Registration(roleManager, RootAssembly); - }); + RunTasks(); SteamExtension.UseSteamIdFile(); ReactorExtension.UseReactorHandshake(); @@ -92,7 +87,7 @@ public override void Load() ConsoleManager.SetConsoleTitle("Among Us " + ModName + " Game"); RegisterManager.Registration(); - + LanguagePack.Init(); CustomCosmeticsManager.LoadHat(); } @@ -163,4 +158,13 @@ private static void LoadDependent() service.BuildDependent(); service.LoadDependent(); } + + private static void RunTasks() + { + Task.Run(() => + { + var roleManager = _Service.Get(); + FastAddRole.Registration(roleManager, RootAssembly); + }); + } } \ No newline at end of file diff --git a/OtherAttribute/FastAddRole.cs b/OtherAttribute/FastAddRole.cs deleted file mode 100644 index 871a8a4..0000000 --- a/OtherAttribute/FastAddRole.cs +++ /dev/null @@ -1,7 +0,0 @@ -using JetBrains.Annotations; - -namespace OtherAttribute; - -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor)] -[MeansImplicitUse] -public class FastAddRole : Attribute; \ No newline at end of file diff --git a/OtherAttribute/FastReadAdd.cs b/OtherAttribute/FastReadAdd.cs deleted file mode 100644 index 06e976a..0000000 --- a/OtherAttribute/FastReadAdd.cs +++ /dev/null @@ -1,9 +0,0 @@ -using JetBrains.Annotations; - -namespace OtherAttribute; - -[MeansImplicitUse, AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] -public class FastReadAdd(byte callId) : Attribute -{ - public readonly byte CallId = callId; -} \ No newline at end of file diff --git a/OtherAttribute/OtherAttribute.csproj b/OtherAttribute/OtherAttribute.csproj deleted file mode 100644 index f8aeaad..0000000 --- a/OtherAttribute/OtherAttribute.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - -