diff --git a/Command/Command/Cmd/CommandAccount.cs b/Command/Command/Cmd/CommandAccount.cs index ee8aff03..89231a6e 100644 --- a/Command/Command/Cmd/CommandAccount.cs +++ b/Command/Command/Cmd/CommandAccount.cs @@ -1,62 +1,50 @@ -using EggLink.DanhengServer.Data.Custom; -using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Database.Account; using EggLink.DanhengServer.Internationalization; -using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using EggLink.DanhengServer.Database.Account; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("account", "Game.Command.Account.Desc", "Game.Command.Account.Usage", permission: "egglink.manage")] +public class CommandAccount : ICommand { - [CommandInfo("account", "Game.Command.Account.Desc", "Game.Command.Account.Usage", permission: "egglink.manage")] - public class CommandAccount : ICommand + [CommandMethod("create")] + public async ValueTask CreateAccount(CommandArg arg) { - [CommandMethod("create")] - public void CreateAccount(CommandArg arg) + if (arg.Args.Count < 2) { - if (arg.Args.Count < 2) + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + var account = arg.Args[1]; + var uid = 0; + + if (arg.Args.Count > 2) + if (!int.TryParse(arg.Args[2], out uid)) { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + await arg.SendMsg(I18nManager.Translate("Game.Command.Account.InvalidUid")); return; } - string account = arg.Args[1]; - int uid = 0; + if (AccountData.GetAccountByUserName(account) != null) + { + await arg.SendMsg(string.Format(I18nManager.Translate("Game.Command.Account.DuplicateAccount"), account)); + return; + } - if (arg.Args.Count > 2) - { - if (!int.TryParse(arg.Args[2], out uid)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Account.InvalidUid")); - return; - } - } + if (uid != 0 && AccountData.GetAccountByUid(uid) != null) + { + await arg.SendMsg(string.Format(I18nManager.Translate("Game.Command.Account.DuplicateUID"), uid)); + return; + } - if (AccountData.GetAccountByUserName(account) != null) - { - arg.SendMsg(string.Format(I18nManager.Translate("Game.Command.Account.DuplicateAccount"), account)); - return; - } - - if (uid != 0 && AccountData.GetAccountByUid(uid) != null) - { - arg.SendMsg(string.Format(I18nManager.Translate("Game.Command.Account.DuplicateUID"), uid)); - return; - } - - try - { - AccountHelper.CreateAccount(account, uid); - arg.SendMsg(I18nManager.Translate("Game.Command.Account.CreateSuccess", account)); - } - catch (Exception ex) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Account.CreateError", ex.Message)); - return; - } + try + { + AccountHelper.CreateAccount(account, uid); + await arg.SendMsg(I18nManager.Translate("Game.Command.Account.CreateSuccess", account)); + } + catch (Exception ex) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Account.CreateError", ex.Message)); } } -} +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandAvatar.cs b/Command/Command/Cmd/CommandAvatar.cs index 408d41d8..445a277e 100644 --- a/Command/Command/Cmd/CommandAvatar.cs +++ b/Command/Command/Cmd/CommandAvatar.cs @@ -1,213 +1,218 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Internationalization; -using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("avatar", "Game.Command.Avatar.Desc", "Game.Command.Avatar.Usage")] +public class CommandAvatar : ICommand { - [CommandInfo("avatar", "Game.Command.Avatar.Desc", "Game.Command.Avatar.Usage")] - public class CommandAvatar : ICommand + [CommandMethod("talent")] + public async ValueTask SetTalent(CommandArg arg) { - [CommandMethod("talent")] - public void SetTalent(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + if (arg.BasicArgs.Count < 2) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + // change basic type + var avatarId = arg.GetInt(0); + var level = arg.GetInt(1); + if (level < 0 || level > 10) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.InvalidLevel", + I18nManager.Translate("Word.Talent"))); + return; + } + + var player = arg.Target.Player!; + if (avatarId == -1) + { + player.AvatarManager!.AvatarData.Avatars.ForEach(avatar => { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - if (arg.BasicArgs.Count < 2) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - var Player = arg.Target.Player!; - // change basic type - var avatarId = arg.GetInt(0); - var level = arg.GetInt(1); - if (level < 0 || level > 10) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.InvalidLevel", I18nManager.Translate("Word.Talent"))); - return; - } - var player = arg.Target.Player!; - if (avatarId == -1) - { - player.AvatarManager!.AvatarData.Avatars.ForEach(avatar => + if (avatar.HeroId > 0) { - if (avatar.HeroId > 0) + avatar.SkillTreeExtra.TryGetValue(avatar.HeroId, out var hero); + hero ??= []; + var excel = GameData.AvatarConfigData[avatar.HeroId]; + excel.SkillTree.ForEach(talent => { hero[talent.PointID] = Math.Min(level, talent.MaxLevel); }); + } + else + { + avatar.Excel?.SkillTree.ForEach(talent => { - avatar.SkillTreeExtra.TryGetValue(avatar.HeroId, out var hero); - hero ??= []; - var excel = GameData.AvatarConfigData[avatar.HeroId]; - excel.SkillTree.ForEach(talent => - { - hero[talent.PointID] = Math.Min(level, talent.MaxLevel); - }); - } else - { - avatar.Excel?.SkillTree.ForEach(talent => - { - avatar.SkillTree![talent.PointID] = Math.Min(level, talent.MaxLevel); - }); - } - }); - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AllAvatarsLevelSet", I18nManager.Translate("Word.Talent"), level.ToString())); - - // sync - player.SendPacket(new PacketPlayerSyncScNotify(player.AvatarManager.AvatarData.Avatars)); - - return; - } - var avatar = player.AvatarManager!.GetAvatar(avatarId); - if (avatar == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarNotFound")); - return; - } - avatar.Excel?.SkillTree.ForEach(talent => - { - avatar.SkillTree![talent.PointID] = Math.Min(level, talent.MaxLevel); + avatar.SkillTree[talent.PointID] = Math.Min(level, talent.MaxLevel); + }); + } }); + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AllAvatarsLevelSet", + I18nManager.Translate("Word.Talent"), level.ToString())); // sync - player.SendPacket(new PacketPlayerSyncScNotify(avatar)); + await player.SendPacket(new PacketPlayerSyncScNotify(player.AvatarManager.AvatarData.Avatars)); - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarLevelSet", avatar.Excel?.Name?.Replace("{NICKNAME}", player.Data.Name) ?? avatarId.ToString(), I18nManager.Translate("Word.Talent"), level.ToString())); + return; } - [CommandMethod("get")] - public void GetAvatar(CommandArg arg) + var avatar = player.AvatarManager!.GetAvatar(avatarId); + if (avatar == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - if (arg.BasicArgs.Count < 1) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - } - - var id = arg.GetInt(0); - var excel = arg.Target.Player!.AvatarManager!.AddAvatar(id); - - if (excel == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarFailedGet", id.ToString())); - return; - } - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarGet", excel.Name ?? id.ToString())); + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarNotFound")); + return; } - [CommandMethod("rank")] - public void SetRank(CommandArg arg) + avatar.Excel?.SkillTree.ForEach(talent => { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } + avatar.SkillTree[talent.PointID] = Math.Min(level, talent.MaxLevel); + }); - if (arg.BasicArgs.Count < 2) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - } + // sync + await player.SendPacket(new PacketPlayerSyncScNotify(avatar)); - var id = arg.GetInt(0); - var rank = arg.GetInt(1); - if (rank < 0 || rank > 6) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.InvalidLevel", I18nManager.Translate("Word.Rank"))); - return; - } - if (id == -1) - { - arg.Target.Player!.AvatarManager!.AvatarData.Avatars.ForEach(avatar => - { - avatar.Rank = Math.Min(rank, 6); - }); - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AllAvatarsLevelSet", I18nManager.Translate("Word.Rank"), rank.ToString())); + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarLevelSet", + avatar.Excel?.Name?.Replace("{NICKNAME}", player.Data.Name) ?? avatarId.ToString(), + I18nManager.Translate("Word.Talent"), level.ToString())); + } - // sync - arg.Target.SendPacket(new PacketPlayerSyncScNotify(arg.Target.Player!.AvatarManager.AvatarData.Avatars)); - } - else + [CommandMethod("get")] + public async ValueTask GetAvatar(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + if (arg.BasicArgs.Count < 1) await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + + var id = arg.GetInt(0); + var excel = await arg.Target.Player!.AvatarManager!.AddAvatar(id); + + if (excel == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarFailedGet", id.ToString())); + return; + } + + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarGet", excel.Name ?? id.ToString())); + } + + [CommandMethod("rank")] + public async ValueTask SetRank(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + if (arg.BasicArgs.Count < 2) await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + + var id = arg.GetInt(0); + var rank = arg.GetInt(1); + if (rank < 0 || rank > 6) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.InvalidLevel", + I18nManager.Translate("Word.Rank"))); + return; + } + + if (id == -1) + { + arg.Target.Player!.AvatarManager!.AvatarData.Avatars.ForEach(avatar => { - var avatar = arg.Target.Player!.AvatarManager!.GetAvatar(id); - if (avatar == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarNotFound")); - return; - } avatar.Rank = Math.Min(rank, 6); + }); + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AllAvatarsLevelSet", + I18nManager.Translate("Word.Rank"), rank.ToString())); - // sync - arg.Target.SendPacket(new PacketPlayerSyncScNotify(avatar)); - - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarLevelSet", avatar.Excel?.Name?.Replace("{NICKNAME}", arg.Target.Player!.Data.Name) ?? id.ToString(), I18nManager.Translate("Word.Rank"), rank.ToString())); - } + // sync + await arg.Target.SendPacket( + new PacketPlayerSyncScNotify(arg.Target.Player!.AvatarManager.AvatarData.Avatars)); } - - [CommandMethod("level")] - public void SetLevel(CommandArg arg) + else { - if (arg.Target == null) + var avatar = arg.Target.Player!.AvatarManager!.GetAvatar(id); + if (avatar == null) { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarNotFound")); return; } - if (arg.BasicArgs.Count < 2) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } + avatar.Rank = Math.Min(rank, 6); - var id = arg.GetInt(0); - var level = arg.GetInt(1); - if (level < 1 || level > 80) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.InvalidLevel", I18nManager.Translate("Word.Avatar"))); - return; - } + // sync + await arg.Target.SendPacket(new PacketPlayerSyncScNotify(avatar)); - if (id == -1) - { - arg.Target.Player!.AvatarManager!.AvatarData.Avatars.ForEach(avatar => - { - avatar.Level = Math.Min(level, 80); - avatar.Promotion = GameData.GetMinPromotionForLevel(avatar.Level); - }); - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AllAvatarsLevelSet", I18nManager.Translate("Word.Avatar"), level.ToString())); - - // sync - arg.Target.SendPacket(new PacketPlayerSyncScNotify(arg.Target.Player!.AvatarManager.AvatarData.Avatars)); - } - else - { - var avatar = arg.Target.Player!.AvatarManager!.GetAvatar(id); - if (avatar == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarNotFound")); - return; - } - avatar.Level = Math.Min(level, 80); - avatar.Promotion = GameData.GetMinPromotionForLevel(avatar.Level); - - // sync - arg.Target.SendPacket(new PacketPlayerSyncScNotify(avatar)); - - arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarLevelSet", avatar.Excel?.Name?.Replace("{NICKNAME}", arg.Target.Player!.Data.Name) ?? id.ToString(), I18nManager.Translate("Word.Avatar"), level.ToString())); - } + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarLevelSet", + avatar.Excel?.Name?.Replace("{NICKNAME}", arg.Target.Player!.Data.Name) ?? id.ToString(), + I18nManager.Translate("Word.Rank"), rank.ToString())); } } -} + + [CommandMethod("level")] + public async ValueTask SetLevel(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + if (arg.BasicArgs.Count < 2) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + var id = arg.GetInt(0); + var level = arg.GetInt(1); + if (level < 1 || level > 80) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.InvalidLevel", + I18nManager.Translate("Word.Avatar"))); + return; + } + + if (id == -1) + { + arg.Target.Player!.AvatarManager!.AvatarData.Avatars.ForEach(avatar => + { + avatar.Level = Math.Min(level, 80); + avatar.Promotion = GameData.GetMinPromotionForLevel(avatar.Level); + }); + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AllAvatarsLevelSet", + I18nManager.Translate("Word.Avatar"), level.ToString())); + + // sync + await arg.Target.SendPacket( + new PacketPlayerSyncScNotify(arg.Target.Player!.AvatarManager.AvatarData.Avatars)); + } + else + { + var avatar = arg.Target.Player!.AvatarManager!.GetAvatar(id); + if (avatar == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarNotFound")); + return; + } + + avatar.Level = Math.Min(level, 80); + avatar.Promotion = GameData.GetMinPromotionForLevel(avatar.Level); + + // sync + await arg.Target.SendPacket(new PacketPlayerSyncScNotify(avatar)); + + await arg.SendMsg(I18nManager.Translate("Game.Command.Avatar.AvatarLevelSet", + avatar.Excel?.Name?.Replace("{NICKNAME}", arg.Target.Player!.Data.Name) ?? id.ToString(), + I18nManager.Translate("Word.Avatar"), level.ToString())); + } + } +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandGive.cs b/Command/Command/Cmd/CommandGive.cs index 4e68026d..f76e6fd1 100644 --- a/Command/Command/Cmd/CommandGive.cs +++ b/Command/Command/Cmd/CommandGive.cs @@ -1,53 +1,51 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Internationalization; -using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Server.Packet.Send.Others; -using EggLink.DanhengServer.Server.Packet.Send.Tutorial; -using Org.BouncyCastle.Ocsp; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("give", "Game.Command.Give.Desc", "Game.Command.Give.Usage")] +public class CommandGive : ICommand { - [CommandInfo("give", "Game.Command.Give.Desc", "Game.Command.Give.Usage")] - public class CommandGive : ICommand + [CommandDefault] + public async ValueTask GiveItem(CommandArg arg) { - [CommandDefault] - public void GiveItem(CommandArg arg) + var player = arg.Target?.Player; + if (player == null) { - var player = arg.Target?.Player; - if (player == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - if (arg.BasicArgs.Count == 0) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - GameData.ItemConfigData.TryGetValue(arg.GetInt(0), out var itemData); - if (itemData == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Give.ItemNotFound")); - return; - } - - arg.CharacterArgs.TryGetValue("x", out var str); - arg.CharacterArgs.TryGetValue("l", out var levelStr); - arg.CharacterArgs.TryGetValue("r", out var rankStr); - str ??= "1"; - levelStr ??= "1"; - rankStr ??= "1"; - if (!int.TryParse(str, out var amount) || !int.TryParse(levelStr, out var level) || !int.TryParse(rankStr, out var rank)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - player.InventoryManager!.AddItem(arg.GetInt(0), amount, rank: Math.Min(rank, 5), level: Math.Max(Math.Min(level, 80), 1)); - - arg.SendMsg(I18nManager.Translate("Game.Command.Give.GiveItem", player.Uid.ToString(), amount.ToString(), itemData.Name ?? itemData.ID.ToString())); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } + + if (arg.BasicArgs.Count == 0) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + GameData.ItemConfigData.TryGetValue(arg.GetInt(0), out var itemData); + if (itemData == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Give.ItemNotFound")); + return; + } + + arg.CharacterArgs.TryGetValue("x", out var str); + arg.CharacterArgs.TryGetValue("l", out var levelStr); + arg.CharacterArgs.TryGetValue("r", out var rankStr); + str ??= "1"; + levelStr ??= "1"; + rankStr ??= "1"; + if (!int.TryParse(str, out var amount) || !int.TryParse(levelStr, out var level) || + !int.TryParse(rankStr, out var rank)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + await player.InventoryManager!.AddItem(arg.GetInt(0), amount, rank: Math.Min(rank, 5), + level: Math.Max(Math.Min(level, 80), 1)); + + await arg.SendMsg(I18nManager.Translate("Game.Command.Give.GiveItem", player.Uid.ToString(), amount.ToString(), + itemData.Name ?? itemData.ID.ToString())); } -} +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandGiveall.cs b/Command/Command/Cmd/CommandGiveall.cs index 94d6eccb..8159702e 100644 --- a/Command/Command/Cmd/CommandGiveall.cs +++ b/Command/Command/Cmd/CommandGiveall.cs @@ -1,205 +1,197 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Inventory; +using EggLink.DanhengServer.Enums.Item; using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("giveall", "Game.Command.GiveAll.Desc", "Game.Command.GiveAll.Usage")] +public class CommandGiveall : ICommand { - [CommandInfo("giveall", "Game.Command.GiveAll.Desc", "Game.Command.GiveAll.Usage")] - public class CommandGiveall : ICommand + [CommandMethod("0 avatar")] + public async ValueTask GiveAllAvatar(CommandArg arg) { - [CommandMethod("0 avatar")] - public void GiveAllAvatar(CommandArg arg) + var player = arg.Target?.Player; + if (player == null) { - var player = arg.Target?.Player; - if (player == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - arg.CharacterArgs.TryGetValue("r", out var rankStr); - arg.CharacterArgs.TryGetValue("l", out var levelStr); - rankStr ??= "1"; - levelStr ??= "1"; - if (!int.TryParse(rankStr, out var rank) || !int.TryParse(levelStr, out var level)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - var avatarList = GameData.AvatarConfigData.Values; - foreach (var avatar in avatarList) - { - if (player.AvatarManager!.GetAvatar(avatar.AvatarID) == null) - { - player.InventoryManager!.AddItem(avatar.AvatarID, 1, false, sync:false); - player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Level = Math.Max(Math.Min(level, 80), 0); - player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Promotion = GameData.GetMinPromotionForLevel(Math.Max(Math.Min(level, 80), 0)); - player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Rank = Math.Max(Math.Min(rank, 6), 0); - } else - { - player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Level = Math.Max(Math.Min(level, 80), 0); - player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Promotion = GameData.GetMinPromotionForLevel(Math.Max(Math.Min(level, 80), 0)); - player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Rank = Math.Max(Math.Min(rank, 6), 0); - } - } - - player.SendPacket(new PacketPlayerSyncScNotify(player.AvatarManager!.AvatarData.Avatars)); - - arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", I18nManager.Translate("Word.Avatar"), "1")); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } - [CommandMethod("0 equipment")] - public void GiveAllLightcone(CommandArg arg) + arg.CharacterArgs.TryGetValue("r", out var rankStr); + arg.CharacterArgs.TryGetValue("l", out var levelStr); + rankStr ??= "1"; + levelStr ??= "1"; + if (!int.TryParse(rankStr, out var rank) || !int.TryParse(levelStr, out var level)) { - var player = arg.Target?.Player; - if (player == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - arg.CharacterArgs.TryGetValue("r", out var rankStr); - arg.CharacterArgs.TryGetValue("l", out var levelStr); - arg.CharacterArgs.TryGetValue("x", out var amountStr); - rankStr ??= "1"; - levelStr ??= "1"; - amountStr ??= "1"; - if (!int.TryParse(rankStr, out var rank) || !int.TryParse(levelStr, out var level) || !int.TryParse(amountStr, out var amount)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - var lightconeList = GameData.EquipmentConfigData.Values; - var items = new List(); - - for (int i = 0; i < amount; i++) - { - foreach (var lightcone in lightconeList) - { - var item = player.InventoryManager!.AddItem(lightcone.EquipmentID, 1, false, Math.Max(Math.Min(rank, 5), 0), Math.Max(Math.Min(level, 80), 0), sync:false); - - if (item != null) - items.Add(item); - } - } - - player.SendPacket(new PacketPlayerSyncScNotify(items)); - - arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", I18nManager.Translate("Word.Equipment"), amount.ToString())); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; } - [CommandMethod("0 material")] - public void GiveAllMaterial(CommandArg arg) - { - var player = arg.Target?.Player; - if (player == null) + var avatarList = GameData.AvatarConfigData.Values; + foreach (var avatar in avatarList) + if (player.AvatarManager!.GetAvatar(avatar.AvatarID) == null) { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; + await player.InventoryManager!.AddItem(avatar.AvatarID, 1, false, sync: false); + player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Level = Math.Max(Math.Min(level, 80), 0); + player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Promotion = + GameData.GetMinPromotionForLevel(Math.Max(Math.Min(level, 80), 0)); + player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Rank = Math.Max(Math.Min(rank, 6), 0); + } + else + { + player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Level = Math.Max(Math.Min(level, 80), 0); + player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Promotion = + GameData.GetMinPromotionForLevel(Math.Max(Math.Min(level, 80), 0)); + player.AvatarManager!.GetAvatar(avatar.AvatarID)!.Rank = Math.Max(Math.Min(rank, 6), 0); } - arg.CharacterArgs.TryGetValue("x", out var amountStr); - amountStr ??= "1"; - if (!int.TryParse(amountStr, out var amount)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } + await player.SendPacket(new PacketPlayerSyncScNotify(player.AvatarManager!.AvatarData.Avatars)); - var materialList = GameData.ItemConfigData.Values; - var items = new List(); - foreach (var material in materialList) - { - if (material.ItemMainType == Enums.Item.ItemMainTypeEnum.Material) - { - items.Add(new() - { - ItemId = material.ID, - Count = amount - }); - } - } - - player.InventoryManager!.AddItems(items, false); - arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", I18nManager.Translate("Word.Material"), amount.ToString())); - } - - [CommandMethod("0 relic")] - public void GiveAllRelic(CommandArg arg) - { - var player = arg.Target?.Player; - if (player == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - arg.CharacterArgs.TryGetValue("l", out var levelStr); - levelStr ??= "1"; - if (!int.TryParse(levelStr, out var level)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - arg.CharacterArgs.TryGetValue("x", out var amountStr); - amountStr ??= "1"; - if (!int.TryParse(amountStr, out var amount)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - var relicList = GameData.RelicConfigData.Values; - var items = new List(); - - for (int i = 0; i < amount; i++) - { - foreach (var relic in relicList) - { - var item = player.InventoryManager!.AddItem(relic.ID, amount, false, 1, Math.Max(Math.Min(level, relic.MaxLevel), 1), sync: false); - - if (item != null) - items.Add(item); - } - } - - player.SendPacket(new PacketPlayerSyncScNotify(items)); - - arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", I18nManager.Translate("Word.Relic"), amount.ToString())); - } - - [CommandMethod("0 unlock")] - public void GiveAllUnlock(CommandArg arg) - { - var player = arg.Target?.Player; - if (player == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - var materialList = GameData.ItemConfigData.Values; - foreach (var material in materialList) - { - if (material.ItemMainType == Enums.Item.ItemMainTypeEnum.Usable) - { - if (material.ItemSubType == Enums.Item.ItemSubTypeEnum.HeadIcon || material.ItemSubType == Enums.Item.ItemSubTypeEnum.PhoneTheme || material.ItemSubType == Enums.Item.ItemSubTypeEnum.ChatBubble) - { - player.InventoryManager!.AddItem(material.ID, 1, false); - } - } - } - - arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", I18nManager.Translate("Word.Unlock"), "1")); - } + await arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", + I18nManager.Translate("Word.Avatar"), "1")); } -} + + [CommandMethod("0 equipment")] + public async ValueTask GiveAllLightcone(CommandArg arg) + { + var player = arg.Target?.Player; + if (player == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + arg.CharacterArgs.TryGetValue("r", out var rankStr); + arg.CharacterArgs.TryGetValue("l", out var levelStr); + arg.CharacterArgs.TryGetValue("x", out var amountStr); + rankStr ??= "1"; + levelStr ??= "1"; + amountStr ??= "1"; + if (!int.TryParse(rankStr, out var rank) || !int.TryParse(levelStr, out var level) || + !int.TryParse(amountStr, out var amount)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + var lightconeList = GameData.EquipmentConfigData.Values; + var items = new List(); + + for (var i = 0; i < amount; i++) + foreach (var lightcone in lightconeList) + { + var item = await player.InventoryManager!.AddItem(lightcone.EquipmentID, 1, false, + Math.Max(Math.Min(rank, 5), 0), Math.Max(Math.Min(level, 80), 0), false); + + if (item != null) + items.Add(item); + } + + await player.SendPacket(new PacketPlayerSyncScNotify(items)); + + await arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", + I18nManager.Translate("Word.Equipment"), amount.ToString())); + } + + [CommandMethod("0 material")] + public async ValueTask GiveAllMaterial(CommandArg arg) + { + var player = arg.Target?.Player; + if (player == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + arg.CharacterArgs.TryGetValue("x", out var amountStr); + amountStr ??= "1"; + if (!int.TryParse(amountStr, out var amount)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + var materialList = GameData.ItemConfigData.Values; + var items = new List(); + foreach (var material in materialList) + if (material.ItemMainType == ItemMainTypeEnum.Material) + items.Add(new ItemData + { + ItemId = material.ID, + Count = amount + }); + + await player.InventoryManager!.AddItems(items, false); + await arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", + I18nManager.Translate("Word.Material"), amount.ToString())); + } + + [CommandMethod("0 relic")] + public async ValueTask GiveAllRelic(CommandArg arg) + { + var player = arg.Target?.Player; + if (player == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + arg.CharacterArgs.TryGetValue("l", out var levelStr); + levelStr ??= "1"; + if (!int.TryParse(levelStr, out var level)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + arg.CharacterArgs.TryGetValue("x", out var amountStr); + amountStr ??= "1"; + if (!int.TryParse(amountStr, out var amount)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + var relicList = GameData.RelicConfigData.Values; + var items = new List(); + + for (var i = 0; i < amount; i++) + foreach (var relic in relicList) + { + var item = await player.InventoryManager!.AddItem(relic.ID, amount, false, 1, + Math.Max(Math.Min(level, relic.MaxLevel), 1), false); + + if (item != null) + items.Add(item); + } + + await player.SendPacket(new PacketPlayerSyncScNotify(items)); + + await arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", + I18nManager.Translate("Word.Relic"), amount.ToString())); + } + + [CommandMethod("0 unlock")] + public async ValueTask GiveAllUnlock(CommandArg arg) + { + var player = arg.Target?.Player; + if (player == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var materialList = GameData.ItemConfigData.Values; + foreach (var material in materialList) + if (material.ItemMainType == ItemMainTypeEnum.Usable) + if (material.ItemSubType == ItemSubTypeEnum.HeadIcon || + material.ItemSubType == ItemSubTypeEnum.PhoneTheme || + material.ItemSubType == ItemSubTypeEnum.ChatBubble) + await player.InventoryManager!.AddItem(material.ID, 1, false); + + await arg.SendMsg(I18nManager.Translate("Game.Command.GiveAll.GiveAllItems", + I18nManager.Translate("Word.Unlock"), "1")); + } +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandHelp.cs b/Command/Command/Cmd/CommandHelp.cs index 1e921ae5..b1de23c9 100644 --- a/Command/Command/Cmd/CommandHelp.cs +++ b/Command/Command/Cmd/CommandHelp.cs @@ -1,34 +1,24 @@ using EggLink.DanhengServer.Internationalization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("help", "Game.Command.Help.Desc", "Game.Command.Help.Usage")] +public class CommandHelp : ICommand { - [CommandInfo("help", "Game.Command.Help.Desc", "Game.Command.Help.Usage")] - public class CommandHelp : ICommand + [CommandDefault] + public async ValueTask Help(CommandArg arg) { - [CommandDefault] - public void Help(CommandArg arg) - { - var commands = CommandManager.Instance?.CommandInfo.Values; - arg.SendMsg(I18nManager.Translate("Game.Command.Help.Commands")); - if (commands == null) - { - return; - } + var commands = CommandManager.Instance?.CommandInfo.Values; + await arg.SendMsg(I18nManager.Translate("Game.Command.Help.Commands")); + if (commands == null) return; - foreach (var command in commands) - { - var msg = $"/{command.Name} - {I18nManager.Translate(command.Description)}\n\n{I18nManager.Translate(command.Usage)}"; - if (command.Permission != "") - { - msg += $"\n\n{I18nManager.Translate("Game.Command.Help.CommandPermission")} {command.Permission}"; - } - arg.SendMsg(msg); - } + foreach (var command in commands) + { + var msg = + $"/{command.Name} - {I18nManager.Translate(command.Description)}\n\n{I18nManager.Translate(command.Usage)}"; + if (command.Permission != "") + msg += $"\n\n{I18nManager.Translate("Game.Command.Help.CommandPermission")} {command.Permission}"; + await arg.SendMsg(msg); } } -} +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandHero.cs b/Command/Command/Cmd/CommandHero.cs index 9f4b3e33..92d82e09 100644 --- a/Command/Command/Cmd/CommandHero.cs +++ b/Command/Command/Cmd/CommandHero.cs @@ -2,74 +2,67 @@ using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Avatar; -using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("hero", "Game.Command.Hero.Desc", "Game.Command.Hero.Usage")] +public class CommandHero : ICommand { - [CommandInfo("hero", "Game.Command.Hero.Desc", "Game.Command.Hero.Usage")] - public class CommandHero : ICommand + [CommandMethod("0 gender")] + public async ValueTask ChangeGender(CommandArg arg) { - [CommandMethod("0 gender")] - public void ChangeGender(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - if (arg.BasicArgs.Count < 1) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - var gender = (Gender)arg.GetInt(0); - if (gender == Gender.None) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Hero.GenderNotSpecified")); - return; - } - - var player = arg.Target!.Player!; - player.Data.CurrentGender = gender; - player.ChangeHeroBasicType(HeroBasicTypeEnum.Warrior); - player.SendPacket(new PacketGetHeroBasicTypeInfoScRsp(player)); - - arg.SendMsg(I18nManager.Translate("Game.Command.Hero.GenderChanged")); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } - [CommandMethod("0 type")] - public void ChangeType(CommandArg arg) + if (arg.BasicArgs.Count < 1) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - if (arg.BasicArgs.Count < 1) - { - arg.SendMsg(""); - return; - } - - var gender = (HeroBasicTypeEnum)arg.GetInt(0); - if (gender == 0) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Hero.HeroTypeNotSpecified")); - return; - } - - var player = arg.Target!.Player!; - player.ChangeHeroBasicType(gender); - - arg.SendMsg(I18nManager.Translate("Game.Command.Hero.HeroTypeChanged")); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; } + + var gender = (Gender)arg.GetInt(0); + if (gender == Gender.None) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Hero.GenderNotSpecified")); + return; + } + + var player = arg.Target!.Player!; + player.Data.CurrentGender = gender; + await player.ChangeHeroBasicType(HeroBasicTypeEnum.Warrior); + await player.SendPacket(new PacketGetHeroBasicTypeInfoScRsp(player)); + + await arg.SendMsg(I18nManager.Translate("Game.Command.Hero.GenderChanged")); } -} + + [CommandMethod("0 type")] + public async ValueTask ChangeType(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + if (arg.BasicArgs.Count < 1) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + var gender = (HeroBasicTypeEnum)arg.GetInt(0); + if (gender == 0) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Hero.HeroTypeNotSpecified")); + return; + } + + var player = arg.Target!.Player!; + await player.ChangeHeroBasicType(gender); + + await arg.SendMsg(I18nManager.Translate("Game.Command.Hero.HeroTypeChanged")); + } +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandKick.cs b/Command/Command/Cmd/CommandKick.cs index 15bbdec4..1e61a860 100644 --- a/Command/Command/Cmd/CommandKick.cs +++ b/Command/Command/Cmd/CommandKick.cs @@ -1,27 +1,22 @@ using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("kick", "Game.Command.Kick.Desc", "Game.Command.Kick.Usage", permission: "egglink.manage")] +public class CommandKick : ICommand { - [CommandInfo("kick", "Game.Command.Kick.Desc", "Game.Command.Kick.Usage", permission: "egglink.manage")] - public class CommandKick : ICommand + [CommandDefault] + public async ValueTask Kick(CommandArg arg) { - [CommandDefault] - public void Kick(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - arg.Target.SendPacket(new PacketPlayerKickOutScNotify()); - arg.SendMsg(I18nManager.Translate("Game.Command.Kick.PlayerKicked", arg.Target.Player!.Data.Name!)); - arg.Target.Stop(); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } + + await arg.Target.SendPacket(new PacketPlayerKickOutScNotify()); + await arg.SendMsg(I18nManager.Translate("Game.Command.Kick.PlayerKicked", arg.Target.Player!.Data.Name!)); + arg.Target.Stop(); } -} +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandLineup.cs b/Command/Command/Cmd/CommandLineup.cs index bdb5a107..7fb4a8f0 100644 --- a/Command/Command/Cmd/CommandLineup.cs +++ b/Command/Command/Cmd/CommandLineup.cs @@ -1,45 +1,37 @@ using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("lineup", "Game.Command.Lineup.Desc", "Game.Command.Lineup.Usage")] +public class CommandLineup : ICommand { - [CommandInfo("lineup", "Game.Command.Lineup.Desc", "Game.Command.Lineup.Usage")] - public class CommandLineup : ICommand + [CommandMethod("0 mp")] + public async ValueTask SetLineupMp(CommandArg arg) { - [CommandMethod("0 mp")] - public void SetLineupMp(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var count = arg.GetInt(0); - arg.Target.Player!.LineupManager!.GainMp(count == 0 ? 2: count); - arg.SendMsg(I18nManager.Translate("Game.Command.Lineup.PlayerGainedMp", Math.Min(count, 2).ToString())); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } - [CommandMethod("0 heal")] - public void HealLineup(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - var player = arg.Target.Player!; - foreach (var avatar in player.LineupManager!.GetCurLineup()!.AvatarData!.Avatars) - { - avatar.CurrentHp = 10000; - } - player.SendPacket(new PacketSyncLineupNotify(player.LineupManager.GetCurLineup()!)); - arg.SendMsg(I18nManager.Translate("Game.Command.Lineup.HealedAllAvatars")); - } + var count = arg.GetInt(0); + await arg.Target.Player!.LineupManager!.GainMp(count == 0 ? 2 : count); + await arg.SendMsg(I18nManager.Translate("Game.Command.Lineup.PlayerGainedMp", Math.Min(count, 2).ToString())); } -} + + [CommandMethod("0 heal")] + public async ValueTask HealLineup(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var player = arg.Target.Player!; + foreach (var avatar in player.LineupManager!.GetCurLineup()!.AvatarData!.Avatars) avatar.CurrentHp = 10000; + await player.SendPacket(new PacketSyncLineupNotify(player.LineupManager.GetCurLineup()!)); + await arg.SendMsg(I18nManager.Translate("Game.Command.Lineup.HealedAllAvatars")); + } +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandMail.cs b/Command/Command/Cmd/CommandMail.cs index 4564e551..952ae889 100644 --- a/Command/Command/Cmd/CommandMail.cs +++ b/Command/Command/Cmd/CommandMail.cs @@ -1,39 +1,33 @@ using EggLink.DanhengServer.Internationalization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Command.Cmd +namespace EggLink.DanhengServer.Command.Command.Cmd; + +[CommandInfo("mail", "Game.Command.Mail.Desc", "Game.Command.Mail.Usage", permission: "")] +public class CommandMail : ICommand { - [CommandInfo("mail", "Game.Command.Mail.Desc", "Game.Command.Mail.Usage", permission: "")] - public class CommandMail : ICommand + [CommandDefault] + public async ValueTask Mail(CommandArg arg) { - [CommandDefault] - public void Mail(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - if (arg.Args.Count < 5) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - var sender = arg.Args[0]; - var title = arg.Args[1]; - var content = arg.Args[2]; - var templateId = int.Parse(arg.Args[3]); - var expiredDay = int.Parse(arg.Args[4]); - - arg.Target.Player!.MailManager!.SendMail(sender, title, content, templateId, expiredDay); - - arg.SendMsg(I18nManager.Translate("Game.Command.Mail.MailSent")); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } + + if (arg.Args.Count < 5) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + var sender = arg.Args[0]; + var title = arg.Args[1]; + var content = arg.Args[2]; + var templateId = int.Parse(arg.Args[3]); + var expiredDay = int.Parse(arg.Args[4]); + + await arg.Target.Player!.MailManager!.SendMail(sender, title, content, templateId, expiredDay); + + await arg.SendMsg(I18nManager.Translate("Game.Command.Mail.MailSent")); } -} +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandMission.cs b/Command/Command/Cmd/CommandMission.cs index cd8fe88e..14c02592 100644 --- a/Command/Command/Cmd/CommandMission.cs +++ b/Command/Command/Cmd/CommandMission.cs @@ -1,191 +1,182 @@ -using EggLink.DanhengServer.Internationalization; -using System.Collections.Generic; -using System.Text; +using System.Text; +using EggLink.DanhengServer.Enums; +using EggLink.DanhengServer.Internationalization; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("mission", "Game.Command.Mission.Desc", "Game.Command.Mission.Usage")] +public class CommandMission : ICommand { - [CommandInfo("mission", "Game.Command.Mission.Desc", "Game.Command.Mission.Usage")] - public class CommandMission : ICommand + [CommandMethod("0 pass")] + public async ValueTask PassRunningMission(CommandArg arg) { - [CommandMethod("0 pass")] - public void PassRunningMission(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var mission = arg.Target!.Player!.MissionManager!; - var count = mission.GetRunningSubMissionIdList().Count; - mission.GetRunningSubMissionIdList().ForEach(mission.FinishSubMission); - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.AllRunningMissionsFinished", count.ToString())); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } - [CommandMethod("0 finish")] - public void FinishRunningMission(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - if (arg.BasicArgs.Count < 1) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - if (!int.TryParse(arg.BasicArgs[0], out var missionId)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.InvalidMissionId")); - return; - } - - var mission = arg.Target!.Player!.MissionManager!; - mission.FinishSubMission(missionId); - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.MissionFinished", missionId.ToString())); - } - - [CommandMethod("0 running")] - public void ListRunningMission(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - var mission = arg.Target!.Player!.MissionManager!; - var runningMissions = mission.GetRunningSubMissionList(); - if (runningMissions.Count == 0) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.NoRunningMissions")); - return; - } - - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.RunningMissions")); - Dictionary> missionMap = []; - - foreach (var m in runningMissions) - { - if (!missionMap.TryGetValue(m.MainMissionID, out List? value)) - { - value = []; - missionMap[m.MainMissionID] = value; - } - - value.Add(m.ID); - } - - var possibleStuckIds = new List(); - var morePossibleStuckIds = new List(); - - foreach (var list in missionMap) - { - arg.SendMsg($"{I18nManager.Translate("Game.Command.Mission.MainMission")} {list.Key}:"); - var sb = new StringBuilder(); - foreach (var id in list.Value) - { - sb.Append($"{id}、"); - - if (id.ToString().StartsWith("10")) - { - possibleStuckIds.Add(id); - - var info = mission.GetSubMissionInfo(id); - if (info != null && info.FinishType == Enums.MissionFinishTypeEnum.PropState) - { - morePossibleStuckIds.Add(id); - } - } - } - - sb.Remove(sb.Length - 1, 1); - - arg.SendMsg(sb.ToString()); - } - - if (morePossibleStuckIds.Count > 0) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.PossibleStuckMissions")); - - var sb = new StringBuilder(); - foreach (var id in morePossibleStuckIds) - { - sb.Append($"{id}、"); - } - - sb.Remove(sb.Length - 1, 1); - - arg.SendMsg(sb.ToString()); - } - else if (possibleStuckIds.Count > 0) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.PossibleStuckMissions")); - - var sb = new StringBuilder(); - foreach (var id in possibleStuckIds) - { - sb.Append($"{id}、"); - } - - sb.Remove(sb.Length - 1, 1); - - arg.SendMsg(sb.ToString()); - } - } - - [CommandMethod("0 reaccept")] - public void ReAcceptMission(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - if (arg.BasicArgs.Count < 1) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - if (!int.TryParse(arg.BasicArgs[0], out var missionId)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.InvalidMissionId")); - return; - } - - var mission = arg.Target!.Player!.MissionManager!; - mission.ReAcceptMainMission(missionId); - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.MissionReAccepted", missionId.ToString())); - } - - [CommandMethod("0 finishmain")] - public void FinishMainMission(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - if (arg.BasicArgs.Count < 1) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - if (!int.TryParse(arg.BasicArgs[0], out var missionId)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.InvalidMissionId")); - return; - } - - var mission = arg.Target!.Player!.MissionManager!; - mission.FinishMainMission(missionId); - arg.SendMsg(I18nManager.Translate("Game.Command.Mission.MissionFinished", missionId.ToString())); - } + var mission = arg.Target!.Player!.MissionManager!; + var count = mission.GetRunningSubMissionIdList().Count; + foreach (var id in mission.GetRunningSubMissionIdList()) await mission.FinishSubMission(id); + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.AllRunningMissionsFinished", count.ToString())); } -} + + [CommandMethod("0 finish")] + public async ValueTask FinishRunningMission(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + if (arg.BasicArgs.Count < 1) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + if (!int.TryParse(arg.BasicArgs[0], out var missionId)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.InvalidMissionId")); + return; + } + + var mission = arg.Target!.Player!.MissionManager!; + await mission.FinishSubMission(missionId); + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.MissionFinished", missionId.ToString())); + } + + [CommandMethod("0 running")] + public async ValueTask ListRunningMission(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var mission = arg.Target!.Player!.MissionManager!; + var runningMissions = mission.GetRunningSubMissionList(); + if (runningMissions.Count == 0) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.NoRunningMissions")); + return; + } + + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.RunningMissions")); + Dictionary> missionMap = []; + + foreach (var m in runningMissions) + { + if (!missionMap.TryGetValue(m.MainMissionID, out var value)) + { + value = []; + missionMap[m.MainMissionID] = value; + } + + value.Add(m.ID); + } + + var possibleStuckIds = new List(); + var morePossibleStuckIds = new List(); + + foreach (var list in missionMap) + { + await arg.SendMsg($"{I18nManager.Translate("Game.Command.Mission.MainMission")} {list.Key}:"); + var sb = new StringBuilder(); + foreach (var id in list.Value) + { + sb.Append($"{id}、"); + + if (!id.ToString().StartsWith("10")) continue; + possibleStuckIds.Add(id); + + var info = mission.GetSubMissionInfo(id); + if (info?.FinishType == MissionFinishTypeEnum.PropState) morePossibleStuckIds.Add(id); + } + + sb.Remove(sb.Length - 1, 1); + + await arg.SendMsg(sb.ToString()); + } + + if (morePossibleStuckIds.Count > 0) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.PossibleStuckMissions")); + + var sb = new StringBuilder(); + foreach (var id in morePossibleStuckIds) sb.Append($"{id}、"); + + sb.Remove(sb.Length - 1, 1); + + await arg.SendMsg(sb.ToString()); + } + else if (possibleStuckIds.Count > 0) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.PossibleStuckMissions")); + + var sb = new StringBuilder(); + foreach (var id in possibleStuckIds) sb.Append($"{id}、"); + + sb.Remove(sb.Length - 1, 1); + + await arg.SendMsg(sb.ToString()); + } + + await Task.CompletedTask; + } + + [CommandMethod("0 reaccept")] + public async ValueTask ReAcceptMission(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + if (arg.BasicArgs.Count < 1) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + if (!int.TryParse(arg.BasicArgs[0], out var missionId)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.InvalidMissionId")); + return; + } + + var mission = arg.Target!.Player!.MissionManager!; + await mission.ReAcceptMainMission(missionId); + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.MissionReAccepted", missionId.ToString())); + } + + [CommandMethod("0 finishmain")] + public async ValueTask FinishMainMission(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + if (arg.BasicArgs.Count < 1) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + if (!int.TryParse(arg.BasicArgs[0], out var missionId)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.InvalidMissionId")); + return; + } + + var mission = arg.Target!.Player!.MissionManager!; + await mission.FinishMainMission(missionId); + await arg.SendMsg(I18nManager.Translate("Game.Command.Mission.MissionFinished", missionId.ToString())); + } +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandRaid.cs b/Command/Command/Cmd/CommandRaid.cs index d0e80d6d..efd4160f 100644 --- a/Command/Command/Cmd/CommandRaid.cs +++ b/Command/Command/Cmd/CommandRaid.cs @@ -1,27 +1,21 @@ using EggLink.DanhengServer.Internationalization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Command.Cmd +namespace EggLink.DanhengServer.Command.Command.Cmd; + +[CommandInfo("raid", "Game.Command.Raid.Desc", "Game.Command.Raid.Usage", permission: "")] +public class CommandRaid : ICommand { - [CommandInfo("raid", "Game.Command.Raid.Desc", "Game.Command.Raid.Usage", permission: "")] - public class CommandRaid : ICommand + [CommandMethod("0 leave")] + public async ValueTask Leave(CommandArg arg) { - [CommandMethod("0 leave")] - public void Leave(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - arg.Target.Player!.RaidManager!.LeaveRaid(false); - - arg.SendMsg(I18nManager.Translate("Game.Command.Raid.Leaved")); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } + + await arg.Target.Player!.RaidManager!.LeaveRaid(false); + + await arg.SendMsg(I18nManager.Translate("Game.Command.Raid.Leaved")); } -} +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandRelic.cs b/Command/Command/Cmd/CommandRelic.cs index 42e21c57..a2412165 100644 --- a/Command/Command/Cmd/CommandRelic.cs +++ b/Command/Command/Cmd/CommandRelic.cs @@ -2,148 +2,138 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("relic", "Game.Command.Relic.Desc", "Game.Command.Relic.Usage")] +public class CommandRelic : ICommand { - [CommandInfo("relic", "Game.Command.Relic.Desc", "Game.Command.Relic.Usage")] - public class CommandRelic : ICommand + [CommandDefault] + public async ValueTask GiveRelic(CommandArg arg) { - [CommandDefault] - public void GiveRelic(CommandArg arg) + var player = arg.Target?.Player; + if (player == null) { - var player = arg.Target?.Player; - if (player == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - if (arg.BasicArgs.Count < 3) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - arg.CharacterArgs.TryGetValue("x", out var str); - arg.CharacterArgs.TryGetValue("l", out var levelStr); - str ??= "1"; - levelStr ??= "1"; - if (!int.TryParse(str, out var amount) || !int.TryParse(levelStr, out var level)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - GameData.RelicConfigData.TryGetValue(int.Parse(arg.BasicArgs[0]), out var itemConfig); - GameData.ItemConfigData.TryGetValue(int.Parse(arg.BasicArgs[0]), out var itemConfigExcel); - if (itemConfig == null || itemConfigExcel == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Relic.RelicNotFound")); - return; - } - - GameData.RelicSubAffixData.TryGetValue(itemConfig.SubAffixGroup, out var subAffixConfig); - GameData.RelicMainAffixData.TryGetValue(itemConfig.MainAffixGroup, out var mainAffixConfig); - if (subAffixConfig == null || mainAffixConfig == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Relic.RelicNotFound")); - return; - } - - int startIndex = 1; - int mainAffixId; - if (arg.BasicArgs[1].Contains(':')) - { - // random main affix - mainAffixId = mainAffixConfig.Keys.ToList().RandomElement(); - } - else - { - mainAffixId = int.Parse(arg.BasicArgs[1]); - if (!mainAffixConfig.ContainsKey(mainAffixId)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Relic.InvalidMainAffixId")); - return; - } - startIndex++; - } - - var remainLevel = 5; - var subAffixes = new List<(int, int)>(); - for (var i = startIndex; i < arg.BasicArgs.Count; i++) - { - var subAffix = arg.BasicArgs[i].Split(':'); - if (subAffix.Length != 2 || !int.TryParse(subAffix[0], out var subId) || !int.TryParse(subAffix[1], out var subLevel)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - if (!subAffixConfig.ContainsKey(subId)) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Relic.InvalidSubAffixId")); - return; - } - subAffixes.Add((subId, subLevel)); - remainLevel -= subLevel - 1; - } - - if (subAffixes.Count < 4) - { - // random sub affix - var subAffixGroup = itemConfig.SubAffixGroup; - var subAffixGroupConfig = GameData.RelicSubAffixData[subAffixGroup]; - var subAffixGroupKeys = subAffixGroupConfig.Keys.ToList(); - while (subAffixes.Count < 4) - { - var subId = subAffixGroupKeys.RandomElement(); - if (subAffixes.Any(x => x.Item1 == subId)) - { - continue; - } - if (remainLevel <= 0) - { - subAffixes.Add((subId, 1)); - } - else - { - var subLevel = Random.Shared.Next(1, Math.Min(remainLevel + 1, 5)) + 1; - subAffixes.Add((subId, subLevel)); - remainLevel -= subLevel - 1; - } - } - } - - var itemData = new ItemData() - { - ItemId = int.Parse(arg.BasicArgs[0]), - Level = Math.Max(Math.Min(level, 9999), 1), - UniqueId = ++player.InventoryManager!.Data.NextUniqueId, - MainAffix = mainAffixId, - Count = 1, - }; - - foreach (var (subId, subLevel) in subAffixes) - { - subAffixConfig.TryGetValue(subId, out var subAffix); - var aff = new ItemSubAffix(subAffix!, 1); - for (var i = 1; i < subLevel; i++) - { - aff.IncreaseStep(subAffix!.StepNum); - } - itemData.SubAffixes.Add(aff); - } - - for (var i = 0; i < amount; i++) - { - player.InventoryManager!.AddItem(itemData, notify: false); - } - - arg.SendMsg(I18nManager.Translate("Game.Command.Relic.RelicGiven", player.Uid.ToString(), amount.ToString(), itemConfigExcel.Name ?? itemData.ItemId.ToString(), itemData.MainAffix.ToString())); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } + + if (arg.BasicArgs.Count < 3) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + arg.CharacterArgs.TryGetValue("x", out var str); + arg.CharacterArgs.TryGetValue("l", out var levelStr); + str ??= "1"; + levelStr ??= "1"; + if (!int.TryParse(str, out var amount) || !int.TryParse(levelStr, out var level)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + GameData.RelicConfigData.TryGetValue(int.Parse(arg.BasicArgs[0]), out var itemConfig); + GameData.ItemConfigData.TryGetValue(int.Parse(arg.BasicArgs[0]), out var itemConfigExcel); + if (itemConfig == null || itemConfigExcel == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Relic.RelicNotFound")); + return; + } + + GameData.RelicSubAffixData.TryGetValue(itemConfig.SubAffixGroup, out var subAffixConfig); + GameData.RelicMainAffixData.TryGetValue(itemConfig.MainAffixGroup, out var mainAffixConfig); + if (subAffixConfig == null || mainAffixConfig == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Relic.RelicNotFound")); + return; + } + + var startIndex = 1; + int mainAffixId; + if (arg.BasicArgs[1].Contains(':')) + { + // random main affix + mainAffixId = mainAffixConfig.Keys.ToList().RandomElement(); + } + else + { + mainAffixId = int.Parse(arg.BasicArgs[1]); + if (!mainAffixConfig.ContainsKey(mainAffixId)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Relic.InvalidMainAffixId")); + return; + } + + startIndex++; + } + + var remainLevel = 5; + var subAffixes = new List<(int, int)>(); + for (var i = startIndex; i < arg.BasicArgs.Count; i++) + { + var subAffix = arg.BasicArgs[i].Split(':'); + if (subAffix.Length != 2 || !int.TryParse(subAffix[0], out var subId) || + !int.TryParse(subAffix[1], out var subLevel)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + if (!subAffixConfig.ContainsKey(subId)) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Relic.InvalidSubAffixId")); + return; + } + + subAffixes.Add((subId, subLevel)); + remainLevel -= subLevel - 1; + } + + if (subAffixes.Count < 4) + { + // random sub affix + var subAffixGroup = itemConfig.SubAffixGroup; + var subAffixGroupConfig = GameData.RelicSubAffixData[subAffixGroup]; + var subAffixGroupKeys = subAffixGroupConfig.Keys.ToList(); + while (subAffixes.Count < 4) + { + var subId = subAffixGroupKeys.RandomElement(); + if (subAffixes.Any(x => x.Item1 == subId)) continue; + if (remainLevel <= 0) + { + subAffixes.Add((subId, 1)); + } + else + { + var subLevel = Random.Shared.Next(1, Math.Min(remainLevel + 1, 5)) + 1; + subAffixes.Add((subId, subLevel)); + remainLevel -= subLevel - 1; + } + } + } + + var itemData = new ItemData + { + ItemId = int.Parse(arg.BasicArgs[0]), + Level = Math.Max(Math.Min(level, 9999), 1), + UniqueId = ++player.InventoryManager!.Data.NextUniqueId, + MainAffix = mainAffixId, + Count = 1 + }; + + foreach (var (subId, subLevel) in subAffixes) + { + subAffixConfig.TryGetValue(subId, out var subAffix); + var aff = new ItemSubAffix(subAffix!, 1); + for (var i = 1; i < subLevel; i++) aff.IncreaseStep(subAffix!.StepNum); + itemData.SubAffixes.Add(aff); + } + + for (var i = 0; i < amount; i++) await player.InventoryManager!.AddItem(itemData, false); + + await arg.SendMsg(I18nManager.Translate("Game.Command.Relic.RelicGiven", player.Uid.ToString(), + amount.ToString(), itemConfigExcel.Name ?? itemData.ItemId.ToString(), itemData.MainAffix.ToString())); } -} +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandReload.cs b/Command/Command/Cmd/CommandReload.cs index ac915156..aefec4b5 100644 --- a/Command/Command/Cmd/CommandReload.cs +++ b/Command/Command/Cmd/CommandReload.cs @@ -1,31 +1,29 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Data.Custom; using EggLink.DanhengServer.Internationalization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("reload", "Game.Command.Reload.Desc", "Game.Command.Reload.Usage", permission: "egglink.manage")] +public class CommandReload : ICommand { - [CommandInfo("reload", "Game.Command.Reload.Desc", "Game.Command.Reload.Usage", permission: "egglink.manage")] - public class CommandReload : ICommand + [CommandMethod("0 banner")] + public async ValueTask ReloadBanner(CommandArg arg) { - [CommandMethod("0 banner")] - public void ReloadBanner(CommandArg arg) - { - // Reload the banners - GameData.BannersConfig = ResourceManager.LoadCustomFile("Banner", "Banners") ?? new(); - arg.SendMsg(I18nManager.Translate("Game.Command.Reload.ConfigReloaded", I18nManager.Translate("Word.Banner"))); - } - - [CommandMethod("0 activity")] - public void ReloadActivity(CommandArg arg) - { - // Reload the activities - GameData.ActivityConfig = ResourceManager.LoadCustomFile("Activity", "ActivityConfig") ?? new(); - arg.SendMsg(I18nManager.Translate("Game.Command.Reload.ConfigReloaded", I18nManager.Translate("Word.Activity"))); - } + // Reload the banners + GameData.BannersConfig = + ResourceManager.LoadCustomFile("Banner", "Banners") ?? new BannersConfig(); + await arg.SendMsg(I18nManager.Translate("Game.Command.Reload.ConfigReloaded", + I18nManager.Translate("Word.Banner"))); } -} + + [CommandMethod("0 activity")] + public async ValueTask ReloadActivity(CommandArg arg) + { + // Reload the activities + GameData.ActivityConfig = ResourceManager.LoadCustomFile("Activity", "ActivityConfig") ?? + new ActivityConfig(); + await arg.SendMsg(I18nManager.Translate("Game.Command.Reload.ConfigReloaded", + I18nManager.Translate("Word.Activity"))); + } +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandRogue.cs b/Command/Command/Cmd/CommandRogue.cs index 24e5b187..f0e71634 100644 --- a/Command/Command/Cmd/CommandRogue.cs +++ b/Command/Command/Cmd/CommandRogue.cs @@ -2,138 +2,165 @@ using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Game.Rogue.Scene.Entity; using EggLink.DanhengServer.Internationalization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("rogue", "Game.Command.Rogue.Desc", "Game.Command.Rogue.Usage")] +public class CommandRogue : ICommand { - [CommandInfo("rogue", "Game.Command.Rogue.Desc", "Game.Command.Rogue.Usage")] - public class CommandRogue : ICommand + [CommandMethod("0 money")] + public async ValueTask GetMoney(CommandArg arg) { - [CommandMethod("0 money")] - public void GetMoney(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var count = arg.GetInt(0); - arg.Target.Player!.RogueManager!.GetRogueInstance()?.GainMoney(count); - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerGainedMoney", count.ToString())); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } - [CommandMethod("0 buff")] - public void GetBuff(CommandArg arg) + var count = arg.GetInt(0); + var instance = arg.Target.Player!.RogueManager?.GetRogueInstance(); + if (instance == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var id = arg.GetInt(0); - - if (id == -1) - { - var buffList = new List(); - foreach (var buff in GameData.RogueBuffData.Values) - { - if (buff.IsAeonBuff || buff.MazeBuffLevel == 2) continue; - buffList.Add(buff); - } - arg.Target.Player!.RogueManager!.GetRogueInstance()?.AddBuffList(buffList); - - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerGainedAllItems", I18nManager.Translate("Word.Buff"))); - } - else - { - GameData.RogueMazeBuffData.TryGetValue(id, out var buff); - if (buff == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.ItemNotFound", I18nManager.Translate("Word.Buff"))); - return; - } - arg.Target.Player!.RogueManager!.GetRogueInstance()?.AddBuff(buff.ID, buff.Lv); - - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerGainedItem", I18nManager.Translate("Word.Buff"), buff.Name ?? id.ToString())); - } + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerNotInRogue")); + return; } - [CommandMethod("0 miracle")] - public void GetMiracle(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var id = arg.GetInt(0); + await instance.GainMoney(count); + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerGainedMoney", count.ToString())); + } - GameData.RogueMiracleData.TryGetValue(id, out var miracle); - if (miracle == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.ItemNotFound", I18nManager.Translate("Word.Miracle"))); - return; - } - arg.Target.Player!.RogueManager!.GetRogueInstance()?.AddMiracle(id); - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerGainedItem", I18nManager.Translate("Word.Miracle"), miracle.Name ?? id.ToString())); + [CommandMethod("0 buff")] + public async ValueTask GetBuff(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } - [CommandMethod("0 enhance")] - public void GetEnhance(CommandArg arg) + var instance = arg.Target.Player!.RogueManager?.GetRogueInstance(); + if (instance == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var id = arg.GetInt(0); - if (id == -1) - { - foreach (var enhance in GameData.RogueBuffData.Values) - { - arg.Target.Player!.RogueManager!.GetRogueInstance()?.EnhanceBuff(enhance.MazeBuffID); - } - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerEnhancedAllBuffs")); - } - else - { - GameData.RogueMazeBuffData.TryGetValue(id, out var buff); - if (buff == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.ItemNotFound", I18nManager.Translate("Word.Buff"))); - return; - } - arg.Target.Player!.RogueManager!.GetRogueInstance()?.EnhanceBuff(buff.ID); - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerEnhancedBuff", buff.Name ?? id.ToString())); - } + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerNotInRogue")); + return; } - [CommandMethod("0 unstuck")] - public void Unstuck(CommandArg arg) + var id = arg.GetInt(0); + + if (id == -1) { - if (arg.Target == null) + var buffList = new List(); + foreach (var buff in GameData.RogueBuffData.Values) { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + if (buff.IsAeonBuff || buff.MazeBuffLevel == 2) continue; + buffList.Add(buff); + } + + await instance.AddBuffList(buffList); + + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerGainedAllItems", + I18nManager.Translate("Word.Buff"))); + } + else + { + GameData.RogueMazeBuffData.TryGetValue(id, out var buff); + if (buff == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.ItemNotFound", + I18nManager.Translate("Word.Buff"))); return; } - var player = arg.Target.Player!; - foreach (var npc in player.SceneInstance!.Entities.Values) - { - if (npc is RogueNpc rNpc) - { - if (rNpc.RogueNpcId > 0) - { - player.SceneInstance!.RemoveEntity(rNpc); - } - } - } + await instance.AddBuff(buff.ID, buff.Lv); - arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerUnstuck")); + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerGainedItem", + I18nManager.Translate("Word.Buff"), buff.Name ?? id.ToString())); } } -} + + [CommandMethod("0 miracle")] + public async ValueTask GetMiracle(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var instance = arg.Target.Player!.RogueManager?.GetRogueInstance(); + if (instance == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerNotInRogue")); + return; + } + + var id = arg.GetInt(0); + + GameData.RogueMiracleData.TryGetValue(id, out var miracle); + if (miracle == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.ItemNotFound", + I18nManager.Translate("Word.Miracle"))); + return; + } + + await instance.AddMiracle(id); + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerGainedItem", + I18nManager.Translate("Word.Miracle"), miracle.Name ?? id.ToString())); + } + + [CommandMethod("0 enhance")] + public async ValueTask GetEnhance(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var instance = arg.Target.Player!.RogueManager?.GetRogueInstance(); + if (instance == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerNotInRogue")); + return; + } + + var id = arg.GetInt(0); + if (id == -1) + { + foreach (var enhance in GameData.RogueBuffData.Values) await instance.EnhanceBuff(enhance.MazeBuffID); + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerEnhancedAllBuffs")); + } + else + { + GameData.RogueMazeBuffData.TryGetValue(id, out var buff); + if (buff == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.ItemNotFound", + I18nManager.Translate("Word.Buff"))); + return; + } + + await instance.EnhanceBuff(buff.ID); + await arg.SendMsg( + I18nManager.Translate("Game.Command.Rogue.PlayerEnhancedBuff", buff.Name ?? id.ToString())); + } + } + + [CommandMethod("0 unstuck")] + public async ValueTask Unstuck(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var player = arg.Target.Player!; + foreach (var npc in player.SceneInstance!.Entities.Values) + if (npc is RogueNpc rNpc && rNpc.RogueNpcId > 0) + await player.SceneInstance!.RemoveEntity(rNpc); + + await arg.SendMsg(I18nManager.Translate("Game.Command.Rogue.PlayerUnstuck")); + } +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandScene.cs b/Command/Command/Cmd/CommandScene.cs index 2b840411..ba2e049b 100644 --- a/Command/Command/Cmd/CommandScene.cs +++ b/Command/Command/Cmd/CommandScene.cs @@ -1,164 +1,153 @@ using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Internationalization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("scene", "Game.Command.Scene.Desc", "Game.Command.Scene.Usage")] +public class CommandScene : ICommand { - [CommandInfo("scene", "Game.Command.Scene.Desc", "Game.Command.Scene.Usage")] - public class CommandScene : ICommand + [CommandMethod("0 group")] + public async ValueTask GetLoadedGroup(CommandArg arg) { - [CommandMethod("0 group")] - public void GetLoadedGroup(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var scene = arg.Target!.Player!.SceneInstance!; - var loadedGroup = new List(); - foreach (var group in scene.Entities) - { - if (!loadedGroup.Contains(group.Value.GroupID)) - { - loadedGroup.Add(group.Value.GroupID); - } - } - arg.SendMsg(I18nManager.Translate("Game.Command.Scene.LoadedGroups", string.Join(", ", loadedGroup))); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } - [CommandMethod("0 prop")] - public void GetProp(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var scene = arg.Target!.Player!.SceneInstance!; - EntityProp? prop = null; - foreach (var entity in scene.GetEntitiesInGroup(arg.GetInt(0))) - { - if (entity.PropInfo.ID == arg.GetInt(1)) - { - prop = entity; - break; - } - } - if (prop == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Scene.PropNotFound")); - return; - } - prop.SetState((PropStateEnum)arg.GetInt(2)); - arg.SendMsg(I18nManager.Translate("Game.Command.Scene.PropStateChanged", prop.PropInfo.ID.ToString(), prop.State.ToString())); - } - - [CommandMethod("0 remove")] - public void RemoveEntity(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var scene = arg.Target!.Player!.SceneInstance!; - scene.Entities.TryGetValue(arg.GetInt(0), out var entity); - if (entity == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Scene.EntityNotFound")); - return; - } - scene.RemoveEntity(entity); - arg.SendMsg(I18nManager.Translate("Game.Command.Scene.EntityRemoved", entity.EntityID.ToString())); - } - - [CommandMethod("0 unlockall")] - public void UnlockAll(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var scene = arg.Target!.Player!.SceneInstance!; - foreach (var entity in scene.Entities.Values) - { - if (entity is EntityProp prop) - { - if (prop.Excel.PropStateList.Contains(PropStateEnum.Open)) - prop.SetState(PropStateEnum.Open); - } - } - arg.SendMsg(I18nManager.Translate("Game.Command.Scene.AllPropsUnlocked")); - } - - [CommandMethod("0 change")] - public void ChangeScene(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - if (arg.GetInt(0) == 0) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - var player = arg.Target!.Player!; - player.EnterScene(arg.GetInt(0), 0, true); - arg.SendMsg(I18nManager.Translate("Game.Command.Scene.SceneChanged", arg.GetInt(0).ToString())); - } - - [CommandMethod("0 reload")] - public void ReloadScene(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - var player = arg.Target!.Player!; - player.EnterScene(player.Data.EntryId, 0, true); - arg.SendMsg(I18nManager.Translate("Game.Command.Scene.SceneReloaded")); - } - - [CommandMethod("0 reset")] - public void ResetFloor(CommandArg arg) - { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - - var floorId = arg.GetInt(0); - if (floorId == 0) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); - return; - } - - var player = arg.Target!.Player!; - if (player.SceneData?.ScenePropData.TryGetValue(floorId, out var _) == true) - { - player.SceneData.ScenePropData[floorId] = []; - } - - if (player.SceneData?.FloorSavedData.TryGetValue(floorId, out var _) == true) - { - player.SceneData.FloorSavedData[floorId] = []; - } - - arg.SendMsg(I18nManager.Translate("Game.Command.Scene.SceneReset", floorId.ToString())); - } + var scene = arg.Target!.Player!.SceneInstance!; + var loadedGroup = new List(); + foreach (var group in scene.Entities) + if (!loadedGroup.Contains(group.Value.GroupID)) + loadedGroup.Add(group.Value.GroupID); + await arg.SendMsg(I18nManager.Translate("Game.Command.Scene.LoadedGroups", string.Join(", ", loadedGroup))); } -} + + [CommandMethod("0 prop")] + public async ValueTask GetProp(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var scene = arg.Target!.Player!.SceneInstance!; + EntityProp? prop = null; + foreach (var entity in scene.GetEntitiesInGroup(arg.GetInt(0))) + if (entity.PropInfo.ID == arg.GetInt(1)) + { + prop = entity; + break; + } + + if (prop == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Scene.PropNotFound")); + return; + } + + await prop.SetState((PropStateEnum)arg.GetInt(2)); + await arg.SendMsg(I18nManager.Translate("Game.Command.Scene.PropStateChanged", prop.PropInfo.ID.ToString(), + prop.State.ToString())); + } + + [CommandMethod("0 remove")] + public async ValueTask RemoveEntity(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var scene = arg.Target!.Player!.SceneInstance!; + scene.Entities.TryGetValue(arg.GetInt(0), out var entity); + if (entity == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Scene.EntityNotFound")); + return; + } + + await scene.RemoveEntity(entity); + await arg.SendMsg(I18nManager.Translate("Game.Command.Scene.EntityRemoved", entity.EntityID.ToString())); + } + + [CommandMethod("0 unlockall")] + public async ValueTask UnlockAll(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var scene = arg.Target!.Player!.SceneInstance!; + foreach (var entity in scene.Entities.Values) + if (entity is EntityProp prop) + if (prop.Excel.PropStateList.Contains(PropStateEnum.Open)) + await prop.SetState(PropStateEnum.Open); + await arg.SendMsg(I18nManager.Translate("Game.Command.Scene.AllPropsUnlocked")); + } + + [CommandMethod("0 change")] + public async ValueTask ChangeScene(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + if (arg.GetInt(0) == 0) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + var player = arg.Target!.Player!; + await player.EnterScene(arg.GetInt(0), 0, true); + await arg.SendMsg(I18nManager.Translate("Game.Command.Scene.SceneChanged", arg.GetInt(0).ToString())); + } + + [CommandMethod("0 reload")] + public async ValueTask ReloadScene(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var player = arg.Target!.Player!; + await player.EnterScene(player.Data.EntryId, 0, true); + await arg.SendMsg(I18nManager.Translate("Game.Command.Scene.SceneReloaded")); + } + + [CommandMethod("0 reset")] + public async ValueTask ResetFloor(CommandArg arg) + { + if (arg.Target == null) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; + } + + var floorId = arg.GetInt(0); + if (floorId == 0) + { + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.InvalidArguments")); + return; + } + + var player = arg.Target!.Player!; + if (player.SceneData?.ScenePropData.TryGetValue(floorId, out var _) == true) + player.SceneData.ScenePropData[floorId] = []; + + if (player.SceneData?.FloorSavedData.TryGetValue(floorId, out var _) == true) + player.SceneData.FloorSavedData[floorId] = []; + + await arg.SendMsg(I18nManager.Translate("Game.Command.Scene.SceneReset", floorId.ToString())); + } +} \ No newline at end of file diff --git a/Command/Command/Cmd/CommandUnlockAll.cs b/Command/Command/Cmd/CommandUnlockAll.cs index 4998dc2c..64964322 100644 --- a/Command/Command/Cmd/CommandUnlockAll.cs +++ b/Command/Command/Cmd/CommandUnlockAll.cs @@ -1,51 +1,46 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Enums; -using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -namespace EggLink.DanhengServer.Command.Cmd +namespace EggLink.DanhengServer.Command.Cmd; + +[CommandInfo("unlockall", "Game.Command.UnlockAll.Desc", "Game.Command.UnlockAll.Usage")] +public class CommandUnlockAll : ICommand { - [CommandInfo("unlockall", "Game.Command.UnlockAll.Desc", "Game.Command.UnlockAll.Usage")] - public class CommandUnlockAll : ICommand + [CommandMethod("0 mission")] + public async ValueTask UnlockAllMissions(CommandArg arg) { - [CommandMethod("0 mission")] - public void UnlockAllMissions(CommandArg arg) + if (arg.Target == null) { - if (arg.Target == null) - { - arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); - return; - } - var player = arg.Target!.Player!; - var missionManager = player.MissionManager!; - - foreach (var mission in GameData.SubMissionData.Values) - { - missionManager.Data.SetSubMissionStatus(mission.SubMissionID, MissionPhaseEnum.Finish); - } - - foreach (var mission in GameData.MainMissionData.Values) - { - missionManager.Data.SetMainMissionStatus(mission.MainMissionID, MissionPhaseEnum.Finish); - } - - if (player.Data.CurrentGender == Gender.Man) - { - player.Data.CurrentGender = Gender.Man; - player.Data.CurBasicType = 8001; - } else - { - player.Data.CurrentGender = Gender.Woman; - player.Data.CurBasicType = 8002; - player.AvatarManager!.GetHero()!.HeroId = 8002; - } - - arg.SendMsg(I18nManager.Translate("Game.Command.UnlockAll.AllMissionsUnlocked")); - arg.Target!.Player!.SendPacket(new PacketPlayerKickOutScNotify()); - arg.Target!.Stop(); + await arg.SendMsg(I18nManager.Translate("Game.Command.Notice.PlayerNotFound")); + return; } + + var player = arg.Target!.Player!; + var missionManager = player.MissionManager!; + + foreach (var mission in GameData.SubMissionData.Values) + missionManager.Data.SetSubMissionStatus(mission.SubMissionID, MissionPhaseEnum.Finish); + + foreach (var mission in GameData.MainMissionData.Values) + missionManager.Data.SetMainMissionStatus(mission.MainMissionID, MissionPhaseEnum.Finish); + + if (player.Data.CurrentGender == Gender.Man) + { + player.Data.CurrentGender = Gender.Man; + player.Data.CurBasicType = 8001; + } + else + { + player.Data.CurrentGender = Gender.Woman; + player.Data.CurBasicType = 8002; + player.AvatarManager!.GetHero()!.HeroId = 8002; + } + + await arg.SendMsg(I18nManager.Translate("Game.Command.UnlockAll.AllMissionsUnlocked")); + await arg.Target!.Player!.SendPacket(new PacketPlayerKickOutScNotify()); + arg.Target!.Stop(); } -} +} \ No newline at end of file diff --git a/Command/Command/CommandArg.cs b/Command/Command/CommandArg.cs index 88c984c3..3e8073f4 100644 --- a/Command/Command/CommandArg.cs +++ b/Command/Command/CommandArg.cs @@ -1,85 +1,70 @@ using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command +namespace EggLink.DanhengServer.Command; + +public class CommandArg { - public class CommandArg + public CommandArg(string raw, ICommandSender sender, Connection? con = null) { - public string Raw { get; } - public List Args { get; } = []; - public List BasicArgs { get; } = []; - public Dictionary CharacterArgs { get; } = []; - public Connection? Target { get; set; } - public ICommandSender Sender { get; } - - public CommandArg(string raw, ICommandSender sender, Connection? con = null) + Raw = raw; + Sender = sender; + var args = raw.Split(' '); + foreach (var arg in args) { - Raw = raw; - Sender = sender; - var args = raw.Split(' '); - foreach (var arg in args) + if (string.IsNullOrEmpty(arg)) continue; + var character = arg[0]; + if (!int.TryParse(character.ToString(), out var _) && character != '-') { - if (string.IsNullOrEmpty(arg)) + try { - continue; + CharacterArgs.Add(arg[..1], arg[1..]); + Args.Add(arg); } - var character = arg[0]; - if (!int.TryParse(character.ToString(), out var _) && character != '-') - { - try - { - CharacterArgs.Add(arg[..1], arg[1..]); - Args.Add(arg); - } catch - { - BasicArgs.Add(arg); - Args.Add(arg); - } - } - else + catch { BasicArgs.Add(arg); Args.Add(arg); } } - if (con != null) + else { - Target = con; - } - - CharacterArgs.TryGetValue("@", out var target); - if (target != null) - { - var connection = Listener.Connections.Values.ToList().Find(item => item.Player?.Uid.ToString() == target); - if (connection != null) - { - Target = connection; - } + BasicArgs.Add(arg); + Args.Add(arg); } } - public int GetInt(int index) - { - if (BasicArgs.Count <= index) - { - return 0; - } - _ = int.TryParse(BasicArgs[index], out int res); - return res; - } - public void SendMsg(string msg) - { - Sender.SendMsg(msg); - } + if (con != null) Target = con; - public override string ToString() + CharacterArgs.TryGetValue("@", out var target); + if (target != null) { - return $"BasicArg: {BasicArgs.ToArrayString()}. CharacterArg: {CharacterArgs.ToJsonString()}."; + var connection = Listener.Connections.Values.ToList().Find(item => item.Player?.Uid.ToString() == target); + if (connection != null) Target = connection; } } -} + + public string Raw { get; } + public List Args { get; } = []; + public List BasicArgs { get; } = []; + public Dictionary CharacterArgs { get; } = []; + public Connection? Target { get; set; } + public ICommandSender Sender { get; } + + public int GetInt(int index) + { + if (BasicArgs.Count <= index) return 0; + _ = int.TryParse(BasicArgs[index], out var res); + return res; + } + + public async ValueTask SendMsg(string msg) + { + await Sender.SendMsg(msg); + } + + public override string ToString() + { + return $"BasicArg: {BasicArgs.ToArrayString()}. CharacterArg: {CharacterArgs.ToJsonString()}."; + } +} \ No newline at end of file diff --git a/Command/Command/CommandManager.cs b/Command/Command/CommandManager.cs index fa67c175..b5cd7c90 100644 --- a/Command/Command/CommandManager.cs +++ b/Command/Command/CommandManager.cs @@ -1,194 +1,187 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.GameServer.Command; +using System.Reflection; using EggLink.DanhengServer.Internationalization; -using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Util; using Spectre.Console; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Command +namespace EggLink.DanhengServer.Command; + +public class CommandManager { - public class CommandManager + public static CommandManager? Instance { get; private set; } + public Dictionary Commands { get; } = []; + public Dictionary CommandInfo { get; } = []; + public Logger Logger { get; } = new("CommandManager"); + public Connection? Target { get; set; } + + public void RegisterCommand() { - public static CommandManager? Instance { get; private set; } - public Dictionary Commands { get; } = []; - public Dictionary CommandInfo { get; } = []; - public Logger Logger { get; } = new Logger("CommandManager"); - public Connection? Target { get; set; } = null; - - public void RegisterCommand() + Instance = this; + foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) { - Instance = this; - foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) + var attr = type.GetCustomAttribute(); + if (attr != null) { - var attr = type.GetCustomAttribute(); - if (attr != null) + var instance = Activator.CreateInstance(type); + if (instance is ICommand command) { - var instance = Activator.CreateInstance(type); - if (instance is ICommand command) - { - Commands.Add(attr.Name, command); - CommandInfo.Add(attr.Name, attr); - } - } - } - - Logger.Info(I18nManager.Translate("Server.ServerInfo.RegisterItem", Commands.Count.ToString(), I18nManager.Translate("Word.Command"))); - } - - public void Start() - { - while (true) - { - try - { - string? input = AnsiConsole.Ask("> "); - if (string.IsNullOrEmpty(input)) - { - continue; - } - HandleCommand(input, new ConsoleCommandSender(Logger)); - } - catch - { - Logger.Error(I18nManager.Translate("Game.Command.Notice.InternalError")); + Commands.Add(attr.Name, command); + CommandInfo.Add(attr.Name, attr); } } } - public void HandleCommand(string input, ICommandSender sender) - { + Logger.Info(I18nManager.Translate("Server.ServerInfo.RegisterItem", Commands.Count.ToString(), + I18nManager.Translate("Word.Command"))); + } + + public void Start() + { + while (true) try { - var cmd = input.Split(' ')[0]; - - var tempTarget = Target; - if (sender is ConsoleCommandSender) - { - if (cmd.StartsWith('@')) - { - var target = cmd[1..]; - var con = Listener.Connections.Values.ToList().Find(item => item.Player?.Uid.ToString() == target); - if (con != null) - { - Target = con; - sender.SendMsg(I18nManager.Translate("Game.Command.Notice.TargetFound", target, con.Player!.Data.Name!)); - } - else - { - // offline or not exist - sender.SendMsg(I18nManager.Translate("Game.Command.Notice.TargetNotFound", target)); - } - return; - } - } else - { - // player - tempTarget = Listener.GetActiveConnection(sender.GetSender()); - if (tempTarget == null) - { - sender.SendMsg(I18nManager.Translate("Game.Command.Notice.TargetNotFound", sender.GetSender().ToString())); - return; - } - } - - if (tempTarget != null && !tempTarget.IsOnline) - { - sender.SendMsg(I18nManager.Translate("Game.Command.Notice.TargetOffline", tempTarget.Player!.Uid.ToString(), tempTarget.Player!.Data.Name!)); - tempTarget = null; - } - - if (Commands.TryGetValue(cmd, out var command)) - { - var split = input.Split(' ').ToList(); - split.RemoveAt(0); - - var arg = new CommandArg(split.JoinFormat(" ", ""), sender, tempTarget); - - // judge permission - if (arg.Target?.Player?.Uid != sender.GetSender() && !sender.HasPermission("command.others")) - { - sender.SendMsg(I18nManager.Translate("Game.Command.Notice.NoPermission")); - return; - } - // find the proper method with attribute CommandMethod - var isFound = false; - CommandInfo info = CommandInfo[cmd]; - - if (!sender.HasPermission(info.Permission)) - { - sender.SendMsg(I18nManager.Translate("Game.Command.Notice.NoPermission")); - return; - } - - foreach (var method in command.GetType().GetMethods()) - { - var attr = method.GetCustomAttribute(); - if (attr != null) - { - var canRun = true; - foreach (var condition in attr.Conditions) - { - if (split.Count <= condition.Index) - { - canRun = false; - break; - } - if (!split[condition.Index].Equals(condition.ShouldBe)) - { - canRun = false; - break; - } - } - if (canRun) - { - isFound = true; - method.Invoke(command, [arg]); - break; - } - } - } - if (!isFound) - { - // find the default method with attribute CommandDefault - foreach (var method in command.GetType().GetMethods()) - { - var attr = method.GetCustomAttribute(); - if (attr != null) - { - isFound = true; - method.Invoke(command, [arg]); - break; - } - } - if (!isFound) - { - if (info != null) - { - sender.SendMsg(I18nManager.Translate(info.Usage)); - } - else - { - sender.SendMsg(I18nManager.Translate("Game.Command.Notice.CommandNotFound")); - } - } - } - } - else - { - sender.SendMsg(I18nManager.Translate("Game.Command.Notice.CommandNotFound")); - } + var input = AnsiConsole.Ask("> "); + if (string.IsNullOrEmpty(input)) continue; + HandleCommand(input, new ConsoleCommandSender(Logger)); } catch { - sender.SendMsg(I18nManager.Translate("Game.Command.Notice.InternalError")); + Logger.Error(I18nManager.Translate("Game.Command.Notice.InternalError")); + } + } + + public void HandleCommand(string input, ICommandSender sender) + { + try + { + var cmd = input.Split(' ')[0]; + + var tempTarget = Target; + if (sender is ConsoleCommandSender) + { + if (cmd.StartsWith('@')) + { + var target = cmd[1..]; + var con = Listener.Connections.Values.ToList().Find(item => item.Player?.Uid.ToString() == target); + if (con != null) + { + Target = con; + sender.SendMsg(I18nManager.Translate("Game.Command.Notice.TargetFound", target, + con.Player!.Data.Name!)); + } + else + { + // offline or not exist + sender.SendMsg(I18nManager.Translate("Game.Command.Notice.TargetNotFound", target)); + } + + return; + } + } + else + { + // player + tempTarget = Listener.GetActiveConnection(sender.GetSender()); + if (tempTarget == null) + { + sender.SendMsg(I18nManager.Translate("Game.Command.Notice.TargetNotFound", + sender.GetSender().ToString())); + return; + } + } + + if (tempTarget != null && !tempTarget.IsOnline) + { + sender.SendMsg(I18nManager.Translate("Game.Command.Notice.TargetOffline", + tempTarget.Player!.Uid.ToString(), tempTarget.Player!.Data.Name!)); + tempTarget = null; + } + + if (Commands.TryGetValue(cmd, out var command)) + { + var split = input.Split(' ').ToList(); + split.RemoveAt(0); + + var arg = new CommandArg(split.JoinFormat(" ", ""), sender, tempTarget); + + // judge permission + if (arg.Target?.Player?.Uid != sender.GetSender() && !sender.HasPermission("command.others")) + { + sender.SendMsg(I18nManager.Translate("Game.Command.Notice.NoPermission")); + return; + } + + // find the proper method with attribute CommandMethod + var isFound = false; + var info = CommandInfo[cmd]; + + if (!sender.HasPermission(info.Permission)) + { + sender.SendMsg(I18nManager.Translate("Game.Command.Notice.NoPermission")); + return; + } + + foreach (var method in command.GetType().GetMethods()) + { + var attr = method.GetCustomAttribute(); + if (attr != null) + { + var canRun = true; + foreach (var condition in attr.Conditions) + { + if (split.Count <= condition.Index) + { + canRun = false; + break; + } + + if (!split[condition.Index].Equals(condition.ShouldBe)) + { + canRun = false; + break; + } + } + + if (canRun) + { + isFound = true; + method.Invoke(command, [arg]); + break; + } + } + } + + if (!isFound) + { + // find the default method with attribute CommandDefault + foreach (var method in command.GetType().GetMethods()) + { + var attr = method.GetCustomAttribute(); + if (attr != null) + { + isFound = true; + method.Invoke(command, [arg]); + break; + } + } + + if (!isFound) + { + if (info != null) + sender.SendMsg(I18nManager.Translate(info.Usage)); + else + sender.SendMsg(I18nManager.Translate("Game.Command.Notice.CommandNotFound")); + } + } + } + else + { + sender.SendMsg(I18nManager.Translate("Game.Command.Notice.CommandNotFound")); } } + catch + { + sender.SendMsg(I18nManager.Translate("Game.Command.Notice.InternalError")); + } } -} +} \ No newline at end of file diff --git a/Common/Command/CommandInfo.cs b/Common/Command/CommandInfo.cs index 311f14b8..3b08927e 100644 --- a/Common/Command/CommandInfo.cs +++ b/Common/Command/CommandInfo.cs @@ -1,51 +1,46 @@ -namespace EggLink.DanhengServer.Command +namespace EggLink.DanhengServer.Command; + +[AttributeUsage(AttributeTargets.Class)] +public class CommandInfo(string name, string description, string usage, string keyword = "", string permission = "") + : Attribute { - [AttributeUsage(AttributeTargets.Class)] - public class CommandInfo(string name, string description, string usage, string keyword = "", string permission = "") : Attribute + public CommandInfo(string name, string description, string usage, List alias, string keyword = "", + string permission = "") : this(name, description, usage, keyword, permission) { - public CommandInfo(string name, string description, string usage, List alias, string keyword = "", string permission = "") : this(name, description, usage, keyword, permission) - { - Alias = alias ?? []; - } - - public string Name { get; } = name; - public string Description { get; } = description; - public string Usage { get; } = usage; - public string Keyword { get; } = keyword; - public string Permission { get; } = permission; - public List Alias { get; } = []; + Alias = alias ?? []; } - [AttributeUsage(AttributeTargets.Method)] - public class CommandMethod(CommandCondition conditions) : Attribute - { - public List Conditions { get; } = [conditions]; - public CommandMethod(string condition) : this(new CommandCondition()) - { - var index = 0; - var conditions = condition.Split(' '); - foreach (var c in conditions) - { - if (int.TryParse(c, out var i)) - { - Conditions[index].Index = i; - } - else if (c is string s) - { - Conditions[index++].ShouldBe = s; - } - } - } - } - - [AttributeUsage(AttributeTargets.Method)] - public class CommandDefault : Attribute - { - } - - public class CommandCondition - { - public int Index { get; set; } - public string ShouldBe { get; set; } = ""; - } + public string Name { get; } = name; + public string Description { get; } = description; + public string Usage { get; } = usage; + public string Keyword { get; } = keyword; + public string Permission { get; } = permission; + public List Alias { get; } = []; } + +[AttributeUsage(AttributeTargets.Method)] +public class CommandMethod(CommandCondition conditions) : Attribute +{ + public CommandMethod(string condition) : this(new CommandCondition()) + { + var index = 0; + var conditions = condition.Split(' '); + foreach (var c in conditions) + if (int.TryParse(c, out var i)) + Conditions[index].Index = i; + else if (c is string s) Conditions[index++].ShouldBe = s; + } + + public List Conditions { get; } = [conditions]; +} + +[AttributeUsage(AttributeTargets.Method)] +public class CommandDefault : Attribute +{ +} + +public class CommandCondition +{ + public int Index { get; set; } + public string ShouldBe { get; set; } = ""; +} \ No newline at end of file diff --git a/Common/Command/CommandSender.cs b/Common/Command/CommandSender.cs index 38631aad..2aad7e35 100644 --- a/Common/Command/CommandSender.cs +++ b/Common/Command/CommandSender.cs @@ -1,37 +1,31 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Database.Account; -using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Command +namespace EggLink.DanhengServer.Command; + +public interface ICommandSender { - public interface ICommandSender - { - public void SendMsg(string msg); + public ValueTask SendMsg(string msg); - public bool HasPermission(string permission); + public bool HasPermission(string permission); - public int GetSender(); - } - - public class ConsoleCommandSender(Logger logger) : ICommandSender - { - public void SendMsg(string msg) - { - logger.Info(msg); - } - - public bool HasPermission(string permission) - { - return true; - } - public int GetSender() - { - return 0; - } - } + public int GetSender(); } + +public class ConsoleCommandSender(Logger logger) : ICommandSender +{ + public async ValueTask SendMsg(string msg) + { + logger.Info(msg); + await Task.CompletedTask; + } + + public bool HasPermission(string permission) + { + return true; + } + + public int GetSender() + { + return 0; + } +} \ No newline at end of file diff --git a/Common/Command/ICommand.cs b/Common/Command/ICommand.cs index cd6e4873..bb8f44b2 100644 --- a/Common/Command/ICommand.cs +++ b/Common/Command/ICommand.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Command; -namespace EggLink.DanhengServer.Command +public interface ICommand { - public interface ICommand - { - } -} +} \ No newline at end of file diff --git a/Common/Configuration/ConfigContainer.cs b/Common/Configuration/ConfigContainer.cs index b0e87ce1..4622a85d 100644 --- a/Common/Configuration/ConfigContainer.cs +++ b/Common/Configuration/ConfigContainer.cs @@ -1,113 +1,112 @@ -using System.Collections.Generic; +namespace EggLink.DanhengServer.Configuration; -namespace EggLink.DanhengServer.Configuration +public class ConfigContainer { - public class ConfigContainer - { - public HttpServerConfig HttpServer { get; set; } = new HttpServerConfig(); - public KeyStoreConfig KeyStore { get; set; } = new KeyStoreConfig(); - public GameServerConfig GameServer { get; set; } = new GameServerConfig(); - public PathConfig Path { get; set; } = new PathConfig(); - public DatabaseConfig Database { get; set; } = new DatabaseConfig(); - public ServerOption ServerOption { get; set; } = new ServerOption(); - public DownloadUrlConfig DownloadUrl { get; set; } = new DownloadUrlConfig(); - public MuipServerConfig MuipServer { get; set; } = new MuipServerConfig(); - } + public HttpServerConfig HttpServer { get; set; } = new(); + public KeyStoreConfig KeyStore { get; set; } = new(); + public GameServerConfig GameServer { get; set; } = new(); + public PathConfig Path { get; set; } = new(); + public DatabaseConfig Database { get; set; } = new(); + public ServerOption ServerOption { get; set; } = new(); + public DownloadUrlConfig DownloadUrl { get; set; } = new(); + public MuipServerConfig MuipServer { get; set; } = new(); +} - public class HttpServerConfig - { - public string PublicAddress { get; set; } = "127.0.0.1"; - public int PublicPort { get; set; } = 443; - public bool UseSSL { get; set; } = true; - public string GetDisplayAddress() - { - return (UseSSL ? "https" : "http") + "://" + PublicAddress + ":" + PublicPort; - } - } +public class HttpServerConfig +{ + public string PublicAddress { get; set; } = "127.0.0.1"; + public int PublicPort { get; set; } = 443; + public bool UseSSL { get; set; } = true; - public class KeyStoreConfig + public string GetDisplayAddress() { - public string KeyStorePath { get; set; } = "certificate.p12"; - public string KeyStorePassword { get; set; } = "123456"; - } - - public class GameServerConfig - { - public string PublicAddress { get; set; } = "127.0.0.1"; - public uint PublicPort { get; set; } = 23301; - public string GameServerId { get; set; } = "dan_heng"; - public string GameServerName { get; set; } = "DanhengServer"; - public string GameServerDescription { get; set; } = "A re-implementation of StarRail server"; - public int KcpInterval { get; set; } = 40; - public string GetDisplayAddress() - { - return PublicAddress + ":" + PublicPort; - } - } - - public class PathConfig - { - public string ResourcePath { get; set; } = "Resources"; - public string ConfigPath { get; set; } = "Config"; - public string DatabasePath { get; set; } = "Config/Database"; - public string LogPath { get; set; } = "Logs"; - public string PluginPath { get; set; } = "Plugins"; - public string PluginConfigPath { get; set; } = "Plugins/Config"; - } - - public class DatabaseConfig - { - public string DatabaseType { get; set; } = "sqlite"; - public string DatabaseName { get; set; } = "danheng.db"; - public string MySqlHost { get; set; } = "127.0.0.1"; - public int MySqlPort { get; set; } = 3306; - public string MySqlUser { get ; set; } = "root"; - public string MySqlPassword { get; set; } = "123456"; - public string MySqlDatabase { get; set; } = "danheng"; - } - - public class ServerOption - { - public int StartTrailblazerLevel { get; set; } = 1; - public bool AutoUpgradeWorldLevel { get; set; } = true; - public bool EnableMission { get; set; } = true; // experimental - public bool AutoLightSection { get; set; } = true; - public string Language { get; set; } = "EN"; - public List DefaultPermissions { get; set; } = ["*"]; - public ServerAnnounce ServerAnnounce { get; set; } = new ServerAnnounce(); - public ServerProfile ServerProfile { get; set; } = new ServerProfile(); - public bool AutoCreateUser { get; set; } = true; - public bool SavePersonalDebugFile { get; set; } = false; - } - - public class ServerAnnounce - { - public bool EnableAnnounce { get; set; } = true; - public string AnnounceContent { get; set; } = "Welcome to danhengserver!"; - } - - public class ServerProfile - { - public string Name { get; set; } = "Server"; - public int Uid { get; set; } = 80; - public string Signature { get; set; } = "Type /help for a list of commands"; - public int Level { get; set; } = 1; - public int HeadIcon { get; set; } = 200105; - public int ChatBubbleId { get; set; } = 220001; - public int DisplayAvatarId { get; set; } = 1001; - public int DisplayAvatarLevel { get; set; } = 1; - } - - public class DownloadUrlConfig - { - public string? AssetBundleUrl { get; set; } = null; - public string? ExResourceUrl { get; set; } = null; - public string? LuaUrl { get; set; } = null; - public string? IfixUrl { get; set; } = null; - } - - public class MuipServerConfig - { - public string AdminKey { get; set; } = "None"; + return (UseSSL ? "https" : "http") + "://" + PublicAddress + ":" + PublicPort; } } + +public class KeyStoreConfig +{ + public string KeyStorePath { get; set; } = "certificate.p12"; + public string KeyStorePassword { get; set; } = "123456"; +} + +public class GameServerConfig +{ + public string PublicAddress { get; set; } = "127.0.0.1"; + public uint PublicPort { get; set; } = 23301; + public string GameServerId { get; set; } = "dan_heng"; + public string GameServerName { get; set; } = "DanhengServer"; + public string GameServerDescription { get; set; } = "A re-implementation of StarRail server"; + public int KcpInterval { get; set; } = 40; + + public string GetDisplayAddress() + { + return PublicAddress + ":" + PublicPort; + } +} + +public class PathConfig +{ + public string ResourcePath { get; set; } = "Resources"; + public string ConfigPath { get; set; } = "Config"; + public string DatabasePath { get; set; } = "Config/Database"; + public string LogPath { get; set; } = "Logs"; + public string PluginPath { get; set; } = "Plugins"; + public string PluginConfigPath { get; set; } = "Plugins/Config"; +} + +public class DatabaseConfig +{ + public string DatabaseType { get; set; } = "sqlite"; + public string DatabaseName { get; set; } = "danheng.db"; + public string MySqlHost { get; set; } = "127.0.0.1"; + public int MySqlPort { get; set; } = 3306; + public string MySqlUser { get; set; } = "root"; + public string MySqlPassword { get; set; } = "123456"; + public string MySqlDatabase { get; set; } = "danheng"; +} + +public class ServerOption +{ + public int StartTrailblazerLevel { get; set; } = 1; + public bool AutoUpgradeWorldLevel { get; set; } = true; + public bool EnableMission { get; set; } = true; // experimental + public bool AutoLightSection { get; set; } = true; + public string Language { get; set; } = "EN"; + public List DefaultPermissions { get; set; } = ["*"]; + public ServerAnnounce ServerAnnounce { get; set; } = new(); + public ServerProfile ServerProfile { get; set; } = new(); + public bool AutoCreateUser { get; set; } = true; + public bool SavePersonalDebugFile { get; set; } = false; +} + +public class ServerAnnounce +{ + public bool EnableAnnounce { get; set; } = true; + public string AnnounceContent { get; set; } = "Welcome to danhengserver!"; +} + +public class ServerProfile +{ + public string Name { get; set; } = "Server"; + public int Uid { get; set; } = 80; + public string Signature { get; set; } = "Type /help for a list of commands"; + public int Level { get; set; } = 1; + public int HeadIcon { get; set; } = 200105; + public int ChatBubbleId { get; set; } = 220001; + public int DisplayAvatarId { get; set; } = 1001; + public int DisplayAvatarLevel { get; set; } = 1; +} + +public class DownloadUrlConfig +{ + public string? AssetBundleUrl { get; set; } = null; + public string? ExResourceUrl { get; set; } = null; + public string? LuaUrl { get; set; } = null; + public string? IfixUrl { get; set; } = null; +} + +public class MuipServerConfig +{ + public string AdminKey { get; set; } = "None"; +} \ No newline at end of file diff --git a/Common/Data/Config/AnchorInfo.cs b/Common/Data/Config/AnchorInfo.cs index fe93a268..39b8e835 100644 --- a/Common/Data/Config/AnchorInfo.cs +++ b/Common/Data/Config/AnchorInfo.cs @@ -1,14 +1,5 @@ -using EggLink.DanhengServer.Data.Excel; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using static System.Runtime.InteropServices.JavaScript.JSType; +namespace EggLink.DanhengServer.Data.Config; -namespace EggLink.DanhengServer.Data.Config +public class AnchorInfo : PositionInfo { - public class AnchorInfo : PositionInfo - { - } -} +} \ No newline at end of file diff --git a/Common/Data/Config/DialogueInfo.cs b/Common/Data/Config/DialogueInfo.cs index 57b96c41..59451ca2 100644 --- a/Common/Data/Config/DialogueInfo.cs +++ b/Common/Data/Config/DialogueInfo.cs @@ -1,52 +1,32 @@ -using EggLink.DanhengServer.Util; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Newtonsoft.Json; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class DialogueInfo { - public class DialogueInfo + public List OnInitSequece { get; set; } = []; + public List OnStartSequece { get; set; } = []; + + [JsonIgnore] public List DialogueIds { get; set; } = []; + + public void Loaded() { - public List OnInitSequece { get; set; } = []; - public List OnStartSequece { get; set; } = []; + foreach (var task in OnInitSequece) + foreach (var ta in task.TaskList) + foreach (var option in ta.OptionList) + DialogueIds.Add(option.DialogueEventID); - [JsonIgnore] - public List DialogueIds { get; set; } = []; - - public void Loaded() - { - foreach (var task in OnInitSequece) - { - foreach (var ta in task.TaskList) - { - foreach (var option in ta.OptionList) - { - DialogueIds.Add(option.DialogueEventID); - } - } - } - - foreach (var task in OnStartSequece) - { - foreach (var ta in task.TaskList) - { - foreach (var option in ta.OptionList) - { - DialogueIds.Add(option.DialogueEventID); - } - } - } - } - } - - public class DialogueTaskInfo - { - public List TaskList { get; set; } = []; - public List OptionList { get; set; } = []; - - public int DialogueEventID { get; set; } + foreach (var task in OnStartSequece) + foreach (var ta in task.TaskList) + foreach (var option in ta.OptionList) + DialogueIds.Add(option.DialogueEventID); } } + +public class DialogueTaskInfo +{ + public List TaskList { get; set; } = []; + public List OptionList { get; set; } = []; + + public int DialogueEventID { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Config/FetchAdvPropData.cs b/Common/Data/Config/FetchAdvPropData.cs index 25e23a0f..467e14a0 100644 --- a/Common/Data/Config/FetchAdvPropData.cs +++ b/Common/Data/Config/FetchAdvPropData.cs @@ -1,15 +1,9 @@ using EggLink.DanhengServer.Data.Config.Task; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class FetchAdvPropData { - public class FetchAdvPropData - { - public DynamicFloat GroupID { get; set; } = new(); - public DynamicFloat ID { get; set; } = new(); - } -} + public DynamicFloat GroupID { get; set; } = new(); + public DynamicFloat ID { get; set; } = new(); +} \ No newline at end of file diff --git a/Common/Data/Config/FloorInfo.cs b/Common/Data/Config/FloorInfo.cs index 13c46bc3..a391a1b9 100644 --- a/Common/Data/Config/FloorInfo.cs +++ b/Common/Data/Config/FloorInfo.cs @@ -1,130 +1,112 @@ using EggLink.DanhengServer.Enums.Scene; -using EggLink.DanhengServer.Util; using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class FloorInfo { - public class FloorInfo + [JsonIgnore] public Dictionary CachedTeleports = []; + + [JsonIgnore] public Dictionary Groups = []; + + [JsonIgnore] public bool Loaded; + + [JsonIgnore] public List UnlockedCheckpoints = []; + + public int FloorID { get; set; } + public int StartGroupIndex { get; set; } + public int StartAnchorID { get; set; } + + public List GroupInstanceList { get; set; } = []; + public List SavedValues { get; set; } = []; + public List CustomValues { get; set; } = []; + public List DimensionList { get; set; } = []; + + [JsonIgnore] public int StartGroupID { get; set; } + + public AnchorInfo? GetAnchorInfo(int groupId, int anchorId) { - public int FloorID { get; set; } - public int StartGroupIndex { get; set; } - public int StartAnchorID { get; set; } + Groups.TryGetValue(groupId, out var group); + if (group == null) return null; - public List GroupInstanceList { get; set; } = []; - public List SavedValues { get; set; } = []; - public List CustomValues { get; set; } = []; - public List DimensionList { get; set; } = []; + return group.AnchorList.Find(info => info.ID == anchorId); + } - [JsonIgnore] - public bool Loaded = false; - [JsonIgnore] - public Dictionary Groups = []; + public void OnLoad() + { + if (Loaded) return; - [JsonIgnore] - public Dictionary CachedTeleports = []; - [JsonIgnore] - public List UnlockedCheckpoints = []; + StartGroupID = GroupInstanceList[StartGroupIndex].ID; - [JsonIgnore] - public int StartGroupID { get; set; } + foreach (var dimension in DimensionList) dimension.OnLoad(this); - public AnchorInfo? GetAnchorInfo(int groupId, int anchorId) - { - Groups.TryGetValue(groupId, out GroupInfo? group); - if (group == null) return null; - - return group.AnchorList.Find(info => info.ID == anchorId); - } - - public void OnLoad() - { - if (Loaded) return; - - StartGroupID = GroupInstanceList[StartGroupIndex].ID; - - foreach (var dimension in DimensionList) + // Cache anchors + foreach (var group in Groups.Values) + foreach (var prop in group.PropList) + // Check if prop can be teleported to + if (prop.AnchorID > 0) { - dimension.OnLoad(this); + // Put inside cached teleport list to send to client when they request map info + CachedTeleports.TryAdd(prop.MappingInfoID, prop); + UnlockedCheckpoints.Add(prop); + + // Force prop to be in the unlocked state + prop.State = PropStateEnum.CheckPointEnable; } - - // Cache anchors - foreach (var group in Groups.Values) + else if (!string.IsNullOrEmpty(prop.InitLevelGraph)) { - foreach (var prop in group.PropList) + var json = prop.InitLevelGraph; + + // Hacky way to setup prop triggers + if (json.Contains("Maze_GroupProp_OpenTreasure_WhenMonsterDie")) { - // Check if prop can be teleported to - if (prop.AnchorID > 0) - { - // Put inside cached teleport list to send to client when they request map info - CachedTeleports.TryAdd(prop.MappingInfoID, prop); - UnlockedCheckpoints.Add(prop); - - // Force prop to be in the unlocked state - prop.State = PropStateEnum.CheckPointEnable; - } - else if (!string.IsNullOrEmpty(prop.InitLevelGraph)) - { - string json = prop.InitLevelGraph; - - // Hacky way to setup prop triggers - if (json.Contains("Maze_GroupProp_OpenTreasure_WhenMonsterDie")) - { - //prop.Trigger = new TriggerOpenTreasureWhenMonsterDie(group.Id); - } - else if (json.Contains("Common_Console")) - { - //prop.CommonConsole = true; - } - - // Clear for garbage collection - prop.ValueSource = null; - prop.InitLevelGraph = null; - } + //prop.Trigger = new TriggerOpenTreasureWhenMonsterDie(group.Id); } + else if (json.Contains("Common_Console")) + { + //prop.CommonConsole = true; + } + + // Clear for garbage collection + prop.ValueSource = null; + prop.InitLevelGraph = null; } - Loaded = true; - } - - } - public class FloorGroupInfo - { - public string GroupPath { get; set; } = ""; - public bool IsDelete { get; set; } - public int ID { get; set; } - public string Name { get; set; } = ""; - } - - - public class FloorSavedValueInfo - { - public int ID { get; set; } - public string Name { get; set; } = string.Empty; - public int DefaultValue { get; set; } - } - - public class FloorCustomValueInfo - { - public int ID { get; set; } - public string Name { get; set; } = string.Empty; - public string DefaultValue { get; set; } = string.Empty; - } - - public class FloorDimensionInfo - { - public int ID { get; set; } - public List GroupIndexList { get; set; } = []; - - [JsonIgnore] - public List GroupIDList { get; set; } = []; - - public void OnLoad(FloorInfo floor) - { - foreach (var index in GroupIndexList) - { - GroupIDList.Add(floor.GroupInstanceList[index].ID); - } - } + Loaded = true; } } + +public class FloorGroupInfo +{ + public string GroupPath { get; set; } = ""; + public bool IsDelete { get; set; } + public int ID { get; set; } + public string Name { get; set; } = ""; +} + +public class FloorSavedValueInfo +{ + public int ID { get; set; } + public string Name { get; set; } = string.Empty; + public int DefaultValue { get; set; } +} + +public class FloorCustomValueInfo +{ + public int ID { get; set; } + public string Name { get; set; } = string.Empty; + public string DefaultValue { get; set; } = string.Empty; +} + +public class FloorDimensionInfo +{ + public int ID { get; set; } + public List GroupIndexList { get; set; } = []; + + [JsonIgnore] public List GroupIDList { get; set; } = []; + + public void OnLoad(FloorInfo floor) + { + foreach (var index in GroupIndexList) GroupIDList.Add(floor.GroupInstanceList[index].ID); + } +} \ No newline at end of file diff --git a/Common/Data/Config/GroupInfo.cs b/Common/Data/Config/GroupInfo.cs index 12a63d3f..82921824 100644 --- a/Common/Data/Config/GroupInfo.cs +++ b/Common/Data/Config/GroupInfo.cs @@ -4,121 +4,121 @@ using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Util; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using static System.Formats.Asn1.AsnWriter; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class GroupInfo { - public class GroupInfo + public int Id; + + [JsonConverter(typeof(StringEnumConverter))] + public GroupLoadSideEnum LoadSide { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public GroupCategoryEnum Category { get; set; } + + public string LevelGraph { get; set; } = ""; + public bool LoadOnInitial { get; set; } + public string GroupName { get; set; } = ""; + public LoadCondition LoadCondition { get; set; } = new(); + public LoadCondition UnloadCondition { get; set; } = new(); + public LoadCondition ForceUnloadCondition { get; set; } = new(); + + [JsonConverter(typeof(StringEnumConverter))] + public SaveTypeEnum SaveType { get; set; } = SaveTypeEnum.Save; + + public int OwnerMainMissionID { get; set; } + public List AnchorList { get; set; } = []; + public List MonsterList { get; set; } = []; + public List PropList { get; set; } = []; + public List NPCList { get; set; } = []; + + [JsonIgnore] public LevelGraphConfigInfo? LevelGraphConfig { get; set; } + + [JsonIgnore] public Dictionary> PropTriggerCustomString { get; set; } = []; + + public void Load() { - public int Id; - [JsonConverter(typeof(StringEnumConverter))] - public GroupLoadSideEnum LoadSide { get; set; } - [JsonConverter(typeof(StringEnumConverter))] - public GroupCategoryEnum Category { get; set; } - public string LevelGraph { get; set; } = ""; - public bool LoadOnInitial { get; set; } - public string GroupName { get; set; } = ""; - public LoadCondition LoadCondition { get; set; } = new(); - public LoadCondition UnloadCondition { get; set; } = new(); - public LoadCondition ForceUnloadCondition { get; set; } = new(); - [JsonConverter(typeof(StringEnumConverter))] - public SaveTypeEnum SaveType { get; set; } = SaveTypeEnum.Save; - public int OwnerMainMissionID { get; set; } - public List AnchorList { get; set; } = []; - public List MonsterList { get; set; } = []; - public List PropList { get; set; } = []; - public List NPCList { get; set; } = []; - - [JsonIgnore] - public LevelGraphConfigInfo? LevelGraphConfig { get; set; } - - [JsonIgnore] - public Dictionary> PropTriggerCustomString { get; set; } = []; - - public void Load() - { - foreach (var prop in PropList) - { - prop.Load(this); - } - } + foreach (var prop in PropList) prop.Load(this); } +} - public class LoadCondition +public class LoadCondition +{ + public List Conditions { get; set; } = []; + + [JsonConverter(typeof(StringEnumConverter))] + public OperationEnum Operation { get; set; } = OperationEnum.And; + + public bool IsTrue(MissionData mission, bool defaultResult = true) { - public List Conditions { get; set; } = []; - - [JsonConverter(typeof(StringEnumConverter))] - public OperationEnum Operation { get; set; } = OperationEnum.And; - - public bool IsTrue(MissionData mission, bool defaultResult = true) - { - if (Conditions.Count == 0) + if (Conditions.Count == 0) return defaultResult; + var canLoad = Operation == OperationEnum.And; + // check load condition + foreach (var condition in Conditions) + if (condition.Type == ConditionTypeEnum.MainMission) { - return defaultResult; - } - bool canLoad = Operation == OperationEnum.And; - // check load condition - foreach (var condition in Conditions) - { - if (condition.Type == ConditionTypeEnum.MainMission) + var info = mission.GetMainMissionStatus(condition.ID); + if (!ConfigManager.Config.ServerOption.EnableMission) info = MissionPhaseEnum.Finish; + + condition.Phase = condition.Phase == MissionPhaseEnum.Cancel + ? MissionPhaseEnum.Finish + : condition.Phase; + + if (info != condition.Phase) { - var info = mission.GetMainMissionStatus(condition.ID); - if (!ConfigManager.Config.ServerOption.EnableMission) info = MissionPhaseEnum.Finish; - - condition.Phase = condition.Phase == MissionPhaseEnum.Cancel ? MissionPhaseEnum.Finish : condition.Phase; - - if (info != condition.Phase) + if (Operation == OperationEnum.And) { - if (Operation == OperationEnum.And) - { - canLoad = false; - break; - } - } - else - { - if (Operation == OperationEnum.Or) - { - canLoad = true; - break; - } + canLoad = false; + break; } } else { - // sub mission - var status = mission.GetSubMissionStatus(condition.ID); - if (!ConfigManager.Config.ServerOption.EnableMission) status = MissionPhaseEnum.Finish; - condition.Phase = condition.Phase == MissionPhaseEnum.Cancel ? MissionPhaseEnum.Finish : condition.Phase; - if (status != condition.Phase) + if (Operation == OperationEnum.Or) { - if (Operation == OperationEnum.And) - { - canLoad = false; - break; - } - } - else - { - if (Operation == OperationEnum.Or) - { - canLoad = true; - break; - } + canLoad = true; + break; + } + } + } + else + { + // sub mission + var status = mission.GetSubMissionStatus(condition.ID); + if (!ConfigManager.Config.ServerOption.EnableMission) status = MissionPhaseEnum.Finish; + condition.Phase = condition.Phase == MissionPhaseEnum.Cancel + ? MissionPhaseEnum.Finish + : condition.Phase; + if (status != condition.Phase) + { + if (Operation == OperationEnum.And) + { + canLoad = false; + break; + } + } + else + { + if (Operation == OperationEnum.Or) + { + canLoad = true; + break; } } } - return canLoad; - } - } - public class Condition - { - [JsonConverter(typeof(StringEnumConverter))] - public ConditionTypeEnum Type { get; set; } = ConditionTypeEnum.MainMission; - public int ID { get; set; } - [JsonConverter(typeof(StringEnumConverter))] - public MissionPhaseEnum Phase { get; set; } = MissionPhaseEnum.Accept; + return canLoad; } } + +public class Condition +{ + [JsonConverter(typeof(StringEnumConverter))] + public ConditionTypeEnum Type { get; set; } = ConditionTypeEnum.MainMission; + + public int ID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public MissionPhaseEnum Phase { get; set; } = MissionPhaseEnum.Accept; +} \ No newline at end of file diff --git a/Common/Data/Config/LevelGraphConfigInfo.cs b/Common/Data/Config/LevelGraphConfigInfo.cs index 5ddefdc2..b888c56c 100644 --- a/Common/Data/Config/LevelGraphConfigInfo.cs +++ b/Common/Data/Config/LevelGraphConfigInfo.cs @@ -1,29 +1,21 @@ using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class LevelGraphConfigInfo { - public class LevelGraphConfigInfo - { - public List OnInitSequece { get; set; } = []; - public List OnStartSequece { get; set; } = []; + public List OnInitSequece { get; set; } = []; + public List OnStartSequece { get; set; } = []; - public static LevelGraphConfigInfo LoadFromJsonObject(JObject obj) - { - LevelGraphConfigInfo info = new(); - if (obj.ContainsKey(nameof(OnInitSequece))) - { - info.OnInitSequece = obj[nameof(OnInitSequece)]?.Select(x => LevelInitSequeceConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; - } - if (obj.ContainsKey(nameof(OnStartSequece))) - { - info.OnStartSequece = obj[nameof(OnStartSequece)]?.Select(x => LevelStartSequeceConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; - } - return info; - } + public static LevelGraphConfigInfo LoadFromJsonObject(JObject obj) + { + LevelGraphConfigInfo info = new(); + if (obj.ContainsKey(nameof(OnInitSequece))) + info.OnInitSequece = obj[nameof(OnInitSequece)] + ?.Select(x => LevelInitSequeceConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; + if (obj.ContainsKey(nameof(OnStartSequece))) + info.OnStartSequece = obj[nameof(OnStartSequece)] + ?.Select(x => LevelStartSequeceConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; + return info; } -} +} \ No newline at end of file diff --git a/Common/Data/Config/LevelInitSequeceConfigInfo.cs b/Common/Data/Config/LevelInitSequeceConfigInfo.cs index 79bf1db7..7d099d30 100644 --- a/Common/Data/Config/LevelInitSequeceConfigInfo.cs +++ b/Common/Data/Config/LevelInitSequeceConfigInfo.cs @@ -1,25 +1,18 @@ using EggLink.DanhengServer.Data.Config.Task; using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class LevelInitSequeceConfigInfo { - public class LevelInitSequeceConfigInfo - { - public List TaskList { get; set; } = []; + public List TaskList { get; set; } = []; - public static LevelInitSequeceConfigInfo LoadFromJsonObject(JObject obj) - { - LevelInitSequeceConfigInfo info = new(); - if (obj.ContainsKey(nameof(TaskList))) - { - info.TaskList = obj[nameof(TaskList)]?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; - } - return info; - } + public static LevelInitSequeceConfigInfo LoadFromJsonObject(JObject obj) + { + LevelInitSequeceConfigInfo info = new(); + if (obj.ContainsKey(nameof(TaskList))) + info.TaskList = obj[nameof(TaskList)]?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)) + .ToList() ?? []; + return info; } -} +} \ No newline at end of file diff --git a/Common/Data/Config/LevelStartSequeceConfigInfo.cs b/Common/Data/Config/LevelStartSequeceConfigInfo.cs index 5725d4d5..70c6067b 100644 --- a/Common/Data/Config/LevelStartSequeceConfigInfo.cs +++ b/Common/Data/Config/LevelStartSequeceConfigInfo.cs @@ -1,37 +1,24 @@ using EggLink.DanhengServer.Data.Config.Task; using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class LevelStartSequeceConfigInfo { - public class LevelStartSequeceConfigInfo + public List TaskList { get; set; } = []; + public bool IsLoop { get; set; } + public int Order { get; set; } + + public static LevelStartSequeceConfigInfo LoadFromJsonObject(JObject obj) { - public List TaskList { get; set; } = []; - public bool IsLoop { get; set; } = false; - public int Order { get; set; } + LevelStartSequeceConfigInfo info = new(); + if (obj.ContainsKey(nameof(TaskList))) + info.TaskList = obj[nameof(TaskList)]?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)) + .ToList() ?? []; - public static LevelStartSequeceConfigInfo LoadFromJsonObject(JObject obj) - { - LevelStartSequeceConfigInfo info = new(); - if (obj.ContainsKey(nameof(TaskList))) - { - info.TaskList = obj[nameof(TaskList)]?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; - } + if (obj.ContainsKey(nameof(IsLoop))) info.IsLoop = obj[nameof(IsLoop)]?.Value() ?? false; - if (obj.ContainsKey(nameof(IsLoop))) - { - info.IsLoop = obj[nameof(IsLoop)]?.Value() ?? false; - } - - if (obj.ContainsKey(nameof(Order))) - { - info.Order = obj[nameof(Order)]?.Value() ?? 0; - } - return info; - } + if (obj.ContainsKey(nameof(Order))) info.Order = obj[nameof(Order)]?.Value() ?? 0; + return info; } -} +} \ No newline at end of file diff --git a/Common/Data/Config/MissionInfo.cs b/Common/Data/Config/MissionInfo.cs index d58278f7..84e99940 100644 --- a/Common/Data/Config/MissionInfo.cs +++ b/Common/Data/Config/MissionInfo.cs @@ -1,58 +1,58 @@ -using EggLink.DanhengServer.Data.Config.Task; -using EggLink.DanhengServer.Data.Excel; +using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Enums; -using EggLink.DanhengServer.Enums.Scene; -using EggLink.DanhengServer.Util; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class MissionInfo { - public class MissionInfo - { - public int MainMissionID { get; set; } - public List StartSubMissionList { get; set; } = []; - public List FinishSubMissionList { get; set; } = []; - public List SubMissionList { get; set; } = []; - public List MissionCustomValueList { get; set; } = []; - } - - public class SubMissionInfo - { - public int ID { get; set; } - public int LevelPlaneID { get; set; } - public int LevelFloorID { get; set; } - public int MainMissionID { get; set; } - public string MissionJsonPath { get; set; } = ""; - - [JsonConverter(typeof(StringEnumConverter))] - public SubMissionTakeTypeEnum TakeType { get; set; } - public List? TakeParamIntList { get; set; } = []; // the mission's prerequisites - [JsonConverter(typeof(StringEnumConverter))] - public MissionFinishTypeEnum FinishType { get; set; } - public int ParamInt1 { get; set; } - public int ParamInt2 { get; set; } - public int ParamInt3 { get; set; } - public string ParamStr1 { get; set; } = ""; - public List? ParamIntList { get; set; } = []; - public List? ParamItemList { get; set; } = []; - public List? FinishActionList { get; set; } = []; - public int Progress { get; set; } - public List? GroupIDList { get; set; } = []; - public int SubRewardID { get; set; } - } - - public class CustomValueInfo - { - public int Index { get; set; } - public List ValidValueParamList { get; set; } = []; - } - - public class FinishActionInfo - { - [JsonConverter(typeof(StringEnumConverter))] - public FinishActionTypeEnum FinishActionType { get; set; } - public List FinishActionPara { get; set; } = []; - public List FinishActionParaString { get; set; } = []; - } + public int MainMissionID { get; set; } + public List StartSubMissionList { get; set; } = []; + public List FinishSubMissionList { get; set; } = []; + public List SubMissionList { get; set; } = []; + public List MissionCustomValueList { get; set; } = []; } + +public class SubMissionInfo +{ + public int ID { get; set; } + public int LevelPlaneID { get; set; } + public int LevelFloorID { get; set; } + public int MainMissionID { get; set; } + public string MissionJsonPath { get; set; } = ""; + + [JsonConverter(typeof(StringEnumConverter))] + public SubMissionTakeTypeEnum TakeType { get; set; } + + public List? TakeParamIntList { get; set; } = []; // the mission's prerequisites + + [JsonConverter(typeof(StringEnumConverter))] + public MissionFinishTypeEnum FinishType { get; set; } + + public int ParamInt1 { get; set; } + public int ParamInt2 { get; set; } + public int ParamInt3 { get; set; } + public string ParamStr1 { get; set; } = ""; + public List? ParamIntList { get; set; } = []; + public List? ParamItemList { get; set; } = []; + public List? FinishActionList { get; set; } = []; + public int Progress { get; set; } + public List? GroupIDList { get; set; } = []; + public int SubRewardID { get; set; } +} + +public class CustomValueInfo +{ + public int Index { get; set; } + public List ValidValueParamList { get; set; } = []; +} + +public class FinishActionInfo +{ + [JsonConverter(typeof(StringEnumConverter))] + public FinishActionTypeEnum FinishActionType { get; set; } + + public List FinishActionPara { get; set; } = []; + public List FinishActionParaString { get; set; } = []; +} \ No newline at end of file diff --git a/Common/Data/Config/MonsterInfo.cs b/Common/Data/Config/MonsterInfo.cs index dfd24ed8..fb90903f 100644 --- a/Common/Data/Config/MonsterInfo.cs +++ b/Common/Data/Config/MonsterInfo.cs @@ -1,17 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using static System.Runtime.InteropServices.JavaScript.JSType; +namespace EggLink.DanhengServer.Data.Config; -namespace EggLink.DanhengServer.Data.Config +public class MonsterInfo : PositionInfo { - public class MonsterInfo : PositionInfo - { - public int NPCMonsterID { get; set; } - public int EventID { get; set; } - public int FarmElementID { get; set; } - public bool IsClientOnly { get; set; } - } -} + public int NPCMonsterID { get; set; } + public int EventID { get; set; } + public int FarmElementID { get; set; } + public bool IsClientOnly { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Config/NpcInfo.cs b/Common/Data/Config/NpcInfo.cs index 23fa4e04..8f6e02eb 100644 --- a/Common/Data/Config/NpcInfo.cs +++ b/Common/Data/Config/NpcInfo.cs @@ -1,15 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using static System.Runtime.InteropServices.JavaScript.JSType; +namespace EggLink.DanhengServer.Data.Config; -namespace EggLink.DanhengServer.Data.Config +public class NpcInfo : PositionInfo { - public class NpcInfo : PositionInfo - { - public int NPCID { get; set; } - public bool IsClientOnly { get; set; } - } -} + public int NPCID { get; set; } + public bool IsClientOnly { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Config/PositionInfo.cs b/Common/Data/Config/PositionInfo.cs index 35b40a21..a0eae5a3 100644 --- a/Common/Data/Config/PositionInfo.cs +++ b/Common/Data/Config/PositionInfo.cs @@ -1,43 +1,36 @@ -using EggLink.DanhengServer.Data.Excel; -using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class PositionInfo { - public class PositionInfo + public int ID { get; set; } + public float PosX { get; set; } + public float PosY { get; set; } + public float PosZ { get; set; } + public bool IsDelete { get; set; } + public string Name { get; set; } = ""; + public float RotX { get; set; } + public float RotY { get; set; } + public float RotZ { get; set; } + + public Position ToPositionProto() { - public int ID { get; set; } - public float PosX { get; set; } - public float PosY { get; set; } - public float PosZ { get; set; } - public bool IsDelete { get; set; } - public string Name { get; set; } = ""; - public float RotX { get; set; } - public float RotY { get; set; } - public float RotZ { get; set; } - - public Position ToPositionProto() + return new Position { - return new() - { - X = (int)(PosX * 1000f), - Y = (int)(PosY * 1000f), - Z = (int)(PosZ * 1000f), - }; - } - - public Position ToRotationProto() - { - return new() - { - Y = (int)(RotY * 1000f), - X = (int)(RotX * 1000f), - Z = (int)(RotZ * 1000f), - }; - } + X = (int)(PosX * 1000f), + Y = (int)(PosY * 1000f), + Z = (int)(PosZ * 1000f) + }; } -} + + public Position ToRotationProto() + { + return new Position + { + Y = (int)(RotY * 1000f), + X = (int)(RotX * 1000f), + Z = (int)(RotZ * 1000f) + }; + } +} \ No newline at end of file diff --git a/Common/Data/Config/PropInfo.cs b/Common/Data/Config/PropInfo.cs index 05d4c53b..3e6a9aec 100644 --- a/Common/Data/Config/PropInfo.cs +++ b/Common/Data/Config/PropInfo.cs @@ -1,101 +1,93 @@ using EggLink.DanhengServer.Enums.Scene; -using EggLink.DanhengServer.Util; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class PropInfo : PositionInfo { - public class PropInfo : PositionInfo + public int MappingInfoID { get; set; } + public int AnchorGroupID { get; set; } + public int AnchorID { get; set; } + public int PropID { get; set; } + public int EventID { get; set; } + public int CocoonID { get; set; } + public int FarmElementID { get; set; } + public bool IsClientOnly { get; set; } + + public PropValueSource? ValueSource { get; set; } + public string? InitLevelGraph { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public PropStateEnum State { get; set; } = PropStateEnum.Closed; + + [JsonIgnore] public Dictionary> UnlockDoorID { get; set; } = []; + + [JsonIgnore] public Dictionary> UnlockControllerID { get; set; } = []; + + [JsonIgnore] public int MazePieceCount { get; set; } + + public void Load(GroupInfo info) { - public int MappingInfoID { get; set; } - public int AnchorGroupID { get; set; } - public int AnchorID { get; set; } - public int PropID { get; set; } - public int EventID { get; set; } - public int CocoonID { get; set; } - public int FarmElementID { get; set; } - public bool IsClientOnly { get; set; } - - public PropValueSource? ValueSource { get; set; } - public string? InitLevelGraph { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public PropStateEnum State { get; set; } = PropStateEnum.Closed; - - [JsonIgnore()] - public Dictionary> UnlockDoorID { get; set; } = []; - - [JsonIgnore()] - public Dictionary> UnlockControllerID { get; set; } = []; - - [JsonIgnore()] - public int MazePieceCount { get; set; } - - public void Load(GroupInfo info) - { - if (ValueSource != null) - { - foreach (var v in ValueSource.Values) + if (ValueSource != null) + foreach (var v in ValueSource.Values) + try { - try + var key = v["Key"]; + var value = v["Value"]; + if (value != null && key != null) { - var key = v["Key"]; - var value = v["Value"]; - if (value != null && key != null) + if (key.ToString() == "ListenTriggerCustomString") { - if (key.ToString() == "ListenTriggerCustomString") + info.PropTriggerCustomString.TryGetValue(value.ToString(), out var list); + if (list == null) { - info.PropTriggerCustomString.TryGetValue(value.ToString(), out var list); - if (list == null) - { - list = []; - info.PropTriggerCustomString.Add(value.ToString(), list); - } - list.Add(ID); + list = []; + info.PropTriggerCustomString.Add(value.ToString(), list); } - else if (key.ToString().Contains("Door") || - key.ToString().Contains("Bridge") || - key.ToString().Contains("UnlockTarget") || - key.ToString().Contains("Rootcontamination") || - key.ToString().Contains("Portal")) + + list.Add(ID); + } + else if (key.ToString().Contains("Door") || + key.ToString().Contains("Bridge") || + key.ToString().Contains("UnlockTarget") || + key.ToString().Contains("Rootcontamination") || + key.ToString().Contains("Portal")) + { + try { - try - { - if (UnlockDoorID.ContainsKey(int.Parse(value.ToString().Split(",")[0])) == false) - { - UnlockDoorID.Add(int.Parse(value.ToString().Split(",")[0]), []); - } - UnlockDoorID[int.Parse(value.ToString().Split(",")[0])].Add(int.Parse(value.ToString().Split(",")[1])); - } - catch - { - } - } - else if (key.ToString().Contains("Controller")) + if (UnlockDoorID.ContainsKey(int.Parse(value.ToString().Split(",")[0])) == false) + UnlockDoorID.Add(int.Parse(value.ToString().Split(",")[0]), []); + UnlockDoorID[int.Parse(value.ToString().Split(",")[0])] + .Add(int.Parse(value.ToString().Split(",")[1])); + } + catch + { + } + } + else if (key.ToString().Contains("Controller")) + { + try + { + if (UnlockControllerID.ContainsKey(int.Parse(value.ToString().Split(",")[0])) == false) + UnlockControllerID.Add(int.Parse(value.ToString().Split(",")[0]), []); + UnlockControllerID[int.Parse(value.ToString().Split(",")[0])] + .Add(int.Parse(value.ToString().Split(",")[1])); + } + catch { - try - { - if (UnlockControllerID.ContainsKey(int.Parse(value.ToString().Split(",")[0])) == false) - { - UnlockControllerID.Add(int.Parse(value.ToString().Split(",")[0]), []); - } - UnlockControllerID[int.Parse(value.ToString().Split(",")[0])].Add(int.Parse(value.ToString().Split(",")[1])); - } - catch - { - } } } } - catch { } } - } - } - } - - public class PropValueSource - { - public List Values { get; set; } = []; + catch + { + } } } + +public class PropValueSource +{ + public List Values { get; set; } = []; +} \ No newline at end of file diff --git a/Common/Data/Config/RogueChestMapInfo.cs b/Common/Data/Config/RogueChestMapInfo.cs index 0d93339f..777b498c 100644 --- a/Common/Data/Config/RogueChestMapInfo.cs +++ b/Common/Data/Config/RogueChestMapInfo.cs @@ -1,74 +1,71 @@ using EggLink.DanhengServer.Enums.Rogue; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +/// +/// Orginal Name: RogueChestMapConfig +/// +public class RogueChestMapInfo { - /// - /// Orginal Name: RogueChestMapConfig - /// - public class RogueChestMapInfo - { - public List PreStartRoomIDList { get; set; } = []; - public int Width { get; set; } - public int Height { get; set; } - public int StartGridItemID { get; set; } - public int EndGridItemID { get; set; } - public Dictionary RogueChestGridItemMap { get; set; } = []; - public Dictionary RogueChestEventMap { get; set; } = []; - public List RogueBlockCreateGroupList { get; set; } = []; - } - - public class RogueChestGridItem - { - public int PosX { get; set; } - public int PosY { get; set; } - - [JsonProperty(ItemConverterType = typeof(StringEnumConverter))] - public List BlockTypeList { get; set; } = []; - public bool ExportToJson { get; set; } - } - - public class RogueChestModifierEvent - { - [JsonConverter(typeof(StringEnumConverter))] - public ModifierTriggerTypeEnum TriggerType { get; set; } - public List TriggerParamList { get; set; } = []; - - [JsonConverter(typeof(StringEnumConverter))] - public ModifierEffectTypeEnum EffectType { get; set; } - public List EffectParamList { get; set; } = []; - public List EffectParam2List { get; set; } = []; - public float Weight { get; set; } - } - - public class RogueBlockCreateGroup - { - public int BlockCreateID { get; set; } - public int GroupID { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public RogueDLCBlockTypeEnum BlockType { get; set; } - - public List BlockCreatNumList { get; set; } = []; - - public List MarkCreateRandomList { get; set; } = []; - } - - public class RogueDLCBlockWeight - { - public int CreateNum { get; set; } - public int Weight { get; set; } - } - - public class RogueDLCMarkType - { - public int TypeID { get; set; } - public int Weight { get; set; } - } + public List PreStartRoomIDList { get; set; } = []; + public int Width { get; set; } + public int Height { get; set; } + public int StartGridItemID { get; set; } + public int EndGridItemID { get; set; } + public Dictionary RogueChestGridItemMap { get; set; } = []; + public Dictionary RogueChestEventMap { get; set; } = []; + public List RogueBlockCreateGroupList { get; set; } = []; } + +public class RogueChestGridItem +{ + public int PosX { get; set; } + public int PosY { get; set; } + + [JsonProperty(ItemConverterType = typeof(StringEnumConverter))] + public List BlockTypeList { get; set; } = []; + + public bool ExportToJson { get; set; } +} + +public class RogueChestModifierEvent +{ + [JsonConverter(typeof(StringEnumConverter))] + public ModifierTriggerTypeEnum TriggerType { get; set; } + + public List TriggerParamList { get; set; } = []; + + [JsonConverter(typeof(StringEnumConverter))] + public ModifierEffectTypeEnum EffectType { get; set; } + + public List EffectParamList { get; set; } = []; + public List EffectParam2List { get; set; } = []; + public float Weight { get; set; } +} + +public class RogueBlockCreateGroup +{ + public int BlockCreateID { get; set; } + public int GroupID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public RogueDLCBlockTypeEnum BlockType { get; set; } + + public List BlockCreatNumList { get; set; } = []; + + public List MarkCreateRandomList { get; set; } = []; +} + +public class RogueDLCBlockWeight +{ + public int CreateNum { get; set; } + public int Weight { get; set; } +} + +public class RogueDLCMarkType +{ + public int TypeID { get; set; } + public int Weight { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Config/SkillAbilityInfo.cs b/Common/Data/Config/SkillAbilityInfo.cs index 08191bbd..a0f44e4d 100644 --- a/Common/Data/Config/SkillAbilityInfo.cs +++ b/Common/Data/Config/SkillAbilityInfo.cs @@ -1,45 +1,30 @@ using EggLink.DanhengServer.Data.Excel; -using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class SkillAbilityInfo { - public class SkillAbilityInfo + public List AbilityList { get; set; } = []; + + public void Loaded(AvatarConfigExcel excel) { - public List AbilityList { get; set; } = []; - - public void Loaded(AvatarConfigExcel excel) + foreach (var ability in AbilityList) { - foreach (var ability in AbilityList) - { - ability.Loaded(); - if (ability.Name.EndsWith("MazeSkill")) - { - excel.MazeSkill = ability; - } - else if (ability.Name.Contains("NormalAtk")) - { - excel.MazeAtk = ability; - } - } - } - } - - public class AbilityInfo - { - public string Name { get; set; } = ""; - public List OnStart { get; set; } = []; - - public void Loaded() - { - foreach (var task in OnStart) - { - task.Loaded(); - } + ability.Loaded(); + if (ability.Name.EndsWith("MazeSkill")) + excel.MazeSkill = ability; + else if (ability.Name.Contains("NormalAtk")) excel.MazeAtk = ability; } } } + +public class AbilityInfo +{ + public string Name { get; set; } = ""; + public List OnStart { get; set; } = []; + + public void Loaded() + { + foreach (var task in OnStart) task.Loaded(); + } +} \ No newline at end of file diff --git a/Common/Data/Config/Task/ByCompareFloorSavedValue.cs b/Common/Data/Config/Task/ByCompareFloorSavedValue.cs index 9d4c9c5a..d275112f 100644 --- a/Common/Data/Config/Task/ByCompareFloorSavedValue.cs +++ b/Common/Data/Config/Task/ByCompareFloorSavedValue.cs @@ -1,20 +1,15 @@ using EggLink.DanhengServer.Enums.Task; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config.Task +namespace EggLink.DanhengServer.Data.Config.Task; + +public class ByCompareFloorSavedValue : PredicateConfigInfo { - public class ByCompareFloorSavedValue : PredicateConfigInfo - { - public string Name { get; set; } = ""; + public string Name { get; set; } = ""; - [JsonConverter(typeof(StringEnumConverter))] - public CompareTypeEnum CompareType { get; set; } = CompareTypeEnum.Equal; - public short CompareValue { get; set; } = 0; - } -} + [JsonConverter(typeof(StringEnumConverter))] + public CompareTypeEnum CompareType { get; set; } = CompareTypeEnum.Equal; + + public short CompareValue { get; set; } = 0; +} \ No newline at end of file diff --git a/Common/Data/Config/Task/ByCompareSubMissionState.cs b/Common/Data/Config/Task/ByCompareSubMissionState.cs index 4cd7881f..8bafc8dd 100644 --- a/Common/Data/Config/Task/ByCompareSubMissionState.cs +++ b/Common/Data/Config/Task/ByCompareSubMissionState.cs @@ -1,16 +1,10 @@ using EggLink.DanhengServer.Enums.Task; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config.Task +namespace EggLink.DanhengServer.Data.Config.Task; + +public class ByCompareSubMissionState : PredicateConfigInfo { - public class ByCompareSubMissionState : PredicateConfigInfo - { - public int SubMissionID { get; set; } - public SubMissionStateEnum SubMissionState { get; set; } - public bool AllStoryLine { get; set; } - } -} + public int SubMissionID { get; set; } + public SubMissionStateEnum SubMissionState { get; set; } + public bool AllStoryLine { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Config/Task/CreateProp.cs b/Common/Data/Config/Task/CreateProp.cs index f3b8b9dc..0a38ffdf 100644 --- a/Common/Data/Config/Task/CreateProp.cs +++ b/Common/Data/Config/Task/CreateProp.cs @@ -1,15 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Config.Task; -namespace EggLink.DanhengServer.Data.Config.Task +public class CreateProp : TaskConfigInfo { - public class CreateProp : TaskConfigInfo - { - public DynamicFloat GroupID { get; set; } = new(); - public DynamicFloat GroupPropID { get; set; } = new(); - public List CreateList { get; set; } = []; - } -} + public DynamicFloat GroupID { get; set; } = new(); + public DynamicFloat GroupPropID { get; set; } = new(); + public List CreateList { get; set; } = []; +} \ No newline at end of file diff --git a/Common/Data/Config/Task/DestroyProp.cs b/Common/Data/Config/Task/DestroyProp.cs index cf804c78..7096bca0 100644 --- a/Common/Data/Config/Task/DestroyProp.cs +++ b/Common/Data/Config/Task/DestroyProp.cs @@ -1,32 +1,25 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Config.Task; -namespace EggLink.DanhengServer.Data.Config.Task +public class DestroyProp : TaskConfigInfo { - public class DestroyProp : TaskConfigInfo - { - public DynamicFloat ID { get; set; } = new(); - public DynamicFloat GroupID { get; set; } = new(); - public List DestroyList { get; set; } = []; - } - - public class GroupEntityInfo - { - public DynamicFloat GroupID { get; set; } = new(); - public DynamicFloat GroupInstanceID { get; set; } = new(); - } - - public class DynamicFloat - { - public bool IsDynamic { get; set; } - public FixedValueInfo FixedValue { get; set; } = new(); - - public int GetValue() - { - return IsDynamic ? 0 : FixedValue.Value; - } - } + public DynamicFloat ID { get; set; } = new(); + public DynamicFloat GroupID { get; set; } = new(); + public List DestroyList { get; set; } = []; } + +public class GroupEntityInfo +{ + public DynamicFloat GroupID { get; set; } = new(); + public DynamicFloat GroupInstanceID { get; set; } = new(); +} + +public class DynamicFloat +{ + public bool IsDynamic { get; set; } + public FixedValueInfo FixedValue { get; set; } = new(); + + public int GetValue() + { + return IsDynamic ? 0 : FixedValue.Value; + } +} \ No newline at end of file diff --git a/Common/Data/Config/Task/EnterMap.cs b/Common/Data/Config/Task/EnterMap.cs index 486f8b49..f5d986a1 100644 --- a/Common/Data/Config/Task/EnterMap.cs +++ b/Common/Data/Config/Task/EnterMap.cs @@ -1,15 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Config.Task; -namespace EggLink.DanhengServer.Data.Config.Task +public class EnterMap : TaskConfigInfo { - public class EnterMap : TaskConfigInfo - { - public int EntranceID { get; set; } - public int GroupID { get; set; } - public int AnchorID { get; set; } - } -} + public int EntranceID { get; set; } + public int GroupID { get; set; } + public int AnchorID { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Config/Task/EnterMapByCondition.cs b/Common/Data/Config/Task/EnterMapByCondition.cs index 455f4384..0ba28771 100644 --- a/Common/Data/Config/Task/EnterMapByCondition.cs +++ b/Common/Data/Config/Task/EnterMapByCondition.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Config.Task; -namespace EggLink.DanhengServer.Data.Config.Task +public class EnterMapByCondition : TaskConfigInfo { - public class EnterMapByCondition : TaskConfigInfo - { - public DynamicFloat EntranceID { get; set; } = new(); - } -} + public DynamicFloat EntranceID { get; set; } = new(); +} \ No newline at end of file diff --git a/Common/Data/Config/Task/PlayMessage.cs b/Common/Data/Config/Task/PlayMessage.cs index 3bedbdb7..0cc92312 100644 --- a/Common/Data/Config/Task/PlayMessage.cs +++ b/Common/Data/Config/Task/PlayMessage.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Config.Task; -namespace EggLink.DanhengServer.Data.Config.Task +public class PlayMessage : TaskConfigInfo { - public class PlayMessage : TaskConfigInfo - { - public int MessageSectionID { get; set; } - } -} + public int MessageSectionID { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Config/Task/PredicateConfigInfo.cs b/Common/Data/Config/Task/PredicateConfigInfo.cs index 1863196c..15f79117 100644 --- a/Common/Data/Config/Task/PredicateConfigInfo.cs +++ b/Common/Data/Config/Task/PredicateConfigInfo.cs @@ -1,33 +1,24 @@ -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; -namespace EggLink.DanhengServer.Data.Config.Task +namespace EggLink.DanhengServer.Data.Config.Task; + +public class PredicateConfigInfo : TaskConfigInfo { - public class PredicateConfigInfo : TaskConfigInfo + public bool Inverse { get; set; } = false; + + public new static PredicateConfigInfo LoadFromJsonObject(JObject obj) { - public bool Inverse { get; set; } = false; + PredicateConfigInfo info = new(); + info.Type = obj[nameof(Type)]!.ToObject()!; - public static new PredicateConfigInfo LoadFromJsonObject(JObject obj) - { - PredicateConfigInfo info = new(); - info.Type = obj[nameof(Type)]!.ToObject()!; - - var typeStr = info.Type.Replace("RPG.GameCore.", ""); - var className = "EggLink.DanhengServer.Data.Config.Task." + typeStr; - var typeClass = System.Type.GetType(className); - if (typeClass != null) - { - info = (PredicateConfigInfo)obj.ToObject(typeClass)!; - } - else - { - info = Newtonsoft.Json.JsonConvert.DeserializeObject(obj.ToString())!; - } - return info; - } + var typeStr = info.Type.Replace("RPG.GameCore.", ""); + var className = "EggLink.DanhengServer.Data.Config.Task." + typeStr; + var typeClass = System.Type.GetType(className); + if (typeClass != null) + info = (PredicateConfigInfo)obj.ToObject(typeClass)!; + else + info = JsonConvert.DeserializeObject(obj.ToString())!; + return info; } -} +} \ No newline at end of file diff --git a/Common/Data/Config/Task/PredicateTaskList.cs b/Common/Data/Config/Task/PredicateTaskList.cs index ac74e572..d37c3fd7 100644 --- a/Common/Data/Config/Task/PredicateTaskList.cs +++ b/Common/Data/Config/Task/PredicateTaskList.cs @@ -1,37 +1,27 @@ using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config.Task +namespace EggLink.DanhengServer.Data.Config.Task; + +public class PredicateTaskList : TaskConfigInfo { - public class PredicateTaskList : TaskConfigInfo + public PredicateConfigInfo Predicate { get; set; } = new(); + public List SuccessTaskList { get; set; } = []; + public List FailedTaskList { get; set; } = []; + + public new static TaskConfigInfo LoadFromJsonObject(JObject obj) { - public PredicateConfigInfo Predicate { get; set; } = new(); - public List SuccessTaskList { get; set; } = []; - public List FailedTaskList { get; set; } = []; + PredicateTaskList info = new(); + info.Type = obj[nameof(Type)]!.ToObject()!; + if (obj.ContainsKey(nameof(Predicate))) + info.Predicate = PredicateConfigInfo.LoadFromJsonObject((obj[nameof(Predicate)] as JObject)!)!; - public static new TaskConfigInfo LoadFromJsonObject(JObject obj) - { - PredicateTaskList info = new(); - info.Type = obj[nameof(Type)]!.ToObject()!; - if (obj.ContainsKey(nameof(Predicate))) - { - info.Predicate = (PredicateConfigInfo.LoadFromJsonObject((obj[nameof(Predicate)] as JObject)!)!); - } + if (obj.ContainsKey(nameof(SuccessTaskList))) + info.SuccessTaskList = obj[nameof(SuccessTaskList)] + ?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; - if (obj.ContainsKey(nameof(SuccessTaskList))) - { - info.SuccessTaskList = obj[nameof(SuccessTaskList)]?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; - } - - if (obj.ContainsKey(nameof(FailedTaskList))) - { - info.FailedTaskList = obj[nameof(FailedTaskList)]?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; - } - return info; - } + if (obj.ContainsKey(nameof(FailedTaskList))) + info.FailedTaskList = obj[nameof(FailedTaskList)] + ?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; + return info; } -} +} \ No newline at end of file diff --git a/Common/Data/Config/Task/PropSetupUITrigger.cs b/Common/Data/Config/Task/PropSetupUITrigger.cs index 9dca009f..091841cb 100644 --- a/Common/Data/Config/Task/PropSetupUITrigger.cs +++ b/Common/Data/Config/Task/PropSetupUITrigger.cs @@ -1,68 +1,67 @@ using Newtonsoft.Json.Linq; -using System; -namespace EggLink.DanhengServer.Data.Config.Task +namespace EggLink.DanhengServer.Data.Config.Task; + +public class PropSetupUITrigger : TaskConfigInfo { - public class PropSetupUITrigger : TaskConfigInfo - { - public string ColliderRelativePath { get; set; } = string.Empty; - public bool DestroyAfterTriggered { get; set; } - public bool DisableAfterTriggered { get; set; } - public bool DisableWhenTriggered { get; set; } - public string ButtonIcon { get; set; } = string.Empty; - //DialogueIconType IconType; - //TextID ButtonText; - //DynamicString ButtonTextCustom; - public List ButtonCallback { get; set; } = []; - public bool ForceInteractInDanger { get; set; } - public bool ConsiderAngleLimit { get; set; } - public float InteractAngleRange { get; set; } - //EntityType[] OverrideTargetTypes; - public bool TriggerByFakeAvatar { get; set; } - public bool SkipFakeAvatar { get; set; } - public PredicateConfigInfo OnEnterFilter { get; set; } = new(); - public TargetEvaluator TargetType { get; set; } = new(); + public string ColliderRelativePath { get; set; } = string.Empty; + public bool DestroyAfterTriggered { get; set; } + public bool DisableAfterTriggered { get; set; } + public bool DisableWhenTriggered { get; set; } - public static new TaskConfigInfo LoadFromJsonObject(JObject obj) + public string ButtonIcon { get; set; } = string.Empty; + + //DialogueIconType IconType; + //TextID ButtonText; + //DynamicString ButtonTextCustom; + public List ButtonCallback { get; set; } = []; + public bool ForceInteractInDanger { get; set; } + public bool ConsiderAngleLimit { get; set; } + + public float InteractAngleRange { get; set; } + + //EntityType[] OverrideTargetTypes; + public bool TriggerByFakeAvatar { get; set; } + public bool SkipFakeAvatar { get; set; } + public PredicateConfigInfo OnEnterFilter { get; set; } = new(); + public TargetEvaluator TargetType { get; set; } = new(); + + public new static TaskConfigInfo LoadFromJsonObject(JObject obj) + { + PropSetupUITrigger info = new(); + info.Type = obj[nameof(Type)]!.ToObject()!; + + if (obj.ContainsKey(nameof(OnEnterFilter))) + info.OnEnterFilter = PredicateConfigInfo.LoadFromJsonObject((obj[nameof(OnEnterFilter)] as JObject)!)!; + + if (obj.ContainsKey(nameof(ButtonCallback))) + info.ButtonCallback = obj[nameof(ButtonCallback)] + ?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; + + if (obj.ContainsKey(nameof(TargetType))) { - PropSetupUITrigger info = new(); + var targetType = obj[nameof(TargetType)] as JObject; + var classType = + System.Type.GetType( + $"EggLink.DanhengServer.Data.Config.Task.{targetType?["Type"]?.ToString().Replace("RPG.GameCore.", "")}"); + classType ??= System.Type.GetType("EggLink.DanhengServer.Data.Config.Task.TargetEvaluator"); + info.TargetType = (targetType!.ToObject(classType!) as TargetEvaluator)!; + } + + if (info.ButtonCallback.Count > 0 && info.ButtonCallback[0].Type == "RPG.GameCore.PropStateExecute") info.Type = obj[nameof(Type)]!.ToObject()!; - if (obj.ContainsKey(nameof(OnEnterFilter))) - { - info.OnEnterFilter = (PredicateConfigInfo.LoadFromJsonObject((obj[nameof(OnEnterFilter)] as JObject)!) as PredicateConfigInfo)!; - } + info.ColliderRelativePath = obj[nameof(ColliderRelativePath)]?.ToString() ?? string.Empty; + info.DestroyAfterTriggered = obj[nameof(DestroyAfterTriggered)]?.ToObject() ?? false; + info.DisableAfterTriggered = obj[nameof(DisableAfterTriggered)]?.ToObject() ?? false; + info.DisableWhenTriggered = obj[nameof(DisableWhenTriggered)]?.ToObject() ?? false; + info.ButtonIcon = obj[nameof(ButtonIcon)]?.ToString() ?? string.Empty; + info.ForceInteractInDanger = obj[nameof(ForceInteractInDanger)]?.ToObject() ?? false; + info.ConsiderAngleLimit = obj[nameof(ConsiderAngleLimit)]?.ToObject() ?? false; + info.InteractAngleRange = obj[nameof(InteractAngleRange)]?.ToObject() ?? 0; + info.TriggerByFakeAvatar = obj[nameof(TriggerByFakeAvatar)]?.ToObject() ?? false; + info.SkipFakeAvatar = obj[nameof(SkipFakeAvatar)]?.ToObject() ?? false; - if (obj.ContainsKey(nameof(ButtonCallback))) - { - info.ButtonCallback = obj[nameof(ButtonCallback)]?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)).ToList() ?? []; - } - - if (obj.ContainsKey(nameof(TargetType))) - { - var targetType = obj[nameof(TargetType)] as JObject; - var classType = System.Type.GetType($"EggLink.DanhengServer.Data.Config.Task.{targetType?["Type"]?.ToString().Replace("RPG.GameCore.","")}"); - classType ??= System.Type.GetType($"EggLink.DanhengServer.Data.Config.Task.TargetEvaluator"); - info.TargetType = (targetType!.ToObject(classType!) as TargetEvaluator)!; - } - - if (info.ButtonCallback.Count > 0 && info.ButtonCallback[0].Type == "RPG.GameCore.PropStateExecute") - { - info.Type = obj[nameof(Type)]!.ToObject()!; - } - - info.ColliderRelativePath = obj[nameof(ColliderRelativePath)]?.ToString() ?? string.Empty; - info.DestroyAfterTriggered = obj[nameof(DestroyAfterTriggered)]?.ToObject() ?? false; - info.DisableAfterTriggered = obj[nameof(DisableAfterTriggered)]?.ToObject() ?? false; - info.DisableWhenTriggered = obj[nameof(DisableWhenTriggered)]?.ToObject() ?? false; - info.ButtonIcon = obj[nameof(ButtonIcon)]?.ToString() ?? string.Empty; - info.ForceInteractInDanger = obj[nameof(ForceInteractInDanger)]?.ToObject() ?? false; - info.ConsiderAngleLimit = obj[nameof(ConsiderAngleLimit)]?.ToObject() ?? false; - info.InteractAngleRange = obj[nameof(InteractAngleRange)]?.ToObject() ?? 0; - info.TriggerByFakeAvatar = obj[nameof(TriggerByFakeAvatar)]?.ToObject() ?? false; - info.SkipFakeAvatar = obj[nameof(SkipFakeAvatar)]?.ToObject() ?? false; - - return info; - } + return info; } -} +} \ No newline at end of file diff --git a/Common/Data/Config/Task/PropStateExecute.cs b/Common/Data/Config/Task/PropStateExecute.cs index 5d3ea896..bf7ad163 100644 --- a/Common/Data/Config/Task/PropStateExecute.cs +++ b/Common/Data/Config/Task/PropStateExecute.cs @@ -2,45 +2,40 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config.Task +namespace EggLink.DanhengServer.Data.Config.Task; + +public class PropStateExecute : TaskConfigInfo { - public class PropStateExecute : TaskConfigInfo + public TargetEvaluator TargetType { get; set; } = new(); + + [JsonConverter(typeof(StringEnumConverter))] + public PropStateEnum State { get; set; } = PropStateEnum.Closed; + + public List Execute { get; set; } = []; + + public new static TaskConfigInfo LoadFromJsonObject(JObject obj) { - public TargetEvaluator TargetType { get; set; } = new(); - [JsonConverter(typeof(StringEnumConverter))] - public PropStateEnum State { get; set; } = PropStateEnum.Closed; - public List Execute { get; set; } = []; + var info = new PropStateExecute(); - public static new TaskConfigInfo LoadFromJsonObject(JObject obj) + info.Type = obj[nameof(Type)]!.ToObject()!; + if (obj.ContainsKey(nameof(TargetType))) { - var info = new PropStateExecute(); - - info.Type = obj[nameof(Type)]!.ToObject()!; - if (obj.ContainsKey(nameof(TargetType))) - { - var targetType = obj[nameof(TargetType)] as JObject; - var classType = System.Type.GetType($"EggLink.DanhengServer.Data.Config.Task.{targetType?["Type"]?.ToString().Replace("RPG.GameCore.", "")}"); - classType ??= System.Type.GetType($"EggLink.DanhengServer.Data.Config.Task.TargetEvaluator"); - info.TargetType = (targetType!.ToObject(classType!) as TargetEvaluator)!; - } - - if (obj.ContainsKey(nameof(State))) - { - info.State = obj[nameof(State)]?.ToObject() ?? PropStateEnum.Closed; - } - - foreach (var item in obj[nameof(Execute)]?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)) ?? []) - { - info.Execute.Add(item); - } - - return info; + var targetType = obj[nameof(TargetType)] as JObject; + var classType = + System.Type.GetType( + $"EggLink.DanhengServer.Data.Config.Task.{targetType?["Type"]?.ToString().Replace("RPG.GameCore.", "")}"); + classType ??= System.Type.GetType("EggLink.DanhengServer.Data.Config.Task.TargetEvaluator"); + info.TargetType = (targetType!.ToObject(classType!) as TargetEvaluator)!; } + + if (obj.ContainsKey(nameof(State))) + info.State = obj[nameof(State)]?.ToObject() ?? PropStateEnum.Closed; + + foreach (var item in + obj[nameof(Execute)]?.Select(x => TaskConfigInfo.LoadFromJsonObject((x as JObject)!)) ?? []) + info.Execute.Add(item); + + return info; } -} +} \ No newline at end of file diff --git a/Common/Data/Config/Task/TargetEvaluator.cs b/Common/Data/Config/Task/TargetEvaluator.cs index 6488c278..b7735239 100644 --- a/Common/Data/Config/Task/TargetEvaluator.cs +++ b/Common/Data/Config/Task/TargetEvaluator.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Config.Task; -namespace EggLink.DanhengServer.Data.Config.Task +public class TargetEvaluator { - public class TargetEvaluator - { - public string Type { get; set; } = ""; - } -} + public string Type { get; set; } = ""; +} \ No newline at end of file diff --git a/Common/Data/Config/Task/TargetFetchAdvPropEx.cs b/Common/Data/Config/Task/TargetFetchAdvPropEx.cs index 48b8c60f..1d2281a2 100644 --- a/Common/Data/Config/Task/TargetFetchAdvPropEx.cs +++ b/Common/Data/Config/Task/TargetFetchAdvPropEx.cs @@ -1,25 +1,21 @@ using EggLink.DanhengServer.Enums.Task; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config.Task +namespace EggLink.DanhengServer.Data.Config.Task; + +public class TargetFetchAdvPropEx : TargetEvaluator { - public class TargetFetchAdvPropEx : TargetEvaluator - { - [JsonConverter(typeof(StringEnumConverter))] - public TargetFetchAdvPropFetchTypeEnum FetchType { get; set; } - //public DynamicString SinglePropKey; - public FetchAdvPropData SinglePropID { get; set; } = new(); - //public DynamicString SingleUniqueName; - //public DynamicString[] MultiPropKey; - //public FetchAdvPropData[] MultiPropID; - //public DynamicString[] MultiUniqueName; - public DynamicFloat PropGroup { get; set; } = new(); - public DynamicFloat PropIDInOwnerGroup { get; set; } = new(); - } -} + [JsonConverter(typeof(StringEnumConverter))] + public TargetFetchAdvPropFetchTypeEnum FetchType { get; set; } + + //public DynamicString SinglePropKey; + public FetchAdvPropData SinglePropID { get; set; } = new(); + + //public DynamicString SingleUniqueName; + //public DynamicString[] MultiPropKey; + //public FetchAdvPropData[] MultiPropID; + //public DynamicString[] MultiUniqueName; + public DynamicFloat PropGroup { get; set; } = new(); + public DynamicFloat PropIDInOwnerGroup { get; set; } = new(); +} \ No newline at end of file diff --git a/Common/Data/Config/Task/TaskConfigInfo.cs b/Common/Data/Config/Task/TaskConfigInfo.cs index 83ca4b8c..d5eda50f 100644 --- a/Common/Data/Config/Task/TaskConfigInfo.cs +++ b/Common/Data/Config/Task/TaskConfigInfo.cs @@ -1,52 +1,49 @@ -using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; -namespace EggLink.DanhengServer.Data.Config.Task +namespace EggLink.DanhengServer.Data.Config.Task; + +public class TaskConfigInfo { - public class TaskConfigInfo + public string Type { get; set; } = ""; + public bool TaskEnabled { get; set; } = false; + + public static TaskConfigInfo LoadFromJsonObject(JObject json) { - public string Type { get; set; } = ""; - public bool TaskEnabled { get; set; } = false; + var type = json[nameof(Type)]?.Value() ?? ""; + if (string.IsNullOrEmpty(type)) return new TaskConfigInfo(); - public static TaskConfigInfo LoadFromJsonObject(JObject json) + var typeStr = type.Replace("RPG.GameCore.", ""); + var className = "EggLink.DanhengServer.Data.Config.Task." + typeStr; + var typeClass = System.Type.GetType(className); + if (typeStr == "PredicateTaskList") { - string type = json[nameof(Type)]?.Value() ?? ""; - if (string.IsNullOrEmpty(type)) - { - return new TaskConfigInfo(); - } - - var typeStr = type.Replace("RPG.GameCore.", ""); - var className = "EggLink.DanhengServer.Data.Config.Task." + typeStr; - var typeClass = System.Type.GetType(className); - if (typeStr == "PredicateTaskList") - { - var res = PredicateTaskList.LoadFromJsonObject(json); - res.Type = type; - return res; - } - - if (typeStr == "PropSetupUITrigger") - { - var res = PropSetupUITrigger.LoadFromJsonObject(json); - res.Type = type; - return res; - } - - if (typeStr == "PropStateExecute") - { - var res = PropStateExecute.LoadFromJsonObject(json); - res.Type = type; - return res; - } - - if (typeClass != null) - { - var res = (TaskConfigInfo)json.ToObject(typeClass)!; - res.Type = type; - return res; - } - - return Newtonsoft.Json.JsonConvert.DeserializeObject(json.ToString())!; + var res = PredicateTaskList.LoadFromJsonObject(json); + res.Type = type; + return res; } + + if (typeStr == "PropSetupUITrigger") + { + var res = PropSetupUITrigger.LoadFromJsonObject(json); + res.Type = type; + return res; + } + + if (typeStr == "PropStateExecute") + { + var res = PropStateExecute.LoadFromJsonObject(json); + res.Type = type; + return res; + } + + if (typeClass != null) + { + var res = (TaskConfigInfo)json.ToObject(typeClass)!; + res.Type = type; + return res; + } + + return JsonConvert.DeserializeObject(json.ToString())!; } -} +} \ No newline at end of file diff --git a/Common/Data/Config/Task/TriggerCustomString.cs b/Common/Data/Config/Task/TriggerCustomString.cs index b6782b41..77b948dc 100644 --- a/Common/Data/Config/Task/TriggerCustomString.cs +++ b/Common/Data/Config/Task/TriggerCustomString.cs @@ -1,18 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Config.Task; -namespace EggLink.DanhengServer.Data.Config.Task +public class TriggerCustomString : TaskConfigInfo { - public class TriggerCustomString : TaskConfigInfo - { - public DynamicString CustomString { get; set; } = new(); - } - - public class DynamicString - { - public string Value { get; set; } = string.Empty; - } + public DynamicString CustomString { get; set; } = new(); } + +public class DynamicString +{ + public string Value { get; set; } = string.Empty; +} \ No newline at end of file diff --git a/Common/Data/Config/Task/TriggerEntityEvent.cs b/Common/Data/Config/Task/TriggerEntityEvent.cs index bcdfda8e..8da2f65d 100644 --- a/Common/Data/Config/Task/TriggerEntityEvent.cs +++ b/Common/Data/Config/Task/TriggerEntityEvent.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Config.Task; -namespace EggLink.DanhengServer.Data.Config.Task +public class TriggerEntityEvent : TaskConfigInfo { - public class TriggerEntityEvent : TaskConfigInfo - { - public DynamicFloat InstanceID { get; set; } = new(); - } -} + public DynamicFloat InstanceID { get; set; } = new(); +} \ No newline at end of file diff --git a/Common/Data/Config/Task/TriggerPerformance.cs b/Common/Data/Config/Task/TriggerPerformance.cs index e75e7528..b75a3147 100644 --- a/Common/Data/Config/Task/TriggerPerformance.cs +++ b/Common/Data/Config/Task/TriggerPerformance.cs @@ -1,18 +1,13 @@ using EggLink.DanhengServer.Enums.Task; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config.Task +namespace EggLink.DanhengServer.Data.Config.Task; + +public class TriggerPerformance : TaskConfigInfo { - public class TriggerPerformance : TaskConfigInfo - { - [JsonConverter(typeof(StringEnumConverter))] - public ELevelPerformanceTypeEnum PerformanceType { get; set; } - public int PerformanceID { get; set; } - } -} + [JsonConverter(typeof(StringEnumConverter))] + public ELevelPerformanceTypeEnum PerformanceType { get; set; } + + public int PerformanceID { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Config/TaskInfo.cs b/Common/Data/Config/TaskInfo.cs index 6b2b2e1f..581d51fe 100644 --- a/Common/Data/Config/TaskInfo.cs +++ b/Common/Data/Config/TaskInfo.cs @@ -1,125 +1,82 @@ using EggLink.DanhengServer.Enums.Avatar; -using EggLink.DanhengServer.Util; using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Config +namespace EggLink.DanhengServer.Data.Config; + +public class TaskInfo { - public class TaskInfo + public string Type { get; set; } = ""; + + public int ID { get; set; } + public int SummonUnitID { get; set; } + + // Here's a conflict between Dimbreath's res and Andy's res ( we recommend to use the one from Andy's res ) + public bool TriggerBattle { get; set; } = false; + + public List OnAttack { get; set; } = []; + public List OnBattle { get; set; } = []; + public List SuccessTaskList { get; set; } = []; + public List OnProjectileHit { get; set; } = []; + public List OnProjectileLifetimeFinish { get; set; } = []; + + public LifeTimeInfo LifeTime { get; set; } = new(); + + [JsonIgnore] public TaskTypeEnum TaskType { get; set; } = TaskTypeEnum.None; + + public void Loaded() { - public string Type { get; set; } = ""; - - public int ID { get; set; } - public int SummonUnitID { get; set; } - - // Here's a conflict between Dimbreath's res and Andy's res ( we recommend to use the one from Andy's res ) - public bool TriggerBattle { get; set; } = false; - - public List OnAttack { get; set; } = []; - public List OnBattle { get; set; } = []; - public List SuccessTaskList { get; set; } = []; - public List OnProjectileHit { get; set; } = []; - public List OnProjectileLifetimeFinish { get; set; } = []; - - public LifeTimeInfo LifeTime { get; set; } = new(); - - [JsonIgnore] - public TaskTypeEnum TaskType { get; set; } = TaskTypeEnum.None; - - public void Loaded() - { - foreach (var task in OnAttack) - { - task.Loaded(); - } - foreach (var task in OnBattle) - { - task.Loaded(); - } - foreach (var task in SuccessTaskList) - { - task.Loaded(); - } - foreach (var task in OnProjectileHit) - { - task.Loaded(); - } - foreach (var task in OnProjectileLifetimeFinish) - { - task.Loaded(); - } - if (Type.Contains("AddMazeBuff")) - { - TaskType = TaskTypeEnum.AddMazeBuff; - } else if (Type.Contains("RemoveMazeBuff")) - { - TaskType = TaskTypeEnum.RemoveMazeBuff; - } else if (Type.Contains("AdventureModifyTeamPlayerHP")) - { - TaskType = TaskTypeEnum.AdventureModifyTeamPlayerHP; - } else if (Type.Contains("AdventureModifyTeamPlayerSP")) - { - TaskType = TaskTypeEnum.AdventureModifyTeamPlayerSP; - } else if (Type.Contains("CreateSummonUnit")) - { - TaskType = TaskTypeEnum.CreateSummonUnit; - } else if (Type.Contains("AdventureSetAttackTargetMonsterDie")) - { - TaskType = TaskTypeEnum.AdventureSetAttackTargetMonsterDie; - } else if (SuccessTaskList.Count > 0) - { - TaskType = TaskTypeEnum.SuccessTaskList; - } - else if (Type.Contains("AdventureTriggerAttack")) - { - TaskType = TaskTypeEnum.AdventureTriggerAttack; - } else if (Type.Contains("AdventureFireProjectile")) - { - TaskType = TaskTypeEnum.AdventureFireProjectile; - } - } - - public int GetID() - { - return ID > 0 ? ID : SummonUnitID; - } - - public List GetAttackInfo() - { - var attackInfo = new List(); - attackInfo.AddRange(OnAttack); - attackInfo.AddRange(OnBattle); - return attackInfo; - } + foreach (var task in OnAttack) task.Loaded(); + foreach (var task in OnBattle) task.Loaded(); + foreach (var task in SuccessTaskList) task.Loaded(); + foreach (var task in OnProjectileHit) task.Loaded(); + foreach (var task in OnProjectileLifetimeFinish) task.Loaded(); + if (Type.Contains("AddMazeBuff")) + TaskType = TaskTypeEnum.AddMazeBuff; + else if (Type.Contains("RemoveMazeBuff")) + TaskType = TaskTypeEnum.RemoveMazeBuff; + else if (Type.Contains("AdventureModifyTeamPlayerHP")) + TaskType = TaskTypeEnum.AdventureModifyTeamPlayerHP; + else if (Type.Contains("AdventureModifyTeamPlayerSP")) + TaskType = TaskTypeEnum.AdventureModifyTeamPlayerSP; + else if (Type.Contains("CreateSummonUnit")) + TaskType = TaskTypeEnum.CreateSummonUnit; + else if (Type.Contains("AdventureSetAttackTargetMonsterDie")) + TaskType = TaskTypeEnum.AdventureSetAttackTargetMonsterDie; + else if (SuccessTaskList.Count > 0) + TaskType = TaskTypeEnum.SuccessTaskList; + else if (Type.Contains("AdventureTriggerAttack")) + TaskType = TaskTypeEnum.AdventureTriggerAttack; + else if (Type.Contains("AdventureFireProjectile")) TaskType = TaskTypeEnum.AdventureFireProjectile; } - public class LifeTimeInfo + public int GetID() { - public bool IsDynamic { get; set; } = false; - public FixedValueInfo FixedValue { get; set; } = new(); - - public int GetLifeTime() - { - if (IsDynamic) - { - return 20; // find a better way to get the value - } - if (FixedValue.Value <= 0) - { - return -1; // infinite - } - return (int)(FixedValue.Value * 10); - } + return ID > 0 ? ID : SummonUnitID; } - public class FixedValueInfo + public List GetAttackInfo() { - public T Value { get; set; } = default!; + var attackInfo = new List(); + attackInfo.AddRange(OnAttack); + attackInfo.AddRange(OnBattle); + return attackInfo; } } + +public class LifeTimeInfo +{ + public bool IsDynamic { get; set; } = false; + public FixedValueInfo FixedValue { get; set; } = new(); + + public int GetLifeTime() + { + if (IsDynamic) return 20; // find a better way to get the value + if (FixedValue.Value <= 0) return -1; // infinite + return (int)(FixedValue.Value * 10); + } +} + +public class FixedValueInfo +{ + public T Value { get; set; } = default!; +} \ No newline at end of file diff --git a/Common/Data/Custom/ActivityConfig.cs b/Common/Data/Custom/ActivityConfig.cs index 54302db3..f468ca80 100644 --- a/Common/Data/Custom/ActivityConfig.cs +++ b/Common/Data/Custom/ActivityConfig.cs @@ -1,21 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Custom; -namespace EggLink.DanhengServer.Data.Custom +public class ActivityConfig { - public class ActivityConfig - { - public List ScheduleData { get; set; } = []; - } - - public class ActivityScheduleData - { - public int ActivityId { get; set; } - public long BeginTime { get; set; } - public long EndTime { get; set; } - public int PanelId { get; set; } - } + public List ScheduleData { get; set; } = []; } + +public class ActivityScheduleData +{ + public int ActivityId { get; set; } + public long BeginTime { get; set; } + public long EndTime { get; set; } + public int PanelId { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Custom/BannersConfig.cs b/Common/Data/Custom/BannersConfig.cs index 37ca03e5..b9271941 100644 --- a/Common/Data/Custom/BannersConfig.cs +++ b/Common/Data/Custom/BannersConfig.cs @@ -1,188 +1,164 @@ using EggLink.DanhengServer.Database; +using EggLink.DanhengServer.Database.Gacha; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using GachaInfo = EggLink.DanhengServer.Proto.GachaInfo; -namespace EggLink.DanhengServer.Data.Custom +namespace EggLink.DanhengServer.Data.Custom; + +public class BannersConfig { - public class BannersConfig - { - public List Banners { get; set; } = []; - } - - public class BannerConfig - { - public int GachaId { get; set; } - public long BeginTime { get; set; } - public long EndTime { get; set; } - public GachaTypeEnum GachaType { get; set; } - public List RateUpItems5 { get; set; } = []; - public List RateUpItems4 { get; set; } = []; - public int GetRateUpItem5Chance { get; set; } = 6; // 0.6% chance (0.6%*1000) - public int MaxCount { get; set; } = 90; - public int EventChance { get; set; } = 50; - - public int DoGacha(List goldAvatars, List purpleAvatars, List purpleWeapons, List goldWeapons, List blueWeapons, Database.Gacha.GachaData data) - { - var random = new Random(); - data.LastGachaFailedCount += 1; - int item; - - var allGoldItems = new List(); - allGoldItems.AddRange(goldAvatars); - allGoldItems.AddRange(goldWeapons); - - var allNormalItems = new List(); - allNormalItems.AddRange(purpleAvatars); - allNormalItems.AddRange(purpleWeapons); - - if (data.LastGachaFailedCount >= MaxCount || IsRateUp()) - { - data.LastGachaFailedCount = 0; - if (GachaType == GachaTypeEnum.WeaponUp) - { - item = GetRateUpItem5(goldWeapons, data.LastWeaponGachaFailed); - if (RateUpItems5.Contains(item)) - { - data.LastWeaponGachaFailed = false; - } - else - { - data.LastWeaponGachaFailed = true; - } - } - else if (GachaType == GachaTypeEnum.AvatarUp) - { - item = GetRateUpItem5(goldAvatars, data.LastAvatarGachaFailed); - if (RateUpItems5.Contains(item)) - { - data.LastAvatarGachaFailed = false; - } - else - { - data.LastAvatarGachaFailed = true; - } - } - else - { - item = GetRateUpItem5(allGoldItems, false); - } - } - else - { - // 4 - 3 star - if (IsRate4() || data.LastGachaPurpleFailedCount >= 10) - { - if (IsRateUp4()) - { - item = RateUpItems4[random.Next(0, RateUpItems4.Count)]; - } - else - { - item = allNormalItems[random.Next(0, allNormalItems.Count)]; - } - data.LastGachaPurpleFailedCount = 0; - } - else - { - item = blueWeapons[random.Next(0, blueWeapons.Count)]; - data.LastGachaPurpleFailedCount += 1; - } - } - DatabaseHelper.Instance?.UpdateInstance(data); - - return item; - } - - public bool IsEvent() - { - var random = new Random(); - return random.Next(0, 100) < EventChance; - } - - public bool IsRateUp() - { - var random = new Random(); - return random.Next(0, 1000) < GetRateUpItem5Chance; - } - - public bool IsRateUp4() - { - var random = new Random(); - return random.Next(0, 100) < 50; - } - - public bool IsRate4() - { - var random = new Random(); - return random.Next(0, 100) < 31; - } - - public int GetRateUpItem5(List gold, bool forceUp) - { - var random = new Random(); - if (IsEvent() || forceUp) - { - return RateUpItems5[random.Next(0, RateUpItems5.Count)]; - } - else - { - return gold[random.Next(0, gold.Count)]; - } - } - - public GachaInfo ToInfo(List goldAvatar) - { - var info = new GachaInfo() - { - GachaId = (uint)GachaId, - DetailWebview = "", - DropHistoryWebview = "", - }; - - if (GachaType != GachaTypeEnum.Normal) - { - info.BeginTime = BeginTime; - info.EndTime = EndTime; - } - if (GachaId == 1001) - { - if (RateUpItems4.Count > 0) - { - info.ItemDetailList.AddRange(RateUpItems4.Select(id => (uint)id)); - } - - if (RateUpItems5.Count > 0) - { - info.PrizeItemList.AddRange(RateUpItems5.Select(id => (uint)id)); - info.ItemDetailList.AddRange(RateUpItems5.Select(id => (uint)id)); - } - - info.GachaCeiling = new() - { - IsClaimed = true, // TODO: Implement this - AvatarList = { goldAvatar.Select(id => new GachaCeilingAvatar() { AvatarId = (uint)id }) } - }; - } - else - { - if (RateUpItems4.Count > 0) - { - info.ItemDetailList.AddRange(RateUpItems4.Select(id => (uint)id)); - } - - if (RateUpItems5.Count > 0) - { - info.PrizeItemList.AddRange(RateUpItems5.Select(id => (uint)id)); - info.ItemDetailList.AddRange(RateUpItems5.Select(id => (uint)id)); - } - } - - return info; - } - } + public List Banners { get; set; } = []; } + +public class BannerConfig +{ + public int GachaId { get; set; } + public long BeginTime { get; set; } + public long EndTime { get; set; } + public GachaTypeEnum GachaType { get; set; } + public List RateUpItems5 { get; set; } = []; + public List RateUpItems4 { get; set; } = []; + public int GetRateUpItem5Chance { get; set; } = 6; // 0.6% chance (0.6%*1000) + public int MaxCount { get; set; } = 90; + public int EventChance { get; set; } = 50; + + public int DoGacha(List goldAvatars, List purpleAvatars, List purpleWeapons, List goldWeapons, + List blueWeapons, GachaData data) + { + var random = new Random(); + data.LastGachaFailedCount += 1; + int item; + + var allGoldItems = new List(); + allGoldItems.AddRange(goldAvatars); + allGoldItems.AddRange(goldWeapons); + + var allNormalItems = new List(); + allNormalItems.AddRange(purpleAvatars); + allNormalItems.AddRange(purpleWeapons); + + if (data.LastGachaFailedCount >= MaxCount || IsRateUp()) + { + data.LastGachaFailedCount = 0; + if (GachaType == GachaTypeEnum.WeaponUp) + { + item = GetRateUpItem5(goldWeapons, data.LastWeaponGachaFailed); + if (RateUpItems5.Contains(item)) + data.LastWeaponGachaFailed = false; + else + data.LastWeaponGachaFailed = true; + } + else if (GachaType == GachaTypeEnum.AvatarUp) + { + item = GetRateUpItem5(goldAvatars, data.LastAvatarGachaFailed); + if (RateUpItems5.Contains(item)) + data.LastAvatarGachaFailed = false; + else + data.LastAvatarGachaFailed = true; + } + else + { + item = GetRateUpItem5(allGoldItems, false); + } + } + else + { + // 4 - 3 star + if (IsRate4() || data.LastGachaPurpleFailedCount >= 10) + { + if (IsRateUp4()) + item = RateUpItems4[random.Next(0, RateUpItems4.Count)]; + else + item = allNormalItems[random.Next(0, allNormalItems.Count)]; + data.LastGachaPurpleFailedCount = 0; + } + else + { + item = blueWeapons[random.Next(0, blueWeapons.Count)]; + data.LastGachaPurpleFailedCount += 1; + } + } + + DatabaseHelper.Instance?.UpdateInstance(data); + + return item; + } + + public bool IsEvent() + { + var random = new Random(); + return random.Next(0, 100) < EventChance; + } + + public bool IsRateUp() + { + var random = new Random(); + return random.Next(0, 1000) < GetRateUpItem5Chance; + } + + public bool IsRateUp4() + { + var random = new Random(); + return random.Next(0, 100) < 50; + } + + public bool IsRate4() + { + var random = new Random(); + return random.Next(0, 100) < 31; + } + + public int GetRateUpItem5(List gold, bool forceUp) + { + var random = new Random(); + if (IsEvent() || forceUp) + return RateUpItems5[random.Next(0, RateUpItems5.Count)]; + return gold[random.Next(0, gold.Count)]; + } + + public GachaInfo ToInfo(List goldAvatar) + { + var info = new GachaInfo + { + GachaId = (uint)GachaId, + DetailWebview = "", + DropHistoryWebview = "" + }; + + if (GachaType != GachaTypeEnum.Normal) + { + info.BeginTime = BeginTime; + info.EndTime = EndTime; + } + + if (GachaId == 1001) + { + if (RateUpItems4.Count > 0) info.ItemDetailList.AddRange(RateUpItems4.Select(id => (uint)id)); + + if (RateUpItems5.Count > 0) + { + info.PrizeItemList.AddRange(RateUpItems5.Select(id => (uint)id)); + info.ItemDetailList.AddRange(RateUpItems5.Select(id => (uint)id)); + } + + info.GachaCeiling = new GachaCeiling + { + IsClaimed = true, // TODO: Implement this + AvatarList = { goldAvatar.Select(id => new GachaCeilingAvatar { AvatarId = (uint)id }) } + }; + } + else + { + if (RateUpItems4.Count > 0) info.ItemDetailList.AddRange(RateUpItems4.Select(id => (uint)id)); + + if (RateUpItems5.Count > 0) + { + info.PrizeItemList.AddRange(RateUpItems5.Select(id => (uint)id)); + info.ItemDetailList.AddRange(RateUpItems5.Select(id => (uint)id)); + } + } + + return info; + } +} \ No newline at end of file diff --git a/Common/Data/Custom/ChessRogueRoomConfig.cs b/Common/Data/Custom/ChessRogueRoomConfig.cs index 799f62d8..b2adcb0e 100644 --- a/Common/Data/Custom/ChessRogueRoomConfig.cs +++ b/Common/Data/Custom/ChessRogueRoomConfig.cs @@ -1,28 +1,24 @@ using EggLink.DanhengServer.Enums.Rogue; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Custom +namespace EggLink.DanhengServer.Data.Custom; + +public class ChessRogueRoomConfig { - public class ChessRogueRoomConfig - { - public int EntranceId { get; set; } - public int RoomPrefix { get; set; } - [JsonConverter(typeof(StringEnumConverter))] - public RogueDLCBlockTypeEnum BlockType { get; set; } - public int AnchorGroup { get; set; } - public int AnchorId { get; set; } + public int EntranceId { get; set; } + public int RoomPrefix { get; set; } - public List DefaultLoadBasicGroup { get; set; } = []; - public List DefaultLoadGroup { get; set; } = []; - public List DoubleEventLoadGroup { get; set; } = []; // override DefaultLoadGroup - public List SelectEventLoadGroup { get; set; } = []; // override DefaultLoadGroup + [JsonConverter(typeof(StringEnumConverter))] + public RogueDLCBlockTypeEnum BlockType { get; set; } - public List SubMonsterGroup { get; set; } = []; // combine with DefaultLoadGroup - } -} + public int AnchorGroup { get; set; } + public int AnchorId { get; set; } + + public List DefaultLoadBasicGroup { get; set; } = []; + public List DefaultLoadGroup { get; set; } = []; + public List DoubleEventLoadGroup { get; set; } = []; // override DefaultLoadGroup + public List SelectEventLoadGroup { get; set; } = []; // override DefaultLoadGroup + + public List SubMonsterGroup { get; set; } = []; // combine with DefaultLoadGroup +} \ No newline at end of file diff --git a/Common/Data/Custom/RogueMiracleEffectConfig.cs b/Common/Data/Custom/RogueMiracleEffectConfig.cs index 3eac56a3..90e3ea86 100644 --- a/Common/Data/Custom/RogueMiracleEffectConfig.cs +++ b/Common/Data/Custom/RogueMiracleEffectConfig.cs @@ -2,29 +2,28 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; -namespace EggLink.DanhengServer.Data.Custom +namespace EggLink.DanhengServer.Data.Custom; + +public class RogueMiracleEffectConfig { - public class RogueMiracleEffectConfig - { - public Dictionary Miracles { get; set; } = []; - } - - public class RogueMiracleEffect - { - public int MiracleId { get; set; } - public int MaxDurability { get; set; } - public Dictionary Effects { get; set; } = []; - } - - public class RogueEffect - { - public int EffectId { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public RogueMiracleEffectTypeEnum Type { get; set; } - - public string DynamicKey { get; set; } = ""; // for arguments - - public List Params { get; set; } = []; - } + public Dictionary Miracles { get; set; } = []; } + +public class RogueMiracleEffect +{ + public int MiracleId { get; set; } + public int MaxDurability { get; set; } + public Dictionary Effects { get; set; } = []; +} + +public class RogueEffect +{ + public int EffectId { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public RogueMiracleEffectTypeEnum Type { get; set; } + + public string DynamicKey { get; set; } = ""; // for arguments + + public List Params { get; set; } = []; +} \ No newline at end of file diff --git a/Common/Data/Excel/ActionPointOverdrawExcel.cs b/Common/Data/Excel/ActionPointOverdrawExcel.cs index 9d6af034..98db7947 100644 --- a/Common/Data/Excel/ActionPointOverdrawExcel.cs +++ b/Common/Data/Excel/ActionPointOverdrawExcel.cs @@ -1,25 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ActionPointOverdraw.json")] +public class ActionPointOverdrawExcel : ExcelResource { - [ResourceEntity("ActionPointOverdraw.json")] - public class ActionPointOverdrawExcel : ExcelResource + public int ActionPoint { get; set; } + public int MazeBuff { get; set; } + + public override int GetId() { - public int ActionPoint { get; set; } - public int MazeBuff { get; set; } - - public override int GetId() - { - return ActionPoint; - } - - public override void Loaded() - { - GameData.ActionPointOverdrawData.Add(ActionPoint, this); - } + return ActionPoint; } -} + + public override void Loaded() + { + GameData.ActionPointOverdrawData.Add(ActionPoint, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/AdventurePlayerExcel.cs b/Common/Data/Excel/AdventurePlayerExcel.cs index 2ff927db..e32a749e 100644 --- a/Common/Data/Excel/AdventurePlayerExcel.cs +++ b/Common/Data/Excel/AdventurePlayerExcel.cs @@ -1,25 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("AdventurePlayer.json")] +public class AdventurePlayerExcel : ExcelResource { - [ResourceEntity("AdventurePlayer.json")] - public class AdventurePlayerExcel : ExcelResource + public int AvatarID { get; set; } = 0; + public string PlayerJsonPath { get; set; } = ""; + + public override int GetId() { - public int AvatarID { get; set; } = 0; - public string PlayerJsonPath { get; set; } = ""; - - public override int GetId() - { - return AvatarID; - } - - public override void Loaded() - { - GameData.AdventurePlayerData[AvatarID] = this; - } + return AvatarID; } -} + + public override void Loaded() + { + GameData.AdventurePlayerData[AvatarID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/AvatarConfigExcel.cs b/Common/Data/Excel/AvatarConfigExcel.cs index 1e2a8604..1b1735f8 100644 --- a/Common/Data/Excel/AvatarConfigExcel.cs +++ b/Common/Data/Excel/AvatarConfigExcel.cs @@ -1,66 +1,56 @@ -using EggLink.DanhengServer.Data.Config; +using System.Text.RegularExpressions; +using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums.Avatar; using EggLink.DanhengServer.Enums.Item; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System.Text.RegularExpressions; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("AvatarConfig.json", true)] +public class AvatarConfigExcel : ExcelResource { - [ResourceEntity("AvatarConfig.json", true)] - public class AvatarConfigExcel : ExcelResource + [JsonIgnore] public List DefaultSkillTree = []; + + [JsonIgnore] public string? Name; + + [JsonIgnore] public List SkillTree = []; + + public int AvatarID { get; set; } = 0; + public HashName AvatarName { get; set; } = new(); + public int ExpGroup { get; set; } = 0; + public int MaxPromotion { get; set; } = 0; + public int MaxRank { get; set; } = 0; + public List RankIDList { get; set; } = []; + public string? JsonPath { get; set; } = ""; + + [JsonConverter(typeof(StringEnumConverter))] + public RarityEnum Rarity { get; set; } = 0; + + [JsonConverter(typeof(StringEnumConverter))] + public DamageTypeEnum DamageType { get; set; } = 0; + + [JsonIgnore] public int RankUpItemId { get; set; } + + [JsonIgnore] public string NameKey { get; set; } = ""; + + [JsonIgnore] public AbilityInfo? MazeSkill { get; set; } + + [JsonIgnore] public AbilityInfo? MazeAtk { get; set; } + + public override int GetId() { - public int AvatarID { get; set; } = 0; - public HashName AvatarName { get; set; } = new(); - public int ExpGroup { get; set; } = 0; - public int MaxPromotion { get; set; } = 0; - public int MaxRank { get; set; } = 0; - public List RankIDList { get; set; } = []; - public string? JsonPath { get; set; } = ""; - - [JsonConverter(typeof(StringEnumConverter))] - public RarityEnum Rarity { get; set; } = 0; - - [JsonConverter(typeof(StringEnumConverter))] - public DamageTypeEnum DamageType { get; set; } = 0; - - [JsonIgnore()] - public List DefaultSkillTree = []; - - [JsonIgnore] - public List SkillTree = []; - - [JsonIgnore()] - public int RankUpItemId { get; set; } - - [JsonIgnore()] - public string NameKey { get; set; } = ""; - - [JsonIgnore] - public string? Name; - - [JsonIgnore()] - public AbilityInfo? MazeSkill { get; set; } - [JsonIgnore()] - public AbilityInfo? MazeAtk { get; set; } - - public override int GetId() - { - return AvatarID; - } - - public override void Loaded() - { - GameData.AvatarConfigData.Add(AvatarID, this); - RankUpItemId = AvatarID + 10000; - - var regex = new Regex(@"(?<=Avatar_)(.*?)(?=_Config)"); - var match = regex.Match(JsonPath??""); - if (match.Success) - { - NameKey = match.Value; - } - JsonPath = null; - } + return AvatarID; } -} + + public override void Loaded() + { + GameData.AvatarConfigData.Add(AvatarID, this); + RankUpItemId = AvatarID + 10000; + + var regex = new Regex(@"(?<=Avatar_)(.*?)(?=_Config)"); + var match = regex.Match(JsonPath ?? ""); + if (match.Success) NameKey = match.Value; + JsonPath = null; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/AvatarExpItemConfigExcel.cs b/Common/Data/Excel/AvatarExpItemConfigExcel.cs index 39a83fc7..8b4827d1 100644 --- a/Common/Data/Excel/AvatarExpItemConfigExcel.cs +++ b/Common/Data/Excel/AvatarExpItemConfigExcel.cs @@ -1,38 +1,25 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("AvatarExpItemConfig.json")] +public class AvatarExpItemConfigExcel : ExcelResource { - [ResourceEntity("AvatarExpItemConfig.json")] - public class AvatarExpItemConfigExcel : ExcelResource + public int ItemID { get; set; } + public int Exp { get; set; } + + public override int GetId() { - public int ItemID { get; set; } - public int Exp { get; set; } - - public override int GetId() - { - return ItemID; - } - - public override void Loaded() - { - if (Exp > 0) - { - GameData.AvatarExpItemConfigData.Add(GetId(), this); - } - } - - public override void AfterAllDone() - { - GameData.ItemConfigData.TryGetValue(ItemID, out ItemConfigExcel? itemConfig); - if (itemConfig == null) - { - return; - } - itemConfig.Exp = Exp; - } + return ItemID; } -} + + public override void Loaded() + { + if (Exp > 0) GameData.AvatarExpItemConfigData.Add(GetId(), this); + } + + public override void AfterAllDone() + { + GameData.ItemConfigData.TryGetValue(ItemID, out var itemConfig); + if (itemConfig == null) return; + itemConfig.Exp = Exp; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/AvatarPromotionConfigExcel.cs b/Common/Data/Excel/AvatarPromotionConfigExcel.cs index f33c45ac..ee302329 100644 --- a/Common/Data/Excel/AvatarPromotionConfigExcel.cs +++ b/Common/Data/Excel/AvatarPromotionConfigExcel.cs @@ -1,35 +1,28 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("AvatarPromotionConfig.json")] +public class AvatarPromotionConfigExcel : ExcelResource { - [ResourceEntity("AvatarPromotionConfig.json")] - public class AvatarPromotionConfigExcel : ExcelResource + public int AvatarID { get; set; } + public int Promotion { get; set; } + public int MaxLevel { get; set; } + public int PlayerLevelRequire { get; set; } + public int WorldLevelRequire { get; set; } + public List PromotionCostList { get; set; } = []; + + public override int GetId() { - public int AvatarID { get; set; } - public int Promotion { get; set; } - public int MaxLevel { get; set; } - public int PlayerLevelRequire { get; set; } - public int WorldLevelRequire { get; set; } - public List PromotionCostList { get; set; } = []; - - public override int GetId() - { - return AvatarID * 10 + Promotion; - } - - public override void Loaded() - { - GameData.AvatarPromotionConfigData.Add(GetId(), this); - } - - public class ItemParam - { - public int ItemID; - public int ItemNum; - } + return AvatarID * 10 + Promotion; } -} + + public override void Loaded() + { + GameData.AvatarPromotionConfigData.Add(GetId(), this); + } + + public class ItemParam + { + public int ItemID; + public int ItemNum; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/AvatarSkillTreeConfigExcel.cs b/Common/Data/Excel/AvatarSkillTreeConfigExcel.cs index d11b4b26..ceea9a93 100644 --- a/Common/Data/Excel/AvatarSkillTreeConfigExcel.cs +++ b/Common/Data/Excel/AvatarSkillTreeConfigExcel.cs @@ -1,32 +1,24 @@ -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("AvatarSkillTreeConfig.json")] +public class AvatarSkillTreeConfigExcel : ExcelResource { - [ResourceEntity("AvatarSkillTreeConfig.json")] - public class AvatarSkillTreeConfigExcel : ExcelResource + public int PointID { get; set; } + public int Level { get; set; } + public int AvatarID { get; set; } + public bool DefaultUnlock { get; set; } + public int MaxLevel { get; set; } + + public override int GetId() { - - public int PointID { get; set; } - public int Level { get; set; } - public int AvatarID { get; set; } - public bool DefaultUnlock { get; set; } - public int MaxLevel { get; set; } - - public override int GetId() - { - return (PointID * 10) + Level; - } - - public override void AfterAllDone() - { - GameData.AvatarConfigData.TryGetValue(AvatarID, out var excel); - if (excel != null && DefaultUnlock) - { - excel.DefaultSkillTree.Add(this); - } - if (excel != null) - { - excel.SkillTree.Add(this); - } - GameData.AvatarSkillTreeConfigData.Add(GetId(), this); - } + return PointID * 10 + Level; } -} + + public override void AfterAllDone() + { + GameData.AvatarConfigData.TryGetValue(AvatarID, out var excel); + if (excel != null && DefaultUnlock) excel.DefaultSkillTree.Add(this); + if (excel != null) excel.SkillTree.Add(this); + GameData.AvatarSkillTreeConfigData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/BackGroundMusicExcel.cs b/Common/Data/Excel/BackGroundMusicExcel.cs index 6016d905..664651be 100644 --- a/Common/Data/Excel/BackGroundMusicExcel.cs +++ b/Common/Data/Excel/BackGroundMusicExcel.cs @@ -1,25 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("BackGroundMusic.json")] +public class BackGroundMusicExcel : ExcelResource { - [ResourceEntity("BackGroundMusic.json")] - public class BackGroundMusicExcel : ExcelResource + public int ID { get; set; } + public int GroupID { get; set; } + + public override int GetId() { - public int ID { get; set; } - public int GroupID { get; set; } - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.BackGroundMusicData[ID] = this; - } + return ID; } -} + + public override void Loaded() + { + GameData.BackGroundMusicData[ID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/BattleEventDataExcel.cs b/Common/Data/Excel/BattleEventDataExcel.cs index 36be0eff..a2f88ecb 100644 --- a/Common/Data/Excel/BattleEventDataExcel.cs +++ b/Common/Data/Excel/BattleEventDataExcel.cs @@ -1,40 +1,34 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; +using System.Text.RegularExpressions; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("BattleEventData.json")] +public partial class BattleEventDataExcel : ExcelResource { - [ResourceEntity("BattleEventData.json")] - public partial class BattleEventDataExcel : ExcelResource + public int BattleEventID { get; set; } + public string Config { get; set; } = ""; + + [GeneratedRegex(@"(?<=Avatar_RogueBattleevent)(.*?)(?=_Config.json)")] + private static partial Regex RegexConfig(); + + public override int GetId() { - public int BattleEventID { get; set; } - public string Config { get; set; } = ""; + return BattleEventID; + } - [GeneratedRegex(@"(?<=Avatar_RogueBattleevent)(.*?)(?=_Config.json)")] - private static partial Regex RegexConfig(); - - public override int GetId() + public override void Loaded() + { + try { - return BattleEventID; - } - - public override void Loaded() - { - try + var match = RegexConfig().Match(Config); + if (match.Success) { - Match match = RegexConfig().Match(Config); - if (match.Success) - { - int rogueBuffType = int.Parse(match.Value); - GameData.RogueBattleEventData.Add(rogueBuffType, this); - } - } catch - { - + var rogueBuffType = int.Parse(match.Value); + GameData.RogueBattleEventData.Add(rogueBuffType, this); } } + catch + { + } } -} +} \ No newline at end of file diff --git a/Common/Data/Excel/ChallengeBossExtraExcel.cs b/Common/Data/Excel/ChallengeBossExtraExcel.cs index 989b5db5..2a16760c 100644 --- a/Common/Data/Excel/ChallengeBossExtraExcel.cs +++ b/Common/Data/Excel/ChallengeBossExtraExcel.cs @@ -1,31 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ChallengeBossMazeExtra.json")] +public class ChallengeBossExtraExcel : ExcelResource { - [ResourceEntity("ChallengeBossMazeExtra.json")] - public class ChallengeBossExtraExcel : ExcelResource + public int ID { get; set; } + public int MonsterID1 { get; set; } + public int MonsterID2 { get; set; } + + + public override int GetId() { - public int ID { get; set; } - public int MonsterID1 { get; set; } - public int MonsterID2 { get; set; } + return ID; + } - - public override int GetId() + public override void Loaded() + { + if (GameData.ChallengeConfigData.ContainsKey(ID)) { - return ID; - } - - public override void Loaded() - { - if (GameData.ChallengeConfigData.ContainsKey(ID)) - { - var challengeExcel = GameData.ChallengeConfigData[ID]; - challengeExcel.SetBossExcel(this); - } + var challengeExcel = GameData.ChallengeConfigData[ID]; + challengeExcel.SetBossExcel(this); } } -} +} \ No newline at end of file diff --git a/Common/Data/Excel/ChallengeConfigExcel.cs b/Common/Data/Excel/ChallengeConfigExcel.cs index be220f06..4d283151 100644 --- a/Common/Data/Excel/ChallengeConfigExcel.cs +++ b/Common/Data/Excel/ChallengeConfigExcel.cs @@ -1,100 +1,98 @@ using Newtonsoft.Json; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("ChallengeMazeConfig.json,ChallengeStoryMazeConfig.json,ChallengeBossMazeConfig.json", + true)] +public class ChallengeConfigExcel : ExcelResource { - [ResourceEntity("ChallengeMazeConfig.json,ChallengeStoryMazeConfig.json,ChallengeBossMazeConfig.json", - isMultifile: true)] - public class ChallengeConfigExcel : ExcelResource + [JsonIgnore] public ChallengeBossExtraExcel? BossExcel; + + [JsonIgnore] public ChallengeStoryExtraExcel? StoryExcel; + + // General item data + public int ID { get; set; } + public int GroupID { get; set; } + public int MapEntranceID { get; set; } + public int StageNum { get; set; } + public int ChallengeCountDown { get; set; } + public int MazeBuffID { get; set; } + + public List? ChallengeTargetID { get; set; } = []; + + public int MazeGroupID1 { get; set; } + public List? ConfigList1 { get; set; } = []; + public List? NpcMonsterIDList1 { get; set; } = []; + public List? EventIDList1 { get; set; } = []; + + public int MazeGroupID2 { get; set; } + public List? ConfigList2 { get; set; } = []; + public List? NpcMonsterIDList2 { get; set; } = []; + public List? EventIDList2 { get; set; } = []; + + [JsonIgnore] public Dictionary ChallengeMonsters1 { get; set; } = new(); + + [JsonIgnore] public Dictionary ChallengeMonsters2 { get; set; } = new(); + + public override int GetId() { - // General item data - public int ID { get; set; } - public int GroupID { get; set; } - public int MapEntranceID { get; set; } - public int StageNum { get; set; } - public int ChallengeCountDown { get; set; } - public int MazeBuffID { get; set; } - - public List? ChallengeTargetID { get; set; } = []; - - public int MazeGroupID1 { get; set; } - public List? ConfigList1 { get; set; } = []; - public List? NpcMonsterIDList1 { get; set; } = []; - public List? EventIDList1 { get; set; } = []; - - public int MazeGroupID2 { get; set; } - public List? ConfigList2 { get; set; } = []; - public List? NpcMonsterIDList2 { get; set; } = []; - public List? EventIDList2 { get; set; } = []; - - [JsonIgnore] - public Dictionary ChallengeMonsters1 { get; set; } = new(); - [JsonIgnore] - public Dictionary ChallengeMonsters2 { get; set; } = new(); - [JsonIgnore] - public ChallengeStoryExtraExcel? StoryExcel; - [JsonIgnore] - public ChallengeBossExtraExcel? BossExcel; - - public override int GetId() - { - return ID; - } - - public bool IsStory() - { - return StoryExcel != null; - } - - public bool IsBoss() - { - return BossExcel != null; - } - - public void SetStoryExcel(ChallengeStoryExtraExcel storyExcel) - { - StoryExcel = storyExcel; - ChallengeCountDown = storyExcel.TurnLimit; - } - - public void SetBossExcel(ChallengeBossExtraExcel bossExcel) - { - BossExcel = bossExcel; - } - - public override void Loaded() - { - // Cache challenge monsters - for (int i = 0; i < ConfigList1?.Count; i++) - { - if (ConfigList1[i] == 0) break; - - var Monster = new ChallengeMonsterInfo(ConfigList1[i], NpcMonsterIDList1![i], EventIDList1![i]); - ChallengeMonsters1.Add(Monster.ConfigId, Monster); - } - - for (int i = 0; i < ConfigList2?.Count; i++) - { - if (ConfigList2[i] == 0) break; - - var Monster = new ChallengeMonsterInfo(ConfigList2[i], NpcMonsterIDList2![i], EventIDList2![i]); - ChallengeMonsters2.Add(Monster.ConfigId, Monster); - } - - ConfigList1 = null; - NpcMonsterIDList1 = null; - EventIDList1 = null; - ConfigList2 = null; - NpcMonsterIDList2 = null; - EventIDList2 = null; - - GameData.ChallengeConfigData[ID] = this; - } - - public class ChallengeMonsterInfo(int ConfigId, int NpcMonsterId, int EventId) - { - public int ConfigId = ConfigId; - public int NpcMonsterId = NpcMonsterId; - public int EventId = EventId; - } + return ID; } -} + + public bool IsStory() + { + return StoryExcel != null; + } + + public bool IsBoss() + { + return BossExcel != null; + } + + public void SetStoryExcel(ChallengeStoryExtraExcel storyExcel) + { + StoryExcel = storyExcel; + ChallengeCountDown = storyExcel.TurnLimit; + } + + public void SetBossExcel(ChallengeBossExtraExcel bossExcel) + { + BossExcel = bossExcel; + } + + public override void Loaded() + { + // Cache challenge monsters + for (var i = 0; i < ConfigList1?.Count; i++) + { + if (ConfigList1[i] == 0) break; + + var Monster = new ChallengeMonsterInfo(ConfigList1[i], NpcMonsterIDList1![i], EventIDList1![i]); + ChallengeMonsters1.Add(Monster.ConfigId, Monster); + } + + for (var i = 0; i < ConfigList2?.Count; i++) + { + if (ConfigList2[i] == 0) break; + + var Monster = new ChallengeMonsterInfo(ConfigList2[i], NpcMonsterIDList2![i], EventIDList2![i]); + ChallengeMonsters2.Add(Monster.ConfigId, Monster); + } + + ConfigList1 = null; + NpcMonsterIDList1 = null; + EventIDList1 = null; + ConfigList2 = null; + NpcMonsterIDList2 = null; + EventIDList2 = null; + + GameData.ChallengeConfigData[ID] = this; + } + + public class ChallengeMonsterInfo(int ConfigId, int NpcMonsterId, int EventId) + { + public int ConfigId = ConfigId; + public int EventId = EventId; + public int NpcMonsterId = NpcMonsterId; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/ChallengeGroupExcel.cs b/Common/Data/Excel/ChallengeGroupExcel.cs index c0b1346f..6c831d3a 100644 --- a/Common/Data/Excel/ChallengeGroupExcel.cs +++ b/Common/Data/Excel/ChallengeGroupExcel.cs @@ -1,27 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ChallengeGroupConfig.json,ChallengeStoryGroupConfig.json,ChallengeBossGroupConfig.json", + true)] +public class ChallengeGroupExcel : ExcelResource { - [ResourceEntity("ChallengeGroupConfig.json,ChallengeStoryGroupConfig.json,ChallengeBossGroupConfig.json", - isMultifile: true)] - public class ChallengeGroupExcel : ExcelResource + public int GroupID { get; set; } + public int RewardLineGroupID { get; set; } + public int SchduleID { get; set; } + + public override int GetId() { - public int GroupID { get; set; } - public int RewardLineGroupID { get; set; } - public int SchduleID { get; set; } - - public override int GetId() - { - return GroupID; - } - - public override void Loaded() - { - GameData.ChallengeGroupData[GroupID] = this; - } + return GroupID; } -} + + public override void Loaded() + { + GameData.ChallengeGroupData[GroupID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/ChallengeRewardExcel.cs b/Common/Data/Excel/ChallengeRewardExcel.cs index 9a8ca75e..d3029596 100644 --- a/Common/Data/Excel/ChallengeRewardExcel.cs +++ b/Common/Data/Excel/ChallengeRewardExcel.cs @@ -1,30 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ChallengeMazeRewardLine.json,ChallengeStoryRewardLine.json", true)] +public class ChallengeRewardExcel : ExcelResource { - [ResourceEntity("ChallengeMazeRewardLine.json,ChallengeStoryRewardLine.json", isMultifile: true)] - public class ChallengeRewardExcel : ExcelResource + public int GroupID { get; set; } + public int StarCount { get; set; } + public int RewardID { get; set; } + + public override int GetId() { - public int GroupID { get; set; } - public int StarCount { get; set; } - public int RewardID { get; set; } - - public override int GetId() - { - return (GroupID << 16) + StarCount; - } - - public override void Loaded() - { - if (!GameData.ChallengeRewardData.ContainsKey(GroupID)) - { - GameData.ChallengeRewardData[GroupID] = new List(); - } - GameData.ChallengeRewardData[GroupID].Add(this); - } + return (GroupID << 16) + StarCount; } -} + + public override void Loaded() + { + if (!GameData.ChallengeRewardData.ContainsKey(GroupID)) + GameData.ChallengeRewardData[GroupID] = new List(); + GameData.ChallengeRewardData[GroupID].Add(this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/ChallengeStoryExtraExcel.cs b/Common/Data/Excel/ChallengeStoryExtraExcel.cs index 71e5eaa3..174e1a0a 100644 --- a/Common/Data/Excel/ChallengeStoryExtraExcel.cs +++ b/Common/Data/Excel/ChallengeStoryExtraExcel.cs @@ -1,26 +1,25 @@ -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("ChallengeStoryMazeExtra.json")] +public class ChallengeStoryExtraExcel : ExcelResource { - [ResourceEntity("ChallengeStoryMazeExtra.json")] - public class ChallengeStoryExtraExcel : ExcelResource + public int ID { get; set; } + public int TurnLimit { get; set; } + public int ClearScore { get; set; } + public List? BattleTargetID { get; set; } + + + public override int GetId() { - public int ID { get; set; } - public int TurnLimit { get; set; } - public int ClearScore { get; set; } - public List? BattleTargetID { get; set; } + return ID; + } - - public override int GetId() + public override void Loaded() + { + if (GameData.ChallengeConfigData.ContainsKey(ID)) { - return ID; - } - - public override void Loaded() - { - if (GameData.ChallengeConfigData.ContainsKey(ID)) - { - var challengeExcel = GameData.ChallengeConfigData[ID]; - challengeExcel.SetStoryExcel(this); - } + var challengeExcel = GameData.ChallengeConfigData[ID]; + challengeExcel.SetStoryExcel(this); } } -} +} \ No newline at end of file diff --git a/Common/Data/Excel/ChallengeTargetExcel.cs b/Common/Data/Excel/ChallengeTargetExcel.cs index 17f9e91e..5e0fed83 100644 --- a/Common/Data/Excel/ChallengeTargetExcel.cs +++ b/Common/Data/Excel/ChallengeTargetExcel.cs @@ -1,31 +1,31 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ChallengeTargetConfig.json,ChallengeStoryTargetConfig.json", true)] +public class ChallengeTargetExcel : ExcelResource { - [ResourceEntity("ChallengeTargetConfig.json,ChallengeStoryTargetConfig.json", isMultifile: true)] - public class ChallengeTargetExcel : ExcelResource + public enum ChallengeType { - public int ID { get; set; } - public ChallengeType ChallengeTargetType { get; set; } - public int ChallengeTargetParam1 { get; set; } - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.ChallengeTargetData[ID] = this; - } - - public enum ChallengeType - { - None, ROUNDS, DEAD_AVATAR, KILL_MONSTER, AVATAR_BASE_TYPE_MORE, AVATAR_BASE_TYPE_LESS, ROUNDS_LEFT, TOTAL_SCORE - } + None, + ROUNDS, + DEAD_AVATAR, + KILL_MONSTER, + AVATAR_BASE_TYPE_MORE, + AVATAR_BASE_TYPE_LESS, + ROUNDS_LEFT, + TOTAL_SCORE } -} + + public int ID { get; set; } + public ChallengeType ChallengeTargetType { get; set; } + public int ChallengeTargetParam1 { get; set; } + + public override int GetId() + { + return ID; + } + + public override void Loaded() + { + GameData.ChallengeTargetData[ID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/ChatBubbleConfigExcel.cs b/Common/Data/Excel/ChatBubbleConfigExcel.cs index a940375f..7a84c08f 100644 --- a/Common/Data/Excel/ChatBubbleConfigExcel.cs +++ b/Common/Data/Excel/ChatBubbleConfigExcel.cs @@ -1,24 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ChatBubbleConfig.json")] +public class ChatBubbleConfigExcel : ExcelResource { - [ResourceEntity("ChatBubbleConfig.json")] - public class ChatBubbleConfigExcel : ExcelResource + public int ID { get; set; } + + public override int GetId() { - public int ID { get; set; } - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.ChatBubbleConfigData[ID] = this; - } + return ID; } -} + + public override void Loaded() + { + GameData.ChatBubbleConfigData[ID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/CocoonConfigExcel.cs b/Common/Data/Excel/CocoonConfigExcel.cs index 2ae7c752..37c39703 100644 --- a/Common/Data/Excel/CocoonConfigExcel.cs +++ b/Common/Data/Excel/CocoonConfigExcel.cs @@ -1,27 +1,24 @@ -using EggLink.DanhengServer.Util; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("CocoonConfig.json")] +public class CocoonConfigExcel : ExcelResource { - [ResourceEntity("CocoonConfig.json")] - public class CocoonConfigExcel : ExcelResource + public int ID { get; set; } + public int MappingInfoID { get; set; } + public int WorldLevel { get; set; } + public int PropID { get; set; } + public int StaminaCost { get; set; } + public int MaxWave { get; set; } + public List StageIDList { get; set; } = []; + public List DropList { get; set; } = []; + + public override int GetId() { - public int ID { get; set; } - public int MappingInfoID { get; set; } - public int WorldLevel { get; set; } - public int PropID { get; set; } - public int StaminaCost { get; set; } - public int MaxWave { get; set; } - public List StageIDList { get; set; } = []; - public List DropList { get; set; } = []; - - public override int GetId() - { - return (ID * 100) + WorldLevel; - } - - public override void Loaded() - { - GameData.CocoonConfigData.Add(GetId(), this); - } + return ID * 100 + WorldLevel; } -} + + public override void Loaded() + { + GameData.CocoonConfigData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/ContentPackageConfigExcel.cs b/Common/Data/Excel/ContentPackageConfigExcel.cs index 40b04b76..15a25da7 100644 --- a/Common/Data/Excel/ContentPackageConfigExcel.cs +++ b/Common/Data/Excel/ContentPackageConfigExcel.cs @@ -1,24 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ContentPackageConfig.json")] +public class ContentPackageConfigExcel : ExcelResource { - [ResourceEntity("ContentPackageConfig.json")] - public class ContentPackageConfigExcel : ExcelResource + public int ContentID { get; set; } + + public override int GetId() { - public int ContentID { get; set; } - - public override int GetId() - { - return ContentID; - } - - public override void Loaded() - { - GameData.ContentPackageConfigData.Add(ContentID, this); - } + return ContentID; } -} + + public override void Loaded() + { + GameData.ContentPackageConfigData.Add(ContentID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/DialogueDynamicContentExcel.cs b/Common/Data/Excel/DialogueDynamicContentExcel.cs index 5df99e23..2ff8ad75 100644 --- a/Common/Data/Excel/DialogueDynamicContentExcel.cs +++ b/Common/Data/Excel/DialogueDynamicContentExcel.cs @@ -1,39 +1,31 @@ using EggLink.DanhengServer.Enums.Rogue; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("DialogueDynamicContent.json")] +public class DialogueDynamicContentExcel : ExcelResource { - [ResourceEntity("DialogueDynamicContent.json")] - public class DialogueDynamicContentExcel : ExcelResource + public int DynamicContentID { get; set; } + public int ArgID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public DialogueDynamicParamTypeEnum DynamicParamType { get; set; } + + public List DynamicParamList { get; set; } = []; + + public override int GetId() { - public int DynamicContentID { get; set; } - public int ArgID { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public DialogueDynamicParamTypeEnum DynamicParamType { get; set; } - public List DynamicParamList { get; set; } = []; - - public override int GetId() - { - return DynamicContentID; - } - - public override void Loaded() - { - if (GameData.DialogueDynamicContentData.TryGetValue(DynamicContentID, out Dictionary? value)) - { - value.Add(ArgID, this); - } - else - { - GameData.DialogueDynamicContentData.Add(DynamicContentID, new() { { ArgID, this } }); - } - } + return DynamicContentID; } -} + + public override void Loaded() + { + if (GameData.DialogueDynamicContentData.TryGetValue(DynamicContentID, out var value)) + value.Add(ArgID, this); + else + GameData.DialogueDynamicContentData.Add(DynamicContentID, + new Dictionary { { ArgID, this } }); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/DialogueEventExcel.cs b/Common/Data/Excel/DialogueEventExcel.cs index 9eedf417..56622549 100644 --- a/Common/Data/Excel/DialogueEventExcel.cs +++ b/Common/Data/Excel/DialogueEventExcel.cs @@ -2,32 +2,33 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("DialogueEvent.json")] +public class DialogueEventExcel : ExcelResource { - [ResourceEntity("DialogueEvent.json")] - public class DialogueEventExcel : ExcelResource + public int EventID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public DialogueEventTypeEnum RogueEffectType { get; set; } + + public List RogueEffectParamList { get; set; } = []; + + [JsonConverter(typeof(StringEnumConverter))] + public DialogueEventCostTypeEnum CostType { get; set; } + + public List CostParamList { get; set; } = []; + + public int DynamicContentID { get; set; } + public int DescValue { get; set; } + + public override int GetId() { - public int EventID { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public DialogueEventTypeEnum RogueEffectType { get; set; } - public List RogueEffectParamList { get; set; } = []; - - [JsonConverter(typeof(StringEnumConverter))] - public DialogueEventCostTypeEnum CostType { get; set; } - public List CostParamList { get; set; } = []; - - public int DynamicContentID { get; set; } - public int DescValue { get; set; } - - public override int GetId() - { - return EventID; - } - - public override void Loaded() - { - GameData.DialogueEventData.Add(EventID, this); - } + return EventID; } -} + + public override void Loaded() + { + GameData.DialogueEventData.Add(EventID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/EquipmentConfigExcel.cs b/Common/Data/Excel/EquipmentConfigExcel.cs index 09fe7759..e9516f9a 100644 --- a/Common/Data/Excel/EquipmentConfigExcel.cs +++ b/Common/Data/Excel/EquipmentConfigExcel.cs @@ -1,37 +1,29 @@ using EggLink.DanhengServer.Enums.Item; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using static EggLink.DanhengServer.Data.Excel.AvatarPromotionConfigExcel; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("EquipmentConfig.json")] +public class EquipmentConfigExcel : ExcelResource { - [ResourceEntity("EquipmentConfig.json")] - public class EquipmentConfigExcel : ExcelResource - { - public int EquipmentID { get; set; } - public bool Release { get; set; } - public int ExpType { get; set; } - public int MaxPromotion { get; set; } = 0; - public int MaxRank { get; set; } = 0; - [JsonConverter(typeof(StringEnumConverter))] - public RarityEnum Rarity { get; set; } = 0; - public override int GetId() - { - return EquipmentID; - } + public int EquipmentID { get; set; } + public bool Release { get; set; } + public int ExpType { get; set; } + public int MaxPromotion { get; set; } = 0; + public int MaxRank { get; set; } = 0; - public override void Loaded() - { - if (Release == false) - { - return; - } - GameData.EquipmentConfigData.Add(EquipmentID, this); - } + [JsonConverter(typeof(StringEnumConverter))] + public RarityEnum Rarity { get; set; } = 0; + + public override int GetId() + { + return EquipmentID; } -} + + public override void Loaded() + { + if (Release == false) return; + GameData.EquipmentConfigData.Add(EquipmentID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/EquipmentExpItemConfigExcel.cs b/Common/Data/Excel/EquipmentExpItemConfigExcel.cs index b0811ca3..b335c338 100644 --- a/Common/Data/Excel/EquipmentExpItemConfigExcel.cs +++ b/Common/Data/Excel/EquipmentExpItemConfigExcel.cs @@ -1,38 +1,25 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("EquipmentExpItemConfig.json")] +public class EquipmentExpItemConfigExcel : ExcelResource { - [ResourceEntity("EquipmentExpItemConfig.json")] - public class EquipmentExpItemConfigExcel : ExcelResource + public int ItemID { get; set; } + public int ExpProvide { get; set; } + + public override int GetId() { - public int ItemID { get; set; } - public int ExpProvide { get; set; } - - public override int GetId() - { - return ItemID; - } - - public override void Loaded() - { - if (ExpProvide > 0) - { - GameData.EquipmentExpItemConfigData.Add(GetId(), this); - } - } - - public override void AfterAllDone() - { - GameData.ItemConfigData.TryGetValue(ItemID, out ItemConfigExcel? itemConfig); - if (itemConfig == null) - { - return; - } - itemConfig.Exp = ExpProvide; - } + return ItemID; } -} + + public override void Loaded() + { + if (ExpProvide > 0) GameData.EquipmentExpItemConfigData.Add(GetId(), this); + } + + public override void AfterAllDone() + { + GameData.ItemConfigData.TryGetValue(ItemID, out var itemConfig); + if (itemConfig == null) return; + itemConfig.Exp = ExpProvide; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/EquipmentExpTypeExcel.cs b/Common/Data/Excel/EquipmentExpTypeExcel.cs index 2b614f1e..e5e670ed 100644 --- a/Common/Data/Excel/EquipmentExpTypeExcel.cs +++ b/Common/Data/Excel/EquipmentExpTypeExcel.cs @@ -1,26 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("EquipmentExpType.json")] +public class EquipmentExpTypeExcel : ExcelResource { - [ResourceEntity("EquipmentExpType.json")] - public class EquipmentExpTypeExcel : ExcelResource + public int ExpType { get; set; } + public int Level { get; set; } + public int Exp { get; set; } + + public override int GetId() { - public int ExpType { get; set; } - public int Level { get; set; } - public int Exp { get; set; } - - public override int GetId() - { - return ExpType * 100 + Level; - } - - public override void Loaded() - { - GameData.EquipmentExpTypeData.Add(GetId(), this); - } + return ExpType * 100 + Level; } -} + + public override void Loaded() + { + GameData.EquipmentExpTypeData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/EquipmentPromotionConfigExcel.cs b/Common/Data/Excel/EquipmentPromotionConfigExcel.cs index 7fc2f32f..20b31944 100644 --- a/Common/Data/Excel/EquipmentPromotionConfigExcel.cs +++ b/Common/Data/Excel/EquipmentPromotionConfigExcel.cs @@ -1,32 +1,27 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("EquipmentPromotionConfig.json")] +public class EquipmentPromotionConfigExcel : ExcelResource { - [ResourceEntity("EquipmentPromotionConfig.json")] - public class EquipmentPromotionConfigExcel : ExcelResource - { - public int EquipmentID { get; set; } - public int Promotion { get; set; } - public int MaxLevel { get; set; } - public int WorldLevelRequire { get; set; } - public List PromotionCostList { get; set; } = []; - public override int GetId() - { - return EquipmentID * 10 + Promotion; - } + public int EquipmentID { get; set; } + public int Promotion { get; set; } + public int MaxLevel { get; set; } + public int WorldLevelRequire { get; set; } + public List PromotionCostList { get; set; } = []; - public override void Loaded() - { - GameData.EquipmentPromotionConfigData.Add(GetId(), this); - } - public class ItemParam - { - public int ItemID; - public int ItemNum; - } + public override int GetId() + { + return EquipmentID * 10 + Promotion; } -} + + public override void Loaded() + { + GameData.EquipmentPromotionConfigData.Add(GetId(), this); + } + + public class ItemParam + { + public int ItemID; + public int ItemNum; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/ExpTypeExcel.cs b/Common/Data/Excel/ExpTypeExcel.cs index 6ef8b5c9..ab7ccdca 100644 --- a/Common/Data/Excel/ExpTypeExcel.cs +++ b/Common/Data/Excel/ExpTypeExcel.cs @@ -1,26 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ExpType.json")] +public class ExpTypeExcel : ExcelResource { - [ResourceEntity("ExpType.json")] - public class ExpTypeExcel : ExcelResource + public int TypeID { get; set; } + public int Level { get; set; } + public int Exp { get; set; } + + public override int GetId() { - public int TypeID { get; set; } - public int Level { get; set; } - public int Exp { get; set; } - - public override int GetId() - { - return (TypeID * 100) + Level; - } - - public override void Loaded() - { - GameData.ExpTypeData.Add(GetId(), this); - } + return TypeID * 100 + Level; } -} + + public override void Loaded() + { + GameData.ExpTypeData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/HeartDialDialogueExcel.cs b/Common/Data/Excel/HeartDialDialogueExcel.cs index b2b86f0d..8fed5805 100644 --- a/Common/Data/Excel/HeartDialDialogueExcel.cs +++ b/Common/Data/Excel/HeartDialDialogueExcel.cs @@ -1,24 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("HeartDialDialogue.json")] +public class HeartDialDialogueExcel : ExcelResource { - [ResourceEntity("HeartDialDialogue.json")] - public class HeartDialDialogueExcel : ExcelResource + public int ID { get; set; } + + public override int GetId() { - public int ID { get; set; } - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.HeartDialDialogueData[ID] = this; - } + return ID; } -} + + public override void Loaded() + { + GameData.HeartDialDialogueData[ID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/HeartDialScriptExcel.cs b/Common/Data/Excel/HeartDialScriptExcel.cs index 89d34890..4b4ffd40 100644 --- a/Common/Data/Excel/HeartDialScriptExcel.cs +++ b/Common/Data/Excel/HeartDialScriptExcel.cs @@ -1,35 +1,30 @@ using EggLink.DanhengServer.Enums.Mission; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("HeartDialScript.json")] +public class HeartDialScriptExcel : ExcelResource { - [ResourceEntity("HeartDialScript.json")] - public class HeartDialScriptExcel : ExcelResource + public int ScriptID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public HeartDialEmoTypeEnum DefaultEmoType { get; set; } = HeartDialEmoTypeEnum.Peace; + + [JsonProperty(ItemConverterType = typeof(StringEnumConverter))] + public List StepList { get; set; } = []; + + [JsonProperty(ItemConverterType = typeof(StringEnumConverter))] + public List MissingEmoList { get; set; } = []; + + public override int GetId() { - public int ScriptID { get; set; } - [JsonConverter(typeof(StringEnumConverter))] - public HeartDialEmoTypeEnum DefaultEmoType { get; set; } = HeartDialEmoTypeEnum.Peace; - - [JsonProperty(ItemConverterType = typeof(StringEnumConverter))] - public List StepList { get; set; } = []; - - [JsonProperty(ItemConverterType = typeof(StringEnumConverter))] - public List MissingEmoList { get; set; } = []; - - public override int GetId() - { - return ScriptID; - } - - public override void Loaded() - { - GameData.HeartDialScriptData[ScriptID] = this; - } + return ScriptID; } -} + + public override void Loaded() + { + GameData.HeartDialScriptData[ScriptID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/HeroConfigExcel.cs b/Common/Data/Excel/HeroConfigExcel.cs index c671b1e1..71093ac1 100644 --- a/Common/Data/Excel/HeroConfigExcel.cs +++ b/Common/Data/Excel/HeroConfigExcel.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +// Deprecated in 2.4, so we don't need to implement this class in this version (2.3) +public class HeroConfigExcel { - // Deprecated in 2.4, so we don't need to implement this class in this version (2.3) - public class HeroConfigExcel - { - } -} +} \ No newline at end of file diff --git a/Common/Data/Excel/InteractConfigExcel.cs b/Common/Data/Excel/InteractConfigExcel.cs index be4bcca5..03f5b7bb 100644 --- a/Common/Data/Excel/InteractConfigExcel.cs +++ b/Common/Data/Excel/InteractConfigExcel.cs @@ -1,28 +1,27 @@ -using EggLink.DanhengServer.Enums.Scene; +using System.Text.Json.Serialization; +using EggLink.DanhengServer.Enums.Scene; using Newtonsoft.Json.Converters; -using System.Text.Json.Serialization; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("InteractConfig.json")] +public class InteractConfigExcel : ExcelResource { - [ResourceEntity("InteractConfig.json")] - public class InteractConfigExcel : ExcelResource + public int InteractID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public PropStateEnum SrcState { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public PropStateEnum TargetState { get; set; } = PropStateEnum.Closed; + + public override int GetId() { - public int InteractID { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public PropStateEnum SrcState { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public PropStateEnum TargetState { get; set; } = PropStateEnum.Closed; - - public override int GetId() - { - return InteractID; - } - - public override void Loaded() - { - GameData.InteractConfigData.Add(InteractID, this); - } + return InteractID; } -} + + public override void Loaded() + { + GameData.InteractConfigData.Add(InteractID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/ItemComposeConfigExcel.cs b/Common/Data/Excel/ItemComposeConfigExcel.cs index 9debc2e4..22041a0a 100644 --- a/Common/Data/Excel/ItemComposeConfigExcel.cs +++ b/Common/Data/Excel/ItemComposeConfigExcel.cs @@ -1,33 +1,26 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ItemComposeConfig.json")] +public class ItemComposeConfigExcel : ExcelResource { - [ResourceEntity("ItemComposeConfig.json")] - public class ItemComposeConfigExcel : ExcelResource + public int ID { get; set; } + public int ItemID { get; set; } + public int CoinCost { get; set; } + public List MaterialCost { get; set; } = []; + + public override int GetId() { - public int ID { get; set; } - public int ItemID { get; set; } - public int CoinCost { get; set; } - public List MaterialCost { get; set; } = []; - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.ItemComposeConfigData[ID] = this; - } + return ID; } - public class MaterialItem + public override void Loaded() { - public int ItemID { get; set; } - public int ItemNum { get; set; } + GameData.ItemComposeConfigData[ID] = this; } } + +public class MaterialItem +{ + public int ItemID { get; set; } + public int ItemNum { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Excel/ItemConfigExcel.cs b/Common/Data/Excel/ItemConfigExcel.cs index 19b2456f..ce103081 100644 --- a/Common/Data/Excel/ItemConfigExcel.cs +++ b/Common/Data/Excel/ItemConfigExcel.cs @@ -2,45 +2,47 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("ItemConfig.json,ItemConfigAvatar.json,ItemConfigAvatarPlayerIcon.json," + + "ItemConfigAvatarRank.json,ItemConfigBook.json,ItemConfigDisk.json," + + "ItemConfigEquipment.json,ItemConfigRelic.json,ItemPlayerCard.json", true)] +public class ItemConfigExcel : ExcelResource { - [ResourceEntity("ItemConfig.json,ItemConfigAvatar.json,ItemConfigAvatarPlayerIcon.json," + - "ItemConfigAvatarRank.json,ItemConfigBook.json,ItemConfigDisk.json," + - "ItemConfigEquipment.json,ItemConfigRelic.json,ItemPlayerCard.json", isMultifile: true)] - public class ItemConfigExcel : ExcelResource + // General item data + public int ID { get; set; } + public HashName ItemName { get; set; } = new(); + + [JsonConverter(typeof(StringEnumConverter))] + public ItemMainTypeEnum ItemMainType { get; set; } = ItemMainTypeEnum.Unknown; + + [JsonConverter(typeof(StringEnumConverter))] + public ItemSubTypeEnum ItemSubType { get; set; } = ItemSubTypeEnum.Unknown; + + [JsonConverter(typeof(StringEnumConverter))] + public ItemRarityEnum Rarity { get; set; } = ItemRarityEnum.Unknown; + + public int PileLimit { get; set; } + public int PurposeType { get; set; } + + public int UseDataID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public ItemUseMethodEnum UseMethod { get; set; } + + public List ReturnItemIDList { get; set; } = []; + + [JsonIgnore] public int Exp { get; set; } + + [JsonIgnore] public string? Name { get; set; } + + public override int GetId() { - // General item data - public int ID { get; set; } - public HashName ItemName { get; set; } = new(); - [JsonConverter(typeof(StringEnumConverter))] - public ItemMainTypeEnum ItemMainType { get; set; } = ItemMainTypeEnum.Unknown; - [JsonConverter(typeof(StringEnumConverter))] - public ItemSubTypeEnum ItemSubType { get; set; } = ItemSubTypeEnum.Unknown; - [JsonConverter(typeof(StringEnumConverter))] - public ItemRarityEnum Rarity { get; set; } = ItemRarityEnum.Unknown; - public int PileLimit { get; set; } - public int PurposeType { get; set; } - - public int UseDataID { get; set; } - [JsonConverter(typeof(StringEnumConverter))] - public ItemUseMethodEnum UseMethod { get; set; } - - public List ReturnItemIDList { get; set; } = []; - - [JsonIgnore] - public int Exp { get; set; } - - [JsonIgnore] - public string? Name { get; set; } - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.ItemConfigData[ID] = this; - } + return ID; } -} + + public override void Loaded() + { + GameData.ItemConfigData[ID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MainMissionExcel.cs b/Common/Data/Excel/MainMissionExcel.cs index b7012d0b..e0a11d83 100644 --- a/Common/Data/Excel/MainMissionExcel.cs +++ b/Common/Data/Excel/MainMissionExcel.cs @@ -1,107 +1,105 @@ -using EggLink.DanhengServer.Data.Config; +using EggLink.DanhengServer.Database.Mission; +using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Enums; using Newtonsoft.Json; using Newtonsoft.Json.Converters; +using MissionInfo = EggLink.DanhengServer.Data.Config.MissionInfo; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MainMission.json")] +public class MainMissionExcel : ExcelResource { - [ResourceEntity("MainMission.json")] - public class MainMissionExcel : ExcelResource + public int MainMissionID { get; set; } + public HashName Name { get; set; } = new(); + + [JsonConverter(typeof(StringEnumConverter))] + public OperationEnum TakeOperation { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public OperationEnum BeginOperation { get; set; } + + public List TakeParam { get; set; } = []; + public List BeginParam { get; set; } = []; + public int RewardID { get; set; } + public List SubRewardList { get; set; } = []; + + [JsonIgnore] private MissionInfo? InnerMissionInfo { get; set; } + + [JsonIgnore] + public MissionInfo? MissionInfo { - public int MainMissionID { get; set; } - public HashName Name { get; set; } = new(); - [JsonConverter(typeof(StringEnumConverter))] - public OperationEnum TakeOperation { get; set; } - [JsonConverter(typeof(StringEnumConverter))] - public OperationEnum BeginOperation { get; set; } - - public List TakeParam { get; set; } = []; - public List BeginParam { get; set; } = []; - public int RewardID { get; set; } - public List SubRewardList { get; set; } = []; - - [JsonIgnore()] - private MissionInfo? InnerMissionInfo { get; set; } - [JsonIgnore()] - public MissionInfo? MissionInfo { get => InnerMissionInfo; set - { - InnerMissionInfo = value; - if (value != null) + get => InnerMissionInfo; + set + { + InnerMissionInfo = value; + if (value != null) + foreach (var sub in value.SubMissionList) { - foreach (var sub in value.SubMissionList) + SubMissionIds.Add(sub.ID); + GameData.SubMissionData.TryGetValue(sub.ID, out var subMission); + if (subMission != null) { - SubMissionIds.Add(sub.ID); - GameData.SubMissionData.TryGetValue(sub.ID, out var subMission); - if (subMission != null) - { - subMission.MainMissionID = MainMissionID; - subMission.MainMissionInfo = InnerMissionInfo; - subMission.SubMissionInfo = sub; - } + subMission.MainMissionID = MainMissionID; + subMission.MainMissionInfo = InnerMissionInfo; + subMission.SubMissionInfo = sub; } } - } - } - [JsonIgnore()] - public List SubMissionIds { get; set; } = []; - - - public override int GetId() - { - return MainMissionID; - } - - public override void Loaded() - { - GameData.MainMissionData[GetId()] = this; - } - - public bool IsEqual(Database.Mission.MissionData data) - { - var result = TakeOperation == OperationEnum.And; - foreach (var param in TakeParam) - { - if (param.IsEqual(data)) - { - if (TakeOperation != OperationEnum.And) - { - return true; - } - } - else - { - if (TakeOperation == OperationEnum.And) - { - return false; - } - } - } - return result; } } - public class MissionParam - { - [JsonConverter(typeof(StringEnumConverter))] - public MissionTakeTypeEnum Type { get; set; } - public int Value { get; set; } + [JsonIgnore] public List SubMissionIds { get; set; } = []; - public bool IsEqual(Database.Mission.MissionData data) - { - switch (Type) + + public override int GetId() + { + return MainMissionID; + } + + public override void Loaded() + { + GameData.MainMissionData[GetId()] = this; + } + + public bool IsEqual(MissionData data) + { + var result = TakeOperation == OperationEnum.And; + foreach (var param in TakeParam) + if (param.IsEqual(data)) { - case MissionTakeTypeEnum.Auto: - return true; - case MissionTakeTypeEnum.PlayerLevel: - return Database.Player.PlayerData.GetPlayerByUid(data.Uid)!.Level >= Value; - case MissionTakeTypeEnum.WorldLevel: - return Database.Player.PlayerData.GetPlayerByUid(data.Uid)!.WorldLevel >= Value; - case MissionTakeTypeEnum.MultiSequence: - var value = data.GetMainMissionStatus(Value); - return value == MissionPhaseEnum.Finish; - default: - return false; + if (TakeOperation != OperationEnum.And) return true; } - } + else + { + if (TakeOperation == OperationEnum.And) return false; + } + + return result; } } + +public class MissionParam +{ + [JsonConverter(typeof(StringEnumConverter))] + public MissionTakeTypeEnum Type { get; set; } + + public int Value { get; set; } + + public bool IsEqual(MissionData data) + { + switch (Type) + { + case MissionTakeTypeEnum.Auto: + return true; + case MissionTakeTypeEnum.PlayerLevel: + return PlayerData.GetPlayerByUid(data.Uid)!.Level >= Value; + case MissionTakeTypeEnum.WorldLevel: + return PlayerData.GetPlayerByUid(data.Uid)!.WorldLevel >= Value; + case MissionTakeTypeEnum.MultiSequence: + var value = data.GetMainMissionStatus(Value); + return value == MissionPhaseEnum.Finish; + default: + return false; + } + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MapEntranceExcel.cs b/Common/Data/Excel/MapEntranceExcel.cs index 295b3a33..d493c104 100644 --- a/Common/Data/Excel/MapEntranceExcel.cs +++ b/Common/Data/Excel/MapEntranceExcel.cs @@ -1,25 +1,24 @@ -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MapEntrance.json", true)] +public class MapEntranceExcel : ExcelResource { - [ResourceEntity("MapEntrance.json", true)] - public class MapEntranceExcel : ExcelResource + public int ID { get; set; } + public int PlaneID { get; set; } + public int FloorID { get; set; } + public int StartGroupID { get; set; } + public int StartAnchorID { get; set; } + + public List FinishMainMissionList { get; set; } = []; + public List FinishSubMissionList { get; set; } = []; + + public override int GetId() { - public int ID { get; set; } - public int PlaneID { get; set; } - public int FloorID { get; set; } - public int StartGroupID { get; set; } - public int StartAnchorID { get; set; } - - public List FinishMainMissionList { get; set; } = []; - public List FinishSubMissionList { get; set; } = []; - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.MapEntranceData.Add(ID, this); - } + return ID; } -} + + public override void Loaded() + { + GameData.MapEntranceData.Add(ID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MappingInfoExcel.cs b/Common/Data/Excel/MappingInfoExcel.cs index 078b64fe..b8cc180f 100644 --- a/Common/Data/Excel/MappingInfoExcel.cs +++ b/Common/Data/Excel/MappingInfoExcel.cs @@ -2,212 +2,205 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MappingInfo.json")] +public class MappingInfoExcel : ExcelResource { - [ResourceEntity("MappingInfo.json")] - public class MappingInfoExcel : ExcelResource + public int ID { get; set; } + public int WorldLevel { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public FarmTypeEnum FarmType { get; set; } = FarmTypeEnum.None; // is enum + + public List DisplayItemList { get; set; } = []; + + [JsonIgnore] public List DropItemList { get; set; } = []; + + [JsonIgnore] public List DropRelicItemList { get; set; } = []; + + public override int GetId() { - public int ID { get; set; } - public int WorldLevel { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public FarmTypeEnum FarmType { get; set; } = FarmTypeEnum.None; // is enum - - public List DisplayItemList { get; set; } = []; - - [JsonIgnore] - public List DropItemList { get; set; } = []; - [JsonIgnore] - public List DropRelicItemList { get; set; } = []; - - public override int GetId() - { - return ID * 10 + WorldLevel; - } - - public override void Loaded() - { - GameData.MappingInfoData.Add(GetId(), this); - if (DisplayItemList.Count == 0) return; - - List equipDrop = []; - Dictionary> relicDrop = []; - - foreach (var item in DisplayItemList) - { - if (item.ItemNum > 0) - { - DropItemList.Add(item); - continue; - } - - if (item.ItemID == 2) - { - DropItemList.Add(new MappingInfoItem() // random credit - { - ItemID = 2, - MinCount = (50 + (WorldLevel * 10)) * (int)FarmType, - MaxCount = (100 + (WorldLevel * 10)) * (int)FarmType - }); - - continue; - } - - GameData.ItemConfigData.TryGetValue(item.ItemID, out var excel); - if (excel == null) continue; - - if (excel.ItemSubType == ItemSubTypeEnum.RelicSetShowOnly) - { - int baseRelicId = (item.ItemID / 10) % 1000; - int baseRarity = item.ItemID % 10; - - // Add relics from the set - int relicStart = 20001 + (baseRarity * 10000) + (baseRelicId * 10); - int relicEnd = relicStart + 3; - for (; relicStart <= relicEnd; relicStart++) - { - GameData.ItemConfigData.TryGetValue(relicStart, out var relicExcel); - if (relicExcel == null) break; - - - if (!relicDrop.TryGetValue(baseRarity, out List? _)) - { - var value = new List(); - relicDrop[baseRarity] = value; - } - - relicDrop[baseRarity].Add(relicStart); - } - } - else if (excel.ItemMainType == ItemMainTypeEnum.Material) - { - // Calculate amount to drop by purpose level - MappingInfoItem? drop; - switch (excel.PurposeType) - { - // Avatar exp. Drop rate is guessed (with data) - case 1: - // Calc amount - double amount = excel.Rarity switch - { - ItemRarityEnum.NotNormal => WorldLevel < 3 ? WorldLevel + 3 : 2.5, - ItemRarityEnum.Rare => WorldLevel < 3 ? WorldLevel + 3 : (WorldLevel * 2) - 3, - _ => 1 - }; - - drop = new(excel.ID, (int)amount); - break; - // Boss materials - case 2: - drop = new(excel.ID, WorldLevel); - break; - // Trace materials. Drop rate is guessed (with data) - case 3: - drop = new(excel.ID, 5); - break; - // Boss Trace materials. Drop rate is guessed (with data) - case 4: - drop = new(excel.ID, (int)((WorldLevel * 0.5) + 0.5)); - break; - // Lightcone exp. Drop rate is guessed (with data) - case 5: - // Calc amount - double count = excel.Rarity switch - { - ItemRarityEnum.NotNormal =>Math.Max(5 - WorldLevel, 2.5), - ItemRarityEnum.Rare => (WorldLevel % 3) + 1, - _ => 1 - }; - - drop = new(excel.ID, (int)count); - break; - // Lucent afterglow - case 11: - drop = new(excel.ID, 4 + WorldLevel); - break; - // Unknown - default: - drop = null; - break; - }; - - // Add to drop list - if (drop != null) - { - DropItemList.Add(drop); - } - } - else if (excel.ItemMainType == ItemMainTypeEnum.Equipment) - { - // Add lightcones - equipDrop.Add(excel.ID); - } - - - // Add equipment drops - if (equipDrop.Count > 0) - { - foreach (var dropId in equipDrop) - { - MappingInfoItem drop = new(dropId, 1) - { - Chance = (WorldLevel * 10) + 40 - }; - DropItemList.Add(drop); - } - } - - // Add relic drops - if (relicDrop.Count > 0) - { - foreach (var entry in relicDrop) - { - // Add items to drop param - foreach (var value in entry.Value) - { - MappingInfoItem drop = new(value, 1); - - // Set count by rarity - double amount = entry.Key switch - { - 4 => - (WorldLevel * 0.5) - 0.5, - 3 => - (WorldLevel * 0.5) + (WorldLevel == 2 ? 1.0 : 0), - 2 => - (6 - WorldLevel) + 0.5 - (WorldLevel == 1 ? 3.75 : 0), - _ => - WorldLevel == 1 ? 6 : 2, - }; - - // Set amount - if (amount > 0) - { - drop.ItemNum = (int)amount; - DropRelicItemList.Add(drop); - } - } - } - } - } - } + return ID * 10 + WorldLevel; } - public class MappingInfoItem + public override void Loaded() { - public int ItemID { get; set; } - public int ItemNum { get; set; } + GameData.MappingInfoData.Add(GetId(), this); + if (DisplayItemList.Count == 0) return; - public int MinCount { get; set; } - public int MaxCount { get; set; } - public int Chance { get; set; } = 100; + List equipDrop = []; + Dictionary> relicDrop = []; - public MappingInfoItem() { } - - public MappingInfoItem(int itemId, int itemNum) + foreach (var item in DisplayItemList) { - ItemID = itemId; - ItemNum = itemNum; + if (item.ItemNum > 0) + { + DropItemList.Add(item); + continue; + } + + if (item.ItemID == 2) + { + DropItemList.Add(new MappingInfoItem() // random credit + { + ItemID = 2, + MinCount = (50 + WorldLevel * 10) * (int)FarmType, + MaxCount = (100 + WorldLevel * 10) * (int)FarmType + }); + + continue; + } + + GameData.ItemConfigData.TryGetValue(item.ItemID, out var excel); + if (excel == null) continue; + + if (excel.ItemSubType == ItemSubTypeEnum.RelicSetShowOnly) + { + var baseRelicId = item.ItemID / 10 % 1000; + var baseRarity = item.ItemID % 10; + + // Add relics from the set + var relicStart = 20001 + baseRarity * 10000 + baseRelicId * 10; + var relicEnd = relicStart + 3; + for (; relicStart <= relicEnd; relicStart++) + { + GameData.ItemConfigData.TryGetValue(relicStart, out var relicExcel); + if (relicExcel == null) break; + + + if (!relicDrop.TryGetValue(baseRarity, out var _)) + { + var value = new List(); + relicDrop[baseRarity] = value; + } + + relicDrop[baseRarity].Add(relicStart); + } + } + else if (excel.ItemMainType == ItemMainTypeEnum.Material) + { + // Calculate amount to drop by purpose level + MappingInfoItem? drop; + switch (excel.PurposeType) + { + // Avatar exp. Drop rate is guessed (with data) + case 1: + // Calc amount + var amount = excel.Rarity switch + { + ItemRarityEnum.NotNormal => WorldLevel < 3 ? WorldLevel + 3 : 2.5, + ItemRarityEnum.Rare => WorldLevel < 3 ? WorldLevel + 3 : WorldLevel * 2 - 3, + _ => 1 + }; + + drop = new MappingInfoItem(excel.ID, (int)amount); + break; + // Boss materials + case 2: + drop = new MappingInfoItem(excel.ID, WorldLevel); + break; + // Trace materials. Drop rate is guessed (with data) + case 3: + drop = new MappingInfoItem(excel.ID, 5); + break; + // Boss Trace materials. Drop rate is guessed (with data) + case 4: + drop = new MappingInfoItem(excel.ID, (int)(WorldLevel * 0.5 + 0.5)); + break; + // Lightcone exp. Drop rate is guessed (with data) + case 5: + // Calc amount + var count = excel.Rarity switch + { + ItemRarityEnum.NotNormal => Math.Max(5 - WorldLevel, 2.5), + ItemRarityEnum.Rare => WorldLevel % 3 + 1, + _ => 1 + }; + + drop = new MappingInfoItem(excel.ID, (int)count); + break; + // Lucent afterglow + case 11: + drop = new MappingInfoItem(excel.ID, 4 + WorldLevel); + break; + // Unknown + default: + drop = null; + break; + } + + ; + + // Add to drop list + if (drop != null) DropItemList.Add(drop); + } + else if (excel.ItemMainType == ItemMainTypeEnum.Equipment) + { + // Add lightcones + equipDrop.Add(excel.ID); + } + + + // Add equipment drops + if (equipDrop.Count > 0) + foreach (var dropId in equipDrop) + { + MappingInfoItem drop = new(dropId, 1) + { + Chance = WorldLevel * 10 + 40 + }; + DropItemList.Add(drop); + } + + // Add relic drops + if (relicDrop.Count > 0) + foreach (var entry in relicDrop) + // Add items to drop param + foreach (var value in entry.Value) + { + MappingInfoItem drop = new(value, 1); + + // Set count by rarity + var amount = entry.Key switch + { + 4 => + WorldLevel * 0.5 - 0.5, + 3 => + WorldLevel * 0.5 + (WorldLevel == 2 ? 1.0 : 0), + 2 => + 6 - WorldLevel + 0.5 - (WorldLevel == 1 ? 3.75 : 0), + _ => + WorldLevel == 1 ? 6 : 2 + }; + + // Set amount + if (amount > 0) + { + drop.ItemNum = (int)amount; + DropRelicItemList.Add(drop); + } + } } } } + +public class MappingInfoItem +{ + public MappingInfoItem() + { + } + + public MappingInfoItem(int itemId, int itemNum) + { + ItemID = itemId; + ItemNum = itemNum; + } + + public int ItemID { get; set; } + public int ItemNum { get; set; } + + public int MinCount { get; set; } + public int MaxCount { get; set; } + public int Chance { get; set; } = 100; +} \ No newline at end of file diff --git a/Common/Data/Excel/MazeBuffExcel.cs b/Common/Data/Excel/MazeBuffExcel.cs index f5c8507d..9151dd0c 100644 --- a/Common/Data/Excel/MazeBuffExcel.cs +++ b/Common/Data/Excel/MazeBuffExcel.cs @@ -1,35 +1,29 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MazeBuff.json")] +public class MazeBuffExcel : ExcelResource { - [ResourceEntity("MazeBuff.json")] - public class MazeBuffExcel : ExcelResource + public int ID { get; set; } + public int Lv { get; set; } + + public override int GetId() { - public int ID { get; set; } - public int Lv { get; set; } - - public override int GetId() - { - return ID * 10 + Lv; - } - - public override void Loaded() - { - GameData.MazeBuffData.Add(GetId(), this); - } - - public BattleBuff ToProto() - { - return new BattleBuff() - { - Id = (uint)ID, - Level = (uint)Lv, - }; - } + return ID * 10 + Lv; } -} + + public override void Loaded() + { + GameData.MazeBuffData.Add(GetId(), this); + } + + public BattleBuff ToProto() + { + return new BattleBuff + { + Id = (uint)ID, + Level = (uint)Lv + }; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MazePlaneExcel.cs b/Common/Data/Excel/MazePlaneExcel.cs index 744e1e8f..cf9136f5 100644 --- a/Common/Data/Excel/MazePlaneExcel.cs +++ b/Common/Data/Excel/MazePlaneExcel.cs @@ -1,33 +1,27 @@ using EggLink.DanhengServer.Enums.Scene; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MazePlane.json", true)] +public class MazePlaneExcel : ExcelResource { - [ResourceEntity("MazePlane.json", true)] - public class MazePlaneExcel : ExcelResource + public int PlaneID { get; set; } + public int WorldID { get; set; } + public int StartFloorID { get; set; } + public HashName PlaneName { get; set; } = new(); + + [JsonConverter(typeof(StringEnumConverter))] + public PlaneTypeEnum PlaneType { get; set; } + + public override int GetId() { - public int PlaneID { get; set; } - public int WorldID { get; set; } - public int StartFloorID { get; set; } - public HashName PlaneName { get; set; } = new(); - - [JsonConverter(typeof(StringEnumConverter))] - public PlaneTypeEnum PlaneType { get; set; } - - public override int GetId() - { - return PlaneID; - } - - public override void Loaded() - { - GameData.MazePlaneData.Add(PlaneID, this); - } + return PlaneID; } -} + + public override void Loaded() + { + GameData.MazePlaneData.Add(PlaneID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MazePropExcel.cs b/Common/Data/Excel/MazePropExcel.cs index a5c9fba4..e002d215 100644 --- a/Common/Data/Excel/MazePropExcel.cs +++ b/Common/Data/Excel/MazePropExcel.cs @@ -1,53 +1,42 @@ using EggLink.DanhengServer.Enums.Scene; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MazeProp.json")] +public class MazePropExcel : ExcelResource { - [ResourceEntity("MazeProp.json")] - public class MazePropExcel : ExcelResource + public bool IsDoor; + + public bool IsHpRecover; + public bool IsMpRecover; + public int ID { get; set; } + public HashName PropName { get; set; } = new(); + public string JsonPath { get; set; } = ""; + + [JsonConverter(typeof(StringEnumConverter))] + public PropTypeEnum PropType { get; set; } + + [JsonProperty(ItemConverterType = typeof(StringEnumConverter))] + public List PropStateList { get; set; } = []; + + public override int GetId() { - public int ID { get; set; } - public HashName PropName { get; set; } = new(); - public string JsonPath { get; set; } = ""; - - [JsonConverter(typeof(StringEnumConverter))] - public PropTypeEnum PropType { get; set; } - - [JsonProperty(ItemConverterType = typeof(StringEnumConverter))] - public List PropStateList { get; set; } = []; - - public bool IsHpRecover = false; - public bool IsMpRecover = false; - public bool IsDoor = false; - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - if (JsonPath != "") - { - if (JsonPath.Contains("MPBox") || JsonPath.Contains("MPRecover")) - { - IsMpRecover = true; - } else if (JsonPath.Contains("HPBox") || JsonPath.Contains("HPRecover")) - { - IsHpRecover = true; - } else if (JsonPath.Contains("_Door_")) - { - IsDoor = true; - } - } - - GameData.MazePropData.Add(ID, this); - } + return ID; } -} + + public override void Loaded() + { + if (JsonPath != "") + { + if (JsonPath.Contains("MPBox") || JsonPath.Contains("MPRecover")) + IsMpRecover = true; + else if (JsonPath.Contains("HPBox") || JsonPath.Contains("HPRecover")) + IsHpRecover = true; + else if (JsonPath.Contains("_Door_")) IsDoor = true; + } + + GameData.MazePropData.Add(ID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MessageContactsConfigExcel.cs b/Common/Data/Excel/MessageContactsConfigExcel.cs index 9ba9593c..5f8649d2 100644 --- a/Common/Data/Excel/MessageContactsConfigExcel.cs +++ b/Common/Data/Excel/MessageContactsConfigExcel.cs @@ -1,28 +1,21 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MessageContactsConfig.json")] +public class MessageContactsConfigExcel : ExcelResource { - [ResourceEntity("MessageContactsConfig.json")] - public class MessageContactsConfigExcel : ExcelResource + public int ID { get; set; } + + [JsonIgnore] public List Groups { get; set; } = []; + + public override int GetId() { - public int ID { get; set; } - - [JsonIgnore] - public List Groups { get; set; } = []; - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.MessageContactsConfigData.Add(ID, this); - } + return ID; } -} + + public override void Loaded() + { + GameData.MessageContactsConfigData.Add(ID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MessageGroupConfigExcel.cs b/Common/Data/Excel/MessageGroupConfigExcel.cs index c752c236..ddf5ea22 100644 --- a/Common/Data/Excel/MessageGroupConfigExcel.cs +++ b/Common/Data/Excel/MessageGroupConfigExcel.cs @@ -1,39 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("MessageGroupConfig.json")] +public class MessageGroupConfigExcel : ExcelResource { - [ResourceEntity("MessageGroupConfig.json")] - public class MessageGroupConfigExcel : ExcelResource + public int ID { get; set; } + public int MessageContactsID { get; set; } + public List MessageSectionIDList { get; set; } = []; + + public override int GetId() { - public int ID { get; set; } - public int MessageContactsID { get; set; } - public List MessageSectionIDList { get; set; } = []; - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.MessageGroupConfigData.Add(ID, this); - } - - public override void AfterAllDone() - { - GameData.MessageContactsConfigData[MessageContactsID].Groups.Add(this); - MessageSectionIDList.ForEach(m => - { - GameData.MessageSectionConfigData.TryGetValue(m, out var section); - if (section != null) - { - section.GroupID = ID; - } - }); - } + return ID; } -} + + public override void Loaded() + { + GameData.MessageGroupConfigData.Add(ID, this); + } + + public override void AfterAllDone() + { + GameData.MessageContactsConfigData[MessageContactsID].Groups.Add(this); + MessageSectionIDList.ForEach(m => + { + GameData.MessageSectionConfigData.TryGetValue(m, out var section); + if (section != null) section.GroupID = ID; + }); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MessageItemConfigExcel.cs b/Common/Data/Excel/MessageItemConfigExcel.cs index 538a8344..af3920f7 100644 --- a/Common/Data/Excel/MessageItemConfigExcel.cs +++ b/Common/Data/Excel/MessageItemConfigExcel.cs @@ -1,39 +1,32 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MessageItemConfig.json")] +public class MessageItemConfigExcel : ExcelResource { - [ResourceEntity("MessageItemConfig.json")] - public class MessageItemConfigExcel : ExcelResource + public int ID { get; set; } + public List NextItemIDList { get; set; } = []; + public int SectionID { get; set; } + + [JsonIgnore] public int GroupID { get; set; } + + public override int GetId() { - public int ID { get; set; } - public List NextItemIDList { get; set; } = []; - public int SectionID { get; set; } + return ID; + } - [JsonIgnore] - public int GroupID { get; set; } + public override void Loaded() + { + GameData.MessageItemConfigData.Add(ID, this); + } - public override int GetId() + public override void AfterAllDone() + { + if (GameData.MessageSectionConfigData.TryGetValue(SectionID, out var value)) { - return ID; - } - - public override void Loaded() - { - GameData.MessageItemConfigData.Add(ID, this); - } - - public override void AfterAllDone() - { - if (GameData.MessageSectionConfigData.TryGetValue(SectionID, out MessageSectionConfigExcel? value)) - { - value.Items.Add(this); - GroupID = value.GroupID; - } + value.Items.Add(this); + GroupID = value.GroupID; } } -} +} \ No newline at end of file diff --git a/Common/Data/Excel/MessageSectionConfigExcel.cs b/Common/Data/Excel/MessageSectionConfigExcel.cs index 051d4111..cac83822 100644 --- a/Common/Data/Excel/MessageSectionConfigExcel.cs +++ b/Common/Data/Excel/MessageSectionConfigExcel.cs @@ -1,34 +1,26 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MessageSectionConfig.json")] +public class MessageSectionConfigExcel : ExcelResource { - [ResourceEntity("MessageSectionConfig.json")] - public class MessageSectionConfigExcel : ExcelResource + public int ID { get; set; } + public List StartMessageItemIDList { get; set; } = []; + public bool IsPerformMessage { get; set; } + public int MainMissionLink { get; set; } + + [JsonIgnore] public List Items { get; set; } = []; + + [JsonIgnore] public int GroupID { get; set; } + + public override int GetId() { - public int ID { get; set; } - public List StartMessageItemIDList { get; set; } = []; - public bool IsPerformMessage { get; set; } - public int MainMissionLink { get; set; } - - [JsonIgnore] - public List Items { get; set; } = []; - - [JsonIgnore] - public int GroupID { get; set; } - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.MessageSectionConfigData.Add(ID, this); - } + return ID; } -} + + public override void Loaded() + { + GameData.MessageSectionConfigData.Add(ID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MonsterConfigExcel.cs b/Common/Data/Excel/MonsterConfigExcel.cs index ec058d11..c29366ad 100644 --- a/Common/Data/Excel/MonsterConfigExcel.cs +++ b/Common/Data/Excel/MonsterConfigExcel.cs @@ -1,24 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("MonsterConfig.json")] +public class MonsterConfigExcel : ExcelResource { - [ResourceEntity("MonsterConfig.json")] - public class MonsterConfigExcel : ExcelResource + public int MonsterID { get; set; } + + public override int GetId() { - public int MonsterID { get; set; } - - public override int GetId() - { - return MonsterID; - } - - public override void Loaded() - { - GameData.MonsterConfigData.Add(MonsterID, this); - } + return MonsterID; } -} + + public override void Loaded() + { + GameData.MonsterConfigData.Add(MonsterID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/MonsterDropExcel.cs b/Common/Data/Excel/MonsterDropExcel.cs index 0b117828..a39688fd 100644 --- a/Common/Data/Excel/MonsterDropExcel.cs +++ b/Common/Data/Excel/MonsterDropExcel.cs @@ -1,78 +1,72 @@ using EggLink.DanhengServer.Database.Inventory; using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("MonsterDrop.json")] +public class MonsterDropExcel : ExcelResource { - [ResourceEntity("MonsterDrop.json")] - public class MonsterDropExcel : ExcelResource + public int MonsterTemplateID { get; set; } + public int WorldLevel { get; set; } + public int AvatarExpReward { get; set; } + + public List DisplayItemList { get; set; } = []; + + [JsonIgnore] public List DropItemList { get; set; } = []; + + public override int GetId() { - public int MonsterTemplateID { get; set; } - public int WorldLevel { get; set; } - public int AvatarExpReward { get; set; } - - public List DisplayItemList { get; set; } = []; - - [JsonIgnore] - public List DropItemList { get; set; } = []; - - public override int GetId() - { - return MonsterTemplateID * 10 + WorldLevel; - } - - public override void AfterAllDone() - { - foreach (var item in DisplayItemList) - { - GameData.ItemConfigData.TryGetValue(item.ItemID, out var config); - if (config == null) continue; - //double mod = config.Rarity switch - //{ - // Enums.ItemRarityEnum.NotNormal => 0.8, - // Enums.ItemRarityEnum.Rare => 0.3, - // Enums.ItemRarityEnum.VeryRare => 0.125, - // Enums.ItemRarityEnum.SuperRare => 0, - // _ => 1, - //}; - double mod = 1; // TODO: Implement rarity - double count = WorldLevel + 3; - var maxCount = (int)(count * mod); - var minCount = (int)(count * mod * 0.5); - item.MinCount = minCount; - item.MaxCount = maxCount; - DropItemList.Add(item); - } - GameData.MonsterDropData.Add(GetId(), this); - } - - public List CalculateDrop() - { - var result = new List(); - foreach (var item in DropItemList) - { - var count = Random.Shared.Next(item.MinCount, item.MaxCount + 1); - result.Add(new ItemData() - { - ItemId = item.ItemID, - Count = count, - }); - } - - return result; - } + return MonsterTemplateID * 10 + WorldLevel; } - public class MonsterDropItem + public override void AfterAllDone() { - public int ItemID { get; set; } - [JsonIgnore] - public int MinCount { get; set; } - [JsonIgnore] - public int MaxCount { get; set; } + foreach (var item in DisplayItemList) + { + GameData.ItemConfigData.TryGetValue(item.ItemID, out var config); + if (config == null) continue; + //double mod = config.Rarity switch + //{ + // Enums.ItemRarityEnum.NotNormal => 0.8, + // Enums.ItemRarityEnum.Rare => 0.3, + // Enums.ItemRarityEnum.VeryRare => 0.125, + // Enums.ItemRarityEnum.SuperRare => 0, + // _ => 1, + //}; + double mod = 1; // TODO: Implement rarity + double count = WorldLevel + 3; + var maxCount = (int)(count * mod); + var minCount = (int)(count * mod * 0.5); + item.MinCount = minCount; + item.MaxCount = maxCount; + DropItemList.Add(item); + } + + GameData.MonsterDropData.Add(GetId(), this); + } + + public List CalculateDrop() + { + var result = new List(); + foreach (var item in DropItemList) + { + var count = Random.Shared.Next(item.MinCount, item.MaxCount + 1); + result.Add(new ItemData + { + ItemId = item.ItemID, + Count = count + }); + } + + return result; } } + +public class MonsterDropItem +{ + public int ItemID { get; set; } + + [JsonIgnore] public int MinCount { get; set; } + + [JsonIgnore] public int MaxCount { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Excel/NPCDataExcel.cs b/Common/Data/Excel/NPCDataExcel.cs index b48b3f1a..46b08838 100644 --- a/Common/Data/Excel/NPCDataExcel.cs +++ b/Common/Data/Excel/NPCDataExcel.cs @@ -1,24 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("NPCData.json")] +public class NPCDataExcel : ExcelResource { - [ResourceEntity("NPCData.json")] - public class NPCDataExcel : ExcelResource + public int ID { get; set; } + + public override int GetId() { - public int ID { get; set; } - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.NpcDataData.Add(ID, this); - } + return ID; } -} + + public override void Loaded() + { + GameData.NpcDataData.Add(ID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/NPCMonsterDataExcel.cs b/Common/Data/Excel/NPCMonsterDataExcel.cs index 07165281..395f33e3 100644 --- a/Common/Data/Excel/NPCMonsterDataExcel.cs +++ b/Common/Data/Excel/NPCMonsterDataExcel.cs @@ -1,31 +1,25 @@ using EggLink.DanhengServer.Enums.Scene; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("NPCMonsterData.json")] +public class NPCMonsterDataExcel : ExcelResource { - [ResourceEntity("NPCMonsterData.json")] - public class NPCMonsterDataExcel : ExcelResource - { - public int ID { get; set; } - public HashName NPCName { get; set; } = new(); + public int ID { get; set; } + public HashName NPCName { get; set; } = new(); - [JsonConverter(typeof(StringEnumConverter))] - public MonsterRankEnum Rank { get; set; } + [JsonConverter(typeof(StringEnumConverter))] + public MonsterRankEnum Rank { get; set; } - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.NpcMonsterDataData.Add(ID, this); - } + public override int GetId() + { + return ID; } -} + + public override void Loaded() + { + GameData.NpcMonsterDataData.Add(ID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/PerformanceDExcel.cs b/Common/Data/Excel/PerformanceDExcel.cs index 48f8a5ba..c0a942c2 100644 --- a/Common/Data/Excel/PerformanceDExcel.cs +++ b/Common/Data/Excel/PerformanceDExcel.cs @@ -1,30 +1,23 @@ using EggLink.DanhengServer.Data.Config; using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("PerformanceD.json")] +public class PerformanceDExcel : ExcelResource { - [ResourceEntity("PerformanceD.json")] - public class PerformanceDExcel : ExcelResource + public int PerformanceID { get; set; } + public string PerformancePath { get; set; } = ""; + + [JsonIgnore] public LevelGraphConfigInfo? ActInfo { get; set; } + + public override int GetId() { - public int PerformanceID { get; set; } - public string PerformancePath { get; set; } = ""; - - [JsonIgnore] - public LevelGraphConfigInfo? ActInfo { get; set; } - - public override int GetId() - { - return PerformanceID; - } - - public override void Loaded() - { - GameData.PerformanceDData.Add(PerformanceID, this); - } + return PerformanceID; } -} + + public override void Loaded() + { + GameData.PerformanceDData.Add(PerformanceID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/PerformanceEExcel.cs b/Common/Data/Excel/PerformanceEExcel.cs index 20ee742b..9c6ea73f 100644 --- a/Common/Data/Excel/PerformanceEExcel.cs +++ b/Common/Data/Excel/PerformanceEExcel.cs @@ -1,30 +1,23 @@ using EggLink.DanhengServer.Data.Config; using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("PerformanceE.json")] +public class PerformanceEExcel : ExcelResource { - [ResourceEntity("PerformanceE.json")] - public class PerformanceEExcel : ExcelResource + public int PerformanceID { get; set; } + public string PerformancePath { get; set; } = ""; + + [JsonIgnore] public LevelGraphConfigInfo? ActInfo { get; set; } + + public override int GetId() { - public int PerformanceID { get; set; } - public string PerformancePath { get; set; } = ""; - - [JsonIgnore] - public LevelGraphConfigInfo? ActInfo { get; set; } - - public override int GetId() - { - return PerformanceID; - } - - public override void Loaded() - { - GameData.PerformanceEData.Add(PerformanceID, this); - } + return PerformanceID; } -} + + public override void Loaded() + { + GameData.PerformanceEData.Add(PerformanceID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/PlaneEventExcel.cs b/Common/Data/Excel/PlaneEventExcel.cs index 6c0cd447..42574c30 100644 --- a/Common/Data/Excel/PlaneEventExcel.cs +++ b/Common/Data/Excel/PlaneEventExcel.cs @@ -1,28 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("PlaneEvent.json")] +public class PlaneEventExcel : ExcelResource { - [ResourceEntity("PlaneEvent.json")] - public class PlaneEventExcel : ExcelResource + public int EventID { get; set; } + public int WorldLevel { get; set; } + public int Reward { get; set; } + public List DropList { get; set; } = []; + public int StageID { get; set; } + + public override int GetId() { - public int EventID { get; set; } - public int WorldLevel { get; set; } - public int Reward { get; set; } - public List DropList { get; set; } = []; - public int StageID { get; set; } - - public override int GetId() - { - return EventID * 10 + WorldLevel; - } - - public override void Loaded() - { - GameData.PlaneEventData.Add(GetId(), this); - } + return EventID * 10 + WorldLevel; } -} + + public override void Loaded() + { + GameData.PlaneEventData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/PlayerLevelConfigExcel.cs b/Common/Data/Excel/PlayerLevelConfigExcel.cs index 8c356dc8..08a49cc1 100644 --- a/Common/Data/Excel/PlayerLevelConfigExcel.cs +++ b/Common/Data/Excel/PlayerLevelConfigExcel.cs @@ -1,27 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("PlayerLevelConfig.json")] +public class PlayerLevelConfigExcel : ExcelResource { - [ResourceEntity("PlayerLevelConfig.json")] - public class PlayerLevelConfigExcel : ExcelResource + public int Level { get; set; } + public int PlayerExp { get; set; } + public int StaminaLimit { get; set; } + public int LevelRewardID { get; set; } + + public override int GetId() { - public int Level { get; set; } - public int PlayerExp { get; set; } - public int StaminaLimit { get; set; } - public int LevelRewardID { get; set; } - - public override int GetId() - { - return Level; - } - - public override void Loaded() - { - GameData.PlayerLevelConfigData.Add(Level, this); - } + return Level; } -} + + public override void Loaded() + { + GameData.PlayerLevelConfigData.Add(Level, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/QuestDataExcel.cs b/Common/Data/Excel/QuestDataExcel.cs index 864fa448..c76ec43d 100644 --- a/Common/Data/Excel/QuestDataExcel.cs +++ b/Common/Data/Excel/QuestDataExcel.cs @@ -1,26 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("QuestData.json")] +public class QuestDataExcel : ExcelResource { - [ResourceEntity("QuestData.json")] - public class QuestDataExcel : ExcelResource + public int QuestID { get; set; } + public int QuestType { get; set; } + public HashName QuestTitle { get; set; } = new(); + + public override int GetId() { - public int QuestID { get; set; } - public int QuestType { get; set; } - public HashName QuestTitle { get; set; } = new(); - - public override int GetId() - { - return QuestID; - } - - public override void Loaded() - { - GameData.QuestDataData.Add(QuestID, this); - } + return QuestID; } -} + + public override void Loaded() + { + GameData.QuestDataData.Add(QuestID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RaidConfigExcel.cs b/Common/Data/Excel/RaidConfigExcel.cs index 5a0878b2..9113d1c1 100644 --- a/Common/Data/Excel/RaidConfigExcel.cs +++ b/Common/Data/Excel/RaidConfigExcel.cs @@ -1,35 +1,30 @@ using EggLink.DanhengServer.Enums.Scene; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RaidConfig.json")] +public class RaidConfigExcel : ExcelResource { - [ResourceEntity("RaidConfig.json")] - public class RaidConfigExcel : ExcelResource + public int RaidID { get; set; } + public int HardLevel { get; set; } + + public int FinishEntranceID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public RaidTeamTypeEnum TeamType { get; set; } + + public List TrialAvatarList { get; set; } = []; + public List MainMissionIDList { get; set; } = []; + + public override int GetId() { - public int RaidID { get; set; } - public int HardLevel { get; set; } - - public int FinishEntranceID { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public RaidTeamTypeEnum TeamType { get; set; } - public List TrialAvatarList { get; set; } = []; - public List MainMissionIDList { get; set; } = []; - - public override int GetId() - { - return RaidID * 100 + HardLevel; - } - - public override void Loaded() - { - GameData.RaidConfigData.Add(GetId(), this); - } + return RaidID * 100 + HardLevel; } -} + + public override void Loaded() + { + GameData.RaidConfigData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RelicConfigExcel.cs b/Common/Data/Excel/RelicConfigExcel.cs index 8ec17602..13256612 100644 --- a/Common/Data/Excel/RelicConfigExcel.cs +++ b/Common/Data/Excel/RelicConfigExcel.cs @@ -1,30 +1,29 @@ using EggLink.DanhengServer.Enums.Avatar; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RelicConfig.json")] +public class RelicConfigExcel : ExcelResource { - [ResourceEntity("RelicConfig.json")] - public class RelicConfigExcel : ExcelResource + public int ID { get; set; } + public int SetID { get; set; } + + public RelicTypeEnum Type { get; set; } + public int MainAffixGroup { get; set; } + public int SubAffixGroup { get; set; } + public int MaxLevel { get; set; } + public int ExpType { get; set; } + + public int ExpProvide { get; set; } + public int CoinCost { get; set; } + + public override int GetId() { - public int ID { get; set; } - public int SetID { get; set; } - - public RelicTypeEnum Type { get; set; } - public int MainAffixGroup { get; set; } - public int SubAffixGroup { get; set; } - public int MaxLevel { get; set; } - public int ExpType { get; set; } - - public int ExpProvide { get; set; } - public int CoinCost { get; set; } - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.RelicConfigData[ID] = this; - } + return ID; } -} + + public override void Loaded() + { + GameData.RelicConfigData[ID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RelicExpItemExcel.cs b/Common/Data/Excel/RelicExpItemExcel.cs index c3e681c8..3b470422 100644 --- a/Common/Data/Excel/RelicExpItemExcel.cs +++ b/Common/Data/Excel/RelicExpItemExcel.cs @@ -1,26 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RelicExpItem.json")] +public class RelicExpItemExcel : ExcelResource { - [ResourceEntity("RelicExpItem.json")] - public class RelicExpItemExcel : ExcelResource + public int ItemID { get; set; } + public int ExpProvide { get; set; } + public int CoinCost { get; set; } + + public override int GetId() { - public int ItemID { get; set; } - public int ExpProvide { get; set; } - public int CoinCost { get; set; } - - public override int GetId() - { - return ItemID; - } - - public override void Loaded() - { - GameData.RelicExpItemData[ItemID] = this; - } + return ItemID; } -} + + public override void Loaded() + { + GameData.RelicExpItemData[ItemID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RelicExpTypeExcel.cs b/Common/Data/Excel/RelicExpTypeExcel.cs index ac37da65..3fa19926 100644 --- a/Common/Data/Excel/RelicExpTypeExcel.cs +++ b/Common/Data/Excel/RelicExpTypeExcel.cs @@ -1,26 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RelicExpType.json")] +public class RelicExpTypeExcel : ExcelResource { - [ResourceEntity("RelicExpType.json")] - public class RelicExpTypeExcel : ExcelResource + public int TypeID { get; set; } + public int Level { get; set; } + public int Exp { get; set; } + + public override int GetId() { - public int TypeID { get; set; } - public int Level { get; set; } - public int Exp { get; set; } - - public override int GetId() - { - return TypeID * 100 + Level; - } - - public override void Loaded() - { - GameData.RelicExpTypeData.Add(GetId(), this); - } + return TypeID * 100 + Level; } -} + + public override void Loaded() + { + GameData.RelicExpTypeData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RelicMainAffixConfigExcel.cs b/Common/Data/Excel/RelicMainAffixConfigExcel.cs index 2d351da6..8f475266 100644 --- a/Common/Data/Excel/RelicMainAffixConfigExcel.cs +++ b/Common/Data/Excel/RelicMainAffixConfigExcel.cs @@ -1,28 +1,24 @@ -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RelicMainAffixConfig.json")] +public class RelicMainAffixConfigExcel : ExcelResource { - [ResourceEntity("RelicMainAffixConfig.json")] - public class RelicMainAffixConfigExcel : ExcelResource + public int GroupID { get; set; } + public int AffixID { get; set; } + + public bool IsAvailable { get; set; } + + public override int GetId() { - public int GroupID { get; set; } - public int AffixID { get; set; } - - public bool IsAvailable { get; set; } - - public override int GetId() - { - return GroupID * 100 + AffixID; - } - - public override void Loaded() - { - GameData.RelicMainAffixData.TryGetValue(GroupID, out var affixes); - if (affixes != null) - { - affixes[AffixID] = this; - } else - { - GameData.RelicMainAffixData[GroupID] = new() { { AffixID, this } }; - } - } + return GroupID * 100 + AffixID; } -} + + public override void Loaded() + { + GameData.RelicMainAffixData.TryGetValue(GroupID, out var affixes); + if (affixes != null) + affixes[AffixID] = this; + else + GameData.RelicMainAffixData[GroupID] = new Dictionary { { AffixID, this } }; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RelicSubAffixConfigExcel.cs b/Common/Data/Excel/RelicSubAffixConfigExcel.cs index ec7a701e..f99fd0ed 100644 --- a/Common/Data/Excel/RelicSubAffixConfigExcel.cs +++ b/Common/Data/Excel/RelicSubAffixConfigExcel.cs @@ -1,29 +1,24 @@ -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RelicSubAffixConfig.json")] +public class RelicSubAffixConfigExcel : ExcelResource { - [ResourceEntity("RelicSubAffixConfig.json")] - public class RelicSubAffixConfigExcel : ExcelResource + public int GroupID { get; set; } + public int AffixID { get; set; } + + public int StepNum { get; set; } + + public override int GetId() { - public int GroupID { get; set; } - public int AffixID { get; set; } - - public int StepNum { get; set; } - - public override int GetId() - { - return GroupID * 100 + AffixID; - } - - public override void Loaded() - { - GameData.RelicSubAffixData.TryGetValue(GroupID, out var affixes); - if (affixes != null) - { - affixes[AffixID] = this; - } - else - { - GameData.RelicSubAffixData[GroupID] = new() { { AffixID, this } }; - } - } + return GroupID * 100 + AffixID; } -} + + public override void Loaded() + { + GameData.RelicSubAffixData.TryGetValue(GroupID, out var affixes); + if (affixes != null) + affixes[AffixID] = this; + else + GameData.RelicSubAffixData[GroupID] = new Dictionary { { AffixID, this } }; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RewardDataExcel.cs b/Common/Data/Excel/RewardDataExcel.cs index b15b1649..b5133abc 100644 --- a/Common/Data/Excel/RewardDataExcel.cs +++ b/Common/Data/Excel/RewardDataExcel.cs @@ -1,67 +1,42 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RewardData.json")] +public class RewardDataExcel : ExcelResource { - [ResourceEntity("RewardData.json")] - public class RewardDataExcel : ExcelResource + public int RewardID { get; set; } + public int Hcoin { get; set; } + public int ItemID_1 { get; set; } + public int Count_1 { get; set; } + public int ItemID_2 { get; set; } + public int Count_2 { get; set; } + public int ItemID_3 { get; set; } + public int Count_3 { get; set; } + public int ItemID_4 { get; set; } + public int Count_4 { get; set; } + public int ItemID_5 { get; set; } + public int Count_5 { get; set; } + public int ItemID_6 { get; set; } + public int Count_6 { get; set; } + + public override int GetId() { - public int RewardID { get; set; } - public int Hcoin { get; set; } - public int ItemID_1 { get; set; } - public int Count_1 { get; set; } - public int ItemID_2 { get; set; } - public int Count_2 { get; set; } - public int ItemID_3 { get; set; } - public int Count_3 { get; set; } - public int ItemID_4 { get; set; } - public int Count_4 { get; set; } - public int ItemID_5 { get; set; } - public int Count_5 { get; set; } - public int ItemID_6 { get; set; } - public int Count_6 { get; set; } - - public override int GetId() - { - return RewardID; - } - - public override void Loaded() - { - GameData.RewardDataData[RewardID] = this; - } - - public List<(int, int)> GetItems() - { - var items = new List<(int, int)>(); - if (ItemID_1 != 0) - { - items.Add((ItemID_1, Count_1)); - } - if (ItemID_2 != 0) - { - items.Add((ItemID_2, Count_2)); - } - if (ItemID_3 != 0) - { - items.Add((ItemID_3, Count_3)); - } - if (ItemID_4 != 0) - { - items.Add((ItemID_4, Count_4)); - } - if (ItemID_5 != 0) - { - items.Add((ItemID_5, Count_5)); - } - if (ItemID_6 != 0) - { - items.Add((ItemID_6, Count_6)); - } - return items; - } + return RewardID; } -} + + public override void Loaded() + { + GameData.RewardDataData[RewardID] = this; + } + + public List<(int, int)> GetItems() + { + var items = new List<(int, int)>(); + if (ItemID_1 != 0) items.Add((ItemID_1, Count_1)); + if (ItemID_2 != 0) items.Add((ItemID_2, Count_2)); + if (ItemID_3 != 0) items.Add((ItemID_3, Count_3)); + if (ItemID_4 != 0) items.Add((ItemID_4, Count_4)); + if (ItemID_5 != 0) items.Add((ItemID_5, Count_5)); + if (ItemID_6 != 0) items.Add((ItemID_6, Count_6)); + return items; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueAeonExcel.cs b/Common/Data/Excel/RogueAeonExcel.cs index 62166f72..7a3b9a9e 100644 --- a/Common/Data/Excel/RogueAeonExcel.cs +++ b/Common/Data/Excel/RogueAeonExcel.cs @@ -1,29 +1,22 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueAeon.json")] +public class RogueAeonExcel : ExcelResource { - [ResourceEntity("RogueAeon.json")] - public class RogueAeonExcel : ExcelResource + public int AeonID { get; set; } + public int RogueVersion { get; set; } + + public int RogueBuffType { get; set; } + public int BattleEventBuffGroup { get; set; } + public int BattleEventEnhanceBuffGroup { get; set; } + + public override int GetId() { - public int AeonID { get; set; } - public int RogueVersion { get; set; } - - public int RogueBuffType { get; set; } - public int BattleEventBuffGroup { get; set; } - public int BattleEventEnhanceBuffGroup { get; set; } - - public override int GetId() - { - return AeonID; - } - - public override void Loaded() - { - GameData.RogueAeonData.Add(GetId(), this); - } + return AeonID; } -} + + public override void Loaded() + { + GameData.RogueAeonData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueAreaConfigExcel.cs b/Common/Data/Excel/RogueAreaConfigExcel.cs index 464b8130..863a3579 100644 --- a/Common/Data/Excel/RogueAreaConfigExcel.cs +++ b/Common/Data/Excel/RogueAreaConfigExcel.cs @@ -1,46 +1,35 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueAreaConfig.json")] +public class RogueAreaConfigExcel : ExcelResource { - [ResourceEntity("RogueAreaConfig.json")] - public class RogueAreaConfigExcel : ExcelResource + public int RogueAreaID { get; set; } + public int AreaProgress { get; set; } + public int Difficulty { get; set; } + public int FirstReward { get; set; } + public Dictionary ScoreMap { get; set; } = []; + + [JsonIgnore] public int MapId { get; set; } + + [JsonIgnore] public Dictionary RogueMaps { get; set; } = []; + + public override int GetId() { - public int RogueAreaID { get; set; } - public int AreaProgress { get; set; } - public int Difficulty { get; set; } - public int FirstReward { get; set; } - public Dictionary ScoreMap { get; set; } = []; - - [JsonIgnore] - public int MapId { get; set; } - - [JsonIgnore] - public Dictionary RogueMaps { get; set; } = []; - - public override int GetId() - { - return RogueAreaID; - } - - public override void Loaded() - { - GameData.RogueAreaConfigData.Add(RogueAreaID, this); - - MapId = AreaProgress * 100 + Difficulty; - } - - public override void AfterAllDone() - { - GameData.RogueMapData.TryGetValue(MapId, out var map); - if (map != null) - { - RogueMaps = map; - } - } + return RogueAreaID; } -} + + public override void Loaded() + { + GameData.RogueAreaConfigData.Add(RogueAreaID, this); + + MapId = AreaProgress * 100 + Difficulty; + } + + public override void AfterAllDone() + { + GameData.RogueMapData.TryGetValue(MapId, out var map); + if (map != null) RogueMaps = map; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueBonusExcel.cs b/Common/Data/Excel/RogueBonusExcel.cs index 7867aa65..6a14fdab 100644 --- a/Common/Data/Excel/RogueBonusExcel.cs +++ b/Common/Data/Excel/RogueBonusExcel.cs @@ -1,25 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueBonus.json")] +public class RogueBonusExcel : ExcelResource { - [ResourceEntity("RogueBonus.json")] - public class RogueBonusExcel : ExcelResource + public int BonusID { get; set; } + public int BonusEvent { get; set; } + + public override int GetId() { - public int BonusID { get; set; } - public int BonusEvent { get; set; } - - public override int GetId() - { - return BonusID; - } - - public override void Loaded() - { - GameData.RogueBonusData.Add(GetId(), this); - } + return BonusID; } -} + + public override void Loaded() + { + GameData.RogueBonusData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueBuffExcel.cs b/Common/Data/Excel/RogueBuffExcel.cs index 5e634aef..082341d4 100644 --- a/Common/Data/Excel/RogueBuffExcel.cs +++ b/Common/Data/Excel/RogueBuffExcel.cs @@ -3,56 +3,54 @@ using EggLink.DanhengServer.Proto; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueBuff.json")] +public class RogueBuffExcel : ExcelResource { - [ResourceEntity("RogueBuff.json")] - public class RogueBuffExcel : ExcelResource + public int MazeBuffID { get; set; } + public int MazeBuffLevel { get; set; } + public int RogueBuffType { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public RogueBuffCategoryEnum RogueBuffCategory { get; set; } + + public int RogueBuffTag { get; set; } + public int AeonID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public RogueBuffAeonTypeEnum BattleEventBuffType { get; set; } = RogueBuffAeonTypeEnum.Normal; + + public bool IsAeonBuff => BattleEventBuffType != RogueBuffAeonTypeEnum.Normal; + + public override int GetId() { - public int MazeBuffID { get; set; } - public int MazeBuffLevel { get; set; } - public int RogueBuffType { get; set; } - [JsonConverter(typeof(StringEnumConverter))] - public RogueBuffCategoryEnum RogueBuffCategory { get; set; } - public int RogueBuffTag { get; set; } - public int AeonID { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public RogueBuffAeonTypeEnum BattleEventBuffType { get; set; } = RogueBuffAeonTypeEnum.Normal; - - public override int GetId() - { - return MazeBuffID * 100 + MazeBuffLevel; - } - - public override void Loaded() - { - GameData.RogueBuffData.Add(GetId(), this); - - if (BattleEventBuffType == RogueBuffAeonTypeEnum.BattleEventBuff) - { - GameData.RogueAeonBuffData.Add(AeonID, this); - } else if (BattleEventBuffType == RogueBuffAeonTypeEnum.BattleEventBuffEnhance) - { - if (GameData.RogueAeonEnhanceData.TryGetValue(AeonID, out var aeonBuff)) - { - aeonBuff.Add(this); - } - else - { - GameData.RogueAeonEnhanceData.Add(AeonID, [this]); - } - } - } - - public RogueCommonBuff ToProto() - { - return new() - { - BuffId = (uint)MazeBuffID, - BuffLevel = (uint)MazeBuffLevel, - }; - } - - public bool IsAeonBuff => BattleEventBuffType != RogueBuffAeonTypeEnum.Normal; + return MazeBuffID * 100 + MazeBuffLevel; } -} + + public override void Loaded() + { + GameData.RogueBuffData.Add(GetId(), this); + + if (BattleEventBuffType == RogueBuffAeonTypeEnum.BattleEventBuff) + { + GameData.RogueAeonBuffData.Add(AeonID, this); + } + else if (BattleEventBuffType == RogueBuffAeonTypeEnum.BattleEventBuffEnhance) + { + if (GameData.RogueAeonEnhanceData.TryGetValue(AeonID, out var aeonBuff)) + aeonBuff.Add(this); + else + GameData.RogueAeonEnhanceData.Add(AeonID, [this]); + } + } + + public RogueCommonBuff ToProto() + { + return new RogueCommonBuff + { + BuffId = (uint)MazeBuffID, + BuffLevel = (uint)MazeBuffLevel + }; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueBuffGroupExcel.cs b/Common/Data/Excel/RogueBuffGroupExcel.cs index 058d54bf..478ade0f 100644 --- a/Common/Data/Excel/RogueBuffGroupExcel.cs +++ b/Common/Data/Excel/RogueBuffGroupExcel.cs @@ -1,73 +1,56 @@ using EggLink.DanhengServer.Util; using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueBuffGroup.json")] +public class RogueBuffGroupExcel : ExcelResource { - [ResourceEntity("RogueBuffGroup.json")] - public class RogueBuffGroupExcel : ExcelResource + [JsonProperty("LIOICIOFLGL")] public int GroupID { get; set; } + + [JsonProperty("LEEMGFGKCMO")] public List BuffTagList { get; set; } = []; + + [JsonIgnore] public List BuffList { get; set; } = []; + + [JsonIgnore] public bool IsLoaded { get; set; } + + public override int GetId() { - [JsonProperty("LIOICIOFLGL")] - public int GroupID { get; set; } + return GroupID; + } - [JsonProperty("LEEMGFGKCMO")] - public List BuffTagList { get; set; } = []; + public override void Loaded() + { + GameData.RogueBuffGroupData.Add(GetId(), this); + LoadBuff(); + } - [JsonIgnore] - public List BuffList { get; set; } = []; + public override void AfterAllDone() + { + LoadBuff(); + } - [JsonIgnore] - public bool IsLoaded { get; set; } - - public override int GetId() - { - return GroupID; - } - - public override void Loaded() - { - GameData.RogueBuffGroupData.Add(GetId(), this); - LoadBuff(); - } - - public override void AfterAllDone() - { - LoadBuff(); - } - - public void LoadBuff() - { - if (IsLoaded) + public void LoadBuff() + { + if (IsLoaded) return; + var count = 0; + foreach (var buffID in BuffTagList) + if (GameData.RogueBuffData.FirstOrDefault(x => x.Value.RogueBuffTag == buffID).Value is RogueBuffExcel buff) { - return; + BuffList.SafeAdd(buff); + count++; } - var count = 0; - foreach (var buffID in BuffTagList) + else { - if (GameData.RogueBuffData.FirstOrDefault(x => x.Value.RogueBuffTag == buffID).Value is RogueBuffExcel buff) + // might is group id + if (GameData.RogueBuffGroupData.TryGetValue(buffID, out var group)) { - BuffList.SafeAdd(buff); + group.LoadBuff(); + BuffList.SafeAddRange(group.BuffList); count++; } - else - { - // might is group id - if (GameData.RogueBuffGroupData.TryGetValue(buffID, out var group)) - { - group.LoadBuff(); - BuffList.SafeAddRange(group.BuffList); - count++; - } - } } - if (count == BuffTagList.Count) - { - IsLoaded = true; - } - } + + if (count == BuffTagList.Count) IsLoaded = true; } -} +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueDLCAreaExcel.cs b/Common/Data/Excel/RogueDLCAreaExcel.cs index 9083d1d6..df2c83ae 100644 --- a/Common/Data/Excel/RogueDLCAreaExcel.cs +++ b/Common/Data/Excel/RogueDLCAreaExcel.cs @@ -1,55 +1,41 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueDLCArea.json")] +public class RogueDLCAreaExcel : ExcelResource { - [ResourceEntity("RogueDLCArea.json")] - public class RogueDLCAreaExcel : ExcelResource + public int AreaID { get; set; } + public string SubType { get; set; } = ""; + public List LayerIDList { get; set; } = []; + public List DifficultyID { get; set; } = []; + public int FirstReward { get; set; } + + public List AreaScoreMap { get; set; } = []; + + [JsonIgnore] public int RogueVersionId { get; set; } + + public override int GetId() { - public int AreaID { get; set; } - public string SubType { get; set; } = ""; - public List LayerIDList { get; set; } = []; - public List DifficultyID { get; set; } = []; - public int FirstReward { get; set; } - - public List AreaScoreMap { get; set; } = []; - - [JsonIgnore] - public int RogueVersionId { get; set; } - - public override int GetId() - { - return AreaID; - } - - public override void Loaded() - { - GameData.RogueDLCAreaData[AreaID] = this; - - if (SubType.Contains("Nous")) - { - RogueVersionId = 202; - } - else - { - RogueVersionId = 201; - } - } + return AreaID; } - public class RogueDLCAreaScoreMap + public override void Loaded() { - [JsonProperty("NALLPFKBHIO")] - public int Layer { get; set; } + GameData.RogueDLCAreaData[AreaID] = this; - [JsonProperty("GGOHPEDAKJE")] - public int ExploreScore { get; set; } - - [JsonProperty("BELDLJADLKO")] - public int FinishScore { get; set; } + if (SubType.Contains("Nous")) + RogueVersionId = 202; + else + RogueVersionId = 201; } } + +public class RogueDLCAreaScoreMap +{ + [JsonProperty("NALLPFKBHIO")] public int Layer { get; set; } + + [JsonProperty("GGOHPEDAKJE")] public int ExploreScore { get; set; } + + [JsonProperty("BELDLJADLKO")] public int FinishScore { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueDLCBossBpExcel.cs b/Common/Data/Excel/RogueDLCBossBpExcel.cs index 41a0c733..2b4cf906 100644 --- a/Common/Data/Excel/RogueDLCBossBpExcel.cs +++ b/Common/Data/Excel/RogueDLCBossBpExcel.cs @@ -1,33 +1,26 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueDLCBossBp.json")] +public class RogueDLCBossBpExcel : ExcelResource { - [ResourceEntity("RogueDLCBossBp.json")] - public class RogueDLCBossBpExcel : ExcelResource + public int BossBpID { get; set; } + public List MonsterAndFloorList { get; set; } = []; + public List BossDecayList { get; set; } = []; + + public override int GetId() { - public int BossBpID { get; set; } - public List MonsterAndFloorList { get; set; } = []; - public List BossDecayList { get; set; } = []; - - public override int GetId() - { - return BossBpID; - } - - public override void Loaded() - { - GameData.RogueDLCBossBpData.Add(BossBpID, this); - } + return BossBpID; } - public class BossAndFloorInfo + public override void Loaded() { - [JsonProperty("LKPOGAKCEMO")] - public int MonsterId { get; set; } + GameData.RogueDLCBossBpData.Add(BossBpID, this); } } + +public class BossAndFloorInfo +{ + [JsonProperty("LKPOGAKCEMO")] public int MonsterId { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueDLCBossDecayExcel.cs b/Common/Data/Excel/RogueDLCBossDecayExcel.cs index 3052c5d9..1e65718b 100644 --- a/Common/Data/Excel/RogueDLCBossDecayExcel.cs +++ b/Common/Data/Excel/RogueDLCBossDecayExcel.cs @@ -1,31 +1,26 @@ using EggLink.DanhengServer.Enums.Rogue; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueDLCBossDecay.json")] +public class RogueDLCBossDecayExcel : ExcelResource { - [ResourceEntity("RogueDLCBossDecay.json")] - public class RogueDLCBossDecayExcel : ExcelResource + public int BossDecayID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public BossDecayEffectTypeEnum EffectType { get; set; } + + public List EffectParamList { get; set; } = []; + + public override int GetId() { - public int BossDecayID { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public BossDecayEffectTypeEnum EffectType { get; set; } - public List EffectParamList { get; set; } = []; - - public override int GetId() - { - return BossDecayID; - } - - public override void Loaded() - { - GameData.RogueDLCBossDecayData.Add(GetId(), this); - } + return BossDecayID; } -} + + public override void Loaded() + { + GameData.RogueDLCBossDecayData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueDLCChessBoardExcel.cs b/Common/Data/Excel/RogueDLCChessBoardExcel.cs index 025def9e..5f0a127f 100644 --- a/Common/Data/Excel/RogueDLCChessBoardExcel.cs +++ b/Common/Data/Excel/RogueDLCChessBoardExcel.cs @@ -1,50 +1,44 @@ using EggLink.DanhengServer.Data.Config; using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueDLCChessBoard.json")] +public class RogueDLCChessBoardExcel : ExcelResource { - [ResourceEntity("RogueDLCChessBoard.json")] - public class RogueDLCChessBoardExcel : ExcelResource + public int ChessBoardID { get; set; } + public string ChessBoardConfiguration { get; set; } = string.Empty; + + [JsonIgnore] public RogueChestMapInfo? MapInfo { get; set; } + + public override int GetId() { - public int ChessBoardID { get; set; } - public string ChessBoardConfiguration { get; set; } = string.Empty; + return ChessBoardID; + } - [JsonIgnore] - public RogueChestMapInfo? MapInfo { get; set; } - - public override int GetId() + public override void Loaded() + { + if (ChessBoardID.ToString().StartsWith("201")) { - return ChessBoardID; - } - - public override void Loaded() - { - if (ChessBoardID.ToString().StartsWith("201")) + var layer = int.Parse(ChessBoardID.ToString().Substring(3, 1)); + if (!GameData.RogueSwarmChessBoardData.TryGetValue(layer, out var value)) { - var layer = int.Parse(ChessBoardID.ToString().Substring(3, 1)); - if (!GameData.RogueSwarmChessBoardData.TryGetValue(layer, out List? value)) - { - value = ([]); - GameData.RogueSwarmChessBoardData[layer] = value; - } - - value.Add(this); - } else if (ChessBoardID.ToString().StartsWith("211")) - { - var layer = int.Parse(ChessBoardID.ToString().Substring(3, 1)); - if (!GameData.RogueNousChessBoardData.TryGetValue(layer, out List? value)) - { - value = ([]); - GameData.RogueNousChessBoardData[layer] = value; - } - - value.Add(this); + value = []; + GameData.RogueSwarmChessBoardData[layer] = value; } + + value.Add(this); + } + else if (ChessBoardID.ToString().StartsWith("211")) + { + var layer = int.Parse(ChessBoardID.ToString().Substring(3, 1)); + if (!GameData.RogueNousChessBoardData.TryGetValue(layer, out var value)) + { + value = []; + GameData.RogueNousChessBoardData[layer] = value; + } + + value.Add(this); } } -} +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueDLCDifficultyExcel.cs b/Common/Data/Excel/RogueDLCDifficultyExcel.cs index 08f0cad9..7ab1e1b4 100644 --- a/Common/Data/Excel/RogueDLCDifficultyExcel.cs +++ b/Common/Data/Excel/RogueDLCDifficultyExcel.cs @@ -1,27 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueDLCDifficulty.json")] +public class RogueDLCDifficultyExcel : ExcelResource { - [ResourceEntity("RogueDLCDifficulty.json")] - public class RogueDLCDifficultyExcel : ExcelResource - { - public int DifficultyID { get; set; } - public List DifficultyCutList { get; set; } = []; - public List DifficultyLevelGroup { get; set; } = []; - public List LevelList { get; set; } = []; + public int DifficultyID { get; set; } + public List DifficultyCutList { get; set; } = []; + public List DifficultyLevelGroup { get; set; } = []; + public List LevelList { get; set; } = []; - public override int GetId() - { - return DifficultyID; - } - - public override void Loaded() - { - GameData.RogueDLCDifficultyData.Add(GetId(), this); - } + public override int GetId() + { + return DifficultyID; } -} + + public override void Loaded() + { + GameData.RogueDLCDifficultyData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueHandBookEventExcel.cs b/Common/Data/Excel/RogueHandBookEventExcel.cs index 7a99973a..bfdc0333 100644 --- a/Common/Data/Excel/RogueHandBookEventExcel.cs +++ b/Common/Data/Excel/RogueHandBookEventExcel.cs @@ -1,28 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueHandBookEvent.json")] +public class RogueHandBookEventExcel : ExcelResource { - [ResourceEntity("RogueHandBookEvent.json")] - public class RogueHandBookEventExcel : ExcelResource + public int EventHandbookID { get; set; } + public HashName EventTitle { get; set; } = new(); + + public int EventReward { get; set; } + public List EventTypeList { get; set; } = []; + + public override int GetId() { - public int EventHandbookID { get; set; } - public HashName EventTitle { get; set; } = new(); - - public int EventReward { get; set; } - public List EventTypeList { get; set; } = []; - - public override int GetId() - { - return EventHandbookID; - } - - public override void Loaded() - { - GameData.RogueHandBookEventData.Add(GetId(), this); - } + return EventHandbookID; } -} + + public override void Loaded() + { + GameData.RogueHandBookEventData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueHandbookMiracleExcel.cs b/Common/Data/Excel/RogueHandbookMiracleExcel.cs index 7503cf3f..01904e42 100644 --- a/Common/Data/Excel/RogueHandbookMiracleExcel.cs +++ b/Common/Data/Excel/RogueHandbookMiracleExcel.cs @@ -1,27 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueHandbookMiracle.json")] +public class RogueHandbookMiracleExcel : ExcelResource { - [ResourceEntity("RogueHandbookMiracle.json")] - public class RogueHandbookMiracleExcel : ExcelResource + public int MiracleHandbookID { get; set; } + public int MiracleReward { get; set; } + + public List MiracleTypeList { get; set; } = []; + + public override int GetId() { - public int MiracleHandbookID { get; set; } - public int MiracleReward { get; set; } - - public List MiracleTypeList { get; set; } = []; - - public override int GetId() - { - return MiracleHandbookID; - } - - public override void Loaded() - { - GameData.RogueHandbookMiracleData.Add(GetId(), this); - } + return MiracleHandbookID; } -} + + public override void Loaded() + { + GameData.RogueHandbookMiracleData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueManagerExcel.cs b/Common/Data/Excel/RogueManagerExcel.cs index 3b00a8a1..c0e220e3 100644 --- a/Common/Data/Excel/RogueManagerExcel.cs +++ b/Common/Data/Excel/RogueManagerExcel.cs @@ -1,36 +1,28 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueManager.json")] +public class RogueManagerExcel : ExcelResource { - [ResourceEntity("RogueManager.json")] - public class RogueManagerExcel : ExcelResource + public int RogueSeason { get; set; } + public string BeginTime { get; set; } = ""; + public string EndTime { get; set; } = ""; + public List RogueAreaIDList { get; set; } = []; + + [JsonIgnore] public DateTime BeginTimeDate { get; set; } + + [JsonIgnore] public DateTime EndTimeDate { get; set; } + + public override int GetId() { - public int RogueSeason { get; set; } - public string BeginTime { get; set; } = ""; - public string EndTime { get; set; } = ""; - public List RogueAreaIDList { get; set; } = []; - - [JsonIgnore] - public DateTime BeginTimeDate { get; set; } - - [JsonIgnore] - public DateTime EndTimeDate { get; set; } - - public override int GetId() - { - return RogueSeason; - } - - public override void Loaded() - { - GameData.RogueManagerData.Add(GetId(), this); - BeginTimeDate = DateTime.Parse(BeginTime); - EndTimeDate = DateTime.Parse(EndTime); - } + return RogueSeason; } -} + + public override void Loaded() + { + GameData.RogueManagerData.Add(GetId(), this); + BeginTimeDate = DateTime.Parse(BeginTime); + EndTimeDate = DateTime.Parse(EndTime); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueMapExcel.cs b/Common/Data/Excel/RogueMapExcel.cs index ec16e585..6fcd4c54 100644 --- a/Common/Data/Excel/RogueMapExcel.cs +++ b/Common/Data/Excel/RogueMapExcel.cs @@ -1,38 +1,27 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueMap.json")] +public class RogueMapExcel : ExcelResource { - [ResourceEntity("RogueMap.json")] - public class RogueMapExcel : ExcelResource + public int RogueMapID { get; set; } + public int SiteID { get; set; } + public bool IsStart { get; set; } + public int PosX { get; set; } + public int PosY { get; set; } + + public List NextSiteIDList { get; set; } = []; + public List LevelList { get; set; } = []; + + public override int GetId() { - public int RogueMapID { get; set; } - public int SiteID { get; set; } - public bool IsStart { get; set; } - public int PosX { get; set; } - public int PosY { get; set; } - - public List NextSiteIDList { get; set; } = []; - public List LevelList { get; set; } = []; - - public override int GetId() - { - return RogueMapID * 1000 + SiteID; - } - - public override void Loaded() - { - if (GameData.RogueMapData.TryGetValue(RogueMapID, out var map)) - { - map.Add(SiteID, this); - } - else - { - GameData.RogueMapData.Add(RogueMapID, new() { { SiteID, this } }); - } - } + return RogueMapID * 1000 + SiteID; } -} + + public override void Loaded() + { + if (GameData.RogueMapData.TryGetValue(RogueMapID, out var map)) + map.Add(SiteID, this); + else + GameData.RogueMapData.Add(RogueMapID, new Dictionary { { SiteID, this } }); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueMazeBuffExcel.cs b/Common/Data/Excel/RogueMazeBuffExcel.cs index 3adea075..2195a515 100644 --- a/Common/Data/Excel/RogueMazeBuffExcel.cs +++ b/Common/Data/Excel/RogueMazeBuffExcel.cs @@ -1,31 +1,24 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueMazeBuff.json")] +public class RogueMazeBuffExcel : ExcelResource { - [ResourceEntity("RogueMazeBuff.json")] - public class RogueMazeBuffExcel : ExcelResource + [JsonIgnore] public string? Name; + + public int ID { get; set; } + public int Lv { get; set; } + public int LvMax { get; set; } + public HashName BuffName { get; set; } = new(); + + public override int GetId() { - public int ID { get; set; } - public int Lv { get; set; } - public int LvMax { get; set; } - public HashName BuffName { get; set; } = new(); - - [JsonIgnore] - public string? Name; - - public override int GetId() - { - return ID * 100 + Lv; - } - - public override void Loaded() - { - GameData.RogueMazeBuffData.Add(GetId(), this); - } + return ID * 100 + Lv; } -} + + public override void Loaded() + { + GameData.RogueMazeBuffData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueMiracleDisplayExcel.cs b/Common/Data/Excel/RogueMiracleDisplayExcel.cs index 766bd790..acd428c8 100644 --- a/Common/Data/Excel/RogueMiracleDisplayExcel.cs +++ b/Common/Data/Excel/RogueMiracleDisplayExcel.cs @@ -1,25 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueMiracleDisplay.json")] +public class RogueMiracleDisplayExcel : ExcelResource { - [ResourceEntity("RogueMiracleDisplay.json")] - public class RogueMiracleDisplayExcel : ExcelResource + public int MiracleDisplayID { get; set; } + public HashName MiracleName { get; set; } = new(); + + public override int GetId() { - public int MiracleDisplayID { get; set; } - public HashName MiracleName { get; set; } = new(); - - public override int GetId() - { - return MiracleDisplayID; - } - - public override void Loaded() - { - GameData.RogueMiracleDisplayData.Add(GetId(), this); - } + return MiracleDisplayID; } -} + + public override void Loaded() + { + GameData.RogueMiracleDisplayData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueMiracleExcel.cs b/Common/Data/Excel/RogueMiracleExcel.cs index 56aaec87..c7df3ecf 100644 --- a/Common/Data/Excel/RogueMiracleExcel.cs +++ b/Common/Data/Excel/RogueMiracleExcel.cs @@ -1,34 +1,26 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueMiracle.json")] +public class RogueMiracleExcel : ExcelResource { - [ResourceEntity("RogueMiracle.json")] - public class RogueMiracleExcel : ExcelResource + public int MiracleID { get; set; } + public int MiracleDisplayID { get; set; } + public int UnlockHandbookMiracleID { get; set; } + + [JsonIgnore] public HashName MiracleName { get; set; } = new(); + + [JsonIgnore] public string? Name { get; set; } + + public override int GetId() { - public int MiracleID { get; set; } - public int MiracleDisplayID { get; set; } - public int UnlockHandbookMiracleID { get; set; } - - [JsonIgnore] - public HashName MiracleName { get; set; } = new(); - - [JsonIgnore] - public string? Name { get; set; } - - public override int GetId() - { - return MiracleID; - } - - public override void AfterAllDone() - { - MiracleName = GameData.RogueMiracleDisplayData[MiracleDisplayID].MiracleName; - GameData.RogueMiracleData[MiracleID] = this; - } + return MiracleID; } -} + + public override void AfterAllDone() + { + MiracleName = GameData.RogueMiracleDisplayData[MiracleDisplayID].MiracleName; + GameData.RogueMiracleData[MiracleID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueMonsterExcel.cs b/Common/Data/Excel/RogueMonsterExcel.cs index afed74ef..fb924d8c 100644 --- a/Common/Data/Excel/RogueMonsterExcel.cs +++ b/Common/Data/Excel/RogueMonsterExcel.cs @@ -1,26 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueMonster.json")] +public class RogueMonsterExcel : ExcelResource { - [ResourceEntity("RogueMonster.json")] - public class RogueMonsterExcel : ExcelResource + public int RogueMonsterID { get; set; } + public int NpcMonsterID { get; set; } + public int EventID { get; set; } + + public override int GetId() { - public int RogueMonsterID { get; set; } - public int NpcMonsterID { get; set; } - public int EventID { get; set; } - - public override int GetId() - { - return RogueMonsterID; - } - - public override void Loaded() - { - GameData.RogueMonsterData.Add(RogueMonsterID, this); - } + return RogueMonsterID; } -} + + public override void Loaded() + { + GameData.RogueMonsterData.Add(RogueMonsterID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueNPCDialogueExcel.cs b/Common/Data/Excel/RogueNPCDialogueExcel.cs index 1a9ad473..3f9fc96a 100644 --- a/Common/Data/Excel/RogueNPCDialogueExcel.cs +++ b/Common/Data/Excel/RogueNPCDialogueExcel.cs @@ -1,38 +1,31 @@ using EggLink.DanhengServer.Data.Config; using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("RogueNPCDialogue.json")] +public class RogueNPCDialogueExcel : ExcelResource { - [ResourceEntity("RogueNPCDialogue.json")] - public class RogueNPCDialogueExcel : ExcelResource + public int RogueNPCID { get; set; } + public int DialogueProgress { get; set; } + public int HandbookEventID { get; set; } + public string DialoguePath { get; set; } = ""; + + [JsonIgnore] public DialogueInfo? DialogueInfo { get; set; } + + public override int GetId() { - public int RogueNPCID { get; set; } - public int DialogueProgress { get; set; } - public int HandbookEventID { get; set; } - public string DialoguePath { get; set; } = ""; - - [JsonIgnore] - public DialogueInfo? DialogueInfo { get; set; } - - public override int GetId() - { - return RogueNPCID * 100 + DialogueProgress; - } - - public override void Loaded() - { - GameData.RogueNPCDialogueData.Add(GetId(), this); - } - - public bool CanUseInVer(int version) - { - GameData.RogueHandBookEventData.TryGetValue(HandbookEventID, out var handbookEvent); - return DialogueInfo != null && handbookEvent != null && handbookEvent.EventTypeList.Contains(version); - } + return RogueNPCID * 100 + DialogueProgress; } -} + + public override void Loaded() + { + GameData.RogueNPCDialogueData.Add(GetId(), this); + } + + public bool CanUseInVer(int version) + { + GameData.RogueHandBookEventData.TryGetValue(HandbookEventID, out var handbookEvent); + return DialogueInfo != null && handbookEvent != null && handbookEvent.EventTypeList.Contains(version); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueNousAeonExcel.cs b/Common/Data/Excel/RogueNousAeonExcel.cs index 7c893bac..9c9d9dce 100644 --- a/Common/Data/Excel/RogueNousAeonExcel.cs +++ b/Common/Data/Excel/RogueNousAeonExcel.cs @@ -1,29 +1,22 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueNousAeon.json")] +public class RogueNousAeonExcel : ExcelResource { - [ResourceEntity("RogueNousAeon.json")] - public class RogueNousAeonExcel : ExcelResource + public int AeonID { get; set; } + public int RogueBuffType { get; set; } + public List EffectParam1 { get; set; } = []; + + public int BattleEventBuffGroup { get; set; } + public int BattleEventEnhanceBuffGroup { get; set; } + + public override int GetId() { - public int AeonID { get; set; } - public int RogueBuffType { get; set; } - public List EffectParam1 { get; set; } = []; - - public int BattleEventBuffGroup { get; set; } - public int BattleEventEnhanceBuffGroup { get; set; } - - public override int GetId() - { - return AeonID; - } - - public override void Loaded() - { - GameData.RogueNousAeonData[AeonID] = this; - } + return AeonID; } -} + + public override void Loaded() + { + GameData.RogueNousAeonData[AeonID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueNousDiceBranchExcel.cs b/Common/Data/Excel/RogueNousDiceBranchExcel.cs index d7cccb73..2b3b4ca1 100644 --- a/Common/Data/Excel/RogueNousDiceBranchExcel.cs +++ b/Common/Data/Excel/RogueNousDiceBranchExcel.cs @@ -1,37 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueNousDiceBranch.json")] +public class RogueNousDiceBranchExcel : ExcelResource { - [ResourceEntity("RogueNousDiceBranch.json")] - public class RogueNousDiceBranchExcel : ExcelResource + public int BranchID { get; set; } + public int DefaultUltraSurface { get; set; } + public List DefaultCommonSurfaceList { get; set; } = []; + + public override int GetId() { - public int BranchID { get; set; } - public int DefaultUltraSurface { get; set; } - public List DefaultCommonSurfaceList { get; set; } = []; - - public override int GetId() - { - return BranchID; - } - - public override void Loaded() - { - GameData.RogueNousDiceBranchData[BranchID] = this; - } - - public List GetDefaultSurfaceList() - { - var list = new List - { - DefaultUltraSurface - }; - list.AddRange(DefaultCommonSurfaceList); - - return list; - } + return BranchID; } -} + + public override void Loaded() + { + GameData.RogueNousDiceBranchData[BranchID] = this; + } + + public List GetDefaultSurfaceList() + { + var list = new List + { + DefaultUltraSurface + }; + list.AddRange(DefaultCommonSurfaceList); + + return list; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueNousDiceSurfaceExcel.cs b/Common/Data/Excel/RogueNousDiceSurfaceExcel.cs index bc15b304..e9c8e950 100644 --- a/Common/Data/Excel/RogueNousDiceSurfaceExcel.cs +++ b/Common/Data/Excel/RogueNousDiceSurfaceExcel.cs @@ -1,29 +1,22 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueNousDiceSurface.json")] +public class RogueNousDiceSurfaceExcel : ExcelResource { - [ResourceEntity("RogueNousDiceSurface.json")] - public class RogueNousDiceSurfaceExcel : ExcelResource + public int SurfaceID { get; set; } + public int ItemID { get; set; } + public int Sort { get; set; } + public int DiceActiveStage { get; set; } + public HashName SurfaceName { get; set; } = new(); + public HashName SurfaceDesc { get; set; } = new(); + + public override int GetId() { - public int SurfaceID { get; set; } - public int ItemID { get; set; } - public int Sort { get; set; } - public int DiceActiveStage { get; set; } - public HashName SurfaceName { get; set; } = new(); - public HashName SurfaceDesc { get; set; } = new(); - - public override int GetId() - { - return SurfaceID; - } - - public override void Loaded() - { - GameData.RogueNousDiceSurfaceData[SurfaceID] = this; - } + return SurfaceID; } -} + + public override void Loaded() + { + GameData.RogueNousDiceSurfaceData[SurfaceID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueNousDifficultyLevelExcel.cs b/Common/Data/Excel/RogueNousDifficultyLevelExcel.cs index a916cb75..e5c6788d 100644 --- a/Common/Data/Excel/RogueNousDifficultyLevelExcel.cs +++ b/Common/Data/Excel/RogueNousDifficultyLevelExcel.cs @@ -1,24 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueNousDifficultyLevel.json")] +public class RogueNousDifficultyLevelExcel : ExcelResource { - [ResourceEntity("RogueNousDifficultyLevel.json")] - public class RogueNousDifficultyLevelExcel : ExcelResource + public int DifficultyID { get; set; } + + public override int GetId() { - public int DifficultyID { get; set; } - - public override int GetId() - { - return DifficultyID; - } - - public override void Loaded() - { - GameData.RogueNousDifficultyLevelData[DifficultyID] = this; - } + return DifficultyID; } -} + + public override void Loaded() + { + GameData.RogueNousDifficultyLevelData[DifficultyID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueNousMainStoryExcel.cs b/Common/Data/Excel/RogueNousMainStoryExcel.cs index 2b178312..6c0c94fd 100644 --- a/Common/Data/Excel/RogueNousMainStoryExcel.cs +++ b/Common/Data/Excel/RogueNousMainStoryExcel.cs @@ -1,28 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueNousMainStory.json")] +public class RogueNousMainStoryExcel : ExcelResource { - [ResourceEntity("RogueNousMainStory.json")] - public class RogueNousMainStoryExcel : ExcelResource - { - public int StoryID { get; set; } - public int Layer { get; set; } - public int RogueNPCID { get; set; } - public int QuestID { get; set; } - public int StoryGroup { get; set; } + public int StoryID { get; set; } + public int Layer { get; set; } + public int RogueNPCID { get; set; } + public int QuestID { get; set; } + public int StoryGroup { get; set; } - public override int GetId() - { - return StoryID; - } - - public override void Loaded() - { - GameData.RogueNousMainStoryData.Add(GetId(), this); - } + public override int GetId() + { + return StoryID; } -} + + public override void Loaded() + { + GameData.RogueNousMainStoryData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueNousSubStoryExcel.cs b/Common/Data/Excel/RogueNousSubStoryExcel.cs index c26427d5..6004f2f5 100644 --- a/Common/Data/Excel/RogueNousSubStoryExcel.cs +++ b/Common/Data/Excel/RogueNousSubStoryExcel.cs @@ -1,28 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueNousSubStory.json")] +public class RogueNousSubStoryExcel : ExcelResource { - [ResourceEntity("RogueNousSubStory.json")] - public class RogueNousSubStoryExcel : ExcelResource + public int StoryID { get; set; } + public int Layer { get; set; } + public int MaxNousValue { get; set; } + public List NextIDList { get; set; } = []; + public int RequireArea { get; set; } + + public override int GetId() { - public int StoryID { get; set; } - public int Layer { get; set; } - public int MaxNousValue { get; set; } - public List NextIDList { get; set; } = []; - public int RequireArea { get; set; } - - public override int GetId() - { - return StoryID; - } - - public override void Loaded() - { - GameData.RogueNousSubStoryData.Add(GetId(), this); - } + return StoryID; } -} + + public override void Loaded() + { + GameData.RogueNousSubStoryData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueNousTalentExcel.cs b/Common/Data/Excel/RogueNousTalentExcel.cs index b4fc79c6..953f2724 100644 --- a/Common/Data/Excel/RogueNousTalentExcel.cs +++ b/Common/Data/Excel/RogueNousTalentExcel.cs @@ -1,24 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueNousTalent.json")] +public class RogueNousTalentExcel : ExcelResource { - [ResourceEntity("RogueNousTalent.json")] - public class RogueNousTalentExcel : ExcelResource + public int TalentID { get; set; } + + public override int GetId() { - public int TalentID { get; set; } - - public override int GetId() - { - return TalentID; - } - - public override void Loaded() - { - GameData.RogueNousTalentData[TalentID] = this; - } + return TalentID; } -} + + public override void Loaded() + { + GameData.RogueNousTalentData[TalentID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueRoomExcel.cs b/Common/Data/Excel/RogueRoomExcel.cs index 1d4192cd..01a670b2 100644 --- a/Common/Data/Excel/RogueRoomExcel.cs +++ b/Common/Data/Excel/RogueRoomExcel.cs @@ -1,28 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueRoom.json")] +public class RogueRoomExcel : ExcelResource { - [ResourceEntity("RogueRoom.json")] - public class RogueRoomExcel : ExcelResource + public int RogueRoomID { get; set; } + public int RogueRoomType { get; set; } + public int MapEntrance { get; set; } + public int GroupID { get; set; } + public Dictionary GroupWithContent { get; set; } = []; + + public override int GetId() { - public int RogueRoomID { get; set; } - public int RogueRoomType { get; set; } - public int MapEntrance { get; set; } - public int GroupID { get; set; } - public Dictionary GroupWithContent { get; set; } = []; - - public override int GetId() - { - return RogueRoomID; - } - - public override void Loaded() - { - GameData.RogueRoomData.Add(RogueRoomID, this); - } + return RogueRoomID; } -} + + public override void Loaded() + { + GameData.RogueRoomData.Add(RogueRoomID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RogueTalentExcel.cs b/Common/Data/Excel/RogueTalentExcel.cs index 2441ae68..33db3d59 100644 --- a/Common/Data/Excel/RogueTalentExcel.cs +++ b/Common/Data/Excel/RogueTalentExcel.cs @@ -1,25 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RogueTalent.json")] +public class RogueTalentExcel : ExcelResource { - [ResourceEntity("RogueTalent.json")] - public class RogueTalentExcel : ExcelResource + public int TalentID { get; set; } + public bool IsImportant { get; set; } + + public override int GetId() { - public int TalentID { get; set; } - public bool IsImportant { get; set; } - - public override int GetId() - { - return TalentID; - } - - public override void Loaded() - { - GameData.RogueTalentData.Add(GetId(), this); - } + return TalentID; } -} + + public override void Loaded() + { + GameData.RogueTalentData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/RollShopConfigExcel.cs b/Common/Data/Excel/RollShopConfigExcel.cs index be5fb938..b523bb82 100644 --- a/Common/Data/Excel/RollShopConfigExcel.cs +++ b/Common/Data/Excel/RollShopConfigExcel.cs @@ -1,41 +1,34 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RollShopConfig.json")] +public class RollShopConfigExcel : ExcelResource { - [ResourceEntity("RollShopConfig.json")] - public class RollShopConfigExcel : ExcelResource + public int RollShopID { get; set; } + public List SpecialGroupList { get; set; } = []; + public uint CostItemID { get; set; } + public uint CostItemNum { get; set; } + public uint T1GroupID { get; set; } + public uint T2GroupID { get; set; } + public uint T3GroupID { get; set; } + public uint T4GroupID { get; set; } + public uint SecretGroupID { get; set; } + public string RollShopType { get; set; } = ""; + public uint IntroduceID { get; set; } + public HashName ShopName { get; set; } = new(); + + public override int GetId() { - public int RollShopID { get; set; } - public List SpecialGroupList { get; set; } = []; - public uint CostItemID { get; set; } - public uint CostItemNum { get; set; } - public uint T1GroupID { get; set; } - public uint T2GroupID { get; set; } - public uint T3GroupID { get; set; } - public uint T4GroupID { get; set; } - public uint SecretGroupID { get; set; } - public string RollShopType { get; set; } = ""; - public uint IntroduceID { get; set; } - public HashName ShopName { get; set; } = new(); - - public override int GetId() - { - return RollShopID; - } - - public override void Loaded() - { - GameData.RollShopConfigData.Add(GetId(), this); - } + return RollShopID; } - public class SpecialGroup + public override void Loaded() { - public string GroupID { get; set; } = ""; - public int GroupValue { get; set; } + GameData.RollShopConfigData.Add(GetId(), this); } } + +public class SpecialGroup +{ + public string GroupID { get; set; } = ""; + public int GroupValue { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Excel/RollShopRewardExcel.cs b/Common/Data/Excel/RollShopRewardExcel.cs index ea14d427..5824d05d 100644 --- a/Common/Data/Excel/RollShopRewardExcel.cs +++ b/Common/Data/Excel/RollShopRewardExcel.cs @@ -1,26 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("RollShopReward.json")] +public class RollShopRewardExcel : ExcelResource { - [ResourceEntity("RollShopReward.json")] - public class RollShopRewardExcel : ExcelResource + public uint GroupID { get; set; } + public uint RewardID { get; set; } + + public override int GetId() { - public uint GroupID { get; set; } - public uint RewardID { get; set; } - - public override int GetId() - { - return (int)RewardID; - } - - - public override void Loaded() - { - GameData.RollShopRewardData.Add(GetId(), this); - } + return (int)RewardID; } -} + + + public override void Loaded() + { + GameData.RollShopRewardData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/ShopConfigExcel.cs b/Common/Data/Excel/ShopConfigExcel.cs index 1fec7c5a..86472104 100644 --- a/Common/Data/Excel/ShopConfigExcel.cs +++ b/Common/Data/Excel/ShopConfigExcel.cs @@ -1,27 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("ShopConfig.json")] +public class ShopConfigExcel : ExcelResource { - [ResourceEntity("ShopConfig.json")] - public class ShopConfigExcel : ExcelResource + public int ShopID { get; set; } + public int ShopType { get; set; } + + public List Goods { get; set; } = []; + + public override int GetId() { - public int ShopID { get; set; } - public int ShopType { get; set; } - - public List Goods { get; set; } = []; - - public override int GetId() - { - return ShopID; - } - - public override void Loaded() - { - GameData.ShopConfigData.Add(GetId(), this); - } + return ShopID; } -} + + public override void Loaded() + { + GameData.ShopConfigData.Add(GetId(), this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/ShopGoodsConfigExcel.cs b/Common/Data/Excel/ShopGoodsConfigExcel.cs index 301a5c36..8003e60f 100644 --- a/Common/Data/Excel/ShopGoodsConfigExcel.cs +++ b/Common/Data/Excel/ShopGoodsConfigExcel.cs @@ -1,50 +1,43 @@ using EggLink.DanhengServer.Proto; using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("ShopGoodsConfig.json")] +public class ShopGoodsConfigExcel : ExcelResource { - [ResourceEntity("ShopGoodsConfig.json")] - public class ShopGoodsConfigExcel : ExcelResource + public int GoodsID { get; set; } + public int ShopID { get; set; } + public int ItemID { get; set; } + public int ItemCount { get; set; } + public List CurrencyList { get; set; } = []; + public List CurrencyCostList { get; set; } = []; + + [JsonIgnore] public Dictionary CostList { get; set; } = []; + + public override int GetId() { - public int GoodsID { get; set; } - public int ShopID { get; set; } - public int ItemID { get; set; } - public int ItemCount { get; set; } - public List CurrencyList { get; set; } = []; - public List CurrencyCostList { get; set; } = []; + return GoodsID; + } - [JsonIgnore] - public Dictionary CostList { get; set; } = []; + public override void Loaded() + { + for (var i = 0; i < CurrencyList.Count; i++) CostList.Add(CurrencyList[i], CurrencyCostList[i]); + } - public override int GetId() - { - return GoodsID; - } + public override void AfterAllDone() + { + var shopConfig = GameData.ShopConfigData[ShopID]; + shopConfig.Goods.Add(this); + } - public override void Loaded() - { - for (int i = 0; i < CurrencyList.Count; i++) - { - CostList.Add(CurrencyList[i], CurrencyCostList[i]); - } - } - - public override void AfterAllDone() - { - var shopConfig = GameData.ShopConfigData[ShopID]; - shopConfig.Goods.Add(this); - } - - public Goods ToProto() => new() + public Goods ToProto() + { + return new Goods { EndTime = long.MaxValue, GoodsId = (uint)GoodsID, - ItemId = (uint)ItemID, + ItemId = (uint)ItemID }; } -} +} \ No newline at end of file diff --git a/Common/Data/Excel/SpecialAvatarExcel.cs b/Common/Data/Excel/SpecialAvatarExcel.cs index f09448bb..ff5ad1ff 100644 --- a/Common/Data/Excel/SpecialAvatarExcel.cs +++ b/Common/Data/Excel/SpecialAvatarExcel.cs @@ -1,98 +1,87 @@ using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Avatar; +using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Enums.Avatar; -using EggLink.DanhengServer.Proto; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("SpecialAvatar.json")] +public class SpecialAvatarExcel : ExcelResource { - [ResourceEntity("SpecialAvatar.json")] - public class SpecialAvatarExcel : ExcelResource + public int SpecialAvatarID { get; set; } + public int WorldLevel { get; set; } + public int AvatarID { get; set; } + public int PlayerID { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public SpecialAvatarTypeEnum Type { get; set; } + + public int Level { get; set; } + public int Promotion { get; set; } + public int Rank { get; set; } + public int EquipmentID { get; set; } + public int EquipmentLevel { get; set; } + public int EquipmentPromotion { get; set; } + public int EquipmentRank { get; set; } + public int RelicPropertyType { get; set; } + public int RelicPropertyTypeExtra { get; set; } + + [JsonIgnore] public Dictionary CurHp { get; set; } = []; + + [JsonIgnore] public Dictionary CurSp { get; set; } = []; + + [JsonIgnore] public Dictionary EntityId { get; set; } = []; + + public override int GetId() { - public int SpecialAvatarID { get; set; } - public int WorldLevel { get; set; } - public int AvatarID { get; set; } - public int PlayerID { get; set; } - - [JsonConverter(typeof(StringEnumConverter))] - public SpecialAvatarTypeEnum Type { get; set; } - - public int Level { get; set; } - public int Promotion { get; set; } - public int Rank { get; set; } - public int EquipmentID { get; set; } - public int EquipmentLevel { get; set; } - public int EquipmentPromotion { get; set; } - public int EquipmentRank { get; set; } - public int RelicPropertyType { get; set; } - public int RelicPropertyTypeExtra { get; set; } - - [JsonIgnore()] - public Dictionary CurHp { get; set; } = []; - [JsonIgnore()] - public Dictionary CurSp { get; set; } = []; - [JsonIgnore()] - public Dictionary EntityId { get; set; } = []; - - public override int GetId() - { - return SpecialAvatarID * 10 + WorldLevel; - } - - public override void Loaded() - { - GameData.SpecialAvatarData[GetId()] = this; - } - - public override void AfterAllDone() - { - // TODO Relic handler - } - - public AvatarInfo ToAvatarData(int uid) - { - CurHp.TryGetValue(uid, out var hp); - CurSp.TryGetValue(uid, out var sp); - EntityId.TryGetValue(uid, out var Id); - - GameData.AvatarConfigData.TryGetValue(PlayerID, out var avatarConfig); - - var instance = new AvatarInfo() - { - AvatarId = AvatarID, - SpecialBaseAvatarId = SpecialAvatarID, - Level = Level, - Promotion = Promotion, - Rank = Rank, - EquipData = new() - { - ItemId = EquipmentID, - Level = EquipmentLevel, - Promotion = EquipmentPromotion, - Rank = EquipmentRank - }, - CurrentHp = hp == 0 ? 10000 : hp, - CurrentSp = sp, - InternalEntityId = Id, - PlayerData = DatabaseHelper.Instance!.GetInstance(uid), - }; - - if (avatarConfig != null) - { - foreach (var skill in avatarConfig.DefaultSkillTree) - { - instance.SkillTree.Add(skill.PointID, skill.Level); - } - } - - return instance; - } + return SpecialAvatarID * 10 + WorldLevel; } -} + + public override void Loaded() + { + GameData.SpecialAvatarData[GetId()] = this; + } + + public override void AfterAllDone() + { + // TODO Relic handler + } + + public AvatarInfo ToAvatarData(int uid) + { + CurHp.TryGetValue(uid, out var hp); + CurSp.TryGetValue(uid, out var sp); + EntityId.TryGetValue(uid, out var Id); + + GameData.AvatarConfigData.TryGetValue(PlayerID, out var avatarConfig); + + var instance = new AvatarInfo + { + AvatarId = AvatarID, + SpecialBaseAvatarId = SpecialAvatarID, + Level = Level, + Promotion = Promotion, + Rank = Rank, + EquipData = new ItemData + { + ItemId = EquipmentID, + Level = EquipmentLevel, + Promotion = EquipmentPromotion, + Rank = EquipmentRank + }, + CurrentHp = hp == 0 ? 10000 : hp, + CurrentSp = sp, + InternalEntityId = Id, + PlayerData = DatabaseHelper.Instance!.GetInstance(uid) + }; + + if (avatarConfig != null) + foreach (var skill in avatarConfig.DefaultSkillTree) + instance.SkillTree.Add(skill.PointID, skill.Level); + + return instance; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/SpecialAvatarRelicExcel.cs b/Common/Data/Excel/SpecialAvatarRelicExcel.cs index 260707f2..bf16cb9b 100644 --- a/Common/Data/Excel/SpecialAvatarRelicExcel.cs +++ b/Common/Data/Excel/SpecialAvatarRelicExcel.cs @@ -1,29 +1,27 @@ using Newtonsoft.Json; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("SpecialAvatarRelic.json")] +public class SpecialAvatarRelicExcel : ExcelResource { - [ResourceEntity("SpecialAvatarRelic.json")] - public class SpecialAvatarRelicExcel : ExcelResource + public int RelicPropertyType { get; set; } + public List RelicIDList { get; set; } = []; + + public override int GetId() { - public int RelicPropertyType { get; set; } - public List RelicIDList { get; set; } = []; - - public override int GetId() - { - return RelicPropertyType; - } - - public override void Loaded() - { - GameData.SpecialAvatarRelicData[GetId()] = this; - } + return RelicPropertyType; } - public class SpecialAvatarRelicInfo + public override void Loaded() { - [JsonProperty("BDHIKPAMCJF")] - public int RelicID { get; set; } - [JsonProperty("PKAFFFBFJII")] - public int RelicLevel { get; set; } + GameData.SpecialAvatarRelicData[GetId()] = this; } } + +public class SpecialAvatarRelicInfo +{ + [JsonProperty("BDHIKPAMCJF")] public int RelicID { get; set; } + + [JsonProperty("PKAFFFBFJII")] public int RelicLevel { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Excel/StageConfigExcel.cs b/Common/Data/Excel/StageConfigExcel.cs index 81cb99a3..eef850b1 100644 --- a/Common/Data/Excel/StageConfigExcel.cs +++ b/Common/Data/Excel/StageConfigExcel.cs @@ -1,81 +1,81 @@ using EggLink.DanhengServer.Proto; -using System.Collections.Generic; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("StageConfig.json", false)] +public class StageConfigExcel : ExcelResource { - [ResourceEntity("StageConfig.json", false)] - public class StageConfigExcel : ExcelResource + public int StageID { get; set; } = 0; + public HashName StageName { get; set; } = new(); + public List MonsterList { get; set; } = []; + public List TrialAvatarList { get; set; } = []; + + + public override int GetId() { - public int StageID { get; set; } = 0; - public HashName StageName { get; set; } = new HashName(); - public List MonsterList { get; set; } = []; - public List TrialAvatarList { get; set; } = []; + return StageID; + } + public override void Loaded() + { + GameData.StageConfigData.Add(StageID, this); + } - public override int GetId() + public List ToProto() + { + var result = new List(); + var waveId = 1; + foreach (var monsters in MonsterList) { - return StageID; - } - public override void Loaded() - { - GameData.StageConfigData.Add(StageID, this); - } - - public List ToProto() - { - var result = new List(); - var waveId = 1; - foreach (var monsters in MonsterList) + var proto = new SceneMonsterWave { - var proto = new SceneMonsterWave() - { - WaveId = (uint)waveId++, - StageId = (uint)StageID, - }; + WaveId = (uint)waveId++, + StageId = (uint)StageID + }; - proto.MonsterList.Add(new SceneMonster() - { - MonsterId = (uint)monsters.Monster0, - }); + proto.MonsterList.Add(new SceneMonster + { + MonsterId = (uint)monsters.Monster0 + }); - proto.MonsterList.Add(new SceneMonster() - { - MonsterId = (uint)monsters.Monster1, - }); + proto.MonsterList.Add(new SceneMonster + { + MonsterId = (uint)monsters.Monster1 + }); - proto.MonsterList.Add(new SceneMonster() - { - MonsterId = (uint)monsters.Monster2, - }); + proto.MonsterList.Add(new SceneMonster + { + MonsterId = (uint)monsters.Monster2 + }); - proto.MonsterList.Add(new SceneMonster() - { - MonsterId = (uint)monsters.Monster3, - }); + proto.MonsterList.Add(new SceneMonster + { + MonsterId = (uint)monsters.Monster3 + }); - proto.MonsterList.Add(new SceneMonster() - { - MonsterId = (uint)monsters.Monster4, - }); + proto.MonsterList.Add(new SceneMonster + { + MonsterId = (uint)monsters.Monster4 + }); - proto.MonsterParam = new(); - result.Add(proto); - } - return result; + proto.MonsterParam = new SceneMonsterWaveParam(); + result.Add(proto); } - } - public class StageMonsterList - { - public int Monster0 { get; set; } = 0; - public int Monster1 { get; set; } = 0; - public int Monster2 { get; set; } = 0; - public int Monster3 { get; set; } = 0; - public int Monster4 { get; set; } = 0; - } - - public class HashName - { - public long Hash { get; set; } = 0; + return result; } } + +public class StageMonsterList +{ + public int Monster0 { get; set; } = 0; + public int Monster1 { get; set; } = 0; + public int Monster2 { get; set; } = 0; + public int Monster3 { get; set; } = 0; + public int Monster4 { get; set; } = 0; +} + +public class HashName +{ + public long Hash { get; set; } = 0; +} \ No newline at end of file diff --git a/Common/Data/Excel/StoryLineExcel.cs b/Common/Data/Excel/StoryLineExcel.cs index 5eb6cf20..a8361224 100644 --- a/Common/Data/Excel/StoryLineExcel.cs +++ b/Common/Data/Excel/StoryLineExcel.cs @@ -1,39 +1,34 @@ using EggLink.DanhengServer.Enums.Mission; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("StoryLine.json")] +public class StoryLineExcel : ExcelResource { - [ResourceEntity("StoryLine.json")] - public class StoryLineExcel : ExcelResource + public int StoryLineID { get; set; } + public StoryLineCondition BeginCondition { get; set; } = new(); + public StoryLineCondition EndCondition { get; set; } = new(); + public int InitEntranceID { get; set; } + public int InitGroupID { get; set; } + public int InitAnchorID { get; set; } + + public override int GetId() { - public int StoryLineID { get; set; } - public StoryLineCondition BeginCondition { get; set; } = new(); - public StoryLineCondition EndCondition { get; set; } = new(); - public int InitEntranceID { get; set; } - public int InitGroupID { get; set; } - public int InitAnchorID { get; set; } - - public override int GetId() - { - return StoryLineID; - } - - public override void Loaded() - { - GameData.StoryLineData[StoryLineID] = this; - } + return StoryLineID; } - public class StoryLineCondition + public override void Loaded() { - [JsonConverter(typeof(StringEnumConverter))] - public StoryLineConditionTypeEnum Type { get; set; } = new(); - public int Param { get; set; } + GameData.StoryLineData[StoryLineID] = this; } } + +public class StoryLineCondition +{ + [JsonConverter(typeof(StringEnumConverter))] + public StoryLineConditionTypeEnum Type { get; set; } = new(); + + public int Param { get; set; } +} \ No newline at end of file diff --git a/Common/Data/Excel/StoryLineFloorDataExcel.cs b/Common/Data/Excel/StoryLineFloorDataExcel.cs index 0b8c8752..c56a7e6e 100644 --- a/Common/Data/Excel/StoryLineFloorDataExcel.cs +++ b/Common/Data/Excel/StoryLineFloorDataExcel.cs @@ -1,32 +1,26 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("StoryLineFloorData.json")] +public class StoryLineFloorDataExcel : ExcelResource { - [ResourceEntity("StoryLineFloorData.json")] - public class StoryLineFloorDataExcel : ExcelResource + public int FloorID { get; set; } + public int StoryLineID { get; set; } + public int DimensionID { get; set; } + + public override int GetId() { - public int FloorID { get; set; } - public int StoryLineID { get; set; } - public int DimensionID { get; set; } - - public override int GetId() - { - return FloorID; - } - - public override void Loaded() - { - GameData.StoryLineFloorDataData.TryGetValue(StoryLineID, out var data); - if (data == null) - { - data = []; - GameData.StoryLineFloorDataData.Add(StoryLineID, data); - } - data.Add(FloorID, this); - } + return FloorID; } -} + + public override void Loaded() + { + GameData.StoryLineFloorDataData.TryGetValue(StoryLineID, out var data); + if (data == null) + { + data = []; + GameData.StoryLineFloorDataData.Add(StoryLineID, data); + } + + data.Add(FloorID, this); + } +} \ No newline at end of file diff --git a/Common/Data/Excel/StroyLineTrialAvatarDataExcel.cs b/Common/Data/Excel/StroyLineTrialAvatarDataExcel.cs index 34c08c04..572805e1 100644 --- a/Common/Data/Excel/StroyLineTrialAvatarDataExcel.cs +++ b/Common/Data/Excel/StroyLineTrialAvatarDataExcel.cs @@ -1,27 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("StroyLineTrialAvatarData.json")] +public class StroyLineTrialAvatarDataExcel : ExcelResource { - [ResourceEntity("StroyLineTrialAvatarData.json")] - public class StroyLineTrialAvatarDataExcel : ExcelResource + public int StoryLineID { get; set; } + public List TrialAvatarList { get; set; } = []; + public List InitTrialAvatarList { get; set; } = []; + public int CaptainAvatarID { get; set; } + + public override int GetId() { - public int StoryLineID { get; set; } - public List TrialAvatarList { get; set; } = []; - public List InitTrialAvatarList { get; set; } = []; - public int CaptainAvatarID { get; set; } - - public override int GetId() - { - return StoryLineID; - } - - public override void Loaded() - { - GameData.StroyLineTrialAvatarDataData[StoryLineID] = this; - } + return StoryLineID; } -} + + public override void Loaded() + { + GameData.StroyLineTrialAvatarDataData[StoryLineID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/SubMissionExcel.cs b/Common/Data/Excel/SubMissionExcel.cs index 4b912d5a..66c0997a 100644 --- a/Common/Data/Excel/SubMissionExcel.cs +++ b/Common/Data/Excel/SubMissionExcel.cs @@ -1,33 +1,30 @@ using EggLink.DanhengServer.Data.Config; using Newtonsoft.Json; -namespace EggLink.DanhengServer.Data.Excel +namespace EggLink.DanhengServer.Data.Excel; + +[ResourceEntity("SubMission.json")] +public class SubMissionExcel : ExcelResource { - [ResourceEntity("SubMission.json")] - public class SubMissionExcel : ExcelResource + public int SubMissionID { get; set; } + + public HashName TargetText { get; set; } = new(); + + [JsonIgnore] public int MainMissionID { get; set; } + + [JsonIgnore] public MissionInfo? MainMissionInfo { get; set; } + + [JsonIgnore] public SubMissionInfo? SubMissionInfo { get; set; } + + [JsonIgnore] public LevelGraphConfigInfo? SubMissionTaskInfo { get; set; } + + public override int GetId() { - public int SubMissionID { get; set; } - - public HashName TargetText { get; set; } = new(); - - [JsonIgnore()] - public int MainMissionID { get; set; } - [JsonIgnore()] - public MissionInfo? MainMissionInfo { get; set; } - [JsonIgnore()] - public SubMissionInfo? SubMissionInfo { get; set; } - - [JsonIgnore()] - public LevelGraphConfigInfo? SubMissionTaskInfo { get; set; } - - public override int GetId() - { - return SubMissionID; - } - - public override void Loaded() - { - GameData.SubMissionData[GetId()] = this; - } + return SubMissionID; } -} + + public override void Loaded() + { + GameData.SubMissionData[GetId()] = this; + } +} \ No newline at end of file diff --git a/Common/Data/Excel/SummonUnitExcel.cs b/Common/Data/Excel/SummonUnitExcel.cs index 5a30165a..138914f9 100644 --- a/Common/Data/Excel/SummonUnitExcel.cs +++ b/Common/Data/Excel/SummonUnitExcel.cs @@ -1,25 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Data.Excel +[ResourceEntity("SummonUnitData.json")] +public class SummonUnitExcel : ExcelResource { - [ResourceEntity("SummonUnitData.json")] - public class SummonUnitExcel : ExcelResource + public int ID { get; set; } = 0; + public string JsonPath { get; set; } = ""; + + public override int GetId() { - public int ID { get; set; } = 0; - public string JsonPath { get; set; } = ""; - - public override int GetId() - { - return ID; - } - - public override void Loaded() - { - GameData.SummonUnitData[ID] = this; - } + return ID; } -} + + public override void Loaded() + { + GameData.SummonUnitData[ID] = this; + } +} \ No newline at end of file diff --git a/Common/Data/ExcelResource.cs b/Common/Data/ExcelResource.cs index 0ec48d3f..b1978cbf 100644 --- a/Common/Data/ExcelResource.cs +++ b/Common/Data/ExcelResource.cs @@ -1,25 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Data; -namespace EggLink.DanhengServer.Data +public abstract class ExcelResource { - public abstract class ExcelResource + public abstract int GetId(); + + public virtual void Loaded() { - public abstract int GetId(); - - public virtual void Loaded() - { - } - - public virtual void Finalized() - { - } - - public virtual void AfterAllDone() - { - } } -} + + public virtual void Finalized() + { + } + + public virtual void AfterAllDone() + { + } +} \ No newline at end of file diff --git a/Common/Data/GameData.cs b/Common/Data/GameData.cs index ca65d4f0..9b5c6dfc 100644 --- a/Common/Data/GameData.cs +++ b/Common/Data/GameData.cs @@ -3,201 +3,224 @@ using EggLink.DanhengServer.Data.Custom; using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Enums.Rogue; -namespace EggLink.DanhengServer.Data +namespace EggLink.DanhengServer.Data; + +public static class GameData { - public static class GameData + #region Activity + + public static ActivityConfig ActivityConfig { get; set; } = new(); + + #endregion + + #region Banners + + public static BannersConfig BannersConfig { get; set; } = new(); + + #endregion + + #region Avatar + + public static Dictionary AvatarConfigData { get; private set; } = []; + public static Dictionary AvatarPromotionConfigData { get; private set; } = []; + public static Dictionary AvatarExpItemConfigData { get; private set; } = []; + public static Dictionary AvatarSkillTreeConfigData { get; private set; } = []; + public static Dictionary ExpTypeData { get; } = []; + public static Dictionary AdventurePlayerData { get; private set; } = []; + public static Dictionary SummonUnitData { get; private set; } = []; + + #endregion + + #region Challenge + + public static Dictionary ChallengeConfigData { get; private set; } = []; + public static Dictionary ChallengeTargetData { get; private set; } = []; + public static Dictionary ChallengeGroupData { get; private set; } = []; + public static Dictionary> ChallengeRewardData { get; private set; } = []; + + #endregion + + #region Battle + + public static Dictionary CocoonConfigData { get; private set; } = []; + public static Dictionary StageConfigData { get; private set; } = []; + public static Dictionary RaidConfigData { get; private set; } = []; + public static Dictionary MazeBuffData { get; private set; } = []; + public static Dictionary InteractConfigData { get; private set; } = []; + public static Dictionary NpcMonsterDataData { get; private set; } = []; + public static Dictionary MonsterConfigData { get; private set; } = []; + public static Dictionary MonsterDropData { get; private set; } = []; + + #endregion + + #region ChessRogue + + public static Dictionary ActionPointOverdrawData { get; private set; } = []; + + public static Dictionary> + ChessRogueRoomData { get; private set; } = []; + + public static Dictionary RogueDLCAreaData { get; private set; } = []; + public static Dictionary RogueDLCBossDecayData { get; private set; } = []; + public static Dictionary RogueDLCBossBpData { get; private set; } = []; + public static Dictionary RogueDLCDifficultyData { get; private set; } = []; + public static Dictionary RogueNousAeonData { get; private set; } = []; + public static Dictionary RogueNousDiceBranchData { get; private set; } = []; + public static Dictionary RogueNousDiceSurfaceData { get; private set; } = []; + + public static Dictionary RogueNousDifficultyLevelData { get; private set; } = + []; + + public static Dictionary RogueNousMainStoryData { get; private set; } = []; + public static Dictionary RogueNousSubStoryData { get; private set; } = []; + public static Dictionary RogueNousTalentData { get; private set; } = []; + public static Dictionary> RogueSwarmChessBoardData { get; private set; } = []; + public static Dictionary> RogueNousChessBoardData { get; private set; } = []; + + #endregion + + #region Player + + public static Dictionary QuestDataData { get; private set; } = []; + public static Dictionary PlayerLevelConfigData { get; private set; } = []; + public static Dictionary BackGroundMusicData { get; private set; } = []; + public static Dictionary ChatBubbleConfigData { get; private set; } = []; + + #endregion + + #region Maze + + public static Dictionary NpcDataData { get; private set; } = []; + public static Dictionary FloorInfoData { get; } = []; + public static Dictionary MapEntranceData { get; private set; } = []; + public static Dictionary MazePlaneData { get; private set; } = []; + public static Dictionary MazePropData { get; private set; } = []; + public static Dictionary PlaneEventData { get; private set; } = []; + public static Dictionary ContentPackageConfigData { get; private set; } = []; + + #endregion + + #region Items + + public static Dictionary MappingInfoData { get; private set; } = []; + public static Dictionary ItemConfigData { get; private set; } = []; + public static Dictionary EquipmentConfigData { get; private set; } = []; + public static Dictionary EquipmentExpTypeData { get; } = []; + public static Dictionary EquipmentExpItemConfigData { get; private set; } = []; + + public static Dictionary EquipmentPromotionConfigData { get; private set; } = + []; + + public static Dictionary> RelicMainAffixData { get; private set; } = + []; // groupId, affixId + + public static Dictionary> RelicSubAffixData { get; private set; } = + []; // groupId, affixId + + public static Dictionary RelicConfigData { get; private set; } = []; + public static Dictionary RelicExpItemData { get; private set; } = []; + public static Dictionary RelicExpTypeData { get; private set; } = []; + + #endregion + + #region Special Avatar + + public static Dictionary SpecialAvatarData { get; private set; } = []; + public static Dictionary SpecialAvatarRelicData { get; private set; } = []; + + #endregion + + #region Mission + + public static Dictionary MainMissionData { get; private set; } = []; + public static Dictionary SubMissionData { get; private set; } = []; + public static Dictionary RewardDataData { get; private set; } = []; + public static Dictionary MessageGroupConfigData { get; private set; } = []; + public static Dictionary MessageSectionConfigData { get; private set; } = []; + public static Dictionary MessageContactsConfigData { get; private set; } = []; + public static Dictionary MessageItemConfigData { get; private set; } = []; + public static Dictionary PerformanceDData { get; private set; } = []; + public static Dictionary PerformanceEData { get; private set; } = []; + public static Dictionary StoryLineData { get; private set; } = []; + + public static Dictionary> + StoryLineFloorDataData { get; private set; } = []; + + public static Dictionary StroyLineTrialAvatarDataData { get; private set; } = + []; + + public static Dictionary HeartDialScriptData { get; private set; } = []; + public static Dictionary HeartDialDialogueData { get; private set; } = []; + + #endregion + + #region Item Exchange + + public static Dictionary ShopConfigData { get; private set; } = []; + public static Dictionary RollShopConfigData { get; private set; } = []; + public static Dictionary RollShopRewardData { get; private set; } = []; + public static Dictionary ItemComposeConfigData { get; private set; } = []; + + #endregion + + #region Rogue + + public static Dictionary DialogueEventData { get; private set; } = []; + + public static Dictionary> DialogueDynamicContentData { - #region Activity + get; + private set; + } = []; - public static ActivityConfig ActivityConfig { get; set; } = new(); + public static Dictionary RogueAeonData { get; private set; } = []; + public static Dictionary RogueAeonBuffData { get; private set; } = []; + public static Dictionary RogueBattleEventData { get; private set; } = []; + public static Dictionary> RogueAeonEnhanceData { get; private set; } = []; + public static Dictionary RogueAreaConfigData { get; private set; } = []; + public static Dictionary RogueBonusData { get; private set; } = []; + public static Dictionary RogueBuffData { get; private set; } = []; + public static Dictionary RogueBuffGroupData { get; private set; } = []; + public static Dictionary RogueHandBookEventData { get; private set; } = []; + public static Dictionary RogueHandbookMiracleData { get; private set; } = []; + public static Dictionary RogueManagerData { get; private set; } = []; + public static Dictionary> RogueMapData { get; private set; } = []; + public static Dictionary> RogueMapGenData { get; set; } = []; + public static Dictionary RogueMazeBuffData { get; private set; } = []; + public static Dictionary RogueMiracleData { get; private set; } = []; + public static RogueMiracleEffectConfig RogueMiracleEffectData { get; set; } = new(); + public static Dictionary> RogueMiracleGroupData { get; set; } = []; + public static Dictionary RogueMiracleDisplayData { get; private set; } = []; + public static Dictionary RogueMonsterData { get; private set; } = []; + public static Dictionary RogueNPCDialogueData { get; private set; } = []; + public static Dictionary RogueRoomData { get; private set; } = []; + public static Dictionary RogueTalentData { get; private set; } = []; - #endregion + #endregion - #region Avatar + #region Actions - public static Dictionary AvatarConfigData { get; private set; } = []; - public static Dictionary AvatarPromotionConfigData { get; private set; } = []; - public static Dictionary AvatarExpItemConfigData { get; private set; } = []; - public static Dictionary AvatarSkillTreeConfigData { get; private set; } = []; - public static Dictionary ExpTypeData { get; private set; } = []; - public static Dictionary AdventurePlayerData { get; private set; } = []; - public static Dictionary SummonUnitData { get; private set; } = []; - - #endregion - - #region Challenge - - public static Dictionary ChallengeConfigData { get; private set; } = []; - public static Dictionary ChallengeTargetData { get; private set; } = []; - public static Dictionary ChallengeGroupData { get; private set; } = []; - public static Dictionary> ChallengeRewardData { get; private set; } = []; - - #endregion - - #region Battle - - public static Dictionary CocoonConfigData { get; private set; } = []; - public static Dictionary StageConfigData { get; private set; } = []; - public static Dictionary RaidConfigData { get; private set; } = []; - public static Dictionary MazeBuffData { get; private set; } = []; - public static Dictionary InteractConfigData { get; private set; } = []; - public static Dictionary NpcMonsterDataData { get; private set; } = []; - public static Dictionary MonsterConfigData { get; private set; } = []; - public static Dictionary MonsterDropData { get; private set; } = []; - - #endregion - - #region ChessRogue - - public static Dictionary ActionPointOverdrawData { get; private set; } = []; - public static Dictionary> ChessRogueRoomData { get; private set; } = []; - public static Dictionary RogueDLCAreaData { get; private set; } = []; - public static Dictionary RogueDLCBossDecayData { get; private set; } = []; - public static Dictionary RogueDLCBossBpData { get; private set; } = []; - public static Dictionary RogueDLCDifficultyData { get; private set; } = []; - public static Dictionary RogueNousAeonData { get; private set; } = []; - public static Dictionary RogueNousDiceBranchData { get; private set; } = []; - public static Dictionary RogueNousDiceSurfaceData { get; private set; } = []; - public static Dictionary RogueNousDifficultyLevelData { get; private set; } = []; - public static Dictionary RogueNousMainStoryData { get; private set; } = []; - public static Dictionary RogueNousSubStoryData { get; private set; } = []; - public static Dictionary RogueNousTalentData { get; private set; } = []; - public static Dictionary> RogueSwarmChessBoardData { get; private set; } = []; - public static Dictionary> RogueNousChessBoardData { get; private set; } = []; - - #endregion - - #region Player - - public static Dictionary QuestDataData { get; private set; } = []; - public static Dictionary PlayerLevelConfigData { get; private set; } = []; - public static Dictionary BackGroundMusicData { get; private set; } = []; - public static Dictionary ChatBubbleConfigData { get; private set; } = []; - - #endregion - - #region Maze - - public static Dictionary NpcDataData { get; private set; } = []; - public static Dictionary FloorInfoData { get; private set; } = []; - public static Dictionary MapEntranceData { get; private set; } = []; - public static Dictionary MazePlaneData { get; private set; } = []; - public static Dictionary MazePropData { get; private set; } = []; - public static Dictionary PlaneEventData { get; private set; } = []; - public static Dictionary ContentPackageConfigData { get; private set; } = []; - - #endregion - - #region Items - - public static Dictionary MappingInfoData { get; private set; } = []; - public static Dictionary ItemConfigData { get; private set; } = []; - public static Dictionary EquipmentConfigData { get; private set; } = []; - public static Dictionary EquipmentExpTypeData { get; private set; } = []; - public static Dictionary EquipmentExpItemConfigData { get; private set; } = []; - public static Dictionary EquipmentPromotionConfigData { get; private set; } = []; - public static Dictionary> RelicMainAffixData { get; private set; } = []; // groupId, affixId - public static Dictionary> RelicSubAffixData { get; private set; } = []; // groupId, affixId - public static Dictionary RelicConfigData { get; private set; } = []; - public static Dictionary RelicExpItemData { get; private set; } = []; - public static Dictionary RelicExpTypeData { get; private set; } = []; - - #endregion - - #region Special Avatar - - public static Dictionary SpecialAvatarData { get; private set; } = []; - public static Dictionary SpecialAvatarRelicData { get; private set; } = []; - - #endregion - - #region Mission - - public static Dictionary MainMissionData { get; private set; } = []; - public static Dictionary SubMissionData { get; private set; } = []; - public static Dictionary RewardDataData { get; private set; } = []; - public static Dictionary MessageGroupConfigData { get; private set; } = []; - public static Dictionary MessageSectionConfigData { get; private set; } = []; - public static Dictionary MessageContactsConfigData { get; private set; } = []; - public static Dictionary MessageItemConfigData { get; private set; } = []; - public static Dictionary PerformanceDData { get; private set; } = []; - public static Dictionary PerformanceEData { get; private set; } = []; - public static Dictionary StoryLineData { get; private set; } = []; - public static Dictionary> StoryLineFloorDataData { get; private set; } = []; - public static Dictionary StroyLineTrialAvatarDataData { get; private set; } = []; - - public static Dictionary HeartDialScriptData { get; private set; } = []; - public static Dictionary HeartDialDialogueData { get; private set; } = []; - - #endregion - - #region Item Exchange - - public static Dictionary ShopConfigData { get; private set; } = []; - public static Dictionary RollShopConfigData { get; private set; } = []; - public static Dictionary RollShopRewardData { get; private set; } = []; - public static Dictionary ItemComposeConfigData { get; private set; } = []; - - #endregion - - #region Rogue - - public static Dictionary DialogueEventData { get; private set; } = []; - public static Dictionary> DialogueDynamicContentData { get; private set; } = []; - public static Dictionary RogueAeonData { get; private set; } = []; - public static Dictionary RogueAeonBuffData { get; private set; } = []; - public static Dictionary RogueBattleEventData { get; private set; } = []; - public static Dictionary> RogueAeonEnhanceData { get; private set; } = []; - public static Dictionary RogueAreaConfigData { get; private set; } = []; - public static Dictionary RogueBonusData { get; private set; } = []; - public static Dictionary RogueBuffData { get; private set; } = []; - public static Dictionary RogueBuffGroupData { get; private set; } = []; - public static Dictionary RogueHandBookEventData { get; private set; } = []; - public static Dictionary RogueHandbookMiracleData { get; private set; } = []; - public static Dictionary RogueManagerData { get; private set; } = []; - public static Dictionary> RogueMapData { get; private set; } = []; - public static Dictionary> RogueMapGenData { get; set; } = []; - public static Dictionary RogueMazeBuffData { get; private set; } = []; - public static Dictionary RogueMiracleData { get; private set; } = []; - public static RogueMiracleEffectConfig RogueMiracleEffectData { get; set; } = new(); - public static Dictionary> RogueMiracleGroupData { get; set; } = []; - public static Dictionary RogueMiracleDisplayData { get; private set; } = []; - public static Dictionary RogueMonsterData { get; private set; } = []; - public static Dictionary RogueNPCDialogueData { get; private set; } = []; - public static Dictionary RogueRoomData { get; private set; } = []; - public static Dictionary RogueTalentData { get; private set; } = []; - - #endregion - - #region Banners - - public static BannersConfig BannersConfig { get; set; } = new(); - - #endregion - - #region Actions - - public static void GetFloorInfo(int planeId, int floorId, out FloorInfo outer) - { - FloorInfoData.TryGetValue("P" + planeId + "_F" + floorId, out outer!); - } - public static int GetAvatarExpRequired(int group, int level) - { - ExpTypeData.TryGetValue((group * 100) + level, out var expType); - return expType?.Exp ?? 0; - } - - public static int GetEquipmentExpRequired(int group, int level) - { - EquipmentExpTypeData.TryGetValue((group * 100) + level, out var expType); - return expType?.Exp ?? 0; - } - - public static int GetMinPromotionForLevel(int level) - { - return Math.Max(Math.Min((int)((level - 11) / 10D), 6), 0); - } - - #endregion + public static void GetFloorInfo(int planeId, int floorId, out FloorInfo outer) + { + FloorInfoData.TryGetValue("P" + planeId + "_F" + floorId, out outer!); } -} + + public static int GetAvatarExpRequired(int group, int level) + { + ExpTypeData.TryGetValue(group * 100 + level, out var expType); + return expType?.Exp ?? 0; + } + + public static int GetEquipmentExpRequired(int group, int level) + { + EquipmentExpTypeData.TryGetValue(group * 100 + level, out var expType); + return expType?.Exp ?? 0; + } + + public static int GetMinPromotionForLevel(int level) + { + return Math.Max(Math.Min((int)((level - 11) / 10D), 6), 0); + } + + #endregion +} \ No newline at end of file diff --git a/Common/Data/ResourceEntity.cs b/Common/Data/ResourceEntity.cs index 185b6e90..46783462 100644 --- a/Common/Data/ResourceEntity.cs +++ b/Common/Data/ResourceEntity.cs @@ -1,42 +1,33 @@ -using System; +namespace EggLink.DanhengServer.Data; -namespace EggLink.DanhengServer.Data +[AttributeUsage(AttributeTargets.Class, Inherited = false)] +public class ResourceEntity : Attribute { - - [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] - public class ResourceEntity : Attribute + [Obsolete("No effect")] + public ResourceEntity(string fileName, bool isCritical = false, bool isMultifile = false) { - public List FileName { get; private set; } - - [Obsolete("No effect")] - public bool IsCritical { get; private set; } // deprecated - - [Obsolete("No effect")] - public ResourceEntity(string fileName, bool isCritical = false, bool isMultifile = false) - { - if (isMultifile) - { - FileName = new List(fileName.Split(',')); - } - else - FileName = [fileName]; - IsCritical = isCritical; - } - - - public ResourceEntity(string fileName, bool isMultifile = false) - { - if (isMultifile) - { - FileName = new List(fileName.Split(',')); - } - else - FileName = [fileName]; - } - - public ResourceEntity(string fileName) - { - FileName = [fileName]; - } + if (isMultifile) + FileName = new List(fileName.Split(',')); + else + FileName = [fileName]; + IsCritical = isCritical; } -} + + + public ResourceEntity(string fileName, bool isMultifile = false) + { + if (isMultifile) + FileName = new List(fileName.Split(',')); + else + FileName = [fileName]; + } + + public ResourceEntity(string fileName) + { + FileName = [fileName]; + } + + public List FileName { get; private set; } + + [Obsolete("No effect")] public bool IsCritical { get; private set; } // deprecated +} \ No newline at end of file diff --git a/Common/Data/ResourceManager.cs b/Common/Data/ResourceManager.cs index f88d8f20..c5fcfaa9 100644 --- a/Common/Data/ResourceManager.cs +++ b/Common/Data/ResourceManager.cs @@ -1,616 +1,654 @@ -using System; -using System.Drawing; -using System.IO; -using System.Reflection; +using System.Reflection; using EggLink.DanhengServer.Data.Config; -using System.Xml.Linq; -using EggLink.DanhengServer.Util; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using EggLink.DanhengServer.Data.Custom; using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Internationalization; +using EggLink.DanhengServer.Util; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; -namespace EggLink.DanhengServer.Data +namespace EggLink.DanhengServer.Data; + +public class ResourceManager { - public class ResourceManager + public static Logger Logger { get; } = new("ResourceManager"); + + public static void LoadGameData() { - public static Logger Logger { get; private set; } = new Logger("ResourceManager"); - public static void LoadGameData() + LoadExcel(); + LoadFloorInfo(); + LoadMissionInfo(); + LoadMazeSkill(); + LoadDialogueInfo(); + LoadPerformanceInfo(); + LoadSubMissionInfo(); + LoadRogueChestMapInfo(); + GameData.ActivityConfig = LoadCustomFile("Activity", "ActivityConfig") ?? new ActivityConfig(); + GameData.BannersConfig = LoadCustomFile("Banner", "Banners") ?? new BannersConfig(); + GameData.RogueMapGenData = LoadCustomFile>>("Rogue Map", "RogueMapGen") ?? []; + GameData.RogueMiracleGroupData = + LoadCustomFile>>("Rogue Miracle Group", "RogueMiracleGroup") ?? []; + GameData.RogueMiracleEffectData = + LoadCustomFile("Rogue Miracle Effect", "RogueMiracleEffectGen") ?? + new RogueMiracleEffectConfig(); + LoadChessRogueRoomData(); + } + + public static void LoadExcel() + { + var classes = Assembly.GetExecutingAssembly().GetTypes(); // Get all classes in the assembly + var resList = new List(); + foreach (var cls in classes) { - LoadExcel(); - LoadFloorInfo(); - LoadMissionInfo(); - LoadMazeSkill(); - LoadDialogueInfo(); - LoadPerformanceInfo(); - LoadSubMissionInfo(); - LoadRogueChestMapInfo(); - GameData.ActivityConfig = LoadCustomFile("Activity", "ActivityConfig") ?? new(); - GameData.BannersConfig = LoadCustomFile("Banner", "Banners") ?? new(); - GameData.RogueMapGenData = LoadCustomFile>>("Rogue Map", "RogueMapGen") ?? []; - GameData.RogueMiracleGroupData = LoadCustomFile>>("Rogue Miracle Group", "RogueMiracleGroup") ?? []; - GameData.RogueMiracleEffectData = LoadCustomFile("Rogue Miracle Effect", "RogueMiracleEffectGen") ?? new(); - LoadChessRogueRoomData(); - } + var attribute = (ResourceEntity)Attribute.GetCustomAttribute(cls, typeof(ResourceEntity))!; - public static void LoadExcel() - { - - var classes = Assembly.GetExecutingAssembly().GetTypes(); // Get all classes in the assembly - var resList = new List(); - foreach (var cls in classes) + if (attribute != null) { - var attribute = (ResourceEntity)Attribute.GetCustomAttribute(cls, typeof(ResourceEntity))!; - - if (attribute != null) - { - var resource = (ExcelResource)Activator.CreateInstance(cls)!; - var count = 0; - foreach (var fileName in attribute.FileName) - { - try - { - var path = ConfigManager.Config.Path.ResourcePath + "/ExcelOutput/" + fileName; - var file = new FileInfo(path); - if (!file.Exists) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", fileName, I18nManager.Translate("Word.NotFound"))); - continue; - } - var json = file.OpenText().ReadToEnd(); - using (var reader = new JsonTextReader(new StringReader(json))) - { - reader.Read(); - if (reader.TokenType == JsonToken.StartArray) - { - // array - var jArray = JArray.Parse(json); - foreach (var item in jArray) - { - var res = JsonConvert.DeserializeObject(item.ToString(), cls); - resList.Add((ExcelResource)res!); - ((ExcelResource?)res)?.Loaded(); - count++; - } - } - else if (reader.TokenType == JsonToken.StartObject) - { - // dictionary - var jObject = JObject.Parse(json); - foreach (var item in jObject) - { - var id = int.Parse(item.Key); - var obj = item.Value; - var instance = JsonConvert.DeserializeObject(obj!.ToString(), cls); - - if (((ExcelResource?)instance)?.GetId() == 0 || ((ExcelResource?)instance) == null) - { - // Deserialize as JObject to handle nested dictionaries - var nestedObject = JsonConvert.DeserializeObject(obj.ToString()); - - foreach (var nestedItem in nestedObject ?? []) - { - var nestedInstance = JsonConvert.DeserializeObject(nestedItem.Value!.ToString(), cls); - resList.Add((ExcelResource)nestedInstance!); - ((ExcelResource?)nestedInstance)?.Loaded(); - count++; - } - } - else - { - resList.Add((ExcelResource)instance!); - ((ExcelResource)instance).Loaded(); - } - count++; - } - } - } - resource.Finalized(); - } - catch (Exception ex) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", fileName, I18nManager.Translate("Word.Error")), ex); - } - } - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), cls.Name)); - } - } - foreach (var cls in resList) - { - cls.AfterAllDone(); - } - } - - public static void LoadFloorInfo() - { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.FloorInfo"))); - DirectoryInfo directory = new(ConfigManager.Config.Path.ResourcePath + "/Config/LevelOutput/RuntimeFloor/"); - bool missingGroupInfos = false; - - if (!directory.Exists) - { - Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", I18nManager.Translate("Word.FloorInfo"), $"{ConfigManager.Config.Path.ResourcePath}/Config/LevelOutput/RuntimeFloor", I18nManager.Translate("Word.FloorMissingResult"))); - return; - } - // Load floor infos - foreach (FileInfo file in directory.GetFiles()) - { - try - { - using var reader = file.OpenRead(); - using StreamReader reader2 = new(reader); - var text = reader2.ReadToEnd(); - var info = JsonConvert.DeserializeObject(text); - var name = file.Name[..file.Name.IndexOf('.')]; - GameData.FloorInfoData.Add(name, info!); - } catch (Exception ex) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, I18nManager.Translate("Word.Error")), ex); - } - } - - foreach (var info in GameData.FloorInfoData.Values) - { - foreach (var groupInfo in info.GroupInstanceList) - { - if (groupInfo.IsDelete) { continue; } - FileInfo file = new(ConfigManager.Config.Path.ResourcePath + "/" + groupInfo.GroupPath); - if (!file.Exists) continue; + var resource = (ExcelResource)Activator.CreateInstance(cls)!; + var count = 0; + foreach (var fileName in attribute.FileName) try { - using var reader = file.OpenRead(); - using StreamReader reader2 = new(reader); - var text = reader2.ReadToEnd(); - GroupInfo? group = JsonConvert.DeserializeObject(text); - if (group != null) + var path = ConfigManager.Config.Path.ResourcePath + "/ExcelOutput/" + fileName; + var file = new FileInfo(path); + if (!file.Exists) { - group.Id = groupInfo.ID; - info.Groups.TryAdd(groupInfo.ID, group); - group.Load(); + Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", fileName, + I18nManager.Translate("Word.NotFound"))); + continue; + } - // load graph - var graphPath = ConfigManager.Config.Path.ResourcePath + "/" + group.LevelGraph; - var graphFile = new FileInfo(graphPath); - if (graphFile.Exists) + var json = file.OpenText().ReadToEnd(); + using (var reader = new JsonTextReader(new StringReader(json))) + { + reader.Read(); + if (reader.TokenType == JsonToken.StartArray) { - using var graphReader = graphFile.OpenRead(); - using StreamReader graphReader2 = new(graphReader); - var graphText = graphReader2.ReadToEnd().Replace("$type", "Type"); - var graphObj = JObject.Parse(graphText); - if (graphObj != null) + // array + var jArray = JArray.Parse(json); + foreach (var item in jArray) { - LevelGraphConfigInfo graphInfo = LevelGraphConfigInfo.LoadFromJsonObject(graphObj); - group.LevelGraphConfig = graphInfo; + var res = JsonConvert.DeserializeObject(item.ToString(), cls); + resList.Add((ExcelResource)res!); + ((ExcelResource?)res)?.Loaded(); + count++; + } + } + else if (reader.TokenType == JsonToken.StartObject) + { + // dictionary + var jObject = JObject.Parse(json); + foreach (var item in jObject) + { + var id = int.Parse(item.Key); + var obj = item.Value; + var instance = JsonConvert.DeserializeObject(obj!.ToString(), cls); + + if (((ExcelResource?)instance)?.GetId() == 0 || (ExcelResource?)instance == null) + { + // Deserialize as JObject to handle nested dictionaries + var nestedObject = JsonConvert.DeserializeObject(obj.ToString()); + + foreach (var nestedItem in nestedObject ?? []) + { + var nestedInstance = + JsonConvert.DeserializeObject(nestedItem.Value!.ToString(), cls); + resList.Add((ExcelResource)nestedInstance!); + ((ExcelResource?)nestedInstance)?.Loaded(); + count++; + } + } + else + { + resList.Add((ExcelResource)instance!); + ((ExcelResource)instance).Loaded(); + } + + count++; } } } - } catch (Exception ex) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, I18nManager.Translate("Word.Error")), ex); - } - if (info.Groups.Count == 0) - { - missingGroupInfos = true; - } - } - info.OnLoad(); - } - if (missingGroupInfos) - Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", I18nManager.Translate("Word.FloorGroupInfo"), $"{ConfigManager.Config.Path.ResourcePath}/Config/LevelOutput/SharedRuntimeGroup", I18nManager.Translate("Word.FloorGroupMissingResult"))); - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", GameData.FloorInfoData.Count.ToString(), I18nManager.Translate("Word.FloorInfo"))); + resource.Finalized(); + } + catch (Exception ex) + { + Logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToReadItem", fileName, + I18nManager.Translate("Word.Error")), ex); + } + + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), cls.Name)); + } } - public static void LoadMissionInfo() + foreach (var cls in resList) cls.AfterAllDone(); + } + + public static void LoadFloorInfo() + { + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.FloorInfo"))); + DirectoryInfo directory = new(ConfigManager.Config.Path.ResourcePath + "/Config/LevelOutput/RuntimeFloor/"); + var missingGroupInfos = false; + + if (!directory.Exists) { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.MissionInfo"))); - DirectoryInfo directory = new(ConfigManager.Config.Path.ResourcePath + "/Config/Level/Mission"); - if (!directory.Exists) - { - Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", I18nManager.Translate("Word.MissionInfo"), $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/Mission", I18nManager.Translate("Word.Mission"))); - return; - } - bool missingMissionInfos = false; - var count = 0; - foreach (var missionExcel in GameData.MainMissionData) - { - var path = $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/Mission/{missionExcel.Key}/MissionInfo_{missionExcel.Key}.json"; - if (!File.Exists(path)) - { - missingMissionInfos = true; - continue; - } - var json = File.ReadAllText(path); - var missionInfo = JsonConvert.DeserializeObject(json); - if (missionInfo != null) - { - GameData.MainMissionData[missionExcel.Key].MissionInfo = missionInfo; - foreach (var subMission in missionInfo.SubMissionList) - { // load mission json - var missionJsonPath = ConfigManager.Config.Path.ResourcePath + "/" + subMission.MissionJsonPath; - if (File.Exists(missionJsonPath)) - { - var missionJson = File.ReadAllText(missionJsonPath).Replace("$type", "Type"); - } - } - count++; - } else - { - missingMissionInfos = true; - } - } - if (missingMissionInfos) - Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", I18nManager.Translate("Word.MissionInfo"), $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/Mission", I18nManager.Translate("Word.Mission"))); - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), I18nManager.Translate("Word.MissionInfo"))); + Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", + I18nManager.Translate("Word.FloorInfo"), + $"{ConfigManager.Config.Path.ResourcePath}/Config/LevelOutput/RuntimeFloor", + I18nManager.Translate("Word.FloorMissingResult"))); + return; } - public static T? LoadCustomFile(string filetype, string filename) - { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", filetype)); - FileInfo file = new(ConfigManager.Config.Path.ConfigPath + $"/{filename}.json"); - T? customFile = default; - if (!file.Exists) - { - Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", filetype, $"{ConfigManager.Config.Path.ConfigPath}/{filename}.json", filetype)); - return customFile; - } + // Load floor infos + foreach (var file in directory.GetFiles()) try { using var reader = file.OpenRead(); using StreamReader reader2 = new(reader); var text = reader2.ReadToEnd(); - var json = JsonConvert.DeserializeObject(text); - customFile = json; - } catch (Exception ex) + var info = JsonConvert.DeserializeObject(text); + var name = file.Name[..file.Name.IndexOf('.')]; + GameData.FloorInfoData.Add(name, info!); + } + catch (Exception ex) { - Logger.Error("Error in reading " + file.Name, ex); + Logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, + I18nManager.Translate("Word.Error")), ex); } - if (customFile is Dictionary d) + foreach (var info in GameData.FloorInfoData.Values) + { + foreach (var groupInfo in info.GroupInstanceList) { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", d.Count.ToString(), filetype)); - } else if (customFile is Dictionary> di) + if (groupInfo.IsDelete) continue; + FileInfo file = new(ConfigManager.Config.Path.ResourcePath + "/" + groupInfo.GroupPath); + if (!file.Exists) continue; + try + { + using var reader = file.OpenRead(); + using StreamReader reader2 = new(reader); + var text = reader2.ReadToEnd(); + var group = JsonConvert.DeserializeObject(text); + if (group != null) + { + group.Id = groupInfo.ID; + info.Groups.TryAdd(groupInfo.ID, group); + group.Load(); + + // load graph + var graphPath = ConfigManager.Config.Path.ResourcePath + "/" + group.LevelGraph; + var graphFile = new FileInfo(graphPath); + if (graphFile.Exists) + { + using var graphReader = graphFile.OpenRead(); + using StreamReader graphReader2 = new(graphReader); + var graphText = graphReader2.ReadToEnd().Replace("$type", "Type"); + var graphObj = JObject.Parse(graphText); + if (graphObj != null) + { + var graphInfo = LevelGraphConfigInfo.LoadFromJsonObject(graphObj); + group.LevelGraphConfig = graphInfo; + } + } + } + } + catch (Exception ex) + { + Logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, + I18nManager.Translate("Word.Error")), ex); + } + + if (info.Groups.Count == 0) missingGroupInfos = true; + } + + info.OnLoad(); + } + + if (missingGroupInfos) + Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", + I18nManager.Translate("Word.FloorGroupInfo"), + $"{ConfigManager.Config.Path.ResourcePath}/Config/LevelOutput/SharedRuntimeGroup", + I18nManager.Translate("Word.FloorGroupMissingResult"))); + + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", GameData.FloorInfoData.Count.ToString(), + I18nManager.Translate("Word.FloorInfo"))); + } + + public static void LoadMissionInfo() + { + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.MissionInfo"))); + DirectoryInfo directory = new(ConfigManager.Config.Path.ResourcePath + "/Config/Level/Mission"); + if (!directory.Exists) + { + Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", + I18nManager.Translate("Word.MissionInfo"), + $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/Mission", + I18nManager.Translate("Word.Mission"))); + return; + } + + var missingMissionInfos = false; + var count = 0; + foreach (var missionExcel in GameData.MainMissionData) + { + var path = + $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/Mission/{missionExcel.Key}/MissionInfo_{missionExcel.Key}.json"; + if (!File.Exists(path)) { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", di.Count.ToString(), filetype)); - } else if (customFile is BannersConfig c) + missingMissionInfos = true; + continue; + } + + var json = File.ReadAllText(path); + var missionInfo = JsonConvert.DeserializeObject(json); + if (missionInfo != null) { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", c.Banners.Count.ToString(), filetype)); - } else if (customFile is RogueMiracleEffectConfig r) - { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", r.Miracles.Count.ToString(), filetype)); - } else if (customFile is ActivityConfig a) - { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", a.ScheduleData.Count.ToString(), filetype)); + GameData.MainMissionData[missionExcel.Key].MissionInfo = missionInfo; + foreach (var subMission in missionInfo.SubMissionList) + { + // load mission json + var missionJsonPath = ConfigManager.Config.Path.ResourcePath + "/" + subMission.MissionJsonPath; + if (File.Exists(missionJsonPath)) + { + var missionJson = File.ReadAllText(missionJsonPath).Replace("$type", "Type"); + } + } + + count++; } else { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItem", filetype)); + missingMissionInfos = true; } + } + if (missingMissionInfos) + Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", + I18nManager.Translate("Word.MissionInfo"), + $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/Mission", + I18nManager.Translate("Word.Mission"))); + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), + I18nManager.Translate("Word.MissionInfo"))); + } + + public static T? LoadCustomFile(string filetype, string filename) + { + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", filetype)); + FileInfo file = new(ConfigManager.Config.Path.ConfigPath + $"/{filename}.json"); + T? customFile = default; + if (!file.Exists) + { + Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", filetype, + $"{ConfigManager.Config.Path.ConfigPath}/{filename}.json", filetype)); return customFile; } - public static void LoadMazeSkill() + try { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.MazeSkillInfo"))); - var count = 0; - foreach (var adventure in GameData.AdventurePlayerData.Values) - { - var avatar = GameData.AvatarConfigData[adventure.AvatarID]; - var adventurePath = adventure.PlayerJsonPath.Replace("_Config.json", "_Ability.json").Replace("ConfigCharacter", "ConfigAdventureAbility"); - var path = ConfigManager.Config.Path.ResourcePath + "/" + adventurePath; - var file = new FileInfo(path); - if (!file.Exists) continue; - try - { - using var reader = file.OpenRead(); - using StreamReader reader2 = new(reader); - var text = reader2.ReadToEnd().Replace("$type", "Type"); - var skillAbilityInfo = JsonConvert.DeserializeObject(text); - skillAbilityInfo?.Loaded(avatar); - count += skillAbilityInfo == null ? 0 : 1; - } - catch (Exception ex) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", adventurePath, I18nManager.Translate("Word.Error")), ex); - } - } - if (count < GameData.AdventurePlayerData.Count) - { - Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", I18nManager.Translate("Word.MazeSkillInfo"), $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/AdventureAbility", I18nManager.Translate("Word.MazeSkill"))); - } - - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), I18nManager.Translate("Word.MazeSkillInfo"))); + using var reader = file.OpenRead(); + using StreamReader reader2 = new(reader); + var text = reader2.ReadToEnd(); + var json = JsonConvert.DeserializeObject(text); + customFile = json; + } + catch (Exception ex) + { + Logger.Error("Error in reading " + file.Name, ex); } - public static void LoadDialogueInfo() + if (customFile is Dictionary d) + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", d.Count.ToString(), filetype)); + else if (customFile is Dictionary> di) + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", di.Count.ToString(), filetype)); + else if (customFile is BannersConfig c) + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", c.Banners.Count.ToString(), filetype)); + else if (customFile is RogueMiracleEffectConfig r) + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", r.Miracles.Count.ToString(), filetype)); + else if (customFile is ActivityConfig a) + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", a.ScheduleData.Count.ToString(), + filetype)); + else + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItem", filetype)); + + return customFile; + } + + public static void LoadMazeSkill() + { + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", + I18nManager.Translate("Word.MazeSkillInfo"))); + var count = 0; + foreach (var adventure in GameData.AdventurePlayerData.Values) { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.DialogueInfo"))); - var count = 0; - foreach (var dialogue in GameData.RogueNPCDialogueData) - { - var path = ConfigManager.Config.Path.ResourcePath + "/" + dialogue.Value.DialoguePath; - var file = new FileInfo(path); - if (!file.Exists) continue; - try - { - using var reader = file.OpenRead(); - using StreamReader reader2 = new(reader); - var text = reader2.ReadToEnd().Replace("$type", "Type"); - var dialogueInfo = JsonConvert.DeserializeObject(text); - if (dialogueInfo != null) - { - dialogue.Value.DialogueInfo = dialogueInfo; - dialogueInfo.Loaded(); - if (dialogueInfo.DialogueIds.Count == 0) - { - // set to invalid - dialogue.Value.DialogueInfo = null; - } - count++; - } - } catch (Exception ex) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, I18nManager.Translate("Word.Error")), ex); - } - - } - - if (count < GameData.RogueNPCDialogueData.Count) - { - Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", I18nManager.Translate("Word.DialogueInfo"), $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/Rogue/Dialogue", I18nManager.Translate("Word.Dialogue"))); - } - - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), I18nManager.Translate("Word.DialogueInfo"))); - } - - public static void LoadPerformanceInfo() - { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.PerformanceInfo"))); - var count = 0; - foreach (var performance in GameData.PerformanceEData.Values) - { - if (performance.PerformancePath == "") - { - count++; - continue; - } - - var path = ConfigManager.Config.Path.ResourcePath + "/" + performance.PerformancePath; - var file = new FileInfo(path); - if (!file.Exists) continue; - try - { - using var reader = file.OpenRead(); - using StreamReader reader2 = new(reader); - var text = reader2.ReadToEnd().Replace("$type", "Type"); - var obj = JObject.Parse(text); - if (obj != null) - { - LevelGraphConfigInfo info = LevelGraphConfigInfo.LoadFromJsonObject(obj); - performance.ActInfo = info; - count++; - } - } - catch (Exception ex) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, I18nManager.Translate("Word.Error")), ex); - } - } - - foreach (var performance in GameData.PerformanceDData.Values) - { - if (performance.PerformancePath == "") - { - count++; - continue; - } - - var path = ConfigManager.Config.Path.ResourcePath + "/" + performance.PerformancePath; - var file = new FileInfo(path); - if (!file.Exists) continue; - try - { - using var reader = file.OpenRead(); - using StreamReader reader2 = new(reader); - var text = reader2.ReadToEnd().Replace("$type", "Type"); - var obj = JObject.Parse(text); - if (obj != null) - { - LevelGraphConfigInfo info = LevelGraphConfigInfo.LoadFromJsonObject(obj); - performance.ActInfo = info; - count++; - } - } - catch (Exception ex) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, I18nManager.Translate("Word.Error")), ex); - } - } - - if (count < GameData.PerformanceEData.Count + GameData.PerformanceDData.Count) - { - // looks like many dont exist - //Logger.Warn("Performance infos are missing, please check your resources folder: " + ConfigManager.Config.Path.ResourcePath + "/Config/Level/Mission/*/Act. Performances may not work!"); - } - - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), I18nManager.Translate("Word.PerformanceInfo"))); - } - - public static void LoadSubMissionInfo() - { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.SubMissionInfo"))); - var count = 0; - foreach (var subMission in GameData.SubMissionData.Values) - { - if (subMission.SubMissionInfo == null || subMission.SubMissionInfo.MissionJsonPath == "") - { - continue; - } - - var path = ConfigManager.Config.Path.ResourcePath + "/" + subMission.SubMissionInfo.MissionJsonPath; - var file = new FileInfo(path); - if (!file.Exists) continue; - try - { - using var reader = file.OpenRead(); - using StreamReader reader2 = new(reader); - var text = reader2.ReadToEnd().Replace("$type", "Type"); - var obj = JObject.Parse(text); - if (obj != null) - { - LevelGraphConfigInfo info = LevelGraphConfigInfo.LoadFromJsonObject(obj); - subMission.SubMissionTaskInfo = info; - count++; - } - } - catch (Exception ex) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, I18nManager.Translate("Word.Error")), ex); - } - - } - - if (count < GameData.SubMissionData.Count) - { - //Logger.Warn("Performance infos are missing, please check your resources folder: " + ConfigManager.Config.Path.ResourcePath + "/Config/Level/Mission/*/Act. Performances may not work!"); - } - - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), I18nManager.Translate("Word.SubMissionInfo"))); - } - - public static void LoadRogueChestMapInfo() - { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.RogueChestMapInfo"))); - var count = 0; - var boardList = new List(); - foreach (var nousMap in GameData.RogueNousChessBoardData.Values) - { - boardList.AddRange(nousMap); - } - - foreach (var nousMap in GameData.RogueSwarmChessBoardData.Values) - { - boardList.AddRange(nousMap); - } - - foreach (var board in boardList) - { - if (board.ChessBoardConfiguration == "") - { - count++; - continue; - } - - var path = ConfigManager.Config.Path.ResourcePath + "/" + board.ChessBoardConfiguration; - - var file = new FileInfo(path); - if (!file.Exists) continue; - try - { - using var reader = file.OpenRead(); - using StreamReader reader2 = new(reader); - var text = reader2.ReadToEnd(); - var map = JsonConvert.DeserializeObject(text); - if (map != null) - { - board.MapInfo = map; - count++; - } - } - catch (Exception ex) - { - Logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, I18nManager.Translate("Word.Error")), ex); - } - } - - if (count < boardList.Count) - { - Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", I18nManager.Translate("Word.RogueChestMapInfo"), $"{ConfigManager.Config.Path.ResourcePath}/Config/Gameplays/RogueDLC", I18nManager.Translate("Word.RogueChestMap"))); - } - - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), I18nManager.Translate("Word.RogueChestMapInfo"))); - } - - public static void LoadChessRogueRoomData() - { - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.ChessRogueRoomInfo"))); - var count = 0; - - FileInfo file = new(ConfigManager.Config.Path.ConfigPath + $"/ChessRogueRoomGen.json"); - List? customFile; - if (!file.Exists) - { - Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", I18nManager.Translate("Word.ChessRogueRoomInfo"), $"{ConfigManager.Config.Path.ConfigPath}/ChessRogueRoomGen.json", I18nManager.Translate("Word.ChessRogueRoom"))); - - return; - } + var avatar = GameData.AvatarConfigData[adventure.AvatarID]; + var adventurePath = adventure.PlayerJsonPath.Replace("_Config.json", "_Ability.json") + .Replace("ConfigCharacter", "ConfigAdventureAbility"); + var path = ConfigManager.Config.Path.ResourcePath + "/" + adventurePath; + var file = new FileInfo(path); + if (!file.Exists) continue; try { using var reader = file.OpenRead(); using StreamReader reader2 = new(reader); - var text = reader2.ReadToEnd(); - var json = JsonConvert.DeserializeObject>(text); - customFile = json; + var text = reader2.ReadToEnd().Replace("$type", "Type"); + var skillAbilityInfo = JsonConvert.DeserializeObject(text); + skillAbilityInfo?.Loaded(avatar); + count += skillAbilityInfo == null ? 0 : 1; + } + catch (Exception ex) + { + Logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToReadItem", adventurePath, + I18nManager.Translate("Word.Error")), ex); + } + } - foreach (var room in customFile!) + if (count < GameData.AdventurePlayerData.Count) + Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", + I18nManager.Translate("Word.MazeSkillInfo"), + $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/AdventureAbility", + I18nManager.Translate("Word.MazeSkill"))); + + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), + I18nManager.Translate("Word.MazeSkillInfo"))); + } + + public static void LoadDialogueInfo() + { + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.DialogueInfo"))); + var count = 0; + foreach (var dialogue in GameData.RogueNPCDialogueData) + { + var path = ConfigManager.Config.Path.ResourcePath + "/" + dialogue.Value.DialoguePath; + var file = new FileInfo(path); + if (!file.Exists) continue; + try + { + using var reader = file.OpenRead(); + using StreamReader reader2 = new(reader); + var text = reader2.ReadToEnd().Replace("$type", "Type"); + var dialogueInfo = JsonConvert.DeserializeObject(text); + if (dialogueInfo != null) { - if (room.BlockType == RogueDLCBlockTypeEnum.MonsterNormal) - { - AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterNormal, room); - AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterSwarm, room); - count += 2; - } - else if (room.BlockType == RogueDLCBlockTypeEnum.MonsterBoss) - { - AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterBoss, room); - AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterNousBoss, room); - AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterSwarmBoss, room); - count += 3; - } - else if (room.BlockType == RogueDLCBlockTypeEnum.Event) - { - AddRoomToGameData(RogueDLCBlockTypeEnum.Event, room); - AddRoomToGameData(RogueDLCBlockTypeEnum.Reward, room); - AddRoomToGameData(RogueDLCBlockTypeEnum.Adventure, room); // adventure is not this type - AddRoomToGameData(RogueDLCBlockTypeEnum.NousSpecialEvent, room); - AddRoomToGameData(RogueDLCBlockTypeEnum.SwarmEvent, room); - AddRoomToGameData(RogueDLCBlockTypeEnum.NousEvent, room); - count += 6; - } - else if (room.BlockType == RogueDLCBlockTypeEnum.Trade) - { - AddRoomToGameData(RogueDLCBlockTypeEnum.Trade, room); - AddRoomToGameData(RogueDLCBlockTypeEnum.BlackMarket, room); - count += 2; - } - else - { - AddRoomToGameData(room.BlockType, room); - count++; - } + dialogue.Value.DialogueInfo = dialogueInfo; + dialogueInfo.Loaded(); + if (dialogueInfo.DialogueIds.Count == 0) + // set to invalid + dialogue.Value.DialogueInfo = null; + count++; } } catch (Exception ex) { - Logger.Error("Error in reading " + file.Name, ex); - } - - Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), I18nManager.Translate("Word.ChessRogueRoomInfo"))); - } - - public static void AddRoomToGameData(RogueDLCBlockTypeEnum type, ChessRogueRoomConfig room) - { - if (GameData.ChessRogueRoomData.TryGetValue(type, out var list)) - { - list.Add(room); - } - else - { - GameData.ChessRogueRoomData.Add(type, [room]); + Logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, + I18nManager.Translate("Word.Error")), ex); } } + + if (count < GameData.RogueNPCDialogueData.Count) + Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", + I18nManager.Translate("Word.DialogueInfo"), + $"{ConfigManager.Config.Path.ResourcePath}/Config/Level/Rogue/Dialogue", + I18nManager.Translate("Word.Dialogue"))); + + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), + I18nManager.Translate("Word.DialogueInfo"))); } -} + + public static void LoadPerformanceInfo() + { + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", + I18nManager.Translate("Word.PerformanceInfo"))); + var count = 0; + foreach (var performance in GameData.PerformanceEData.Values) + { + if (performance.PerformancePath == "") + { + count++; + continue; + } + + var path = ConfigManager.Config.Path.ResourcePath + "/" + performance.PerformancePath; + var file = new FileInfo(path); + if (!file.Exists) continue; + try + { + using var reader = file.OpenRead(); + using StreamReader reader2 = new(reader); + var text = reader2.ReadToEnd().Replace("$type", "Type"); + var obj = JObject.Parse(text); + if (obj != null) + { + var info = LevelGraphConfigInfo.LoadFromJsonObject(obj); + performance.ActInfo = info; + count++; + } + } + catch (Exception ex) + { + Logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, + I18nManager.Translate("Word.Error")), ex); + } + } + + foreach (var performance in GameData.PerformanceDData.Values) + { + if (performance.PerformancePath == "") + { + count++; + continue; + } + + var path = ConfigManager.Config.Path.ResourcePath + "/" + performance.PerformancePath; + var file = new FileInfo(path); + if (!file.Exists) continue; + try + { + using var reader = file.OpenRead(); + using StreamReader reader2 = new(reader); + var text = reader2.ReadToEnd().Replace("$type", "Type"); + var obj = JObject.Parse(text); + if (obj != null) + { + var info = LevelGraphConfigInfo.LoadFromJsonObject(obj); + performance.ActInfo = info; + count++; + } + } + catch (Exception ex) + { + Logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, + I18nManager.Translate("Word.Error")), ex); + } + } + + if (count < GameData.PerformanceEData.Count + GameData.PerformanceDData.Count) + { + // looks like many dont exist + //Logger.Warn("Performance infos are missing, please check your resources folder: " + ConfigManager.Config.Path.ResourcePath + "/Config/Level/Mission/*/Act. Performances may not work!"); + } + + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), + I18nManager.Translate("Word.PerformanceInfo"))); + } + + public static void LoadSubMissionInfo() + { + Logger.Info( + I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.SubMissionInfo"))); + var count = 0; + foreach (var subMission in GameData.SubMissionData.Values) + { + if (subMission.SubMissionInfo == null || subMission.SubMissionInfo.MissionJsonPath == "") continue; + + var path = ConfigManager.Config.Path.ResourcePath + "/" + subMission.SubMissionInfo.MissionJsonPath; + var file = new FileInfo(path); + if (!file.Exists) continue; + try + { + using var reader = file.OpenRead(); + using StreamReader reader2 = new(reader); + var text = reader2.ReadToEnd().Replace("$type", "Type"); + var obj = JObject.Parse(text); + if (obj != null) + { + var info = LevelGraphConfigInfo.LoadFromJsonObject(obj); + subMission.SubMissionTaskInfo = info; + count++; + } + } + catch (Exception ex) + { + Logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, + I18nManager.Translate("Word.Error")), ex); + } + } + + if (count < GameData.SubMissionData.Count) + { + //Logger.Warn("Performance infos are missing, please check your resources folder: " + ConfigManager.Config.Path.ResourcePath + "/Config/Level/Mission/*/Act. Performances may not work!"); + } + + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), + I18nManager.Translate("Word.SubMissionInfo"))); + } + + public static void LoadRogueChestMapInfo() + { + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", + I18nManager.Translate("Word.RogueChestMapInfo"))); + var count = 0; + var boardList = new List(); + foreach (var nousMap in GameData.RogueNousChessBoardData.Values) boardList.AddRange(nousMap); + + foreach (var nousMap in GameData.RogueSwarmChessBoardData.Values) boardList.AddRange(nousMap); + + foreach (var board in boardList) + { + if (board.ChessBoardConfiguration == "") + { + count++; + continue; + } + + var path = ConfigManager.Config.Path.ResourcePath + "/" + board.ChessBoardConfiguration; + + var file = new FileInfo(path); + if (!file.Exists) continue; + try + { + using var reader = file.OpenRead(); + using StreamReader reader2 = new(reader); + var text = reader2.ReadToEnd(); + var map = JsonConvert.DeserializeObject(text); + if (map != null) + { + board.MapInfo = map; + count++; + } + } + catch (Exception ex) + { + Logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToReadItem", file.Name, + I18nManager.Translate("Word.Error")), ex); + } + } + + if (count < boardList.Count) + Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", + I18nManager.Translate("Word.RogueChestMapInfo"), + $"{ConfigManager.Config.Path.ResourcePath}/Config/Gameplays/RogueDLC", + I18nManager.Translate("Word.RogueChestMap"))); + + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), + I18nManager.Translate("Word.RogueChestMapInfo"))); + } + + public static void LoadChessRogueRoomData() + { + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", + I18nManager.Translate("Word.ChessRogueRoomInfo"))); + var count = 0; + + FileInfo file = new(ConfigManager.Config.Path.ConfigPath + "/ChessRogueRoomGen.json"); + List? customFile; + if (!file.Exists) + { + Logger.Warn(I18nManager.Translate("Server.ServerInfo.ConfigMissing", + I18nManager.Translate("Word.ChessRogueRoomInfo"), + $"{ConfigManager.Config.Path.ConfigPath}/ChessRogueRoomGen.json", + I18nManager.Translate("Word.ChessRogueRoom"))); + + return; + } + + try + { + using var reader = file.OpenRead(); + using StreamReader reader2 = new(reader); + var text = reader2.ReadToEnd(); + var json = JsonConvert.DeserializeObject>(text); + customFile = json; + + foreach (var room in customFile!) + if (room.BlockType == RogueDLCBlockTypeEnum.MonsterNormal) + { + AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterNormal, room); + AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterSwarm, room); + count += 2; + } + else if (room.BlockType == RogueDLCBlockTypeEnum.MonsterBoss) + { + AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterBoss, room); + AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterNousBoss, room); + AddRoomToGameData(RogueDLCBlockTypeEnum.MonsterSwarmBoss, room); + count += 3; + } + else if (room.BlockType == RogueDLCBlockTypeEnum.Event) + { + AddRoomToGameData(RogueDLCBlockTypeEnum.Event, room); + AddRoomToGameData(RogueDLCBlockTypeEnum.Reward, room); + AddRoomToGameData(RogueDLCBlockTypeEnum.Adventure, room); // adventure is not this type + AddRoomToGameData(RogueDLCBlockTypeEnum.NousSpecialEvent, room); + AddRoomToGameData(RogueDLCBlockTypeEnum.SwarmEvent, room); + AddRoomToGameData(RogueDLCBlockTypeEnum.NousEvent, room); + count += 6; + } + else if (room.BlockType == RogueDLCBlockTypeEnum.Trade) + { + AddRoomToGameData(RogueDLCBlockTypeEnum.Trade, room); + AddRoomToGameData(RogueDLCBlockTypeEnum.BlackMarket, room); + count += 2; + } + else + { + AddRoomToGameData(room.BlockType, room); + count++; + } + } + catch (Exception ex) + { + Logger.Error("Error in reading " + file.Name, ex); + } + + Logger.Info(I18nManager.Translate("Server.ServerInfo.LoadedItems", count.ToString(), + I18nManager.Translate("Word.ChessRogueRoomInfo"))); + } + + public static void AddRoomToGameData(RogueDLCBlockTypeEnum type, ChessRogueRoomConfig room) + { + if (GameData.ChessRogueRoomData.TryGetValue(type, out var list)) + list.Add(room); + else + GameData.ChessRogueRoomData.Add(type, [room]); + } +} \ No newline at end of file diff --git a/Common/Database/Account/AccountData.cs b/Common/Database/Account/AccountData.cs index 373f05cf..83f5a79d 100644 --- a/Common/Database/Account/AccountData.cs +++ b/Common/Database/Account/AccountData.cs @@ -1,54 +1,47 @@ using EggLink.DanhengServer.Util; -using Microsoft.Data.Sqlite; using SqlSugar; -namespace EggLink.DanhengServer.Database.Account +namespace EggLink.DanhengServer.Database.Account; + +[SugarTable("Account")] +public class AccountData : BaseDatabaseDataHelper { - [SugarTable("Account")] - public class AccountData() : BaseDatabaseDataHelper + public string? Username { get; set; } + + [SugarColumn(IsNullable = true)] public string? ComboToken { get; set; } + + [SugarColumn(IsNullable = true)] public string? DispatchToken { get; set; } + + [SugarColumn(IsNullable = true)] + public string? Permissions { get; set; } // type: permission1,permission2,permission3... + + public static AccountData? GetAccountByUserName(string username) { - public string? Username { get; set; } - - [SugarColumn(IsNullable = true)] - public string? ComboToken { get; set; } - - [SugarColumn(IsNullable = true)] - public string? DispatchToken { get; set; } - - [SugarColumn(IsNullable = true)] - public string? Permissions { get; set; } // type: permission1,permission2,permission3... - - public static AccountData? GetAccountByUserName(string username) + AccountData? result = null; + DatabaseHelper.GetAllInstance()?.ForEach(account => { - AccountData? result = null; - DatabaseHelper.GetAllInstance()?.ForEach((account) => - { - if (account.Username == username) - { - result = account; - } - }); - return result; - } - - public static AccountData? GetAccountByUid(int uid) - { - AccountData? result = DatabaseHelper.Instance?.GetInstance(uid); - return result; - } - - public string GenerateDispatchToken() - { - DispatchToken = Crypto.CreateSessionKey(Uid.ToString()); - DatabaseHelper.Instance?.UpdateInstance(this); - return DispatchToken; - } - - public string GenerateComboToken() - { - ComboToken = Crypto.CreateSessionKey(Uid.ToString()); - DatabaseHelper.Instance?.UpdateInstance(this); - return ComboToken; - } + if (account.Username == username) result = account; + }); + return result; } -} + + public static AccountData? GetAccountByUid(int uid) + { + var result = DatabaseHelper.Instance?.GetInstance(uid); + return result; + } + + public string GenerateDispatchToken() + { + DispatchToken = Crypto.CreateSessionKey(Uid.ToString()); + DatabaseHelper.Instance?.UpdateInstance(this); + return DispatchToken; + } + + public string GenerateComboToken() + { + ComboToken = Crypto.CreateSessionKey(Uid.ToString()); + DatabaseHelper.Instance?.UpdateInstance(this); + return ComboToken; + } +} \ No newline at end of file diff --git a/Common/Database/Account/AccountHelper.cs b/Common/Database/Account/AccountHelper.cs index 5f79aa73..ad0dba47 100644 --- a/Common/Database/Account/AccountHelper.cs +++ b/Common/Database/Account/AccountHelper.cs @@ -1,37 +1,31 @@ using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Database.Account -{ - public static class AccountHelper - { - public static void CreateAccount(string username, int uid) - { - if (AccountData.GetAccountByUserName(username) != null) - { - throw new Exception("Account already exists"); - } - if (AccountData.GetAccountByUid(uid) != null) - { +namespace EggLink.DanhengServer.Database.Account; - } - int newUid = uid; - if (uid == 0) - { - newUid = 10001; // start from 10001 - while (AccountData.GetAccountByUid(newUid) != null) - { - newUid++; - } - } - var per = ConfigManager.Config.ServerOption.DefaultPermissions; - var perStr = string.Join(",", per); - var account = new AccountData() - { - Uid = newUid, - Username = username, - Permissions = perStr - }; - DatabaseHelper.SaveInstance(account); +public static class AccountHelper +{ + public static void CreateAccount(string username, int uid) + { + if (AccountData.GetAccountByUserName(username) != null) throw new Exception("Account already exists"); + if (AccountData.GetAccountByUid(uid) != null) + { } + + var newUid = uid; + if (uid == 0) + { + newUid = 10001; // start from 10001 + while (AccountData.GetAccountByUid(newUid) != null) newUid++; + } + + var per = ConfigManager.Config.ServerOption.DefaultPermissions; + var perStr = string.Join(",", per); + var account = new AccountData + { + Uid = newUid, + Username = username, + Permissions = perStr + }; + DatabaseHelper.SaveInstance(account); } -} +} \ No newline at end of file diff --git a/Common/Database/Avatar/AvatarData.cs b/Common/Database/Avatar/AvatarData.cs index 24b0f04d..520edbee 100644 --- a/Common/Database/Avatar/AvatarData.cs +++ b/Common/Database/Avatar/AvatarData.cs @@ -3,423 +3,383 @@ using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Util; using Newtonsoft.Json; using SqlSugar; +using LineupInfo = EggLink.DanhengServer.Database.Lineup.LineupInfo; -namespace EggLink.DanhengServer.Database.Avatar +namespace EggLink.DanhengServer.Database.Avatar; + +[SugarTable("Avatar")] +public class AvatarData : BaseDatabaseDataHelper { - [SugarTable("Avatar")] - public class AvatarData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public List Avatars { get; set; } = []; + [SugarColumn(IsJson = true)] public List Avatars { get; set; } = []; - [SugarColumn(IsJson = true)] - public List AssistAvatars { get; set; } = []; - [SugarColumn(IsJson = true)] - public List DisplayAvatars { get; set; } = []; + [SugarColumn(IsJson = true)] public List AssistAvatars { get; set; } = []; + + [SugarColumn(IsJson = true)] public List DisplayAvatars { get; set; } = []; +} + +public class AvatarInfo +{ + [JsonIgnore] public AvatarConfigExcel? Excel; + + [JsonIgnore] public PlayerData? PlayerData; + + public AvatarInfo() + { + // only for db } - public class AvatarInfo + public AvatarInfo(AvatarConfigExcel excel) { - public int AvatarId { get; set; } - [JsonIgnore] - public int SpecialBaseAvatarId { get; set; } - public int HeroId { get; set; } - public int Level { get; set; } - public int Exp { get; set; } - public int Promotion { get; set; } - public int Rewards { get; set; } - public long Timestamp { get; set; } - public int CurrentHp { get; set; } = 10000; - public int CurrentSp { get; set; } = 0; - public int ExtraLineupHp { get; set; } = 10000; - public int ExtraLineupSp { get; set; } = 0; - public int Rank { get; set; } - public Dictionary SkillTree { get; set; } = []; - public Dictionary> SkillTreeExtra { get; set; } = []; // for hero heroId -> skillId -> level - public int EquipId { get; set; } = 0; - public Dictionary Relic { get; set; } = []; - - [JsonIgnore()] - public ItemData? EquipData { get; set; } // for special avatar - - [JsonIgnore()] - public AvatarConfigExcel? Excel; - [JsonIgnore()] - public int InternalEntityId { get; set; } - [JsonIgnore()] - public int EntityId { get => InternalEntityId; set { - if (SpecialBaseAvatarId > 0 && PlayerData != null) - { - // set in SpecialAvatarExcel - GameData.SpecialAvatarData.TryGetValue(SpecialBaseAvatarId * 10 + PlayerData.WorldLevel, out var specialAvatar); - if (specialAvatar != null) - { - specialAvatar.EntityId[PlayerData.Uid] = value; - InternalEntityId = value; - } - } - InternalEntityId = value; - } - } - [JsonIgnore()] - public PlayerData? PlayerData; - - public AvatarInfo() + Excel = excel; + SkillTree = []; + if (AvatarId == 8001) { - // only for db } - - public AvatarInfo(AvatarConfigExcel excel) + else { - Excel = excel; - SkillTree = []; - if (AvatarId == 8001) - { - } - else - { - excel.DefaultSkillTree.ForEach(skill => - { - SkillTree.Add(skill.PointID, skill.Level); - }); - } + excel.DefaultSkillTree.ForEach(skill => { SkillTree.Add(skill.PointID, skill.Level); }); } + } - public void ValidateHero() + public int AvatarId { get; set; } + + [JsonIgnore] public int SpecialBaseAvatarId { get; set; } + + public int HeroId { get; set; } + public int Level { get; set; } + public int Exp { get; set; } + public int Promotion { get; set; } + public int Rewards { get; set; } + public long Timestamp { get; set; } + public int CurrentHp { get; set; } = 10000; + public int CurrentSp { get; set; } + public int ExtraLineupHp { get; set; } = 10000; + public int ExtraLineupSp { get; set; } + public int Rank { get; set; } + public Dictionary SkillTree { get; set; } = []; + + public Dictionary> SkillTreeExtra { get; set; } = + []; // for hero heroId -> skillId -> level + + public int EquipId { get; set; } = 0; + public Dictionary Relic { get; set; } = []; + + [JsonIgnore] public ItemData? EquipData { get; set; } // for special avatar + + [JsonIgnore] public int InternalEntityId { get; set; } + + [JsonIgnore] + public int EntityId + { + get => InternalEntityId; + set { - if (HeroId == 0) + if (SpecialBaseAvatarId > 0 && PlayerData != null) { - return; - } - - var isWoman = HeroId % 2 == 0; - - var shouldRemove = new List(); - foreach (var skill in SkillTreeExtra.Keys) - { - if (skill % 2 == 0 != isWoman) // remove + // set in SpecialAvatarExcel + GameData.SpecialAvatarData.TryGetValue(SpecialBaseAvatarId * 10 + PlayerData.WorldLevel, + out var specialAvatar); + if (specialAvatar != null) { - shouldRemove.Add(skill); + specialAvatar.EntityId[PlayerData.Uid] = value; + InternalEntityId = value; } } - foreach (var skill in shouldRemove) + InternalEntityId = value; + } + } + + public void ValidateHero() + { + if (HeroId == 0) return; + + var isWoman = HeroId % 2 == 0; + + var shouldRemove = new List(); + foreach (var skill in SkillTreeExtra.Keys) + if (skill % 2 == 0 != isWoman) // remove + shouldRemove.Add(skill); + + foreach (var skill in shouldRemove) SkillTreeExtra.Remove(skill); + } + + public bool HasTakenReward(int promotion) + { + return (Rewards & (1 << promotion)) != 0; + } + + public void TakeReward(int promotion) + { + Rewards |= 1 << promotion; + } + + public int GetCurHp(bool isExtraLineup) + { + return isExtraLineup ? ExtraLineupHp : CurrentHp; + } + + public int GetCurSp(bool isExtraLineup) + { + return isExtraLineup ? ExtraLineupSp : CurrentSp; + } + + public int GetAvatarId() + { + return HeroId > 0 ? HeroId : AvatarId; + } + + public int GetBaseAvatarId() + { + return HeroId > 0 ? 8001 : AvatarId; + } + + public int GetSpecialAvatarId() + { + return SpecialBaseAvatarId > 0 ? SpecialBaseAvatarId : GetAvatarId(); + } + + public int GetUniqueAvatarId() + { + return SpecialBaseAvatarId > 0 ? SpecialBaseAvatarId : HeroId > 0 ? 8001 : AvatarId; + } + + public Dictionary GetSkillTree() + { + var value = SkillTree; + if (HeroId > 0) + if (!SkillTreeExtra.TryGetValue(HeroId, out value)) { - SkillTreeExtra.Remove(skill); - } - } - - public bool HasTakenReward(int promotion) - { - return (Rewards & (1 << promotion)) != 0; - } - - public void TakeReward(int promotion) - { - Rewards |= 1 << promotion; - } - - public int GetCurHp(bool isExtraLineup) - { - return isExtraLineup ? ExtraLineupHp : CurrentHp; - } - - public int GetCurSp(bool isExtraLineup) - { - return isExtraLineup ? ExtraLineupSp : CurrentSp; - } - - public int GetAvatarId() - { - return HeroId > 0 ? HeroId : AvatarId; - } - - public int GetBaseAvatarId() - { - return HeroId > 0 ? 8001 : AvatarId; - } - - public int GetSpecialAvatarId() - { - return SpecialBaseAvatarId > 0 ? SpecialBaseAvatarId : GetAvatarId(); - } - - public int GetUniqueAvatarId() - { - return SpecialBaseAvatarId > 0 ? SpecialBaseAvatarId : (HeroId > 0 ? 8001 : AvatarId); - } - - public Dictionary GetSkillTree() - { - var value = SkillTree; - if (HeroId > 0) - { - if (!SkillTreeExtra.TryGetValue(HeroId, out value)) - { - value = ([]); - // for old data - SkillTreeExtra[HeroId] = value; - var excel = GameData.AvatarConfigData[HeroId]; - excel.DefaultSkillTree.ForEach(skill => - { - SkillTreeExtra[HeroId].Add(skill.PointID, skill.Level); - }); - } - } - return value; - } - - public void SetCurHp(int value, bool isExtraLineup) - { - if (isExtraLineup) - { - ExtraLineupHp = value; - } - else - { - CurrentHp = value; - } - } - - public void SetCurSp(int value, bool isExtraLineup) - { - if (isExtraLineup) - { - ExtraLineupSp = value; - } - else - { - CurrentSp = value; - } - } - - public Proto.Avatar ToProto() - { - var proto = new Proto.Avatar() - { - BaseAvatarId = (uint)GetUniqueAvatarId(), - Level = (uint)Level, - Exp = (uint)Exp, - Promotion = (uint)Promotion, - Rank = (uint)Rank, - FirstMetTimeStamp = (ulong)Timestamp, - }; - - foreach (var item in Relic) - { - proto.EquipRelicList.Add(new EquipRelic() - { - RelicUniqueId = (uint)item.Value, - Type = (uint)item.Key - }); + value = []; + // for old data + SkillTreeExtra[HeroId] = value; + var excel = GameData.AvatarConfigData[HeroId]; + excel.DefaultSkillTree.ForEach(skill => { SkillTreeExtra[HeroId].Add(skill.PointID, skill.Level); }); } - if (EquipId != 0) - { - proto.EquipmentUniqueId = (uint)EquipId; - } + return value; + } - foreach (var skill in GetSkillTree()) - { - proto.SkilltreeList.Add(new AvatarSkillTree() - { - PointId = (uint)skill.Key, - Level = (uint)skill.Value - }); - } + public void SetCurHp(int value, bool isExtraLineup) + { + if (isExtraLineup) + ExtraLineupHp = value; + else + CurrentHp = value; + } - for (int i = 0; i < Promotion; i++) - { - if (HasTakenReward(i)) - { - proto.HasTakenPromotionRewardList.Add((uint)i); - } - } + public void SetCurSp(int value, bool isExtraLineup) + { + if (isExtraLineup) + ExtraLineupSp = value; + else + CurrentSp = value; + } - return proto; - } - - public SceneEntityInfo ToSceneEntityInfo(AvatarType avatarType = AvatarType.AvatarFormalType) + public Proto.Avatar ToProto() + { + var proto = new Proto.Avatar { - return new() - { - EntityId = (uint)EntityId, - Motion = new() - { - Pos = PlayerData?.Pos?.ToProto() ?? new(), - Rot = PlayerData?.Rot?.ToProto() ?? new(), - }, - Actor = new() - { - BaseAvatarId = (uint)GetBaseAvatarId(), - AvatarType = avatarType - } - }; - } + BaseAvatarId = (uint)GetUniqueAvatarId(), + Level = (uint)Level, + Exp = (uint)Exp, + Promotion = (uint)Promotion, + Rank = (uint)Rank, + FirstMetTimeStamp = (ulong)Timestamp + }; - public LineupAvatar ToLineupInfo(int slot, Lineup.LineupInfo info, AvatarType avatarType = AvatarType.AvatarFormalType) + foreach (var item in Relic) + proto.EquipRelicList.Add(new EquipRelic + { + RelicUniqueId = (uint)item.Value, + Type = (uint)item.Key + }); + + if (EquipId != 0) proto.EquipmentUniqueId = (uint)EquipId; + + foreach (var skill in GetSkillTree()) + proto.SkilltreeList.Add(new AvatarSkillTree + { + PointId = (uint)skill.Key, + Level = (uint)skill.Value + }); + + for (var i = 0; i < Promotion; i++) + if (HasTakenReward(i)) + proto.HasTakenPromotionRewardList.Add((uint)i); + + return proto; + } + + public SceneEntityInfo ToSceneEntityInfo(AvatarType avatarType = AvatarType.AvatarFormalType) + { + return new SceneEntityInfo { - return new() + EntityId = (uint)EntityId, + Motion = new MotionInfo { - Id = (uint)GetUniqueAvatarId(), - Slot = (uint)slot, - AvatarType = avatarType, - Hp = info.IsExtraLineup() ? (uint)ExtraLineupHp : (uint)CurrentHp, - SpBar = new() - { - CurSp = info.IsExtraLineup() ? (uint)ExtraLineupSp : (uint)CurrentSp, - MaxSp = 10000, - }, - }; - } + Pos = PlayerData?.Pos?.ToProto() ?? new Vector(), + Rot = PlayerData?.Rot?.ToProto() ?? new Vector() + }, + Actor = new SceneActorInfo + { + BaseAvatarId = (uint)GetBaseAvatarId(), + AvatarType = avatarType + } + }; + } - public BattleAvatar ToBattleProto(Lineup.LineupInfo lineup, InventoryData inventory, AvatarType avatarType = AvatarType.AvatarFormalType) + public LineupAvatar ToLineupInfo(int slot, LineupInfo info, AvatarType avatarType = AvatarType.AvatarFormalType) + { + return new LineupAvatar { - var proto = new BattleAvatar() + Id = (uint)GetUniqueAvatarId(), + Slot = (uint)slot, + AvatarType = avatarType, + Hp = info.IsExtraLineup() ? (uint)ExtraLineupHp : (uint)CurrentHp, + SpBar = new SpBarInfo { - Id = (uint)GetSpecialAvatarId(), - AvatarType = avatarType, - Level = (uint)Level, - Promotion = (uint)Promotion, - Rank = (uint)Rank, - Index = (uint)lineup.GetSlot(GetBaseAvatarId()), - Hp = (uint)GetCurHp(lineup.LineupType != 0), - SpBar = new() - { - CurSp = (uint)GetCurSp(lineup.LineupType != 0), - MaxSp = 10000, - }, - WorldLevel = (uint)(PlayerData?.WorldLevel ?? 0), - }; - - foreach (var skill in GetSkillTree()) - { - proto.SkilltreeList.Add(new AvatarSkillTree() - { - PointId = (uint)skill.Key, - Level = (uint)skill.Value - }); + CurSp = info.IsExtraLineup() ? (uint)ExtraLineupSp : (uint)CurrentSp, + MaxSp = 10000 } + }; + } - foreach (var relic in Relic) - { - var item = inventory.RelicItems?.Find(item => item.UniqueId == relic.Value); - if (item != null) - { - var protoRelic = new BattleRelic() - { - Id = (uint)item.ItemId, - UniqueId = (uint)item.UniqueId, - Level = (uint)item.Level, - MainAffixId = (uint)item.MainAffix, - }; - - if (item.SubAffixes.Count >= 1) - { - foreach (var subAffix in item.SubAffixes) - { - protoRelic.SubAffixList.Add(subAffix.ToProto()); - } - } - - proto.RelicList.Add(protoRelic); - } - } - - if (EquipId != 0) - { - var item = inventory.EquipmentItems?.Find(item => item.UniqueId == EquipId); - if (item != null) - { - proto.EquipmentList.Add(new BattleEquipment() - { - Id = (uint)item.ItemId, - Level = (uint)item.Level, - Promotion = (uint)item.Promotion, - Rank = (uint)item.Rank, - }); - } - } else if (EquipData != null) - { - proto.EquipmentList.Add(new BattleEquipment() - { - Id = (uint)EquipData.ItemId, - Level = (uint)EquipData.Level, - Promotion = (uint)EquipData.Promotion, - Rank = (uint)EquipData.Rank, - }); - } - - return proto; - } - - public List ToHeroProto() + public BattleAvatar ToBattleProto(LineupInfo lineup, InventoryData inventory, + AvatarType avatarType = AvatarType.AvatarFormalType) + { + var proto = new BattleAvatar { - var res = new List(); - - GetSkillTree(); - - foreach (var hero in SkillTreeExtra) + Id = (uint)GetSpecialAvatarId(), + AvatarType = avatarType, + Level = (uint)Level, + Promotion = (uint)Promotion, + Rank = (uint)Rank, + Index = (uint)lineup.GetSlot(GetBaseAvatarId()), + Hp = (uint)GetCurHp(lineup.LineupType != 0), + SpBar = new SpBarInfo { - var proto = new PlayerHeroBasicTypeInfo() + CurSp = (uint)GetCurSp(lineup.LineupType != 0), + MaxSp = 10000 + }, + WorldLevel = (uint)(PlayerData?.WorldLevel ?? 0) + }; + + foreach (var skill in GetSkillTree()) + proto.SkilltreeList.Add(new AvatarSkillTree + { + PointId = (uint)skill.Key, + Level = (uint)skill.Value + }); + + foreach (var relic in Relic) + { + var item = inventory.RelicItems?.Find(item => item.UniqueId == relic.Value); + if (item != null) + { + var protoRelic = new BattleRelic { - BasicType = (HeroBasicType)hero.Key, - Rank = (uint)Rank, + Id = (uint)item.ItemId, + UniqueId = (uint)item.UniqueId, + Level = (uint)item.Level, + MainAffixId = (uint)item.MainAffix }; - foreach (var skill in hero.Value) - { - proto.SkillTreeList.Add(new AvatarSkillTree() - { - PointId = (uint)skill.Key, - Level = (uint)skill.Value - }); - } + if (item.SubAffixes.Count >= 1) + foreach (var subAffix in item.SubAffixes) + protoRelic.SubAffixList.Add(subAffix.ToProto()); - res.Add(proto); + proto.RelicList.Add(protoRelic); } - - return res; } - public DisplayAvatarDetailInfo ToDetailProto(int pos) + if (EquipId != 0) { - var proto = new DisplayAvatarDetailInfo() + var item = inventory.EquipmentItems?.Find(item => item.UniqueId == EquipId); + if (item != null) + proto.EquipmentList.Add(new BattleEquipment + { + Id = (uint)item.ItemId, + Level = (uint)item.Level, + Promotion = (uint)item.Promotion, + Rank = (uint)item.Rank + }); + } + else if (EquipData != null) + { + proto.EquipmentList.Add(new BattleEquipment { - AvatarId = (uint)GetAvatarId(), - Level = (uint)Level, - Exp = (uint)Exp, - Promotion = (uint)Promotion, - Rank = (uint)Rank, - Pos = (uint)pos, + Id = (uint)EquipData.ItemId, + Level = (uint)EquipData.Level, + Promotion = (uint)EquipData.Promotion, + Rank = (uint)EquipData.Rank + }); + } + + return proto; + } + + public List ToHeroProto() + { + var res = new List(); + + GetSkillTree(); + + foreach (var hero in SkillTreeExtra) + { + var proto = new PlayerHeroBasicTypeInfo + { + BasicType = (HeroBasicType)hero.Key, + Rank = (uint)Rank }; - var inventory = DatabaseHelper.Instance!.GetInstance(PlayerData!.Uid)!; - foreach (var item in Relic) - { - var relic = inventory.RelicItems.Find(x => x.UniqueId == item.Value)!; - proto.RelicList.Add(relic.ToDisplayRelicProto()); - } - - if (EquipId != 0) - { - var equip = inventory.EquipmentItems.Find(x => x.UniqueId == EquipId)!; - proto.Equipment = equip.ToDisplayEquipmentProto(); - } - - foreach (var skill in GetSkillTree()) - { - proto.SkilltreeList.Add(new AvatarSkillTree() + foreach (var skill in hero.Value) + proto.SkillTreeList.Add(new AvatarSkillTree { PointId = (uint)skill.Key, Level = (uint)skill.Value }); - } - return proto; + res.Add(proto); } + + return res; } -} + + public DisplayAvatarDetailInfo ToDetailProto(int pos) + { + var proto = new DisplayAvatarDetailInfo + { + AvatarId = (uint)GetAvatarId(), + Level = (uint)Level, + Exp = (uint)Exp, + Promotion = (uint)Promotion, + Rank = (uint)Rank, + Pos = (uint)pos + }; + + var inventory = DatabaseHelper.Instance!.GetInstance(PlayerData!.Uid)!; + foreach (var item in Relic) + { + var relic = inventory.RelicItems.Find(x => x.UniqueId == item.Value)!; + proto.RelicList.Add(relic.ToDisplayRelicProto()); + } + + if (EquipId != 0) + { + var equip = inventory.EquipmentItems.Find(x => x.UniqueId == EquipId)!; + proto.Equipment = equip.ToDisplayEquipmentProto(); + } + + foreach (var skill in GetSkillTree()) + proto.SkilltreeList.Add(new AvatarSkillTree + { + PointId = (uint)skill.Key, + Level = (uint)skill.Value + }); + + return proto; + } +} \ No newline at end of file diff --git a/Common/Database/BaseDatabaseDataHelper.cs b/Common/Database/BaseDatabaseDataHelper.cs index 6bec6e21..44bde879 100644 --- a/Common/Database/BaseDatabaseDataHelper.cs +++ b/Common/Database/BaseDatabaseDataHelper.cs @@ -1,11 +1,8 @@ -using Microsoft.Data.Sqlite; -using SqlSugar; +using SqlSugar; -namespace EggLink.DanhengServer.Database +namespace EggLink.DanhengServer.Database; + +public abstract class BaseDatabaseDataHelper { - public abstract class BaseDatabaseDataHelper - { - [SugarColumn(IsPrimaryKey = true)] - public int Uid { get; set; } - } -} + [SugarColumn(IsPrimaryKey = true)] public int Uid { get; set; } +} \ No newline at end of file diff --git a/Common/Database/Challenge/ChallengeData.cs b/Common/Database/Challenge/ChallengeData.cs index b343e5cf..544b1ed2 100644 --- a/Common/Database/Challenge/ChallengeData.cs +++ b/Common/Database/Challenge/ChallengeData.cs @@ -2,107 +2,102 @@ using EggLink.DanhengServer.Util; using SqlSugar; -namespace EggLink.DanhengServer.Database.Challenge +namespace EggLink.DanhengServer.Database.Challenge; + +[SugarTable("Challenge")] +public class ChallengeData : BaseDatabaseDataHelper { - [SugarTable("Challenge")] - public class ChallengeData : BaseDatabaseDataHelper + [SugarColumn(IsJson = true)] public Dictionary History { get; set; } = new(); + + [SugarColumn(IsJson = true)] public ChallengeInstanceData Instance { get; set; } = new(); + + [SugarColumn(IsJson = true)] public Dictionary TakenRewards { get; set; } = new(); + + public void delete(int ChallengeId) { - [SugarColumn(IsJson = true)] - public Dictionary History { get; set; } = new(); - [SugarColumn(IsJson = true)] - public ChallengeInstanceData Instance { get; set; } = new(); - [SugarColumn(IsJson = true)] - public Dictionary TakenRewards { get; set; } = new(); - - public void delete(int ChallengeId) - { - History.Remove(ChallengeId); - } - } - - public class ChallengeHistoryData(int uid, int challengeId) - { - public int OwnerId { get; set; } = uid; - - public int ChallengeId { get; set; } = challengeId; - public int GroupId { get; set; } - public int TakenReward { get; set; } - public int Stars { get; set; } - public int Score { get; set; } - - public void SetStars(int stars) - { - Stars = Math.Max(Stars, stars); - } - - public int GetTotalStars() - { - int total = 0; - for (int i = 0; i < 3; i++) - { - total += (Stars & (1 << i)) != 0 ? 1 : 0; - } - return total; - } - - public Proto.Challenge ToProto() - { - var proto = new Proto.Challenge - { - ChallengeId = (uint)ChallengeId, - TakenReward = (uint)TakenReward, - ScoreId = (uint)Score, - Star = (uint)Stars - }; - - return proto; - } - } - - public class ChallengeInstanceData - { - public Position StartPos { get; set; } = new(); - public Position StartRot { get; set; } = new(); - public int ChallengeId { get; set; } = 0; - public int CurrentStage { get; set; } - public int CurrentExtraLineup { get; set; } - public int Status { get; set; } - public bool HasAvatarDied { get; set; } - - public int SavedMp { get; set; } - public int RoundsLeft { get; set; } - public int Stars { get; set; } - public int ScoreStage1 { get; set; } - public int ScoreStage2 { get; set; } - public List StoryBuffs { get; set; } = []; - public List BossBuffs { get; set; } = []; - } - - public class ChallengeGroupReward(int uid, int groupId) - { - public int OwnerUid = uid; - public int GroupId { get; set; } = groupId; - public long TakenStars { get; set; } - - public bool HasTakenReward(int starCount) - { - return (TakenStars & (1L << starCount)) != 0; - } - - public void SetTakenReward(int starCount) - { - TakenStars |= 1L << starCount; - } - - public ChallengeGroup ToProto() - { - var proto = new ChallengeGroup() - { - GroupId = (uint)GroupId, - TakenStarsCountReward = (ulong)TakenStars - }; - - return proto; - } + History.Remove(ChallengeId); } } + +public class ChallengeHistoryData(int uid, int challengeId) +{ + public int OwnerId { get; set; } = uid; + + public int ChallengeId { get; set; } = challengeId; + public int GroupId { get; set; } + public int TakenReward { get; set; } + public int Stars { get; set; } + public int Score { get; set; } + + public void SetStars(int stars) + { + Stars = Math.Max(Stars, stars); + } + + public int GetTotalStars() + { + var total = 0; + for (var i = 0; i < 3; i++) total += (Stars & (1 << i)) != 0 ? 1 : 0; + return total; + } + + public Proto.Challenge ToProto() + { + var proto = new Proto.Challenge + { + ChallengeId = (uint)ChallengeId, + TakenReward = (uint)TakenReward, + ScoreId = (uint)Score, + Star = (uint)Stars + }; + + return proto; + } +} + +public class ChallengeInstanceData +{ + public Position StartPos { get; set; } = new(); + public Position StartRot { get; set; } = new(); + public int ChallengeId { get; set; } = 0; + public int CurrentStage { get; set; } + public int CurrentExtraLineup { get; set; } + public int Status { get; set; } + public bool HasAvatarDied { get; set; } + + public int SavedMp { get; set; } + public int RoundsLeft { get; set; } + public int Stars { get; set; } + public int ScoreStage1 { get; set; } + public int ScoreStage2 { get; set; } + public List StoryBuffs { get; set; } = []; + public List BossBuffs { get; set; } = []; +} + +public class ChallengeGroupReward(int uid, int groupId) +{ + public int OwnerUid = uid; + public int GroupId { get; set; } = groupId; + public long TakenStars { get; set; } + + public bool HasTakenReward(int starCount) + { + return (TakenStars & (1L << starCount)) != 0; + } + + public void SetTakenReward(int starCount) + { + TakenStars |= 1L << starCount; + } + + public ChallengeGroup ToProto() + { + var proto = new ChallengeGroup + { + GroupId = (uint)GroupId, + TakenStarsCountReward = (ulong)TakenStars + }; + + return proto; + } +} \ No newline at end of file diff --git a/Common/Database/ChessRogue/ChessRogueNousData.cs b/Common/Database/ChessRogue/ChessRogueNousData.cs index 09d20e92..4746b054 100644 --- a/Common/Database/ChessRogue/ChessRogueNousData.cs +++ b/Common/Database/ChessRogue/ChessRogueNousData.cs @@ -1,36 +1,32 @@ using EggLink.DanhengServer.Proto; using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.ChessRogue +namespace EggLink.DanhengServer.Database.ChessRogue; + +[SugarTable("ChessRogueNous")] +public class ChessRogueNousData : BaseDatabaseDataHelper { - [SugarTable("ChessRogueNous")] - public class ChessRogueNousData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public Dictionary RogueDiceData { get; set; } = []; - } - - public class ChessRogueNousDiceData - { - public int BranchId { get; set; } - public Dictionary Surfaces { get; set; } = []; - public int AreaId { get; set; } - public int DifficultyLevel { get; set; } - - public ChessRogueDice ToProto() - { - return new ChessRogueDice() - { - BranchId = (uint)BranchId, - SurfaceList = { Surfaces.Select(x => new ChessRogueDiceSurfaceInfo() { Index = (uint)x.Key, SurfaceId = (uint)x.Value }) }, - AreaId = (uint)AreaId, - DifficultyLevel = (uint)DifficultyLevel, - }; - } - } + [SugarColumn(IsJson = true)] public Dictionary RogueDiceData { get; set; } = []; } + +public class ChessRogueNousDiceData +{ + public int BranchId { get; set; } + public Dictionary Surfaces { get; set; } = []; + public int AreaId { get; set; } + public int DifficultyLevel { get; set; } + + public ChessRogueDice ToProto() + { + return new ChessRogueDice + { + BranchId = (uint)BranchId, + SurfaceList = + { + Surfaces.Select(x => new ChessRogueDiceSurfaceInfo { Index = (uint)x.Key, SurfaceId = (uint)x.Value }) + }, + AreaId = (uint)AreaId, + DifficultyLevel = (uint)DifficultyLevel + }; + } +} \ No newline at end of file diff --git a/Common/Database/CustomSerializeService.cs b/Common/Database/CustomSerializeService.cs index f37c9732..9e0aefca 100644 --- a/Common/Database/CustomSerializeService.cs +++ b/Common/Database/CustomSerializeService.cs @@ -1,38 +1,32 @@ using Newtonsoft.Json; using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database +namespace EggLink.DanhengServer.Database; + +public class CustomSerializeService : ISerializeService { - public class CustomSerializeService : ISerializeService + private readonly JsonSerializerSettings _jsonSettings; + + public CustomSerializeService() { - private JsonSerializerSettings _jsonSettings; - - public CustomSerializeService() + _jsonSettings = new JsonSerializerSettings { - _jsonSettings = new JsonSerializerSettings - { - DefaultValueHandling = DefaultValueHandling.Ignore // ignore default values - }; - } - - public string SerializeObject(object value) - { - return JsonConvert.SerializeObject(value, _jsonSettings); - } - - public T DeserializeObject(string value) - { - return JsonConvert.DeserializeObject(value)!; - } - - public string SugarSerializeObject(object value) - { - return JsonConvert.SerializeObject(value, _jsonSettings); - } + DefaultValueHandling = DefaultValueHandling.Ignore // ignore default values + }; } -} + + public string SerializeObject(object value) + { + return JsonConvert.SerializeObject(value, _jsonSettings); + } + + public T DeserializeObject(string value) + { + return JsonConvert.DeserializeObject(value)!; + } + + public string SugarSerializeObject(object value) + { + return JsonConvert.SerializeObject(value, _jsonSettings); + } +} \ No newline at end of file diff --git a/Common/Database/DatabaseHelper.cs b/Common/Database/DatabaseHelper.cs index 31c0c266..1ea8671b 100644 --- a/Common/Database/DatabaseHelper.cs +++ b/Common/Database/DatabaseHelper.cs @@ -1,328 +1,306 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Database.Mission; -using EggLink.DanhengServer.Database.Scene; using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Util; using SqlSugar; -namespace EggLink.DanhengServer.Database +namespace EggLink.DanhengServer.Database; + +public class DatabaseHelper { - public class DatabaseHelper + public static Logger logger = new("Database"); + public static SqlSugarScope? sqlSugarScope; + public static DatabaseHelper? Instance; + public static readonly Dictionary> UidInstanceMap = []; + public static readonly List ToSaveUidList = []; + public static long LastSaveTick = DateTime.UtcNow.Ticks; + public static Thread? SaveThread; + + public DatabaseHelper() { - public static Logger logger = new("Database"); - public static SqlSugarScope? sqlSugarScope; - public static DatabaseHelper? Instance; - public readonly static Dictionary> UidInstanceMap = []; - public readonly static List ToSaveUidList = []; - public static long LastSaveTick = DateTime.UtcNow.Ticks; - public static Thread? SaveThread; + Instance = this; + } - public DatabaseHelper() + public void Initialize() + { + logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.Database"))); + var config = ConfigManager.Config; + DbType type; + string connectionString; + switch (config.Database.DatabaseType) { - Instance = this; + case "sqlite": + type = DbType.Sqlite; + var f = new FileInfo(config.Path.DatabasePath + "/" + config.Database.DatabaseName); + if (!f.Exists && f.Directory != null) f.Directory.Create(); + connectionString = $"Data Source={f.FullName};"; + break; + case "mysql": + type = DbType.MySql; + connectionString = + $"server={config.Database.MySqlHost};Port={config.Database.MySqlPort};Database={config.Database.MySqlDatabase};Uid={config.Database.MySqlUser};Pwd={config.Database.MySqlPassword};"; + break; + default: + return; } - public void Initialize() + sqlSugarScope = new SqlSugarScope(new ConnectionConfig { - logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.Database"))); - var config = ConfigManager.Config; - DbType type; - string connectionString; - switch (config.Database.DatabaseType) + ConnectionString = connectionString, + DbType = type, + IsAutoCloseConnection = true, + ConfigureExternalServices = new ConfigureExternalServices { - case "sqlite": - type = DbType.Sqlite; - var f = new FileInfo(config.Path.DatabasePath + "/" + config.Database.DatabaseName); - if (!f.Exists && f.Directory != null) - { - f.Directory.Create(); - } - connectionString = $"Data Source={f.FullName};"; - break; - case "mysql": - type = DbType.MySql; - connectionString = $"server={config.Database.MySqlHost};Port={config.Database.MySqlPort};Database={config.Database.MySqlDatabase};Uid={config.Database.MySqlUser};Pwd={config.Database.MySqlPassword};"; - break; - default: - return; + SerializeService = new CustomSerializeService() } + }); - sqlSugarScope = new(new ConnectionConfig() - { - ConnectionString = connectionString, - DbType = type, - IsAutoCloseConnection = true, - ConfigureExternalServices = new() - { - SerializeService = new CustomSerializeService() - } - }); - - switch (config.Database.DatabaseType) - { - case "sqlite": - InitializeSqlite(); // for all database types - break; - case "mysql": - InitializeMysql(); - break; - default: - logger.Error("Unsupported database type"); - break; - } - - var baseType = typeof(BaseDatabaseDataHelper); - var assembly = typeof(BaseDatabaseDataHelper).Assembly; - var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType)); - foreach (var t in types) - { - typeof(DatabaseHelper).GetMethod("InitializeTable")?.MakeGenericMethod(t).Invoke(null, null); // cache the data - } - - LastSaveTick = DateTime.UtcNow.Ticks; - - SaveThread = new(() => - { - while (true) - { - CalcSaveDatabase(); - } - }); - SaveThread.Start(); + switch (config.Database.DatabaseType) + { + case "sqlite": + InitializeSqlite(); // for all database types + break; + case "mysql": + InitializeMysql(); + break; + default: + logger.Error("Unsupported database type"); + break; } - public static void InitializeTable() where T : class, new() + var baseType = typeof(BaseDatabaseDataHelper); + var assembly = typeof(BaseDatabaseDataHelper).Assembly; + var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType)); + foreach (var t in types) + typeof(DatabaseHelper).GetMethod("InitializeTable")?.MakeGenericMethod(t) + .Invoke(null, null); // cache the data + + LastSaveTick = DateTime.UtcNow.Ticks; + + SaveThread = new Thread(() => { - var list = sqlSugarScope?.Queryable() - .Select(x => x) - .ToList(); + while (true) CalcSaveDatabase(); + }); + SaveThread.Start(); + } - foreach (var instance in list!) - { - var inst = (instance as BaseDatabaseDataHelper)!; - if (!UidInstanceMap.TryGetValue(inst.Uid, out List? value)) - { - value = []; - UidInstanceMap[inst.Uid] = value; - } + public static void InitializeTable() where T : class, new() + { + var list = sqlSugarScope?.Queryable() + .Select(x => x) + .ToList(); - value.Add(inst); // add to the map - } - } - - public void UpgradeDatabase() + foreach (var instance in list!) { - logger.Info("Upgrading database..."); - - foreach (var instance in GetAllInstance()!) + var inst = (instance as BaseDatabaseDataHelper)!; + if (!UidInstanceMap.TryGetValue(inst.Uid, out var value)) { - instance.MoveFromOld(); + value = []; + UidInstanceMap[inst.Uid] = value; } - foreach (var instance in GetAllInstance()!) - { - UpdateInstance(instance); - } - } - - public void MoveFromSqlite() - { - logger.Info("Moving from sqlite..."); - - var config = ConfigManager.Config; - var f = new FileInfo(config.Path.DatabasePath + "/" + config.Database.DatabaseName); - var sqliteScope = new SqlSugarScope(new ConnectionConfig() - { - ConnectionString = $"Data Source={f.FullName};", - DbType = DbType.Sqlite, - IsAutoCloseConnection = true, - ConfigureExternalServices = new() - { - SerializeService = new CustomSerializeService() - }, - }); - - var baseType = typeof(BaseDatabaseDataHelper); - var assembly = typeof(BaseDatabaseDataHelper).Assembly; - var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType)); - foreach (var type in types) - { - typeof(DatabaseHelper).GetMethod("MoveSqliteTable")?.MakeGenericMethod(type).Invoke(null, [sqliteScope]); - } - - // exit the program - Environment.Exit(0); - } - - public static void MoveSqliteTable(SqlSugarScope scope) where T : class, new() - { - try - { - var list = scope.Queryable().ToList(); - foreach (var instance in list!) - { - sqlSugarScope?.Insertable(instance).ExecuteCommand(); - } - } - catch (Exception e) - { - Logger.GetByClassName().Error("An error occurred while moving the table", e); - } - } - - public static void InitializeSqlite() - { - var baseType = typeof(BaseDatabaseDataHelper); - var assembly = typeof(BaseDatabaseDataHelper).Assembly; - var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType)); - foreach (var type in types) - { - typeof(DatabaseHelper).GetMethod("InitializeSqliteTable")?.MakeGenericMethod(type).Invoke(null, null); - } - } - - public static void InitializeMysql() - { - sqlSugarScope?.DbMaintenance.CreateDatabase(); - InitializeSqlite(); - } - - public static void InitializeSqliteTable() where T : class, new() - { - try - { - sqlSugarScope?.CodeFirst.InitTables(); - } - catch - { - } - } - - public T? GetInstance(int uid) where T : class, new() - { - try - { - if (!UidInstanceMap.TryGetValue(uid, out List? value)) - { - value = []; - UidInstanceMap[uid] = value; - } - - foreach (var instance in value) - { - if (instance is T) - { - return instance as T; // found - } - } - - return null; // not found - } - catch (Exception e) - { - logger.Error("Unsupported type", e); - return null; - } - } - - public T GetInstanceOrCreateNew(int uid) where T : class, new() - { - var instance = GetInstance(uid); - if (instance == null) - { - instance = new(); - (instance as BaseDatabaseDataHelper)!.Uid = uid; - SaveInstance(instance); - } - return instance; - } - - public static List? GetAllInstance() where T : class, new() - { - try - { - return sqlSugarScope?.Queryable() - .Select(x => x) - .ToList(); - } - catch (Exception e) - { - logger.Error("Unsupported type", e); - return null; - } - } - - public static void SaveInstance(T instance) where T : class, new() - { - sqlSugarScope?.Insertable(instance).ExecuteCommand(); - UidInstanceMap[(instance as BaseDatabaseDataHelper)!.Uid].Add((instance as BaseDatabaseDataHelper)!); // add to the map - } - - public void UpdateInstance(T instance) where T : class, new() - { - //lock (GetLock((instance as BaseDatabaseDataHelper)!.Uid)) - //{ - // sqlSugarScope?.Updateable(instance).ExecuteCommand(); - //} - } - - public void CalcSaveDatabase() // per 5 min - { - if (LastSaveTick + TimeSpan.TicksPerMinute * 5 > DateTime.UtcNow.Ticks) return; - SaveDatabase(); - } - - public void SaveDatabase() // per 5 min - { - try - { - var prev = DateTime.Now; - var list = ToSaveUidList.ToList(); // copy the list to avoid the exception - foreach (var uid in list) - { - var value = UidInstanceMap[uid]; - var baseType = typeof(BaseDatabaseDataHelper); - var assembly = typeof(BaseDatabaseDataHelper).Assembly; - var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType)); - foreach (var type in types) - { - var instance = value.Find(x => x.GetType() == type); - if (instance != null) - { - typeof(DatabaseHelper).GetMethod("SaveDatabaseType")?.MakeGenericMethod(type).Invoke(null, [instance]); - } - } - } - - logger.Info(I18nManager.Translate("Server.ServerInfo.SaveDatabase", (DateTime.Now - prev).TotalSeconds.ToString()[..4])); - - ToSaveUidList.Clear(); - } - catch (Exception e) - { - logger.Error("An error occurred while saving the database", e); - } - - LastSaveTick = DateTime.UtcNow.Ticks; - } - - public static void SaveDatabaseType(T instance) where T : class, new() - { - try - { - sqlSugarScope?.Updateable(instance).ExecuteCommand(); - } - catch (Exception e) - { - logger.Error("An error occurred while saving the database", e); - } - } - - public void DeleteInstance(T instance) where T : class, new() - { - sqlSugarScope?.Deleteable(instance).ExecuteCommand(); - UidInstanceMap[(instance as BaseDatabaseDataHelper)!.Uid].Remove((instance as BaseDatabaseDataHelper)!); // remove from the map - ToSaveUidList.Remove((instance as BaseDatabaseDataHelper)!.Uid); // remove from the save list + value.Add(inst); // add to the map } } -} + + public void UpgradeDatabase() + { + logger.Info("Upgrading database..."); + + foreach (var instance in GetAllInstance()!) instance.MoveFromOld(); + + foreach (var instance in GetAllInstance()!) UpdateInstance(instance); + } + + public void MoveFromSqlite() + { + logger.Info("Moving from sqlite..."); + + var config = ConfigManager.Config; + var f = new FileInfo(config.Path.DatabasePath + "/" + config.Database.DatabaseName); + var sqliteScope = new SqlSugarScope(new ConnectionConfig + { + ConnectionString = $"Data Source={f.FullName};", + DbType = DbType.Sqlite, + IsAutoCloseConnection = true, + ConfigureExternalServices = new ConfigureExternalServices + { + SerializeService = new CustomSerializeService() + } + }); + + var baseType = typeof(BaseDatabaseDataHelper); + var assembly = typeof(BaseDatabaseDataHelper).Assembly; + var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType)); + foreach (var type in types) + typeof(DatabaseHelper).GetMethod("MoveSqliteTable")?.MakeGenericMethod(type).Invoke(null, [sqliteScope]); + + // exit the program + Environment.Exit(0); + } + + public static void MoveSqliteTable(SqlSugarScope scope) where T : class, new() + { + try + { + var list = scope.Queryable().ToList(); + foreach (var instance in list!) sqlSugarScope?.Insertable(instance).ExecuteCommand(); + } + catch (Exception e) + { + Logger.GetByClassName().Error("An error occurred while moving the table", e); + } + } + + public static void InitializeSqlite() + { + var baseType = typeof(BaseDatabaseDataHelper); + var assembly = typeof(BaseDatabaseDataHelper).Assembly; + var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType)); + foreach (var type in types) + typeof(DatabaseHelper).GetMethod("InitializeSqliteTable")?.MakeGenericMethod(type).Invoke(null, null); + } + + public static void InitializeMysql() + { + sqlSugarScope?.DbMaintenance.CreateDatabase(); + InitializeSqlite(); + } + + public static void InitializeSqliteTable() where T : class, new() + { + try + { + sqlSugarScope?.CodeFirst.InitTables(); + } + catch + { + } + } + + public T? GetInstance(int uid) where T : class, new() + { + try + { + if (!UidInstanceMap.TryGetValue(uid, out var value)) + { + value = []; + UidInstanceMap[uid] = value; + } + + foreach (var instance in value) + if (instance is T) + return instance as T; // found + + return null; // not found + } + catch (Exception e) + { + logger.Error("Unsupported type", e); + return null; + } + } + + public T GetInstanceOrCreateNew(int uid) where T : class, new() + { + var instance = GetInstance(uid); + if (instance == null) + { + instance = new T(); + (instance as BaseDatabaseDataHelper)!.Uid = uid; + SaveInstance(instance); + } + + return instance; + } + + public static List? GetAllInstance() where T : class, new() + { + try + { + return sqlSugarScope?.Queryable() + .Select(x => x) + .ToList(); + } + catch (Exception e) + { + logger.Error("Unsupported type", e); + return null; + } + } + + public static void SaveInstance(T instance) where T : class, new() + { + sqlSugarScope?.Insertable(instance).ExecuteCommand(); + UidInstanceMap[(instance as BaseDatabaseDataHelper)!.Uid] + .Add((instance as BaseDatabaseDataHelper)!); // add to the map + } + + public void UpdateInstance(T instance) where T : class, new() + { + //lock (GetLock((instance as BaseDatabaseDataHelper)!.Uid)) + //{ + // sqlSugarScope?.Updateable(instance).ExecuteCommand(); + //} + } + + public void CalcSaveDatabase() // per 5 min + { + if (LastSaveTick + TimeSpan.TicksPerMinute * 5 > DateTime.UtcNow.Ticks) return; + SaveDatabase(); + } + + public void SaveDatabase() // per 5 min + { + try + { + var prev = DateTime.Now; + var list = ToSaveUidList.ToList(); // copy the list to avoid the exception + foreach (var uid in list) + { + var value = UidInstanceMap[uid]; + var baseType = typeof(BaseDatabaseDataHelper); + var assembly = typeof(BaseDatabaseDataHelper).Assembly; + var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType)); + foreach (var type in types) + { + var instance = value.Find(x => x.GetType() == type); + if (instance != null) + typeof(DatabaseHelper).GetMethod("SaveDatabaseType")?.MakeGenericMethod(type) + .Invoke(null, [instance]); + } + } + + logger.Info(I18nManager.Translate("Server.ServerInfo.SaveDatabase", + (DateTime.Now - prev).TotalSeconds.ToString()[..4])); + + ToSaveUidList.Clear(); + } + catch (Exception e) + { + logger.Error("An error occurred while saving the database", e); + } + + LastSaveTick = DateTime.UtcNow.Ticks; + } + + public static void SaveDatabaseType(T instance) where T : class, new() + { + try + { + sqlSugarScope?.Updateable(instance).ExecuteCommand(); + } + catch (Exception e) + { + logger.Error("An error occurred while saving the database", e); + } + } + + public void DeleteInstance(T instance) where T : class, new() + { + sqlSugarScope?.Deleteable(instance).ExecuteCommand(); + UidInstanceMap[(instance as BaseDatabaseDataHelper)!.Uid] + .Remove((instance as BaseDatabaseDataHelper)!); // remove from the map + ToSaveUidList.Remove((instance as BaseDatabaseDataHelper)!.Uid); // remove from the save list + } +} \ No newline at end of file diff --git a/Common/Database/Friend/FriendData.cs b/Common/Database/Friend/FriendData.cs index fd313663..6856887b 100644 --- a/Common/Database/Friend/FriendData.cs +++ b/Common/Database/Friend/FriendData.cs @@ -1,42 +1,32 @@ using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.Friend +namespace EggLink.DanhengServer.Database.Friend; + +[SugarTable("Friend")] +public class FriendData : BaseDatabaseDataHelper { - [SugarTable("Friend")] - public class FriendData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public List FriendList { get; set; } = []; + [SugarColumn(IsJson = true)] public List FriendList { get; set; } = []; - [SugarColumn(IsJson = true)] - public List BlackList { get; set; } = []; + [SugarColumn(IsJson = true)] public List BlackList { get; set; } = []; - [SugarColumn(IsJson = true)] - public List SendApplyList { get; set; } = []; + [SugarColumn(IsJson = true)] public List SendApplyList { get; set; } = []; - [SugarColumn(IsJson = true)] - public List ReceiveApplyList { get; set; } = []; + [SugarColumn(IsJson = true)] public List ReceiveApplyList { get; set; } = []; - [SugarColumn(IsJson = true)] - public Dictionary ChatHistory { get; set; } = []; // key: friend uid - } - - public class FriendChatHistory - { - public List MessageList { get; set; } = []; - } - - public class FriendChatData - { - public long SendTime { get; set; } - public string Message { get; set; } = ""; - public int ExtraId { get; set; } - public int SendUid { get; set; } - public int ReceiveUid { get; set; } - } + [SugarColumn(IsJson = true)] + public Dictionary ChatHistory { get; set; } = []; // key: friend uid } + +public class FriendChatHistory +{ + public List MessageList { get; set; } = []; +} + +public class FriendChatData +{ + public long SendTime { get; set; } + public string Message { get; set; } = ""; + public int ExtraId { get; set; } + public int SendUid { get; set; } + public int ReceiveUid { get; set; } +} \ No newline at end of file diff --git a/Common/Database/Gacha/GachaData.cs b/Common/Database/Gacha/GachaData.cs index b93a4427..8c8b4d5d 100644 --- a/Common/Database/Gacha/GachaData.cs +++ b/Common/Database/Gacha/GachaData.cs @@ -1,27 +1,21 @@ using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.Gacha +namespace EggLink.DanhengServer.Database.Gacha; + +[SugarTable("Gacha")] +public class GachaData : BaseDatabaseDataHelper { - [SugarTable("Gacha")] - public class GachaData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public List GachaHistory { get; set; } = []; - public bool LastAvatarGachaFailed { get; set; } = false; - public bool LastWeaponGachaFailed { get; set; } = false; - public int LastGachaFailedCount { get; set; } = 0; - public int LastGachaPurpleFailedCount { get; set; } = 0; - } + [SugarColumn(IsJson = true)] public List GachaHistory { get; set; } = []; - public class GachaInfo - { - public int GachaId { get; set; } - public long Time { get; set; } - public int ItemId { get; set; } - } + public bool LastAvatarGachaFailed { get; set; } = false; + public bool LastWeaponGachaFailed { get; set; } = false; + public int LastGachaFailedCount { get; set; } = 0; + public int LastGachaPurpleFailedCount { get; set; } = 0; } + +public class GachaInfo +{ + public int GachaId { get; set; } + public long Time { get; set; } + public int ItemId { get; set; } +} \ No newline at end of file diff --git a/Common/Database/Inventory/InventoryData.cs b/Common/Database/Inventory/InventoryData.cs index 330f0c7d..672d4c61 100644 --- a/Common/Database/Inventory/InventoryData.cs +++ b/Common/Database/Inventory/InventoryData.cs @@ -2,270 +2,254 @@ using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using Newtonsoft.Json; using SqlSugar; -namespace EggLink.DanhengServer.Database.Inventory +namespace EggLink.DanhengServer.Database.Inventory; + +[SugarTable("InventoryData")] +public class InventoryData : BaseDatabaseDataHelper { - [SugarTable("InventoryData")] - public class InventoryData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public List MaterialItems { get; set; } = []; - [SugarColumn(IsJson = true)] - public List EquipmentItems { get; set; } = []; - [SugarColumn(IsJson = true)] - public List RelicItems { get; set; } = []; + [SugarColumn(IsJson = true)] public List MaterialItems { get; set; } = []; - public int NextUniqueId { get; set; } = 100; + [SugarColumn(IsJson = true)] public List EquipmentItems { get; set; } = []; + + [SugarColumn(IsJson = true)] public List RelicItems { get; set; } = []; + + public int NextUniqueId { get; set; } = 100; +} + +public class ItemData +{ + public int UniqueId { get; set; } + public int ItemId { get; set; } + public int Count { get; set; } + public int Level { get; set; } + public int Exp { get; set; } + public int TotalExp { get; set; } + public int Promotion { get; set; } + public int Rank { get; set; } // Superimpose + public bool Locked { get; set; } + public bool Discarded { get; set; } + + public int MainAffix { get; set; } + public List SubAffixes { get; set; } = []; + + public int EquipAvatar { get; set; } + + #region Action + + public void AddRandomRelicMainAffix() + { + GameData.RelicConfigData.TryGetValue(ItemId, out var config); + if (config == null) return; + var affixId = GameTools.GetRandomRelicMainAffix(config.MainAffixGroup); + MainAffix = affixId; } - public class ItemData + public void IncreaseRandomRelicSubAffix() { - public int UniqueId { get; set; } - public int ItemId { get; set; } - public int Count { get; set; } - public int Level { get; set; } - public int Exp { get; set; } - public int TotalExp { get; set; } - public int Promotion { get; set; } - public int Rank { get; set; } // Superimpose - public bool Locked { get; set; } - public bool Discarded { get; set; } - - public int MainAffix { get; set; } - public List SubAffixes { get; set; } = []; - - public int EquipAvatar { get; set; } - - #region Action - - public void AddRandomRelicMainAffix() - { - GameData.RelicConfigData.TryGetValue(ItemId, out var config); - if (config == null) return; - var affixId = GameTools.GetRandomRelicMainAffix(config.MainAffixGroup); - MainAffix = affixId; - } - - public void IncreaseRandomRelicSubAffix() - { - GameData.RelicConfigData.TryGetValue(ItemId, out var config); - if (config == null) return; - GameData.RelicSubAffixData.TryGetValue(config.SubAffixGroup, out var affixes); - if (affixes == null) return; - var element = SubAffixes.RandomElement(); - var affix = affixes.Values.ToList().Find(x => x.AffixID == element.Id); - if (affix == null) return; - element.IncreaseStep(affix.StepNum); - } - - public void AddRandomRelicSubAffix(int count = 1) - { - GameData.RelicConfigData.TryGetValue(ItemId, out var config); - if (config == null) - { - return; - } - GameData.RelicSubAffixData.TryGetValue(config.SubAffixGroup, out var affixes); - - if (affixes == null) - { - return; - } - - var rollPool = new List(); - foreach (var affix in affixes.Values) - { - if (SubAffixes.Find(x => x.Id == affix.AffixID) == null) - { - rollPool.Add(affix); - } - } - - for (int i = 0; i < count; i++) - { - var affixConfig = rollPool.RandomElement(); - ItemSubAffix subAffix = new(affixConfig, 1); - SubAffixes.Add(subAffix); - rollPool.Remove(affixConfig); - } - } - - #endregion - - #region Serialization - - public Material ToMaterialProto() - { - return new() - { - Tid = (uint)ItemId, - Num = (uint)Count, - }; - } - - public Relic ToRelicProto() - { - Relic relic = new() - { - Tid = (uint)ItemId, - UniqueId = (uint)UniqueId, - Level = (uint)Level, - IsProtected = Locked, - Exp = (uint)Exp, - IsDiscarded = Discarded, - DressAvatarId = (uint)EquipAvatar, - MainAffixId = (uint)MainAffix, - }; - if (SubAffixes.Count >= 1) - { - foreach (var subAffix in SubAffixes) - { - relic.SubAffixList.Add(subAffix.ToProto()); - } - } - return relic; - } - - public Equipment ToEquipmentProto() - { - return new() - { - Tid = (uint)ItemId, - UniqueId = (uint)UniqueId, - Level = (uint)Level, - Exp = (uint)Exp, - IsProtected = Locked, - Promotion = (uint)Promotion, - Rank = (uint)Rank, - DressAvatarId = (uint)EquipAvatar - }; - } - - public Item ToProto() - { - return new() - { - ItemId = (uint)ItemId, - Num = (uint)Count, - Level = (uint)Level, - MainAffixId = (uint)MainAffix, - Rank = (uint)Rank, - Promotion = (uint)Promotion, - UniqueId = (uint)UniqueId, - }; - } - - public PileItem ToPileProto() - { - return new() - { - ItemId = (uint)ItemId, - ItemNum = (uint)Count, - }; - } - - public DisplayEquipmentInfo ToDisplayEquipmentProto() - { - return new() - { - Tid = (uint)ItemId, - Level = (uint)Level, - Exp = (uint)Exp, - Promotion = (uint)Promotion, - Rank = (uint)Rank, - }; - } - - public DisplayRelicInfo ToDisplayRelicProto() - { - DisplayRelicInfo relic = new() - { - Tid = (uint)ItemId, - Level = (uint)Level, - Type = (uint)GameData.RelicConfigData[ItemId].Type, - MainAffixId = (uint)MainAffix, - }; - - if (SubAffixes.Count >= 1) - { - foreach (var subAffix in SubAffixes) - { - relic.SubAffixList.Add(subAffix.ToProto()); - } - } - - return relic; - } - - public ItemData Clone() - { - return new() - { - UniqueId = UniqueId, - ItemId = ItemId, - Count = Count, - Level = Level, - Exp = Exp, - TotalExp = TotalExp, - Promotion = Promotion, - Rank = Rank, - Locked = Locked, - Discarded = Discarded, - MainAffix = MainAffix, - SubAffixes = SubAffixes.Select(x => x.Clone()).ToList(), - EquipAvatar = EquipAvatar - }; - } - - #endregion + GameData.RelicConfigData.TryGetValue(ItemId, out var config); + if (config == null) return; + GameData.RelicSubAffixData.TryGetValue(config.SubAffixGroup, out var affixes); + if (affixes == null) return; + var element = SubAffixes.RandomElement(); + var affix = affixes.Values.ToList().Find(x => x.AffixID == element.Id); + if (affix == null) return; + element.IncreaseStep(affix.StepNum); } - public class ItemSubAffix + public void AddRandomRelicSubAffix(int count = 1) { - public int Id { get; set; } // Affix id + GameData.RelicConfigData.TryGetValue(ItemId, out var config); + if (config == null) return; + GameData.RelicSubAffixData.TryGetValue(config.SubAffixGroup, out var affixes); - public int Count { get; set; } - public int Step { get; set; } + if (affixes == null) return; - public ItemSubAffix() { } + var rollPool = new List(); + foreach (var affix in affixes.Values) + if (SubAffixes.Find(x => x.Id == affix.AffixID) == null) + rollPool.Add(affix); - public ItemSubAffix(RelicSubAffixConfigExcel excel, int count) + for (var i = 0; i < count; i++) { - Id = excel.AffixID; - Count = count; - Step = Extensions.RandomInt(0, excel.StepNum * count + 1); + var affixConfig = rollPool.RandomElement(); + ItemSubAffix subAffix = new(affixConfig, 1); + SubAffixes.Add(subAffix); + rollPool.Remove(affixConfig); } + } - public ItemSubAffix(int id, int count, int step) + #endregion + + #region Serialization + + public Material ToMaterialProto() + { + return new Material { - Id = id; - Count = count; - Step = step; - } + Tid = (uint)ItemId, + Num = (uint)Count + }; + } - public void IncreaseStep(int stepNum) + public Relic ToRelicProto() + { + Relic relic = new() { - Count++; - Step += Extensions.RandomInt(0, stepNum + 1); - } + Tid = (uint)ItemId, + UniqueId = (uint)UniqueId, + Level = (uint)Level, + IsProtected = Locked, + Exp = (uint)Exp, + IsDiscarded = Discarded, + DressAvatarId = (uint)EquipAvatar, + MainAffixId = (uint)MainAffix + }; + if (SubAffixes.Count >= 1) + foreach (var subAffix in SubAffixes) + relic.SubAffixList.Add(subAffix.ToProto()); + return relic; + } - public RelicAffix ToProto() => new() + public Equipment ToEquipmentProto() + { + return new Equipment + { + Tid = (uint)ItemId, + UniqueId = (uint)UniqueId, + Level = (uint)Level, + Exp = (uint)Exp, + IsProtected = Locked, + Promotion = (uint)Promotion, + Rank = (uint)Rank, + DressAvatarId = (uint)EquipAvatar + }; + } + + public Item ToProto() + { + return new Item + { + ItemId = (uint)ItemId, + Num = (uint)Count, + Level = (uint)Level, + MainAffixId = (uint)MainAffix, + Rank = (uint)Rank, + Promotion = (uint)Promotion, + UniqueId = (uint)UniqueId + }; + } + + public PileItem ToPileProto() + { + return new PileItem + { + ItemId = (uint)ItemId, + ItemNum = (uint)Count + }; + } + + public DisplayEquipmentInfo ToDisplayEquipmentProto() + { + return new DisplayEquipmentInfo + { + Tid = (uint)ItemId, + Level = (uint)Level, + Exp = (uint)Exp, + Promotion = (uint)Promotion, + Rank = (uint)Rank + }; + } + + public DisplayRelicInfo ToDisplayRelicProto() + { + DisplayRelicInfo relic = new() + { + Tid = (uint)ItemId, + Level = (uint)Level, + Type = (uint)GameData.RelicConfigData[ItemId].Type, + MainAffixId = (uint)MainAffix + }; + + if (SubAffixes.Count >= 1) + foreach (var subAffix in SubAffixes) + relic.SubAffixList.Add(subAffix.ToProto()); + + return relic; + } + + public ItemData Clone() + { + return new ItemData + { + UniqueId = UniqueId, + ItemId = ItemId, + Count = Count, + Level = Level, + Exp = Exp, + TotalExp = TotalExp, + Promotion = Promotion, + Rank = Rank, + Locked = Locked, + Discarded = Discarded, + MainAffix = MainAffix, + SubAffixes = SubAffixes.Select(x => x.Clone()).ToList(), + EquipAvatar = EquipAvatar + }; + } + + #endregion +} + +public class ItemSubAffix +{ + public ItemSubAffix() + { + } + + public ItemSubAffix(RelicSubAffixConfigExcel excel, int count) + { + Id = excel.AffixID; + Count = count; + Step = Extensions.RandomInt(0, excel.StepNum * count + 1); + } + + public ItemSubAffix(int id, int count, int step) + { + Id = id; + Count = count; + Step = step; + } + + public int Id { get; set; } // Affix id + + public int Count { get; set; } + public int Step { get; set; } + + public void IncreaseStep(int stepNum) + { + Count++; + Step += Extensions.RandomInt(0, stepNum + 1); + } + + public RelicAffix ToProto() + { + return new RelicAffix { AffixId = (uint)Id, Cnt = (uint)Count, Step = (uint)Step }; - - public ItemSubAffix Clone() - { - return new() - { - Id = Id, - Count = Count, - Step = Step - }; - } } -} + + public ItemSubAffix Clone() + { + return new ItemSubAffix + { + Id = Id, + Count = Count, + Step = Step + }; + } +} \ No newline at end of file diff --git a/Common/Database/Lineup/LineupData.cs b/Common/Database/Lineup/LineupData.cs index 208d1332..437b0aac 100644 --- a/Common/Database/Lineup/LineupData.cs +++ b/Common/Database/Lineup/LineupData.cs @@ -1,176 +1,155 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Database.Avatar; using EggLink.DanhengServer.Database.Mission; -using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Proto; using Newtonsoft.Json; using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.Lineup +namespace EggLink.DanhengServer.Database.Lineup; + +[SugarTable("Lineup")] +public class LineupData : BaseDatabaseDataHelper { - [SugarTable("Lineup")] - public class LineupData : BaseDatabaseDataHelper + public int CurLineup { get; set; } // index of current lineup + public int CurExtraLineup { get; set; } = -1; // index of current extra lineup + + [SugarColumn(IsJson = true)] public Dictionary Lineups { get; set; } = []; // 9 * 4 + + public int GetCurLineupIndex() { - public int CurLineup { get; set; } // index of current lineup - public int CurExtraLineup { get; set; } = -1; // index of current extra lineup - [SugarColumn(IsJson = true)] - public Dictionary Lineups { get; set; } = []; // 9 * 4 - - public int GetCurLineupIndex() - { - return CurExtraLineup == -1 ? CurLineup : CurExtraLineup; - } - } - - public class LineupInfo - { - public string? Name { get; set; } - public int LineupType { get; set; } - public int LeaderAvatarId { get; set; } - public List? BaseAvatars { get; set; } - public int Mp { get; set; } = 5; - - [JsonIgnore()] - public LineupData? LineupData { get; set; } - - [JsonIgnore()] - public AvatarData? AvatarData { get; set; } - - public int GetSlot(int avatarId) - { - return BaseAvatars?.FindIndex(item => item.BaseAvatarId == avatarId) ?? -1; - } - - public bool Heal(int count, bool allowRevive) - { - bool result = false; - if (BaseAvatars != null && AvatarData != null) - { - foreach (var avatar in BaseAvatars) - { - var avatarInfo = AvatarData?.Avatars?.Find(item => item.GetBaseAvatarId() == avatar.BaseAvatarId); - if (avatarInfo != null) - { - if (avatarInfo.GetCurHp(IsExtraLineup()) <= 0 && !allowRevive) - { - continue; - } - if (avatarInfo.GetCurHp(IsExtraLineup()) >= 10000) - { - continue; - } - avatarInfo.SetCurHp(Math.Min(avatarInfo.GetCurHp(IsExtraLineup()) + count, 10000), IsExtraLineup()); - result = true; - } - } - DatabaseHelper.Instance?.UpdateInstance(AvatarData!); - } - return result; - } - - public bool CostNowPercentHp(double count) - { - bool result = false; - if (BaseAvatars != null && AvatarData != null) - { - foreach (var avatar in BaseAvatars) - { - var avatarInfo = AvatarData?.Avatars?.Find(item => item.GetAvatarId() == avatar.BaseAvatarId); - if (avatarInfo != null) - { - if (avatarInfo.CurrentHp <= 0) - { - continue; - } - avatarInfo.SetCurHp((int)Math.Max(avatarInfo.GetCurHp(IsExtraLineup()) * (1 - count), 100), IsExtraLineup()); - result = true; - } - } - DatabaseHelper.Instance?.UpdateInstance(AvatarData!); - } - return result; - } - - public bool IsExtraLineup() - { - return LineupType != 0; - } - - public Proto.LineupInfo ToProto() - { - Proto.LineupInfo info = new() - { - Name = Name, - MaxMp = 5, - Mp = (uint)Mp, - ExtraLineupType = (ExtraLineupType)(LineupType == (int)ExtraLineupType.LineupHeliobus ? (int)ExtraLineupType.LineupNone : LineupType), - Index = (uint)(LineupData?.Lineups?.Values.ToList().IndexOf(this) ?? 0), - }; - - if (LineupType != (int)ExtraLineupType.LineupNone) - { - info.Index = (uint)(LineupType + 10); - } - - if (BaseAvatars?.Find(item => item.BaseAvatarId == LeaderAvatarId) != null) // find leader,if not exist,set to 0 - { - info.LeaderSlot = (uint)BaseAvatars.IndexOf(BaseAvatars.Find(item => item.BaseAvatarId == LeaderAvatarId)!); - } else - { - info.LeaderSlot = 0; - } - - if (BaseAvatars != null) - { - foreach (var avatar in BaseAvatars) - { - if (avatar.AssistUid != 0) // assist avatar - { - var assistPlayer = DatabaseHelper.Instance?.GetInstance(avatar.AssistUid); - if (assistPlayer != null) - { - info.AvatarList.Add(assistPlayer?.Avatars?.Find(item => item.GetAvatarId() == avatar.BaseAvatarId)?.ToLineupInfo(BaseAvatars.IndexOf(avatar), this, AvatarType.AvatarAssistType)); // assist avatar may not work - } - } else if (avatar.SpecialAvatarId != 0) // special avatar - { - var specialAvatar = GameData.SpecialAvatarData[avatar.SpecialAvatarId]; - if (specialAvatar != null) - { - info.AvatarList.Add(specialAvatar.ToAvatarData(LineupData!.Uid).ToLineupInfo(BaseAvatars.IndexOf(avatar), this, AvatarType.AvatarTrialType)); - } - } else // normal avatar - { - info.AvatarList.Add(AvatarData?.Avatars?.Find(item => item.AvatarId == avatar.BaseAvatarId)?.ToLineupInfo(BaseAvatars.IndexOf(avatar), this)); - } - } - } - - var storyId = DatabaseHelper.Instance!.GetInstance(AvatarData!.Uid)?.CurStoryLineId; - if (storyId != null && storyId != 0) - { - info.GameStoryLineId = (uint)storyId; - BaseAvatars?.ForEach(item => - { - if (item.SpecialAvatarId != 0) - { - info.StoryLineBaseAvatarIdList.Add((uint)item.BaseAvatarId); - } - }); - } - - return info; - } - } - - public class LineupAvatarInfo - { - public int BaseAvatarId { get; set; } - public int AssistUid { get; set; } - public int SpecialAvatarId { get; set; } + return CurExtraLineup == -1 ? CurLineup : CurExtraLineup; } } + +public class LineupInfo +{ + public string? Name { get; set; } + public int LineupType { get; set; } + public int LeaderAvatarId { get; set; } + public List? BaseAvatars { get; set; } + public int Mp { get; set; } = 5; + + [JsonIgnore] public LineupData? LineupData { get; set; } + + [JsonIgnore] public AvatarData? AvatarData { get; set; } + + public int GetSlot(int avatarId) + { + return BaseAvatars?.FindIndex(item => item.BaseAvatarId == avatarId) ?? -1; + } + + public bool Heal(int count, bool allowRevive) + { + var result = false; + if (BaseAvatars != null && AvatarData != null) + { + foreach (var avatar in BaseAvatars) + { + var avatarInfo = AvatarData?.Avatars?.Find(item => item.GetBaseAvatarId() == avatar.BaseAvatarId); + if (avatarInfo != null) + { + if (avatarInfo.GetCurHp(IsExtraLineup()) <= 0 && !allowRevive) continue; + if (avatarInfo.GetCurHp(IsExtraLineup()) >= 10000) continue; + avatarInfo.SetCurHp(Math.Min(avatarInfo.GetCurHp(IsExtraLineup()) + count, 10000), IsExtraLineup()); + result = true; + } + } + + DatabaseHelper.Instance?.UpdateInstance(AvatarData!); + } + + return result; + } + + public bool CostNowPercentHp(double count) + { + var result = false; + if (BaseAvatars != null && AvatarData != null) + { + foreach (var avatar in BaseAvatars) + { + var avatarInfo = AvatarData?.Avatars?.Find(item => item.GetAvatarId() == avatar.BaseAvatarId); + if (avatarInfo != null) + { + if (avatarInfo.CurrentHp <= 0) continue; + avatarInfo.SetCurHp((int)Math.Max(avatarInfo.GetCurHp(IsExtraLineup()) * (1 - count), 100), + IsExtraLineup()); + result = true; + } + } + + DatabaseHelper.Instance?.UpdateInstance(AvatarData!); + } + + return result; + } + + public bool IsExtraLineup() + { + return LineupType != 0; + } + + public Proto.LineupInfo ToProto() + { + Proto.LineupInfo info = new() + { + Name = Name, + MaxMp = 5, + Mp = (uint)Mp, + ExtraLineupType = (ExtraLineupType)(LineupType == (int)ExtraLineupType.LineupHeliobus + ? (int)ExtraLineupType.LineupNone + : LineupType), + Index = (uint)(LineupData?.Lineups?.Values.ToList().IndexOf(this) ?? 0) + }; + + if (LineupType != (int)ExtraLineupType.LineupNone) info.Index = (uint)(LineupType + 10); + + if (BaseAvatars?.Find(item => item.BaseAvatarId == LeaderAvatarId) != null) // find leader,if not exist,set to 0 + info.LeaderSlot = (uint)BaseAvatars.IndexOf(BaseAvatars.Find(item => item.BaseAvatarId == LeaderAvatarId)!); + else + info.LeaderSlot = 0; + + if (BaseAvatars != null) + foreach (var avatar in BaseAvatars) + if (avatar.AssistUid != 0) // assist avatar + { + var assistPlayer = DatabaseHelper.Instance?.GetInstance(avatar.AssistUid); + if (assistPlayer != null) + info.AvatarList.Add(assistPlayer?.Avatars + ?.Find(item => item.GetAvatarId() == avatar.BaseAvatarId) + ?.ToLineupInfo(BaseAvatars.IndexOf(avatar), this, + AvatarType.AvatarAssistType)); // assist avatar may not work + } + else if (avatar.SpecialAvatarId != 0) // special avatar + { + var specialAvatar = GameData.SpecialAvatarData[avatar.SpecialAvatarId]; + if (specialAvatar != null) + info.AvatarList.Add(specialAvatar.ToAvatarData(LineupData!.Uid) + .ToLineupInfo(BaseAvatars.IndexOf(avatar), this, AvatarType.AvatarTrialType)); + } + else // normal avatar + { + info.AvatarList.Add(AvatarData?.Avatars?.Find(item => item.AvatarId == avatar.BaseAvatarId) + ?.ToLineupInfo(BaseAvatars.IndexOf(avatar), this)); + } + + var storyId = DatabaseHelper.Instance!.GetInstance(AvatarData!.Uid)?.CurStoryLineId; + if (storyId != null && storyId != 0) + { + info.GameStoryLineId = (uint)storyId; + BaseAvatars?.ForEach(item => + { + if (item.SpecialAvatarId != 0) info.StoryLineBaseAvatarIdList.Add((uint)item.BaseAvatarId); + }); + } + + return info; + } +} + +public class LineupAvatarInfo +{ + public int BaseAvatarId { get; set; } + public int AssistUid { get; set; } + public int SpecialAvatarId { get; set; } +} \ No newline at end of file diff --git a/Common/Database/Mail/MailData.cs b/Common/Database/Mail/MailData.cs index 4bd8f1e4..c85d7c38 100644 --- a/Common/Database/Mail/MailData.cs +++ b/Common/Database/Mail/MailData.cs @@ -1,67 +1,59 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Proto; using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.Mail +namespace EggLink.DanhengServer.Database.Mail; + +[SugarTable("Mail")] +public class MailData : BaseDatabaseDataHelper { - [SugarTable("Mail")] - public class MailData : BaseDatabaseDataHelper + [SugarColumn(IsJson = true)] public List MailList { get; set; } = []; + + [SugarColumn(IsJson = true)] public List NoticeMailList { get; set; } = []; + + public int NextMailId { get; set; } = 1; +} + +public class MailInfo +{ + public int MailID { get; set; } + public string SenderName { get; set; } = ""; + public string Title { get; set; } = ""; + public string Content { get; set; } = ""; + public bool IsRead { get; set; } + public bool IsStar { get; set; } + public long SendTime { get; set; } + public long ExpireTime { get; set; } + public int TemplateID { get; set; } + public MailAttachmentInfo Attachment { get; set; } = new(); + + public ClientMail ToProto() { - [SugarColumn(IsJson = true)] - public List MailList { get; set; } = []; - - [SugarColumn(IsJson = true)] - public List NoticeMailList { get; set; } = []; - - public int NextMailId { get; set; } = 1; - } - - public class MailInfo - { - public int MailID { get; set; } - public string SenderName { get; set; } = ""; - public string Title { get; set; } = ""; - public string Content { get; set; } = ""; - public bool IsRead { get; set; } - public bool IsStar { get; set; } - public long SendTime { get; set; } - public long ExpireTime { get; set; } - public int TemplateID { get; set; } - public MailAttachmentInfo Attachment { get; set; } = new(); - - public ClientMail ToProto() + return new ClientMail { - return new() - { - Id = (uint)MailID, - Sender = SenderName, - MessageText = Content, - MailType = IsStar ? MailType.Star : MailType.Normal, - ExpireTime = ExpireTime, - IsRead = IsRead, - TemplateId = (uint)TemplateID, - Title = Title, - Time = SendTime, - Attachment = Attachment.ToProto() - }; - } - } - - public class MailAttachmentInfo - { - public List Items { get; set; } = []; - - public ItemList ToProto() - { - return new() - { - ItemList_ = { Items.Select(x => x.ToProto()).ToList() } - }; - } + Id = (uint)MailID, + Sender = SenderName, + MessageText = Content, + MailType = IsStar ? MailType.Star : MailType.Normal, + ExpireTime = ExpireTime, + IsRead = IsRead, + TemplateId = (uint)TemplateID, + Title = Title, + Time = SendTime, + Attachment = Attachment.ToProto() + }; } } + +public class MailAttachmentInfo +{ + public List Items { get; set; } = []; + + public ItemList ToProto() + { + return new ItemList + { + ItemList_ = { Items.Select(x => x.ToProto()).ToList() } + }; + } +} \ No newline at end of file diff --git a/Common/Database/Message/MessageData.cs b/Common/Database/Message/MessageData.cs index b74a7b67..23100cb6 100644 --- a/Common/Database/Message/MessageData.cs +++ b/Common/Database/Message/MessageData.cs @@ -1,39 +1,32 @@ using EggLink.DanhengServer.Proto; using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.Message +namespace EggLink.DanhengServer.Database.Message; + +[SugarTable("Message")] +public class MessageData : BaseDatabaseDataHelper { - [SugarTable("Message")] - public class MessageData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public Dictionary Groups { get; set; } = []; - } - - public class MessageGroupData - { - public int GroupId { get; set; } - public List Sections { get; set; } = []; - public MessageGroupStatus Status { get; set; } = MessageGroupStatus.MessageGroupNone; - public long RefreshTime { get; set; } - public int CurrentSectionId { get; set; } - } - - public class MessageSectionData - { - public int SectionId { get; set; } - public MessageSectionStatus Status { get; set; } = MessageSectionStatus.MessageSectionNone; - public List Items { get; set; } = []; - public List ToChooseItemId { get; set; } = []; - } - - public class MessageItemData - { - public int ItemId { get; set; } - } + [SugarColumn(IsJson = true)] public Dictionary Groups { get; set; } = []; } + +public class MessageGroupData +{ + public int GroupId { get; set; } + public List Sections { get; set; } = []; + public MessageGroupStatus Status { get; set; } = MessageGroupStatus.MessageGroupNone; + public long RefreshTime { get; set; } + public int CurrentSectionId { get; set; } +} + +public class MessageSectionData +{ + public int SectionId { get; set; } + public MessageSectionStatus Status { get; set; } = MessageSectionStatus.MessageSectionNone; + public List Items { get; set; } = []; + public List ToChooseItemId { get; set; } = []; +} + +public class MessageItemData +{ + public int ItemId { get; set; } +} \ No newline at end of file diff --git a/Common/Database/Mission/MissionData.cs b/Common/Database/Mission/MissionData.cs index 27c24126..5e759bba 100644 --- a/Common/Database/Mission/MissionData.cs +++ b/Common/Database/Mission/MissionData.cs @@ -2,135 +2,108 @@ using EggLink.DanhengServer.Util; using SqlSugar; -namespace EggLink.DanhengServer.Database.Mission +namespace EggLink.DanhengServer.Database.Mission; + +[SugarTable("Mission")] +public class MissionData : BaseDatabaseDataHelper { - [SugarTable("Mission")] - public class MissionData : BaseDatabaseDataHelper + [SugarColumn(IsJson = true)] + public Dictionary> MissionInfo { get; set; } = + []; // Dictionary> // seems like main missionId is not used + + [SugarColumn(IsJson = true)] + public Dictionary MainMissionInfo { get; set; } = + []; // Dictionary + + [SugarColumn(IsJson = true, ColumnDataType = "text")] + public List FinishedSubMissionIds { get; set; } = []; + + [SugarColumn(IsJson = true, ColumnDataType = "text")] + public List RunningSubMissionIds { get; set; } = []; + + [SugarColumn(IsJson = true)] public List FinishedMainMissionIds { get; set; } = []; + + [SugarColumn(IsJson = true)] public List RunningMainMissionIds { get; set; } = []; + + [SugarColumn(IsJson = true)] public Dictionary SubMissionProgressDict { get; set; } = []; + + public int TrackingMainMissionId { get; set; } + + public MissionPhaseEnum GetMainMissionStatus(int missionId) { - [SugarColumn(IsJson = true)] - public Dictionary> MissionInfo { get; set; } = []; // Dictionary> // seems like main missionId is not used - [SugarColumn(IsJson = true)] - public Dictionary MainMissionInfo { get; set; } = []; // Dictionary + if (FinishedMainMissionIds.Contains(missionId)) return MissionPhaseEnum.Finish; + if (RunningMainMissionIds.Contains(missionId)) return MissionPhaseEnum.Accept; + return MissionPhaseEnum.None; + } - [SugarColumn(IsJson = true, ColumnDataType = "text")] - public List FinishedSubMissionIds { get; set; } = []; - [SugarColumn(IsJson = true, ColumnDataType = "text")] - public List RunningSubMissionIds { get; set; } = []; + public MissionPhaseEnum GetSubMissionStatus(int missionId) + { + if (FinishedSubMissionIds.Contains(missionId)) return MissionPhaseEnum.Finish; + if (RunningSubMissionIds.Contains(missionId)) return MissionPhaseEnum.Accept; + return MissionPhaseEnum.None; + } - [SugarColumn(IsJson = true)] - public List FinishedMainMissionIds { get; set; } = []; - [SugarColumn(IsJson = true)] - public List RunningMainMissionIds { get; set; } = []; - - [SugarColumn(IsJson = true)] - public Dictionary SubMissionProgressDict { get; set; } = []; - - public int TrackingMainMissionId { get; set; } - - public MissionPhaseEnum GetMainMissionStatus(int missionId) + public void SetMainMissionStatus(int missionId, MissionPhaseEnum phase) + { + if (phase == MissionPhaseEnum.Finish) { - if (FinishedMainMissionIds.Contains(missionId)) - { - return MissionPhaseEnum.Finish; - } - if (RunningMainMissionIds.Contains(missionId)) - { - return MissionPhaseEnum.Accept; - } - return MissionPhaseEnum.None; + FinishedMainMissionIds.SafeAdd(missionId); + RunningMainMissionIds.Remove(missionId); } - - public MissionPhaseEnum GetSubMissionStatus(int missionId) + else if (phase == MissionPhaseEnum.Accept) { - if (FinishedSubMissionIds.Contains(missionId)) - { - return MissionPhaseEnum.Finish; - } - if (RunningSubMissionIds.Contains(missionId)) - { - return MissionPhaseEnum.Accept; - } - return MissionPhaseEnum.None; + FinishedMainMissionIds.Remove(missionId); + RunningMainMissionIds.SafeAdd(missionId); } - - public void SetMainMissionStatus(int missionId, MissionPhaseEnum phase) + else { - if (phase == MissionPhaseEnum.Finish) - { - FinishedMainMissionIds.SafeAdd(missionId); - RunningMainMissionIds.Remove(missionId); - } - else if (phase == MissionPhaseEnum.Accept) - { - FinishedMainMissionIds.Remove(missionId); - RunningMainMissionIds.SafeAdd(missionId); - } - else - { - FinishedMainMissionIds.Remove(missionId); - RunningMainMissionIds.Remove(missionId); - } - } - - public void SetSubMissionStatus(int missionId, MissionPhaseEnum phase) - { - if (phase == MissionPhaseEnum.Finish) - { - FinishedSubMissionIds.SafeAdd(missionId); - RunningSubMissionIds.Remove(missionId); - } - else if (phase == MissionPhaseEnum.Accept) - { - FinishedSubMissionIds.Remove(missionId); - RunningSubMissionIds.SafeAdd(missionId); - } - else - { - FinishedSubMissionIds.Remove(missionId); - RunningSubMissionIds.Remove(missionId); - } - } - - public void MoveFromOld() - { - foreach (var main in MissionInfo) - { - foreach (var sub in main.Value) - { - if (sub.Value.Status == MissionPhaseEnum.Finish) - { - FinishedSubMissionIds.SafeAdd(sub.Key); - } - else if (sub.Value.Status == MissionPhaseEnum.Accept) - { - RunningSubMissionIds.SafeAdd(sub.Key); - } - } - } - - MissionInfo.Clear(); - - foreach (var main in MainMissionInfo) - { - if (main.Value == MissionPhaseEnum.Finish) - { - FinishedMainMissionIds.SafeAdd(main.Key); - } - else if (main.Value == MissionPhaseEnum.Accept) - { - RunningMainMissionIds.SafeAdd(main.Key); - } - } - - MainMissionInfo.Clear(); - - DatabaseHelper.Instance!.UpdateInstance(this); + FinishedMainMissionIds.Remove(missionId); + RunningMainMissionIds.Remove(missionId); } } - public class MissionInfo + public void SetSubMissionStatus(int missionId, MissionPhaseEnum phase) { - public int MissionId { get; set; } - public MissionPhaseEnum Status { get; set; } + if (phase == MissionPhaseEnum.Finish) + { + FinishedSubMissionIds.SafeAdd(missionId); + RunningSubMissionIds.Remove(missionId); + } + else if (phase == MissionPhaseEnum.Accept) + { + FinishedSubMissionIds.Remove(missionId); + RunningSubMissionIds.SafeAdd(missionId); + } + else + { + FinishedSubMissionIds.Remove(missionId); + RunningSubMissionIds.Remove(missionId); + } + } + + public void MoveFromOld() + { + foreach (var main in MissionInfo) + foreach (var sub in main.Value) + if (sub.Value.Status == MissionPhaseEnum.Finish) + FinishedSubMissionIds.SafeAdd(sub.Key); + else if (sub.Value.Status == MissionPhaseEnum.Accept) RunningSubMissionIds.SafeAdd(sub.Key); + + MissionInfo.Clear(); + + foreach (var main in MainMissionInfo) + if (main.Value == MissionPhaseEnum.Finish) + FinishedMainMissionIds.SafeAdd(main.Key); + else if (main.Value == MissionPhaseEnum.Accept) RunningMainMissionIds.SafeAdd(main.Key); + + MainMissionInfo.Clear(); + + DatabaseHelper.Instance!.UpdateInstance(this); } } + +public class MissionInfo +{ + public int MissionId { get; set; } + public MissionPhaseEnum Status { get; set; } +} \ No newline at end of file diff --git a/Common/Database/Mission/StoryLineData.cs b/Common/Database/Mission/StoryLineData.cs index 5f18e9fb..5e27df2f 100644 --- a/Common/Database/Mission/StoryLineData.cs +++ b/Common/Database/Mission/StoryLineData.cs @@ -1,43 +1,35 @@ using EggLink.DanhengServer.Database.Lineup; using EggLink.DanhengServer.Util; using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.Mission +namespace EggLink.DanhengServer.Database.Mission; + +[SugarTable("StoryLineData")] +public class StoryLineData : BaseDatabaseDataHelper { - [SugarTable("StoryLineData")] - public class StoryLineData : BaseDatabaseDataHelper - { - public int CurStoryLineId { get; set; } + public int CurStoryLineId { get; set; } - public int OldPlaneId { get; set; } - public int OldFloorId { get; set; } - public int OldEntryId { get; set; } + public int OldPlaneId { get; set; } + public int OldFloorId { get; set; } + public int OldEntryId { get; set; } - [SugarColumn(IsJson = true)] - public Position OldPos { get; set; } = new(); + [SugarColumn(IsJson = true)] public Position OldPos { get; set; } = new(); - [SugarColumn(IsJson = true)] - public Position OldRot { get; set; } = new(); + [SugarColumn(IsJson = true)] public Position OldRot { get; set; } = new(); - [SugarColumn(IsJson = true)] - public Dictionary RunningStoryLines { get; set; } = []; // finished one will be deleted - } - - public class StoryLineInfo - { - public int StoryLineId { get; set; } - - // Save Data - public int SavedPlaneId { get; set; } - public int SavedFloorId { get; set; } - public int SavedEntryId { get; set; } - public Position SavedPos { get; set; } = new(); - public Position SavedRot { get; set; } = new(); - public List Lineup { get; set; } = []; - } + [SugarColumn(IsJson = true)] + public Dictionary RunningStoryLines { get; set; } = []; // finished one will be deleted } + +public class StoryLineInfo +{ + public int StoryLineId { get; set; } + + // Save Data + public int SavedPlaneId { get; set; } + public int SavedFloorId { get; set; } + public int SavedEntryId { get; set; } + public Position SavedPos { get; set; } = new(); + public Position SavedRot { get; set; } = new(); + public List Lineup { get; set; } = []; +} \ No newline at end of file diff --git a/Common/Database/Player/PlayerData.cs b/Common/Database/Player/PlayerData.cs index f0b6e421..98bb2bfd 100644 --- a/Common/Database/Player/PlayerData.cs +++ b/Common/Database/Player/PlayerData.cs @@ -1,155 +1,151 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database.Account; using EggLink.DanhengServer.Database.Avatar; -using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; using SqlSugar; -namespace EggLink.DanhengServer.Database.Player +namespace EggLink.DanhengServer.Database.Player; + +[SugarTable("Player")] +public class PlayerData : BaseDatabaseDataHelper { - [SugarTable("Player")] - public class PlayerData : BaseDatabaseDataHelper + public string? Name { get; set; } = ""; + public string? Signature { get; set; } = ""; + public int Birthday { get; set; } = 0; + public int CurBasicType { get; set; } = 8001; + public int HeadIcon { get; set; } = 208001; + public int PhoneTheme { get; set; } = 221000; + public int ChatBubble { get; set; } = 220000; + public int CurrentBgm { get; set; } = 210007; + public Gender CurrentGender { get; set; } = Gender.Man; + public int Level { get; set; } = 1; + public int Exp { get; set; } = 0; + public int WorldLevel { get; set; } = 0; + public int Scoin { get; set; } = 0; // Credits + public int Hcoin { get; set; } = 0; // Jade + public int Mcoin { get; set; } = 0; // Crystals + public int TalentPoints { get; set; } = 0; // Rogue talent points + + public int Stamina { get; set; } = 240; + public double StaminaReserve { get; set; } = 0; + public long NextStaminaRecover { get; set; } = 0; + + [SugarColumn(IsNullable = true, IsJson = true)] + public Position? Pos { get; set; } + + [SugarColumn(IsNullable = true, IsJson = true)] + public Position? Rot { get; set; } + + [SugarColumn(IsNullable = true)] public int PlaneId { get; set; } + + [SugarColumn(IsNullable = true)] public int FloorId { get; set; } + + [SugarColumn(IsNullable = true)] public int EntryId { get; set; } + + [SugarColumn(IsNullable = true)] public long LastActiveTime { get; set; } + + public static PlayerData? GetPlayerByUid(long uid) { - public string? Name { get; set; } = ""; - public string? Signature { get; set; } = ""; - public int Birthday { get; set; } = 0; - public int CurBasicType { get; set; } = 8001; - public int HeadIcon { get; set; } = 208001; - public int PhoneTheme { get; set; } = 221000; - public int ChatBubble { get; set; } = 220000; - public int CurrentBgm { get; set; } = 210007; - public Gender CurrentGender { get; set; } = Gender.Man; - public int Level { get; set; } = 1; - public int Exp { get; set; } = 0; - public int WorldLevel { get; set; } = 0; - public int Scoin { get; set; } = 0; // Credits - public int Hcoin { get; set; } = 0; // Jade - public int Mcoin { get; set; } = 0; // Crystals - public int TalentPoints { get; set; } = 0; // Rogue talent points + var result = DatabaseHelper.Instance?.GetInstance((int)uid); + return result; + } - public int Stamina { get; set; } = 240; - public double StaminaReserve { get; set; } = 0; - public long NextStaminaRecover { get; set; } = 0; - - [SugarColumn(IsNullable = true, IsJson = true)] - public Position? Pos { get; set; } - [SugarColumn(IsNullable = true, IsJson = true)] - public Position? Rot { get; set; } - [SugarColumn(IsNullable = true)] - public int PlaneId { get; set; } - [SugarColumn(IsNullable = true)] - public int FloorId { get; set; } - [SugarColumn(IsNullable = true)] - public int EntryId { get; set; } - - [SugarColumn(IsNullable = true)] - public long LastActiveTime { get; set; } - - public static PlayerData? GetPlayerByUid(long uid) + public PlayerBasicInfo ToProto() + { + return new PlayerBasicInfo { - PlayerData? result = DatabaseHelper.Instance?.GetInstance((int)uid); - return result; + Nickname = Name, + Level = (uint)Level, + Exp = (uint)Exp, + WorldLevel = (uint)WorldLevel, + Scoin = (uint)Scoin, + Hcoin = (uint)Hcoin, + Mcoin = (uint)Mcoin, + Stamina = (uint)Stamina + }; + } + + public PlayerSimpleInfo ToSimpleProto(FriendOnlineStatus status) + { + if (!GameData.ChatBubbleConfigData.ContainsKey(ChatBubble)) // to avoid npe + ChatBubble = 220000; + + var AvatarInfo = DatabaseHelper.Instance!.GetInstance(Uid)!; + + foreach (var avatar in AvatarInfo.Avatars) + { + avatar.PlayerData = this; + avatar.Excel = GameData.AvatarConfigData[avatar.AvatarId]; } - public PlayerBasicInfo ToProto() + var info = new PlayerSimpleInfo { - return new() + Nickname = Name, + Level = (uint)Level, + Signature = Signature, + Uid = (uint)Uid, + OnlineStatus = status, + HeadIcon = (uint)HeadIcon, + Platform = PlatformType.Pc, + LastActiveTime = LastActiveTime, + ChatBubbleId = (uint)ChatBubble + }; + + var pos = 0; + foreach (var assist in AvatarInfo.AssistAvatars) + { + var avatar = AvatarInfo.Avatars.Find(x => x.AvatarId == assist)!; + info.AssistSimpleList.Add(new AssistSimpleInfo { - Nickname = Name, - Level = (uint)Level, - Exp = (uint)Exp, - WorldLevel = (uint)WorldLevel, - Scoin = (uint)Scoin, - Hcoin = (uint)Hcoin, - Mcoin = (uint)Mcoin, - Stamina = (uint)Stamina, - }; + AvatarId = (uint)avatar.AvatarId, + Level = (uint)avatar.Level, + Pos = (uint)pos++ + }); } - public PlayerSimpleInfo ToSimpleProto(FriendOnlineStatus status) + return info; + } + + public PlayerDetailInfo ToDetailProto() + { + var info = new PlayerDetailInfo { - if (!GameData.ChatBubbleConfigData.ContainsKey(ChatBubble)) // to avoid npe - { - ChatBubble = 220000; - } + Nickname = Name, + Level = (uint)Level, + Signature = Signature, + IsBanned = false, + HeadIcon = (uint)HeadIcon, + Platform = PlatformType.Pc, + Uid = (uint)Uid, + WorldLevel = (uint)WorldLevel, + RecordInfo = new DisplayRecordInfo() + }; - var AvatarInfo = DatabaseHelper.Instance!.GetInstance(Uid)!; + var AvatarInfo = DatabaseHelper.Instance!.GetInstance(Uid); + if (AvatarInfo != null) + { foreach (var avatar in AvatarInfo.Avatars) { avatar.PlayerData = this; avatar.Excel = GameData.AvatarConfigData[avatar.AvatarId]; } - var info = new PlayerSimpleInfo() - { - Nickname = Name, - Level = (uint)Level, - Signature = Signature, - Uid = (uint)Uid, - OnlineStatus = status, - HeadIcon = (uint)HeadIcon, - Platform = PlatformType.Pc, - LastActiveTime = LastActiveTime, - ChatBubbleId = (uint)ChatBubble - }; - var pos = 0; foreach (var assist in AvatarInfo.AssistAvatars) { var avatar = AvatarInfo.Avatars.Find(x => x.AvatarId == assist)!; - info.AssistSimpleList.Add(new AssistSimpleInfo() - { - AvatarId = (uint)avatar.AvatarId, - Level = (uint)avatar.Level, - Pos = (uint)pos++ - }); + info.AssistAvatarList.Add(avatar.ToDetailProto(pos++)); } - return info; - } - - public PlayerDetailInfo ToDetailProto() - { - var info = new PlayerDetailInfo() + pos = 0; + foreach (var display in AvatarInfo.DisplayAvatars) { - Nickname = Name, - Level = (uint)Level, - Signature = Signature, - IsBanned = false, - HeadIcon = (uint)HeadIcon, - Platform = PlatformType.Pc, - Uid = (uint)Uid, - WorldLevel = (uint)WorldLevel, - RecordInfo = new(), - }; - - var AvatarInfo = DatabaseHelper.Instance!.GetInstance(Uid); - - if (AvatarInfo != null) - { - foreach (var avatar in AvatarInfo.Avatars) - { - avatar.PlayerData = this; - avatar.Excel = GameData.AvatarConfigData[avatar.AvatarId]; - } - var pos = 0; - foreach (var assist in AvatarInfo.AssistAvatars) - { - var avatar = AvatarInfo.Avatars.Find(x => x.AvatarId == assist)!; - info.AssistAvatarList.Add(avatar.ToDetailProto(pos++)); - } - - pos = 0; - foreach (var display in AvatarInfo.DisplayAvatars) - { - var avatar = AvatarInfo.Avatars.Find(x => x.AvatarId == display)!; - info.DisplayAvatarList.Add(avatar.ToDetailProto(pos++)); - } + var avatar = AvatarInfo.Avatars.Find(x => x.AvatarId == display)!; + info.DisplayAvatarList.Add(avatar.ToDetailProto(pos++)); } - - return info; } + + return info; } -} +} \ No newline at end of file diff --git a/Common/Database/Player/PlayerUnlockData.cs b/Common/Database/Player/PlayerUnlockData.cs index dbe26026..cb734497 100644 --- a/Common/Database/Player/PlayerUnlockData.cs +++ b/Common/Database/Player/PlayerUnlockData.cs @@ -1,15 +1,13 @@ using SqlSugar; -namespace EggLink.DanhengServer.Database.Player +namespace EggLink.DanhengServer.Database.Player; + +[SugarTable("UnlockData")] +public class PlayerUnlockData : BaseDatabaseDataHelper { - [SugarTable("UnlockData")] - public class PlayerUnlockData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public List HeadIcons { get; set; } = []; - [SugarColumn(IsJson = true)] - public List ChatBubbles { get; set; } = []; - [SugarColumn(IsJson = true)] - public List PhoneThemes { get; set; } = []; - } -} + [SugarColumn(IsJson = true)] public List HeadIcons { get; set; } = []; + + [SugarColumn(IsJson = true)] public List ChatBubbles { get; set; } = []; + + [SugarColumn(IsJson = true)] public List PhoneThemes { get; set; } = []; +} \ No newline at end of file diff --git a/Common/Database/Scene/HeartDialData.cs b/Common/Database/Scene/HeartDialData.cs index cfd7c153..b059f057 100644 --- a/Common/Database/Scene/HeartDialData.cs +++ b/Common/Database/Scene/HeartDialData.cs @@ -1,69 +1,62 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Enums.Mission; using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.Scene +namespace EggLink.DanhengServer.Database.Scene; + +[SugarTable("HeartDial")] +public class HeartDialData : BaseDatabaseDataHelper { - [SugarTable("HeartDial")] - public class HeartDialData : BaseDatabaseDataHelper + [SugarColumn(IsJson = true)] public Dictionary DialList { get; set; } = []; + + public HeartDialInfo ChangeScriptEmotion(int scriptId, HeartDialEmoTypeEnum emoType, HeartDialStepTypeEnum stepType) { - [SugarColumn(IsJson = true)] - public Dictionary DialList { get; set; } = []; - - public HeartDialInfo ChangeScriptEmotion(int scriptId, HeartDialEmoTypeEnum emoType, HeartDialStepTypeEnum stepType) + if (DialList.TryGetValue(scriptId, out var dialInfo)) { - if (DialList.TryGetValue(scriptId, out var dialInfo)) + dialInfo.EmoType = emoType; + dialInfo.StepType = stepType; + } + else + { + DialList.Add(scriptId, new HeartDialInfo { - dialInfo.EmoType = emoType; - dialInfo.StepType = stepType; - } - else - { - DialList.Add(scriptId, new HeartDialInfo - { - ScriptId = scriptId, - EmoType = emoType, - StepType = stepType - }); + ScriptId = scriptId, + EmoType = emoType, + StepType = stepType + }); - dialInfo = DialList[scriptId]; - } - - return dialInfo; + dialInfo = DialList[scriptId]; } - public HeartDialInfo ChangeScriptEmotion(int scriptId, HeartDialEmoTypeEnum emoType) - { - if (DialList.TryGetValue(scriptId, out var dialInfo)) - { - dialInfo.EmoType = emoType; - } - else - { - GameData.HeartDialScriptData.TryGetValue(scriptId, out var scriptData); - DialList.Add(scriptId, new HeartDialInfo - { - ScriptId = scriptId, - EmoType = emoType, - StepType = scriptData?.StepList[0] ?? HeartDialStepTypeEnum.Normal - }); - - dialInfo = DialList[scriptId]; - } - - return dialInfo; - } + return dialInfo; } - public class HeartDialInfo + public HeartDialInfo ChangeScriptEmotion(int scriptId, HeartDialEmoTypeEnum emoType) { - public int ScriptId { get; set; } - public HeartDialEmoTypeEnum EmoType { get; set; } = HeartDialEmoTypeEnum.Peace; - public HeartDialStepTypeEnum StepType { get; set; } = HeartDialStepTypeEnum.Normal; + if (DialList.TryGetValue(scriptId, out var dialInfo)) + { + dialInfo.EmoType = emoType; + } + else + { + GameData.HeartDialScriptData.TryGetValue(scriptId, out var scriptData); + DialList.Add(scriptId, new HeartDialInfo + { + ScriptId = scriptId, + EmoType = emoType, + StepType = scriptData?.StepList[0] ?? HeartDialStepTypeEnum.Normal + }); + + dialInfo = DialList[scriptId]; + } + + return dialInfo; } } + +public class HeartDialInfo +{ + public int ScriptId { get; set; } + public HeartDialEmoTypeEnum EmoType { get; set; } = HeartDialEmoTypeEnum.Peace; + public HeartDialStepTypeEnum StepType { get; set; } = HeartDialStepTypeEnum.Normal; +} \ No newline at end of file diff --git a/Common/Database/Scene/RaidData.cs b/Common/Database/Scene/RaidData.cs index e4d95764..b09d5696 100644 --- a/Common/Database/Scene/RaidData.cs +++ b/Common/Database/Scene/RaidData.cs @@ -2,55 +2,48 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.Scene +namespace EggLink.DanhengServer.Database.Scene; + +[SugarTable("RaidData")] +public class RaidData : BaseDatabaseDataHelper { - [SugarTable("RaidData")] - public class RaidData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public Dictionary> RaidRecordDatas { get; set; } = []; + [SugarColumn(IsJson = true)] public Dictionary> RaidRecordDatas { get; set; } = []; - [SugarColumn(IsJson = true)] - [Obsolete("Using RaidRecordDatas")] - public Dictionary RaidRecordData { get; set; } = []; + [SugarColumn(IsJson = true)] + [Obsolete("Using RaidRecordDatas")] + public Dictionary RaidRecordData { get; set; } = []; - //[SugarColumn(IsJson = true, IsNullable = true)] - //public Position? OldPos { get; set; } + //[SugarColumn(IsJson = true, IsNullable = true)] + //public Position? OldPos { get; set; } - //[SugarColumn(IsJson = true, IsNullable = true)] - //public Position? OldRot { get; set; } + //[SugarColumn(IsJson = true, IsNullable = true)] + //public Position? OldRot { get; set; } - //public int OldEntryId { get; set; } - public int CurRaidId { get; set; } - public int CurRaidWorldLevel { get; set; } - } - - public class RaidRecord - { - // Basic Info - public int RaidId { get; set; } - public int WorldLevel { get; set; } - public RaidStatus Status { get; set; } - public long FinishTimeStamp { get; set; } - - // Lineup Info - public List Lineup { get; set; } = []; - - // Scene Info - public Position Pos { get; set; } = new(); - public Position Rot { get; set; } = new(); - public int PlaneId { get; set; } - public int FloorId { get; set; } - public int EntryId { get; set; } - - public Position OldPos { get; set; } = new(); - public Position OldRot { get; set; } = new(); - public int OldEntryId { get; set; } - } + //public int OldEntryId { get; set; } + public int CurRaidId { get; set; } + public int CurRaidWorldLevel { get; set; } } + +public class RaidRecord +{ + // Basic Info + public int RaidId { get; set; } + public int WorldLevel { get; set; } + public RaidStatus Status { get; set; } + public long FinishTimeStamp { get; set; } + + // Lineup Info + public List Lineup { get; set; } = []; + + // Scene Info + public Position Pos { get; set; } = new(); + public Position Rot { get; set; } = new(); + public int PlaneId { get; set; } + public int FloorId { get; set; } + public int EntryId { get; set; } + + public Position OldPos { get; set; } = new(); + public Position OldRot { get; set; } = new(); + public int OldEntryId { get; set; } +} \ No newline at end of file diff --git a/Common/Database/Scene/SceneData.cs b/Common/Database/Scene/SceneData.cs index 88364f5e..7524abd6 100644 --- a/Common/Database/Scene/SceneData.cs +++ b/Common/Database/Scene/SceneData.cs @@ -1,27 +1,29 @@ using EggLink.DanhengServer.Enums.Scene; using SqlSugar; -namespace EggLink.DanhengServer.Database.Scene +namespace EggLink.DanhengServer.Database.Scene; + +[SugarTable("Scene")] +public class SceneData : BaseDatabaseDataHelper { - [SugarTable("Scene")] - public class SceneData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public Dictionary>> ScenePropData { get; set; } = []; // Dictionary> - - [SugarColumn(IsJson = true)] - public Dictionary> UnlockSectionIdList { get; set; } = []; // Dictionary> + [SugarColumn(IsJson = true)] + public Dictionary>> ScenePropData { get; set; } = + []; // Dictionary> - [SugarColumn(IsJson = true)] - public Dictionary> CustomSaveData { get; set; } = []; // Dictionary> + [SugarColumn(IsJson = true)] + public Dictionary> UnlockSectionIdList { get; set; } = []; // Dictionary> - [SugarColumn(IsJson = true)] - public Dictionary> FloorSavedData { get; set; } = []; // Dictionary> - } + [SugarColumn(IsJson = true)] + public Dictionary> CustomSaveData { get; set; } = + []; // Dictionary> - public class ScenePropData - { - public int PropId; - public PropStateEnum State; - } + [SugarColumn(IsJson = true)] + public Dictionary> FloorSavedData { get; set; } = + []; // Dictionary> } + +public class ScenePropData +{ + public int PropId; + public PropStateEnum State; +} \ No newline at end of file diff --git a/Common/Database/Tutorial/TutorialData.cs b/Common/Database/Tutorial/TutorialData.cs index 12163164..68129460 100644 --- a/Common/Database/Tutorial/TutorialData.cs +++ b/Common/Database/Tutorial/TutorialData.cs @@ -1,12 +1,10 @@ using EggLink.DanhengServer.Proto; using SqlSugar; -namespace EggLink.DanhengServer.Database.Tutorial +namespace EggLink.DanhengServer.Database.Tutorial; + +[SugarTable("Tutorial")] +public class TutorialData : BaseDatabaseDataHelper { - [SugarTable("Tutorial")] - public class TutorialData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public Dictionary Tutorials { get; set; } = []; - } -} + [SugarColumn(IsJson = true)] public Dictionary Tutorials { get; set; } = []; +} \ No newline at end of file diff --git a/Common/Database/Tutorial/TutorialGuideData.cs b/Common/Database/Tutorial/TutorialGuideData.cs index b4059142..1712ddf1 100644 --- a/Common/Database/Tutorial/TutorialGuideData.cs +++ b/Common/Database/Tutorial/TutorialGuideData.cs @@ -1,17 +1,10 @@ using EggLink.DanhengServer.Proto; using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Database.Tutorial +namespace EggLink.DanhengServer.Database.Tutorial; + +[SugarTable("TutorialGuide")] +public class TutorialGuideData : BaseDatabaseDataHelper { - [SugarTable("TutorialGuide")] - public class TutorialGuideData : BaseDatabaseDataHelper - { - [SugarColumn(IsJson = true)] - public Dictionary Tutorials { get; set; } = []; - } -} + [SugarColumn(IsJson = true)] public Dictionary Tutorials { get; set; } = []; +} \ No newline at end of file diff --git a/Common/Enums/Avatar/DamageTypeEnum.cs b/Common/Enums/Avatar/DamageTypeEnum.cs index 2c046fe5..0ef2bcf6 100644 --- a/Common/Enums/Avatar/DamageTypeEnum.cs +++ b/Common/Enums/Avatar/DamageTypeEnum.cs @@ -1,19 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Avatar; -namespace EggLink.DanhengServer.Enums.Avatar +public enum DamageTypeEnum { - public enum DamageTypeEnum - { - Physical = 1000111, - Fire = 1000112, - Ice = 1000113, - Thunder = 1000114, - Wind = 1000115, - Quantum = 1000116, - Imaginary = 1000117 - } -} + Physical = 1000111, + Fire = 1000112, + Ice = 1000113, + Thunder = 1000114, + Wind = 1000115, + Quantum = 1000116, + Imaginary = 1000117 +} \ No newline at end of file diff --git a/Common/Enums/Avatar/HeroBasicTypeEnum.cs b/Common/Enums/Avatar/HeroBasicTypeEnum.cs index c8ea5fed..b8f487f2 100644 --- a/Common/Enums/Avatar/HeroBasicTypeEnum.cs +++ b/Common/Enums/Avatar/HeroBasicTypeEnum.cs @@ -1,15 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Avatar; -namespace EggLink.DanhengServer.Enums.Avatar +public enum HeroBasicTypeEnum { - public enum HeroBasicTypeEnum - { - Warrior = 8001, - Knight = 8003, - Shaman = 8005 - } -} + Warrior = 8001, + Knight = 8003, + Shaman = 8005 +} \ No newline at end of file diff --git a/Common/Enums/Avatar/RelicTypeEnum.cs b/Common/Enums/Avatar/RelicTypeEnum.cs index 8ffb5f95..6f12c8b2 100644 --- a/Common/Enums/Avatar/RelicTypeEnum.cs +++ b/Common/Enums/Avatar/RelicTypeEnum.cs @@ -1,13 +1,12 @@ -namespace EggLink.DanhengServer.Enums.Avatar +namespace EggLink.DanhengServer.Enums.Avatar; + +public enum RelicTypeEnum { - public enum RelicTypeEnum - { - Unknow = 0, - HEAD = 1, - HAND = 2, - BODY = 3, - FOOT = 4, - NECK = 5, - OBJECT = 6 - } -} + Unknow = 0, + HEAD = 1, + HAND = 2, + BODY = 3, + FOOT = 4, + NECK = 5, + OBJECT = 6 +} \ No newline at end of file diff --git a/Common/Enums/Avatar/SpecialAvatarTypeEnum.cs b/Common/Enums/Avatar/SpecialAvatarTypeEnum.cs index 4ede68fd..3f2e5fa9 100644 --- a/Common/Enums/Avatar/SpecialAvatarTypeEnum.cs +++ b/Common/Enums/Avatar/SpecialAvatarTypeEnum.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Avatar; -namespace EggLink.DanhengServer.Enums.Avatar +public enum SpecialAvatarTypeEnum { - public enum SpecialAvatarTypeEnum - { - TYPE_TRIAL = 1, - TYPE_PLOT = 2, // mission - } -} + TYPE_TRIAL = 1, + TYPE_PLOT = 2 // mission +} \ No newline at end of file diff --git a/Common/Enums/Avatar/TaskTypeEnum.cs b/Common/Enums/Avatar/TaskTypeEnum.cs index d836099f..138e96db 100644 --- a/Common/Enums/Avatar/TaskTypeEnum.cs +++ b/Common/Enums/Avatar/TaskTypeEnum.cs @@ -1,22 +1,15 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Avatar; -namespace EggLink.DanhengServer.Enums.Avatar +public enum TaskTypeEnum { - public enum TaskTypeEnum - { - None = 0, - AddMazeBuff = 1, - RemoveMazeBuff = 2, - AdventureModifyTeamPlayerHP = 3, - AdventureModifyTeamPlayerSP = 4, - CreateSummonUnit = 5, - AdventureSetAttackTargetMonsterDie = 6, - SuccessTaskList = 7, - AdventureTriggerAttack = 8, - AdventureFireProjectile = 9, - } -} + None = 0, + AddMazeBuff = 1, + RemoveMazeBuff = 2, + AdventureModifyTeamPlayerHP = 3, + AdventureModifyTeamPlayerSP = 4, + CreateSummonUnit = 5, + AdventureSetAttackTargetMonsterDie = 6, + SuccessTaskList = 7, + AdventureTriggerAttack = 8, + AdventureFireProjectile = 9 +} \ No newline at end of file diff --git a/Common/Enums/GachaTypeEnum.cs b/Common/Enums/GachaTypeEnum.cs index b6dbb850..fc6d4b8c 100644 --- a/Common/Enums/GachaTypeEnum.cs +++ b/Common/Enums/GachaTypeEnum.cs @@ -1,30 +1,23 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums; -namespace EggLink.DanhengServer.Enums +public enum GachaTypeEnum { - public enum GachaTypeEnum - { - Unknown = 0, - Newbie = 1, - Normal = 2, - AvatarUp = 11, - WeaponUp = 12, - } - - public static class GachaTypeEnumExtensions - { - public static int GetCostItemId(this GachaTypeEnum type) - { - return type switch - { - GachaTypeEnum.Newbie or GachaTypeEnum.Normal => 101, - GachaTypeEnum.AvatarUp or GachaTypeEnum.WeaponUp => 102, - _ => 0, - }; - } - } + Unknown = 0, + Newbie = 1, + Normal = 2, + AvatarUp = 11, + WeaponUp = 12 } + +public static class GachaTypeEnumExtensions +{ + public static int GetCostItemId(this GachaTypeEnum type) + { + return type switch + { + GachaTypeEnum.Newbie or GachaTypeEnum.Normal => 101, + GachaTypeEnum.AvatarUp or GachaTypeEnum.WeaponUp => 102, + _ => 0 + }; + } +} \ No newline at end of file diff --git a/Common/Enums/Item/FarmTypeEnum.cs b/Common/Enums/Item/FarmTypeEnum.cs index 4238ecf2..bc699897 100644 --- a/Common/Enums/Item/FarmTypeEnum.cs +++ b/Common/Enums/Item/FarmTypeEnum.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Item; -namespace EggLink.DanhengServer.Enums.Item +public enum FarmTypeEnum { - public enum FarmTypeEnum - { - COCOON = 1, - None = COCOON, - RELIC = 4, - COCOON2 = 3, - ELEMENT = COCOON2, - } -} + COCOON = 1, + None = COCOON, + RELIC = 4, + COCOON2 = 3, + ELEMENT = COCOON2 +} \ No newline at end of file diff --git a/Common/Enums/Item/ItemMainTypeEnum.cs b/Common/Enums/Item/ItemMainTypeEnum.cs index 2570810a..329ebd7c 100644 --- a/Common/Enums/Item/ItemMainTypeEnum.cs +++ b/Common/Enums/Item/ItemMainTypeEnum.cs @@ -1,15 +1,14 @@ -namespace EggLink.DanhengServer.Enums.Item +namespace EggLink.DanhengServer.Enums.Item; + +public enum ItemMainTypeEnum { - public enum ItemMainTypeEnum - { - Unknown = 0, - Virtual = 1, - AvatarCard = 2, - Equipment = 3, - Relic = 4, - Usable = 5, - Material = 6, - Mission = 7, - Display = 8 - } -} + Unknown = 0, + Virtual = 1, + AvatarCard = 2, + Equipment = 3, + Relic = 4, + Usable = 5, + Material = 6, + Mission = 7, + Display = 8 +} \ No newline at end of file diff --git a/Common/Enums/Item/ItemRarityEnum.cs b/Common/Enums/Item/ItemRarityEnum.cs index 82710a62..4dd5e21a 100644 --- a/Common/Enums/Item/ItemRarityEnum.cs +++ b/Common/Enums/Item/ItemRarityEnum.cs @@ -1,12 +1,11 @@ -namespace EggLink.DanhengServer.Enums.Item +namespace EggLink.DanhengServer.Enums.Item; + +public enum ItemRarityEnum { - public enum ItemRarityEnum - { - Unknown = 0, - Normal = 1, - NotNormal = 2, - Rare = 3, - VeryRare = 4, - SuperRare = 5 - } -} + Unknown = 0, + Normal = 1, + NotNormal = 2, + Rare = 3, + VeryRare = 4, + SuperRare = 5 +} \ No newline at end of file diff --git a/Common/Enums/Item/ItemSubTypeEnum.cs b/Common/Enums/Item/ItemSubTypeEnum.cs index 2e7f0eb9..9523d802 100644 --- a/Common/Enums/Item/ItemSubTypeEnum.cs +++ b/Common/Enums/Item/ItemSubTypeEnum.cs @@ -1,34 +1,33 @@ -namespace EggLink.DanhengServer.Enums.Item +namespace EggLink.DanhengServer.Enums.Item; + +public enum ItemSubTypeEnum { - public enum ItemSubTypeEnum - { - Unknown = 0, - Virtual = 101, - GameplayCounter = 102, - AvatarCard = 201, - Equipment = 301, - Relic = 401, - Gift = 501, - Food = 502, - ForceOpitonalGift = 503, - Book = 504, - HeadIcon = 505, - MusicAlbum = 506, - Formula = 507, - ChatBubble = 508, - AvatarSkin = 509, - PhoneTheme = 510, - TravelBrochurePaster = 511, - ChessRogueDiceSurface = 512, - RogueMedal = 513, - Material = 601, - Eidolon = 602, - MuseumExhibit = 603, - MuseumStuff = 604, - AetherSkill = 605, - AetherSpirit = 606, - Mission = 701, - RelicSetShowOnly = 801, - RelicRarityShowOnly = 802, - } -} + Unknown = 0, + Virtual = 101, + GameplayCounter = 102, + AvatarCard = 201, + Equipment = 301, + Relic = 401, + Gift = 501, + Food = 502, + ForceOpitonalGift = 503, + Book = 504, + HeadIcon = 505, + MusicAlbum = 506, + Formula = 507, + ChatBubble = 508, + AvatarSkin = 509, + PhoneTheme = 510, + TravelBrochurePaster = 511, + ChessRogueDiceSurface = 512, + RogueMedal = 513, + Material = 601, + Eidolon = 602, + MuseumExhibit = 603, + MuseumStuff = 604, + AetherSkill = 605, + AetherSpirit = 606, + Mission = 701, + RelicSetShowOnly = 801, + RelicRarityShowOnly = 802 +} \ No newline at end of file diff --git a/Common/Enums/Item/ItemUseMethodEnum.cs b/Common/Enums/Item/ItemUseMethodEnum.cs index b15ccbed..1ef4c033 100644 --- a/Common/Enums/Item/ItemUseMethodEnum.cs +++ b/Common/Enums/Item/ItemUseMethodEnum.cs @@ -1,24 +1,23 @@ -namespace EggLink.DanhengServer.Enums.Item +namespace EggLink.DanhengServer.Enums.Item; + +public enum ItemUseMethodEnum { - public enum ItemUseMethodEnum - { - Unknown = 0, - FixedRewardGift = 101, - RandomRewardGift = 102, - PlayerSelectedReward = 103, - TeamFoodBenefit = 201, - TeamSpecificFoodBenefit = 202, - ExternalSystemFoodBenefit = 203, - PlayerSelectedDropGift = 301, - TreasureMap = 401, - Recipe = 501, - PerformanceProp = 601, - MonthlyCard = 701, - BPUnlock68 = 702, - BPUnlock128 = 703, - BPUpgradeFrom68To128 = 704, - AutoConversionItem = 801, - TravelBrochureUse = 901, - TravelBrochurePasterUse = 902, - } -} + Unknown = 0, + FixedRewardGift = 101, + RandomRewardGift = 102, + PlayerSelectedReward = 103, + TeamFoodBenefit = 201, + TeamSpecificFoodBenefit = 202, + ExternalSystemFoodBenefit = 203, + PlayerSelectedDropGift = 301, + TreasureMap = 401, + Recipe = 501, + PerformanceProp = 601, + MonthlyCard = 701, + BPUnlock68 = 702, + BPUnlock128 = 703, + BPUpgradeFrom68To128 = 704, + AutoConversionItem = 801, + TravelBrochureUse = 901, + TravelBrochurePasterUse = 902 +} \ No newline at end of file diff --git a/Common/Enums/Item/RarityEnum.cs b/Common/Enums/Item/RarityEnum.cs index 71345086..5ba2abbf 100644 --- a/Common/Enums/Item/RarityEnum.cs +++ b/Common/Enums/Item/RarityEnum.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Item; -namespace EggLink.DanhengServer.Enums.Item +public enum RarityEnum { - public enum RarityEnum - { - CombatPowerAvatarRarityType4 = 1, - CombatPowerAvatarRarityType5 = 2, - CombatPowerLightconeRarity3 = 3, - CombatPowerLightconeRarity4 = 4, - CombatPowerLightconeRarity5 = 5, - } -} + CombatPowerAvatarRarityType4 = 1, + CombatPowerAvatarRarityType5 = 2, + CombatPowerLightconeRarity3 = 3, + CombatPowerLightconeRarity4 = 4, + CombatPowerLightconeRarity5 = 5 +} \ No newline at end of file diff --git a/Common/Enums/Mission/ConditionTypeEnum.cs b/Common/Enums/Mission/ConditionTypeEnum.cs index 1ab185d5..2448abbe 100644 --- a/Common/Enums/Mission/ConditionTypeEnum.cs +++ b/Common/Enums/Mission/ConditionTypeEnum.cs @@ -1,8 +1,7 @@ -namespace EggLink.DanhengServer.Enums +namespace EggLink.DanhengServer.Enums; + +public enum ConditionTypeEnum { - public enum ConditionTypeEnum - { - MainMission = 0, - SubMission = 1, - } -} + MainMission = 0, + SubMission = 1 +} \ No newline at end of file diff --git a/Common/Enums/Mission/FinishActionTypeEnum.cs b/Common/Enums/Mission/FinishActionTypeEnum.cs index 55824e75..c9e9964c 100644 --- a/Common/Enums/Mission/FinishActionTypeEnum.cs +++ b/Common/Enums/Mission/FinishActionTypeEnum.cs @@ -1,32 +1,31 @@ -namespace EggLink.DanhengServer.Enums +namespace EggLink.DanhengServer.Enums; + +public enum FinishActionTypeEnum { - public enum FinishActionTypeEnum - { - None = 0, - Recover = 1, - ChangeLineup = 2, - addHeroItem = 3, - addMissionItem = 4, - delMissionItem = 5, - addRecoverMissionItem = 6, - delMission = 7, - ActivateGameplayCounter = 8, - DeactivateGameplayCounter = 9, - delSubMission = 10, - RandomCustomValue = 11, - CompensateMissionItem = 12, - RecycleMissionItem = 13, - DisableMission = 14, - SetFloorSavedValue = 15, - SetGroupState = 16, - EnterEntryIfNotThere = 17, - SetCustomValue = 18, - AddCustomValue = 19, - ChangeStoryLine = 20, - MoveToAnchor = 21, - ActivateAnchor = 22, - TeleportRotatableRegion = 23, - ChangeHeroBasicTypeAndSetLeader = 24, - UpdateFloorSavedValue = 25, - } -} + None = 0, + Recover = 1, + ChangeLineup = 2, + addHeroItem = 3, + addMissionItem = 4, + delMissionItem = 5, + addRecoverMissionItem = 6, + delMission = 7, + ActivateGameplayCounter = 8, + DeactivateGameplayCounter = 9, + delSubMission = 10, + RandomCustomValue = 11, + CompensateMissionItem = 12, + RecycleMissionItem = 13, + DisableMission = 14, + SetFloorSavedValue = 15, + SetGroupState = 16, + EnterEntryIfNotThere = 17, + SetCustomValue = 18, + AddCustomValue = 19, + ChangeStoryLine = 20, + MoveToAnchor = 21, + ActivateAnchor = 22, + TeleportRotatableRegion = 23, + ChangeHeroBasicTypeAndSetLeader = 24, + UpdateFloorSavedValue = 25 +} \ No newline at end of file diff --git a/Common/Enums/Mission/HeartDialEmoTypeEnum.cs b/Common/Enums/Mission/HeartDialEmoTypeEnum.cs index 0dbb9bdf..7437becc 100644 --- a/Common/Enums/Mission/HeartDialEmoTypeEnum.cs +++ b/Common/Enums/Mission/HeartDialEmoTypeEnum.cs @@ -1,11 +1,10 @@ -namespace EggLink.DanhengServer.Enums.Mission +namespace EggLink.DanhengServer.Enums.Mission; + +public enum HeartDialEmoTypeEnum { - public enum HeartDialEmoTypeEnum - { - Peace = 0, - Anger = 1, - Happy = 2, - Sad = 3, - Count = 4, - } -} + Peace = 0, + Anger = 1, + Happy = 2, + Sad = 3, + Count = 4 +} \ No newline at end of file diff --git a/Common/Enums/Mission/HeartDialStepTypeEnum.cs b/Common/Enums/Mission/HeartDialStepTypeEnum.cs index ee37d0dd..edb16c1f 100644 --- a/Common/Enums/Mission/HeartDialStepTypeEnum.cs +++ b/Common/Enums/Mission/HeartDialStepTypeEnum.cs @@ -1,12 +1,11 @@ -namespace EggLink.DanhengServer.Enums.Mission +namespace EggLink.DanhengServer.Enums.Mission; + +public enum HeartDialStepTypeEnum { - public enum HeartDialStepTypeEnum - { - Missing = 0, - Full = 1, - Lock = 2, - UnLock = 3, - Normal = 4, - Control = 5, - } -} + Missing = 0, + Full = 1, + Lock = 2, + UnLock = 3, + Normal = 4, + Control = 5 +} \ No newline at end of file diff --git a/Common/Enums/Mission/MissionFinishTypeEnum.cs b/Common/Enums/Mission/MissionFinishTypeEnum.cs index 7d72c689..a341b334 100644 --- a/Common/Enums/Mission/MissionFinishTypeEnum.cs +++ b/Common/Enums/Mission/MissionFinishTypeEnum.cs @@ -1,499 +1,498 @@ -namespace EggLink.DanhengServer.Enums +namespace EggLink.DanhengServer.Enums; + +public enum MissionFinishTypeEnum { - public enum MissionFinishTypeEnum - { - Unknown = 0, - AutoFinish = 1, - Talk = 2, - StageWin = 3, - EnterRegion = 4, - PropState = 5, - ItemNum = 6, - BuyShopGoods = 7, - FinishMission = 8, - GetAvatarStar = 9, - EquipmentLevel = 11, - EquipmentPromoteUp = 12, - EquipmentRankUp = 13, - EquipmentStarCnt = 14, - EquipmentLevelCnt = 15, - EquipmentPromoteCnt = 16, - EquipmentRankCnt = 17, - WorldLevel = 18, - EnterMapByEntrance = 19, - BookNum = 20, - PropTypeInteract = 21, - ChallengeFinish = 22, - CocoonFinish = 25, - AnyCocoonFinish = 26, - ConsumeMissionItem = 27, - EnterFloor = 28, - GetTrialAvatar = 29, - DelTrialAvatar = 30, - FinishMainMission = 31, - RelicSuit = 32, - ChallengeFinishCnt = 33, - SubMissionFinishCnt = 34, - FinishMissionEvent = 35, - ClientProgress = 36, - RelicLevelCnt = 37, - TreasureChestOpenCnt = 38, - CreateCharacter = 39, - ChallengeStars = 40, - FinishDailyMissionCnt = 41, - DialogueEventCnt = 42, - ItemCompose = 43, - ConsecutiveLoginDays = 44, - MessageSectionFinish = 45, - DialogueEventCntWithGameMode = 46, - ExpeditionRewardCnt = 47, - GachaWithType = 48, - Gacha = 49, - MessagePerformSectionFinish = 50, - FinishTodayDailyMissionCnt = 52, - ExpeditionBeginCnt = 53, - InclinationTextWithType = 54, - TrialStageFinish = 55, - LeavePlane = 56, - UnlockSpring = 57, - PropDestruct = 58, - ExcellentEnterBattle = 59, - BadEnterBattle = 60, - UseMazeSkill = 61, - BattleWithAvatar = 62, - BattleWinWithSpecificProfessionAvatar = 63, - BattleWinWithSpecificDamageAvatar = 64, - BattleWinWithSingleAvatar = 65, - TreasureChestOpenWithWorld = 66, - FinishTreasureChallengeWithTag = 67, - RaidFinishCnt = 69, - ActivityFightFinish = 70, - ExcellentEnterBattleAndWin = 71, - RaidTargetFinish = 72, - ActivityFightFirstFinishDifficulty = 73, - TotalLoginDays = 74, - BoxingClubAccomplish = 75, - ActivityFightMaxWave = 76, - TakePictureCnt = 77, - TriggerHealVoiceBySpecificAvatar = 78, - RandomMessageFinishCount = 79, - EnterRaidScene = 80, - EnterPlane = 81, - LeaveFloor = 82, - NotInPlane = 83, - NotInFloor = 84, - TreasureDungeonFinishFloor = 85, - TreasureDungeonAccomplish = 86, - TeamLeaderChange = 87, - FinishQuestByClient = 88, - UAVOutBound = 89, - DeliveryTwelve = 91, - AnyChallengeStars = 92, - ChangeChatBubbleCnt = 93, - ChangePhoneThemeCnt = 94, - ConsumeStamina = 101, - PlayerLevel = 102, - FinishQuest = 104, - TakePlayerLevelReward = 105, - FinishQuestAndTakeReward = 106, - KillMonsterGroupList = 107, - GetTrialAvatarList = 108, - AlleyLogisticsShopLink = 109, - AlleyLogisticsShopListLink = 110, - AlleyLogisticsCnt = 111, - AlleyLogisticsShopRankReachN = 112, - AlleyLogisticsBattery = 113, - AlleyLogisticsShopBattery = 114, - AlleyLogisticsDetonateStarSkiff = 115, - FinishQuestListAndTakeReward = 116, - GetItem = 201, - UseItem = 202, - GetItemWithType = 203, - EquipmentTypeCnt = 204, - AnyEquipmentPromoteCnt = 205, - GetItemWithList = 206, - UseItemWithType = 207, - GetBookWithWorld = 208, - ComposeItemWithId = 209, - ComposeItemWithType = 210, - ComposeConsumeItemWithId = 211, - ResolveRelic = 212, - GetPlanar = 213, - AnyEquipmentLevelUp = 214, - AnyRelicLevelUp = 215, - UseSelectedItem = 216, - GetAnyRarityRelic = 217, - ReplaceMaterialCnt = 218, - SpecificRarityRelicLevelUp = 219, - UseItemInContinuousDays = 220, - AvatarLevel = 301, - AvatarPromote = 302, - AvatarRank = 303, - UnlockSkilltree = 304, - AvatarRankUp = 307, - AvatarLevelCnt = 309, - AvatarPromoteCnt = 310, - AvatarRankCnt = 311, - UnlockSkilltreeCnt = 312, - AnyAvatarUnlockSkilltreeCnt = 313, - AnyAvatarPromoteCnt = 314, - AllAvatarUnlockSkilltreeCnt = 315, - AllAvatarPromoteCnt = 316, - AnyAvatarLevelUp = 317, - AnyAvatarDressAllRelicMax = 318, - AnyAvatarSkilltreeMax = 319, - KillMonster = 402, - KillMonsterList = 404, - InteractPropList = 405, - FarmElementFinish = 406, - AnyFarmElementFinish = 407, - FarmRelicFinish = 408, - AnyFarmRelicFinish = 409, - AnyMaterialStageFinish = 410, - KillMonsterWithGameMode = 411, - KillMonsterWithRogue = 412, - KillMonsterInBattle = 413, - HeroPathLevel = 601, - HeroPathLevelUpCnt = 602, - WaitDays = 604, - PropStateChangedList = 605, - RogueFinishCnt = 701, - RogueFinishWithScore = 702, - RogueChallengeScore = 703, - RogueExploreRoomFinishCnt = 704, - RogueGetBuffTypeCnt = 705, - RogueFinishRoomTypeCnt = 706, - RogueBuffLevel = 707, - RogueExploreScore = 708, - RogueAppraisalResult = 709, - RogueBlessLevel = 710, - RogueQuestFinishWithGameMode = 711, - RogueFinishUnlock = 722, - RoguePassAreaProgress = 723, - RogueAeonLevel = 724, - RogueImmerseLevel = 725, - RogueTalentEnable = 726, - RogueKillMonster = 727, - RogueAreaProgressScore = 728, - RogueFinishWithDifficulty = 729, - RogueEncounterSpecialEvent = 730, - RoguePropDestruct = 731, - RogueBuffEnhance = 732, - RogueMiracleUnlock = 733, - RogueMonsterEscape = 734, - RogueUnlockBuff = 735, - RogueFinishWithBuff = 736, - RogueFinishWithBuffType = 737, - RogueFinishWithBuffCnt = 738, - RogueFinishWithMiracleCnt = 739, - RogueFinishWithCoinCnt = 740, - RogueFinishWithMonster = 741, - RogueFinishWithDownloadCnt = 742, - RogueFinishWithPropDestroyCnt = 743, - RogueFinishWithSkillCastCnt = 744, - RogueFinishWithAvatarCnt = 745, - RogueFinishWithAllSameBaseType = 746, - RogueFinishWithEvent = 747, - RogueFinishWithAllBattleFullHp = 748, - RogueFinishDialogueWithCnt = 749, - RogueKillChestMonster = 750, - RogueFreeChestMonster = 751, - RogueKillBattleMonster = 752, - RogueKillMonsterWithRoomLevel = 753, - RogueEnterRoomWithLevel = 754, - RogueFinishArea = 755, - BattleChallenge = 801, - WinBattleWithSomeAvatar = 802, - WinBattleWithAssistAvatarCnt = 803, - SkillHitTargetAfterDuration = 804, - EnterAggroRangeForDuration = 805, - PunkLordSummonMonsterCnt = 851, - PunkLordSupportCnt = 852, - PunkLordShareMonsterCnt = 853, - PunkLordKillMonsterCnt = 854, - PunkLordKillSelfMonsterCnt = 855, - PunkLordStageFinish = 856, - MuseumPhaseFinish = 857, - MuseumCollectStuffCnt = 858, - MuseumCollectExhibitCnt = 859, - ActivityMonsterResearchFinishCnt = 860, - ActivityExpeditionFinishCnt = 861, - ActivityFantasticStoryFinishBattleWithScore = 862, - GetActivePoint = 871, - RogueChallengeSuccessCnt = 881, - RogueChallengeFinishWithScore = 882, - RogueChallengeFinishWithGoal = 883, - MuseumWorkDayCnt = 884, - MuseumAreaLevel = 885, - MuseumTargetFinishCnt = 886, - PlayStationLogin = 887, - AlleySpecialOrderFinish = 890, - AlleyPrestigeLevel = 891, - AlleyEventFinishByType = 892, - AlleySpecialOrderFinishById = 893, - AlleyShipmentFinish = 894, - AlleyShipmentFinishByShipType = 895, - AlleyShipmentProfit = 896, - AlleyShipmentProfitByShipType = 897, - AlleyNormalOrderFinish = 898, - AlleyPlacingGameGoodsNum = 899, - AetherDivideCollectSpiritType = 900, - AetherDivideTrainerLevel = 901, - AetherDivideCollectPassiveSkillType = 902, - AetherDivideSpiritLevel = 903, - AetherDivideFinishHyperlinkDuel = 904, - AetherDivideCertainFinishHyperlinkDuel = 905, - StageWinList = 906, - SceneTreasureChestOpenCnt = 907, - AlleyPlacingGameGoodsNumByGoodsId = 908, - AetherDivideCollectSpiritId = 909, - RogueDLCFinishCnt = 130000, - RogueDLCBlockFinishCnt = 130001, - RogueDLCBlockEnterCnt = 130002, - RogueDLCChessBoardEventCnt = 130003, - RogueDLCGetBuffTypeCnt = 130004, - RogueDLCGetMiracleCnt = 130005, - RogueDLCMarkTypeFinishCnt = 130006, - RogueDLCGetCoinCnt = 130007, - RogueDLCEnterLayerCnt = 130008, - RogueDLCFinishCabinetCnt = 130009, - RogueDLCDialogueEventCnt = 130010, - RogueDLCAeonDimensionCnt = 130011, - RogueDLCAeonFinishCnt = 130012, - RogueDLCFinishMainStory = 130013, - RogueDLCFinishMainStoryCnt = 130014, - RogueDLCFinishSubStoryGroup = 130015, - RogueDLCFinishSubStoryGroupCnt = 130016, - RogueDLCRollDiceContinuousCnt = 130017, - RogueDLCRollDiceMemeryRewardCnt = 130018, - RogueDLCFinishByWarriorDice = 130019, - RogueDLCFinishByWarlockDice = 130020, - RogueDLCFinishByKnightDice = 130021, - RogueDLCFinishByPriestDicePosivive = 130022, - RogueDLCFinishByBreedDice = 130023, - RogueDLCRollDiceAccumulateCnt = 130024, - RogueDLCLightenFirstHiddenCabinet = 130025, - RogueDLCRollDiceUseCheatCnt = 130028, - RogueDLCRollDiceUseRepeatCnt = 130029, - RogueDLCNotWarlockDiceEnterEmptyRoom = 130030, - RogueDLCFinishAdventureRoomWithLevelCnt = 130031, - RogueDLCNotBreedkDiceEnterSwarmRoom = 130032, - RogueDLCShopSoldOutCnt = 130035, - RogueDLCKillBattleChestMonsterWithAeon = 130036, - RogueDLCFinishWithEvent = 130037, - RogueDLCFinishWithPropDestructCnt = 130038, - RogueDLCFinishAdventureRoomWithMonsterCnt = 130039, - RogueDLCFinishWithAeonCrossCnt = 130040, - RogueDLCFinishAeonEventWithAeonCnt = 130041, - RogueDLCFinishWithMainStoryCnt = 130042, - RogueDLCFinishWithSubStoryGroupCnt = 130043, - RogueDLCFinishManyMoney = 130045, - RogueDLCSelectedAeonDimensionCnt = 130046, - RogueDLCFailCnt = 130047, - RogueDLCFinishByAnyDiceNegative = 130049, - RogueDLCFinishDialogueEvent = 130050, - RogueDLCGetAeonBuffEnhanceCnt = 130051, - RogueDLCDiceNegativeCnt = 130052, - RogueDLCGetCoinExceptBattleCnt = 130053, - RogueDLCBuyShopItemOnceRoomCnt = 130054, - RogueDLCContinuationEnterBattleBlockCnt = 130055, - RogueDLCBlockFinishFullHpCnt = 130056, - RogueDLCEnterBlockWithCoinCnt = 130057, - RogueDLCContinuationEnterDiffBlockCnt = 130058, - RogueDLCAeonOptionCnt = 130059, - RogueDLCEnterBlockWithDiceZero = 130060, - RogueDLCMarkTypeFinishOneLayerCnt = 130061, - RogueDLCFinishByHappyDice = 130062, - SendChatEmojiCnt = 130200, - SendTrainMemberChatEmojiCnt = 130201, - RecvOppositeGenderChatEmoji = 130202, - FinishRogueEndlessWithScore = 140000, - FinishRogueEndlessWithAllScore = 140001, - SendMaxChatMsgByChatBubble = 140002, - MainMissionHasCustomValue = 140003, - HeliobusSnsSpecialPost = 150000, - HeliobusLevel = 150001, - HeliobusPhase = 150002, - HeliobusSnsSpecialPostCnt = 150003, - HeliobusSnsCommentCnt = 150004, - HeliobusSnsSubCommentCnt = 150005, - HeliobusSnsLikeCnt = 150006, - HeliobusSnsSpecialComment = 150007, - HeliobusChallengeWithSkill = 150008, - HeliobusChallengeFirstClear = 150009, - HeliobusChallengeTargetFinish = 150010, - TrainVisitorMissionFinish = 150011, - GroupState = 150012, - WinWithFriendAssist = 150013, - BattleLastStandAndEscape = 150014, - TriggerAvatarVoice = 150015, - HeliobusSnsSpecialPostTendencyCnt = 150016, - HeliobusSnsAllCommentCnt = 150017, - RaidFinished = 150018, - RogueDialogueWithAvatar = 150019, - HeliobusSnsSpecialPostTendency = 150020, - SpaceZooHybridCount = 160000, - ActivityStrongChallengeEndScore = 160001, - ActivityStrongChallengeAllQuestFinish = 160002, - SpaceZooUnlockSpecialCount = 160003, - SpaceZooUnlockSpecialID = 160004, - SpaceZooOpCatteryCount = 160005, - SpaceZooExpPoint = 160006, - SpaceZooUnlockFeatureCount = 160007, - SpaceZooExpLevel = 160008, - FinishFirstTalkPerformance = 160011, - AnyItemComposeCount = 160012, - ChallengeStorySettleCnt = 160013, - RogueNousFinishWithNousValue = 160019, - RogueNousFinishWithDifficultyComp = 160020, - ChallengeGivenTypeFloorSettleSuccCnt = 160021, - TriggerRepeatableAvatarVoice = 160022, - ActivityStrongChallengeBegin = 160023, - RogueNousFinishSubStory = 160024, - RogueNousFinishSubStoryAsRecommend = 160025, - RogueNousFinishWithActionPoint = 160026, - RogueNousNousValueChange = 160027, - RogueNousFinishWithDifficultyCompDicePassive = 160028, - RogueNousFinishWithAeonDifficultyComp = 160029, - RogueNousFinishMainStory = 160030, - RogueNousValueReachNeagtive = 160031, - RogueNousValueReachPositive = 160032, - RogueNousTalentEnable = 160033, - RogueCommonGameGetAeonTypeBuffEnhance = 160034, - RogueChessEnterBlockWithTypeCnt = 160035, - RogueChessEnterBlockWithMarkTypeCnt = 160036, - RogueChessGameWatchSttReach = 160037, - RogueNousFinishDiceWithStt = 160038, - RogueNousUnlockDiceSurfaceCnt = 160039, - RogueNousUnlockDiceBranchCnt = 160040, - RogueNousFinishWithDiceBranch = 160041, - RogueNousFinishWithDiceSurfaceTag = 160042, - RogueNousFinishWithDiceSurfaceRarity = 160043, - RogueNousContinuousRollDiffSurface = 160044, - RogueChessSetSpecialTypeCnt = 160045, - RogueNousUnlockDiceBranch = 160046, - RogueNousFinishDiceWithMiracleNum = 160047, - RogueNousFinishDiceWithMoneyNum = 160048, - RogueNousContinuationEnterNotAroundCellWithDiceCnt = 160049, - FinishQuestInList = 160050, - RogueAdventureEscapeLazerSuccInContinuousRounds = 160051, - RogueChessFinishWithMiracleInGroupNum = 160052, - RogueNousFinishStoryCnt = 160053, - RogueNousFinishDiceWithMapStt = 160054, - TravelBrochureProgrss = 200001, - ChangeStoryLine = 200002, - HeartDialScriptListStep = 200003, - HeartDialScriptListEmotion = 200004, - HeartDialScriptChangeEmotionCnt = 200005, - SceneTreasureChestOpenByTypeCnt = 200006, - PropStateChangeWithSpecificPropId = 200007, - TravelBrochurePasterCollectProgrss = 200008, - BattleLose = 200009, - BattleQuit = 200010, - TelevisionActivityStageScore = 200011, - TelevisionActivityFisrtStageScore = 200012, - KillMonsterInTrackList = 200013, - HeartDialDialoguePerformanceFinish = 200014, - HeartDialScriptChangeStepCnt = 200015, - RaidCollectionIDFinishList = 200016, - RaidCollectionGroupIDFinishList = 200017, - FloorSavedValue = 200018, - SwitchFloor = 200019, - UseSpecificAssistAvatar = 200020, - RollShopTakeSecretReward = 200021, - RollShopTakeSpecialRewardByBuff = 200022, - HeartDialChangedEmotionScriptCnt = 200023, - HeartDialScriptFinishAllDialogueCnt = 200024, - ActivityMonsterResearchGiftTakeCnt = 200025, - DrinkMakerLastSequenceEnd = 210000, - FinishMovieGame = 210001, - DrinkMakerLevel = 210002, - DrinkMakerGivenChallengeCount = 210003, - DrinkMakerFinishSequenceCount = 210004, - DrinkMakerRequestSuccCount = 210005, - DrinkMakerRequestFailCount = 210006, - DrinkMakerMakeDrinkByFormulaCount = 210007, - OfferingLevel = 210008, - ActivityFeverTimeFinish = 210009, - MonopolyMoveRollCnt = 210010, - MonopolyPassCellCnt = 210011, - MonopolyFinishEventCnt = 210012, - MonopolyTotalDonateCnt = 210013, - MonopolyAssetUpgrade = 210014, - GetItemListOnce = 210015, - WolfBroKillMonster = 210016, - WolfBroBulletCntReachMax = 210017, - GroupPropDestruct = 210018, - MonopolyTakePhaseRewardCnt = 210019, - MonopolyTakeRafflePoolRewardCnt = 210020, - ChallengeStarsRepeatable = 210021, - MonopolyTotalDonateCntWhenRegionProgressComplete = 210022, - MonopolyTakeMbtiRewardCnt = 210023, - EvolveBuildLevelStart = 220000, - EvolveBuildLevelScore = 220001, - EvolveBuildKillMonster = 220002, - EvolveBuildFinishLevel = 220003, - ClockParkProgress = 220004, - ClockParkReachEndingNum = 220005, - ClockParkReachSpecificEnding = 220006, - ClockParkReachAttribute = 220007, - EvolveBuildGetSuperWeapon = 220008, - EvolveBuildTakeExpReward = 220009, - ClockParkReachEndlessScore = 220010, - ClockParkEnterChapterList = 220011, - ClockParkGetSameDice = 220012, - ClockParkPassCheckpointExactly = 220013, - FinishGunPlayGame = 220014, - SpecificRaidTargetFinish = 220015, - FloorSavedValueList = 220016, - FinishGunPlayGamePerfect = 220017, - OrigamiCnt = 220018, - RogueTournPermanentEnable = 230000, - RogueTournFinishCnt = 230001, - RogueTournFinishCurWeekChallengeCnt = 230002, - RogueTournFinishWithDifficultyCompCnt = 230003, - RogueTournGetSimpleMiracleCnt = 230004, - RogueTournGetHexMiracleCnt = 230005, - RogueTournGetBuffCnt = 230006, - RogueTournGetFormulaCnt = 230007, - RogueTournGetEventCnt = 230008, - MatchThreeFinishLevel = 230009, - MatchThreeBirdUseSkill = 230010, - MatchThreeFinishPvp = 230011, - MatchThreePvpScore = 230012, - MatchThreeBirdPos = 230017, - MatchThreeBomb = 230018, - MatchThreeMaxPower = 230019, - ChallengeBossWinBattleCnt = 230013, - ChallengeBossCompleteOnce = 230014, - StarFightStageFinish = 230015, - StarFightStageFinishWithWave = 230016, - RogueTournGetMiracleCnt = 230030, - RogueTournActiveFormulaCnt = 230031, - RogueTournFinishWithActiveFormulaCnt = 230032, - RogueTournFinishWithFormulaCnt = 230033, - RogueTournFinishWithNoInActiveFormula = 230034, - RogueTournGetCollectionCnt = 230035, - RogueTournGetExhibitionCnt = 230036, - RogueTournFinishRelicCnt = 230037, - RogueTournFinishWeekChallengeCnt = 230038, - RogueTournBossExtraChallengeScore = 230039, - RogueTournGetCoin = 230040, - RogueTournFinishWithCoinCnt = 230041, - RogueTournFinishWithBattleWinCnt = 230042, - RogueTournEnterRoomWithType = 230043, - RogueTournFinishWorkbenchCnt = 230044, - RogueTournGambleWithMiracleCnt = 230045, - RogueTournGambleWithBuffCnt = 230046, - RogueTournOpenChestCnt = 230047, - RogueTournGetExpCnt = 230048, - RogueTournExpLevelReach = 230049, - RogueTournFinishWithMiracleCnt = 230050, - RogueTournGambleCnt = 230051, - PlayerReturnTakeDailyRewardCnt = 230101, - PlayerReturnTakeBPRewardCnt = 230102, - PlayerReturnPlayTrialCnt = 230103, - PlayerReturnPlayRogueCnt = 230104, - PlayerReturnFinishCocoonCnt = 230105, - } -} + Unknown = 0, + AutoFinish = 1, + Talk = 2, + StageWin = 3, + EnterRegion = 4, + PropState = 5, + ItemNum = 6, + BuyShopGoods = 7, + FinishMission = 8, + GetAvatarStar = 9, + EquipmentLevel = 11, + EquipmentPromoteUp = 12, + EquipmentRankUp = 13, + EquipmentStarCnt = 14, + EquipmentLevelCnt = 15, + EquipmentPromoteCnt = 16, + EquipmentRankCnt = 17, + WorldLevel = 18, + EnterMapByEntrance = 19, + BookNum = 20, + PropTypeInteract = 21, + ChallengeFinish = 22, + CocoonFinish = 25, + AnyCocoonFinish = 26, + ConsumeMissionItem = 27, + EnterFloor = 28, + GetTrialAvatar = 29, + DelTrialAvatar = 30, + FinishMainMission = 31, + RelicSuit = 32, + ChallengeFinishCnt = 33, + SubMissionFinishCnt = 34, + FinishMissionEvent = 35, + ClientProgress = 36, + RelicLevelCnt = 37, + TreasureChestOpenCnt = 38, + CreateCharacter = 39, + ChallengeStars = 40, + FinishDailyMissionCnt = 41, + DialogueEventCnt = 42, + ItemCompose = 43, + ConsecutiveLoginDays = 44, + MessageSectionFinish = 45, + DialogueEventCntWithGameMode = 46, + ExpeditionRewardCnt = 47, + GachaWithType = 48, + Gacha = 49, + MessagePerformSectionFinish = 50, + FinishTodayDailyMissionCnt = 52, + ExpeditionBeginCnt = 53, + InclinationTextWithType = 54, + TrialStageFinish = 55, + LeavePlane = 56, + UnlockSpring = 57, + PropDestruct = 58, + ExcellentEnterBattle = 59, + BadEnterBattle = 60, + UseMazeSkill = 61, + BattleWithAvatar = 62, + BattleWinWithSpecificProfessionAvatar = 63, + BattleWinWithSpecificDamageAvatar = 64, + BattleWinWithSingleAvatar = 65, + TreasureChestOpenWithWorld = 66, + FinishTreasureChallengeWithTag = 67, + RaidFinishCnt = 69, + ActivityFightFinish = 70, + ExcellentEnterBattleAndWin = 71, + RaidTargetFinish = 72, + ActivityFightFirstFinishDifficulty = 73, + TotalLoginDays = 74, + BoxingClubAccomplish = 75, + ActivityFightMaxWave = 76, + TakePictureCnt = 77, + TriggerHealVoiceBySpecificAvatar = 78, + RandomMessageFinishCount = 79, + EnterRaidScene = 80, + EnterPlane = 81, + LeaveFloor = 82, + NotInPlane = 83, + NotInFloor = 84, + TreasureDungeonFinishFloor = 85, + TreasureDungeonAccomplish = 86, + TeamLeaderChange = 87, + FinishQuestByClient = 88, + UAVOutBound = 89, + DeliveryTwelve = 91, + AnyChallengeStars = 92, + ChangeChatBubbleCnt = 93, + ChangePhoneThemeCnt = 94, + ConsumeStamina = 101, + PlayerLevel = 102, + FinishQuest = 104, + TakePlayerLevelReward = 105, + FinishQuestAndTakeReward = 106, + KillMonsterGroupList = 107, + GetTrialAvatarList = 108, + AlleyLogisticsShopLink = 109, + AlleyLogisticsShopListLink = 110, + AlleyLogisticsCnt = 111, + AlleyLogisticsShopRankReachN = 112, + AlleyLogisticsBattery = 113, + AlleyLogisticsShopBattery = 114, + AlleyLogisticsDetonateStarSkiff = 115, + FinishQuestListAndTakeReward = 116, + GetItem = 201, + UseItem = 202, + GetItemWithType = 203, + EquipmentTypeCnt = 204, + AnyEquipmentPromoteCnt = 205, + GetItemWithList = 206, + UseItemWithType = 207, + GetBookWithWorld = 208, + ComposeItemWithId = 209, + ComposeItemWithType = 210, + ComposeConsumeItemWithId = 211, + ResolveRelic = 212, + GetPlanar = 213, + AnyEquipmentLevelUp = 214, + AnyRelicLevelUp = 215, + UseSelectedItem = 216, + GetAnyRarityRelic = 217, + ReplaceMaterialCnt = 218, + SpecificRarityRelicLevelUp = 219, + UseItemInContinuousDays = 220, + AvatarLevel = 301, + AvatarPromote = 302, + AvatarRank = 303, + UnlockSkilltree = 304, + AvatarRankUp = 307, + AvatarLevelCnt = 309, + AvatarPromoteCnt = 310, + AvatarRankCnt = 311, + UnlockSkilltreeCnt = 312, + AnyAvatarUnlockSkilltreeCnt = 313, + AnyAvatarPromoteCnt = 314, + AllAvatarUnlockSkilltreeCnt = 315, + AllAvatarPromoteCnt = 316, + AnyAvatarLevelUp = 317, + AnyAvatarDressAllRelicMax = 318, + AnyAvatarSkilltreeMax = 319, + KillMonster = 402, + KillMonsterList = 404, + InteractPropList = 405, + FarmElementFinish = 406, + AnyFarmElementFinish = 407, + FarmRelicFinish = 408, + AnyFarmRelicFinish = 409, + AnyMaterialStageFinish = 410, + KillMonsterWithGameMode = 411, + KillMonsterWithRogue = 412, + KillMonsterInBattle = 413, + HeroPathLevel = 601, + HeroPathLevelUpCnt = 602, + WaitDays = 604, + PropStateChangedList = 605, + RogueFinishCnt = 701, + RogueFinishWithScore = 702, + RogueChallengeScore = 703, + RogueExploreRoomFinishCnt = 704, + RogueGetBuffTypeCnt = 705, + RogueFinishRoomTypeCnt = 706, + RogueBuffLevel = 707, + RogueExploreScore = 708, + RogueAppraisalResult = 709, + RogueBlessLevel = 710, + RogueQuestFinishWithGameMode = 711, + RogueFinishUnlock = 722, + RoguePassAreaProgress = 723, + RogueAeonLevel = 724, + RogueImmerseLevel = 725, + RogueTalentEnable = 726, + RogueKillMonster = 727, + RogueAreaProgressScore = 728, + RogueFinishWithDifficulty = 729, + RogueEncounterSpecialEvent = 730, + RoguePropDestruct = 731, + RogueBuffEnhance = 732, + RogueMiracleUnlock = 733, + RogueMonsterEscape = 734, + RogueUnlockBuff = 735, + RogueFinishWithBuff = 736, + RogueFinishWithBuffType = 737, + RogueFinishWithBuffCnt = 738, + RogueFinishWithMiracleCnt = 739, + RogueFinishWithCoinCnt = 740, + RogueFinishWithMonster = 741, + RogueFinishWithDownloadCnt = 742, + RogueFinishWithPropDestroyCnt = 743, + RogueFinishWithSkillCastCnt = 744, + RogueFinishWithAvatarCnt = 745, + RogueFinishWithAllSameBaseType = 746, + RogueFinishWithEvent = 747, + RogueFinishWithAllBattleFullHp = 748, + RogueFinishDialogueWithCnt = 749, + RogueKillChestMonster = 750, + RogueFreeChestMonster = 751, + RogueKillBattleMonster = 752, + RogueKillMonsterWithRoomLevel = 753, + RogueEnterRoomWithLevel = 754, + RogueFinishArea = 755, + BattleChallenge = 801, + WinBattleWithSomeAvatar = 802, + WinBattleWithAssistAvatarCnt = 803, + SkillHitTargetAfterDuration = 804, + EnterAggroRangeForDuration = 805, + PunkLordSummonMonsterCnt = 851, + PunkLordSupportCnt = 852, + PunkLordShareMonsterCnt = 853, + PunkLordKillMonsterCnt = 854, + PunkLordKillSelfMonsterCnt = 855, + PunkLordStageFinish = 856, + MuseumPhaseFinish = 857, + MuseumCollectStuffCnt = 858, + MuseumCollectExhibitCnt = 859, + ActivityMonsterResearchFinishCnt = 860, + ActivityExpeditionFinishCnt = 861, + ActivityFantasticStoryFinishBattleWithScore = 862, + GetActivePoint = 871, + RogueChallengeSuccessCnt = 881, + RogueChallengeFinishWithScore = 882, + RogueChallengeFinishWithGoal = 883, + MuseumWorkDayCnt = 884, + MuseumAreaLevel = 885, + MuseumTargetFinishCnt = 886, + PlayStationLogin = 887, + AlleySpecialOrderFinish = 890, + AlleyPrestigeLevel = 891, + AlleyEventFinishByType = 892, + AlleySpecialOrderFinishById = 893, + AlleyShipmentFinish = 894, + AlleyShipmentFinishByShipType = 895, + AlleyShipmentProfit = 896, + AlleyShipmentProfitByShipType = 897, + AlleyNormalOrderFinish = 898, + AlleyPlacingGameGoodsNum = 899, + AetherDivideCollectSpiritType = 900, + AetherDivideTrainerLevel = 901, + AetherDivideCollectPassiveSkillType = 902, + AetherDivideSpiritLevel = 903, + AetherDivideFinishHyperlinkDuel = 904, + AetherDivideCertainFinishHyperlinkDuel = 905, + StageWinList = 906, + SceneTreasureChestOpenCnt = 907, + AlleyPlacingGameGoodsNumByGoodsId = 908, + AetherDivideCollectSpiritId = 909, + RogueDLCFinishCnt = 130000, + RogueDLCBlockFinishCnt = 130001, + RogueDLCBlockEnterCnt = 130002, + RogueDLCChessBoardEventCnt = 130003, + RogueDLCGetBuffTypeCnt = 130004, + RogueDLCGetMiracleCnt = 130005, + RogueDLCMarkTypeFinishCnt = 130006, + RogueDLCGetCoinCnt = 130007, + RogueDLCEnterLayerCnt = 130008, + RogueDLCFinishCabinetCnt = 130009, + RogueDLCDialogueEventCnt = 130010, + RogueDLCAeonDimensionCnt = 130011, + RogueDLCAeonFinishCnt = 130012, + RogueDLCFinishMainStory = 130013, + RogueDLCFinishMainStoryCnt = 130014, + RogueDLCFinishSubStoryGroup = 130015, + RogueDLCFinishSubStoryGroupCnt = 130016, + RogueDLCRollDiceContinuousCnt = 130017, + RogueDLCRollDiceMemeryRewardCnt = 130018, + RogueDLCFinishByWarriorDice = 130019, + RogueDLCFinishByWarlockDice = 130020, + RogueDLCFinishByKnightDice = 130021, + RogueDLCFinishByPriestDicePosivive = 130022, + RogueDLCFinishByBreedDice = 130023, + RogueDLCRollDiceAccumulateCnt = 130024, + RogueDLCLightenFirstHiddenCabinet = 130025, + RogueDLCRollDiceUseCheatCnt = 130028, + RogueDLCRollDiceUseRepeatCnt = 130029, + RogueDLCNotWarlockDiceEnterEmptyRoom = 130030, + RogueDLCFinishAdventureRoomWithLevelCnt = 130031, + RogueDLCNotBreedkDiceEnterSwarmRoom = 130032, + RogueDLCShopSoldOutCnt = 130035, + RogueDLCKillBattleChestMonsterWithAeon = 130036, + RogueDLCFinishWithEvent = 130037, + RogueDLCFinishWithPropDestructCnt = 130038, + RogueDLCFinishAdventureRoomWithMonsterCnt = 130039, + RogueDLCFinishWithAeonCrossCnt = 130040, + RogueDLCFinishAeonEventWithAeonCnt = 130041, + RogueDLCFinishWithMainStoryCnt = 130042, + RogueDLCFinishWithSubStoryGroupCnt = 130043, + RogueDLCFinishManyMoney = 130045, + RogueDLCSelectedAeonDimensionCnt = 130046, + RogueDLCFailCnt = 130047, + RogueDLCFinishByAnyDiceNegative = 130049, + RogueDLCFinishDialogueEvent = 130050, + RogueDLCGetAeonBuffEnhanceCnt = 130051, + RogueDLCDiceNegativeCnt = 130052, + RogueDLCGetCoinExceptBattleCnt = 130053, + RogueDLCBuyShopItemOnceRoomCnt = 130054, + RogueDLCContinuationEnterBattleBlockCnt = 130055, + RogueDLCBlockFinishFullHpCnt = 130056, + RogueDLCEnterBlockWithCoinCnt = 130057, + RogueDLCContinuationEnterDiffBlockCnt = 130058, + RogueDLCAeonOptionCnt = 130059, + RogueDLCEnterBlockWithDiceZero = 130060, + RogueDLCMarkTypeFinishOneLayerCnt = 130061, + RogueDLCFinishByHappyDice = 130062, + SendChatEmojiCnt = 130200, + SendTrainMemberChatEmojiCnt = 130201, + RecvOppositeGenderChatEmoji = 130202, + FinishRogueEndlessWithScore = 140000, + FinishRogueEndlessWithAllScore = 140001, + SendMaxChatMsgByChatBubble = 140002, + MainMissionHasCustomValue = 140003, + HeliobusSnsSpecialPost = 150000, + HeliobusLevel = 150001, + HeliobusPhase = 150002, + HeliobusSnsSpecialPostCnt = 150003, + HeliobusSnsCommentCnt = 150004, + HeliobusSnsSubCommentCnt = 150005, + HeliobusSnsLikeCnt = 150006, + HeliobusSnsSpecialComment = 150007, + HeliobusChallengeWithSkill = 150008, + HeliobusChallengeFirstClear = 150009, + HeliobusChallengeTargetFinish = 150010, + TrainVisitorMissionFinish = 150011, + GroupState = 150012, + WinWithFriendAssist = 150013, + BattleLastStandAndEscape = 150014, + TriggerAvatarVoice = 150015, + HeliobusSnsSpecialPostTendencyCnt = 150016, + HeliobusSnsAllCommentCnt = 150017, + RaidFinished = 150018, + RogueDialogueWithAvatar = 150019, + HeliobusSnsSpecialPostTendency = 150020, + SpaceZooHybridCount = 160000, + ActivityStrongChallengeEndScore = 160001, + ActivityStrongChallengeAllQuestFinish = 160002, + SpaceZooUnlockSpecialCount = 160003, + SpaceZooUnlockSpecialID = 160004, + SpaceZooOpCatteryCount = 160005, + SpaceZooExpPoint = 160006, + SpaceZooUnlockFeatureCount = 160007, + SpaceZooExpLevel = 160008, + FinishFirstTalkPerformance = 160011, + AnyItemComposeCount = 160012, + ChallengeStorySettleCnt = 160013, + RogueNousFinishWithNousValue = 160019, + RogueNousFinishWithDifficultyComp = 160020, + ChallengeGivenTypeFloorSettleSuccCnt = 160021, + TriggerRepeatableAvatarVoice = 160022, + ActivityStrongChallengeBegin = 160023, + RogueNousFinishSubStory = 160024, + RogueNousFinishSubStoryAsRecommend = 160025, + RogueNousFinishWithActionPoint = 160026, + RogueNousNousValueChange = 160027, + RogueNousFinishWithDifficultyCompDicePassive = 160028, + RogueNousFinishWithAeonDifficultyComp = 160029, + RogueNousFinishMainStory = 160030, + RogueNousValueReachNeagtive = 160031, + RogueNousValueReachPositive = 160032, + RogueNousTalentEnable = 160033, + RogueCommonGameGetAeonTypeBuffEnhance = 160034, + RogueChessEnterBlockWithTypeCnt = 160035, + RogueChessEnterBlockWithMarkTypeCnt = 160036, + RogueChessGameWatchSttReach = 160037, + RogueNousFinishDiceWithStt = 160038, + RogueNousUnlockDiceSurfaceCnt = 160039, + RogueNousUnlockDiceBranchCnt = 160040, + RogueNousFinishWithDiceBranch = 160041, + RogueNousFinishWithDiceSurfaceTag = 160042, + RogueNousFinishWithDiceSurfaceRarity = 160043, + RogueNousContinuousRollDiffSurface = 160044, + RogueChessSetSpecialTypeCnt = 160045, + RogueNousUnlockDiceBranch = 160046, + RogueNousFinishDiceWithMiracleNum = 160047, + RogueNousFinishDiceWithMoneyNum = 160048, + RogueNousContinuationEnterNotAroundCellWithDiceCnt = 160049, + FinishQuestInList = 160050, + RogueAdventureEscapeLazerSuccInContinuousRounds = 160051, + RogueChessFinishWithMiracleInGroupNum = 160052, + RogueNousFinishStoryCnt = 160053, + RogueNousFinishDiceWithMapStt = 160054, + TravelBrochureProgrss = 200001, + ChangeStoryLine = 200002, + HeartDialScriptListStep = 200003, + HeartDialScriptListEmotion = 200004, + HeartDialScriptChangeEmotionCnt = 200005, + SceneTreasureChestOpenByTypeCnt = 200006, + PropStateChangeWithSpecificPropId = 200007, + TravelBrochurePasterCollectProgrss = 200008, + BattleLose = 200009, + BattleQuit = 200010, + TelevisionActivityStageScore = 200011, + TelevisionActivityFisrtStageScore = 200012, + KillMonsterInTrackList = 200013, + HeartDialDialoguePerformanceFinish = 200014, + HeartDialScriptChangeStepCnt = 200015, + RaidCollectionIDFinishList = 200016, + RaidCollectionGroupIDFinishList = 200017, + FloorSavedValue = 200018, + SwitchFloor = 200019, + UseSpecificAssistAvatar = 200020, + RollShopTakeSecretReward = 200021, + RollShopTakeSpecialRewardByBuff = 200022, + HeartDialChangedEmotionScriptCnt = 200023, + HeartDialScriptFinishAllDialogueCnt = 200024, + ActivityMonsterResearchGiftTakeCnt = 200025, + DrinkMakerLastSequenceEnd = 210000, + FinishMovieGame = 210001, + DrinkMakerLevel = 210002, + DrinkMakerGivenChallengeCount = 210003, + DrinkMakerFinishSequenceCount = 210004, + DrinkMakerRequestSuccCount = 210005, + DrinkMakerRequestFailCount = 210006, + DrinkMakerMakeDrinkByFormulaCount = 210007, + OfferingLevel = 210008, + ActivityFeverTimeFinish = 210009, + MonopolyMoveRollCnt = 210010, + MonopolyPassCellCnt = 210011, + MonopolyFinishEventCnt = 210012, + MonopolyTotalDonateCnt = 210013, + MonopolyAssetUpgrade = 210014, + GetItemListOnce = 210015, + WolfBroKillMonster = 210016, + WolfBroBulletCntReachMax = 210017, + GroupPropDestruct = 210018, + MonopolyTakePhaseRewardCnt = 210019, + MonopolyTakeRafflePoolRewardCnt = 210020, + ChallengeStarsRepeatable = 210021, + MonopolyTotalDonateCntWhenRegionProgressComplete = 210022, + MonopolyTakeMbtiRewardCnt = 210023, + EvolveBuildLevelStart = 220000, + EvolveBuildLevelScore = 220001, + EvolveBuildKillMonster = 220002, + EvolveBuildFinishLevel = 220003, + ClockParkProgress = 220004, + ClockParkReachEndingNum = 220005, + ClockParkReachSpecificEnding = 220006, + ClockParkReachAttribute = 220007, + EvolveBuildGetSuperWeapon = 220008, + EvolveBuildTakeExpReward = 220009, + ClockParkReachEndlessScore = 220010, + ClockParkEnterChapterList = 220011, + ClockParkGetSameDice = 220012, + ClockParkPassCheckpointExactly = 220013, + FinishGunPlayGame = 220014, + SpecificRaidTargetFinish = 220015, + FloorSavedValueList = 220016, + FinishGunPlayGamePerfect = 220017, + OrigamiCnt = 220018, + RogueTournPermanentEnable = 230000, + RogueTournFinishCnt = 230001, + RogueTournFinishCurWeekChallengeCnt = 230002, + RogueTournFinishWithDifficultyCompCnt = 230003, + RogueTournGetSimpleMiracleCnt = 230004, + RogueTournGetHexMiracleCnt = 230005, + RogueTournGetBuffCnt = 230006, + RogueTournGetFormulaCnt = 230007, + RogueTournGetEventCnt = 230008, + MatchThreeFinishLevel = 230009, + MatchThreeBirdUseSkill = 230010, + MatchThreeFinishPvp = 230011, + MatchThreePvpScore = 230012, + MatchThreeBirdPos = 230017, + MatchThreeBomb = 230018, + MatchThreeMaxPower = 230019, + ChallengeBossWinBattleCnt = 230013, + ChallengeBossCompleteOnce = 230014, + StarFightStageFinish = 230015, + StarFightStageFinishWithWave = 230016, + RogueTournGetMiracleCnt = 230030, + RogueTournActiveFormulaCnt = 230031, + RogueTournFinishWithActiveFormulaCnt = 230032, + RogueTournFinishWithFormulaCnt = 230033, + RogueTournFinishWithNoInActiveFormula = 230034, + RogueTournGetCollectionCnt = 230035, + RogueTournGetExhibitionCnt = 230036, + RogueTournFinishRelicCnt = 230037, + RogueTournFinishWeekChallengeCnt = 230038, + RogueTournBossExtraChallengeScore = 230039, + RogueTournGetCoin = 230040, + RogueTournFinishWithCoinCnt = 230041, + RogueTournFinishWithBattleWinCnt = 230042, + RogueTournEnterRoomWithType = 230043, + RogueTournFinishWorkbenchCnt = 230044, + RogueTournGambleWithMiracleCnt = 230045, + RogueTournGambleWithBuffCnt = 230046, + RogueTournOpenChestCnt = 230047, + RogueTournGetExpCnt = 230048, + RogueTournExpLevelReach = 230049, + RogueTournFinishWithMiracleCnt = 230050, + RogueTournGambleCnt = 230051, + PlayerReturnTakeDailyRewardCnt = 230101, + PlayerReturnTakeBPRewardCnt = 230102, + PlayerReturnPlayTrialCnt = 230103, + PlayerReturnPlayRogueCnt = 230104, + PlayerReturnFinishCocoonCnt = 230105 +} \ No newline at end of file diff --git a/Common/Enums/Mission/MissionPhaseEnum.cs b/Common/Enums/Mission/MissionPhaseEnum.cs index 7eb67606..f56002db 100644 --- a/Common/Enums/Mission/MissionPhaseEnum.cs +++ b/Common/Enums/Mission/MissionPhaseEnum.cs @@ -1,40 +1,39 @@ using EggLink.DanhengServer.Enums.Task; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Enums +namespace EggLink.DanhengServer.Enums; + +public enum MissionPhaseEnum { - public enum MissionPhaseEnum - { - Accept = 0, - Finish = 1, - None = 3, - Cancel = 4, - } - - public static class MissionStatusExtensions - { - public static MissionStatus ToProto(this MissionPhaseEnum status) - { - return status switch - { - MissionPhaseEnum.None => MissionStatus.MissionNone, - MissionPhaseEnum.Accept => MissionStatus.MissionDoing, - MissionPhaseEnum.Finish => MissionStatus.MissionFinish, - MissionPhaseEnum.Cancel => MissionStatus.MissionNone, - _ => MissionStatus.MissionNone, - }; - } - - public static SubMissionStateEnum ToStateEnum(this MissionPhaseEnum status) - { - return status switch - { - MissionPhaseEnum.None => SubMissionStateEnum.Unknow, - MissionPhaseEnum.Accept => SubMissionStateEnum.Started, - MissionPhaseEnum.Finish => SubMissionStateEnum.Finish, - MissionPhaseEnum.Cancel => SubMissionStateEnum.TakenAndNotStarted, - _ => SubMissionStateEnum.Unknow, - }; - } - } + Accept = 0, + Finish = 1, + None = 3, + Cancel = 4 } + +public static class MissionStatusExtensions +{ + public static MissionStatus ToProto(this MissionPhaseEnum status) + { + return status switch + { + MissionPhaseEnum.None => MissionStatus.MissionNone, + MissionPhaseEnum.Accept => MissionStatus.MissionDoing, + MissionPhaseEnum.Finish => MissionStatus.MissionFinish, + MissionPhaseEnum.Cancel => MissionStatus.MissionNone, + _ => MissionStatus.MissionNone + }; + } + + public static SubMissionStateEnum ToStateEnum(this MissionPhaseEnum status) + { + return status switch + { + MissionPhaseEnum.None => SubMissionStateEnum.Unknow, + MissionPhaseEnum.Accept => SubMissionStateEnum.Started, + MissionPhaseEnum.Finish => SubMissionStateEnum.Finish, + MissionPhaseEnum.Cancel => SubMissionStateEnum.TakenAndNotStarted, + _ => SubMissionStateEnum.Unknow + }; + } +} \ No newline at end of file diff --git a/Common/Enums/Mission/MissionTakeTypeEnum.cs b/Common/Enums/Mission/MissionTakeTypeEnum.cs index 4eda47d4..910ec2b4 100644 --- a/Common/Enums/Mission/MissionTakeTypeEnum.cs +++ b/Common/Enums/Mission/MissionTakeTypeEnum.cs @@ -1,22 +1,22 @@ -namespace EggLink.DanhengServer.Enums +namespace EggLink.DanhengServer.Enums; + +public enum MissionTakeTypeEnum { - public enum MissionTakeTypeEnum - { - MultiSequence = 0, - Auto = 1, - PlayerLevel = 2, - WorldLevel = 3, - Manual = 4, - SequenceNextDay = 5, - MuseumPhaseRenewPointReach = 6, - HeliobusPhaseReach = 7, - } - public enum SubMissionTakeTypeEnum - { - Unknown = 0, - AnySequence = 2, - Auto = 1, - CustomValue = 4, - MultiSequence = 3, - } + MultiSequence = 0, + Auto = 1, + PlayerLevel = 2, + WorldLevel = 3, + Manual = 4, + SequenceNextDay = 5, + MuseumPhaseRenewPointReach = 6, + HeliobusPhaseReach = 7 } + +public enum SubMissionTakeTypeEnum +{ + Unknown = 0, + AnySequence = 2, + Auto = 1, + CustomValue = 4, + MultiSequence = 3 +} \ No newline at end of file diff --git a/Common/Enums/Mission/StoryLineConditionTypeEnum.cs b/Common/Enums/Mission/StoryLineConditionTypeEnum.cs index b8323241..50f9e39c 100644 --- a/Common/Enums/Mission/StoryLineConditionTypeEnum.cs +++ b/Common/Enums/Mission/StoryLineConditionTypeEnum.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Mission; -namespace EggLink.DanhengServer.Enums.Mission +public enum StoryLineConditionTypeEnum { - public enum StoryLineConditionTypeEnum - { - FinishSubMission = 1, - } -} + FinishSubMission = 1 +} \ No newline at end of file diff --git a/Common/Enums/OperationEnum.cs b/Common/Enums/OperationEnum.cs index 69f614b2..f5d88682 100644 --- a/Common/Enums/OperationEnum.cs +++ b/Common/Enums/OperationEnum.cs @@ -1,8 +1,7 @@ -namespace EggLink.DanhengServer.Enums +namespace EggLink.DanhengServer.Enums; + +public enum OperationEnum { - public enum OperationEnum - { - And = 0, - Or = 1, - } -} + And = 0, + Or = 1 +} \ No newline at end of file diff --git a/Common/Enums/PlayerStatusEnum.cs b/Common/Enums/PlayerStatusEnum.cs index 47dd61ab..1e19f390 100644 --- a/Common/Enums/PlayerStatusEnum.cs +++ b/Common/Enums/PlayerStatusEnum.cs @@ -1,30 +1,23 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums; -namespace EggLink.DanhengServer.Enums +public enum PlayerStatusEnum { - public enum PlayerStatusEnum - { - Offline = 0, - Explore = 1, - Rogue = 2, - ChessRogue = 3, - ChessRogueNous = 4, - RogueTourn = 5, - Challenge = 6, - ChallengeStory = 7, - ChallengeBoss = 8, - Raid = 9, - StoryLine = 10, - Activity = 11, - } - - public enum PlayerSubStatusEnum - { - None = 0, - Battle = 1 - } + Offline = 0, + Explore = 1, + Rogue = 2, + ChessRogue = 3, + ChessRogueNous = 4, + RogueTourn = 5, + Challenge = 6, + ChallengeStory = 7, + ChallengeBoss = 8, + Raid = 9, + StoryLine = 10, + Activity = 11 } + +public enum PlayerSubStatusEnum +{ + None = 0, + Battle = 1 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/BossDecayEffectTypeEnum.cs b/Common/Enums/Rogue/BossDecayEffectTypeEnum.cs index f2273d33..fe2e281f 100644 --- a/Common/Enums/Rogue/BossDecayEffectTypeEnum.cs +++ b/Common/Enums/Rogue/BossDecayEffectTypeEnum.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Rogue; -namespace EggLink.DanhengServer.Enums.Rogue +public enum BossDecayEffectTypeEnum { - public enum BossDecayEffectTypeEnum - { - None = 0, - AddMazeBuff = 1, - AddMazeBuffList = 2, - RemoveMazeBuffList = 3, - } -} + None = 0, + AddMazeBuff = 1, + AddMazeBuffList = 2, + RemoveMazeBuffList = 3 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/DialogueDynamicParamTypeEnum.cs b/Common/Enums/Rogue/DialogueDynamicParamTypeEnum.cs index 90906ea0..57fd331f 100644 --- a/Common/Enums/Rogue/DialogueDynamicParamTypeEnum.cs +++ b/Common/Enums/Rogue/DialogueDynamicParamTypeEnum.cs @@ -1,15 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Rogue; -namespace EggLink.DanhengServer.Enums.Rogue +public enum DialogueDynamicParamTypeEnum { - public enum DialogueDynamicParamTypeEnum - { - None = 0, - ReplaceAll = 1, - ReplaceOne = 2, - } -} + None = 0, + ReplaceAll = 1, + ReplaceOne = 2 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/DialogueEventCostTypeEnum.cs b/Common/Enums/Rogue/DialogueEventCostTypeEnum.cs index ee779d34..364dc705 100644 --- a/Common/Enums/Rogue/DialogueEventCostTypeEnum.cs +++ b/Common/Enums/Rogue/DialogueEventCostTypeEnum.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Rogue; -namespace EggLink.DanhengServer.Enums.Rogue +public enum DialogueEventCostTypeEnum { - public enum DialogueEventCostTypeEnum - { - None = 0, - CostItemValue = 1, - CostHpCurrentPercent = 2, - CostItemPercent = 3, - CostHpSpToPercent = 4, - } -} + None = 0, + CostItemValue = 1, + CostHpCurrentPercent = 2, + CostItemPercent = 3, + CostHpSpToPercent = 4 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/DialogueEventTypeEnum.cs b/Common/Enums/Rogue/DialogueEventTypeEnum.cs index ca4d1cde..77a33fd3 100644 --- a/Common/Enums/Rogue/DialogueEventTypeEnum.cs +++ b/Common/Enums/Rogue/DialogueEventTypeEnum.cs @@ -1,57 +1,50 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Rogue; -namespace EggLink.DanhengServer.Enums.Rogue +public enum DialogueEventTypeEnum { - public enum DialogueEventTypeEnum - { - None = 0, - GetItem = 1, - TriggerRogueBuffSelect = 2, - TriggerRogueMiracleSelect = 3, - EnhanceRogueBuff = 4, - TriggerRandomEventList = 5, - ChangeLineupData = 6, - TriggerRogueBuffReforge = 8, - GetRogueMiracle = 9, - TriggerDialogueEventList = 10, - GetAllRogueBuffInGroup = 11, - GetAllRogueBuffInGroupAndGetItem = 12, - TriggerBattle = 13, - TriggerRogueMiracleTrade = 14, - RepeatableGamble = 15, - ReplaceRogueBuffKeepLevel = 16, - FinishChessRogue = 17, - GetRogueBuff = 21, - GetChessRogueCheatDice = 18, - SetChessRogueNextStartCellAdventureRoomType = 19, - ChangeChessRogueActionPoint = 20, - ReplaceRogueBuff = 23, - DestroyRogueMiracle = 22, - TriggerRogueBuffDrop = 26, - ChangeRogueMiracleToRogueCoin = 24, - RemoveRogueMiracle = 27, - GetItemByPercent = 25, - RemoveRogueBuff = 28, - TriggerRogueMiracleRepair = 29, - RepairRogueMiracle = 30, - ChangeRogueMiracleToRogueMiracle = 31, - ChangeRogueMiracleToRogueBuff = 32, - GetChessRogueRerollDice = 33, - GetRogueBuffByMiracleCount = 34, - ChangeNousValue = 35, - ReviveAvatar = 36, - TriggerDialogueEventListByCondition = 37, - TriggerRogueMiracleDropWithEvent = 38, - TriggerRogueBuffEnhance = 39, - GetCoinByLoseCoin = 40, - ChangeRogueNpcWeight = 41, - GetDestroyedRogueMiracle = 42, - ChangeDestroyedRogueMiracleToRogueMiracle = 43, - DestroyRogueMiracleThenGetRogueMiracle = 44, - TriggerDestroyedRogueMiracleSelect = 45 - } -} + None = 0, + GetItem = 1, + TriggerRogueBuffSelect = 2, + TriggerRogueMiracleSelect = 3, + EnhanceRogueBuff = 4, + TriggerRandomEventList = 5, + ChangeLineupData = 6, + TriggerRogueBuffReforge = 8, + GetRogueMiracle = 9, + TriggerDialogueEventList = 10, + GetAllRogueBuffInGroup = 11, + GetAllRogueBuffInGroupAndGetItem = 12, + TriggerBattle = 13, + TriggerRogueMiracleTrade = 14, + RepeatableGamble = 15, + ReplaceRogueBuffKeepLevel = 16, + FinishChessRogue = 17, + GetRogueBuff = 21, + GetChessRogueCheatDice = 18, + SetChessRogueNextStartCellAdventureRoomType = 19, + ChangeChessRogueActionPoint = 20, + ReplaceRogueBuff = 23, + DestroyRogueMiracle = 22, + TriggerRogueBuffDrop = 26, + ChangeRogueMiracleToRogueCoin = 24, + RemoveRogueMiracle = 27, + GetItemByPercent = 25, + RemoveRogueBuff = 28, + TriggerRogueMiracleRepair = 29, + RepairRogueMiracle = 30, + ChangeRogueMiracleToRogueMiracle = 31, + ChangeRogueMiracleToRogueBuff = 32, + GetChessRogueRerollDice = 33, + GetRogueBuffByMiracleCount = 34, + ChangeNousValue = 35, + ReviveAvatar = 36, + TriggerDialogueEventListByCondition = 37, + TriggerRogueMiracleDropWithEvent = 38, + TriggerRogueBuffEnhance = 39, + GetCoinByLoseCoin = 40, + ChangeRogueNpcWeight = 41, + GetDestroyedRogueMiracle = 42, + ChangeDestroyedRogueMiracleToRogueMiracle = 43, + DestroyRogueMiracleThenGetRogueMiracle = 44, + TriggerDestroyedRogueMiracleSelect = 45 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/ModifierEffectTypeEnum.cs b/Common/Enums/Rogue/ModifierEffectTypeEnum.cs index 55270fab..8f2c43b2 100644 --- a/Common/Enums/Rogue/ModifierEffectTypeEnum.cs +++ b/Common/Enums/Rogue/ModifierEffectTypeEnum.cs @@ -1,281 +1,280 @@ -namespace EggLink.DanhengServer.Enums.Rogue +namespace EggLink.DanhengServer.Enums.Rogue; + +/// +/// Original Name: ModifierEffectType +/// +public enum ModifierEffectTypeEnum { - /// - /// Original Name: ModifierEffectType - /// - public enum ModifierEffectTypeEnum - { - // Fields - None = 0, - AddMazeBuff = 1, - MoveChessRogueBoard = 2, - MoveCellWinMiracle = 3, - ReRandomSameBlockCell = 4, - TurnToLastCell = 5, - ReRandomAroundCell = 6, - CellVictoryAndToTrap = 7, - SelectAndAddCellMark = 8, - SelectAndToFightCell = 9, - RogueBuffLevelUpOnWin = 10, - ExtraRogueMoney = 11, - ExtraRogueBuff = 12, - DoubleNextMoveCell = 13, - EnsureMoveCellCount = 14, - AddAccumulateMazeBuff = 15, - ExtraMarkAndRandomSwap = 16, - LockMarkCell = 17, - MoveMarkCellUpgradeReward = 18, - SetColCanMove = 19, - SetMarkToRandomCell = 20, - ExtraMoneyAndRandomSwap = 21, - ReplicateAroundCell = 22, - ReplicateLastCell = 23, - ReplicateCellToAround = 24, - AllowMoveToReplicateCell = 25, - ReplicateAllAroundCell = 26, - SetCellTypeAndTakeReward = 27, - ReRandomEmptyCell = 28, - SelectMiracleToEmpty = 29, - SelectBuffToEmpty = 30, - TurnFightCellToEmpty = 31, - TurnEventCellToEmpty = 32, - TrunEmptyToReward = 33, - EnterEmptyGetMoney = 34, - ProtectCellNoCollapse = 35, - SelectCellToProtect = 36, - ProtectCollaspeCell = 37, - GetMoneyByProtectCell = 38, - RandomGenSwarm = 39, - SetBlocktype = 40, - SetMarkType = 41, - ToRandomBlockType = 42, - MoveToSwarmGetBuff = 43, - GetHelpOnEnterCell = 44, - SelectCellGetHelp = 45, - SelectAroundGetHelp = 46, - AddAccumulateHurt = 47, - FertileAeonGain = 48, - EnhanceSeedCell = 49, - SetSpecialType = 50, - BenefitsBySeed = 51, - RandomSetSpecialType = 52, - RandomNeighborSpecialType = 53, - SetNeighborSpecialType = 54, - AddCellMazeBuff = 55, - SelectExceptCellGetHelp = 56, - SetAroundBlockType = 57, - DestroyAeonGain = 58, - AddMazeBuffByBlock = 59, - EnterCellTriggerBuff = 60, - StartBoardRandomSetBlockType = 61, - StartBoardRandomSetSpecialType = 62, - StartBoardRandomSetMarkType = 63, - StartBoardSetMarkType = 64, - StartBoardExpandBoard = 65, - TriggerBuffOnBattleWin = 66, - TriggerMiracleOnBattleWin = 67, - TriggerBuffOnMove = 68, - TriggerMiracleOnMove = 69, - ExtraMoneyOnKillMonster = 70, - ResetActionPointOnMoveByMark = 71, - TriggerRandomMarkOnSetSpecialType = 72, - ProtectSpecialCellAndTriggerMoney = 73, - TriggerMoneyAndDoubleOnCollapse = 74, - TriggerShopRandomFreeOnEnterCell = 75, - AccumulateValue = 76, - SelectCellToEmptyGetBuff = 77, - TrunAroundToEmptyGetBuff = 78, - SelectCellTurnAroundToEmpty = 79, - IncAccumulateValueRate = 80, - GiveupMiracleGetMoney = 81, - ChangeActionPointByRange = 82, - GetActionPointByMoney = 83, - SetBlocktypeWithProbability = 84, - SetSepcialTypeByReplicate = 85, - ReplicateCurCellToSelectCell = 86, - ReplicateSelectCellToAround = 87, - ReRandomCellTypeGetMoney = 88, - SetBlockTypeToAround = 89, - ReplicateSelectCellToRandom = 90, - SetBlockTypeToAroundWithCandidate = 91, - SetBlockTypeWithCandidate = 92, - SwapCellToCurAround = 93, - SetBlockTypeGetMoney = 94, - GetMoneyBySetBlockType = 95, - SetMarkTypeWithCandidate = 96, - TurnBlockTypeTriggerBuff = 97, - SetBlockTypeBySelectMarkCell = 98, - SetMarkCellTypeTakeReward = 99, - ReplicateCurCellToRandom = 100, - SwapMarkCellToAroundGetMoney = 101, - TurnRandomCellBlockType = 102, - SwapRandomCellToCurAround = 103, - SetNearestBlockCanMove = 104, - SetSpecialTypeCanMove = 105, - SetMarkTypeCanMove = 106, - RandomGenMark = 107, - RandomSetMarkType = 108, - RandomSetReplaceMarkType = 109, - RandomGenMarkWithSpecialType = 110, - SetAroundSpecialType = 111, - RandomSetAroundSpecialType = 112, - MoveSetCollapseSpecialType = 113, - MoveSetAroundSpecialType = 114, - TakeRewardBySpecialType = 115, - AddActionPointOnMove = 116, - TriggerBuffOnMoveSameBlock = 117, - GetMoneyOnMoveSpecial = 118, - TriggerBuffOnMoveMark = 119, - RandomGenSpecialTypeOnMoveSpecial = 120, - RandomGenMarkOnMoveMark = 121, - StartBoardGetDiceCheatNum = 122, - ChangeActionPoint = 123, - ChangeActionPointOnMoveSpecial = 124, - TriggerBuffByActionPointOnMove = 125, - ReturnMoneyOnBuyGoods = 126, - GetMoneyOnGetMiracle = 127, - TriggerBuffMiracleOnMoveMark = 128, - ActivateAllBuffSurface = 129, - GetRerollNumOnMove = 130, - SetCellTypeAndAddActionPoint = 131, - GetMoneyActionPointOnAbandonMiracle = 132, - AddActionPointOnGetMiracle = 133, - AddActionPointOnSetCellType = 134, - GetMoneyChangeActionPoint = 135, - ShopDiscountOnTradeCell = 136, - GetMoneyByMiracleCount = 137, - GetMoneyOnSelectCellToTargetType = 138, - GetMoneyOnEnterCell = 139, - SetRandomCellToTargeType = 140, - AddMiracleList = 141, - ChangeSelectCellType = 142, - GetMoneyOnAbandonMiracle = 143, - GetMoneyOnMoveCollapse = 144, - SetMarkOnSelectThenSwap = 145, - AbandonReGetMiracle = 146, - SelectSpecialCellEmptyTriggerBuff = 147, - GetMoneyBySpecialCellCnt = 148, - SelectCellLoseAroundSpecialAndGetMoney = 149, - RandomSetSpecialCellBlockType = 150, - SelectMarkCellToRandomMarkAndTriggerBuff = 151, - TriggerBuffByMarkTypeCnt = 152, - ReRandomMarkAndGenMark = 153, - SelectCellLoseMarkAndGetMoney = 154, - GetMoneyAndTriggerBuffOnMove = 155, - GiveRandomBuffOnMove = 156, - TriggerRogueBuffSelect = 201, - TriggerRogueMiracleSelect = 202, - GetItem = 203, - UpRogueBuffLevel = 204, - RecoverLineup = 205, - TriggerRogueBuffReforge = 206, - GetRogueMiracle = 207, - GetAllRogueBuffInGroup = 208, - TriggerBattle = 209, - ReplaceBlock = 210, - TriggerAreaShuffle = 211, - TriggerMark = 212, - TriggerExtension = 213, - RandomReplaceBlock = 214, - DestroyColList = 215, - ChangeItemRatio = 401, - ChangeCostRatio = 402, - ExtraBuffRandomCount = 403, - ChangeCurrentItemImmediately = 404, - ExtraBuffSelectReduceNumber = 405, - ExtraFreeBuffRoll = 406, - SetSelectBuffLevel = 407, - ChangePropDestructNumber = 408, - AddMazeBuffAfterMonsterKill = 409, - ReviveLineupAvatar = 410, - SetSelectBuffGroupCount = 411, - RepairRandomMiracle = 412, - UpgradeRandomBuff = 413, - ReplaceAllMiracles = 414, - SetBattleWinOnBattleFail = 415, - StartDestructPropExtraMiracle = 416, - ChangeAllRogueAvatarLineupDataByCurrent = 417, - SetSelectBuffRandomEnhance = 418, - StartDestructPropRecord = 419, - ChangePropHitResultRatio = 420, - ChangeItemRatioOnNextRoom = 421, - ChangeRogueShopDiscountRatio = 422, - AddMazeBuffOnEnterCellWithBlockType = 423, - GetItemWithFullHpCountAfterMonsterKill = 424, - SetIsBattleTriggerNoBuffSelect = 425, - MultipleMonsterDropItemRatio = 426, - AddMiracleFromListOnBattleWin = 427, - GetDiceRollNum = 428, - AddCurAeonBuffWithRandomCnt = 429, - ReplaceAllBuffs = 430, - SelectMazeBuffOnSelectAeon = 431, - TurnBlockTypeToTarget = 432, - SetCountByConsumeItem = 433, - StartDestructPropExtraBuff = 434, - GetOrRemoveItemOnEnterRoom = 435, - SetCountByEnterCellType = 436, - StartEnhanceAndRollBuffRecord = 437, - MultipleItemRatio = 438, - AccumulateCoinRecord = 439, - GetItemOnKillMonster = 440, - ModifyAdventureRoomTime = 441, - AdventureRoomExtraGroup = 442, - GetCoinByBlockType = 443, - SetDiceReRollNum = 444, - SetDiceCheatNum = 445, - SetDiceReRollFree = 446, - RoomRepeatedSurfaceUseMiracle = 447, - ModifyBuffTypeCount = 448, - UseMiracleByEnterCellType = 449, - ModifyDiceSurfaceWeightByRarity = 450, - RefreshBuffSelectGuaranteedAeonBuff = 451, - AddCoinOnStart = 501, - AddDiceCheatCntOnStart = 502, - AddCoinGiveupDice = 503, - AddActionPointOnStart = 504, - EnterLeaderCellFullSp = 505, - EnterTopThreeNotLeaderCellLowMonsterHp = 506, - EnterCellAddDiceExtraCnt = 507, - TeachingLevelLatentRule = 601, - RecordInfo = 602, - BoardEvent = 603, - GmMode = 604, - NousTeachingRule = 605, - SetChessRogueNextStartCellAdventureRoomType = 701, - SetChessRogueNextCellAdventureRoomType = 702, - ActivityEndlessGetRogueBuffOnFirstRoom = 801, - ActivityEndlessGetRogueMiracleOnFirstRoom = 802, - ActivityEndlessTriggerSelectBuffOnNextRoom = 803, - ActivityEndlessTriggerSelectMiracleOnNextRoom = 804, - ActivityEndlessMonsterKillSpecialDropBuffSelectRatio = 805, - ActivityEndlessNoBuffSelectAndAddCoin = 806, - ActivityEndlessGetRogueBuffByAeonOnFirstRoom = 807, - ActivityEndlessTriggerSelectBuffOnFinishDialogue = 808, - ActivityEndlessGetItemOnFinishDialogue = 810, - ActivityEndlessShopGuaranteedAeonBuff = 811, - ActivityEndlessFirstSelectGuaranteedAeonBuff = 812, - ActivityEndlessTriggerSelectBuffOnBattleWin = 813, - ChangeCellBlockType = 820, - ForbidRepeatDiceFaceAsBefore = 821, - ReplaceBossBpDecayGroup = 822, - ReplaceBossBpMonsterAndFloorList = 823, - SubActionPointOnStart = 824, - SubExtraActionPointOnNegative = 825, - ChangeCoinOnRerollBuff = 826, - GetRogueMiracleOnEnterLayer = 827, - ChangeRogueCoinOnStart = 828, - ChangeDiceRepeatNumOnStart = 829, - NoBuffSelect = 1000, - ModifyItemOnBattleWin = 1001, - AddItemOnEnterNextRoom = 1002, - ModifyItemOnHitProp = 1003, - AddItemOnBattleWin = 1004, - TriggerSelectBuffOnMonsterKill = 1005, - GetRogueCoinWithNotify = 1006, - AddMazeBuffList = 1007, - RemoveMazeBuffList = 1008, - ModifyBuffShopBuffNum = 1009, - ChangeRogueNpcWeight = 1010, - PassiveIncreasingCounter = 1011, - } -} + // Fields + None = 0, + AddMazeBuff = 1, + MoveChessRogueBoard = 2, + MoveCellWinMiracle = 3, + ReRandomSameBlockCell = 4, + TurnToLastCell = 5, + ReRandomAroundCell = 6, + CellVictoryAndToTrap = 7, + SelectAndAddCellMark = 8, + SelectAndToFightCell = 9, + RogueBuffLevelUpOnWin = 10, + ExtraRogueMoney = 11, + ExtraRogueBuff = 12, + DoubleNextMoveCell = 13, + EnsureMoveCellCount = 14, + AddAccumulateMazeBuff = 15, + ExtraMarkAndRandomSwap = 16, + LockMarkCell = 17, + MoveMarkCellUpgradeReward = 18, + SetColCanMove = 19, + SetMarkToRandomCell = 20, + ExtraMoneyAndRandomSwap = 21, + ReplicateAroundCell = 22, + ReplicateLastCell = 23, + ReplicateCellToAround = 24, + AllowMoveToReplicateCell = 25, + ReplicateAllAroundCell = 26, + SetCellTypeAndTakeReward = 27, + ReRandomEmptyCell = 28, + SelectMiracleToEmpty = 29, + SelectBuffToEmpty = 30, + TurnFightCellToEmpty = 31, + TurnEventCellToEmpty = 32, + TrunEmptyToReward = 33, + EnterEmptyGetMoney = 34, + ProtectCellNoCollapse = 35, + SelectCellToProtect = 36, + ProtectCollaspeCell = 37, + GetMoneyByProtectCell = 38, + RandomGenSwarm = 39, + SetBlocktype = 40, + SetMarkType = 41, + ToRandomBlockType = 42, + MoveToSwarmGetBuff = 43, + GetHelpOnEnterCell = 44, + SelectCellGetHelp = 45, + SelectAroundGetHelp = 46, + AddAccumulateHurt = 47, + FertileAeonGain = 48, + EnhanceSeedCell = 49, + SetSpecialType = 50, + BenefitsBySeed = 51, + RandomSetSpecialType = 52, + RandomNeighborSpecialType = 53, + SetNeighborSpecialType = 54, + AddCellMazeBuff = 55, + SelectExceptCellGetHelp = 56, + SetAroundBlockType = 57, + DestroyAeonGain = 58, + AddMazeBuffByBlock = 59, + EnterCellTriggerBuff = 60, + StartBoardRandomSetBlockType = 61, + StartBoardRandomSetSpecialType = 62, + StartBoardRandomSetMarkType = 63, + StartBoardSetMarkType = 64, + StartBoardExpandBoard = 65, + TriggerBuffOnBattleWin = 66, + TriggerMiracleOnBattleWin = 67, + TriggerBuffOnMove = 68, + TriggerMiracleOnMove = 69, + ExtraMoneyOnKillMonster = 70, + ResetActionPointOnMoveByMark = 71, + TriggerRandomMarkOnSetSpecialType = 72, + ProtectSpecialCellAndTriggerMoney = 73, + TriggerMoneyAndDoubleOnCollapse = 74, + TriggerShopRandomFreeOnEnterCell = 75, + AccumulateValue = 76, + SelectCellToEmptyGetBuff = 77, + TrunAroundToEmptyGetBuff = 78, + SelectCellTurnAroundToEmpty = 79, + IncAccumulateValueRate = 80, + GiveupMiracleGetMoney = 81, + ChangeActionPointByRange = 82, + GetActionPointByMoney = 83, + SetBlocktypeWithProbability = 84, + SetSepcialTypeByReplicate = 85, + ReplicateCurCellToSelectCell = 86, + ReplicateSelectCellToAround = 87, + ReRandomCellTypeGetMoney = 88, + SetBlockTypeToAround = 89, + ReplicateSelectCellToRandom = 90, + SetBlockTypeToAroundWithCandidate = 91, + SetBlockTypeWithCandidate = 92, + SwapCellToCurAround = 93, + SetBlockTypeGetMoney = 94, + GetMoneyBySetBlockType = 95, + SetMarkTypeWithCandidate = 96, + TurnBlockTypeTriggerBuff = 97, + SetBlockTypeBySelectMarkCell = 98, + SetMarkCellTypeTakeReward = 99, + ReplicateCurCellToRandom = 100, + SwapMarkCellToAroundGetMoney = 101, + TurnRandomCellBlockType = 102, + SwapRandomCellToCurAround = 103, + SetNearestBlockCanMove = 104, + SetSpecialTypeCanMove = 105, + SetMarkTypeCanMove = 106, + RandomGenMark = 107, + RandomSetMarkType = 108, + RandomSetReplaceMarkType = 109, + RandomGenMarkWithSpecialType = 110, + SetAroundSpecialType = 111, + RandomSetAroundSpecialType = 112, + MoveSetCollapseSpecialType = 113, + MoveSetAroundSpecialType = 114, + TakeRewardBySpecialType = 115, + AddActionPointOnMove = 116, + TriggerBuffOnMoveSameBlock = 117, + GetMoneyOnMoveSpecial = 118, + TriggerBuffOnMoveMark = 119, + RandomGenSpecialTypeOnMoveSpecial = 120, + RandomGenMarkOnMoveMark = 121, + StartBoardGetDiceCheatNum = 122, + ChangeActionPoint = 123, + ChangeActionPointOnMoveSpecial = 124, + TriggerBuffByActionPointOnMove = 125, + ReturnMoneyOnBuyGoods = 126, + GetMoneyOnGetMiracle = 127, + TriggerBuffMiracleOnMoveMark = 128, + ActivateAllBuffSurface = 129, + GetRerollNumOnMove = 130, + SetCellTypeAndAddActionPoint = 131, + GetMoneyActionPointOnAbandonMiracle = 132, + AddActionPointOnGetMiracle = 133, + AddActionPointOnSetCellType = 134, + GetMoneyChangeActionPoint = 135, + ShopDiscountOnTradeCell = 136, + GetMoneyByMiracleCount = 137, + GetMoneyOnSelectCellToTargetType = 138, + GetMoneyOnEnterCell = 139, + SetRandomCellToTargeType = 140, + AddMiracleList = 141, + ChangeSelectCellType = 142, + GetMoneyOnAbandonMiracle = 143, + GetMoneyOnMoveCollapse = 144, + SetMarkOnSelectThenSwap = 145, + AbandonReGetMiracle = 146, + SelectSpecialCellEmptyTriggerBuff = 147, + GetMoneyBySpecialCellCnt = 148, + SelectCellLoseAroundSpecialAndGetMoney = 149, + RandomSetSpecialCellBlockType = 150, + SelectMarkCellToRandomMarkAndTriggerBuff = 151, + TriggerBuffByMarkTypeCnt = 152, + ReRandomMarkAndGenMark = 153, + SelectCellLoseMarkAndGetMoney = 154, + GetMoneyAndTriggerBuffOnMove = 155, + GiveRandomBuffOnMove = 156, + TriggerRogueBuffSelect = 201, + TriggerRogueMiracleSelect = 202, + GetItem = 203, + UpRogueBuffLevel = 204, + RecoverLineup = 205, + TriggerRogueBuffReforge = 206, + GetRogueMiracle = 207, + GetAllRogueBuffInGroup = 208, + TriggerBattle = 209, + ReplaceBlock = 210, + TriggerAreaShuffle = 211, + TriggerMark = 212, + TriggerExtension = 213, + RandomReplaceBlock = 214, + DestroyColList = 215, + ChangeItemRatio = 401, + ChangeCostRatio = 402, + ExtraBuffRandomCount = 403, + ChangeCurrentItemImmediately = 404, + ExtraBuffSelectReduceNumber = 405, + ExtraFreeBuffRoll = 406, + SetSelectBuffLevel = 407, + ChangePropDestructNumber = 408, + AddMazeBuffAfterMonsterKill = 409, + ReviveLineupAvatar = 410, + SetSelectBuffGroupCount = 411, + RepairRandomMiracle = 412, + UpgradeRandomBuff = 413, + ReplaceAllMiracles = 414, + SetBattleWinOnBattleFail = 415, + StartDestructPropExtraMiracle = 416, + ChangeAllRogueAvatarLineupDataByCurrent = 417, + SetSelectBuffRandomEnhance = 418, + StartDestructPropRecord = 419, + ChangePropHitResultRatio = 420, + ChangeItemRatioOnNextRoom = 421, + ChangeRogueShopDiscountRatio = 422, + AddMazeBuffOnEnterCellWithBlockType = 423, + GetItemWithFullHpCountAfterMonsterKill = 424, + SetIsBattleTriggerNoBuffSelect = 425, + MultipleMonsterDropItemRatio = 426, + AddMiracleFromListOnBattleWin = 427, + GetDiceRollNum = 428, + AddCurAeonBuffWithRandomCnt = 429, + ReplaceAllBuffs = 430, + SelectMazeBuffOnSelectAeon = 431, + TurnBlockTypeToTarget = 432, + SetCountByConsumeItem = 433, + StartDestructPropExtraBuff = 434, + GetOrRemoveItemOnEnterRoom = 435, + SetCountByEnterCellType = 436, + StartEnhanceAndRollBuffRecord = 437, + MultipleItemRatio = 438, + AccumulateCoinRecord = 439, + GetItemOnKillMonster = 440, + ModifyAdventureRoomTime = 441, + AdventureRoomExtraGroup = 442, + GetCoinByBlockType = 443, + SetDiceReRollNum = 444, + SetDiceCheatNum = 445, + SetDiceReRollFree = 446, + RoomRepeatedSurfaceUseMiracle = 447, + ModifyBuffTypeCount = 448, + UseMiracleByEnterCellType = 449, + ModifyDiceSurfaceWeightByRarity = 450, + RefreshBuffSelectGuaranteedAeonBuff = 451, + AddCoinOnStart = 501, + AddDiceCheatCntOnStart = 502, + AddCoinGiveupDice = 503, + AddActionPointOnStart = 504, + EnterLeaderCellFullSp = 505, + EnterTopThreeNotLeaderCellLowMonsterHp = 506, + EnterCellAddDiceExtraCnt = 507, + TeachingLevelLatentRule = 601, + RecordInfo = 602, + BoardEvent = 603, + GmMode = 604, + NousTeachingRule = 605, + SetChessRogueNextStartCellAdventureRoomType = 701, + SetChessRogueNextCellAdventureRoomType = 702, + ActivityEndlessGetRogueBuffOnFirstRoom = 801, + ActivityEndlessGetRogueMiracleOnFirstRoom = 802, + ActivityEndlessTriggerSelectBuffOnNextRoom = 803, + ActivityEndlessTriggerSelectMiracleOnNextRoom = 804, + ActivityEndlessMonsterKillSpecialDropBuffSelectRatio = 805, + ActivityEndlessNoBuffSelectAndAddCoin = 806, + ActivityEndlessGetRogueBuffByAeonOnFirstRoom = 807, + ActivityEndlessTriggerSelectBuffOnFinishDialogue = 808, + ActivityEndlessGetItemOnFinishDialogue = 810, + ActivityEndlessShopGuaranteedAeonBuff = 811, + ActivityEndlessFirstSelectGuaranteedAeonBuff = 812, + ActivityEndlessTriggerSelectBuffOnBattleWin = 813, + ChangeCellBlockType = 820, + ForbidRepeatDiceFaceAsBefore = 821, + ReplaceBossBpDecayGroup = 822, + ReplaceBossBpMonsterAndFloorList = 823, + SubActionPointOnStart = 824, + SubExtraActionPointOnNegative = 825, + ChangeCoinOnRerollBuff = 826, + GetRogueMiracleOnEnterLayer = 827, + ChangeRogueCoinOnStart = 828, + ChangeDiceRepeatNumOnStart = 829, + NoBuffSelect = 1000, + ModifyItemOnBattleWin = 1001, + AddItemOnEnterNextRoom = 1002, + ModifyItemOnHitProp = 1003, + AddItemOnBattleWin = 1004, + TriggerSelectBuffOnMonsterKill = 1005, + GetRogueCoinWithNotify = 1006, + AddMazeBuffList = 1007, + RemoveMazeBuffList = 1008, + ModifyBuffShopBuffNum = 1009, + ChangeRogueNpcWeight = 1010, + PassiveIncreasingCounter = 1011 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/ModifierTriggerTypeEnum.cs b/Common/Enums/Rogue/ModifierTriggerTypeEnum.cs index 7a188b4b..ca12fa14 100644 --- a/Common/Enums/Rogue/ModifierTriggerTypeEnum.cs +++ b/Common/Enums/Rogue/ModifierTriggerTypeEnum.cs @@ -1,12 +1,11 @@ -namespace EggLink.DanhengServer.Enums.Rogue +namespace EggLink.DanhengServer.Enums.Rogue; + +/// +/// Original Name: ModifierTriggerType +/// +public enum ModifierTriggerTypeEnum { - /// - /// Original Name: ModifierTriggerType - /// - public enum ModifierTriggerTypeEnum - { - None = 0, - EnterChessRogueCell = 1, - EnterChessRogueRow = 2, - } -} + None = 0, + EnterChessRogueCell = 1, + EnterChessRogueRow = 2 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/RogueBuffAeonTypeEnum.cs b/Common/Enums/Rogue/RogueBuffAeonTypeEnum.cs index cd82a268..da73532b 100644 --- a/Common/Enums/Rogue/RogueBuffAeonTypeEnum.cs +++ b/Common/Enums/Rogue/RogueBuffAeonTypeEnum.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Rogue; -namespace EggLink.DanhengServer.Enums.Rogue +public enum RogueBuffAeonTypeEnum { - public enum RogueBuffAeonTypeEnum - { - Normal = 0, - BattleEventBuff = 1, - BattleEventBuffEnhance = 2, - BattleEventBuffCross = 3 - } -} + Normal = 0, + BattleEventBuff = 1, + BattleEventBuffEnhance = 2, + BattleEventBuffCross = 3 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/RogueBuffCategoryEnum.cs b/Common/Enums/Rogue/RogueBuffCategoryEnum.cs index d82ef2bb..0067b0e4 100644 --- a/Common/Enums/Rogue/RogueBuffCategoryEnum.cs +++ b/Common/Enums/Rogue/RogueBuffCategoryEnum.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Rogue; -namespace EggLink.DanhengServer.Enums.Rogue +public enum RogueBuffCategoryEnum { - public enum RogueBuffCategoryEnum - { - None = 0, - Common = 1, - Rare = 2, - Legendary = 3, - } -} + None = 0, + Common = 1, + Rare = 2, + Legendary = 3 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/RogueDLCBlockTypeEnum.cs b/Common/Enums/Rogue/RogueDLCBlockTypeEnum.cs index b2177aa4..52c363aa 100644 --- a/Common/Enums/Rogue/RogueDLCBlockTypeEnum.cs +++ b/Common/Enums/Rogue/RogueDLCBlockTypeEnum.cs @@ -1,31 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Rogue; -namespace EggLink.DanhengServer.Enums.Rogue +// Original class: RogueDLCBlockType +public enum RogueDLCBlockTypeEnum { - // Original class: RogueDLCBlockType - public enum RogueDLCBlockTypeEnum - { - // Fields - Empty = 1, - Respite = 2, - MonsterNormal = 3, - MonsterSwarm = 4, - MonsterElite = 5, - Adventure = 6, - Reward = 7, - Event = 8, - SwarmEvent = 9, - Trap = 10, - MonsterBoss = 11, - MonsterSwarmBoss = 12, - Trade = 13, - BlackMarket = 14, - MonsterNousBoss = 15, - NousEvent = 16, - NousSpecialEvent = 17, - } -} + // Fields + Empty = 1, + Respite = 2, + MonsterNormal = 3, + MonsterSwarm = 4, + MonsterElite = 5, + Adventure = 6, + Reward = 7, + Event = 8, + SwarmEvent = 9, + Trap = 10, + MonsterBoss = 11, + MonsterSwarmBoss = 12, + Trade = 13, + BlackMarket = 14, + MonsterNousBoss = 15, + NousEvent = 16, + NousSpecialEvent = 17 +} \ No newline at end of file diff --git a/Common/Enums/Rogue/RogueMiracleEffectTypeEnum.cs b/Common/Enums/Rogue/RogueMiracleEffectTypeEnum.cs index e7e78e70..56903fe1 100644 --- a/Common/Enums/Rogue/RogueMiracleEffectTypeEnum.cs +++ b/Common/Enums/Rogue/RogueMiracleEffectTypeEnum.cs @@ -1,57 +1,50 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Rogue; -namespace EggLink.DanhengServer.Enums.Rogue +public enum RogueMiracleEffectTypeEnum { - public enum RogueMiracleEffectTypeEnum - { - // effects + // effects - None = 0, - ExtraBuffSelect = 1, - ExtraFreeBuffRoll = 2, - SetSelectBuffLevel = 3, - ReviveLineupAvatar = 4, - GetMiracle = 5, - GetRogueBuff = 6, - SetSelectBuffGroup = 7, - AddMazeBuff = 8, - ChangeItemRatio = 9, - ChangeItemNum = 10, - ChangeCostRatio = 11, - ChangeLineupInfo = 12, - RepairRandomMiracle = 13, - EnhanceRandomBuff = 14, - ReplaceAllMiracles = 15, - DoAllEffects = 16, - DoRandomEffect = 17, - DestroyMiracle = 18, - CostDurability = 19, - GetRogueBuffByAeon = 20, - ChangeItemNumByArg = 21, - ChangeItemRatioAndSetVar = 22, + None = 0, + ExtraBuffSelect = 1, + ExtraFreeBuffRoll = 2, + SetSelectBuffLevel = 3, + ReviveLineupAvatar = 4, + GetMiracle = 5, + GetRogueBuff = 6, + SetSelectBuffGroup = 7, + AddMazeBuff = 8, + ChangeItemRatio = 9, + ChangeItemNum = 10, + ChangeCostRatio = 11, + ChangeLineupInfo = 12, + RepairRandomMiracle = 13, + EnhanceRandomBuff = 14, + ReplaceAllMiracles = 15, + DoAllEffects = 16, + DoRandomEffect = 17, + DestroyMiracle = 18, + CostDurability = 19, + GetRogueBuffByAeon = 20, + ChangeItemNumByArg = 21, + ChangeItemRatioAndSetVar = 22, - // events + // events - OnGetMiracle = 100, - OnBattleStart = 101, - OnBattleEnd = 102, - OnEnterNextRoom = 103, - OnDestroy = 104, - OnGainMoney = 105, - OnDestroyProp = 106, - OnGenerateBuffMenu = 107, + OnGetMiracle = 100, + OnBattleStart = 101, + OnBattleEnd = 102, + OnEnterNextRoom = 103, + OnDestroy = 104, + OnGainMoney = 105, + OnDestroyProp = 106, + OnGenerateBuffMenu = 107, - // arguments + // arguments - CurMoney = 200, - CurDestroyCount = 201, - CurBrokenMiracleCount = 202, - AvatarWithLeastHP = 203, - UseMoney = 204, - BuffTypeNum = 205, - } -} + CurMoney = 200, + CurDestroyCount = 201, + CurBrokenMiracleCount = 202, + AvatarWithLeastHP = 203, + UseMoney = 204, + BuffTypeNum = 205 +} \ No newline at end of file diff --git a/Common/Enums/Scene/GroupCategoryEnum.cs b/Common/Enums/Scene/GroupCategoryEnum.cs index ca2205af..1a92ef52 100644 --- a/Common/Enums/Scene/GroupCategoryEnum.cs +++ b/Common/Enums/Scene/GroupCategoryEnum.cs @@ -1,12 +1,11 @@ -namespace EggLink.DanhengServer.Enums.Scene +namespace EggLink.DanhengServer.Enums.Scene; + +public enum GroupCategoryEnum { - public enum GroupCategoryEnum - { - Normal = 0, - Mission = 1, - BattleProps = 2, - Custom = 3, - System = 4, - Atmosphere = 5, - } -} + Normal = 0, + Mission = 1, + BattleProps = 2, + Custom = 3, + System = 4, + Atmosphere = 5 +} \ No newline at end of file diff --git a/Common/Enums/Scene/GroupLoadSideEnum.cs b/Common/Enums/Scene/GroupLoadSideEnum.cs index 0c10f7ec..1d138327 100644 --- a/Common/Enums/Scene/GroupLoadSideEnum.cs +++ b/Common/Enums/Scene/GroupLoadSideEnum.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Scene; -namespace EggLink.DanhengServer.Enums.Scene +public enum GroupLoadSideEnum { - public enum GroupLoadSideEnum - { - Client = 0, - Server = 1, - } -} + Client = 0, + Server = 1 +} \ No newline at end of file diff --git a/Common/Enums/Scene/MonsterRankEnum.cs b/Common/Enums/Scene/MonsterRankEnum.cs index ef27eec7..793b0cdd 100644 --- a/Common/Enums/Scene/MonsterRankEnum.cs +++ b/Common/Enums/Scene/MonsterRankEnum.cs @@ -1,18 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Scene; -namespace EggLink.DanhengServer.Enums.Scene +public enum MonsterRankEnum { - public enum MonsterRankEnum - { - Unknown = 0, - Minion = 1, - MinionLv2 = 2, - Elite = 3, - LittleBoss = 4, - BigBoss = 5, - } -} + Unknown = 0, + Minion = 1, + MinionLv2 = 2, + Elite = 3, + LittleBoss = 4, + BigBoss = 5 +} \ No newline at end of file diff --git a/Common/Enums/Scene/PlaneTypeEnum.cs b/Common/Enums/Scene/PlaneTypeEnum.cs index c30b7a0e..20698767 100644 --- a/Common/Enums/Scene/PlaneTypeEnum.cs +++ b/Common/Enums/Scene/PlaneTypeEnum.cs @@ -1,21 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Scene; -namespace EggLink.DanhengServer.Enums.Scene +public enum PlaneTypeEnum { - public enum PlaneTypeEnum - { - Unknown = 0, - Town = 1, - Maze = 2, - Train = 3, - Challenge = 4, - Rogue = 5, - Raid = 8, - AetherDivide = 15, - TrialActivity = 14 - } -} + Unknown = 0, + Town = 1, + Maze = 2, + Train = 3, + Challenge = 4, + Rogue = 5, + Raid = 8, + AetherDivide = 15, + TrialActivity = 14 +} \ No newline at end of file diff --git a/Common/Enums/Scene/PropStateEnum.cs b/Common/Enums/Scene/PropStateEnum.cs index 0aedd65c..b2ceb1e4 100644 --- a/Common/Enums/Scene/PropStateEnum.cs +++ b/Common/Enums/Scene/PropStateEnum.cs @@ -1,41 +1,40 @@ -namespace EggLink.DanhengServer.Enums.Scene +namespace EggLink.DanhengServer.Enums.Scene; + +public enum PropStateEnum { - public enum PropStateEnum - { - Closed = 0, - Open = 1, - Locked = 2, - BridgeState1 = 3, - BridgeState2 = 4, - BridgeState3 = 5, - BridgeState4 = 6, - CheckPointDisable = 7, - CheckPointEnable = 8, - TriggerDisable = 9, - TriggerEnable = 10, - ChestLocked = 11, - ChestClosed = 12, - ChestUsed = 13, - Elevator1 = 14, - Elevator2 = 15, - Elevator3 = 16, - WaitActive = 17, - EventClose = 18, - EventOpen = 19, - Hidden = 20, - TeleportGate0 = 21, - TeleportGate1 = 22, - TeleportGate2 = 23, - TeleportGate3 = 24, - Destructed = 25, - CustomState01 = 101, - CustomState02 = 102, - CustomState03 = 103, - CustomState04 = 104, - CustomState05 = 105, - CustomState06 = 106, - CustomState07 = 107, - CustomState08 = 108, - CustomState09 = 109 - } -} + Closed = 0, + Open = 1, + Locked = 2, + BridgeState1 = 3, + BridgeState2 = 4, + BridgeState3 = 5, + BridgeState4 = 6, + CheckPointDisable = 7, + CheckPointEnable = 8, + TriggerDisable = 9, + TriggerEnable = 10, + ChestLocked = 11, + ChestClosed = 12, + ChestUsed = 13, + Elevator1 = 14, + Elevator2 = 15, + Elevator3 = 16, + WaitActive = 17, + EventClose = 18, + EventOpen = 19, + Hidden = 20, + TeleportGate0 = 21, + TeleportGate1 = 22, + TeleportGate2 = 23, + TeleportGate3 = 24, + Destructed = 25, + CustomState01 = 101, + CustomState02 = 102, + CustomState03 = 103, + CustomState04 = 104, + CustomState05 = 105, + CustomState06 = 106, + CustomState07 = 107, + CustomState08 = 108, + CustomState09 = 109 +} \ No newline at end of file diff --git a/Common/Enums/Scene/PropTypeEnum.cs b/Common/Enums/Scene/PropTypeEnum.cs index 5e8141c0..1545822d 100644 --- a/Common/Enums/Scene/PropTypeEnum.cs +++ b/Common/Enums/Scene/PropTypeEnum.cs @@ -1,36 +1,35 @@ -namespace EggLink.DanhengServer.Enums.Scene +namespace EggLink.DanhengServer.Enums.Scene; + +public enum PropTypeEnum { - public enum PropTypeEnum - { - PROP_NONE = 0, - PROP_ORDINARY = 1, - PROP_SUMMON = 2, - PROP_DESTRUCT = 3, - PROP_SPRING = 4, - PROP_PLATFORM = 5, - PROP_TREASURE_CHEST = 6, - PROP_MATERIAL_ZONE = 7, - PROP_COCOON = 8, - PROP_MAPPINGINFO = 9, - PROP_PUZZLES = 10, - PROP_ELEVATOR = 11, - PROP_NO_REWARD_DESTRUCT = 12, - PROP_LIGHT = 13, - PROP_ROGUE_DOOR = 14, - PROP_ROGUE_OBJECT = 15, - PROP_ROGUE_CHEST = 16, - PROP_TELEVISION = 17, - PROP_RELIC = 18, - PROP_ELEMENT = 19, - PROP_ROGUE_HIDDEN_DOOR = 20, - PROP_PERSPECTIVE_WALL = 21, - PROP_MAZE_PUZZLE = 22, - PROP_MAZE_DECAL = 23, - PROP_ROGUE_REWARD_OBJECT = 24, - PROP_MAP_ROTATION_CHARGER = 25, - PROP_MAP_ROTATION_VOLUME = 26, - PROP_MAP_ROTATION_SWITCHER = 27, - PROP_BOXMAN_BINDED = 28, - PROP_MAZE_JIGSAW = 29, - } -} + PROP_NONE = 0, + PROP_ORDINARY = 1, + PROP_SUMMON = 2, + PROP_DESTRUCT = 3, + PROP_SPRING = 4, + PROP_PLATFORM = 5, + PROP_TREASURE_CHEST = 6, + PROP_MATERIAL_ZONE = 7, + PROP_COCOON = 8, + PROP_MAPPINGINFO = 9, + PROP_PUZZLES = 10, + PROP_ELEVATOR = 11, + PROP_NO_REWARD_DESTRUCT = 12, + PROP_LIGHT = 13, + PROP_ROGUE_DOOR = 14, + PROP_ROGUE_OBJECT = 15, + PROP_ROGUE_CHEST = 16, + PROP_TELEVISION = 17, + PROP_RELIC = 18, + PROP_ELEMENT = 19, + PROP_ROGUE_HIDDEN_DOOR = 20, + PROP_PERSPECTIVE_WALL = 21, + PROP_MAZE_PUZZLE = 22, + PROP_MAZE_DECAL = 23, + PROP_ROGUE_REWARD_OBJECT = 24, + PROP_MAP_ROTATION_CHARGER = 25, + PROP_MAP_ROTATION_VOLUME = 26, + PROP_MAP_ROTATION_SWITCHER = 27, + PROP_BOXMAN_BINDED = 28, + PROP_MAZE_JIGSAW = 29 +} \ No newline at end of file diff --git a/Common/Enums/Scene/RaidTeamTypeEnum.cs b/Common/Enums/Scene/RaidTeamTypeEnum.cs index 7c04afdd..f12c3cbd 100644 --- a/Common/Enums/Scene/RaidTeamTypeEnum.cs +++ b/Common/Enums/Scene/RaidTeamTypeEnum.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Enums.Scene; -namespace EggLink.DanhengServer.Enums.Scene +public enum RaidTeamTypeEnum { - public enum RaidTeamTypeEnum - { - None, - Player, - TrialOnly, - TrialAndPlayer, - TrialOrPlayer - } -} + None, + Player, + TrialOnly, + TrialAndPlayer, + TrialOrPlayer +} \ No newline at end of file diff --git a/Common/Enums/Scene/SaveTypeEnum.cs b/Common/Enums/Scene/SaveTypeEnum.cs index 102232b8..f356261d 100644 --- a/Common/Enums/Scene/SaveTypeEnum.cs +++ b/Common/Enums/Scene/SaveTypeEnum.cs @@ -1,10 +1,9 @@ -namespace EggLink.DanhengServer.Enums.Scene +namespace EggLink.DanhengServer.Enums.Scene; + +public enum SaveTypeEnum { - public enum SaveTypeEnum - { - Save = 0, - Reset = 1, - Temporary = 2, - Permanent = 3, - } -} + Save = 0, + Reset = 1, + Temporary = 2, + Permanent = 3 +} \ No newline at end of file diff --git a/Common/Enums/SessionStateEnum.cs b/Common/Enums/SessionStateEnum.cs index 258ca5e4..bbf87989 100644 --- a/Common/Enums/SessionStateEnum.cs +++ b/Common/Enums/SessionStateEnum.cs @@ -1,11 +1,10 @@ -namespace EggLink.DanhengServer.Common.Enums +namespace EggLink.DanhengServer.Common.Enums; + +public enum SessionStateEnum { - public enum SessionStateEnum - { - INACTIVE, - WAITING_FOR_TOKEN, - WAITING_FOR_LOGIN, - PICKING_CHARACTER, - ACTIVE - } -} + INACTIVE, + WAITING_FOR_TOKEN, + WAITING_FOR_LOGIN, + PICKING_CHARACTER, + ACTIVE +} \ No newline at end of file diff --git a/Common/Enums/Task/CompareTypeEnum.cs b/Common/Enums/Task/CompareTypeEnum.cs index 80f2bda2..1de343e8 100644 --- a/Common/Enums/Task/CompareTypeEnum.cs +++ b/Common/Enums/Task/CompareTypeEnum.cs @@ -1,13 +1,12 @@ -namespace EggLink.DanhengServer.Enums.Task +namespace EggLink.DanhengServer.Enums.Task; + +public enum CompareTypeEnum { - public enum CompareTypeEnum - { - Unknow = 0, - Greater = 1, - GreaterEqual = 2, - NotEqual = 3, - Equal = 4, - LessEqual = 5, - Less = 6, - } -} + Unknow = 0, + Greater = 1, + GreaterEqual = 2, + NotEqual = 3, + Equal = 4, + LessEqual = 5, + Less = 6 +} \ No newline at end of file diff --git a/Common/Enums/Task/ELevelPerformanceTypeEnum.cs b/Common/Enums/Task/ELevelPerformanceTypeEnum.cs index eb416588..587f34f3 100644 --- a/Common/Enums/Task/ELevelPerformanceTypeEnum.cs +++ b/Common/Enums/Task/ELevelPerformanceTypeEnum.cs @@ -1,12 +1,11 @@ -namespace EggLink.DanhengServer.Enums.Task +namespace EggLink.DanhengServer.Enums.Task; + +public enum ELevelPerformanceTypeEnum { - public enum ELevelPerformanceTypeEnum - { - Unknown = 0, - A = 1, - C = 2, - D = 3, - E = 4, - PlayVideo = 10, - } -} + Unknown = 0, + A = 1, + C = 2, + D = 3, + E = 4, + PlayVideo = 10 +} \ No newline at end of file diff --git a/Common/Enums/Task/SubMissionStateEnum.cs b/Common/Enums/Task/SubMissionStateEnum.cs index 743779e3..bbe92309 100644 --- a/Common/Enums/Task/SubMissionStateEnum.cs +++ b/Common/Enums/Task/SubMissionStateEnum.cs @@ -1,10 +1,9 @@ -namespace EggLink.DanhengServer.Enums.Task +namespace EggLink.DanhengServer.Enums.Task; + +public enum SubMissionStateEnum { - public enum SubMissionStateEnum - { - Unknow = 0, - Started = 1, - Finish = 2, - TakenAndNotStarted = 3 - } -} + Unknow = 0, + Started = 1, + Finish = 2, + TakenAndNotStarted = 3 +} \ No newline at end of file diff --git a/Common/Enums/Task/TargetFetchAdvPropFetchTypeEnum.cs b/Common/Enums/Task/TargetFetchAdvPropFetchTypeEnum.cs index 3142199d..b8920277 100644 --- a/Common/Enums/Task/TargetFetchAdvPropFetchTypeEnum.cs +++ b/Common/Enums/Task/TargetFetchAdvPropFetchTypeEnum.cs @@ -1,15 +1,14 @@ -namespace EggLink.DanhengServer.Enums.Task +namespace EggLink.DanhengServer.Enums.Task; + +public enum TargetFetchAdvPropFetchTypeEnum { - public enum TargetFetchAdvPropFetchTypeEnum - { - Owner = 0, - SinglePropByPropKey = 1, - SinglePropByPropID = 2, - SinglePropByUniqueName = 3, - MultiPropByPropKey = 4, - MultiPropByPropID = 5, - MultiPropByUniqueName = 6, - MultiPropByGroup = 7, - SinglePropByOwnerGroupAndID = 8, - } -} + Owner = 0, + SinglePropByPropKey = 1, + SinglePropByPropID = 2, + SinglePropByUniqueName = 3, + MultiPropByPropKey = 4, + MultiPropByPropID = 5, + MultiPropByUniqueName = 6, + MultiPropByGroup = 7, + SinglePropByOwnerGroupAndID = 8 +} \ No newline at end of file diff --git a/Common/Internationalization/I18nManager.cs b/Common/Internationalization/I18nManager.cs index 3da1a48d..8478c168 100644 --- a/Common/Internationalization/I18nManager.cs +++ b/Common/Internationalization/I18nManager.cs @@ -1,62 +1,54 @@ using EggLink.DanhengServer.Internationalization.Message; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Internationalization +namespace EggLink.DanhengServer.Internationalization; + +public static class I18nManager { - public static class I18nManager + public static Logger Logger = new("I18nManager"); + + public static object Language { get; set; } = new LanguageEN(); + + public static void LoadLanguage() { - public static Logger Logger = new("I18nManager"); - - public static object Language { get; set; } = new LanguageEN(); - - public static void LoadLanguage() + var languageStr = "EggLink.DanhengServer.Internationalization.Message.Language" + + ConfigManager.Config.ServerOption.Language; + var languageType = Type.GetType(languageStr); + if (languageType == null) { - var languageStr = "EggLink.DanhengServer.Internationalization.Message.Language" + ConfigManager.Config.ServerOption.Language; - var languageType = Type.GetType(languageStr); - if (languageType == null) - { - Logger.Error("Language not found, fallback to EN"); - // fallback to English - languageType = Type.GetType("EggLink.DanhengServer.Internationalization.Message.LanguageEN")!; - } - var language = Activator.CreateInstance(languageType) ?? throw new Exception("Language not found"); - Language = language; - - Logger.Info(Translate("Server.ServerInfo.LoadedItem", Translate("Word.Language"))); + Logger.Error("Language not found, fallback to EN"); + // fallback to English + languageType = Type.GetType("EggLink.DanhengServer.Internationalization.Message.LanguageEN")!; } - public static string Translate(string key, params string[] args) - { - var value = GetNestedPropertyValue(Language, key); + var language = Activator.CreateInstance(languageType) ?? throw new Exception("Language not found"); + Language = language; - foreach (var arg in args) - { - value = value.Replace("{" + args.ToList().IndexOf(arg) + "}", arg); - } - return value; - } - - - public static string GetNestedPropertyValue(object? obj, string propertyName) - { - foreach (string part in propertyName.Split('.')) - { - if (obj == null) return propertyName; - - Type type = obj.GetType(); - PropertyInfo? property = type.GetProperty(part); - if (property == null) return propertyName; - - obj = property.GetValue(obj, null); - } - - return (string)(obj ?? propertyName); - } + Logger.Info(Translate("Server.ServerInfo.LoadedItem", Translate("Word.Language"))); } -} + + public static string Translate(string key, params string[] args) + { + var value = GetNestedPropertyValue(Language, key); + + foreach (var arg in args) value = value.Replace("{" + args.ToList().IndexOf(arg) + "}", arg); + return value; + } + + + public static string GetNestedPropertyValue(object? obj, string propertyName) + { + foreach (var part in propertyName.Split('.')) + { + if (obj == null) return propertyName; + + var type = obj.GetType(); + var property = type.GetProperty(part); + if (property == null) return propertyName; + + obj = property.GetValue(obj, null); + } + + return (string)(obj ?? propertyName); + } +} \ No newline at end of file diff --git a/Common/Internationalization/Message/LanguageCHS.cs b/Common/Internationalization/Message/LanguageCHS.cs index c7e2b8cd..3f8cafc3 100644 --- a/Common/Internationalization/Message/LanguageCHS.cs +++ b/Common/Internationalization/Message/LanguageCHS.cs @@ -1,396 +1,413 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Internationalization.Message; -namespace EggLink.DanhengServer.Internationalization.Message +#region Root + +public class LanguageCHS { - #region Root - - public class LanguageCHS - { - public GameTextCHS Game { get; } = new(); - public ServerTextCHS Server { get; } = new(); - public WordTextCHS Word { get; } = new(); // a placeholder for the actual word text - } - - #endregion - - #region Layer 1 - - /// - /// path: Game - /// - public class GameTextCHS - { - public CommandTextCHS Command { get; } = new(); - } - - /// - /// path: Server - /// - public class ServerTextCHS - { - public WebTextCHS Web { get; } = new(); - public ServerInfoTextCHS ServerInfo { get; } = new(); - } - - /// - /// path: Word - /// - public class WordTextCHS - { - public string Rank { get; } = "星魂"; - public string Avatar { get; } = "角色"; - public string Material { get; } = "材料"; - public string Relic { get; } = "遗器"; - public string Equipment { get; } = "光锥"; - public string Talent { get; } = "行迹"; - public string Banner { get; } = "卡池"; - public string Activity { get; } = "活动"; - public string Buff { get; } = "祝福"; - public string Miracle { get; } = "奇物"; - public string Unlock { get; } = "奢侈品"; - - // server info - public string Config { get; } = "配置文件"; - public string Language { get; } = "语言"; - public string Log { get; } = "日志"; - public string GameData { get; } = "游戏数据"; - public string Database { get; } = "数据库"; - public string Command { get; } = "命令"; - public string WebServer { get; } = "Web服务器"; - public string Plugin { get; } = "插件"; - public string Handler { get; } = "包处理器"; - public string Dispatch { get; } = "全局分发"; - public string Game { get; } = "游戏"; - public string Handbook { get; } = "手册"; - public string NotFound { get; } = "未找到"; - public string Error { get; } = "错误"; - public string FloorInfo { get; } = "区域文件"; - public string FloorGroupInfo { get; } = "区域组文件"; - public string FloorMissingResult { get; } = "传送与世界生成"; - public string FloorGroupMissingResult { get; } = "传送、怪物战斗与世界生成"; - public string Mission { get; } = "任务"; - public string MissionInfo { get; } = "任务文件"; - public string SubMission { get; } = "子任务"; - public string SubMissionInfo { get; } = "子任务文件"; - public string MazeSkill { get; } = "角色秘技"; - public string MazeSkillInfo { get; } = "角色秘技文件"; - public string Dialogue { get; } = "模拟宇宙事件"; - public string DialogueInfo { get; } = "模拟宇宙事件文件"; - public string Performance { get; } = "剧情操作"; - public string PerformanceInfo { get; } = "剧情操作文件"; - public string RogueChestMap { get; } = "模拟宇宙地图"; - public string RogueChestMapInfo { get; } = "模拟宇宙地图文件"; - public string ChessRogueRoom { get; } = "模拟宇宙DLC"; - public string ChessRogueRoomInfo { get; } = "模拟宇宙DLC文件"; - } - - #endregion - - #region Layer 2 - - #region GameText - - /// - /// path: Game.Command - /// - public class CommandTextCHS - { - public NoticeTextCHS Notice { get; } = new(); - - public HeroTextCHS Hero { get; } = new(); - public AvatarTextCHS Avatar { get; } = new(); - public GiveTextCHS Give { get; } = new(); - public GiveAllTextCHS GiveAll { get; } = new(); - public LineupTextCHS Lineup { get; } = new(); - public HelpTextCHS Help { get; } = new(); - public KickTextCHS Kick { get; } = new(); - public MissionTextCHS Mission { get; } = new(); - public RelicTextCHS Relic { get; } = new(); - public ReloadTextCHS Reload { get; } = new(); - public RogueTextCHS Rogue { get; } = new(); - public SceneTextCHS Scene { get; } = new(); - public UnlockAllTextCHS UnlockAll { get; } = new(); - public MailTextCHS Mail { get; } = new(); - public RaidTextCHS Raid { get; } = new(); - public AccountTextCHS Account { get; } = new(); - } - - #endregion - - #region ServerText - - /// - /// path: Server.Web - /// - public class WebTextCHS - { - } - - /// - /// path: Server.ServerInfo - /// - public class ServerInfoTextCHS - { - public string Shutdown { get; } = "关闭中…"; - public string CancelKeyPressed { get; } = "已按下取消键 (Ctrl + C),服务器即将关闭…"; - public string StartingServer { get; } = "正在启动 DanhengServer…"; - public string LoadingItem { get; } = "正在加载 {0}…"; - public string RegisterItem { get; } = "注册了 {0} 个 {1}。"; - public string FailedToLoadItem { get; } = "加载 {0} 失败。"; - public string FailedToInitializeItem { get; } = "初始化 {0} 失败。"; - public string FailedToReadItem { get; } = "读取 {0} 失败,文件{1}"; - public string GeneratedItem { get; } = "已生成 {0}。"; - public string LoadedItem { get; } = "已加载 {0}。"; - public string LoadedItems { get; } = "已加载 {0} 个 {1}。"; - public string ServerRunning { get; } = "{0} 服务器正在监听 {1}"; - public string ServerStarted { get; } = "启动完成!用时 {0}s,击败了99%的用户,输入 ‘help’ 来获取命令帮助"; // 玩梗,考虑英语版本将其本土化 - public string MissionEnabled { get; } = "任务系统已启用,此功能仍在开发中,且可能不会按预期工作,如果遇见任何bug,请汇报给开发者。"; - - public string ConfigMissing { get; } = "{0} 缺失,请检查你的资源文件夹:{1},{2} 可能不能使用。"; - public string UnloadedItems { get; } = "卸载了所有 {0}。"; - public string SaveDatabase { get; } = "已保存数据库,用时 {0}s"; - } - - #endregion - - #endregion - - #region Layer 3 - - #region CommandText - - /// - /// path: Game.Command.Notice - /// - public class NoticeTextCHS - { - public string PlayerNotFound { get; } = "未找到玩家!"; - public string InvalidArguments { get; } = "无效的参数!"; - public string NoPermission { get; } = "你没有权限这么做!"; - public string CommandNotFound { get; } = "未找到命令! 输入 '/help' 来获取帮助"; - public string TargetOffline { get; } = "目标 {0}({1}) 离线了!清除当前目标"; - public string TargetFound { get; } = "找到目标 {0}({1}),下一次命令将默认对其执行"; - public string TargetNotFound { get; } = "未找到目标 {0}!"; - public string InternalError { get; } = "在处理命令时发生了内部错误!"; - } - - /// - /// path: Game.Command.Hero - /// - public class HeroTextCHS - { - public string Desc { get; } = "切换主角的性别/形态\n当切换性别时,genderId为1代表男性,2代表女性\n当切换形态时,8001代表毁灭命途,8003代表存护命途,8005代表同谐命途。\n注意,切换性别时会清空所有可选命途以及行迹,为不可逆操作!"; - public string Usage { get; } = "用法:/hero gender [genderId]\n\n用法:/hero type [typeId]"; - public string GenderNotSpecified { get; } = "性别不存在!"; - public string HeroTypeNotSpecified { get; } = "主角类型不存在!"; - public string GenderChanged { get; } = "性别已更改!"; - public string HeroTypeChanged { get; } = "主角类型已更改!"; - } - - /// - /// path: Game.Command.UnlockAll - /// - public class UnlockAllTextCHS - { - public string Desc { get; } = "解锁所有在类别内的对象\n" + - "使用 /unlockall mission 以完成所有任务,使用后会被踢出,重新登录后可能会被教程卡住,请谨慎使用"; - public string Usage { get; } = "用法:/unlockall mission"; - public string AllMissionsUnlocked { get; } = "所有任务已解锁!"; - } - - /// - /// path: Game.Command.Avatar - /// - public class AvatarTextCHS - { - public string Desc { get; } = "设定玩家已有角色的属性\n设置行迹等级时,设置X级即设置所有行迹节点至X级,若大于此节点允许的最高等级,设置为最高等级\n注意:-1意为所有已拥有角色"; - public string Usage { get; } = "用法:/avatar talent [角色ID/-1] [行迹等级]\n\n用法:/avatar get [角色ID]\n\n用法:/avatar rank [角色ID/-1] [星魂]\n\n用法:/avatar level [角色ID/-1] [角色等级]"; - public string InvalidLevel { get; } = "{0}等级无效"; - public string AllAvatarsLevelSet { get; } = "已将全部角色 {0}等级设置为 {1}"; - public string AvatarLevelSet { get; } = "已将 {0} 角色 {1}等级设置为 {2}"; - public string AvatarNotFound { get; } = "角色不存在!"; - public string AvatarGet { get; } = "获取到角色 {0}!"; - public string AvatarFailedGet { get; } = "获取角色 {0} 失败!"; - } - - /// - /// path: Game.Command.Give - /// - public class GiveTextCHS - { - public string Desc { get; } = "给予玩家物品,此处可输入角色ID,但无法设置行迹、等级及星魂"; - public string Usage { get; } = "用法:/give <物品ID> l<等级> x<数量> r<叠影>"; - public string ItemNotFound { get; } = "未找到物品!"; - public string GiveItem { get; } = "给予 @{0} {1} 个物品 {2}"; - } - - /// - /// path: Game.Command.GiveAll - /// - public class GiveAllTextCHS - { - public string Desc { get; } = "给予玩家全部指定类型的物品\navatar意为角色,equipment意为光锥,relic意为遗器,unlock意为气泡、手机壁纸、头像"; - public string Usage { get; } = "用法:/giveall avatar r<星魂> l<等级>\n\n用法:/giveall equipment r<叠影> l<等级> x<数量>\n\n用法:/giveall relic l<等级> x<数量>\n\n用法:/giveall unlock"; - public string GiveAllItems { get; } = "已给予所有 {0}, 各 {1} 个"; - } - - /// - /// path: Game.Command.Lineup - /// - public class LineupTextCHS - { - public string Desc { get; } = "管理玩家的队伍\n秘技点一次性只能获得两个"; - public string Usage { get; } = "用法:/lineup mp [秘技点数量]\n\n用法:/lineup heal"; - public string PlayerGainedMp { get; } = "玩家已获得 {0} 秘技点"; - public string HealedAllAvatars { get; } = "成功治愈当前队伍中的所有角色"; - } - - /// - /// path: Game.Command.Help - /// - public class HelpTextCHS - { - public string Desc { get; } = "显示帮助信息"; - public string Usage { get; } = "用法:/help"; - public string Commands { get; } = "命令:"; - public string CommandPermission { get; } = "所需权限: "; - } - - /// - /// path: Game.Command.Kick - /// - public class KickTextCHS - { - public string Desc { get; } = "踢出玩家"; - public string Usage { get; } = "用法:/kick"; - public string PlayerKicked { get; } = "玩家 {0} 已被踢出!"; - } - - /// - /// path: Game.Command.Mission - /// - public class MissionTextCHS - { - public string Desc { get; } = "管理玩家的任务\n" + - "使用 pass 完成当前正在进行的所有任务,此命令易造成严重卡顿,请尽量使用 /mission finish 替代\n" + - "使用 running 获取正在进行的任务以及可能卡住的任务,使用后可能会出现较长任务列表,请注意甄别\n" + - "使用 reaccept 可重新进行指定主任务,请浏览 handbook 来获取主任务ID"; - public string Usage { get; } = "用法:/mission pass\n\n用法:/mission finish [子任务ID]\n\n用法:/mission running\n\n用法:/mission reaccept [主任务ID]"; - public string AllMissionsFinished { get; } = "所有任务已完成!"; - public string AllRunningMissionsFinished { get; } = "共 {0} 个进行中的任务已完成!"; - public string MissionFinished { get; } = "任务 {0} 已完成!"; - public string InvalidMissionId { get; } = "无效的任务ID!"; - public string NoRunningMissions { get; } = "没有正在进行的任务!"; - - public string RunningMissions { get; } = "正在进行的任务:"; - public string PossibleStuckMissions { get; } = "可能卡住的任务:"; - public string MainMission { get; } = "主任务"; - - public string MissionReAccepted { get; } = "重新接受任务 {0}!"; - } - - /// - /// path: Game.Command.Relic - /// - public class RelicTextCHS - { - public string Desc { get; } = "管理玩家的遗器\n主词条可选,副词条可选,但至少存在其中之一\n等级限制:1≤等级≤9999"; - public string Usage { get; } = "用法:/relic <遗器ID> <主词条ID> <小词条ID1:小词条等级> <小词条ID2:小词条等级> <小词条ID3:小词条等级> <小词条ID4:小词条等级> l<等级> x<数量>"; - public string RelicNotFound { get; } = "遗器不存在!"; - public string InvalidMainAffixId { get; } = "主词条ID无效"; - public string InvalidSubAffixId { get; } = "副词条ID无效"; - public string RelicGiven { get; } = "给予玩家 @{0} {1} 个遗器 {2}, 主词条 {3}"; - } - - /// - /// path: Game.Command.Reload - /// - public class ReloadTextCHS - { - public string Desc { get; } = "重新加载指定的配置\n配置名:banner - 卡池, activity - 活动"; - public string Usage { get; } = "用法:/reload <配置名>"; - public string ConfigReloaded { get; } = "配置 {0} 已重新加载!"; - } - - /// - /// path: Game.Command.Rogue - /// - public class RogueTextCHS - { - public string Desc { get; } = "管理玩家模拟宇宙中的数据\n-1意为所有祝福(已拥有祝福)\n使用 buff 来获取祝福\n使用 enhance 来强化祝福"; - public string Usage { get; } = "用法:/rogue money [宇宙碎片数量]\n\n用法:/rogue buff [祝福ID/-1]\n\n用法:/rogue miracle [奇物ID]\n\n用法:/rogue enhance [祝福ID/-1]\n\n用法:/rogue unstuck - 脱离事件"; - public string PlayerGainedMoney { get; } = "玩家已获得 {0} 宇宙碎片"; - public string PlayerGainedAllItems { get; } = "玩家已获得所有{0}"; - public string PlayerGainedItem { get; } = "玩家已获得{0} {1}"; - public string PlayerEnhancedBuff { get; } = "玩家已强化祝福 {0}"; - public string PlayerEnhancedAllBuffs { get; } = "玩家已强化所有祝福"; - public string PlayerUnstuck { get; } = "玩家已脱离事件"; - public string NotFoundItem { get; } = "未找到 {0}!"; - } - - /// - /// path: Game.Command.Scene - /// - public class SceneTextCHS - { - public string Desc { get; } = "管理玩家场景\n" + - "提示:此组大多为调试使用,使用命令前,请确保你清楚你在做什么!\n" + - "使用 prop 来设置道具状态,在Common/Enums/Scene/PropStateEnum.cs获取状态列表\n" + - "使用 unlockall 来解锁场景内所有道具(即将所有能设置为open状态的道具设置为open状态),此命令有较大可能会导致游戏加载卡条约90%,使用 /scene reset 来解决问题\n" + - "使用 change 来进入指定场景,要获取EntryId,请访问 Resources/MapEntrance.json\n" + - "使用 reload 来重新加载当前场景,并回到初始位置\n" + - "使用 reset 来重置指定场景所有道具状态,要获取当前FloorId,请访问数据库 Player 表"; - public string Usage { get; } = "用法:/scene prop [组ID] [道具ID] [状态]\n\n用法:/scene remove [实体ID]\n\n用法:/scene unlockall\n\n用法:/scene change [entryId]\n\n用法:/scene reload\n\n用法:/scene reset "; - public string LoadedGroups { get; } = "已加载组: {0}"; - public string PropStateChanged { get; } = "道具: {0} 的状态已设置为 {1}"; - public string PropNotFound { get; } = "未找到道具!"; - public string EntityRemoved { get; } = "实体 {0} 已被移除"; - public string EntityNotFound { get; } = "未找到实体!"; - public string AllPropsUnlocked { get; } = "所有道具已解锁!"; - public string SceneChanged { get; } = "已进入场景 {0}"; - public string SceneReloaded { get; } = "场景已重新加载!"; - public string SceneReset { get; } = "已重置场景 {0} 中所有道具状态!"; - } - - /// - /// path: Game.Command.Mail - /// - public class MailTextCHS - { - public string Desc { get; } = "管理玩家的邮件"; - public string Usage { get; } = "用法:/mail send [发送名称] [标题] [内容] [模板ID] [过期天数]"; - public string MailSent { get; } = "邮件已发送!"; - public string MailSentWithAttachment { get; } = "带附件的邮件已发送!"; - } - - /// - /// path: Game.Command.Raid - /// - public class RaidTextCHS - { - public string Desc { get; } = "管理玩家的任务临时场景"; - public string Usage { get; } = "用法:/raid leave - 离开临时场景"; - public string Leaved { get; } = "已离开临时场景!"; - } - /// - /// path: Game.Command.Account - /// - public class AccountTextCHS - { - public string Desc { get; } = "创建账号\n注意:此命令未经测试,请谨慎使用!"; - public string Usage { get; } = "用法:/account create <用户名>"; - public string InvalidUid { get; } = "无效UID参数!"; - public string CreateError { get; } = "出现内部错误 {0} "; - public string CreateSuccess { get; } = "新账号 {0} 创建成功!"; - public string DuplicateAccount { get; } = "账号 {0} 已存在!"; - public string DuplicateUID { get; } = "UID {0} 已存在!"; - public string DataError { get; } = "新账号获取失败! {0}!"; - } - #endregion - - #endregion + public GameTextCHS Game { get; } = new(); + public ServerTextCHS Server { get; } = new(); + public WordTextCHS Word { get; } = new(); // a placeholder for the actual word text } + +#endregion + +#region Layer 1 + +/// +/// path: Game +/// +public class GameTextCHS +{ + public CommandTextCHS Command { get; } = new(); +} + +/// +/// path: Server +/// +public class ServerTextCHS +{ + public WebTextCHS Web { get; } = new(); + public ServerInfoTextCHS ServerInfo { get; } = new(); +} + +/// +/// path: Word +/// +public class WordTextCHS +{ + public string Rank { get; } = "星魂"; + public string Avatar { get; } = "角色"; + public string Material { get; } = "材料"; + public string Relic { get; } = "遗器"; + public string Equipment { get; } = "光锥"; + public string Talent { get; } = "行迹"; + public string Banner { get; } = "卡池"; + public string Activity { get; } = "活动"; + public string Buff { get; } = "祝福"; + public string Miracle { get; } = "奇物"; + public string Unlock { get; } = "奢侈品"; + + // server info + public string Config { get; } = "配置文件"; + public string Language { get; } = "语言"; + public string Log { get; } = "日志"; + public string GameData { get; } = "游戏数据"; + public string Database { get; } = "数据库"; + public string Command { get; } = "命令"; + public string WebServer { get; } = "Web服务器"; + public string Plugin { get; } = "插件"; + public string Handler { get; } = "包处理器"; + public string Dispatch { get; } = "全局分发"; + public string Game { get; } = "游戏"; + public string Handbook { get; } = "手册"; + public string NotFound { get; } = "未找到"; + public string Error { get; } = "错误"; + public string FloorInfo { get; } = "区域文件"; + public string FloorGroupInfo { get; } = "区域组文件"; + public string FloorMissingResult { get; } = "传送与世界生成"; + public string FloorGroupMissingResult { get; } = "传送、怪物战斗与世界生成"; + public string Mission { get; } = "任务"; + public string MissionInfo { get; } = "任务文件"; + public string SubMission { get; } = "子任务"; + public string SubMissionInfo { get; } = "子任务文件"; + public string MazeSkill { get; } = "角色秘技"; + public string MazeSkillInfo { get; } = "角色秘技文件"; + public string Dialogue { get; } = "模拟宇宙事件"; + public string DialogueInfo { get; } = "模拟宇宙事件文件"; + public string Performance { get; } = "剧情操作"; + public string PerformanceInfo { get; } = "剧情操作文件"; + public string RogueChestMap { get; } = "模拟宇宙地图"; + public string RogueChestMapInfo { get; } = "模拟宇宙地图文件"; + public string ChessRogueRoom { get; } = "模拟宇宙DLC"; + public string ChessRogueRoomInfo { get; } = "模拟宇宙DLC文件"; +} + +#endregion + +#region Layer 2 + +#region GameText + +/// +/// path: Game.Command +/// +public class CommandTextCHS +{ + public NoticeTextCHS Notice { get; } = new(); + + public HeroTextCHS Hero { get; } = new(); + public AvatarTextCHS Avatar { get; } = new(); + public GiveTextCHS Give { get; } = new(); + public GiveAllTextCHS GiveAll { get; } = new(); + public LineupTextCHS Lineup { get; } = new(); + public HelpTextCHS Help { get; } = new(); + public KickTextCHS Kick { get; } = new(); + public MissionTextCHS Mission { get; } = new(); + public RelicTextCHS Relic { get; } = new(); + public ReloadTextCHS Reload { get; } = new(); + public RogueTextCHS Rogue { get; } = new(); + public SceneTextCHS Scene { get; } = new(); + public UnlockAllTextCHS UnlockAll { get; } = new(); + public MailTextCHS Mail { get; } = new(); + public RaidTextCHS Raid { get; } = new(); + public AccountTextCHS Account { get; } = new(); +} + +#endregion + +#region ServerText + +/// +/// path: Server.Web +/// +public class WebTextCHS +{ +} + +/// +/// path: Server.ServerInfo +/// +public class ServerInfoTextCHS +{ + public string Shutdown { get; } = "关闭中…"; + public string CancelKeyPressed { get; } = "已按下取消键 (Ctrl + C),服务器即将关闭…"; + public string StartingServer { get; } = "正在启动 DanhengServer…"; + public string LoadingItem { get; } = "正在加载 {0}…"; + public string RegisterItem { get; } = "注册了 {0} 个 {1}。"; + public string FailedToLoadItem { get; } = "加载 {0} 失败。"; + public string FailedToInitializeItem { get; } = "初始化 {0} 失败。"; + public string FailedToReadItem { get; } = "读取 {0} 失败,文件{1}"; + public string GeneratedItem { get; } = "已生成 {0}。"; + public string LoadedItem { get; } = "已加载 {0}。"; + public string LoadedItems { get; } = "已加载 {0} 个 {1}。"; + public string ServerRunning { get; } = "{0} 服务器正在监听 {1}"; + public string ServerStarted { get; } = "启动完成!用时 {0}s,击败了99%的用户,输入 ‘help’ 来获取命令帮助"; // 玩梗,考虑英语版本将其本土化 + public string MissionEnabled { get; } = "任务系统已启用,此功能仍在开发中,且可能不会按预期工作,如果遇见任何bug,请汇报给开发者。"; + + public string ConfigMissing { get; } = "{0} 缺失,请检查你的资源文件夹:{1},{2} 可能不能使用。"; + public string UnloadedItems { get; } = "卸载了所有 {0}。"; + public string SaveDatabase { get; } = "已保存数据库,用时 {0}s"; +} + +#endregion + +#endregion + +#region Layer 3 + +#region CommandText + +/// +/// path: Game.Command.Notice +/// +public class NoticeTextCHS +{ + public string PlayerNotFound { get; } = "未找到玩家!"; + public string InvalidArguments { get; } = "无效的参数!"; + public string NoPermission { get; } = "你没有权限这么做!"; + public string CommandNotFound { get; } = "未找到命令! 输入 '/help' 来获取帮助"; + public string TargetOffline { get; } = "目标 {0}({1}) 离线了!清除当前目标"; + public string TargetFound { get; } = "找到目标 {0}({1}),下一次命令将默认对其执行"; + public string TargetNotFound { get; } = "未找到目标 {0}!"; + public string InternalError { get; } = "在处理命令时发生了内部错误!"; +} + +/// +/// path: Game.Command.Hero +/// +public class HeroTextCHS +{ + public string Desc { get; } = + "切换主角的性别/形态\n当切换性别时,genderId为1代表男性,2代表女性\n当切换形态时,8001代表毁灭命途,8003代表存护命途,8005代表同谐命途。\n注意,切换性别时会清空所有可选命途以及行迹,为不可逆操作!"; + + public string Usage { get; } = "用法:/hero gender [genderId]\n\n用法:/hero type [typeId]"; + public string GenderNotSpecified { get; } = "性别不存在!"; + public string HeroTypeNotSpecified { get; } = "主角类型不存在!"; + public string GenderChanged { get; } = "性别已更改!"; + public string HeroTypeChanged { get; } = "主角类型已更改!"; +} + +/// +/// path: Game.Command.UnlockAll +/// +public class UnlockAllTextCHS +{ + public string Desc { get; } = "解锁所有在类别内的对象\n" + + "使用 /unlockall mission 以完成所有任务,使用后会被踢出,重新登录后可能会被教程卡住,请谨慎使用"; + + public string Usage { get; } = "用法:/unlockall mission"; + public string AllMissionsUnlocked { get; } = "所有任务已解锁!"; +} + +/// +/// path: Game.Command.Avatar +/// +public class AvatarTextCHS +{ + public string Desc { get; } = "设定玩家已有角色的属性\n设置行迹等级时,设置X级即设置所有行迹节点至X级,若大于此节点允许的最高等级,设置为最高等级\n注意:-1意为所有已拥有角色"; + + public string Usage { get; } = + "用法:/avatar talent [角色ID/-1] [行迹等级]\n\n用法:/avatar get [角色ID]\n\n用法:/avatar rank [角色ID/-1] [星魂]\n\n用法:/avatar level [角色ID/-1] [角色等级]"; + + public string InvalidLevel { get; } = "{0}等级无效"; + public string AllAvatarsLevelSet { get; } = "已将全部角色 {0}等级设置为 {1}"; + public string AvatarLevelSet { get; } = "已将 {0} 角色 {1}等级设置为 {2}"; + public string AvatarNotFound { get; } = "角色不存在!"; + public string AvatarGet { get; } = "获取到角色 {0}!"; + public string AvatarFailedGet { get; } = "获取角色 {0} 失败!"; +} + +/// +/// path: Game.Command.Give +/// +public class GiveTextCHS +{ + public string Desc { get; } = "给予玩家物品,此处可输入角色ID,但无法设置行迹、等级及星魂"; + public string Usage { get; } = "用法:/give <物品ID> l<等级> x<数量> r<叠影>"; + public string ItemNotFound { get; } = "未找到物品!"; + public string GiveItem { get; } = "给予 @{0} {1} 个物品 {2}"; +} + +/// +/// path: Game.Command.GiveAll +/// +public class GiveAllTextCHS +{ + public string Desc { get; } = "给予玩家全部指定类型的物品\navatar意为角色,equipment意为光锥,relic意为遗器,unlock意为气泡、手机壁纸、头像"; + + public string Usage { get; } = + "用法:/giveall avatar r<星魂> l<等级>\n\n用法:/giveall equipment r<叠影> l<等级> x<数量>\n\n用法:/giveall relic l<等级> x<数量>\n\n用法:/giveall unlock"; + + public string GiveAllItems { get; } = "已给予所有 {0}, 各 {1} 个"; +} + +/// +/// path: Game.Command.Lineup +/// +public class LineupTextCHS +{ + public string Desc { get; } = "管理玩家的队伍\n秘技点一次性只能获得两个"; + public string Usage { get; } = "用法:/lineup mp [秘技点数量]\n\n用法:/lineup heal"; + public string PlayerGainedMp { get; } = "玩家已获得 {0} 秘技点"; + public string HealedAllAvatars { get; } = "成功治愈当前队伍中的所有角色"; +} + +/// +/// path: Game.Command.Help +/// +public class HelpTextCHS +{ + public string Desc { get; } = "显示帮助信息"; + public string Usage { get; } = "用法:/help"; + public string Commands { get; } = "命令:"; + public string CommandPermission { get; } = "所需权限: "; +} + +/// +/// path: Game.Command.Kick +/// +public class KickTextCHS +{ + public string Desc { get; } = "踢出玩家"; + public string Usage { get; } = "用法:/kick"; + public string PlayerKicked { get; } = "玩家 {0} 已被踢出!"; +} + +/// +/// path: Game.Command.Mission +/// +public class MissionTextCHS +{ + public string Desc { get; } = "管理玩家的任务\n" + + "使用 pass 完成当前正在进行的所有任务,此命令易造成严重卡顿,请尽量使用 /mission finish 替代\n" + + "使用 running 获取正在进行的任务以及可能卡住的任务,使用后可能会出现较长任务列表,请注意甄别\n" + + "使用 reaccept 可重新进行指定主任务,请浏览 handbook 来获取主任务ID"; + + public string Usage { get; } = + "用法:/mission pass\n\n用法:/mission finish [子任务ID]\n\n用法:/mission running\n\n用法:/mission reaccept [主任务ID]"; + + public string AllMissionsFinished { get; } = "所有任务已完成!"; + public string AllRunningMissionsFinished { get; } = "共 {0} 个进行中的任务已完成!"; + public string MissionFinished { get; } = "任务 {0} 已完成!"; + public string InvalidMissionId { get; } = "无效的任务ID!"; + public string NoRunningMissions { get; } = "没有正在进行的任务!"; + + public string RunningMissions { get; } = "正在进行的任务:"; + public string PossibleStuckMissions { get; } = "可能卡住的任务:"; + public string MainMission { get; } = "主任务"; + + public string MissionReAccepted { get; } = "重新接受任务 {0}!"; +} + +/// +/// path: Game.Command.Relic +/// +public class RelicTextCHS +{ + public string Desc { get; } = "管理玩家的遗器\n主词条可选,副词条可选,但至少存在其中之一\n等级限制:1≤等级≤9999"; + + public string Usage { get; } = + "用法:/relic <遗器ID> <主词条ID> <小词条ID1:小词条等级> <小词条ID2:小词条等级> <小词条ID3:小词条等级> <小词条ID4:小词条等级> l<等级> x<数量>"; + + public string RelicNotFound { get; } = "遗器不存在!"; + public string InvalidMainAffixId { get; } = "主词条ID无效"; + public string InvalidSubAffixId { get; } = "副词条ID无效"; + public string RelicGiven { get; } = "给予玩家 @{0} {1} 个遗器 {2}, 主词条 {3}"; +} + +/// +/// path: Game.Command.Reload +/// +public class ReloadTextCHS +{ + public string Desc { get; } = "重新加载指定的配置\n配置名:banner - 卡池, activity - 活动"; + public string Usage { get; } = "用法:/reload <配置名>"; + public string ConfigReloaded { get; } = "配置 {0} 已重新加载!"; +} + +/// +/// path: Game.Command.Rogue +/// +public class RogueTextCHS +{ + public string Desc { get; } = "管理玩家模拟宇宙中的数据\n-1意为所有祝福(已拥有祝福)\n使用 buff 来获取祝福\n使用 enhance 来强化祝福"; + + public string Usage { get; } = + "用法:/rogue money [宇宙碎片数量]\n\n用法:/rogue buff [祝福ID/-1]\n\n用法:/rogue miracle [奇物ID]\n\n用法:/rogue enhance [祝福ID/-1]\n\n用法:/rogue unstuck - 脱离事件"; + + public string PlayerGainedMoney { get; } = "玩家已获得 {0} 宇宙碎片"; + public string PlayerGainedAllItems { get; } = "玩家已获得所有{0}"; + public string PlayerGainedItem { get; } = "玩家已获得{0} {1}"; + public string PlayerEnhancedBuff { get; } = "玩家已强化祝福 {0}"; + public string PlayerEnhancedAllBuffs { get; } = "玩家已强化所有祝福"; + public string PlayerUnstuck { get; } = "玩家已脱离事件"; + public string NotFoundItem { get; } = "未找到 {0}!"; + public string PlayerNotInRogue { get; } = "玩家不在模拟宇宙中!"; +} + +/// +/// path: Game.Command.Scene +/// +public class SceneTextCHS +{ + public string Desc { get; } = "管理玩家场景\n" + + "提示:此组大多为调试使用,使用命令前,请确保你清楚你在做什么!\n" + + "使用 prop 来设置道具状态,在Common/Enums/Scene/PropStateEnum.cs获取状态列表\n" + + "使用 unlockall 来解锁场景内所有道具(即将所有能设置为open状态的道具设置为open状态),此命令有较大可能会导致游戏加载卡条约90%,使用 /scene reset 来解决问题\n" + + "使用 change 来进入指定场景,要获取EntryId,请访问 Resources/MapEntrance.json\n" + + "使用 reload 来重新加载当前场景,并回到初始位置\n" + + "使用 reset 来重置指定场景所有道具状态,要获取当前FloorId,请访问数据库 Player 表"; + + public string Usage { get; } = + "用法:/scene prop [组ID] [道具ID] [状态]\n\n用法:/scene remove [实体ID]\n\n用法:/scene unlockall\n\n用法:/scene change [entryId]\n\n用法:/scene reload\n\n用法:/scene reset "; + + public string LoadedGroups { get; } = "已加载组: {0}"; + public string PropStateChanged { get; } = "道具: {0} 的状态已设置为 {1}"; + public string PropNotFound { get; } = "未找到道具!"; + public string EntityRemoved { get; } = "实体 {0} 已被移除"; + public string EntityNotFound { get; } = "未找到实体!"; + public string AllPropsUnlocked { get; } = "所有道具已解锁!"; + public string SceneChanged { get; } = "已进入场景 {0}"; + public string SceneReloaded { get; } = "场景已重新加载!"; + public string SceneReset { get; } = "已重置场景 {0} 中所有道具状态!"; +} + +/// +/// path: Game.Command.Mail +/// +public class MailTextCHS +{ + public string Desc { get; } = "管理玩家的邮件"; + public string Usage { get; } = "用法:/mail send [发送名称] [标题] [内容] [模板ID] [过期天数]"; + public string MailSent { get; } = "邮件已发送!"; + public string MailSentWithAttachment { get; } = "带附件的邮件已发送!"; +} + +/// +/// path: Game.Command.Raid +/// +public class RaidTextCHS +{ + public string Desc { get; } = "管理玩家的任务临时场景"; + public string Usage { get; } = "用法:/raid leave - 离开临时场景"; + public string Leaved { get; } = "已离开临时场景!"; +} + +/// +/// path: Game.Command.Account +/// +public class AccountTextCHS +{ + public string Desc { get; } = "创建账号\n注意:此命令未经测试,请谨慎使用!"; + public string Usage { get; } = "用法:/account create <用户名>"; + public string InvalidUid { get; } = "无效UID参数!"; + public string CreateError { get; } = "出现内部错误 {0} "; + public string CreateSuccess { get; } = "新账号 {0} 创建成功!"; + public string DuplicateAccount { get; } = "账号 {0} 已存在!"; + public string DuplicateUID { get; } = "UID {0} 已存在!"; + public string DataError { get; } = "新账号获取失败! {0}!"; +} + +#endregion + +#endregion \ No newline at end of file diff --git a/Common/Internationalization/Message/LanguageCHT.cs b/Common/Internationalization/Message/LanguageCHT.cs index 47aedcbe..80a78eff 100644 --- a/Common/Internationalization/Message/LanguageCHT.cs +++ b/Common/Internationalization/Message/LanguageCHT.cs @@ -1,385 +1,397 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Internationalization.Message; -namespace EggLink.DanhengServer.Internationalization.Message +#region Root + +public class LanguageCHT { - #region Root - - public class LanguageCHT - { - public GameTextCHT Game { get; } = new(); - public ServerTextCHT Server { get; } = new(); - public WordTextCHT Word { get; } = new(); // a placeholder for the actual word text - } - - #endregion - - #region Layer 1 - - /// - /// path: Game - /// - public class GameTextCHT - { - public CommandTextCHT Command { get; } = new(); - } - - /// - /// path: Server - /// - public class ServerTextCHT - { - public WebTextCHT Web { get; } = new(); - public ServerInfoTextCHT ServerInfo { get; } = new(); - } - - /// - /// path: Word - /// - public class WordTextCHT - { - public string Rank { get; } = "星魂"; - public string Avatar { get; } = "角色"; - public string Material { get; } = "材料"; - public string Relic { get; } = "遺器"; - public string Equipment { get; } = "光錐"; - public string Talent { get; } = "行跡"; - public string Banner { get; } = "卡池"; - public string Activity { get; } = "活動"; - public string Buff { get; } = "祝福"; - public string Miracle { get; } = "奇物"; - public string Unlock { get; } = "奢侈品"; - - // server info - public string Config { get; } = "配置文件"; - public string Language { get; } = "語言"; - public string Log { get; } = "日誌"; - public string GameData { get; } = "遊戲數據"; - public string Database { get; } = "數據庫"; - public string Command { get; } = "命令"; - public string WebServer { get; } = "Web服務器"; - public string Plugin { get; } = "插件"; - public string Handler { get; } = "包處理器"; - public string Dispatch { get; } = "全局分發"; - public string Game { get; } = "遊戲"; - public string Handbook { get; } = "手冊"; - public string NotFound { get; } = "未找到"; - public string Error { get; } = "錯誤"; - public string FloorInfo { get; } = "區域文件"; - public string FloorGroupInfo { get; } = "區域組文件"; - public string FloorMissingResult { get; } = "傳送與世界生成"; - public string FloorGroupMissingResult { get; } = "傳送、怪物戰鬥與世界生成"; - public string Mission { get; } = "任務"; - public string MissionInfo { get; } = "任務文件"; - public string MazeSkill { get; } = "角色秘技"; - public string MazeSkillInfo { get; } = "角色秘技文件"; - public string Dialogue { get; } = "模擬宇宙事件"; - public string DialogueInfo { get; } = "模擬宇宙事件文件"; - public string Performance { get; } = "劇情操作"; - public string PerformanceInfo { get; } = "劇情操作文件"; - public string RogueChestMap { get; } = "模擬宇宙地圖"; - public string RogueChestMapInfo { get; } = "模擬宇宙地圖文件"; - public string ChessRogueRoom { get; } = "模擬宇宙DLC"; - public string ChessRogueRoomInfo { get; } = "模擬宇宙DLC文件"; - } - - #endregion - - #region Layer 2 - - #region GameText - - /// - /// path: Game.Command - /// - public class CommandTextCHT - { - public NoticeTextCHT Notice { get; } = new(); - - public HeroTextCHT Hero { get; } = new(); - public AvatarTextCHT Avatar { get; } = new(); - public GiveTextCHT Give { get; } = new(); - public GiveAllTextCHT GiveAll { get; } = new(); - public LineupTextCHT Lineup { get; } = new(); - public HelpTextCHT Help { get; } = new(); - public KickTextCHT Kick { get; } = new(); - public MissionTextCHT Mission { get; } = new(); - public RelicTextCHT Relic { get; } = new(); - public ReloadTextCHT Reload { get; } = new(); - public RogueTextCHT Rogue { get; } = new(); - public SceneTextCHT Scene { get; } = new(); - public UnlockAllTextCHT UnlockAll { get; } = new(); - public MailTextCHT Mail { get; } = new(); - public RaidTextCHT Raid { get; } = new(); - public AccountTextCHT Account { get; } = new(); - } - - #endregion - - #region ServerText - - /// - /// path: Server.Web - /// - public class WebTextCHT - { - } - - /// - /// path: Server.ServerInfo - /// - public class ServerInfoTextCHT - { - public string Shutdown { get; } = "關閉中…"; - public string CancelKeyPressed { get; } = "已按下取消鍵 (Ctrl + C),服務器即將關閉…"; - public string StartingServer { get; } = "正在啟動 DanhengServer…"; - public string LoadingItem { get; } = "正在加載 {0}…"; - public string RegisterItem { get; } = "註冊了 {0} 個 {1}。"; - public string FailedToLoadItem { get; } = "加載 {0} 失敗。"; - public string FailedToInitializeItem { get; } = "初始化 {0} 失敗。"; - public string FailedToReadItem { get; } = "讀取 {0} 失敗,文件{1}"; - public string GeneratedItem { get; } = "已生成 {0}。"; - public string LoadedItem { get; } = "已加載 {0}。"; - public string LoadedItems { get; } = "已加載 {0} 個 {1}。"; - public string ServerRunning { get; } = "{0} 服務器正在監聽 {1}"; - public string ServerStarted { get; } = "啟動完成!用時 {0}s,擊敗了99%的用戶,輸入 『help』 來獲取命令幫助"; // 玩梗,考慮英語版本將其本土化 - public string MissionEnabled { get; } = "任務系統已啟用,此功能仍在開發中,且可能不會按預期工作,如果遇見任何bug,請匯報給開發者。"; - - public string ConfigMissing { get; } = "{0} 缺失,請檢查你的資源文件夾:{1},{2} 可能不能使用。"; - public string UnloadedItems { get; } = "卸載了所有 {0}。"; - public string SaveDatabase { get; } = "已保存數據庫,用時 {0}s"; - } - - #endregion - - #endregion - - #region Layer 3 - - #region CommandText - - /// - /// path: Game.Command.Notice - /// - public class NoticeTextCHT - { - public string PlayerNotFound { get; } = "未找到玩家!"; - public string InvalidArguments { get; } = "無效的參數!"; - public string NoPermission { get; } = "你沒有權限這麼做!"; - public string CommandNotFound { get; } = "未找到命令! 輸入 '/help' 來獲取幫助"; - public string TargetOffline { get; } = "目標 {0}({1}) 離線了!清除當前目標"; - public string TargetFound { get; } = "找到目標 {0}({1}),下一次命令將默認對其執行"; - public string TargetNotFound { get; } = "未找到目標 {0}!"; - public string InternalError { get; } = "在處理命令時發生了內部錯誤!"; - } - - /// - /// path: Game.Command.Hero - /// - public class HeroTextCHT - { - public string Desc { get; } = "切換主角的性別/形態"; - public string Usage { get; } = "/hero /"; - public string GenderNotSpecified { get; } = "性別不存在!"; - public string HeroTypeNotSpecified { get; } = "主角類型不存在!"; - public string GenderChanged { get; } = "性別已更改!"; - public string HeroTypeChanged { get; } = "主角類型已更改!"; - } - - /// - /// path: Game.Command.UnlockAll - /// - public class UnlockAllTextCHT - { - public string Desc { get; } = "解鎖所有在類別內的對象"; - public string Usage { get; } = "/unlockall "; - public string AllMissionsUnlocked { get; } = "所有任務已解鎖!"; - } - - /// - /// path: Game.Command.Avatar - /// - public class AvatarTextCHT - { - public string Desc { get; } = "設定玩家已有角色的屬性"; - public string Usage { get; } = "/avatar ///"; - public string InvalidLevel { get; } = "無效 {0}等級"; - public string AllAvatarsLevelSet { get; } = "已將全部角色 {0}等級設置為 {1}"; - public string AvatarLevelSet { get; } = "已將 {0} 角色 {1}等級設置為 {2}"; - public string AvatarNotFound { get; } = "角色不存在!"; - public string AvatarGet { get; } = "獲取到角色 {0}!"; - public string AvatarFailedGet { get; } = "獲取角色 {0} 失敗!"; - } - - /// - /// path: Game.Command.Give - /// - public class GiveTextCHT - { - public string Desc { get; } = "給予玩家物品"; - public string Usage { get; } = "/give <物品ID> l<等級> x<數量> r<疊影>"; - public string ItemNotFound { get; } = "未找到物品!"; - public string GiveItem { get; } = "給予 @{0} {1} 個物品 {2}"; - } - - /// - /// path: Game.Command.GiveAll - /// - public class GiveAllTextCHT - { - public string Desc { get; } = "給予玩家全部指定類型的物品"; - public string Usage { get; } = "/giveall r<疊影> l<等級> x<數量>"; - public string GiveAllItems { get; } = "已給予所有 {0}, 各 {1} 個"; - } - - /// - /// path: Game.Command.Lineup - /// - public class LineupTextCHT - { - public string Desc { get; } = "管理玩家的隊伍"; - public string Usage { get; } = "/lineup /"; - public string PlayerGainedMp { get; } = "玩家已獲得 {0} 秘技點"; - public string HealedAllAvatars { get; } = "成功治癒當前隊伍中的所有角色"; - } - - /// - /// path: Game.Command.Help - /// - public class HelpTextCHT - { - public string Desc { get; } = "顯示幫助信息"; - public string Usage { get; } = "/help"; - public string Commands { get; } = "命令:"; - public string CommandUsage { get; } = "用法: "; - } - - /// - /// path: Game.Command.Kick - /// - public class KickTextCHT - { - public string Desc { get; } = "踢出玩家"; - public string Usage { get; } = "/kick"; - public string PlayerKicked { get; } = "玩家 {0} 已被踢出!"; - } - - /// - /// path: Game.Command.Mission - /// - public class MissionTextCHT - { - public string Desc { get; } = "管理玩家的任務"; - public string Usage { get; } = "/mission ////"; - public string AllMissionsFinished { get; } = "所有任務已完成!"; - public string AllRunningMissionsFinished { get; } = "共 {0} 個進行中的任務已完成!"; - public string MissionFinished { get; } = "任務 {0} 已完成!"; - public string InvalidMissionId { get; } = "無效的任務ID!"; - public string NoRunningMissions { get; } = "沒有正在進行的任務!"; - - public string RunningMissions { get; } = "正在進行的任務:"; - public string PossibleStuckMissions { get; } = "可能卡住的任務:"; - public string MainMission { get; } = "主任務"; - - public string MissionReAccepted { get; } = "重新接受任務 {0}!"; - } - - /// - /// path: Game.Command.Relic - /// - public class RelicTextCHT - { - public string Desc { get; } = "管理玩家的遺器"; - public string Usage { get; } = "/relic <遺器ID> <主詞條ID> <小詞條ID1:小詞條等級> <小詞條ID2:小詞條等級> <小詞條ID3:小詞條等級> <小詞條ID4:小詞條等級> l<等級> x<數量>"; - public string RelicNotFound { get; } = "遺器不存在!"; - public string InvalidMainAffixId { get; } = "主詞條ID無效"; - public string InvalidSubAffixId { get; } = "副詞條ID無效"; - public string RelicGiven { get; } = "給予玩家 @{0} {1} 個遺器 {2}, 主詞條 {3}"; - } - - /// - /// path: Game.Command.Reload - /// - public class ReloadTextCHT - { - public string Desc { get; } = "重新加載指定的配置"; - public string Usage { get; } = "/reload <配置名>(banner - 卡池, activity - 活動)"; - public string ConfigReloaded { get; } = "配置 {0} 已重新加載!"; - } - - /// - /// path: Game.Command.Rogue - /// - public class RogueTextCHT - { - public string Desc { get; } = "管理玩家模擬宇宙中的數據"; - public string Usage { get; } = "/rogue ////"; - public string PlayerGainedMoney { get; } = "玩家已獲得 {0} 宇宙碎片"; - public string PlayerGainedAllItems { get; } = "玩家已獲得所有{0}"; - public string PlayerGainedItem { get; } = "玩家已獲得{0} {1}"; - public string PlayerEnhancedBuff { get; } = "玩家已強化祝福 {0}"; - public string PlayerEnhancedAllBuffs { get; } = "玩家已強化所有祝福"; - public string PlayerUnstuck { get; } = "玩家已脫離事件"; - public string NotFoundItem { get; } = "未找到 {0}!"; - } - - /// - /// path: Game.Command.Scene - /// - public class SceneTextCHT - { - public string Desc { get; } = "管理玩家場景"; - public string Usage { get; } = "/scene ////"; - public string LoadedGroups { get; } = "已加載組: {0}"; - public string PropStateChanged { get; } = "道具: {0} 的狀態已設置為 {1}"; - public string PropNotFound { get; } = "未找到道具!"; - public string EntityRemoved { get; } = "實體 {0} 已被移除"; - public string EntityNotFound { get; } = "未找到實體!"; - public string AllPropsUnlocked { get; } = "所有道具已解鎖!"; - public string SceneChanged { get; } = "已進入場景 {0}"; - public string SceneReloaded { get; } = "場景已重新加載!"; - public string SceneReset { get; } = "已重置場景 {0} 中所有道具狀態!"; - } - - /// - /// path: Game.Command.Mail - /// - public class MailTextCHT - { - public string Desc { get; } = "管理玩家的郵件"; - public string Usage { get; } = "/mail /"; - public string MailSent { get; } = "郵件已發送!"; - public string MailSentWithAttachment { get; } = "帶附件的郵件已發送!"; - } - - /// - /// path: Game.Command.Raid - /// - public class RaidTextCHT - { - public string Desc { get; } = "管理玩家的任務臨時場景"; - public string Usage { get; } = "/raid "; - public string Leaved { get; } = "已離開臨時場景!"; - } - - /// - /// path: Game.Command.Account - /// - public class AccountTextCHT - { - public string Desc { get; } = "創建賬號"; - public string Usage { get; } = "/account create <用戶名>"; - public string InvalidUid { get; } = "無效UID參數!"; - public string CreateError { get; } = "出現內部錯誤 {0} "; - public string CreateSuccess { get; } = "新賬號 {0} 創建成功!"; - public string DuplicateAccount { get; } = "賬號 {0} 已存在!"; - public string DuplicateUID { get; } = "UID {0} 已存在!"; - public string DataError { get; } = "新賬號獲取失敗! {0}!"; - } - #endregion - - #endregion + public GameTextCHT Game { get; } = new(); + public ServerTextCHT Server { get; } = new(); + public WordTextCHT Word { get; } = new(); // a placeholder for the actual word text } + +#endregion + +#region Layer 1 + +/// +/// path: Game +/// +public class GameTextCHT +{ + public CommandTextCHT Command { get; } = new(); +} + +/// +/// path: Server +/// +public class ServerTextCHT +{ + public WebTextCHT Web { get; } = new(); + public ServerInfoTextCHT ServerInfo { get; } = new(); +} + +/// +/// path: Word +/// +public class WordTextCHT +{ + public string Rank { get; } = "星魂"; + public string Avatar { get; } = "角色"; + public string Material { get; } = "材料"; + public string Relic { get; } = "遺器"; + public string Equipment { get; } = "光錐"; + public string Talent { get; } = "行跡"; + public string Banner { get; } = "卡池"; + public string Activity { get; } = "活動"; + public string Buff { get; } = "祝福"; + public string Miracle { get; } = "奇物"; + public string Unlock { get; } = "奢侈品"; + + // server info + public string Config { get; } = "配置文件"; + public string Language { get; } = "語言"; + public string Log { get; } = "日誌"; + public string GameData { get; } = "遊戲數據"; + public string Database { get; } = "數據庫"; + public string Command { get; } = "命令"; + public string WebServer { get; } = "Web服務器"; + public string Plugin { get; } = "插件"; + public string Handler { get; } = "包處理器"; + public string Dispatch { get; } = "全局分發"; + public string Game { get; } = "遊戲"; + public string Handbook { get; } = "手冊"; + public string NotFound { get; } = "未找到"; + public string Error { get; } = "錯誤"; + public string FloorInfo { get; } = "區域文件"; + public string FloorGroupInfo { get; } = "區域組文件"; + public string FloorMissingResult { get; } = "傳送與世界生成"; + public string FloorGroupMissingResult { get; } = "傳送、怪物戰鬥與世界生成"; + public string Mission { get; } = "任務"; + public string MissionInfo { get; } = "任務文件"; + public string MazeSkill { get; } = "角色秘技"; + public string MazeSkillInfo { get; } = "角色秘技文件"; + public string Dialogue { get; } = "模擬宇宙事件"; + public string DialogueInfo { get; } = "模擬宇宙事件文件"; + public string Performance { get; } = "劇情操作"; + public string PerformanceInfo { get; } = "劇情操作文件"; + public string RogueChestMap { get; } = "模擬宇宙地圖"; + public string RogueChestMapInfo { get; } = "模擬宇宙地圖文件"; + public string ChessRogueRoom { get; } = "模擬宇宙DLC"; + public string ChessRogueRoomInfo { get; } = "模擬宇宙DLC文件"; +} + +#endregion + +#region Layer 2 + +#region GameText + +/// +/// path: Game.Command +/// +public class CommandTextCHT +{ + public NoticeTextCHT Notice { get; } = new(); + + public HeroTextCHT Hero { get; } = new(); + public AvatarTextCHT Avatar { get; } = new(); + public GiveTextCHT Give { get; } = new(); + public GiveAllTextCHT GiveAll { get; } = new(); + public LineupTextCHT Lineup { get; } = new(); + public HelpTextCHT Help { get; } = new(); + public KickTextCHT Kick { get; } = new(); + public MissionTextCHT Mission { get; } = new(); + public RelicTextCHT Relic { get; } = new(); + public ReloadTextCHT Reload { get; } = new(); + public RogueTextCHT Rogue { get; } = new(); + public SceneTextCHT Scene { get; } = new(); + public UnlockAllTextCHT UnlockAll { get; } = new(); + public MailTextCHT Mail { get; } = new(); + public RaidTextCHT Raid { get; } = new(); + public AccountTextCHT Account { get; } = new(); +} + +#endregion + +#region ServerText + +/// +/// path: Server.Web +/// +public class WebTextCHT +{ +} + +/// +/// path: Server.ServerInfo +/// +public class ServerInfoTextCHT +{ + public string Shutdown { get; } = "關閉中…"; + public string CancelKeyPressed { get; } = "已按下取消鍵 (Ctrl + C),服務器即將關閉…"; + public string StartingServer { get; } = "正在啟動 DanhengServer…"; + public string LoadingItem { get; } = "正在加載 {0}…"; + public string RegisterItem { get; } = "註冊了 {0} 個 {1}。"; + public string FailedToLoadItem { get; } = "加載 {0} 失敗。"; + public string FailedToInitializeItem { get; } = "初始化 {0} 失敗。"; + public string FailedToReadItem { get; } = "讀取 {0} 失敗,文件{1}"; + public string GeneratedItem { get; } = "已生成 {0}。"; + public string LoadedItem { get; } = "已加載 {0}。"; + public string LoadedItems { get; } = "已加載 {0} 個 {1}。"; + public string ServerRunning { get; } = "{0} 服務器正在監聽 {1}"; + public string ServerStarted { get; } = "啟動完成!用時 {0}s,擊敗了99%的用戶,輸入 『help』 來獲取命令幫助"; // 玩梗,考慮英語版本將其本土化 + public string MissionEnabled { get; } = "任務系統已啟用,此功能仍在開發中,且可能不會按預期工作,如果遇見任何bug,請匯報給開發者。"; + + public string ConfigMissing { get; } = "{0} 缺失,請檢查你的資源文件夾:{1},{2} 可能不能使用。"; + public string UnloadedItems { get; } = "卸載了所有 {0}。"; + public string SaveDatabase { get; } = "已保存數據庫,用時 {0}s"; +} + +#endregion + +#endregion + +#region Layer 3 + +#region CommandText + +/// +/// path: Game.Command.Notice +/// +public class NoticeTextCHT +{ + public string PlayerNotFound { get; } = "未找到玩家!"; + public string InvalidArguments { get; } = "無效的參數!"; + public string NoPermission { get; } = "你沒有權限這麼做!"; + public string CommandNotFound { get; } = "未找到命令! 輸入 '/help' 來獲取幫助"; + public string TargetOffline { get; } = "目標 {0}({1}) 離線了!清除當前目標"; + public string TargetFound { get; } = "找到目標 {0}({1}),下一次命令將默認對其執行"; + public string TargetNotFound { get; } = "未找到目標 {0}!"; + public string InternalError { get; } = "在處理命令時發生了內部錯誤!"; +} + +/// +/// path: Game.Command.Hero +/// +public class HeroTextCHT +{ + public string Desc { get; } = "切換主角的性別/形態"; + public string Usage { get; } = "/hero /"; + public string GenderNotSpecified { get; } = "性別不存在!"; + public string HeroTypeNotSpecified { get; } = "主角類型不存在!"; + public string GenderChanged { get; } = "性別已更改!"; + public string HeroTypeChanged { get; } = "主角類型已更改!"; +} + +/// +/// path: Game.Command.UnlockAll +/// +public class UnlockAllTextCHT +{ + public string Desc { get; } = "解鎖所有在類別內的對象"; + public string Usage { get; } = "/unlockall "; + public string AllMissionsUnlocked { get; } = "所有任務已解鎖!"; +} + +/// +/// path: Game.Command.Avatar +/// +public class AvatarTextCHT +{ + public string Desc { get; } = "設定玩家已有角色的屬性"; + + public string Usage { get; } = + "/avatar ///"; + + public string InvalidLevel { get; } = "無效 {0}等級"; + public string AllAvatarsLevelSet { get; } = "已將全部角色 {0}等級設置為 {1}"; + public string AvatarLevelSet { get; } = "已將 {0} 角色 {1}等級設置為 {2}"; + public string AvatarNotFound { get; } = "角色不存在!"; + public string AvatarGet { get; } = "獲取到角色 {0}!"; + public string AvatarFailedGet { get; } = "獲取角色 {0} 失敗!"; +} + +/// +/// path: Game.Command.Give +/// +public class GiveTextCHT +{ + public string Desc { get; } = "給予玩家物品"; + public string Usage { get; } = "/give <物品ID> l<等級> x<數量> r<疊影>"; + public string ItemNotFound { get; } = "未找到物品!"; + public string GiveItem { get; } = "給予 @{0} {1} 個物品 {2}"; +} + +/// +/// path: Game.Command.GiveAll +/// +public class GiveAllTextCHT +{ + public string Desc { get; } = "給予玩家全部指定類型的物品"; + public string Usage { get; } = "/giveall r<疊影> l<等級> x<數量>"; + public string GiveAllItems { get; } = "已給予所有 {0}, 各 {1} 個"; +} + +/// +/// path: Game.Command.Lineup +/// +public class LineupTextCHT +{ + public string Desc { get; } = "管理玩家的隊伍"; + public string Usage { get; } = "/lineup /"; + public string PlayerGainedMp { get; } = "玩家已獲得 {0} 秘技點"; + public string HealedAllAvatars { get; } = "成功治癒當前隊伍中的所有角色"; +} + +/// +/// path: Game.Command.Help +/// +public class HelpTextCHT +{ + public string Desc { get; } = "顯示幫助信息"; + public string Usage { get; } = "/help"; + public string Commands { get; } = "命令:"; + public string CommandUsage { get; } = "用法: "; +} + +/// +/// path: Game.Command.Kick +/// +public class KickTextCHT +{ + public string Desc { get; } = "踢出玩家"; + public string Usage { get; } = "/kick"; + public string PlayerKicked { get; } = "玩家 {0} 已被踢出!"; +} + +/// +/// path: Game.Command.Mission +/// +public class MissionTextCHT +{ + public string Desc { get; } = "管理玩家的任務"; + + public string Usage { get; } = + "/mission ////"; + + public string AllMissionsFinished { get; } = "所有任務已完成!"; + public string AllRunningMissionsFinished { get; } = "共 {0} 個進行中的任務已完成!"; + public string MissionFinished { get; } = "任務 {0} 已完成!"; + public string InvalidMissionId { get; } = "無效的任務ID!"; + public string NoRunningMissions { get; } = "沒有正在進行的任務!"; + + public string RunningMissions { get; } = "正在進行的任務:"; + public string PossibleStuckMissions { get; } = "可能卡住的任務:"; + public string MainMission { get; } = "主任務"; + + public string MissionReAccepted { get; } = "重新接受任務 {0}!"; +} + +/// +/// path: Game.Command.Relic +/// +public class RelicTextCHT +{ + public string Desc { get; } = "管理玩家的遺器"; + + public string Usage { get; } = + "/relic <遺器ID> <主詞條ID> <小詞條ID1:小詞條等級> <小詞條ID2:小詞條等級> <小詞條ID3:小詞條等級> <小詞條ID4:小詞條等級> l<等級> x<數量>"; + + public string RelicNotFound { get; } = "遺器不存在!"; + public string InvalidMainAffixId { get; } = "主詞條ID無效"; + public string InvalidSubAffixId { get; } = "副詞條ID無效"; + public string RelicGiven { get; } = "給予玩家 @{0} {1} 個遺器 {2}, 主詞條 {3}"; +} + +/// +/// path: Game.Command.Reload +/// +public class ReloadTextCHT +{ + public string Desc { get; } = "重新加載指定的配置"; + public string Usage { get; } = "/reload <配置名>(banner - 卡池, activity - 活動)"; + public string ConfigReloaded { get; } = "配置 {0} 已重新加載!"; +} + +/// +/// path: Game.Command.Rogue +/// +public class RogueTextCHT +{ + public string Desc { get; } = "管理玩家模擬宇宙中的數據"; + + public string Usage { get; } = + "/rogue ////"; + + public string PlayerGainedMoney { get; } = "玩家已獲得 {0} 宇宙碎片"; + public string PlayerGainedAllItems { get; } = "玩家已獲得所有{0}"; + public string PlayerGainedItem { get; } = "玩家已獲得{0} {1}"; + public string PlayerEnhancedBuff { get; } = "玩家已強化祝福 {0}"; + public string PlayerEnhancedAllBuffs { get; } = "玩家已強化所有祝福"; + public string PlayerUnstuck { get; } = "玩家已脫離事件"; + public string NotFoundItem { get; } = "未找到 {0}!"; +} + +/// +/// path: Game.Command.Scene +/// +public class SceneTextCHT +{ + public string Desc { get; } = "管理玩家場景"; + + public string Usage { get; } = + "/scene ////"; + + public string LoadedGroups { get; } = "已加載組: {0}"; + public string PropStateChanged { get; } = "道具: {0} 的狀態已設置為 {1}"; + public string PropNotFound { get; } = "未找到道具!"; + public string EntityRemoved { get; } = "實體 {0} 已被移除"; + public string EntityNotFound { get; } = "未找到實體!"; + public string AllPropsUnlocked { get; } = "所有道具已解鎖!"; + public string SceneChanged { get; } = "已進入場景 {0}"; + public string SceneReloaded { get; } = "場景已重新加載!"; + public string SceneReset { get; } = "已重置場景 {0} 中所有道具狀態!"; +} + +/// +/// path: Game.Command.Mail +/// +public class MailTextCHT +{ + public string Desc { get; } = "管理玩家的郵件"; + + public string Usage { get; } = + "/mail /"; + + public string MailSent { get; } = "郵件已發送!"; + public string MailSentWithAttachment { get; } = "帶附件的郵件已發送!"; +} + +/// +/// path: Game.Command.Raid +/// +public class RaidTextCHT +{ + public string Desc { get; } = "管理玩家的任務臨時場景"; + public string Usage { get; } = "/raid "; + public string Leaved { get; } = "已離開臨時場景!"; +} + +/// +/// path: Game.Command.Account +/// +public class AccountTextCHT +{ + public string Desc { get; } = "創建賬號"; + public string Usage { get; } = "/account create <用戶名>"; + public string InvalidUid { get; } = "無效UID參數!"; + public string CreateError { get; } = "出現內部錯誤 {0} "; + public string CreateSuccess { get; } = "新賬號 {0} 創建成功!"; + public string DuplicateAccount { get; } = "賬號 {0} 已存在!"; + public string DuplicateUID { get; } = "UID {0} 已存在!"; + public string DataError { get; } = "新賬號獲取失敗! {0}!"; +} + +#endregion + +#endregion \ No newline at end of file diff --git a/Common/Internationalization/Message/LanguageEN.cs b/Common/Internationalization/Message/LanguageEN.cs index 285e5d4c..67283e09 100644 --- a/Common/Internationalization/Message/LanguageEN.cs +++ b/Common/Internationalization/Message/LanguageEN.cs @@ -2,383 +2,412 @@ // THIS FILE IS GENERATED BY ChatGPT // THERES MANY ERRORS IN THIS FILE -namespace EggLink.DanhengServer.Internationalization.Message +namespace EggLink.DanhengServer.Internationalization.Message; + +#region Root + +public class LanguageEN { - #region Root - - public class LanguageEN - { - public GameTextEN Game { get; } = new(); - public ServerTextEN Server { get; } = new(); - public WordTextEN Word { get; } = new(); // a placeholder for the actual word text - } - - #endregion - - #region Layer 1 - - /// - /// path: Game - /// - public class GameTextEN - { - public CommandTextEN Command { get; } = new(); - } - - /// - /// path: Server - /// - public class ServerTextEN - { - public WebTextEN Web { get; } = new(); - public ServerInfoTextEN ServerInfo { get; } = new(); - } - - /// - /// path: Word - /// - public class WordTextEN - { - public string Rank { get; } = "Rank"; - public string Avatar { get; } = "Avatar"; - public string Material { get; } = "Material"; - public string Relic { get; } = "Relic"; - public string Equipment { get; } = "Light Cone"; - public string Talent { get; } = "Talent"; - public string Banner { get; } = "Gacha"; - public string Activity { get; } = "Activity"; - public string Buff { get; } = "Blessing"; - public string Miracle { get; } = "Curio"; - public string Unlock { get; } = "Luxury"; - - // server info - public string Config { get; } = "Config File"; - public string Language { get; } = "Language"; - public string Log { get; } = "Log"; - public string GameData { get; } = "Game Data"; - public string Database { get; } = "Database"; - public string Command { get; } = "Command"; - public string WebServer { get; } = "Web Server"; - public string Plugin { get; } = "Plugin"; - public string Handler { get; } = "Packet Handler"; - public string Dispatch { get; } = "Global Dispatch"; - public string Game { get; } = "Game"; - public string Handbook { get; } = "Handbook"; - public string NotFound { get; } = "Not Found"; - public string Error { get; } = "Error"; - public string FloorInfo { get; } = "Floor Info"; - public string FloorGroupInfo { get; } = "Floor Group Info"; - public string FloorMissingResult { get; } = "Teleportation and World Generation"; - public string FloorGroupMissingResult { get; } = "Teleportation, Monster Battles, and World Generation"; - public string Mission { get; } = "Mission"; - public string MissionInfo { get; } = "Mission Info"; - public string MazeSkill { get; } = "Maze Skill"; - public string MazeSkillInfo { get; } = "Maze Skill Info"; - public string Dialogue { get; } = "Simulated Universe Event"; - public string DialogueInfo { get; } = "Simulated Universe Event Info"; - public string Performance { get; } = "Performance"; - public string PerformanceInfo { get; } = "Performance Info"; - public string RogueChestMap { get; } = "Simulated Universe Map"; - public string RogueChestMapInfo { get; } = "Simulated Universe Map Info"; - public string ChessRogueRoom { get; } = "Simulated Universe DLC"; - public string ChessRogueRoomInfo { get; } = "Simulated Universe DLC Info"; - } - - #endregion - - #region Layer 2 - - #region GameText - - /// - /// path: Game.Command - /// - public class CommandTextEN - { - public NoticeTextEN Notice { get; } = new(); - - public HeroTextEN Hero { get; } = new(); - public AvatarTextEN Avatar { get; } = new(); - public GiveTextEN Give { get; } = new(); - public GiveAllTextEN GiveAll { get; } = new(); - public LineupTextEN Lineup { get; } = new(); - public HelpTextEN Help { get; } = new(); - public KickTextEN Kick { get; } = new(); - public MissionTextEN Mission { get; } = new(); - public RelicTextEN Relic { get; } = new(); - public ReloadTextEN Reload { get; } = new(); - public RogueTextEN Rogue { get; } = new(); - public SceneTextEN Scene { get; } = new(); - public UnlockAllTextEN UnlockAll { get; } = new(); - public MailTextEN Mail { get; } = new(); - public RaidTextEN Raid { get; } = new(); - public AccountTextEN Account { get; } = new(); - } - - #endregion - - #region ServerTextEN - - /// - /// path: Server.Web - /// - public class WebTextEN - { - } - - /// - /// path: Server.ServerInfo - /// - public class ServerInfoTextEN - { - public string Shutdown { get; } = "Shutting down..."; - public string CancelKeyPressed { get; } = "Cancel key pressed (Ctrl + C), server shutting down..."; - public string StartingServer { get; } = "Starting DanhengServer..."; - public string LoadingItem { get; } = "Loading {0}..."; - public string RegisterItem { get; } = "Registered {0} {1}(s)."; - public string FailedToLoadItem { get; } = "Failed to load {0}."; - public string FailedToInitializeItem { get; } = "Failed to initialize {0}."; - public string FailedToReadItem { get; } = "Failed to read {0}, file {1}"; - public string GeneratedItem { get; } = "Generated {0}."; - public string LoadedItem { get; } = "Loaded {0}."; - public string LoadedItems { get; } = "Loaded {0} {1}(s)."; - public string ServerRunning { get; } = "{0} server listening on {1}"; - public string ServerStarted { get; } = "Startup complete! Took {0}s, better than 99% of users. Type 'help' for command help"; // This is a meme, consider localizing in English - public string MissionEnabled { get; } = "Mission system enabled. This feature is still in development and may not work as expected. Please report any bugs to the developers."; - - public string ConfigMissing { get; } = "{0} is missing. Please check your resource folder: {1}, {2} may not be available."; - public string UnloadedItems { get; } = "Unloaded all {0}."; - public string SaveDatabase { get; } = "Database saved in {0}s"; - } - - - #endregion - - #endregion - - #region Layer 3 - - #region CommandText - - /// - /// path: Game.Command.Notice - /// - public class NoticeTextEN - { - public string PlayerNotFound { get; } = "Player not found!"; - public string InvalidArguments { get; } = "Invalid arguments!"; - public string NoPermission { get; } = "You do not have permission to do this!"; - public string CommandNotFound { get; } = "Command not found! Type '/help' to get help."; - public string TargetNotFound { get; } = "Target {0} not found!"; - public string TargetOffline { get; } = "Target {0}({1}) is offline! Clear the target."; - public string TargetFound { get; } = "Online player {0}({1}) is found, the next command will target it by default."; - public string InternalError { get; } = "An error occurred while executing the command!"; - } - - /// - /// path: Game.Command.Hero - /// - public class HeroTextEN - { - public string Desc { get; } = "Switch the gender/type of the main character"; - public string Usage { get; } = "/hero /"; - public string GenderNotSpecified { get; } = "Gender does not exist!"; - public string HeroTypeNotSpecified { get; } = "Main character type does not exist!"; - public string GenderChanged { get; } = "Gender has been changed!"; - public string HeroTypeChanged { get; } = "Main character type has been changed!"; - } - - /// - /// path: Game.Command.UnlockAll - /// - public class UnlockAllTextEN - { - public string Desc { get; } = "Unlock all objects in the category"; - public string Usage { get; } = "/unlockall "; - public string AllMissionsUnlocked { get; } = "All tasks have been unlocked!"; - } - - /// - /// path: Game.Command.Avatar - /// - public class AvatarTextEN - { - public string Desc { get; } = "Set the properties of the player's existing characters"; - public string Usage { get; } = "/avatar ///"; - public string InvalidLevel { get; } = "Invalid {0} level"; - public string AllAvatarsLevelSet { get; } = "Set all characters' {0} level to {1}"; - public string AvatarLevelSet { get; } = "Set character {0}'s {1} level to {2}"; - public string AvatarNotFound { get; } = "Character does not exist!"; - public string AvatarGet { get; } = "Obtained character {0}!"; - public string AvatarFailedGet { get; } = "Failed to obtain character {0}!"; - } - - /// - /// path: Game.Command.Give - /// - public class GiveTextEN - { - public string Desc { get; } = "Give player items"; - public string Usage { get; } = "/give l x r"; - public string ItemNotFound { get; } = "Item not found!"; - public string GiveItem { get; } = "Gave @{0} {1} item(s) {2}"; - } - - /// - /// path: Game.Command.GiveAll - /// - public class GiveAllTextEN - { - public string Desc { get; } = "Give the player all specified types of items"; - public string Usage { get; } = "/giveall r l x"; - public string GiveAllItems { get; } = "Gave all {0}, each {1} items"; - } - - /// - /// path: Game.Command.Lineup - /// - public class LineupTextEN - { - public string Desc { get; } = "Manage player's lineup"; - public string Usage { get; } = "/lineup /"; - public string PlayerGainedMp { get; } = "Player gained {0} skill points"; - public string HealedAllAvatars { get; } = "Successfully healed all characters in the current lineup"; - } - - /// - /// path: Game.Command.Help - /// - public class HelpTextEN - { - public string Desc { get; } = "Show help information"; - public string Usage { get; } = "/help"; - public string Commands { get; } = "Commands:"; - public string CommandUsage { get; } = "Usage: "; - } - - /// - /// path: Game.Command.Kick - /// - public class KickTextEN - { - public string Desc { get; } = "Kick out player"; - public string Usage { get; } = "/kick"; - public string PlayerKicked { get; } = "Player {0} has been kicked out!"; - } - - /// - /// path: Game.Command.Mission - /// - public class MissionTextEN - { - public string Desc { get; } = "Manage player's tasks"; - public string Usage { get; } = "/mission ////"; - public string AllMissionsFinished { get; } = "All tasks have been completed!"; - public string AllRunningMissionsFinished { get; } = "A total of {0} ongoing tasks have been completed!"; - public string MissionFinished { get; } = "Task {0} has been completed!"; - public string InvalidMissionId { get; } = "Invalid task ID!"; - public string NoRunningMissions { get; } = "No ongoing tasks!"; - - public string RunningMissions { get; } = "Ongoing tasks:"; - public string PossibleStuckMissions { get; } = "Possibly stuck tasks:"; - public string MainMission { get; } = "Main task"; - - public string MissionReAccepted { get; } = "Reaccepted task {0}!"; - } - - /// - /// path: Game.Command.Relic - /// - public class RelicTextEN - { - public string Desc { get; } = "Manage player's relics"; - public string Usage { get; } = "/relic
l x"; - public string RelicNotFound { get; } = "Relic does not exist!"; - public string InvalidMainAffixId { get; } = "Invalid main affix ID"; - public string InvalidSubAffixId { get; } = "Invalid sub affix ID"; - public string RelicGiven { get; } = "Gave player @{0} {1} relic(s) {2}, main affix {3}"; - } - - /// - /// path: Game.Command.Reload - /// - public class ReloadTextEN - { - public string Desc { get; } = "Reload specified configuration"; - public string Usage { get; } = "/reload (banner - gacha, activity - event)"; - public string ConfigReloaded { get; } = "Configuration {0} has been reloaded!"; - } - - /// - /// path: Game.Command.Rogue - /// - public class RogueTextEN - { - public string Desc { get; } = "Manage player's data in the simulated universe"; - public string Usage { get; } = "/rogue ////"; - public string PlayerGainedMoney { get; } = "Player gained {0} cosmic fragments"; - public string PlayerGainedAllItems { get; } = "Player gained all {0}"; - public string PlayerGainedItem { get; } = "Player gained {0} {1}"; - public string PlayerEnhancedBuff { get; } = "Player enhanced blessing {0}"; - public string PlayerEnhancedAllBuffs { get; } = "Player enhanced all blessings"; - public string PlayerUnstuck { get; } = "Player unstuck from event"; - public string NotFoundItem { get; } = "{0} not found!"; - } - - /// - /// path: Game.Command.Scene - /// - public class SceneTextEN - { - public string Desc { get; } = "Manage player's scenes"; - public string Usage { get; } = "/scene ////"; - public string LoadedGroups { get; } = "Loaded groups: {0}"; - public string PropStateChanged { get; } = "Prop: {0} state set to {1}"; - public string PropNotFound { get; } = "Prop not found!"; - public string EntityRemoved { get; } = "Entity {0} has been removed"; - public string EntityNotFound { get; } = "Entity not found!"; - public string AllPropsUnlocked { get; } = "All props have been unlocked!"; - public string SceneChanged { get; } = "Entered scene {0}"; - public string SceneReloaded { get; } = "Scene has been reloaded!"; - public string SceneReset { get; } = "The prop state in floor {0} has been reset!"; - } - - /// - /// path: Game.Command.Mail - /// - public class MailTextEN - { - public string Desc { get; } = "Manage player's mails"; - public string Usage { get; } = "/mail /"; - public string MailSent { get; } = "Mail has been sent!"; - public string MailSentWithAttachment { get; } = "Mail with attachments has been sent!"; - } - - /// - /// path: Game.Command.Raid - /// - public class RaidTextEN - { - public string Desc { get; } = "Manage player's temporary scene"; - public string Usage { get; } = "/raid "; - public string Leaved { get; } = "Leaved temporary scene!"; - } - /// - /// path: Game.Command.Account - /// - public class AccountTextEN - { - public string Desc { get; } = "Create Account"; - public string Usage { get; } = "/account create "; - public string InvalidUid { get; } = "Invalid UID argument!"; - public string CreateError { get; } = "An internal error occurred {0}"; - public string CreateSuccess { get; } = "New account {0} created successfully!"; - public string DuplicateAccount { get; } = "Account {0} already exists!"; - public string DuplicateUID { get; } = "UID {0} already exists!"; - public string DataError { get; } = "Failed to retrieve new account! {0}!"; - } - - #endregion - - #endregion + public GameTextEN Game { get; } = new(); + public ServerTextEN Server { get; } = new(); + public WordTextEN Word { get; } = new(); // a placeholder for the actual word text } + +#endregion + +#region Layer 1 + +/// +/// path: Game +/// +public class GameTextEN +{ + public CommandTextEN Command { get; } = new(); +} + +/// +/// path: Server +/// +public class ServerTextEN +{ + public WebTextEN Web { get; } = new(); + public ServerInfoTextEN ServerInfo { get; } = new(); +} + +/// +/// path: Word +/// +public class WordTextEN +{ + public string Rank { get; } = "Rank"; + public string Avatar { get; } = "Avatar"; + public string Material { get; } = "Material"; + public string Relic { get; } = "Relic"; + public string Equipment { get; } = "Light Cone"; + public string Talent { get; } = "Talent"; + public string Banner { get; } = "Gacha"; + public string Activity { get; } = "Activity"; + public string Buff { get; } = "Blessing"; + public string Miracle { get; } = "Curio"; + public string Unlock { get; } = "Luxury"; + + // server info + public string Config { get; } = "Config File"; + public string Language { get; } = "Language"; + public string Log { get; } = "Log"; + public string GameData { get; } = "Game Data"; + public string Database { get; } = "Database"; + public string Command { get; } = "Command"; + public string WebServer { get; } = "Web Server"; + public string Plugin { get; } = "Plugin"; + public string Handler { get; } = "Packet Handler"; + public string Dispatch { get; } = "Global Dispatch"; + public string Game { get; } = "Game"; + public string Handbook { get; } = "Handbook"; + public string NotFound { get; } = "Not Found"; + public string Error { get; } = "Error"; + public string FloorInfo { get; } = "Floor Info"; + public string FloorGroupInfo { get; } = "Floor Group Info"; + public string FloorMissingResult { get; } = "Teleportation and World Generation"; + public string FloorGroupMissingResult { get; } = "Teleportation, Monster Battles, and World Generation"; + public string Mission { get; } = "Mission"; + public string MissionInfo { get; } = "Mission Info"; + public string MazeSkill { get; } = "Maze Skill"; + public string MazeSkillInfo { get; } = "Maze Skill Info"; + public string Dialogue { get; } = "Simulated Universe Event"; + public string DialogueInfo { get; } = "Simulated Universe Event Info"; + public string Performance { get; } = "Performance"; + public string PerformanceInfo { get; } = "Performance Info"; + public string RogueChestMap { get; } = "Simulated Universe Map"; + public string RogueChestMapInfo { get; } = "Simulated Universe Map Info"; + public string ChessRogueRoom { get; } = "Simulated Universe DLC"; + public string ChessRogueRoomInfo { get; } = "Simulated Universe DLC Info"; +} + +#endregion + +#region Layer 2 + +#region GameText + +/// +/// path: Game.Command +/// +public class CommandTextEN +{ + public NoticeTextEN Notice { get; } = new(); + + public HeroTextEN Hero { get; } = new(); + public AvatarTextEN Avatar { get; } = new(); + public GiveTextEN Give { get; } = new(); + public GiveAllTextEN GiveAll { get; } = new(); + public LineupTextEN Lineup { get; } = new(); + public HelpTextEN Help { get; } = new(); + public KickTextEN Kick { get; } = new(); + public MissionTextEN Mission { get; } = new(); + public RelicTextEN Relic { get; } = new(); + public ReloadTextEN Reload { get; } = new(); + public RogueTextEN Rogue { get; } = new(); + public SceneTextEN Scene { get; } = new(); + public UnlockAllTextEN UnlockAll { get; } = new(); + public MailTextEN Mail { get; } = new(); + public RaidTextEN Raid { get; } = new(); + public AccountTextEN Account { get; } = new(); +} + +#endregion + +#region ServerTextEN + +/// +/// path: Server.Web +/// +public class WebTextEN +{ +} + +/// +/// path: Server.ServerInfo +/// +public class ServerInfoTextEN +{ + public string Shutdown { get; } = "Shutting down..."; + public string CancelKeyPressed { get; } = "Cancel key pressed (Ctrl + C), server shutting down..."; + public string StartingServer { get; } = "Starting DanhengServer..."; + public string LoadingItem { get; } = "Loading {0}..."; + public string RegisterItem { get; } = "Registered {0} {1}(s)."; + public string FailedToLoadItem { get; } = "Failed to load {0}."; + public string FailedToInitializeItem { get; } = "Failed to initialize {0}."; + public string FailedToReadItem { get; } = "Failed to read {0}, file {1}"; + public string GeneratedItem { get; } = "Generated {0}."; + public string LoadedItem { get; } = "Loaded {0}."; + public string LoadedItems { get; } = "Loaded {0} {1}(s)."; + public string ServerRunning { get; } = "{0} server listening on {1}"; + + public string ServerStarted { get; } = + "Startup complete! Took {0}s, better than 99% of users. Type 'help' for command help"; // This is a meme, consider localizing in English + + public string MissionEnabled { get; } = + "Mission system enabled. This feature is still in development and may not work as expected. Please report any bugs to the developers."; + + public string ConfigMissing { get; } = + "{0} is missing. Please check your resource folder: {1}, {2} may not be available."; + + public string UnloadedItems { get; } = "Unloaded all {0}."; + public string SaveDatabase { get; } = "Database saved in {0}s"; +} + +#endregion + +#endregion + +#region Layer 3 + +#region CommandText + +/// +/// path: Game.Command.Notice +/// +public class NoticeTextEN +{ + public string PlayerNotFound { get; } = "Player not found!"; + public string InvalidArguments { get; } = "Invalid arguments!"; + public string NoPermission { get; } = "You do not have permission to do this!"; + public string CommandNotFound { get; } = "Command not found! Type '/help' to get help."; + public string TargetNotFound { get; } = "Target {0} not found!"; + public string TargetOffline { get; } = "Target {0}({1}) is offline! Clear the target."; + public string TargetFound { get; } = "Online player {0}({1}) is found, the next command will target it by default."; + public string InternalError { get; } = "An error occurred while executing the command!"; +} + +/// +/// path: Game.Command.Hero +/// +public class HeroTextEN +{ + public string Desc { get; } = "Switch the gender/type of the main character"; + + public string Usage { get; } = + "/hero /"; + + public string GenderNotSpecified { get; } = "Gender does not exist!"; + public string HeroTypeNotSpecified { get; } = "Main character type does not exist!"; + public string GenderChanged { get; } = "Gender has been changed!"; + public string HeroTypeChanged { get; } = "Main character type has been changed!"; +} + +/// +/// path: Game.Command.UnlockAll +/// +public class UnlockAllTextEN +{ + public string Desc { get; } = "Unlock all objects in the category"; + public string Usage { get; } = "/unlockall "; + public string AllMissionsUnlocked { get; } = "All tasks have been unlocked!"; +} + +/// +/// path: Game.Command.Avatar +/// +public class AvatarTextEN +{ + public string Desc { get; } = "Set the properties of the player's existing characters"; + + public string Usage { get; } = + "/avatar ///"; + + public string InvalidLevel { get; } = "Invalid {0} level"; + public string AllAvatarsLevelSet { get; } = "Set all characters' {0} level to {1}"; + public string AvatarLevelSet { get; } = "Set character {0}'s {1} level to {2}"; + public string AvatarNotFound { get; } = "Character does not exist!"; + public string AvatarGet { get; } = "Obtained character {0}!"; + public string AvatarFailedGet { get; } = "Failed to obtain character {0}!"; +} + +/// +/// path: Game.Command.Give +/// +public class GiveTextEN +{ + public string Desc { get; } = "Give player items"; + public string Usage { get; } = "/give l x r"; + public string ItemNotFound { get; } = "Item not found!"; + public string GiveItem { get; } = "Gave @{0} {1} item(s) {2}"; +} + +/// +/// path: Game.Command.GiveAll +/// +public class GiveAllTextEN +{ + public string Desc { get; } = "Give the player all specified types of items"; + + public string Usage { get; } = + "/giveall r l x"; + + public string GiveAllItems { get; } = "Gave all {0}, each {1} items"; +} + +/// +/// path: Game.Command.Lineup +/// +public class LineupTextEN +{ + public string Desc { get; } = "Manage player's lineup"; + public string Usage { get; } = "/lineup /"; + public string PlayerGainedMp { get; } = "Player gained {0} skill points"; + public string HealedAllAvatars { get; } = "Successfully healed all characters in the current lineup"; +} + +/// +/// path: Game.Command.Help +/// +public class HelpTextEN +{ + public string Desc { get; } = "Show help information"; + public string Usage { get; } = "/help"; + public string Commands { get; } = "Commands:"; + public string CommandUsage { get; } = "Usage: "; +} + +/// +/// path: Game.Command.Kick +/// +public class KickTextEN +{ + public string Desc { get; } = "Kick out player"; + public string Usage { get; } = "/kick"; + public string PlayerKicked { get; } = "Player {0} has been kicked out!"; +} + +/// +/// path: Game.Command.Mission +/// +public class MissionTextEN +{ + public string Desc { get; } = "Manage player's tasks"; + + public string Usage { get; } = + "/mission ////"; + + public string AllMissionsFinished { get; } = "All tasks have been completed!"; + public string AllRunningMissionsFinished { get; } = "A total of {0} ongoing tasks have been completed!"; + public string MissionFinished { get; } = "Task {0} has been completed!"; + public string InvalidMissionId { get; } = "Invalid task ID!"; + public string NoRunningMissions { get; } = "No ongoing tasks!"; + + public string RunningMissions { get; } = "Ongoing tasks:"; + public string PossibleStuckMissions { get; } = "Possibly stuck tasks:"; + public string MainMission { get; } = "Main task"; + + public string MissionReAccepted { get; } = "Reaccepted task {0}!"; +} + +/// +/// path: Game.Command.Relic +/// +public class RelicTextEN +{ + public string Desc { get; } = "Manage player's relics"; + + public string Usage { get; } = + "/relic
l x"; + + public string RelicNotFound { get; } = "Relic does not exist!"; + public string InvalidMainAffixId { get; } = "Invalid main affix ID"; + public string InvalidSubAffixId { get; } = "Invalid sub affix ID"; + public string RelicGiven { get; } = "Gave player @{0} {1} relic(s) {2}, main affix {3}"; +} + +/// +/// path: Game.Command.Reload +/// +public class ReloadTextEN +{ + public string Desc { get; } = "Reload specified configuration"; + public string Usage { get; } = "/reload (banner - gacha, activity - event)"; + public string ConfigReloaded { get; } = "Configuration {0} has been reloaded!"; +} + +/// +/// path: Game.Command.Rogue +/// +public class RogueTextEN +{ + public string Desc { get; } = "Manage player's data in the simulated universe"; + + public string Usage { get; } = + "/rogue ////"; + + public string PlayerGainedMoney { get; } = "Player gained {0} cosmic fragments"; + public string PlayerGainedAllItems { get; } = "Player gained all {0}"; + public string PlayerGainedItem { get; } = "Player gained {0} {1}"; + public string PlayerEnhancedBuff { get; } = "Player enhanced blessing {0}"; + public string PlayerEnhancedAllBuffs { get; } = "Player enhanced all blessings"; + public string PlayerUnstuck { get; } = "Player unstuck from event"; + public string NotFoundItem { get; } = "{0} not found!"; +} + +/// +/// path: Game.Command.Scene +/// +public class SceneTextEN +{ + public string Desc { get; } = "Manage player's scenes"; + + public string Usage { get; } = + "/scene ////"; + + public string LoadedGroups { get; } = "Loaded groups: {0}"; + public string PropStateChanged { get; } = "Prop: {0} state set to {1}"; + public string PropNotFound { get; } = "Prop not found!"; + public string EntityRemoved { get; } = "Entity {0} has been removed"; + public string EntityNotFound { get; } = "Entity not found!"; + public string AllPropsUnlocked { get; } = "All props have been unlocked!"; + public string SceneChanged { get; } = "Entered scene {0}"; + public string SceneReloaded { get; } = "Scene has been reloaded!"; + public string SceneReset { get; } = "The prop state in floor {0} has been reset!"; +} + +/// +/// path: Game.Command.Mail +/// +public class MailTextEN +{ + public string Desc { get; } = "Manage player's mails"; + + public string Usage { get; } = + "/mail /"; + + public string MailSent { get; } = "Mail has been sent!"; + public string MailSentWithAttachment { get; } = "Mail with attachments has been sent!"; +} + +/// +/// path: Game.Command.Raid +/// +public class RaidTextEN +{ + public string Desc { get; } = "Manage player's temporary scene"; + public string Usage { get; } = "/raid "; + public string Leaved { get; } = "Leaved temporary scene!"; +} + +/// +/// path: Game.Command.Account +/// +public class AccountTextEN +{ + public string Desc { get; } = "Create Account"; + public string Usage { get; } = "/account create "; + public string InvalidUid { get; } = "Invalid UID argument!"; + public string CreateError { get; } = "An internal error occurred {0}"; + public string CreateSuccess { get; } = "New account {0} created successfully!"; + public string DuplicateAccount { get; } = "Account {0} already exists!"; + public string DuplicateUID { get; } = "UID {0} already exists!"; + public string DataError { get; } = "Failed to retrieve new account! {0}!"; +} + +#endregion + +#endregion \ No newline at end of file diff --git a/Common/Util/ConfigManager.cs b/Common/Util/ConfigManager.cs index 651a2ebd..47798fc3 100644 --- a/Common/Util/ConfigManager.cs +++ b/Common/Util/ConfigManager.cs @@ -1,34 +1,35 @@ using EggLink.DanhengServer.Configuration; using Newtonsoft.Json; -namespace EggLink.DanhengServer.Util +namespace EggLink.DanhengServer.Util; + +public static class ConfigManager { - public static class ConfigManager + public static Logger logger = new("ConfigManager"); + public static ConfigContainer Config { get; private set; } = new(); + + public static void LoadConfig() { - public static Logger logger = new("ConfigManager"); - public static ConfigContainer Config { get; private set; } = new ConfigContainer(); - public static void LoadConfig() + var file = new FileInfo("config.json"); + if (!file.Exists) { - var file = new FileInfo("config.json"); - if (!file.Exists) - { - logger.Warn("Config file not found, creating a new one"); - Config = new ConfigContainer(); - Config.MuipServer.AdminKey = Guid.NewGuid().ToString(); - logger.Info("Muipserver Admin key: " + Config.MuipServer.AdminKey); - SaveConfig(); - } - using (var reader = new StreamReader(file.OpenRead())) - { - var json = reader.ReadToEnd(); - Config = JsonConvert.DeserializeObject(json)!; - } + logger.Warn("Config file not found, creating a new one"); + Config = new ConfigContainer(); + Config.MuipServer.AdminKey = Guid.NewGuid().ToString(); + logger.Info("Muipserver Admin key: " + Config.MuipServer.AdminKey); + SaveConfig(); } - public static void SaveConfig() + using (var reader = new StreamReader(file.OpenRead())) { - var json = JsonConvert.SerializeObject(Config, Formatting.Indented); - File.WriteAllText("config.json", json); + var json = reader.ReadToEnd(); + Config = JsonConvert.DeserializeObject(json)!; } } -} + + public static void SaveConfig() + { + var json = JsonConvert.SerializeObject(Config, Formatting.Indented); + File.WriteAllText("config.json", json); + } +} \ No newline at end of file diff --git a/Common/Util/Crypto.cs b/Common/Util/Crypto.cs index f859ab77..bd31fe54 100644 --- a/Common/Util/Crypto.cs +++ b/Common/Util/Crypto.cs @@ -1,50 +1,42 @@ -using System; -using System.Buffers.Text; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; +using System.Security.Cryptography; using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Util +namespace EggLink.DanhengServer.Util; + +public class Crypto { - public class Crypto + private static readonly Random secureRandom = new(); + public static Logger logger = new("Crypto"); + + public static void Xor(byte[] packet, byte[] key) { - private static Random secureRandom = new(); - public static Logger logger = new("Crypto"); - public static void Xor(byte[] packet, byte[] key) + try { - try - { - for (int i = 0; i < packet.Length; i++) - { - packet[i] ^= key[i % key.Length]; - } - } - catch (Exception e) - { - logger.Error("Crypto error.", e); - } + for (var i = 0; i < packet.Length; i++) packet[i] ^= key[i % key.Length]; } - - // Simple way to create a unique session key - public static string CreateSessionKey(string accountUid) + catch (Exception e) { - byte[] random = new byte[64]; - secureRandom.NextBytes(random); - - string temp = accountUid + "." + DateTime.Now.Ticks + "." + secureRandom.ToString(); - - try - { - byte[] bytes = SHA512.HashData(Encoding.UTF8.GetBytes(temp)); - return Convert.ToBase64String(bytes); - } - catch - { - byte[] bytes = SHA512.HashData(Encoding.UTF8.GetBytes(temp)); - return Convert.ToBase64String(bytes); - } + logger.Error("Crypto error.", e); } } -} + + // Simple way to create a unique session key + public static string CreateSessionKey(string accountUid) + { + var random = new byte[64]; + secureRandom.NextBytes(random); + + var temp = accountUid + "." + DateTime.Now.Ticks + "." + secureRandom; + + try + { + var bytes = SHA512.HashData(Encoding.UTF8.GetBytes(temp)); + return Convert.ToBase64String(bytes); + } + catch + { + var bytes = SHA512.HashData(Encoding.UTF8.GetBytes(temp)); + return Convert.ToBase64String(bytes); + } + } +} \ No newline at end of file diff --git a/Common/Util/Extensions.cs b/Common/Util/Extensions.cs index b5973af2..f9c1921d 100644 --- a/Common/Util/Extensions.cs +++ b/Common/Util/Extensions.cs @@ -1,79 +1,11 @@ -using EggLink.DanhengServer.Proto; +using System.Buffers.Binary; +using EggLink.DanhengServer.Proto; using Newtonsoft.Json; -using System.Buffers.Binary; namespace EggLink.DanhengServer.Util; public static class Extensions { - #region Kcp Utils - - public static string JoinFormat(this IEnumerable list, string separator, - string formatString) - { - formatString = string.IsNullOrWhiteSpace(formatString) ? "{0}" : formatString; - return string.Join(separator, - list.Select(item => string.Format(formatString, item))); - } - public static void WriteConvID(this BinaryWriter bw, long convId) - { - //bw.Write(convId); - bw.Write((int)(convId >> 32)); - bw.Write((int)(convId & 0xFFFFFFFF)); - } - - public static long GetNextAvailableIndex(this SortedList sortedList) - { - long key = 1; - long count = sortedList.Count; - long counter = 0; - do - { - if (count == 0) break; - long nextKeyInList = sortedList.Keys.ElementAt((Index)counter++); - if (key != nextKeyInList) break; - key = nextKeyInList + 1; - } while (count != 1 && counter != count && key == sortedList.Keys.ElementAt((Index)counter)); - return key; - } - - public static long AddNext(this SortedList sortedList, T item) - { - long key = sortedList.GetNextAvailableIndex(); - sortedList.Add(key, item); - return key; - } - public static int ReadInt32BE(this BinaryReader br) => BinaryPrimitives.ReadInt32BigEndian(br.ReadBytes(sizeof(int))); - public static uint ReadUInt32BE(this BinaryReader br) => BinaryPrimitives.ReadUInt32BigEndian(br.ReadBytes(sizeof(uint))); - public static ushort ReadUInt16BE(this BinaryReader br) => BinaryPrimitives.ReadUInt16BigEndian(br.ReadBytes(sizeof(ushort))); - public static void WriteUInt16BE(this BinaryWriter bw, ushort value) - { - Span data = stackalloc byte[sizeof(ushort)]; - BinaryPrimitives.WriteUInt16BigEndian(data, value); - bw.Write(data); - } - public static void WriteInt32BE(this BinaryWriter bw, int value) - { - Span data = stackalloc byte[sizeof(int)]; - BinaryPrimitives.WriteInt32BigEndian(data, value); - bw.Write(data); - } - public static void WriteUInt32BE(this BinaryWriter bw, uint value) - { - Span data = stackalloc byte[sizeof(uint)]; - BinaryPrimitives.WriteUInt32BigEndian(data, value); - bw.Write(data); - } - - public static void WriteUInt64BE(this BinaryWriter bw, ulong value) - { - Span data = stackalloc byte[sizeof(ulong)]; - BinaryPrimitives.WriteUInt64BigEndian(data, value); - bw.Write(data); - } - - #endregion - public static Position ToPosition(this Vector vector) { return new Position @@ -84,31 +16,25 @@ public static class Extensions }; } - public static T RandomElement (this List values) + public static T RandomElement(this List values) { var index = new Random().Next(values.Count); return values[index]; } - public static int RandomInt (int from, int to) + public static int RandomInt(int from, int to) { return new Random().Next(from, to); } public static void SafeAdd(this List list, T item) { - if (!list.Contains(item)) - { - list.Add(item); - } + if (!list.Contains(item)) list.Add(item); } public static void SafeAddRange(this List list, List item) { - foreach (var i in item) - { - list.SafeAdd(i); - } + foreach (var i in item) list.SafeAdd(i); } public static long GetUnixSec() @@ -130,8 +56,94 @@ public static class Extensions { return list.JoinFormat(", ", ""); } + public static string ToJsonString(this Dictionary dic) { return JsonConvert.SerializeObject(dic); } -} + + #region Kcp Utils + + public static string JoinFormat(this IEnumerable list, string separator, + string formatString) + { + formatString = string.IsNullOrWhiteSpace(formatString) ? "{0}" : formatString; + return string.Join(separator, + list.Select(item => string.Format(formatString, item))); + } + + public static void WriteConvID(this BinaryWriter bw, long convId) + { + //bw.Write(convId); + bw.Write((int)(convId >> 32)); + bw.Write((int)(convId & 0xFFFFFFFF)); + } + + public static long GetNextAvailableIndex(this SortedList sortedList) + { + long key = 1; + long count = sortedList.Count; + long counter = 0; + do + { + if (count == 0) break; + var nextKeyInList = sortedList.Keys.ElementAt((Index)counter++); + if (key != nextKeyInList) break; + key = nextKeyInList + 1; + } while (count != 1 && counter != count && key == sortedList.Keys.ElementAt((Index)counter)); + + return key; + } + + public static long AddNext(this SortedList sortedList, T item) + { + var key = sortedList.GetNextAvailableIndex(); + sortedList.Add(key, item); + return key; + } + + public static int ReadInt32BE(this BinaryReader br) + { + return BinaryPrimitives.ReadInt32BigEndian(br.ReadBytes(sizeof(int))); + } + + public static uint ReadUInt32BE(this BinaryReader br) + { + return BinaryPrimitives.ReadUInt32BigEndian(br.ReadBytes(sizeof(uint))); + } + + public static ushort ReadUInt16BE(this BinaryReader br) + { + return BinaryPrimitives.ReadUInt16BigEndian(br.ReadBytes(sizeof(ushort))); + } + + public static void WriteUInt16BE(this BinaryWriter bw, ushort value) + { + Span data = stackalloc byte[sizeof(ushort)]; + BinaryPrimitives.WriteUInt16BigEndian(data, value); + bw.Write(data); + } + + public static void WriteInt32BE(this BinaryWriter bw, int value) + { + Span data = stackalloc byte[sizeof(int)]; + BinaryPrimitives.WriteInt32BigEndian(data, value); + bw.Write(data); + } + + public static void WriteUInt32BE(this BinaryWriter bw, uint value) + { + Span data = stackalloc byte[sizeof(uint)]; + BinaryPrimitives.WriteUInt32BigEndian(data, value); + bw.Write(data); + } + + public static void WriteUInt64BE(this BinaryWriter bw, ulong value) + { + Span data = stackalloc byte[sizeof(ulong)]; + BinaryPrimitives.WriteUInt64BigEndian(data, value); + bw.Write(data); + } + + #endregion +} \ No newline at end of file diff --git a/Common/Util/GameConstants.cs b/Common/Util/GameConstants.cs index ed5278f3..3023ee60 100644 --- a/Common/Util/GameConstants.cs +++ b/Common/Util/GameConstants.cs @@ -1,29 +1,28 @@ -namespace EggLink.DanhengServer.Util +namespace EggLink.DanhengServer.Util; + +public static class GameConstants { - public static class GameConstants - { - public const int MATERIAL_HCOIN_ID = 1; // Material id for jades. DO NOT CHANGE - public const int MATERIAL_COIN_ID = 2; // Material id for credits. DO NOT CHANGE - public const int TRAILBLAZER_EXP_ID = 22; - public const int RELIC_REMAINS_ID = 235; + public const int MATERIAL_HCOIN_ID = 1; // Material id for jades. DO NOT CHANGE + public const int MATERIAL_COIN_ID = 2; // Material id for credits. DO NOT CHANGE + public const int TRAILBLAZER_EXP_ID = 22; + public const int RELIC_REMAINS_ID = 235; - public const int INVENTORY_MAX_EQUIPMENT = 1500; - public const int INVENTORY_MAX_RELIC = 1500; - public const int INVENTORY_MAX_MATERIAL = 2000; + public const int INVENTORY_MAX_EQUIPMENT = 1500; + public const int INVENTORY_MAX_RELIC = 1500; + public const int INVENTORY_MAX_MATERIAL = 2000; - public const int MAX_LINEUP_COUNT = 9; + public const int MAX_LINEUP_COUNT = 9; - public static readonly List UpgradeWorldLevel = [20, 30, 40, 50, 60, 65]; - public static readonly List AllowedChessRogueEntranceId = [8020701, 8020901, 8020401, 8020201]; + public const int AMBUSH_BUFF_ID = 1000102; - public const int AMBUSH_BUFF_ID = 1000102; + public const int MAX_STAMINA = 240; + public const int MAX_STAMINA_RESERVE = 2400; + public const int STAMINA_RECOVERY_TIME = 360; // 6 minutes + public const int STAMINA_RESERVE_RECOVERY_TIME = 1080; // 18 minutes - public const int MAX_STAMINA = 240; - public const int MAX_STAMINA_RESERVE = 2400; - public const int STAMINA_RECOVERY_TIME = 360; // 6 minutes - public const int STAMINA_RESERVE_RECOVERY_TIME = 1080; // 18 minutes + public const int CHALLENGE_ENTRANCE = 100000103; + public const int CHALLENGE_STORY_ENTRANCE = 102020107; - public const int CHALLENGE_ENTRANCE = 100000103; - public const int CHALLENGE_STORY_ENTRANCE = 102020107; - } -} + public static readonly List UpgradeWorldLevel = [20, 30, 40, 50, 60, 65]; + public static readonly List AllowedChessRogueEntranceId = [8020701, 8020901, 8020401, 8020201]; +} \ No newline at end of file diff --git a/Common/Util/GameTools.cs b/Common/Util/GameTools.cs index 68e2e7b1..a1f4e9e7 100644 --- a/Common/Util/GameTools.cs +++ b/Common/Util/GameTools.cs @@ -1,35 +1,18 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database.Inventory; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Util +namespace EggLink.DanhengServer.Util; + +public static class GameTools { - public static class GameTools + public static int GetRandomRelicMainAffix(int GroupId) { - public static int GetRandomRelicMainAffix(int GroupId) - { - GameData.RelicMainAffixData.TryGetValue(GroupId, out var affixes); - if (affixes == null) - { - return 0; - } - List affixList = []; - foreach (var affix in affixes.Values) - { - if (affix.IsAvailable) - { - affixList.Add(affix.AffixID); - } - } - if (affixList.Count == 0) - { - return 0; - } - return affixList.RandomElement(); - } + GameData.RelicMainAffixData.TryGetValue(GroupId, out var affixes); + if (affixes == null) return 0; + List affixList = []; + foreach (var affix in affixes.Values) + if (affix.IsAvailable) + affixList.Add(affix.AffixID); + if (affixList.Count == 0) return 0; + return affixList.RandomElement(); } -} +} \ No newline at end of file diff --git a/Common/Util/Logger.cs b/Common/Util/Logger.cs index c3430f59..0d240cca 100644 --- a/Common/Util/Logger.cs +++ b/Common/Util/Logger.cs @@ -1,138 +1,129 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Diagnostics; -namespace EggLink.DanhengServer.Util +namespace EggLink.DanhengServer.Util; + +public class Logger(string moduleName) { - public class Logger(string moduleName) + private static FileInfo? LogFile; + private static readonly object _lock = new(); + private readonly string ModuleName = moduleName; + + public void Log(string message, LoggerLevel level) { - private readonly string ModuleName = moduleName; - private static FileInfo? LogFile; - private static object _lock = new(); - - public void Log(string message, LoggerLevel level) + lock (_lock) { - lock (_lock) - { - Console.Write("["); + Console.Write("["); - Console.ForegroundColor = ConsoleColor.DarkCyan; - Console.Write(DateTime.Now.ToString("HH:mm:ss")); - Console.ResetColor(); + Console.ForegroundColor = ConsoleColor.DarkCyan; + Console.Write(DateTime.Now.ToString("HH:mm:ss")); + Console.ResetColor(); - Console.Write("] "); - Console.Write("["); + Console.Write("] "); + Console.Write("["); - Console.ForegroundColor = ConsoleColor.DarkGray; - Console.Write(ModuleName); - Console.ResetColor(); + Console.ForegroundColor = ConsoleColor.DarkGray; + Console.Write(ModuleName); + Console.ResetColor(); - Console.Write("] "); - Console.Write("["); + Console.Write("] "); + Console.Write("["); - Console.ForegroundColor = (ConsoleColor)level; - Console.Write(level); - Console.ResetColor(); + Console.ForegroundColor = (ConsoleColor)level; + Console.Write(level); + Console.ResetColor(); - Console.WriteLine("] " + message); + Console.WriteLine("] " + message); - var logMessage = $"[{DateTime.Now:HH:mm:ss}] [{ModuleName}] [{level}] {message}"; - WriteToFile(logMessage); - } + var logMessage = $"[{DateTime.Now:HH:mm:ss}] [{ModuleName}] [{level}] {message}"; + WriteToFile(logMessage); } + } - public void Info(string message, Exception? e = null) + public void Info(string message, Exception? e = null) + { + Log(message, LoggerLevel.INFO); + if (e != null) { - Log(message, LoggerLevel.INFO); - if (e != null) - { - Log(e.Message, LoggerLevel.INFO); - Log(e.StackTrace!, LoggerLevel.INFO); - } + Log(e.Message, LoggerLevel.INFO); + Log(e.StackTrace!, LoggerLevel.INFO); } + } - public void Warn(string message, Exception? e = null) + public void Warn(string message, Exception? e = null) + { + Log(message, LoggerLevel.WARN); + if (e != null) { - Log(message, LoggerLevel.WARN); - if (e != null) - { - Log(e.Message, LoggerLevel.WARN); - Log(e.StackTrace!, LoggerLevel.WARN); - } + Log(e.Message, LoggerLevel.WARN); + Log(e.StackTrace!, LoggerLevel.WARN); } + } - public void Error(string message, Exception? e = null) + public void Error(string message, Exception? e = null) + { + Log(message, LoggerLevel.ERROR); + if (e != null) { - Log(message, LoggerLevel.ERROR); - if (e != null) - { - Log(e.Message, LoggerLevel.ERROR); - Log(e.StackTrace!, LoggerLevel.ERROR); - } + Log(e.Message, LoggerLevel.ERROR); + Log(e.StackTrace!, LoggerLevel.ERROR); } + } - public void Fatal(string message, Exception? e = null) + public void Fatal(string message, Exception? e = null) + { + Log(message, LoggerLevel.FATAL); + if (e != null) { - Log(message, LoggerLevel.FATAL); - if (e != null) - { - Log(e.Message, LoggerLevel.FATAL); - Log(e.StackTrace!, LoggerLevel.FATAL); - } + Log(e.Message, LoggerLevel.FATAL); + Log(e.StackTrace!, LoggerLevel.FATAL); } + } - public void Debug(string message, Exception? e = null) + public void Debug(string message, Exception? e = null) + { + Log(message, LoggerLevel.DEBUG); + if (e != null) { - Log(message, LoggerLevel.DEBUG); - if (e != null) - { - Log(e.Message, LoggerLevel.DEBUG); - Log(e.StackTrace!, LoggerLevel.DEBUG); - } + Log(e.Message, LoggerLevel.DEBUG); + Log(e.StackTrace!, LoggerLevel.DEBUG); } + } - public static void SetLogFile(FileInfo file) + public static void SetLogFile(FileInfo file) + { + LogFile = file; + } + + public static void WriteToFile(string message) + { + try { - LogFile = file; + if (LogFile == null) throw new Exception("LogFile is not set"); + using var sw = LogFile.AppendText(); + sw.WriteLine(message); } - - public static void WriteToFile(string message) + catch { - try - { - if (LogFile == null) - { - throw new Exception("LogFile is not set"); - } - using StreamWriter sw = LogFile.AppendText(); - sw.WriteLine(message); - } - catch - { - - } } + } -#pragma warning disable CS8602 - public static Logger GetByClassName() => new(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Name); +#pragma warning disable CS8602 + public static Logger GetByClassName() + { + return new Logger(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Name); + } #pragma warning restore CS8602 - } - - public enum LoggerLevel - { - INFO = ConsoleColor.Cyan, - WARN = ConsoleColor.Yellow, - ERROR = ConsoleColor.Red, - FATAL = ConsoleColor.DarkRed, - DEBUG = ConsoleColor.Blue - } - - public class LoggerLevelHelper - { - - } } + +public enum LoggerLevel +{ + INFO = ConsoleColor.Cyan, + WARN = ConsoleColor.Yellow, + ERROR = ConsoleColor.Red, + FATAL = ConsoleColor.DarkRed, + DEBUG = ConsoleColor.Blue +} + +public class LoggerLevelHelper +{ +} \ No newline at end of file diff --git a/Common/Util/Position.cs b/Common/Util/Position.cs index 07ac29bc..1bea3d38 100644 --- a/Common/Util/Position.cs +++ b/Common/Util/Position.cs @@ -1,138 +1,132 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Util +namespace EggLink.DanhengServer.Util; + +public class Position { - public class Position + public Position(int x, int y, int z) { - public int X { get; set; } - public int Y { get; set; } - public int Z { get; set; } - - public Position(int x, int y, int z) - { - X = x; - Y = y; - Z = z; - } - - public Position(Vector vector) - { - X = vector.X; - Y = vector.Y; - Z = vector.Z; - } - - public Position() - { - X = 0; - Y = 0; - Z = 0; - } - - public Position(Position position) - { - X = position.X; - Y = position.Y; - Z = position.Z; - } - - public void Set(int x, int y, int z) - { - X = x; - Y = y; - Z = z; - } - - public void Set(Position position) - { - X = position.X; - Y = position.Y; - Z = position.Z; - } - - public void Set(Vector vector) - { - X = vector.X; - Y = vector.Y; - Z = vector.Z; - } - - public void Add(int x, int y, int z) - { - X += x; - Y += y; - Z += z; - } - - public void Add(Position position) - { - X += position.X; - Y += position.Y; - Z += position.Z; - } - - public void Sub(int x, int y, int z) - { - X -= x; - Y -= y; - Z -= z; - } - - public void Sub(Position position) - { - X -= position.X; - Y -= position.Y; - Z -= position.Z; - } - - public void Mul(int x, int y, int z) - { - X *= x; - Y *= y; - Z *= z; - } - - public void Mul(Position position) - { - X *= position.X; - Y *= position.Y; - Z *= position.Z; - } - - public void Div(int x, int y, int z) - { - X /= x; - Y /= y; - Z /= z; - } - - public void Div(Position position) - { - X /= position.X; - Y /= position.Y; - Z /= position.Z; - } - - public Vector ToProto() - { - return new() - { - X = X, - Y = Y, - Z = Z - }; - } - - public long GetFast2dDist(Position pos) - { - long x = X - pos.X; - long z = Z - pos.Z; - return (x * x) + (z * z); - } + X = x; + Y = y; + Z = z; } -} + + public Position(Vector vector) + { + X = vector.X; + Y = vector.Y; + Z = vector.Z; + } + + public Position() + { + X = 0; + Y = 0; + Z = 0; + } + + public Position(Position position) + { + X = position.X; + Y = position.Y; + Z = position.Z; + } + + public int X { get; set; } + public int Y { get; set; } + public int Z { get; set; } + + public void Set(int x, int y, int z) + { + X = x; + Y = y; + Z = z; + } + + public void Set(Position position) + { + X = position.X; + Y = position.Y; + Z = position.Z; + } + + public void Set(Vector vector) + { + X = vector.X; + Y = vector.Y; + Z = vector.Z; + } + + public void Add(int x, int y, int z) + { + X += x; + Y += y; + Z += z; + } + + public void Add(Position position) + { + X += position.X; + Y += position.Y; + Z += position.Z; + } + + public void Sub(int x, int y, int z) + { + X -= x; + Y -= y; + Z -= z; + } + + public void Sub(Position position) + { + X -= position.X; + Y -= position.Y; + Z -= position.Z; + } + + public void Mul(int x, int y, int z) + { + X *= x; + Y *= y; + Z *= z; + } + + public void Mul(Position position) + { + X *= position.X; + Y *= position.Y; + Z *= position.Z; + } + + public void Div(int x, int y, int z) + { + X /= x; + Y /= y; + Z /= z; + } + + public void Div(Position position) + { + X /= position.X; + Y /= position.Y; + Z /= position.Z; + } + + public Vector ToProto() + { + return new Vector + { + X = X, + Y = Y, + Z = Z + }; + } + + public long GetFast2dDist(Position pos) + { + long x = X - pos.X; + long z = Z - pos.Z; + return x * x + z * z; + } +} \ No newline at end of file diff --git a/Common/Util/RandomList.cs b/Common/Util/RandomList.cs index 0db33501..4798b8e5 100644 --- a/Common/Util/RandomList.cs +++ b/Common/Util/RandomList.cs @@ -1,75 +1,55 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Util +/// +/// A list that can be used to randomly select an element with a certain weight from it. +/// +/// +public class RandomList { - /// - /// A list that can be used to randomly select an element with a certain weight from it. - /// - /// - public class RandomList + private readonly List _List = []; + + public RandomList() { - private readonly List _List = []; - - public RandomList() - { - } - - public RandomList(IEnumerable collection) - { - _List.AddRange(collection); - } - - public void Add(T item, int weight) - { - for (int i = 0; i < weight; i++) - { - _List.Add(item); - } - } - - public void Remove(T item) - { - var temp = _List.ToList(); - _List.Clear(); - foreach (var i in temp) - { - if (i?.Equals(item) == false) - { - _List.Add(i); - } - } - } - - public void AddRange(IEnumerable collection, IEnumerable weights) - { - var list = collection.ToList(); - for (int i = 0; i < list.Count; i++) - { - Add(list[i], weights.ElementAt(i)); - } - } - - public T? GetRandom() - { - if (_List.Count == 0) - { - return default; - } - return _List[Random.Shared.Next(_List.Count)]; - } - - public void Clear() - { - _List.Clear(); - } - - public int GetCount() - { - return _List.Count; - } } -} + + public RandomList(IEnumerable collection) + { + _List.AddRange(collection); + } + + public void Add(T item, int weight) + { + for (var i = 0; i < weight; i++) _List.Add(item); + } + + public void Remove(T item) + { + var temp = _List.ToList(); + _List.Clear(); + foreach (var i in temp) + if (i?.Equals(item) == false) + _List.Add(i); + } + + public void AddRange(IEnumerable collection, IEnumerable weights) + { + var list = collection.ToList(); + for (var i = 0; i < list.Count; i++) Add(list[i], weights.ElementAt(i)); + } + + public T? GetRandom() + { + if (_List.Count == 0) return default; + return _List[Random.Shared.Next(_List.Count)]; + } + + public void Clear() + { + _List.Clear(); + } + + public int GetCount() + { + return _List.Count; + } +} \ No newline at end of file diff --git a/GameServer/Command/CommandExecutor.cs b/GameServer/Command/CommandExecutor.cs index f731e818..60d4d896 100644 --- a/GameServer/Command/CommandExecutor.cs +++ b/GameServer/Command/CommandExecutor.cs @@ -1,20 +1,15 @@ using EggLink.DanhengServer.Command; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Command +namespace EggLink.DanhengServer.GameServer.Command; + +public static class CommandExecutor { - public static class CommandExecutor - { - public delegate void RunCommand(ICommandSender sender, string cmd); - public static event RunCommand? OnRunCommand; + public delegate void RunCommand(ICommandSender sender, string cmd); - public static void ExecuteCommand(ICommandSender sender, string cmd) - { - OnRunCommand?.Invoke(sender, cmd); - } + public static event RunCommand? OnRunCommand; + + public static void ExecuteCommand(ICommandSender sender, string cmd) + { + OnRunCommand?.Invoke(sender, cmd); } -} +} \ No newline at end of file diff --git a/GameServer/Command/PlayerCommandSender.cs b/GameServer/Command/PlayerCommandSender.cs index 341e6e95..4913aeae 100644 --- a/GameServer/Command/PlayerCommandSender.cs +++ b/GameServer/Command/PlayerCommandSender.cs @@ -1,35 +1,30 @@ using EggLink.DanhengServer.Command; -using EggLink.DanhengServer.Database.Account; using EggLink.DanhengServer.Database; +using EggLink.DanhengServer.Database.Account; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Server.Packet.Send.Friend; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Command +namespace EggLink.DanhengServer.GameServer.Command; + +public class PlayerCommandSender(PlayerInstance player) : ICommandSender { - public class PlayerCommandSender(PlayerInstance player) : ICommandSender + public PlayerInstance Player = player; + + public async ValueTask SendMsg(string msg) { - public PlayerInstance Player = player; - - public void SendMsg(string msg) - { - Player.SendPacket(new PacketRevcMsgScNotify(toUid: (uint)Player.Uid, fromUid: (uint)ConfigManager.Config.ServerOption.ServerProfile.Uid, msg.Replace("\n", " "))); - } - - public bool HasPermission(string permission) - { - var account = DatabaseHelper.Instance!.GetInstance(Player.Uid)!; - return account.Permissions!.Contains(permission); - } - - public int GetSender() - { - return Player.Uid; - } + await Player.SendPacket(new PacketRevcMsgScNotify((uint)Player.Uid, + (uint)ConfigManager.Config.ServerOption.ServerProfile.Uid, msg.Replace("\n", " "))); } -} + + public bool HasPermission(string permission) + { + var account = DatabaseHelper.Instance!.GetInstance(Player.Uid)!; + return account.Permissions!.Contains(permission); + } + + public int GetSender() + { + return Player.Uid; + } +} \ No newline at end of file diff --git a/GameServer/Game/Activity/ActivityManager.cs b/GameServer/Game/Activity/ActivityManager.cs index b16eaeae..5ca1d1be 100644 --- a/GameServer/Game/Activity/ActivityManager.cs +++ b/GameServer/Game/Activity/ActivityManager.cs @@ -1,32 +1,24 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Activity +namespace EggLink.DanhengServer.Game.Activity; + +public class ActivityManager(PlayerInstance player) : BasePlayerManager(player) { - public class ActivityManager(PlayerInstance player) : BasePlayerManager(player) + public List ToProto() { - public List ToProto() - { - var proto = new List(); + var proto = new List(); - foreach (var activity in GameData.ActivityConfig.ScheduleData) + foreach (var activity in GameData.ActivityConfig.ScheduleData) + proto.Add(new ActivityScheduleData { - proto.Add(new ActivityScheduleData() - { - ActivityId = (uint)activity.ActivityId, - BeginTime = activity.BeginTime, - EndTime = activity.EndTime, - PanelId = (uint)activity.PanelId, - }); - } + ActivityId = (uint)activity.ActivityId, + BeginTime = activity.BeginTime, + EndTime = activity.EndTime, + PanelId = (uint)activity.PanelId + }); - return proto; - } + return proto; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Avatar/AvatarManager.cs b/GameServer/Game/Avatar/AvatarManager.cs index c456520f..94d24734 100644 --- a/GameServer/Game/Avatar/AvatarManager.cs +++ b/GameServer/Game/Avatar/AvatarManager.cs @@ -3,75 +3,68 @@ using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Avatar; using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Avatar; using EggLink.DanhengServer.Server.Packet.Send.Player; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Avatar +namespace EggLink.DanhengServer.Game.Avatar; + +public class AvatarManager : BasePlayerManager { - public class AvatarManager : BasePlayerManager + public AvatarManager(PlayerInstance player) : base(player) { - public AvatarData AvatarData { get; private set; } - - public AvatarManager(PlayerInstance player) : base(player) + AvatarData = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + foreach (var avatar in AvatarData.Avatars) { - AvatarData = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); - foreach (var avatar in AvatarData.Avatars) - { - avatar.PlayerData = player.Data; - avatar.Excel = GameData.AvatarConfigData[avatar.AvatarId]; - } - } - - public AvatarConfigExcel? AddAvatar(int avatarId, bool sync = true, bool notify = true, bool isGacha = false) - { - GameData.AvatarConfigData.TryGetValue(avatarId, out AvatarConfigExcel? avatarExcel); - if (avatarExcel == null) - { - return null; - } - - if (AvatarData.Avatars.Find(x => x.AvatarId == avatarId) != null) return null; - - var avatar = new AvatarInfo(avatarExcel) - { - AvatarId = avatarId >= 8001 ? 8001 : avatarId, - Level = 1, - Timestamp = Extensions.GetUnixSec(), - CurrentHp = 10000, - CurrentSp = 0 - }; - - if (avatarId >= 8001) - { - if (GetHero() != null) return null; // Only one hero - avatar.HeroId = avatarId; - } - - avatar.PlayerData = Player.Data; - AvatarData.Avatars.Add(avatar); - - if (sync) - Player.SendPacket(new PacketPlayerSyncScNotify(avatar)); - - if (notify) - { - Player.SendPacket(new PacketAddAvatarScNotify(avatar.GetBaseAvatarId(), isGacha)); - } - - return avatarExcel; - } - - public AvatarInfo? GetAvatar(int baseAvatarId) - { - if (baseAvatarId > 8000) baseAvatarId = 8001; - return AvatarData.Avatars.Find(avatar => avatar.AvatarId == baseAvatarId); - } - - public AvatarInfo? GetHero() - { - return AvatarData.Avatars.Find(avatar => avatar.HeroId > 0); + avatar.PlayerData = player.Data; + avatar.Excel = GameData.AvatarConfigData[avatar.AvatarId]; } } -} + + public AvatarData AvatarData { get; } + + public async ValueTask AddAvatar(int avatarId, bool sync = true, bool notify = true, + bool isGacha = false) + { + GameData.AvatarConfigData.TryGetValue(avatarId, out var avatarExcel); + if (avatarExcel == null) return null; + + if (AvatarData.Avatars.Find(x => x.AvatarId == avatarId) != null) return null; + + var avatar = new AvatarInfo(avatarExcel) + { + AvatarId = avatarId >= 8001 ? 8001 : avatarId, + Level = 1, + Timestamp = Extensions.GetUnixSec(), + CurrentHp = 10000, + CurrentSp = 0 + }; + + if (avatarId >= 8001) + { + if (GetHero() != null) return null; // Only one hero + avatar.HeroId = avatarId; + } + + avatar.PlayerData = Player.Data; + AvatarData.Avatars.Add(avatar); + + if (sync) + await Player.SendPacket(new PacketPlayerSyncScNotify(avatar)); + + if (notify) await Player.SendPacket(new PacketAddAvatarScNotify(avatar.GetBaseAvatarId(), isGacha)); + + return avatarExcel; + } + + public AvatarInfo? GetAvatar(int baseAvatarId) + { + if (baseAvatarId > 8000) baseAvatarId = 8001; + return AvatarData.Avatars.Find(avatar => avatar.AvatarId == baseAvatarId); + } + + public AvatarInfo? GetHero() + { + return AvatarData.Avatars.Find(avatar => avatar.HeroId > 0); + } +} \ No newline at end of file diff --git a/GameServer/Game/BasePlayerManager.cs b/GameServer/Game/BasePlayerManager.cs index a6fcde69..23815255 100644 --- a/GameServer/Game/BasePlayerManager.cs +++ b/GameServer/Game/BasePlayerManager.cs @@ -1,14 +1,8 @@ using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game +namespace EggLink.DanhengServer.Game; + +public class BasePlayerManager(PlayerInstance player) { - public class BasePlayerManager(PlayerInstance player) - { - public PlayerInstance Player { get; private set; } = player; - } -} + public PlayerInstance Player { get; private set; } = player; +} \ No newline at end of file diff --git a/GameServer/Game/Battle/BattleEventInstance.cs b/GameServer/Game/Battle/BattleEventInstance.cs index a2866d40..eb8e6a40 100644 --- a/GameServer/Game/Battle/BattleEventInstance.cs +++ b/GameServer/Game/Battle/BattleEventInstance.cs @@ -1,40 +1,36 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Battle +namespace EggLink.DanhengServer.Game.Battle; + +public class BattleEventInstance(int battleEventId, int curSp, int maxSp = 10000) { - public class BattleEventInstance(int battleEventId, int curSp, int maxSp = 10000) + public int BattleEventId { get; set; } = battleEventId; + public int CurSp { get; set; } = curSp; + public int MaxSp { get; set; } = maxSp; + + public void AddSp(int sp) { - public int BattleEventId { get; set; } = battleEventId; - public int CurSp { get; set; } = curSp; - public int MaxSp { get; set; } = maxSp; + CurSp = Math.Min(CurSp + sp, MaxSp); + } - public void AddSp(int sp) - { - CurSp = Math.Min(CurSp + sp, MaxSp); - } + public void SubSp(int sp) + { + CurSp = Math.Max(CurSp - sp, 0); + } - public void SubSp(int sp) - { - CurSp = Math.Max(CurSp - sp, 0); - } - - public BattleEventBattleInfo ToProto() => new() + public BattleEventBattleInfo ToProto() + { + return new BattleEventBattleInfo { BattleEventId = (uint)BattleEventId, - Status = new() + Status = new BattleEventProperty { - SpBar = new() + SpBar = new SpBarInfo { CurSp = (uint)CurSp, MaxSp = (uint)MaxSp } - }, - SkillInfo = { } + } }; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Battle/BattleInstance.cs b/GameServer/Game/Battle/BattleInstance.cs index b56e6c62..44824e7f 100644 --- a/GameServer/Game/Battle/BattleInstance.cs +++ b/GameServer/Game/Battle/BattleInstance.cs @@ -7,245 +7,216 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Proto; -using Google.Protobuf; +using LineupInfo = EggLink.DanhengServer.Database.Lineup.LineupInfo; -namespace EggLink.DanhengServer.Game.Battle +namespace EggLink.DanhengServer.Game.Battle; + +public class BattleInstance(PlayerInstance player, LineupInfo lineup, List stages) + : BasePlayerManager(player) { - public class BattleInstance(PlayerInstance player, Database.Lineup.LineupInfo lineup, List stages) : BasePlayerManager(player) + public BattleInstance(PlayerInstance player, LineupInfo lineup, List monsters) : this(player, lineup, + new List()) { - public int BattleId { get; set; } = ++player.NextBattleId; - public int StaminaCost { get; set; } - public int WorldLevel { get; set; } - public int CocoonWave { get; set; } - public int MappingInfoId { get; set; } - public int RoundLimit { get; set; } - public int StageId { get; set; } = stages.Count > 0 ? stages[0].StageID : 0; // Set to 0 when hit monster - public int EventId { get; set; } - public int CustomLevel { get; set; } - public BattleEndStatus BattleEndStatus { get; set; } - - public List MonsterDropItems { get; set; } = []; - - public List Stages { get; set; } = stages; - public Database.Lineup.LineupInfo Lineup { get; set; } = lineup; - public List EntityMonsters { get; set; } = []; - public List AvatarInfo { get; set; } = []; - public List Buffs { get; set; } = []; - public Dictionary BattleEvents { get; set; } = []; - public Dictionary BattleTargets { get; set; } = []; - - public BattleInstance(PlayerInstance player, Database.Lineup.LineupInfo lineup, List monsters) : this(player, lineup, new List()) + foreach (var monster in monsters) { - foreach (var monster in monsters) + var id = monster.GetStageId(); + GameData.StageConfigData.TryGetValue(id, out var stage); + if (stage != null) Stages.Add(stage); + } + + EntityMonsters = monsters; + StageId = Stages[0].StageID; + } + + public int BattleId { get; set; } = ++player.NextBattleId; + public int StaminaCost { get; set; } + public int WorldLevel { get; set; } + public int CocoonWave { get; set; } + public int MappingInfoId { get; set; } + public int RoundLimit { get; set; } + public int StageId { get; set; } = stages.Count > 0 ? stages[0].StageID : 0; // Set to 0 when hit monster + public int EventId { get; set; } + public int CustomLevel { get; set; } + public BattleEndStatus BattleEndStatus { get; set; } + + public List MonsterDropItems { get; set; } = []; + + public List Stages { get; set; } = stages; + public LineupInfo Lineup { get; set; } = lineup; + public List EntityMonsters { get; set; } = []; + public List AvatarInfo { get; set; } = []; + public List Buffs { get; set; } = []; + public Dictionary BattleEvents { get; set; } = []; + public Dictionary BattleTargets { get; set; } = []; + + public ItemList GetDropItemList() + { + if (BattleEndStatus != BattleEndStatus.BattleEndWin) return new ItemList(); + var list = new ItemList(); + + foreach (var item in MonsterDropItems) list.ItemList_.Add(item.ToProto()); + + var t = System.Threading.Tasks.Task.Run(async () => + { + foreach (var item in await Player.InventoryManager!.HandleMappingInfo(MappingInfoId, WorldLevel)) + list.ItemList_.Add(item.ToProto()); + }); + t.Wait(); + + return list; + } + + public void AddBattleTarget(int key, int targetId, int progress, int totalProgress = 0) + { + if (!BattleTargets.TryGetValue(key, out var value)) + { + value = new BattleTargetList(); + BattleTargets.Add(key, value); + } + + var battleTarget = new BattleTarget + { + Id = (uint)targetId, + Progress = (uint)progress, + TotalProgress = (uint)totalProgress + }; + value.BattleTargetList_.Add(battleTarget); + } + + public Dictionary GetBattleAvatars() + { + var excel = GameData.StageConfigData[StageId]; + List list = [.. excel.TrialAvatarList]; + + if (list.Count > 0) + { + if (Player.Data.CurrentGender == Gender.Man) { - var id = monster.GetStageId(); - GameData.StageConfigData.TryGetValue(id, out var stage); - if (stage != null) + foreach (var avatar in excel.TrialAvatarList) + if (avatar > 10000) // else is Base Avatar + if (avatar.ToString().EndsWith("8002") || + avatar.ToString().EndsWith("8004") || + avatar.ToString().EndsWith("8006")) + list.Remove(avatar); + } + else + { + foreach (var avatar in excel.TrialAvatarList) + if (avatar > 10000) // else is Base Avatar + if (avatar.ToString().EndsWith("8001") || + avatar.ToString().EndsWith("8003") || + avatar.ToString().EndsWith("8005")) + list.Remove(avatar); + } + } + + if (list.Count > 0) + { + Dictionary dict = []; + foreach (var avatar in list) + { + GameData.SpecialAvatarData.TryGetValue(avatar * 10 + Player.Data.WorldLevel, out var specialAvatar); + if (specialAvatar != null) { - Stages.Add(stage); + dict.Add(specialAvatar.ToAvatarData(Player.Uid), AvatarType.AvatarTrialType); + } + else + { + var avatarInfo = Player.AvatarManager!.GetAvatar(avatar); + if (avatarInfo != null) dict.Add(avatarInfo, AvatarType.AvatarFormalType); } } - EntityMonsters = monsters; - StageId = Stages[0].StageID; + + return dict; } - - public ItemList GetDropItemList() + else { - if (BattleEndStatus != BattleEndStatus.BattleEndWin) return new(); - var list = new ItemList(); - - foreach (var item in MonsterDropItems) + Dictionary dict = []; + foreach (var avatar in Lineup.BaseAvatars!) { - list.ItemList_.Add(item.ToProto()); - } + AvatarInfo? avatarInstance = null; + var avatarType = AvatarType.AvatarFormalType; - foreach (var item in Player.InventoryManager!.HandleMappingInfo(MappingInfoId, WorldLevel)) - { - list.ItemList_.Add(item.ToProto()); - } - - return list; - } - - public void AddBattleTarget(int key, int targetId, int progress, int totalProgress = 0) - { - if (!BattleTargets.TryGetValue(key, out BattleTargetList? value)) - { - value = new BattleTargetList(); - BattleTargets.Add(key, value); - } - - var battleTarget = new BattleTarget() - { - Id = (uint)targetId, - Progress = (uint)progress, - TotalProgress = (uint)totalProgress - }; - value.BattleTargetList_.Add(battleTarget); - } - - public Dictionary GetBattleAvatars() - { - var excel = GameData.StageConfigData[StageId]; - List list = [.. excel.TrialAvatarList]; - - if (list.Count > 0) - { - if (Player.Data.CurrentGender == Gender.Man) + if (avatar.AssistUid != 0) { - foreach (var avatar in excel.TrialAvatarList) + var player = DatabaseHelper.Instance!.GetInstance(avatar.AssistUid); + if (player != null) { - if (avatar > 10000) // else is Base Avatar - { - if (avatar.ToString().EndsWith("8002") || - avatar.ToString().EndsWith("8004") || - avatar.ToString().EndsWith("8006")) - { - list.Remove(avatar); - } - } + avatarInstance = player.Avatars!.Find(item => item.GetAvatarId() == avatar.BaseAvatarId); + avatarType = AvatarType.AvatarAssistType; + } + } + else if (avatar.SpecialAvatarId != 0) + { + GameData.SpecialAvatarData.TryGetValue(avatar.SpecialAvatarId, out var specialAvatar); + if (specialAvatar != null) + { + avatarInstance = specialAvatar.ToAvatarData(Player.Uid); + avatarType = AvatarType.AvatarTrialType; } } else { - foreach (var avatar in excel.TrialAvatarList) - { - if (avatar > 10000) // else is Base Avatar - { - if (avatar.ToString().EndsWith("8001") || - avatar.ToString().EndsWith("8003") || - avatar.ToString().EndsWith("8005")) - { - list.Remove(avatar); - } - } - } - } - } - - if (list.Count > 0) - { - Dictionary dict = []; - foreach (var avatar in list) - { - GameData.SpecialAvatarData.TryGetValue(avatar * 10 + Player.Data.WorldLevel, out var specialAvatar); - if (specialAvatar != null) - { - dict.Add(specialAvatar.ToAvatarData(Player.Uid), AvatarType.AvatarTrialType); - } - else - { - var avatarInfo = Player.AvatarManager!.GetAvatar(avatar); - if (avatarInfo != null) - { - dict.Add(avatarInfo, AvatarType.AvatarFormalType); - } - } + avatarInstance = Player.AvatarManager!.GetAvatar(avatar.BaseAvatarId); } - return dict; - } - else - { - Dictionary dict = []; - foreach (var avatar in Lineup.BaseAvatars!) - { - AvatarInfo? avatarInstance = null; - AvatarType avatarType = AvatarType.AvatarFormalType; + if (avatarInstance == null) continue; - if (avatar.AssistUid != 0) - { - var player = DatabaseHelper.Instance!.GetInstance(avatar.AssistUid); - if (player != null) - { - avatarInstance = player.Avatars!.Find(item => item.GetAvatarId() == avatar.BaseAvatarId); - avatarType = AvatarType.AvatarAssistType; - } - } - else if (avatar.SpecialAvatarId != 0) - { - GameData.SpecialAvatarData.TryGetValue(avatar.SpecialAvatarId, out var specialAvatar); - if (specialAvatar != null) - { - avatarInstance = specialAvatar.ToAvatarData(Player.Uid); - avatarType = AvatarType.AvatarTrialType; - } - } - else - { - avatarInstance = Player.AvatarManager!.GetAvatar(avatar.BaseAvatarId); - } - if (avatarInstance == null) continue; - - dict.Add(avatarInstance, avatarType); - } - - return dict; - } - } - - public SceneBattleInfo ToProto() - { - var proto = new SceneBattleInfo() - { - BattleId = (uint)BattleId, - WorldLevel = (uint)WorldLevel, - RoundsLimit = (uint)RoundLimit, - StageId = (uint)StageId, - LogicRandomSeed = (uint)Random.Shared.Next(), - }; - - foreach (var wave in Stages) - { - var protoWave = wave.ToProto(); - if (CustomLevel > 0) - { - foreach (var item in protoWave) - { - item.MonsterParam.Level = (uint)CustomLevel; - } - } - proto.MonsterWaveList.AddRange(protoWave); + dict.Add(avatarInstance, avatarType); } - foreach (var avatar in GetBattleAvatars()) - { - proto.AvatarBattleList.Add(avatar.Key.ToBattleProto(Player.LineupManager!.GetCurLineup()!, Player.InventoryManager!.Data, avatar.Value)); - } - - foreach (var monster in EntityMonsters) - { - monster.ApplyBuff(this); - } - - foreach (var avatar in AvatarInfo) - { - avatar.ApplyBuff(this); - } - - foreach (var eventInstance in BattleEvents.Values) - { - proto.BattleEvent.Add(eventInstance.ToProto()); - } - - if (BattleTargets != null) - { - for (int i = 1; i <= 5; i++) - { - var battleTargetEntry = new BattleTargetList(); - - if (BattleTargets.ContainsKey(i)) - { - var battleTargetList = BattleTargets[i]; - battleTargetEntry.BattleTargetList_.AddRange(battleTargetList.BattleTargetList_); - } - - proto.BattleTargetInfo.Add((uint)i, battleTargetEntry); - } - } - - proto.BuffList.AddRange(Buffs.Select(buff => buff.ToProto(this))); - return proto; + return dict; } } -} + + public SceneBattleInfo ToProto() + { + var proto = new SceneBattleInfo + { + BattleId = (uint)BattleId, + WorldLevel = (uint)WorldLevel, + RoundsLimit = (uint)RoundLimit, + StageId = (uint)StageId, + LogicRandomSeed = (uint)Random.Shared.Next() + }; + + foreach (var wave in Stages) + { + var protoWave = wave.ToProto(); + if (CustomLevel > 0) + foreach (var item in protoWave) + item.MonsterParam.Level = (uint)CustomLevel; + proto.MonsterWaveList.AddRange(protoWave); + } + + foreach (var avatar in GetBattleAvatars()) + proto.AvatarBattleList.Add(avatar.Key.ToBattleProto(Player.LineupManager!.GetCurLineup()!, + Player.InventoryManager!.Data, avatar.Value)); + + System.Threading.Tasks.Task.Run(async () => + { + foreach (var monster in EntityMonsters) await monster.ApplyBuff(this); + + foreach (var avatar in AvatarInfo) await avatar.ApplyBuff(this); + }).Wait(); + + foreach (var eventInstance in BattleEvents.Values) proto.BattleEvent.Add(eventInstance.ToProto()); + + if (BattleTargets != null) + for (var i = 1; i <= 5; i++) + { + var battleTargetEntry = new BattleTargetList(); + + if (BattleTargets.ContainsKey(i)) + { + var battleTargetList = BattleTargets[i]; + battleTargetEntry.BattleTargetList_.AddRange(battleTargetList.BattleTargetList_); + } + + proto.BattleTargetInfo.Add((uint)i, battleTargetEntry); + } + + proto.BuffList.AddRange(Buffs.Select(buff => buff.ToProto(this))); + return proto; + } +} \ No newline at end of file diff --git a/GameServer/Game/Battle/BattleManager.cs b/GameServer/Game/Battle/BattleManager.cs index ade00898..0a6b5a50 100644 --- a/GameServer/Game/Battle/BattleManager.cs +++ b/GameServer/Game/Battle/BattleManager.cs @@ -11,205 +11,152 @@ using EggLink.DanhengServer.Server.Packet.Send.Battle; using EggLink.DanhengServer.Server.Packet.Send.Lineup; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Battle +namespace EggLink.DanhengServer.Game.Battle; + +public class BattleManager(PlayerInstance player) : BasePlayerManager(player) { - public class BattleManager(PlayerInstance player) : BasePlayerManager(player) + public async ValueTask StartBattle(SceneCastSkillCsReq req, MazeSkill skill, List hitTargetEntityIdList) { - public void StartBattle(SceneCastSkillCsReq req, MazeSkill skill, List hitTargetEntityIdList) + if (Player.BattleInstance != null) return; + var targetList = new List(); + var avatarList = new List(); + var propList = new List(); + Player.SceneInstance!.AvatarInfo.TryGetValue((int)req.AttackedByEntityId, out var castAvatar); + + if (Player.SceneInstance!.AvatarInfo.ContainsKey((int)req.AttackedByEntityId)) { - if (Player.BattleInstance != null) return; - var targetList = new List(); - var avatarList = new List(); - var propList = new List(); - Player.SceneInstance!.AvatarInfo.TryGetValue((int)req.AttackedByEntityId, out var castAvatar); - - if (Player.SceneInstance!.AvatarInfo.ContainsKey((int)req.AttackedByEntityId)) + foreach (var entity in hitTargetEntityIdList) { - foreach (var entity in hitTargetEntityIdList) - { - Player.SceneInstance!.Entities.TryGetValue((int)entity, out var entityInstance); - if (entityInstance is EntityMonster monster) - { - targetList.Add(monster); - } else if (entityInstance is EntityProp prop) - { - propList.Add(prop); - } - } + Player.SceneInstance!.Entities.TryGetValue((int)entity, out var entityInstance); + if (entityInstance is EntityMonster monster) + targetList.Add(monster); + else if (entityInstance is EntityProp prop) propList.Add(prop); + } - foreach (var info in req.AssistMonsterEntityInfo) - { - foreach (var entity in info.EntityIdList) - { - Player.SceneInstance!.Entities.TryGetValue((int)entity, out var entityInstance); - if (entityInstance is EntityMonster monster) - { - if (targetList.Contains(monster)) continue; // avoid adding the same monster twice - targetList.Add(monster); - } - } - } - } else + foreach (var info in req.AssistMonsterEntityInfo) + foreach (var entity in info.EntityIdList) { - bool isAmbushed = false; - foreach (var entity in hitTargetEntityIdList) - { - if (Player.SceneInstance!.AvatarInfo.ContainsKey((int)entity)) - { - isAmbushed = true; - break; - } - } - if (!isAmbushed) - { - Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); - return; - } - var monsterEntity = Player.SceneInstance!.Entities[(int)req.AttackedByEntityId]; - if (monsterEntity is EntityMonster monster) + Player.SceneInstance!.Entities.TryGetValue((int)entity, out var entityInstance); + if (entityInstance is EntityMonster monster) { + if (targetList.Contains(monster)) continue; // avoid adding the same monster twice targetList.Add(monster); } } - if (targetList.Count == 0 && propList.Count == 0) + } + else + { + var isAmbushed = false; + foreach (var entity in hitTargetEntityIdList) + if (Player.SceneInstance!.AvatarInfo.ContainsKey((int)entity)) + { + isAmbushed = true; + break; + } + + if (!isAmbushed) { - Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); + await Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); return; } - foreach (var prop in propList) - { - Player.SceneInstance!.RemoveEntity(prop); - if (prop.Excel.IsMpRecover) - { - Player.LineupManager!.GainMp(2); - } else if (prop.Excel.IsHpRecover) - { - Player.LineupManager!.GetCurLineup()!.Heal(2000, false); - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - } else - { - Player.InventoryManager!.HandlePlaneEvent(prop.PropInfo.EventID); - } - Player.RogueManager!.GetRogueInstance()?.OnPropDestruct(prop); - } - - if (targetList.Count > 0) - { - // Skill handle - if (!skill.TriggerBattle) - { - skill.OnHitTarget(Player.SceneInstance!.AvatarInfo[(int)req.AttackedByEntityId], targetList); - Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); - return; - } - if (castAvatar != null) - { - skill.OnAttack(Player.SceneInstance!.AvatarInfo[(int)req.AttackedByEntityId], targetList); - skill.OnCast(castAvatar); - } - - var triggerBattle = false; - foreach (var target in targetList) - { - if (target.IsAlive) - { - triggerBattle = true; - break; - } - } - if (!triggerBattle) - { - Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); - return; - } - - BattleInstance battleInstance = new(Player, Player.LineupManager!.GetCurLineup()!, targetList) - { - WorldLevel = Player.Data.WorldLevel, - }; - - foreach (var item in Player.LineupManager!.GetCurLineup()!.BaseAvatars!) // get all avatars in the lineup and add them to the battle instance - { - var avatar = Player.SceneInstance!.AvatarInfo.Values.FirstOrDefault(x => x.AvatarInfo.AvatarId == item.BaseAvatarId); - if (avatar != null) - { - avatarList.Add(avatar); - } - } - - MazeBuff? mazeBuff = null; - if (castAvatar != null) - { - var index = battleInstance.Lineup.BaseAvatars!.FindIndex(x => x.BaseAvatarId == castAvatar.AvatarInfo.AvatarId); - GameData.AvatarConfigData.TryGetValue(castAvatar.AvatarInfo.GetAvatarId(), out var avatarExcel); - if (avatarExcel != null) - { - mazeBuff = new((int)avatarExcel.DamageType, 1, index); - mazeBuff.DynamicValues.Add("SkillIndex", skill.IsMazeSkill ? 2 : 1); - } - } else - { - mazeBuff = new(GameConstants.AMBUSH_BUFF_ID, 1, -1) - { - WaveFlag = 1 - }; - } - - if (mazeBuff != null && mazeBuff.BuffID != 0) // avoid adding a buff with ID 0 - { - battleInstance.Buffs.Add(mazeBuff); - } - - battleInstance.AvatarInfo = avatarList; - - // call battle start - Player.RogueManager!.GetRogueInstance()?.OnBattleStart(battleInstance); - Player.ChallengeManager!.ChallengeInstance?.OnBattleStart(battleInstance); - - Player.BattleInstance = battleInstance; - Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId, battleInstance)); - } else - { - Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); - } + var monsterEntity = Player.SceneInstance!.Entities[(int)req.AttackedByEntityId]; + if (monsterEntity is EntityMonster monster) targetList.Add(monster); } - public void StartStage(int eventId) + if (targetList.Count == 0 && propList.Count == 0) { - if (Player.BattleInstance != null) + await Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); + return; + } + + foreach (var prop in propList) + { + await Player.SceneInstance!.RemoveEntity(prop); + if (prop.Excel.IsMpRecover) { - Player.SendPacket(new PacketSceneEnterStageScRsp(Player.BattleInstance)); + await Player.LineupManager!.GainMp(2); + } + else if (prop.Excel.IsHpRecover) + { + Player.LineupManager!.GetCurLineup()!.Heal(2000, false); + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + } + else + { + Player.InventoryManager!.HandlePlaneEvent(prop.PropInfo.EventID); + } + + Player.RogueManager!.GetRogueInstance()?.OnPropDestruct(prop); + } + + if (targetList.Count > 0) + { + // Skill handle + if (!skill.TriggerBattle) + { + skill.OnHitTarget(Player.SceneInstance!.AvatarInfo[(int)req.AttackedByEntityId], targetList); + await Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); return; } - GameData.StageConfigData.TryGetValue(eventId, out var stageConfig); - if (stageConfig == null) + if (castAvatar != null) { - GameData.StageConfigData.TryGetValue(eventId * 10 + Player.Data.WorldLevel, out stageConfig); - if (stageConfig == null) - { - Player.SendPacket(new PacketSceneEnterStageScRsp()); - return; - } + skill.OnAttack(Player.SceneInstance!.AvatarInfo[(int)req.AttackedByEntityId], targetList); + skill.OnCast(castAvatar); } - BattleInstance battleInstance = new(Player, Player.LineupManager!.GetCurLineup()!, [stageConfig]) + var triggerBattle = false; + foreach (var target in targetList) + if (target.IsAlive) + { + triggerBattle = true; + break; + } + + if (!triggerBattle) { - WorldLevel = Player.Data.WorldLevel, - EventId = eventId, + await Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); + return; + } + + BattleInstance battleInstance = new(Player, Player.LineupManager!.GetCurLineup()!, targetList) + { + WorldLevel = Player.Data.WorldLevel }; - var avatarList = new List(); - - foreach (var item in Player.LineupManager!.GetCurLineup()!.BaseAvatars!) // get all avatars in the lineup and add them to the battle instance + foreach (var item in + Player.LineupManager!.GetCurLineup()! + .BaseAvatars!) // get all avatars in the lineup and add them to the battle instance { - var avatar = Player.SceneInstance!.AvatarInfo.Values.FirstOrDefault(x => x.AvatarInfo.AvatarId == item.BaseAvatarId); - if (avatar != null) + var avatar = + Player.SceneInstance!.AvatarInfo.Values.FirstOrDefault(x => + x.AvatarInfo.AvatarId == item.BaseAvatarId); + if (avatar != null) avatarList.Add(avatar); + } + + MazeBuff? mazeBuff = null; + if (castAvatar != null) + { + var index = battleInstance.Lineup.BaseAvatars!.FindIndex(x => + x.BaseAvatarId == castAvatar.AvatarInfo.AvatarId); + GameData.AvatarConfigData.TryGetValue(castAvatar.AvatarInfo.GetAvatarId(), out var avatarExcel); + if (avatarExcel != null) { - avatarList.Add(avatar); + mazeBuff = new MazeBuff((int)avatarExcel.DamageType, 1, index); + mazeBuff.DynamicValues.Add("SkillIndex", skill.IsMazeSkill ? 2 : 1); } } + else + { + mazeBuff = new MazeBuff(GameConstants.AMBUSH_BUFF_ID, 1, -1) + { + WaveFlag = 1 + }; + } + + if (mazeBuff != null && mazeBuff.BuffID != 0) // avoid adding a buff with ID 0 + battleInstance.Buffs.Add(mazeBuff); battleInstance.AvatarInfo = avatarList; @@ -218,162 +165,213 @@ namespace EggLink.DanhengServer.Game.Battle Player.ChallengeManager!.ChallengeInstance?.OnBattleStart(battleInstance); Player.BattleInstance = battleInstance; - - Player.SendPacket(new PacketSceneEnterStageScRsp(battleInstance)); + await Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId, battleInstance)); } - - public void StartCocoonStage(int cocoonId, int wave, int worldLevel) + else { - if (Player.BattleInstance != null) return; - - GameData.CocoonConfigData.TryGetValue(cocoonId * 100 + worldLevel, out var config); - if (config == null) - { - Player.SendPacket(new PacketStartCocoonStageScRsp()); - return; - } - wave = Math.Min(Math.Max(wave, 1), config.MaxWave); - - int cost = config.StaminaCost * wave; - if (Player.Data.Stamina < cost) - { - Player.SendPacket(new PacketStartCocoonStageScRsp()); - return; - } - - List stageConfigExcels = []; - for (int i = 0; i < wave; i++) - { - var stageId = config.StageIDList.RandomElement(); - GameData.StageConfigData.TryGetValue(stageId, out var stageConfig); - if (stageConfig == null) continue; - - stageConfigExcels.Add(stageConfig); - } - - if (stageConfigExcels.Count == 0) - { - Player.SendPacket(new PacketStartCocoonStageScRsp()); - return; - } - - BattleInstance battleInstance = new(Player, Player.LineupManager!.GetCurLineup()!, stageConfigExcels) - { - StaminaCost = cost, - WorldLevel = config.WorldLevel, - CocoonWave = wave, - MappingInfoId = config.MappingInfoID, - }; - - var avatarList = new List(); - - foreach (var item in Player.LineupManager!.GetCurLineup()!.BaseAvatars!) // get all avatars in the lineup and add them to the battle instance - { - var avatar = Player.SceneInstance!.AvatarInfo.Values.FirstOrDefault(x => x.AvatarInfo.AvatarId == item.BaseAvatarId); - if (avatar != null) - { - avatarList.Add(avatar); - } - } - - battleInstance.AvatarInfo = avatarList; - - Player.BattleInstance = battleInstance; - - Player.SendPacket(new PacketStartCocoonStageScRsp(battleInstance, cocoonId, wave)); - } - - public void EndBattle(PVEBattleResultCsReq req) - { - if (Player.BattleInstance == null) - { - Player.SendPacket(new PacketPVEBattleResultScRsp()); - return; - } - Player.BattleInstance.BattleEndStatus = req.EndStatus; - var battle = Player.BattleInstance; - bool updateStatus = true; - bool teleportToAnchor = false; - var minimumHp = 0; - var dropItems = new List(); - switch (req.EndStatus) - { - case BattleEndStatus.BattleEndWin: - // Drops - foreach (var monster in battle.EntityMonsters) - { - dropItems.AddRange(monster.Kill(false)); - } - // Spend stamina - if (battle.StaminaCost > 0) - { - Player.SpendStamina(battle.StaminaCost); - } - break; - case BattleEndStatus.BattleEndLose: - // Set avatar hp to 20% if the player's party is downed - minimumHp = 2000; - teleportToAnchor = true; - break; - default: - teleportToAnchor = true; - if (battle.CocoonWave > 0) teleportToAnchor = false; - updateStatus = false; - break; - } - if (updateStatus) - { - var lineup = Player.LineupManager!.GetCurLineup()!; - // Update battle status - foreach (var avatar in req.Stt.AvatarBattleList) - { - var avatarInstance = Player.AvatarManager!.GetAvatar((int)avatar.Id); - var prop = avatar.AvatarStatus; - int curHp = (int)Math.Max(Math.Round(prop.LeftHp / prop.MaxHp * 10000), minimumHp); - int curSp = (int)prop.LeftSp * 100; - if (avatarInstance == null) - { - GameData.SpecialAvatarData.TryGetValue((int)(avatar.Id * 10 + Player.Data.WorldLevel), out var specialAvatar); - if (specialAvatar == null) continue; - specialAvatar.CurHp[Player.Uid] = curHp; - specialAvatar.CurSp[Player.Uid] = curSp; - avatarInstance?.SetCurHp(curHp, lineup.LineupType != 0); - avatarInstance?.SetCurSp(curSp, lineup.LineupType != 0); - } else - { - avatarInstance.SetCurHp(curHp, lineup.LineupType != 0); - avatarInstance.SetCurSp(curSp, lineup.LineupType != 0); - } - } - - DatabaseHelper.Instance?.UpdateInstance(Player.AvatarManager!.AvatarData!); - Player.SendPacket(new PacketSyncLineupNotify(lineup)); - } - if (teleportToAnchor) - { - var anchorProp = Player.SceneInstance?.GetNearestSpring(long.MaxValue); - if (anchorProp != null && anchorProp.PropInfo != null) - { - var anchor = Player!.SceneInstance?.FloorInfo?.GetAnchorInfo( - anchorProp.PropInfo.AnchorGroupID, - anchorProp.PropInfo.AnchorID - ); - if (anchor != null) - { - Player.MoveTo(anchor.ToPositionProto()); - } - } - } - // call battle end - battle.MonsterDropItems = dropItems; - - Player.BattleInstance = null; - - Player.MissionManager!.OnBattleFinish(req); - Player.RogueManager!.GetRogueInstance()?.OnBattleEnd(battle, req); - Player.ChallengeManager!.ChallengeInstance?.OnBattleEnd(battle, req); - - Player.SendPacket(new PacketPVEBattleResultScRsp(req, Player, battle)); + await Player.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); } } -} + + public async ValueTask StartStage(int eventId) + { + if (Player.BattleInstance != null) + { + await Player.SendPacket(new PacketSceneEnterStageScRsp(Player.BattleInstance)); + return; + } + + GameData.StageConfigData.TryGetValue(eventId, out var stageConfig); + if (stageConfig == null) + { + GameData.StageConfigData.TryGetValue(eventId * 10 + Player.Data.WorldLevel, out stageConfig); + if (stageConfig == null) + { + await Player.SendPacket(new PacketSceneEnterStageScRsp()); + return; + } + } + + BattleInstance battleInstance = new(Player, Player.LineupManager!.GetCurLineup()!, [stageConfig]) + { + WorldLevel = Player.Data.WorldLevel, + EventId = eventId + }; + + var avatarList = new List(); + + foreach (var item in + Player.LineupManager!.GetCurLineup()! + .BaseAvatars!) // get all avatars in the lineup and add them to the battle instance + { + var avatar = + Player.SceneInstance!.AvatarInfo.Values.FirstOrDefault(x => x.AvatarInfo.AvatarId == item.BaseAvatarId); + if (avatar != null) avatarList.Add(avatar); + } + + battleInstance.AvatarInfo = avatarList; + + // call battle start + Player.RogueManager!.GetRogueInstance()?.OnBattleStart(battleInstance); + Player.ChallengeManager!.ChallengeInstance?.OnBattleStart(battleInstance); + + Player.BattleInstance = battleInstance; + + await Player.SendPacket(new PacketSceneEnterStageScRsp(battleInstance)); + } + + public async ValueTask StartCocoonStage(int cocoonId, int wave, int worldLevel) + { + if (Player.BattleInstance != null) return; + + GameData.CocoonConfigData.TryGetValue(cocoonId * 100 + worldLevel, out var config); + if (config == null) + { + await Player.SendPacket(new PacketStartCocoonStageScRsp()); + return; + } + + wave = Math.Min(Math.Max(wave, 1), config.MaxWave); + + var cost = config.StaminaCost * wave; + if (Player.Data.Stamina < cost) + { + await Player.SendPacket(new PacketStartCocoonStageScRsp()); + return; + } + + List stageConfigExcels = []; + for (var i = 0; i < wave; i++) + { + var stageId = config.StageIDList.RandomElement(); + GameData.StageConfigData.TryGetValue(stageId, out var stageConfig); + if (stageConfig == null) continue; + + stageConfigExcels.Add(stageConfig); + } + + if (stageConfigExcels.Count == 0) + { + await Player.SendPacket(new PacketStartCocoonStageScRsp()); + return; + } + + BattleInstance battleInstance = new(Player, Player.LineupManager!.GetCurLineup()!, stageConfigExcels) + { + StaminaCost = cost, + WorldLevel = config.WorldLevel, + CocoonWave = wave, + MappingInfoId = config.MappingInfoID + }; + + var avatarList = new List(); + + foreach (var item in + Player.LineupManager!.GetCurLineup()! + .BaseAvatars!) // get all avatars in the lineup and add them to the battle instance + { + var avatar = + Player.SceneInstance!.AvatarInfo.Values.FirstOrDefault(x => x.AvatarInfo.AvatarId == item.BaseAvatarId); + if (avatar != null) avatarList.Add(avatar); + } + + battleInstance.AvatarInfo = avatarList; + + Player.BattleInstance = battleInstance; + + await Player.SendPacket(new PacketStartCocoonStageScRsp(battleInstance, cocoonId, wave)); + } + + public async ValueTask EndBattle(PVEBattleResultCsReq req) + { + if (Player.BattleInstance == null) + { + await Player.SendPacket(new PacketPVEBattleResultScRsp()); + return; + } + + Player.BattleInstance.BattleEndStatus = req.EndStatus; + var battle = Player.BattleInstance; + var updateStatus = true; + var teleportToAnchor = false; + var minimumHp = 0; + var dropItems = new List(); + switch (req.EndStatus) + { + case BattleEndStatus.BattleEndWin: + // Drops + foreach (var monster in battle.EntityMonsters) dropItems.AddRange(await monster.Kill(false)); + // Spend stamina + if (battle.StaminaCost > 0) await Player.SpendStamina(battle.StaminaCost); + break; + case BattleEndStatus.BattleEndLose: + // Set avatar hp to 20% if the player's party is downed + minimumHp = 2000; + teleportToAnchor = true; + break; + default: + teleportToAnchor = true; + if (battle.CocoonWave > 0) teleportToAnchor = false; + updateStatus = false; + break; + } + + if (updateStatus) + { + var lineup = Player.LineupManager!.GetCurLineup()!; + // Update battle status + foreach (var avatar in req.Stt.AvatarBattleList) + { + var avatarInstance = Player.AvatarManager!.GetAvatar((int)avatar.Id); + var prop = avatar.AvatarStatus; + var curHp = (int)Math.Max(Math.Round(prop.LeftHp / prop.MaxHp * 10000), minimumHp); + var curSp = (int)prop.LeftSp * 100; + if (avatarInstance == null) + { + GameData.SpecialAvatarData.TryGetValue((int)(avatar.Id * 10 + Player.Data.WorldLevel), + out var specialAvatar); + if (specialAvatar == null) continue; + specialAvatar.CurHp[Player.Uid] = curHp; + specialAvatar.CurSp[Player.Uid] = curSp; + avatarInstance?.SetCurHp(curHp, lineup.LineupType != 0); + avatarInstance?.SetCurSp(curSp, lineup.LineupType != 0); + } + else + { + avatarInstance.SetCurHp(curHp, lineup.LineupType != 0); + avatarInstance.SetCurSp(curSp, lineup.LineupType != 0); + } + } + + DatabaseHelper.Instance?.UpdateInstance(Player.AvatarManager!.AvatarData!); + await Player.SendPacket(new PacketSyncLineupNotify(lineup)); + } + + if (teleportToAnchor) + { + var anchorProp = Player.SceneInstance?.GetNearestSpring(long.MaxValue); + if (anchorProp != null && anchorProp.PropInfo != null) + { + var anchor = Player!.SceneInstance?.FloorInfo?.GetAnchorInfo( + anchorProp.PropInfo.AnchorGroupID, + anchorProp.PropInfo.AnchorID + ); + if (anchor != null) await Player.MoveTo(anchor.ToPositionProto()); + } + } + + // call battle end + battle.MonsterDropItems = dropItems; + + Player.BattleInstance = null; + + await Player.MissionManager!.OnBattleFinish(req); + if (Player.RogueManager?.GetRogueInstance() != null) + await Player.RogueManager!.GetRogueInstance()!.OnBattleEnd(battle, req); + + if (Player.ChallengeManager?.ChallengeInstance != null) + await Player.ChallengeManager!.ChallengeInstance.OnBattleEnd(battle, req); + + await Player.SendPacket(new PacketPVEBattleResultScRsp(req, Player, battle)); + } +} \ No newline at end of file diff --git a/GameServer/Game/Battle/MazeBuff.cs b/GameServer/Game/Battle/MazeBuff.cs index 2d24eedf..a8c2328a 100644 --- a/GameServer/Game/Battle/MazeBuff.cs +++ b/GameServer/Game/Battle/MazeBuff.cs @@ -1,58 +1,50 @@ using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Battle +namespace EggLink.DanhengServer.Game.Battle; + +public class MazeBuff(int buffID, int buffLevel, int owner) { - public class MazeBuff(int buffID, int buffLevel, int owner) + public MazeBuff(SceneBuff buff) : this(buff.BuffID, buff.BuffLevel, 0) { - public int BuffID { get; private set; } = buffID; - public int BuffLevel { get; private set; } = buffLevel; - public int OwnerIndex { get; private set; } = owner; - public int OwnerAvatarId { get; private set; } = -1; - public int? WaveFlag { get; set; } = null; - public int Duration { get; private set; } = -1; - public Dictionary DynamicValues { get; private set; } = []; - - public MazeBuff(SceneBuff buff) : this(buff.BuffID, buff.BuffLevel, 0) - { - Duration = buff.Duration; - OwnerAvatarId = buff.OwnerAvatarId; - } - - public BattleBuff ToProto(BattleInstance battle) - { - return ToProto(battle, WaveFlag ?? -1); - } - - public BattleBuff ToProto(BattleInstance instance, int waveFlag) - { - var buffInfo = new BattleBuff() - { - Id = (uint)BuffID, - Level = (uint)BuffLevel, - OwnerIndex = (uint)OwnerIndex, - WaveFlag = (uint)waveFlag, - }; - - foreach (var item in DynamicValues) - { - buffInfo.DynamicValues.Add(item.Key, item.Value); - } - - if (OwnerAvatarId != -1) - { - buffInfo.OwnerIndex = (uint)instance.Lineup.BaseAvatars!.FindIndex(x => x.BaseAvatarId == OwnerAvatarId); - OwnerIndex = (int)buffInfo.OwnerIndex; - } - if (OwnerIndex != -1) - buffInfo.TargetIndexList.Add((uint)OwnerIndex); - - return buffInfo; - } + Duration = buff.Duration; + OwnerAvatarId = buff.OwnerAvatarId; } -} + + public int BuffID { get; } = buffID; + public int BuffLevel { get; } = buffLevel; + public int OwnerIndex { get; private set; } = owner; + public int OwnerAvatarId { get; } = -1; + public int? WaveFlag { get; set; } = null; + public int Duration { get; private set; } = -1; + public Dictionary DynamicValues { get; } = []; + + public BattleBuff ToProto(BattleInstance battle) + { + return ToProto(battle, WaveFlag ?? -1); + } + + public BattleBuff ToProto(BattleInstance instance, int waveFlag) + { + var buffInfo = new BattleBuff + { + Id = (uint)BuffID, + Level = (uint)BuffLevel, + OwnerIndex = (uint)OwnerIndex, + WaveFlag = (uint)waveFlag + }; + + foreach (var item in DynamicValues) buffInfo.DynamicValues.Add(item.Key, item.Value); + + if (OwnerAvatarId != -1) + { + buffInfo.OwnerIndex = (uint)instance.Lineup.BaseAvatars!.FindIndex(x => x.BaseAvatarId == OwnerAvatarId); + OwnerIndex = (int)buffInfo.OwnerIndex; + } + + if (OwnerIndex != -1) + buffInfo.TargetIndexList.Add((uint)OwnerIndex); + + return buffInfo; + } +} \ No newline at end of file diff --git a/GameServer/Game/Battle/Skill/Action/MazeAddMazeBuff.cs b/GameServer/Game/Battle/Skill/Action/MazeAddMazeBuff.cs index 41d820b8..b1ffcb7c 100644 --- a/GameServer/Game/Battle/Skill/Action/MazeAddMazeBuff.cs +++ b/GameServer/Game/Battle/Skill/Action/MazeAddMazeBuff.cs @@ -1,38 +1,28 @@ -using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Data.Excel; -using EggLink.DanhengServer.Game.Scene; +using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Battle.Skill.Action +namespace EggLink.DanhengServer.Game.Battle.Skill.Action; + +public class MazeAddMazeBuff(int buffId, int duration) : IMazeSkillAction { - public class MazeAddMazeBuff(int buffId, int duration) : IMazeSkillAction + public int BuffId { get; } = buffId; + + public async ValueTask OnAttack(AvatarSceneInfo avatar, List entities) { - public int BuffId { get; private set; } = buffId; + foreach (var entity in entities) + entity.TempBuff = new SceneBuff(BuffId, 1, avatar.AvatarInfo.AvatarId, duration); - public void OnAttack(AvatarSceneInfo avatar, List entities) - { - foreach (var entity in entities) - { - entity.TempBuff = new SceneBuff(BuffId, 1, avatar.AvatarInfo.AvatarId, duration); - } - } - - public void OnCast(AvatarSceneInfo avatar) - { - avatar.AddBuff(new SceneBuff(BuffId, 1, avatar.AvatarInfo.AvatarId, duration)); - } - - public void OnHitTarget(AvatarSceneInfo avatar, List entities) - { - foreach (var entity in entities) - { - entity.AddBuff(new SceneBuff(BuffId, 1, avatar.AvatarInfo.AvatarId, duration)); - } - } + await System.Threading.Tasks.Task.CompletedTask; } -} + + public async ValueTask OnCast(AvatarSceneInfo avatar) + { + await avatar.AddBuff(new SceneBuff(BuffId, 1, avatar.AvatarInfo.AvatarId, duration)); + } + + public async ValueTask OnHitTarget(AvatarSceneInfo avatar, List entities) + { + foreach (var entity in entities) + await entity.AddBuff(new SceneBuff(BuffId, 1, avatar.AvatarInfo.AvatarId, duration)); + } +} \ No newline at end of file diff --git a/GameServer/Game/Battle/Skill/Action/MazeSetTargetMonsterDie.cs b/GameServer/Game/Battle/Skill/Action/MazeSetTargetMonsterDie.cs index 1859669d..45435600 100644 --- a/GameServer/Game/Battle/Skill/Action/MazeSetTargetMonsterDie.cs +++ b/GameServer/Game/Battle/Skill/Action/MazeSetTargetMonsterDie.cs @@ -1,38 +1,31 @@ using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Battle.Skill.Action +namespace EggLink.DanhengServer.Game.Battle.Skill.Action; + +public class MazeSetTargetMonsterDie : IMazeSkillAction { - public class MazeSetTargetMonsterDie : IMazeSkillAction + public async ValueTask OnAttack(AvatarSceneInfo avatar, List entities) { - public void OnAttack(AvatarSceneInfo avatar, List entities) - { - foreach (var entity in entities) + foreach (var entity in entities) + if (entity.MonsterData.Rank < MonsterRankEnum.Elite) { - if (entity.MonsterData.Rank < MonsterRankEnum.Elite) - { - entity.Kill(); + await entity.Kill(); - entity.Scene.Player.LineupManager!.CostMp(1); - entity.Scene.Player.RogueManager!.GetRogueInstance()?.RollBuff(1); - entity.Scene.Player.RogueManager!.GetRogueInstance()?.GainMoney(Random.Shared.Next(20, 60)); - } + await entity.Scene.Player.LineupManager!.CostMp(1); + entity.Scene.Player.RogueManager!.GetRogueInstance()?.RollBuff(1); + entity.Scene.Player.RogueManager!.GetRogueInstance()?.GainMoney(Random.Shared.Next(20, 60)); } - } - - public void OnCast(AvatarSceneInfo avatar) - { - - } - - public void OnHitTarget(AvatarSceneInfo avatar, List entities) - { - } } -} + + public async ValueTask OnCast(AvatarSceneInfo avatar) + { + await System.Threading.Tasks.Task.CompletedTask; + } + + public async ValueTask OnHitTarget(AvatarSceneInfo avatar, List entities) + { + await System.Threading.Tasks.Task.CompletedTask; + } +} \ No newline at end of file diff --git a/GameServer/Game/Battle/Skill/IMazeSkillAction.cs b/GameServer/Game/Battle/Skill/IMazeSkillAction.cs index ef4ce1be..6a49196a 100644 --- a/GameServer/Game/Battle/Skill/IMazeSkillAction.cs +++ b/GameServer/Game/Battle/Skill/IMazeSkillAction.cs @@ -1,19 +1,13 @@ using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Battle.Skill +namespace EggLink.DanhengServer.Game.Battle.Skill; + +public interface IMazeSkillAction { - public interface IMazeSkillAction - { - public void OnCast(AvatarSceneInfo avatar); + public ValueTask OnCast(AvatarSceneInfo avatar); - public void OnHitTarget(AvatarSceneInfo avatar, List entities); + public ValueTask OnHitTarget(AvatarSceneInfo avatar, List entities); - public void OnAttack(AvatarSceneInfo avatar, List entities); - } -} + public ValueTask OnAttack(AvatarSceneInfo avatar, List entities); +} \ No newline at end of file diff --git a/GameServer/Game/Battle/Skill/MazeSkill.cs b/GameServer/Game/Battle/Skill/MazeSkill.cs index b3b7d4dd..42102dd5 100644 --- a/GameServer/Game/Battle/Skill/MazeSkill.cs +++ b/GameServer/Game/Battle/Skill/MazeSkill.cs @@ -4,106 +4,72 @@ using EggLink.DanhengServer.Enums.Avatar; using EggLink.DanhengServer.Game.Battle.Skill.Action; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; -using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Battle.Skill +namespace EggLink.DanhengServer.Game.Battle.Skill; + +public class MazeSkill { - public class MazeSkill + public MazeSkill(List taskInfos, bool isSkill = false, AvatarConfigExcel? excel = null) { - public List Actions { get; private set; } = []; - public bool TriggerBattle { get; private set; } = true; - public bool IsMazeSkill { get; private set; } = true; - public AvatarConfigExcel? Excel { get; private set; } + foreach (var task in taskInfos) AddAction(task); + IsMazeSkill = isSkill; + Excel = excel; + } - public MazeSkill(List taskInfos, bool isSkill = false, AvatarConfigExcel? excel = null) + public List Actions { get; } = []; + public bool TriggerBattle { get; private set; } = true; + public bool IsMazeSkill { get; } = true; + public AvatarConfigExcel? Excel { get; private set; } + + public void AddAction(TaskInfo task) + { + switch (task.TaskType) { - foreach (var task in taskInfos) - { - AddAction(task); - } - IsMazeSkill = isSkill; - Excel = excel; - } + case TaskTypeEnum.None: + break; + case TaskTypeEnum.AddMazeBuff: + Actions.Add(new MazeAddMazeBuff(task.ID, task.LifeTime.GetLifeTime())); + break; + case TaskTypeEnum.RemoveMazeBuff: + Actions.RemoveAll(a => a is MazeAddMazeBuff buff && buff.BuffId == task.ID); + break; + case TaskTypeEnum.AdventureModifyTeamPlayerHP: + break; + case TaskTypeEnum.AdventureModifyTeamPlayerSP: + break; + case TaskTypeEnum.CreateSummonUnit: + break; + case TaskTypeEnum.AdventureSetAttackTargetMonsterDie: + Actions.Add(new MazeSetTargetMonsterDie()); + break; + case TaskTypeEnum.SuccessTaskList: + foreach (var t in task.SuccessTaskList) AddAction(t); + break; + case TaskTypeEnum.AdventureTriggerAttack: + if (IsMazeSkill) TriggerBattle = task.TriggerBattle; - public void AddAction(TaskInfo task) - { - switch (task.TaskType) - { - case TaskTypeEnum.None: - break; - case TaskTypeEnum.AddMazeBuff: - Actions.Add(new MazeAddMazeBuff(task.ID, task.LifeTime.GetLifeTime())); - break; - case TaskTypeEnum.RemoveMazeBuff: - Actions.RemoveAll(a => a is MazeAddMazeBuff buff && buff.BuffId == task.ID); - break; - case TaskTypeEnum.AdventureModifyTeamPlayerHP: - break; - case TaskTypeEnum.AdventureModifyTeamPlayerSP: - break; - case TaskTypeEnum.CreateSummonUnit: - break; - case TaskTypeEnum.AdventureSetAttackTargetMonsterDie: - Actions.Add(new MazeSetTargetMonsterDie()); - break; - case TaskTypeEnum.SuccessTaskList: - foreach (var t in task.SuccessTaskList) - { - AddAction(t); - } - break; - case TaskTypeEnum.AdventureTriggerAttack: - if (IsMazeSkill) - { - TriggerBattle = task.TriggerBattle; - } + foreach (var t in task.GetAttackInfo()) AddAction(t); + break; + case TaskTypeEnum.AdventureFireProjectile: + foreach (var t in task.OnProjectileHit) AddAction(t); - foreach (var t in task.GetAttackInfo()) - { - AddAction(t); - } - break; - case TaskTypeEnum.AdventureFireProjectile: - foreach (var t in task.OnProjectileHit) - { - AddAction(t); - } - - foreach (var t in task.OnProjectileLifetimeFinish) - { - AddAction(t); - } - break; - } - } - - public void OnCast(AvatarSceneInfo info) - { - foreach (var action in Actions) - { - action.OnCast(info); - } - } - - public void OnAttack(AvatarSceneInfo info, List entities) - { - foreach (var action in Actions) - { - action.OnAttack(info, entities); - } - } - - public void OnHitTarget(AvatarSceneInfo info, List entities) - { - foreach (var action in Actions) - { - action.OnHitTarget(info, entities); - } + foreach (var t in task.OnProjectileLifetimeFinish) AddAction(t); + break; } } -} + + public void OnCast(AvatarSceneInfo info) + { + foreach (var action in Actions) action.OnCast(info); + } + + public void OnAttack(AvatarSceneInfo info, List entities) + { + foreach (var action in Actions) action.OnAttack(info, entities); + } + + public void OnHitTarget(AvatarSceneInfo info, List entities) + { + foreach (var action in Actions) action.OnHitTarget(info, entities); + } +} \ No newline at end of file diff --git a/GameServer/Game/Battle/Skill/MazeSkillManager.cs b/GameServer/Game/Battle/Skill/MazeSkillManager.cs index bc884e0e..e9d4a029 100644 --- a/GameServer/Game/Battle/Skill/MazeSkillManager.cs +++ b/GameServer/Game/Battle/Skill/MazeSkillManager.cs @@ -1,31 +1,21 @@ using EggLink.DanhengServer.Data; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Battle.Skill +namespace EggLink.DanhengServer.Game.Battle.Skill; + +public static class MazeSkillManager { - public static class MazeSkillManager + public static MazeSkill GetSkill(int baseAvatarId, int skillIndex) { - public static MazeSkill GetSkill(int baseAvatarId, int skillIndex) - { - GameData.AvatarConfigData.TryGetValue(baseAvatarId, out var avatarConfig); - MazeSkill mazeSkill = new([]); - if (avatarConfig == null) return mazeSkill; + GameData.AvatarConfigData.TryGetValue(baseAvatarId, out var avatarConfig); + MazeSkill mazeSkill = new([]); + if (avatarConfig == null) return mazeSkill; - if (skillIndex == 0) - { - // normal atk - mazeSkill = new(avatarConfig.MazeAtk?.OnStart.ToList() ?? [], false, avatarConfig); - } - else - { - // maze skill - mazeSkill = new(avatarConfig.MazeSkill?.OnStart.ToList() ?? [], true, avatarConfig); - } - return mazeSkill; - } + if (skillIndex == 0) + // normal atk + mazeSkill = new MazeSkill(avatarConfig.MazeAtk?.OnStart.ToList() ?? [], false, avatarConfig); + else + // maze skill + mazeSkill = new MazeSkill(avatarConfig.MazeSkill?.OnStart.ToList() ?? [], true, avatarConfig); + return mazeSkill; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Challenge/ChallengeEntityLoader.cs b/GameServer/Game/Challenge/ChallengeEntityLoader.cs index d4005345..5c53058d 100644 --- a/GameServer/Game/Challenge/ChallengeEntityLoader.cs +++ b/GameServer/Game/Challenge/ChallengeEntityLoader.cs @@ -1,97 +1,87 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Data.Excel; +using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Challenge +namespace EggLink.DanhengServer.Game.Challenge; + +public class ChallengeEntityLoader(SceneInstance scene, PlayerInstance player) : SceneEntityLoader(scene) { - public class ChallengeEntityLoader(SceneInstance scene, PlayerInstance player) : SceneEntityLoader(scene) + public PlayerInstance Player = player; + + public override async ValueTask LoadEntity() { - public PlayerInstance Player = player; + if (Scene.IsLoaded) return; - public override void LoadEntity() + // Get challenge instance + if (Player.ChallengeManager!.ChallengeInstance == null) return; + var instance = Player.ChallengeManager.ChallengeInstance; + + // Setup first stage + var excel = instance.Excel; + Scene.FloorInfo!.Groups.TryGetValue(excel.MazeGroupID1, out var groupData); + if (groupData != null) await LoadGroup(groupData); + ; + + // Set leave entry + Scene.LeaveEntityId = + instance.IsStory() ? GameConstants.CHALLENGE_STORY_ENTRANCE : GameConstants.CHALLENGE_ENTRANCE; + + foreach (var group in Scene.FloorInfo.Groups.Values) { - if (Scene.IsLoaded) return; + // Skip non-server groups + if (group.LoadSide != GroupLoadSideEnum.Server) continue; - // Get challenge instance - if (Player.ChallengeManager!.ChallengeInstance == null) return; - ChallengeInstance instance = Player.ChallengeManager.ChallengeInstance; - - // Setup first stage - var excel = instance.Excel; - Scene.FloorInfo!.Groups.TryGetValue(excel.MazeGroupID1, out var groupData); - if (groupData != null) - { - LoadGroup(groupData); - }; - - // Set leave entry - Scene.LeaveEntityId = instance.IsStory() ? GameConstants.CHALLENGE_STORY_ENTRANCE : GameConstants.CHALLENGE_ENTRANCE; - - foreach (var group in Scene.FloorInfo.Groups.Values) - { - // Skip non-server groups - if (group.LoadSide != Enums.Scene.GroupLoadSideEnum.Server) continue; - - // Dont load the groups that have monsters in them - if (group.PropList.Count > 0 && group.MonsterList.Count > 0) - { - LoadGroup(group); - } - } - - Scene.IsLoaded = true; + // Dont load the groups that have monsters in them + if (group.PropList.Count > 0 && group.MonsterList.Count > 0) await LoadGroup(group); } - public override EntityMonster? LoadMonster(MonsterInfo info, GroupInfo group, bool sendPacket = false) - { - if (info.IsClientOnly || info.IsDelete) - { - return null; - } - - // Get challenge instance - if (Player.ChallengeManager!.ChallengeInstance == null) return null; - ChallengeInstance instance = Player.ChallengeManager.ChallengeInstance; - - // Get current stage monster infos - Dictionary challengeMonsters; - if (instance.Excel.MazeGroupID1 == group.Id) - { - challengeMonsters = instance.Excel.ChallengeMonsters1; - } - else if (instance.Excel.MazeGroupID2 == group.Id) - { - challengeMonsters = instance.Excel.ChallengeMonsters2; - } - else - { - return null; - } - - // Get challenge monster info - if (!challengeMonsters.ContainsKey(info.ID)) return null; - var challengeMonsterInfo = challengeMonsters[info.ID]; - - // Get excels from game data - if (!GameData.NpcMonsterDataData.ContainsKey(challengeMonsterInfo.NpcMonsterId)) return null; - NPCMonsterDataExcel npcMonsterExcel = GameData.NpcMonsterDataData[challengeMonsterInfo.NpcMonsterId]; - - // Create monster from group monster info - EntityMonster entity = new EntityMonster(scene, info.ToPositionProto(), info.ToRotationProto(), group.Id, info.ID, npcMonsterExcel, info); - entity.EventID = challengeMonsterInfo.EventId; - entity.CustomStageID = challengeMonsterInfo.EventId; - Scene.AddEntity(entity, sendPacket); - - return entity; - } - - public override EntityNpc? LoadNpc(NpcInfo info, GroupInfo group, bool sendPacket = false) - { - return null; - } + Scene.IsLoaded = true; } -} + + public override async ValueTask LoadMonster(MonsterInfo info, GroupInfo group, + bool sendPacket = false) + { + if (info.IsClientOnly || info.IsDelete) return null; + + // Get challenge instance + if (Player.ChallengeManager!.ChallengeInstance == null) return null; + var instance = Player.ChallengeManager.ChallengeInstance; + + // Get current stage monster infos + Dictionary challengeMonsters; + if (instance.Excel.MazeGroupID1 == group.Id) + challengeMonsters = instance.Excel.ChallengeMonsters1; + else if (instance.Excel.MazeGroupID2 == group.Id) + challengeMonsters = instance.Excel.ChallengeMonsters2; + else + return null; + + // Get challenge monster info + if (!challengeMonsters.ContainsKey(info.ID)) return null; + var challengeMonsterInfo = challengeMonsters[info.ID]; + + // Get excels from game data + if (!GameData.NpcMonsterDataData.ContainsKey(challengeMonsterInfo.NpcMonsterId)) return null; + var npcMonsterExcel = GameData.NpcMonsterDataData[challengeMonsterInfo.NpcMonsterId]; + + // Create monster from group monster info + var entity = new EntityMonster(scene, info.ToPositionProto(), info.ToRotationProto(), group.Id, info.ID, + npcMonsterExcel, info); + entity.EventID = challengeMonsterInfo.EventId; + entity.CustomStageID = challengeMonsterInfo.EventId; + await Scene.AddEntity(entity, sendPacket); + + return entity; + } + + public override async ValueTask LoadNpc(NpcInfo info, GroupInfo group, bool sendPacket = false) + { + await System.Threading.Tasks.Task.CompletedTask; + return null; + } +} \ No newline at end of file diff --git a/GameServer/Game/Challenge/ChallengeInstance.cs b/GameServer/Game/Challenge/ChallengeInstance.cs index efdb8bed..c6fed70a 100644 --- a/GameServer/Game/Challenge/ChallengeInstance.cs +++ b/GameServer/Game/Challenge/ChallengeInstance.cs @@ -1,347 +1,308 @@ -using EggLink.DanhengServer.Data; +using System.Text.Json.Serialization; +using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Database.Challenge; using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; +using EggLink.DanhengServer.GameServer.Server.Packet.Send.Challenge; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Challenge; using EggLink.DanhengServer.Server.Packet.Send.Lineup; using EggLink.DanhengServer.Util; -using System.Text.Json.Serialization; -using EggLink.DanhengServer.GameServer.Server.Packet.Send.Challenge; -namespace EggLink.DanhengServer.Game.Challenge +namespace EggLink.DanhengServer.Game.Challenge; + +public class ChallengeInstance { - public class ChallengeInstance + public ChallengeInstance(PlayerInstance player, ChallengeConfigExcel excel) { - public Position StartPos { get; set; } - public Position StartRot { get; set; } - public int ChallengeId { get; set; } - public int CurrentStage { get; set; } - public int CurrentExtraLineup { get; set; } - public int Status { get; set; } - public bool HasAvatarDied { get; set; } + Player = player; + Excel = excel; + ChallengeId = excel.GetId(); + StartPos = new Position(); + StartRot = new Position(); + CurrentStage = 1; + RoundsLeft = Excel.IsStory() ? 5 : Excel.ChallengeCountDown; + SetStatus(ChallengeStatus.ChallengeDoing); + SetCurrentExtraLineup(ExtraLineupType.LineupChallenge); + } - public int SavedMp { get; set; } - public int RoundsLeft { get; set; } - public int Stars { get; set; } - public int ScoreStage1 { get; set; } - public int ScoreStage2 { get; set; } + public ChallengeInstance(PlayerInstance player, ChallengeConfigExcel excel, ChallengeInstanceData data) + { + Player = player; + Excel = excel; - [JsonIgnore] - public List? BossTarget1 { get; set; } - [JsonIgnore] - public List? BossTarget2 { get; set; } - [JsonIgnore] - PlayerInstance Player { get; set; } - [JsonIgnore] - public ChallengeConfigExcel Excel { get; set; } + StartPos = data.StartPos; + StartRot = data.StartRot; + ChallengeId = data.ChallengeId; + CurrentStage = data.CurrentStage; + CurrentExtraLineup = data.CurrentExtraLineup; + Status = data.Status; + HasAvatarDied = data.HasAvatarDied; + SavedMp = data.SavedMp; + RoundsLeft = data.RoundsLeft; + Stars = data.Stars; + ScoreStage1 = data.ScoreStage1; + ScoreStage2 = data.ScoreStage2; + StoryBuffs = data.StoryBuffs; + BossBuffs = data.BossBuffs; + } - public List StoryBuffs { get; set; } = []; - public List BossBuffs { get; set; } = []; + public Position StartPos { get; set; } + public Position StartRot { get; set; } + public int ChallengeId { get; set; } + public int CurrentStage { get; set; } + public int CurrentExtraLineup { get; set; } + public int Status { get; set; } + public bool HasAvatarDied { get; set; } - public ChallengeInstance(PlayerInstance player, ChallengeConfigExcel excel) + public int SavedMp { get; set; } + public int RoundsLeft { get; set; } + public int Stars { get; set; } + public int ScoreStage1 { get; set; } + public int ScoreStage2 { get; set; } + + [JsonIgnore] public List? BossTarget1 { get; set; } + + [JsonIgnore] public List? BossTarget2 { get; set; } + + [JsonIgnore] private PlayerInstance Player { get; } + + [JsonIgnore] public ChallengeConfigExcel Excel { get; set; } + + public List StoryBuffs { get; set; } = []; + public List BossBuffs { get; set; } = []; + + public SceneInstance GetScene() + { + return Player.SceneInstance!; + } + + public int GetChallengeId() + { + return Excel.GetId(); + } + + public bool IsStory() + { + return Excel.IsStory(); + } + + public bool IsBoss() + { + return Excel.IsBoss(); + } + + public void SetStatus(ChallengeStatus status) + { + Status = (int)status; + } + + public void SetCurrentExtraLineup(ExtraLineupType type) + { + CurrentExtraLineup = (int)type; + } + + public int GetRoundsElapsed() + { + return Excel.ChallengeCountDown - RoundsLeft; + } + + public int GetTotalScore() + { + return ScoreStage1 + ScoreStage2; + } + + public bool IsWin() + { + return Status == (int)ChallengeStatus.ChallengeFinish; + } + + #region Serialization + + public CurChallenge ToProto() + { + var proto = new CurChallenge { - Player = player; - Excel = excel; - ChallengeId = excel.GetId(); - StartPos = new Position(); - StartRot = new Position(); - CurrentStage = 1; - RoundsLeft = Excel.IsStory() ? 5 : Excel.ChallengeCountDown; - SetStatus(ChallengeStatus.ChallengeDoing); - SetCurrentExtraLineup(ExtraLineupType.LineupChallenge); - } - - public ChallengeInstance(PlayerInstance player, ChallengeConfigExcel excel, ChallengeInstanceData data) - { - Player = player; - Excel = excel; - - StartPos = data.StartPos; - StartRot = data.StartRot; - ChallengeId = data.ChallengeId; - CurrentStage = data.CurrentStage; - CurrentExtraLineup = data.CurrentExtraLineup; - Status = data.Status; - HasAvatarDied = data.HasAvatarDied; - SavedMp = data.SavedMp; - RoundsLeft = data.RoundsLeft; - Stars = data.Stars; - ScoreStage1 = data.ScoreStage1; - ScoreStage2 = data.ScoreStage2; - StoryBuffs = data.StoryBuffs; - BossBuffs = data.BossBuffs; - } - - public SceneInstance GetScene() - { - return Player.SceneInstance!; - } - - public int GetChallengeId() - { - return Excel.GetId(); - } - - public bool IsStory() - { - return Excel.IsStory(); - } - - public bool IsBoss() - { - return Excel.IsBoss(); - } - - public void SetStatus(ChallengeStatus status) - { - Status = (int)status; - } - - public void SetCurrentExtraLineup(ExtraLineupType type) - { - CurrentExtraLineup = (int)type; - } - - public int GetRoundsElapsed() - { - return Excel.ChallengeCountDown - RoundsLeft; - } - - public int GetTotalScore() - { - return ScoreStage1 + ScoreStage2; - } - - public bool IsWin() - { - return Status == (int)ChallengeStatus.ChallengeFinish; - } - - #region Management - - public void OnBattleStart(BattleInstance battle) - { - battle.RoundLimit = RoundsLeft; - - if (StoryBuffs != null) + ChallengeId = (uint)Excel.GetId(), + Status = (ChallengeStatus)Status, + ScoreId = (uint)ScoreStage1, + ScoreTwo = (uint)ScoreStage2, + RoundCount = (uint)GetRoundsElapsed(), + ExtraLineupType = (ExtraLineupType)CurrentExtraLineup, + PlayerInfo = new ChallengeStoryInfo { - battle.Buffs.Add(new MazeBuff(Excel.MazeBuffID, 1, -1)); - - if (StoryBuffs.Count >= CurrentStage) - { - int buffId = StoryBuffs[CurrentStage - 1]; - battle.Buffs.Add(new MazeBuff(buffId, 1, -1)); - } + CurStoryBuff = new ChallengeStoryBuffInfo(), + CurBossBuff = new ChallengeBossBuffInfo() } + }; - if (Excel.StoryExcel != null) + if (StoryBuffs != null && StoryBuffs.Count >= CurrentStage) + proto.PlayerInfo.CurStoryBuff.BuffList.Add(StoryBuffs.Select(x => (uint)x)); + + if (BossBuffs != null && BossBuffs.Count >= CurrentStage) + proto.PlayerInfo.CurBossBuff.BuffList.Add(BossBuffs.Select(x => (uint)x)); + + return proto; + } + + #endregion + + #region Management + + public void OnBattleStart(BattleInstance battle) + { + battle.RoundLimit = RoundsLeft; + + if (StoryBuffs != null) + { + battle.Buffs.Add(new MazeBuff(Excel.MazeBuffID, 1, -1)); + + if (StoryBuffs.Count >= CurrentStage) { - battle.AddBattleTarget(1, 10001, GetTotalScore()); - - foreach (var id in Excel.StoryExcel.BattleTargetID!) - { - battle.AddBattleTarget(5, id, GetTotalScore()); - } + var buffId = StoryBuffs[CurrentStage - 1]; + battle.Buffs.Add(new MazeBuff(buffId, 1, -1)); } } - public virtual void OnBattleEnd(BattleInstance battle, PVEBattleResultCsReq req) + if (Excel.StoryExcel != null) { - if (IsStory()) - { - // Calculate score for current stage - int stageScore = (int)req.Stt.ChallengeScore - GetTotalScore(); + battle.AddBattleTarget(1, 10001, GetTotalScore()); - // Set score - if (CurrentStage == 1) - { - ScoreStage1 = stageScore; - } else - { - ScoreStage2 = stageScore; - } - } + foreach (var id in Excel.StoryExcel.BattleTargetID!) battle.AddBattleTarget(5, id, GetTotalScore()); + } + } - switch (req.EndStatus) - { - case BattleEndStatus.BattleEndWin: - // Check if any avatar in the lineup has died - foreach (var avatar in battle.Lineup.AvatarData!.Avatars) - { - if (avatar.CurrentHp <= 0) - { - HasAvatarDied = true; - } - } + public virtual async ValueTask OnBattleEnd(BattleInstance battle, PVEBattleResultCsReq req) + { + if (IsStory()) + { + // Calculate score for current stage + var stageScore = (int)req.Stt.ChallengeScore - GetTotalScore(); - // Get monster count in stage - long monsters = Player.SceneInstance!.Entities.Values.OfType().Count(); - - if (monsters == 0) - { - AdvanceStage(); - } - - // Calculate rounds left - if (IsStory()) - { - RoundsLeft = (int)Math.Min(Math.Max(RoundsLeft - req.Stt.RoundCnt, 1), RoundsLeft); - } - - // Set saved technique points (This will be restored if the player resets the challenge) - SavedMp = Player.LineupManager!.GetCurLineup()!.Mp; - break; - case BattleEndStatus.BattleEndQuit: - // Reset technique points and move back to start position - var lineup = Player.LineupManager!.GetCurLineup()!; - lineup.Mp = SavedMp; - Player.MoveTo(StartPos, StartRot); - Player.SendPacket(new PacketSyncLineupNotify(lineup)); - break; - default: - // Determine challenge result - if ((IsStory() || IsBoss()) && req.Stt.EndReason == BattleEndReason.TurnLimit) - { - AdvanceStage(); - } - else - { - // Fail challenge - Status = (int)ChallengeStatus.ChallengeFailed; - - // Send challenge result data - Player.SendPacket(new PacketChallengeSettleNotify(this)); - } - break; - } + // Set score + if (CurrentStage == 1) + ScoreStage1 = stageScore; + else + ScoreStage2 = stageScore; } - private void AdvanceStage() + switch (req.EndStatus) { - if (CurrentStage >= Excel.StageNum) - { - // Last stage - Status = (int)ChallengeStatus.ChallengeFinish; - Stars = CalculateStars(); + case BattleEndStatus.BattleEndWin: + // Check if any avatar in the lineup has died + foreach (var avatar in battle.Lineup.AvatarData!.Avatars) + if (avatar.CurrentHp <= 0) + HasAvatarDied = true; - // Save history - Player.ChallengeManager!.AddHistory(ChallengeId, Stars, GetTotalScore()); + // Get monster count in stage + long monsters = Player.SceneInstance!.Entities.Values.OfType().Count(); - // Send challenge result data - if (IsBoss()) + if (monsters == 0) await AdvanceStage(); + + // Calculate rounds left + if (IsStory()) RoundsLeft = (int)Math.Min(Math.Max(RoundsLeft - req.Stt.RoundCnt, 1), RoundsLeft); + + // Set saved technique points (This will be restored if the player resets the challenge) + SavedMp = Player.LineupManager!.GetCurLineup()!.Mp; + break; + case BattleEndStatus.BattleEndQuit: + // Reset technique points and move back to start position + var lineup = Player.LineupManager!.GetCurLineup()!; + lineup.Mp = SavedMp; + await Player.MoveTo(StartPos, StartRot); + await Player.SendPacket(new PacketSyncLineupNotify(lineup)); + break; + default: + // Determine challenge result + if ((IsStory() || IsBoss()) && req.Stt.EndReason == BattleEndReason.TurnLimit) { - Player.SendPacket(new PacketChallengeBossPhaseSettleNotify(this)); + await AdvanceStage(); } else { - Player.SendPacket(new PacketChallengeSettleNotify(this)); + // Fail challenge + Status = (int)ChallengeStatus.ChallengeFailed; + + // Send challenge result data + await Player.SendPacket(new PacketChallengeSettleNotify(this)); } - } - else - { - // Increment and reset stage - CurrentStage++; - // Load scene group for stage 2 - Player.SceneInstance!.EntityLoader!.LoadGroup(Excel.MazeGroupID2); - - // Change player line up - SetCurrentExtraLineup(ExtraLineupType.LineupChallenge2); - Player.LineupManager!.SetCurLineup(CurrentExtraLineup + 10); - Player.SendPacket(new PacketChallengeLineupNotify((ExtraLineupType)CurrentExtraLineup)); - SavedMp = Player.LineupManager.GetCurLineup()!.Mp; - - // Move player - Player.MoveTo(StartPos, StartRot); - } + break; } - - public void OnUpdate() - { - // End challenge if its done - if (Status != (int)ChallengeStatus.ChallengeDoing) - { - Player.ChallengeManager!.ChallengeInstance = null; - } - } - - public int CalculateStars() - { - List targets = Excel.ChallengeTargetID!; - int stars = 0; - - for (int i = 0; i < targets.Count; i++) - { - if (!GameData.ChallengeTargetData.ContainsKey(targets[i])) continue; - - var target = GameData.ChallengeTargetData[targets[i]]; - - switch (target.ChallengeTargetType) - { - case ChallengeTargetExcel.ChallengeType.ROUNDS_LEFT: - if (RoundsLeft >= target.ChallengeTargetParam1) - { - stars += (1 << i); - } - break; - case ChallengeTargetExcel.ChallengeType.DEAD_AVATAR: - if (!HasAvatarDied) - { - stars += (1 << i); - } - break; - case ChallengeTargetExcel.ChallengeType.TOTAL_SCORE: - if (GetTotalScore() >= target.ChallengeTargetParam1) - { - stars += (1 << i); - } - break; - default: - break; - } - } - - return Math.Min(stars, 7); - } - - #endregion - - #region Serialization - - public CurChallenge ToProto() - { - CurChallenge proto = new CurChallenge() - { - ChallengeId = (uint)Excel.GetId(), - Status = (ChallengeStatus)Status, - ScoreId = (uint)ScoreStage1, - ScoreTwo = (uint)ScoreStage2, - RoundCount = (uint)GetRoundsElapsed(), - ExtraLineupType = (ExtraLineupType)CurrentExtraLineup, - PlayerInfo = new ChallengeStoryInfo() - { - CurStoryBuff = new ChallengeStoryBuffInfo(), - CurBossBuff = new ChallengeBossBuffInfo(), - } - }; - - if (StoryBuffs != null && StoryBuffs.Count >= CurrentStage) - { - proto.PlayerInfo.CurStoryBuff.BuffList.Add(StoryBuffs.Select(x => (uint)x)); - } - - if (BossBuffs != null && BossBuffs.Count >= CurrentStage) - { - proto.PlayerInfo.CurBossBuff.BuffList.Add(BossBuffs.Select(x => (uint)x)); - } - - return proto; - } - - #endregion } -} + + private async ValueTask AdvanceStage() + { + if (CurrentStage >= Excel.StageNum) + { + // Last stage + Status = (int)ChallengeStatus.ChallengeFinish; + Stars = CalculateStars(); + + // Save history + Player.ChallengeManager!.AddHistory(ChallengeId, Stars, GetTotalScore()); + + // Send challenge result data + if (IsBoss()) + await Player.SendPacket(new PacketChallengeBossPhaseSettleNotify(this)); + else + await Player.SendPacket(new PacketChallengeSettleNotify(this)); + } + else + { + // Increment and reset stage + CurrentStage++; + + // Load scene group for stage 2 + await Player.SceneInstance!.EntityLoader!.LoadGroup(Excel.MazeGroupID2); + + // Change player line up + SetCurrentExtraLineup(ExtraLineupType.LineupChallenge2); + await Player.LineupManager!.SetCurLineup(CurrentExtraLineup + 10); + await Player.SendPacket(new PacketChallengeLineupNotify((ExtraLineupType)CurrentExtraLineup)); + SavedMp = Player.LineupManager.GetCurLineup()!.Mp; + + // Move player + await Player.MoveTo(StartPos, StartRot); + } + } + + public void OnUpdate() + { + // End challenge if its done + if (Status != (int)ChallengeStatus.ChallengeDoing) Player.ChallengeManager!.ChallengeInstance = null; + } + + public int CalculateStars() + { + var targets = Excel.ChallengeTargetID!; + var stars = 0; + + for (var i = 0; i < targets.Count; i++) + { + if (!GameData.ChallengeTargetData.ContainsKey(targets[i])) continue; + + var target = GameData.ChallengeTargetData[targets[i]]; + + switch (target.ChallengeTargetType) + { + case ChallengeTargetExcel.ChallengeType.ROUNDS_LEFT: + if (RoundsLeft >= target.ChallengeTargetParam1) stars += 1 << i; + break; + case ChallengeTargetExcel.ChallengeType.DEAD_AVATAR: + if (!HasAvatarDied) stars += 1 << i; + break; + case ChallengeTargetExcel.ChallengeType.TOTAL_SCORE: + if (GetTotalScore() >= target.ChallengeTargetParam1) stars += 1 << i; + break; + } + } + + return Math.Min(stars, 7); + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Challenge/ChallengeManager.cs b/GameServer/Game/Challenge/ChallengeManager.cs index 80dc660f..6ec6f9c8 100644 --- a/GameServer/Game/Challenge/ChallengeManager.cs +++ b/GameServer/Game/Challenge/ChallengeManager.cs @@ -1,272 +1,260 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Game.Player; +using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Challenge; -using EggLink.DanhengServer.Data.Excel; -using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Database.Inventory; +using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Challenge; -using EggLink.DanhengServer.Database.Lineup; -using EggLink.DanhengServer.Database.Inventory; -namespace EggLink.DanhengServer.Game.Challenge +namespace EggLink.DanhengServer.Game.Challenge; + +public class ChallengeManager(PlayerInstance player) : BasePlayerManager(player) { - public class ChallengeManager(PlayerInstance player) : BasePlayerManager(player) + #region Properties + + public ChallengeInstance? ChallengeInstance { get; set; } + + public ChallengeData ChallengeData { get; } = + DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + + #endregion + + #region Management + + public async ValueTask StartChallenge(int challengeId, StartChallengeStoryBuffInfo? storyBuffs, + StartChallengeBossBuffInfo? bossBuffs) { - #region Properties - - public ChallengeInstance? ChallengeInstance { get; set; } - public ChallengeData ChallengeData { get; private set; } = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); - - #endregion - - #region Management - - public void StartChallenge(int challengeId, StartChallengeStoryBuffInfo? storyBuffs, StartChallengeBossBuffInfo? bossBuffs) + // Get challenge excel + if (!GameData.ChallengeConfigData.TryGetValue(challengeId, out var value)) { - // Get challenge excel - if (!GameData.ChallengeConfigData.TryGetValue(challengeId, out ChallengeConfigExcel? value)) + await Player.SendPacket(new PacketStartChallengeScRsp((uint)Retcode.RetChallengeNotExist)); + return; + } + + var Excel = value; + + // Sanity check lineups + if (Excel.StageNum > 0) + { + // Get lineup + var Lineup = Player.LineupManager!.GetExtraLineup(ExtraLineupType.LineupChallenge)!; + + // Make sure this lineup has avatars set + if (Lineup.AvatarData!.Avatars.Count == 0) { - Player.SendPacket(new PacketStartChallengeScRsp((uint)Retcode.RetChallengeNotExist)); - return; - } - ChallengeConfigExcel Excel = value; - - // Sanity check lineups - if (Excel.StageNum > 0) - { - // Get lineup - var Lineup = Player.LineupManager!.GetExtraLineup(ExtraLineupType.LineupChallenge)!; - - // Make sure this lineup has avatars set - if (Lineup.AvatarData!.Avatars.Count == 0) - { - Player.SendPacket(new PacketStartChallengeScRsp((uint)Retcode.RetChallengeLineupEmpty)); - return; - } - - // Reset hp/sp - foreach (var avatar in Lineup.AvatarData!.Avatars) - { - avatar.SetCurHp(10000, true); - avatar.SetCurSp(avatar.GetCurSp(true) / 2, true); - } - - // Set technique points to full - Lineup.Mp = 5; // Max Mp - } - - if (Excel.StageNum >= 2) - { - // Get lineup - var Lineup = Player.LineupManager!.GetExtraLineup(ExtraLineupType.LineupChallenge2)!; - - // Make sure this lineup has avatars set - if (Lineup.AvatarData!.Avatars.Count == 0) - { - Player.SendPacket(new PacketStartChallengeScRsp((uint)Retcode.RetChallengeLineupEmpty)); - return; - } - - // Reset hp/sp - foreach (var avatar in Lineup.AvatarData!.Avatars) - { - avatar.SetCurHp(10000, true); - avatar.SetCurSp(avatar.GetCurSp(true) / 2, true); - } - - // Set technique points to full - Lineup.Mp = 5; // Max Mp - } - - // Set challenge data for player - ChallengeInstance instance = new(Player, Excel); - ChallengeInstance = instance; - - // Set first lineup before we enter scenes - Player.LineupManager!.SetCurLineup(instance.CurrentExtraLineup + 10); - - // Enter scene - try - { - Player.EnterScene(Excel.MapEntranceID, 0, false); - } - catch - { - // Reset lineup/instance if entering scene failed - ChallengeInstance = null; - - // Send error packet - Player.SendPacket(new PacketStartChallengeScRsp((uint)Retcode.RetChallengeNotExist)); + await Player.SendPacket(new PacketStartChallengeScRsp((uint)Retcode.RetChallengeLineupEmpty)); return; } - // Save start positions - instance.StartPos = Player.Data.Pos!; - instance.StartRot = Player.Data.Rot!; - instance.SavedMp = Player.LineupManager.GetCurLineup()!.Mp; - - if (Excel.IsStory() && storyBuffs != null) + // Reset hp/sp + foreach (var avatar in Lineup.AvatarData!.Avatars) { - instance.StoryBuffs.Add((int)storyBuffs.StoryBuffOne); - instance.StoryBuffs.Add((int)storyBuffs.StoryBuffTwo); + avatar.SetCurHp(10000, true); + avatar.SetCurSp(avatar.GetCurSp(true) / 2, true); } - if (bossBuffs != null) - { - instance.BossBuffs.Add((int)bossBuffs.StoryBuffOne); - instance.BossBuffs.Add((int)bossBuffs.StoryBuffTwo); - } - - // Send packet - Player.SendPacket(new PacketStartChallengeScRsp(Player)); - - // Save instance - SaveInstance(instance); + // Set technique points to full + Lineup.Mp = 5; // Max Mp } - public void AddHistory(int challengeId, int stars, int score) + if (Excel.StageNum >= 2) { - if (stars <= 0) return; + // Get lineup + var Lineup = Player.LineupManager!.GetExtraLineup(ExtraLineupType.LineupChallenge2)!; - if (!ChallengeData.History.ContainsKey(challengeId)) + // Make sure this lineup has avatars set + if (Lineup.AvatarData!.Avatars.Count == 0) { - ChallengeData.History[challengeId] = new ChallengeHistoryData(Player.Uid, challengeId); - } - var info = ChallengeData.History[challengeId]; - - // Set - info.SetStars(stars); - info.Score = score; - } - - public List? TakeRewards(int groupId) - { - // Get excels - if (!GameData.ChallengeGroupData.ContainsKey(groupId)) return null; - var challengeGroup = GameData.ChallengeGroupData[groupId]; - - if (!GameData.ChallengeRewardData.ContainsKey(challengeGroup.RewardLineGroupID)) return null; - var challengeRewardLine = GameData.ChallengeRewardData[challengeGroup.RewardLineGroupID]; - - // Get total stars - int totalStars = 0; - foreach (ChallengeHistoryData ch in ChallengeData.History.Values) - { - // Legacy compatibility - if (ch.GroupId == 0) - { - if (!GameData.ChallengeConfigData.ContainsKey(ch.ChallengeId)) continue; - var challengeExcel = GameData.ChallengeConfigData[ch.ChallengeId]; - - ch.GroupId = challengeExcel.GroupID; - } - - // Add total stars - if (ch.GroupId == groupId) - { - totalStars += ch.GetTotalStars(); - } + await Player.SendPacket(new PacketStartChallengeScRsp((uint)Retcode.RetChallengeLineupEmpty)); + return; } - // Rewards - List rewardInfos = new List(); - List data = new List(); - - // Get challenge rewards - foreach (var challengeReward in challengeRewardLine) + // Reset hp/sp + foreach (var avatar in Lineup.AvatarData!.Avatars) { - // Check if we have enough stars to take this reward - if (totalStars < challengeReward.StarCount) - { - continue; - } - - // Get reward info - if (!ChallengeData.TakenRewards.ContainsKey(groupId)) - { - ChallengeData.TakenRewards[groupId] = new ChallengeGroupReward(Player.Uid, groupId); - } - var reward = ChallengeData.TakenRewards[groupId]; - - // Check if reward has been taken - if (reward.HasTakenReward(challengeReward.StarCount)) - { - continue; - } - - // Set reward as taken - reward.SetTakenReward(challengeReward.StarCount); - - // Get reward excel - if (!GameData.RewardDataData.ContainsKey(challengeReward.RewardID)) continue; - var rewardExcel = GameData.RewardDataData[challengeReward.RewardID]; - - // Add rewards - var proto = new TakenChallengeRewardInfo() - { - StarCount = (uint)challengeReward.StarCount, - Reward = new ItemList() - }; - - foreach (var item in rewardExcel.GetItems()) - { - var itemData = new ItemData() - { - ItemId = item.Item1, - Count = item.Item2 - }; - - proto.Reward.ItemList_.Add(itemData.ToProto()); - data.Add(itemData); - } - - rewardInfos.Add(proto); + avatar.SetCurHp(10000, true); + avatar.SetCurSp(avatar.GetCurSp(true) / 2, true); } - // Add items to inventory - Player.InventoryManager!.AddItems(data); - return rewardInfos; + // Set technique points to full + Lineup.Mp = 5; // Max Mp } - public void SaveInstance(ChallengeInstance instance) + // Set challenge data for player + ChallengeInstance instance = new(Player, Excel); + ChallengeInstance = instance; + + // Set first lineup before we enter scenes + await Player.LineupManager!.SetCurLineup(instance.CurrentExtraLineup + 10); + + // Enter scene + try { - ChallengeData.Instance.StartPos = instance.StartPos; - ChallengeData.Instance.StartRot = instance.StartRot; - ChallengeData.Instance.ChallengeId = instance.ChallengeId; - ChallengeData.Instance.CurrentStage = instance.CurrentStage; - ChallengeData.Instance.CurrentExtraLineup = instance.CurrentExtraLineup; - ChallengeData.Instance.Status = instance.Status; - ChallengeData.Instance.HasAvatarDied = instance.HasAvatarDied; - ChallengeData.Instance.SavedMp = instance.SavedMp; - ChallengeData.Instance.RoundsLeft = instance.RoundsLeft; - ChallengeData.Instance.Stars = instance.Stars; - ChallengeData.Instance.ScoreStage1 = instance.ScoreStage1; - ChallengeData.Instance.ScoreStage2 = instance.ScoreStage2; - ChallengeData.Instance.StoryBuffs = instance.StoryBuffs; - ChallengeData.Instance.BossBuffs = instance.BossBuffs; + await Player.EnterScene(Excel.MapEntranceID, 0, false); } - - public void ClearInstance() + catch { - ChallengeData.Instance.ChallengeId = 0; + // Reset lineup/instance if entering scene failed + ChallengeInstance = null; + + // Send error packet + await Player.SendPacket(new PacketStartChallengeScRsp((uint)Retcode.RetChallengeNotExist)); + return; } - public void ResurrectInstance() + // Save start positions + instance.StartPos = Player.Data.Pos!; + instance.StartRot = Player.Data.Rot!; + instance.SavedMp = Player.LineupManager.GetCurLineup()!.Mp; + + if (Excel.IsStory() && storyBuffs != null) { - if (ChallengeData.Instance != null && ChallengeData.Instance.ChallengeId != 0) - { - int ChallengeId = ChallengeData.Instance.ChallengeId; - if (GameData.ChallengeConfigData.TryGetValue(ChallengeId, out ChallengeConfigExcel? value)) - { - ChallengeConfigExcel Excel = value; - ChallengeInstance instance = new ChallengeInstance(Player, Excel, ChallengeData.Instance); - ChallengeInstance = instance; - } - } + instance.StoryBuffs.Add((int)storyBuffs.StoryBuffOne); + instance.StoryBuffs.Add((int)storyBuffs.StoryBuffTwo); } - #endregion + if (bossBuffs != null) + { + instance.BossBuffs.Add((int)bossBuffs.StoryBuffOne); + instance.BossBuffs.Add((int)bossBuffs.StoryBuffTwo); + } + + // Send packet + await Player.SendPacket(new PacketStartChallengeScRsp(Player)); + + // Save instance + SaveInstance(instance); } - // WatchAndyTW was here + public void AddHistory(int challengeId, int stars, int score) + { + if (stars <= 0) return; + + if (!ChallengeData.History.ContainsKey(challengeId)) + ChallengeData.History[challengeId] = new ChallengeHistoryData(Player.Uid, challengeId); + var info = ChallengeData.History[challengeId]; + + // Set + info.SetStars(stars); + info.Score = score; + } + + public async ValueTask?> TakeRewards(int groupId) + { + // Get excels + if (!GameData.ChallengeGroupData.ContainsKey(groupId)) return null; + var challengeGroup = GameData.ChallengeGroupData[groupId]; + + if (!GameData.ChallengeRewardData.ContainsKey(challengeGroup.RewardLineGroupID)) return null; + var challengeRewardLine = GameData.ChallengeRewardData[challengeGroup.RewardLineGroupID]; + + // Get total stars + var totalStars = 0; + foreach (var ch in ChallengeData.History.Values) + { + // Legacy compatibility + if (ch.GroupId == 0) + { + if (!GameData.ChallengeConfigData.ContainsKey(ch.ChallengeId)) continue; + var challengeExcel = GameData.ChallengeConfigData[ch.ChallengeId]; + + ch.GroupId = challengeExcel.GroupID; + } + + // Add total stars + if (ch.GroupId == groupId) totalStars += ch.GetTotalStars(); + } + + // Rewards + var rewardInfos = new List(); + var data = new List(); + + // Get challenge rewards + foreach (var challengeReward in challengeRewardLine) + { + // Check if we have enough stars to take this reward + if (totalStars < challengeReward.StarCount) continue; + + // Get reward info + if (!ChallengeData.TakenRewards.ContainsKey(groupId)) + ChallengeData.TakenRewards[groupId] = new ChallengeGroupReward(Player.Uid, groupId); + var reward = ChallengeData.TakenRewards[groupId]; + + // Check if reward has been taken + if (reward.HasTakenReward(challengeReward.StarCount)) continue; + + // Set reward as taken + reward.SetTakenReward(challengeReward.StarCount); + + // Get reward excel + if (!GameData.RewardDataData.ContainsKey(challengeReward.RewardID)) continue; + var rewardExcel = GameData.RewardDataData[challengeReward.RewardID]; + + // Add rewards + var proto = new TakenChallengeRewardInfo + { + StarCount = (uint)challengeReward.StarCount, + Reward = new ItemList() + }; + + foreach (var item in rewardExcel.GetItems()) + { + var itemData = new ItemData + { + ItemId = item.Item1, + Count = item.Item2 + }; + + proto.Reward.ItemList_.Add(itemData.ToProto()); + data.Add(itemData); + } + + rewardInfos.Add(proto); + } + + // Add items to inventory + await Player.InventoryManager!.AddItems(data); + return rewardInfos; + } + + public void SaveInstance(ChallengeInstance instance) + { + ChallengeData.Instance.StartPos = instance.StartPos; + ChallengeData.Instance.StartRot = instance.StartRot; + ChallengeData.Instance.ChallengeId = instance.ChallengeId; + ChallengeData.Instance.CurrentStage = instance.CurrentStage; + ChallengeData.Instance.CurrentExtraLineup = instance.CurrentExtraLineup; + ChallengeData.Instance.Status = instance.Status; + ChallengeData.Instance.HasAvatarDied = instance.HasAvatarDied; + ChallengeData.Instance.SavedMp = instance.SavedMp; + ChallengeData.Instance.RoundsLeft = instance.RoundsLeft; + ChallengeData.Instance.Stars = instance.Stars; + ChallengeData.Instance.ScoreStage1 = instance.ScoreStage1; + ChallengeData.Instance.ScoreStage2 = instance.ScoreStage2; + ChallengeData.Instance.StoryBuffs = instance.StoryBuffs; + ChallengeData.Instance.BossBuffs = instance.BossBuffs; + } + + public void ClearInstance() + { + ChallengeData.Instance.ChallengeId = 0; + } + + public void ResurrectInstance() + { + if (ChallengeData.Instance != null && ChallengeData.Instance.ChallengeId != 0) + { + var ChallengeId = ChallengeData.Instance.ChallengeId; + if (GameData.ChallengeConfigData.TryGetValue(ChallengeId, out var value)) + { + var Excel = value; + var instance = new ChallengeInstance(Player, Excel, ChallengeData.Instance); + ChallengeInstance = instance; + } + } + } + + #endregion } + +// WatchAndyTW was here \ No newline at end of file diff --git a/GameServer/Game/ChessRogue/Cell/ChessRogueCellInstance.cs b/GameServer/Game/ChessRogue/Cell/ChessRogueCellInstance.cs index 748c6526..6e324e66 100644 --- a/GameServer/Game/ChessRogue/Cell/ChessRogueCellInstance.cs +++ b/GameServer/Game/ChessRogue/Cell/ChessRogueCellInstance.cs @@ -5,241 +5,232 @@ using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.ChessRogue.Cell +namespace EggLink.DanhengServer.Game.ChessRogue.Cell; + +public class ChessRogueCellInstance { - public class ChessRogueCellInstance + public ChessRogueCellInstance(ChessRogueInstance instance, RogueChestGridItem item) { - public RogueDLCBlockTypeEnum CellType { get; set; } - public int PosY { get; set; } - public int PosX { get; set; } - public int CellId { get; set; } - public int RoomId { get; set; } - public int Layer { get; set; } = 1; - public int MapId { get; set; } - public ChessRogueInstance Instance { get; set; } - public ChessRogueBoardCellStatus CellStatus { get; set; } = ChessRogueBoardCellStatus.Idle; - public ChessRogueRoomConfig? RoomConfig { get; set; } - public int SelectMonsterId { get; set; } + Instance = instance; + Layer = instance.Layers.IndexOf(instance.CurLayer) + 1; + var list = new RandomList(); + list.Add(RogueDLCBlockTypeEnum.MonsterNormal, 8); + list.Add(RogueDLCBlockTypeEnum.Reward, 4); + list.Add(RogueDLCBlockTypeEnum.Event, 6); + list.Add(RogueDLCBlockTypeEnum.NousSpecialEvent, 4); + list.Add(RogueDLCBlockTypeEnum.NousEvent, 2); - public List SelectedDecayId { get; set; } = []; + if (item.BlockTypeList.Count > 0) + CellType = item.BlockTypeList.RandomElement(); + else + CellType = list.GetRandom(); + } - public List CellAdvanceInfo { get; set; } = []; - - public ChessRogueCellInstance(ChessRogueInstance instance, RogueChestGridItem item) + public RogueDLCBlockTypeEnum CellType { get; set; } + public int PosY { get; set; } + public int PosX { get; set; } + public int CellId { get; set; } + public int RoomId { get; set; } + public int Layer { get; set; } = 1; + public int MapId { get; set; } + public ChessRogueInstance Instance { get; set; } + public ChessRogueBoardCellStatus CellStatus { get; set; } = ChessRogueBoardCellStatus.Idle; + public ChessRogueRoomConfig? RoomConfig { get; set; } + public int SelectMonsterId { get; set; } + + public List SelectedDecayId { get; set; } = []; + + public List CellAdvanceInfo { get; set; } = []; + + public void Init() + { + if (CellType == RogueDLCBlockTypeEnum.MonsterBoss) { - Instance = instance; - Layer = instance.Layers.IndexOf(instance.CurLayer) + 1; - var list = new RandomList(); - list.Add(RogueDLCBlockTypeEnum.MonsterNormal, 8); - list.Add(RogueDLCBlockTypeEnum.Reward, 4); - list.Add(RogueDLCBlockTypeEnum.Event, 6); - list.Add(RogueDLCBlockTypeEnum.NousSpecialEvent, 4); - list.Add(RogueDLCBlockTypeEnum.NousEvent, 2); - - if (item.BlockTypeList.Count > 0) + // boss + if (Layer == 1) { - CellType = item.BlockTypeList.RandomElement(); + var randomList = new List(); + foreach (var i in Enumerable.Range(101, 7)) + { + if (i == 103) continue; + randomList.Add(i); + } + + var random1 = randomList.RandomElement(); + randomList.Remove(random1); + CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo + { + BossDecayId = random1, + MonsterId = Random.Shared.Next(221001, 221018) + }); + + CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo + { + BossDecayId = randomList.RandomElement(), + MonsterId = Random.Shared.Next(221001, 221018) + }); } else { - CellType = list.GetRandom(); - } - } + var randomList = new List(); + foreach (var i in Enumerable.Range(2, 3)) randomList.Add(i * 10 + 101); - public void Init() - { - if (CellType == RogueDLCBlockTypeEnum.MonsterBoss) - { - // boss - if (Layer == 1) + var random1 = randomList.RandomElement(); + randomList.Remove(random1); + + CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo { - var randomList = new List(); - foreach (var i in Enumerable.Range(101, 7)) - { - if (i == 103) continue; - randomList.Add(i); - } - - var random1 = randomList.RandomElement(); - randomList.Remove(random1); - CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo() - { - BossDecayId = random1, - MonsterId = Random.Shared.Next(221001, 221018), - }); - - CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo() - { - BossDecayId = randomList.RandomElement(), - MonsterId = Random.Shared.Next(221001, 221018), - }); - } - else - { - var randomList = new List(); - foreach (var i in Enumerable.Range(2, 3)) - { - randomList.Add(i * 10 + 101); - } - - var random1 = randomList.RandomElement(); - randomList.Remove(random1); - - CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo() - { - BossDecayId = random1, - MonsterId = Random.Shared.Next(222001, 222007) - }); - - CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo() - { - BossDecayId = randomList.RandomElement(), - MonsterId = Random.Shared.Next(222001, 222017) - }); - } - } - else if (CellType == RogueDLCBlockTypeEnum.MonsterNousBoss || CellType == RogueDLCBlockTypeEnum.MonsterSwarmBoss) - { - // last boss - CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo() - { - BossDecayId = 114, - MonsterId = 223003 - }); - CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo() - { - BossDecayId = 102 + Instance.BossAeonId * 10, - MonsterId = Random.Shared.Next(223001, 223003) + BossDecayId = random1, + MonsterId = Random.Shared.Next(222001, 222007) }); - foreach (var decay in Instance.BossBuff) + CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo { - SelectedDecayId.Add(decay.BossDecayID); - } + BossDecayId = randomList.RandomElement(), + MonsterId = Random.Shared.Next(222001, 222017) + }); } } - - public int GetBossAeonId(int monsterId) + else if (CellType == RogueDLCBlockTypeEnum.MonsterNousBoss || + CellType == RogueDLCBlockTypeEnum.MonsterSwarmBoss) { - var info = CellAdvanceInfo.Find(x => x.MonsterId == monsterId); - if (info != null) + // last boss + CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo { - return Math.Max((info.BossDecayId - 101 ) / 10, 0); - } - return 0; - } - - public RogueDLCBossDecayExcel? GetBossDecayExcel(int monsterId) - { - var info = CellAdvanceInfo.Find(x => x.MonsterId == monsterId); - if (info != null) + BossDecayId = 114, + MonsterId = 223003 + }); + CellAdvanceInfo.Add(new ChessRogueCellAdvanceInfo { - GameData.RogueDLCBossDecayData.TryGetValue(info.BossDecayId, out var excel); - return excel; - } - return null; - } + BossDecayId = 102 + Instance.BossAeonId * 10, + MonsterId = Random.Shared.Next(223001, 223003) + }); - public int GetCellId() => CellId; - - public int GetEntryId() - { - if (RoomConfig == null) - { - var pool = GameData.ChessRogueRoomData[CellType].FindAll(x => x.EntranceId == Instance.LayerMap).ToList(); - RoomConfig = pool.RandomElement(); - if (Instance.FirstEnterBattle && CellType == RogueDLCBlockTypeEnum.MonsterNormal) - { - do - { - RoomConfig = pool.RandomElement(); - } while (RoomConfig.SubMonsterGroup.Count == 0); // make sure the room has sub monster - Instance.FirstEnterBattle = false; - } - RoomId = RoomConfig.RoomPrefix * 10000 + (int) CellType * 100 + Random.Shared.Next(1, 10); // find a better way to generate room id - } - return RoomConfig.EntranceId; - } - - public int GetRow() - { - return PosX; - } - - public List GetLoadGroupList() - { - var groupList = new List(); - groupList.AddRange(RoomConfig!.DefaultLoadBasicGroup); - groupList.AddRange(RoomConfig.DefaultLoadGroup); - groupList.AddRange(RoomConfig.SubMonsterGroup); - - return groupList; - } - - public ChessRogueCell ToProto() - { - var info = new ChessRogueCell() - { - CellStatus = CellStatus, - PosY = (uint)PosY, - Id = (uint)GetCellId(), - CellType = (uint)CellType, - IsUnlock = true, - RoomId = (uint)RoomId, - MGEHIHCCHHO = true, - PosX = (uint)GetRow(), - }; - - if (CellAdvanceInfo.Count > 0) - { - info.PlayerInfo = new() - { - BossInfo = new() - { - MonsterList = { CellAdvanceInfo.Select(x => x.ToProto()).ToList() }, - SelectBossId = (uint)SelectMonsterId - }, - }; - - if (SelectedDecayId.Count > 0) - { - info.PlayerInfo.SelectBossInfo = new() - { - SelectDecayId = { SelectedDecayId.Select(x => (uint)x).ToList() } - }; - } - } - - return info; - } - - public ChessRogueHistoryCellInfo ToHistoryProto() - { - var info = new ChessRogueHistoryCellInfo() - { - RoomId = (uint)RoomId, - CellId = (uint)GetCellId(), - }; - - return info; + foreach (var decay in Instance.BossBuff) SelectedDecayId.Add(decay.BossDecayID); } } - public class ChessRogueCellAdvanceInfo + public int GetBossAeonId(int monsterId) { - public int BossDecayId { get; set; } - public int MonsterId { get; set; } + var info = CellAdvanceInfo.Find(x => x.MonsterId == monsterId); + if (info != null) return Math.Max((info.BossDecayId - 101) / 10, 0); + return 0; + } - public CellMonster ToProto() => new() + public RogueDLCBossDecayExcel? GetBossDecayExcel(int monsterId) + { + var info = CellAdvanceInfo.Find(x => x.MonsterId == monsterId); + if (info != null) + { + GameData.RogueDLCBossDecayData.TryGetValue(info.BossDecayId, out var excel); + return excel; + } + + return null; + } + + public int GetCellId() + { + return CellId; + } + + public int GetEntryId() + { + if (RoomConfig == null) + { + var pool = GameData.ChessRogueRoomData[CellType].FindAll(x => x.EntranceId == Instance.LayerMap).ToList(); + RoomConfig = pool.RandomElement(); + if (Instance.FirstEnterBattle && CellType == RogueDLCBlockTypeEnum.MonsterNormal) + { + do + { + RoomConfig = pool.RandomElement(); + } while (RoomConfig.SubMonsterGroup.Count == 0); // make sure the room has sub monster + + Instance.FirstEnterBattle = false; + } + + RoomId = RoomConfig.RoomPrefix * 10000 + (int)CellType * 100 + + Random.Shared.Next(1, 10); // find a better way to generate room id + } + + return RoomConfig.EntranceId; + } + + public int GetRow() + { + return PosX; + } + + public List GetLoadGroupList() + { + var groupList = new List(); + groupList.AddRange(RoomConfig!.DefaultLoadBasicGroup); + groupList.AddRange(RoomConfig.DefaultLoadGroup); + groupList.AddRange(RoomConfig.SubMonsterGroup); + + return groupList; + } + + public ChessRogueCell ToProto() + { + var info = new ChessRogueCell + { + CellStatus = CellStatus, + PosY = (uint)PosY, + Id = (uint)GetCellId(), + CellType = (uint)CellType, + IsUnlock = true, + RoomId = (uint)RoomId, + MGEHIHCCHHO = true, + PosX = (uint)GetRow() + }; + + if (CellAdvanceInfo.Count > 0) + { + info.PlayerInfo = new CellAdvanceInfo + { + BossInfo = new CellMonsterInfo + { + MonsterList = { CellAdvanceInfo.Select(x => x.ToProto()).ToList() }, + SelectBossId = (uint)SelectMonsterId + } + }; + + if (SelectedDecayId.Count > 0) + info.PlayerInfo.SelectBossInfo = new CellMonsterSelectInfo + { + SelectDecayId = { SelectedDecayId.Select(x => (uint)x).ToList() } + }; + } + + return info; + } + + public ChessRogueHistoryCellInfo ToHistoryProto() + { + var info = new ChessRogueHistoryCellInfo + { + RoomId = (uint)RoomId, + CellId = (uint)GetCellId() + }; + + return info; + } +} + +public class ChessRogueCellAdvanceInfo +{ + public int BossDecayId { get; set; } + public int MonsterId { get; set; } + + public CellMonster ToProto() + { + return new CellMonster { BossDecayId = (uint)BossDecayId, MonsterId = (uint)MonsterId }; } -} +} \ No newline at end of file diff --git a/GameServer/Game/ChessRogue/Cell/ChessRogueEntityLoader.cs b/GameServer/Game/ChessRogue/Cell/ChessRogueEntityLoader.cs index 68b0d3d2..501eb91a 100644 --- a/GameServer/Game/ChessRogue/Cell/ChessRogueEntityLoader.cs +++ b/GameServer/Game/ChessRogue/Cell/ChessRogueEntityLoader.cs @@ -1,173 +1,136 @@ -using EggLink.DanhengServer.Data.Config; -using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Data.Config; +using EggLink.DanhengServer.Data.Excel; +using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Rogue.Scene.Entity; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using EggLink.DanhengServer.Game.Rogue; using EggLink.DanhengServer.Util; -using EggLink.DanhengServer.Enums.Rogue; -using EggLink.DanhengServer.Data.Excel; -namespace EggLink.DanhengServer.Game.ChessRogue.Cell +namespace EggLink.DanhengServer.Game.ChessRogue.Cell; + +public class ChessRogueEntityLoader(SceneInstance scene) : SceneEntityLoader(scene) { - public class ChessRogueEntityLoader(SceneInstance scene) : SceneEntityLoader(scene) + public ChessRogueInstance instance = scene.Player.ChessRogueManager!.RogueInstance!; + + public override async ValueTask LoadEntity() { - public ChessRogueInstance instance = scene.Player.ChessRogueManager!.RogueInstance!; + if (Scene.IsLoaded) return; - public override void LoadEntity() + foreach (var group in Scene?.FloorInfo?.Groups.Values!) // Sanity check in SceneInstance { - if (Scene.IsLoaded) return; - - foreach (var group in Scene?.FloorInfo?.Groups.Values!) // Sanity check in SceneInstance - { - if (group.LoadSide == GroupLoadSideEnum.Client) - { - continue; - } - if (instance.CurCell!.GetLoadGroupList().Contains(group.Id)) - { - LoadGroup(group); - } - else if (group.Category == GroupCategoryEnum.Normal) - { - LoadGroup(group); - } - } - Scene.IsLoaded = true; + if (group.LoadSide == GroupLoadSideEnum.Client) continue; + if (instance.CurCell!.GetLoadGroupList().Contains(group.Id)) + await LoadGroup(group); + else if (group.Category == GroupCategoryEnum.Normal) await LoadGroup(group); } + Scene.IsLoaded = true; + } - public override EntityNpc? LoadNpc(NpcInfo info, GroupInfo group, bool sendPacket = false) + + public override async ValueTask LoadNpc(NpcInfo info, GroupInfo group, bool sendPacket = false) + { + if (info.IsClientOnly || info.IsDelete) return null; + if (!GameData.NpcDataData.ContainsKey(info.NPCID)) return null; + + RogueNpc npc = new(Scene, group, info); + if (info.NPCID == 3013) { - if (info.IsClientOnly || info.IsDelete) + // generate event + var i = await instance.GenerateEvent(npc); + if (i != null) { - return null; + npc.RogueEvent = i; + npc.RogueNpcId = i.EventId; + npc.UniqueId = i.EventUniqueId; } - if (!GameData.NpcDataData.ContainsKey(info.NPCID)) - { - return null; - } - - bool hasDuplicateNpcId = false; - foreach (IGameEntity entity in Scene.Entities.Values) - { - if (entity is EntityNpc eNpc && eNpc.NpcId == info.NPCID) - { - hasDuplicateNpcId = true; - break; - } - } - if (hasDuplicateNpcId) - { - return null; - } - - RogueNpc npc = new(Scene, group, info); - if (info.NPCID == 3013) - { - // generate event - var eventInstance = instance.GenerateEvent(npc); - if (instance != null) - { - npc.RogueEvent = eventInstance; - npc.RogueNpcId = eventInstance.EventId; - npc.UniqueId = eventInstance.EventUniqueId; - } - } - Scene.AddEntity(npc, sendPacket); - - return npc; } - public override EntityMonster? LoadMonster(MonsterInfo info, GroupInfo group, bool sendPacket = false) + await Scene.AddEntity(npc, sendPacket); + + return npc; + } + + public override async ValueTask LoadMonster(MonsterInfo info, GroupInfo group, + bool sendPacket = false) + { + if (info.IsClientOnly || info.IsDelete) return null; + + var room = instance.CurCell; + if (room == null) return null; + int monsterId; + RogueMonsterExcel? rogueMonster; + if (room.SelectMonsterId > 0) { - if (info.IsClientOnly || info.IsDelete) - { - return null; - } + monsterId = room.SelectMonsterId; - var room = instance.CurCell; - if (room == null) return null; - int monsterId; - RogueMonsterExcel? rogueMonster; - if (room.SelectMonsterId > 0) + GameData.RogueMonsterData.TryGetValue(monsterId * 10 + 1, out rogueMonster); + if (rogueMonster == null) return null; + } + else + { + List allowedRank = []; + if (room.CellType == RogueDLCBlockTypeEnum.MonsterElite) { - monsterId = room.SelectMonsterId; - - GameData.RogueMonsterData.TryGetValue(monsterId * 10 + 1, out rogueMonster); - if (rogueMonster == null) return null; + allowedRank.Add(MonsterRankEnum.Elite); } else { - List allowedRank = []; - if (room.CellType == RogueDLCBlockTypeEnum.MonsterElite) - { - allowedRank.Add(MonsterRankEnum.Elite); - } else - { - allowedRank.Add(MonsterRankEnum.Minion); - allowedRank.Add(MonsterRankEnum.MinionLv2); - } - - NPCMonsterDataExcel? data; - do - { - rogueMonster = GameData.RogueMonsterData.Values.ToList().RandomElement(); - GameData.NpcMonsterDataData.TryGetValue(rogueMonster.NpcMonsterID, out data); - } while (data == null || !allowedRank.Contains(data.Rank)); + allowedRank.Add(MonsterRankEnum.Minion); + allowedRank.Add(MonsterRankEnum.MinionLv2); } - GameData.NpcMonsterDataData.TryGetValue(rogueMonster.NpcMonsterID, out var excel); - if (excel == null) return null; + NPCMonsterDataExcel? data; + do + { + rogueMonster = GameData.RogueMonsterData.Values.ToList().RandomElement(); + GameData.NpcMonsterDataData.TryGetValue(rogueMonster.NpcMonsterID, out data); + } while (data == null || !allowedRank.Contains(data.Rank)); + } - EntityMonster entity = new(Scene, info.ToPositionProto(), info.ToRotationProto(), group.Id, info.ID, excel, info) + GameData.NpcMonsterDataData.TryGetValue(rogueMonster.NpcMonsterID, out var excel); + if (excel == null) return null; + + EntityMonster entity = + new(Scene, info.ToPositionProto(), info.ToRotationProto(), group.Id, info.ID, excel, info) { EventID = rogueMonster.EventID, CustomStageID = rogueMonster.EventID }; - Scene.AddEntity(entity, sendPacket); + await Scene.AddEntity(entity, sendPacket); - return entity; - } - - public override EntityProp? LoadProp(PropInfo info, GroupInfo group, bool sendPacket = false) - { - GameData.MazePropData.TryGetValue(info.PropID, out var propExcel); - if (propExcel == null) - { - return null; - } - - var prop = new RogueProp(Scene, propExcel, group, info); - - if (prop.PropInfo.PropID == 1026) - { - prop.SetState(PropStateEnum.CustomState02); - prop.IsChessRogue = true; - if (instance.CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterBoss || instance.CurCell.CellType == RogueDLCBlockTypeEnum.MonsterNousBoss || instance.CurCell.CellType == RogueDLCBlockTypeEnum.MonsterSwarmBoss) - { - prop.SetState(PropStateEnum.CustomState04); - if (instance.CurCell!.CellType != RogueDLCBlockTypeEnum.MonsterBoss) - { - prop.IsLastRoom = true; - } - } - } - else - { - prop.SetState(info.State); - } - - Scene.AddEntity(prop, sendPacket); - - return null; - } + return entity; } -} + + public override async ValueTask LoadProp(PropInfo info, GroupInfo group, bool sendPacket = false) + { + GameData.MazePropData.TryGetValue(info.PropID, out var propExcel); + if (propExcel == null) return null; + + var prop = new RogueProp(Scene, propExcel, group, info); + + if (prop.PropInfo.PropID == 1026) + { + await prop.SetState(PropStateEnum.CustomState02); + prop.IsChessRogue = true; + if (instance.CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterBoss || + instance.CurCell.CellType == RogueDLCBlockTypeEnum.MonsterNousBoss || + instance.CurCell.CellType == RogueDLCBlockTypeEnum.MonsterSwarmBoss) + { + await prop.SetState(PropStateEnum.CustomState04); + if (instance.CurCell!.CellType != RogueDLCBlockTypeEnum.MonsterBoss) prop.IsLastRoom = true; + } + } + else + { + await prop.SetState(info.State); + } + + await Scene.AddEntity(prop, sendPacket); + + return null; + } +} \ No newline at end of file diff --git a/GameServer/Game/ChessRogue/ChessRogueInstance.cs b/GameServer/Game/ChessRogue/ChessRogueInstance.cs index 14fdd126..f24826d2 100644 --- a/GameServer/Game/ChessRogue/ChessRogueInstance.cs +++ b/GameServer/Game/ChessRogue/ChessRogueInstance.cs @@ -7,756 +7,690 @@ using EggLink.DanhengServer.Game.ChessRogue.Dice; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Rogue; using EggLink.DanhengServer.Game.Rogue.Buff; +using EggLink.DanhengServer.Game.Rogue.Event; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.ChessRogue; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.ChessRogue +namespace EggLink.DanhengServer.Game.ChessRogue; + +public class ChessRogueInstance : BaseRogueInstance { - public class ChessRogueInstance : BaseRogueInstance + public ChessRogueInstance(PlayerInstance player, RogueDLCAreaExcel areaExcel, RogueNousAeonExcel aeonExcel, + int rogueVersionId, int branchId) : base(player, rogueVersionId, aeonExcel.RogueBuffType) { - public RogueDLCAreaExcel AreaExcel { get; set; } - public RogueNousAeonExcel AeonExcel { get; set; } - public List DifficultyLevel { get; set; } = []; - public List BossBuff { get; set; } = []; - public int BossAeonId { get; set; } - public List DifficultyExcel { get; set; } = []; - public ChessRogueDiceInstance DiceInstance { get; set; } + CurLineup = player.LineupManager!.GetCurLineup()!; + Player = player; + AeonId = aeonExcel.AeonID; + AreaExcel = areaExcel; + AeonExcel = aeonExcel; + DiceInstance = new ChessRogueDiceInstance(this, player.ChessRogueManager!.GetDice(branchId)); + Layers = areaExcel.LayerIDList; + CurLayer = Layers.First(); + EventManager = new RogueEventManager(player, this); - public Dictionary RogueCells { get; set; } = []; - public ChessRogueCellInstance? CurCell { get; set; } - public List HistoryCell { get; set; } = []; - public int StartCell { get; set; } = 0; + if (rogueVersionId == 202) + RogueType = 160; + else + RogueType = 130; - public List Layers { get; set; } = []; - public int CurLayer { get; set; } = 0; - public RogueDLCChessBoardExcel? CurBoardExcel { get; set; } - public ChessRogueLevelStatusType CurLevelStatus { get; set; } = ChessRogueLevelStatusType.ChessRogueLevelProcessing; + foreach (var difficulty in areaExcel.DifficultyID) + if (GameData.RogueDLCDifficultyData.TryGetValue(difficulty, out var diff)) + DifficultyExcel.Add(diff); - public bool FirstEnterBattle { get; set; } = true; - public int LayerMap { get; set; } = 0; - - public int ActionPoint { get; set; } = 15; - - public List DisableAeonIds { get; set; } = []; - - public ChessRogueInstance(PlayerInstance player, RogueDLCAreaExcel areaExcel, RogueNousAeonExcel aeonExcel, int rogueVersionId, int branchId) : base(player, rogueVersionId, aeonExcel.RogueBuffType) + var action = new RogueActionInstance { - CurLineup = player.LineupManager!.GetCurLineup()!; - Player = player; - AeonId = aeonExcel.AeonID; - AreaExcel = areaExcel; - AeonExcel = aeonExcel; - DiceInstance = new(this, player.ChessRogueManager!.GetDice(branchId)); - Layers = areaExcel.LayerIDList; - CurLayer = Layers.First(); - EventManager = new(player, this); + QueuePosition = CurActionQueuePosition + }; + action.SetBonus(); - if (rogueVersionId == 202) - { - RogueType = 160; - } else - { - RogueType = 130; - } + RogueActions.Add(CurActionQueuePosition, action); - foreach (var difficulty in areaExcel.DifficultyID) - { - if (GameData.RogueDLCDifficultyData.TryGetValue(difficulty, out var diff)) - DifficultyExcel.Add(diff); - } + // generate cells + GenerateLayer(); + } - var action = new RogueActionInstance() - { - QueuePosition = CurActionQueuePosition, - }; - action.SetBonus(); + public RogueDLCAreaExcel AreaExcel { get; set; } + public RogueNousAeonExcel AeonExcel { get; set; } + public List DifficultyLevel { get; set; } = []; + public List BossBuff { get; set; } = []; + public int BossAeonId { get; set; } + public List DifficultyExcel { get; set; } = []; + public ChessRogueDiceInstance DiceInstance { get; set; } - RogueActions.Add(CurActionQueuePosition, action); + public Dictionary RogueCells { get; set; } = []; + public ChessRogueCellInstance? CurCell { get; set; } + public List HistoryCell { get; set; } = []; + public int StartCell { get; set; } - // generate cells - GenerateLayer(); + public List Layers { get; set; } = []; + public int CurLayer { get; set; } + public RogueDLCChessBoardExcel? CurBoardExcel { get; set; } + public ChessRogueLevelStatusType CurLevelStatus { get; set; } = ChessRogueLevelStatusType.ChessRogueLevelProcessing; + + public bool FirstEnterBattle { get; set; } = true; + public int LayerMap { get; set; } + + public int ActionPoint { get; set; } = 15; + + public List DisableAeonIds { get; set; } = []; + + public override void OnBattleStart(BattleInstance battle) + { + base.OnBattleStart(battle); + + if (DifficultyExcel.Count > 0) battle.CustomLevel = DifficultyExcel.RandomElement().LevelList.RandomElement(); + + if (ActionPoint < 0) + { + GameData.ActionPointOverdrawData.TryGetValue(Math.Max(ActionPoint, -50), out var overdrawData); + if (overdrawData != null) + battle.Buffs.Add(new MazeBuff(overdrawData.MazeBuff, 1, -1) + { + WaveFlag = -1 + }); } - #region Buff Management + CalculateDifficulty(battle); - public override void RollBuff(int amount) + if (CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterNousBoss || + CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterSwarmBoss) { - if (CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterBoss) + var buffList = new List(); + foreach (var buff in BossBuff) + if (buff.EffectType == BossDecayEffectTypeEnum.AddMazeBuffList) + buffList.SafeAddRange(buff.EffectParamList); // add buff + else + foreach (var param in buff.EffectParamList) // remove buff + buffList.Remove(param); + + foreach (var buffId in buffList) + battle.Buffs.Add(new MazeBuff(buffId, 1, -1) + { + WaveFlag = -1 + }); + } + } + + public void CalculateDifficulty(BattleInstance battle) + { + if (DifficultyExcel.Count > 0) + { + List difficultyIds = []; + List buffs = []; + + foreach (var difficulty in DifficultyLevel) difficultyIds.Add(difficulty.DifficultyID); + + if (difficultyIds.Contains(103)) + buffs.Add(new MazeBuff(610121, 1, -1) + { + WaveFlag = -1 + }); + + if (difficultyIds.Contains(105)) + buffs.Add(new MazeBuff(610121, 1, -1) + { + WaveFlag = -1 + }); + + var attributeBuffId = 0; + + if (difficultyIds.Contains(106)) + attributeBuffId = 650204; + else if (difficultyIds.Contains(104)) + attributeBuffId = 650203; + else if (difficultyIds.Contains(102)) + attributeBuffId = 650202; + else if (difficultyIds.Contains(101)) attributeBuffId = 650201; + + buffs.Add(new MazeBuff(attributeBuffId, 1, -1) { - RollBuff(amount, 100003, 2); // boss room - RollMiracle(1); - } - else - { - RollBuff(amount, 100005); - } + WaveFlag = -1, + DynamicValues = { { "_RogueLayer", Layers.IndexOf(CurLayer) + 1 } } + }); + + foreach (var buff in buffs) battle.Buffs.Add(buff); + } + } + + public override async ValueTask OnBattleEnd(BattleInstance battle, PVEBattleResultCsReq req) + { + foreach (var miracle in RogueMiracles.Values) miracle.OnEndBattle(battle); + + if (req.EndStatus != BattleEndStatus.BattleEndWin) + { + // quit + CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelFailed; + await Player.SendPacket(new PacketChessRogueUpdateLevelBaseInfoScNotify(CurLevelStatus)); + return; } - public void AddAeonBuff() // TODO: support for aeon cross + await RollBuff(battle.Stages.Count); + + if (CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterBoss) { - if (AeonBuffPending) return; - if (CurAeonBuffCount + CurAeonEnhanceCount >= 4) - { - // max aeon buff count - return; - } - int curAeonBuffCount = 0; // current path buff count - int hintId = AeonId * 100 + 1; - var enhanceData = GameData.RogueAeonEnhanceData[AeonId]; - var buffData = GameData.RogueAeonBuffData[AeonId]; - foreach (var buff in RogueBuffs) - { - if (buff.BuffExcel.RogueBuffType == AeonExcel.RogueBuffType) - { - if (!buff.BuffExcel.IsAeonBuff) - { - curAeonBuffCount++; - } - else - { - hintId++; // next hint - enhanceData.Remove(buff.BuffExcel); - } - } - } + await Player.SendPacket(new PacketChessRogueLayerAccountInfoNotify(this)); + } + else if (CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterNousBoss || + CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterSwarmBoss) + { + CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelFinish; + await Player.SendPacket(new PacketChessRogueLayerAccountInfoNotify(this)); + await Player.SendPacket(new PacketChessRogueUpdateLevelBaseInfoScNotify(CurLevelStatus)); + } + } - var needAeonBuffCount = (CurAeonBuffCount + CurAeonEnhanceCount) switch - { - 0 => 3, - 1 => 6, - 2 => 10, - 3 => 14, - _ => 100, - }; + #region Buff Management - if (curAeonBuffCount >= needAeonBuffCount) + public override async ValueTask RollBuff(int amount) + { + if (CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterBoss) + { + await RollBuff(amount, 100003, 2); // boss room + await RollMiracle(1); + } + else + { + await RollBuff(amount, 100005); + } + } + + public async ValueTask AddAeonBuff() // TODO: support for aeon cross + { + if (AeonBuffPending) return; + if (CurAeonBuffCount + CurAeonEnhanceCount >= 4) + // max aeon buff count + return; + var curAeonBuffCount = 0; // current path buff count + var hintId = AeonId * 100 + 1; + var enhanceData = GameData.RogueAeonEnhanceData[AeonId]; + var buffData = GameData.RogueAeonBuffData[AeonId]; + foreach (var buff in RogueBuffs) + if (buff.BuffExcel.RogueBuffType == AeonExcel.RogueBuffType) { - RogueBuffSelectMenu menu = new(this) + if (!buff.BuffExcel.IsAeonBuff) { - QueueAppend = 2, - HintId = hintId, - RollMaxCount = 0, - RollFreeCount = 0, - IsAeonBuff = true, - }; - if (CurAeonBuffCount < 1) - { - CurAeonBuffCount++; - // add aeon buff - menu.RollBuff([buffData], 1); + curAeonBuffCount++; } else { - CurAeonEnhanceCount++; - // add enhance buff - menu.RollBuff(enhanceData, enhanceData.Count); + hintId++; // next hint + enhanceData.Remove(buff.BuffExcel); } - - var action = menu.GetActionInstance(); - RogueActions.Add(action.QueuePosition, action); - - AeonBuffPending = true; - UpdateMenu(); - } - } - public override void UpdateMenu() - { - base.UpdateMenu(); - - - AddAeonBuff(); // check if aeon buff can be added - } - - #endregion - - #region Map Management - - public void EnterNextLayer() - { - HistoryCell.Clear(); - CurLayer = Layers[Layers.IndexOf(CurLayer) + 1]; - CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelProcessing; - - GenerateLayer(); - EnterCell(StartCell); - - Player.SendPacket(new PacketChessRogueEnterNextLayerScRsp(this)); - } - - public void GenerateLayer() - { - var level = Layers.IndexOf(CurLayer) + 1; - FirstEnterBattle = true; - - LayerMap = GameConstants.AllowedChessRogueEntranceId.RandomElement(); - - if (RogueVersionId == 201) - { - CurBoardExcel = GameData.RogueSwarmChessBoardData[level].RandomElement(); - } else - { - CurBoardExcel = GameData.RogueNousChessBoardData[level].RandomElement(); } - RogueCells.Clear(); - CurCell = null; - - StartCell = CurBoardExcel.MapInfo!.StartGridItemID; - - foreach (var item in CurBoardExcel.MapInfo!.RogueChestGridItemMap) - { - var cell = new ChessRogueCellInstance(this, item.Value) - { - PosY = item.Value.PosY, - PosX = item.Value.PosX, - CellId = item.Key, - }; - RogueCells.Add(item.Key, cell); - - //if (cell.GetCellId() == CurBoardExcel.MapInfo!.EndGridItemID) // last cell - //{ - cell.Init(); - //} - } - } - - public void EnterCell(int id, int monsterId = 0) + var needAeonBuffCount = (CurAeonBuffCount + CurAeonEnhanceCount) switch { - if (RogueCells.TryGetValue(id, out var cell)) - { - if (monsterId > 0) - { - cell.SelectMonsterId = monsterId; - if (BossAeonId == 0) - { - BossAeonId = cell.GetBossAeonId(monsterId); - } + 0 => 3, + 1 => 6, + 2 => 10, + 3 => 14, + _ => 100 + }; - var excel = cell.GetBossDecayExcel(monsterId); - if (excel != null) - { - BossBuff.Add(excel); - } - } - - CurCell = cell; - cell.CellStatus = ChessRogueBoardCellStatus.Finish; - - Player.EnterMissionScene(cell.GetEntryId(), cell.RoomConfig!.AnchorGroup, cell.RoomConfig!.AnchorId, false); - - HistoryCell.Add(cell); - - DiceInstance.CurSurfaceId = 0; - DiceInstance.DiceStatus = ChessRogueDiceStatus.ChessRogueDiceIdle; - Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); - } - } - - public void SelectCell(int cellId) + if (curAeonBuffCount >= needAeonBuffCount) { - var cell = RogueCells[cellId]; - if (cell.CellStatus == ChessRogueBoardCellStatus.Finish) + RogueBuffSelectMenu menu = new(this) { - return; + QueueAppend = 2, + HintId = hintId, + RollMaxCount = 0, + RollFreeCount = 0, + IsAeonBuff = true + }; + if (CurAeonBuffCount < 1) + { + CurAeonBuffCount++; + // add aeon buff + menu.RollBuff([buffData], 1); + } + else + { + CurAeonEnhanceCount++; + // add enhance buff + menu.RollBuff(enhanceData, enhanceData.Count); } - cell.CellStatus = ChessRogueBoardCellStatus.Selected; + var action = menu.GetActionInstance(); + RogueActions.Add(action.QueuePosition, action); - Player.SendPacket(new PacketChessRogueCellUpdateNotify(cell, CurBoardExcel?.ChessBoardID ?? 0)); - CostActionPoint(1); - - Player.SendPacket(new PacketChessRogueSelectCellScRsp(cellId)); + AeonBuffPending = true; + await UpdateMenu(); } + } - #endregion + public override async ValueTask UpdateMenu() + { + await base.UpdateMenu(); - #region Dice Management - public void RollDice() + await AddAeonBuff(); // check if aeon buff can be added + } + + #endregion + + #region Map Management + + public async ValueTask EnterNextLayer() + { + HistoryCell.Clear(); + CurLayer = Layers[Layers.IndexOf(CurLayer) + 1]; + CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelProcessing; + + GenerateLayer(); + await EnterCell(StartCell); + + await Player.SendPacket(new PacketChessRogueEnterNextLayerScRsp(this)); + } + + public void GenerateLayer() + { + var level = Layers.IndexOf(CurLayer) + 1; + FirstEnterBattle = true; + + LayerMap = GameConstants.AllowedChessRogueEntranceId.RandomElement(); + + if (RogueVersionId == 201) + CurBoardExcel = GameData.RogueSwarmChessBoardData[level].RandomElement(); + else + CurBoardExcel = GameData.RogueNousChessBoardData[level].RandomElement(); + + RogueCells.Clear(); + CurCell = null; + + StartCell = CurBoardExcel.MapInfo!.StartGridItemID; + + foreach (var item in CurBoardExcel.MapInfo!.RogueChestGridItemMap) { - DiceInstance.RollDice(); + var cell = new ChessRogueCellInstance(this, item.Value) + { + PosY = item.Value.PosY, + PosX = item.Value.PosX, + CellId = item.Key + }; + RogueCells.Add(item.Key, cell); - Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); - Player.SendPacket(new PacketChessRogueRollDiceScRsp(DiceInstance)); - } - - public void ReRollDice() - { - DiceInstance.RerollTimes--; - DiceInstance.RollDice(); - - Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); - Player.SendPacket(new PacketChessRogueReRollDiceScRsp(DiceInstance)); - } - - public void CheatDice(int surfaceId) - { - DiceInstance.CheatTimes--; - DiceInstance.CurSurfaceId = surfaceId; - - Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); - Player.SendPacket(new PacketChessRogueCheatRollScRsp(DiceInstance, surfaceId)); - } - - public void ConfirmRoll() - { - DiceInstance.DiceStatus = ChessRogueDiceStatus.ChessRogueDiceConfirmed; - - Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); - Player.SendPacket(new PacketChessRogueConfirmRollScRsp(DiceInstance)); - - //var cellIds = new List(); - - //foreach (var cell in RogueCells) + //if (cell.GetCellId() == CurBoardExcel.MapInfo!.EndGridItemID) // last cell //{ - // if (cell.Key == CurCell!.GetCellId() || cell.Value.CellStatus == ChessRogueBoardCellStatus.Finish) - // { - // continue; - // } - // cellIds.Add(cell.Key); + cell.Init(); //} - - //Player.SendPacket(new PacketChessRogueUpdateAllowedSelectCellScNotify(CurLayerData![-1][0], cellIds)); } + } - #endregion - - #region Action Management - - public void CostActionPoint(int cost) + public async ValueTask EnterCell(int id, int monsterId = 0) + { + if (RogueCells.TryGetValue(id, out var cell)) { - ActionPoint -= cost; - - Player.SendPacket(new PacketChessRogueUpdateActionPointScNotify(ActionPoint)); - } - - public void QuitRogue() - { - CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelFinish; - Player.SendPacket(new PacketChessRogueUpdateLevelBaseInfoScNotify(CurLevelStatus)); - - Player.ChessRogueManager!.RogueInstance = null; - Player.EnterScene(801120102, 0, false); - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); - - Player.SendPacket(new PacketChessRogueQuitScRsp(this)); - } - - public void LeaveRogue() - { - CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelFinish; - Player.SendPacket(new PacketChessRogueUpdateLevelBaseInfoScNotify(CurLevelStatus)); - - Player.ChessRogueManager!.RogueInstance = null; - Player.EnterScene(801120102, 0, false); - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); - - Player.SendPacket(new PacketChessRogueLeaveScRsp(this)); - } - - #endregion - - public override void OnBattleStart(BattleInstance battle) - { - base.OnBattleStart(battle); - - if (DifficultyExcel.Count > 0) + if (monsterId > 0) { - battle.CustomLevel = DifficultyExcel.RandomElement().LevelList.RandomElement(); + cell.SelectMonsterId = monsterId; + if (BossAeonId == 0) BossAeonId = cell.GetBossAeonId(monsterId); + + var excel = cell.GetBossDecayExcel(monsterId); + if (excel != null) BossBuff.Add(excel); } - if (ActionPoint < 0) - { - GameData.ActionPointOverdrawData.TryGetValue(Math.Max(ActionPoint, -50), out var overdrawData); - if (overdrawData != null) - { - battle.Buffs.Add(new MazeBuff(overdrawData.MazeBuff, 1, -1) - { - WaveFlag = -1, - }); - } - } + CurCell = cell; + cell.CellStatus = ChessRogueBoardCellStatus.Finish; - CalculateDifficulty(battle); + await Player.EnterMissionScene(cell.GetEntryId(), cell.RoomConfig!.AnchorGroup, cell.RoomConfig!.AnchorId, + false); - if (CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterNousBoss || CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterSwarmBoss) + HistoryCell.Add(cell); + + DiceInstance.CurSurfaceId = 0; + DiceInstance.DiceStatus = ChessRogueDiceStatus.ChessRogueDiceIdle; + await Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); + } + } + + public async ValueTask SelectCell(int cellId) + { + var cell = RogueCells[cellId]; + if (cell.CellStatus == ChessRogueBoardCellStatus.Finish) return; + + cell.CellStatus = ChessRogueBoardCellStatus.Selected; + + await Player.SendPacket(new PacketChessRogueCellUpdateNotify(cell, CurBoardExcel?.ChessBoardID ?? 0)); + await CostActionPoint(1); + + await Player.SendPacket(new PacketChessRogueSelectCellScRsp(cellId)); + } + + #endregion + + #region Dice Management + + public async ValueTask RollDice() + { + DiceInstance.RollDice(); + + await Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); + await Player.SendPacket(new PacketChessRogueRollDiceScRsp(DiceInstance)); + } + + public async ValueTask ReRollDice() + { + DiceInstance.RerollTimes--; + DiceInstance.RollDice(); + + await Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); + await Player.SendPacket(new PacketChessRogueReRollDiceScRsp(DiceInstance)); + } + + public async ValueTask CheatDice(int surfaceId) + { + DiceInstance.CheatTimes--; + DiceInstance.CurSurfaceId = surfaceId; + + await Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); + await Player.SendPacket(new PacketChessRogueCheatRollScRsp(DiceInstance, surfaceId)); + } + + public async ValueTask ConfirmRoll() + { + DiceInstance.DiceStatus = ChessRogueDiceStatus.ChessRogueDiceConfirmed; + + await Player.SendPacket(new PacketChessRogueUpdateDiceInfoScNotify(DiceInstance)); + await Player.SendPacket(new PacketChessRogueConfirmRollScRsp(DiceInstance)); + + //var cellIds = new List(); + + //foreach (var cell in RogueCells) + //{ + // if (cell.Key == CurCell!.GetCellId() || cell.Value.CellStatus == ChessRogueBoardCellStatus.Finish) + // { + // continue; + // } + // cellIds.Add(cell.Key); + //} + + //Player.SendPacket(new PacketChessRogueUpdateAllowedSelectCellScNotify(CurLayerData![-1][0], cellIds)); + } + + #endregion + + #region Action Management + + public async ValueTask CostActionPoint(int cost) + { + ActionPoint -= cost; + + await Player.SendPacket(new PacketChessRogueUpdateActionPointScNotify(ActionPoint)); + } + + public async ValueTask QuitRogue() + { + CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelFinish; + await Player.SendPacket(new PacketChessRogueUpdateLevelBaseInfoScNotify(CurLevelStatus)); + + Player.ChessRogueManager!.RogueInstance = null; + await Player.EnterScene(801120102, 0, false); + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); + + await Player.SendPacket(new PacketChessRogueQuitScRsp(this)); + } + + public async ValueTask LeaveRogue() + { + CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelFinish; + await Player.SendPacket(new PacketChessRogueUpdateLevelBaseInfoScNotify(CurLevelStatus)); + + Player.ChessRogueManager!.RogueInstance = null; + await Player.EnterScene(801120102, 0, false); + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); + + await Player.SendPacket(new PacketChessRogueLeaveScRsp(this)); + } + + #endregion + + #region Serialization + + public ChessRogueCurrentInfo ToProto() + { + var proto = new ChessRogueCurrentInfo + { + GameMiracleInfo = ToMiracleInfo(), + RogueBuffInfo = ToBuffInfo(), + RogueAeonInfo = ToAeonInfo(), + RogueSubMode = (uint)RogueVersionId, + RogueDiceInfo = DiceInstance.ToProto(), + RogueLineupInfo = ToLineupInfo(), + RogueDifficultyInfo = ToDifficultyInfo(), + RogueVirtualItem = ToVirtualItemInfo(), + LevelInfo = ToLevelInfo() + }; + + if (RogueActions.Count > 0) + proto.PendingAction = RogueActions.First().Value.ToProto(); + else + proto.PendingAction = new RogueCommonPendingAction(); + + proto.RogueCurrentGameInfo.AddRange(ToGameInfo()); + + return proto; + } + + public ChessRoguePlayerInfo ToPlayerProto() + { + var playerInfo = new ChessRoguePlayerInfo + { + Lineup = Player.LineupManager!.GetCurLineup()!.ToProto(), + Scene = Player.SceneInstance!.ToProto() + }; + + return playerInfo; + } + + public ChessRogueQueryGameInfo ToRogueGameInfo() + { + var proto = new ChessRogueQueryGameInfo + { + RogueSubMode = (uint)RogueVersionId + }; + + proto.RogueCurrentGameInfo.AddRange(ToGameInfo()); + + return proto; + } + + public ChessRogueMiracleInfo ToMiracleInfo() + { + var proto = new ChessRogueMiracleInfo + { + MiracleInfo = new ChessRogueMiracle() + }; + + proto.MiracleInfo.MiracleList.AddRange(RogueMiracles.Select(x => x.Value.ToGameMiracleProto()).ToList()); + + return proto; + } + + public RogueDLCBuffInfo ToBuffInfo() + { + var proto = new RogueDLCBuffInfo + { + RogueDlcMazeBuffInfo = new RogueMazeBuffInfo() + }; + + proto.RogueDlcMazeBuffInfo.BuffList.AddRange(RogueBuffs.Select(x => x.ToCommonProto()).ToList()); + + return proto; + } + + public ChessRogueAeonInfo ToAeonInfo() + { + var proto = new ChessRogueAeonInfo + { + AeonId = (uint)AeonId + }; + + return proto; + } + + public ChessRogueGameAeonInfo ToGameAeonInfo() + { + var proto = new ChessRogueGameAeonInfo + { + AeonId = (uint)AeonId + }; + + return proto; + } + + public ChessRogueLineupInfo ToLineupInfo() + { + var proto = new ChessRogueLineupInfo + { + ReviveInfo = new IBHFIGDHELO { - var buffList = new List(); - foreach (var buff in BossBuff) + GameItemInfo = new ItemCostData { - if (buff.EffectType == BossDecayEffectTypeEnum.AddMazeBuffList) + ItemList = { - buffList.SafeAddRange(buff.EffectParamList); // add buff - } else - { - foreach (var param in buff.EffectParamList) // remove buff + new ItemCost { - buffList.Remove(param); - } - } - } - - foreach (var buffId in buffList) - { - battle.Buffs.Add(new MazeBuff(buffId, 1, -1) - { - WaveFlag = -1, - }); - } - } - } - - public void CalculateDifficulty(BattleInstance battle) - { - if (DifficultyExcel.Count > 0) - { - List difficultyIds = []; - List buffs = []; - - foreach (var difficulty in DifficultyLevel) - { - difficultyIds.Add(difficulty.DifficultyID); - } - - if (difficultyIds.Contains(103)) - { - buffs.Add(new MazeBuff(610121, 1, -1) - { - WaveFlag = -1 - }); - } - - if (difficultyIds.Contains(105)) - { - buffs.Add(new MazeBuff(610121, 1, -1) - { - WaveFlag = -1 - }); - } - - var attributeBuffId = 0; - - if (difficultyIds.Contains(106)) - { - attributeBuffId = 650204; - } else if (difficultyIds.Contains(104)) - { - attributeBuffId = 650203; - } else if (difficultyIds.Contains(102)) - { - attributeBuffId = 650202; - } else if (difficultyIds.Contains(101)) - { - attributeBuffId = 650201; - } - - buffs.Add(new MazeBuff(attributeBuffId, 1, -1) - { - WaveFlag = -1, - DynamicValues = { { "_RogueLayer", Layers.IndexOf(CurLayer) + 1 } } - }); - - foreach (var buff in buffs) - { - battle.Buffs.Add(buff); - } - } - } - - public override void OnBattleEnd(BattleInstance battle, PVEBattleResultCsReq req) - { - base.OnBattleEnd(battle, req); - - if (req.EndStatus != BattleEndStatus.BattleEndWin) - { - // quit - CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelFailed; - Player.SendPacket(new PacketChessRogueUpdateLevelBaseInfoScNotify(CurLevelStatus)); - return; - } - - RollBuff(battle.Stages.Count); - - if (CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterBoss) - { - Player.SendPacket(new PacketChessRogueLayerAccountInfoNotify(this)); - } - else if (CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterNousBoss || CurCell!.CellType == RogueDLCBlockTypeEnum.MonsterSwarmBoss) - { - CurLevelStatus = ChessRogueLevelStatusType.ChessRogueLevelFinish; - Player.SendPacket(new PacketChessRogueLayerAccountInfoNotify(this)); - Player.SendPacket(new PacketChessRogueUpdateLevelBaseInfoScNotify(CurLevelStatus)); - } - } - - #region Serialization - - public ChessRogueCurrentInfo ToProto() - { - var proto = new ChessRogueCurrentInfo() - { - GameMiracleInfo = ToMiracleInfo(), - RogueBuffInfo = ToBuffInfo(), - RogueAeonInfo = ToAeonInfo(), - RogueSubMode = (uint)RogueVersionId, - RogueDiceInfo = DiceInstance.ToProto(), - RogueLineupInfo = ToLineupInfo(), - RogueDifficultyInfo = ToDifficultyInfo(), - RogueVirtualItem = ToVirtualItemInfo(), - LevelInfo = ToLevelInfo(), - }; - - if (RogueActions.Count > 0) - { - proto.PendingAction = RogueActions.First().Value.ToProto(); - } else - { - proto.PendingAction = new(); - } - - proto.RogueCurrentGameInfo.AddRange(ToGameInfo()); - - return proto; - } - - public ChessRoguePlayerInfo ToPlayerProto() - { - var playerInfo = new ChessRoguePlayerInfo() - { - Lineup = Player.LineupManager!.GetCurLineup()!.ToProto(), - Scene = Player.SceneInstance!.ToProto(), - }; - - return playerInfo; - } - - public ChessRogueQueryGameInfo ToRogueGameInfo() - { - var proto = new ChessRogueQueryGameInfo() - { - RogueSubMode = (uint)RogueVersionId, - }; - - proto.RogueCurrentGameInfo.AddRange(ToGameInfo()); - - return proto; - } - - public ChessRogueMiracleInfo ToMiracleInfo() - { - var proto = new ChessRogueMiracleInfo() - { - MiracleInfo = new() - }; - - proto.MiracleInfo.MiracleList.AddRange(RogueMiracles.Select(x => x.Value.ToGameMiracleProto()).ToList()); - - return proto; - } - - public RogueDLCBuffInfo ToBuffInfo() - { - var proto = new RogueDLCBuffInfo() - { - RogueDlcMazeBuffInfo = new() - }; - - proto.RogueDlcMazeBuffInfo.BuffList.AddRange(RogueBuffs.Select(x => x.ToCommonProto()).ToList()); - - return proto; - } - - public ChessRogueAeonInfo ToAeonInfo() - { - var proto = new ChessRogueAeonInfo() - { - AeonId = (uint)AeonId, - }; - - return proto; - } - - public ChessRogueGameAeonInfo ToGameAeonInfo() - { - var proto = new ChessRogueGameAeonInfo() - { - AeonId = (uint)AeonId, - }; - - return proto; - } - - public ChessRogueLineupInfo ToLineupInfo() - { - var proto = new ChessRogueLineupInfo() - { - ReviveInfo = new() - { - GameItemInfo = new() - { - ItemList = { new ItemCost() - { - PileItem = new() + PileItem = new PileItem { ItemId = 31, ItemNum = (uint)CurReviveCost } - } } - } - }, - }; - - foreach (var avatar in CurLineup!.BaseAvatars!) - { - proto.ChessAvatarList.Add(new ChessRogueLineupAvatarInfo() - { - AvatarId = (uint)avatar.BaseAvatarId, - }); - } - - return proto; - } - - public RogueGameItemInfo ToGameItemInfo() - { - var proto = new RogueGameItemInfo(); - - proto.VirtualItem.Add(31, (uint)CurMoney); - - return proto; - } - - public List ToGameInfo() - { - var proto = new List - { - new() - { - RogueDifficultyInfo = ToDifficultyLevelInfo() - }, - new() - { - RogueAeonInfo = ToGameAeonInfo() - }, - new() - { - - }, - new() - { - GameMiracleInfo = ToMiracleInfo() - }, - new() - { - RogueBuffInfo = ToBuffInfo() - } - }; - - return proto; - } - - public ChessRogueCurrentDifficultyInfo ToDifficultyInfo() - { - var proto = new ChessRogueCurrentDifficultyInfo(); - - foreach (var level in DifficultyLevel) - { - proto.ChessDifficultyId.Add((uint)level.DifficultyID); - } - - return proto; - } - - public RogueDifficultyLevelInfo ToDifficultyLevelInfo() - { - var proto = new RogueDifficultyLevelInfo(); - - foreach (var level in DifficultyLevel) - { - proto.ChessDifficultyId.Add((uint)level.DifficultyID); - } - - return proto; - } - - public RogueVirtualItem ToVirtualItemInfo() - { - return new() - { - RogueMoney = (uint)CurMoney - }; - } - - public ChessRogueLevelInfo ToLevelInfo() - { - List canSelected = []; - foreach (var cell in RogueCells) - { - if (cell.Value.CellStatus == ChessRogueBoardCellStatus.Idle) - { - if (cell.Value.PosY == CurCell!.PosY - 1 || cell.Value.PosY == CurCell!.PosY + 1) - { - if (cell.Value.PosX == CurCell!.PosX || cell.Value.PosX == CurCell!.PosX + 1) - { - canSelected.Add((uint)cell.Value.GetCellId()); - } - } - if (cell.Value.PosY == CurCell!.PosY) - { - if (cell.Value.PosX == CurCell!.PosX + 2) - { - canSelected.Add((uint)cell.Value.GetCellId()); } } } } + }; - var proto = new ChessRogueLevelInfo() + foreach (var avatar in CurLineup!.BaseAvatars!) + proto.ChessAvatarList.Add(new ChessRogueLineupAvatarInfo { - LevelStatus = CurLevelStatus, - ActionPoint = ActionPoint, - Id = (uint)AreaExcel.AreaID, - LayerId = (uint)CurLayer, - AreaInfo = new() - { - LayerStatus = ChessRogueBoardCellStatus.Processing, - CurId = (uint)CurCell!.GetCellId(), - CurBoardId = (uint)(CurBoardExcel?.ChessBoardID ?? 0), - Cell = new() - { - CellList = { RogueCells.Select(x => x.Value.ToProto()).ToList() } - }, - AllowedSelectCellIdList = { canSelected }, - HistoryCell = { HistoryCell.Select(x => x.ToHistoryProto()).ToList() }, - } - }; + AvatarId = (uint)avatar.BaseAvatarId + }); - return proto; - } - - public ChessRogueFinishInfo ToFinishInfo() - { - var info = new ChessRogueFinishInfo() - { - EndAreaId = (uint)AreaExcel.AreaID, - CurLayerId = (uint)CurLayer, - CurLineup = CurLineup!.ToProto(), - AreaDifficultyLevel = uint.Parse(AreaExcel.AreaID.ToString().Substring(AreaExcel.AreaID.ToString().Length - 1, 1)), - RogueSubMode = (uint)RogueVersionId, - RogueBuffInfo = new() - { - BuffList = { RogueBuffs.Select(x => x.ToCommonProto()) } - }, - GameMiracleInfo = new() - { - MiracleList = { RogueMiracles.Select(x => x.Value.ToGameMiracleProto()) } - }, - }; - - return info; - } - - #endregion + return proto; } -} + + public RogueGameItemInfo ToGameItemInfo() + { + var proto = new RogueGameItemInfo(); + + proto.VirtualItem.Add(31, (uint)CurMoney); + + return proto; + } + + public List ToGameInfo() + { + var proto = new List + { + new() + { + RogueDifficultyInfo = ToDifficultyLevelInfo() + }, + new() + { + RogueAeonInfo = ToGameAeonInfo() + }, + new(), + new() + { + GameMiracleInfo = ToMiracleInfo() + }, + new() + { + RogueBuffInfo = ToBuffInfo() + } + }; + + return proto; + } + + public ChessRogueCurrentDifficultyInfo ToDifficultyInfo() + { + var proto = new ChessRogueCurrentDifficultyInfo(); + + foreach (var level in DifficultyLevel) proto.ChessDifficultyId.Add((uint)level.DifficultyID); + + return proto; + } + + public RogueDifficultyLevelInfo ToDifficultyLevelInfo() + { + var proto = new RogueDifficultyLevelInfo(); + + foreach (var level in DifficultyLevel) proto.ChessDifficultyId.Add((uint)level.DifficultyID); + + return proto; + } + + public RogueVirtualItem ToVirtualItemInfo() + { + return new RogueVirtualItem + { + RogueMoney = (uint)CurMoney + }; + } + + public ChessRogueLevelInfo ToLevelInfo() + { + List canSelected = []; + foreach (var cell in RogueCells) + if (cell.Value.CellStatus == ChessRogueBoardCellStatus.Idle) + { + if (cell.Value.PosY == CurCell!.PosY - 1 || cell.Value.PosY == CurCell!.PosY + 1) + if (cell.Value.PosX == CurCell!.PosX || cell.Value.PosX == CurCell!.PosX + 1) + canSelected.Add((uint)cell.Value.GetCellId()); + if (cell.Value.PosY == CurCell!.PosY) + if (cell.Value.PosX == CurCell!.PosX + 2) + canSelected.Add((uint)cell.Value.GetCellId()); + } + + var proto = new ChessRogueLevelInfo + { + LevelStatus = CurLevelStatus, + ActionPoint = ActionPoint, + Id = (uint)AreaExcel.AreaID, + LayerId = (uint)CurLayer, + AreaInfo = new ChessRogueAreaInfo + { + LayerStatus = ChessRogueBoardCellStatus.Processing, + CurId = (uint)CurCell!.GetCellId(), + CurBoardId = (uint)(CurBoardExcel?.ChessBoardID ?? 0), + Cell = new CellInfo + { + CellList = { RogueCells.Select(x => x.Value.ToProto()).ToList() } + }, + AllowedSelectCellIdList = { canSelected }, + HistoryCell = { HistoryCell.Select(x => x.ToHistoryProto()).ToList() } + } + }; + + return proto; + } + + public ChessRogueFinishInfo ToFinishInfo() + { + var info = new ChessRogueFinishInfo + { + EndAreaId = (uint)AreaExcel.AreaID, + CurLayerId = (uint)CurLayer, + CurLineup = CurLineup!.ToProto(), + AreaDifficultyLevel = + uint.Parse(AreaExcel.AreaID.ToString().Substring(AreaExcel.AreaID.ToString().Length - 1, 1)), + RogueSubMode = (uint)RogueVersionId, + RogueBuffInfo = new RogueMazeBuffInfo + { + BuffList = { RogueBuffs.Select(x => x.ToCommonProto()) } + }, + GameMiracleInfo = new ChessRogueMiracle + { + MiracleList = { RogueMiracles.Select(x => x.Value.ToGameMiracleProto()) } + } + }; + + return info; + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/ChessRogue/ChessRogueManager.cs b/GameServer/Game/ChessRogue/ChessRogueManager.cs index 2aa7d80d..4a288ce9 100644 --- a/GameServer/Game/ChessRogue/ChessRogueManager.cs +++ b/GameServer/Game/ChessRogue/ChessRogueManager.cs @@ -6,331 +6,314 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.ChessRogue; using EggLink.DanhengServer.Server.Packet.Send.Lineup; -namespace EggLink.DanhengServer.Game.ChessRogue +namespace EggLink.DanhengServer.Game.ChessRogue; + +public class ChessRogueManager(PlayerInstance player) : BasePlayerManager(player) { - public class ChessRogueManager(PlayerInstance player) : BasePlayerManager(player) + public ChessRogueNousData ChessRogueNousData { get; } = + DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + + public ChessRogueInstance? RogueInstance { get; set; } + + #region Game Management + + public async ValueTask StartRogue(int aeonId, List avatarIds, int areaId, int branchId, + List difficultyIds, List disableAeonIdList) { - public ChessRogueNousData ChessRogueNousData { get; private set; } = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + GameData.RogueNousAeonData.TryGetValue(aeonId, out var aeonData); + GameData.RogueDLCAreaData.TryGetValue(areaId, out var areaData); + if (aeonData == null || areaData == null) return; - public ChessRogueInstance? RogueInstance { get; set; } + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupChessRogue, avatarIds.Select(x => (int)x).ToList()); + await Player.LineupManager!.GainMp(5, false); + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - #region Game Management - - public void StartRogue(int aeonId, List avatarIds, int areaId, int branchId, List difficultyIds, List disableAeonIdList) + foreach (var id in avatarIds) { - GameData.RogueNousAeonData.TryGetValue(aeonId, out var aeonData); - GameData.RogueDLCAreaData.TryGetValue(areaId, out var areaData); - if (aeonData == null || areaData == null) return; - - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupChessRogue, avatarIds.Select(x => (int)x).ToList()); - Player.LineupManager!.GainMp(5, false); - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - - foreach (var id in avatarIds) - { - Player.AvatarManager!.GetAvatar((int)id)?.SetCurHp(10000, true); - Player.AvatarManager!.GetAvatar((int)id)?.SetCurSp(10000, true); - } - - var difficultyLevel = difficultyIds.Select(x => GameData.RogueNousDifficultyLevelData[x]).ToList(); - - var instance = new ChessRogueInstance(Player, areaData, aeonData, areaData.RogueVersionId, branchId) - { - DisableAeonIds = disableAeonIdList, - DifficultyLevel = difficultyLevel, - }; - - RogueInstance = instance; - - instance.EnterCell(instance.StartCell); - - Player.SendPacket(new PacketChessRogueStartScRsp(Player)); + Player.AvatarManager!.GetAvatar((int)id)?.SetCurHp(10000, true); + Player.AvatarManager!.GetAvatar((int)id)?.SetCurSp(10000, true); } - #endregion + var difficultyLevel = difficultyIds.Select(x => GameData.RogueNousDifficultyLevelData[x]).ToList(); - #region Dice Management - - public ChessRogueNousDiceData GetDice(int branchId) + var instance = new ChessRogueInstance(Player, areaData, aeonData, areaData.RogueVersionId, branchId) { - ChessRogueNousData.RogueDiceData.TryGetValue(branchId, out var diceData); + DisableAeonIds = disableAeonIdList, + DifficultyLevel = difficultyLevel + }; - if (diceData == null) // set to default - { - var branch = GameData.RogueNousDiceBranchData[branchId]; - var surface = branch.GetDefaultSurfaceList(); - return SetDice(branchId, surface.Select((id, i) => new { id, i }).ToDictionary(x => x.i + 1, x => x.id)); // convert to dictionary - } + RogueInstance = instance; - return diceData; - } + await instance.EnterCell(instance.StartCell); - public ChessRogueNousDiceData SetDice(int branchId, Dictionary surfaceId) - { - ChessRogueNousData.RogueDiceData.TryGetValue(branchId, out var diceData); - - if (diceData == null) - { - diceData = new ChessRogueNousDiceData() - { - BranchId = branchId, - Surfaces = surfaceId, - }; - - ChessRogueNousData.RogueDiceData[branchId] = diceData; - } - else - { - diceData.Surfaces = surfaceId; - } - - DatabaseHelper.Instance!.UpdateInstance(ChessRogueNousData); - - return diceData; - } - - public ChessRogueNousDiceData SetDice(int branchId, int index, int surfaceId) - { - ChessRogueNousData.RogueDiceData.TryGetValue(branchId, out var diceData); - if (diceData == null) - { - // set to default - var branch = GameData.RogueNousDiceBranchData[branchId]; - var surface = branch.GetDefaultSurfaceList(); - surface[index] = surfaceId; - - return SetDice(branchId, surface.Select((id, i) => new { id, i }).ToDictionary(x => x.i + 1, x => x.id)); // convert to dictionary - } else - { - diceData.Surfaces[index] = surfaceId; - DatabaseHelper.Instance!.UpdateInstance(ChessRogueNousData); - - return diceData; - } - } - - public ChessRogueNousDiceData SetDice(ChessRogueDice dice) - { - var branchId = (int)dice.BranchId; - ChessRogueNousData.RogueDiceData.TryGetValue(branchId, out var diceData); - if (diceData == null) - { - // set to default - var branch = GameData.RogueNousDiceBranchData[branchId]; - var surface = branch.GetDefaultSurfaceList(); - - foreach (var d in dice.SurfaceList) - { - surface[(int)d.Index - 1] = (int)d.SurfaceId; - } - - return SetDice(branchId, surface.Select((id, i) => new { id, i }).ToDictionary(x => x.i + 1, x => x.id)); // convert to dictionary - } - else - { - foreach (var d in dice.SurfaceList) - { - diceData.Surfaces[(int)d.Index] = (int)d.SurfaceId; - } - - DatabaseHelper.Instance!.UpdateInstance(ChessRogueNousData); - - return diceData; - } - } - - #endregion - - #region Serialization - - public ChessRogueGetInfo ToGetInfo() - { - var info = new ChessRogueGetInfo - { - ChessAeonInfo = ToAeonInfo(), - DiceInfo = ToDiceInfo(), - RogueTalentInfo = ToTalentInfo(), - RogueDifficultyInfo = new(), - }; - - foreach (var area in GameData.RogueDLCAreaData.Keys) - { - info.AreaIdList.Add((uint)area); - info.ExploredAreaIdList.Add((uint)area); - } - - foreach (var item in GameData.RogueNousDifficultyLevelData.Keys) - { - info.RogueDifficultyInfo.QueryDifficultyIdList.Add((uint)item); - } - - return info; - } - - public ChessRogueCurrentInfo ToCurrentInfo() - { - if (RogueInstance != null) return RogueInstance.ToProto(); - var info = new ChessRogueCurrentInfo - { - RogueSubMode = 201, - LevelInfo = ToLevelInfo(), - RogueAeonInfo = ToRogueAeonInfo(), - RogueDiceInfo = ToRogueDiceInfo(), - RogueDifficultyInfo = new(), - GameMiracleInfo = new() { MiracleInfo = new() }, // needed for avoiding null reference exception (below 4 lines) - RogueBuffInfo = new() { RogueDlcMazeBuffInfo = new() }, - PendingAction = new(), - RogueLineupInfo = ToLineupInfo(), - RogueVirtualItem = new(), - }; - - return info; - } - - public ChessRogueQueryInfo ToQueryInfo() - { - var info = new ChessRogueQueryInfo - { - ChessAeonInfo = ToAeonInfo(), - RogueTalentInfo = ToTalentInfo(), - RogueDifficultyInfo = new(), - DiceInfo = ToDiceInfo(), - }; - - foreach (var area in GameData.RogueDLCAreaData.Keys) - { - info.AreaIdList.Add((uint)area); - info.ExploredAreaIdList.Add((uint)area); - } - - foreach (var item in GameData.RogueNousDifficultyLevelData.Keys) - { - info.RogueDifficultyInfo.QueryDifficultyIdList.Add((uint)item); - } - - return info; - } - - public ChessRogueLevelInfo ToLevelInfo() - { - var proto = new ChessRogueLevelInfo() - { - AreaInfo = new() - { - Cell = new(), - NFPIJHGAEGM = new(), - } - }; - - foreach (var area in GameData.RogueDLCAreaData.Keys) - { - proto.ExploredAreaIdList.Add((uint)area); - } - - - return proto; - } - - public ChessRogueQueryAeonInfo ToAeonInfo() - { - var proto = new ChessRogueQueryAeonInfo(); - - foreach (var aeon in GameData.RogueNousAeonData.Values) - { - if (aeon.AeonID > 7) continue; - proto.AeonList.Add(new ChessRogueQueryAeon() - { - AeonId = (uint)aeon.AeonID, - }); - } - - return proto; - } - - public ChessRogueAeonInfo ToRogueAeonInfo() - { - var proto = new ChessRogueAeonInfo() - { - ChessAeonInfo = ToAeonInfo(), - }; - - - foreach (var aeon in GameData.RogueNousAeonData.Values) - { - if (aeon.AeonID > 8) continue; - proto.AeonIdList.Add((uint)aeon.AeonID); - } - - return proto; - } - - public ChessRogueQueryDiceInfo ToDiceInfo() - { - var proto = new ChessRogueQueryDiceInfo() - { - DicePhase = ChessRogueNousDicePhase.PhaseTwo, - }; - - foreach (var branch in GameData.RogueNousDiceSurfaceData.Keys) - { - proto.SurfaceIdList.Add((uint)branch); - } - - foreach (var dice in GameData.RogueNousDiceBranchData) - { - proto.DiceList.Add(GetDice(dice.Key).ToProto()); - } - - for (var i = 1; i < 7; i++) - { - proto.GEMMFOEDJJA.Add((uint)i, i % 3 == 0); - } - proto.GEMMFOEDJJA[5] = true; - - return proto; - } - - public ChessRogueDiceInfo ToRogueDiceInfo() - { - var proto = new ChessRogueDiceInfo(); - - return proto; - } - - public ChessRogueTalentInfo ToTalentInfo() - { - var talentInfo = new RogueTalentInfo(); - - foreach (var talent in GameData.RogueNousTalentData.Values) - { - talentInfo.RogueTalentList.Add(new RogueTalent() - { - TalentId = (uint)talent.TalentID, - Status = RogueTalentStatus.Enable - }); - } - - var proto = new ChessRogueTalentInfo() - { - TalentInfo = talentInfo, - }; - - return proto; - } - - public ChessRogueLineupInfo ToLineupInfo() - { - var proto = new ChessRogueLineupInfo() - { - ReviveInfo = new() - { - GameItemInfo = new() - } - }; - - return proto; - } - - #endregion + await Player.SendPacket(new PacketChessRogueStartScRsp(Player)); } -} + + #endregion + + #region Dice Management + + public ChessRogueNousDiceData GetDice(int branchId) + { + ChessRogueNousData.RogueDiceData.TryGetValue(branchId, out var diceData); + + if (diceData == null) // set to default + { + var branch = GameData.RogueNousDiceBranchData[branchId]; + var surface = branch.GetDefaultSurfaceList(); + return SetDice(branchId, + surface.Select((id, i) => new { id, i }) + .ToDictionary(x => x.i + 1, x => x.id)); // convert to dictionary + } + + return diceData; + } + + public ChessRogueNousDiceData SetDice(int branchId, Dictionary surfaceId) + { + ChessRogueNousData.RogueDiceData.TryGetValue(branchId, out var diceData); + + if (diceData == null) + { + diceData = new ChessRogueNousDiceData + { + BranchId = branchId, + Surfaces = surfaceId + }; + + ChessRogueNousData.RogueDiceData[branchId] = diceData; + } + else + { + diceData.Surfaces = surfaceId; + } + + DatabaseHelper.Instance!.UpdateInstance(ChessRogueNousData); + + return diceData; + } + + public ChessRogueNousDiceData SetDice(int branchId, int index, int surfaceId) + { + ChessRogueNousData.RogueDiceData.TryGetValue(branchId, out var diceData); + if (diceData == null) + { + // set to default + var branch = GameData.RogueNousDiceBranchData[branchId]; + var surface = branch.GetDefaultSurfaceList(); + surface[index] = surfaceId; + + return SetDice(branchId, + surface.Select((id, i) => new { id, i }) + .ToDictionary(x => x.i + 1, x => x.id)); // convert to dictionary + } + + diceData.Surfaces[index] = surfaceId; + DatabaseHelper.Instance!.UpdateInstance(ChessRogueNousData); + + return diceData; + } + + public ChessRogueNousDiceData SetDice(ChessRogueDice dice) + { + var branchId = (int)dice.BranchId; + ChessRogueNousData.RogueDiceData.TryGetValue(branchId, out var diceData); + if (diceData == null) + { + // set to default + var branch = GameData.RogueNousDiceBranchData[branchId]; + var surface = branch.GetDefaultSurfaceList(); + + foreach (var d in dice.SurfaceList) surface[(int)d.Index - 1] = (int)d.SurfaceId; + + return SetDice(branchId, + surface.Select((id, i) => new { id, i }) + .ToDictionary(x => x.i + 1, x => x.id)); // convert to dictionary + } + + foreach (var d in dice.SurfaceList) diceData.Surfaces[(int)d.Index] = (int)d.SurfaceId; + + DatabaseHelper.Instance!.UpdateInstance(ChessRogueNousData); + + return diceData; + } + + #endregion + + #region Serialization + + public ChessRogueGetInfo ToGetInfo() + { + var info = new ChessRogueGetInfo + { + ChessAeonInfo = ToAeonInfo(), + DiceInfo = ToDiceInfo(), + RogueTalentInfo = ToTalentInfo(), + RogueDifficultyInfo = new ChessRogueQueryDiffcultyInfo() + }; + + foreach (var area in GameData.RogueDLCAreaData.Keys) + { + info.AreaIdList.Add((uint)area); + info.ExploredAreaIdList.Add((uint)area); + } + + foreach (var item in GameData.RogueNousDifficultyLevelData.Keys) + info.RogueDifficultyInfo.QueryDifficultyIdList.Add((uint)item); + + return info; + } + + public ChessRogueCurrentInfo ToCurrentInfo() + { + if (RogueInstance != null) return RogueInstance.ToProto(); + var info = new ChessRogueCurrentInfo + { + RogueSubMode = 201, + LevelInfo = ToLevelInfo(), + RogueAeonInfo = ToRogueAeonInfo(), + RogueDiceInfo = ToRogueDiceInfo(), + RogueDifficultyInfo = new ChessRogueCurrentDifficultyInfo(), + GameMiracleInfo = new ChessRogueMiracleInfo + { + MiracleInfo = new ChessRogueMiracle() + }, // needed for avoiding null reference exception (below 4 lines) + RogueBuffInfo = new RogueDLCBuffInfo { RogueDlcMazeBuffInfo = new RogueMazeBuffInfo() }, + PendingAction = new RogueCommonPendingAction(), + RogueLineupInfo = ToLineupInfo(), + RogueVirtualItem = new RogueVirtualItem() + }; + + return info; + } + + public ChessRogueQueryInfo ToQueryInfo() + { + var info = new ChessRogueQueryInfo + { + ChessAeonInfo = ToAeonInfo(), + RogueTalentInfo = ToTalentInfo(), + RogueDifficultyInfo = new ChessRogueQueryDiffcultyInfo(), + DiceInfo = ToDiceInfo() + }; + + foreach (var area in GameData.RogueDLCAreaData.Keys) + { + info.AreaIdList.Add((uint)area); + info.ExploredAreaIdList.Add((uint)area); + } + + foreach (var item in GameData.RogueNousDifficultyLevelData.Keys) + info.RogueDifficultyInfo.QueryDifficultyIdList.Add((uint)item); + + return info; + } + + public ChessRogueLevelInfo ToLevelInfo() + { + var proto = new ChessRogueLevelInfo + { + AreaInfo = new ChessRogueAreaInfo + { + Cell = new CellInfo(), + NFPIJHGAEGM = new JJPJGJJGCKJ() + } + }; + + foreach (var area in GameData.RogueDLCAreaData.Keys) proto.ExploredAreaIdList.Add((uint)area); + + + return proto; + } + + public ChessRogueQueryAeonInfo ToAeonInfo() + { + var proto = new ChessRogueQueryAeonInfo(); + + foreach (var aeon in GameData.RogueNousAeonData.Values) + { + if (aeon.AeonID > 7) continue; + proto.AeonList.Add(new ChessRogueQueryAeon + { + AeonId = (uint)aeon.AeonID + }); + } + + return proto; + } + + public ChessRogueAeonInfo ToRogueAeonInfo() + { + var proto = new ChessRogueAeonInfo + { + ChessAeonInfo = ToAeonInfo() + }; + + + foreach (var aeon in GameData.RogueNousAeonData.Values) + { + if (aeon.AeonID > 8) continue; + proto.AeonIdList.Add((uint)aeon.AeonID); + } + + return proto; + } + + public ChessRogueQueryDiceInfo ToDiceInfo() + { + var proto = new ChessRogueQueryDiceInfo + { + DicePhase = ChessRogueNousDicePhase.PhaseTwo + }; + + foreach (var branch in GameData.RogueNousDiceSurfaceData.Keys) proto.SurfaceIdList.Add((uint)branch); + + foreach (var dice in GameData.RogueNousDiceBranchData) proto.DiceList.Add(GetDice(dice.Key).ToProto()); + + for (var i = 1; i < 7; i++) proto.GEMMFOEDJJA.Add((uint)i, i % 3 == 0); + proto.GEMMFOEDJJA[5] = true; + + return proto; + } + + public ChessRogueDiceInfo ToRogueDiceInfo() + { + var proto = new ChessRogueDiceInfo(); + + return proto; + } + + public ChessRogueTalentInfo ToTalentInfo() + { + var talentInfo = new RogueTalentInfo(); + + foreach (var talent in GameData.RogueNousTalentData.Values) + talentInfo.RogueTalentList.Add(new RogueTalent + { + TalentId = (uint)talent.TalentID, + Status = RogueTalentStatus.Enable + }); + + var proto = new ChessRogueTalentInfo + { + TalentInfo = talentInfo + }; + + return proto; + } + + public ChessRogueLineupInfo ToLineupInfo() + { + var proto = new ChessRogueLineupInfo + { + ReviveInfo = new IBHFIGDHELO + { + GameItemInfo = new ItemCostData() + } + }; + + return proto; + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/ChessRogue/Dice/ChessRogueDiceInstance.cs b/GameServer/Game/ChessRogue/Dice/ChessRogueDiceInstance.cs index e15d549c..d2b4c461 100644 --- a/GameServer/Game/ChessRogue/Dice/ChessRogueDiceInstance.cs +++ b/GameServer/Game/ChessRogue/Dice/ChessRogueDiceInstance.cs @@ -1,53 +1,45 @@ -using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database.ChessRogue; +using EggLink.DanhengServer.Database.ChessRogue; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.ChessRogue.Dice +namespace EggLink.DanhengServer.Game.ChessRogue.Dice; + +public class ChessRogueDiceInstance(ChessRogueInstance instance, ChessRogueNousDiceData diceData) { - public class ChessRogueDiceInstance(ChessRogueInstance instance, ChessRogueNousDiceData diceData) + public int CheatTimes = 1; + + public int CurSurfaceId; + public ChessRogueNousDiceData DiceData = diceData; + + public ChessRogueDiceStatus DiceStatus = ChessRogueDiceStatus.ChessRogueDiceIdle; + public ChessRogueInstance Instance = instance; + public int RerollTimes = 1; + + public void RollDice() { - public ChessRogueInstance Instance = instance; - public ChessRogueNousDiceData DiceData = diceData; - - public int CheatTimes = 1; - public int RerollTimes = 1; - - public int CurSurfaceId = 0; - - public ChessRogueDiceStatus DiceStatus = ChessRogueDiceStatus.ChessRogueDiceIdle; - - public void RollDice() - { - CurSurfaceId = DiceData.Surfaces.ToList().RandomElement().Value; - DiceStatus = ChessRogueDiceStatus.ChessRogueDiceRolled; - } - - - public ChessRogueDiceInfo ToProto() - { - var index = DiceData.Surfaces.ToList().FindIndex(x => x.Value == CurSurfaceId) + 1; - return new() - { - BranchId = (uint)DiceData.BranchId, - Dice = DiceData.ToProto(), - DiceStatus = DiceStatus, - CurSurfaceId = (uint)CurSurfaceId, - CheatTimes = (uint)CheatTimes, - RerollTimes = (uint)RerollTimes, - CurBranchId = (uint)DiceData.BranchId, - DiceType = ChessRogueDiceType.ChessRogueDiceEditable, - OPIIBFEJFHD = true, - CurSurfaceIndex = (uint)(index > 0 ? index : 0), - //DisplayId = (uint)(CurSurfaceId > 0 ? GameData.RogueNousDiceSurfaceData[CurSurfaceId].Sort : 0), - CanRerollDice = RerollTimes > 0, - BDMBIDHFKJF = new() { HNHONCDLMEE = { } }, - }; - } + CurSurfaceId = DiceData.Surfaces.ToList().RandomElement().Value; + DiceStatus = ChessRogueDiceStatus.ChessRogueDiceRolled; } -} + + + public ChessRogueDiceInfo ToProto() + { + var index = DiceData.Surfaces.ToList().FindIndex(x => x.Value == CurSurfaceId) + 1; + return new ChessRogueDiceInfo + { + BranchId = (uint)DiceData.BranchId, + Dice = DiceData.ToProto(), + DiceStatus = DiceStatus, + CurSurfaceId = (uint)CurSurfaceId, + CheatTimes = (uint)CheatTimes, + RerollTimes = (uint)RerollTimes, + CurBranchId = (uint)DiceData.BranchId, + DiceType = ChessRogueDiceType.ChessRogueDiceEditable, + OPIIBFEJFHD = true, + CurSurfaceIndex = (uint)(index > 0 ? index : 0), + //DisplayId = (uint)(CurSurfaceId > 0 ? GameData.RogueNousDiceSurfaceData[CurSurfaceId].Sort : 0), + CanRerollDice = RerollTimes > 0, + BDMBIDHFKJF = new KEGPAIEJBGE() + }; + } +} \ No newline at end of file diff --git a/GameServer/Game/Drop/DropService.cs b/GameServer/Game/Drop/DropService.cs index 1f8eb293..83bea18a 100644 --- a/GameServer/Game/Drop/DropService.cs +++ b/GameServer/Game/Drop/DropService.cs @@ -1,32 +1,30 @@ using EggLink.DanhengServer.Database.Inventory; -using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Game.Drop +namespace EggLink.DanhengServer.Game.Drop; + +public class DropService { - public class DropService + public static List CalculateDropsFromProp() { - public static List CalculateDropsFromProp() - { - List drops = - [ - new ItemData() - { - ItemId = 1, - Count = 5 - }, - new ItemData() - { - ItemId = 22, - Count = 5 - }, - new ItemData() - { - ItemId = 2, - Count = new Random().Next(20, 100) - }, - ]; + List drops = + [ + new ItemData + { + ItemId = 1, + Count = 5 + }, + new ItemData + { + ItemId = 22, + Count = 5 + }, + new ItemData + { + ItemId = 2, + Count = new Random().Next(20, 100) + } + ]; - return drops; - } + return drops; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Friend/FriendManager.cs b/GameServer/Game/Friend/FriendManager.cs index 0f891c2f..85557721 100644 --- a/GameServer/Game/Friend/FriendManager.cs +++ b/GameServer/Game/Friend/FriendManager.cs @@ -1,7 +1,5 @@ -using EggLink.DanhengServer.Command; -using EggLink.DanhengServer.Database; +using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Friend; -using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.GameServer.Command; @@ -10,371 +8,318 @@ using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet.Send.Friend; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Friend +namespace EggLink.DanhengServer.Game.Friend; + +public class FriendManager(PlayerInstance player) : BasePlayerManager(player) { - public class FriendManager(PlayerInstance player) : BasePlayerManager(player) + public FriendData FriendData { get; set; } = + DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + + public async ValueTask AddFriend(int targetUid) { - public FriendData FriendData { get; set; } = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + var target = DatabaseHelper.Instance!.GetInstance(targetUid); + if (target == null) return; - public void AddFriend(int targetUid) + if (FriendData.FriendList.Contains(targetUid)) // already friend + return; + + if (FriendData.BlackList.Contains(targetUid)) // in black list + return; + + if (FriendData.SendApplyList.Contains(targetUid)) // already send apply + return; + + if (FriendData.ReceiveApplyList.Contains(targetUid)) // already receive apply + return; + + FriendData.SendApplyList.Add(targetUid); + target.ReceiveApplyList.Add(Player.Uid); + + var targetPlayer = Listener.GetActiveConnection(targetUid); + if (targetPlayer != null) { - var target = DatabaseHelper.Instance!.GetInstance(targetUid); - if (target == null) - { - return; - } - - if (FriendData.FriendList.Contains(targetUid)) // already friend - { - return; - } - - if (FriendData.BlackList.Contains(targetUid)) // in black list - { - return; - } - - if (FriendData.SendApplyList.Contains(targetUid)) // already send apply - { - return; - } - - if (FriendData.ReceiveApplyList.Contains(targetUid)) // already receive apply - { - return; - } - - FriendData.SendApplyList.Add(targetUid); - target.ReceiveApplyList.Add(Player.Uid); - - var targetPlayer = Listener.GetActiveConnection(targetUid); - targetPlayer?.SendPacket(new PacketSyncApplyFriendScNotify(Player.Data)); - targetPlayer?.Player!.FriendManager!.FriendData.ReceiveApplyList.Add(Player.Uid); - DatabaseHelper.ToSaveUidList.Add(targetUid); - - DatabaseHelper.Instance!.UpdateInstance(FriendData); - DatabaseHelper.Instance!.UpdateInstance(target); + await targetPlayer.SendPacket(new PacketSyncApplyFriendScNotify(Player.Data)); + targetPlayer.Player!.FriendManager!.FriendData.ReceiveApplyList.Add(Player.Uid); } - public PlayerData? ConfirmAddFriend(int targetUid) + DatabaseHelper.ToSaveUidList.Add(targetUid); + } + + public async ValueTask ConfirmAddFriend(int targetUid) + { + var target = DatabaseHelper.Instance!.GetInstance(targetUid); + if (target == null) return null; + + if (FriendData.FriendList.Contains(targetUid)) return null; + + if (FriendData.BlackList.Contains(targetUid)) return null; + + if (!FriendData.ReceiveApplyList.Contains(targetUid)) return null; + + FriendData.ReceiveApplyList.Remove(targetUid); + FriendData.FriendList.Add(targetUid); + target.FriendList.Add(Player.Uid); + target.SendApplyList.Remove(Player.Uid); + + DatabaseHelper.Instance!.UpdateInstance(FriendData); + DatabaseHelper.Instance!.UpdateInstance(target); + + var targetData = PlayerData.GetPlayerByUid(targetUid)!; + var targetPlayer = Listener.GetActiveConnection(targetUid); + if (targetPlayer != null) + await targetPlayer.SendPacket(new PacketSyncHandleFriendScNotify((uint)Player.Uid, true, Player.Data)); + + await Player.SendPacket(new PacketSyncHandleFriendScNotify((uint)targetData.Uid, true, targetData)); + + return targetData; + } + + public void RefuseAddFriend(int targetUid) + { + var target = DatabaseHelper.Instance!.GetInstance(targetUid); + if (target == null) return; + + if (!FriendData.ReceiveApplyList.Contains(targetUid)) return; + + FriendData.ReceiveApplyList.Remove(targetUid); + target.SendApplyList.Remove(Player.Uid); + + var targetPlayer = Listener.GetActiveConnection(targetUid); + targetPlayer?.Player!.FriendManager!.FriendData.SendApplyList.Remove(Player.Uid); + DatabaseHelper.ToSaveUidList.Add(targetUid); + } + + public void RemoveFriend() + { + } + + public async ValueTask SendMessage(int sendUid, int recvUid, string? message = null, int? extraId = null) + { + var data = new FriendChatData { - var target = DatabaseHelper.Instance!.GetInstance(targetUid); - if (target == null) - { - return null; - } + SendUid = sendUid, + ReceiveUid = recvUid, + Message = message ?? "", + ExtraId = extraId ?? 0, + SendTime = Extensions.GetUnixSec() + }; - if (FriendData.FriendList.Contains(targetUid)) - { - return null; - } - - if (FriendData.BlackList.Contains(targetUid)) - { - return null; - } - - if (!FriendData.ReceiveApplyList.Contains(targetUid)) - { - return null; - } - - FriendData.ReceiveApplyList.Remove(targetUid); - FriendData.FriendList.Add(targetUid); - target.FriendList.Add(Player.Uid); - target.SendApplyList.Remove(Player.Uid); - - DatabaseHelper.Instance!.UpdateInstance(FriendData); - DatabaseHelper.Instance!.UpdateInstance(target); - - var targetData = PlayerData.GetPlayerByUid(targetUid)!; - var targetPlayer = Listener.GetActiveConnection(targetUid); - targetPlayer?.SendPacket(new PacketSyncHandleFriendScNotify((uint)Player.Uid, true, Player.Data)); - targetPlayer?.Player!.FriendManager!.FriendData.SendApplyList.Remove(Player.Uid); - targetPlayer?.Player!.FriendManager!.FriendData.FriendList.Add(Player.Uid); - - Player.SendPacket(new PacketSyncHandleFriendScNotify((uint)targetData.Uid, true, targetData)); - - return targetData; + if (!FriendData.ChatHistory.TryGetValue(recvUid, out var value)) + { + FriendData.ChatHistory[recvUid] = new FriendChatHistory(); + value = FriendData.ChatHistory[recvUid]; } - public void RefuseAddFriend(int targetUid) + value.MessageList.Add(data); + + PacketRevcMsgScNotify proto; + if (message != null) + proto = new PacketRevcMsgScNotify((uint)recvUid, (uint)sendUid, message); + else + proto = new PacketRevcMsgScNotify((uint)recvUid, (uint)sendUid, (uint)(extraId ?? 0)); + + await Player.SendPacket(proto); + + if (recvUid == ConfigManager.Config.ServerOption.ServerProfile.Uid) + if (message?.StartsWith('/') == true) + { + var cmd = message[1..]; + CommandExecutor.ExecuteCommand(new PlayerCommandSender(Player), cmd); + } + + // receive message + var recvPlayer = Listener.GetActiveConnection(recvUid)?.Player!; + if (recvPlayer != null) { - var target = DatabaseHelper.Instance!.GetInstance(targetUid); - if (target == null) + await recvPlayer.FriendManager!.ReceiveMessage(sendUid, recvUid, message, extraId); + } + else + { + // offline + var friendData = DatabaseHelper.Instance!.GetInstance(recvUid); + if (friendData == null) return; // not exist maybe server profile + if (!friendData.ChatHistory.TryGetValue(sendUid, out var history)) { - return; + friendData.ChatHistory[sendUid] = new FriendChatHistory(); + history = friendData.ChatHistory[sendUid]; } - if (!FriendData.ReceiveApplyList.Contains(targetUid)) - { - return; - } + history.MessageList.Add(data); - FriendData.ReceiveApplyList.Remove(targetUid); - target.SendApplyList.Remove(Player.Uid); + DatabaseHelper.ToSaveUidList.Add(recvUid); + } + } - var targetPlayer = Listener.GetActiveConnection(targetUid); - targetPlayer?.Player!.FriendManager!.FriendData.SendApplyList.Remove(Player.Uid); - DatabaseHelper.ToSaveUidList.Add(targetUid); + public async ValueTask ReceiveMessage(int sendUid, int recvUid, string? message = null, int? extraId = null) + { + var data = new FriendChatData + { + SendUid = sendUid, + ReceiveUid = recvUid, + Message = message ?? "", + ExtraId = extraId ?? 0, + SendTime = Extensions.GetUnixSec() + }; - DatabaseHelper.Instance!.UpdateInstance(FriendData); - DatabaseHelper.Instance!.UpdateInstance(target); + if (!FriendData.ChatHistory.TryGetValue(sendUid, out var value)) + { + FriendData.ChatHistory[sendUid] = new FriendChatHistory(); + value = FriendData.ChatHistory[sendUid]; } - public void RemoveFriend() - { + value.MessageList.Add(data); + PacketRevcMsgScNotify proto; + if (message != null) + proto = new PacketRevcMsgScNotify((uint)recvUid, (uint)sendUid, message); + else + proto = new PacketRevcMsgScNotify((uint)recvUid, (uint)sendUid, (uint)(extraId ?? 0)); + + await Player.SendPacket(proto); + } + + public List GetHistoryInfo(int uid) + { + if (!FriendData.ChatHistory.TryGetValue(uid, out var history)) return []; + + var info = new List(); + + foreach (var chat in history.MessageList) + info.Add(new ChatMessageData + { + Timestamp = (ulong)chat.SendTime, + MessageText = chat.Message, + ExtraId = (uint)chat.ExtraId, + SenderId = (uint)chat.SendUid, + MessageType = chat.ExtraId > 0 ? MsgType.Emoji : MsgType.CustomText + }); + + info.Reverse(); + + return info; + } + + public List GetFriendList() + { + List list = []; + + foreach (var friend in FriendData.FriendList) + { + var player = PlayerData.GetPlayerByUid(friend); + + if (player != null) list.Add(player); } - public void SendMessage(int sendUid, int recvUid, string? message = null, int? extraId = null) + return list; + } + + public List GetBlackList() + { + List list = []; + + foreach (var friend in FriendData.BlackList) { - var data = new FriendChatData() - { - SendUid = sendUid, - ReceiveUid = recvUid, - Message = message ?? "", - ExtraId = extraId ?? 0, - SendTime = Extensions.GetUnixSec(), - }; + var player = PlayerData.GetPlayerByUid(friend); - if (!FriendData.ChatHistory.TryGetValue(recvUid, out FriendChatHistory? value)) - { - FriendData.ChatHistory[recvUid] = new FriendChatHistory(); - value = FriendData.ChatHistory[recvUid]; - } - - value.MessageList.Add(data); - - PacketRevcMsgScNotify proto; - if (message != null) - { - proto = new((uint)recvUid, (uint)sendUid, message); - } else - { - proto = new((uint)recvUid, (uint)sendUid, (uint)(extraId ?? 0)); - } - - Player.SendPacket(proto); - - if (recvUid == ConfigManager.Config.ServerOption.ServerProfile.Uid) - { - if (message?.StartsWith('/') == true) - { - var cmd = message[1..]; - CommandExecutor.ExecuteCommand(new PlayerCommandSender(Player), cmd); - } - } - - // receive message - var recvPlayer = Listener.GetActiveConnection(recvUid)?.Player!; - if (recvPlayer != null) - { - recvPlayer.FriendManager!.ReceiveMessage(sendUid, recvUid, message, extraId); - } else - { - // offline - var friendData = DatabaseHelper.Instance!.GetInstance(recvUid); - if (friendData == null) return; // not exist maybe server profile - if (!friendData.ChatHistory.TryGetValue(sendUid, out FriendChatHistory? history)) - { - friendData.ChatHistory[sendUid] = new FriendChatHistory(); - history = friendData.ChatHistory[sendUid]; - } - history.MessageList.Add(data); - - DatabaseHelper.ToSaveUidList.Add(recvUid); - } + if (player != null) list.Add(player); } - public void ReceiveMessage(int sendUid, int recvUid, string? message = null, int? extraId = null) + return list; + } + + public List GetSendApplyList() + { + List list = []; + + foreach (var friend in FriendData.SendApplyList) { - var data = new FriendChatData() - { - SendUid = sendUid, - ReceiveUid = recvUid, - Message = message ?? "", - ExtraId = extraId ?? 0, - SendTime = Extensions.GetUnixSec(), - }; + var player = PlayerData.GetPlayerByUid(friend); - if (!FriendData.ChatHistory.TryGetValue(sendUid, out FriendChatHistory? value)) - { - FriendData.ChatHistory[sendUid] = new FriendChatHistory(); - value = FriendData.ChatHistory[sendUid]; - } - value.MessageList.Add(data); - - PacketRevcMsgScNotify proto; - if (message != null) - { - proto = new((uint)recvUid, (uint)sendUid, message); - } - else - { - proto = new((uint)recvUid, (uint)sendUid, (uint)(extraId ?? 0)); - } - - Player.SendPacket(proto); + if (player != null) list.Add(player); } - public List GetHistoryInfo(int uid) + return list; + } + + public List GetReceiveApplyList() + { + List list = []; + + foreach (var friend in FriendData.ReceiveApplyList) { - if (!FriendData.ChatHistory.TryGetValue(uid, out FriendChatHistory? history)) - { - return []; - } + var player = PlayerData.GetPlayerByUid(friend); - var info = new List(); - - foreach (var chat in history.MessageList) - { - info.Add(new ChatMessageData() - { - Timestamp = (ulong)chat.SendTime, - MessageText = chat.Message, - ExtraId = (uint)chat.ExtraId, - SenderId = (uint)chat.SendUid, - MessageType = chat.ExtraId > 0 ? MsgType.Emoji : MsgType.CustomText, - }); - } - - info.Reverse(); - - return info; + if (player != null) list.Add(player); } - public List GetFriendList() + return list; + } + + public GetFriendListInfoScRsp ToProto() + { + var proto = new GetFriendListInfoScRsp(); + + var serverProfile = ConfigManager.Config.ServerOption.ServerProfile; + + proto.FriendList.Add(new FriendSimpleInfo { - List list = []; - - foreach (var friend in FriendData.FriendList) + PlayerInfo = new PlayerSimpleInfo { - var player = PlayerData.GetPlayerByUid(friend); + Uid = (uint)serverProfile.Uid, + HeadIcon = (uint)serverProfile.HeadIcon, + IsBanned = false, + Level = (uint)serverProfile.Level, + Nickname = serverProfile.Name, + ChatBubbleId = (uint)serverProfile.ChatBubbleId, + OnlineStatus = FriendOnlineStatus.Online, + Platform = PlatformType.Pc, + Signature = serverProfile.Signature + }, + IsMarked = false, + RemarkName = "" + }); - if (player != null) - { - list.Add(player); - } - } - - return list; - } - - public List GetBlackList() + foreach (var player in GetFriendList()) { - List list = []; - - foreach (var friend in FriendData.BlackList) + var status = Listener.GetActiveConnection(player.Uid) == null + ? FriendOnlineStatus.Offline + : FriendOnlineStatus.Online; + proto.FriendList.Add(new FriendSimpleInfo { - var player = PlayerData.GetPlayerByUid(friend); - - if (player != null) - { - list.Add(player); - } - } - - return list; - } - - public List GetSendApplyList() - { - List list = []; - - foreach (var friend in FriendData.SendApplyList) - { - var player = PlayerData.GetPlayerByUid(friend); - - if (player != null) - { - list.Add(player); - } - } - - return list; - } - - public List GetReceiveApplyList() - { - List list = []; - - foreach (var friend in FriendData.ReceiveApplyList) - { - var player = PlayerData.GetPlayerByUid(friend); - - if (player != null) - { - list.Add(player); - } - } - - return list; - } - - public GetFriendListInfoScRsp ToProto() - { - var proto = new GetFriendListInfoScRsp(); - - var serverProfile = ConfigManager.Config.ServerOption.ServerProfile; - - proto.FriendList.Add(new FriendSimpleInfo() - { - PlayerInfo = new PlayerSimpleInfo() - { - Uid = (uint)serverProfile.Uid, - HeadIcon = (uint)serverProfile.HeadIcon, - IsBanned = false, - Level = (uint)serverProfile.Level, - Nickname = serverProfile.Name, - ChatBubbleId = (uint)serverProfile.ChatBubbleId, - OnlineStatus = FriendOnlineStatus.Online, - Platform = PlatformType.Pc, - Signature = serverProfile.Signature, - }, + PlayerInfo = player.ToSimpleProto(status), IsMarked = false, RemarkName = "" }); - - foreach (var player in GetFriendList()) - { - var status = Listener.GetActiveConnection(player.Uid) == null ? FriendOnlineStatus.Offline : FriendOnlineStatus.Online; - proto.FriendList.Add(new FriendSimpleInfo() - { - PlayerInfo = player.ToSimpleProto(status), - IsMarked = false, - RemarkName = "" - }); - } - - foreach (var player in GetBlackList()) - { - var status = Listener.GetActiveConnection(player.Uid) == null ? FriendOnlineStatus.Offline : FriendOnlineStatus.Online; - proto.BlackList.Add(player.ToSimpleProto(status)); - } - - return proto; } - public GetFriendApplyListInfoScRsp ToApplyListProto() + foreach (var player in GetBlackList()) { - GetFriendApplyListInfoScRsp proto = new(); - - foreach (var player in GetSendApplyList()) - { - proto.SendApplyList.Add((uint)player.Uid); - } - - foreach (var player in GetReceiveApplyList()) - { - var status = Listener.GetActiveConnection(player.Uid) == null ? FriendOnlineStatus.Offline : FriendOnlineStatus.Online; - proto.ReceiveApplyList.Add(new FriendApplyInfo() - { - PlayerInfo = player.ToSimpleProto(status) - }); - } - - return proto; + var status = Listener.GetActiveConnection(player.Uid) == null + ? FriendOnlineStatus.Offline + : FriendOnlineStatus.Online; + proto.BlackList.Add(player.ToSimpleProto(status)); } + + return proto; } -} + + public GetFriendApplyListInfoScRsp ToApplyListProto() + { + GetFriendApplyListInfoScRsp proto = new(); + + foreach (var player in GetSendApplyList()) proto.SendApplyList.Add((uint)player.Uid); + + foreach (var player in GetReceiveApplyList()) + { + var status = Listener.GetActiveConnection(player.Uid) == null + ? FriendOnlineStatus.Offline + : FriendOnlineStatus.Online; + proto.ReceiveApplyList.Add(new FriendApplyInfo + { + PlayerInfo = player.ToSimpleProto(status) + }); + } + + return proto; + } +} \ No newline at end of file diff --git a/GameServer/Game/Gacha/GachaManager.cs b/GameServer/Game/Gacha/GachaManager.cs index b20c0044..e9524156 100644 --- a/GameServer/Game/Gacha/GachaManager.cs +++ b/GameServer/Game/Gacha/GachaManager.cs @@ -2,332 +2,287 @@ using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Gacha; using EggLink.DanhengServer.Database.Inventory; -using EggLink.DanhengServer.Database.Message; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Enums.Item; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System.Numerics; +using GachaInfo = EggLink.DanhengServer.Database.Gacha.GachaInfo; -namespace EggLink.DanhengServer.Game.Gacha +namespace EggLink.DanhengServer.Game.Gacha; + +public class GachaManager(PlayerInstance player) : BasePlayerManager(player) { - public class GachaManager(PlayerInstance player) : BasePlayerManager(player) + public GachaData GachaData { get; } = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + + public List GetPurpleAvatars() { - public GachaData GachaData { get; private set; } = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + var purpleAvatars = new List(); + foreach (var avatar in GameData.AvatarConfigData.Values) + if (avatar.Rarity == RarityEnum.CombatPowerAvatarRarityType4) + purpleAvatars.Add(avatar.AvatarID); + return purpleAvatars; + } - public List GetPurpleAvatars() + public List GetGoldAvatars() + { + return [1003, 1004, 1101, 1107, 1104, 1209, 1211]; + } + + public List GetAllGoldAvatars() + { + var avatars = new List(); + foreach (var avatar in GameData.AvatarConfigData.Values) + if (avatar.Rarity == RarityEnum.CombatPowerAvatarRarityType5) + avatars.Add(avatar.AvatarID); + return avatars; + } + + public List GetBlueWeapons() + { + var purpleWeapons = new List(); + foreach (var weapon in GameData.EquipmentConfigData.Values) + if (weapon.Rarity == RarityEnum.CombatPowerLightconeRarity3) + purpleWeapons.Add(weapon.EquipmentID); + return purpleWeapons; + } + + public List GetPurpleWeapons() + { + var purpleWeapons = new List(); + foreach (var weapon in GameData.EquipmentConfigData.Values) + if (weapon.Rarity == RarityEnum.CombatPowerLightconeRarity4) + purpleWeapons.Add(weapon.EquipmentID); + return purpleWeapons; + } + + public List GetGoldWeapons() + { + return [23000, 23002, 23003, 23004, 23005, 23012, 23013]; + } + + public List GetAllGoldWeapons() + { + var weapons = new List(); + foreach (var weapon in GameData.EquipmentConfigData.Values) + if (weapon.Rarity == RarityEnum.CombatPowerLightconeRarity5) + weapons.Add(weapon.EquipmentID); + return weapons; + } + + public int GetRarity(int itemId) + { + if (GetAllGoldAvatars().Contains(itemId) || GetAllGoldWeapons().Contains(itemId)) return 5; + + if (GetPurpleAvatars().Contains(itemId) || GetPurpleWeapons().Contains(itemId)) return 4; + + if (GetBlueWeapons().Contains(itemId)) return 3; + + return 0; + } + + public int GetType(int itemId) + { + if (GetAllGoldAvatars().Contains(itemId) || GetPurpleAvatars().Contains(itemId)) return 1; + + if (GetAllGoldWeapons().Contains(itemId) || GetPurpleWeapons().Contains(itemId) || + GetBlueWeapons().Contains(itemId)) return 2; + + return 0; + } + + public async ValueTask DoGacha(int bannerId, int times) + { + var banner = GameData.BannersConfig.Banners.Find(x => x.GachaId == bannerId); + if (banner == null) return null; + Player.InventoryManager?.RemoveItem(banner.GachaType.GetCostItemId(), times); + + var items = new List(); + for (var i = 0; i < times; i++) { - var purpleAvatars = new List(); - foreach (var avatar in GameData.AvatarConfigData.Values) + var item = banner.DoGacha(GetGoldAvatars(), GetPurpleAvatars(), GetPurpleWeapons(), GetGoldWeapons(), + GetBlueWeapons(), GachaData); + items.Add(item); + } + + var gachaItems = new List(); + var syncItems = new List(); + // get rarity of item + foreach (var item in items) + { + var dirt = 0; + var star = 0; + var rarity = GetRarity(item); + + GachaData.GachaHistory.Add(new GachaInfo { - if (avatar.Rarity == RarityEnum.CombatPowerAvatarRarityType4) + GachaId = bannerId, + ItemId = item, + Time = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + }); + var gachaItem = new GachaItem(); + if (rarity == 5) + { + var type = GetType(item); + if (type == 1) { - purpleAvatars.Add(avatar.AvatarID); - } - } - return purpleAvatars; - } - - public List GetGoldAvatars() - { - return [1003, 1004, 1101, 1107, 1104, 1209, 1211]; - } - - public List GetAllGoldAvatars() - { - var avatars = new List(); - foreach (var avatar in GameData.AvatarConfigData.Values) - { - if (avatar.Rarity == RarityEnum.CombatPowerAvatarRarityType5) - { - avatars.Add(avatar.AvatarID); - } - } - return avatars; - } - - public List GetBlueWeapons() - { - var purpleWeapons = new List(); - foreach (var weapon in GameData.EquipmentConfigData.Values) - { - if (weapon.Rarity == RarityEnum.CombatPowerLightconeRarity3) - { - purpleWeapons.Add(weapon.EquipmentID); - } - } - return purpleWeapons; - } - - public List GetPurpleWeapons() - { - var purpleWeapons = new List(); - foreach (var weapon in GameData.EquipmentConfigData.Values) - { - if (weapon.Rarity == RarityEnum.CombatPowerLightconeRarity4) - { - purpleWeapons.Add(weapon.EquipmentID); - } - } - return purpleWeapons; - } - - public List GetGoldWeapons() - { - return [23000, 23002, 23003, 23004, 23005, 23012, 23013]; - } - - public List GetAllGoldWeapons() - { - var weapons = new List(); - foreach (var weapon in GameData.EquipmentConfigData.Values) - { - if (weapon.Rarity == RarityEnum.CombatPowerLightconeRarity5) - { - weapons.Add(weapon.EquipmentID); - } - } - return weapons; - } - - public int GetRarity(int itemId) - { - if (GetAllGoldAvatars().Contains(itemId) || GetAllGoldWeapons().Contains(itemId)) - { - return 5; - } - - if (GetPurpleAvatars().Contains(itemId) || GetPurpleWeapons().Contains(itemId)) - { - return 4; - } - - if (GetBlueWeapons().Contains(itemId)) - { - return 3; - } - - return 0; - } - - public int GetType(int itemId) - { - if (GetAllGoldAvatars().Contains(itemId) || GetPurpleAvatars().Contains(itemId)) - { - return 1; - } - - if (GetAllGoldWeapons().Contains(itemId) || GetPurpleWeapons().Contains(itemId) || GetBlueWeapons().Contains(itemId)) - { - return 2; - } - - return 0; - } - - public DoGachaScRsp? DoGacha(int bannerId, int times) - { - var banner = GameData.BannersConfig.Banners.Find(x => x.GachaId == bannerId); - if (banner == null) - { - return null; - } - Player.InventoryManager?.RemoveItem(banner.GachaType.GetCostItemId(), times); - - var items = new List(); - for (int i = 0; i < times; i++) - { - var item = banner.DoGacha(GetGoldAvatars(), GetPurpleAvatars(), GetPurpleWeapons(), GetGoldWeapons(), GetBlueWeapons(), GachaData); - items.Add(item); - } - var gachaItems = new List(); - var syncItems = new List(); - // get rarity of item - foreach (var item in items) - { - var dirt = 0; - var star = 0; - var rarity = GetRarity(item); - - GachaData.GachaHistory.Add(new Database.Gacha.GachaInfo() - { - GachaId = bannerId, - ItemId = item, - Time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), - }); - var gachaItem = new GachaItem(); - if (rarity == 5) - { - var type = GetType(item); - if (type == 1) + var avatar = Player.AvatarManager?.GetAvatar(item); + if (avatar != null) { - var avatar = Player.AvatarManager?.GetAvatar(item); - if (avatar != null) + star += 40; + var rankUpItemId = avatar.Excel?.RankUpItemId; + if (rankUpItemId != null) { - star += 40; - var rankUpItemId = avatar.Excel?.RankUpItemId; - if (rankUpItemId != null) + var rankUpItem = Player.InventoryManager!.GetItem(rankUpItemId.Value); + if (avatar.Rank + rankUpItem?.Count >= 6) { - var rankUpItem = Player.InventoryManager!.GetItem(rankUpItemId.Value); - if (avatar.Rank + rankUpItem?.Count >= 6) + star += 60; + } + else + { + var dupeItem = new ItemList(); + dupeItem.ItemList_.Add(new Item { - star += 60; - } - else - { - var dupeItem = new ItemList(); - dupeItem.ItemList_.Add(new Item() - { - ItemId = (uint)rankUpItemId.Value, - Num = 1, - }); - gachaItem.TransferItemList = dupeItem; - } + ItemId = (uint)rankUpItemId.Value, + Num = 1 + }); + gachaItem.TransferItemList = dupeItem; } } } - else - { - star += 20; - } } - else if (rarity == 4) - { - var type = GetType(item); - if (type == 1) - { - var avatar = Player.AvatarManager?.GetAvatar(item); - if (avatar != null) - { - star += 8; - var rankUpItemId = avatar.Excel?.RankUpItemId; - if (rankUpItemId != null) - { - var rankUpItem = Player.InventoryManager!.GetItem(rankUpItemId.Value); - if (avatar.Rank + rankUpItem?.Count >= 6) - { - star += 12; - } - else - { - var dupeItem = new ItemList(); - dupeItem.ItemList_.Add(new Item() - { - ItemId = (uint)rankUpItemId.Value, - Num = 1, - }); - gachaItem.TransferItemList = dupeItem; - } - } - } - } - else - { - star += 8; - } - } else - { - dirt += 20; - } - - ItemData? i; - if (GameData.ItemConfigData[item].ItemMainType == ItemMainTypeEnum.AvatarCard && Player.AvatarManager!.GetAvatar(item) == null) - { - i = null; - Player.AvatarManager!.AddAvatar(item, isGacha:true); - } - else { - i = Player.InventoryManager?.AddItem(item, 1, false, sync: false, returnRaw: true); + star += 20; } - - if (i != null) - { - syncItems.Add(i); - } - - gachaItem.GachaItem_ = new() - { - ItemId = (uint)item, - Num = 1, - Level = 1, - Rank = 1, - }; - - var tokenItem = new ItemList(); - if (dirt > 0) - { - var it = Player.InventoryManager?.AddItem(251, dirt, false, sync: false, returnRaw: true); - if (it != null) - { - var oldItem = syncItems.Find(x => x.ItemId == 251); - if (oldItem == null) - { - syncItems.Add(it); - } - else - { - oldItem.Count = it.Count; - } - } - tokenItem.ItemList_.Add(new Item() - { - ItemId = 251, - Num = (uint)dirt, - }); - } - - if (star > 0) - { - var it = Player.InventoryManager?.AddItem(252, star, false, sync: false, returnRaw: true); - if (it != null) - { - var oldItem = syncItems.Find(x => x.ItemId == 252); - if (oldItem == null) - { - syncItems.Add(it); - } - else - { - oldItem.Count = it.Count; - } - } - tokenItem.ItemList_.Add(new Item() - { - ItemId = 252, - Num = (uint)star, - }); - } - gachaItem.TokenItem = tokenItem; - - gachaItem.TransferItemList ??= new(); - - gachaItems.Add(gachaItem); } - Player.SendPacket(new PacketPlayerSyncScNotify(syncItems)); - var proto = new DoGachaScRsp() + else if (rarity == 4) { - GachaId = (uint)bannerId, - GachaNum = (uint)times, - }; - proto.GachaItemList.AddRange(gachaItems); + var type = GetType(item); + if (type == 1) + { + var avatar = Player.AvatarManager?.GetAvatar(item); + if (avatar != null) + { + star += 8; + var rankUpItemId = avatar.Excel?.RankUpItemId; + if (rankUpItemId != null) + { + var rankUpItem = Player.InventoryManager!.GetItem(rankUpItemId.Value); + if (avatar.Rank + rankUpItem?.Count >= 6) + { + star += 12; + } + else + { + var dupeItem = new ItemList(); + dupeItem.ItemList_.Add(new Item + { + ItemId = (uint)rankUpItemId.Value, + Num = 1 + }); + gachaItem.TransferItemList = dupeItem; + } + } + } + } + else + { + star += 8; + } + } + else + { + dirt += 20; + } - return proto; + ItemData? i; + if (GameData.ItemConfigData[item].ItemMainType == ItemMainTypeEnum.AvatarCard && + Player.AvatarManager!.GetAvatar(item) == null) + { + i = null; + await Player.AvatarManager!.AddAvatar(item, isGacha: true); + } + + else + { + i = await Player.InventoryManager!.AddItem(item, 1, false, sync: false, returnRaw: true); + } + + if (i != null) syncItems.Add(i); + + gachaItem.GachaItem_ = new Item + { + ItemId = (uint)item, + Num = 1, + Level = 1, + Rank = 1 + }; + + var tokenItem = new ItemList(); + if (dirt > 0) + { + var it = await Player.InventoryManager!.AddItem(251, dirt, false, sync: false, returnRaw: true); + if (it != null) + { + var oldItem = syncItems.Find(x => x.ItemId == 251); + if (oldItem == null) + syncItems.Add(it); + else + oldItem.Count = it.Count; + } + + tokenItem.ItemList_.Add(new Item + { + ItemId = 251, + Num = (uint)dirt + }); + } + + if (star > 0) + { + var it = await Player.InventoryManager!.AddItem(252, star, false, sync: false, returnRaw: true); + if (it != null) + { + var oldItem = syncItems.Find(x => x.ItemId == 252); + if (oldItem == null) + syncItems.Add(it); + else + oldItem.Count = it.Count; + } + + tokenItem.ItemList_.Add(new Item + { + ItemId = 252, + Num = (uint)star + }); + } + + gachaItem.TokenItem = tokenItem; + + gachaItem.TransferItemList ??= new ItemList(); + + gachaItems.Add(gachaItem); } - public GetGachaInfoScRsp ToProto() + await Player.SendPacket(new PacketPlayerSyncScNotify(syncItems)); + var proto = new DoGachaScRsp { - var proto = new GetGachaInfoScRsp() - { - GachaRandom = (uint)Random.Shared.Next(1000, 1999), - }; - foreach (var banner in GameData.BannersConfig.Banners) - { - proto.GachaInfoList.Add(banner.ToInfo(GetGoldAvatars())); - } - return proto; - } + GachaId = (uint)bannerId, + GachaNum = (uint)times + }; + proto.GachaItemList.AddRange(gachaItems); + + return proto; } -} + + public GetGachaInfoScRsp ToProto() + { + var proto = new GetGachaInfoScRsp + { + GachaRandom = (uint)Random.Shared.Next(1000, 1999) + }; + foreach (var banner in GameData.BannersConfig.Banners) proto.GachaInfoList.Add(banner.ToInfo(GetGoldAvatars())); + return proto; + } +} \ No newline at end of file diff --git a/GameServer/Game/Inventory/InventoryManager.cs b/GameServer/Game/Inventory/InventoryManager.cs index e55a483e..cd602509 100644 --- a/GameServer/Game/Inventory/InventoryManager.cs +++ b/GameServer/Game/Inventory/InventoryManager.cs @@ -1,1099 +1,1017 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Database.Avatar; using EggLink.DanhengServer.Database.Inventory; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Enums.Item; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.GameServer.Server.Packet.Send.Others; using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Server.Packet.Send.Avatar; using EggLink.DanhengServer.Server.Packet.Send.Player; using EggLink.DanhengServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Util; -using System.Collections.Generic; -using System.Text.RegularExpressions; -namespace EggLink.DanhengServer.Game.Inventory +namespace EggLink.DanhengServer.Game.Inventory; + +public class InventoryManager(PlayerInstance player) : BasePlayerManager(player) { - public class InventoryManager(PlayerInstance player) : BasePlayerManager(player) + public InventoryData Data = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + + public async ValueTask AddItem(ItemData itemData, bool notify = true) { - public InventoryData Data = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + await PutItem(itemData.ItemId, itemData.Count, + itemData.Rank, itemData.Promotion, + itemData.Level, itemData.Exp, itemData.TotalExp, + itemData.MainAffix, itemData.SubAffixes, + itemData.UniqueId); - public void AddItem(ItemData itemData, bool notify = true) + await Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); + if (notify) await Player.SendPacket(new PacketScenePlaneEventScNotify(itemData)); + } + + public async ValueTask AddItems(List items, bool notify = true) + { + var syncItems = new List(); + foreach (var item in items) { - PutItem(itemData.ItemId, itemData.Count, - itemData.Rank, itemData.Promotion, - itemData.Level, itemData.Exp, itemData.TotalExp, - itemData.MainAffix, itemData.SubAffixes, - itemData.UniqueId); - - Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); - if (notify) - { - Player.SendPacket(new PacketScenePlaneEventScNotify(itemData)); - } - DatabaseHelper.Instance?.UpdateInstance(Data); + var i = await AddItem(item.ItemId, item.Count, false, sync: false, returnRaw: true); + if (i != null) syncItems.Add(i); } - public void AddItems(List items, bool notify = true) + await Player.SendPacket(new PacketPlayerSyncScNotify(syncItems)); + if (notify) await Player.SendPacket(new PacketScenePlaneEventScNotify(items)); + } + + public async ValueTask AddItem(int itemId, int count, bool notify = true, int rank = 1, int level = 1, + bool sync = true, bool returnRaw = false) + { + GameData.ItemConfigData.TryGetValue(itemId, out var itemConfig); + if (itemConfig == null) return null; + + ItemData? itemData = null; + + switch (itemConfig.ItemMainType) { - var syncItems = new List(); - foreach (var item in items) - { - var i = AddItem(item.ItemId, item.Count, false, sync:false, returnRaw:true); - if (i != null) + case ItemMainTypeEnum.Equipment: + if (Data.RelicItems.Count + 1 > GameConstants.INVENTORY_MAX_EQUIPMENT) // get the max equipment { - syncItems.Add(i); - } - } - Player.SendPacket(new PacketPlayerSyncScNotify(syncItems)); - if (notify) - { - Player.SendPacket(new PacketScenePlaneEventScNotify(items)); - } - - DatabaseHelper.Instance?.UpdateInstance(Data); - } - - public ItemData? AddItem(int itemId, int count, bool notify = true, int rank = 1, int level = 1, bool sync = true, bool returnRaw = false) - { - GameData.ItemConfigData.TryGetValue(itemId, out var itemConfig); - if (itemConfig == null) return null; - - ItemData? itemData = null; - - switch (itemConfig.ItemMainType) - { - case ItemMainTypeEnum.Equipment: - if (Data.RelicItems.Count + 1 > GameConstants.INVENTORY_MAX_EQUIPMENT) // get the max equipment - { - Player.SendPacket(new PacketRetcodeNotify(Retcode.RetEquipmentExceedLimit)); - break; - } - itemData = PutItem(itemId, 1, rank: rank, level: level, uniqueId: ++Data.NextUniqueId); + await Player.SendPacket(new PacketRetcodeNotify(Retcode.RetEquipmentExceedLimit)); break; - case ItemMainTypeEnum.Usable: - switch (itemConfig.ItemSubType) - { - case ItemSubTypeEnum.HeadIcon: - Player.PlayerUnlockData!.HeadIcons.Add(itemId); - break; - case ItemSubTypeEnum.ChatBubble: - Player.PlayerUnlockData!.ChatBubbles.Add(itemId); - break; - case ItemSubTypeEnum.PhoneTheme: - Player.PlayerUnlockData!.PhoneThemes.Add(itemId); - break; - case ItemSubTypeEnum.Food: - case ItemSubTypeEnum.Book: - itemData = PutItem(itemId, count); - break; - } - itemData ??= new() + } + + itemData = await PutItem(itemId, 1, rank, level: level, uniqueId: ++Data.NextUniqueId); + break; + case ItemMainTypeEnum.Usable: + switch (itemConfig.ItemSubType) + { + case ItemSubTypeEnum.HeadIcon: + Player.PlayerUnlockData!.HeadIcons.Add(itemId); + break; + case ItemSubTypeEnum.ChatBubble: + Player.PlayerUnlockData!.ChatBubbles.Add(itemId); + break; + case ItemSubTypeEnum.PhoneTheme: + Player.PlayerUnlockData!.PhoneThemes.Add(itemId); + break; + case ItemSubTypeEnum.Food: + case ItemSubTypeEnum.Book: + itemData = await PutItem(itemId, count); + break; + } + + itemData ??= new ItemData + { + ItemId = itemId, + Count = count + }; + break; + case ItemMainTypeEnum.Relic: + if (Data.RelicItems.Count + 1 > + GameConstants + .INVENTORY_MAX_RELIC) // get the max relic, i dont think one player can have more than max count of relic until i see a player get 50000 relic and the client crashed :( + { + await Player.SendPacket(new PacketRetcodeNotify(Retcode.RetRelicExceedLimit)); + break; + } + + var item = await PutItem(itemId, 1, 1, level: 0, uniqueId: ++Data.NextUniqueId); + item.AddRandomRelicMainAffix(); + item.AddRandomRelicSubAffix(3); + Data.RelicItems.Find(x => x.UniqueId == item.UniqueId)!.SubAffixes = item.SubAffixes; + itemData = item; + break; + case ItemMainTypeEnum.Virtual: + var actualCount = 0; + switch (itemConfig.ID) + { + case 1: + Player.Data.Hcoin += count; + actualCount = Player.Data.Hcoin; + break; + case 2: + Player.Data.Scoin += count; + actualCount = Player.Data.Scoin; + break; + case 3: + Player.Data.Mcoin += count; + actualCount = Player.Data.Mcoin; + break; + case 11: + Player.Data.Stamina += count; + actualCount = Player.Data.Stamina; + break; + case 22: + Player.Data.Exp += count; + Player.OnAddExp(); + actualCount = Player.Data.Exp; + break; + case 32: + Player.Data.TalentPoints += count; + // TODO : send VirtualItemPacket instead of PlayerSyncPacket + break; + } + + if (count != 0) + { + await Player.SendPacket(new PacketPlayerSyncScNotify(Player.ToProto())); + itemData = new ItemData { ItemId = itemId, - Count = count, + Count = actualCount }; - break; - case ItemMainTypeEnum.Relic: - if (Data.RelicItems.Count + 1 > GameConstants.INVENTORY_MAX_RELIC) // get the max relic, i dont think one player can have more than max count of relic until i see a player get 50000 relic and the client crashed :( - { - Player.SendPacket(new PacketRetcodeNotify(Retcode.RetRelicExceedLimit)); - break; - } - var item = PutItem(itemId, 1, rank: 1, level: 0, uniqueId: ++Data.NextUniqueId); - item.AddRandomRelicMainAffix(); - item.AddRandomRelicSubAffix(3); - Data.RelicItems.Find(x => x.UniqueId == item.UniqueId)!.SubAffixes = item.SubAffixes; - itemData = item; - break; - case ItemMainTypeEnum.Virtual: - var actualCount = 0; - switch (itemConfig.ID) - { - case 1: - Player.Data.Hcoin += count; - actualCount = Player.Data.Hcoin; - break; - case 2: - Player.Data.Scoin += count; - actualCount = Player.Data.Scoin; - break; - case 3: - Player.Data.Mcoin += count; - actualCount = Player.Data.Mcoin; - break; - case 11: - Player.Data.Stamina += count; - actualCount = Player.Data.Stamina; - break; - case 22: - Player.Data.Exp += count; - Player.OnAddExp(); - actualCount = Player.Data.Exp; - break; - case 32: - Player.Data.TalentPoints += count; - // TODO : send VirtualItemPacket instead of PlayerSyncPacket - break; - } - if (count != 0) - { - Player.SendPacket(new PacketPlayerSyncScNotify(Player.ToProto())); - itemData = new() - { - ItemId = itemId, - Count = actualCount, - }; - } - break; - case ItemMainTypeEnum.AvatarCard: - // add avatar - var avatar = Player.AvatarManager?.GetAvatar(itemId); - if (avatar != null && avatar.Excel != null) - { - var rankUpItem = Player.InventoryManager!.GetItem(avatar.Excel.RankUpItemId); - if ((avatar.Rank + rankUpItem?.Count ?? 0) <= 5) - itemData = PutItem(avatar.Excel.RankUpItemId, 1); - } - else - { - Player.AddAvatar(itemId, sync, notify); - AddItem(itemId + 200000, 1, false); - } - break; - case ItemMainTypeEnum.Mission: - itemData = PutItem(itemId, count); - break; - default: - itemData = PutItem(itemId, Math.Min(count, itemConfig.PileLimit)); - break; - } - - ItemData? clone = null; - if (itemData != null) - { - clone = itemData.Clone(); - if (sync) - Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); - clone.Count = count; - if (notify) - { - Player.SendPacket(new PacketScenePlaneEventScNotify(clone)); } - Player.MissionManager?.HandleFinishType(Enums.MissionFinishTypeEnum.GetItem, itemData); - } - - return returnRaw ? itemData : clone ?? itemData; - } - - public ItemData PutItem(int itemId, int count, int rank = 0, int promotion = 0, int level = 0, int exp = 0, int totalExp = 0, int mainAffix = 0, List? subAffixes = null, int uniqueId = 0) - { - if (promotion == 0 && level > 10) - { - promotion = GameData.GetMinPromotionForLevel(level); - } - var item = new ItemData() - { - ItemId = itemId, - Count = count, - Rank = rank, - Promotion = promotion, - Level = level, - Exp = exp, - TotalExp = totalExp, - MainAffix = mainAffix, - SubAffixes = subAffixes ?? [], - }; - - if (uniqueId > 0) - { - item.UniqueId = uniqueId; - } - - switch (GameData.ItemConfigData[itemId].ItemMainType) - { - case ItemMainTypeEnum.Material: - case ItemMainTypeEnum.Virtual: - case ItemMainTypeEnum.Usable: - case ItemMainTypeEnum.Mission: - var oldItem = Data.MaterialItems.Find(x => x.ItemId == itemId); - if (oldItem != null) - { - oldItem.Count += count; - item = oldItem; - break; - } - Data.MaterialItems.Add(item); - break; - case ItemMainTypeEnum.Equipment: - if (Data.RelicItems.Count + 1 > GameConstants.INVENTORY_MAX_EQUIPMENT) - { - Player.SendPacket(new PacketRetcodeNotify(Retcode.RetEquipmentExceedLimit)); - return item; - } - Data.EquipmentItems.Add(item); - break; - case ItemMainTypeEnum.Relic: - if (Data.RelicItems.Count + 1 > GameConstants.INVENTORY_MAX_RELIC) - { - Player.SendPacket(new PacketRetcodeNotify(Retcode.RetRelicExceedLimit)); - return item; - } - Data.RelicItems.Add(item); - break; - } - - return item; - } - - public List RemoveItems(List<(int itemId, int count, int uniqueId)> items, bool sync = true) - { - List removedItems = new List(); - foreach (var item in items) - { - var removedItem = RemoveItem(item.itemId, item.count, item.uniqueId, sync: false); - if (removedItem != null) + break; + case ItemMainTypeEnum.AvatarCard: + // add avatar + var avatar = Player.AvatarManager?.GetAvatar(itemId); + if (avatar != null && avatar.Excel != null) { - removedItems.Add(removedItem); - } - } - if (sync && removedItems.Count > 0) - { - Player.SendPacket(new PacketPlayerSyncScNotify(removedItems)); - } - DatabaseHelper.Instance?.UpdateInstance(Data); - return removedItems; - } - - public ItemData? RemoveItem(int itemId, int count, int uniqueId = 0, bool sync = true) - { - GameData.ItemConfigData.TryGetValue(itemId, out var itemConfig); - if (itemConfig == null) - { - return null; - } - - ItemData? itemData = null; - - switch (itemConfig.ItemMainType) - { - case ItemMainTypeEnum.Material: - case ItemMainTypeEnum.Mission: - var item = Data.MaterialItems.Find(x => x.ItemId == itemId); - if (item == null) - { - return null; - } - item.Count -= count; - if (item.Count <= 0) - { - Data.MaterialItems.Remove(item); - item.Count = 0; - } - itemData = item; - break; - case ItemMainTypeEnum.Virtual: - switch (itemConfig.ID) - { - case 1: - Player.Data.Hcoin -= count; - itemData = new ItemData { ItemId = itemId, Count = count }; - break; - case 2: - Player.Data.Scoin -= count; - itemData = new ItemData { ItemId = itemId, Count = count }; - break; - case 3: - Player.Data.Mcoin -= count; - itemData = new ItemData { ItemId = itemId, Count = count }; - break; - case 32: - Player.Data.TalentPoints -= count; - itemData = new ItemData { ItemId = itemId, Count = count }; - break; - } - if (sync && itemData != null) - { - Player.SendPacket(new PacketPlayerSyncScNotify(Player.ToProto())); - } - break; - case ItemMainTypeEnum.Equipment: - var equipment = Data.EquipmentItems.Find(x => x.UniqueId == uniqueId); - if (equipment == null) - { - return null; - } - Data.EquipmentItems.Remove(equipment); - equipment.Count = 0; - itemData = equipment; - break; - case ItemMainTypeEnum.Relic: - var relic = Data.RelicItems.Find(x => x.UniqueId == uniqueId); - if (relic == null) - { - return null; - } - Data.RelicItems.Remove(relic); - relic.Count = 0; - itemData = relic; - break; - } - - if (itemData != null && sync) - { - Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); - } - - Player.MissionManager?.HandleFinishType(Enums.MissionFinishTypeEnum.UseItem, new ItemData() - { - ItemId = itemId, - Count = count, - }); - - return itemData; - } - - public ItemData? GetItem(int itemId) - { - GameData.ItemConfigData.TryGetValue(itemId, out var itemConfig); - if (itemConfig == null) return null; - switch (itemConfig.ItemMainType) - { - case ItemMainTypeEnum.Material: - return Data.MaterialItems.Find(x => x.ItemId == itemId); - case ItemMainTypeEnum.Equipment: - return Data.EquipmentItems.Find(x => x.ItemId == itemId); - case ItemMainTypeEnum.Relic: - return Data.RelicItems.Find(x => x.ItemId == itemId); - case ItemMainTypeEnum.Virtual: - switch (itemConfig.ID) - { - case 1: - return new ItemData() - { - ItemId = itemId, - Count = Player.Data.Hcoin, - }; - case 2: - return new ItemData() - { - ItemId = itemId, - Count = Player.Data.Scoin, - }; - case 3: - return new ItemData() - { - ItemId = itemId, - Count = Player.Data.Mcoin, - }; - case 11: - return new ItemData() - { - ItemId = itemId, - Count = Player.Data.Stamina, - }; - case 22: - return new ItemData() - { - ItemId = itemId, - Count = Player.Data.Exp, - }; - case 32: - return new ItemData() - { - ItemId = itemId, - Count = Player.Data.TalentPoints, - }; - } - break; - } - return null; - } - - public void HandlePlaneEvent(int eventId) - { - GameData.PlaneEventData.TryGetValue(eventId * 10 + Player.Data.WorldLevel, out var planeEvent); - if (planeEvent == null) return; - GameData.RewardDataData.TryGetValue(planeEvent.Reward, out var rewardData); - rewardData?.GetItems().ForEach(x => AddItem(x.Item1, x.Item2)); - - foreach (var id in planeEvent.DropList) - { - GameData.RewardDataData.TryGetValue(id, out var reward); - reward?.GetItems().ForEach(x => AddItem(x.Item1, x.Item2)); - } - } - - public List HandleMappingInfo(int mappingId, int worldLevel) - { - // calculate drops - List items = []; - GameData.MappingInfoData.TryGetValue(mappingId * 10 + worldLevel, out var mapping); - if (mapping != null) - { - foreach (var item in mapping.DropItemList) - { - var random = Random.Shared.Next(0, 101); - - if (random <= item.Chance) - { - var amount = item.ItemNum > 0 ? item.ItemNum : Random.Shared.Next(item.MinCount, item.MaxCount + 1); - - GameData.ItemConfigData.TryGetValue(item.ItemID, out var itemData); - if (itemData == null) continue; - - items.Add(new ItemData() - { - ItemId = item.ItemID, - Count = amount, - }); - } - } - - // randomize the order of the relics - var relics = mapping.DropRelicItemList.OrderBy(x => Random.Shared.Next()).ToList(); - - var relic5Count = Random.Shared.Next(worldLevel - 4, worldLevel - 2); - var relic4Count = worldLevel - 2; - foreach (var relic in relics) - { - var random = Random.Shared.Next(0, 101); - - if (random <= relic.Chance) - { - var amount = relic.ItemNum > 0 ? relic.ItemNum : Random.Shared.Next(relic.MinCount, relic.MaxCount + 1); - - GameData.ItemConfigData.TryGetValue(relic.ItemID, out var itemData); - if (itemData == null) continue; - - if (itemData.Rarity == ItemRarityEnum.SuperRare && relic5Count > 0) - { - relic5Count--; - } - else if (itemData.Rarity == ItemRarityEnum.VeryRare && relic4Count > 0) - { - relic4Count--; - } - else - { - continue; - } - - items.Add(new ItemData() - { - ItemId = relic.ItemID, - Count = 1, - }); - } - } - - foreach (var item in items) - { - var i = Player.InventoryManager!.AddItem(item.ItemId, item.Count, false)!; - i.Count = item.Count; // return the all thing - } - - DatabaseHelper.Instance!.UpdateInstance(Player.InventoryManager!.Data); - } - - return items; - } - - public ItemData? ComposeItem(int composeId, int count) - { - GameData.ItemComposeConfigData.TryGetValue(composeId, out var composeConfig); - if (composeConfig == null) return null; - foreach (var cost in composeConfig.MaterialCost) - { - RemoveItem(cost.ItemID, cost.ItemNum * count); - } - - RemoveItem(2, composeConfig.CoinCost * count); - - return AddItem(composeConfig.ItemID, count, false); - } - - public List SellItem(ItemCostData costData) - { - List items = new List(); - Dictionary itemMap = new Dictionary(); - List<(int itemId, int count, int uniqueId)> removeItems = new List<(int itemId, int count, int uniqueId)>(); - - foreach (var cost in costData.ItemList) - { - if (cost.EquipmentUniqueId != 0) // equipment - { - var itemData = Data.EquipmentItems.Find(x => x.UniqueId == cost.EquipmentUniqueId); - if (itemData == null) continue; - removeItems.Add((itemData.ItemId, 1, (int)cost.EquipmentUniqueId)); - GameData.ItemConfigData.TryGetValue(itemData.ItemId, out var itemConfig); - if (itemConfig == null) continue; - foreach (var returnItem in itemConfig.ReturnItemIDList) // return items - { - if (!itemMap.ContainsKey(returnItem.ItemID)) - { - itemMap[returnItem.ItemID] = 0; - } - itemMap[returnItem.ItemID] += returnItem.ItemNum; - } - } - else if (cost.RelicUniqueId != 0) // relic - { - var itemData = Data.RelicItems.Find(x => x.UniqueId == cost.RelicUniqueId); - if (itemData == null) continue; - removeItems.Add((itemData.ItemId, 1, (int)cost.RelicUniqueId)); - GameData.ItemConfigData.TryGetValue(itemData.ItemId, out var itemConfig); - if (itemConfig == null) continue; - foreach (var returnItem in itemConfig.ReturnItemIDList) // return items - { - if (!itemMap.ContainsKey(returnItem.ItemID)) - { - itemMap[returnItem.ItemID] = 0; - } - itemMap[returnItem.ItemID] += returnItem.ItemNum; - } + var rankUpItem = Player.InventoryManager!.GetItem(avatar.Excel.RankUpItemId); + if ((avatar.Rank + rankUpItem?.Count ?? 0) <= 5) + itemData = await PutItem(avatar.Excel.RankUpItemId, 1); } else { - removeItems.Add(((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum, 0)); + await Player.AddAvatar(itemId, sync, notify); + await AddItem(itemId + 200000, 1, false); } - } - var removedItems = RemoveItems(removeItems); - - foreach (var itemInfo in itemMap) - { - var item = AddItem(itemInfo.Key, itemInfo.Value, false); - if (item != null) - { - items.Add(item); - } - } - - return items; + break; + case ItemMainTypeEnum.Mission: + itemData = await PutItem(itemId, count); + break; + default: + itemData = await PutItem(itemId, Math.Min(count, itemConfig.PileLimit)); + break; } - #region Equip - - public void EquipAvatar(int baseAvatarId, int equipmentUniqueId) + ItemData? clone = null; + if (itemData != null) { - var itemData = Data.EquipmentItems.Find(x => x.UniqueId == equipmentUniqueId); - var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); - if (itemData == null || avatarData == null) return; - var oldItem = Data.EquipmentItems.Find(x => x.UniqueId == avatarData.EquipId); - if (itemData.EquipAvatar > 0) // already be dressed - { - var equipAvatar = Player.AvatarManager.GetAvatar(itemData.EquipAvatar); - if (equipAvatar != null && oldItem != null) - { - // switch - equipAvatar.EquipId = oldItem.UniqueId; - oldItem.EquipAvatar = equipAvatar.GetAvatarId(); - Player.SendPacket(new PacketPlayerSyncScNotify(equipAvatar, oldItem)); - } - } else - { + clone = itemData.Clone(); + if (sync) + await Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); + clone.Count = count; + if (notify) await Player.SendPacket(new PacketScenePlaneEventScNotify(clone)); + + Player.MissionManager?.HandleFinishType(MissionFinishTypeEnum.GetItem, itemData); + } + + return returnRaw ? itemData : clone ?? itemData; + } + + public async ValueTask PutItem(int itemId, int count, int rank = 0, int promotion = 0, int level = 0, + int exp = 0, int totalExp = 0, int mainAffix = 0, List? subAffixes = null, int uniqueId = 0) + { + if (promotion == 0 && level > 10) promotion = GameData.GetMinPromotionForLevel(level); + var item = new ItemData + { + ItemId = itemId, + Count = count, + Rank = rank, + Promotion = promotion, + Level = level, + Exp = exp, + TotalExp = totalExp, + MainAffix = mainAffix, + SubAffixes = subAffixes ?? [] + }; + + if (uniqueId > 0) item.UniqueId = uniqueId; + + switch (GameData.ItemConfigData[itemId].ItemMainType) + { + case ItemMainTypeEnum.Material: + case ItemMainTypeEnum.Virtual: + case ItemMainTypeEnum.Usable: + case ItemMainTypeEnum.Mission: + var oldItem = Data.MaterialItems.Find(x => x.ItemId == itemId); if (oldItem != null) { - oldItem.EquipAvatar = 0; - Player.SendPacket(new PacketPlayerSyncScNotify(oldItem)); + oldItem.Count += count; + item = oldItem; + break; + } + + Data.MaterialItems.Add(item); + break; + case ItemMainTypeEnum.Equipment: + if (Data.RelicItems.Count + 1 > GameConstants.INVENTORY_MAX_EQUIPMENT) + { + await Player.SendPacket(new PacketRetcodeNotify(Retcode.RetEquipmentExceedLimit)); + return item; + } + + Data.EquipmentItems.Add(item); + break; + case ItemMainTypeEnum.Relic: + if (Data.RelicItems.Count + 1 > GameConstants.INVENTORY_MAX_RELIC) + { + await Player.SendPacket(new PacketRetcodeNotify(Retcode.RetRelicExceedLimit)); + return item; + } + + Data.RelicItems.Add(item); + break; + } + + return item; + } + + public async ValueTask> RemoveItems(List<(int itemId, int count, int uniqueId)> items, + bool sync = true) + { + List removedItems = []; + foreach (var item in items) + { + var removedItem = await RemoveItem(item.itemId, item.count, item.uniqueId, false); + if (removedItem != null) removedItems.Add(removedItem); + } + + if (sync && removedItems.Count > 0) await Player.SendPacket(new PacketPlayerSyncScNotify(removedItems)); + DatabaseHelper.Instance?.UpdateInstance(Data); + return removedItems; + } + + public async ValueTask RemoveItem(int itemId, int count, int uniqueId = 0, bool sync = true) + { + GameData.ItemConfigData.TryGetValue(itemId, out var itemConfig); + if (itemConfig == null) return null; + + ItemData? itemData = null; + + switch (itemConfig.ItemMainType) + { + case ItemMainTypeEnum.Material: + case ItemMainTypeEnum.Mission: + var item = Data.MaterialItems.Find(x => x.ItemId == itemId); + if (item == null) return null; + item.Count -= count; + if (item.Count <= 0) + { + Data.MaterialItems.Remove(item); + item.Count = 0; + } + + itemData = item; + break; + case ItemMainTypeEnum.Virtual: + switch (itemConfig.ID) + { + case 1: + Player.Data.Hcoin -= count; + itemData = new ItemData { ItemId = itemId, Count = count }; + break; + case 2: + Player.Data.Scoin -= count; + itemData = new ItemData { ItemId = itemId, Count = count }; + break; + case 3: + Player.Data.Mcoin -= count; + itemData = new ItemData { ItemId = itemId, Count = count }; + break; + case 32: + Player.Data.TalentPoints -= count; + itemData = new ItemData { ItemId = itemId, Count = count }; + break; + } + + if (sync && itemData != null) await Player.SendPacket(new PacketPlayerSyncScNotify(Player.ToProto())); + break; + case ItemMainTypeEnum.Equipment: + var equipment = Data.EquipmentItems.Find(x => x.UniqueId == uniqueId); + if (equipment == null) return null; + Data.EquipmentItems.Remove(equipment); + equipment.Count = 0; + itemData = equipment; + break; + case ItemMainTypeEnum.Relic: + var relic = Data.RelicItems.Find(x => x.UniqueId == uniqueId); + if (relic == null) return null; + Data.RelicItems.Remove(relic); + relic.Count = 0; + itemData = relic; + break; + } + + if (itemData != null && sync) await Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); + + Player.MissionManager?.HandleFinishType(MissionFinishTypeEnum.UseItem, new ItemData + { + ItemId = itemId, + Count = count + }); + + return itemData; + } + + public ItemData? GetItem(int itemId) + { + GameData.ItemConfigData.TryGetValue(itemId, out var itemConfig); + if (itemConfig == null) return null; + switch (itemConfig.ItemMainType) + { + case ItemMainTypeEnum.Material: + return Data.MaterialItems.Find(x => x.ItemId == itemId); + case ItemMainTypeEnum.Equipment: + return Data.EquipmentItems.Find(x => x.ItemId == itemId); + case ItemMainTypeEnum.Relic: + return Data.RelicItems.Find(x => x.ItemId == itemId); + case ItemMainTypeEnum.Virtual: + switch (itemConfig.ID) + { + case 1: + return new ItemData + { + ItemId = itemId, + Count = Player.Data.Hcoin + }; + case 2: + return new ItemData + { + ItemId = itemId, + Count = Player.Data.Scoin + }; + case 3: + return new ItemData + { + ItemId = itemId, + Count = Player.Data.Mcoin + }; + case 11: + return new ItemData + { + ItemId = itemId, + Count = Player.Data.Stamina + }; + case 22: + return new ItemData + { + ItemId = itemId, + Count = Player.Data.Exp + }; + case 32: + return new ItemData + { + ItemId = itemId, + Count = Player.Data.TalentPoints + }; + } + + break; + } + + return null; + } + + public void HandlePlaneEvent(int eventId) + { + GameData.PlaneEventData.TryGetValue(eventId * 10 + Player.Data.WorldLevel, out var planeEvent); + if (planeEvent == null) return; + GameData.RewardDataData.TryGetValue(planeEvent.Reward, out var rewardData); + rewardData?.GetItems().ForEach(async x => await AddItem(x.Item1, x.Item2)); + + foreach (var id in planeEvent.DropList) + { + GameData.RewardDataData.TryGetValue(id, out var reward); + reward?.GetItems().ForEach(async x => await AddItem(x.Item1, x.Item2)); + } + } + + public async ValueTask> HandleMappingInfo(int mappingId, int worldLevel) + { + // calculate drops + List items = []; + GameData.MappingInfoData.TryGetValue(mappingId * 10 + worldLevel, out var mapping); + if (mapping != null) + { + foreach (var item in mapping.DropItemList) + { + var random = Random.Shared.Next(0, 101); + + if (random <= item.Chance) + { + var amount = item.ItemNum > 0 ? item.ItemNum : Random.Shared.Next(item.MinCount, item.MaxCount + 1); + + GameData.ItemConfigData.TryGetValue(item.ItemID, out var itemData); + if (itemData == null) continue; + + items.Add(new ItemData + { + ItemId = item.ItemID, + Count = amount + }); } } - itemData.EquipAvatar = avatarData.GetAvatarId(); - avatarData.EquipId = itemData.UniqueId; - Player.SendPacket(new PacketPlayerSyncScNotify(avatarData, itemData)); - } - public void EquipRelic(int baseAvatarId, int relicUniqueId, int slot) - { - var itemData = Data.RelicItems.Find(x => x.UniqueId == relicUniqueId); - var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); - if (itemData == null || avatarData == null) return; - avatarData.Relic.TryGetValue(slot, out int id); - var oldItem = Data.RelicItems.Find(x => x.UniqueId == id); + // randomize the order of the relics + var relics = mapping.DropRelicItemList.OrderBy(x => Random.Shared.Next()).ToList(); - if (itemData.EquipAvatar > 0) // already be dressed + var relic5Count = Random.Shared.Next(worldLevel - 4, worldLevel - 2); + var relic4Count = worldLevel - 2; + foreach (var relic in relics) { - var equipAvatar = Player.AvatarManager!.GetAvatar(itemData.EquipAvatar); - if (equipAvatar != null && oldItem != null) + var random = Random.Shared.Next(0, 101); + + if (random <= relic.Chance) { - // switch - equipAvatar.Relic[slot] = oldItem.UniqueId; - oldItem.EquipAvatar = equipAvatar.GetAvatarId(); - Player.SendPacket(new PacketPlayerSyncScNotify(equipAvatar, oldItem)); - } - } else - { - if (oldItem != null) - { - oldItem.EquipAvatar = 0; - Player.SendPacket(new PacketPlayerSyncScNotify(oldItem)); + var amount = relic.ItemNum > 0 + ? relic.ItemNum + : Random.Shared.Next(relic.MinCount, relic.MaxCount + 1); + + GameData.ItemConfigData.TryGetValue(relic.ItemID, out var itemData); + if (itemData == null) continue; + + if (itemData.Rarity == ItemRarityEnum.SuperRare && relic5Count > 0) + relic5Count--; + else if (itemData.Rarity == ItemRarityEnum.VeryRare && relic4Count > 0) + relic4Count--; + else + continue; + + items.Add(new ItemData + { + ItemId = relic.ItemID, + Count = 1 + }); } } - itemData.EquipAvatar = avatarData.GetAvatarId(); - avatarData.Relic[slot] = itemData.UniqueId; - // save - DatabaseHelper.Instance!.UpdateInstance(Data); - DatabaseHelper.Instance!.UpdateInstance(Player.AvatarManager.AvatarData!); - Player.SendPacket(new PacketPlayerSyncScNotify(avatarData, itemData)); + + foreach (var item in items) + { + var i = (await Player.InventoryManager!.AddItem(item.ItemId, item.Count, false))!; + i.Count = item.Count; // return the all thing + } + + DatabaseHelper.Instance!.UpdateInstance(Player.InventoryManager!.Data); } - public void UnequipRelic(int baseAvatarId, int slot) + return items; + } + + public async ValueTask ComposeItem(int composeId, int count) + { + GameData.ItemComposeConfigData.TryGetValue(composeId, out var composeConfig); + if (composeConfig == null) return null; + foreach (var cost in composeConfig.MaterialCost) await RemoveItem(cost.ItemID, cost.ItemNum * count); + + await RemoveItem(2, composeConfig.CoinCost * count); + + return await AddItem(composeConfig.ItemID, count, false); + } + + public async ValueTask> SellItem(ItemCostData costData) + { + List items = []; + Dictionary itemMap = []; + List<(int itemId, int count, int uniqueId)> removeItems = []; + + foreach (var cost in costData.ItemList) + if (cost.EquipmentUniqueId != 0) // equipment + { + var itemData = Data.EquipmentItems.Find(x => x.UniqueId == cost.EquipmentUniqueId); + if (itemData == null) continue; + removeItems.Add((itemData.ItemId, 1, (int)cost.EquipmentUniqueId)); + GameData.ItemConfigData.TryGetValue(itemData.ItemId, out var itemConfig); + if (itemConfig == null) continue; + foreach (var returnItem in itemConfig.ReturnItemIDList) // return items + { + if (!itemMap.ContainsKey(returnItem.ItemID)) itemMap[returnItem.ItemID] = 0; + itemMap[returnItem.ItemID] += returnItem.ItemNum; + } + } + else if (cost.RelicUniqueId != 0) // relic + { + var itemData = Data.RelicItems.Find(x => x.UniqueId == cost.RelicUniqueId); + if (itemData == null) continue; + removeItems.Add((itemData.ItemId, 1, (int)cost.RelicUniqueId)); + GameData.ItemConfigData.TryGetValue(itemData.ItemId, out var itemConfig); + if (itemConfig == null) continue; + foreach (var returnItem in itemConfig.ReturnItemIDList) // return items + { + if (!itemMap.ContainsKey(returnItem.ItemID)) itemMap[returnItem.ItemID] = 0; + itemMap[returnItem.ItemID] += returnItem.ItemNum; + } + } + else + { + removeItems.Add(((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum, 0)); + } + + var removedItems = RemoveItems(removeItems); + + foreach (var itemInfo in itemMap) { - var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); - if (avatarData == null) return; - avatarData.Relic.TryGetValue(slot, out var uniqueId); - var itemData = Data.RelicItems.Find(x => x.UniqueId == uniqueId); - if (itemData == null) return; - avatarData.Relic.Remove(slot); - itemData.EquipAvatar = 0; - Player.SendPacket(new PacketPlayerSyncScNotify(avatarData, itemData)); + var item = await AddItem(itemInfo.Key, itemInfo.Value, false); + if (item != null) items.Add(item); } - public void UnequipEquipment(int baseAvatarId) + return items; + } + + #region Equip + + public async ValueTask EquipAvatar(int baseAvatarId, int equipmentUniqueId) + { + var itemData = Data.EquipmentItems.Find(x => x.UniqueId == equipmentUniqueId); + var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); + if (itemData == null || avatarData == null) return; + var oldItem = Data.EquipmentItems.Find(x => x.UniqueId == avatarData.EquipId); + if (itemData.EquipAvatar > 0) // already be dressed { - var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); - if (avatarData == null) return; - var itemData = Data.EquipmentItems.Find(x => x.UniqueId == avatarData.EquipId); - if (itemData == null) return; - itemData.EquipAvatar = 0; - avatarData.EquipId = 0; - Player.SendPacket(new PacketPlayerSyncScNotify(avatarData, itemData)); + var equipAvatar = Player.AvatarManager.GetAvatar(itemData.EquipAvatar); + if (equipAvatar != null && oldItem != null) + { + // switch + equipAvatar.EquipId = oldItem.UniqueId; + oldItem.EquipAvatar = equipAvatar.GetAvatarId(); + await Player.SendPacket(new PacketPlayerSyncScNotify(equipAvatar, oldItem)); + } + } + else + { + if (oldItem != null) + { + oldItem.EquipAvatar = 0; + await Player.SendPacket(new PacketPlayerSyncScNotify(oldItem)); + } } - public List LevelUpAvatar(int baseAvatarId, ItemCostData item) - { - var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); - if (avatarData == null) return []; - GameData.AvatarPromotionConfigData.TryGetValue(avatarData.AvatarId * 10 + avatarData.Promotion, out var promotionConfig); - if (promotionConfig == null) return []; - var exp = 0; + itemData.EquipAvatar = avatarData.GetAvatarId(); + avatarData.EquipId = itemData.UniqueId; + await Player.SendPacket(new PacketPlayerSyncScNotify(avatarData, itemData)); + } - foreach (var cost in item.ItemList) + public async ValueTask EquipRelic(int baseAvatarId, int relicUniqueId, int slot) + { + var itemData = Data.RelicItems.Find(x => x.UniqueId == relicUniqueId); + var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); + if (itemData == null || avatarData == null) return; + avatarData.Relic.TryGetValue(slot, out var id); + var oldItem = Data.RelicItems.Find(x => x.UniqueId == id); + + if (itemData.EquipAvatar > 0) // already be dressed + { + var equipAvatar = Player.AvatarManager!.GetAvatar(itemData.EquipAvatar); + if (equipAvatar != null && oldItem != null) + { + // switch + equipAvatar.Relic[slot] = oldItem.UniqueId; + oldItem.EquipAvatar = equipAvatar.GetAvatarId(); + await Player.SendPacket(new PacketPlayerSyncScNotify(equipAvatar, oldItem)); + } + } + else + { + if (oldItem != null) + { + oldItem.EquipAvatar = 0; + await Player.SendPacket(new PacketPlayerSyncScNotify(oldItem)); + } + } + + itemData.EquipAvatar = avatarData.GetAvatarId(); + avatarData.Relic[slot] = itemData.UniqueId; + // save + await Player.SendPacket(new PacketPlayerSyncScNotify(avatarData, itemData)); + } + + public async ValueTask UnequipRelic(int baseAvatarId, int slot) + { + var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); + if (avatarData == null) return; + avatarData.Relic.TryGetValue(slot, out var uniqueId); + var itemData = Data.RelicItems.Find(x => x.UniqueId == uniqueId); + if (itemData == null) return; + avatarData.Relic.Remove(slot); + itemData.EquipAvatar = 0; + await Player.SendPacket(new PacketPlayerSyncScNotify(avatarData, itemData)); + } + + public async ValueTask UnequipEquipment(int baseAvatarId) + { + var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); + if (avatarData == null) return; + var itemData = Data.EquipmentItems.Find(x => x.UniqueId == avatarData.EquipId); + if (itemData == null) return; + itemData.EquipAvatar = 0; + avatarData.EquipId = 0; + await Player.SendPacket(new PacketPlayerSyncScNotify(avatarData, itemData)); + } + + public async ValueTask> LevelUpAvatar(int baseAvatarId, ItemCostData item) + { + var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); + if (avatarData == null) return []; + GameData.AvatarPromotionConfigData.TryGetValue(avatarData.AvatarId * 10 + avatarData.Promotion, + out var promotionConfig); + if (promotionConfig == null) return []; + var exp = 0; + + foreach (var cost in item.ItemList) + { + GameData.ItemConfigData.TryGetValue((int)cost.PileItem.ItemId, out var itemConfig); + if (itemConfig == null) continue; + exp += itemConfig.Exp * (int)cost.PileItem.ItemNum; + } + + // payment + var costScoin = exp / 10; + if (Player.Data.Scoin < costScoin) return []; + foreach (var cost in item.ItemList) await RemoveItem((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum); + await RemoveItem(2, costScoin); + + var maxLevel = promotionConfig.MaxLevel; + var curExp = avatarData.Exp; + var curLevel = avatarData.Level; + var nextLevelExp = GameData.GetAvatarExpRequired(avatarData.Excel!.ExpGroup, avatarData.Level); + do + { + int toGain; + if (curExp + exp >= nextLevelExp) + toGain = nextLevelExp - curExp; + else + toGain = exp; + curExp += toGain; + exp -= toGain; + // level up + if (curExp >= nextLevelExp) + { + curExp = 0; + curLevel++; + nextLevelExp = GameData.GetAvatarExpRequired(avatarData.Excel!.ExpGroup, curLevel); + } + } while (exp > 0 && nextLevelExp > 0 && curLevel < maxLevel); + + avatarData.Level = curLevel; + avatarData.Exp = curExp; + DatabaseHelper.Instance!.UpdateInstance(Player.AvatarManager.AvatarData!); + // leftover + Dictionary list = []; + var leftover = exp; + while (leftover > 0) + { + var gain = false; + foreach (var expItem in GameData.EquipmentExpItemConfigData.Values.Reverse()) + if (leftover >= expItem.ExpProvide) + { + // add + await PutItem(expItem.ItemID, 1); + if (list.TryGetValue(expItem.ItemID, out var i)) + { + i.Count++; + } + else + { + i = new ItemData + { + ItemId = expItem.ItemID, + Count = 1 + }; + list[expItem.ItemID] = i; + } + + leftover -= expItem.ExpProvide; + gain = true; + break; + } + + if (!gain) break; // no more item + } + + if (list.Count > 0) await Player.SendPacket(new PacketPlayerSyncScNotify(list.Values.ToList())); + await Player.SendPacket(new PacketPlayerSyncScNotify(avatarData)); + return [.. list.Values]; + } + + #endregion + + #region Levelup + + public async ValueTask> LevelUpEquipment(int equipmentUniqueId, ItemCostData item) + { + var itemData = Data.EquipmentItems.Find(x => x.UniqueId == equipmentUniqueId); + if (itemData == null) return []; + GameData.EquipmentPromotionConfigData.TryGetValue(itemData.ItemId * 10 + itemData.Promotion, + out var equipmentPromotionConfig); + GameData.EquipmentConfigData.TryGetValue(itemData.ItemId, out var equipmentConfig); + if (equipmentConfig == null || equipmentPromotionConfig == null) return []; + var exp = 0; + + foreach (var cost in item.ItemList) + if (cost.PileItem == null) + { + // TODO : add equipment + exp += 100; + } + else { GameData.ItemConfigData.TryGetValue((int)cost.PileItem.ItemId, out var itemConfig); if (itemConfig == null) continue; exp += itemConfig.Exp * (int)cost.PileItem.ItemNum; } - // payment - int costScoin = exp / 10; - if (Player.Data.Scoin < costScoin) return []; - foreach (var cost in item.ItemList) - { - RemoveItem((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum); - } - RemoveItem(2, costScoin); - - int maxLevel = promotionConfig.MaxLevel; - int curExp = avatarData.Exp; - int curLevel = avatarData.Level; - int nextLevelExp = GameData.GetAvatarExpRequired(avatarData.Excel!.ExpGroup, avatarData.Level); - do - { - int toGain; - if (curExp + exp >= nextLevelExp) - { - toGain = nextLevelExp - curExp; - } else - { - toGain = exp; - } - curExp += toGain; - exp -= toGain; - // level up - if (curExp >= nextLevelExp) - { - curExp = 0; - curLevel++; - nextLevelExp = GameData.GetAvatarExpRequired(avatarData.Excel!.ExpGroup, curLevel); - } - } while (exp > 0 && nextLevelExp > 0 && curLevel < maxLevel); - - avatarData.Level = curLevel; - avatarData.Exp = curExp; - DatabaseHelper.Instance!.UpdateInstance(Player.AvatarManager.AvatarData!); - // leftover - Dictionary list = []; - var leftover = exp; - while (leftover > 0) - { - var gain = false; - foreach (var expItem in GameData.EquipmentExpItemConfigData.Values.Reverse()) - { - if (leftover >= expItem.ExpProvide) - { - // add - PutItem(expItem.ItemID, 1); - if (list.TryGetValue(expItem.ItemID, out var i)) - { - i.Count++; - } - else - { - i = new ItemData() - { - ItemId = expItem.ItemID, - Count = 1 - }; - list[expItem.ItemID] = i; - } - leftover -= expItem.ExpProvide; - gain = true; - break; - } - } - if (!gain) - { - break; // no more item - } - } - - if (list.Count > 0) - { - Player.SendPacket(new PacketPlayerSyncScNotify(list.Values.ToList())); - } - Player.SendPacket(new PacketPlayerSyncScNotify(avatarData)); - return [.. list.Values]; - } - - #endregion - - #region Levelup - - public List LevelUpEquipment(int equipmentUniqueId, ItemCostData item) - { - var itemData = Data.EquipmentItems.Find(x => x.UniqueId == equipmentUniqueId); - if (itemData == null) return []; - GameData.EquipmentPromotionConfigData.TryGetValue(itemData.ItemId * 10 + itemData.Promotion, out var equipmentPromotionConfig); - GameData.EquipmentConfigData.TryGetValue(itemData.ItemId, out var equipmentConfig); - if (equipmentConfig == null || equipmentPromotionConfig == null) return []; - var exp = 0; - - foreach (var cost in item.ItemList) - { - if (cost.PileItem == null) - { - // TODO : add equipment - exp += 100; - } else - { - GameData.ItemConfigData.TryGetValue((int)cost.PileItem.ItemId, out var itemConfig); - if (itemConfig == null) continue; - exp += itemConfig.Exp * (int)cost.PileItem.ItemNum; - } - } - - // payment - int costScoin = exp / 2; - if (Player.Data.Scoin < costScoin) return []; - foreach (var cost in item.ItemList) - { - if (cost.PileItem == null) - { - // TODO : add equipment - var costItem = Data.EquipmentItems.Find(x => x.UniqueId == cost.EquipmentUniqueId); - if (costItem == null) continue; - RemoveItem(costItem.ItemId, 1, (int)cost.EquipmentUniqueId); - } else - { - RemoveItem((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum); - } - } - RemoveItem(2, costScoin); - - int maxLevel = equipmentPromotionConfig.MaxLevel; - int curExp = itemData.Exp; - int curLevel = itemData.Level; - int nextLevelExp = GameData.GetEquipmentExpRequired(equipmentConfig.ExpType, itemData.Level); - do - { - int toGain; - if (curExp + exp >= nextLevelExp) - { - toGain = nextLevelExp - curExp; - } else - { - toGain = exp; - } - curExp += toGain; - exp -= toGain; - // level up - if (curExp >= nextLevelExp) - { - curExp = 0; - curLevel++; - nextLevelExp = GameData.GetEquipmentExpRequired(equipmentConfig.ExpType, curLevel); - } - } while (exp > 0 && nextLevelExp > 0 && curLevel < maxLevel); - - itemData.Level = curLevel; - itemData.Exp = curExp; - DatabaseHelper.Instance!.UpdateInstance(Data); - // leftover - Dictionary list = []; - var leftover = exp; - while (leftover > 0) - { - var gain = false; - foreach (var expItem in GameData.EquipmentExpItemConfigData.Values.Reverse()) - { - if (leftover >= expItem.ExpProvide) - { - // add - PutItem(expItem.ItemID, 1); - if (list.TryGetValue(expItem.ItemID, out var i)) - { - i.Count++; - } - else - { - i = new ItemData() - { - ItemId = expItem.ItemID, - Count = 1 - }; - list[expItem.ItemID] = i; - } - leftover -= expItem.ExpProvide; - gain = true; - break; - } - } - if (!gain) - { - break; // no more item - } - } - - if (list.Count > 0) - { - Player.SendPacket(new PacketPlayerSyncScNotify(list.Values.ToList())); - } - Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); - return [.. list.Values]; - } - - public Boolean promoteAvatar(int avatarId) { - // Get avatar - AvatarInfo avatarData = Player.AvatarManager!.GetAvatar(avatarId)!; - if (avatarData == null || avatarData.Excel == null || avatarData.Promotion >= avatarData.Excel.MaxPromotion) return false; - - // Get promotion data - Data.Excel.AvatarPromotionConfigExcel promotion = GameData.AvatarPromotionConfigData.Values.FirstOrDefault(x => x.AvatarID == avatarId && x.Promotion == avatarData.Promotion)!; - - // Sanity check - if ((promotion == null) || avatarData.Level < promotion.MaxLevel || Player.Data.Level < promotion.PlayerLevelRequire || Player.Data.WorldLevel < promotion.WorldLevelRequire) { - return false; - } - - // Pay items - foreach (var cost in promotion.PromotionCostList) { - Player.InventoryManager!.RemoveItem(cost.ItemID, cost.ItemNum); - } - - // Promote - avatarData.Promotion = avatarData.Promotion + 1; - - // Send packets - Player.SendPacket(new PacketPlayerSyncScNotify(avatarData)); - return true; - } - - public bool PromoteEquipment(int equipmentUniqueId) - { - var equipmentData = Player.InventoryManager!.Data.EquipmentItems.FirstOrDefault(x => x.UniqueId == equipmentUniqueId); - if (equipmentData == null || equipmentData.Promotion >= GameData.EquipmentConfigData[equipmentData.ItemId].MaxPromotion) return false; - - var promotionConfig = GameData.EquipmentPromotionConfigData.Values - .FirstOrDefault(x => x.EquipmentID == equipmentData.ItemId && x.Promotion == equipmentData.Promotion); - - if (promotionConfig == null || equipmentData.Level < promotionConfig.MaxLevel || Player.Data.WorldLevel < promotionConfig.WorldLevelRequire) - { - return false; - } - - foreach (var cost in promotionConfig.PromotionCostList) - { - Player.InventoryManager!.RemoveItem(cost.ItemID, cost.ItemNum); - } - - equipmentData.Promotion++; - DatabaseHelper.Instance!.UpdateInstance(Player.InventoryManager.Data); - Player.SendPacket(new PacketPlayerSyncScNotify(equipmentData)); - - return true; - } - - public List LevelUpRelic(int uniqueId, ItemCostData costData) - { - var relicItem = Data.RelicItems.Find(x => x.UniqueId == uniqueId); - if (relicItem == null) return []; - - var exp = 0; - var money = 0; - foreach (var cost in costData.ItemList) - { - if (cost.PileItem != null) - { - GameData.RelicExpItemData.TryGetValue((int)cost.PileItem.ItemId, out var excel); - if (excel != null) - { - exp += excel.ExpProvide * (int)cost.PileItem.ItemNum; - money += excel.CoinCost * (int)cost.PileItem.ItemNum; - } - - RemoveItem((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum); - } else if (cost.RelicUniqueId != 0) - { - var costItem = Data.RelicItems.Find(x => x.UniqueId == cost.RelicUniqueId); - if (costItem != null) - { - GameData.RelicConfigData.TryGetValue(costItem.ItemId, out var costExcel); - if (costExcel == null) continue; - - if (costItem.Level > 0) - { - foreach (var level in Enumerable.Range(0, costItem.Level)) - { - GameData.RelicExpTypeData.TryGetValue(costExcel.ExpType * 100 + level, out var typeExcel); - if (typeExcel != null) - exp += typeExcel.Exp; - } - } else - { - exp += costExcel.ExpProvide; - } - exp += costItem.Exp; - money += costExcel.CoinCost; - - RemoveItem(costItem.ItemId, 1, (int)cost.RelicUniqueId); - } - } - } - - // credit - RemoveItem(2, money); - - // level up - GameData.RelicConfigData.TryGetValue(relicItem.ItemId, out var relicExcel); - if (relicExcel == null) return []; - - GameData.RelicExpTypeData.TryGetValue(relicExcel.ExpType * 100 + relicItem.Level, out var relicType); - do - { - if (relicType == null) break; - int toGain; - if (relicItem.Exp + exp >= relicType.Exp) - { - toGain = relicType.Exp - relicItem.Exp; - } - else - { - toGain = exp; - } - relicItem.Exp += toGain; - exp -= toGain; - - // level up - if (relicItem.Exp >= relicType.Exp) - { - relicItem.Exp = 0; - relicItem.Level++; - GameData.RelicExpTypeData.TryGetValue(relicExcel.ExpType * 100 + relicItem.Level, out relicType); - // relic attribute - if (relicItem.Level % 3 == 0) - { - if (relicItem.SubAffixes.Count >= 4) - { - relicItem.IncreaseRandomRelicSubAffix(); - } - else - { - relicItem.AddRandomRelicSubAffix(); - } - } - } - } while (exp > 0 && relicType?.Exp > 0 && relicItem.Level < relicExcel.MaxLevel); - - // leftover - Dictionary list = []; - var leftover = exp; - while (leftover > 0) - { - var gain = false; - foreach (var expItem in GameData.RelicExpItemData.Values.Reverse()) - { - if (leftover >= expItem.ExpProvide) - { - // add - PutItem(expItem.ItemID, 1); - if (list.TryGetValue(expItem.ItemID, out var i)) - { - i.Count++; - } else - { - i = new ItemData() - { - ItemId = expItem.ItemID, - Count = 1 - }; - list[expItem.ItemID] = i; - } - leftover -= expItem.ExpProvide; - gain = true; - break; - } - } - if (!gain) - { - break; // no more item - } - } - - if (list.Count > 0) - { - Player.SendPacket(new PacketPlayerSyncScNotify(list.Values.ToList())); - } - - // sync - Player.SendPacket(new PacketPlayerSyncScNotify(relicItem)); - - return [.. list.Values]; - } - - public void RankUpAvatar(int baseAvatarId, ItemCostData costData) - { - foreach (var cost in costData.ItemList) - { - RemoveItem((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum); - } - var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); - if (avatarData == null) return; - avatarData.Rank++; - DatabaseHelper.Instance!.UpdateInstance(Player.AvatarManager.AvatarData!); - Player.SendPacket(new PacketPlayerSyncScNotify(avatarData)); - } - - public void RankUpEquipment(int equipmentUniqueId, ItemCostData costData) - { - var rank = 0; - foreach (var cost in costData.ItemList) + // payment + var costScoin = exp / 2; + if (Player.Data.Scoin < costScoin) return []; + foreach (var cost in item.ItemList) + if (cost.PileItem == null) { + // TODO : add equipment var costItem = Data.EquipmentItems.Find(x => x.UniqueId == cost.EquipmentUniqueId); if (costItem == null) continue; - RemoveItem(costItem.ItemId, 0, (int)cost.EquipmentUniqueId); - rank++; + await RemoveItem(costItem.ItemId, 1, (int)cost.EquipmentUniqueId); } - var itemData = Data.EquipmentItems.Find(x => x.UniqueId == equipmentUniqueId); - if (itemData == null) return; - itemData.Rank += rank; - DatabaseHelper.Instance!.UpdateInstance(Data); - Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); + else + { + await RemoveItem((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum); + } + + await RemoveItem(2, costScoin); + + var maxLevel = equipmentPromotionConfig.MaxLevel; + var curExp = itemData.Exp; + var curLevel = itemData.Level; + var nextLevelExp = GameData.GetEquipmentExpRequired(equipmentConfig.ExpType, itemData.Level); + do + { + int toGain; + if (curExp + exp >= nextLevelExp) + toGain = nextLevelExp - curExp; + else + toGain = exp; + curExp += toGain; + exp -= toGain; + // level up + if (curExp >= nextLevelExp) + { + curExp = 0; + curLevel++; + nextLevelExp = GameData.GetEquipmentExpRequired(equipmentConfig.ExpType, curLevel); + } + } while (exp > 0 && nextLevelExp > 0 && curLevel < maxLevel); + + itemData.Level = curLevel; + itemData.Exp = curExp; + DatabaseHelper.Instance!.UpdateInstance(Data); + // leftover + Dictionary list = []; + var leftover = exp; + while (leftover > 0) + { + var gain = false; + foreach (var expItem in GameData.EquipmentExpItemConfigData.Values.Reverse()) + if (leftover >= expItem.ExpProvide) + { + // add + await PutItem(expItem.ItemID, 1); + if (list.TryGetValue(expItem.ItemID, out var i)) + { + i.Count++; + } + else + { + i = new ItemData + { + ItemId = expItem.ItemID, + Count = 1 + }; + list[expItem.ItemID] = i; + } + + leftover -= expItem.ExpProvide; + gain = true; + break; + } + + if (!gain) break; // no more item } - #endregion + if (list.Count > 0) await Player.SendPacket(new PacketPlayerSyncScNotify(list.Values.ToList())); + await Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); + return [.. list.Values]; } -} + + public async ValueTask PromoteAvatar(int avatarId) + { + // Get avatar + var avatarData = Player.AvatarManager!.GetAvatar(avatarId)!; + if (avatarData == null || avatarData.Excel == null || + avatarData.Promotion >= avatarData.Excel.MaxPromotion) return false; + + // Get promotion data + var promotion = + GameData.AvatarPromotionConfigData.Values.FirstOrDefault(x => + x.AvatarID == avatarId && x.Promotion == avatarData.Promotion)!; + + // Sanity check + if (promotion == null || avatarData.Level < promotion.MaxLevel || + Player.Data.Level < promotion.PlayerLevelRequire || + Player.Data.WorldLevel < promotion.WorldLevelRequire) return false; + + // Pay items + foreach (var cost in promotion.PromotionCostList) + await Player.InventoryManager!.RemoveItem(cost.ItemID, cost.ItemNum); + + // Promote + avatarData.Promotion = avatarData.Promotion + 1; + + // Send packets + await Player.SendPacket(new PacketPlayerSyncScNotify(avatarData)); + return true; + } + + public async ValueTask PromoteEquipment(int equipmentUniqueId) + { + var equipmentData = + Player.InventoryManager!.Data.EquipmentItems.FirstOrDefault(x => x.UniqueId == equipmentUniqueId); + if (equipmentData == null || + equipmentData.Promotion >= GameData.EquipmentConfigData[equipmentData.ItemId].MaxPromotion) return false; + + var promotionConfig = GameData.EquipmentPromotionConfigData.Values + .FirstOrDefault(x => x.EquipmentID == equipmentData.ItemId && x.Promotion == equipmentData.Promotion); + + if (promotionConfig == null || equipmentData.Level < promotionConfig.MaxLevel || + Player.Data.WorldLevel < promotionConfig.WorldLevelRequire) return false; + + foreach (var cost in promotionConfig.PromotionCostList) + await Player.InventoryManager!.RemoveItem(cost.ItemID, cost.ItemNum); + + equipmentData.Promotion++; + DatabaseHelper.Instance!.UpdateInstance(Player.InventoryManager.Data); + await Player.SendPacket(new PacketPlayerSyncScNotify(equipmentData)); + + return true; + } + + public async ValueTask> LevelUpRelic(int uniqueId, ItemCostData costData) + { + var relicItem = Data.RelicItems.Find(x => x.UniqueId == uniqueId); + if (relicItem == null) return []; + + var exp = 0; + var money = 0; + foreach (var cost in costData.ItemList) + if (cost.PileItem != null) + { + GameData.RelicExpItemData.TryGetValue((int)cost.PileItem.ItemId, out var excel); + if (excel != null) + { + exp += excel.ExpProvide * (int)cost.PileItem.ItemNum; + money += excel.CoinCost * (int)cost.PileItem.ItemNum; + } + + await RemoveItem((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum); + } + else if (cost.RelicUniqueId != 0) + { + var costItem = Data.RelicItems.Find(x => x.UniqueId == cost.RelicUniqueId); + if (costItem != null) + { + GameData.RelicConfigData.TryGetValue(costItem.ItemId, out var costExcel); + if (costExcel == null) continue; + + if (costItem.Level > 0) + foreach (var level in Enumerable.Range(0, costItem.Level)) + { + GameData.RelicExpTypeData.TryGetValue(costExcel.ExpType * 100 + level, out var typeExcel); + if (typeExcel != null) + exp += typeExcel.Exp; + } + else + exp += costExcel.ExpProvide; + + exp += costItem.Exp; + money += costExcel.CoinCost; + + await RemoveItem(costItem.ItemId, 1, (int)cost.RelicUniqueId); + } + } + + // credit + await RemoveItem(2, money); + + // level up + GameData.RelicConfigData.TryGetValue(relicItem.ItemId, out var relicExcel); + if (relicExcel == null) return []; + + GameData.RelicExpTypeData.TryGetValue(relicExcel.ExpType * 100 + relicItem.Level, out var relicType); + do + { + if (relicType == null) break; + int toGain; + if (relicItem.Exp + exp >= relicType.Exp) + toGain = relicType.Exp - relicItem.Exp; + else + toGain = exp; + relicItem.Exp += toGain; + exp -= toGain; + + // level up + if (relicItem.Exp >= relicType.Exp) + { + relicItem.Exp = 0; + relicItem.Level++; + GameData.RelicExpTypeData.TryGetValue(relicExcel.ExpType * 100 + relicItem.Level, out relicType); + // relic attribute + if (relicItem.Level % 3 == 0) + { + if (relicItem.SubAffixes.Count >= 4) + relicItem.IncreaseRandomRelicSubAffix(); + else + relicItem.AddRandomRelicSubAffix(); + } + } + } while (exp > 0 && relicType?.Exp > 0 && relicItem.Level < relicExcel.MaxLevel); + + // leftover + Dictionary list = []; + var leftover = exp; + while (leftover > 0) + { + var gain = false; + foreach (var expItem in GameData.RelicExpItemData.Values.Reverse()) + if (leftover >= expItem.ExpProvide) + { + // add + await PutItem(expItem.ItemID, 1); + if (list.TryGetValue(expItem.ItemID, out var i)) + { + i.Count++; + } + else + { + i = new ItemData + { + ItemId = expItem.ItemID, + Count = 1 + }; + list[expItem.ItemID] = i; + } + + leftover -= expItem.ExpProvide; + gain = true; + break; + } + + if (!gain) break; // no more item + } + + if (list.Count > 0) await Player.SendPacket(new PacketPlayerSyncScNotify(list.Values.ToList())); + + // sync + await Player.SendPacket(new PacketPlayerSyncScNotify(relicItem)); + + return [.. list.Values]; + } + + public async ValueTask RankUpAvatar(int baseAvatarId, ItemCostData costData) + { + foreach (var cost in costData.ItemList) await RemoveItem((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum); + var avatarData = Player.AvatarManager!.GetAvatar(baseAvatarId); + if (avatarData == null) return; + avatarData.Rank++; + DatabaseHelper.Instance!.UpdateInstance(Player.AvatarManager.AvatarData!); + await Player.SendPacket(new PacketPlayerSyncScNotify(avatarData)); + } + + public async ValueTask RankUpEquipment(int equipmentUniqueId, ItemCostData costData) + { + var rank = 0; + foreach (var cost in costData.ItemList) + { + var costItem = Data.EquipmentItems.Find(x => x.UniqueId == cost.EquipmentUniqueId); + if (costItem == null) continue; + await RemoveItem(costItem.ItemId, 0, (int)cost.EquipmentUniqueId); + rank++; + } + + var itemData = Data.EquipmentItems.Find(x => x.UniqueId == equipmentUniqueId); + if (itemData == null) return; + itemData.Rank += rank; + DatabaseHelper.Instance!.UpdateInstance(Data); + await Player.SendPacket(new PacketPlayerSyncScNotify(itemData)); + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Lineup/LineupManager.cs b/GameServer/Game/Lineup/LineupManager.cs index b1cc08f2..3288ca46 100644 --- a/GameServer/Game/Lineup/LineupManager.cs +++ b/GameServer/Game/Lineup/LineupManager.cs @@ -1,5 +1,6 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Database; +using EggLink.DanhengServer.Database.Avatar; using EggLink.DanhengServer.Database.Lineup; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Scene; @@ -8,444 +9,357 @@ using EggLink.DanhengServer.Server.Packet.Send.Lineup; using EggLink.DanhengServer.Util; using LineupInfo = EggLink.DanhengServer.Database.Lineup.LineupInfo; -namespace EggLink.DanhengServer.Game.Lineup +namespace EggLink.DanhengServer.Game.Lineup; + +public class LineupManager : BasePlayerManager { - public class LineupManager : BasePlayerManager + public LineupManager(PlayerInstance player) : base(player) { - public LineupData LineupData { get; private set; } - - public LineupManager(PlayerInstance player) : base(player) + LineupData = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + foreach (var lineupInfo in LineupData.Lineups.Values) { - LineupData = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); - foreach (var lineupInfo in LineupData.Lineups.Values) + lineupInfo.LineupData = LineupData; + lineupInfo.AvatarData = player.AvatarManager!.AvatarData; + } + } + + public LineupData LineupData { get; } + + #region Detail + + public LineupInfo? GetLineup(int lineupIndex) + { + LineupData.Lineups.TryGetValue(lineupIndex, out var lineup); + return lineup; + } + + public LineupInfo? GetExtraLineup(ExtraLineupType type) + { + var index = (int)type + 10; + LineupData.Lineups.TryGetValue(index, out var lineup); + return lineup; + } + + public LineupInfo? GetCurLineup() + { + return GetLineup(LineupData.GetCurLineupIndex()); + } + + public List GetAvatarsFromTeam(int index) + { + var lineup = GetLineup(index); + if (lineup == null) return []; + + var avatarList = new List(); + foreach (var avatar in lineup.BaseAvatars!) + { + var avatarType = AvatarType.AvatarFormalType; + AvatarInfo? avatarInfo = null; + if (avatar.SpecialAvatarId > 0) { - lineupInfo.LineupData = LineupData; - lineupInfo.AvatarData = player.AvatarManager!.AvatarData; + GameData.SpecialAvatarData.TryGetValue(avatar.SpecialAvatarId, out var specialAvatar); + if (specialAvatar == null) continue; + avatarType = AvatarType.AvatarTrialType; + avatarInfo = specialAvatar.ToAvatarData(Player.Uid); } - } - - #region Detail - - public LineupInfo? GetLineup(int lineupIndex) - { - LineupData.Lineups.TryGetValue(lineupIndex, out var lineup); - return lineup; - } - - public LineupInfo? GetExtraLineup(ExtraLineupType type) - { - var index = (int)type + 10; - LineupData.Lineups.TryGetValue(index, out var lineup); - return lineup; - } - - public LineupInfo? GetCurLineup() - { - return GetLineup(LineupData.GetCurLineupIndex()); - } - - public List GetAvatarsFromTeam(int index) - { - var lineup = GetLineup(index); - if (lineup == null) + else if (avatar.AssistUid > 0) { - return []; - } - - var avatarList = new List(); - foreach (var avatar in lineup.BaseAvatars!) - { - AvatarType avatarType = AvatarType.AvatarFormalType; - Database.Avatar.AvatarInfo? avatarInfo = null; - if (avatar.SpecialAvatarId > 0) - { - GameData.SpecialAvatarData.TryGetValue(avatar.SpecialAvatarId, out var specialAvatar); - if (specialAvatar == null) continue; - avatarType = AvatarType.AvatarTrialType; - avatarInfo = specialAvatar.ToAvatarData(Player.Uid); - } - else if (avatar.AssistUid > 0) - { - var avatarStorage = DatabaseHelper.Instance?.GetInstance(avatar.AssistUid); - avatarType = AvatarType.AvatarAssistType; - if (avatarStorage == null) continue; - foreach (var avatarData in avatarStorage.Avatars!) + var avatarStorage = DatabaseHelper.Instance?.GetInstance(avatar.AssistUid); + avatarType = AvatarType.AvatarAssistType; + if (avatarStorage == null) continue; + foreach (var avatarData in avatarStorage.Avatars!) + if (avatarData.AvatarId == avatar.BaseAvatarId) { - if (avatarData.AvatarId == avatar.BaseAvatarId) - { - avatarInfo = avatarData; - break; - } + avatarInfo = avatarData; + break; } - } - else + } + else + { + avatarInfo = Player.AvatarManager!.GetAvatar(avatar.BaseAvatarId); + } + + if (avatarInfo == null) continue; + avatarList.Add(new AvatarSceneInfo(avatarInfo, avatarType, Player)); + } + + return avatarList; + } + + public List GetAvatarsFromCurTeam() + { + return GetAvatarsFromTeam(LineupData.GetCurLineupIndex()); + } + + public List GetAllLineup() + { + var lineupList = new List(); + foreach (var lineupInfo in LineupData.Lineups.Values) lineupList.Add(lineupInfo); + if (lineupList.Count < GameConstants.MAX_LINEUP_COUNT) + for (var i = lineupList.Count; i < GameConstants.MAX_LINEUP_COUNT; i++) + { + var lineup = new LineupInfo { - avatarInfo = Player.AvatarManager!.GetAvatar(avatar.BaseAvatarId); - } - if (avatarInfo == null) continue; - avatarList.Add(new AvatarSceneInfo(avatarInfo, avatarType, Player)); + Name = "", + LineupType = 0, + BaseAvatars = [], + LineupData = LineupData, + AvatarData = Player.AvatarManager!.AvatarData + }; + lineupList.Add(lineup); + LineupData.Lineups.Add(i, lineup); } - return avatarList; - } + return lineupList; + } - public List GetAvatarsFromCurTeam() + #endregion + + #region Management + + public async ValueTask SetCurLineup(int lineupIndex) + { + if (lineupIndex < 0 || !LineupData.Lineups.ContainsKey(lineupIndex)) return false; + if (GetLineup(lineupIndex)!.BaseAvatars!.Count == 0) return false; + LineupData.CurLineup = lineupIndex; + LineupData.CurExtraLineup = -1; + DatabaseHelper.Instance?.UpdateInstance(LineupData); + + Player.SceneInstance?.SyncLineup(); + await Player.SendPacket(new PacketSyncLineupNotify(GetCurLineup()!)); + + return true; + } + + public void SetExtraLineup(ExtraLineupType type, List baseAvatarIds) + { + if (type == ExtraLineupType.LineupNone) { - return GetAvatarsFromTeam(LineupData.GetCurLineupIndex()); - } - - public List GetAllLineup() - { - var lineupList = new List(); - foreach (var lineupInfo in LineupData.Lineups.Values) - { - lineupList.Add(lineupInfo); - } - if (lineupList.Count < GameConstants.MAX_LINEUP_COUNT) - { - for (int i = lineupList.Count; i < GameConstants.MAX_LINEUP_COUNT; i++) - { - var lineup = new LineupInfo() - { - Name = "", - LineupType = 0, - BaseAvatars = [], - LineupData = LineupData, - AvatarData = Player.AvatarManager!.AvatarData, - }; - lineupList.Add(lineup); - LineupData.Lineups.Add(i, lineup); - } - } - return lineupList; - } - - #endregion - - #region Management - - public bool SetCurLineup(int lineupIndex) - { - if (lineupIndex < 0 || !LineupData.Lineups.ContainsKey(lineupIndex)) - { - return false; - } - if (GetLineup(lineupIndex)!.BaseAvatars!.Count == 0) - { - return false; - } - LineupData.CurLineup = lineupIndex; + // reset lineup LineupData.CurExtraLineup = -1; DatabaseHelper.Instance?.UpdateInstance(LineupData); - - Player.SceneInstance?.SyncLineup(); - Player.SendPacket(new PacketSyncLineupNotify(GetCurLineup()!)); - - return true; + return; } - public void SetExtraLineup(ExtraLineupType type, List baseAvatarIds) + var index = (int)type + 10; + + // destroy old lineup + LineupData.Lineups.Remove(index); + + // create new lineup + var lineup = new LineupInfo { - if (type == ExtraLineupType.LineupNone) - { - // reset lineup - LineupData.CurExtraLineup = -1; - DatabaseHelper.Instance?.UpdateInstance(LineupData); - return; - } - var index = (int)type + 10; + Name = "", + LineupType = (int)type, + BaseAvatars = [], + LineupData = LineupData, + AvatarData = Player.AvatarManager!.AvatarData + }; - // destroy old lineup - LineupData.Lineups.Remove(index); - - // create new lineup - var lineup = new LineupInfo() - { - Name = "", - LineupType = (int)type, - BaseAvatars = [], - LineupData = LineupData, - AvatarData = Player.AvatarManager!.AvatarData, - }; - - foreach (var avatarId in baseAvatarIds) - { - GameData.SpecialAvatarData.TryGetValue(avatarId * 10 + Player.Data.WorldLevel, out var specialAvatar); - if (specialAvatar != null) - { - lineup.BaseAvatars!.Add(new() { BaseAvatarId = specialAvatar.AvatarID, SpecialAvatarId = specialAvatar.GetId() }); - } else - { - lineup.BaseAvatars!.Add(new() { BaseAvatarId = avatarId }); - } - } - - LineupData.Lineups.Add(index, lineup); - LineupData.CurExtraLineup = index; - } - - public void AddAvatar(int lineupIndex, int avatarId, bool sendPacket = true) + foreach (var avatarId in baseAvatarIds) { - if (lineupIndex < 0) - { - return; - } - LineupData.Lineups.TryGetValue(lineupIndex, out LineupInfo? lineup); - - if (lineup == null) - { - var baseAvatarId = avatarId; - var specialAvatarId = avatarId * 10 + Player.Data.WorldLevel; - GameData.SpecialAvatarData.TryGetValue(specialAvatarId, out var specialAvatar); - if (specialAvatar != null) - { - baseAvatarId = specialAvatar.AvatarID; - } - else - { - specialAvatarId = 0; - if (baseAvatarId > 8000) - { - baseAvatarId = 8001; - } - } - - lineup = new() - { - Name = "", - LineupType = 0, - BaseAvatars = [new() { BaseAvatarId = baseAvatarId, SpecialAvatarId = specialAvatarId }], - LineupData = LineupData, - AvatarData = Player.AvatarManager!.AvatarData, - }; - LineupData.Lineups.Add(lineupIndex, lineup); - } else - { - if (lineup.BaseAvatars!.Count >= 4) - { - return; - } - - var baseAvatarId = avatarId; - var specialAvatarId = avatarId * 10 + Player.Data.WorldLevel; - GameData.SpecialAvatarData.TryGetValue(specialAvatarId, out var specialAvatar); - if (specialAvatar != null) - { - baseAvatarId = specialAvatar.AvatarID; - } - else - { - specialAvatarId = 0; - if (baseAvatarId > 8000) - { - baseAvatarId = 8001; - } - } - - lineup.BaseAvatars?.Add(new() { BaseAvatarId = baseAvatarId, SpecialAvatarId = specialAvatarId }); - LineupData.Lineups[lineupIndex] = lineup; - } - - if (sendPacket) - { - if (lineupIndex == LineupData.GetCurLineupIndex()) - { - Player.SceneInstance?.SyncLineup(); - } - Player.SendPacket(new PacketSyncLineupNotify(lineup)); - } - } - - public void AddAvatarToCurTeam(int avatarId, bool sendPacket = true) - { - AddAvatar(LineupData.GetCurLineupIndex(), avatarId, sendPacket); - } - - public void AddSpecialAvatarToCurTeam(int specialAvatarId, bool sendPacket = true) - { - LineupData.Lineups.TryGetValue(LineupData.GetCurLineupIndex(), out LineupInfo? lineup); - GameData.SpecialAvatarData.TryGetValue(specialAvatarId, out var specialAvatar); - if (specialAvatar == null) - { - return; - } - if (lineup == null) - { - lineup = new() - { - Name = "", - LineupType = 0, - BaseAvatars = [new() { BaseAvatarId = specialAvatar.AvatarID, SpecialAvatarId = specialAvatarId }], - LineupData = LineupData, - AvatarData = Player.AvatarManager!.AvatarData, - }; - LineupData.Lineups.Add(LineupData.GetCurLineupIndex(), lineup); - } else - { - if (lineup.BaseAvatars!.Count >= 4) - { - lineup.BaseAvatars!.RemoveAt(3); // remove last avatar - } - lineup.BaseAvatars?.Add(new() { BaseAvatarId = specialAvatar.AvatarID, SpecialAvatarId = specialAvatarId }); - LineupData.Lineups[LineupData.GetCurLineupIndex()] = lineup; - } - - if (sendPacket) - { - Player.SceneInstance?.SyncLineup(); - Player.SendPacket(new PacketSyncLineupNotify(lineup)); - } - } - - public void RemoveAvatar(int lineupIndex, int avatarId, bool sendPacket = true) - { - if (lineupIndex < 0) - { - return; - } - LineupData.Lineups.TryGetValue(lineupIndex, out LineupInfo? lineup); - if (lineup == null) - { - return; - } GameData.SpecialAvatarData.TryGetValue(avatarId * 10 + Player.Data.WorldLevel, out var specialAvatar); if (specialAvatar != null) - { - lineup.BaseAvatars?.RemoveAll(avatar => avatar.BaseAvatarId == specialAvatar.AvatarID); - } + lineup.BaseAvatars!.Add(new LineupAvatarInfo + { BaseAvatarId = specialAvatar.AvatarID, SpecialAvatarId = specialAvatar.GetId() }); else - { - lineup.BaseAvatars?.RemoveAll(avatar => avatar.BaseAvatarId == avatarId); - } - LineupData.Lineups[lineupIndex] = lineup; - DatabaseHelper.Instance?.UpdateInstance(LineupData); - - if (sendPacket) - { - if (lineupIndex == LineupData.GetCurLineupIndex()) - { - Player.SceneInstance?.SyncLineup(); - } - Player.SendPacket(new PacketSyncLineupNotify(lineup)); - } + lineup.BaseAvatars!.Add(new LineupAvatarInfo { BaseAvatarId = avatarId }); } - public void RemoveAvatarFromCurTeam(int avatarId, bool sendPacket = true) - { - RemoveAvatar(LineupData.GetCurLineupIndex(), avatarId, sendPacket); - } - - public void RemoveSpecialAvatarFromCurTeam(int specialAvatarId) - { - LineupData.Lineups.TryGetValue(LineupData.GetCurLineupIndex(), out LineupInfo? lineup); - if (lineup == null) - { - return; - } - lineup.BaseAvatars?.RemoveAll(avatar => avatar.SpecialAvatarId == specialAvatarId); - LineupData.Lineups[LineupData.GetCurLineupIndex()] = lineup; - DatabaseHelper.Instance?.UpdateInstance(LineupData); - Player.SceneInstance?.SyncLineup(); - Player.SendPacket(new PacketSyncLineupNotify(lineup)); - } - - public void ReplaceLineup(int lineupIndex, List lineupSlotList, ExtraLineupType extraLineupType = ExtraLineupType.LineupNone) - { - if (extraLineupType != ExtraLineupType.LineupNone) - { - LineupData.CurExtraLineup = (int)extraLineupType + 10; - if (!LineupData.Lineups.ContainsKey(LineupData.CurExtraLineup)) - { - SetExtraLineup(extraLineupType, []); - } - } - - LineupInfo lineup; - if (LineupData.CurExtraLineup != -1) - { - lineup = LineupData.Lineups[LineupData.CurExtraLineup]; // Extra lineup - } - else if (lineupIndex < 0 || !LineupData.Lineups.ContainsKey(lineupIndex)) - { - return; - } - else - { - lineup = LineupData.Lineups[lineupIndex]; - } - lineup.BaseAvatars = []; - var index = lineup.LineupType == 0 ? lineupIndex : LineupData.GetCurLineupIndex(); - foreach (var avatar in lineupSlotList) - { - AddAvatar(index, avatar, false); - } - - if (index == LineupData.GetCurLineupIndex()) - { - Player.SceneInstance?.SyncLineup(); - } - Player.SendPacket(new PacketSyncLineupNotify(lineup)); - } - - public void ReplaceLineup(ReplaceLineupCsReq req) - { - if (req.ExtraLineupType != ExtraLineupType.LineupNone) - { - LineupData.CurExtraLineup = (int)req.ExtraLineupType + 10; - if (!LineupData.Lineups.ContainsKey(LineupData.CurExtraLineup)) - { - SetExtraLineup(req.ExtraLineupType, []); - } - } - - LineupInfo lineup; - if (LineupData.CurExtraLineup != -1) - { - lineup = LineupData.Lineups[LineupData.CurExtraLineup]; // Extra lineup - } else if (req.Index < 0 || !LineupData.Lineups.ContainsKey((int)req.Index)) - { - return; - } else - { - lineup = LineupData.Lineups[(int)req.Index]; - } - lineup.BaseAvatars = []; - var index = lineup.LineupType == 0 ? (int)req.Index : LineupData.GetCurLineupIndex(); - foreach (var avatar in req.LineupSlotList) - { - AddAvatar(index, (int)avatar.Id, false); - } - - if (index == LineupData.GetCurLineupIndex()) - { - Player.SceneInstance?.SyncLineup(); - } - Player.SendPacket(new PacketSyncLineupNotify(lineup)); - } - - public void CostMp(int count) - { - var curLineup = GetCurLineup()!; - curLineup.Mp -= count; - curLineup.Mp = Math.Min(Math.Max(0, curLineup.Mp), 5); - DatabaseHelper.Instance?.UpdateInstance(LineupData); - - Player.SendPacket(new PacketSceneCastSkillMpUpdateScNotify(1, curLineup.Mp)); - } - - public void GainMp(int count, bool sendPacket = true) - { - count = Math.Min(Math.Max(0, count), 2); - var curLineup = GetCurLineup()!; - curLineup.Mp += count; - curLineup.Mp = Math.Min(Math.Max(0, curLineup.Mp), 5); - DatabaseHelper.Instance?.UpdateInstance(LineupData); - if (sendPacket) - { - Player.SendPacket(new PacketSyncLineupNotify(GetCurLineup()!, Proto.SyncLineupReason.SyncReasonMpAddPropHit)); - } - } - - #endregion + LineupData.Lineups.Add(index, lineup); + LineupData.CurExtraLineup = index; } -} + + public async ValueTask AddAvatar(int lineupIndex, int avatarId, bool sendPacket = true) + { + if (lineupIndex < 0) return; + LineupData.Lineups.TryGetValue(lineupIndex, out var lineup); + + if (lineup == null) + { + var baseAvatarId = avatarId; + var specialAvatarId = avatarId * 10 + Player.Data.WorldLevel; + GameData.SpecialAvatarData.TryGetValue(specialAvatarId, out var specialAvatar); + if (specialAvatar != null) + { + baseAvatarId = specialAvatar.AvatarID; + } + else + { + specialAvatarId = 0; + if (baseAvatarId > 8000) baseAvatarId = 8001; + } + + lineup = new LineupInfo + { + Name = "", + LineupType = 0, + BaseAvatars = [new LineupAvatarInfo { BaseAvatarId = baseAvatarId, SpecialAvatarId = specialAvatarId }], + LineupData = LineupData, + AvatarData = Player.AvatarManager!.AvatarData + }; + LineupData.Lineups.Add(lineupIndex, lineup); + } + else + { + if (lineup.BaseAvatars!.Count >= 4) return; + + var baseAvatarId = avatarId; + var specialAvatarId = avatarId * 10 + Player.Data.WorldLevel; + GameData.SpecialAvatarData.TryGetValue(specialAvatarId, out var specialAvatar); + if (specialAvatar != null) + { + baseAvatarId = specialAvatar.AvatarID; + } + else + { + specialAvatarId = 0; + if (baseAvatarId > 8000) baseAvatarId = 8001; + } + + lineup.BaseAvatars?.Add(new LineupAvatarInfo + { BaseAvatarId = baseAvatarId, SpecialAvatarId = specialAvatarId }); + LineupData.Lineups[lineupIndex] = lineup; + } + + if (sendPacket) + { + if (lineupIndex == LineupData.GetCurLineupIndex()) Player.SceneInstance?.SyncLineup(); + await Player.SendPacket(new PacketSyncLineupNotify(lineup)); + } + } + + public async ValueTask AddAvatarToCurTeam(int avatarId, bool sendPacket = true) + { + await AddAvatar(LineupData.GetCurLineupIndex(), avatarId, sendPacket); + } + + public async ValueTask AddSpecialAvatarToCurTeam(int specialAvatarId, bool sendPacket = true) + { + LineupData.Lineups.TryGetValue(LineupData.GetCurLineupIndex(), out var lineup); + GameData.SpecialAvatarData.TryGetValue(specialAvatarId, out var specialAvatar); + if (specialAvatar == null) return; + if (lineup == null) + { + lineup = new LineupInfo + { + Name = "", + LineupType = 0, + BaseAvatars = + [new LineupAvatarInfo { BaseAvatarId = specialAvatar.AvatarID, SpecialAvatarId = specialAvatarId }], + LineupData = LineupData, + AvatarData = Player.AvatarManager!.AvatarData + }; + LineupData.Lineups.Add(LineupData.GetCurLineupIndex(), lineup); + } + else + { + if (lineup.BaseAvatars!.Count >= 4) lineup.BaseAvatars!.RemoveAt(3); // remove last avatar + lineup.BaseAvatars?.Add(new LineupAvatarInfo + { BaseAvatarId = specialAvatar.AvatarID, SpecialAvatarId = specialAvatarId }); + LineupData.Lineups[LineupData.GetCurLineupIndex()] = lineup; + } + + if (sendPacket) + { + Player.SceneInstance?.SyncLineup(); + await Player.SendPacket(new PacketSyncLineupNotify(lineup)); + } + } + + public async ValueTask RemoveAvatar(int lineupIndex, int avatarId, bool sendPacket = true) + { + if (lineupIndex < 0) return; + LineupData.Lineups.TryGetValue(lineupIndex, out var lineup); + if (lineup == null) return; + GameData.SpecialAvatarData.TryGetValue(avatarId * 10 + Player.Data.WorldLevel, out var specialAvatar); + if (specialAvatar != null) + lineup.BaseAvatars?.RemoveAll(avatar => avatar.BaseAvatarId == specialAvatar.AvatarID); + else + lineup.BaseAvatars?.RemoveAll(avatar => avatar.BaseAvatarId == avatarId); + LineupData.Lineups[lineupIndex] = lineup; + DatabaseHelper.Instance?.UpdateInstance(LineupData); + + if (sendPacket) + { + if (lineupIndex == LineupData.GetCurLineupIndex()) Player.SceneInstance?.SyncLineup(); + await Player.SendPacket(new PacketSyncLineupNotify(lineup)); + } + } + + public async ValueTask RemoveAvatarFromCurTeam(int avatarId, bool sendPacket = true) + { + await RemoveAvatar(LineupData.GetCurLineupIndex(), avatarId, sendPacket); + } + + public async ValueTask ReplaceLineup(int lineupIndex, List lineupSlotList, + ExtraLineupType extraLineupType = ExtraLineupType.LineupNone) + { + if (extraLineupType != ExtraLineupType.LineupNone) + { + LineupData.CurExtraLineup = (int)extraLineupType + 10; + if (!LineupData.Lineups.ContainsKey(LineupData.CurExtraLineup)) SetExtraLineup(extraLineupType, []); + } + + LineupInfo lineup; + if (LineupData.CurExtraLineup != -1) + lineup = LineupData.Lineups[LineupData.CurExtraLineup]; // Extra lineup + else if (lineupIndex < 0 || !LineupData.Lineups.ContainsKey(lineupIndex)) + return; + else + lineup = LineupData.Lineups[lineupIndex]; + lineup.BaseAvatars = []; + var index = lineup.LineupType == 0 ? lineupIndex : LineupData.GetCurLineupIndex(); + foreach (var avatar in lineupSlotList) await AddAvatar(index, avatar, false); + + if (index == LineupData.GetCurLineupIndex()) Player.SceneInstance?.SyncLineup(); + await Player.SendPacket(new PacketSyncLineupNotify(lineup)); + } + + public async ValueTask ReplaceLineup(ReplaceLineupCsReq req) + { + if (req.ExtraLineupType != ExtraLineupType.LineupNone) + { + LineupData.CurExtraLineup = (int)req.ExtraLineupType + 10; + if (!LineupData.Lineups.ContainsKey(LineupData.CurExtraLineup)) SetExtraLineup(req.ExtraLineupType, []); + } + + LineupInfo lineup; + if (LineupData.CurExtraLineup != -1) + lineup = LineupData.Lineups[LineupData.CurExtraLineup]; // Extra lineup + else if (req.Index < 0 || !LineupData.Lineups.ContainsKey((int)req.Index)) + return; + else + lineup = LineupData.Lineups[(int)req.Index]; + lineup.BaseAvatars = []; + var index = lineup.LineupType == 0 ? (int)req.Index : LineupData.GetCurLineupIndex(); + foreach (var avatar in req.LineupSlotList) await AddAvatar(index, (int)avatar.Id, false); + + if (index == LineupData.GetCurLineupIndex()) Player.SceneInstance?.SyncLineup(); + await Player.SendPacket(new PacketSyncLineupNotify(lineup)); + } + + public async ValueTask CostMp(int count) + { + var curLineup = GetCurLineup()!; + curLineup.Mp -= count; + curLineup.Mp = Math.Min(Math.Max(0, curLineup.Mp), 5); + DatabaseHelper.Instance?.UpdateInstance(LineupData); + + await Player.SendPacket(new PacketSceneCastSkillMpUpdateScNotify(1, curLineup.Mp)); + } + + public async ValueTask GainMp(int count, bool sendPacket = true) + { + count = Math.Min(Math.Max(0, count), 2); + var curLineup = GetCurLineup()!; + curLineup.Mp += count; + curLineup.Mp = Math.Min(Math.Max(0, curLineup.Mp), 5); + DatabaseHelper.Instance?.UpdateInstance(LineupData); + if (sendPacket) + await Player.SendPacket( + new PacketSyncLineupNotify(GetCurLineup()!, SyncLineupReason.SyncReasonMpAddPropHit)); + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Mail/MailManager.cs b/GameServer/Game/Mail/MailManager.cs index fc823325..6182fd34 100644 --- a/GameServer/Game/Mail/MailManager.cs +++ b/GameServer/Game/Mail/MailManager.cs @@ -6,91 +6,79 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.GameServer.Server.Packet.Send.Mail; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Mail; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mail +namespace EggLink.DanhengServer.GameServer.Game.Mail; + +public class MailManager(PlayerInstance player) : BasePlayerManager(player) { - public class MailManager(PlayerInstance player) : BasePlayerManager(player) + public MailData MailData { get; } = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + + public List GetMailList() { - public MailData MailData { get; private set; } = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); - - public List GetMailList() - { - return MailData.MailList; - } - - public MailInfo? GetMail(int mailId) - { - return MailData.MailList.Find(x => x.MailID == mailId); - } - - public void SendMail(string sender, string title, string content, int templateId, int expiredDay = 30) - { - var mail = new MailInfo() - { - MailID = MailData.NextMailId++, - SenderName = sender, - Content = content, - Title = title, - TemplateID = templateId, - SendTime = DateTime.Now.ToUnixSec(), - ExpireTime = DateTime.Now.AddDays(expiredDay).ToUnixSec(), - }; - - MailData.MailList.Add(mail); - - Player.SendPacket(new PacketNewMailScNotify(mail.MailID)); - } - - public void SendMail(string sender, string title, string content, int templateId, List attachments, int expiredDay = 30) - { - var mail = new MailInfo() - { - MailID = MailData.NextMailId++, - SenderName = sender, - Content = content, - Title = title, - TemplateID = templateId, - SendTime = DateTime.Now.ToUnixSec(), - ExpireTime = DateTime.Now.AddDays(expiredDay).ToUnixSec(), - Attachment = new() - { - Items = attachments - } - }; - - MailData.MailList.Add(mail); - - Player.SendPacket(new PacketNewMailScNotify(mail.MailID)); - } - - public List ToMailProto() - { - var list = new List(); - - foreach (var mail in MailData.MailList) - { - list.Add(mail.ToProto()); - } - - return list; - } - - public List ToNoticeMailProto() - { - var list = new List(); - - foreach (var mail in MailData.NoticeMailList) - { - list.Add(mail.ToProto()); - } - - return list; - } + return MailData.MailList; } -} + + public MailInfo? GetMail(int mailId) + { + return MailData.MailList.Find(x => x.MailID == mailId); + } + + public async ValueTask SendMail(string sender, string title, string content, int templateId, int expiredDay = 30) + { + var mail = new MailInfo + { + MailID = MailData.NextMailId++, + SenderName = sender, + Content = content, + Title = title, + TemplateID = templateId, + SendTime = DateTime.Now.ToUnixSec(), + ExpireTime = DateTime.Now.AddDays(expiredDay).ToUnixSec() + }; + + MailData.MailList.Add(mail); + + await Player.SendPacket(new PacketNewMailScNotify(mail.MailID)); + } + + public async ValueTask SendMail(string sender, string title, string content, int templateId, + List attachments, int expiredDay = 30) + { + var mail = new MailInfo + { + MailID = MailData.NextMailId++, + SenderName = sender, + Content = content, + Title = title, + TemplateID = templateId, + SendTime = DateTime.Now.ToUnixSec(), + ExpireTime = DateTime.Now.AddDays(expiredDay).ToUnixSec(), + Attachment = new MailAttachmentInfo + { + Items = attachments + } + }; + + MailData.MailList.Add(mail); + + await Player.SendPacket(new PacketNewMailScNotify(mail.MailID)); + } + + public List ToMailProto() + { + var list = new List(); + + foreach (var mail in MailData.MailList) list.Add(mail.ToProto()); + + return list; + } + + public List ToNoticeMailProto() + { + var list = new List(); + + foreach (var mail in MailData.NoticeMailList) list.Add(mail.ToProto()); + + return list; + } +} \ No newline at end of file diff --git a/GameServer/Game/Message/MessageManager.cs b/GameServer/Game/Message/MessageManager.cs index 032ca19b..70ca7ceb 100644 --- a/GameServer/Game/Message/MessageManager.cs +++ b/GameServer/Game/Message/MessageManager.cs @@ -1,217 +1,192 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Message; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; using EggLink.DanhengServer.Util; -using Microsoft.EntityFrameworkCore.Storage; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Message +namespace EggLink.DanhengServer.Game.Message; + +public class MessageManager(PlayerInstance player) : BasePlayerManager(player) { - public class MessageManager(PlayerInstance player) : BasePlayerManager(player) + public MessageData Data { get; } = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + public List PendingMessagePerformSectionList { get; private set; } = []; + + #region Get + + public MessageSectionData? GetMessageSectionData(int sectionId) { - public MessageData Data { get; private set; } = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); - public List PendingMessagePerformSectionList { get; private set; } = []; + GameData.MessageSectionConfigData.TryGetValue(sectionId, out var sectionConfig); + if (sectionConfig == null) return null; + var groupId = sectionConfig.GroupID; + if (!Data.Groups.TryGetValue(groupId, out var group)) return null; + return group.Sections.FirstOrDefault(m => m.SectionId == sectionId); + } - #region Get - - public MessageSectionData? GetMessageSectionData(int sectionId) - { - GameData.MessageSectionConfigData.TryGetValue(sectionId, out var sectionConfig); - if (sectionConfig == null) + public List GetMessageGroup(int contactId) + { + GameData.MessageContactsConfigData.TryGetValue(contactId, out var contactConfig); + if (contactConfig == null) return []; + var result = new List(); + foreach (var item in contactConfig.Groups) + if (Data.Groups.TryGetValue(item.ID, out var group)) { - return null; - } - var groupId = sectionConfig.GroupID; - if (!Data.Groups.TryGetValue(groupId, out var group)) - { - return null; - } - return group.Sections.FirstOrDefault(m => m.SectionId == sectionId); - } - - public List GetMessageGroup(int contactId) - { - GameData.MessageContactsConfigData.TryGetValue(contactId, out var contactConfig); - if (contactConfig == null) - { - return []; - } - var result = new List(); - foreach (var item in contactConfig.Groups) - { - if (Data.Groups.TryGetValue(item.ID, out var group)) + var groupInfo = new MessageGroup { - var groupInfo = new MessageGroup - { - Id = (uint)item.ID, - Status = group.Status, - RefreshTime = group.RefreshTime, - }; - foreach (var section in group.Sections) - { - var sectionInfo = new MessageSection - { - Id = (uint)section.SectionId, - Status = section.Status, - }; - sectionInfo.ToChooseItemId.AddRange(section.ToChooseItemId.Select(m => (uint)m)); - sectionInfo.ItemList.AddRange(section.Items.Select(m => new MessageItem() - { - ItemId = (uint)m.ItemId, - })); - groupInfo.MessageSectionList.Add(sectionInfo); - } - groupInfo.MessageSectionId = (uint)group.CurrentSectionId; - result.Add(groupInfo); - } - else - { - result.Add(new MessageGroup - { - Id = (uint)item.ID, - Status = MessageGroupStatus.MessageGroupNone, - RefreshTime = 0, - }); - } - } - return result; - } - - #endregion - - #region Action - - public void AddMessageSection(int sectionId) - { - GameData.MessageSectionConfigData.TryGetValue(sectionId, out var sectionConfig); - if (sectionConfig == null) return; - foreach (var item in sectionConfig.StartMessageItemIDList) - { - AddMessageItem(item); - } - } - - public void AddMessageItem(int itemId, bool sendPacket = true) - { - GameData.MessageItemConfigData.TryGetValue(itemId, out var itemConfig); - if (itemConfig == null) return; - var groupId = itemConfig.GroupID; - var sectionId = itemConfig.SectionID; - if (!Data.Groups.TryGetValue(groupId, out var group)) - { - group = new MessageGroupData - { - GroupId = groupId, - CurrentSectionId = sectionId, - RefreshTime = Extensions.GetUnixSec(), - Status = MessageGroupStatus.MessageGroupDoing, + Id = (uint)item.ID, + Status = group.Status, + RefreshTime = group.RefreshTime }; + foreach (var section in group.Sections) + { + var sectionInfo = new MessageSection + { + Id = (uint)section.SectionId, + Status = section.Status + }; + sectionInfo.ToChooseItemId.AddRange(section.ToChooseItemId.Select(m => (uint)m)); + sectionInfo.ItemList.AddRange(section.Items.Select(m => new MessageItem + { + ItemId = (uint)m.ItemId + })); + groupInfo.MessageSectionList.Add(sectionInfo); + } + + groupInfo.MessageSectionId = (uint)group.CurrentSectionId; + result.Add(groupInfo); + } + else + { + result.Add(new MessageGroup + { + Id = (uint)item.ID, + Status = MessageGroupStatus.MessageGroupNone, + RefreshTime = 0 + }); + } + + return result; + } + + #endregion + + #region Action + + public async ValueTask AddMessageSection(int sectionId) + { + GameData.MessageSectionConfigData.TryGetValue(sectionId, out var sectionConfig); + if (sectionConfig == null) return; + foreach (var item in sectionConfig.StartMessageItemIDList) await AddMessageItem(item); + } + + public async ValueTask AddMessageItem(int itemId, bool sendPacket = true) + { + GameData.MessageItemConfigData.TryGetValue(itemId, out var itemConfig); + if (itemConfig == null) return; + var groupId = itemConfig.GroupID; + var sectionId = itemConfig.SectionID; + if (!Data.Groups.TryGetValue(groupId, out var group)) + { + group = new MessageGroupData + { + GroupId = groupId, + CurrentSectionId = sectionId, + RefreshTime = Extensions.GetUnixSec(), + Status = MessageGroupStatus.MessageGroupDoing + }; + group.Sections.Add(new MessageSectionData + { + SectionId = sectionId, + Status = MessageSectionStatus.MessageSectionDoing, + ToChooseItemId = itemConfig.NextItemIDList + }); + Data.Groups.Add(groupId, group); + } + else + { + group.CurrentSectionId = sectionId; + group.RefreshTime = Extensions.GetUnixSec(); + group.Status = MessageGroupStatus.MessageGroupDoing; + if (!group.Sections.Any(m => m.SectionId == sectionId)) // new section + { group.Sections.Add(new MessageSectionData { SectionId = sectionId, Status = MessageSectionStatus.MessageSectionDoing, - ToChooseItemId = itemConfig.NextItemIDList, + ToChooseItemId = itemConfig.NextItemIDList }); - Data.Groups.Add(groupId, group); - } - else - { - group.CurrentSectionId = sectionId; - group.RefreshTime = Extensions.GetUnixSec(); - group.Status = MessageGroupStatus.MessageGroupDoing; - if (!group.Sections.Any(m => m.SectionId == sectionId)) // new section - { - group.Sections.Add(new MessageSectionData - { - SectionId = sectionId, - Status = MessageSectionStatus.MessageSectionDoing, - ToChooseItemId = itemConfig.NextItemIDList, - }); - if (itemConfig.NextItemIDList.Count == 1) - { - FinishMessageItem(itemConfig.NextItemIDList[0], false); - } - } - else // old - { - group.Sections.First(m => m.SectionId == sectionId).Status = MessageSectionStatus.MessageSectionDoing; - } + if (itemConfig.NextItemIDList.Count == 1) await FinishMessageItem(itemConfig.NextItemIDList[0], false); } - - // sync - if (sendPacket) + else // old { - var notify = new PacketPlayerSyncScNotify(group, group.Sections.First(m => m.SectionId == sectionId)); - Player.SendPacket(notify); + group.Sections.First(m => m.SectionId == sectionId).Status = MessageSectionStatus.MessageSectionDoing; } } - public void FinishSection(int sectionId, bool sendPacket = true) + // sync + if (sendPacket) { - GameData.MessageSectionConfigData.TryGetValue(sectionId, out var sectionConfig); - if (sectionConfig == null) return; - var groupId = sectionConfig.GroupID; - if (!Data.Groups.TryGetValue(groupId, out var group)) return; - var section = group.Sections.First(m => m.SectionId == sectionId); - if (section.Status != MessageSectionStatus.MessageSectionDoing) return; - section.Status = MessageSectionStatus.MessageSectionFinish; - if (group.Sections.All(m => m.Status == MessageSectionStatus.MessageSectionFinish)) - { - group.Status = MessageGroupStatus.MessageGroupFinish; - } - - // sync - if (sendPacket) - { - var notify = new PacketPlayerSyncScNotify(group, section); - Player.SendPacket(notify); - } - - // broadcast to mission system - Player.MissionManager!.HandleFinishType(Enums.MissionFinishTypeEnum.MessagePerformSectionFinish); - Player.MissionManager!.HandleFinishType(Enums.MissionFinishTypeEnum.MessageSectionFinish); + var notify = new PacketPlayerSyncScNotify(group, group.Sections.First(m => m.SectionId == sectionId)); + await Player.SendPacket(notify); } - - public void FinishMessageItem(int itemId, bool sendPacket = true) - { - GameData.MessageItemConfigData.TryGetValue(itemId, out var itemConfig); - if (itemConfig == null) return; - var groupId = itemConfig.GroupID; - var sectionId = itemConfig.SectionID; - if (!Data.Groups.TryGetValue(groupId, out var group)) return; - var section = group.Sections.First(m => m.SectionId == sectionId); - if (section.Status != MessageSectionStatus.MessageSectionDoing) return; - //if (!section.ToChooseItemId.Contains(itemId)) return; - section.ToChooseItemId.Clear(); - section.Items.Add(new MessageItemData - { - ItemId = itemId, - }); - section.ToChooseItemId.AddRange(itemConfig.NextItemIDList); - - group.RefreshTime = Extensions.GetUnixSec(); - - if (section.ToChooseItemId.Count == 1) // if only one item, auto finish - { - FinishMessageItem(section.ToChooseItemId[0], false); - } - - if (sendPacket) - { - // sync - var notify = new PacketPlayerSyncScNotify(group, section); - Player.SendPacket(notify); - } - } - - #endregion } -} + + public async ValueTask FinishSection(int sectionId, bool sendPacket = true) + { + GameData.MessageSectionConfigData.TryGetValue(sectionId, out var sectionConfig); + if (sectionConfig == null) return; + var groupId = sectionConfig.GroupID; + if (!Data.Groups.TryGetValue(groupId, out var group)) return; + var section = group.Sections.First(m => m.SectionId == sectionId); + if (section.Status != MessageSectionStatus.MessageSectionDoing) return; + section.Status = MessageSectionStatus.MessageSectionFinish; + if (group.Sections.All(m => m.Status == MessageSectionStatus.MessageSectionFinish)) + group.Status = MessageGroupStatus.MessageGroupFinish; + + // sync + if (sendPacket) + { + var notify = new PacketPlayerSyncScNotify(group, section); + await Player.SendPacket(notify); + } + + // broadcast to mission system + await Player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.MessagePerformSectionFinish); + await Player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.MessageSectionFinish); + } + + public async ValueTask FinishMessageItem(int itemId, bool sendPacket = true) + { + GameData.MessageItemConfigData.TryGetValue(itemId, out var itemConfig); + if (itemConfig == null) return; + var groupId = itemConfig.GroupID; + var sectionId = itemConfig.SectionID; + if (!Data.Groups.TryGetValue(groupId, out var group)) return; + var section = group.Sections.First(m => m.SectionId == sectionId); + if (section.Status != MessageSectionStatus.MessageSectionDoing) return; + //if (!section.ToChooseItemId.Contains(itemId)) return; + section.ToChooseItemId.Clear(); + section.Items.Add(new MessageItemData + { + ItemId = itemId + }); + section.ToChooseItemId.AddRange(itemConfig.NextItemIDList); + + group.RefreshTime = Extensions.GetUnixSec(); + + if (section.ToChooseItemId.Count == 1) // if only one item, auto finish + await FinishMessageItem(section.ToChooseItemId[0], false); + + if (sendPacket) + { + // sync + var notify = new PacketPlayerSyncScNotify(group, section); + await Player.SendPacket(notify); + } + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerAddMissionItem.cs b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerAddMissionItem.cs index cb5e5c5d..ed894aab 100644 --- a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerAddMissionItem.cs +++ b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerAddMissionItem.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler; + +[MissionFinishAction(FinishActionTypeEnum.addMissionItem)] +public class MissionHandlerAddMissionItem : MissionFinishActionHandler { - [MissionFinishAction(FinishActionTypeEnum.addMissionItem)] - public class MissionHandlerAddMissionItem : MissionFinishActionHandler + public override async ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player) { - public override void OnHandle(List Params, List ParamString, PlayerInstance Player) + if (Params.Count < 2) return; + for (var i = 0; i < Params.Count; i += 2) { - if (Params.Count < 2) return; - for (var i = 0; i < Params.Count; i += 2) - { - var itemId = Params[i]; - var count = Params[i + 1]; - Player.InventoryManager!.AddItem(itemId, count); - } + var itemId = Params[i]; + var count = Params[i + 1]; + await Player.InventoryManager!.AddItem(itemId, count); } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerAddRecoverMissionItem.cs b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerAddRecoverMissionItem.cs index acb0480b..a2bd81a4 100644 --- a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerAddRecoverMissionItem.cs +++ b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerAddRecoverMissionItem.cs @@ -1,25 +1,20 @@ -using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Enums; +using EggLink.DanhengServer.Game.Player; -namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler; + +[MissionFinishAction(FinishActionTypeEnum.addRecoverMissionItem)] +public class MissionHandlerAddRecoverMissionItem : MissionFinishActionHandler { - [MissionFinishAction(Enums.FinishActionTypeEnum.addRecoverMissionItem)] - public class MissionHandlerAddRecoverMissionItem : MissionFinishActionHandler + public override async ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player) { - public override void OnHandle(List Params, List ParamString, PlayerInstance Player) - { - if (Params.Count < 2) return; + if (Params.Count < 2) return; - for (int i = 0; i < Params.Count; i += 2) - { - var itemId = Params[i]; - var count = Params[i + 1]; - Player.InventoryManager!.AddItem(itemId, count); - } + for (var i = 0; i < Params.Count; i += 2) + { + var itemId = Params[i]; + var count = Params[i + 1]; + await Player.InventoryManager!.AddItem(itemId, count); } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerChangeLineup.cs b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerChangeLineup.cs index bef4119f..28014f0c 100644 --- a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerChangeLineup.cs +++ b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerChangeLineup.cs @@ -1,48 +1,42 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler; + +[MissionFinishAction(FinishActionTypeEnum.ChangeLineup)] +public class MissionHandlerChangeLineup : MissionFinishActionHandler { - [MissionFinishAction(FinishActionTypeEnum.ChangeLineup)] - public class MissionHandlerChangeLineup : MissionFinishActionHandler + public override async ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player) { - - public override void OnHandle(List Params, List ParamString, PlayerInstance Player) + Player.LineupManager!.GetCurLineup()!.BaseAvatars!.Clear(); + var count = 0; + var avatarCount = Params.Count(value => value != 0) - 1; + foreach (var avatarId in Params) { - Player.LineupManager!.GetCurLineup()!.BaseAvatars!.Clear(); - var count = 0; - var avatarCount = Params.Count(value => value != 0) - 1; - foreach (var avatarId in Params) + if (count++ >= 4) break; + GameData.SpecialAvatarData.TryGetValue(avatarId * 10 + Player.Data.WorldLevel, out var specialAvatar); + if (specialAvatar == null) { - if (count++ >= 4) break; - GameData.SpecialAvatarData.TryGetValue(avatarId * 10 + Player.Data.WorldLevel, out var specialAvatar); - if (specialAvatar == null) - { - GameData.AvatarConfigData.TryGetValue(avatarId, out var avatar); - if (avatar == null) continue; - var ava = Player.AvatarManager!.GetAvatar(avatarId); - if (ava == null) Player.AvatarManager!.AddAvatar(avatarId); - Player.LineupManager!.AddAvatarToCurTeam(avatarId, count == avatarCount); - } - else - { - Player.LineupManager!.AddSpecialAvatarToCurTeam(avatarId * 10 + Player.Data.WorldLevel, count == avatarCount); - } - } - GameData.SpecialAvatarData.TryGetValue(Params[4] * 10 + Player.Data.WorldLevel, out var leaderAvatar); - if (leaderAvatar == null) - { - Player.LineupManager!.GetCurLineup()!.LeaderAvatarId = Params[4]; + GameData.AvatarConfigData.TryGetValue(avatarId, out var avatar); + if (avatar == null) continue; + var ava = Player.AvatarManager!.GetAvatar(avatarId); + if (ava == null) await Player.AvatarManager!.AddAvatar(avatarId); + await Player.LineupManager!.AddAvatarToCurTeam(avatarId, count == avatarCount); } else { - Player.LineupManager!.GetCurLineup()!.LeaderAvatarId = leaderAvatar.AvatarID; + await Player.LineupManager!.AddSpecialAvatarToCurTeam(avatarId * 10 + Player.Data.WorldLevel, + count == avatarCount); } - DatabaseHelper.Instance!.UpdateInstance(Player.LineupManager!.LineupData); - Player.SceneInstance!.SyncLineup(); } + + GameData.SpecialAvatarData.TryGetValue(Params[4] * 10 + Player.Data.WorldLevel, out var leaderAvatar); + if (leaderAvatar == null) + Player.LineupManager!.GetCurLineup()!.LeaderAvatarId = Params[4]; + else + Player.LineupManager!.GetCurLineup()!.LeaderAvatarId = leaderAvatar.AvatarID; + + await Player.SceneInstance!.SyncLineup(); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerChangeStoryLine.cs b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerChangeStoryLine.cs index 7af3b031..2a1a3eb7 100644 --- a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerChangeStoryLine.cs +++ b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerChangeStoryLine.cs @@ -1,33 +1,23 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishAction; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishAction.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishAction.Handler; + +[MissionFinishAction(FinishActionTypeEnum.ChangeStoryLine)] +public class MissionHandlerChangeStoryLine : MissionFinishActionHandler { - [MissionFinishAction(FinishActionTypeEnum.ChangeStoryLine)] - public class MissionHandlerChangeStoryLine : MissionFinishActionHandler + public override async ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player) { - public override void OnHandle(List Params, List ParamString, PlayerInstance Player) - { - var toStoryLineId = Params[0]; - var toEntryId = Params[1]; - var toAnchorGroup = Params[2]; - var toAnchorId = Params[3]; + var toStoryLineId = Params[0]; + var toEntryId = Params[1]; + var toAnchorGroup = Params[2]; + var toAnchorId = Params[3]; - if (toStoryLineId == 0) - { - // exit - Player.StoryLineManager!.FinishStoryLine(toEntryId, toAnchorGroup, toAnchorId); - } - else - { - Player.StoryLineManager!.InitStoryLine(toStoryLineId, toEntryId, toAnchorGroup, toAnchorId); - } - } + if (toStoryLineId == 0) + // exit + await Player.StoryLineManager!.FinishStoryLine(toEntryId, toAnchorGroup, toAnchorId); + else + await Player.StoryLineManager!.InitStoryLine(toStoryLineId, toEntryId, toAnchorGroup, toAnchorId); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelMission.cs b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelMission.cs index 07b519ba..2b280143 100644 --- a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelMission.cs +++ b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelMission.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler; + +[MissionFinishAction(FinishActionTypeEnum.delMission)] +public class MissionHandlerDelMission : MissionFinishActionHandler { - [MissionFinishAction(FinishActionTypeEnum.delMission)] - public class MissionHandlerDelMission : MissionFinishActionHandler + public override async ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player) { - public override void OnHandle(List Params, List ParamString, PlayerInstance Player) - { - if (Params.Count < 1) return; - var missionId = Params[0]; - Player.MissionManager?.FinishSubMission(missionId); - } + if (Params.Count < 1) return; + var missionId = Params[0]; + await Player.MissionManager!.FinishSubMission(missionId); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelMissionItem.cs b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelMissionItem.cs index da64befc..0282cfcf 100644 --- a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelMissionItem.cs +++ b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelMissionItem.cs @@ -1,26 +1,20 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishAction; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishAction.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishAction.Handler; + +[MissionFinishAction(FinishActionTypeEnum.delMissionItem)] +public class MissionHandlerDelMissionItem : MissionFinishActionHandler { - [MissionFinishAction(FinishActionTypeEnum.delMissionItem)] - public class MissionHandlerDelMissionItem : MissionFinishActionHandler + public override async ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player) { - public override void OnHandle(List Params, List ParamString, PlayerInstance Player) + if (Params.Count < 2) return; + for (var i = 0; i < Params.Count; i += 2) { - if (Params.Count < 2) return; - for (var i = 0; i < Params.Count; i += 2) - { - var itemId = Params[i]; - var count = Params[i + 1]; - Player.InventoryManager!.RemoveItem(itemId, count); - } + var itemId = Params[i]; + var count = Params[i + 1]; + await Player.InventoryManager!.RemoveItem(itemId, count); } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelSubMission.cs b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelSubMission.cs index 62deb53e..600dbad3 100644 --- a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelSubMission.cs +++ b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerDelSubMission.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler; + +[MissionFinishAction(FinishActionTypeEnum.delSubMission)] +public class MissionHandlerDelSubMission : MissionFinishActionHandler { - [MissionFinishAction(FinishActionTypeEnum.delSubMission)] - public class MissionHandlerDelSubMission : MissionFinishActionHandler + public override async ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player) { - public override void OnHandle(List Params, List ParamString, PlayerInstance Player) - { - if (Params.Count < 1) return; + if (Params.Count < 1) return; - foreach (var subMissionId in Params) - { - Player.MissionManager?.AcceptSubMission(subMissionId); - Player.MissionManager?.FinishSubMission(subMissionId); - } + foreach (var subMissionId in Params) + { + await Player.MissionManager!.AcceptSubMission(subMissionId); + await Player.MissionManager!.FinishSubMission(subMissionId); } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerEnterEntryIfNotThere.cs b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerEnterEntryIfNotThere.cs index 0df90dea..a9c70cae 100644 --- a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerEnterEntryIfNotThere.cs +++ b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerEnterEntryIfNotThere.cs @@ -1,24 +1,18 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishAction; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishAction.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishAction.Handler; + +[MissionFinishAction(FinishActionTypeEnum.EnterEntryIfNotThere)] +public class MissionHandlerEnterEntryIfNotThere : MissionFinishActionHandler { - [MissionFinishAction(FinishActionTypeEnum.EnterEntryIfNotThere)] - public class MissionHandlerEnterEntryIfNotThere : MissionFinishActionHandler + public override async ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player) { - public override void OnHandle(List Params, List ParamString, PlayerInstance Player) - { - var entryId = Params[0]; - var anchorGroup = Params[1]; - var anchorId = Params[2]; + var entryId = Params[0]; + var anchorGroup = Params[1]; + var anchorId = Params[2]; - Player.EnterMissionScene(entryId, anchorGroup, anchorId, true); - } + await Player.EnterMissionScene(entryId, anchorGroup, anchorId, true); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerSetFloorSavedValue.cs b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerSetFloorSavedValue.cs index b7de1b5b..2f5175fd 100644 --- a/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerSetFloorSavedValue.cs +++ b/GameServer/Game/Mission/FinishAction/Handler/MissionHandlerSetFloorSavedValue.cs @@ -1,32 +1,26 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishAction.Handler; + +[MissionFinishAction(FinishActionTypeEnum.SetFloorSavedValue)] +public class MissionHandlerSetFloorSavedValue : MissionFinishActionHandler { - [MissionFinishAction(FinishActionTypeEnum.SetFloorSavedValue)] - public class MissionHandlerSetFloorSavedValue : MissionFinishActionHandler + public override async ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player) { - public override void OnHandle(List Params, List ParamString, PlayerInstance Player) + _ = int.TryParse(ParamString[0], out var plane); + _ = int.TryParse(ParamString[1], out var floor); + Player.SceneData!.FloorSavedData.TryGetValue(floor, out var value); + if (value == null) { - _ = int.TryParse(ParamString[0], out var plane); - _ = int.TryParse(ParamString[1], out var floor); - Player.SceneData!.FloorSavedData.TryGetValue(floor, out var value); - if (value == null) - { - value = []; - Player.SceneData.FloorSavedData[floor] = value; - } - - value[ParamString[2]] = int.Parse(ParamString[3]); // ParamString[2] is the key - Player.SendPacket(new PacketUpdateFloorSavedValueNotify(ParamString[2], int.Parse(ParamString[3]))); - - Player.TaskManager?.SceneTaskTrigger.TriggerFloor(plane, floor); + value = []; + Player.SceneData.FloorSavedData[floor] = value; } + + value[ParamString[2]] = int.Parse(ParamString[3]); // ParamString[2] is the key + await Player.SendPacket(new PacketUpdateFloorSavedValueNotify(ParamString[2], int.Parse(ParamString[3]))); + + Player.TaskManager?.SceneTaskTrigger.TriggerFloor(plane, floor); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/MissionFinishActionAttribute.cs b/GameServer/Game/Mission/FinishAction/MissionFinishActionAttribute.cs index 65bd88b9..eb255234 100644 --- a/GameServer/Game/Mission/FinishAction/MissionFinishActionAttribute.cs +++ b/GameServer/Game/Mission/FinishAction/MissionFinishActionAttribute.cs @@ -1,10 +1,9 @@ using EggLink.DanhengServer.Enums; -namespace EggLink.DanhengServer.Game.Mission.FinishAction +namespace EggLink.DanhengServer.Game.Mission.FinishAction; + +[AttributeUsage(AttributeTargets.Class)] +public class MissionFinishActionAttribute(FinishActionTypeEnum finishAction) : Attribute { - [AttributeUsage(AttributeTargets.Class)] - public class MissionFinishActionAttribute(FinishActionTypeEnum finishAction) : Attribute - { - public FinishActionTypeEnum FinishAction { get; } = finishAction; - } -} + public FinishActionTypeEnum FinishAction { get; } = finishAction; +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishAction/MissionFinishActionHandler.cs b/GameServer/Game/Mission/FinishAction/MissionFinishActionHandler.cs index 5a7cd2c0..1f55118f 100644 --- a/GameServer/Game/Mission/FinishAction/MissionFinishActionHandler.cs +++ b/GameServer/Game/Mission/FinishAction/MissionFinishActionHandler.cs @@ -1,10 +1,8 @@ -using EggLink.DanhengServer.Enums; -using EggLink.DanhengServer.Game.Player; +using EggLink.DanhengServer.Game.Player; -namespace EggLink.DanhengServer.Game.Mission.FinishAction +namespace EggLink.DanhengServer.Game.Mission.FinishAction; + +public abstract class MissionFinishActionHandler { - public abstract class MissionFinishActionHandler - { - public abstract void OnHandle(List Params, List ParamString, PlayerInstance Player); - } -} + public abstract ValueTask OnHandle(List Params, List ParamString, PlayerInstance Player); +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerBuyShopGoods.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerBuyShopGoods.cs index 8d460a55..be9c94ff 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerBuyShopGoods.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerBuyShopGoods.cs @@ -2,30 +2,16 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.BuyShopGoods)] +public class MissionHandlerBuyShopGoods : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.BuyShopGoods)] - public class MissionHandlerBuyShopGoods : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (arg != null && arg is string x) - { - if (x == "BuyGoods") - { - player.MissionManager!.FinishSubMission(info.ID); - } - } - } + if (arg != null && arg is string x) + if (x == "BuyGoods") + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerDelTrialAvatar.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerDelTrialAvatar.cs index 83ce87fa..9ea802b2 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerDelTrialAvatar.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerDelTrialAvatar.cs @@ -1,30 +1,14 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.DelTrialAvatar)] +public class MissionHandlerDelTrialAvatar : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.DelTrialAvatar)] - public class MissionHandlerDelTrialAvatar : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - // MOVE TO TASK HANDLER - //if (player.LineupManager!.GetCurLineup() == null) return; - //var actualSpecialAvatarId = info.ParamInt1 * 10 + player.Data.WorldLevel; - //var item = player.LineupManager!.GetCurLineup()!.BaseAvatars!.Find(item => item.SpecialAvatarId == actualSpecialAvatarId); - //if (item == null) return; // avatar not found - //player.LineupManager!.RemoveSpecialAvatarFromCurTeam(actualSpecialAvatarId); - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - player.MissionManager!.FinishSubMission(info.ID); - } + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterFloor.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterFloor.cs index d092aedc..6ff8aa48 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterFloor.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterFloor.cs @@ -1,29 +1,14 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.EnterFloor)] +public class MissionHandlerEnterFloor : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.EnterFloor)] - public class MissionHandlerEnterFloor : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - // MOVE TO TASK HANDLER - //player.EnterMissionScene(info.MapEntranceID, info.AnchorGroupID, info.AnchorID, true); - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (player.Data.FloorId == info.ParamInt2) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } + if (player.Data.FloorId == info.ParamInt2) await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterMapByEntrance.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterMapByEntrance.cs index b379b500..bec3e084 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterMapByEntrance.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterMapByEntrance.cs @@ -1,30 +1,16 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.EnterMapByEntrance)] +public class MissionHandlerEnterMapByEntrance : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.EnterMapByEntrance)] - public class MissionHandlerEnterMapByEntrance : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (arg is int v) - { - if (v == info.ParamInt1) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } - } + if (arg is int v) + if (v == info.ParamInt1) + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterPlane.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterPlane.cs index 8a2fb2b0..c04593ac 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterPlane.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterPlane.cs @@ -2,25 +2,15 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.EnterPlane)] +public class MissionHandlerEnterPlane : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.EnterPlane)] - public class MissionHandlerEnterPlane : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (player.Data.PlaneId != info.ParamInt1) return; // not a same scene - player.MissionManager!.FinishSubMission(info.ID); - } + if (player.Data.PlaneId != info.ParamInt1) return; // not a same scene + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterRaidScene.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterRaidScene.cs index 259e6b89..bd8db1d4 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterRaidScene.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerEnterRaidScene.cs @@ -1,32 +1,18 @@ -using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Data.Config; +using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.Server.Packet.Send.Scene; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.EnterRaidScene)] +public class MissionHandlerEnterRaidScene : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.EnterRaidScene)] - public class MissionHandlerEnterRaidScene : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (player.RaidManager!.RaidData.CurRaidId != info.ParamInt1) - { - // change raid - player.RaidManager!.EnterRaid(info.ParamInt1, 0); - } - player.EnterScene(info.ParamInt2, 0, true); - player.MissionManager!.FinishSubMission(info.ID); - } + if (player.RaidManager!.RaidData.CurRaidId != info.ParamInt1) + // change raid + await player.RaidManager!.EnterRaid(info.ParamInt1, 0); + await player.EnterScene(info.ParamInt2, 0, true); + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerFinishMission.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerFinishMission.cs index c22829e3..533746f2 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerFinishMission.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerFinishMission.cs @@ -1,36 +1,22 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.FinishMission)] +public class MissionHandlerFinishMission : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.FinishMission)] - public class MissionHandlerFinishMission : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } + var send = true; + foreach (var mainMissionId in info.ParamIntList ?? []) + if (player.MissionManager!.GetMainMissionStatus(mainMissionId) != MissionPhaseEnum.Finish) + { + send = false; + break; + } - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - var send = true; - foreach (var mainMissionId in info.ParamIntList ?? []) - { - if (player.MissionManager!.GetMainMissionStatus(mainMissionId) != MissionPhaseEnum.Finish) - { - send = false; - break; - } - } - if (send) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } + if (send) await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerFloorSavedValue.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerFloorSavedValue.cs index ea46fe03..11f82632 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerFloorSavedValue.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerFloorSavedValue.cs @@ -1,33 +1,18 @@ using EggLink.DanhengServer.Data.Config; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.FloorSavedValue)] +public class MissionHandlerFloorSavedValue : MissionFinishTypeHandler { - [MissionFinishType(Enums.MissionFinishTypeEnum.FloorSavedValue)] - public class MissionHandlerFloorSavedValue : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (player.SceneData?.FloorSavedData.TryGetValue(info.LevelFloorID, out var floor) == true) - { - if (floor.TryGetValue(info.ParamStr1, out var value)) - { - if (value == info.ParamInt1) - { - player.MissionManager?.FinishSubMission(info.ID); - } - } - } - } + if (player.SceneData?.FloorSavedData.TryGetValue(info.LevelFloorID, out var floor) == true) + if (floor.TryGetValue(info.ParamStr1, out var value)) + if (value == info.ParamInt1) + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerGetItem.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerGetItem.cs index 737e5657..d0d02ac5 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerGetItem.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerGetItem.cs @@ -1,31 +1,18 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Database.Inventory; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.GetItem)] +public class MissionHandlerGetItem : MissionFinishTypeHandler { - [MissionFinishType(Enums.MissionFinishTypeEnum.GetItem)] - internal class MissionHandlerGetItem : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (arg != null && arg is ItemData item) - { - if (item.ItemId == info.ParamInt1) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } - } + if (arg != null && arg is ItemData item) + if (item.ItemId == info.ParamInt1) + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerGetTrialAvatar.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerGetTrialAvatar.cs index a3cf0a57..f0087951 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerGetTrialAvatar.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerGetTrialAvatar.cs @@ -1,27 +1,14 @@ -using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Data.Config; +using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.Server.Packet.Send.Player; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.GetTrialAvatar)] +public class MissionHandlerGetTrialAvatar : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.GetTrialAvatar)] - public class MissionHandlerGetTrialAvatar : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - // MOVE TO TASK HANDLER - //if (player.LineupManager!.GetCurLineup() == null) return; - //var actualSpecialAvatarId = info.ParamInt1 * 10 + player.Data.WorldLevel; - //var item = player.LineupManager!.GetCurLineup()!.BaseAvatars!.Find(item => item.SpecialAvatarId == actualSpecialAvatarId); - //if (item != null) return; // existing avatar - //player.LineupManager!.AddSpecialAvatarToCurTeam(actualSpecialAvatarId); - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - player.MissionManager!.FinishSubMission(info.ID); - } + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerHeartDialDialoguePerformanceFinish.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerHeartDialDialoguePerformanceFinish.cs index cb55d4de..82dc0f92 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerHeartDialDialoguePerformanceFinish.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerHeartDialDialoguePerformanceFinish.cs @@ -2,36 +2,24 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.HeartDialDialoguePerformanceFinish)] +public class MissionHandlerHeartDialDialoguePerformanceFinish : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.HeartDialDialoguePerformanceFinish)] - public class MissionHandlerHeartDialDialoguePerformanceFinish : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) + if (arg is string str && str.StartsWith("HeartDial_")) { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (arg is string str && str.StartsWith("HeartDial_")) + var dialogueId = int.Parse(str.Replace("HeartDial_", "")); + if (info.ParamIntList?.Contains(dialogueId) == true) { - var dialogueId = int.Parse(str.Replace("HeartDial_", "")); - if (info.ParamIntList?.Contains(dialogueId) == true) - { - player.MissionManager!.AddMissionProgress(info.ID, 1); - var curProgress = player.MissionManager!.GetMissionProgress(info.ID); - if (curProgress >= info.Progress) // finish count >= progress, finish mission - { - player.MissionManager!.FinishSubMission(info.ID); - } - } + await player.MissionManager!.AddMissionProgress(info.ID, 1); + var curProgress = player.MissionManager!.GetMissionProgress(info.ID); + if (curProgress >= info.Progress) // finish count >= progress, finish mission + await player.MissionManager!.FinishSubMission(info.ID); } } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerHeartDialScriptListStep.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerHeartDialScriptListStep.cs index 3528a740..1d4d8ff6 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerHeartDialScriptListStep.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerHeartDialScriptListStep.cs @@ -1,44 +1,32 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Database.Scene; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.HeartDialScriptListStep)] +public class MissionHandlerHeartDialScriptListStep : MissionFinishTypeHandler { - [MissionFinishType(Enums.MissionFinishTypeEnum.HeartDialScriptListStep)] - public class MissionHandlerHeartDialScriptListStep : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) + var count = 0; + foreach (var scriptId in info.ParamIntList ?? []) { + HeartDialInfo? dialInfo = null; + player.HeartDialData?.DialList.TryGetValue(scriptId, out dialInfo); + if (dialInfo != null && (int)dialInfo.StepType == info.ParamInt1) count++; } - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) + if (count >= info.Progress) { - var count = 0; - foreach (var scriptId in info.ParamIntList ?? []) - { - HeartDialInfo? dialInfo = null; - player.HeartDialData?.DialList.TryGetValue(scriptId, out dialInfo); - if (dialInfo != null && (int)dialInfo.StepType == info.ParamInt1) - { - count++; - } - } - - if (count >= info.Progress) - { - player.MissionManager?.FinishSubMission(info.ID); - } - else - { - if (player.MissionManager?.GetMissionProgress(info.ID) != count) - player.MissionManager?.SetMissionProgress(info.ID, count); - } + await player.MissionManager!.FinishSubMission(info.ID); + } + else + { + if (player.MissionManager?.GetMissionProgress(info.ID) != count) + await player.MissionManager!.SetMissionProgress(info.ID, count); } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerItemNum.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerItemNum.cs index b1de6820..979775c6 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerItemNum.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerItemNum.cs @@ -1,42 +1,30 @@ using EggLink.DanhengServer.Data.Config; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.ItemNum)] +public class MissionHandlerItemNum : MissionFinishTypeHandler { - [MissionFinishType(Enums.MissionFinishTypeEnum.ItemNum)] - public class MissionHandlerItemNum : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) + var count = 0; + foreach (var itemId in info.ParamIntList ?? []) { + var item = player.InventoryManager?.GetItem(itemId); + if (item != null) count += item.Count; } - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) + if (count == info.Progress) { - var count = 0; - foreach (var itemId in info.ParamIntList ?? []) - { - var item = player.InventoryManager?.GetItem(itemId); - if (item != null) - { - count += item.Count; - } - } - - if (count == info.Progress) - { - player.MissionManager?.FinishSubMission(info.ID); - } - else - { - if (player.MissionManager?.GetMissionProgress(info.ID) != count) - player.MissionManager?.SetMissionProgress(info.ID, count); - } + await player.MissionManager!.FinishSubMission(info.ID); + } + else + { + if (player.MissionManager?.GetMissionProgress(info.ID) != count) + await player.MissionManager!.SetMissionProgress(info.ID, count); } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerKillMonster.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerKillMonster.cs index 03404b20..a91a1734 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerKillMonster.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerKillMonster.cs @@ -2,31 +2,17 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Scene.Entity; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.KillMonster)] +public class MissionHandlerKillMonster : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.KillMonster)] - public class MissionHandlerKillMonster : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (arg is not EntityMonster monster) return; - if (monster.InstID == info.ParamInt2) - { - if (!monster.IsAlive) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } - } + if (arg is not EntityMonster monster) return; + if (monster.InstID == info.ParamInt2) + if (!monster.IsAlive) + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerLeaveFloor.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerLeaveFloor.cs index 4791fef2..b940cf2c 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerLeaveFloor.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerLeaveFloor.cs @@ -2,27 +2,14 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.LeaveFloor)] +public class MissionHandlerLeaveFloor : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.LeaveFloor)] - public class MissionHandlerLeaveFloor : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (player.Data.FloorId != info.ParamInt2) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } + if (player.Data.FloorId != info.ParamInt2) await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerMessagePerformSectionFinish.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerMessagePerformSectionFinish.cs index 014cffc8..851f6719 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerMessagePerformSectionFinish.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerMessagePerformSectionFinish.cs @@ -1,35 +1,19 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.MessagePerformSectionFinish)] +public class MissionHandlerMessagePerformSectionFinish : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.MessagePerformSectionFinish)] - public class MissionHandlerMessagePerformSectionFinish : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - // MOVE TO TASK HANDLER - //player.MessageManager!.AddMessageSection(info.ParamInt1); - } + var data = player.MessageManager!.GetMessageSectionData(info.ParamInt1); + if (data == null) return; - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - var data = player.MessageManager!.GetMessageSectionData(info.ParamInt1); - if (data == null) - { - return; - } - - if (data.Status == Proto.MessageSectionStatus.MessageSectionFinish) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } + if (data.Status == MessageSectionStatus.MessageSectionFinish) + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerMessageSectionFinish.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerMessageSectionFinish.cs index 62ffd277..07a3a297 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerMessageSectionFinish.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerMessageSectionFinish.cs @@ -1,35 +1,19 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.MessageSectionFinish)] +public class MissionHandlerMessageSectionFinish : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.MessageSectionFinish)] - public class MissionHandlerMessageSectionFinish : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - // MOVE TO TASK HANDLER - //player.MessageManager!.AddMessageSection(info.ParamInt1); - } + var data = player.MessageManager!.GetMessageSectionData(info.ParamInt1); + if (data == null) return; - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - var data = player.MessageManager!.GetMessageSectionData(info.ParamInt1); - if (data == null) - { - return; - } - - if (data.Status == Proto.MessageSectionStatus.MessageSectionFinish) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } + if (data.Status == MessageSectionStatus.MessageSectionFinish) + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerNotInFloor.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerNotInFloor.cs index f1ac711f..64689dd9 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerNotInFloor.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerNotInFloor.cs @@ -1,27 +1,14 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.NotInFloor)] +public class MissionHandlerNotInFloor : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.NotInFloor)] - public class MissionHandlerNotInFloor : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (player.Data.FloorId != info.ParamInt1) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } + if (player.Data.FloorId != info.ParamInt1) await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerNotInPlane.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerNotInPlane.cs index 1182d336..218b5535 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerNotInPlane.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerNotInPlane.cs @@ -2,25 +2,15 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.NotInPlane)] +public class MissionHandlerNotInPlane : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.NotInPlane)] - public class MissionHandlerNotInPlane : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (player.Data.PlaneId == info.ParamInt1) return; // not a same scene - player.MissionManager!.FinishSubMission(info.ID); - } + if (player.Data.PlaneId == info.ParamInt1) return; // not a same scene + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerPlayerLevel.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerPlayerLevel.cs index 84d6e20a..eb87c3d8 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerPlayerLevel.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerPlayerLevel.cs @@ -2,24 +2,14 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.PlayerLevel)] +public class MissionHandlerPlayerLevel : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.PlayerLevel)] - public class MissionHandlerPlayerLevel : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - player.MissionManager!.FinishSubMission(info.ID); - } + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerPropState.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerPropState.cs index 6b8e010d..6929a999 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerPropState.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerPropState.cs @@ -1,68 +1,25 @@ -using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Data.Config; +using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Scene.Entity; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.PropState)] +public class MissionHandlerPropState : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.PropState)] - public class MissionHandlerPropState : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - // MOVE TO TASK HANDLER - //var prop = player.SceneInstance?.GetEntitiesInGroup(info.ParamInt1); - //if (prop == null) return; + if (player.SceneInstance?.FloorId != info.LevelFloorID) return; // not a same scene + var prop = player.SceneInstance.GetEntitiesInGroup(info.ParamInt1); + if (prop == null) return; - //foreach (var p in prop) - //{ - // if (p.PropInfo.ID == info.ParamInt2) - // { - // //if (player.SceneInstance?.Excel.WorldID != 101) - // //{ - // // if (p.PropInfo.State == PropStateEnum.Locked && info.SourceState == PropStateEnum.Closed) - // // { - // // GameData.MazePropData.TryGetValue(p.PropInfo.PropID, out var propData); - // // if (propData != null && propData.PropStateList.Contains(PropStateEnum.Closed)) - // // { - // // p.SetState(PropStateEnum.Closed); - // // } - // // else - // // { - // // } - // // } - // //} else - // //{ - // // p.SetState(info.SourceState); - // //} - // GameData.MazePropData.TryGetValue(p.PropInfo.PropID, out var data); - // if (data?.PropStateList.Contains(info.SourceState) == true) - // { - // p.SetState(info.SourceState); - // } - // } - //} - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (player.SceneInstance?.FloorId != info.LevelFloorID) return; // not a same scene - var prop = player.SceneInstance.GetEntitiesInGroup(info.ParamInt1); - if (prop == null) return; - - foreach (var p in prop) - { - if (p.PropInfo.ID == info.ParamInt2 && (int)p.State == info.ParamInt3) - { - player.MissionManager!.FinishSubMission(info.ID); - } - else if (info.ParamInt3 == (int)PropStateEnum.CheckPointDisable || info.ParamInt3 == (int)PropStateEnum.CheckPointEnable) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } - } + foreach (var p in prop) + if (p.PropInfo.ID == info.ParamInt2 && (int)p.State == info.ParamInt3) + await player.MissionManager!.FinishSubMission(info.ID); + else if (info.ParamInt3 == (int)PropStateEnum.CheckPointDisable || + info.ParamInt3 == (int)PropStateEnum.CheckPointEnable) + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerRaidFinishCnt.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerRaidFinishCnt.cs index d025db1f..afbb9cb6 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerRaidFinishCnt.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerRaidFinishCnt.cs @@ -1,36 +1,20 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.RaidFinishCnt)] +public class MissionHandlerRaidFinishCnt : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.RaidFinishCnt)] - public class MissionHandlerRaidFinishCnt : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } + var finishCount = 0; + foreach (var raidId in info.ParamIntList ?? []) + if (player.RaidManager!.GetRaidStatus(raidId) == RaidStatus.Finish) + finishCount++; - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - var finishCount = 0; - foreach (var raidId in info.ParamIntList ?? []) - { - if (player.RaidManager!.GetRaidStatus(raidId) == Proto.RaidStatus.Finish) - { - finishCount++; - } - } - - if (finishCount >= info.Progress) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } + if (finishCount >= info.Progress) await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerSubMissionFinishCnt.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerSubMissionFinishCnt.cs index dea5f3d8..93e8cf7b 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerSubMissionFinishCnt.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerSubMissionFinishCnt.cs @@ -1,39 +1,29 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.Server.Packet.Send.Player; -namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.SubMissionFinishCnt)] +public class MissionHandlerSubMissionFinishCnt : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.SubMissionFinishCnt)] - public class MissionHandlerSubMissionFinishCnt : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) + var finishCount = 0; + foreach (var missionId in info.ParamIntList ?? []) { - // Do nothing + var status = player.MissionManager!.GetSubMissionStatus(missionId); + if (status == MissionPhaseEnum.Finish || status == MissionPhaseEnum.Cancel) finishCount++; } - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) + if (finishCount >= info.Progress) // finish count >= progress, finish mission { - var finishCount = 0; - foreach (var missionId in info.ParamIntList ?? []) - { - var status = player.MissionManager!.GetSubMissionStatus(missionId); - if (status == MissionPhaseEnum.Finish || status == MissionPhaseEnum.Cancel) - { - finishCount++; - } - } - if (finishCount >= info.Progress) // finish count >= progress, finish mission - { - player.MissionManager!.FinishSubMission(info.ID); - } else // update progress - { - if (player.MissionManager!.GetMissionProgress(info.ID) != finishCount) - { - player.MissionManager!.SetMissionProgress(info.ID, finishCount); - } - } + await player.MissionManager!.FinishSubMission(info.ID); + } + else // update progress + { + if (player.MissionManager!.GetMissionProgress(info.ID) != finishCount) + await player.MissionManager!.SetMissionProgress(info.ID, finishCount); } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerTeamLeaderChange.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerTeamLeaderChange.cs index 0e84728c..7b6971c9 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerTeamLeaderChange.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerTeamLeaderChange.cs @@ -2,27 +2,15 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.TeamLeaderChange)] +public class MissionHandlerTeamLeaderChange : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.TeamLeaderChange)] - public class MissionHandlerTeamLeaderChange : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (player.LineupManager!.GetCurLineup()!.LeaderAvatarId == info.ParamInt1) - { - player.MissionManager!.FinishSubMission(info.ID); - } - } + if (player.LineupManager!.GetCurLineup()!.LeaderAvatarId == info.ParamInt1) + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerUseItem.cs b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerUseItem.cs index 91e08169..ce3efca6 100644 --- a/GameServer/Game/Mission/FinishType/Handler/MissionHandlerUseItem.cs +++ b/GameServer/Game/Mission/FinishType/Handler/MissionHandlerUseItem.cs @@ -3,35 +3,19 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler +namespace EggLink.DanhengServer.GameServer.Game.Mission.FinishType.Handler; + +[MissionFinishType(MissionFinishTypeEnum.UseItem)] +public class MissionHandlerUseItem : MissionFinishTypeHandler { - [MissionFinishType(MissionFinishTypeEnum.UseItem)] - public class MissionHandlerUseItem : MissionFinishTypeHandler + public override async ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) { - public override void Init(PlayerInstance player, SubMissionInfo info, object? arg) - { - } + if (arg is ItemData item) + if (info.ParamInt1 == item.ItemId) + await player.MissionManager!.AddMissionProgress(info.ID, 1); - public override void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - if (arg is ItemData item) - { - if (info.ParamInt1 == item.ItemId) - { - player.MissionManager?.AddMissionProgress(info.ID, 1); - } - } - - if (player.MissionManager?.GetMissionProgress(info.ID) >= info.Progress) - { - player.MissionManager?.FinishSubMission(info.ID); - } - } + if (player.MissionManager!.GetMissionProgress(info.ID) >= info.Progress) + await player.MissionManager!.FinishSubMission(info.ID); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/MissionFinishTypeAttribute.cs b/GameServer/Game/Mission/FinishType/MissionFinishTypeAttribute.cs index 8181934a..b342bede 100644 --- a/GameServer/Game/Mission/FinishType/MissionFinishTypeAttribute.cs +++ b/GameServer/Game/Mission/FinishType/MissionFinishTypeAttribute.cs @@ -1,9 +1,8 @@ using EggLink.DanhengServer.Enums; -namespace EggLink.DanhengServer.Game.Mission.FinishType +namespace EggLink.DanhengServer.Game.Mission.FinishType; + +public class MissionFinishTypeAttribute(MissionFinishTypeEnum finishType) : Attribute { - public class MissionFinishTypeAttribute(MissionFinishTypeEnum finishType) : Attribute - { - public MissionFinishTypeEnum FinishType { get; private set; } = finishType; - } -} + public MissionFinishTypeEnum FinishType { get; private set; } = finishType; +} \ No newline at end of file diff --git a/GameServer/Game/Mission/FinishType/MissionFinishTypeHandler.cs b/GameServer/Game/Mission/FinishType/MissionFinishTypeHandler.cs index 452cab71..d4f02da8 100644 --- a/GameServer/Game/Mission/FinishType/MissionFinishTypeHandler.cs +++ b/GameServer/Game/Mission/FinishType/MissionFinishTypeHandler.cs @@ -1,14 +1,9 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Game.Player; -namespace EggLink.DanhengServer.Game.Mission.FinishType -{ - public abstract class MissionFinishTypeHandler - { - public abstract void Init(PlayerInstance player, SubMissionInfo info, object? arg); +namespace EggLink.DanhengServer.Game.Mission.FinishType; - public virtual void HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg) - { - } - } -} +public abstract class MissionFinishTypeHandler +{ + public abstract ValueTask HandleFinishType(PlayerInstance player, SubMissionInfo info, object? arg); +} \ No newline at end of file diff --git a/GameServer/Game/Mission/MissionManager.cs b/GameServer/Game/Mission/MissionManager.cs index 7903185b..bdd08170 100644 --- a/GameServer/Game/Mission/MissionManager.cs +++ b/GameServer/Game/Mission/MissionManager.cs @@ -1,7 +1,7 @@ -using EggLink.DanhengServer.Data; +using System.Reflection; +using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Database.Inventory; -using EggLink.DanhengServer.Database.Mission; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Enums.Item; using EggLink.DanhengServer.Game.Mission.FinishAction; @@ -9,686 +9,610 @@ using EggLink.DanhengServer.Game.Mission.FinishType; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; using EggLink.DanhengServer.Plugin.Event; -using EggLink.DanhengServer.Server.Packet.Send.Lineup; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; using EggLink.DanhengServer.Server.Packet.Send.Player; using EggLink.DanhengServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Util; -using System.Reflection; +using MissionData = EggLink.DanhengServer.Database.Mission.MissionData; -namespace EggLink.DanhengServer.Game.Mission +namespace EggLink.DanhengServer.Game.Mission; + +public class MissionManager : BasePlayerManager { - public class MissionManager : BasePlayerManager + #region Initializer & Properties + + public MissionData Data { get; set; } + public Dictionary ActionHandlers = []; + public Dictionary FinishTypeHandlers = []; + + public readonly List SkipSubMissionList = []; // bug + + public MissionManager(PlayerInstance player) : base(player) { - #region Initializer & Properties + Data = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); - public MissionData Data { get; set; } - public Dictionary ActionHandlers = []; - public Dictionary FinishTypeHandlers = []; - - public readonly List SkipSubMissionList = []; // bug - - public MissionManager(PlayerInstance player) : base(player) + var types = Assembly.GetExecutingAssembly().GetTypes(); + foreach (var type in types) { - Data = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); - - var types = Assembly.GetExecutingAssembly().GetTypes(); - foreach (var type in types) + var attr = type.GetCustomAttribute(); + if (attr != null) { - var attr = type.GetCustomAttribute(); - if (attr != null) - { - var handler = (MissionFinishActionHandler)Activator.CreateInstance(type, null)!; - ActionHandlers.Add(attr.FinishAction, handler); - } - var attr2 = type.GetCustomAttribute(); - if (attr2 != null) - { - var handler = (MissionFinishTypeHandler)Activator.CreateInstance(type, null)!; - FinishTypeHandlers.Add(attr2.FinishType, handler); - } + var handler = (MissionFinishActionHandler)Activator.CreateInstance(type, null)!; + ActionHandlers.Add(attr.FinishAction, handler); + } + + var attr2 = type.GetCustomAttribute(); + if (attr2 != null) + { + var handler = (MissionFinishTypeHandler)Activator.CreateInstance(type, null)!; + FinishTypeHandlers.Add(attr2.FinishType, handler); } } + } - #endregion + #endregion - #region Mission Actions + #region Mission Actions - public List AcceptMainMission(int missionId, bool sendPacket = true) + public async ValueTask> AcceptMainMission(int missionId, bool sendPacket = true) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return []; + if (Data.GetMainMissionStatus(missionId) != MissionPhaseEnum.None) return []; // already accepted + // Get entry sub mission + GameData.MainMissionData.TryGetValue(missionId, out var mission); + if (mission == null) return []; + + Data.SetMainMissionStatus(missionId, MissionPhaseEnum.Accept); + + var list = new List(); + mission.MissionInfo?.StartSubMissionList.ForEach(async i => list.Add(await AcceptSubMission(i, sendPacket))); + if (missionId == 4030001 || missionId == 4030002) { - if (!ConfigManager.Config.ServerOption.EnableMission) return []; - if (Data.GetMainMissionStatus(missionId) != MissionPhaseEnum.None) return []; // already accepted - // Get entry sub mission - GameData.MainMissionData.TryGetValue(missionId, out var mission); - if (mission == null) return []; - - Data.SetMainMissionStatus(missionId, MissionPhaseEnum.Accept); - - var list = new List(); - mission.MissionInfo?.StartSubMissionList.ForEach(i => list.Add(AcceptSubMission(i, sendPacket))); - if (missionId == 4030001 || missionId == 4030002) - { - // skip not implemented - mission.MissionInfo?.SubMissionList.ForEach(x=> AcceptSubMission(x.ID)); - mission.MissionInfo?.SubMissionList.ForEach(x => FinishSubMission(x.ID)); - } - - if (missionId == 1000400) - { - Player.AddAvatar(1003); - Player.LineupManager!.AddAvatarToCurTeam(1003); - } - - return list; + // skip not implemented + mission.MissionInfo?.SubMissionList.ForEach(async x => await AcceptSubMission(x.ID)); + mission.MissionInfo?.SubMissionList.ForEach(async x => await FinishSubMission(x.ID)); } - public Proto.MissionSync AcceptMainMissionByCondition(bool sendPacket = true) + if (missionId == 1000400) { - var sync = new Proto.MissionSync(); - foreach (var nextMission in GameData.MainMissionData.Values) - { - if (!nextMission.IsEqual(Data)) continue; - if (Data.GetMainMissionStatus(nextMission.MainMissionID) != MissionPhaseEnum.None) continue; // already accepted - var res = AcceptMainMission(nextMission.MainMissionID, sendPacket); - foreach (var subMission in res) - { - if (subMission != null) - { - sync.MissionList.AddRange(subMission.MissionList); - } - } - } - - return sync; + await Player.AddAvatar(1003); + await Player.LineupManager!.AddAvatarToCurTeam(1003); } - public List ReAcceptMainMission(int missionId, bool sendPacket = true) + return list; + } + + public async ValueTask AcceptMainMissionByCondition(bool sendPacket = true) + { + var sync = new MissionSync(); + foreach (var nextMission in GameData.MainMissionData.Values) { - if (!ConfigManager.Config.ServerOption.EnableMission) return []; - - GameData.MainMissionData.TryGetValue(missionId, out var mission); - if (mission == null) return []; - Proto.MissionSync sync = new(); - - foreach (var subMission in mission.SubMissionIds) - { - if (Data.GetSubMissionStatus(subMission) == MissionPhaseEnum.Finish || Data.GetSubMissionStatus(subMission) == MissionPhaseEnum.Accept) - { - sync.MissionList.Add(new Proto.Mission() - { - Id = (uint)subMission, - Status = Proto.MissionStatus.MissionNone, - }); - } - } - - foreach (var subMission in mission.SubMissionIds) - { - Data.SetSubMissionStatus(subMission, MissionPhaseEnum.None); // reset - } - - Data.SetMainMissionStatus(missionId, MissionPhaseEnum.None); // reset - Player.SendPacket(new PacketPlayerSyncScNotify(sync)); - - return AcceptMainMission(missionId, sendPacket); + if (!nextMission.IsEqual(Data)) continue; + if (Data.GetMainMissionStatus(nextMission.MainMissionID) != MissionPhaseEnum.None) + continue; // already accepted + var res = await AcceptMainMission(nextMission.MainMissionID, sendPacket); + foreach (var subMission in res) + if (subMission != null) + sync.MissionList.AddRange(subMission.MissionList); } - public void RemoveMainMission(int missionId) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return; - Data.SetMainMissionStatus(missionId, MissionPhaseEnum.None); + return sync; + } - GameData.MainMissionData.TryGetValue(missionId, out var mission); - if (mission == null) return; + public async ValueTask> ReAcceptMainMission(int missionId, bool sendPacket = true) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return []; - Proto.MissionSync sync = new(); + GameData.MainMissionData.TryGetValue(missionId, out var mission); + if (mission == null) return []; + MissionSync sync = new(); - foreach (var subMission in mission.SubMissionIds) - { - Data.SetSubMissionStatus(subMission, MissionPhaseEnum.None); - SetMissionProgress(subMission, 0); - sync.MissionList.Add(new Proto.Mission() + foreach (var subMission in mission.SubMissionIds) + if (Data.GetSubMissionStatus(subMission) == MissionPhaseEnum.Finish || + Data.GetSubMissionStatus(subMission) == MissionPhaseEnum.Accept) + sync.MissionList.Add(new Proto.Mission { Id = (uint)subMission, - Status = Proto.MissionStatus.MissionNone, + Status = MissionStatus.MissionNone }); - } - Player.SendPacket(new PacketPlayerSyncScNotify(sync)); - } + foreach (var subMission in + mission.SubMissionIds) Data.SetSubMissionStatus(subMission, MissionPhaseEnum.None); // reset - public void AcceptSubMission(int missionId) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return; - AcceptSubMission(missionId, true); - } + Data.SetMainMissionStatus(missionId, MissionPhaseEnum.None); // reset + await Player.SendPacket(new PacketPlayerSyncScNotify(sync)); - public Proto.MissionSync? AcceptSubMission(int missionId, bool sendPacket, bool doFinishTypeAction = true) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return null; - GameData.SubMissionData.TryGetValue(missionId, out var mission); - if (mission == null) return null; - if (Data.GetSubMissionStatus(missionId) != MissionPhaseEnum.None) return null; // already accepted - - Data.SetSubMissionStatus(missionId, MissionPhaseEnum.Accept); - - var sync = new Proto.MissionSync(); - sync.MissionList.Add(new Proto.Mission() - { - Id = (uint)missionId, - Status = Proto.MissionStatus.MissionDoing, - }); - - DatabaseHelper.Instance?.UpdateInstance(Data); - if (sendPacket) Player.SendPacket(new PacketPlayerSyncScNotify(sync)); - Player.SceneInstance!.SyncGroupInfo(); - if (mission.SubMissionInfo != null) - { - try - { - FinishTypeHandlers.TryGetValue(mission.SubMissionInfo.FinishType, out var handler); - handler?.Init(Player, mission.SubMissionInfo, null); - if (doFinishTypeAction) - handler?.HandleFinishType(Player, mission.SubMissionInfo, null); - } catch - { - } - } - - if (SkipSubMissionList.Contains(missionId)) - { - //FinishSubMission(missionId); - } - - if (mission.SubMissionInfo?.LevelFloorID == Player.SceneInstance?.FloorId) - { - if (mission.SubMissionInfo?.GroupIDList != null) - { - foreach (var group in mission.SubMissionInfo.GroupIDList) - { - Player.SceneInstance?.EntityLoader?.LoadGroup(group); - } - } - } - - // TODO: Mission Task - Player.TaskManager?.MissionTaskTrigger?.TriggerMissionTask(missionId); - - return sync; - } - - public void FinishMainMission(int missionId) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return; - if (!GameData.MainMissionData.TryGetValue(missionId, out var mainMission)) return; - if (Data.GetMainMissionStatus(missionId) != MissionPhaseEnum.Accept) return; - Data.SetMainMissionStatus(missionId, MissionPhaseEnum.Finish); - var sync = new Proto.MissionSync(); - sync.MainMissionIdList.Add((uint)missionId); - // get next main mission - foreach (var mission in mainMission.SubMissionIds) - { - if (GetSubMissionStatus(mission) != MissionPhaseEnum.Finish) - { - if (Data.GetSubMissionStatus(mission) != MissionPhaseEnum.Finish) - { - Data.SetSubMissionStatus(mission, MissionPhaseEnum.Finish); - sync.MissionList.Add(new Proto.Mission() - { - Id = (uint)mission, - Status = Proto.MissionStatus.MissionFinish, - }); - } - } - } - - var mainSync = AcceptMainMissionByCondition(false); - sync.MissionList.AddRange(mainSync.MissionList); - - Player.SendPacket(new PacketPlayerSyncScNotify(sync)); - Player.SendPacket(new PacketStartFinishMainMissionScNotify(missionId)); - HandleMissionReward(missionId); - HandleFinishType(MissionFinishTypeEnum.FinishMission); - - Player.RaidManager!.CheckIfLeaveRaid(); - - PluginEvent.InvokeOnPlayerFinishMainMission(Player, missionId); - } - - public void FinishSubMission(int missionId) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return; - GameData.SubMissionData.TryGetValue(missionId, out var subMission); - if (subMission == null) return; - var mainMissionId = subMission.MainMissionID; - if (Data.GetSubMissionStatus(missionId) != MissionPhaseEnum.Accept) return; // not accepted - GameData.MainMissionData.TryGetValue(mainMissionId, out var mainMission); // get main mission - if (mainMission == null) return; - Data.SetSubMissionStatus(missionId, MissionPhaseEnum.Finish); // set finish - - SetMissionProgress(missionId, subMission.SubMissionInfo?.Progress ?? 1); - - var sync = new Proto.MissionSync(); - sync.MissionList.Add(new Proto.Mission() - { - Id = (uint)missionId, - Status = Proto.MissionStatus.MissionFinish, - Progress = (uint)(subMission.SubMissionInfo?.Progress ?? 1) - }); - - var subMissionInfo = subMission?.SubMissionInfo; - - // get next sub mission - foreach (var nextMission in mainMission.MissionInfo?.SubMissionList ?? []) - { - if (nextMission.TakeType != SubMissionTakeTypeEnum.AnySequence && nextMission.TakeType != SubMissionTakeTypeEnum.MultiSequence) continue; - bool canAccept = nextMission.TakeType == SubMissionTakeTypeEnum.MultiSequence; // mean and operation - foreach (var id in nextMission.TakeParamIntList ?? []) - { - if (GetSubMissionStatus(id) != MissionPhaseEnum.Finish && nextMission.TakeType == SubMissionTakeTypeEnum.MultiSequence) - { - canAccept = false; - break; - } - else if (GetSubMissionStatus(id) == MissionPhaseEnum.Finish && nextMission.TakeType == SubMissionTakeTypeEnum.AnySequence) // or operation - { - canAccept = true; - break; - } - } - if (canAccept) - { - var s = AcceptSubMission(nextMission.ID, false, false); - if (s != null) - { - sync.MissionList.Add(new Proto.Mission() - { - Id = (uint)nextMission.ID, - Status = Proto.MissionStatus.MissionDoing, - }); - } - } - } - Player.SendPacket(new PacketPlayerSyncScNotify(sync)); - Player.SendPacket(new PacketStartFinishSubMissionScNotify(missionId)); - - if (mainMission.MissionInfo != null) - HandleFinishAction(mainMission.MissionInfo, missionId); - - // Get if it should finish main mission - // get current main mission - var shouldFinish = true; - mainMission.MissionInfo?.FinishSubMissionList.ForEach(id => - { - if (GetSubMissionStatus(id) != MissionPhaseEnum.Finish) - { - shouldFinish = false; - } - }); - - foreach (var nextMission in GetRunningSubMissionList()) - { - FinishTypeHandlers.TryGetValue(nextMission.FinishType, out var handler); - handler?.HandleFinishType(Player, nextMission, null); - } - - if (shouldFinish) - { - FinishMainMission(mainMissionId); - } - - if (missionId == 101140201) - { - //Player.ChangeHeroBasicType(Enums.Avatar.HeroBasicTypeEnum.Knight); - var list = Player.LineupManager!.GetCurLineup()!.BaseAvatars!.Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId).ToList(); - list[list.IndexOf(8001)] = Player.Data.CurrentGender == Proto.Gender.Man ? 1008003 : 1008004; - Player.LineupManager!.SetExtraLineup(Proto.ExtraLineupType.LineupHeliobus, list); - } - - if (missionId == 103040103) - { - Player.SendPacket(new PacketHeartDialScriptChangeScNotify(Proto.HeartDialUnlockStatus.UnlockSingle)); - } - - if (missionId == 103040104) - { - Player.SendPacket(new PacketHeartDialScriptChangeScNotify(Proto.HeartDialUnlockStatus.UnlockAll)); - } - - // handle reward - HandleSubMissionReward(missionId); - //Player.StoryLineManager!.CheckIfEnterStoryLine(); - //Player.StoryLineManager!.CheckIfFinishStoryLine(); - - PluginEvent.InvokeOnPlayerFinishSubMission(Player, missionId); - } - - public void HandleFinishAction(Data.Config.MissionInfo info, int subMissionId) - { - var subMission = info.SubMissionList.Find(x => x.ID == subMissionId); - if (subMission == null) return; - - foreach (var action in subMission.FinishActionList ?? []) - { - HandleFinishAction(action); - } - } - - public void HandleFinishAction(Data.Config.FinishActionInfo actionInfo) - { - ActionHandlers.TryGetValue(actionInfo.FinishActionType, out var handler); - handler?.OnHandle(actionInfo.FinishActionPara, actionInfo.FinishActionParaString, Player); - } - - public void HandleMissionReward(int mainMissionId) - { - GameData.MainMissionData.TryGetValue(mainMissionId, out var mainMission); - if (mainMission == null) return; - GameData.RewardDataData.TryGetValue(mainMission.RewardID, out var reward); - var ItemList = new Proto.ItemList(); - reward?.GetItems().ForEach(i => - { - GameData.ItemConfigData.TryGetValue(i.Item1, out var item); - var res = Player.InventoryManager!.AddItem(i.Item1, i.Item2, item?.ItemMainType == ItemMainTypeEnum.AvatarCard); - if (res != null) - { - ItemList.ItemList_.Add(res.ToProto()); - } - }); - - mainMission.SubRewardList.ForEach(i => - { - GameData.RewardDataData.TryGetValue(i, out var reward); - reward?.GetItems().ForEach(j => - { - GameData.ItemConfigData.TryGetValue(j.Item1, out var item); - var res = Player.InventoryManager!.AddItem(j.Item1, j.Item2, item?.ItemMainType == ItemMainTypeEnum.AvatarCard); - if (res != null) - { - ItemList.ItemList_.Add(res.ToProto()); - } - }); - }); - - Player.SendPacket(new PacketMissionRewardScNotify(mainMissionId, 0, ItemList)); - Player.SendPacket(new PacketScenePlaneEventScNotify(ItemList)); - } - - public void HandleSubMissionReward(int subMissionId) - { - GameData.SubMissionData.TryGetValue(subMissionId, out var subMission); - if (subMission == null) return; - GameData.RewardDataData.TryGetValue(subMission.SubMissionInfo?.SubRewardID ?? 0, out var reward); - var ItemList = new Proto.ItemList(); - reward?.GetItems().ForEach(i => - { - var res = Player.InventoryManager!.AddItem(i.Item1, i.Item2, false); - if (res != null) - { - ItemList.ItemList_.Add(res.ToProto()); - } - }); - - Player.SendPacket(new PacketMissionRewardScNotify(0, subMissionId, ItemList)); - Player.SendPacket(new PacketScenePlaneEventScNotify(ItemList)); - } - - public void HandleFinishType(MissionFinishTypeEnum finishType, object? arg = null) - { - FinishTypeHandlers.TryGetValue(finishType, out var handler); - foreach (var mission in GetRunningSubMissionList()) - { - if (mission.FinishType == finishType) - { - handler?.HandleFinishType(Player, mission, arg); - } - } - } - - public void HandleTalkStr(string talkString) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return; - - foreach (var mission in GetRunningSubMissionList()) - { - if (mission.FinishType == MissionFinishTypeEnum.Talk) - { - if (mission.ParamStr1 == talkString) - { - FinishSubMission(mission.ID); - } - } - } - } - - public void HandleCustomValue(List values, int missionId) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return; - - GameData.SubMissionData.TryGetValue(missionId, out var subMission); - if (subMission == null) return; - var mainMissionId = subMission.MainMissionID; - GameData.MainMissionData.TryGetValue(mainMissionId, out var mainMission); - if (mainMission == null) return; - - foreach (var mission in mainMission?.MissionInfo?.SubMissionList ?? []) - { - if (mission.TakeType == SubMissionTakeTypeEnum.CustomValue) - { - int index = 0; - bool accept = true; - foreach (var customValue in mission.TakeParamIntList ?? []) - { - if (customValue == 0 && index == 0) continue; // skip 0 - var valueInst = values.Find(x => x.Index == index); - if (valueInst == null) continue; - if (valueInst.CustomValue != customValue) - { - accept = false; - break; - } - } - - if (accept) - { - AcceptSubMission(mission.ID); - } - } - } - } - - public void AddMissionProgress(int missionId, int progress) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return; - - Data.SubMissionProgressDict.TryGetValue(missionId, out var currentProgress); - Data.SubMissionProgressDict[missionId] = currentProgress + progress; - GameData.SubMissionData.TryGetValue(missionId, out var subMission); - if (subMission == null) return; - - if ((currentProgress + progress) >= (subMission.SubMissionInfo?.Progress ?? 1)) - { - return; - } - - var sync = new Proto.MissionSync(); - sync.MissionList.Add(new Proto.Mission() - { - Id = (uint)missionId, - Progress = (uint)(currentProgress + progress), - }); - - Player.SendPacket(new PacketPlayerSyncScNotify(sync)); - } - - public void SetMissionProgress(int missionId, int progress) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return; - - Data.SubMissionProgressDict[missionId] = progress; - GameData.SubMissionData.TryGetValue(missionId, out var subMission); - if (subMission == null) return; - - if (progress >= (subMission.SubMissionInfo?.Progress ?? 1)) - { - return; - } - - var sync = new Proto.MissionSync(); - sync.MissionList.Add(new Proto.Mission() - { - Id = (uint)missionId, - Progress = (uint)progress, - }); - - Player.SendPacket(new PacketPlayerSyncScNotify(sync)); - } - - #endregion - - #region Mission Status - - public MissionPhaseEnum GetMainMissionStatus(int missionId) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return MissionPhaseEnum.Finish; - - return Data.GetMainMissionStatus(missionId); - } - - public MissionPhaseEnum GetSubMissionStatus(int missionId) - { - if (!ConfigManager.Config.ServerOption.EnableMission) return MissionPhaseEnum.Finish; - - return Data.GetSubMissionStatus(missionId); - } - - public Data.Config.SubMissionInfo? GetSubMissionInfo(int missionId) - { - GameData.SubMissionData.TryGetValue(missionId, out var subMission); - if (subMission == null) return null; - return subMission.SubMissionInfo; - } - - public List GetRunningSubMissionIdList() - { - if (!ConfigManager.Config.ServerOption.EnableMission) return []; - - var list = new List(); - foreach (var id in Data.RunningSubMissionIds) - { - list.Add(id); - } - return list; - } - - public List GetRunningSubMissionList() - { - if (!ConfigManager.Config.ServerOption.EnableMission) return []; - - var list = new List(); - foreach (var id in Data.RunningSubMissionIds) - { - GameData.SubMissionData.TryGetValue(id, out var mission); - if (mission != null && mission.SubMissionInfo != null) - { - list.Add(mission.SubMissionInfo); - } - } - return list; - } - - public int GetMissionProgress(int missionId) - { - GameData.SubMissionData.TryGetValue(missionId, out var subMission); - if (!ConfigManager.Config.ServerOption.EnableMission) return subMission?.SubMissionInfo?.Progress ?? 0; - - Data.SubMissionProgressDict.TryGetValue(missionId, out var progress); - return progress; - } - - #endregion - - #region Handlers - - public void OnBattleFinish(Proto.PVEBattleResultCsReq req) - { - foreach (var mission in GetRunningSubMissionIdList()) - { - var subMission = GetSubMissionInfo(mission); - if (subMission != null && subMission.FinishType == MissionFinishTypeEnum.StageWin && req.EndStatus == Proto.BattleEndStatus.BattleEndWin) // TODO: Move to handler - { - if (req.StageId.ToString().StartsWith(subMission.ParamInt1.ToString())) - { - FinishSubMission(mission); - } - } - } - } - - public void OnPlayerInteractWithProp() - { - foreach (var id in GetRunningSubMissionIdList()) - { - if (GetSubMissionInfo(id)?.FinishType == MissionFinishTypeEnum.PropState) - { - FinishTypeHandlers.TryGetValue(MissionFinishTypeEnum.PropState, out var handler); - handler?.HandleFinishType(Player, GetSubMissionInfo(id)!, null); - } - } - } - - public void OnPlayerChangeScene() - { - foreach (var id in GetRunningSubMissionIdList()) - { - var info = GetSubMissionInfo(id); - if (info == null) continue; - - if (info.LevelFloorID == Player.SceneInstance?.FloorId) - { - if (info.GroupIDList == null) continue; - foreach (var group in info.GroupIDList) - { - Player.SceneInstance.EntityLoader!.LoadGroup(group, false); - } - } - } - } - - public void OnLoadScene(Proto.SceneInfo info) - { - foreach (var mainMission in GameData.MainMissionData.Values) - { - foreach (var subMission in mainMission.MissionInfo?.SubMissionList ?? []) - { - if (subMission.LevelFloorID == info.FloorId) - { - info.SceneMissionInfo.SceneSubMissionList.Add(new Proto.Mission() - { - Id = (uint)subMission.ID, - Status = GetSubMissionStatus(subMission.ID).ToProto(), - Progress = (uint)GetMissionProgress(subMission.ID), - }); - } - } - - foreach (var subMission in mainMission.MissionInfo?.SubMissionList ?? []) - { - if (subMission.LevelFloorID == info.FloorId) - { - if (GetMainMissionStatus(mainMission.MainMissionID) == MissionPhaseEnum.Finish) - { - info.SceneMissionInfo.MainMissionIdList.Add((uint)mainMission.MainMissionID); - } else if (GetMainMissionStatus(mainMission.MainMissionID) == MissionPhaseEnum.Accept) - { - info.SceneMissionInfo.AcceptMainMissionIdList.Add((uint)mainMission.MainMissionID); - } - break; // only one - } - } - } - } - - #endregion + return await AcceptMainMission(missionId, sendPacket); } -} + + public async ValueTask RemoveMainMission(int missionId) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return; + Data.SetMainMissionStatus(missionId, MissionPhaseEnum.None); + + GameData.MainMissionData.TryGetValue(missionId, out var mission); + if (mission == null) return; + + MissionSync sync = new(); + + foreach (var subMission in mission.SubMissionIds) + { + Data.SetSubMissionStatus(subMission, MissionPhaseEnum.None); + await SetMissionProgress(subMission, 0); + sync.MissionList.Add(new Proto.Mission + { + Id = (uint)subMission, + Status = MissionStatus.MissionNone + }); + } + + await Player.SendPacket(new PacketPlayerSyncScNotify(sync)); + } + + public async ValueTask AcceptSubMission(int missionId) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return; + await AcceptSubMission(missionId, true); + } + + public async ValueTask AcceptSubMission(int missionId, bool sendPacket, + bool doFinishTypeAction = true) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return null; + GameData.SubMissionData.TryGetValue(missionId, out var mission); + if (mission == null) return null; + if (Data.GetSubMissionStatus(missionId) != MissionPhaseEnum.None) return null; // already accepted + + Data.SetSubMissionStatus(missionId, MissionPhaseEnum.Accept); + + var sync = new MissionSync(); + sync.MissionList.Add(new Proto.Mission + { + Id = (uint)missionId, + Status = MissionStatus.MissionDoing + }); + + DatabaseHelper.Instance?.UpdateInstance(Data); + if (sendPacket) await Player.SendPacket(new PacketPlayerSyncScNotify(sync)); + Player.SceneInstance!.SyncGroupInfo(); + if (mission.SubMissionInfo != null) + try + { + FinishTypeHandlers.TryGetValue(mission.SubMissionInfo.FinishType, out var handler); + if (doFinishTypeAction) + if (handler != null) + await handler.HandleFinishType(Player, mission.SubMissionInfo, null); + } + catch + { + } + + if (SkipSubMissionList.Contains(missionId)) + { + //FinishSubMission(missionId); + } + + if (mission.SubMissionInfo?.LevelFloorID == Player.SceneInstance?.FloorId) + if (mission.SubMissionInfo?.GroupIDList != null) + foreach (var group in mission.SubMissionInfo.GroupIDList) + await Player.SceneInstance!.EntityLoader!.LoadGroup(group); + + // TODO: Mission Task + Player.TaskManager?.MissionTaskTrigger?.TriggerMissionTask(missionId); + + return sync; + } + + public async ValueTask FinishMainMission(int missionId) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return; + if (!GameData.MainMissionData.TryGetValue(missionId, out var mainMission)) return; + if (Data.GetMainMissionStatus(missionId) != MissionPhaseEnum.Accept) return; + Data.SetMainMissionStatus(missionId, MissionPhaseEnum.Finish); + var sync = new MissionSync(); + sync.MainMissionIdList.Add((uint)missionId); + // get next main mission + foreach (var mission in mainMission.SubMissionIds) + if (GetSubMissionStatus(mission) != MissionPhaseEnum.Finish) + if (Data.GetSubMissionStatus(mission) != MissionPhaseEnum.Finish) + { + Data.SetSubMissionStatus(mission, MissionPhaseEnum.Finish); + sync.MissionList.Add(new Proto.Mission + { + Id = (uint)mission, + Status = MissionStatus.MissionFinish + }); + } + + var mainSync = await AcceptMainMissionByCondition(false); + sync.MissionList.AddRange(mainSync.MissionList); + + await Player.SendPacket(new PacketPlayerSyncScNotify(sync)); + await Player.SendPacket(new PacketStartFinishMainMissionScNotify(missionId)); + await HandleMissionReward(missionId); + await HandleFinishType(MissionFinishTypeEnum.FinishMission); + + await Player.RaidManager!.CheckIfLeaveRaid(); + + PluginEvent.InvokeOnPlayerFinishMainMission(Player, missionId); + } + + public async ValueTask FinishSubMission(int missionId) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return; + GameData.SubMissionData.TryGetValue(missionId, out var subMission); + if (subMission == null) return; + var mainMissionId = subMission.MainMissionID; + if (Data.GetSubMissionStatus(missionId) != MissionPhaseEnum.Accept) return; // not accepted + GameData.MainMissionData.TryGetValue(mainMissionId, out var mainMission); // get main mission + if (mainMission == null) return; + Data.SetSubMissionStatus(missionId, MissionPhaseEnum.Finish); // set finish + + await SetMissionProgress(missionId, subMission.SubMissionInfo?.Progress ?? 1); + + var sync = new MissionSync(); + sync.MissionList.Add(new Proto.Mission + { + Id = (uint)missionId, + Status = MissionStatus.MissionFinish, + Progress = (uint)(subMission.SubMissionInfo?.Progress ?? 1) + }); + + var subMissionInfo = subMission?.SubMissionInfo; + + // get next sub mission + foreach (var nextMission in mainMission.MissionInfo?.SubMissionList ?? []) + { + if (nextMission.TakeType != SubMissionTakeTypeEnum.AnySequence && + nextMission.TakeType != SubMissionTakeTypeEnum.MultiSequence) continue; + var canAccept = nextMission.TakeType == SubMissionTakeTypeEnum.MultiSequence; // mean and operation + foreach (var id in nextMission.TakeParamIntList ?? []) + if (GetSubMissionStatus(id) != MissionPhaseEnum.Finish && + nextMission.TakeType == SubMissionTakeTypeEnum.MultiSequence) + { + canAccept = false; + break; + } + else if (GetSubMissionStatus(id) == MissionPhaseEnum.Finish && + nextMission.TakeType == SubMissionTakeTypeEnum.AnySequence) // or operation + { + canAccept = true; + break; + } + + if (canAccept) + { + var s = await AcceptSubMission(nextMission.ID, false, false); + if (s != null) + sync.MissionList.Add(new Proto.Mission + { + Id = (uint)nextMission.ID, + Status = MissionStatus.MissionDoing + }); + } + } + + await Player.SendPacket(new PacketPlayerSyncScNotify(sync)); + await Player.SendPacket(new PacketStartFinishSubMissionScNotify(missionId)); + + if (mainMission.MissionInfo != null) + await HandleFinishAction(mainMission.MissionInfo, missionId); + + // Get if it should finish main mission + // get current main mission + var shouldFinish = true; + mainMission.MissionInfo?.FinishSubMissionList.ForEach(id => + { + if (GetSubMissionStatus(id) != MissionPhaseEnum.Finish) shouldFinish = false; + }); + + foreach (var nextMission in GetRunningSubMissionList()) + { + FinishTypeHandlers.TryGetValue(nextMission.FinishType, out var handler); + if (handler != null) await handler.HandleFinishType(Player, nextMission, null); + } + + if (shouldFinish) await FinishMainMission(mainMissionId); + + if (missionId == 101140201) + { + //Player.ChangeHeroBasicType(Enums.Avatar.HeroBasicTypeEnum.Knight); + var list = Player.LineupManager!.GetCurLineup()!.BaseAvatars! + .Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId).ToList(); + list[list.IndexOf(8001)] = Player.Data.CurrentGender == Gender.Man ? 1008003 : 1008004; + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, list); + } + + if (missionId == 103040103) + await Player.SendPacket(new PacketHeartDialScriptChangeScNotify(HeartDialUnlockStatus.UnlockSingle)); + + if (missionId == 103040104) + await Player.SendPacket(new PacketHeartDialScriptChangeScNotify(HeartDialUnlockStatus.UnlockAll)); + + // handle reward + await HandleSubMissionReward(missionId); + //Player.StoryLineManager!.CheckIfEnterStoryLine(); + //Player.StoryLineManager!.CheckIfFinishStoryLine(); + + PluginEvent.InvokeOnPlayerFinishSubMission(Player, missionId); + } + + public async ValueTask HandleFinishAction(MissionInfo info, int subMissionId) + { + var subMission = info.SubMissionList.Find(x => x.ID == subMissionId); + if (subMission == null) return; + + foreach (var action in subMission.FinishActionList ?? []) await HandleFinishAction(action); + } + + public async ValueTask HandleFinishAction(FinishActionInfo actionInfo) + { + ActionHandlers.TryGetValue(actionInfo.FinishActionType, out var handler); + if (handler != null) + await handler.OnHandle(actionInfo.FinishActionPara, actionInfo.FinishActionParaString, Player); + } + + public async ValueTask HandleMissionReward(int mainMissionId) + { + GameData.MainMissionData.TryGetValue(mainMissionId, out var mainMission); + if (mainMission == null) return; + GameData.RewardDataData.TryGetValue(mainMission.RewardID, out var reward); + var ItemList = new ItemList(); + reward?.GetItems().ForEach(async i => + { + GameData.ItemConfigData.TryGetValue(i.Item1, out var item); + var res = await Player.InventoryManager!.AddItem(i.Item1, i.Item2, + item?.ItemMainType == ItemMainTypeEnum.AvatarCard); + if (res != null) ItemList.ItemList_.Add(res.ToProto()); + }); + + mainMission.SubRewardList.ForEach(i => + { + GameData.RewardDataData.TryGetValue(i, out var reward); + reward?.GetItems().ForEach(async j => + { + GameData.ItemConfigData.TryGetValue(j.Item1, out var item); + var res = await Player.InventoryManager!.AddItem(j.Item1, j.Item2, + item?.ItemMainType == ItemMainTypeEnum.AvatarCard); + if (res != null) ItemList.ItemList_.Add(res.ToProto()); + }); + }); + + await Player.SendPacket(new PacketMissionRewardScNotify(mainMissionId, 0, ItemList)); + await Player.SendPacket(new PacketScenePlaneEventScNotify(ItemList)); + } + + public async ValueTask HandleSubMissionReward(int subMissionId) + { + GameData.SubMissionData.TryGetValue(subMissionId, out var subMission); + if (subMission == null) return; + GameData.RewardDataData.TryGetValue(subMission.SubMissionInfo?.SubRewardID ?? 0, out var reward); + var ItemList = new ItemList(); + reward?.GetItems().ForEach(async i => + { + var res = await Player.InventoryManager!.AddItem(i.Item1, i.Item2, false); + if (res != null) ItemList.ItemList_.Add(res.ToProto()); + }); + + await Player.SendPacket(new PacketMissionRewardScNotify(0, subMissionId, ItemList)); + await Player.SendPacket(new PacketScenePlaneEventScNotify(ItemList)); + } + + public async ValueTask HandleFinishType(MissionFinishTypeEnum finishType, object? arg = null) + { + FinishTypeHandlers.TryGetValue(finishType, out var handler); + foreach (var mission in GetRunningSubMissionList()) + if (mission.FinishType == finishType) + if (handler != null) + await handler.HandleFinishType(Player, mission, arg); + } + + public async ValueTask HandleTalkStr(string talkString) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return; + + foreach (var mission in GetRunningSubMissionList()) + if (mission.FinishType == MissionFinishTypeEnum.Talk) + if (mission.ParamStr1 == talkString) + await FinishSubMission(mission.ID); + } + + public async ValueTask HandleCustomValue(List values, int missionId) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return; + + GameData.SubMissionData.TryGetValue(missionId, out var subMission); + if (subMission == null) return; + var mainMissionId = subMission.MainMissionID; + GameData.MainMissionData.TryGetValue(mainMissionId, out var mainMission); + if (mainMission == null) return; + + foreach (var mission in mainMission?.MissionInfo?.SubMissionList ?? []) + if (mission.TakeType == SubMissionTakeTypeEnum.CustomValue) + { + var index = 0; + var accept = true; + foreach (var customValue in mission.TakeParamIntList ?? []) + { + if (customValue == 0 && index == 0) continue; // skip 0 + var valueInst = values.Find(x => x.Index == index); + if (valueInst == null) continue; + if (valueInst.CustomValue != customValue) + { + accept = false; + break; + } + } + + if (accept) await AcceptSubMission(mission.ID); + } + } + + public async ValueTask AddMissionProgress(int missionId, int progress) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return; + + Data.SubMissionProgressDict.TryGetValue(missionId, out var currentProgress); + Data.SubMissionProgressDict[missionId] = currentProgress + progress; + GameData.SubMissionData.TryGetValue(missionId, out var subMission); + if (subMission == null) return; + + if (currentProgress + progress >= (subMission.SubMissionInfo?.Progress ?? 1)) return; + + var sync = new MissionSync(); + sync.MissionList.Add(new Proto.Mission + { + Id = (uint)missionId, + Progress = (uint)(currentProgress + progress) + }); + + await Player.SendPacket(new PacketPlayerSyncScNotify(sync)); + } + + public async ValueTask SetMissionProgress(int missionId, int progress) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return; + + Data.SubMissionProgressDict[missionId] = progress; + GameData.SubMissionData.TryGetValue(missionId, out var subMission); + if (subMission == null) return; + + if (progress >= (subMission.SubMissionInfo?.Progress ?? 1)) return; + + var sync = new MissionSync(); + sync.MissionList.Add(new Proto.Mission + { + Id = (uint)missionId, + Progress = (uint)progress + }); + + await Player.SendPacket(new PacketPlayerSyncScNotify(sync)); + } + + #endregion + + #region Mission Status + + public MissionPhaseEnum GetMainMissionStatus(int missionId) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return MissionPhaseEnum.Finish; + + return Data.GetMainMissionStatus(missionId); + } + + public MissionPhaseEnum GetSubMissionStatus(int missionId) + { + if (!ConfigManager.Config.ServerOption.EnableMission) return MissionPhaseEnum.Finish; + + return Data.GetSubMissionStatus(missionId); + } + + public SubMissionInfo? GetSubMissionInfo(int missionId) + { + GameData.SubMissionData.TryGetValue(missionId, out var subMission); + if (subMission == null) return null; + return subMission.SubMissionInfo; + } + + public List GetRunningSubMissionIdList() + { + if (!ConfigManager.Config.ServerOption.EnableMission) return []; + + var list = new List(); + foreach (var id in Data.RunningSubMissionIds) list.Add(id); + return list; + } + + public List GetRunningSubMissionList() + { + if (!ConfigManager.Config.ServerOption.EnableMission) return []; + + var list = new List(); + foreach (var id in Data.RunningSubMissionIds) + { + GameData.SubMissionData.TryGetValue(id, out var mission); + if (mission != null && mission.SubMissionInfo != null) list.Add(mission.SubMissionInfo); + } + + return list; + } + + public int GetMissionProgress(int missionId) + { + GameData.SubMissionData.TryGetValue(missionId, out var subMission); + if (!ConfigManager.Config.ServerOption.EnableMission) return subMission?.SubMissionInfo?.Progress ?? 0; + + Data.SubMissionProgressDict.TryGetValue(missionId, out var progress); + return progress; + } + + #endregion + + #region Handlers + + public async ValueTask OnBattleFinish(PVEBattleResultCsReq req) + { + foreach (var mission in GetRunningSubMissionIdList()) + { + var subMission = GetSubMissionInfo(mission); + if (subMission != null && subMission.FinishType == MissionFinishTypeEnum.StageWin && + req.EndStatus == BattleEndStatus.BattleEndWin) // TODO: Move to handler + if (req.StageId.ToString().StartsWith(subMission.ParamInt1.ToString())) + await FinishSubMission(mission); + } + } + + public async ValueTask OnPlayerInteractWithProp() + { + foreach (var id in GetRunningSubMissionIdList()) + if (GetSubMissionInfo(id)?.FinishType == MissionFinishTypeEnum.PropState) + { + FinishTypeHandlers.TryGetValue(MissionFinishTypeEnum.PropState, out var handler); + if (handler != null) await handler.HandleFinishType(Player, GetSubMissionInfo(id)!, null); + } + } + + public async ValueTask OnPlayerChangeScene() + { + foreach (var id in GetRunningSubMissionIdList()) + { + var info = GetSubMissionInfo(id); + if (info == null) continue; + + if (info.LevelFloorID == Player.SceneInstance?.FloorId) + { + if (info.GroupIDList == null) continue; + foreach (var group in info.GroupIDList) + await Player.SceneInstance.EntityLoader!.LoadGroup(group, false); + } + } + } + + public void OnLoadScene(SceneInfo info) + { + foreach (var mainMission in GameData.MainMissionData.Values) + { + foreach (var subMission in mainMission.MissionInfo?.SubMissionList ?? []) + if (subMission.LevelFloorID == info.FloorId) + info.SceneMissionInfo.SceneSubMissionList.Add(new Proto.Mission + { + Id = (uint)subMission.ID, + Status = GetSubMissionStatus(subMission.ID).ToProto(), + Progress = (uint)GetMissionProgress(subMission.ID) + }); + + foreach (var subMission in mainMission.MissionInfo?.SubMissionList ?? []) + if (subMission.LevelFloorID == info.FloorId) + { + if (GetMainMissionStatus(mainMission.MainMissionID) == MissionPhaseEnum.Finish) + info.SceneMissionInfo.MainMissionIdList.Add((uint)mainMission.MainMissionID); + else if (GetMainMissionStatus(mainMission.MainMissionID) == MissionPhaseEnum.Accept) + info.SceneMissionInfo.AcceptMainMissionIdList.Add((uint)mainMission.MainMissionID); + break; // only one + } + } + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Mission/StoryLineEntityLoader.cs b/GameServer/Game/Mission/StoryLineEntityLoader.cs index f21f8678..461f5233 100644 --- a/GameServer/Game/Mission/StoryLineEntityLoader.cs +++ b/GameServer/Game/Mission/StoryLineEntityLoader.cs @@ -3,105 +3,85 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Mission +namespace EggLink.DanhengServer.GameServer.Game.Mission; + +public class StoryLineEntityLoader(SceneInstance scene) : SceneEntityLoader(scene) { - public class StoryLineEntityLoader(SceneInstance scene) : SceneEntityLoader(scene) + public List LoadGroups = []; + + public override async ValueTask LoadEntity() { - public List LoadGroups = []; - public override void LoadEntity() + if (Scene.IsLoaded) return; + + var storyId = Scene.Player.StoryLineManager?.StoryLineData.CurStoryLineId ?? 0; + if (storyId == 0) return; + + GameData.StoryLineFloorDataData.TryGetValue(storyId, out var floorData); + if (floorData == null) return; + + floorData.TryGetValue(Scene.FloorInfo?.FloorID ?? 0, out var floorInfo); + if (floorInfo == null) return; + + var dim = Scene?.FloorInfo?.DimensionList.Find(d => d.ID == floorInfo.DimensionID); + if (dim == null) return; + + LoadGroups.AddRange(dim.GroupIDList); + + foreach (var group in Scene?.FloorInfo?.Groups.Values!) // Sanity check in SceneInstance { - if (Scene.IsLoaded) return; - - var storyId = Scene.Player.StoryLineManager?.StoryLineData.CurStoryLineId ?? 0; - if (storyId == 0) return; - - GameData.StoryLineFloorDataData.TryGetValue(storyId, out var floorData); - if (floorData == null) return; - - floorData.TryGetValue(Scene.FloorInfo?.FloorID ?? 0, out var floorInfo); - if (floorInfo == null) return; - - var dim = Scene?.FloorInfo?.DimensionList.Find(d => d.ID == floorInfo.DimensionID); - if (dim == null) return; - - LoadGroups.AddRange(dim.GroupIDList); - - foreach (var group in Scene?.FloorInfo?.Groups.Values!) // Sanity check in SceneInstance - { - if (group.LoadSide == GroupLoadSideEnum.Client) - { - continue; - } - if (group.GroupName.Contains("TrainVisitor")) - { - continue; - } - LoadGroup(group); - } - Scene.IsLoaded = true; + if (group.LoadSide == GroupLoadSideEnum.Client) continue; + if (group.GroupName.Contains("TrainVisitor")) continue; + await LoadGroup(group); } - public override List? LoadGroup(GroupInfo info, bool forceLoad = false) - { - if (!LoadGroups.Contains(info.Id)) return null; - - if (Scene.Entities.Values.ToList().FindIndex(x => x.GroupID == info.Id) != -1) // check if group is already loaded - { - return null; - } - - // load - Scene.Groups.Add(info.Id); - - var entityList = new List(); - foreach (var npc in info.NPCList) - { - try - { - if (LoadNpc(npc, info) is EntityNpc entity) - { - entityList.Add(entity); - } - } - catch { } - } - - foreach (var monster in info.MonsterList) - { - try - { - if (LoadMonster(monster, info) is EntityMonster entity) - { - entityList.Add(entity); - } - } - catch { } - } - - foreach (var prop in info.PropList) - { - try - { - if (LoadProp(prop, info) is EntityProp entity) - { - entityList.Add(entity); - } - } - catch { } - } - - return entityList; - } - - public override void SyncEntity() - { - return; - } + Scene.IsLoaded = true; } -} + + public override async ValueTask?> LoadGroup(GroupInfo info, bool forceLoad = false) + { + if (!LoadGroups.Contains(info.Id)) return null; + + if (Scene.Entities.Values.ToList().FindIndex(x => x.GroupID == info.Id) != + -1) // check if group is already loaded + return null; + + // load + Scene.Groups.Add(info.Id); + + var entityList = new List(); + foreach (var npc in info.NPCList) + try + { + if (await LoadNpc(npc, info) is EntityNpc entity) entityList.Add(entity); + } + catch + { + } + + foreach (var monster in info.MonsterList) + try + { + if (await LoadMonster(monster, info) is EntityMonster entity) entityList.Add(entity); + } + catch + { + } + + foreach (var prop in info.PropList) + try + { + if (await LoadProp(prop, info) is EntityProp entity) entityList.Add(entity); + } + catch + { + } + + return entityList; + } + + public override async ValueTask SyncEntity() + { + await System.Threading.Tasks.Task.CompletedTask; + } +} \ No newline at end of file diff --git a/GameServer/Game/Mission/StoryLineManager.cs b/GameServer/Game/Mission/StoryLineManager.cs index 6f20f6d3..7942bfff 100644 --- a/GameServer/Game/Mission/StoryLineManager.cs +++ b/GameServer/Game/Mission/StoryLineManager.cs @@ -1,224 +1,210 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Mission; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.GameServer.Game.Mission +namespace EggLink.DanhengServer.GameServer.Game.Mission; + +public class StoryLineManager : BasePlayerManager { - public class StoryLineManager : BasePlayerManager + public StoryLineManager(PlayerInstance player) : base(player) { - public StoryLineData StoryLineData { get; set; } + StoryLineData = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + } - public StoryLineManager(PlayerInstance player) : base(player) + public StoryLineData StoryLineData { get; set; } + + public async ValueTask CheckIfEnterStoryLine() + { + if (StoryLineData.CurStoryLineId != 0) return; + + foreach (var storyLine in GameData.StoryLineData.Values) + if (Player.MissionManager!.GetSubMissionStatus(storyLine.BeginCondition.Param) == MissionPhaseEnum.Finish) + { + await InitStoryLine(storyLine.StoryLineID); + return; + } + } + + public async ValueTask InitStoryLine(int storyLineId, int entryId = 0, int anchorGroupId = 0, int anchorId = 0) + { + if (StoryLineData.CurStoryLineId != 0) await FinishStoryLine(entryId, anchorGroupId, anchorId, false); + GameData.StoryLineData.TryGetValue(storyLineId, out var storyExcel); + GameData.StroyLineTrialAvatarDataData.TryGetValue(storyLineId, out var storyAvatarExcel); + if (storyExcel == null || storyAvatarExcel == null) return; + StoryLineData.OldEntryId = Player.Data.EntryId; + StoryLineData.OldFloorId = Player.Data.FloorId; + StoryLineData.OldPlaneId = Player.Data.PlaneId; + StoryLineData.OldPos = Player.Data.Pos!; + StoryLineData.OldRot = Player.Data.Rot!; + + var avatarList = Player.LineupManager!.GetCurLineup()!.BaseAvatars! + .Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId).ToList(); + + for (var i = 0; i < storyAvatarExcel.InitTrialAvatarList.Count; i++) + avatarList[i] = storyAvatarExcel.InitTrialAvatarList[i]; // replace the avatar with the special avatar + + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, avatarList); + + StoryLineData.CurStoryLineId = storyExcel.StoryLineID; + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + await Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); + await Player.SendPacket( + new PacketChangeStoryLineFinishScNotify(storyExcel.StoryLineID, ChangeStoryLineAction.FinishAction)); + + if (entryId > 0) + await Player.EnterMissionScene(entryId, anchorGroupId, anchorId, true, ChangeStoryLineAction.FinishAction); + else + await Player.EnterMissionScene(storyExcel.InitEntranceID, storyExcel.InitGroupID, storyExcel.InitAnchorID, + true, ChangeStoryLineAction.FinishAction); + + var record = new StoryLineInfo { - StoryLineData = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + Lineup = Player.LineupManager!.GetCurLineup()!.BaseAvatars!, + SavedEntryId = Player.Data.EntryId, + SavedFloorId = Player.Data.FloorId, + SavedPlaneId = Player.Data.PlaneId, + SavedPos = Player.Data.Pos!, + SavedRot = Player.Data.Rot!, + StoryLineId = storyExcel.StoryLineID + }; + + StoryLineData.RunningStoryLines[storyExcel.StoryLineID] = record; + } + + public async ValueTask EnterStoryLine(int storyLineId, bool tp = true) + { + if (StoryLineData.CurStoryLineId == storyLineId) return; // already in this story line + + if (storyLineId == 0) // leave story line + { + await LeaveStoryLine(tp); + return; } - public void CheckIfEnterStoryLine() - { - if (StoryLineData.CurStoryLineId != 0) return; + StoryLineData.RunningStoryLines.TryGetValue(storyLineId, out var lineInfo); + if (lineInfo == null) return; - foreach (var storyLine in GameData.StoryLineData.Values) - { - if (Player.MissionManager!.GetSubMissionStatus(storyLine.BeginCondition.Param) == Enums.MissionPhaseEnum.Finish) - { - InitStoryLine(storyLine.StoryLineID); - return; - } - } - } - - public void InitStoryLine(int storyLineId, int entryId = 0, int anchorGroupId = 0, int anchorId = 0) + if (StoryLineData.CurStoryLineId == 0) // not in any story line { - if (StoryLineData.CurStoryLineId != 0) - { - FinishStoryLine(entryId, anchorGroupId, anchorId, false); - } - GameData.StoryLineData.TryGetValue(storyLineId, out var storyExcel); - GameData.StroyLineTrialAvatarDataData.TryGetValue(storyLineId, out var storyAvatarExcel); - if (storyExcel == null || storyAvatarExcel == null) return; StoryLineData.OldEntryId = Player.Data.EntryId; StoryLineData.OldFloorId = Player.Data.FloorId; StoryLineData.OldPlaneId = Player.Data.PlaneId; StoryLineData.OldPos = Player.Data.Pos!; StoryLineData.OldRot = Player.Data.Rot!; - - List avatarList = Player.LineupManager!.GetCurLineup()!.BaseAvatars!.Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId).ToList(); - - for (int i = 0; i < storyAvatarExcel.InitTrialAvatarList.Count; i++) - { - avatarList[i] = storyAvatarExcel.InitTrialAvatarList[i]; // replace the avatar with the special avatar - } - - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, avatarList); - - StoryLineData.CurStoryLineId = storyExcel.StoryLineID; - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); - Player.SendPacket(new PacketChangeStoryLineFinishScNotify(storyExcel.StoryLineID, ChangeStoryLineAction.FinishAction)); - - if (entryId > 0) - { - Player.EnterMissionScene(entryId, anchorGroupId, anchorId, true, ChangeStoryLineAction.FinishAction); - } - else - { - Player.EnterMissionScene(storyExcel.InitEntranceID, storyExcel.InitGroupID, storyExcel.InitAnchorID, true, ChangeStoryLineAction.FinishAction); - } - - var record = new StoryLineInfo() - { - Lineup = Player.LineupManager!.GetCurLineup()!.BaseAvatars!, - SavedEntryId = Player.Data.EntryId, - SavedFloorId = Player.Data.FloorId, - SavedPlaneId = Player.Data.PlaneId, - SavedPos = Player.Data.Pos!, - SavedRot = Player.Data.Rot!, - StoryLineId = storyExcel.StoryLineID - }; - - StoryLineData.RunningStoryLines[storyExcel.StoryLineID] = record; + } + else // in another story line + { + await LeaveStoryLine(false); } - public void EnterStoryLine(int storyLineId, bool tp = true) + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, + lineInfo.Lineup.Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId).ToList()); + + StoryLineData.CurStoryLineId = lineInfo.StoryLineId; + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + await Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); + await Player.SendPacket( + new PacketChangeStoryLineFinishScNotify(StoryLineData.CurStoryLineId, ChangeStoryLineAction.Client)); + + if (tp) + await Player.LoadScene(lineInfo.SavedPlaneId, lineInfo.SavedFloorId, lineInfo.SavedEntryId, + lineInfo.SavedPos, lineInfo.SavedRot, true, ChangeStoryLineAction.Client); + } + + public async ValueTask LeaveStoryLine(bool tp) + { + if (StoryLineData.CurStoryLineId == 0) return; + + GameData.StoryLineData.TryGetValue(StoryLineData.CurStoryLineId, out var storyExcel); + if (storyExcel == null) return; + + var record = new StoryLineInfo { - if (StoryLineData.CurStoryLineId == storyLineId) return; // already in this story line + Lineup = Player.LineupManager!.GetCurLineup()!.BaseAvatars!, + SavedEntryId = Player.Data.EntryId, + SavedFloorId = Player.Data.FloorId, + SavedPlaneId = Player.Data.PlaneId, + SavedPos = Player.Data.Pos!, + SavedRot = Player.Data.Rot!, + StoryLineId = storyExcel.StoryLineID + }; - if (storyLineId == 0) // leave story line - { - LeaveStoryLine(tp); - return; - } + // reset + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); - StoryLineData.RunningStoryLines.TryGetValue(storyLineId, out var lineInfo); - if (lineInfo == null) return; + // save + StoryLineData.RunningStoryLines[storyExcel.StoryLineID] = record; + StoryLineData.CurStoryLineId = 0; - if (StoryLineData.CurStoryLineId == 0) // not in any story line - { - StoryLineData.OldEntryId = Player.Data.EntryId; - StoryLineData.OldFloorId = Player.Data.FloorId; - StoryLineData.OldPlaneId = Player.Data.PlaneId; - StoryLineData.OldPos = Player.Data.Pos!; - StoryLineData.OldRot = Player.Data.Rot!; - } - else // in another story line - { - LeaveStoryLine(false); - } + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + await Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); + await Player.SendPacket(new PacketChangeStoryLineFinishScNotify(0, ChangeStoryLineAction.None)); - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, lineInfo.Lineup.Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId).ToList()); - - StoryLineData.CurStoryLineId = lineInfo.StoryLineId; - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); - Player.SendPacket(new PacketChangeStoryLineFinishScNotify(StoryLineData.CurStoryLineId, ChangeStoryLineAction.Client)); - - if (tp) - { - Player.LoadScene(lineInfo.SavedPlaneId, lineInfo.SavedFloorId, lineInfo.SavedEntryId, lineInfo.SavedPos, lineInfo.SavedRot, true, ChangeStoryLineAction.Client); - } - } - - public void LeaveStoryLine(bool tp) + if (tp) { - if (StoryLineData.CurStoryLineId == 0) return; - - GameData.StoryLineData.TryGetValue(StoryLineData.CurStoryLineId, out var storyExcel); - if (storyExcel == null) return; - - var record = new StoryLineInfo() - { - Lineup = Player.LineupManager!.GetCurLineup()!.BaseAvatars!, - SavedEntryId = Player.Data.EntryId, - SavedFloorId = Player.Data.FloorId, - SavedPlaneId = Player.Data.PlaneId, - SavedPos = Player.Data.Pos!, - SavedRot = Player.Data.Rot!, - StoryLineId = storyExcel.StoryLineID - }; - - // reset - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); - - // save - StoryLineData.RunningStoryLines[storyExcel.StoryLineID] = record; - StoryLineData.CurStoryLineId = 0; - - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); - Player.SendPacket(new PacketChangeStoryLineFinishScNotify(0, ChangeStoryLineAction.None)); - - if (tp) - { - Player.LoadScene(StoryLineData.OldPlaneId, StoryLineData.OldFloorId, StoryLineData.OldEntryId, StoryLineData.OldPos, StoryLineData.OldRot, true, ChangeStoryLineAction.None); - - StoryLineData.OldPlaneId = 0; - StoryLineData.OldEntryId = 0; - StoryLineData.OldFloorId = 0; - StoryLineData.OldPos = new(); - StoryLineData.OldRot = new(); - } - } - - public void CheckIfFinishStoryLine() // seems like a story line end with another ChangeStoryLine finish action that Params[0] = 0 - { - if (StoryLineData.CurStoryLineId == 0) return; - GameData.StoryLineData.TryGetValue(StoryLineData.CurStoryLineId, out var storyExcel); - if (storyExcel == null) return; - - if (Player.MissionManager!.GetSubMissionStatus(storyExcel.EndCondition.Param) == Enums.MissionPhaseEnum.Finish) - { - FinishStoryLine(); - } - } - - public void FinishStoryLine(int entryId = 0, int anchorGroupId = 0, int anchorId = 0, bool tp = true) - { - if (StoryLineData.CurStoryLineId == 0) return; - - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); - - // delete old & reset - StoryLineData.RunningStoryLines.Remove(StoryLineData.CurStoryLineId); - StoryLineData.CurStoryLineId = 0; + await Player.LoadScene(StoryLineData.OldPlaneId, StoryLineData.OldFloorId, StoryLineData.OldEntryId, + StoryLineData.OldPos, StoryLineData.OldRot, true); StoryLineData.OldPlaneId = 0; StoryLineData.OldEntryId = 0; StoryLineData.OldFloorId = 0; - StoryLineData.OldPos = new(); - StoryLineData.OldRot = new(); - - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); - Player.SendPacket(new PacketChangeStoryLineFinishScNotify(0, ChangeStoryLineAction.None)); - - if (tp) - { - if (entryId > 0) - { - Player.EnterMissionScene(entryId, anchorGroupId, anchorId, true, ChangeStoryLineAction.None); - } - else - { - Player.LoadScene(StoryLineData.OldPlaneId, StoryLineData.OldFloorId, StoryLineData.OldEntryId, StoryLineData.OldPos, StoryLineData.OldRot, true, ChangeStoryLineAction.FinishAction); - } - } - } - - public void OnLogin() - { - if (StoryLineData.CurStoryLineId == 0) return; - - Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); + StoryLineData.OldPos = new Position(); + StoryLineData.OldRot = new Position(); } } -} + + public async ValueTask + CheckIfFinishStoryLine() // seems like a story line end with another ChangeStoryLine finish action that Params[0] = 0 + { + if (StoryLineData.CurStoryLineId == 0) return; + GameData.StoryLineData.TryGetValue(StoryLineData.CurStoryLineId, out var storyExcel); + if (storyExcel == null) return; + + if (Player.MissionManager!.GetSubMissionStatus(storyExcel.EndCondition.Param) == MissionPhaseEnum.Finish) + await FinishStoryLine(); + } + + public async ValueTask FinishStoryLine(int entryId = 0, int anchorGroupId = 0, int anchorId = 0, bool tp = true) + { + if (StoryLineData.CurStoryLineId == 0) return; + + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); + + // delete old & reset + StoryLineData.RunningStoryLines.Remove(StoryLineData.CurStoryLineId); + StoryLineData.CurStoryLineId = 0; + + StoryLineData.OldPlaneId = 0; + StoryLineData.OldEntryId = 0; + StoryLineData.OldFloorId = 0; + StoryLineData.OldPos = new Position(); + StoryLineData.OldRot = new Position(); + + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + await Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); + await Player.SendPacket(new PacketChangeStoryLineFinishScNotify(0, ChangeStoryLineAction.None)); + + if (tp) + { + if (entryId > 0) + await Player.EnterMissionScene(entryId, anchorGroupId, anchorId, true); + else + await Player.LoadScene(StoryLineData.OldPlaneId, StoryLineData.OldFloorId, StoryLineData.OldEntryId, + StoryLineData.OldPos, StoryLineData.OldRot, true, ChangeStoryLineAction.FinishAction); + } + } + + public async ValueTask OnLogin() + { + if (StoryLineData.CurStoryLineId == 0) return; + + await Player.SendPacket(new PacketStoryLineInfoScNotify(Player)); + } +} \ No newline at end of file diff --git a/GameServer/Game/Player/PlayerInstance.cs b/GameServer/Game/Player/PlayerInstance.cs index 611ae30a..9eb2066a 100644 --- a/GameServer/Game/Player/PlayerInstance.cs +++ b/GameServer/Game/Player/PlayerInstance.cs @@ -1,16 +1,18 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Database.Scene; using EggLink.DanhengServer.Database.Tutorial; using EggLink.DanhengServer.Enums; +using EggLink.DanhengServer.Enums.Avatar; using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Activity; using EggLink.DanhengServer.Game.Avatar; using EggLink.DanhengServer.Game.Battle; -using EggLink.DanhengServer.Game.Friend; +using EggLink.DanhengServer.Game.Challenge; using EggLink.DanhengServer.Game.ChessRogue; +using EggLink.DanhengServer.Game.Drop; +using EggLink.DanhengServer.Game.Friend; using EggLink.DanhengServer.Game.Gacha; using EggLink.DanhengServer.Game.Inventory; using EggLink.DanhengServer.Game.Lineup; @@ -20,696 +22,671 @@ using EggLink.DanhengServer.Game.Rogue; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Game.Shop; +using EggLink.DanhengServer.GameServer.Game.Mail; +using EggLink.DanhengServer.GameServer.Game.Mission; +using EggLink.DanhengServer.GameServer.Game.Raid; +using EggLink.DanhengServer.GameServer.Game.Task; +using EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; +using EggLink.DanhengServer.Server.Packet.Send.Avatar; using EggLink.DanhengServer.Server.Packet.Send.Lineup; using EggLink.DanhengServer.Server.Packet.Send.Player; using EggLink.DanhengServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Util; -using EggLink.DanhengServer.Enums.Avatar; -using EggLink.DanhengServer.Server.Packet.Send.Avatar; -using EggLink.DanhengServer.Game.Challenge; -using EggLink.DanhengServer.Game.Drop; using static EggLink.DanhengServer.Plugin.Event.PluginEvent; -using EggLink.DanhengServer.Game.Task; -using EggLink.DanhengServer.GameServer.Game.Mail; -using EggLink.DanhengServer.GameServer.Game.Raid; -using EggLink.DanhengServer.GameServer.Game.Mission; -using EggLink.DanhengServer.GameServer.Game.Task; -using EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; -namespace EggLink.DanhengServer.Game.Player +namespace EggLink.DanhengServer.Game.Player; + +public class PlayerInstance(PlayerData data) { - public class PlayerInstance(PlayerData data) + #region Managers + + public ActivityManager? ActivityManager { get; private set; } + public AvatarManager? AvatarManager { get; private set; } + public LineupManager? LineupManager { get; private set; } + public InventoryManager? InventoryManager { get; private set; } + public BattleManager? BattleManager { get; private set; } + public BattleInstance? BattleInstance { get; set; } + public MissionManager? MissionManager { get; private set; } + public GachaManager? GachaManager { get; private set; } + public MessageManager? MessageManager { get; private set; } + public MailManager? MailManager { get; private set; } + + public RaidManager? RaidManager { get; private set; } + public StoryLineManager? StoryLineManager { get; private set; } + + public FriendManager? FriendManager { get; private set; } + public RogueManager? RogueManager { get; private set; } + public ChessRogueManager? ChessRogueManager { get; private set; } + public ShopService? ShopService { get; private set; } + public ChallengeManager? ChallengeManager { get; private set; } + + public TaskManager? TaskManager { get; private set; } + + #endregion + + #region Datas + + public PlayerData Data { get; set; } = data; + public PlayerUnlockData? PlayerUnlockData { get; private set; } + public SceneData? SceneData { get; private set; } + public HeartDialData? HeartDialData { get; private set; } + public TutorialData? TutorialData { get; private set; } + public TutorialGuideData? TutorialGuideData { get; private set; } + public SceneInstance? SceneInstance { get; private set; } + public int Uid { get; set; } + public Connection? Connection { get; set; } + public bool Initialized { get; set; } + public bool IsNewPlayer { get; set; } + public int NextBattleId { get; set; } = 0; + public int ChargerNum { get; set; } = 0; + + #endregion + + #region Initializers + + public PlayerInstance(int uid) : this(new PlayerData { Uid = uid }) { - #region Managers + // new player + IsNewPlayer = true; + Data.NextStaminaRecover = Extensions.GetUnixSec() + GameConstants.STAMINA_RESERVE_RECOVERY_TIME; + Data.Level = ConfigManager.Config.ServerOption.StartTrailblazerLevel; - public ActivityManager? ActivityManager { get; private set; } - public AvatarManager? AvatarManager { get; private set; } - public LineupManager? LineupManager { get; private set; } - public InventoryManager? InventoryManager { get; private set; } - public BattleManager? BattleManager { get; private set; } - public BattleInstance? BattleInstance { get; set; } - public MissionManager? MissionManager { get; private set; } - public GachaManager? GachaManager { get; private set; } - public MessageManager? MessageManager { get; private set; } - public MailManager? MailManager { get; private set; } + DatabaseHelper.SaveInstance(Data); - public RaidManager? RaidManager { get; private set; } - public StoryLineManager? StoryLineManager { get; private set; } - public FriendManager? FriendManager { get; private set; } - public RogueManager? RogueManager { get; private set; } - public ChessRogueManager? ChessRogueManager { get; private set; } - public ShopService? ShopService { get; private set; } - public ChallengeManager? ChallengeManager { get; private set; } - - public TaskManager? TaskManager { get; private set; } - - #endregion - - #region Datas - - public PlayerData Data { get; set; } = data; - public PlayerUnlockData? PlayerUnlockData { get; private set; } - public SceneData? SceneData { get; private set; } - public HeartDialData? HeartDialData { get; private set; } - public TutorialData? TutorialData { get; private set; } - public TutorialGuideData? TutorialGuideData { get; private set; } - public SceneInstance? SceneInstance { get; private set; } - public int Uid { get; set; } - public Connection? Connection { get; set; } - public bool Initialized { get; set; } = false; - public bool IsNewPlayer { get; set; } = false; - public int NextBattleId { get; set; } = 0; - public int ChargerNum { get; set; } = 0; - - #endregion - - #region Initializers - - public PlayerInstance(int uid) : this(new PlayerData() { Uid = uid }) + var t = System.Threading.Tasks.Task.Run(async () => { - // new player - IsNewPlayer = true; - Data.NextStaminaRecover = Extensions.GetUnixSec() + GameConstants.STAMINA_RESERVE_RECOVERY_TIME; - Data.Level = ConfigManager.Config.ServerOption.StartTrailblazerLevel; + await InitialPlayerManager(); - DatabaseHelper.SaveInstance(Data); - - InitialPlayerManager(); - - AddAvatar(8001); - AddAvatar(1001); - + await AddAvatar(8001); + await AddAvatar(1001); if (ConfigManager.Config.ServerOption.EnableMission) { - LineupManager?.AddSpecialAvatarToCurTeam(10010050); - MissionManager!.AcceptMainMissionByCondition(); - } else + await LineupManager!.AddSpecialAvatarToCurTeam(10010050); + await MissionManager!.AcceptMainMissionByCondition(); + } + else { - LineupManager?.AddAvatarToCurTeam(8001); + await LineupManager!.AddAvatarToCurTeam(8001); Data.CurrentGender = Gender.Man; Data.CurBasicType = 8001; } + }); + t.Wait(); - Initialized = true; - } + Initialized = true; + } - private void InitialPlayerManager() + private async ValueTask InitialPlayerManager() + { + Uid = Data.Uid; + ActivityManager = new ActivityManager(this); + AvatarManager = new AvatarManager(this); + LineupManager = new LineupManager(this); + InventoryManager = new InventoryManager(this); + BattleManager = new BattleManager(this); + MissionManager = new MissionManager(this); + GachaManager = new GachaManager(this); + MessageManager = new MessageManager(this); + MailManager = new MailManager(this); + FriendManager = new FriendManager(this); + RogueManager = new RogueManager(this); + ShopService = new ShopService(this); + ChessRogueManager = new ChessRogueManager(this); + ChallengeManager = new ChallengeManager(this); + TaskManager = new TaskManager(this); + RaidManager = new RaidManager(this); + StoryLineManager = new StoryLineManager(this); + + PlayerUnlockData = InitializeDatabase(); + SceneData = InitializeDatabase(); + HeartDialData = InitializeDatabase(); + TutorialData = InitializeDatabase(); + TutorialGuideData = InitializeDatabase(); + + Data.LastActiveTime = Extensions.GetUnixSec(); + DatabaseHelper.Instance?.UpdateInstance(Data); + + ChallengeManager.ResurrectInstance(); + await StoryLineManager.OnLogin(); + + if (LineupManager!.GetCurLineup() != null) // null -> ignore(new player) { - Uid = Data.Uid; - ActivityManager = new(this); - AvatarManager = new(this); - LineupManager = new(this); - InventoryManager = new(this); - BattleManager = new(this); - MissionManager = new(this); - GachaManager = new(this); - MessageManager = new(this); - MailManager = new(this); - FriendManager = new(this); - RogueManager = new(this); - ShopService = new(this); - ChessRogueManager = new(this); - ChallengeManager = new(this); - TaskManager = new(this); - RaidManager = new(this); - StoryLineManager = new(this); - - PlayerUnlockData = InitializeDatabase(); - SceneData = InitializeDatabase(); - HeartDialData = InitializeDatabase(); - TutorialData = InitializeDatabase(); - TutorialGuideData = InitializeDatabase(); - - Data.LastActiveTime = Extensions.GetUnixSec(); - DatabaseHelper.Instance?.UpdateInstance(Data); - - ChallengeManager.ResurrectInstance(); - StoryLineManager.OnLogin(); - - if (LineupManager!.GetCurLineup() != null) // null -> ignore(new player) + if (LineupManager!.GetCurLineup()!.IsExtraLineup() && + RaidManager!.RaidData.CurRaidId == 0 && StoryLineManager!.StoryLineData.CurStoryLineId == 0 && + ChallengeManager!.ChallengeInstance == null) // do not use extra lineup when login { - if (LineupManager!.GetCurLineup()!.IsExtraLineup() && - RaidManager!.RaidData.CurRaidId == 0 && StoryLineManager!.StoryLineData.CurStoryLineId == 0 && - ChallengeManager!.ChallengeInstance == null) // do not use extra lineup when login - { - LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); - if (LineupManager!.GetCurLineup()!.IsExtraLineup()) - { - LineupManager!.SetCurLineup(0); - } - } + LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); + if (LineupManager!.GetCurLineup()!.IsExtraLineup()) await LineupManager!.SetCurLineup(0); + } - foreach (var lineup in LineupManager.LineupData.Lineups) - { - if (lineup.Value.BaseAvatars!.Count >= 5) - { - lineup.Value.BaseAvatars = lineup.Value.BaseAvatars.GetRange(0, 4); - } + foreach (var lineup in LineupManager.LineupData.Lineups) + { + if (lineup.Value.BaseAvatars!.Count >= 5) + lineup.Value.BaseAvatars = lineup.Value.BaseAvatars.GetRange(0, 4); - foreach (var avatar in lineup.Value.BaseAvatars!) + foreach (var avatar in lineup.Value.BaseAvatars!) + if (avatar.BaseAvatarId > 10000) { - if (avatar.BaseAvatarId > 10000) + GameData.SpecialAvatarData.TryGetValue(avatar.BaseAvatarId, out var special); + if (special != null) { - GameData.SpecialAvatarData.TryGetValue(avatar.BaseAvatarId, out var special); + avatar.SpecialAvatarId = special.GetId(); + avatar.BaseAvatarId = special.AvatarID; + } + else + { + GameData.SpecialAvatarData.TryGetValue(avatar.BaseAvatarId * 10 + Data.WorldLevel, + out special); if (special != null) { avatar.SpecialAvatarId = special.GetId(); avatar.BaseAvatarId = special.AvatarID; - } - else - { - GameData.SpecialAvatarData.TryGetValue(avatar.BaseAvatarId * 10 + Data.WorldLevel, out special); - if (special != null) - { - avatar.SpecialAvatarId = special.GetId(); - avatar.BaseAvatarId = special.AvatarID; - } } } } - } - - foreach (var avatar in LineupManager.GetCurLineup()!.BaseAvatars!) - { - var avatarData = AvatarManager.GetAvatar(avatar.BaseAvatarId); - if (avatarData != null && avatarData.CurrentHp <= 0) - { - // revive - avatarData.CurrentHp = 2000; - } - } } - - LoadScene(Data.PlaneId, Data.FloorId, Data.EntryId, Data.Pos!, Data.Rot!, false); - if (SceneInstance == null) + foreach (var avatar in LineupManager.GetCurLineup()!.BaseAvatars!) { - EnterScene(2000101, 0, false); + var avatarData = AvatarManager.GetAvatar(avatar.BaseAvatarId); + if (avatarData != null && avatarData.CurrentHp <= 0) + // revive + avatarData.CurrentHp = 2000; } } - public T InitializeDatabase() where T : class, new() - { - var instance = DatabaseHelper.Instance?.GetInstanceOrCreateNew(Uid); - return instance!; - } - - #endregion - - #region Network - public void OnLogin() - { - if (!Initialized) - { - InitialPlayerManager(); - } - - SendPacket(new PacketStaminaInfoScNotify(this)); - - InvokeOnPlayerLogin(this); - } - - public void OnLogoutAsync() - { - InvokeOnPlayerLogout(this); - } - - public void SendPacket(BasePacket packet) - { - if (Connection?.IsOnline == true) - { - Connection?.SendPacket(packet); - } - } - #endregion - - #region Actions - - public void ChangeHeroBasicType(HeroBasicTypeEnum type) - { - var id = (int)((int)type + Data.CurrentGender - 1); - if (Data.CurBasicType == id) return; - Data.CurBasicType = id; - AvatarManager!.GetHero()!.HeroId = id; - AvatarManager!.GetHero()!.ValidateHero(); - AvatarManager!.GetHero()!.SetCurSp(0, LineupManager!.GetCurLineup()!.IsExtraLineup()); - SendPacket(new PacketHeroBasicTypeChangedNotify(id)); - SendPacket(new PacketPlayerSyncScNotify(AvatarManager!.GetHero()!)); - } - - public void AddAvatar(int avatarId, bool sync = true, bool notify = true) - { - AvatarManager?.AddAvatar(avatarId, sync, notify); - } - - public void SpendStamina(int staminaCost) - { - Data.Stamina -= staminaCost; - SendPacket(new PacketStaminaInfoScNotify(this)); - } - - public void OnAddExp() - { - GameData.PlayerLevelConfigData.TryGetValue(Data.Level, out var config); - GameData.PlayerLevelConfigData.TryGetValue(Data.Level + 1, out var config2); - if (config == null || config2 == null) return; - var nextExp = config2.PlayerExp - config.PlayerExp; - - while (Data.Exp >= nextExp) - { - Data.Exp -= nextExp; - Data.Level++; - GameData.PlayerLevelConfigData.TryGetValue(Data.Level, out config); - GameData.PlayerLevelConfigData.TryGetValue(Data.Level + 1, out config2); - if (config == null || config2 == null) break; - nextExp = config2.PlayerExp - config.PlayerExp; - } - - OnLevelChange(); - } - - public void OnLevelChange() - { - if (!ConfigManager.Config.ServerOption.AutoUpgradeWorldLevel) return; - int worldLevel = 0; - foreach (var level in GameConstants.UpgradeWorldLevel) - { - if (level <= Data.Level) - { - worldLevel++; - } - } - - if (Data.WorldLevel != worldLevel) - { - Data.WorldLevel = worldLevel; - } - } - - public void OnStaminaRecover() - { - var sendPacket = false; - while (Data.NextStaminaRecover <= Extensions.GetUnixSec()) - { - if (Data.Stamina >= GameConstants.MAX_STAMINA) - { - if (Data.StaminaReserve >= GameConstants.MAX_STAMINA_RESERVE) // needn't recover - { - break; - } - Data.StaminaReserve = Math.Min(Data.StaminaReserve + 1, GameConstants.MAX_STAMINA_RESERVE); - } - else - { - Data.Stamina++; - } - Data.NextStaminaRecover = Data.NextStaminaRecover + (Data.Stamina >= GameConstants.MAX_STAMINA ? GameConstants.STAMINA_RESERVE_RECOVERY_TIME : GameConstants.STAMINA_RECOVERY_TIME); - sendPacket = true; - } - - if (sendPacket) - { - SendPacket(new PacketStaminaInfoScNotify(this)); - } - } - - public void OnHeartBeat() - { - OnStaminaRecover(); - - InvokeOnPlayerHeartBeat(this); - - DatabaseHelper.ToSaveUidList.SafeAdd(Uid); - } - - #endregion - - #region Scene Actions - - public void OnMove() - { - if (SceneInstance != null) - { - EntityProp? prop = SceneInstance.GetNearestSpring(25_000_000); - - bool isInRange = prop != null; - - if (isInRange) - { - if (LineupManager?.GetCurLineup()?.Heal(10000, true) == true) - { - SendPacket(new PacketSyncLineupNotify(LineupManager.GetCurLineup()!)); - } - } - } - } - - public EntityProp? InteractProp(int propEntityId, int interactId) - { - if (SceneInstance != null) - { - SceneInstance.Entities.TryGetValue(propEntityId, out IGameEntity? entity); - if (entity == null) return null; - if (entity is EntityProp prop) - { - GameData.InteractConfigData.TryGetValue(interactId, out var config); - if (config == null || config.SrcState != prop.State) return prop; - var oldState = prop.State; - prop.SetState(config.TargetState); - var newState = prop.State; - SendPacket(new PacketGroupStateChangeScNotify(Data.EntryId, prop.GroupID, prop.State)); - - switch (prop.Excel.PropType) - { - case PropTypeEnum.PROP_TREASURE_CHEST: - if (oldState == PropStateEnum.ChestClosed && newState == PropStateEnum.ChestUsed) - { - // TODO: Filter treasure chest - var items = DropService.CalculateDropsFromProp(); - SceneInstance.Player.InventoryManager!.AddItems(items); - } - break; - case PropTypeEnum.PROP_DESTRUCT: - if (newState == PropStateEnum.Closed) - { - prop.SetState(PropStateEnum.Open); - } - break; - case PropTypeEnum.PROP_MAZE_PUZZLE: - if (newState == PropStateEnum.Closed || newState == PropStateEnum.Open) - { - foreach (var p in SceneInstance.GetEntitiesInGroup(prop.GroupID)) - { - if (p.Excel.PropType == PropTypeEnum.PROP_TREASURE_CHEST) - { - p.SetState(PropStateEnum.ChestUsed); - } - else if (p.Excel.PropType == PropTypeEnum.PROP_MAZE_PUZZLE) - { - // Skip - } - else - { - p.SetState(PropStateEnum.Open); - } - MissionManager!.OnPlayerInteractWithProp(); - } - } - break; - } - - // for door unlock - if (prop.PropInfo.UnlockDoorID.Count > 0) - { - foreach (var id in prop.PropInfo.UnlockDoorID) - { - foreach (var p in SceneInstance.GetEntitiesInGroup(id.Key)) - { - if (id.Value.Contains(p.PropInfo.ID)) - { - p.SetState(PropStateEnum.Open); - MissionManager!.OnPlayerInteractWithProp(); - } - } - } - } - - // for mission - MissionManager!.OnPlayerInteractWithProp(); - - // plane event - InventoryManager!.HandlePlaneEvent(prop.PropInfo.EventID); - - // handle plugin event - InvokeOnPlayerInteract(this, prop); - - var floorSavedKey = prop.PropInfo.Name.Replace("Controller_", ""); - var key = $"FSV_ML{floorSavedKey}{(config.TargetState == PropStateEnum.Open ? "Started":"Complete")}"; - if (SceneInstance?.FloorInfo?.SavedValues.Find(x => x.Name == key) != null) - { - // should save - var plane = SceneInstance.PlaneId; - var floor = SceneInstance.FloorId; - SceneData!.FloorSavedData.TryGetValue(floor, out var value); - if (value == null) - { - value = []; - SceneData.FloorSavedData[floor] = value; - } - - value[key] = 1; // ParamString[2] is the key - SendPacket(new PacketUpdateFloorSavedValueNotify(key, 1)); - - TaskManager?.SceneTaskTrigger.TriggerFloor(plane, floor); - MissionManager?.HandleFinishType(MissionFinishTypeEnum.FloorSavedValue); - } - - return prop; - } - } - return null; - } - - public bool EnterScene(int entryId, int teleportId, bool sendPacket, ChangeStoryLineAction storyLineAction = ChangeStoryLineAction.None, int storyLineId = 0, bool mapTp = false) - { - if (storyLineId != StoryLineManager?.StoryLineData.CurStoryLineId) - { - StoryLineManager?.EnterStoryLine(storyLineId, entryId == 0); // entryId == 0 -> teleport - mapTp = false; // do not use mapTp when enter story line - } - - GameData.MapEntranceData.TryGetValue(entryId, out var entrance); - if (entrance == null) return false; - - GameData.GetFloorInfo(entrance.PlaneID, entrance.FloorID, out var floorInfo); - if (floorInfo == null) return false; - - int StartGroup = entrance.StartGroupID; - int StartAnchor = entrance.StartAnchorID; - - if (teleportId != 0) - { - floorInfo.CachedTeleports.TryGetValue(teleportId, out var teleport); - if (teleport != null) - { - StartGroup = teleport.AnchorGroupID; - StartAnchor = teleport.AnchorID; - } - } else if (StartAnchor == 0) - { - StartGroup = floorInfo.StartGroupID; - StartAnchor = floorInfo.StartAnchorID; - } - AnchorInfo? anchor = floorInfo.GetAnchorInfo(StartGroup, StartAnchor); - - MissionManager?.HandleFinishType(MissionFinishTypeEnum.EnterMapByEntrance, entryId); - - var beforeEntryId = Data.EntryId; - - LoadScene(entrance.PlaneID, entrance.FloorID, entryId, anchor!.ToPositionProto(), anchor.ToRotationProto(), sendPacket, storyLineAction, mapTp); - - var afterEntryId = Data.EntryId; - - return beforeEntryId != afterEntryId; // return true if entryId changed - } - - public void EnterMissionScene(int entranceId, int anchorGroupId, int anchorId, bool sendPacket, ChangeStoryLineAction storyLineAction = ChangeStoryLineAction.None) - { - GameData.MapEntranceData.TryGetValue(entranceId, out var entrance); - if (entrance == null) return; - - GameData.GetFloorInfo(entrance.PlaneID, entrance.FloorID, out var floorInfo); - if (floorInfo == null) return; - - int StartGroup = anchorGroupId == 0 ? entrance.StartGroupID : anchorGroupId; - int StartAnchor = anchorId == 0 ? entrance.StartAnchorID : anchorId; - - if (StartAnchor == 0) - { - StartGroup = floorInfo.StartGroupID; - StartAnchor = floorInfo.StartAnchorID; - } - AnchorInfo? anchor = floorInfo.GetAnchorInfo(StartGroup, StartAnchor); - - LoadScene(entrance.PlaneID, entrance.FloorID, entranceId, anchor!.ToPositionProto(), anchor.ToRotationProto(), sendPacket, storyLineAction); - } - - public void MoveTo(Position position) - { - Data.Pos = position; - SendPacket(new PacketSceneEntityMoveScNotify(this)); - } - - public void MoveTo(EntityMotion motion) - { - Data.Pos = motion.Motion.Pos.ToPosition(); - Data.Rot = motion.Motion.Rot.ToPosition(); - } - - public void MoveTo(Position pos, Position rot) - { - Data.Pos = pos; - Data.Rot = rot; - SendPacket(new PacketSceneEntityMoveScNotify(this)); - } - - public void LoadScene(int planeId, int floorId, int entryId, Position pos, Position rot, bool sendPacket, ChangeStoryLineAction storyLineAction = ChangeStoryLineAction.None, bool mapTp = false) - { - GameData.MazePlaneData.TryGetValue(planeId, out var plane); - if (plane == null) return; - - if (plane.PlaneType == PlaneTypeEnum.Rogue && RogueManager!.GetRogueInstance() == null) - { - EnterScene(801120102, 0, sendPacket); - return; - } else if (plane.PlaneType == PlaneTypeEnum.Raid && RaidManager!.RaidData.CurRaidId == 0) - { - EnterScene(2000101, 0, sendPacket); - return; - } else if (plane.PlaneType == PlaneTypeEnum.Challenge && ChallengeManager!.ChallengeInstance == null) - { - EnterScene(100000103, 0, sendPacket); - return; - } - - // TODO: Sanify check - Data.Pos = pos; - Data.Rot = rot; - var notSendMove = true; - SceneInstance instance = new(this, plane, floorId, entryId); - if (planeId != Data.PlaneId || floorId != Data.FloorId || entryId != Data.EntryId) - { - Data.PlaneId = planeId; - Data.FloorId = floorId; - Data.EntryId = entryId; - } - else if (StoryLineManager?.StoryLineData.CurStoryLineId == 0 && mapTp) // only send move packet when not in story line and mapTp - { - notSendMove = false; - } - SceneInstance = instance; - - MissionManager?.OnPlayerChangeScene(); - - Connection?.SendPacket(CmdIds.SyncServerSceneChangeNotify); - if (sendPacket && notSendMove) - { - SendPacket(new PacketEnterSceneByServerScNotify(instance, storyLineAction)); - } - else if (sendPacket && !notSendMove) // send move packet - { - SendPacket(new PacketSceneEntityMoveScNotify(this)); - } - - MissionManager?.HandleFinishType(MissionFinishTypeEnum.EnterFloor); - MissionManager?.HandleFinishType(MissionFinishTypeEnum.EnterPlane); - MissionManager?.HandleFinishType(MissionFinishTypeEnum.NotInFloor); - MissionManager?.HandleFinishType(MissionFinishTypeEnum.NotInPlane); - } - - public ScenePropData? GetScenePropData(int floorId, int groupId, int propId) - { - if (SceneData != null) - { - if (SceneData.ScenePropData.TryGetValue(floorId, out var floorData)) - { - if (floorData.TryGetValue(groupId, out var groupData)) - { - var propData = groupData.Find(x => x.PropId == propId); - return propData; - } - } - } - return null; - } - - public void SetScenePropData(int floorId, int groupId, int propId, PropStateEnum state) - { - if (SceneData != null) - { - if (!SceneData.ScenePropData.TryGetValue(floorId, out var floorData)) - { - floorData = []; - SceneData.ScenePropData.Add(floorId, floorData); - } - if (!floorData.TryGetValue(groupId, out var groupData)) - { - groupData = []; - floorData.Add(groupId, groupData); - } - var propData = groupData.Find(x => x.PropId == propId); // find prop data - if (propData == null) - { - propData = new ScenePropData() - { - PropId = propId, - State = state, - }; - groupData.Add(propData); - } - else - { - propData.State = state; - } - } - } - - public void EnterSection(int sectionId) - { - if (SceneInstance != null) - { - SceneData!.UnlockSectionIdList.TryGetValue(SceneInstance.FloorId, out var unlockList); - if (unlockList == null) - { - unlockList = [sectionId]; - SceneData.UnlockSectionIdList.Add(SceneInstance.FloorId, unlockList); - } else - { - SceneData.UnlockSectionIdList[SceneInstance.FloorId].Add(sectionId); - } - } - } - - public void SetCustomSaveData(int entryId, int groupId, string data) - { - if (SceneData != null) - { - if (!SceneData.CustomSaveData.TryGetValue(entryId, out var entryData)) - { - entryData = []; - SceneData.CustomSaveData.Add(entryId, entryData); - } - entryData[groupId] = data; - } - } - - public void ForceQuitBattle() - { - if (BattleInstance != null) - { - BattleInstance = null; - Connection!.SendPacket(CmdIds.QuitBattleScNotify); - } - } - - #endregion - - #region Serialization - - public PlayerBasicInfo ToProto() - { - return Data.ToProto(); - } - - public PlayerSimpleInfo ToSimpleProto() - { - return Data.ToSimpleProto(FriendOnlineStatus.Online); - } - - #endregion + await LoadScene(Data.PlaneId, Data.FloorId, Data.EntryId, Data.Pos!, Data.Rot!, false); + if (SceneInstance == null) await EnterScene(2000101, 0, false); } -} + + public T InitializeDatabase() where T : class, new() + { + var instance = DatabaseHelper.Instance?.GetInstanceOrCreateNew(Uid); + return instance!; + } + + #endregion + + #region Network + + public async ValueTask OnLogin() + { + if (!Initialized) await InitialPlayerManager(); + + await SendPacket(new PacketStaminaInfoScNotify(this)); + + InvokeOnPlayerLogin(this); + } + + public void OnLogoutAsync() + { + InvokeOnPlayerLogout(this); + } + + public async ValueTask SendPacket(BasePacket packet) + { + if (Connection?.IsOnline == true) await Connection.SendPacket(packet); + } + + #endregion + + #region Actions + + public async ValueTask ChangeHeroBasicType(HeroBasicTypeEnum type) + { + var id = (int)((int)type + Data.CurrentGender - 1); + if (Data.CurBasicType == id) return; + Data.CurBasicType = id; + AvatarManager!.GetHero()!.HeroId = id; + AvatarManager!.GetHero()!.ValidateHero(); + AvatarManager!.GetHero()!.SetCurSp(0, LineupManager!.GetCurLineup()!.IsExtraLineup()); + await SendPacket(new PacketHeroBasicTypeChangedNotify(id)); + await SendPacket(new PacketPlayerSyncScNotify(AvatarManager!.GetHero()!)); + } + + public async ValueTask AddAvatar(int avatarId, bool sync = true, bool notify = true) + { + await AvatarManager!.AddAvatar(avatarId, sync, notify); + } + + public async ValueTask SpendStamina(int staminaCost) + { + Data.Stamina -= staminaCost; + await SendPacket(new PacketStaminaInfoScNotify(this)); + } + + public void OnAddExp() + { + GameData.PlayerLevelConfigData.TryGetValue(Data.Level, out var config); + GameData.PlayerLevelConfigData.TryGetValue(Data.Level + 1, out var config2); + if (config == null || config2 == null) return; + var nextExp = config2.PlayerExp - config.PlayerExp; + + while (Data.Exp >= nextExp) + { + Data.Exp -= nextExp; + Data.Level++; + GameData.PlayerLevelConfigData.TryGetValue(Data.Level, out config); + GameData.PlayerLevelConfigData.TryGetValue(Data.Level + 1, out config2); + if (config == null || config2 == null) break; + nextExp = config2.PlayerExp - config.PlayerExp; + } + + OnLevelChange(); + } + + public void OnLevelChange() + { + if (!ConfigManager.Config.ServerOption.AutoUpgradeWorldLevel) return; + var worldLevel = 0; + foreach (var level in GameConstants.UpgradeWorldLevel) + if (level <= Data.Level) + worldLevel++; + + if (Data.WorldLevel != worldLevel) Data.WorldLevel = worldLevel; + } + + public async ValueTask OnStaminaRecover() + { + var sendPacket = false; + while (Data.NextStaminaRecover <= Extensions.GetUnixSec()) + { + if (Data.Stamina >= GameConstants.MAX_STAMINA) + { + if (Data.StaminaReserve >= GameConstants.MAX_STAMINA_RESERVE) // needn't recover + break; + Data.StaminaReserve = Math.Min(Data.StaminaReserve + 1, GameConstants.MAX_STAMINA_RESERVE); + } + else + { + Data.Stamina++; + } + + Data.NextStaminaRecover = Data.NextStaminaRecover + (Data.Stamina >= GameConstants.MAX_STAMINA + ? GameConstants.STAMINA_RESERVE_RECOVERY_TIME + : GameConstants.STAMINA_RECOVERY_TIME); + sendPacket = true; + } + + if (sendPacket) await SendPacket(new PacketStaminaInfoScNotify(this)); + } + + public async ValueTask OnHeartBeat() + { + await OnStaminaRecover(); + + InvokeOnPlayerHeartBeat(this); + + DatabaseHelper.ToSaveUidList.SafeAdd(Uid); + } + + #endregion + + #region Scene Actions + + public async ValueTask OnMove() + { + if (SceneInstance != null) + { + var prop = SceneInstance.GetNearestSpring(25_000_000); + + var isInRange = prop != null; + + if (isInRange) + if (LineupManager?.GetCurLineup()?.Heal(10000, true) == true) + await SendPacket(new PacketSyncLineupNotify(LineupManager.GetCurLineup()!)); + } + } + + public async ValueTask InteractProp(int propEntityId, int interactId) + { + if (SceneInstance != null) + { + SceneInstance.Entities.TryGetValue(propEntityId, out var entity); + if (entity == null) return null; + if (entity is EntityProp prop) + { + GameData.InteractConfigData.TryGetValue(interactId, out var config); + if (config == null || config.SrcState != prop.State) return prop; + var oldState = prop.State; + await prop.SetState(config.TargetState); + var newState = prop.State; + await SendPacket(new PacketGroupStateChangeScNotify(Data.EntryId, prop.GroupID, prop.State)); + + switch (prop.Excel.PropType) + { + case PropTypeEnum.PROP_TREASURE_CHEST: + if (oldState == PropStateEnum.ChestClosed && newState == PropStateEnum.ChestUsed) + { + // TODO: Filter treasure chest + var items = DropService.CalculateDropsFromProp(); + await SceneInstance.Player.InventoryManager!.AddItems(items); + } + + break; + case PropTypeEnum.PROP_DESTRUCT: + if (newState == PropStateEnum.Closed) await prop.SetState(PropStateEnum.Open); + break; + case PropTypeEnum.PROP_MAZE_PUZZLE: + if (newState == PropStateEnum.Closed || newState == PropStateEnum.Open) + foreach (var p in SceneInstance.GetEntitiesInGroup(prop.GroupID)) + { + if (p.Excel.PropType == PropTypeEnum.PROP_TREASURE_CHEST) + { + await p.SetState(PropStateEnum.ChestUsed); + } + else if (p.Excel.PropType == PropTypeEnum.PROP_MAZE_PUZZLE) + { + // Skip + } + else + { + await p.SetState(PropStateEnum.Open); + } + + await MissionManager!.OnPlayerInteractWithProp(); + } + + break; + } + + // for door unlock + if (prop.PropInfo.UnlockDoorID.Count > 0) + foreach (var id in prop.PropInfo.UnlockDoorID) + foreach (var p in SceneInstance.GetEntitiesInGroup(id.Key)) + if (id.Value.Contains(p.PropInfo.ID)) + { + await p.SetState(PropStateEnum.Open); + await MissionManager!.OnPlayerInteractWithProp(); + } + + // for mission + await MissionManager!.OnPlayerInteractWithProp(); + + // plane event + InventoryManager!.HandlePlaneEvent(prop.PropInfo.EventID); + + // handle plugin event + InvokeOnPlayerInteract(this, prop); + + var floorSavedKey = prop.PropInfo.Name.Replace("Controller_", ""); + var key = $"FSV_ML{floorSavedKey}{(config.TargetState == PropStateEnum.Open ? "Started" : "Complete")}"; + if (SceneInstance?.FloorInfo?.SavedValues.Find(x => x.Name == key) != null) + { + // should save + var plane = SceneInstance.PlaneId; + var floor = SceneInstance.FloorId; + SceneData!.FloorSavedData.TryGetValue(floor, out var value); + if (value == null) + { + value = []; + SceneData.FloorSavedData[floor] = value; + } + + value[key] = 1; // ParamString[2] is the key + await SendPacket(new PacketUpdateFloorSavedValueNotify(key, 1)); + + TaskManager?.SceneTaskTrigger.TriggerFloor(plane, floor); + MissionManager?.HandleFinishType(MissionFinishTypeEnum.FloorSavedValue); + } + + return prop; + } + } + + return null; + } + + public async ValueTask EnterScene(int entryId, int teleportId, bool sendPacket, + ChangeStoryLineAction storyLineAction = ChangeStoryLineAction.None, int storyLineId = 0, bool mapTp = false) + { + if (storyLineId != StoryLineManager?.StoryLineData.CurStoryLineId) + { + StoryLineManager?.EnterStoryLine(storyLineId, entryId == 0); // entryId == 0 -> teleport + mapTp = false; // do not use mapTp when enter story line + } + + GameData.MapEntranceData.TryGetValue(entryId, out var entrance); + if (entrance == null) return false; + + GameData.GetFloorInfo(entrance.PlaneID, entrance.FloorID, out var floorInfo); + if (floorInfo == null) return false; + + var StartGroup = entrance.StartGroupID; + var StartAnchor = entrance.StartAnchorID; + + if (teleportId != 0) + { + floorInfo.CachedTeleports.TryGetValue(teleportId, out var teleport); + if (teleport != null) + { + StartGroup = teleport.AnchorGroupID; + StartAnchor = teleport.AnchorID; + } + } + else if (StartAnchor == 0) + { + StartGroup = floorInfo.StartGroupID; + StartAnchor = floorInfo.StartAnchorID; + } + + var anchor = floorInfo.GetAnchorInfo(StartGroup, StartAnchor); + + MissionManager?.HandleFinishType(MissionFinishTypeEnum.EnterMapByEntrance, entryId); + + var beforeEntryId = Data.EntryId; + + await LoadScene(entrance.PlaneID, entrance.FloorID, entryId, anchor!.ToPositionProto(), + anchor.ToRotationProto(), sendPacket, storyLineAction, mapTp); + + var afterEntryId = Data.EntryId; + + return beforeEntryId != afterEntryId; // return true if entryId changed + } + + public async ValueTask EnterMissionScene(int entranceId, int anchorGroupId, int anchorId, bool sendPacket, + ChangeStoryLineAction storyLineAction = ChangeStoryLineAction.None) + { + GameData.MapEntranceData.TryGetValue(entranceId, out var entrance); + if (entrance == null) return; + + GameData.GetFloorInfo(entrance.PlaneID, entrance.FloorID, out var floorInfo); + if (floorInfo == null) return; + + var StartGroup = anchorGroupId == 0 ? entrance.StartGroupID : anchorGroupId; + var StartAnchor = anchorId == 0 ? entrance.StartAnchorID : anchorId; + + if (StartAnchor == 0) + { + StartGroup = floorInfo.StartGroupID; + StartAnchor = floorInfo.StartAnchorID; + } + + var anchor = floorInfo.GetAnchorInfo(StartGroup, StartAnchor); + + await LoadScene(entrance.PlaneID, entrance.FloorID, entranceId, anchor!.ToPositionProto(), + anchor.ToRotationProto(), sendPacket, storyLineAction); + } + + public async ValueTask MoveTo(Position position) + { + Data.Pos = position; + await SendPacket(new PacketSceneEntityMoveScNotify(this)); + } + + public void MoveTo(EntityMotion motion) + { + Data.Pos = motion.Motion.Pos.ToPosition(); + Data.Rot = motion.Motion.Rot.ToPosition(); + } + + public async ValueTask MoveTo(Position pos, Position rot) + { + Data.Pos = pos; + Data.Rot = rot; + await SendPacket(new PacketSceneEntityMoveScNotify(this)); + } + + public async ValueTask LoadScene(int planeId, int floorId, int entryId, Position pos, Position rot, bool sendPacket, + ChangeStoryLineAction storyLineAction = ChangeStoryLineAction.None, bool mapTp = false) + { + GameData.MazePlaneData.TryGetValue(planeId, out var plane); + if (plane == null) return; + + if (plane.PlaneType == PlaneTypeEnum.Rogue && RogueManager!.GetRogueInstance() == null) + { + await EnterScene(801120102, 0, sendPacket); + return; + } + + if (plane.PlaneType == PlaneTypeEnum.Raid && RaidManager!.RaidData.CurRaidId == 0) + { + await EnterScene(2000101, 0, sendPacket); + return; + } + + if (plane.PlaneType == PlaneTypeEnum.Challenge && ChallengeManager!.ChallengeInstance == null) + { + await EnterScene(100000103, 0, sendPacket); + return; + } + + // TODO: Sanify check + Data.Pos = pos; + Data.Rot = rot; + var notSendMove = true; + SceneInstance instance = new(this, plane, floorId, entryId); + if (planeId != Data.PlaneId || floorId != Data.FloorId || entryId != Data.EntryId) + { + Data.PlaneId = planeId; + Data.FloorId = floorId; + Data.EntryId = entryId; + } + else if (StoryLineManager?.StoryLineData.CurStoryLineId == 0 && + mapTp) // only send move packet when not in story line and mapTp + { + notSendMove = false; + } + + SceneInstance = instance; + + MissionManager?.OnPlayerChangeScene(); + + Connection?.SendPacket(CmdIds.SyncServerSceneChangeNotify); + if (sendPacket && notSendMove) + await SendPacket(new PacketEnterSceneByServerScNotify(instance, storyLineAction)); + else if (sendPacket && !notSendMove) // send move packet + await SendPacket(new PacketSceneEntityMoveScNotify(this)); + + MissionManager?.HandleFinishType(MissionFinishTypeEnum.EnterFloor); + MissionManager?.HandleFinishType(MissionFinishTypeEnum.EnterPlane); + MissionManager?.HandleFinishType(MissionFinishTypeEnum.NotInFloor); + MissionManager?.HandleFinishType(MissionFinishTypeEnum.NotInPlane); + } + + public ScenePropData? GetScenePropData(int floorId, int groupId, int propId) + { + if (SceneData != null) + if (SceneData.ScenePropData.TryGetValue(floorId, out var floorData)) + if (floorData.TryGetValue(groupId, out var groupData)) + { + var propData = groupData.Find(x => x.PropId == propId); + return propData; + } + + return null; + } + + public void SetScenePropData(int floorId, int groupId, int propId, PropStateEnum state) + { + if (SceneData != null) + { + if (!SceneData.ScenePropData.TryGetValue(floorId, out var floorData)) + { + floorData = []; + SceneData.ScenePropData.Add(floorId, floorData); + } + + if (!floorData.TryGetValue(groupId, out var groupData)) + { + groupData = []; + floorData.Add(groupId, groupData); + } + + var propData = groupData.Find(x => x.PropId == propId); // find prop data + if (propData == null) + { + propData = new ScenePropData + { + PropId = propId, + State = state + }; + groupData.Add(propData); + } + else + { + propData.State = state; + } + } + } + + public void EnterSection(int sectionId) + { + if (SceneInstance != null) + { + SceneData!.UnlockSectionIdList.TryGetValue(SceneInstance.FloorId, out var unlockList); + if (unlockList == null) + { + unlockList = [sectionId]; + SceneData.UnlockSectionIdList.Add(SceneInstance.FloorId, unlockList); + } + else + { + SceneData.UnlockSectionIdList[SceneInstance.FloorId].Add(sectionId); + } + } + } + + public void SetCustomSaveData(int entryId, int groupId, string data) + { + if (SceneData != null) + { + if (!SceneData.CustomSaveData.TryGetValue(entryId, out var entryData)) + { + entryData = []; + SceneData.CustomSaveData.Add(entryId, entryData); + } + + entryData[groupId] = data; + } + } + + public async ValueTask ForceQuitBattle() + { + if (BattleInstance != null) + { + BattleInstance = null; + await Connection!.SendPacket(CmdIds.QuitBattleScNotify); + } + } + + #endregion + + #region Serialization + + public PlayerBasicInfo ToProto() + { + return Data.ToProto(); + } + + public PlayerSimpleInfo ToSimpleProto() + { + return Data.ToSimpleProto(FriendOnlineStatus.Online); + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Raid/RaidManager.cs b/GameServer/Game/Raid/RaidManager.cs index cb767894..a67a2a9f 100644 --- a/GameServer/Game/Raid/RaidManager.cs +++ b/GameServer/Game/Raid/RaidManager.cs @@ -1,316 +1,285 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Database.ChessRogue; using EggLink.DanhengServer.Database.Scene; using EggLink.DanhengServer.Enums; +using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game; -using EggLink.DanhengServer.Game.Lineup; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using EggLink.DanhengServer.Server.Packet.Send.Scene; -using Org.BouncyCastle.Ocsp; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Raid +namespace EggLink.DanhengServer.GameServer.Game.Raid; + +public class RaidManager : BasePlayerManager { - public class RaidManager : BasePlayerManager + public RaidManager(PlayerInstance player) : base(player) { - public RaidData RaidData { get; private set; } + RaidData = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); + var task = System.Threading.Tasks.Task.Run(async () => { await OnLogin(); }); + task.Wait(); + } - public RaidManager(PlayerInstance player) : base(player) + public RaidData RaidData { get; } + + #region Information + + public RaidStatus GetRaidStatus(int raidId, int worldLevel = 0) + { + if (!RaidData.RaidRecordDatas.TryGetValue(raidId, out var dict)) return RaidStatus.None; + if (!dict.TryGetValue(worldLevel, out var record)) return RaidStatus.None; + return record.Status; + } + + #endregion + + #region Player Handler + + public async ValueTask OnLogin() + { + // try resume + if (RaidData.CurRaidId > 0 && RaidData.RaidRecordDatas.TryGetValue(RaidData.CurRaidId, out var value)) { - RaidData = DatabaseHelper.Instance!.GetInstanceOrCreateNew(player.Uid); - OnLogin(); - } - - #region Player Action - - public void EnterRaid(int raidId, int worldLevel, List? avatarList = null, bool enterSaved = false) - { - if (RaidData.CurRaidId != 0) return; - - GameData.RaidConfigData.TryGetValue(raidId * 100 + worldLevel, out var excel); - if (excel == null) return; // not exist - - RaidData.RaidRecordDatas.TryGetValue(raidId, out var dict); - dict ??= []; - if (dict.ContainsKey(worldLevel) && !enterSaved) + if (value.TryGetValue(RaidData.CurRaidWorldLevel, out var record)) { - // clear old record - ClearRaid(raidId, worldLevel); - } - dict.TryGetValue(worldLevel, out var record); - - RaidData.CurRaidId = excel.RaidID; - RaidData.CurRaidWorldLevel = worldLevel; - - if (record == null) - { - // first enter - var entranceId = 0; - var firstMission = excel.MainMissionIDList[0]; - var subMissionId = GameData.MainMissionData[firstMission].MissionInfo!.StartSubMissionList[0]; // get the first sub mission - var subMission = GameData.SubMissionData[subMissionId]; - - entranceId = int.Parse(subMission.SubMissionInfo!.LevelFloorID.ToString().Replace("00", "0")); // get entrance id ( need to find a better way to do it ) - - if (!GameData.MapEntranceData.ContainsKey(entranceId)) - { - entranceId = subMission.SubMissionInfo!.LevelFloorID; - } - - if (avatarList?.Count > 0) - { - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, avatarList); - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - } - else if (excel.TeamType == Enums.Scene.RaidTeamTypeEnum.TrialOnly) - { - // set lineup - List list = [..excel.TrialAvatarList]; - if (list.Count > 0) - { - if (Player.Data.CurrentGender == Gender.Man) - { - foreach (var avatar in excel.TrialAvatarList) - { - if (avatar > 10000) // else is Base Avatar - { - if (avatar.ToString().EndsWith("8002") || - avatar.ToString().EndsWith("8004") || - avatar.ToString().EndsWith("8006")) - { - list.Remove(avatar); - } - } - } - } - else - { - foreach (var avatar in excel.TrialAvatarList) - { - if (avatar > 10000) // else is Base Avatar - { - if (avatar.ToString().EndsWith("8001") || - avatar.ToString().EndsWith("8003") || - avatar.ToString().EndsWith("8005")) - { - list.Remove(avatar); - } - } - } - } - } - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, list); - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - } - else - { - // set cur lineup - var lineup = Player.LineupManager!.GetCurLineup()!; - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, lineup.BaseAvatars!.Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId).ToList()); - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - } - var oldEntryId = Player.Data.EntryId; - var oldPos = Player.Data.Pos; - var oldRot = Player.Data.Rot; - - Player.MissionManager!.AcceptMainMission(firstMission); - - Player.EnterScene(entranceId, 0, true); - - record = new RaidRecord() - { - PlaneId = Player.Data.PlaneId, - FloorId = Player.Data.FloorId, - EntryId = entranceId, - Pos = Player.Data.Pos!, - Rot = Player.Data.Rot!, - Status = RaidStatus.Doing, - WorldLevel = worldLevel, - RaidId = raidId, - Lineup = Player.LineupManager!.GetCurLineup()!.BaseAvatars!, - OldEntryId = oldEntryId, - OldPos = oldPos!, - OldRot = oldRot! - }; - - if (RaidData.RaidRecordDatas.TryGetValue(raidId, out Dictionary? value)) - { - value[worldLevel] = record; - } - else - { - RaidData.RaidRecordDatas[raidId] = new Dictionary() { { worldLevel, record } }; - } + await Player.SendPacket(new PacketRaidInfoNotify(record)); } else - { - // just resume - record.Status = RaidStatus.Doing; - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, record.Lineup.Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId).ToList()); - Player.LoadScene(record.PlaneId, record.FloorId, record.EntryId, record.Pos, record.Rot, true); - } - - Player.SendPacket(new PacketRaidInfoNotify(record)); - } - - public void CheckIfLeaveRaid() - { - if (RaidData.CurRaidId == 0) return; - - var record = RaidData.RaidRecordDatas[RaidData.CurRaidId][RaidData.CurRaidWorldLevel]; - - GameData.RaidConfigData.TryGetValue(RaidData.CurRaidId * 100 + record.WorldLevel, out var excel); - if (excel == null) return; - bool leave = true; - foreach (var id in excel.MainMissionIDList) - { - if (Player.MissionManager!.GetMainMissionStatus(id) != MissionPhaseEnum.Finish) - { - leave = false; - } - } - - if (leave) - { - FinishRaid(); - // finish - Player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.RaidFinishCnt); - } - } - - public void FinishRaid() - { - if (RaidData.CurRaidId == 0) return; - - var record = RaidData.RaidRecordDatas[RaidData.CurRaidId][RaidData.CurRaidWorldLevel]; - GameData.RaidConfigData.TryGetValue(RaidData.CurRaidId * 100 + record.WorldLevel, out var config); - if (config == null) return; - - record.Status = RaidStatus.Finish; - - Player.SendPacket(new PacketRaidInfoNotify(record)); - } - - public void LeaveRaid(bool save) - { - if (RaidData.CurRaidId == 0) return; - - var record = RaidData.RaidRecordDatas[RaidData.CurRaidId][RaidData.CurRaidWorldLevel]; - GameData.RaidConfigData.TryGetValue(RaidData.CurRaidId * 100 + record.WorldLevel, out var config); - if (config == null) return; - - record.PlaneId = Player.Data.PlaneId; - record.FloorId = Player.Data.FloorId; - record.EntryId = Player.Data.EntryId; - record.Pos = Player.Data.Pos!; - record.Rot = Player.Data.Rot!; - - if (Player.LineupManager!.GetCurLineup()!.IsExtraLineup()) - { - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - } - - if (record.Status == RaidStatus.Finish) - { - Player.SendPacket(new PacketRaidInfoNotify()); - if (config.FinishEntranceID > 0) - { - Player.EnterScene(config.FinishEntranceID, 0, true); - } - else - { - Player.EnterScene(record.OldEntryId, 0, true); - Player.MoveTo(record.OldPos, record.OldRot); - } - } - else - { - Player.EnterScene(record.OldEntryId, 0, true); - Player.MoveTo(record.OldPos, record.OldRot); - - // reset raid info - - Player.SendPacket(new PacketRaidInfoNotify()); - - if (!save) - { - ClearRaid(record.RaidId, record.WorldLevel); - } - } - - RaidData.CurRaidId = 0; - RaidData.CurRaidWorldLevel = 0; - } - - public void ClearRaid(int raidId, int worldLevel) - { - if (!RaidData.RaidRecordDatas.TryGetValue(raidId, out var dict)) return; - if (!dict.TryGetValue(worldLevel, out var record)) return; - - GameData.RaidConfigData.TryGetValue(raidId * 100 + worldLevel, out var config); - if (config == null) return; - - config.MainMissionIDList.ForEach(missionId => - { - Player.MissionManager!.RemoveMainMission(missionId); - }); - - dict.Remove(worldLevel); - - if (dict.Count == 0) - { - RaidData.RaidRecordDatas.Remove(raidId); - } - - Player.SendPacket(new PacketDelSaveRaidScNotify(raidId, worldLevel)); - } - - #endregion - - #region Information - - public RaidStatus GetRaidStatus(int raidId, int worldLevel = 0) - { - if (!RaidData.RaidRecordDatas.TryGetValue(raidId, out var dict)) return RaidStatus.None; - if (!dict.TryGetValue(worldLevel, out var record)) return RaidStatus.None; - return record.Status; - } - - #endregion - - #region Player Handler - - public void OnLogin() - { - // try resume - if (RaidData.CurRaidId > 0 && RaidData.RaidRecordDatas.TryGetValue(RaidData.CurRaidId, out Dictionary? value)) - { - if (value.TryGetValue(RaidData.CurRaidWorldLevel, out var record)) - { - Player.SendPacket(new PacketRaidInfoNotify(record)); - } - else - { - RaidData.CurRaidId = 0; - RaidData.CurRaidWorldLevel = 0; - } - } else { RaidData.CurRaidId = 0; RaidData.CurRaidWorldLevel = 0; } } - - #endregion + else + { + RaidData.CurRaidId = 0; + RaidData.CurRaidWorldLevel = 0; + } } + + #endregion + + #region Player Action + + public async ValueTask EnterRaid(int raidId, int worldLevel, List? avatarList = null, bool enterSaved = false) + { + if (RaidData.CurRaidId != 0) return; + + GameData.RaidConfigData.TryGetValue(raidId * 100 + worldLevel, out var excel); + if (excel == null) return; // not exist + + RaidData.RaidRecordDatas.TryGetValue(raidId, out var dict); + dict ??= []; + if (dict.ContainsKey(worldLevel) && !enterSaved) + // clear old record + await ClearRaid(raidId, worldLevel); + dict.TryGetValue(worldLevel, out var record); + + RaidData.CurRaidId = excel.RaidID; + RaidData.CurRaidWorldLevel = worldLevel; + + if (record == null) + { + // first enter + var entranceId = 0; + var firstMission = excel.MainMissionIDList[0]; + var subMissionId = + GameData.MainMissionData[firstMission].MissionInfo!.StartSubMissionList[0]; // get the first sub mission + var subMission = GameData.SubMissionData[subMissionId]; + + entranceId = + int.Parse(subMission.SubMissionInfo!.LevelFloorID.ToString() + .Replace("00", "0")); // get entrance id ( need to find a better way to do it ) + + if (!GameData.MapEntranceData.ContainsKey(entranceId)) entranceId = subMission.SubMissionInfo!.LevelFloorID; + + if (avatarList?.Count > 0) + { + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, avatarList); + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + } + else if (excel.TeamType == RaidTeamTypeEnum.TrialOnly) + { + // set lineup + List list = [..excel.TrialAvatarList]; + if (list.Count > 0) + { + if (Player.Data.CurrentGender == Gender.Man) + { + foreach (var avatar in excel.TrialAvatarList) + if (avatar > 10000) // else is Base Avatar + if (avatar.ToString().EndsWith("8002") || + avatar.ToString().EndsWith("8004") || + avatar.ToString().EndsWith("8006")) + list.Remove(avatar); + } + else + { + foreach (var avatar in excel.TrialAvatarList) + if (avatar > 10000) // else is Base Avatar + if (avatar.ToString().EndsWith("8001") || + avatar.ToString().EndsWith("8003") || + avatar.ToString().EndsWith("8005")) + list.Remove(avatar); + } + } + + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, list); + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + } + else + { + // set cur lineup + var lineup = Player.LineupManager!.GetCurLineup()!; + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, + lineup.BaseAvatars!.Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId) + .ToList()); + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + } + + var oldEntryId = Player.Data.EntryId; + var oldPos = Player.Data.Pos; + var oldRot = Player.Data.Rot; + + await Player.MissionManager!.AcceptMainMission(firstMission); + + await Player.EnterScene(entranceId, 0, true); + + record = new RaidRecord + { + PlaneId = Player.Data.PlaneId, + FloorId = Player.Data.FloorId, + EntryId = entranceId, + Pos = Player.Data.Pos!, + Rot = Player.Data.Rot!, + Status = RaidStatus.Doing, + WorldLevel = worldLevel, + RaidId = raidId, + Lineup = Player.LineupManager!.GetCurLineup()!.BaseAvatars!, + OldEntryId = oldEntryId, + OldPos = oldPos!, + OldRot = oldRot! + }; + + if (RaidData.RaidRecordDatas.TryGetValue(raidId, out var value)) + value[worldLevel] = record; + else + RaidData.RaidRecordDatas[raidId] = new Dictionary { { worldLevel, record } }; + } + else + { + // just resume + record.Status = RaidStatus.Doing; + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupHeliobus, + record.Lineup.Select(x => x.SpecialAvatarId > 0 ? x.SpecialAvatarId / 10 : x.BaseAvatarId).ToList()); + await Player.LoadScene(record.PlaneId, record.FloorId, record.EntryId, record.Pos, record.Rot, true); + } + + await Player.SendPacket(new PacketRaidInfoNotify(record)); + } + + public async ValueTask CheckIfLeaveRaid() + { + if (RaidData.CurRaidId == 0) return; + + var record = RaidData.RaidRecordDatas[RaidData.CurRaidId][RaidData.CurRaidWorldLevel]; + + GameData.RaidConfigData.TryGetValue(RaidData.CurRaidId * 100 + record.WorldLevel, out var excel); + if (excel == null) return; + var leave = true; + foreach (var id in excel.MainMissionIDList) + if (Player.MissionManager!.GetMainMissionStatus(id) != MissionPhaseEnum.Finish) + leave = false; + + if (leave) + { + await FinishRaid(); + // finish + await Player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.RaidFinishCnt); + } + } + + public async ValueTask FinishRaid() + { + if (RaidData.CurRaidId == 0) return; + + var record = RaidData.RaidRecordDatas[RaidData.CurRaidId][RaidData.CurRaidWorldLevel]; + GameData.RaidConfigData.TryGetValue(RaidData.CurRaidId * 100 + record.WorldLevel, out var config); + if (config == null) return; + + record.Status = RaidStatus.Finish; + + await Player.SendPacket(new PacketRaidInfoNotify(record)); + } + + public async ValueTask LeaveRaid(bool save) + { + if (RaidData.CurRaidId == 0) return; + + var record = RaidData.RaidRecordDatas[RaidData.CurRaidId][RaidData.CurRaidWorldLevel]; + GameData.RaidConfigData.TryGetValue(RaidData.CurRaidId * 100 + record.WorldLevel, out var config); + if (config == null) return; + + record.PlaneId = Player.Data.PlaneId; + record.FloorId = Player.Data.FloorId; + record.EntryId = Player.Data.EntryId; + record.Pos = Player.Data.Pos!; + record.Rot = Player.Data.Rot!; + + if (Player.LineupManager!.GetCurLineup()!.IsExtraLineup()) + { + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + } + + if (record.Status == RaidStatus.Finish) + { + await Player.SendPacket(new PacketRaidInfoNotify()); + if (config.FinishEntranceID > 0) + { + await Player.EnterScene(config.FinishEntranceID, 0, true); + } + else + { + await Player.EnterScene(record.OldEntryId, 0, true); + await Player.MoveTo(record.OldPos, record.OldRot); + } + } + else + { + await Player.EnterScene(record.OldEntryId, 0, true); + await Player.MoveTo(record.OldPos, record.OldRot); + + // reset raid info + + await Player.SendPacket(new PacketRaidInfoNotify()); + + if (!save) await ClearRaid(record.RaidId, record.WorldLevel); + } + + RaidData.CurRaidId = 0; + RaidData.CurRaidWorldLevel = 0; + } + + public async ValueTask ClearRaid(int raidId, int worldLevel) + { + if (!RaidData.RaidRecordDatas.TryGetValue(raidId, out var dict)) return; + if (!dict.TryGetValue(worldLevel, out var record)) return; + + GameData.RaidConfigData.TryGetValue(raidId * 100 + worldLevel, out var config); + if (config == null) return; + + config.MainMissionIDList.ForEach(async missionId => + { + await Player.MissionManager!.RemoveMainMission(missionId); + }); + + dict.Remove(worldLevel); + + if (dict.Count == 0) RaidData.RaidRecordDatas.Remove(raidId); + + await Player.SendPacket(new PacketDelSaveRaidScNotify(raidId, worldLevel)); + } + + #endregion } \ No newline at end of file diff --git a/GameServer/Game/Rogue/BaseRogueInstance.cs b/GameServer/Game/Rogue/BaseRogueInstance.cs index 4b73388b..b1464138 100644 --- a/GameServer/Game/Rogue/BaseRogueInstance.cs +++ b/GameServer/Game/Rogue/BaseRogueInstance.cs @@ -1,482 +1,426 @@ -using EggLink.DanhengServer.Data.Excel; -using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Data.Excel; +using EggLink.DanhengServer.Database.Inventory; +using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Rogue.Buff; using EggLink.DanhengServer.Game.Rogue.Event; using EggLink.DanhengServer.Game.Rogue.Miracle; -using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Server.Packet.Send.Rogue; using EggLink.DanhengServer.Game.Rogue.Scene.Entity; -using EggLink.DanhengServer.Util; -using EggLink.DanhengServer.Server.Packet.Send.Scene; -using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.GameServer.Server.Packet.Send.Rogue; +using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Server.Packet.Send.Rogue; +using EggLink.DanhengServer.Server.Packet.Send.Scene; +using EggLink.DanhengServer.Util; +using LineupInfo = EggLink.DanhengServer.Database.Lineup.LineupInfo; -namespace EggLink.DanhengServer.Game.Rogue +namespace EggLink.DanhengServer.Game.Rogue; + +public abstract class BaseRogueInstance(PlayerInstance player, int rogueVersionId, int rogueBuffType) { - public class BaseRogueInstance(PlayerInstance player, int rogueVersionId, int rogueBuffType) + public PlayerInstance Player { get; set; } = player; + public LineupInfo? CurLineup { get; set; } + public int RogueVersionId { get; set; } = rogueVersionId; + public int RogueType { get; set; } = 100; + public int CurReviveCost { get; set; } = 80; + public int CurRerollCost { get; set; } = 30; + public int BaseRerollCount { get; set; } = 1; + public int BaseRerollFreeCount { get; set; } = 0; + public int CurMoney { get; set; } = 100; + public int CurDestroyCount { get; set; } + public int AeonId { get; set; } = 0; + public int RogueBuffType { get; set; } = rogueBuffType; + public bool IsWin { get; set; } = false; + public List RogueBuffs { get; set; } = []; + public Dictionary RogueMiracles { get; set; } = []; + + public SortedDictionary RogueActions { get; set; } = []; // queue_position -> action + public int CurActionQueuePosition { get; set; } = 0; + public int CurEventUniqueID { get; set; } = 100; + + public int CurAeonBuffCount { get; set; } = 0; + public int CurAeonEnhanceCount { get; set; } = 0; + public bool AeonBuffPending { get; set; } // prevent multiple aeon buff + + public RogueEventManager? EventManager { get; set; } + + #region Buffs + + public virtual async ValueTask RollBuff(int amount) { - public PlayerInstance Player { get; set; } = player; - public Database.Lineup.LineupInfo? CurLineup { get; set; } - public int RogueVersionId { get; set; } = rogueVersionId; - public int RogueType { get; set; } = 100; - public int CurReviveCost { get; set; } = 80; - public int CurRerollCost { get; set; } = 30; - public int BaseRerollCount { get; set; } = 1; - public int BaseRerollFreeCount { get; set; } = 0; - public int CurMoney { get; set; } = 100; - public int CurDestroyCount { get; set; } = 0; - public int AeonId { get; set; } = 0; - public int RogueBuffType { get; set; } = rogueBuffType; - public bool IsWin { get; set; } = false; - public List RogueBuffs { get; set; } = []; - public Dictionary RogueMiracles { get; set; } = []; + await RollBuff(amount, 100005); + } - public SortedDictionary RogueActions { get; set; } = []; // queue_position -> action - public int CurActionQueuePosition { get; set; } = 0; - public int CurEventUniqueID { get; set; } = 100; + public virtual async ValueTask RollBuff(int amount, int buffGroupId, int buffHintType = 1) + { + var buffGroup = GameData.RogueBuffGroupData[buffGroupId]; + var buffList = buffGroup.BuffList; + var actualBuffList = new List(); + foreach (var buff in buffList) + if (!RogueBuffs.Exists(x => x.BuffExcel.MazeBuffID == buff.MazeBuffID)) + actualBuffList.Add(buff); - public int CurAeonBuffCount { get; set; } = 0; - public int CurAeonEnhanceCount { get; set; } = 0; - public bool AeonBuffPending { get; set; } = false; // prevent multiple aeon buff + if (actualBuffList.Count == 0) return; // no buffs to roll - public RogueEventManager? EventManager { get; set; } - - #region Buffs - - public virtual void RollBuff(int amount) + for (var i = 0; i < amount; i++) { - RollBuff(amount, 100005); + var menu = new RogueBuffSelectMenu(this) + { + CurCount = i + 1, + TotalCount = amount + }; + menu.RollBuff(actualBuffList); + menu.HintId = buffHintType; + var action = menu.GetActionInstance(); + RogueActions.Add(action.QueuePosition, action); } - public virtual void RollBuff(int amount, int buffGroupId, int buffHintType = 1) - { - var buffGroup = GameData.RogueBuffGroupData[buffGroupId]; - var buffList = buffGroup.BuffList; - var actualBuffList = new List(); - foreach (var buff in buffList) - { - if (!RogueBuffs.Exists(x => x.BuffExcel.MazeBuffID == buff.MazeBuffID)) - { - actualBuffList.Add(buff); - } - } + await UpdateMenu(); + } - if (actualBuffList.Count == 0) - { - return; // no buffs to roll - } - - for (int i = 0; i < amount; i++) - { - var menu = new RogueBuffSelectMenu(this) - { - CurCount = i + 1, - TotalCount = amount, - }; - menu.RollBuff(actualBuffList); - menu.HintId = buffHintType; - var action = menu.GetActionInstance(); - RogueActions.Add(action.QueuePosition, action); - } - - UpdateMenu(); - } - - public virtual RogueCommonActionResult? AddBuff(int buffId, int level = 1, RogueActionSource source = RogueActionSource.RogueCommonActionResultSourceTypeDialogue, RogueActionDisplayType displayType = RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle, bool updateMenu = true, bool notify = true) - { - if (RogueBuffs.Exists(x => x.BuffExcel.MazeBuffID == buffId)) - { + public virtual async ValueTask AddBuff(int buffId, int level = 1, + RogueActionSource source = RogueActionSource.RogueCommonActionResultSourceTypeDialogue, + RogueActionDisplayType displayType = RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle, + bool updateMenu = true, bool notify = true) + { + if (RogueBuffs.Exists(x => x.BuffExcel.MazeBuffID == buffId)) return null; + GameData.RogueBuffData.TryGetValue(buffId * 100 + level, out var excel); + if (excel == null) return null; + if (CurAeonBuffCount > 0) // check if aeon buff exists + if (excel.IsAeonBuff) return null; - } - GameData.RogueBuffData.TryGetValue(buffId * 100 + level, out var excel); - if (excel == null) return null; - if (CurAeonBuffCount > 0) // check if aeon buff exists + var buff = new RogueBuffInstance(buffId, level); + RogueBuffs.Add(buff); + var result = buff.ToResultProto(source); + + if (notify) + await Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, result, displayType)); + + if (updateMenu) await UpdateMenu(); + + return result; + } + + public virtual async ValueTask AddBuffList(List excel) + { + List resultList = []; + foreach (var buff in excel) + { + var res = await AddBuff(buff.MazeBuffID, buff.MazeBuffLevel, + displayType: RogueActionDisplayType.RogueCommonActionResultDisplayTypeMulti, updateMenu: false, + notify: false); + if (res != null) resultList.Add(res); + } + + await Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, resultList, + RogueActionDisplayType.RogueCommonActionResultDisplayTypeMulti)); + + await UpdateMenu(); + } + + public virtual async ValueTask EnhanceBuff(int buffId, + RogueActionSource source = RogueActionSource.RogueCommonActionResultSourceTypeDialogue) + { + var buff = RogueBuffs.Find(x => x.BuffExcel.MazeBuffID == buffId); + if (buff != null) + { + GameData.RogueBuffData.TryGetValue(buffId * 100 + buff.BuffLevel + 1, + out var excel); // make sure the next level exists + if (excel != null) { - if (excel.IsAeonBuff) + buff.BuffLevel++; + await Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, + buff.ToResultProto(source), RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle)); + } + } + } + + public virtual List GetRogueBuffInGroup(int groupId) + { + var group = GameData.RogueBuffGroupData[groupId]; + return RogueBuffs.FindAll(x => group.BuffList.Contains(x.BuffExcel)); + } + + public virtual async ValueTask HandleBuffSelect(int buffId) + { + if (RogueActions.Count == 0) return; + + var action = RogueActions.First().Value; + if (action.RogueBuffSelectMenu != null) + { + var buff = action.RogueBuffSelectMenu.Buffs.Find(x => x.MazeBuffID == buffId); + if (buff != null) // check if buff is in the list + { + if (RogueBuffs.Exists(x => x.BuffExcel.MazeBuffID == buffId)) // check if buff already exists { - return null; + // enhance + await EnhanceBuff(buffId, RogueActionSource.RogueCommonActionResultSourceTypeSelect); } - } - var buff = new RogueBuffInstance(buffId, level); - RogueBuffs.Add(buff); - var result = buff.ToResultProto(source); - - if (notify) - { - Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, result, displayType)); - } - - if (updateMenu) - { - UpdateMenu(); - } - - return result; - } - - public virtual void AddBuffList(List excel) - { - List resultList = []; - foreach (var buff in excel) - { - var res = AddBuff(buff.MazeBuffID, buff.MazeBuffLevel, displayType: RogueActionDisplayType.RogueCommonActionResultDisplayTypeMulti, updateMenu: false, notify: false); - if (res != null) + else { - resultList.Add(res); + var instance = new RogueBuffInstance(buff.MazeBuffID, buff.MazeBuffLevel); + RogueBuffs.Add(instance); + await Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, + instance.ToResultProto(RogueActionSource.RogueCommonActionResultSourceTypeSelect))); } } - Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, resultList, RogueActionDisplayType.RogueCommonActionResultDisplayTypeMulti)); - - UpdateMenu(); - } - - public virtual void EnhanceBuff(int buffId, RogueActionSource source = RogueActionSource.RogueCommonActionResultSourceTypeDialogue) - { - var buff = RogueBuffs.Find(x => x.BuffExcel.MazeBuffID == buffId); - if (buff != null) - { - GameData.RogueBuffData.TryGetValue(buffId * 100 + buff.BuffLevel + 1, out var excel); // make sure the next level exists - if (excel != null) - { - buff.BuffLevel++; - Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, buff.ToResultProto(source), RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle)); - } - } - } - - public virtual List GetRogueBuffInGroup(int groupId) - { - var group = GameData.RogueBuffGroupData[groupId]; - return RogueBuffs.FindAll(x => group.BuffList.Contains(x.BuffExcel)); - } - - public virtual void HandleBuffSelect(int buffId) - { - if (RogueActions.Count == 0) - { - return; - } - - var action = RogueActions.First().Value; - if (action.RogueBuffSelectMenu != null) - { - var buff = action.RogueBuffSelectMenu.Buffs.Find(x => x.MazeBuffID == buffId); - if (buff != null) // check if buff is in the list - { - if (RogueBuffs.Exists(x => x.BuffExcel.MazeBuffID == buffId)) // check if buff already exists - { - // enhance - EnhanceBuff(buffId, RogueActionSource.RogueCommonActionResultSourceTypeSelect); - } - else - { - var instance = new RogueBuffInstance(buff.MazeBuffID, buff.MazeBuffLevel); - RogueBuffs.Add(instance); - Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, instance.ToResultProto(RogueActionSource.RogueCommonActionResultSourceTypeSelect))); - } - } - RogueActions.Remove(action.QueuePosition); - if (action.RogueBuffSelectMenu.IsAeonBuff) - { - AeonBuffPending = false; // aeon buff added - } - } - - UpdateMenu(); - - Player.SendPacket(new PacketHandleRogueCommonPendingActionScRsp(action.QueuePosition, selectBuff: true)); - } - - public virtual void HandleRerollBuff() - { - if (RogueActions.Count == 0) - { - return; - } - var action = RogueActions.First().Value; - if (action.RogueBuffSelectMenu != null) - { - action.RogueBuffSelectMenu.RerollBuff(); // reroll - Player.SendPacket(new PacketHandleRogueCommonPendingActionScRsp(RogueVersionId, menu: action.RogueBuffSelectMenu)); - } - } - - #endregion - - #region Money - - public void CostMoney(int amount, RogueActionDisplayType displayType = RogueActionDisplayType.RogueCommonActionResultDisplayTypeNone) - { - CurMoney -= amount; - Player.SendPacket(new PacketSyncRogueCommonVirtualItemInfoScNotify(this)); - - Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, new RogueCommonActionResult() - { - Source = RogueActionSource.RogueCommonActionResultSourceTypeDialogue, - RogueAction = new() - { - RemoveItemList = new() - { - Num = (uint)amount, - DisplayType = (uint)displayType + 1, - }, - }, - }, displayType)); - } - - public void GainMoney(int amount, int displayType = 2, RogueActionDisplayType display = RogueActionDisplayType.RogueCommonActionResultDisplayTypeNone) - { - CurMoney += amount; - Player.SendPacket(new PacketSyncRogueCommonVirtualItemInfoScNotify(this)); - Player.SendPacket(new PacketScenePlaneEventScNotify(new Database.Inventory.ItemData() - { - ItemId = 31, - Count = amount, - })); - - Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, new RogueCommonActionResult() - { - Source = RogueActionSource.RogueCommonActionResultSourceTypeDialogue, - RogueAction = new() - { - GetItemList = new() - { - Num = (uint)amount, - DisplayType = (uint)displayType, - }, - }, - }, display)); - } - - #endregion - - - #region Miracles - - public virtual void RollMiracle(int amount, int groupId = 10002) - { - GameData.RogueMiracleGroupData.TryGetValue(groupId, out var group); - if (group == null) return; - - for (int i = 0; i < amount; i++) - { - var list = new List(); - - foreach (var miracle in group) - { - if (RogueMiracles.ContainsKey(miracle)) - { - continue; - } - list.Add(miracle); - } - - if (list.Count == 0) return; - - var menu = new RogueMiracleSelectMenu(this); - menu.RollMiracle(list); - var action = menu.GetActionInstance(); - RogueActions.Add(action.QueuePosition, action); - } - - UpdateMenu(); - } - - public virtual void HandleMiracleSelect(uint miracleId) - { - if (RogueActions.Count == 0) - { - return; - } - - var action = RogueActions.First().Value; - if (action.RogueMiracleSelectMenu != null) - { - var miracle = action.RogueMiracleSelectMenu.Results.Find(x => x == miracleId); - if (miracle != 0) - { - AddMiracle((int)miracle); - } - RogueActions.Remove(action.QueuePosition); - } - - UpdateMenu(); - - Player.SendPacket(new PacketHandleRogueCommonPendingActionScRsp(action.QueuePosition, selectMiracle: true)); - } - - public virtual void AddMiracle(int miracleId) - { - if (RogueMiracles.ContainsKey(miracleId)) - { - return; - } - - GameData.RogueMiracleData.TryGetValue(miracleId, out var excel); - if (excel == null) return; - - var miracle = new RogueMiracleInstance(this, miracleId); - RogueMiracles.Add(miracleId, miracle); - Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, miracle.ToGetResult(), RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle)); - } - - #endregion - - #region Actions - - public virtual void HandleBonusSelect(int bonusId) - { - if (RogueActions.Count == 0) - { - return; - } - - var action = RogueActions.First().Value; - - // TODO: handle bonus - GameData.RogueBonusData.TryGetValue(bonusId, out var bonus); - if (bonus != null) - { - TriggerEvent(null, bonus.BonusEvent); - } - RogueActions.Remove(action.QueuePosition); - UpdateMenu(); - - Player.SendPacket(new PacketHandleRogueCommonPendingActionScRsp(action.QueuePosition, selectBonus: true)); + if (action.RogueBuffSelectMenu.IsAeonBuff) AeonBuffPending = false; // aeon buff added } - public virtual void UpdateMenu() - { - if (RogueActions.Count > 0) - { - Player.SendPacket(new PacketSyncRogueCommonPendingActionScNotify(RogueActions.First().Value, RogueVersionId)); - } - } + await UpdateMenu(); - #endregion - - #region Handlers - - public virtual void OnBattleStart(BattleInstance battle) - { - foreach (var miracle in RogueMiracles.Values) - { - miracle.OnStartBattle(battle); - } - - foreach (var buff in RogueBuffs) - { - buff.OnStartBattle(battle); - } - } - - public virtual void OnBattleEnd(BattleInstance battle, PVEBattleResultCsReq req) - { - foreach (var miracle in RogueMiracles.Values) - { - miracle.OnEndBattle(battle); - } - } - - public virtual void OnPropDestruct(EntityProp prop) - { - if (!prop.Excel.IsHpRecover && !prop.Excel.IsMpRecover) - { - // gain money - GainMoney(Random.Shared.Next(10, 30)); - } - - CurDestroyCount++; - } - - #endregion - - #region Events - - public void TriggerEvent(RogueEventInstance? rogueEvent, int eventId) - { - EventManager?.TriggerEvent(rogueEvent, eventId); - } - - public RogueEventInstance GenerateEvent(RogueNpc npc) - { - RogueNPCDialogueExcel? dialogue; - do - { - dialogue = GameData.RogueNPCDialogueData.Values.ToList().RandomElement(); - } while (dialogue == null || !dialogue.CanUseInVer(RogueType)); - - var instance = new RogueEventInstance(dialogue, npc, CurEventUniqueID++); - EventManager?.AddEvent(instance); - - return instance; - } - - public void HandleSelectOption(int eventUniqueId, int optionId) - { - var entity = Player.SceneInstance!.Entities.Values.FirstOrDefault(x => x is RogueNpc npc && npc.RogueEvent?.EventUniqueId == eventUniqueId); - if (entity is not RogueNpc npc) - { - return; - } - - EventManager?.SelectOption(npc.RogueEvent!, optionId); - } - - public void HandleFinishDialogueGroup(int eventUniqueId) - { - var entity = Player.SceneInstance!.Entities.Values.FirstOrDefault(x => x is RogueNpc npc && npc.RogueEvent?.EventUniqueId == eventUniqueId); - if (entity == null || entity is not RogueNpc npc) - { - return; - } - - EventManager?.FinishEvent(npc.RogueEvent!); - } - - public void HandleNpcDisappear(int entityId) - { - Player.SceneInstance!.Entities.TryGetValue(entityId, out var entity); - if (entity == null || entity is not RogueNpc npc) - { - return; - } - - EventManager?.NpcDisappear(npc.RogueEvent!); - } - - #endregion - - #region Serialization - - public RogueBuffEnhanceInfo ToEnhanceInfo() - { - var proto = new RogueBuffEnhanceInfo(); - - foreach (var buff in RogueBuffs) - { - proto.EnhanceInfo.Add(buff.ToEnhanceProto()); - } - - return proto; - } - - public ChessRogueBuffEnhanceInfo ToChessEnhanceInfo() - { - var proto = new ChessRogueBuffEnhanceInfo(); - - foreach (var buff in RogueBuffs) - { - proto.EnhanceInfo.Add(buff.ToChessEnhanceProto()); - } - - return proto; - } - - #endregion + await Player.SendPacket(new PacketHandleRogueCommonPendingActionScRsp(action.QueuePosition, true)); } -} + + public virtual async ValueTask HandleRerollBuff() + { + if (RogueActions.Count == 0) return; + var action = RogueActions.First().Value; + if (action.RogueBuffSelectMenu != null) + { + await action.RogueBuffSelectMenu.RerollBuff(); // reroll + await Player.SendPacket( + new PacketHandleRogueCommonPendingActionScRsp(RogueVersionId, menu: action.RogueBuffSelectMenu)); + } + } + + #endregion + + #region Money + + public async ValueTask CostMoney(int amount, + RogueActionDisplayType displayType = RogueActionDisplayType.RogueCommonActionResultDisplayTypeNone) + { + CurMoney -= amount; + await Player.SendPacket(new PacketSyncRogueCommonVirtualItemInfoScNotify(this)); + + await Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, + new RogueCommonActionResult + { + Source = RogueActionSource.RogueCommonActionResultSourceTypeDialogue, + RogueAction = new RogueCommonActionResultData + { + RemoveItemList = new RogueCommonMoney + { + Num = (uint)amount, + DisplayType = (uint)displayType + 1 + } + } + }, displayType)); + } + + public async ValueTask GainMoney(int amount, int displayType = 2, + RogueActionDisplayType display = RogueActionDisplayType.RogueCommonActionResultDisplayTypeNone) + { + CurMoney += amount; + await Player.SendPacket(new PacketSyncRogueCommonVirtualItemInfoScNotify(this)); + await Player.SendPacket(new PacketScenePlaneEventScNotify(new ItemData + { + ItemId = 31, + Count = amount + })); + + await Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, + new RogueCommonActionResult + { + Source = RogueActionSource.RogueCommonActionResultSourceTypeDialogue, + RogueAction = new RogueCommonActionResultData + { + GetItemList = new RogueCommonMoney + { + Num = (uint)amount, + DisplayType = (uint)displayType + } + } + }, display)); + } + + #endregion + + + #region Miracles + + public virtual async ValueTask RollMiracle(int amount, int groupId = 10002) + { + GameData.RogueMiracleGroupData.TryGetValue(groupId, out var group); + if (group == null) return; + + for (var i = 0; i < amount; i++) + { + var list = new List(); + + foreach (var miracle in group) + { + if (RogueMiracles.ContainsKey(miracle)) continue; + list.Add(miracle); + } + + if (list.Count == 0) return; + + var menu = new RogueMiracleSelectMenu(this); + menu.RollMiracle(list); + var action = menu.GetActionInstance(); + RogueActions.Add(action.QueuePosition, action); + } + + await UpdateMenu(); + } + + public virtual async ValueTask HandleMiracleSelect(uint miracleId) + { + if (RogueActions.Count == 0) return; + + var action = RogueActions.First().Value; + if (action.RogueMiracleSelectMenu != null) + { + var miracle = action.RogueMiracleSelectMenu.Results.Find(x => x == miracleId); + if (miracle != 0) await AddMiracle((int)miracle); + RogueActions.Remove(action.QueuePosition); + } + + await UpdateMenu(); + + await Player.SendPacket( + new PacketHandleRogueCommonPendingActionScRsp(action.QueuePosition, selectMiracle: true)); + } + + public virtual async ValueTask AddMiracle(int miracleId) + { + if (RogueMiracles.ContainsKey(miracleId)) return; + + GameData.RogueMiracleData.TryGetValue(miracleId, out var excel); + if (excel == null) return; + + var miracle = new RogueMiracleInstance(this, miracleId); + RogueMiracles.Add(miracleId, miracle); + await Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(RogueVersionId, miracle.ToGetResult(), + RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle)); + } + + #endregion + + #region Actions + + public virtual async ValueTask HandleBonusSelect(int bonusId) + { + if (RogueActions.Count == 0) return; + + var action = RogueActions.First().Value; + + // TODO: handle bonus + GameData.RogueBonusData.TryGetValue(bonusId, out var bonus); + if (bonus != null) TriggerEvent(null, bonus.BonusEvent); + + RogueActions.Remove(action.QueuePosition); + await UpdateMenu(); + + await Player.SendPacket(new PacketHandleRogueCommonPendingActionScRsp(action.QueuePosition, selectBonus: true)); + } + + public virtual async ValueTask UpdateMenu() + { + if (RogueActions.Count > 0) + await Player.SendPacket( + new PacketSyncRogueCommonPendingActionScNotify(RogueActions.First().Value, RogueVersionId)); + } + + #endregion + + #region Handlers + + public virtual void OnBattleStart(BattleInstance battle) + { + foreach (var miracle in RogueMiracles.Values) miracle.OnStartBattle(battle); + + foreach (var buff in RogueBuffs) buff.OnStartBattle(battle); + } + + public abstract ValueTask OnBattleEnd(BattleInstance battle, PVEBattleResultCsReq req); + + public virtual async ValueTask OnPropDestruct(EntityProp prop) + { + if (!prop.Excel.IsHpRecover && !prop.Excel.IsMpRecover) + // gain money + await GainMoney(Random.Shared.Next(10, 30)); + + CurDestroyCount++; + } + + #endregion + + #region Events + + public void TriggerEvent(RogueEventInstance? rogueEvent, int eventId) + { + EventManager?.TriggerEvent(rogueEvent, eventId); + } + + public async ValueTask GenerateEvent(RogueNpc npc) + { + RogueNPCDialogueExcel? dialogue; + do + { + dialogue = GameData.RogueNPCDialogueData.Values.ToList().RandomElement(); + } while (!dialogue.CanUseInVer(RogueType)); + + var instance = new RogueEventInstance(dialogue, npc, CurEventUniqueID++); + if (EventManager == null) return instance; + await EventManager.AddEvent(instance); + + return instance; + } + + public async ValueTask HandleSelectOption(int eventUniqueId, int optionId) + { + var entity = Player.SceneInstance!.Entities.Values.FirstOrDefault(x => + x is RogueNpc npc && npc.RogueEvent?.EventUniqueId == eventUniqueId); + if (entity is not RogueNpc npc) return; + + if (EventManager == null) return; + await EventManager.SelectOption(npc.RogueEvent!, optionId); + } + + public async ValueTask HandleFinishDialogueGroup(int eventUniqueId) + { + var entity = Player.SceneInstance!.Entities.Values.FirstOrDefault(x => + x is RogueNpc npc && npc.RogueEvent?.EventUniqueId == eventUniqueId); + if (entity is not RogueNpc npc) return; + + await EventManager!.FinishEvent(npc.RogueEvent!); + } + + public async ValueTask HandleNpcDisappear(int entityId) + { + Player.SceneInstance!.Entities.TryGetValue(entityId, out var entity); + if (entity is not RogueNpc npc) return; + + await EventManager!.NpcDisappear(npc.RogueEvent!); + } + + #endregion + + #region Serialization + + public RogueBuffEnhanceInfo ToEnhanceInfo() + { + var proto = new RogueBuffEnhanceInfo(); + + foreach (var buff in RogueBuffs) proto.EnhanceInfo.Add(buff.ToEnhanceProto()); + + return proto; + } + + public ChessRogueBuffEnhanceInfo ToChessEnhanceInfo() + { + var proto = new ChessRogueBuffEnhanceInfo(); + + foreach (var buff in RogueBuffs) proto.EnhanceInfo.Add(buff.ToChessEnhanceProto()); + + return proto; + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Buff/RogueBuffInstance.cs b/GameServer/Game/Rogue/Buff/RogueBuffInstance.cs index 9d91c16a..6a8fccb0 100644 --- a/GameServer/Game/Rogue/Buff/RogueBuffInstance.cs +++ b/GameServer/Game/Rogue/Buff/RogueBuffInstance.cs @@ -1,57 +1,62 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Data.Excel; +using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Buff +namespace EggLink.DanhengServer.Game.Rogue.Buff; + +public class RogueBuffInstance(int buffId, int buffLevel) { - public class RogueBuffInstance(int buffId, int buffLevel) + public int BuffId { get; set; } = buffId; + public int BuffLevel { get; set; } = buffLevel; + public RogueBuffExcel BuffExcel { get; set; } = GameData.RogueBuffData[buffId * 100 + buffLevel]; + + public int CurSp { get; set; } = 10000; + public int MaxSp { get; set; } = 10000; + + public int EnhanceCost => 100 + ((int)BuffExcel.RogueBuffCategory - 1) * 30; + + public void OnStartBattle(BattleInstance battle) { - public int BuffId { get; set; } = buffId; - public int BuffLevel { get; set; } = buffLevel; - public RogueBuffExcel BuffExcel { get; set; } = GameData.RogueBuffData[buffId * 100 + buffLevel]; - - public int CurSp { get; set; } = 10000; - public int MaxSp { get; set; } = 10000; - - public void OnStartBattle(BattleInstance battle) + if (BuffExcel.BattleEventBuffType == RogueBuffAeonTypeEnum.BattleEventBuff) { - if (BuffExcel.BattleEventBuffType == Enums.Rogue.RogueBuffAeonTypeEnum.BattleEventBuff) - { - GameData.RogueBattleEventData.TryGetValue(BuffExcel.RogueBuffType, out var battleEvent); - if (battleEvent == null) return; - battle.BattleEvents.Add(BuffId, new(battleEvent.BattleEventID, CurSp, MaxSp)); - } - battle.Buffs.Add(new(BuffId, BuffLevel, -1) - { - WaveFlag = -1 - }); + GameData.RogueBattleEventData.TryGetValue(BuffExcel.RogueBuffType, out var battleEvent); + if (battleEvent == null) return; + battle.BattleEvents.Add(BuffId, new BattleEventInstance(battleEvent.BattleEventID, CurSp, MaxSp)); } - public int EnhanceCost => 100 + (((int)BuffExcel.RogueBuffCategory - 1) * 30); + battle.Buffs.Add(new MazeBuff(BuffId, BuffLevel, -1) + { + WaveFlag = -1 + }); + } - public RogueBuff ToProto() => new() + public RogueBuff ToProto() + { + return new RogueBuff { BuffId = (uint)BuffId, Level = (uint)BuffLevel }; + } - public RogueCommonBuff ToCommonProto() => new() + public RogueCommonBuff ToCommonProto() + { + return new RogueCommonBuff { BuffId = (uint)BuffId, BuffLevel = (uint)BuffLevel }; + } - public RogueCommonActionResult ToResultProto(RogueActionSource source) => new() + public RogueCommonActionResult ToResultProto(RogueActionSource source) + { + return new RogueCommonActionResult { - RogueAction = new() + RogueAction = new RogueCommonActionResultData { - GetBuffList = new() + GetBuffList = new RogueCommonBuff { BuffId = (uint)BuffId, BuffLevel = (uint)BuffLevel @@ -59,37 +64,49 @@ namespace EggLink.DanhengServer.Game.Rogue.Buff }, Source = source }; + } - public RogueBuffEnhance ToEnhanceProto() => new() + public RogueBuffEnhance ToEnhanceProto() + { + return new RogueBuffEnhance { BuffId = (uint)BuffId, - CostData = new() + CostData = new ItemCostData { - ItemList = { new ItemCost() + ItemList = { - PileItem = new() + new ItemCost { - ItemId = 31, - ItemNum = (uint)EnhanceCost + PileItem = new PileItem + { + ItemId = 31, + ItemNum = (uint)EnhanceCost + } } - } } - } - }; - - public ChessRogueBuffEnhance ToChessEnhanceProto() => new() - { - BuffId = (uint)BuffId, - CostData = new() - { - ItemList = { new ItemCost() - { - PileItem = new() - { - ItemId = 31, - ItemNum = (uint)EnhanceCost - } - } } + } } }; } -} + + public ChessRogueBuffEnhance ToChessEnhanceProto() + { + return new ChessRogueBuffEnhance + { + BuffId = (uint)BuffId, + CostData = new ItemCostData + { + ItemList = + { + new ItemCost + { + PileItem = new PileItem + { + ItemId = 31, + ItemNum = (uint)EnhanceCost + } + } + } + } + }; + } +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Buff/RogueBuffSelectMenu.cs b/GameServer/Game/Rogue/Buff/RogueBuffSelectMenu.cs index 60ed2b16..86b94d03 100644 --- a/GameServer/Game/Rogue/Buff/RogueBuffSelectMenu.cs +++ b/GameServer/Game/Rogue/Buff/RogueBuffSelectMenu.cs @@ -1,111 +1,105 @@ using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Buff +namespace EggLink.DanhengServer.Game.Rogue.Buff; + +public class RogueBuffSelectMenu(BaseRogueInstance rogue) { - public class RogueBuffSelectMenu(BaseRogueInstance rogue) + public int HintId { get; set; } = 1; + public List Buffs { get; set; } = []; + public int RollMaxCount { get; set; } = rogue.BaseRerollCount; + public int RollCount { get; set; } = rogue.BaseRerollCount; + public int RollFreeCount { get; set; } = rogue.BaseRerollFreeCount; + public int RollCost { get; set; } = rogue.CurRerollCost; + public int QueueAppend { get; set; } = 3; + public bool IsAeonBuff { get; set; } = false; + public int CurCount { get; set; } = 1; + public int TotalCount { get; set; } = 1; + public List BuffPool { get; set; } = []; + + public void RollBuff(List buffs, int count = 3) { - public int HintId { get; set; } = 1; - public List Buffs { get; set; } = []; - public int RollMaxCount { get; set; } = rogue.BaseRerollCount; - public int RollCount { get; set; } = rogue.BaseRerollCount; - public int RollFreeCount { get; set; } = rogue.BaseRerollFreeCount; - public int RollCost { get; set; } = rogue.CurRerollCost; - public int QueueAppend { get; set; } = 3; - public bool IsAeonBuff { get; set; } = false; - public int CurCount { get; set; } = 1; - public int TotalCount { get; set; } = 1; - public List BuffPool { get; set; } = []; + BuffPool.Clear(); + BuffPool.AddRange(buffs); - public void RollBuff(List buffs, int count = 3) + var list = new RandomList(); + + foreach (var buff in buffs) + if (buff.RogueBuffType == rogue.RogueBuffType) + list.Add(buff, (int)(20 / (int)buff.RogueBuffCategory * 2.5)); + else + list.Add(buff, (int)(20 / (int)buff.RogueBuffCategory * 0.7)); + var result = new List(); + + for (var i = 0; i < count; i++) { - BuffPool.Clear(); - BuffPool.AddRange(buffs); - - var list = new RandomList(); - - foreach (var buff in buffs) + var buff = list.GetRandom(); + if (buff != null) { - if (buff.RogueBuffType == rogue.RogueBuffType) - { - list.Add(buff, (int)(20 / (int)buff.RogueBuffCategory * 2.5)); - } else - { - list.Add(buff, (int)(20 / (int)buff.RogueBuffCategory * 0.7)); - } - } - var result = new List(); - - for (var i = 0; i < count; i++) - { - var buff = list.GetRandom(); - if (buff != null) - { - result.Add(buff); - list.Remove(buff); - } - if (list.GetCount() == 0) break; // No more buffs to roll + result.Add(buff); + list.Remove(buff); } - Buffs = result; + if (list.GetCount() == 0) break; // No more buffs to roll } - public void RerollBuff() - { - if (RollFreeCount > 0) - { - RollFreeCount--; // Free reroll - } else - { - if (RollCount <= 0) return; - RollCount--; // Paid reroll - rogue.CostMoney(RollCost); - } + Buffs = result; + } - RollBuff(BuffPool); + public async ValueTask RerollBuff() + { + if (RollFreeCount > 0) + { + RollFreeCount--; // Free reroll + } + else + { + if (RollCount <= 0) return; + RollCount--; // Paid reroll + await rogue.CostMoney(RollCost); } - public RogueActionInstance GetActionInstance() - { - rogue.CurActionQueuePosition += QueueAppend; - return new() - { - QueuePosition = rogue.CurActionQueuePosition, - RogueBuffSelectMenu = this - }; - } + RollBuff(BuffPool); + } - public RogueCommonBuffSelectInfo ToProto() + public RogueActionInstance GetActionInstance() + { + rogue.CurActionQueuePosition += QueueAppend; + return new RogueActionInstance { - return new() + QueuePosition = rogue.CurActionQueuePosition, + RogueBuffSelectMenu = this + }; + } + + public RogueCommonBuffSelectInfo ToProto() + { + return new RogueCommonBuffSelectInfo + { + CanRoll = RollCount > 0, + RollBuffCount = (uint)RollCount, + RollBuffFreeCount = (uint)RollFreeCount, + RollBuffMaxCount = (uint)RollMaxCount, + SourceCurCount = (uint)CurCount, + SourceTotalCount = (uint)TotalCount, + RollBuffCostData = new ItemCostData { - CanRoll = RollCount > 0, - RollBuffCount = (uint)RollCount, - RollBuffFreeCount = (uint)RollFreeCount, - RollBuffMaxCount = (uint)RollMaxCount, - SourceCurCount = (uint)CurCount, - SourceTotalCount = (uint)TotalCount, - RollBuffCostData = new ItemCostData() + ItemList = { - ItemList = { new ItemCost() + new ItemCost { - PileItem = new() + PileItem = new PileItem { ItemId = 31, ItemNum = (uint)RollCost } - } } - }, - SourceHintId = (uint)HintId, - HandbookUnlockBuffIdList = { Buffs.Select(x => (uint)x.MazeBuffID) }, - SelectBuffList = { Buffs.Select(x => x.ToProto()) } - }; - } + } + } + }, + SourceHintId = (uint)HintId, + HandbookUnlockBuffIdList = { Buffs.Select(x => (uint)x.MazeBuffID) }, + SelectBuffList = { Buffs.Select(x => x.ToProto()) } + }; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostHpCurrentPercent.cs b/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostHpCurrentPercent.cs index 0bc6be7c..09b3cd6e 100644 --- a/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostHpCurrentPercent.cs +++ b/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostHpCurrentPercent.cs @@ -1,23 +1,16 @@ using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.CostHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.CostHandler; + +[RogueEvent(costType: DialogueEventCostTypeEnum.CostHpCurrentPercent)] +public class EventHandlerCostHpCurrentPercent : RogueEventCostHandler { - [RogueEvent(costType: DialogueEventCostTypeEnum.CostHpCurrentPercent)] - public class EventHandlerCostHpCurrentPercent : RogueEventCostHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) - { - if (rogue.CurLineup!.CostNowPercentHp(ParamList[0] / 100f)) - { - // sync - rogue.Player!.SendPacket(new PacketSyncLineupNotify(rogue.CurLineup!)); - } - } + if (rogue.CurLineup!.CostNowPercentHp(paramList[0] / 100f)) + // sync + await rogue.Player!.SendPacket(new PacketSyncLineupNotify(rogue.CurLineup!)); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostHpSpToPercent.cs b/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostHpSpToPercent.cs index 37ca2a2f..fbe158b7 100644 --- a/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostHpSpToPercent.cs +++ b/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostHpSpToPercent.cs @@ -1,22 +1,15 @@ using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.CostHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.CostHandler; + +[RogueEvent(costType: DialogueEventCostTypeEnum.CostHpSpToPercent)] +public class EventHandlerCostHpSpToPercent : RogueEventCostHandler { - [RogueEvent(costType: DialogueEventCostTypeEnum.CostHpSpToPercent)] - public class EventHandlerCostHpSpToPercent : RogueEventCostHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) - { - if (rogue.CurLineup!.CostNowPercentHp(1 - ParamList[0] / 100f)) - { - rogue.Player!.SendPacket(new PacketSyncLineupNotify(rogue.CurLineup!)); - } - } + if (rogue.CurLineup!.CostNowPercentHp(1 - paramList[0] / 100f)) + await rogue.Player!.SendPacket(new PacketSyncLineupNotify(rogue.CurLineup!)); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostItemPercent.cs b/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostItemPercent.cs index 67c67a55..8b2ae49e 100644 --- a/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostItemPercent.cs +++ b/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostItemPercent.cs @@ -1,19 +1,15 @@ using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.CostHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.CostHandler; + +[RogueEvent(costType: DialogueEventCostTypeEnum.CostItemPercent)] +public class EventHandlerCostItemPercent : RogueEventCostHandler { - [RogueEvent(costType: DialogueEventCostTypeEnum.CostItemPercent)] - public class EventHandlerCostItemPercent : RogueEventCostHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) - { - rogue.CostMoney((int)(rogue.CurMoney * (ParamList[1] / 100f)), RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle); - } + await rogue.CostMoney((int)(rogue.CurMoney * (paramList[1] / 100f)), + RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostItemValue.cs b/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostItemValue.cs index f5bd1a56..fed8e431 100644 --- a/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostItemValue.cs +++ b/GameServer/Game/Rogue/Event/CostHandler/EventHandlerCostItemValue.cs @@ -1,20 +1,15 @@ using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.CostHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.CostHandler; + +[RogueEvent(costType: DialogueEventCostTypeEnum.CostItemValue)] +public class EventHandlerCostItemValue : RogueEventCostHandler { - [RogueEvent(costType: DialogueEventCostTypeEnum.CostItemValue)] - public class EventHandlerCostItemValue : RogueEventCostHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) - { - int decreaseMoney = ParamList[1]; - rogue.CostMoney(decreaseMoney, RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle); - } + var decreaseMoney = paramList[1]; + await rogue.CostMoney(decreaseMoney, RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerEnhanceRogueBuff.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerEnhanceRogueBuff.cs index 3cf4f92d..932cc911 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerEnhanceRogueBuff.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerEnhanceRogueBuff.cs @@ -1,41 +1,36 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.EnhanceRogueBuff)] +public class EventHandlerEnhanceRogueBuff : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.EnhanceRogueBuff)] - public class EventHandlerEnhanceRogueBuff : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) + var group = paramList[0]; + GameData.RogueBuffGroupData.TryGetValue(group, out var buffGroup); + if (buffGroup == null) return; + var count = paramList[1]; + + var buffs = rogue.GetRogueBuffInGroup(buffGroup.GroupID); + if (buffs.Count == 0) return; + + for (var i = 0; i < count;) { - var group = ParamList[0]; - GameData.RogueBuffGroupData.TryGetValue(group, out var buffGroup); - if (buffGroup == null) return; - var count = ParamList[1]; - - var buffs = rogue.GetRogueBuffInGroup(buffGroup.GroupID); - if (buffs == null) return; - - for (int i = 0; i < count;) + if (buffs.Count == 0) break; // No more buffs to enhance + var buff = buffs.RandomElement(); + if (buff.BuffLevel == 2) { - if (buffs.Count == 0) break; // No more buffs to enhance - var buff = buffs.RandomElement(); - if (buff == null) break; - if (buff.BuffLevel == 2) - { - // Buff is already at max level - buffs.Remove(buff); - continue; - } - rogue.EnhanceBuff(buff.BuffId); - i++; + // Buff is already at max level + buffs.Remove(buff); + continue; } + + await rogue.EnhanceBuff(buff.BuffId); + i++; } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetAllRogueBuffInGroup.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetAllRogueBuffInGroup.cs index 55f10033..89e4c769 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetAllRogueBuffInGroup.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetAllRogueBuffInGroup.cs @@ -1,22 +1,17 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Enums.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.GetAllRogueBuffInGroup)] +public class EventHandlerGetAllRogueBuffInGroup : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.GetAllRogueBuffInGroup)] - public class EventHandlerGetAllRogueBuffInGroup : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) - { - var group = ParamList[0]; - GameData.RogueBuffGroupData.TryGetValue(group, out var buffGroup); - if (buffGroup == null) return; - rogue.AddBuffList(buffGroup.BuffList); - } + var group = paramList[0]; + GameData.RogueBuffGroupData.TryGetValue(group, out var buffGroup); + if (buffGroup == null) return; + await rogue.AddBuffList(buffGroup.BuffList); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetAllRogueBuffInGroupAndGetItem.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetAllRogueBuffInGroupAndGetItem.cs index 9eb4518c..252b806c 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetAllRogueBuffInGroupAndGetItem.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetAllRogueBuffInGroupAndGetItem.cs @@ -1,18 +1,20 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Enums.Rogue; +using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.GetAllRogueBuffInGroupAndGetItem)] +public class EventHandlerGetAllRogueBuffInGroupAndGetItem : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.GetAllRogueBuffInGroupAndGetItem)] - public class EventHandlerGetAllRogueBuffInGroupAndGetItem : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) - { - var group = ParamList[0]; - GameData.RogueBuffGroupData.TryGetValue(group, out var buffGroup); - if (buffGroup == null) return; - rogue.AddBuffList(buffGroup.BuffList); - rogue.GainMoney(ParamList[2], ParamList[3], Proto.RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle); - } + var group = paramList[0]; + GameData.RogueBuffGroupData.TryGetValue(group, out var buffGroup); + if (buffGroup == null) return; + await rogue.AddBuffList(buffGroup.BuffList); + await rogue.GainMoney(paramList[2], paramList[3], + RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetItem.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetItem.cs index 5c35799c..526db715 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetItem.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetItem.cs @@ -1,18 +1,15 @@ using EggLink.DanhengServer.Enums.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.GetItem)] +public class EventHandlerGetItem : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.GetItem)] - public class EventHandlerGetItem : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) - { - rogue.GainMoney(ParamList[1], ParamList[2], Proto.RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle); - } + await rogue.GainMoney(paramList[1], paramList[2], + RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetRogueBuff.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetRogueBuff.cs index 42b649c6..6559b135 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetRogueBuff.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetRogueBuff.cs @@ -1,27 +1,22 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.GetRogueBuff)] +public class EventHandlerGetRogueBuff : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.GetRogueBuff)] - public class EventHandlerGetRogueBuff : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) + var groupId = paramList[0]; + GameData.RogueBuffGroupData.TryGetValue(groupId, out var buffGroup); + if (buffGroup == null) return; + for (var i = 0; i < paramList[1]; i++) { - var groupId = ParamList[0]; - GameData.RogueBuffGroupData.TryGetValue(groupId, out var buffGroup); - if (buffGroup == null) return; - for (int i = 0; i < ParamList[1]; i++) - { - var buff = buffGroup.BuffList.RandomElement(); - rogue.AddBuff(buff.MazeBuffID, buff.MazeBuffLevel); - } + var buff = buffGroup.BuffList.RandomElement(); + await rogue.AddBuff(buff.MazeBuffID, buff.MazeBuffLevel); } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetRogueMiracle.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetRogueMiracle.cs index 8d534671..dfc8705a 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetRogueMiracle.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerGetRogueMiracle.cs @@ -1,44 +1,36 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.GetRogueMiracle)] +public class EventHandlerGetRogueMiracle : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.GetRogueMiracle)] - public class EventHandlerGetRogueMiracle : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) + var miracleGroupId = paramList[0]; + GameData.RogueMiracleGroupData.TryGetValue(miracleGroupId, out var miracleGroup); + if (miracleGroup == null) return; + + var list = new List(); + + foreach (var id in miracleGroup) + if (!rogue.RogueMiracles.ContainsKey(id)) + // Add the miracle to the list if the player doesn't have it + list.Add(id); + + if (list.Count == 0) return; // If the player already has all the miracles in the group, return + + for (var i = 0; i < paramList[1]; i++) { - var miracleGroupId = ParamList[0]; - GameData.RogueMiracleGroupData.TryGetValue(miracleGroupId, out var miracleGroup); - if (miracleGroup == null) return; + if (list.Count == 0) break; // If the player has all the miracles in the group, break - var list = new List(); - foreach (var id in miracleGroup) - { - if (!rogue.RogueMiracles.ContainsKey(id)) - { - // Add the miracle to the list if the player doesn't have it - list.Add(id); - } - } + var miracleId = list.RandomElement(); + await rogue.AddMiracle(miracleId); - if (list.Count == 0) return; // If the player already has all the miracles in the group, return - - for (int i = 0; i < ParamList[1]; i++) - { - if (list.Count == 0) break; // If the player has all the miracles in the group, break - - var miracleId = list.RandomElement(); - rogue.AddMiracle(miracleId); - - list.Remove(i); // Remove the miracle from the list so it can't be added again - } + list.Remove(i); // Remove the miracle from the list so it can't be added again } } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerDialogueEventList.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerDialogueEventList.cs index 690c80a1..e41996ef 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerDialogueEventList.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerDialogueEventList.cs @@ -1,25 +1,22 @@ using EggLink.DanhengServer.Enums.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.TriggerDialogueEventList)] +public class EventHandlerTriggerDialogueEventList : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.TriggerDialogueEventList)] - public class EventHandlerTriggerDialogueEventList : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) + foreach (var param in paramList) { - foreach (var param in ParamList) + eventInstance!.Options.Add(new RogueEventParam { - eventInstance!.Options.Add(new() - { - OptionId = param, - }); - rogue.TriggerEvent(eventInstance, param); - } + OptionId = param + }); + rogue.TriggerEvent(eventInstance, param); } + + await System.Threading.Tasks.Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRandomEventList.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRandomEventList.cs index 102ed5b9..e79291e7 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRandomEventList.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRandomEventList.cs @@ -1,24 +1,24 @@ using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.TriggerRandomEventList)] +public class EventHandlerTriggerRandomEventList : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.TriggerRandomEventList)] - public class EventHandlerTriggerRandomEventList : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) + var list = new RandomList(); + for (var i = 0; i < paramList.Count; i += 2) list.Add(paramList[i], paramList[i + 1]); + + var randomEvent = list.GetRandom(); + eventInstance!.Options.Add(new RogueEventParam { - var list = new RandomList(); - for (int i = 0; i < ParamList.Count; i += 2) - { - list.Add(ParamList[i], ParamList[i + 1]); - } - var randomEvent = list.GetRandom(); - eventInstance!.Options.Add(new() - { - OptionId = randomEvent, - }); - rogue.TriggerEvent(eventInstance, randomEvent); - } + OptionId = randomEvent + }); + rogue.TriggerEvent(eventInstance, randomEvent); + + await System.Threading.Tasks.Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRogueBuffSelect.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRogueBuffSelect.cs index afc03195..0e6f112c 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRogueBuffSelect.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRogueBuffSelect.cs @@ -1,18 +1,13 @@ using EggLink.DanhengServer.Enums.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.TriggerRogueBuffSelect)] +public class EventHandlerTriggerRogueBuffSelect : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.TriggerRogueBuffSelect)] - public class EventHandlerTriggerRogueBuffSelect : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) - { - rogue.RollBuff(ParamList[2], ParamList[0], ParamList[1]); - } + await rogue.RollBuff(paramList[2], paramList[0], paramList[1]); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRogueMiracleSelect.cs b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRogueMiracleSelect.cs index ce21c7ef..151e4ba2 100644 --- a/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRogueMiracleSelect.cs +++ b/GameServer/Game/Rogue/Event/EffectHandler/EventHandlerTriggerRogueMiracleSelect.cs @@ -1,18 +1,13 @@ using EggLink.DanhengServer.Enums.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler +namespace EggLink.DanhengServer.Game.Rogue.Event.EffectHandler; + +[RogueEvent(DialogueEventTypeEnum.TriggerRogueMiracleSelect)] +public class EventHandlerTriggerRogueMiracleSelect : RogueEventEffectHandler { - [RogueEvent(DialogueEventTypeEnum.TriggerRogueMiracleSelect)] - public class EventHandlerTriggerRogueMiracleSelect : RogueEventEffectHandler + public override async ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, + List paramList) { - public override void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList) - { - rogue.RollMiracle(ParamList[2], ParamList[0]); - } + await rogue.RollMiracle(paramList[2], paramList[0]); } -} +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/RogueEventAttribute.cs b/GameServer/Game/Rogue/Event/RogueEventAttribute.cs index 2ff86c56..afe22bb9 100644 --- a/GameServer/Game/Rogue/Event/RogueEventAttribute.cs +++ b/GameServer/Game/Rogue/Event/RogueEventAttribute.cs @@ -1,16 +1,12 @@ using EggLink.DanhengServer.Enums.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event +namespace EggLink.DanhengServer.Game.Rogue.Event; + +[AttributeUsage(AttributeTargets.Class)] +public class RogueEventAttribute( + DialogueEventTypeEnum effectType = DialogueEventTypeEnum.None, + DialogueEventCostTypeEnum costType = DialogueEventCostTypeEnum.None) : Attribute { - [AttributeUsage(AttributeTargets.Class)] - public class RogueEventAttribute(DialogueEventTypeEnum effectType = DialogueEventTypeEnum.None, DialogueEventCostTypeEnum costType = DialogueEventCostTypeEnum.None) : Attribute - { - public DialogueEventTypeEnum EffectType { get; } = effectType; - public DialogueEventCostTypeEnum CostType { get; } = costType; - } -} + public DialogueEventTypeEnum EffectType { get; } = effectType; + public DialogueEventCostTypeEnum CostType { get; } = costType; +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/RogueEventCostHandler.cs b/GameServer/Game/Rogue/Event/RogueEventCostHandler.cs index 8f9b2d28..7a946906 100644 --- a/GameServer/Game/Rogue/Event/RogueEventCostHandler.cs +++ b/GameServer/Game/Rogue/Event/RogueEventCostHandler.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Game.Rogue.Event; -namespace EggLink.DanhengServer.Game.Rogue.Event +public abstract class RogueEventCostHandler { - public abstract class RogueEventCostHandler - { - public abstract void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList); - } -} + public abstract ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List paramList); +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/RogueEventEffectHandler.cs b/GameServer/Game/Rogue/Event/RogueEventEffectHandler.cs index c0b1aeb5..e4f61c88 100644 --- a/GameServer/Game/Rogue/Event/RogueEventEffectHandler.cs +++ b/GameServer/Game/Rogue/Event/RogueEventEffectHandler.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Game.Rogue.Event; -namespace EggLink.DanhengServer.Game.Rogue.Event +public abstract class RogueEventEffectHandler { - public abstract class RogueEventEffectHandler - { - public abstract void Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List ParamList); - } -} + public abstract ValueTask Handle(BaseRogueInstance rogue, RogueEventInstance? eventInstance, List paramList); +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/RogueEventInstance.cs b/GameServer/Game/Rogue/Event/RogueEventInstance.cs index 1a34fc19..2204fe11 100644 --- a/GameServer/Game/Rogue/Event/RogueEventInstance.cs +++ b/GameServer/Game/Rogue/Event/RogueEventInstance.cs @@ -4,107 +4,101 @@ using EggLink.DanhengServer.Game.Rogue.Scene.Entity; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Rogue.Event +namespace EggLink.DanhengServer.Game.Rogue.Event; + +public class RogueEventInstance(int eventId, RogueNpc npc, List optionIds, int uniqueId) { - public class RogueEventInstance(int eventId, RogueNpc npc, List optionIds, int uniqueId) + public RogueEventInstance(RogueNPCDialogueExcel excel, RogueNpc npc, int uniqueId) : this(excel.RogueNPCID, npc, [], + uniqueId) // check in RogueInstance.cs { - public int EventId { get; set; } = eventId; - public bool Finished { get; set; } = false; - public RogueNpc EventEntity { get; set; } = npc; - public List Options { get; set; } = optionIds; - public int EventUniqueId { get; set; } = uniqueId; - public int SelectedOptionId { get; set; } = 0; - - public RogueEventInstance(RogueNPCDialogueExcel excel, RogueNpc npc, int uniqueId) : this(excel.RogueNPCID, npc, [], uniqueId) // check in RogueInstance.cs + foreach (var option in excel.DialogueInfo!.DialogueIds) { - foreach (var option in excel.DialogueInfo!.DialogueIds) + GameData.DialogueEventData.TryGetValue(option, out var dialogueEvent); + if (dialogueEvent == null) continue; + + var argId = 0; + if (dialogueEvent.DynamicContentID > 0) { - GameData.DialogueEventData.TryGetValue(option, out var dialogueEvent); - if (dialogueEvent == null) continue; - - var argId = 0; - if (dialogueEvent.DynamicContentID > 0) - { - GameData.DialogueDynamicContentData.TryGetValue(dialogueEvent.DynamicContentID, out var dynamicContent); - if (dynamicContent != null) - { - argId = dynamicContent.Keys.ToList().RandomElement(); - } - } - - Options.Add(new RogueEventParam() - { - OptionId = option, - ArgId = argId, - }); - } - } - - public void Finish() - { - Finished = true; - EventEntity.FinishDialogue(); - } - - public RogueCommonDialogueDataInfo ToProto() - { - var proto = new RogueCommonDialogueDataInfo() - { - DialogueInfo = ToDialogueInfo(), - EventUniqueId = (uint)EventUniqueId, - }; - - foreach (var option in Options) - { - proto.OptionList.Add(option.ToProto()); + GameData.DialogueDynamicContentData.TryGetValue(dialogueEvent.DynamicContentID, out var dynamicContent); + if (dynamicContent != null) argId = dynamicContent.Keys.ToList().RandomElement(); } - return proto; - } - - public RogueCommonDialogueInfo ToDialogueInfo() - { - var proto = new RogueCommonDialogueInfo() + Options.Add(new RogueEventParam { - DialogueBasicInfo = new() - { - EventId = (uint)EventId, - } - }; - - return proto; + OptionId = option, + ArgId = argId + }); } } - public class RogueEventParam + public int EventId { get; set; } = eventId; + public bool Finished { get; set; } + public RogueNpc EventEntity { get; set; } = npc; + public List Options { get; set; } = optionIds; + public int EventUniqueId { get; set; } = uniqueId; + public int SelectedOptionId { get; set; } = 0; + + public async ValueTask Finish() { - public int OptionId { get; set; } - public int ArgId { get; set; } - public float Ratio { get; set; } - public bool IsSelected { get; set; } = false; + Finished = true; + await EventEntity.FinishDialogue(); + } - public RogueCommonDialogueOptionInfo ToProto() + public RogueCommonDialogueDataInfo ToProto() + { + var proto = new RogueCommonDialogueDataInfo { - return new RogueCommonDialogueOptionInfo() - { - ArgId = (uint)ArgId, - IsValid = true, - OptionId = (uint)OptionId, - DisplayValue = new() - { - FloatValue = Ratio - }, - Confirm = IsSelected, - }; - } + DialogueInfo = ToDialogueInfo(), + EventUniqueId = (uint)EventUniqueId + }; - public NpcDialogueEventParam ToNpcProto() + foreach (var option in Options) proto.OptionList.Add(option.ToProto()); + + return proto; + } + + public RogueCommonDialogueInfo ToDialogueInfo() + { + var proto = new RogueCommonDialogueInfo { - return new NpcDialogueEventParam() + DialogueBasicInfo = new RogueCommonDialogueBasicInfo { - DialogueEventId = (uint)OptionId, - ArgId = (uint)ArgId, - }; - } + EventId = (uint)EventId + } + }; + + return proto; } } + +public class RogueEventParam +{ + public int OptionId { get; set; } + public int ArgId { get; set; } + public float Ratio { get; set; } + public bool IsSelected { get; set; } = false; + + public RogueCommonDialogueOptionInfo ToProto() + { + return new RogueCommonDialogueOptionInfo + { + ArgId = (uint)ArgId, + IsValid = true, + OptionId = (uint)OptionId, + DisplayValue = new RogueCommonDialogueOptionDisplayInfo + { + FloatValue = Ratio + }, + Confirm = IsSelected + }; + } + + public NpcDialogueEventParam ToNpcProto() + { + return new NpcDialogueEventParam + { + DialogueEventId = (uint)OptionId, + ArgId = (uint)ArgId + }; + } +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Event/RogueEventManager.cs b/GameServer/Game/Rogue/Event/RogueEventManager.cs index a32e6f3b..3327c9f3 100644 --- a/GameServer/Game/Rogue/Event/RogueEventManager.cs +++ b/GameServer/Game/Rogue/Event/RogueEventManager.cs @@ -1,164 +1,144 @@ -using EggLink.DanhengServer.Data; +using System.Reflection; +using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.GameServer.Server.Packet.Send.Rogue; using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using Google.Protobuf.WellKnownTypes; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Event +namespace EggLink.DanhengServer.Game.Rogue.Event; + +public class RogueEventManager { - public class RogueEventManager + public Dictionary CostHandler = []; + public Dictionary EffectHandler = []; + public PlayerInstance Player; + public BaseRogueInstance Rogue; + public List RunningEvent = []; + + public RogueEventManager(PlayerInstance player, BaseRogueInstance rogueInstance) { - public PlayerInstance Player; - public BaseRogueInstance Rogue; - public List RunningEvent = []; - public Dictionary EffectHandler = []; - public Dictionary CostHandler = []; + Player = player; + Rogue = rogueInstance; - public RogueEventManager(PlayerInstance player, BaseRogueInstance rogueInstance) + var types = Assembly.GetExecutingAssembly().GetTypes(); + foreach (var type in types) { - Player = player; - Rogue = rogueInstance; - - var types = Assembly.GetExecutingAssembly().GetTypes(); - foreach (var type in types) + var attr = type.GetCustomAttribute(); + if (attr != null) { - var attr = type.GetCustomAttribute(); - if (attr != null) + if (attr.EffectType != DialogueEventTypeEnum.None) { - if (attr.EffectType != DialogueEventTypeEnum.None) - { - // Effect - var effect = (RogueEventEffectHandler)Activator.CreateInstance(type, null)!; - EffectHandler.Add(attr.EffectType, effect); - } else - { - // Cost - var cost = (RogueEventCostHandler)Activator.CreateInstance(type, null)!; - CostHandler.Add(attr.CostType, cost); - } + // Effect + var effect = (RogueEventEffectHandler)Activator.CreateInstance(type, null)!; + EffectHandler.Add(attr.EffectType, effect); + } + else + { + // Cost + var cost = (RogueEventCostHandler)Activator.CreateInstance(type, null)!; + CostHandler.Add(attr.CostType, cost); } } } - - public void OnNextRoom() - { - RunningEvent.Clear(); // Clear all running events - } - - public void AddEvent(RogueEventInstance eventInstance) - { - RunningEvent.Add(eventInstance); - Player.SendPacket(new PacketSyncRogueCommonDialogueDataScNotify(eventInstance)); - } - - public void RemoveEvent(RogueEventInstance eventInstance) - { - RunningEvent.Remove(eventInstance); - } - - public void FinishEvent(RogueEventInstance eventInstance) - { - eventInstance.Finish(); - } - - public void NpcDisappear(RogueEventInstance eventInstance) - { - RunningEvent.Remove(eventInstance); - Player.SceneInstance!.RemoveEntity(eventInstance.EventEntity); - } - - public RogueEventInstance? FindEvent(int optionId) - { - foreach (var eventInstance in RunningEvent) - { - if (eventInstance.Options.Exists(x => x.OptionId == optionId)) - { - return eventInstance; - } - } - return null; - } - - public void TriggerEvent(RogueEventInstance? eventInstance, int eventId) - { - GameData.DialogueEventData.TryGetValue(eventId, out var dialogueEvent); - if (dialogueEvent == null) return; - - List Param = dialogueEvent.RogueEffectParamList; - - // Handle option - if (EffectHandler.TryGetValue(dialogueEvent.RogueEffectType, out var effectHandler)) - { - effectHandler.Handle(Rogue, eventInstance, Param); - } - - // Handle cost - if (CostHandler.TryGetValue(dialogueEvent.CostType, out var costHandler)) - { - costHandler.Handle(Rogue, eventInstance, dialogueEvent.CostParamList); - } - } - - public void SelectOption(RogueEventInstance eventInstance, int optionId) - { - eventInstance.SelectedOptionId = optionId; - var option = eventInstance.Options.Find(x => x.OptionId == optionId); - if (option == null) - { - Player.SendPacket(new PacketSelectRogueCommonDialogueOptionScRsp()); - return; - } - GameData.DialogueEventData.TryGetValue(option.OptionId, out var dialogueEvent); - if (dialogueEvent == null) - { - Player.SendPacket(new PacketSelectRogueCommonDialogueOptionScRsp()); - return; - } - option.IsSelected = true; - - List Param = dialogueEvent.RogueEffectParamList; - if (option.ArgId > 0) - { - GameData.DialogueDynamicContentData.TryGetValue(dialogueEvent.DynamicContentID, out var dynamicContent); - if (dynamicContent != null) - { - dynamicContent.TryGetValue(option.ArgId, out var content); - if (content != null) - { - if (content.DynamicParamType == DialogueDynamicParamTypeEnum.ReplaceAll) - { - Param = content.DynamicParamList; - } else - { - Param[content.DynamicParamList[0] - 1] = content.DynamicParamList[1]; - } - } - } - } - - // Handle option - if (EffectHandler.TryGetValue(dialogueEvent.RogueEffectType, out var effectHandler)) - { - effectHandler.Handle(Rogue, eventInstance, Param); - } - - // Handle cost - if (CostHandler.TryGetValue(dialogueEvent.CostType, out var costHandler)) - { - costHandler.Handle(Rogue, eventInstance, dialogueEvent.CostParamList); - } - - // send rsp - Player.SendPacket(new PacketSyncRogueCommonDialogueOptionFinishScNotify(eventInstance)); - Player.SendPacket(new PacketSelectRogueCommonDialogueOptionScRsp(eventInstance)); - } } -} + + public void OnNextRoom() + { + RunningEvent.Clear(); // Clear all running events + } + + public async ValueTask AddEvent(RogueEventInstance eventInstance) + { + RunningEvent.Add(eventInstance); + await Player.SendPacket(new PacketSyncRogueCommonDialogueDataScNotify(eventInstance)); + } + + public void RemoveEvent(RogueEventInstance eventInstance) + { + RunningEvent.Remove(eventInstance); + } + + public async ValueTask FinishEvent(RogueEventInstance eventInstance) + { + await eventInstance.Finish(); + } + + public async ValueTask NpcDisappear(RogueEventInstance eventInstance) + { + RunningEvent.Remove(eventInstance); + await Player.SceneInstance!.RemoveEntity(eventInstance.EventEntity); + } + + public RogueEventInstance? FindEvent(int optionId) + { + foreach (var eventInstance in RunningEvent) + if (eventInstance.Options.Exists(x => x.OptionId == optionId)) + return eventInstance; + return null; + } + + public void TriggerEvent(RogueEventInstance? eventInstance, int eventId) + { + GameData.DialogueEventData.TryGetValue(eventId, out var dialogueEvent); + if (dialogueEvent == null) return; + + var Param = dialogueEvent.RogueEffectParamList; + + // Handle option + if (EffectHandler.TryGetValue(dialogueEvent.RogueEffectType, out var effectHandler)) + effectHandler.Handle(Rogue, eventInstance, Param); + + // Handle cost + if (CostHandler.TryGetValue(dialogueEvent.CostType, out var costHandler)) + costHandler.Handle(Rogue, eventInstance, dialogueEvent.CostParamList); + } + + public async ValueTask SelectOption(RogueEventInstance eventInstance, int optionId) + { + eventInstance.SelectedOptionId = optionId; + var option = eventInstance.Options.Find(x => x.OptionId == optionId); + if (option == null) + { + await Player.SendPacket(new PacketSelectRogueCommonDialogueOptionScRsp()); + return; + } + + GameData.DialogueEventData.TryGetValue(option.OptionId, out var dialogueEvent); + if (dialogueEvent == null) + { + await Player.SendPacket(new PacketSelectRogueCommonDialogueOptionScRsp()); + return; + } + + option.IsSelected = true; + + var param = dialogueEvent.RogueEffectParamList; + if (option.ArgId > 0) + { + GameData.DialogueDynamicContentData.TryGetValue(dialogueEvent.DynamicContentID, out var dynamicContent); + if (dynamicContent != null) + { + dynamicContent.TryGetValue(option.ArgId, out var content); + if (content != null) + { + if (content.DynamicParamType == DialogueDynamicParamTypeEnum.ReplaceAll) + param = content.DynamicParamList; + else + param[content.DynamicParamList[0] - 1] = content.DynamicParamList[1]; + } + } + } + + // Handle option + if (EffectHandler.TryGetValue(dialogueEvent.RogueEffectType, out var effectHandler)) + await effectHandler.Handle(Rogue, eventInstance, param); + + // Handle cost + if (CostHandler.TryGetValue(dialogueEvent.CostType, out var costHandler)) + await costHandler.Handle(Rogue, eventInstance, dialogueEvent.CostParamList); + + // send rsp + await Player.SendPacket(new PacketSyncRogueCommonDialogueOptionFinishScNotify(eventInstance)); + await Player.SendPacket(new PacketSelectRogueCommonDialogueOptionScRsp(eventInstance)); + } +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Miracle/RogueMiracleInstance.cs b/GameServer/Game/Rogue/Miracle/RogueMiracleInstance.cs index 3d0101da..08401c31 100644 --- a/GameServer/Game/Rogue/Miracle/RogueMiracleInstance.cs +++ b/GameServer/Game/Rogue/Miracle/RogueMiracleInstance.cs @@ -4,177 +4,158 @@ using EggLink.DanhengServer.Enums.Rogue; using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Miracle +namespace EggLink.DanhengServer.Game.Rogue.Miracle; + +public class RogueMiracleInstance { - public class RogueMiracleInstance + public RogueMiracleInstance(BaseRogueInstance instance, int miracleId) { - public BaseRogueInstance Instance { get; } - public int MiracleId { get; private set; } - public int Durability { get; private set; } - public int UsedTimes { get; set; } - public int UseMoney { get; set; } - public bool IsDestroyed { get; set; } = false; - public RogueMiracleEffect? MiracleEffect { get; private set; } + Instance = instance; + MiracleId = miracleId; - public RogueMiracleInstance(BaseRogueInstance instance, int miracleId) - { - Instance = instance; - MiracleId = miracleId; + GameData.RogueMiracleEffectData.Miracles.TryGetValue(MiracleId, out var effect); + MiracleEffect = effect; - GameData.RogueMiracleEffectData.Miracles.TryGetValue(MiracleId, out var effect); - MiracleEffect = effect; + if (MiracleEffect != null) Durability = MiracleEffect.MaxDurability; - if (MiracleEffect != null) - { - Durability = MiracleEffect.MaxDurability; - } + OnGetMiracle(); + } - OnGetMiracle(); - } + public BaseRogueInstance Instance { get; } + public int MiracleId { get; } + public int Durability { get; } + public int UsedTimes { get; set; } + public int UseMoney { get; set; } + public bool IsDestroyed { get; set; } + public RogueMiracleEffect? MiracleEffect { get; } - public void OnStartBattle(BattleInstance battle) - { - if (IsDestroyed) return; - if (MiracleEffect == null) return; + public void OnStartBattle(BattleInstance battle) + { + if (IsDestroyed) return; + if (MiracleEffect == null) return; - foreach (var effect in MiracleEffect.Effects.Values) - { - if (effect.Type == RogueMiracleEffectTypeEnum.OnBattleStart) + foreach (var effect in MiracleEffect.Effects.Values) + if (effect.Type == RogueMiracleEffectTypeEnum.OnBattleStart) + foreach (var param in effect.Params) { - foreach (var param in effect.Params) + MiracleEffect.Effects.TryGetValue(param, out var target); + if (target == null) continue; + + if (target.Type == RogueMiracleEffectTypeEnum.AddMazeBuff) { - MiracleEffect.Effects.TryGetValue(param, out var target); - if (target == null) continue; - - if (target.Type == RogueMiracleEffectTypeEnum.AddMazeBuff) + var buffId = target.Params[0]; + var dynamicEffect = target.Params[1]; + var buff = new MazeBuff(buffId, 1, -1) { - var buffId = target.Params[0]; - var dynamicEffect = target.Params[1]; - var buff = new MazeBuff(buffId, 1, -1) - { - WaveFlag = -1 - }; + WaveFlag = -1 + }; - if (dynamicEffect != 0) - { - MiracleEffect.Effects.TryGetValue(dynamicEffect, out var dynamic); - if (dynamic != null) - { - buff.DynamicValues.Add(dynamic.DynamicKey, CalculateArg(dynamic.Type)); - } - } - - battle.Buffs.Add(buff); + if (dynamicEffect != 0) + { + MiracleEffect.Effects.TryGetValue(dynamicEffect, out var dynamic); + if (dynamic != null) buff.DynamicValues.Add(dynamic.DynamicKey, CalculateArg(dynamic.Type)); } + + battle.Buffs.Add(buff); } } - } - } + } - public void OnEndBattle(BattleInstance battle) + public void OnEndBattle(BattleInstance battle) + { + if (IsDestroyed) return; + if (MiracleEffect == null) return; + } + + public void OnEnterNextRoom() + { + if (IsDestroyed) return; + if (MiracleEffect == null) return; + } + + public void OnGetMiracle() + { + if (IsDestroyed) return; + if (MiracleEffect == null) return; + } + + public void OnDestroy() + { + if (IsDestroyed) return; + if (MiracleEffect == null) return; + } + + public int CalculateArg(RogueMiracleEffectTypeEnum type) + { + switch (type) { - if (IsDestroyed) return; - if (MiracleEffect == null) return; - } - - public void OnEnterNextRoom() - { - if (IsDestroyed) return; - if (MiracleEffect == null) return; - } - - public void OnGetMiracle() - { - if (IsDestroyed) return; - if (MiracleEffect == null) return; - } - - public void OnDestroy() - { - if (IsDestroyed) return; - if (MiracleEffect == null) return; - } - - public int CalculateArg(RogueMiracleEffectTypeEnum type) - { - switch (type) - { - case RogueMiracleEffectTypeEnum.CurMoney: - return Instance.CurMoney; - case RogueMiracleEffectTypeEnum.CurDestroyCount: - return Instance.CurDestroyCount; - case RogueMiracleEffectTypeEnum.CurBrokenMiracleCount: - int count = 0; - foreach (var miracle in Instance.RogueMiracles.Values) - { - if (miracle.IsDestroyed) - { - count++; - } - } - return count; - case RogueMiracleEffectTypeEnum.UseMoney: - return UseMoney; - default: - return 0; - } - } - - public void CostDurability(int value) - { - UsedTimes = Math.Min(UsedTimes + value, Durability); // Prevent overflow - if (Durability > 0) // 0 means infinite durability - { - if (Durability <= UsedTimes) // Destroy the miracle - { - OnDestroy(); - IsDestroyed = true; - } - - // send packet - Instance.Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(Instance.RogueVersionId, ToGetResult(), RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle)); - } - } - - public RogueMiracle ToProto() - { - return new() - { - MiracleId = (uint)MiracleId, - MaxTimes = (uint)Durability, - CurTimes = (uint)UsedTimes - }; - } - - public GameRogueMiracle ToGameMiracleProto() - { - return new() - { - MiracleId = (uint)MiracleId, - MaxTimes = (uint)Durability, - CurTimes = (uint)UsedTimes - }; - } - - public RogueCommonActionResult ToGetResult() - { - return new() - { - Source = RogueActionSource.RogueCommonActionResultSourceTypeSelect, - RogueAction = new() - { - GetMiracleList = new() - { - MiracleInfo = ToGameMiracleProto() - }, - } - }; + case RogueMiracleEffectTypeEnum.CurMoney: + return Instance.CurMoney; + case RogueMiracleEffectTypeEnum.CurDestroyCount: + return Instance.CurDestroyCount; + case RogueMiracleEffectTypeEnum.CurBrokenMiracleCount: + var count = 0; + foreach (var miracle in Instance.RogueMiracles.Values) + if (miracle.IsDestroyed) + count++; + return count; + case RogueMiracleEffectTypeEnum.UseMoney: + return UseMoney; + default: + return 0; } } -} + + public async ValueTask CostDurability(int value) + { + UsedTimes = Math.Min(UsedTimes + value, Durability); // Prevent overflow + if (Durability > 0) // 0 means infinite durability + { + if (Durability <= UsedTimes) // Destroy the miracle + { + OnDestroy(); + IsDestroyed = true; + } + + // send packet + await Instance.Player.SendPacket(new PacketSyncRogueCommonActionResultScNotify(Instance.RogueVersionId, + ToGetResult(), RogueActionDisplayType.RogueCommonActionResultDisplayTypeSingle)); + } + } + + public RogueMiracle ToProto() + { + return new RogueMiracle + { + MiracleId = (uint)MiracleId, + MaxTimes = (uint)Durability, + CurTimes = (uint)UsedTimes + }; + } + + public GameRogueMiracle ToGameMiracleProto() + { + return new GameRogueMiracle + { + MiracleId = (uint)MiracleId, + MaxTimes = (uint)Durability, + CurTimes = (uint)UsedTimes + }; + } + + public RogueCommonActionResult ToGetResult() + { + return new RogueCommonActionResult + { + Source = RogueActionSource.RogueCommonActionResultSourceTypeSelect, + RogueAction = new RogueCommonActionResultData + { + GetMiracleList = new RogueCommonMiracle + { + MiracleInfo = ToGameMiracleProto() + } + } + }; + } +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Miracle/RogueMiracleSelectMenu.cs b/GameServer/Game/Rogue/Miracle/RogueMiracleSelectMenu.cs index 81ac6ec1..83fbd799 100644 --- a/GameServer/Game/Rogue/Miracle/RogueMiracleSelectMenu.cs +++ b/GameServer/Game/Rogue/Miracle/RogueMiracleSelectMenu.cs @@ -1,55 +1,45 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using Microsoft.AspNetCore.Routing; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Miracle +namespace EggLink.DanhengServer.Game.Rogue.Miracle; + +public class RogueMiracleSelectMenu(BaseRogueInstance instance) { - public class RogueMiracleSelectMenu(BaseRogueInstance instance) + public List Pools { get; set; } = []; + + public List Results { get; set; } = []; + + public void RollMiracle(List pools) { - public List Pools { get; set; } = []; + Pools = pools; + Results.Clear(); - public List Results { get; set; } = []; - - public void RollMiracle(List pools) + for (var i = 0; i < 3; i++) { - Pools = pools; - Results.Clear(); + var id = Pools.RandomElement(); + Results.Add((uint)id); + Pools.Remove(id); - for (int i = 0; i < 3; i++) - { - var id = Pools.RandomElement(); - Results.Add((uint)id); - Pools.Remove(id); - - if (Pools.Count == 0) - { - break; - } - } - } - - public RogueActionInstance GetActionInstance() - { - instance.CurActionQueuePosition += 3; - return new() - { - QueuePosition = instance.CurActionQueuePosition, - RogueMiracleSelectMenu = this - }; - } - - public RogueMiracleSelectInfo ToProto() - { - var info = new RogueMiracleSelectInfo(); - info.SelectMiracleList.AddRange(Results); - info.MiracleHandbookList.AddRange(Results); - - return info; + if (Pools.Count == 0) break; } } -} + + public RogueActionInstance GetActionInstance() + { + instance.CurActionQueuePosition += 3; + return new RogueActionInstance + { + QueuePosition = instance.CurActionQueuePosition, + RogueMiracleSelectMenu = this + }; + } + + public RogueMiracleSelectInfo ToProto() + { + var info = new RogueMiracleSelectInfo(); + info.SelectMiracleList.AddRange(Results); + info.MiracleHandbookList.AddRange(Results); + + return info; + } +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/RogueActionInstance.cs b/GameServer/Game/Rogue/RogueActionInstance.cs index e58e6742..5b513a2f 100644 --- a/GameServer/Game/Rogue/RogueActionInstance.cs +++ b/GameServer/Game/Rogue/RogueActionInstance.cs @@ -1,55 +1,38 @@ -using EggLink.DanhengServer.Data.Excel; -using EggLink.DanhengServer.Game.Rogue.Buff; +using EggLink.DanhengServer.Game.Rogue.Buff; using EggLink.DanhengServer.Game.Rogue.Miracle; using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue +namespace EggLink.DanhengServer.Game.Rogue; + +public class RogueActionInstance { - public class RogueActionInstance + public int QueuePosition { get; set; } = 0; + public RogueBuffSelectMenu? RogueBuffSelectMenu { get; set; } + public RogueMiracleSelectMenu? RogueMiracleSelectMenu { get; set; } + public RogueBonusSelectInfo? RogueBonusSelectInfo { get; set; } + + public void SetBonus() { - public int QueuePosition { get; set; } = 0; - public RogueBuffSelectMenu? RogueBuffSelectMenu { get; set; } - public RogueMiracleSelectMenu? RogueMiracleSelectMenu { get; set; } - public RogueBonusSelectInfo? RogueBonusSelectInfo { get; set; } - - public void SetBonus() + RogueBonusSelectInfo = new RogueBonusSelectInfo { - RogueBonusSelectInfo = new() - { - BonusIdList = { 4, 5, 6 } - }; - } - - public RogueCommonPendingAction ToProto() - { - var action = new RogueAction(); - - if (RogueBuffSelectMenu != null) - { - action.BuffSelectInfo = RogueBuffSelectMenu.ToProto(); - } - - if (RogueMiracleSelectMenu != null) - { - action.MiracleSelectInfo = RogueMiracleSelectMenu.ToProto(); - } - - if (RogueBonusSelectInfo != null) - { - action.BonusSelectInfo = RogueBonusSelectInfo; - } - - return new() - { - QueuePosition = (uint)QueuePosition, - RogueAction = action - }; - } + BonusIdList = { 4, 5, 6 } + }; } -} + + public RogueCommonPendingAction ToProto() + { + var action = new RogueAction(); + + if (RogueBuffSelectMenu != null) action.BuffSelectInfo = RogueBuffSelectMenu.ToProto(); + + if (RogueMiracleSelectMenu != null) action.MiracleSelectInfo = RogueMiracleSelectMenu.ToProto(); + + if (RogueBonusSelectInfo != null) action.BonusSelectInfo = RogueBonusSelectInfo; + + return new RogueCommonPendingAction + { + QueuePosition = (uint)QueuePosition, + RogueAction = action + }; + } +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/RogueInstance.cs b/GameServer/Game/Rogue/RogueInstance.cs index a9975109..7d27719e 100644 --- a/GameServer/Game/Rogue/RogueInstance.cs +++ b/GameServer/Game/Rogue/RogueInstance.cs @@ -1,421 +1,387 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Rogue.Buff; +using EggLink.DanhengServer.Game.Rogue.Event; using EggLink.DanhengServer.Game.Rogue.Scene; using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Util; using EggLink.DanhengServer.Server.Packet.Send.Rogue; +using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Rogue +namespace EggLink.DanhengServer.Game.Rogue; + +public class RogueInstance : BaseRogueInstance { - public class RogueInstance : BaseRogueInstance + #region Initialization + + public RogueInstance(RogueAreaConfigExcel areaExcel, RogueAeonExcel aeonExcel, PlayerInstance player) : base(player, + 101, aeonExcel.RogueBuffType) { - #region Properties + AreaExcel = areaExcel; + AeonExcel = aeonExcel; + AeonId = aeonExcel.AeonID; + Player = player; + CurLineup = player.LineupManager!.GetCurLineup()!; + EventManager = new RogueEventManager(player, this); - public RogueStatus Status { get; set; } = RogueStatus.Doing; - public int CurReachedRoom { get; set; } = 0; - - public RogueAeonExcel AeonExcel { get; set; } - public RogueAreaConfigExcel AreaExcel { get; set; } - public Dictionary RogueRooms { get; set; } = []; - public RogueRoomInstance? CurRoom { get; set; } - public int StartSiteId { get; set; } = 0; - - #endregion - - #region Initialization - - public RogueInstance(RogueAreaConfigExcel areaExcel, RogueAeonExcel aeonExcel, PlayerInstance player) : base(player, 101, aeonExcel.RogueBuffType) + foreach (var item in areaExcel.RogueMaps.Values) { - AreaExcel = areaExcel; - AeonExcel = aeonExcel; - AeonId = aeonExcel.AeonID; - Player = player; - CurLineup = player.LineupManager!.GetCurLineup()!; - EventManager = new(player, this); - - foreach (var item in areaExcel.RogueMaps.Values) - { - RogueRooms.Add(item.SiteID, new(item)); - if (item.IsStart) - { - StartSiteId = item.SiteID; - } - } - - // add bonus - var action = new RogueActionInstance() - { - QueuePosition = CurActionQueuePosition, - }; - action.SetBonus(); - - RogueActions.Add(CurActionQueuePosition, action); + RogueRooms.Add(item.SiteID, new RogueRoomInstance(item)); + if (item.IsStart) StartSiteId = item.SiteID; } - #endregion - - #region Buffs - - public override void RollBuff(int amount) + // add bonus + var action = new RogueActionInstance { - if (CurRoom!.Excel.RogueRoomType == 6) - { - RollBuff(amount, 100003, 2); // boss room - RollMiracle(1); - } - else - { - RollBuff(amount, 100005); - } + QueuePosition = CurActionQueuePosition + }; + action.SetBonus(); + + RogueActions.Add(CurActionQueuePosition, action); + } + + #endregion + + #region Properties + + public RogueStatus Status { get; set; } = RogueStatus.Doing; + public int CurReachedRoom { get; set; } + + public RogueAeonExcel AeonExcel { get; set; } + public RogueAreaConfigExcel AreaExcel { get; set; } + public Dictionary RogueRooms { get; set; } = []; + public RogueRoomInstance? CurRoom { get; set; } + public int StartSiteId { get; set; } + + #endregion + + #region Buffs + + public override async ValueTask RollBuff(int amount) + { + if (CurRoom!.Excel.RogueRoomType == 6) + { + await RollBuff(amount, 100003, 2); // boss room + await RollMiracle(1); } - - public void AddAeonBuff() + else { - if (AeonBuffPending) return; - if (CurAeonBuffCount + CurAeonEnhanceCount >= 4) - { - // max aeon buff count - return; - } - int curAeonBuffCount = 0; // current path buff count - int hintId = AeonId * 100 + 1; - var enhanceData = GameData.RogueAeonEnhanceData[AeonId]; - var buffData = GameData.RogueAeonBuffData[AeonId]; - foreach (var buff in RogueBuffs) - { - if (buff.BuffExcel.RogueBuffType == AeonExcel.RogueBuffType) - { - if (!buff.BuffExcel.IsAeonBuff) - { - curAeonBuffCount++; - } - else - { - hintId++; // next hint - enhanceData.Remove(buff.BuffExcel); - } - } - } + await RollBuff(amount, 100005); + } + } - var needAeonBuffCount = (CurAeonBuffCount + CurAeonEnhanceCount) switch + public async ValueTask AddAeonBuff() + { + if (AeonBuffPending) return; + if (CurAeonBuffCount + CurAeonEnhanceCount >= 4) + // max aeon buff count + return; + var curAeonBuffCount = 0; // current path buff count + var hintId = AeonId * 100 + 1; + var enhanceData = GameData.RogueAeonEnhanceData[AeonId]; + var buffData = GameData.RogueAeonBuffData[AeonId]; + foreach (var buff in RogueBuffs) + if (buff.BuffExcel.RogueBuffType == AeonExcel.RogueBuffType) { - 0 => 3, - 1 => 6, - 2 => 10, - 3 => 14, - _ => 100, - }; - - if (curAeonBuffCount >= needAeonBuffCount) - { - RogueBuffSelectMenu menu = new(this) + if (!buff.BuffExcel.IsAeonBuff) { - QueueAppend = 2, - HintId = hintId, - RollMaxCount = 0, - RollFreeCount = 0, - IsAeonBuff = true, - }; - if (CurAeonBuffCount < 1) - { - CurAeonBuffCount++; - // add aeon buff - menu.RollBuff([buffData], 1); + curAeonBuffCount++; } else { - CurAeonEnhanceCount++; - // add enhance buff - menu.RollBuff(enhanceData, enhanceData.Count); - } - - var action = menu.GetActionInstance(); - RogueActions.Add(action.QueuePosition, action); - - AeonBuffPending = true; - UpdateMenu(); - } - } - - #endregion - - #region Methods - - public override void UpdateMenu() - { - base.UpdateMenu(); - - - AddAeonBuff(); // check if aeon buff can be added - } - - public RogueRoomInstance? EnterRoom(int siteId) - { - var prevRoom = CurRoom; - if (prevRoom != null) - { - if (!prevRoom.NextSiteIds.Contains(siteId)) - { - return null; - } - prevRoom.Status = RogueRoomStatus.Finish; - // send - Player.SendPacket(new PacketSyncRogueMapRoomScNotify(prevRoom, AreaExcel.MapId)); - } - - // next room - CurReachedRoom++; - CurRoom = RogueRooms[siteId]; - CurRoom.Status = RogueRoomStatus.Play; - - Player.EnterScene(CurRoom.Excel.MapEntrance, 0, false); - - // move - AnchorInfo? anchor = Player.SceneInstance!.FloorInfo?.GetAnchorInfo(CurRoom.Excel.GroupID, 1); - if (anchor != null) - { - Player.Data.Pos = anchor.ToPositionProto(); - Player.Data.Rot = anchor.ToRotationProto(); - } - - // send - Player.SendPacket(new PacketSyncRogueMapRoomScNotify(CurRoom, AreaExcel.MapId)); - - // call event - EventManager?.OnNextRoom(); - foreach (var miracle in RogueMiracles.Values) - { - miracle.OnEnterNextRoom(); - } - - return CurRoom; - } - - public void LeaveRogue() - { - Player.RogueManager!.RogueInstance = null; - Player.EnterScene(801120102, 0, false); - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); - } - - public void QuitRogue() - { - Status = RogueStatus.Finish; - Player.SendPacket(new PacketSyncRogueStatusScNotify(Status)); - Player.SendPacket(new PacketSyncRogueFinishScNotify(ToFinishInfo())); - } - - #endregion - - #region Handlers - - public override void OnBattleStart(BattleInstance battle) - { - base.OnBattleStart(battle); - - GameData.RogueMapData.TryGetValue(AreaExcel.MapId, out var mapData); - if (mapData != null) - { - mapData.TryGetValue(CurRoom!.SiteId, out var mapInfo); - if (mapInfo != null && mapInfo.LevelList.Count > 0) - { - battle.CustomLevel = mapInfo.LevelList.RandomElement(); + hintId++; // next hint + enhanceData.Remove(buff.BuffExcel); } } - } - public override void OnBattleEnd(BattleInstance battle, PVEBattleResultCsReq req) + var needAeonBuffCount = (CurAeonBuffCount + CurAeonEnhanceCount) switch { - foreach (var miracle in RogueMiracles.Values) - { - miracle.OnEndBattle(battle); - } + 0 => 3, + 1 => 6, + 2 => 10, + 3 => 14, + _ => 100 + }; - if (req.EndStatus != BattleEndStatus.BattleEndWin) + if (curAeonBuffCount >= needAeonBuffCount) + { + RogueBuffSelectMenu menu = new(this) { - // quit - QuitRogue(); - return; - } - - if (CurRoom!.NextSiteIds.Count == 0) + QueueAppend = 2, + HintId = hintId, + RollMaxCount = 0, + RollFreeCount = 0, + IsAeonBuff = true + }; + if (CurAeonBuffCount < 1) { - // last room - IsWin = true; - Player.SendPacket(new PacketSyncRogueExploreWinScNotify()); + CurAeonBuffCount++; + // add aeon buff + menu.RollBuff([buffData], 1); } else { - RollBuff(battle.Stages.Count); - GainMoney(Random.Shared.Next(20, 60) * battle.Stages.Count); + CurAeonEnhanceCount++; + // add enhance buff + menu.RollBuff(enhanceData, enhanceData.Count); } + + var action = menu.GetActionInstance(); + RogueActions.Add(action.QueuePosition, action); + + AeonBuffPending = true; + await UpdateMenu(); + } + } + + #endregion + + #region Methods + + public override async ValueTask UpdateMenu() + { + await base.UpdateMenu(); + + + await AddAeonBuff(); // check if aeon buff can be added + } + + public async ValueTask EnterRoom(int siteId) + { + var prevRoom = CurRoom; + if (prevRoom != null) + { + if (!prevRoom.NextSiteIds.Contains(siteId)) return null; + prevRoom.Status = RogueRoomStatus.Finish; + // send + await Player.SendPacket(new PacketSyncRogueMapRoomScNotify(prevRoom, AreaExcel.MapId)); } - #endregion + // next room + CurReachedRoom++; + CurRoom = RogueRooms[siteId]; + CurRoom.Status = RogueRoomStatus.Play; - #region Serialization + await Player.EnterScene(CurRoom.Excel.MapEntrance, 0, false); - public RogueCurrentInfo ToProto() + // move + var anchor = Player.SceneInstance!.FloorInfo?.GetAnchorInfo(CurRoom.Excel.GroupID, 1); + if (anchor != null) { - var proto = new RogueCurrentInfo() + Player.Data.Pos = anchor.ToPositionProto(); + Player.Data.Rot = anchor.ToRotationProto(); + } + + // send + await Player.SendPacket(new PacketSyncRogueMapRoomScNotify(CurRoom, AreaExcel.MapId)); + + // call event + EventManager?.OnNextRoom(); + foreach (var miracle in RogueMiracles.Values) miracle.OnEnterNextRoom(); + + return CurRoom; + } + + public async ValueTask LeaveRogue() + { + Player.RogueManager!.RogueInstance = null; + await Player.EnterScene(801120102, 0, false); + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupNone, []); + } + + public async ValueTask QuitRogue() + { + Status = RogueStatus.Finish; + await Player.SendPacket(new PacketSyncRogueStatusScNotify(Status)); + await Player.SendPacket(new PacketSyncRogueFinishScNotify(ToFinishInfo())); + } + + #endregion + + #region Handlers + + public override void OnBattleStart(BattleInstance battle) + { + base.OnBattleStart(battle); + + GameData.RogueMapData.TryGetValue(AreaExcel.MapId, out var mapData); + if (mapData != null) + { + mapData.TryGetValue(CurRoom!.SiteId, out var mapInfo); + if (mapInfo != null && mapInfo.LevelList.Count > 0) battle.CustomLevel = mapInfo.LevelList.RandomElement(); + } + } + + public override async ValueTask OnBattleEnd(BattleInstance battle, PVEBattleResultCsReq req) + { + foreach (var miracle in RogueMiracles.Values) miracle.OnEndBattle(battle); + + if (req.EndStatus != BattleEndStatus.BattleEndWin) + { + // quit + await QuitRogue(); + return; + } + + if (CurRoom!.NextSiteIds.Count == 0) + { + // last room + IsWin = true; + await Player.SendPacket(new PacketSyncRogueExploreWinScNotify()); + } + else + { + await RollBuff(battle.Stages.Count); + await GainMoney(Random.Shared.Next(20, 60) * battle.Stages.Count); + } + } + + #endregion + + #region Serialization + + public RogueCurrentInfo ToProto() + { + var proto = new RogueCurrentInfo + { + Status = Status, + GameMiracleInfo = ToMiracleInfo(), + RogueAeonInfo = ToAeonInfo(), + RogueLineupInfo = ToLineupInfo(), + RogueBuffInfo = ToBuffInfo(), + RogueVirtualItem = ToVirtualItemInfo(), + MapInfo = ToMapInfo(), + ModuleInfo = new RogueModuleInfo { - Status = Status, - GameMiracleInfo = ToMiracleInfo(), - RogueAeonInfo = ToAeonInfo(), - RogueLineupInfo = ToLineupInfo(), - RogueBuffInfo = ToBuffInfo(), - RogueVirtualItem = ToVirtualItemInfo(), - MapInfo = ToMapInfo(), - ModuleInfo = new() + ModuleIdList = { 1, 2, 3, 4, 5 } + }, + IsWin = IsWin + }; + + if (RogueActions.Count > 0) + proto.PendingAction = RogueActions.First().Value.ToProto(); + else + proto.PendingAction = new RogueCommonPendingAction(); + + return proto; + } + + public GameAeonInfo ToAeonInfo() + { + return new GameAeonInfo + { + AeonId = (uint)AeonId, + IsUnlocked = AeonId != 0, + UnlockedAeonEnhanceNum = (uint)(AeonId != 0 ? 3 : 0) + }; + } + + public RogueLineupInfo ToLineupInfo() + { + var proto = new RogueLineupInfo(); + + foreach (var avatar in CurLineup!.BaseAvatars!) proto.BaseAvatarIdList.Add((uint)avatar.BaseAvatarId); + + proto.ReviveInfo = new RogueReviveInfo + { + RogueReviveCost = new ItemCostData + { + ItemList = { - ModuleIdList = { 1, 2, 3, 4, 5 }, - }, - IsWin = IsWin, - }; - - if (RogueActions.Count > 0) - { - proto.PendingAction = RogueActions.First().Value.ToProto(); - } else - { - proto.PendingAction = new(); - } - - return proto; - } - - public GameAeonInfo ToAeonInfo() - { - return new() - { - AeonId = (uint)AeonId, - IsUnlocked = AeonId != 0, - UnlockedAeonEnhanceNum = (uint)(AeonId != 0 ? 3 : 0) - }; - } - - public RogueLineupInfo ToLineupInfo() - { - var proto = new RogueLineupInfo(); - - foreach (var avatar in CurLineup!.BaseAvatars!) - { - proto.BaseAvatarIdList.Add((uint)avatar.BaseAvatarId); - } - - proto.ReviveInfo = new() - { - RogueReviveCost = new() - { - ItemList = { - new ItemCost() { - PileItem = new PileItem() { - ItemId = 31, - ItemNum = (uint)CurReviveCost - } - }, + new ItemCost + { + PileItem = new PileItem + { + ItemId = 31, + ItemNum = (uint)CurReviveCost + } } } - }; - - return proto; - } - - public RogueVirtualItem ToVirtualItemInfo() - { - return new() - { - RogueMoney = (uint)CurMoney, - }; - } - - public RogueMapInfo ToMapInfo() - { - var proto = new RogueMapInfo() - { - CurSiteId = (uint)CurRoom!.SiteId, - CurRoomId = (uint)CurRoom!.RoomId, - AreaId = (uint)AreaExcel.RogueAreaID, - MapId = (uint)AreaExcel.MapId, - }; - - foreach (var room in RogueRooms) - { - proto.RoomList.Add(room.Value.ToProto()); } + }; - return proto; - } + return proto; + } - public GameMiracleInfo ToMiracleInfo() + public RogueVirtualItem ToVirtualItemInfo() + { + return new RogueVirtualItem { - var proto = new GameMiracleInfo() + RogueMoney = (uint)CurMoney + }; + } + + public RogueMapInfo ToMapInfo() + { + var proto = new RogueMapInfo + { + CurSiteId = (uint)CurRoom!.SiteId, + CurRoomId = (uint)CurRoom!.RoomId, + AreaId = (uint)AreaExcel.RogueAreaID, + MapId = (uint)AreaExcel.MapId + }; + + foreach (var room in RogueRooms) proto.RoomList.Add(room.Value.ToProto()); + + return proto; + } + + public GameMiracleInfo ToMiracleInfo() + { + var proto = new GameMiracleInfo + { + GameMiracleInfo_ = new RogueMiracleInfo() + }; + + foreach (var miracle in RogueMiracles.Values) proto.GameMiracleInfo_.MiracleList.Add(miracle.ToProto()); + + return proto; + } + + public RogueBuffInfo ToBuffInfo() + { + var proto = new RogueBuffInfo(); + + foreach (var buff in RogueBuffs) proto.MazeBuffList.Add(buff.ToProto()); + + return proto; + } + + public RogueFinishInfo ToFinishInfo() + { + AreaExcel.ScoreMap.TryGetValue(CurReachedRoom, out var score); + var prev = Player.RogueManager!.ToRewardProto(); + Player.RogueManager!.AddRogueScore(score); + var next = Player.RogueManager!.ToRewardProto(); + + return new RogueFinishInfo + { + ScoreId = (uint)score, + //TotalScore = (uint)score, + //PrevRewardInfo = prev, + //NextRewardInfo = next, + AreaId = (uint)AreaExcel.RogueAreaID, + //FinishedRoomCount = (uint)CurReachedRoom, + //ReachedRoomCount = (uint)CurReachedRoom, + IsWin = IsWin, + Record = new RogueRecordInfo { - GameMiracleInfo_ = new() + AvatarList = { - MiracleList = { }, // for the client serialization - } - }; - - foreach (var miracle in RogueMiracles.Values) - { - proto.GameMiracleInfo_.MiracleList.Add(miracle.ToProto()); - } - - return proto; - } - - public RogueBuffInfo ToBuffInfo() - { - var proto = new RogueBuffInfo() - { - MazeBuffList = { } - }; - - foreach (var buff in RogueBuffs) - { - proto.MazeBuffList.Add(buff.ToProto()); - } - - return proto; - } - - public RogueFinishInfo ToFinishInfo() - { - AreaExcel.ScoreMap.TryGetValue(CurReachedRoom, out var score); - var prev = Player.RogueManager!.ToRewardProto(); - Player.RogueManager!.AddRogueScore(score); - var next = Player.RogueManager!.ToRewardProto(); - - return new() - { - ScoreId = (uint)score, - //TotalScore = (uint)score, - //PrevRewardInfo = prev, - //NextRewardInfo = next, - AreaId = (uint)AreaExcel.RogueAreaID, - //FinishedRoomCount = (uint)CurReachedRoom, - //ReachedRoomCount = (uint)CurReachedRoom, - IsWin = IsWin, - Record = new() - { - AvatarList = { CurLineup!.BaseAvatars!.Select(avatar => new RogueRecordAvatar() + CurLineup!.BaseAvatars!.Select(avatar => new RogueRecordAvatar { Id = (uint)avatar.BaseAvatarId, AvatarType = AvatarType.AvatarFormalType, Level = (uint)(Player.AvatarManager!.GetAvatar(avatar.BaseAvatarId)?.Level ?? 0), - Slot = (uint)CurLineup!.BaseAvatars!.IndexOf(avatar), - }) }, - BuffList = { RogueBuffs.Select(buff => buff.ToProto()) }, - MiracleList = { RogueMiracles.Values.Select(miracle => (uint)miracle.MiracleId) }, - } - }; - } - - #endregion + Slot = (uint)CurLineup!.BaseAvatars!.IndexOf(avatar) + }) + }, + BuffList = { RogueBuffs.Select(buff => buff.ToProto()) }, + MiracleList = { RogueMiracles.Values.Select(miracle => (uint)miracle.MiracleId) } + } + }; } -} + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/RogueManager.cs b/GameServer/Game/Rogue/RogueManager.cs index edbcaa58..f5720d08 100644 --- a/GameServer/Game/Rogue/RogueManager.cs +++ b/GameServer/Game/Rogue/RogueManager.cs @@ -5,220 +5,194 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Lineup; using EggLink.DanhengServer.Server.Packet.Send.Rogue; using EggLink.DanhengServer.Util; -using Spectre.Console; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue +namespace EggLink.DanhengServer.Game.Rogue; + +public class RogueManager(PlayerInstance player) : BasePlayerManager(player) { - public class RogueManager(PlayerInstance player) : BasePlayerManager(player) + #region Properties + + public RogueInstance? RogueInstance { get; set; } + + #endregion + + #region Information + + /// + /// Get the begin time and end time + /// + /// + public static (long, long) GetCurrentRogueTime() { - #region Properties + // get the first day of the week + var beginTime = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).AddHours(4); + var endTime = beginTime.AddDays(7); + return (beginTime.ToUnixSec(), endTime.ToUnixSec()); + } - public RogueInstance? RogueInstance { get; set; } + public int GetRogueScore() + { + return 0; + // TODO: Implement + } - #endregion + public void AddRogueScore(int score) + { + } - #region Information + public static RogueManagerExcel? GetCurrentManager() + { + foreach (var manager in GameData.RogueManagerData.Values) + if (DateTime.Now >= manager.BeginTimeDate && DateTime.Now <= manager.EndTimeDate) + return manager; + return null; + } - /// - /// Get the begin time and end time - /// - /// - public static (long, long) GetCurrentRogueTime() + #endregion + + #region Actions + + public async ValueTask StartRogue(int areaId, int aeonId, List disableAeonId, List baseAvatarIds) + { + if (GetRogueInstance() != null) return; + GameData.RogueAreaConfigData.TryGetValue(areaId, out var area); + GameData.RogueAeonData.TryGetValue(aeonId, out var aeon); + + if (area == null || aeon == null) return; + + Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupRogue, baseAvatarIds); + await Player.LineupManager!.GainMp(5, false); + await Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); + + foreach (var id in baseAvatarIds) { - // get the first day of the week - var beginTime = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).AddHours(4); - var endTime = beginTime.AddDays(7); - return (beginTime.ToUnixSec(), endTime.ToUnixSec()); + Player.AvatarManager!.GetAvatar(id)?.SetCurHp(10000, true); + Player.AvatarManager!.GetAvatar(id)?.SetCurSp(5000, true); } - public int GetRogueScore() => 0; // TODO: Implement + RogueInstance = new RogueInstance(area, aeon, Player); + await RogueInstance.EnterRoom(RogueInstance.StartSiteId); - public void AddRogueScore(int score) + await Player.SendPacket(new PacketSyncRogueStatusScNotify(RogueInstance.Status)); + await Player.SendPacket(new PacketStartRogueScRsp(Player)); + } + + public BaseRogueInstance? GetRogueInstance() + { + if (RogueInstance != null) + return RogueInstance; + return Player.ChessRogueManager!.RogueInstance; + } + + #endregion + + #region Serialization + + public RogueInfo ToProto() + { + var proto = new RogueInfo { + RogueGetInfo = ToGetProto() + }; - } + if (RogueInstance != null) proto.RogueCurrentInfo = RogueInstance.ToProto(); - public static RogueManagerExcel? GetCurrentManager() + return proto; + } + + public RogueGetInfo ToGetProto() + { + return new RogueGetInfo { - foreach (var manager in GameData.RogueManagerData.Values) - { - if (DateTime.Now >= manager.BeginTimeDate && DateTime.Now <= manager.EndTimeDate) - { - return manager; - } - } - return null; - } + RogueScoreRewardInfo = ToRewardProto(), + RogueAeonInfo = ToAeonInfo(), + RogueSeasonInfo = ToSeasonProto(), + RogueAreaInfo = ToAreaProto(), + RogueVirtualItemInfo = ToVirtualItemProto() + }; + } - #endregion + public RogueScoreRewardInfo ToRewardProto() + { + var time = GetCurrentRogueTime(); - #region Actions - - public void StartRogue(int areaId, int aeonId, List disableAeonId, List baseAvatarIds) + return new RogueScoreRewardInfo { - if (GetRogueInstance() != null) - { - return; - } - GameData.RogueAreaConfigData.TryGetValue(areaId, out var area); - GameData.RogueAeonData.TryGetValue(aeonId, out var aeon); + ExploreScore = (uint)GetRogueScore(), + PoolRefreshed = true, + PoolId = (uint)(20 + Player.Data.WorldLevel), + BeginTime = time.Item1, + EndTime = time.Item2, + HasTakenInitialScore = true + }; + } - if (area == null || aeon == null) - { - return; - } - - Player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupRogue, baseAvatarIds); - Player.LineupManager!.GainMp(5, false); - Player.SendPacket(new PacketSyncLineupNotify(Player.LineupManager!.GetCurLineup()!)); - - foreach (var id in baseAvatarIds) - { - Player.AvatarManager!.GetAvatar(id)?.SetCurHp(10000, true); - Player.AvatarManager!.GetAvatar(id)?.SetCurSp(5000, true); - } - - RogueInstance = new RogueInstance(area, aeon, Player); - RogueInstance.EnterRoom(RogueInstance.StartSiteId); - - Player.SendPacket(new PacketSyncRogueStatusScNotify(RogueInstance.Status)); - Player.SendPacket(new PacketStartRogueScRsp(Player)); - } - - public BaseRogueInstance? GetRogueInstance() + public static RogueAeonInfo ToAeonInfo() + { + var proto = new RogueAeonInfo { - if (RogueInstance != null) - { - return RogueInstance; - } else - { - return Player.ChessRogueManager!.RogueInstance; - } - } + IsUnlocked = true, + UnlockedAeonNum = (uint)GameData.RogueAeonData.Count, + UnlockedAeonEnhanceNum = 3 + }; - #endregion + proto.AeonIdList.AddRange(GameData.RogueAeonData.Keys.Select(x => (uint)x)); - #region Serialization + return proto; + } - public RogueInfo ToProto() + public static RogueSeasonInfo ToSeasonProto() + { + var manager = GetCurrentManager(); + if (manager == null) return new RogueSeasonInfo(); + + return new RogueSeasonInfo { - var proto = new RogueInfo() - { - RogueGetInfo = ToGetProto() - }; + Season = (uint)manager.RogueSeason, + BeginTime = manager.BeginTimeDate.ToUnixSec(), + EndTime = manager.EndTimeDate.ToUnixSec() + }; + } - if (RogueInstance != null) - { - proto.RogueCurrentInfo = RogueInstance.ToProto(); - } - - return proto; - } - - public RogueGetInfo ToGetProto() + public static RogueAreaInfo ToAreaProto() + { + var manager = GetCurrentManager(); + if (manager == null) return new RogueAreaInfo(); + return new RogueAreaInfo { - return new() + RogueAreaList = { - RogueScoreRewardInfo = ToRewardProto(), - RogueAeonInfo = ToAeonInfo(), - RogueSeasonInfo = ToSeasonProto(), - RogueAreaInfo = ToAreaProto(), - RogueVirtualItemInfo = ToVirtualItemProto() - }; - } - - public RogueScoreRewardInfo ToRewardProto() - { - var time = GetCurrentRogueTime(); - - return new() - { - ExploreScore = (uint)GetRogueScore(), - PoolRefreshed = true, - PoolId = (uint)(20 + Player.Data.WorldLevel), - BeginTime = time.Item1, - EndTime = time.Item2, - HasTakenInitialScore = true - }; - } - - public static RogueAeonInfo ToAeonInfo() - { - var proto = new RogueAeonInfo() - { - IsUnlocked = true, - UnlockedAeonNum = (uint)GameData.RogueAeonData.Count, - UnlockedAeonEnhanceNum = 3 - }; - - proto.AeonIdList.AddRange(GameData.RogueAeonData.Keys.Select(x => (uint)x)); - - return proto; - } - - public static RogueSeasonInfo ToSeasonProto() - { - var manager = GetCurrentManager(); - if (manager == null) - { - return new RogueSeasonInfo(); - } - - return new() - { - Season = (uint)manager.RogueSeason, - BeginTime = manager.BeginTimeDate.ToUnixSec(), - EndTime = manager.EndTimeDate.ToUnixSec(), - }; - } - - public static RogueAreaInfo ToAreaProto() - { - var manager = GetCurrentManager(); - if (manager == null) - { - return new RogueAreaInfo(); - } - return new() - { - RogueAreaList = {manager.RogueAreaIDList.Select(x => new RogueArea() + manager.RogueAreaIDList.Select(x => new RogueArea { AreaId = (uint)x, AreaStatus = RogueAreaStatus.FirstPass, HasTakenReward = true - })} - }; - } - - public static RogueGetVirtualItemInfo ToVirtualItemProto() - { - return new() - { - // TODO: Implement - }; - } - - public static RogueTalentInfo ToTalentProto() - { - var proto = new RogueTalentInfo(); - - foreach (var talent in GameData.RogueTalentData) - { - proto.RogueTalentList.Add(new RogueTalent() - { - TalentId = (uint)talent.Key, - Status = RogueTalentStatus.Enable, - }); + }) } - - return proto; - } - - #endregion + }; } -} + + public static RogueGetVirtualItemInfo ToVirtualItemProto() + { + return new RogueGetVirtualItemInfo + { + // TODO: Implement + }; + } + + public static RogueTalentInfo ToTalentProto() + { + var proto = new RogueTalentInfo(); + + foreach (var talent in GameData.RogueTalentData) + proto.RogueTalentList.Add(new RogueTalent + { + TalentId = (uint)talent.Key, + Status = RogueTalentStatus.Enable + }); + + return proto; + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Scene/Entity/RogueNpc.cs b/GameServer/Game/Rogue/Scene/Entity/RogueNpc.cs index c00d46d6..17995f29 100644 --- a/GameServer/Game/Rogue/Scene/Entity/RogueNpc.cs +++ b/GameServer/Game/Rogue/Scene/Entity/RogueNpc.cs @@ -4,52 +4,44 @@ using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Scene.Entity +namespace EggLink.DanhengServer.Game.Rogue.Scene.Entity; + +public class RogueNpc(SceneInstance scene, GroupInfo group, NpcInfo npcInfo) : EntityNpc(scene, group, npcInfo) { - public class RogueNpc(SceneInstance scene, GroupInfo group, NpcInfo npcInfo) : EntityNpc(scene, group, npcInfo) + public int RogueNpcId { get; set; } + public int UniqueId { get; set; } + private bool IsFinish { get; set; } + + public RogueEventInstance? RogueEvent { get; set; } + + public async ValueTask FinishDialogue() { - public int RogueNpcId { get; set; } - public int UniqueId { get; set; } - private bool IsFinish { get; set; } = false; - - public RogueEventInstance? RogueEvent { get; set; } - - public void FinishDialogue() - { - IsFinish = true; - Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(this)); - } - - public override SceneEntityInfo ToProto() - { - var proto = base.ToProto(); - - if (RogueNpcId > 0 && RogueEvent != null) - { - proto.Npc.ExtraInfo = new() - { - RogueInfo = new() - { - EventId = (uint)RogueNpcId, - EventUniqueId = (uint)UniqueId, - FinishDialogue = IsFinish, - //DialogueGroupId = (uint)GroupID - } - }; - - foreach (var param in RogueEvent.Options) - { - proto.Npc.ExtraInfo.RogueInfo.DialogueEventParamList.Add(param.ToNpcProto()); - } - } - - return proto; - } + IsFinish = true; + await Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(this)); } -} + + public override SceneEntityInfo ToProto() + { + var proto = base.ToProto(); + + if (RogueNpcId > 0 && RogueEvent != null) + { + proto.Npc.ExtraInfo = new NpcExtraInfo + { + RogueInfo = new NpcRogueInfo + { + EventId = (uint)RogueNpcId, + EventUniqueId = (uint)UniqueId, + FinishDialogue = IsFinish + //DialogueGroupId = (uint)GroupID + } + }; + + foreach (var param in RogueEvent.Options) + proto.Npc.ExtraInfo.RogueInfo.DialogueEventParamList.Add(param.ToNpcProto()); + } + + return proto; + } +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Scene/Entity/RogueProp.cs b/GameServer/Game/Rogue/Scene/Entity/RogueProp.cs index fee5d910..7ffae35e 100644 --- a/GameServer/Game/Rogue/Scene/Entity/RogueProp.cs +++ b/GameServer/Game/Rogue/Scene/Entity/RogueProp.cs @@ -3,61 +3,49 @@ using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Rogue.Scene.Entity +namespace EggLink.DanhengServer.Game.Rogue.Scene.Entity; + +public class RogueProp(SceneInstance scene, MazePropExcel excel, GroupInfo group, PropInfo prop) + : EntityProp(scene, excel, group, prop) { - public class RogueProp(SceneInstance scene, MazePropExcel excel, GroupInfo group, PropInfo prop) : EntityProp(scene, excel, group, prop) + public RogueProp(EntityProp prop) : this(prop.Scene, prop.Excel, prop.Group, prop.PropInfo) { - public int NextRoomID { get; set; } - public int NextSiteID { get; set; } - public int ChestCanUseTimes { get; set; } - public int CustomPropID { get; set; } - - public bool IsChessRogue { get; set; } = false; - public bool IsLastRoom { get; set; } = false; - - public RogueProp(EntityProp prop) : this(prop.Scene, prop.Excel, prop.Group, prop.PropInfo) - { - } - - public override SceneEntityInfo ToProto() - { - var proto = base.ToProto(); - - if (NextRoomID != 0 || NextSiteID != 0 || ChestCanUseTimes != 0) // do not set if all are 0 - { - proto.Prop.ExtraInfo = new() - { - RogueInfo = new() - { - RoomId = (uint)NextRoomID, - SiteId = (uint)NextSiteID, - } - }; - } - - if (IsChessRogue) - { - proto.Prop.ExtraInfo = new() - { - ChessRogueInfo = new() - { - EnterNextCell = !IsLastRoom, - } - }; - } - - if (CustomPropID != 0) - { - proto.Prop.PropId = (uint)CustomPropID; - } - - return proto; - } } -} + + public int NextRoomID { get; set; } + public int NextSiteID { get; set; } + public int ChestCanUseTimes { get; set; } + public int CustomPropID { get; set; } + + public bool IsChessRogue { get; set; } = false; + public bool IsLastRoom { get; set; } = false; + + public override SceneEntityInfo ToProto() + { + var proto = base.ToProto(); + + if (NextRoomID != 0 || NextSiteID != 0 || ChestCanUseTimes != 0) // do not set if all are 0 + proto.Prop.ExtraInfo = new PropExtraInfo + { + RogueInfo = new PropRogueInfo + { + RoomId = (uint)NextRoomID, + SiteId = (uint)NextSiteID + } + }; + + if (IsChessRogue) + proto.Prop.ExtraInfo = new PropExtraInfo + { + ChessRogueInfo = new PropChessRogueInfo + { + EnterNextCell = !IsLastRoom + } + }; + + if (CustomPropID != 0) proto.Prop.PropId = (uint)CustomPropID; + + return proto; + } +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Scene/RogueEntityLoader.cs b/GameServer/Game/Rogue/Scene/RogueEntityLoader.cs index 329a62c8..8d639efc 100644 --- a/GameServer/Game/Rogue/Scene/RogueEntityLoader.cs +++ b/GameServer/Game/Rogue/Scene/RogueEntityLoader.cs @@ -6,202 +6,174 @@ using EggLink.DanhengServer.Game.Rogue.Scene.Entity; using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; -namespace EggLink.DanhengServer.Game.Rogue.Scene +namespace EggLink.DanhengServer.Game.Rogue.Scene; + +public class RogueEntityLoader(SceneInstance scene, PlayerInstance player) : SceneEntityLoader(scene) { - public class RogueEntityLoader(SceneInstance scene, PlayerInstance player) : SceneEntityLoader(scene) + public List NextRoomIds = []; + public PlayerInstance Player = player; + public List RogueDoorPropIds = [1000, 1021, 1022, 1023]; + + public override async ValueTask LoadEntity() { - public PlayerInstance Player = player; - public List RogueDoorPropIds = [1000, 1021, 1022, 1023]; - public List NextRoomIds = []; + if (Scene.IsLoaded) return; - public override void LoadEntity() + var instance = Player.RogueManager?.GetRogueInstance(); + if (instance is RogueInstance rogue) { - if (Scene.IsLoaded) return; + var excel = rogue.CurRoom?.Excel; + if (excel == null) return; - var instance = Player.RogueManager?.GetRogueInstance(); - if (instance is RogueInstance rogue) + foreach (var group in excel.GroupWithContent) { - var excel = rogue.CurRoom?.Excel; - if (excel == null) return; - - foreach (var group in excel.GroupWithContent) - { - Scene.FloorInfo!.Groups.TryGetValue(group.Key, out var groupData); - if (groupData == null) continue; - LoadGroup(groupData); - } + Scene.FloorInfo!.Groups.TryGetValue(group.Key, out var groupData); + if (groupData == null) continue; + await LoadGroup(groupData); } - - Scene.IsLoaded = true; } - public override List? LoadGroup(GroupInfo info, bool forceLoad = false) + Scene.IsLoaded = true; + } + + public override async ValueTask?> LoadGroup(GroupInfo info, bool forceLoad = false) + { + var entityList = new List(); + foreach (var npc in info.NPCList) + try + { + if (await LoadNpc(npc, info) is EntityNpc entity) entityList.Add(entity); + } + catch + { + } + + foreach (var monster in info.MonsterList) + try + { + if (await LoadMonster(monster, info) is EntityMonster entity) entityList.Add(entity); + } + catch + { + } + + foreach (var prop in info.PropList) + try + { + if (await LoadProp(prop, info) is EntityProp entity) entityList.Add(entity); + } + catch + { + } + + return entityList; + } + + public override async ValueTask LoadNpc(NpcInfo info, GroupInfo group, bool sendPacket = false) + { + if (info.IsClientOnly || info.IsDelete) return null; + if (!GameData.NpcDataData.ContainsKey(info.NPCID)) return null; + + RogueNpc npc = new(Scene, group, info); + if (info.NPCID == 3013) { - var entityList = new List(); - foreach (var npc in info.NPCList) + // generate event + var instance = await Player.RogueManager!.GetRogueInstance()!.GenerateEvent(npc); + if (instance != null) { - try - { - if (LoadNpc(npc, info) is EntityNpc entity) - { - entityList.Add(entity); - } - } - catch { } + npc.RogueEvent = instance; + npc.RogueNpcId = instance.EventId; + npc.UniqueId = instance.EventUniqueId; } - foreach (var monster in info.MonsterList) - { - try - { - if (LoadMonster(monster, info) is EntityMonster entity) - { - entityList.Add(entity); - } - } - catch { } - } - - foreach (var prop in info.PropList) - { - try - { - if (LoadProp(prop, info) is EntityProp entity) - { - entityList.Add(entity); - } - } - catch { } - } - - return entityList; + ; } - public override EntityNpc? LoadNpc(NpcInfo info, GroupInfo group, bool sendPacket = false) + await Scene.AddEntity(npc, sendPacket); + + return npc; + } + + public override async ValueTask LoadMonster(MonsterInfo info, GroupInfo group, + bool sendPacket = false) + { + if (info.IsClientOnly || info.IsDelete) return null; + var instance = Player.RogueManager?.GetRogueInstance(); + if (instance is RogueInstance rogueInstance) { - if (info.IsClientOnly || info.IsDelete) - { - return null; - } - if (!GameData.NpcDataData.ContainsKey(info.NPCID)) - { - return null; - } + var room = rogueInstance.CurRoom; + if (room == null) return null; - bool hasDuplicateNpcId = false; - foreach (IGameEntity entity in Scene.Entities.Values) - { - if (entity is EntityNpc eNpc && eNpc.NpcId == info.NPCID) - { - hasDuplicateNpcId = true; - break; - } - } - if (hasDuplicateNpcId) - { - return null; - } + var content = room.Excel?.GroupWithContent[group.Id]; + if (content == null) return null; - RogueNpc npc = new(Scene, group, info); - if (info.NPCID == 3013) - { - // generate event - var instance = Player.RogueManager?.GetRogueInstance()?.GenerateEvent(npc); - if (instance != null) - { - npc.RogueEvent = instance; - npc.RogueNpcId = instance.EventId; - npc.UniqueId = instance.EventUniqueId; - } - } - Scene.AddEntity(npc, sendPacket); + GameData.RogueMonsterData.TryGetValue((int)(content * 10 + 1), out var rogueMonster); + if (rogueMonster == null) return null; - return npc; - } + GameData.NpcMonsterDataData.TryGetValue(rogueMonster.NpcMonsterID, out var excel); + if (excel == null) return null; - public override EntityMonster? LoadMonster(MonsterInfo info, GroupInfo group, bool sendPacket = false) - { - if (info.IsClientOnly || info.IsDelete) - { - return null; - } - var instance = Player.RogueManager?.GetRogueInstance(); - if (instance is RogueInstance rogueInstance) - { - var room = rogueInstance.CurRoom; - if (room == null) return null; - - var content = room.Excel?.GroupWithContent[group.Id]; - if (content == null) return null; - - GameData.RogueMonsterData.TryGetValue((int)((content * 10) + 1), out var rogueMonster); - if (rogueMonster == null) return null; - - GameData.NpcMonsterDataData.TryGetValue(rogueMonster.NpcMonsterID, out var excel); - if (excel == null) return null; - - EntityMonster entity = new(Scene, info.ToPositionProto(), info.ToRotationProto(), group.Id, info.ID, excel, info) + EntityMonster entity = + new(Scene, info.ToPositionProto(), info.ToRotationProto(), group.Id, info.ID, excel, info) { EventID = rogueMonster.EventID, CustomStageID = rogueMonster.EventID }; - Scene.AddEntity(entity, sendPacket); + await Scene.AddEntity(entity, sendPacket); - return entity; - } - return null; + return entity; } - public override EntityProp? LoadProp(PropInfo info, GroupInfo group, bool sendPacket = false) - { - var room = Player.RogueManager?.RogueInstance?.CurRoom; - if (room == null) return null; - var excel = room.Excel; - if (excel == null) return null; - - GameData.MazePropData.TryGetValue(info.PropID, out var propExcel); - if (propExcel == null) - { - return null; - } - - var prop = new RogueProp(Scene, propExcel, group, info); - - if (RogueDoorPropIds.Contains(prop.PropInfo.PropID)) - { - int index = NextRoomIds.Count; - var nextSiteIds = room.NextSiteIds; - if (nextSiteIds.Count == 0) - { - // exit - prop.CustomPropID = 1000; - } else - { - index = Math.Min(index, nextSiteIds.Count - 1); // Sanity check - var nextRoom = Player.RogueManager?.RogueInstance?.RogueRooms[nextSiteIds[index]]; - prop.NextSiteID = nextSiteIds[index]; - prop.NextRoomID = nextRoom!.Excel?.RogueRoomID ?? 0; - NextRoomIds.Add(prop.NextRoomID); - - prop.CustomPropID = nextRoom!.Excel!.RogueRoomType switch // door style - { - 3 => 1022, - 8 => 1022, - 5 => 1023, - _ => 1021 - }; - } - - prop.SetState(PropStateEnum.Open); - } else - { - prop.SetState(info.State); - } - - Scene.AddEntity(prop, sendPacket); - - return null; - } + return null; } -} + + public override async ValueTask LoadProp(PropInfo info, GroupInfo group, bool sendPacket = false) + { + var room = Player.RogueManager?.RogueInstance?.CurRoom; + if (room == null) return null; + var excel = room.Excel; + if (excel == null) return null; + + GameData.MazePropData.TryGetValue(info.PropID, out var propExcel); + if (propExcel == null) return null; + + var prop = new RogueProp(Scene, propExcel, group, info); + + if (RogueDoorPropIds.Contains(prop.PropInfo.PropID)) + { + var index = NextRoomIds.Count; + var nextSiteIds = room.NextSiteIds; + if (nextSiteIds.Count == 0) + { + // exit + prop.CustomPropID = 1000; + } + else + { + index = Math.Min(index, nextSiteIds.Count - 1); // Sanity check + var nextRoom = Player.RogueManager?.RogueInstance?.RogueRooms[nextSiteIds[index]]; + prop.NextSiteID = nextSiteIds[index]; + prop.NextRoomID = nextRoom!.Excel?.RogueRoomID ?? 0; + NextRoomIds.Add(prop.NextRoomID); + + prop.CustomPropID = nextRoom!.Excel!.RogueRoomType switch // door style + { + 3 => 1022, + 8 => 1022, + 5 => 1023, + _ => 1021 + }; + } + + await prop.SetState(PropStateEnum.Open); + } + else + { + await prop.SetState(info.State); + } + + await Scene.AddEntity(prop, sendPacket); + + return prop; + } +} \ No newline at end of file diff --git a/GameServer/Game/Rogue/Scene/RogueRoomInstance.cs b/GameServer/Game/Rogue/Scene/RogueRoomInstance.cs index 993bc73f..0eda0881 100644 --- a/GameServer/Game/Rogue/Scene/RogueRoomInstance.cs +++ b/GameServer/Game/Rogue/Scene/RogueRoomInstance.cs @@ -3,34 +3,33 @@ using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Rogue.Scene +namespace EggLink.DanhengServer.Game.Rogue.Scene; + +public class RogueRoomInstance { - public class RogueRoomInstance + public RogueRoomInstance(RogueMapExcel excel) { - public int RoomId { get; set; } - public int SiteId { get; set; } - public RogueRoomStatus Status { get; set; } = RogueRoomStatus.Lock; - public List NextSiteIds { get; set; } = []; - public RogueRoomExcel Excel { get; set; } + SiteId = excel.SiteID; + NextSiteIds = excel.NextSiteIDList; - public RogueRoomInstance(RogueMapExcel excel) - { - SiteId = excel.SiteID; - NextSiteIds = excel.NextSiteIDList; + GameData.RogueMapGenData.TryGetValue(excel.SiteID, out var genData); + if (genData != null) RoomId = genData.RandomElement(); + Excel = GameData.RogueRoomData[RoomId]; + } - GameData.RogueMapGenData.TryGetValue(excel.SiteID, out var genData); - if (genData != null) - { - RoomId = genData.RandomElement(); - } - Excel = GameData.RogueRoomData[RoomId]; - } + public int RoomId { get; set; } + public int SiteId { get; set; } + public RogueRoomStatus Status { get; set; } = RogueRoomStatus.Lock; + public List NextSiteIds { get; set; } = []; + public RogueRoomExcel Excel { get; set; } - public RogueRoom ToProto() => new() + public RogueRoom ToProto() + { + return new RogueRoom { RoomId = (uint)RoomId, SiteId = (uint)SiteId, CurStatus = Status }; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Scene/Entity/EntityMonster.cs b/GameServer/Game/Scene/Entity/EntityMonster.cs index e30d83a6..c5521fcc 100644 --- a/GameServer/Game/Scene/Entity/EntityMonster.cs +++ b/GameServer/Game/Scene/Entity/EntityMonster.cs @@ -7,105 +7,101 @@ using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Scene.Entity +namespace EggLink.DanhengServer.Game.Scene.Entity; + +public class EntityMonster( + SceneInstance scene, + Position pos, + Position rot, + int GroupID, + int InstID, + NPCMonsterDataExcel excel, + MonsterInfo info) : IGameEntity { - public class EntityMonster(SceneInstance scene, Position pos, Position rot, int GroupID, int InstID, NPCMonsterDataExcel excel, MonsterInfo info) : IGameEntity + public Position Position { get; set; } = pos; + public Position Rotation { get; set; } = rot; + public int InstID { get; set; } = InstID; + public SceneInstance Scene { get; set; } = scene; + public NPCMonsterDataExcel MonsterData { get; set; } = excel; + public MonsterInfo Info { get; set; } = info; + public List BuffList { get; set; } = []; + public SceneBuff? TempBuff { get; set; } + public bool IsAlive { get; private set; } = true; + + public int EventID { get; set; } = info.EventID; + public int CustomStageID { get; set; } = 0; + public int EntityID { get; set; } = 0; + public int GroupID { get; set; } = GroupID; + + public async ValueTask AddBuff(SceneBuff buff) { - public int EntityID { get; set; } = 0; - public int GroupID { get; set; } = GroupID; - public Position Position { get; set; } = pos; - public Position Rotation { get; set; } = rot; - public int InstID { get; set; } = InstID; - public SceneInstance Scene { get; set; } = scene; - public NPCMonsterDataExcel MonsterData { get; set; } = excel; - public MonsterInfo Info { get; set; } = info; - public List BuffList { get; set; } = []; - public SceneBuff? TempBuff { get; set; } - public bool IsAlive { get; private set; } = true; - - public int EventID { get; set; } = info.EventID; - public int CustomStageID { get; set; } = 0; - - public void AddBuff(SceneBuff buff) - { - BuffList.Add(buff); - Scene.Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, buff)); - } - - public void ApplyBuff(BattleInstance instance) - { - if (TempBuff != null) - { - instance.Buffs.Add(new MazeBuff(TempBuff)); - TempBuff = null; - } - foreach (var buff in BuffList) - { - if (buff.IsExpired()) - { - continue; - } - instance.Buffs.Add(new MazeBuff(buff)); - } - Scene.Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, BuffList)); - - BuffList.Clear(); - } - - public int GetStageId() - { - if (CustomStageID > 0) - { - return CustomStageID; - } - var id = Info.EventID * 10 + Scene.Player.Data.WorldLevel; - if (GameData.StageConfigData.ContainsKey(id)) - return id; - else - return Info.EventID; - } - - public List Kill(bool sendPacket = true) - { - Scene.RemoveEntity(this); - IsAlive = false; - - GameData.MonsterDropData.TryGetValue(MonsterData.ID * 10 + Scene.Player.Data.WorldLevel, out var dropData); - if (dropData == null) return []; - var dropItems = dropData.CalculateDrop(); - Scene.Player.InventoryManager!.AddItems(dropItems, sendPacket); - - // TODO: Rogue support - // call mission handler - Scene.Player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.KillMonster, this); - return dropItems; - } - - public SceneEntityInfo ToProto() - { - return new() - { - EntityId = (uint)EntityID, - GroupId = (uint)GroupID, - InstId = (uint)InstID, - Motion = new() - { - Pos = Position.ToProto(), - Rot = Rotation.ToProto() - }, - NpcMonster = new() - { - EventId = (uint)EventID, - MonsterId = (uint)MonsterData.ID, - WorldLevel = (uint)Scene.Player.Data.WorldLevel, - } - }; - } + BuffList.Add(buff); + await Scene.Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, buff)); } -} + + public async ValueTask ApplyBuff(BattleInstance instance) + { + if (TempBuff != null) + { + instance.Buffs.Add(new MazeBuff(TempBuff)); + TempBuff = null; + } + + foreach (var buff in BuffList) + { + if (buff.IsExpired()) continue; + instance.Buffs.Add(new MazeBuff(buff)); + } + + await Scene.Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, BuffList)); + + BuffList.Clear(); + } + + public SceneEntityInfo ToProto() + { + return new SceneEntityInfo + { + EntityId = (uint)EntityID, + GroupId = (uint)GroupID, + InstId = (uint)InstID, + Motion = new MotionInfo + { + Pos = Position.ToProto(), + Rot = Rotation.ToProto() + }, + NpcMonster = new SceneNpcMonsterInfo + { + EventId = (uint)EventID, + MonsterId = (uint)MonsterData.ID, + WorldLevel = (uint)Scene.Player.Data.WorldLevel + } + }; + } + + public int GetStageId() + { + if (CustomStageID > 0) return CustomStageID; + var id = Info.EventID * 10 + Scene.Player.Data.WorldLevel; + if (GameData.StageConfigData.ContainsKey(id)) + return id; + return Info.EventID; + } + + public async ValueTask> Kill(bool sendPacket = true) + { + await Scene.RemoveEntity(this); + IsAlive = false; + + GameData.MonsterDropData.TryGetValue(MonsterData.ID * 10 + Scene.Player.Data.WorldLevel, out var dropData); + if (dropData == null) return []; + var dropItems = dropData.CalculateDrop(); + await Scene.Player.InventoryManager!.AddItems(dropItems, sendPacket); + + // TODO: Rogue support + // call mission handler + await Scene.Player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.KillMonster, this); + return dropItems; + } +} \ No newline at end of file diff --git a/GameServer/Game/Scene/Entity/EntityNpc.cs b/GameServer/Game/Scene/Entity/EntityNpc.cs index ed3d8097..3a10ba5a 100644 --- a/GameServer/Game/Scene/Entity/EntityNpc.cs +++ b/GameServer/Game/Scene/Entity/EntityNpc.cs @@ -2,52 +2,47 @@ using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Scene.Entity +namespace EggLink.DanhengServer.Game.Scene.Entity; + +public class EntityNpc(SceneInstance scene, GroupInfo group, NpcInfo npcInfo) : IGameEntity { - public class EntityNpc(SceneInstance scene, GroupInfo group, NpcInfo npcInfo) : IGameEntity + public SceneInstance Scene { get; set; } = scene; + public Position Position { get; set; } = npcInfo.ToPositionProto(); + public Position Rotation { get; set; } = npcInfo.ToRotationProto(); + public int NpcId { get; set; } = npcInfo.NPCID; + public int InstId { get; set; } = npcInfo.ID; + public int EntityID { get; set; } + public int GroupID { get; set; } = group.Id; + + public async ValueTask AddBuff(SceneBuff buff) { - public SceneInstance Scene { get; set; } = scene; - public int EntityID { get; set; } - public int GroupID { get; set; } = group.Id; - public Position Position { get; set; } = npcInfo.ToPositionProto(); - public Position Rotation { get; set; } = npcInfo.ToRotationProto(); - public int NpcId { get; set; } = npcInfo.NPCID; - public int InstId { get; set; } = npcInfo.ID; - - public void AddBuff(SceneBuff buff) - { - } - - public void ApplyBuff(BattleInstance instance) - { - } - - public virtual SceneEntityInfo ToProto() - { - SceneNpcInfo npc = new() - { - NpcId = (uint)NpcId, - }; - - return new SceneEntityInfo() - { - EntityId = (uint)EntityID, - GroupId = (uint)GroupID, - Motion = new MotionInfo() - { - Pos = Position.ToProto(), - Rot = Rotation.ToProto(), - }, - InstId = (uint)InstId, - Npc = npc, - }; - } + await System.Threading.Tasks.Task.CompletedTask; } -} + + public async ValueTask ApplyBuff(BattleInstance instance) + { + await System.Threading.Tasks.Task.CompletedTask; + } + + public virtual SceneEntityInfo ToProto() + { + SceneNpcInfo npc = new() + { + NpcId = (uint)NpcId + }; + + return new SceneEntityInfo + { + EntityId = (uint)EntityID, + GroupId = (uint)GroupID, + Motion = new MotionInfo + { + Pos = Position.ToProto(), + Rot = Rotation.ToProto() + }, + InstId = (uint)InstId, + Npc = npc + }; + } +} \ No newline at end of file diff --git a/GameServer/Game/Scene/Entity/EntityProp.cs b/GameServer/Game/Scene/Entity/EntityProp.cs index 0a4bb691..a6de3a5d 100644 --- a/GameServer/Game/Scene/Entity/EntityProp.cs +++ b/GameServer/Game/Scene/Entity/EntityProp.cs @@ -6,72 +6,67 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Scene.Entity +namespace EggLink.DanhengServer.Game.Scene.Entity; + +public class EntityProp(SceneInstance scene, MazePropExcel excel, GroupInfo group, PropInfo prop) : IGameEntity { - public class EntityProp(SceneInstance scene, MazePropExcel excel, GroupInfo group, PropInfo prop) : IGameEntity + public Position Position { get; set; } = prop.ToPositionProto(); + public Position Rotation { get; set; } = prop.ToRotationProto(); + public SceneInstance Scene { get; set; } = scene; + public PropStateEnum State { get; set; } = PropStateEnum.Closed; + public int InstId { get; set; } = prop.ID; + public MazePropExcel Excel { get; set; } = excel; + public PropInfo PropInfo { get; set; } = prop; + public GroupInfo Group { get; set; } = group; + public int EntityID { get; set; } + public int GroupID { get; set; } = group.Id; + + public async ValueTask AddBuff(SceneBuff buff) { - public int EntityID { get; set; } - public int GroupID { get; set; } = group.Id; - public Position Position { get; set; } = prop.ToPositionProto(); - public Position Rotation { get; set; } = prop.ToRotationProto(); - public SceneInstance Scene { get; set; } = scene; - public PropStateEnum State { get; set; } = PropStateEnum.Closed; - public int InstId { get; set; } = prop.ID; - public MazePropExcel Excel { get; set; } = excel; - public PropInfo PropInfo { get; set; } = prop; - public GroupInfo Group { get; set; } = group; - - public void AddBuff(SceneBuff buff) - { - } - - public void ApplyBuff(BattleInstance instance) - { - } - - public void SetState(PropStateEnum state) - { - if (state == State) return; - SetState(state, Scene.IsLoaded); - } - - public void SetState(PropStateEnum state, bool sendPacket) - { - //if (State == PropStateEnum.Open) return; // already open DO NOT CLOSE AGAIN - State = state; - if (sendPacket) - { - Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(this)); - } - - // save - if (Group.SaveType == SaveTypeEnum.Reset) - { - return; - } - Scene.Player.SetScenePropData(Scene.FloorId, Group.Id, PropInfo.ID, state); - } - - public virtual SceneEntityInfo ToProto() - { - var prop = new ScenePropInfo() - { - PropId = (uint)Excel.ID, - PropState = (uint)State, - }; - - return new SceneEntityInfo() - { - EntityId = (uint)EntityID, - GroupId = (uint)GroupID, - Motion = new MotionInfo() - { - Pos = Position.ToProto(), - Rot = Rotation.ToProto(), - }, - InstId = (uint)InstId, - Prop = prop, - }; - } + await System.Threading.Tasks.Task.CompletedTask; } -} + + public async ValueTask ApplyBuff(BattleInstance instance) + { + await System.Threading.Tasks.Task.CompletedTask; + } + + public virtual SceneEntityInfo ToProto() + { + var prop = new ScenePropInfo + { + PropId = (uint)Excel.ID, + PropState = (uint)State + }; + + return new SceneEntityInfo + { + EntityId = (uint)EntityID, + GroupId = (uint)GroupID, + Motion = new MotionInfo + { + Pos = Position.ToProto(), + Rot = Rotation.ToProto() + }, + InstId = (uint)InstId, + Prop = prop + }; + } + + public async ValueTask SetState(PropStateEnum state) + { + if (state == State) return; + await SetState(state, Scene.IsLoaded); + } + + public async ValueTask SetState(PropStateEnum state, bool sendPacket) + { + //if (State == PropStateEnum.Open) return; // already open DO NOT CLOSE AGAIN + State = state; + if (sendPacket) await Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(this)); + + // save + if (Group.SaveType == SaveTypeEnum.Reset) return; + Scene.Player.SetScenePropData(Scene.FloorId, Group.Id, PropInfo.ID, state); + } +} \ No newline at end of file diff --git a/GameServer/Game/Scene/Entity/IGameEntity.cs b/GameServer/Game/Scene/Entity/IGameEntity.cs index 3b9d61f9..2b68b750 100644 --- a/GameServer/Game/Scene/Entity/IGameEntity.cs +++ b/GameServer/Game/Scene/Entity/IGameEntity.cs @@ -1,23 +1,16 @@ using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Scene.Entity +namespace EggLink.DanhengServer.Game.Scene.Entity; + +public interface IGameEntity { - public interface IGameEntity - { - public int EntityID { get; set; } - public int GroupID { get; set; } + public int EntityID { get; set; } + public int GroupID { get; set; } - public void AddBuff(SceneBuff buff); - public void ApplyBuff(BattleInstance instance); + public ValueTask AddBuff(SceneBuff buff); + public ValueTask ApplyBuff(BattleInstance instance); - public SceneEntityInfo ToProto(); - } -} + public SceneEntityInfo ToProto(); +} \ No newline at end of file diff --git a/GameServer/Game/Scene/SceneBuff.cs b/GameServer/Game/Scene/SceneBuff.cs index 1f178b83..d372b1b9 100644 --- a/GameServer/Game/Scene/SceneBuff.cs +++ b/GameServer/Game/Scene/SceneBuff.cs @@ -1,41 +1,36 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Scene +namespace EggLink.DanhengServer.Game.Scene; + +public class SceneBuff(int buffID, int buffLevel, int owner, int duration = -1) { - public class SceneBuff(int buffID, int buffLevel, int owner, int duration = -1) + public Dictionary DynamicValues = []; + public int BuffID { get; } = buffID; + public int BuffLevel { get; } = buffLevel; + public int OwnerAvatarId { get; } = owner; + + public int Duration { get; set; } = duration; + public long CreatedTime { get; set; } = Extensions.GetUnixMs(); + + public bool IsExpired() { - public int BuffID { get; private set; } = buffID; - public int BuffLevel { get; private set; } = buffLevel; - public int OwnerAvatarId { get; private set; } = owner; - - public int Duration { get; set; } = duration; - public long CreatedTime { get; set; } = Extensions.GetUnixMs(); - public Dictionary DynamicValues = []; - - public bool IsExpired() - { - if (Duration < 0) - return false; // Permanent buff - return Extensions.GetUnixMs() - CreatedTime >= Duration; - } - - public BuffInfo ToProto() { - var buffInfo = new BuffInfo() - { - BuffId = (uint)BuffID, - Level = (uint)BuffLevel, - BaseAvatarId = (uint)OwnerAvatarId, - AddTimeMs = (ulong)CreatedTime, - LifeTime = (ulong)Duration, - }; - - return buffInfo; - } + if (Duration < 0) + return false; // Permanent buff + return Extensions.GetUnixMs() - CreatedTime >= Duration; } -} + + public BuffInfo ToProto() + { + var buffInfo = new BuffInfo + { + BuffId = (uint)BuffID, + Level = (uint)BuffLevel, + BaseAvatarId = (uint)OwnerAvatarId, + AddTimeMs = (ulong)CreatedTime, + LifeTime = (ulong)Duration + }; + + return buffInfo; + } +} \ No newline at end of file diff --git a/GameServer/Game/Scene/SceneEntityLoader.cs b/GameServer/Game/Scene/SceneEntityLoader.cs index ad6f12cf..a06e5877 100644 --- a/GameServer/Game/Scene/SceneEntityLoader.cs +++ b/GameServer/Game/Scene/SceneEntityLoader.cs @@ -1,344 +1,280 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Data.Config; -using EggLink.DanhengServer.Data.Excel; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Server.Packet.Send.Scene; -using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Game.Scene +namespace EggLink.DanhengServer.Game.Scene; + +public class SceneEntityLoader(SceneInstance scene) { - public class SceneEntityLoader(SceneInstance scene) + public SceneInstance Scene { get; set; } = scene; + + public virtual async ValueTask LoadEntity() { - public SceneInstance Scene { get; set; } = scene; + if (Scene.IsLoaded) return; - public virtual void LoadEntity() + foreach (var group in Scene?.FloorInfo?.Groups.Values!) // Sanity check in SceneInstance { - if (Scene.IsLoaded) return; - - foreach (var group in Scene?.FloorInfo?.Groups.Values!) // Sanity check in SceneInstance - { - if (group.LoadSide == GroupLoadSideEnum.Client) - { - continue; - } - if (group.GroupName.Contains("TrainVisitor")) - { - continue; - } - LoadGroup(group); - } - Scene.IsLoaded = true; + if (group.LoadSide == GroupLoadSideEnum.Client) continue; + if (group.GroupName.Contains("TrainVisitor")) continue; + await LoadGroup(group); } - public virtual void SyncEntity() + Scene.IsLoaded = true; + } + + public virtual async ValueTask SyncEntity() + { + if (Scene.Excel.PlaneType == PlaneTypeEnum.Raid) return; + + var refreshed = false; + var oldGroupId = new List(); + foreach (var entity in Scene.Entities.Values) + if (!oldGroupId.Contains(entity.GroupID)) + oldGroupId.Add(entity.GroupID); + + var removeList = new List(); + var addList = new List(); + + foreach (var group in Scene.FloorInfo!.Groups.Values) { - if (Scene.Excel.PlaneType == PlaneTypeEnum.Raid) return; + if (group.LoadSide == GroupLoadSideEnum.Client) continue; - bool refreshed = false; - var oldGroupId = new List(); - foreach (var entity in Scene.Entities.Values) + if (group.GroupName.Contains("TrainVisitor")) continue; + + if (oldGroupId.Contains(group.Id)) // check if it should be unloaded { - if (!oldGroupId.Contains(entity.GroupID)) - oldGroupId.Add(entity.GroupID); - } - - var removeList = new List(); - var addList = new List(); - - foreach (var group in Scene.FloorInfo!.Groups.Values) - { - if (group.LoadSide == GroupLoadSideEnum.Client) + if (group.ForceUnloadCondition.IsTrue(Scene.Player.MissionManager!.Data, false) || + group.UnloadCondition.IsTrue(Scene.Player.MissionManager!.Data, false)) { - continue; - } - - if (group.GroupName.Contains("TrainVisitor")) - { - continue; - } - - if (oldGroupId.Contains(group.Id)) // check if it should be unloaded - { - if (group.ForceUnloadCondition.IsTrue(Scene.Player.MissionManager!.Data, false) || group.UnloadCondition.IsTrue(Scene.Player.MissionManager!.Data, false)) - { - foreach (var entity in Scene.Entities.Values) + foreach (var entity in Scene.Entities.Values) + if (entity.GroupID == group.Id) { - if (entity.GroupID == group.Id) - { - Scene.RemoveEntity(entity, false); - removeList.Add(entity); - refreshed = true; - } + await Scene.RemoveEntity(entity, false); + removeList.Add(entity); + refreshed = true; } - Scene.Groups.Remove(group.Id); - } - else if (group.OwnerMainMissionID != 0 && Scene.Player.MissionManager!.GetMainMissionStatus(group.OwnerMainMissionID) != Enums.MissionPhaseEnum.Accept) - { - foreach (var entity in Scene.Entities.Values) + + Scene.Groups.Remove(group.Id); + } + else if (group.OwnerMainMissionID != 0 && + Scene.Player.MissionManager!.GetMainMissionStatus(group.OwnerMainMissionID) != + MissionPhaseEnum.Accept) + { + foreach (var entity in Scene.Entities.Values) + if (entity.GroupID == group.Id) { - if (entity.GroupID == group.Id) - { - Scene.RemoveEntity(entity, false); - removeList.Add(entity); - refreshed = true; - } + await Scene.RemoveEntity(entity, false); + removeList.Add(entity); + refreshed = true; } - Scene.Groups.Remove(group.Id); - } - } else // check if it should be loaded - { - var groupList = LoadGroup(group); - refreshed = groupList != null || refreshed; - addList.AddRange(groupList ?? []); + + Scene.Groups.Remove(group.Id); } } - if (refreshed && (addList.Count > 0 || removeList.Count > 0)) + else // check if it should be loaded { - Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(addList, removeList)); + var groupList = await LoadGroup(group); + refreshed = groupList != null || refreshed; + addList.AddRange(groupList ?? []); } } - public virtual List? LoadGroup(GroupInfo info, bool forceLoad = false) + if (refreshed && (addList.Count > 0 || removeList.Count > 0)) + await Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(addList, removeList)); + } + + public virtual async ValueTask?> LoadGroup(GroupInfo info, bool forceLoad = false) + { + var missionData = Scene.Player.MissionManager!.Data; + if (info.LoadSide == GroupLoadSideEnum.Client) return null; + + if (info.GroupName.Contains("TrainVisitor")) return null; + + if (Scene.Excel.PlaneType != PlaneTypeEnum.Raid) { - var missionData = Scene.Player.MissionManager!.Data; - if (info.LoadSide == GroupLoadSideEnum.Client) - { - return null; - } + if (!(info.OwnerMainMissionID == 0 || + Scene.Player.MissionManager!.GetMainMissionStatus(info.OwnerMainMissionID) == + MissionPhaseEnum.Accept)) return null; - if (info.GroupName.Contains("TrainVisitor")) - { - return null; - } - - if (Scene.Excel.PlaneType != PlaneTypeEnum.Raid) - { - if (!(info.OwnerMainMissionID == 0 || Scene.Player.MissionManager!.GetMainMissionStatus(info.OwnerMainMissionID) == Enums.MissionPhaseEnum.Accept)) - { - return null; - } - - if ((!info.LoadCondition.IsTrue(missionData) || info.UnloadCondition.IsTrue(missionData, false) || info.ForceUnloadCondition.IsTrue(missionData, false)) && !forceLoad) - { - return null; - } - } - - if (Scene.Entities.Values.ToList().FindIndex(x => x.GroupID == info.Id) != -1) // check if group is already loaded - { - return null; - } - - // load - Scene.Groups.Add(info.Id); - - var entityList = new List(); - foreach (var npc in info.NPCList) - { - try - { - if (LoadNpc(npc, info) is EntityNpc entity) - { - entityList.Add(entity); - } - } catch{ } - } - - foreach (var monster in info.MonsterList) - { - try - { - if (LoadMonster(monster, info) is EntityMonster entity) - { - entityList.Add(entity); - } - } - catch { } - } - - foreach (var prop in info.PropList) - { - try - { - if (LoadProp(prop, info) is EntityProp entity) - { - entityList.Add(entity); - } - } catch { } - } - - return entityList; + if ((!info.LoadCondition.IsTrue(missionData) || info.UnloadCondition.IsTrue(missionData, false) || + info.ForceUnloadCondition.IsTrue(missionData, false)) && !forceLoad) return null; } - public virtual List? LoadGroup(int groupId, bool sendPacket = true) - { - var group = Scene.FloorInfo?.Groups.TryGetValue(groupId, out GroupInfo? v1) == true ? v1 : null; - if (group == null) { return null; } - var entities = LoadGroup(group, true); + if (Scene.Entities.Values.ToList().FindIndex(x => x.GroupID == info.Id) != + -1) // check if group is already loaded + return null; - if (sendPacket && entities != null && entities.Count > 0) + // load + Scene.Groups.Add(info.Id); + + var entityList = new List(); + foreach (var npc in info.NPCList) + try + { + if (await LoadNpc(npc, info) is EntityNpc entity) entityList.Add(entity); + } + catch { - Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(addEntity: entities)); } - return entities; + foreach (var monster in info.MonsterList) + try + { + if (await LoadMonster(monster, info) is EntityMonster entity) entityList.Add(entity); + } + catch + { + } + + foreach (var prop in info.PropList) + try + { + if (await LoadProp(prop, info) is EntityProp entity) entityList.Add(entity); + } + catch + { + } + + return entityList; + } + + public virtual async ValueTask?> LoadGroup(int groupId, bool sendPacket = true) + { + var group = Scene.FloorInfo?.Groups.TryGetValue(groupId, out var v1) == true ? v1 : null; + if (group == null) return null; + var entities = await LoadGroup(group, true); + + if (sendPacket && entities != null && entities.Count > 0) + await Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(entities)); + + return entities; + } + + public virtual async ValueTask UnloadGroup(int groupId) + { + var group = Scene.FloorInfo?.Groups.TryGetValue(groupId, out var v1) == true ? v1 : null; + if (group == null) return; + + var removeList = new List(); + var refreshed = false; + + foreach (var entity in Scene.Entities.Values) + if (entity.GroupID == group.Id) + { + await Scene.RemoveEntity(entity, false); + removeList.Add(entity); + refreshed = true; + } + + Scene.Groups.Remove(group.Id); + + if (refreshed) await Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(removeEntity: removeList)); + } + + public virtual async ValueTask LoadNpc(NpcInfo info, GroupInfo group, bool sendPacket = false) + { + if (info.IsClientOnly || info.IsDelete) return null; + + if (group.Id == 117) GameData.GetAvatarExpRequired(0, 0); + + if (!GameData.NpcDataData.ContainsKey(info.NPCID)) return null; + + var hasDuplicateNpcId = false; + foreach (var entity in Scene.Entities.Values) + if (entity is EntityNpc eNpc && eNpc.NpcId == info.NPCID) + { + hasDuplicateNpcId = true; + break; + } + + if (hasDuplicateNpcId) + { + //return null; } - public virtual void UnloadGroup(int groupId) + EntityNpc npc = new(Scene, group, info); + await Scene.AddEntity(npc, sendPacket); + + return npc; + } + + public virtual async ValueTask LoadMonster(MonsterInfo info, GroupInfo group, + bool sendPacket = false) + { + if (info.IsClientOnly || info.IsDelete) return null; + + GameData.NpcMonsterDataData.TryGetValue(info.NPCMonsterID, out var excel); + if (excel == null) return null; + + EntityMonster entity = new(Scene, info.ToPositionProto(), info.ToRotationProto(), group.Id, info.ID, excel, + info); + await Scene.AddEntity(entity, sendPacket); + return entity; + } + + public virtual async ValueTask LoadProp(PropInfo info, GroupInfo group, bool sendPacket = false) + { + if (info.IsClientOnly || info.IsDelete) return null; + + GameData.MazePropData.TryGetValue(info.PropID, out var excel); + if (excel == null) return null; + + var prop = new EntityProp(Scene, excel, group, info); + + if (excel.PropType == PropTypeEnum.PROP_SPRING) { - var group = Scene.FloorInfo?.Groups.TryGetValue(groupId, out GroupInfo? v1) == true ? v1 : null; - if (group == null) return; - - var removeList = new List(); - bool refreshed = false; - - foreach (var entity in Scene.Entities.Values) - { - if (entity.GroupID == group.Id) - { - Scene.RemoveEntity(entity, false); - removeList.Add(entity); - refreshed = true; - } - } - Scene.Groups.Remove(group.Id); - - if (refreshed) - { - Scene.Player.SendPacket(new PacketSceneGroupRefreshScNotify(removeEntity:removeList)); - } + Scene.HealingSprings.Add(prop); + await prop.SetState(PropStateEnum.CheckPointEnable); } - public virtual EntityNpc? LoadNpc(NpcInfo info, GroupInfo group, bool sendPacket = false) + // load from database + var propData = Scene.Player.GetScenePropData(Scene.FloorId, group.Id, info.ID); + if (propData != null && Scene.Excel.PlaneType != PlaneTypeEnum.Raid) // raid is not saved { - if (info.IsClientOnly || info.IsDelete) - { - return null; - } - - if (group.Id == 117) - { - GameData.GetAvatarExpRequired(0, 0); - } - - if (!GameData.NpcDataData.ContainsKey(info.NPCID)) - { - return null; - } - - bool hasDuplicateNpcId = false; - foreach (IGameEntity entity in Scene.Entities.Values) - { - if (entity is EntityNpc eNpc && eNpc.NpcId == info.NPCID) - { - hasDuplicateNpcId = true; - break; - } - } - - if (hasDuplicateNpcId) - { - //return null; - } - - EntityNpc npc = new(Scene, group, info); - Scene.AddEntity(npc, sendPacket); - - return npc; + prop.State = propData.State; } - - public virtual EntityMonster? LoadMonster(MonsterInfo info, GroupInfo group, bool sendPacket = false) + else { - if (info.IsClientOnly || info.IsDelete) + if (Scene.Excel.PlaneType == PlaneTypeEnum.Raid) { - return null; + prop.State = info.State; } - - GameData.NpcMonsterDataData.TryGetValue(info.NPCMonsterID, out var excel); - if (excel == null) - { - return null; - } - - EntityMonster entity = new(Scene, info.ToPositionProto(), info.ToRotationProto(), group.Id, info.ID, excel, info); - Scene.AddEntity(entity, sendPacket); - return entity; - } - - public virtual EntityProp? LoadProp(PropInfo info, GroupInfo group, bool sendPacket = false) - { - if (info.IsClientOnly || info.IsDelete) - { - return null; - } - - GameData.MazePropData.TryGetValue(info.PropID, out var excel); - if (excel == null) - { - return null; - } - - var prop = new EntityProp(Scene, excel, group, info); - - if (excel.PropType == PropTypeEnum.PROP_SPRING) - { - Scene.HealingSprings.Add(prop); - prop.SetState(PropStateEnum.CheckPointEnable); - } - - // load from database - var propData = Scene.Player.GetScenePropData(Scene.FloorId, group.Id, info.ID); - if (propData != null && Scene.Excel.PlaneType != PlaneTypeEnum.Raid) // raid is not saved - { - prop.State = propData.State; - } else { - if (Scene.Excel.PlaneType == PlaneTypeEnum.Raid) - { - prop.State = info.State; - } + // elevator + if (prop.Excel.PropType == PropTypeEnum.PROP_ELEVATOR) + prop.State = PropStateEnum.Elevator1; else - { - // elevator - if (prop.Excel.PropType == PropTypeEnum.PROP_ELEVATOR) - { - prop.State = PropStateEnum.Elevator1; - } - else - { - prop.State = info.State; - } - } - } - - if (group.GroupName.Contains("Machine")) - { - prop.SetState(PropStateEnum.Open); - Scene.AddEntity(prop, sendPacket); - return prop; - } - - if (prop.PropInfo.Name.Contains("Case") && prop.PropInfo.State == PropStateEnum.Open) - { - prop.SetState(PropStateEnum.Closed); - } - - if (prop.PropInfo.PropID == 1003) - { - if (prop.PropInfo.MappingInfoID == 2220) - { - prop.SetState(PropStateEnum.Open); - Scene.AddEntity(prop, sendPacket); - } - } - else - { - Scene.AddEntity(prop, sendPacket); + prop.State = info.State; } + } + if (group.GroupName.Contains("Machine")) + { + await prop.SetState(PropStateEnum.Open); + await Scene.AddEntity(prop, sendPacket); return prop; } + + if (prop.PropInfo.Name.Contains("Case") && prop.PropInfo.State == PropStateEnum.Open) + await prop.SetState(PropStateEnum.Closed); + + if (prop.PropInfo.PropID == 1003) + { + if (prop.PropInfo.MappingInfoID == 2220) + { + await prop.SetState(PropStateEnum.Open); + await Scene.AddEntity(prop, sendPacket); + } + } + else + { + await Scene.AddEntity(prop, sendPacket); + } + + return prop; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Scene/SceneInstance.cs b/GameServer/Game/Scene/SceneInstance.cs index 759d775b..33458e86 100644 --- a/GameServer/Game/Scene/SceneInstance.cs +++ b/GameServer/Game/Scene/SceneInstance.cs @@ -1,8 +1,8 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Data.Excel; -using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Avatar; +using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Game.Challenge; using EggLink.DanhengServer.Game.ChessRogue.Cell; @@ -11,412 +11,368 @@ using EggLink.DanhengServer.Game.Rogue.Scene; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.GameServer.Game.Mission; using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Server.Packet; -using EggLink.DanhengServer.Server.Packet.Send.Lineup; using EggLink.DanhengServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Util; -using System.Numerics; -namespace EggLink.DanhengServer.Game.Scene +namespace EggLink.DanhengServer.Game.Scene; + +public class SceneInstance { - public class SceneInstance + #region Scene Details + + public EntityProp? GetNearestSpring(long minDistSq) { - #region Data + EntityProp? spring = null; + long springDist = 0; - public PlayerInstance Player; - public MazePlaneExcel Excel; - public FloorInfo? FloorInfo; - public int FloorId; - public int PlaneId; - public int EntryId; - - public int LeaveEntityId; - public int LastEntityId; - public bool IsLoaded = false; - - public Dictionary AvatarInfo = []; - public int LeaderEntityId; - public Dictionary Entities = []; - public List Groups = []; - public List HealingSprings = []; - - public SceneEntityLoader? EntityLoader; - - public int CustomGameModeId = 0; - - public SceneInstance(PlayerInstance player, MazePlaneExcel excel, int floorId, int entryId) + foreach (var prop in HealingSprings) { - Player = player; - Excel = excel; - PlaneId = excel.PlaneID; - FloorId = floorId; - EntryId = entryId; - LeaveEntityId = 0; + var dist = Player.Data?.Pos?.GetFast2dDist(prop.Position) ?? 1000000; + if (dist > minDistSq) continue; - SyncLineup(true, true); - - GameData.GetFloorInfo(PlaneId, FloorId, out FloorInfo); - if (FloorInfo == null) return; - - switch (Excel.PlaneType) + if (spring == null || dist < springDist) { - case Enums.Scene.PlaneTypeEnum.Rogue: - if (Player.ChessRogueManager!.RogueInstance != null) - { - EntityLoader = new ChessRogueEntityLoader(this); - CustomGameModeId = 16; // ChessRogue - } else - { - EntityLoader = new RogueEntityLoader(this, Player); - } - break; - case Enums.Scene.PlaneTypeEnum.Challenge: - EntityLoader = new ChallengeEntityLoader(this, Player); - break; - default: - if (Player.StoryLineManager?.StoryLineData.CurStoryLineId != 0) - { - EntityLoader = new StoryLineEntityLoader(this); - } - else - { - EntityLoader = new SceneEntityLoader(this); - } - break; - } - - EntityLoader.LoadEntity(); - - Player.TaskManager?.SceneTaskTrigger.TriggerFloor(PlaneId, FloorId); - } - - #endregion - - #region Scene Actions - - public void SyncLineup(bool notSendPacket = false, bool forceSetEntityId = false) - { - var oldAvatarInfo = AvatarInfo.Values.ToList(); - AvatarInfo.Clear(); - bool sendPacket = false; - var AddAvatar = new List(); - var RemoveAvatar = new List(); - foreach (var avatar in Player.LineupManager?.GetAvatarsFromCurTeam() ?? []) - { - if (avatar == null) continue; - avatar.AvatarInfo.PlayerData = Player.Data; - if (forceSetEntityId && avatar.AvatarInfo.EntityId != 0) - { - RemoveAvatar.Add(new AvatarSceneInfo(new() - { - EntityId = avatar.AvatarInfo.EntityId, - }, AvatarType.AvatarFormalType, Player)); - avatar.AvatarInfo.EntityId = 0; - sendPacket = true; - } - var avatarInstance = oldAvatarInfo.Find(x => x.AvatarInfo.AvatarId == avatar.AvatarInfo.AvatarId); - if (avatarInstance == null) - { - if (avatar.AvatarInfo.EntityId == 0) - { - avatar.AvatarInfo.EntityId = ++LastEntityId; - } - AddAvatar.Add(avatar); - AvatarInfo.Add(avatar.AvatarInfo.EntityId, avatar); - sendPacket = true; - } else - { - AvatarInfo.Add(avatarInstance.AvatarInfo.EntityId, avatarInstance); - } - }; - foreach (var avatar in oldAvatarInfo) - { - if (AvatarInfo.Values.ToList().FindIndex(x => x.AvatarInfo.AvatarId == avatar.AvatarInfo.AvatarId) == -1) - { - RemoveAvatar.Add(new AvatarSceneInfo(new() - { - EntityId = avatar.AvatarInfo.EntityId, - }, AvatarType.AvatarFormalType, Player)); - avatar.AvatarInfo.EntityId = 0; - sendPacket = true; - } - } - - var LeaderAvatarId = Player.LineupManager?.GetCurLineup()?.LeaderAvatarId; - var LeaderAvatarSlot = Player.LineupManager?.GetCurLineup()?.BaseAvatars?.FindIndex(x => x.BaseAvatarId == LeaderAvatarId); - if (LeaderAvatarSlot == -1) LeaderAvatarSlot = 0; - if (AvatarInfo.Count == 0) return; - var info = AvatarInfo.Values.ToList()[LeaderAvatarSlot ?? 0]; - LeaderEntityId = info.AvatarInfo.EntityId; - if (sendPacket && !notSendPacket) - { - Player.SendPacket(new PacketSceneGroupRefreshScNotify(AddAvatar, RemoveAvatar)); + spring = prop; + springDist = dist; } } - public void SyncGroupInfo() + return spring; + } + + #endregion + + #region Serialization + + public SceneInfo ToProto() + { + SceneInfo sceneInfo = new() { - EntityLoader?.SyncEntity(); - } + WorldId = (uint)Excel.WorldID, + GameModeType = (uint)(CustomGameModeId > 0 ? CustomGameModeId : (int)Excel.PlaneType), + PlaneId = (uint)PlaneId, + FloorId = (uint)FloorId, + EntryId = (uint)EntryId, + SceneMissionInfo = new MissionStatusBySceneInfo() + }; - #endregion - - #region Scene Details - - public EntityProp? GetNearestSpring(long minDistSq) + var playerGroupInfo = new SceneEntityGroupInfo(); // avatar group + foreach (var avatar in AvatarInfo) + playerGroupInfo.EntityList.Add(avatar.Value.AvatarInfo.ToSceneEntityInfo(avatar.Value.AvatarType)); + if (playerGroupInfo.EntityList.Count > 0) { - EntityProp? spring = null; - long springDist = 0; - - foreach (EntityProp prop in HealingSprings) + if (LeaderEntityId == 0) { - long dist = Player.Data?.Pos?.GetFast2dDist(prop.Position) ?? 1000000; - if (dist > minDistSq) continue; - - if (spring == null || dist < springDist) - { - spring = prop; - springDist = dist; - } + LeaderEntityId = AvatarInfo.Values.First().AvatarInfo.EntityId; + sceneInfo.LeaderEntityId = (uint)LeaderEntityId; } - - return spring; - } - - #endregion - - #region Entity Management - - public void AddEntity(IGameEntity entity) - { - AddEntity(entity, IsLoaded); - } - - public void AddEntity(IGameEntity entity, bool SendPacket) - { - if (entity == null || entity.EntityID != 0) return; - entity.EntityID = ++LastEntityId; - - Entities.Add(entity.EntityID, entity); - if (SendPacket) + else { - Player.SendPacket(new PacketSceneGroupRefreshScNotify(entity)); + sceneInfo.LeaderEntityId = (uint)LeaderEntityId; } } - public void RemoveEntity(IGameEntity monster) + sceneInfo.EntityGroupList.Add(playerGroupInfo); + + List groups = []; // other groups + + // add entities to groups + foreach (var entity in Entities) { - RemoveEntity(monster, IsLoaded); + if (entity.Value.GroupID == 0) continue; + if (groups.FindIndex(x => x.GroupId == entity.Value.GroupID) == -1) + groups.Add(new SceneEntityGroupInfo + { + GroupId = (uint)entity.Value.GroupID + }); + groups[groups.FindIndex(x => x.GroupId == entity.Value.GroupID)].EntityList.Add(entity.Value.ToProto()); } - public void RemoveEntity(IGameEntity monster, bool SendPacket) - { - Entities.Remove(monster.EntityID); + foreach (var groupId in Groups) // Add for empty group + if (groups.FindIndex(x => x.GroupId == groupId) == -1) + groups.Add(new SceneEntityGroupInfo + { + GroupId = (uint)groupId + }); - if (SendPacket) + foreach (var group in groups) sceneInfo.EntityGroupList.Add(group); + + // custom save data and floor saved data + Player.SceneData!.CustomSaveData.TryGetValue(EntryId, out var data); + + if (data != null) + foreach (var customData in data) + sceneInfo.SaveDataList.Add(new CustomSaveData + { + GroupId = (uint)customData.Key, + SaveData = customData.Value + }); + + Player.SceneData!.FloorSavedData.TryGetValue(FloorId, out var floorData); + + foreach (var value in FloorInfo?.SavedValues ?? []) + if (floorData != null && floorData.TryGetValue(value.Name, out var v)) + sceneInfo.FloorSavedData[value.Name] = v; + else + sceneInfo.FloorSavedData[value.Name] = value.DefaultValue; + + foreach (var value in FloorInfo?.CustomValues ?? []) + if (floorData != null && floorData.TryGetValue(value.Name, out var v)) { - Player.SendPacket(new PacketSceneGroupRefreshScNotify(null, monster)); + sceneInfo.FloorSavedData[value.Name] = v; } + else + { + _ = int.TryParse(value.DefaultValue, out var x); + sceneInfo.FloorSavedData[value.Name] = x; + } + + // mission + Player.MissionManager!.OnLoadScene(sceneInfo); + + // unlock section + if (!ConfigManager.Config.ServerOption.AutoLightSection) + { + Player.SceneData!.UnlockSectionIdList.TryGetValue(FloorId, out var unlockSectionList); + if (unlockSectionList != null) + foreach (var sectionId in unlockSectionList) + sceneInfo.LightenSectionList.Add((uint)sectionId); + } + else + { + for (uint i = 1; i <= 100; i++) sceneInfo.LightenSectionList.Add(i); } - public List GetEntitiesInGroup(int groupID) + return sceneInfo; + } + + #endregion + + #region Data + + public PlayerInstance Player; + public MazePlaneExcel Excel; + public FloorInfo? FloorInfo; + public int FloorId; + public int PlaneId; + public int EntryId; + + public int LeaveEntityId; + public int LastEntityId; + public bool IsLoaded = false; + + public Dictionary AvatarInfo = []; + public int LeaderEntityId; + public Dictionary Entities = []; + public List Groups = []; + public List HealingSprings = []; + + public SceneEntityLoader? EntityLoader; + + public int CustomGameModeId; + + public SceneInstance(PlayerInstance player, MazePlaneExcel excel, int floorId, int entryId) + { + Player = player; + Excel = excel; + PlaneId = excel.PlaneID; + FloorId = floorId; + EntryId = entryId; + LeaveEntityId = 0; + + System.Threading.Tasks.Task.Run(async () => { await SyncLineup(true, true); }).Wait(); + + GameData.GetFloorInfo(PlaneId, FloorId, out FloorInfo); + if (FloorInfo == null) return; + + switch (Excel.PlaneType) { - List entities = []; - foreach (var entity in Entities) - { - if (entity.Value.GroupID == groupID && entity.Value is T t) + case PlaneTypeEnum.Rogue: + if (Player.ChessRogueManager!.RogueInstance != null) { - entities.Add(t); - } - } - return entities; - } - - #endregion - - #region Serialization - - public SceneInfo ToProto() - { - SceneInfo sceneInfo = new() - { - WorldId = (uint)Excel.WorldID, - GameModeType = (uint)(CustomGameModeId > 0 ? CustomGameModeId : (int)Excel.PlaneType), - PlaneId = (uint)PlaneId, - FloorId = (uint)FloorId, - EntryId = (uint)EntryId, - SceneMissionInfo = new(), - }; - - var playerGroupInfo = new SceneEntityGroupInfo(); // avatar group - foreach (var avatar in AvatarInfo) - { - playerGroupInfo.EntityList.Add(avatar.Value.AvatarInfo.ToSceneEntityInfo(avatar.Value.AvatarType)); - } - if (playerGroupInfo.EntityList.Count > 0) - { - if (LeaderEntityId == 0) - { - LeaderEntityId = AvatarInfo.Values.First().AvatarInfo.EntityId; - sceneInfo.LeaderEntityId = (uint)LeaderEntityId; - } else - { - sceneInfo.LeaderEntityId = (uint)LeaderEntityId; - } - } - sceneInfo.EntityGroupList.Add(playerGroupInfo); - - List groups = []; // other groups - - // add entities to groups - foreach (var entity in Entities) - { - if (entity.Value.GroupID == 0) continue; - if (groups.FindIndex(x => x.GroupId == entity.Value.GroupID) == -1) - { - groups.Add(new SceneEntityGroupInfo() - { - GroupId = (uint)entity.Value.GroupID - }); - } - groups[groups.FindIndex(x => x.GroupId == entity.Value.GroupID)].EntityList.Add(entity.Value.ToProto()); - } - - foreach (var groupId in Groups) // Add for empty group - { - if (groups.FindIndex(x => x.GroupId == groupId) == -1) - { - groups.Add(new SceneEntityGroupInfo() - { - GroupId = (uint)groupId - }); - } - } - - foreach (var group in groups) - { - sceneInfo.EntityGroupList.Add(group); - } - - // custom save data and floor saved data - Player.SceneData!.CustomSaveData.TryGetValue(EntryId, out var data); - - if (data != null) - { - foreach (var customData in data) - { - sceneInfo.SaveDataList.Add(new CustomSaveData() - { - GroupId = (uint)customData.Key, - SaveData = customData.Value - }); - } - } - - Player.SceneData!.FloorSavedData.TryGetValue(FloorId, out var floorData); - - foreach (var value in FloorInfo?.SavedValues ?? []) - { - if (floorData != null && floorData.TryGetValue(value.Name, out int v)) - { - sceneInfo.FloorSavedData[value.Name] = v; + EntityLoader = new ChessRogueEntityLoader(this); + CustomGameModeId = 16; // ChessRogue } else { - sceneInfo.FloorSavedData[value.Name] = value.DefaultValue; + EntityLoader = new RogueEntityLoader(this, Player); } - } - foreach (var value in FloorInfo?.CustomValues ?? []) - { - if (floorData != null && floorData.TryGetValue(value.Name, out int v)) - { - sceneInfo.FloorSavedData[value.Name] = v; - } + break; + case PlaneTypeEnum.Challenge: + EntityLoader = new ChallengeEntityLoader(this, Player); + break; + default: + if (Player.StoryLineManager?.StoryLineData.CurStoryLineId != 0) + EntityLoader = new StoryLineEntityLoader(this); else - { - _ = int.TryParse(value.DefaultValue, out int x); - sceneInfo.FloorSavedData[value.Name] = x; - } - } - - // mission - Player.MissionManager!.OnLoadScene(sceneInfo); - - // unlock section - if (!ConfigManager.Config.ServerOption.AutoLightSection) - { - Player.SceneData!.UnlockSectionIdList.TryGetValue(FloorId, out var unlockSectionList); - if (unlockSectionList != null) - { - foreach (var sectionId in unlockSectionList) - { - sceneInfo.LightenSectionList.Add((uint)sectionId); - } - } - } else - { - for (uint i = 1; i <= 100; i++) - { - sceneInfo.LightenSectionList.Add(i); - } - } - - return sceneInfo; + EntityLoader = new SceneEntityLoader(this); + break; } - #endregion + System.Threading.Tasks.Task.Run(async () => { await EntityLoader.LoadEntity(); }).Wait(); + + Player.TaskManager?.SceneTaskTrigger.TriggerFloor(PlaneId, FloorId); } - public class AvatarSceneInfo(AvatarInfo avatarInfo, AvatarType avatarType, PlayerInstance Player) : IGameEntity + #endregion + + #region Scene Actions + + public async ValueTask SyncLineup(bool notSendPacket = false, bool forceSetEntityId = false) { - public AvatarInfo AvatarInfo = avatarInfo; - public AvatarType AvatarType = avatarType; - - public int EntityID { get; set; } = avatarInfo.EntityId; - public int GroupID { get; set; } = 0; - - public List BuffList = []; - public void AddBuff(SceneBuff buff) + var oldAvatarInfo = AvatarInfo.Values.ToList(); + AvatarInfo.Clear(); + var sendPacket = false; + var AddAvatar = new List(); + var RemoveAvatar = new List(); + foreach (var avatar in Player.LineupManager?.GetAvatarsFromCurTeam() ?? []) { - var oldBuff = BuffList.Find(x => x.BuffID == buff.BuffID); - if (oldBuff != null) + if (avatar == null) continue; + avatar.AvatarInfo.PlayerData = Player.Data; + if (forceSetEntityId && avatar.AvatarInfo.EntityId != 0) { - if (oldBuff.IsExpired()) + RemoveAvatar.Add(new AvatarSceneInfo(new AvatarInfo { - BuffList.Remove(oldBuff); - BuffList.Add(buff); - } else - { - oldBuff.CreatedTime = Extensions.GetUnixMs(); - oldBuff.Duration = buff.Duration; - - Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, oldBuff)); - return; - } + EntityId = avatar.AvatarInfo.EntityId + }, AvatarType.AvatarFormalType, Player)); + avatar.AvatarInfo.EntityId = 0; + sendPacket = true; } - BuffList.Add(buff); - Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, buff)); - } - public void ApplyBuff(BattleInstance instance) - { - foreach (var buff in BuffList) + var avatarInstance = oldAvatarInfo.Find(x => x.AvatarInfo.AvatarId == avatar.AvatarInfo.AvatarId); + if (avatarInstance == null) { - if (buff.IsExpired()) - { - continue; - } - instance.Buffs.Add(new MazeBuff(buff)); + if (avatar.AvatarInfo.EntityId == 0) avatar.AvatarInfo.EntityId = ++LastEntityId; + AddAvatar.Add(avatar); + AvatarInfo.Add(avatar.AvatarInfo.EntityId, avatar); + sendPacket = true; + } + else + { + AvatarInfo.Add(avatarInstance.AvatarInfo.EntityId, avatarInstance); } - Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, BuffList)); - - BuffList.Clear(); } - public SceneEntityInfo ToProto() - { - return AvatarInfo.ToSceneEntityInfo(AvatarType); - } + ; + foreach (var avatar in oldAvatarInfo) + if (AvatarInfo.Values.ToList().FindIndex(x => x.AvatarInfo.AvatarId == avatar.AvatarInfo.AvatarId) == -1) + { + RemoveAvatar.Add(new AvatarSceneInfo(new AvatarInfo + { + EntityId = avatar.AvatarInfo.EntityId + }, AvatarType.AvatarFormalType, Player)); + avatar.AvatarInfo.EntityId = 0; + sendPacket = true; + } + + var LeaderAvatarId = Player.LineupManager?.GetCurLineup()?.LeaderAvatarId; + var LeaderAvatarSlot = Player.LineupManager?.GetCurLineup()?.BaseAvatars + ?.FindIndex(x => x.BaseAvatarId == LeaderAvatarId); + if (LeaderAvatarSlot == -1) LeaderAvatarSlot = 0; + if (AvatarInfo.Count == 0) return; + var info = AvatarInfo.Values.ToList()[LeaderAvatarSlot ?? 0]; + LeaderEntityId = info.AvatarInfo.EntityId; + if (sendPacket && !notSendPacket) + await Player.SendPacket(new PacketSceneGroupRefreshScNotify(AddAvatar, RemoveAvatar)); } + + public void SyncGroupInfo() + { + EntityLoader?.SyncEntity(); + } + + #endregion + + #region Entity Management + + public async ValueTask AddEntity(IGameEntity entity) + { + await AddEntity(entity, IsLoaded); + } + + public async ValueTask AddEntity(IGameEntity entity, bool SendPacket) + { + if (entity == null || entity.EntityID != 0) return; + entity.EntityID = ++LastEntityId; + + Entities.Add(entity.EntityID, entity); + if (SendPacket) await Player.SendPacket(new PacketSceneGroupRefreshScNotify(entity)); + } + + public async ValueTask RemoveEntity(IGameEntity monster) + { + await RemoveEntity(monster, IsLoaded); + } + + public async ValueTask RemoveEntity(IGameEntity monster, bool SendPacket) + { + Entities.Remove(monster.EntityID); + + if (SendPacket) await Player.SendPacket(new PacketSceneGroupRefreshScNotify(null, monster)); + } + + public List GetEntitiesInGroup(int groupID) + { + List entities = []; + foreach (var entity in Entities) + if (entity.Value.GroupID == groupID && entity.Value is T t) + entities.Add(t); + return entities; + } + + #endregion } + +public class AvatarSceneInfo(AvatarInfo avatarInfo, AvatarType avatarType, PlayerInstance Player) : IGameEntity +{ + public AvatarInfo AvatarInfo = avatarInfo; + public AvatarType AvatarType = avatarType; + + public List BuffList = []; + + public int EntityID { get; set; } = avatarInfo.EntityId; + public int GroupID { get; set; } = 0; + + public async ValueTask AddBuff(SceneBuff buff) + { + var oldBuff = BuffList.Find(x => x.BuffID == buff.BuffID); + if (oldBuff != null) + { + if (oldBuff.IsExpired()) + { + BuffList.Remove(oldBuff); + BuffList.Add(buff); + } + else + { + oldBuff.CreatedTime = Extensions.GetUnixMs(); + oldBuff.Duration = buff.Duration; + + await Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, oldBuff)); + return; + } + } + + BuffList.Add(buff); + await Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, buff)); + } + + public async ValueTask ApplyBuff(BattleInstance instance) + { + foreach (var buff in BuffList) + { + if (buff.IsExpired()) continue; + instance.Buffs.Add(new MazeBuff(buff)); + } + + await Player.SendPacket(new PacketSyncEntityBuffChangeListScNotify(this, BuffList)); + + BuffList.Clear(); + } + + public SceneEntityInfo ToProto() + { + return AvatarInfo.ToSceneEntityInfo(AvatarType); + } +} \ No newline at end of file diff --git a/GameServer/Game/Shop/ShopService.cs b/GameServer/Game/Shop/ShopService.cs index 6e078fd6..b37958d5 100644 --- a/GameServer/Game/Shop/ShopService.cs +++ b/GameServer/Game/Shop/ShopService.cs @@ -1,56 +1,40 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Enums.Item; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Shop +namespace EggLink.DanhengServer.Game.Shop; + +public class ShopService(PlayerInstance player) : BasePlayerManager(player) { - public class ShopService(PlayerInstance player) : BasePlayerManager(player) + public async ValueTask> BuyItem(int shopId, int goodsId, int count) { - public List BuyItem(int shopId, int goodsId, int count) + GameData.ShopConfigData.TryGetValue(shopId, out var shopConfig); + if (shopConfig == null) return []; + var goods = shopConfig.Goods.Find(g => g.GoodsID == goodsId); + if (goods == null) return []; + GameData.ItemConfigData.TryGetValue(goods.ItemID, out var itemConfig); + if (itemConfig == null) return []; + + foreach (var cost in goods.CostList) await Player.InventoryManager!.RemoveItem(cost.Key, cost.Value * count); + var items = new List(); + if (itemConfig.ItemMainType == ItemMainTypeEnum.Equipment || itemConfig.ItemMainType == ItemMainTypeEnum.Relic) { - GameData.ShopConfigData.TryGetValue(shopId, out var shopConfig); - if (shopConfig == null) return []; - var goods = shopConfig.Goods.Find(g => g.GoodsID == goodsId); - if (goods == null) return []; - GameData.ItemConfigData.TryGetValue(goods.ItemID, out var itemConfig); - if (itemConfig == null) return []; - - foreach (var cost in goods.CostList) + for (var i = 0; i < count; i++) { - Player.InventoryManager!.RemoveItem(cost.Key, cost.Value * count); + var item = await Player.InventoryManager!.AddItem(itemConfig.ID, 1, false); + if (item != null) items.Add(item); } - var items = new List(); - if (itemConfig.ItemMainType == ItemMainTypeEnum.Equipment || itemConfig.ItemMainType == ItemMainTypeEnum.Relic) - { - for (int i = 0; i < count; i++) - { - var item = Player.InventoryManager!.AddItem(itemConfig.ID, 1, false); - if (item != null) - { - items.Add(item); - } - } - } - else - { - var item = Player.InventoryManager!.AddItem(itemConfig.ID, count, false); - if (item != null) - { - items.Add(item); - } - } - - Player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.BuyShopGoods, "BuyGoods"); - - return items; } + else + { + var item = await Player.InventoryManager!.AddItem(itemConfig.ID, count, false); + if (item != null) items.Add(item); + } + + await Player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.BuyShopGoods, "BuyGoods"); + + return items; } -} +} \ No newline at end of file diff --git a/GameServer/Game/Task/LevelTask.cs b/GameServer/Game/Task/LevelTask.cs index 241e8a67..91a3d51a 100644 --- a/GameServer/Game/Task/LevelTask.cs +++ b/GameServer/Game/Task/LevelTask.cs @@ -1,459 +1,358 @@ -using EggLink.DanhengServer.Data.Config.Task; -using EggLink.DanhengServer.Data.Config; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Data.Config; +using EggLink.DanhengServer.Data.Config.Task; +using EggLink.DanhengServer.Data.Excel; +using EggLink.DanhengServer.Enums; +using EggLink.DanhengServer.Enums.Scene; +using EggLink.DanhengServer.Enums.Task; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Scene.Entity; -using EggLink.DanhengServer.Enums; -using EggLink.DanhengServer.Data.Excel; -using EggLink.DanhengServer.Enums.Task; -using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.GameServer.Game.Task +namespace EggLink.DanhengServer.GameServer.Game.Task; + +public class LevelTask(PlayerInstance player) { - public class LevelTask(PlayerInstance player) + public PlayerInstance Player { get; } = player; + + #region Prop Target + + public EntityProp? TargetFetchAdvPropEx(TargetEvaluator act, SubMissionExcel subMission, GroupInfo? group = null) { - public PlayerInstance Player { get; } = player; - - #region Manage - - public void TriggerInitAct(LevelInitSequeceConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + if (act is TargetFetchAdvPropEx fetch) { - foreach (var task in act.TaskList) - { - TriggerTask(task, subMission, group); - } + if (fetch.FetchType != TargetFetchAdvPropFetchTypeEnum.SinglePropByPropID) return null; + foreach (var entity in Player.SceneInstance!.Entities.Values) + if (entity is EntityProp prop && prop.GroupID == fetch.SinglePropID.GroupID.GetValue() && + prop.InstId == fetch.SinglePropID.ID.GetValue()) + return prop; } - public void TriggerStartAct(LevelStartSequeceConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - foreach (var task in act.TaskList) - { - TriggerTask(task, subMission, group); - } - } - - private void TriggerTask(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - try - { - var methodName = act.Type.Replace("RPG.GameCore.", ""); - - var method = GetType().GetMethod(methodName); - if (method != null) - { - _ = method.Invoke(this, [act, subMission, group]); - } - } - catch - { - } - } - - #endregion - - #region Task - - public void PlayMessage(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is PlayMessage message) - { - Player.MessageManager!.AddMessageSection(message.MessageSectionID); - } - } - - public void DestroyProp(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is DestroyProp destroyProp) - { - foreach (var entity in Player.SceneInstance!.Entities.Values) - { - if (entity is EntityProp prop && prop.GroupID == destroyProp.GroupID.GetValue() && prop.InstId == destroyProp.ID.GetValue()) - { - Player.SceneInstance.RemoveEntity(entity); - } - } - } - } - - public void TriggerCustomString(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is TriggerCustomString triggerCustomString) - { - foreach (var groupInfo in Player.SceneInstance?.FloorInfo?.Groups ?? []) - { - if (groupInfo.Value.PropTriggerCustomString.TryGetValue(triggerCustomString.CustomString.Value, out var list)) - { - foreach (var id in list) - { - foreach (var entity in Player.SceneInstance?.Entities.Values.ToList() ?? []) - { - if (entity is EntityProp prop && prop.GroupID == groupInfo.Key && prop.InstId == id) - { - prop.SetState(PropStateEnum.Closed); - } - } - } - } - } - - Player.MissionManager?.HandleFinishType(MissionFinishTypeEnum.PropState); - } - } - - public void EnterMap(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is EnterMap enterMap) - { - Player.EnterMissionScene(enterMap.EntranceID, enterMap.GroupID, enterMap.AnchorID, true); - } - } - - public void EnterMapByCondition(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is EnterMapByCondition enterMapByCondition) - { - Player.EnterMissionScene(enterMapByCondition.EntranceID.GetValue(), 0, 0, true); - } - } - - public void TriggerPerformance(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is TriggerPerformance triggerPerformance) - { - if (triggerPerformance.PerformanceType == ELevelPerformanceTypeEnum.E) - { - Player.TaskManager?.PerformanceTrigger.TriggerPerformanceE(triggerPerformance.PerformanceID, subMission); - } - else if (triggerPerformance.PerformanceType == ELevelPerformanceTypeEnum.D) - { - Player.TaskManager?.PerformanceTrigger.TriggerPerformanceD(triggerPerformance.PerformanceID, subMission); - } - } - } - - public void PredicateTaskList(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is PredicateTaskList predicateTaskList) - { - // handle predicateCondition - var methodName = predicateTaskList.Predicate.Type.Replace("RPG.GameCore.", ""); - - var method = GetType().GetMethod(methodName); - if (method != null) - { - var resp = method.Invoke(this, [predicateTaskList.Predicate, subMission, group]); - if (resp is bool result && result) - { - foreach (var task in predicateTaskList.SuccessTaskList) - { - TriggerTask(task, subMission, group); - } - } - else - { - foreach (var task in predicateTaskList.FailedTaskList) - { - TriggerTask(task, subMission, group); - } - } - } - } - } - - public void ChangePropState(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.PropState) - { - foreach (var entity in Player.SceneInstance!.Entities.Values) - { - if (entity is EntityProp prop && prop.GroupID == subMission.SubMissionInfo.ParamInt1 && prop.InstId == subMission.SubMissionInfo.ParamInt2) - { - try - { - if (prop.Excel.PropStateList.Contains(PropStateEnum.Closed)) - { - prop.SetState(PropStateEnum.Closed); - } - else - { - prop.SetState(prop.Excel.PropStateList[prop.Excel.PropStateList.IndexOf(prop.State) + 1]); - - // Elevator - foreach (var id in prop.PropInfo.UnlockControllerID) - { - foreach (var entity2 in Player.SceneInstance!.Entities.Values) - { - if (entity2 is EntityProp prop2 && prop2.GroupID == id.Key && id.Value.Contains(prop2.InstId)) - { - prop2.SetState(PropStateEnum.Closed); - } - } - } - } - } - catch - { - } - } - } - } - } - - public void CreateTrialPlayer(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatar) - { - Player.LineupManager!.AddAvatarToCurTeam(subMission.SubMissionInfo.ParamInt1); - } - - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatarList) - { - subMission.SubMissionInfo.ParamIntList?.ForEach(x => Player.LineupManager!.AddAvatarToCurTeam(x)); - } - } - - public void ReplaceTrialPlayer(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatar) - { - var ids = Player.LineupManager!.GetCurLineup()?.BaseAvatars?.ToList() ?? []; - ids.ForEach(x => Player.LineupManager!.RemoveAvatarFromCurTeam(x.BaseAvatarId, false)); - Player.LineupManager!.AddAvatarToCurTeam(subMission.SubMissionInfo.ParamInt1); - } - - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatarList) - { - var ids = Player.LineupManager!.GetCurLineup()?.BaseAvatars?.ToList() ?? []; - ids.ForEach(x => Player.LineupManager!.RemoveAvatarFromCurTeam(x.BaseAvatarId, false)); - subMission.SubMissionInfo.ParamIntList?.ForEach(x => Player.LineupManager!.AddAvatarToCurTeam(x)); - } - } - - public void ReplaceVirtualTeam(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (!(Player.LineupManager!.GetCurLineup()?.IsExtraLineup() == true)) - { - return; - } - - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatar) - { - var ids = Player.LineupManager!.GetCurLineup()?.BaseAvatars?.ToList() ?? []; - ids.ForEach(x => Player.LineupManager!.RemoveAvatarFromCurTeam(x.BaseAvatarId, false)); ; - Player.LineupManager!.AddAvatarToCurTeam(subMission.SubMissionInfo.ParamInt1); - } - - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatarList) - { - var ids = Player.LineupManager!.GetCurLineup()?.BaseAvatars?.ToList() ?? []; - ids.ForEach(x => Player.LineupManager!.RemoveAvatarFromCurTeam(x.BaseAvatarId, false)); - subMission.SubMissionInfo.ParamIntList?.ForEach(x => Player.LineupManager!.AddAvatarToCurTeam(x)); - } - } - - public void CreateHeroTrialPlayer(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatar) - { - Player.LineupManager!.AddAvatarToCurTeam(subMission.SubMissionInfo.ParamInt1); - } - - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatarList) - { - List list = [.. subMission.SubMissionInfo.ParamIntList]; - - if (list.Count > 0) - { - if (Player.Data.CurrentGender == Gender.Man) - { - foreach (var avatar in subMission.SubMissionInfo?.ParamIntList ?? []) - { - if (avatar > 10000) // else is Base Avatar - { - if (avatar.ToString().EndsWith("8002") || - avatar.ToString().EndsWith("8004") || - avatar.ToString().EndsWith("8006")) - { - list.Remove(avatar); - } - } - } - } - else - { - foreach (var avatar in subMission.SubMissionInfo?.ParamIntList ?? []) - { - if (avatar > 10000) // else is Base Avatar - { - if (avatar.ToString().EndsWith("8001") || - avatar.ToString().EndsWith("8003") || - avatar.ToString().EndsWith("8005")) - { - list.Remove(avatar); - } - } - } - } - } - - list.ForEach(x => Player.LineupManager!.AddAvatarToCurTeam(x)); - } - } - - public void DestroyTrialPlayer(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.DelTrialAvatar) - { - Player.LineupManager!.RemoveAvatarFromCurTeam(subMission.SubMissionInfo.ParamInt1); - } - } - - public void ChangeGroupState(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (group != null) - { - foreach (var entity in Player.SceneInstance?.Entities.Values.ToList() ?? []) - { - if (entity is EntityProp prop && prop.GroupID == group.Id) - { - if (prop.Excel.PropStateList.Contains(PropStateEnum.Open)) - { - prop.SetState(PropStateEnum.Open); - } - } - } - } - } - - public void TriggerEntityServerEvent(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (group != null) - { - foreach (var entity in Player.SceneInstance?.Entities.Values.ToList() ?? []) - { - if (entity is EntityProp prop && prop.GroupID == group.Id) - { - if (prop.Excel.PropStateList.Contains(PropStateEnum.Open) && (prop.State == PropStateEnum.Closed || prop.State == PropStateEnum.Locked)) - { - prop.SetState(PropStateEnum.Open); - } - } - } - } - } - - public void TriggerEntityEvent(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is TriggerEntityEvent triggerEntityEvent) - { - if (group != null) - { - foreach (var entity in Player.SceneInstance?.Entities.Values.ToList() ?? []) - { - if (entity is EntityProp prop && prop.GroupID == group.Id && prop.InstId == triggerEntityEvent.InstanceID.GetValue()) - { - if (prop.Excel.PropStateList.Contains(PropStateEnum.Closed)) - { - prop.SetState(PropStateEnum.Closed); - } - } - } - } - } - } - - public void PropSetupUITrigger(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is PropSetupUITrigger propSetupUITrigger) - { - foreach (var task in propSetupUITrigger.ButtonCallback) - { - TriggerTask(task, subMission, group); - } - } - } - - public void PropStateExecute(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is PropStateExecute propStateExecute) - { - // handle targetType - var methodName = propStateExecute.TargetType.Type.Replace("RPG.GameCore.", ""); - - var method = GetType().GetMethod(methodName); - if (method != null) - { - var resp = method.Invoke(this, [propStateExecute.TargetType, subMission, group]); - if (resp is EntityProp result && result != null) - { - result.SetState(propStateExecute.State); - } - } - } - } - - #endregion - - #region Task Condition - - public bool ByCompareSubMissionState(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is ByCompareSubMissionState compare) - { - var mission = Player.MissionManager!.GetSubMissionStatus(compare.SubMissionID); - return mission.ToStateEnum() == compare.SubMissionState; - } - - return false; - } - - public bool ByCompareFloorSavedValue(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is ByCompareFloorSavedValue compare) - { - var value = Player.SceneData!.FloorSavedData.GetValueOrDefault(Player.Data.FloorId, []); - return compare.CompareType switch - { - CompareTypeEnum.Equal => value.GetValueOrDefault(compare.Name, 0) == compare.CompareValue, - CompareTypeEnum.Greater => value.GetValueOrDefault(compare.Name, 0) > compare.CompareValue, - CompareTypeEnum.Less => value.GetValueOrDefault(compare.Name, 0) < compare.CompareValue, - CompareTypeEnum.GreaterEqual => value.GetValueOrDefault(compare.Name, 0) >= compare.CompareValue, - CompareTypeEnum.LessEqual => value.GetValueOrDefault(compare.Name, 0) <= compare.CompareValue, - CompareTypeEnum.NotEqual => value.GetValueOrDefault(compare.Name, 0) != compare.CompareValue, - _ => false, - }; - } - - return false; - } - - #endregion - - #region Prop Target - - public EntityProp? TargetFetchAdvPropEx(TargetEvaluator act, SubMissionExcel subMission, GroupInfo? group = null) - { - if (act is TargetFetchAdvPropEx fetch) - { - if (fetch.FetchType != TargetFetchAdvPropFetchTypeEnum.SinglePropByPropID) return null; - foreach (var entity in Player.SceneInstance!.Entities.Values) - { - if (entity is EntityProp prop && prop.GroupID == fetch.SinglePropID.GroupID.GetValue() && prop.InstId == fetch.SinglePropID.ID.GetValue()) - { - return prop; - } - } - } - - return null; - } - - #endregion + return null; } -} + + #endregion + + #region Manage + + public void TriggerInitAct(LevelInitSequeceConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + foreach (var task in act.TaskList) TriggerTask(task, subMission, group); + } + + public void TriggerStartAct(LevelStartSequeceConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + foreach (var task in act.TaskList) TriggerTask(task, subMission, group); + } + + private void TriggerTask(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + try + { + var methodName = act.Type.Replace("RPG.GameCore.", ""); + + var method = GetType().GetMethod(methodName); + if (method != null) _ = method.Invoke(this, [act, subMission, group]); + } + catch + { + } + } + + #endregion + + #region Task + + public async ValueTask PlayMessage(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is PlayMessage message) await Player.MessageManager!.AddMessageSection(message.MessageSectionID); + } + + public async ValueTask DestroyProp(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is DestroyProp destroyProp) + foreach (var entity in Player.SceneInstance!.Entities.Values) + if (entity is EntityProp prop && prop.GroupID == destroyProp.GroupID.GetValue() && + prop.InstId == destroyProp.ID.GetValue()) + await Player.SceneInstance.RemoveEntity(entity); + } + + public async ValueTask TriggerCustomString(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is TriggerCustomString triggerCustomString) + { + foreach (var groupInfo in Player.SceneInstance?.FloorInfo?.Groups ?? []) + if (groupInfo.Value.PropTriggerCustomString.TryGetValue(triggerCustomString.CustomString.Value, + out var list)) + foreach (var id in list) + foreach (var entity in Player.SceneInstance?.Entities.Values.ToList() ?? []) + if (entity is EntityProp prop && prop.GroupID == groupInfo.Key && prop.InstId == id) + await prop.SetState(PropStateEnum.Closed); + + Player.MissionManager?.HandleFinishType(MissionFinishTypeEnum.PropState); + } + } + + public async ValueTask EnterMap(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is EnterMap enterMap) + await Player.EnterMissionScene(enterMap.EntranceID, enterMap.GroupID, enterMap.AnchorID, true); + } + + public async ValueTask EnterMapByCondition(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is EnterMapByCondition enterMapByCondition) + await Player.EnterMissionScene(enterMapByCondition.EntranceID.GetValue(), 0, 0, true); + } + + public async ValueTask TriggerPerformance(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is TriggerPerformance triggerPerformance) + { + if (triggerPerformance.PerformanceType == ELevelPerformanceTypeEnum.E) + Player.TaskManager?.PerformanceTrigger.TriggerPerformanceE(triggerPerformance.PerformanceID, + subMission); + else if (triggerPerformance.PerformanceType == ELevelPerformanceTypeEnum.D) + Player.TaskManager?.PerformanceTrigger.TriggerPerformanceD(triggerPerformance.PerformanceID, + subMission); + } + + await System.Threading.Tasks.Task.CompletedTask; + } + + public async ValueTask PredicateTaskList(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is PredicateTaskList predicateTaskList) + { + // handle predicateCondition + var methodName = predicateTaskList.Predicate.Type.Replace("RPG.GameCore.", ""); + + var method = GetType().GetMethod(methodName); + if (method != null) + { + var resp = method.Invoke(this, [predicateTaskList.Predicate, subMission, group]); + if (resp is bool res && res) + foreach (var task in predicateTaskList.SuccessTaskList) + TriggerTask(task, subMission, group); + else + foreach (var task in predicateTaskList.FailedTaskList) + TriggerTask(task, subMission, group); + } + } + + await System.Threading.Tasks.Task.CompletedTask; + } + + public async ValueTask ChangePropState(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.PropState) + foreach (var entity in Player.SceneInstance!.Entities.Values) + if (entity is EntityProp prop && prop.GroupID == subMission.SubMissionInfo.ParamInt1 && + prop.InstId == subMission.SubMissionInfo.ParamInt2) + try + { + if (prop.Excel.PropStateList.Contains(PropStateEnum.Closed)) + { + await prop.SetState(PropStateEnum.Closed); + } + else + { + await prop.SetState( + prop.Excel.PropStateList[prop.Excel.PropStateList.IndexOf(prop.State) + 1]); + + // Elevator + foreach (var id in prop.PropInfo.UnlockControllerID) + foreach (var entity2 in Player.SceneInstance!.Entities.Values) + if (entity2 is EntityProp prop2 && prop2.GroupID == id.Key && + id.Value.Contains(prop2.InstId)) + await prop2.SetState(PropStateEnum.Closed); + } + } + catch + { + } + } + + public async ValueTask CreateTrialPlayer(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatar) + await Player.LineupManager!.AddAvatarToCurTeam(subMission.SubMissionInfo.ParamInt1); + + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatarList) + subMission.SubMissionInfo.ParamIntList?.ForEach( + async x => await Player.LineupManager!.AddAvatarToCurTeam(x)); + } + + public async ValueTask ReplaceTrialPlayer(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatar) + { + var ids = Player.LineupManager!.GetCurLineup()?.BaseAvatars?.ToList() ?? []; + ids.ForEach(async x => await Player.LineupManager!.RemoveAvatarFromCurTeam(x.BaseAvatarId, false)); + await Player.LineupManager!.AddAvatarToCurTeam(subMission.SubMissionInfo.ParamInt1); + } + + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatarList) + { + var ids = Player.LineupManager!.GetCurLineup()?.BaseAvatars?.ToList() ?? []; + ids.ForEach(async x => await Player.LineupManager!.RemoveAvatarFromCurTeam(x.BaseAvatarId, false)); + subMission.SubMissionInfo.ParamIntList?.ForEach( + async x => await Player.LineupManager!.AddAvatarToCurTeam(x)); + } + } + + public async ValueTask ReplaceVirtualTeam(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (!(Player.LineupManager!.GetCurLineup()?.IsExtraLineup() == true)) return; + + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatar) + { + var ids = Player.LineupManager!.GetCurLineup()?.BaseAvatars?.ToList() ?? []; + ids.ForEach(async x => await Player.LineupManager!.RemoveAvatarFromCurTeam(x.BaseAvatarId, false)); + ; + await Player.LineupManager!.AddAvatarToCurTeam(subMission.SubMissionInfo.ParamInt1); + } + + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatarList) + { + var ids = Player.LineupManager!.GetCurLineup()?.BaseAvatars?.ToList() ?? []; + ids.ForEach(async x => await Player.LineupManager!.RemoveAvatarFromCurTeam(x.BaseAvatarId, false)); + subMission.SubMissionInfo.ParamIntList?.ForEach( + async x => await Player.LineupManager!.AddAvatarToCurTeam(x)); + } + } + + public async ValueTask CreateHeroTrialPlayer(TaskConfigInfo act, SubMissionExcel subMission, + GroupInfo? group = null) + { + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatar) + await Player.LineupManager!.AddAvatarToCurTeam(subMission.SubMissionInfo.ParamInt1); + + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.GetTrialAvatarList) + { + List list = [.. subMission.SubMissionInfo.ParamIntList]; + + if (list.Count > 0) + { + if (Player.Data.CurrentGender == Gender.Man) + { + foreach (var avatar in subMission.SubMissionInfo?.ParamIntList ?? []) + if (avatar > 10000) // else is Base Avatar + if (avatar.ToString().EndsWith("8002") || + avatar.ToString().EndsWith("8004") || + avatar.ToString().EndsWith("8006")) + list.Remove(avatar); + } + else + { + foreach (var avatar in subMission.SubMissionInfo?.ParamIntList ?? []) + if (avatar > 10000) // else is Base Avatar + if (avatar.ToString().EndsWith("8001") || + avatar.ToString().EndsWith("8003") || + avatar.ToString().EndsWith("8005")) + list.Remove(avatar); + } + } + + list.ForEach(async x => await Player.LineupManager!.AddAvatarToCurTeam(x)); + } + } + + public async ValueTask DestroyTrialPlayer(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (subMission.SubMissionInfo?.FinishType == MissionFinishTypeEnum.DelTrialAvatar) + await Player.LineupManager!.RemoveAvatarFromCurTeam(subMission.SubMissionInfo.ParamInt1); + } + + public async ValueTask ChangeGroupState(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (group != null) + foreach (var entity in Player.SceneInstance?.Entities.Values.ToList() ?? []) + if (entity is EntityProp prop && prop.GroupID == group.Id) + if (prop.Excel.PropStateList.Contains(PropStateEnum.Open)) + await prop.SetState(PropStateEnum.Open); + } + + public async ValueTask TriggerEntityServerEvent(TaskConfigInfo act, SubMissionExcel subMission, + GroupInfo? group = null) + { + if (group != null) + foreach (var entity in Player.SceneInstance?.Entities.Values.ToList() ?? []) + if (entity is EntityProp prop && prop.GroupID == group.Id) + if (prop.Excel.PropStateList.Contains(PropStateEnum.Open) && + (prop.State == PropStateEnum.Closed || prop.State == PropStateEnum.Locked)) + await prop.SetState(PropStateEnum.Open); + } + + public async ValueTask TriggerEntityEvent(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is TriggerEntityEvent triggerEntityEvent) + if (group != null) + foreach (var entity in Player.SceneInstance?.Entities.Values.ToList() ?? []) + if (entity is EntityProp prop && prop.GroupID == group.Id && + prop.InstId == triggerEntityEvent.InstanceID.GetValue()) + if (prop.Excel.PropStateList.Contains(PropStateEnum.Closed)) + await prop.SetState(PropStateEnum.Closed); + } + + public async ValueTask PropSetupUITrigger(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is PropSetupUITrigger propSetupUITrigger) + foreach (var task in propSetupUITrigger.ButtonCallback) + TriggerTask(task, subMission, group); + + await System.Threading.Tasks.Task.CompletedTask; + } + + public async ValueTask PropStateExecute(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is PropStateExecute propStateExecute) + { + // handle targetType + var methodName = propStateExecute.TargetType.Type.Replace("RPG.GameCore.", ""); + + var method = GetType().GetMethod(methodName); + if (method != null) + { + var resp = method.Invoke(this, [propStateExecute.TargetType, subMission, group]); + if (resp is EntityProp result && result != null) await result.SetState(propStateExecute.State); + } + } + } + + #endregion + + #region Task Condition + + public bool ByCompareSubMissionState(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is ByCompareSubMissionState compare) + { + var mission = Player.MissionManager!.GetSubMissionStatus(compare.SubMissionID); + return mission.ToStateEnum() == compare.SubMissionState; + } + + return false; + } + + public bool ByCompareFloorSavedValue(TaskConfigInfo act, SubMissionExcel subMission, GroupInfo? group = null) + { + if (act is ByCompareFloorSavedValue compare) + { + var value = Player.SceneData!.FloorSavedData.GetValueOrDefault(Player.Data.FloorId, []); + return compare.CompareType switch + { + CompareTypeEnum.Equal => value.GetValueOrDefault(compare.Name, 0) == compare.CompareValue, + CompareTypeEnum.Greater => value.GetValueOrDefault(compare.Name, 0) > compare.CompareValue, + CompareTypeEnum.Less => value.GetValueOrDefault(compare.Name, 0) < compare.CompareValue, + CompareTypeEnum.GreaterEqual => value.GetValueOrDefault(compare.Name, 0) >= compare.CompareValue, + CompareTypeEnum.LessEqual => value.GetValueOrDefault(compare.Name, 0) <= compare.CompareValue, + CompareTypeEnum.NotEqual => value.GetValueOrDefault(compare.Name, 0) != compare.CompareValue, + _ => false + }; + } + + return false; + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Game/Task/MissionTaskTrigger.cs b/GameServer/Game/Task/MissionTaskTrigger.cs index 51013054..8c06b563 100644 --- a/GameServer/Game/Task/MissionTaskTrigger.cs +++ b/GameServer/Game/Task/MissionTaskTrigger.cs @@ -2,38 +2,26 @@ using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Task +namespace EggLink.DanhengServer.GameServer.Game.Task; + +public class MissionTaskTrigger(PlayerInstance player) { - public class MissionTaskTrigger(PlayerInstance player) + public PlayerInstance Player { get; } = player; + + public void TriggerMissionTask(int missionId) { - public PlayerInstance Player { get; } = player; - - public void TriggerMissionTask(int missionId) - { - GameData.SubMissionData.TryGetValue(missionId, out var subMission); - if (subMission != null) - { - TriggerMissionTask(subMission.SubMissionTaskInfo ?? new(), subMission); - } - } - - public void TriggerMissionTask(LevelGraphConfigInfo subMissionTaskInfo, SubMissionExcel subMission) - { - foreach (var task in subMissionTaskInfo.OnInitSequece) - { - Player.TaskManager?.LevelTask.TriggerInitAct(task, subMission); - } - - foreach (var task in subMissionTaskInfo.OnStartSequece) - { - Player.TaskManager?.LevelTask.TriggerStartAct(task, subMission); - } - } + GameData.SubMissionData.TryGetValue(missionId, out var subMission); + if (subMission != null) + TriggerMissionTask(subMission.SubMissionTaskInfo ?? new LevelGraphConfigInfo(), subMission); } -} + + public void TriggerMissionTask(LevelGraphConfigInfo subMissionTaskInfo, SubMissionExcel subMission) + { + foreach (var task in subMissionTaskInfo.OnInitSequece) + Player.TaskManager?.LevelTask.TriggerInitAct(task, subMission); + + foreach (var task in subMissionTaskInfo.OnStartSequece) + Player.TaskManager?.LevelTask.TriggerStartAct(task, subMission); + } +} \ No newline at end of file diff --git a/GameServer/Game/Task/PerformanceTrigger.cs b/GameServer/Game/Task/PerformanceTrigger.cs index 1ec4f756..baf1096d 100644 --- a/GameServer/Game/Task/PerformanceTrigger.cs +++ b/GameServer/Game/Task/PerformanceTrigger.cs @@ -1,64 +1,40 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Data.Config; -using EggLink.DanhengServer.Data.Config.Task; using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Game.Task +namespace EggLink.DanhengServer.Game.Task; + +public class PerformanceTrigger(PlayerInstance player) { - public class PerformanceTrigger(PlayerInstance player) + public PlayerInstance Player { get; } = player; + + public void TriggerPerformanceE(int performanceEId, SubMissionExcel subMission) { - public PlayerInstance Player { get; } = player; - - public void TriggerPerformanceE(int performanceEId, SubMissionExcel subMission) - { - GameData.PerformanceEData.TryGetValue(performanceEId, out var excel); - if (excel != null) - { - TriggerPerformanceE(excel, subMission); - } - } - - public void TriggerPerformanceE(PerformanceEExcel excel, SubMissionExcel subMission) - { - if (excel.ActInfo == null) return; - foreach (var act in excel.ActInfo.OnInitSequece) - { - Player.TaskManager?.LevelTask.TriggerInitAct(act, subMission); - } - - foreach (var act in excel.ActInfo.OnStartSequece) - { - Player.TaskManager?.LevelTask.TriggerStartAct(act, subMission); - } - } - - public void TriggerPerformanceD(int performanceDId, SubMissionExcel subMission) - { - GameData.PerformanceDData.TryGetValue(performanceDId, out var excel); - if (excel != null) - { - TriggerPerformanceD(excel, subMission); - } - } - - public void TriggerPerformanceD(PerformanceDExcel excel, SubMissionExcel subMission) - { - if (excel.ActInfo == null) return; - foreach (var act in excel.ActInfo.OnInitSequece) - { - Player.TaskManager?.LevelTask.TriggerInitAct(act, subMission); - } - - foreach (var act in excel.ActInfo.OnStartSequece) - { - Player.TaskManager?.LevelTask.TriggerStartAct(act, subMission); - } - } + GameData.PerformanceEData.TryGetValue(performanceEId, out var excel); + if (excel != null) TriggerPerformanceE(excel, subMission); } -} + + public void TriggerPerformanceE(PerformanceEExcel excel, SubMissionExcel subMission) + { + if (excel.ActInfo == null) return; + foreach (var act in excel.ActInfo.OnInitSequece) Player.TaskManager?.LevelTask.TriggerInitAct(act, subMission); + + foreach (var act in excel.ActInfo.OnStartSequece) + Player.TaskManager?.LevelTask.TriggerStartAct(act, subMission); + } + + public void TriggerPerformanceD(int performanceDId, SubMissionExcel subMission) + { + GameData.PerformanceDData.TryGetValue(performanceDId, out var excel); + if (excel != null) TriggerPerformanceD(excel, subMission); + } + + public void TriggerPerformanceD(PerformanceDExcel excel, SubMissionExcel subMission) + { + if (excel.ActInfo == null) return; + foreach (var act in excel.ActInfo.OnInitSequece) Player.TaskManager?.LevelTask.TriggerInitAct(act, subMission); + + foreach (var act in excel.ActInfo.OnStartSequece) + Player.TaskManager?.LevelTask.TriggerStartAct(act, subMission); + } +} \ No newline at end of file diff --git a/GameServer/Game/Task/SceneTaskTrigger.cs b/GameServer/Game/Task/SceneTaskTrigger.cs index e6f19f5f..669ebe87 100644 --- a/GameServer/Game/Task/SceneTaskTrigger.cs +++ b/GameServer/Game/Task/SceneTaskTrigger.cs @@ -1,54 +1,41 @@ using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Data.Excel; using EggLink.DanhengServer.Game.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Task +namespace EggLink.DanhengServer.GameServer.Game.Task; + +public class SceneTaskTrigger(PlayerInstance player) { - public class SceneTaskTrigger(PlayerInstance player) + public PlayerInstance Player { get; } = player; + + public void TriggerFloor(int planeId, int floorId) { - public PlayerInstance Player { get; } = player; + GameData.GetFloorInfo(planeId, floorId, out var floor); + if (floor == null) return; - public void TriggerFloor(int planeId, int floorId) + foreach (var group in floor.Groups.Values) { - GameData.GetFloorInfo(planeId, floorId, out var floor); - if (floor == null) return; - - foreach (var group in floor.Groups.Values) - { - if (group.LevelGraphConfig == null) continue; - foreach (var task in group.LevelGraphConfig.OnInitSequece) - { - Player.TaskManager?.LevelTask.TriggerInitAct(task, new(), group); - } + if (group.LevelGraphConfig == null) continue; + foreach (var task in group.LevelGraphConfig.OnInitSequece) + Player.TaskManager?.LevelTask.TriggerInitAct(task, new SubMissionExcel(), group); - foreach (var task in group.LevelGraphConfig.OnStartSequece) - { - Player.TaskManager?.LevelTask.TriggerStartAct(task, new(), group); - } - } - } - - public void TriggerGroup(int planeId, int floorId, int groupId) - { - GameData.GetFloorInfo(planeId, floorId, out var floor); - if (floor == null) return; - if (floor.Groups.TryGetValue(groupId, out var group)) - { - if (group.LevelGraphConfig == null) return; - foreach (var task in group.LevelGraphConfig.OnInitSequece) - { - Player.TaskManager?.LevelTask.TriggerInitAct(task, new(), group); - } - - foreach (var task in group.LevelGraphConfig.OnStartSequece) - { - Player.TaskManager?.LevelTask.TriggerStartAct(task, new(), group); - } - } + foreach (var task in group.LevelGraphConfig.OnStartSequece) + Player.TaskManager?.LevelTask.TriggerStartAct(task, new SubMissionExcel(), group); } } -} + + public void TriggerGroup(int planeId, int floorId, int groupId) + { + GameData.GetFloorInfo(planeId, floorId, out var floor); + if (floor == null) return; + if (floor.Groups.TryGetValue(groupId, out var group)) + { + if (group.LevelGraphConfig == null) return; + foreach (var task in group.LevelGraphConfig.OnInitSequece) + Player.TaskManager?.LevelTask.TriggerInitAct(task, new SubMissionExcel(), group); + + foreach (var task in group.LevelGraphConfig.OnStartSequece) + Player.TaskManager?.LevelTask.TriggerStartAct(task, new SubMissionExcel(), group); + } + } +} \ No newline at end of file diff --git a/GameServer/Game/Task/TaskManager.cs b/GameServer/Game/Task/TaskManager.cs index 9f99c8d3..7dc966eb 100644 --- a/GameServer/Game/Task/TaskManager.cs +++ b/GameServer/Game/Task/TaskManager.cs @@ -1,19 +1,13 @@ using EggLink.DanhengServer.Game; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Task; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Game.Task +namespace EggLink.DanhengServer.GameServer.Game.Task; + +public class TaskManager(PlayerInstance player) : BasePlayerManager(player) { - public class TaskManager(PlayerInstance player) : BasePlayerManager(player) - { - public PerformanceTrigger PerformanceTrigger { get; } = new(player); - public LevelTask LevelTask { get; } = new(player); - public MissionTaskTrigger MissionTaskTrigger { get; } = new(player); - public SceneTaskTrigger SceneTaskTrigger { get; } = new(player); - } -} + public PerformanceTrigger PerformanceTrigger { get; } = new(player); + public LevelTask LevelTask { get; } = new(player); + public MissionTaskTrigger MissionTaskTrigger { get; } = new(player); + public SceneTaskTrigger SceneTaskTrigger { get; } = new(player); +} \ No newline at end of file diff --git a/GameServer/KcpSharp/ArrayMemoryOwner.cs b/GameServer/KcpSharp/ArrayMemoryOwner.cs index ac3e690d..03291d34 100644 --- a/GameServer/KcpSharp/ArrayMemoryOwner.cs +++ b/GameServer/KcpSharp/ArrayMemoryOwner.cs @@ -2,21 +2,22 @@ using System.Buffers; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class ArrayMemoryOwner : IMemoryOwner { - internal sealed class ArrayMemoryOwner : IMemoryOwner + private readonly byte[] _buffer; + + public ArrayMemoryOwner(byte[] buffer) { - private readonly byte[] _buffer; + _buffer = buffer ?? throw new ArgumentNullException(nameof(buffer)); + } - public ArrayMemoryOwner(byte[] buffer) - { - _buffer = buffer ?? throw new ArgumentNullException(nameof(buffer)); - } + public Memory Memory => _buffer; - public Memory Memory => _buffer; - - public void Dispose() { } + public void Dispose() + { } } -#endif +#endif \ No newline at end of file diff --git a/GameServer/KcpSharp/AsyncAutoResetEvent.cs b/GameServer/KcpSharp/AsyncAutoResetEvent.cs index e882d8f9..49f1675e 100644 --- a/GameServer/KcpSharp/AsyncAutoResetEvent.cs +++ b/GameServer/KcpSharp/AsyncAutoResetEvent.cs @@ -1,117 +1,112 @@ using System.Diagnostics; using System.Threading.Tasks.Sources; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal class AsyncAutoResetEvent : IValueTaskSource { - internal class AsyncAutoResetEvent : IValueTaskSource + private bool _activeWait; + private bool _isSet; + private SpinLock _lock; + private ManualResetValueTaskSourceCore _rvtsc; + private bool _signaled; + + private T? _value; + + public AsyncAutoResetEvent() { - private ManualResetValueTaskSourceCore _rvtsc; - private SpinLock _lock; - private bool _isSet; - private bool _activeWait; - private bool _signaled; - - private T? _value; - - public AsyncAutoResetEvent() + _rvtsc = new ManualResetValueTaskSourceCore { - _rvtsc = new ManualResetValueTaskSourceCore() - { - RunContinuationsAsynchronously = true - }; - _lock = new SpinLock(); + RunContinuationsAsynchronously = true + }; + _lock = new SpinLock(); + } + + T IValueTaskSource.GetResult(short token) + { + try + { + return _rvtsc.GetResult(token); } - - T IValueTaskSource.GetResult(short token) + finally { - try - { - return _rvtsc.GetResult(token); - } - finally - { - _rvtsc.Reset(); + _rvtsc.Reset(); - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); - - _activeWait = false; - _signaled = false; - } - finally - { - if (lockTaken) - { - _lock.Exit(); - } - } - } - } - - ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _rvtsc.GetStatus(token); - void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) - => _rvtsc.OnCompleted(continuation, state, token, flags); - - public ValueTask WaitAsync() - { - bool lockTaken = false; + var lockTaken = false; try { _lock.Enter(ref lockTaken); - if (_activeWait) - { - return new ValueTask(Task.FromException(new InvalidOperationException("Another thread is already waiting."))); - } - if (_isSet) - { - _isSet = false; - T value = _value!; - _value = default; - return new ValueTask(value); - } - - _activeWait = true; - Debug.Assert(!_signaled); - - return new ValueTask(this, _rvtsc.Version); + _activeWait = false; + _signaled = false; } finally { - if (lockTaken) - { - _lock.Exit(); - } - } - } - - public void Set(T value) - { - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); - - if (_activeWait && !_signaled) - { - _signaled = true; - _rvtsc.SetResult(value); - return; - } - - _isSet = true; - _value = value; - } - finally - { - if (lockTaken) - { - _lock.Exit(); - } + if (lockTaken) _lock.Exit(); } } } -} + ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) + { + return _rvtsc.GetStatus(token); + } + + void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, + ValueTaskSourceOnCompletedFlags flags) + { + _rvtsc.OnCompleted(continuation, state, token, flags); + } + + public ValueTask WaitAsync() + { + var lockTaken = false; + try + { + _lock.Enter(ref lockTaken); + + if (_activeWait) + return new ValueTask( + Task.FromException(new InvalidOperationException("Another thread is already waiting."))); + if (_isSet) + { + _isSet = false; + var value = _value!; + _value = default; + return new ValueTask(value); + } + + _activeWait = true; + Debug.Assert(!_signaled); + + return new ValueTask(this, _rvtsc.Version); + } + finally + { + if (lockTaken) _lock.Exit(); + } + } + + public void Set(T value) + { + var lockTaken = false; + try + { + _lock.Enter(ref lockTaken); + + if (_activeWait && !_signaled) + { + _signaled = true; + _rvtsc.SetResult(value); + return; + } + + _isSet = true; + _value = value; + } + finally + { + if (lockTaken) _lock.Exit(); + } + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/DefaultArrayPoolBufferAllocator.cs b/GameServer/KcpSharp/DefaultArrayPoolBufferAllocator.cs index 0707adc8..5a06436a 100644 --- a/GameServer/KcpSharp/DefaultArrayPoolBufferAllocator.cs +++ b/GameServer/KcpSharp/DefaultArrayPoolBufferAllocator.cs @@ -1,13 +1,11 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class DefaultArrayPoolBufferAllocator : IKcpBufferPool { - internal sealed class DefaultArrayPoolBufferAllocator : IKcpBufferPool + public static DefaultArrayPoolBufferAllocator Default { get; } = new(); + + public KcpRentedBuffer Rent(KcpBufferPoolRentOptions options) { - public static DefaultArrayPoolBufferAllocator Default { get; } = new(); - - public KcpRentedBuffer Rent(KcpBufferPoolRentOptions options) - { - return KcpRentedBuffer.FromSharedArrayPool(options.Size); - } + return KcpRentedBuffer.FromSharedArrayPool(options.Size); } - -} +} \ No newline at end of file diff --git a/GameServer/KcpSharp/IKcpBufferPool.cs b/GameServer/KcpSharp/IKcpBufferPool.cs index 953cb94c..44d54476 100644 --- a/GameServer/KcpSharp/IKcpBufferPool.cs +++ b/GameServer/KcpSharp/IKcpBufferPool.cs @@ -1,15 +1,14 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// The buffer pool to rent buffers from. +/// +public interface IKcpBufferPool { /// - /// The buffer pool to rent buffers from. + /// Rent a buffer using the specified options. /// - public interface IKcpBufferPool - { - /// - /// Rent a buffer using the specified options. - /// - /// The options used to rent this buffer. - /// - KcpRentedBuffer Rent(KcpBufferPoolRentOptions options); - } -} + /// The options used to rent this buffer. + /// + KcpRentedBuffer Rent(KcpBufferPoolRentOptions options); +} \ No newline at end of file diff --git a/GameServer/KcpSharp/IKcpConversation.cs b/GameServer/KcpSharp/IKcpConversation.cs index 261b1b3a..b981b467 100644 --- a/GameServer/KcpSharp/IKcpConversation.cs +++ b/GameServer/KcpSharp/IKcpConversation.cs @@ -1,23 +1,25 @@ using System.Net.Sockets; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// A conversation or a channel over the transport. +/// +public interface IKcpConversation : IDisposable { /// - /// A conversation or a channel over the transport. + /// Put message into the receive queue of the channel. /// - public interface IKcpConversation : IDisposable - { - /// - /// Put message into the receive queue of the channel. - /// - /// The packet content with the optional conversation ID. This buffer should not contain space for pre-buffer and post-buffer. - /// The token to cancel this operation. - /// A that completes when the packet is put into the receive queue. - ValueTask InputPakcetAsync(UdpReceiveResult packet, CancellationToken cancellationToken); + /// + /// The packet content with the optional conversation ID. This buffer should not contain space for + /// pre-buffer and post-buffer. + /// + /// The token to cancel this operation. + /// A that completes when the packet is put into the receive queue. + ValueTask InputPakcetAsync(UdpReceiveResult packet, CancellationToken cancellationToken); - /// - /// Mark the underlying transport as closed. Abort all active send or receive operations. - /// - void SetTransportClosed(); - } -} + /// + /// Mark the underlying transport as closed. Abort all active send or receive operations. + /// + void SetTransportClosed(); +} \ No newline at end of file diff --git a/GameServer/KcpSharp/IKcpConversationUpdateNotificationSource.cs b/GameServer/KcpSharp/IKcpConversationUpdateNotificationSource.cs index 880ef8d4..d85e804b 100644 --- a/GameServer/KcpSharp/IKcpConversationUpdateNotificationSource.cs +++ b/GameServer/KcpSharp/IKcpConversationUpdateNotificationSource.cs @@ -1,8 +1,7 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal interface IKcpConversationUpdateNotificationSource { - internal interface IKcpConversationUpdateNotificationSource - { - ReadOnlyMemory Packet { get; } - void Release(); - } -} + ReadOnlyMemory Packet { get; } + void Release(); +} \ No newline at end of file diff --git a/GameServer/KcpSharp/IKcpExceptionProducer.cs b/GameServer/KcpSharp/IKcpExceptionProducer.cs index 79aab8a2..9333dd1a 100644 --- a/GameServer/KcpSharp/IKcpExceptionProducer.cs +++ b/GameServer/KcpSharp/IKcpExceptionProducer.cs @@ -1,16 +1,16 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// An instance that can produce exceptions in background jobs. +/// +/// The type of the instance. +public interface IKcpExceptionProducer { /// - /// An instance that can produce exceptions in background jobs. + /// Set the handler to invoke when exception is thrown. Return true in the handler to ignore the error and continue + /// running. Return false in the handler to abort the operation. /// - /// The type of the instance. - public interface IKcpExceptionProducer - { - /// - /// Set the handler to invoke when exception is thrown. Return true in the handler to ignore the error and continue running. Return false in the handler to abort the operation. - /// - /// The exception handler. - /// The state object to pass into the exception handler. - void SetExceptionHandler(Func handler, object? state); - } -} + /// The exception handler. + /// The state object to pass into the exception handler. + void SetExceptionHandler(Func handler, object? state); +} \ No newline at end of file diff --git a/GameServer/KcpSharp/IKcpMultiplexConnection.cs b/GameServer/KcpSharp/IKcpMultiplexConnection.cs index fe58be96..8ba31986 100644 --- a/GameServer/KcpSharp/IKcpMultiplexConnection.cs +++ b/GameServer/KcpSharp/IKcpMultiplexConnection.cs @@ -1,58 +1,57 @@ -using KcpSharp; -using System.Net; +using System.Net; +using KcpSharp; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Multiplex many channels or conversations over the same transport. +/// +public interface IKcpMultiplexConnection : IDisposable { /// - /// Multiplex many channels or conversations over the same transport. + /// Determine whether the multiplex connection contains a conversation with the specified id. /// - public interface IKcpMultiplexConnection : IDisposable - { - /// - /// Determine whether the multiplex connection contains a conversation with the specified id. - /// - /// The conversation ID. - /// True if the multiplex connection contains the specified conversation. Otherwise false. - bool Contains(long id); + /// The conversation ID. + /// True if the multiplex connection contains the specified conversation. Otherwise false. + bool Contains(long id); - /// - /// Create a raw channel with the specified conversation ID. - /// - /// The conversation ID. - /// The remote endpoint - /// The options of the . - /// The raw channel created. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - KcpRawChannel CreateRawChannel(long id, IPEndPoint remoteEndpoint, KcpRawChannelOptions? options = null); + /// + /// Create a raw channel with the specified conversation ID. + /// + /// The conversation ID. + /// The remote endpoint + /// The options of the . + /// The raw channel created. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + KcpRawChannel CreateRawChannel(long id, IPEndPoint remoteEndpoint, KcpRawChannelOptions? options = null); - /// - /// Create a conversation with the specified conversation ID. - /// - /// The conversation ID. - /// The remote endpoint - /// The options of the . - /// The KCP conversation created. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - KcpConversation CreateConversation(long id, IPEndPoint remoteEndpoint, KcpConversationOptions? options = null); + /// + /// Create a conversation with the specified conversation ID. + /// + /// The conversation ID. + /// The remote endpoint + /// The options of the . + /// The KCP conversation created. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + KcpConversation CreateConversation(long id, IPEndPoint remoteEndpoint, KcpConversationOptions? options = null); - /// - /// Register a conversation or channel with the specified conversation ID and user state. - /// - /// The conversation or channel to register. - /// The conversation ID. - /// is not provided. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - void RegisterConversation(IKcpConversation conversation, long id); + /// + /// Register a conversation or channel with the specified conversation ID and user state. + /// + /// The conversation or channel to register. + /// The conversation ID. + /// is not provided. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + void RegisterConversation(IKcpConversation conversation, long id); - /// - /// Unregister a conversation or channel with the specified conversation ID. - /// - /// The conversation ID. - /// The conversation unregistered. Returns null when the conversation with the specified ID is not found. - IKcpConversation? UnregisterConversation(long id); - } -} + /// + /// Unregister a conversation or channel with the specified conversation ID. + /// + /// The conversation ID. + /// The conversation unregistered. Returns null when the conversation with the specified ID is not found. + IKcpConversation? UnregisterConversation(long id); +} \ No newline at end of file diff --git a/GameServer/KcpSharp/IKcpMultiplexConnectionOfT.cs b/GameServer/KcpSharp/IKcpMultiplexConnectionOfT.cs index d1aa9ea8..f433f68f 100644 --- a/GameServer/KcpSharp/IKcpMultiplexConnectionOfT.cs +++ b/GameServer/KcpSharp/IKcpMultiplexConnectionOfT.cs @@ -1,54 +1,57 @@ -using KcpSharp; -using System.Net; +using System.Net; +using KcpSharp; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Multiplex many channels or conversations over the same transport. +/// +public interface IKcpMultiplexConnection : IKcpMultiplexConnection { /// - /// Multiplex many channels or conversations over the same transport. + /// Create a raw channel with the specified conversation ID. /// - public interface IKcpMultiplexConnection : IKcpMultiplexConnection - { - /// - /// Create a raw channel with the specified conversation ID. - /// - /// The conversation ID. - /// The remote Endpoint - /// The user state of this channel. - /// The options of the . - /// The raw channel created. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - KcpRawChannel CreateRawChannel(long id, IPEndPoint remoteEndpoint, T state, KcpRawChannelOptions? options = null); + /// The conversation ID. + /// The remote Endpoint + /// The user state of this channel. + /// The options of the . + /// The raw channel created. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + KcpRawChannel CreateRawChannel(long id, IPEndPoint remoteEndpoint, T state, KcpRawChannelOptions? options = null); - /// - /// Create a conversation with the specified conversation ID. - /// - /// The conversation ID. - /// The remote Endpoint - /// The user state of this conversation. - /// The options of the . - /// The KCP conversation created. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - KcpConversation CreateConversation(long id, IPEndPoint remoteEndpoint, T state, KcpConversationOptions? options = null); + /// + /// Create a conversation with the specified conversation ID. + /// + /// The conversation ID. + /// The remote Endpoint + /// The user state of this conversation. + /// The options of the . + /// The KCP conversation created. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + KcpConversation CreateConversation(long id, IPEndPoint remoteEndpoint, T state, + KcpConversationOptions? options = null); - /// - /// Register a conversation or channel with the specified conversation ID and user state. - /// - /// The conversation or channel to register. - /// The conversation ID. - /// The user state - /// is not provided. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - void RegisterConversation(IKcpConversation conversation, long id, T? state); + /// + /// Register a conversation or channel with the specified conversation ID and user state. + /// + /// The conversation or channel to register. + /// The conversation ID. + /// The user state + /// is not provided. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + void RegisterConversation(IKcpConversation conversation, long id, T? state); - /// - /// Unregister a conversation or channel with the specified conversation ID. - /// - /// The conversation ID. - /// The user state. - /// The conversation unregistered with the user state. Returns default when the conversation with the specified ID is not found. - IKcpConversation? UnregisterConversation(long id, out T? state); - } -} + /// + /// Unregister a conversation or channel with the specified conversation ID. + /// + /// The conversation ID. + /// The user state. + /// + /// The conversation unregistered with the user state. Returns default when the conversation with the specified ID + /// is not found. + /// + IKcpConversation? UnregisterConversation(long id, out T? state); +} \ No newline at end of file diff --git a/GameServer/KcpSharp/IKcpTransport.cs b/GameServer/KcpSharp/IKcpTransport.cs index fe14bc25..52ff8ca0 100644 --- a/GameServer/KcpSharp/IKcpTransport.cs +++ b/GameServer/KcpSharp/IKcpTransport.cs @@ -1,19 +1,18 @@ using System.Net; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// A transport to send and receive packets. +/// +public interface IKcpTransport { /// - /// A transport to send and receive packets. + /// Send a packet into the transport. /// - public interface IKcpTransport - { - /// - /// Send a packet into the transport. - /// - /// The content of the packet. - /// The remote endpoint - /// A token to cancel this operation. - /// A that completes when the packet is sent. - ValueTask SendPacketAsync(Memory packet, IPEndPoint remoteEndpoint, CancellationToken cancellationToken); - } -} + /// The content of the packet. + /// The remote endpoint + /// A token to cancel this operation. + /// A that completes when the packet is sent. + ValueTask SendPacketAsync(Memory packet, IPEndPoint remoteEndpoint, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/GameServer/KcpSharp/IKcpTransportOfT.cs b/GameServer/KcpSharp/IKcpTransportOfT.cs index 6efdf80d..86902d6d 100644 --- a/GameServer/KcpSharp/IKcpTransportOfT.cs +++ b/GameServer/KcpSharp/IKcpTransportOfT.cs @@ -1,22 +1,22 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// A transport instance for upper-level connections. +/// +/// The type of the upper-level connection. +public interface IKcpTransport : IKcpTransport, IKcpExceptionProducer>, IDisposable { /// - /// A transport instance for upper-level connections. + /// Get the upper-level connection instace. If Start is not called or the transport is closed, + /// will be thrown. /// - /// The type of the upper-level connection. - public interface IKcpTransport : IKcpTransport, IKcpExceptionProducer>, IDisposable - { - /// - /// Get the upper-level connection instace. If Start is not called or the transport is closed, will be thrown. - /// - /// Start is not called or the transport is closed. - T Connection { get; } + /// Start is not called or the transport is closed. + T Connection { get; } - /// - /// Create the upper-level connection and start pumping packets from the socket to the upper-level connection. - /// - /// The current instance is disposed. - /// has been called before. - void Start(); - } -} + /// + /// Create the upper-level connection and start pumping packets from the socket to the upper-level connection. + /// + /// The current instance is disposed. + /// has been called before. + void Start(); +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpAcknowledgeList.cs b/GameServer/KcpSharp/KcpAcknowledgeList.cs index bd7093f6..8fb89d1e 100644 --- a/GameServer/KcpSharp/KcpAcknowledgeList.cs +++ b/GameServer/KcpSharp/KcpAcknowledgeList.cs @@ -1,104 +1,93 @@ using System.Runtime.CompilerServices; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class KcpAcknowledgeList { - internal sealed class KcpAcknowledgeList + private readonly KcpSendQueue _sendQueue; + private (uint SerialNumber, uint Timestamp)[] _array; + private int _count; + private SpinLock _lock; + + public KcpAcknowledgeList(KcpSendQueue sendQueue, int windowSize) { - private readonly KcpSendQueue _sendQueue; - private (uint SerialNumber, uint Timestamp)[] _array; - private int _count; - private SpinLock _lock; + _array = new (uint SerialNumber, uint Timestamp)[windowSize]; + _count = 0; + _lock = new SpinLock(); + _sendQueue = sendQueue; + } - public KcpAcknowledgeList(KcpSendQueue sendQueue, int windowSize) + public bool TryGetAt(int index, out uint serialNumber, out uint timestamp) + { + var lockTaken = false; + try { - _array = new (uint SerialNumber, uint Timestamp)[windowSize]; - _count = 0; - _lock = new SpinLock(); - _sendQueue = sendQueue; + _lock.Enter(ref lockTaken); + + if ((uint)index >= (uint)_count) + { + serialNumber = default; + timestamp = default; + return false; + } + + (serialNumber, timestamp) = _array[index]; + return true; } - - public bool TryGetAt(int index, out uint serialNumber, out uint timestamp) + finally { - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); - - if ((uint)index >= (uint)_count) - { - serialNumber = default; - timestamp = default; - return false; - } - - (serialNumber, timestamp) = _array[index]; - return true; - } - finally - { - if (lockTaken) - { - _lock.Exit(); - } - } - } - - public void Clear() - { - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); - - _count = 0; - } - finally - { - if (lockTaken) - { - _lock.Exit(); - } - } - _sendQueue.NotifyAckListChanged(false); - } - - public void Add(uint serialNumber, uint timestamp) - { - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); - - EnsureCapacity(); - _array[_count++] = (serialNumber, timestamp); - } - finally - { - if (lockTaken) - { - _lock.Exit(); - } - } - _sendQueue.NotifyAckListChanged(true); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void EnsureCapacity() - { - if (_count == _array.Length) - { - Expand(); - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private void Expand() - { - int capacity = _count + 1; - capacity = Math.Max(capacity + capacity / 2, 16); - (uint SerialNumber, uint Timestamp)[]? newArray = new (uint SerialNumber, uint Timestamp)[capacity]; - _array.AsSpan(0, _count).CopyTo(newArray); - _array = newArray; + if (lockTaken) _lock.Exit(); } } -} + + public void Clear() + { + var lockTaken = false; + try + { + _lock.Enter(ref lockTaken); + + _count = 0; + } + finally + { + if (lockTaken) _lock.Exit(); + } + + _sendQueue.NotifyAckListChanged(false); + } + + public void Add(uint serialNumber, uint timestamp) + { + var lockTaken = false; + try + { + _lock.Enter(ref lockTaken); + + EnsureCapacity(); + _array[_count++] = (serialNumber, timestamp); + } + finally + { + if (lockTaken) _lock.Exit(); + } + + _sendQueue.NotifyAckListChanged(true); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EnsureCapacity() + { + if (_count == _array.Length) Expand(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void Expand() + { + var capacity = _count + 1; + capacity = Math.Max(capacity + capacity / 2, 16); + var newArray = new (uint SerialNumber, uint Timestamp)[capacity]; + _array.AsSpan(0, _count).CopyTo(newArray); + _array = newArray; + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpBuffer.cs b/GameServer/KcpSharp/KcpBuffer.cs index bc002a8f..74cf5dcd 100644 --- a/GameServer/KcpSharp/KcpBuffer.cs +++ b/GameServer/KcpSharp/KcpBuffer.cs @@ -1,59 +1,51 @@ using System.Diagnostics; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal readonly struct KcpBuffer { - internal readonly struct KcpBuffer + private readonly object? _owner; + private readonly Memory _memory; + + public ReadOnlyMemory DataRegion => _memory.Slice(0, Length); + + public int Length { get; } + + private KcpBuffer(object? owner, Memory memory, int length) { - private readonly object? _owner; - private readonly Memory _memory; - private readonly int _length; - - public ReadOnlyMemory DataRegion => _memory.Slice(0, _length); - - public int Length => _length; - - private KcpBuffer(object? owner, Memory memory, int length) - { - _owner = owner; - _memory = memory; - _length = length; - } - - public static KcpBuffer CreateFromSpan(KcpRentedBuffer buffer, ReadOnlySpan dataSource) - { - Memory memory = buffer.Memory; - if (dataSource.Length > memory.Length) - { - ThrowRentedBufferTooSmall(); - } - dataSource.CopyTo(memory.Span); - return new KcpBuffer(buffer.Owner, memory, dataSource.Length); - } - - public KcpBuffer AppendData(ReadOnlySpan data) - { - if (_length + data.Length > _memory.Length) - { - ThrowRentedBufferTooSmall(); - } - data.CopyTo(_memory.Span.Slice(_length)); - return new KcpBuffer(_owner, _memory, _length + data.Length); - } - - public KcpBuffer Consume(int length) - { - Debug.Assert((uint)length <= (uint)_length); - return new KcpBuffer(_owner, _memory.Slice(length), _length - length); - } - - public void Release() - { - new KcpRentedBuffer(_owner, _memory).Dispose(); - } - - private static void ThrowRentedBufferTooSmall() - { - throw new InvalidOperationException("The rented buffer is not large enough to hold the data."); - } + _owner = owner; + _memory = memory; + Length = length; } -} + + public static KcpBuffer CreateFromSpan(KcpRentedBuffer buffer, ReadOnlySpan dataSource) + { + var memory = buffer.Memory; + if (dataSource.Length > memory.Length) ThrowRentedBufferTooSmall(); + dataSource.CopyTo(memory.Span); + return new KcpBuffer(buffer.Owner, memory, dataSource.Length); + } + + public KcpBuffer AppendData(ReadOnlySpan data) + { + if (Length + data.Length > _memory.Length) ThrowRentedBufferTooSmall(); + data.CopyTo(_memory.Span.Slice(Length)); + return new KcpBuffer(_owner, _memory, Length + data.Length); + } + + public KcpBuffer Consume(int length) + { + Debug.Assert((uint)length <= (uint)Length); + return new KcpBuffer(_owner, _memory.Slice(length), Length - length); + } + + public void Release() + { + new KcpRentedBuffer(_owner, _memory).Dispose(); + } + + private static void ThrowRentedBufferTooSmall() + { + throw new InvalidOperationException("The rented buffer is not large enough to hold the data."); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpBufferPoolRentOptions.cs b/GameServer/KcpSharp/KcpBufferPoolRentOptions.cs index 9fa89dfd..5cdf95a9 100644 --- a/GameServer/KcpSharp/KcpBufferPoolRentOptions.cs +++ b/GameServer/KcpSharp/KcpBufferPoolRentOptions.cs @@ -1,41 +1,50 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// The options to use when renting buffers from the pool. +/// +public readonly struct KcpBufferPoolRentOptions : IEquatable { /// - /// The options to use when renting buffers from the pool. + /// The minimum size of the buffer. /// - public readonly struct KcpBufferPoolRentOptions : IEquatable + public int Size { get; } + + /// + /// True if the buffer may be passed to the outside of KcpSharp. False if the buffer is only used internally in + /// KcpSharp. + /// + public bool IsOutbound { get; } + + /// + /// Create a with the specified parameters. + /// + /// The minimum size of the buffer. + /// + /// True if the buffer may be passed to the outside of KcpSharp. False if the buffer is only used + /// internally in KcpSharp. + /// + public KcpBufferPoolRentOptions(int size, bool isOutbound) { - private readonly int _size; - private readonly bool _isOutbound; - - /// - /// The minimum size of the buffer. - /// - public int Size => _size; - - /// - /// True if the buffer may be passed to the outside of KcpSharp. False if the buffer is only used internally in KcpSharp. - /// - public bool IsOutbound => _isOutbound; - - /// - /// Create a with the specified parameters. - /// - /// The minimum size of the buffer. - /// True if the buffer may be passed to the outside of KcpSharp. False if the buffer is only used internally in KcpSharp. - public KcpBufferPoolRentOptions(int size, bool isOutbound) - { - _size = size; - _isOutbound = isOutbound; - } - - /// - public bool Equals(KcpBufferPoolRentOptions other) => _size == other._size && _isOutbound == other.IsOutbound; - - /// - public override bool Equals(object? obj) => obj is KcpBufferPoolRentOptions other && Equals(other); - - /// - public override int GetHashCode() => HashCode.Combine(_size, _isOutbound); + Size = size; + IsOutbound = isOutbound; } -} + + /// + public bool Equals(KcpBufferPoolRentOptions other) + { + return Size == other.Size && IsOutbound == other.IsOutbound; + } + + /// + public override bool Equals(object? obj) + { + return obj is KcpBufferPoolRentOptions other && Equals(other); + } + + /// + public override int GetHashCode() + { + return HashCode.Combine(Size, IsOutbound); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpCommand.cs b/GameServer/KcpSharp/KcpCommand.cs index 2e8d8c5b..dce15e47 100644 --- a/GameServer/KcpSharp/KcpCommand.cs +++ b/GameServer/KcpSharp/KcpCommand.cs @@ -1,10 +1,9 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal enum KcpCommand : byte { - internal enum KcpCommand : byte - { - Push = 81, - Ack = 82, - WindowProbe = 83, - WindowSize = 84 - } -} + Push = 81, + Ack = 82, + WindowProbe = 83, + WindowSize = 84 +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpConversation.FlushAsyncMethodBuilder.cs b/GameServer/KcpSharp/KcpConversation.FlushAsyncMethodBuilder.cs index 21dd5eb3..e0089484 100644 --- a/GameServer/KcpSharp/KcpConversation.FlushAsyncMethodBuilder.cs +++ b/GameServer/KcpSharp/KcpConversation.FlushAsyncMethodBuilder.cs @@ -4,272 +4,269 @@ using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Threading.Tasks.Sources; -namespace KcpSharp +namespace KcpSharp; + +partial class KcpConversation { - partial class KcpConversation - { #if NET6_0_OR_GREATER - [ThreadStatic] - private static KcpConversation? s_currentObject; - private object? _flushStateMachine; + [ThreadStatic] private static KcpConversation? s_currentObject; - private struct KcpFlushAsyncMethodBuilder + private object? _flushStateMachine; + + private struct KcpFlushAsyncMethodBuilder + { + private readonly KcpConversation _conversation; + private StateMachineBox? _task; + + private static readonly StateMachineBox s_syncSuccessSentinel = new SyncSuccessSentinelStateMachineBox(); + + public KcpFlushAsyncMethodBuilder(KcpConversation conversation) { - private readonly KcpConversation _conversation; - private StateMachineBox? _task; + _conversation = conversation; + _task = null; + } - private static readonly StateMachineBox s_syncSuccessSentinel = new SyncSuccessSentinelStateMachineBox(); + public static KcpFlushAsyncMethodBuilder Create() + { + var conversation = s_currentObject; + Debug.Assert(conversation is not null); + s_currentObject = null; - public KcpFlushAsyncMethodBuilder(KcpConversation conversation) - { - _conversation = conversation; - _task = null; - } - - public static KcpFlushAsyncMethodBuilder Create() - { - KcpConversation? conversation = s_currentObject; - Debug.Assert(conversation is not null); - s_currentObject = null; - - return new KcpFlushAsyncMethodBuilder(conversation); - } + return new KcpFlushAsyncMethodBuilder(conversation); + } #pragma warning disable CA1822 // Mark members as static - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Start(ref TStateMachine stateMachine) - where TStateMachine : IAsyncStateMachine + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Start(ref TStateMachine stateMachine) + where TStateMachine : IAsyncStateMachine #pragma warning restore CA1822 // Mark members as static - { - Debug.Assert(stateMachine is not null); + { + Debug.Assert(stateMachine is not null); - stateMachine.MoveNext(); + stateMachine.MoveNext(); + } + + public ValueTask Task + { + get + { + if (ReferenceEquals(_task, s_syncSuccessSentinel)) return default; + var stateMachineBox = _task ??= CreateWeaklyTypedStateMachineBox(); + return new ValueTask(stateMachineBox, stateMachineBox.Version); } + } - public ValueTask Task +#pragma warning disable CA1822 // Mark members as static + public void SetStateMachine(IAsyncStateMachine stateMachine) +#pragma warning restore CA1822 // Mark members as static + { + Debug.Fail("SetStateMachine should not be used."); + } + + public void SetResult() + { + if (_task == null) + _task = s_syncSuccessSentinel; + else + _task.SetResult(); + } + + public void SetException(Exception exception) + { + SetException(exception, ref _task); + } + + private static void SetException(Exception exception, ref StateMachineBox? boxFieldRef) + { + if (exception == null) throw new ArgumentNullException(nameof(exception)); + (boxFieldRef ??= CreateWeaklyTypedStateMachineBox()).SetException(exception); + } + + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : INotifyCompletion + where TStateMachine : IAsyncStateMachine + { + AwaitOnCompleted(ref awaiter, ref stateMachine, ref _task, _conversation); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, + ref TStateMachine stateMachine) + where TAwaiter : ICriticalNotifyCompletion + where TStateMachine : IAsyncStateMachine + { + AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref _task, _conversation); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, + ref TStateMachine stateMachine, ref StateMachineBox? boxRef, KcpConversation conversation) + where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine + { + var stateMachineBox = GetStateMachineBox(ref stateMachine, ref boxRef, conversation); + AwaitUnsafeOnCompleted(ref awaiter, stateMachineBox); + } + + private static void AwaitOnCompleted(ref TAwaiter awaiter, + ref TStateMachine stateMachine, ref StateMachineBox? box, KcpConversation conversation) + where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine + { + try { - get + awaiter.OnCompleted(GetStateMachineBox(ref stateMachine, ref box, conversation).MoveNextAction); + } + catch (Exception exception) + { + var edi = ExceptionDispatchInfo.Capture(exception); + ThreadPool.QueueUserWorkItem(static state => ((ExceptionDispatchInfo)state!).Throw(), edi); + } + } + + private static void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, StateMachineBox box) + where TAwaiter : ICriticalNotifyCompletion + { + try + { + awaiter.UnsafeOnCompleted(box.MoveNextAction); + } + catch (Exception exception) + { + var edi = ExceptionDispatchInfo.Capture(exception); + ThreadPool.QueueUserWorkItem(static state => ((ExceptionDispatchInfo)state!).Throw(), edi); + } + } + + + private static StateMachineBox CreateWeaklyTypedStateMachineBox() + { + return new StateMachineBox(null); + } + + private static StateMachineBox GetStateMachineBox(ref TStateMachine stateMachine, + ref StateMachineBox? boxFieldRef, KcpConversation conversation) where TStateMachine : IAsyncStateMachine + { + var stateMachineBox = boxFieldRef as StateMachineBox; + if (stateMachineBox != null) return stateMachineBox; + var stateMachineBox2 = boxFieldRef as StateMachineBox; + if (stateMachineBox2 != null) + { + if (stateMachineBox2.StateMachine == null) { - if (ReferenceEquals(_task, s_syncSuccessSentinel)) - { - return default; - } - StateMachineBox stateMachineBox = _task ??= CreateWeaklyTypedStateMachineBox(); - return new ValueTask(stateMachineBox, stateMachineBox.Version); + Debugger.NotifyOfCrossThreadDependency(); + stateMachineBox2.StateMachine = stateMachine; } + + return stateMachineBox2; } -#pragma warning disable CA1822 // Mark members as static - public void SetStateMachine(IAsyncStateMachine stateMachine) -#pragma warning restore CA1822 // Mark members as static + Debugger.NotifyOfCrossThreadDependency(); + var stateMachineBox3 = + (StateMachineBox)(boxFieldRef = + StateMachineBox.GetOrCreateBox(conversation)); + stateMachineBox3.StateMachine = stateMachine; + return stateMachineBox3; + } + + private abstract class StateMachineBox : IValueTaskSource + { + protected Action? _moveNextAction; + protected ManualResetValueTaskSourceCore _mrvtsc; + + public virtual Action MoveNextAction => _moveNextAction!; + + public short Version => _mrvtsc.Version; + + public ValueTaskSourceStatus GetStatus(short token) { - Debug.Fail("SetStateMachine should not be used."); + return _mrvtsc.GetStatus(token); + } + + public void OnCompleted(Action continuation, object? state, short token, + ValueTaskSourceOnCompletedFlags flags) + { + _mrvtsc.OnCompleted(continuation, state, token, flags); + } + + void IValueTaskSource.GetResult(short token) + { + throw new NotSupportedException(); } public void SetResult() { - if (_task == null) - { - _task = s_syncSuccessSentinel; - } - else - { - _task.SetResult(); - } + _mrvtsc.SetResult(true); } - public void SetException(Exception exception) + public void SetException(Exception error) { - SetException(exception, ref _task); + _mrvtsc.SetException(error); } + } - private static void SetException(Exception exception, ref StateMachineBox? boxFieldRef) + private sealed class SyncSuccessSentinelStateMachineBox : StateMachineBox + { + public SyncSuccessSentinelStateMachineBox() { - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } - (boxFieldRef ??= CreateWeaklyTypedStateMachineBox()).SetException(exception); + SetResult(); } + } - public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : INotifyCompletion - where TStateMachine : IAsyncStateMachine + + private sealed class StateMachineBox : StateMachineBox, IValueTaskSource + where TStateMachine : IAsyncStateMachine + { + private KcpConversation? _conversation; + + [MaybeNull] public TStateMachine StateMachine; + + internal StateMachineBox(KcpConversation? conversation) { - AwaitOnCompleted(ref awaiter, ref stateMachine, ref _task, _conversation); + _conversation = conversation; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : ICriticalNotifyCompletion - where TStateMachine : IAsyncStateMachine - { - AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref _task, _conversation); - } + public override Action MoveNextAction => _moveNextAction ??= MoveNext; - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine, ref StateMachineBox? boxRef, KcpConversation conversation) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine - { - StateMachineBox stateMachineBox = GetStateMachineBox(ref stateMachine, ref boxRef, conversation); - AwaitUnsafeOnCompleted(ref awaiter, stateMachineBox); - } - - private static void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine, ref StateMachineBox? box, KcpConversation conversation) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine + void IValueTaskSource.GetResult(short token) { try { - awaiter.OnCompleted(GetStateMachineBox(ref stateMachine, ref box, conversation).MoveNextAction); + _mrvtsc.GetResult(token); } - catch (Exception exception) + finally { - ExceptionDispatchInfo? edi = ExceptionDispatchInfo.Capture(exception); - ThreadPool.QueueUserWorkItem(static state => ((ExceptionDispatchInfo)state!).Throw(), edi); + ReturnOrDropBox(); } } - private static void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, StateMachineBox box) where TAwaiter : ICriticalNotifyCompletion + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static StateMachineBox GetOrCreateBox(KcpConversation conversation) { - try + if (conversation._flushStateMachine is StateMachineBox stateMachine) { - awaiter.UnsafeOnCompleted(box.MoveNextAction); - } - catch (Exception exception) - { - ExceptionDispatchInfo? edi = ExceptionDispatchInfo.Capture(exception); - ThreadPool.QueueUserWorkItem(static state => ((ExceptionDispatchInfo)state!).Throw(), edi); + stateMachine._conversation = conversation; + conversation._flushStateMachine = null; + return stateMachine; } + + return new StateMachineBox(conversation); } - - private static StateMachineBox CreateWeaklyTypedStateMachineBox() + public void MoveNext() { - return new StateMachineBox(null); + if (StateMachine is not null) StateMachine.MoveNext(); } - private static StateMachineBox GetStateMachineBox(ref TStateMachine stateMachine, ref StateMachineBox? boxFieldRef, KcpConversation conversation) where TStateMachine : IAsyncStateMachine + private void ReturnOrDropBox() { - StateMachineBox? stateMachineBox = boxFieldRef as StateMachineBox; - if (stateMachineBox != null) + StateMachine = default!; + _mrvtsc.Reset(); + if (_conversation is not null) { - return stateMachineBox; - } - StateMachineBox? stateMachineBox2 = boxFieldRef as StateMachineBox; - if (stateMachineBox2 != null) - { - if (stateMachineBox2.StateMachine == null) - { - Debugger.NotifyOfCrossThreadDependency(); - stateMachineBox2.StateMachine = stateMachine; - } - return stateMachineBox2; - } - Debugger.NotifyOfCrossThreadDependency(); - StateMachineBox stateMachineBox3 = (StateMachineBox)(boxFieldRef = StateMachineBox.GetOrCreateBox(conversation)); - stateMachineBox3.StateMachine = stateMachine; - return stateMachineBox3; - } - - private abstract class StateMachineBox : IValueTaskSource - { - protected ManualResetValueTaskSourceCore _mrvtsc; - protected Action? _moveNextAction; - - public virtual Action MoveNextAction => _moveNextAction!; - - public short Version => _mrvtsc.Version; - - public void SetResult() - { - _mrvtsc.SetResult(true); - } - - public void SetException(Exception error) - { - _mrvtsc.SetException(error); - } - - public ValueTaskSourceStatus GetStatus(short token) - { - return _mrvtsc.GetStatus(token); - } - - public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) - { - _mrvtsc.OnCompleted(continuation, state, token, flags); - } - - void IValueTaskSource.GetResult(short token) - { - throw new NotSupportedException(); - } - } - - private sealed class SyncSuccessSentinelStateMachineBox : StateMachineBox - { - public SyncSuccessSentinelStateMachineBox() - { - SetResult(); - } - } - - - private sealed class StateMachineBox : StateMachineBox, IValueTaskSource where TStateMachine : IAsyncStateMachine - { - [MaybeNull] - public TStateMachine StateMachine; - private KcpConversation? _conversation; - - public override Action MoveNextAction => _moveNextAction ??= MoveNext; - - internal StateMachineBox(KcpConversation? conversation) - { - _conversation = conversation; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static StateMachineBox GetOrCreateBox(KcpConversation conversation) - { - if (conversation._flushStateMachine is StateMachineBox stateMachine) - { - stateMachine._conversation = conversation; - conversation._flushStateMachine = null; - return stateMachine; - } - return new StateMachineBox(conversation); - } - - void IValueTaskSource.GetResult(short token) - { - try - { - _mrvtsc.GetResult(token); - } - finally - { - ReturnOrDropBox(); - } - } - - public void MoveNext() - { - if (StateMachine is not null) - { - StateMachine.MoveNext(); - } - } - - private void ReturnOrDropBox() - { - StateMachine = default!; - _mrvtsc.Reset(); - if (_conversation is not null) - { - _conversation._flushStateMachine = this; - _conversation = null; - } + _conversation._flushStateMachine = this; + _conversation = null; } } } -#endif } -} +#endif +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpConversation.cs b/GameServer/KcpSharp/KcpConversation.cs index a6fe7ef0..ebe8eb9e 100644 --- a/GameServer/KcpSharp/KcpConversation.cs +++ b/GameServer/KcpSharp/KcpConversation.cs @@ -1,343 +1,426 @@ -using System.Buffers.Binary; -using System.Runtime.CompilerServices; -using System.Net; -using System.Net.Sockets; -using EggLink.DanhengServer.Util; -using EggLink.DanhengServer.KcpSharp; - - - -#if NEED_LINKEDLIST_SHIM +#if NEED_LINKEDLIST_SHIM using LinkedListOfBufferItem = KcpSharp.NetstandardShim.LinkedList; using LinkedListNodeOfBufferItem = KcpSharp.NetstandardShim.LinkedListNode; #else -using LinkedListOfBufferItem = System.Collections.Generic.LinkedList; -using LinkedListNodeOfBufferItem = System.Collections.Generic.LinkedListNode; +using LinkedListOfBufferItem = + System.Collections.Generic.LinkedList; +using LinkedListNodeOfBufferItem = + System.Collections.Generic.LinkedListNode; #endif +using System.Buffers.Binary; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using EggLink.DanhengServer.KcpSharp; +using EggLink.DanhengServer.Util; -namespace KcpSharp +namespace KcpSharp; + +/// +/// A reliable channel over an unreliable transport implemented in KCP protocol. +/// +public sealed partial class KcpConversation : IKcpConversation, IKcpExceptionProducer { + private readonly IKcpBufferPool _bufferPool; + private readonly IKcpTransport _transport; + private readonly IPEndPoint _remoteEndPoint; + private readonly ulong? _id; + + private readonly int _mtu; + private readonly int _mss; + private readonly int _preBufferSize; + private readonly int _postBufferSize; + + private uint _snd_una; + private uint _snd_nxt; + private uint _rcv_nxt; + + private uint _ssthresh; + + private int _rx_rttval; + private int _rx_srtt; + private uint _rx_rto; + private readonly uint _rx_minrto; + + private readonly uint _snd_wnd; + private readonly uint _rcv_wnd; + private uint _rmt_wnd; + private uint _cwnd; + private KcpProbeType _probe; + private SpinLock _cwndUpdateLock; + + private readonly uint _interval; + private uint _ts_flush; + + private readonly bool _nodelay; + private uint _ts_probe; + private uint _probe_wait; + + private uint _incr; + + private readonly KcpSendReceiveQueueItemCache _queueItemCache; + private readonly KcpSendQueue _sendQueue; + private readonly KcpReceiveQueue _receiveQueue; + + private readonly LinkedListOfBufferItem _sndBuf = new(); + private readonly LinkedListOfBufferItem _rcvBuf = new(); + private KcpSendReceiveBufferItemCache _cache = KcpSendReceiveBufferItemCache.Create(); + + private readonly KcpAcknowledgeList _ackList; + + private readonly int _fastresend; + private readonly int _fastlimit; + private readonly bool _nocwnd; + + private readonly bool _keepAliveEnabled; + private readonly uint _keepAliveInterval; + private readonly uint _keepAliveGracePeriod; + private uint _lastReceiveTick; + private uint _lastSendTick; + + private readonly KcpReceiveWindowNotificationOptions? _receiveWindowNotificationOptions; + private uint _ts_rcv_notify; + private uint _ts_rcv_notify_wait; + + private KcpConversationUpdateActivation? _updateActivation; + private CancellationTokenSource? _updateLoopCts; + private bool _disposed; + + private Func? _exceptionHandler; + private object? _exceptionHandlerState; + + private const uint IKCP_RTO_MAX = 60000; + private const int IKCP_THRESH_MIN = 2; + private const uint IKCP_PROBE_INIT = 7000; // 7 secs to probe window size + private const uint IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window + /// - /// A reliable channel over an unreliable transport implemented in KCP protocol. + /// Construct a reliable channel using KCP protocol. /// - public sealed partial class KcpConversation : IKcpConversation, IKcpExceptionProducer + /// The remote endpoint + /// The underlying transport. + /// The options of the . + public KcpConversation(IPEndPoint remoteEndpoint, IKcpTransport transport, KcpConversationOptions? options) + : this(remoteEndpoint, transport, null, options) { - private readonly IKcpBufferPool _bufferPool; - private readonly IKcpTransport _transport; - private readonly IPEndPoint _remoteEndPoint; - private readonly ulong? _id; + } - private readonly int _mtu; - private readonly int _mss; - private readonly int _preBufferSize; - private readonly int _postBufferSize; + /// + /// Construct a reliable channel using KCP protocol. + /// + /// The remote endpoint + /// The underlying transport. + /// The conversation ID. + /// The options of the . + public KcpConversation(IPEndPoint remoteEndpoint, IKcpTransport transport, long conversationId, + KcpConversationOptions? options) + : this(remoteEndpoint, transport, (ulong)conversationId, options) + { + } - private uint _snd_una; - private uint _snd_nxt; - private uint _rcv_nxt; + private KcpConversation(IPEndPoint remoteEndpoint, IKcpTransport transport, ulong? conversationId, + KcpConversationOptions? options) + { + _bufferPool = options?.BufferPool ?? DefaultArrayPoolBufferAllocator.Default; + _transport = transport; + _remoteEndPoint = remoteEndpoint; + _id = conversationId; - private uint _ssthresh; + if (options is null) + _mtu = KcpConversationOptions.MtuDefaultValue; + else if (options.Mtu < 50) + throw new ArgumentException("MTU must be at least 50.", nameof(options)); + else + _mtu = options.Mtu; - private int _rx_rttval; - private int _rx_srtt; - private uint _rx_rto; - private uint _rx_minrto; + _preBufferSize = options?.PreBufferSize ?? 0; + _postBufferSize = options?.PostBufferSize ?? 0; + if (_preBufferSize < 0) + throw new ArgumentException("PreBufferSize must be a non-negative integer.", nameof(options)); + if (_postBufferSize < 0) + throw new ArgumentException("PostBufferSize must be a non-negative integer.", nameof(options)); + if ((uint)(_preBufferSize + _postBufferSize) >= (uint)(_mtu - KcpGlobalVars.HEADER_LENGTH_WITHOUT_CONVID)) + throw new ArgumentException( + "The sum of PreBufferSize and PostBufferSize is too large. There is not enough space in the packet for the KCP header.", + nameof(options)); + if (conversationId.HasValue && (uint)(_preBufferSize + _postBufferSize) >= + (uint)(_mtu - KcpGlobalVars.HEADER_LENGTH_WITH_CONVID)) + throw new ArgumentException( + "The sum of PreBufferSize and PostBufferSize is too large. There is not enough space in the packet for the KCP header.", + nameof(options)); - private uint _snd_wnd; - private uint _rcv_wnd; - private uint _rmt_wnd; - private uint _cwnd; - private KcpProbeType _probe; - private SpinLock _cwndUpdateLock; + _mss = conversationId.HasValue + ? _mtu - KcpGlobalVars.HEADER_LENGTH_WITH_CONVID + : _mtu - KcpGlobalVars.HEADER_LENGTH_WITHOUT_CONVID; + _mss = _mss - _preBufferSize - _postBufferSize; - private uint _interval; - private uint _ts_flush; + _ssthresh = 2; - private bool _nodelay; - private uint _ts_probe; - private uint _probe_wait; - - private uint _incr; - - private readonly KcpSendReceiveQueueItemCache _queueItemCache; - private readonly KcpSendQueue _sendQueue; - private readonly KcpReceiveQueue _receiveQueue; - - private readonly LinkedListOfBufferItem _sndBuf = new(); - private readonly LinkedListOfBufferItem _rcvBuf = new(); - private KcpSendReceiveBufferItemCache _cache = KcpSendReceiveBufferItemCache.Create(); - - private readonly KcpAcknowledgeList _ackList; - - private int _fastresend; - private int _fastlimit; - private bool _nocwnd; - private bool _stream; - - private bool _keepAliveEnabled; - private uint _keepAliveInterval; - private uint _keepAliveGracePeriod; - private uint _lastReceiveTick; - private uint _lastSendTick; - - private KcpReceiveWindowNotificationOptions? _receiveWindowNotificationOptions; - private uint _ts_rcv_notify; - private uint _ts_rcv_notify_wait; - - private KcpConversationUpdateActivation? _updateActivation; - private CancellationTokenSource? _updateLoopCts; - private bool _transportClosed; - private bool _disposed; - - private Func? _exceptionHandler; - private object? _exceptionHandlerState; - - private const uint IKCP_RTO_MAX = 60000; - private const int IKCP_THRESH_MIN = 2; - private const uint IKCP_PROBE_INIT = 7000; // 7 secs to probe window size - private const uint IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window - - /// - /// Construct a reliable channel using KCP protocol. - /// - /// The remote endpoint - /// The underlying transport. - /// The options of the . - public KcpConversation(IPEndPoint remoteEndpoint, IKcpTransport transport, KcpConversationOptions? options) - : this(remoteEndpoint, transport, null, options) - { } - - /// - /// Construct a reliable channel using KCP protocol. - /// - /// The remote endpoint - /// The underlying transport. - /// The conversation ID. - /// The options of the . - public KcpConversation(IPEndPoint remoteEndpoint, IKcpTransport transport, long conversationId, KcpConversationOptions? options) - : this(remoteEndpoint, transport, (ulong)conversationId, options) - { } - - private KcpConversation(IPEndPoint remoteEndpoint, IKcpTransport transport, ulong? conversationId, KcpConversationOptions? options) + _nodelay = options is not null && options.NoDelay; + if (_nodelay) { - _bufferPool = options?.BufferPool ?? DefaultArrayPoolBufferAllocator.Default; - _transport = transport; - _remoteEndPoint = remoteEndpoint; - _id = conversationId; - - if (options is null) - { - _mtu = KcpConversationOptions.MtuDefaultValue; - } - else if (options.Mtu < 50) - { - throw new ArgumentException("MTU must be at least 50.", nameof(options)); - } - else - { - _mtu = options.Mtu; - } - - _preBufferSize = options?.PreBufferSize ?? 0; - _postBufferSize = options?.PostBufferSize ?? 0; - if (_preBufferSize < 0) - { - throw new ArgumentException("PreBufferSize must be a non-negative integer.", nameof(options)); - } - if (_postBufferSize < 0) - { - throw new ArgumentException("PostBufferSize must be a non-negative integer.", nameof(options)); - } - if ((uint)(_preBufferSize + _postBufferSize) >= (uint)(_mtu - KcpGlobalVars.HEADER_LENGTH_WITHOUT_CONVID)) - { - throw new ArgumentException("The sum of PreBufferSize and PostBufferSize is too large. There is not enough space in the packet for the KCP header.", nameof(options)); - } - if (conversationId.HasValue && (uint)(_preBufferSize + _postBufferSize) >= (uint)(_mtu - KcpGlobalVars.HEADER_LENGTH_WITH_CONVID)) - { - throw new ArgumentException("The sum of PreBufferSize and PostBufferSize is too large. There is not enough space in the packet for the KCP header.", nameof(options)); - } - - _mss = conversationId.HasValue ? _mtu - KcpGlobalVars.HEADER_LENGTH_WITH_CONVID : _mtu - KcpGlobalVars.HEADER_LENGTH_WITHOUT_CONVID; - _mss = _mss - _preBufferSize - _postBufferSize; - - _ssthresh = 2; - - _nodelay = options is not null && options.NoDelay; - if (_nodelay) - { - _rx_minrto = 30; - } - else - { - _rx_rto = 200; - _rx_minrto = 100; - } - - _snd_wnd = options is null || options.SendWindow <= 0 ? KcpConversationOptions.SendWindowDefaultValue : (uint)options.SendWindow; - _rcv_wnd = options is null || options.ReceiveWindow <= 0 ? KcpConversationOptions.ReceiveWindowDefaultValue : (uint)options.ReceiveWindow; - _rmt_wnd = options is null || options.RemoteReceiveWindow <= 0 ? KcpConversationOptions.RemoteReceiveWindowDefaultValue : (uint)options.RemoteReceiveWindow; - _rcv_nxt = 0; - - _interval = options is null || options.UpdateInterval < 10 ? KcpConversationOptions.UpdateIntervalDefaultValue : (uint)options.UpdateInterval; - - _fastresend = options is null ? 0 : options.FastResend; - _fastlimit = 5; - _nocwnd = options is not null && options.DisableCongestionControl; - _stream = options is not null && options.StreamMode; - - _updateActivation = new KcpConversationUpdateActivation((int)_interval); - _queueItemCache = new KcpSendReceiveQueueItemCache(); - _sendQueue = new KcpSendQueue(_bufferPool, _updateActivation, _stream, options is null || options.SendQueueSize <= 0 ? KcpConversationOptions.SendQueueSizeDefaultValue : options.SendQueueSize, _mss, _queueItemCache); - _receiveQueue = new KcpReceiveQueue(_stream, options is null || options.ReceiveQueueSize <= 0 ? KcpConversationOptions.ReceiveQueueSizeDefaultValue : options.ReceiveQueueSize, _queueItemCache); - _ackList = new KcpAcknowledgeList(_sendQueue, (int)_snd_wnd); - - _updateLoopCts = new CancellationTokenSource(); - - _ts_flush = GetTimestamp(); - - _lastSendTick = _ts_flush; - _lastReceiveTick = _ts_flush; - KcpKeepAliveOptions? keepAliveOptions = options?.KeepAliveOptions; - if (keepAliveOptions is not null) - { - _keepAliveEnabled = true; - _keepAliveInterval = (uint)keepAliveOptions.SendInterval; - _keepAliveGracePeriod = (uint)keepAliveOptions.GracePeriod; - } - - _receiveWindowNotificationOptions = options?.ReceiveWindowNotificationOptions; - if (_receiveWindowNotificationOptions is not null) - { - _ts_rcv_notify_wait = 0; - _ts_rcv_notify = _ts_flush + (uint)_receiveWindowNotificationOptions.InitialInterval; - } - - RunUpdateOnActivation(); + _rx_minrto = 30; + } + else + { + _rx_rto = 200; + _rx_minrto = 100; } - /// - /// Set the handler to invoke when exception is thrown during flushing packets to the transport. Return true in the handler to ignore the error and continue running. Return false in the handler to abort the operation and mark the transport as closed. - /// - /// The exception handler. - /// The state object to pass into the exception handler. - public void SetExceptionHandler(Func handler, object? state) - { - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } + _snd_wnd = options is null || options.SendWindow <= 0 + ? KcpConversationOptions.SendWindowDefaultValue + : (uint)options.SendWindow; + _rcv_wnd = options is null || options.ReceiveWindow <= 0 + ? KcpConversationOptions.ReceiveWindowDefaultValue + : (uint)options.ReceiveWindow; + _rmt_wnd = options is null || options.RemoteReceiveWindow <= 0 + ? KcpConversationOptions.RemoteReceiveWindowDefaultValue + : (uint)options.RemoteReceiveWindow; + _rcv_nxt = 0; - _exceptionHandler = handler; - _exceptionHandlerState = state; + _interval = options is null || options.UpdateInterval < 10 + ? KcpConversationOptions.UpdateIntervalDefaultValue + : (uint)options.UpdateInterval; + + _fastresend = options is null ? 0 : options.FastResend; + _fastlimit = 5; + _nocwnd = options is not null && options.DisableCongestionControl; + StreamMode = options is not null && options.StreamMode; + + _updateActivation = new KcpConversationUpdateActivation((int)_interval); + _queueItemCache = new KcpSendReceiveQueueItemCache(); + _sendQueue = new KcpSendQueue(_bufferPool, _updateActivation, StreamMode, + options is null || options.SendQueueSize <= 0 + ? KcpConversationOptions.SendQueueSizeDefaultValue + : options.SendQueueSize, _mss, _queueItemCache); + _receiveQueue = new KcpReceiveQueue(StreamMode, + options is null || options.ReceiveQueueSize <= 0 + ? KcpConversationOptions.ReceiveQueueSizeDefaultValue + : options.ReceiveQueueSize, _queueItemCache); + _ackList = new KcpAcknowledgeList(_sendQueue, (int)_snd_wnd); + + _updateLoopCts = new CancellationTokenSource(); + + _ts_flush = GetTimestamp(); + + _lastSendTick = _ts_flush; + _lastReceiveTick = _ts_flush; + var keepAliveOptions = options?.KeepAliveOptions; + if (keepAliveOptions is not null) + { + _keepAliveEnabled = true; + _keepAliveInterval = (uint)keepAliveOptions.SendInterval; + _keepAliveGracePeriod = (uint)keepAliveOptions.GracePeriod; } - /// - /// Get the ID of the current conversation. - /// - public long? ConversationId => (long?)_id; + _receiveWindowNotificationOptions = options?.ReceiveWindowNotificationOptions; + if (_receiveWindowNotificationOptions is not null) + { + _ts_rcv_notify_wait = 0; + _ts_rcv_notify = _ts_flush + (uint)_receiveWindowNotificationOptions.InitialInterval; + } - /// - /// Get whether the transport is marked as closed. - /// - public bool TransportClosed => _transportClosed; + RunUpdateOnActivation(); + } - /// - /// Get whether the conversation is in stream mode. - /// - public bool StreamMode => _stream; + /// + /// Set the handler to invoke when exception is thrown during flushing packets to the transport. Return true in the + /// handler to ignore the error and continue running. Return false in the handler to abort the operation and mark the + /// transport as closed. + /// + /// The exception handler. + /// The state object to pass into the exception handler. + public void SetExceptionHandler(Func handler, object? state) + { + if (handler is null) throw new ArgumentNullException(nameof(handler)); - /// - /// Get the available byte count and available segment count in the send queue. - /// - /// The available byte count in the send queue. - /// The available segment count in the send queue. - /// True if the transport is not closed. Otherwise false. - public bool TryGetSendQueueAvailableSpace(out int byteCount, out int segmentCount) - => _sendQueue.TryGetAvailableSpace(out byteCount, out segmentCount); + _exceptionHandler = handler; + _exceptionHandlerState = state; + } - /// - /// Try to put message into the send queue. - /// - /// The content of the message. - /// True if the message is put into the send queue. False if the message is too large to fit in the send queue, or the transport is closed. - /// The size of the message is larger than 256 * mtu, thus it can not be correctly fragmented and sent. This exception is never thrown in stream mode. - /// The send or flush operation is initiated concurrently. - public bool TrySend(ReadOnlySpan buffer) - => _sendQueue.TrySend(buffer, false, out _); + /// + /// Get the ID of the current conversation. + /// + public long? ConversationId => (long?)_id; - /// - /// Try to put message into the send queue. - /// - /// The content of the message. - /// Whether partial sending is allowed in stream mode. This must not be true in non-stream mode. - /// The number of bytes put into the send queue. This is always the same as the size of the unless is set to true. - /// True if the message is put into the send queue. False if the message is too large to fit in the send queue, or the transport is closed. - /// is set to true in non-stream mode. Or the size of the message is larger than 256 * mtu, thus it can not be correctly fragmented and sent. This exception is never thrown in stream mode. - /// The send or flush operation is initiated concurrently. - public bool TrySend(ReadOnlySpan buffer, bool allowPartialSend, out int bytesWritten) - => _sendQueue.TrySend(buffer, allowPartialSend, out bytesWritten); + /// + /// Get whether the transport is marked as closed. + /// + public bool TransportClosed { get; private set; } - /// - /// Wait until the send queue contains at least bytes of free space, and also available segments. - /// - /// The number of bytes in the available space. - /// The count of segments in the available space. - /// The token to cancel this operation. - /// or is larger than the total space of the send queue. - /// The is fired before send operation is completed. Or is called before this operation is completed. - /// A that completes when there is enough space in the send queue. The result of the task is false when the transport is closed. - public ValueTask WaitForSendQueueAvailableSpaceAsync(int minimumBytes, int minimumSegments, CancellationToken cancellationToken = default) - => _sendQueue.WaitForAvailableSpaceAsync(minimumBytes, minimumSegments, cancellationToken); + /// + /// Get whether the conversation is in stream mode. + /// + public bool StreamMode { get; } - /// - /// Put message into the send queue. - /// - /// The content of the message. - /// The token to cancel this operation. - /// The size of the message is larger than 256 * mtu, thus it can not be correctly fragmented and sent. This exception is never thrown in stream mode. - /// The is fired before send operation is completed. Or is called before this operation is completed. - /// The send or flush operation is initiated concurrently. - /// A that completes when the entire message is put into the queue. The result of the task is false when the transport is closed. - public ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) - => _sendQueue.SendAsync(buffer, cancellationToken); + /// + /// Get the available byte count and available segment count in the send queue. + /// + /// The available byte count in the send queue. + /// The available segment count in the send queue. + /// True if the transport is not closed. Otherwise false. + public bool TryGetSendQueueAvailableSpace(out int byteCount, out int segmentCount) + { + return _sendQueue.TryGetAvailableSpace(out byteCount, out segmentCount); + } - internal ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) - => _sendQueue.WriteAsync(buffer, cancellationToken); + /// + /// Try to put message into the send queue. + /// + /// The content of the message. + /// + /// True if the message is put into the send queue. False if the message is too large to fit in the send queue, or + /// the transport is closed. + /// + /// + /// The size of the message is larger than 256 * mtu, thus it can not be correctly + /// fragmented and sent. This exception is never thrown in stream mode. + /// + /// The send or flush operation is initiated concurrently. + public bool TrySend(ReadOnlySpan buffer) + { + return _sendQueue.TrySend(buffer, false, out _); + } - /// - /// Cancel the current send operation or flush operation. - /// - /// True if the current operation is canceled. False if there is no active send operation. - public bool CancelPendingSend() - => _sendQueue.CancelPendingOperation(null, default); + /// + /// Try to put message into the send queue. + /// + /// The content of the message. + /// + /// Whether partial sending is allowed in stream mode. This must not be true in non-stream + /// mode. + /// + /// + /// The number of bytes put into the send queue. This is always the same as the size of the + /// unless is set to true. + /// + /// + /// True if the message is put into the send queue. False if the message is too large to fit in the send queue, or + /// the transport is closed. + /// + /// + /// is set to true in non-stream mode. Or the size + /// of the message is larger than 256 * mtu, thus it can not be correctly fragmented and sent. This exception is never + /// thrown in stream mode. + /// + /// The send or flush operation is initiated concurrently. + public bool TrySend(ReadOnlySpan buffer, bool allowPartialSend, out int bytesWritten) + { + return _sendQueue.TrySend(buffer, allowPartialSend, out bytesWritten); + } - /// - /// Cancel the current send operation or flush operation. - /// - /// The inner exception of the thrown by the method or method. - /// The in the thrown by the method or method. - /// True if the current operation is canceled. False if there is no active send operation. - public bool CancelPendingSend(Exception? innerException, CancellationToken cancellationToken) - => _sendQueue.CancelPendingOperation(innerException, cancellationToken); + /// + /// Wait until the send queue contains at least bytes of free space, and also + /// available segments. + /// + /// The number of bytes in the available space. + /// The count of segments in the available space. + /// The token to cancel this operation. + /// + /// or + /// is larger than the total space of the send queue. + /// + /// + /// The is fired before send operation + /// is completed. Or is called before this operation is + /// completed. + /// + /// + /// A that completes when there is enough space in the send queue. The result of + /// the task is false when the transport is closed. + /// + public ValueTask WaitForSendQueueAvailableSpaceAsync(int minimumBytes, int minimumSegments, + CancellationToken cancellationToken = default) + { + return _sendQueue.WaitForAvailableSpaceAsync(minimumBytes, minimumSegments, cancellationToken); + } - /// - /// Gets the count of bytes not yet sent to the remote host or not acknowledged by the remote host. - /// - public long UnflushedBytes => _sendQueue.GetUnflushedBytes(); + /// + /// Put message into the send queue. + /// + /// The content of the message. + /// The token to cancel this operation. + /// + /// The size of the message is larger than 256 * mtu, thus it can not be correctly + /// fragmented and sent. This exception is never thrown in stream mode. + /// + /// + /// The is fired before send operation + /// is completed. Or is called before this operation is + /// completed. + /// + /// The send or flush operation is initiated concurrently. + /// + /// A that completes when the entire message is put into the queue. The result + /// of the task is false when the transport is closed. + /// + public ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + return _sendQueue.SendAsync(buffer, cancellationToken); + } - /// - /// Wait until all messages are sent and acknowledged by the remote host, as well as all the acknowledgements are sent. - /// - /// The token to cancel this operation. - /// The is fired before send operation is completed. Or is called before this operation is completed. - /// The send or flush operation is initiated concurrently. - /// The instance is disposed. - /// A that completes when the all messages are sent and acknowledged. The result of the task is false when the transport is closed. - public ValueTask FlushAsync(CancellationToken cancellationToken = default) - => _sendQueue.FlushAsync(cancellationToken); + internal ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) + { + return _sendQueue.WriteAsync(buffer, cancellationToken); + } - internal ValueTask FlushForStreamAsync(CancellationToken cancellationToken) - => _sendQueue.FlushForStreamAsync(cancellationToken); + /// + /// Cancel the current send operation or flush operation. + /// + /// True if the current operation is canceled. False if there is no active send operation. + public bool CancelPendingSend() + { + return _sendQueue.CancelPendingOperation(null, default); + } + + /// + /// Cancel the current send operation or flush operation. + /// + /// + /// The inner exception of the thrown by the + /// method or + /// method. + /// + /// + /// The in the + /// thrown by the method or + /// method. + /// + /// True if the current operation is canceled. False if there is no active send operation. + public bool CancelPendingSend(Exception? innerException, CancellationToken cancellationToken) + { + return _sendQueue.CancelPendingOperation(innerException, cancellationToken); + } + + /// + /// Gets the count of bytes not yet sent to the remote host or not acknowledged by the remote host. + /// + public long UnflushedBytes => _sendQueue.GetUnflushedBytes(); + + /// + /// Wait until all messages are sent and acknowledged by the remote host, as well as all the acknowledgements are sent. + /// + /// The token to cancel this operation. + /// + /// The is fired before send operation + /// is completed. Or is called before this operation is + /// completed. + /// + /// The send or flush operation is initiated concurrently. + /// The instance is disposed. + /// + /// A that completes when the all messages are sent and acknowledged. The result + /// of the task is false when the transport is closed. + /// + public ValueTask FlushAsync(CancellationToken cancellationToken = default) + { + return _sendQueue.FlushAsync(cancellationToken); + } + + internal ValueTask FlushForStreamAsync(CancellationToken cancellationToken) + { + return _sendQueue.FlushForStreamAsync(cancellationToken); + } #if !NET6_0_OR_GREATER private ValueTask FlushCoreAsync(CancellationToken cancellationToken) @@ -345,1055 +428,1041 @@ namespace KcpSharp private async Task FlushCore2Async(CancellationToken cancellationToken) #else - private ValueTask FlushCoreAsync(CancellationToken cancellationToken) - { - s_currentObject = this; - return FlushCore2Async(cancellationToken); - } + private ValueTask FlushCoreAsync(CancellationToken cancellationToken) + { + s_currentObject = this; + return FlushCore2Async(cancellationToken); + } - [AsyncMethodBuilder(typeof(KcpFlushAsyncMethodBuilder))] - private async ValueTask FlushCore2Async(CancellationToken cancellationToken) + [AsyncMethodBuilder(typeof(KcpFlushAsyncMethodBuilder))] + private async ValueTask FlushCore2Async(CancellationToken cancellationToken) #endif + { + var preBufferSize = _preBufferSize; + var postBufferSize = _postBufferSize; + int packetHeaderSize = _id.HasValue + ? KcpGlobalVars.HEADER_LENGTH_WITH_CONVID + : KcpGlobalVars.HEADER_LENGTH_WITHOUT_CONVID; + var sizeLimitBeforePostBuffer = _mtu - _postBufferSize; + var anyPacketSent = false; + + var windowSize = (ushort)GetUnusedReceiveWindow(); + var unacknowledged = _rcv_nxt; + + using var bufferOwner = + _bufferPool.Rent(new KcpBufferPoolRentOptions(_mtu + (_mtu - preBufferSize - postBufferSize), true)); + var buffer = bufferOwner.Memory; + var size = preBufferSize; + buffer.Span.Slice(0, size).Clear(); + + // flush acknowledges { - int preBufferSize = _preBufferSize; - int postBufferSize = _postBufferSize; - int packetHeaderSize = _id.HasValue ? KcpGlobalVars.HEADER_LENGTH_WITH_CONVID : KcpGlobalVars.HEADER_LENGTH_WITHOUT_CONVID; - int sizeLimitBeforePostBuffer = _mtu - _postBufferSize; - bool anyPacketSent = false; - - ushort windowSize = (ushort)GetUnusedReceiveWindow(); - uint unacknowledged = _rcv_nxt; - - using KcpRentedBuffer bufferOwner = _bufferPool.Rent(new KcpBufferPoolRentOptions(_mtu + (_mtu - preBufferSize - postBufferSize), true)); - Memory buffer = bufferOwner.Memory; - int size = preBufferSize; - buffer.Span.Slice(0, size).Clear(); - - // flush acknowledges + var index = 0; + while (_ackList.TryGetAt(index++, out var serialNumber, out var timestamp)) { - int index = 0; - while (_ackList.TryGetAt(index++, out uint serialNumber, out uint timestamp)) - { - if ((size + packetHeaderSize) > sizeLimitBeforePostBuffer) - { - buffer.Span.Slice(size, postBufferSize).Clear(); - await _transport.SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken).ConfigureAwait(false); - _lastSendTick = GetTimestamp(); - size = preBufferSize; - buffer.Span.Slice(0, size).Clear(); - anyPacketSent = true; - } - KcpPacketHeader header = new(KcpCommand.Ack, 0, windowSize, timestamp, serialNumber, unacknowledged); - header.EncodeHeader(_id, 0, buffer.Span.Slice(size), out int bytesWritten); - size += bytesWritten; - } - } - - uint current = GetTimestamp(); - - // calculate window size - uint cwnd = Math.Min(_snd_wnd, _rmt_wnd); - if (!_nocwnd) - { - cwnd = Math.Min(_cwnd, cwnd); - } - - // move data from snd_queue to snd_buf - while (TimeDiff(_snd_nxt, _snd_una + cwnd) < 0) - { - if (!_sendQueue.TryDequeue(out KcpBuffer data, out byte fragment)) - { - break; - } - - lock (_sndBuf) - { - if (_transportClosed) - { - data.Release(); - return; - } - - _sndBuf.AddLast(CreateSendBufferItem(in data, fragment, current, windowSize, (uint)Interlocked.Increment(ref Unsafe.As(ref _snd_nxt)) - 1, unacknowledged, _rx_rto)); - } - } - - // calculate resent - uint resent = _fastresend > 0 ? (uint)_fastresend : 0xffffffff; - uint rtomin = !_nodelay ? (_rx_rto >> 3) : 0; - - // flush data segments - bool lost = false; - bool change = false; - LinkedListNodeOfBufferItem? segmentNode = _sndBuf.First; - while (segmentNode is not null && !_transportClosed) - { - LinkedListNodeOfBufferItem? nextSegmentNode = segmentNode.Next; - - bool needsend = false; - KcpSendSegmentStats stats = segmentNode.ValueRef.Stats; - - if (segmentNode.ValueRef.Stats.TransmitCount == 0) - { - needsend = true; - segmentNode.ValueRef.Stats = new KcpSendSegmentStats(current + segmentNode.ValueRef.Stats.Rto + rtomin, _rx_rto, stats.FastAck, stats.TransmitCount + 1); - } - else if (TimeDiff(current, stats.ResendTimestamp) >= 0) - { - needsend = true; - uint rto = stats.Rto; - if (!_nodelay) - { - rto += Math.Max(stats.Rto, _rx_rto); - } - else - { - uint step = rto; //_nodelay < 2 ? segment.rto : _rx_rto; - rto += step / 2; - } - segmentNode.ValueRef.Stats = new KcpSendSegmentStats(current + rto, rto, stats.FastAck, stats.TransmitCount + 1); - lost = true; - } - else if (stats.FastAck > resent) - { - if (stats.TransmitCount <= _fastlimit || _fastlimit == 0) - { - needsend = true; - segmentNode.ValueRef.Stats = new KcpSendSegmentStats(current, stats.Rto, 0, stats.TransmitCount + 1); - change = true; - } - } - - if (needsend) - { - KcpPacketHeader header = DeplicateHeader(ref segmentNode.ValueRef.Segment, current, windowSize, unacknowledged); - - int need = packetHeaderSize + segmentNode.ValueRef.Data.Length; - if ((size + need) > sizeLimitBeforePostBuffer) - { - buffer.Span.Slice(size, postBufferSize).Clear(); - await _transport.SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken).ConfigureAwait(false); - _lastSendTick = GetTimestamp(); - size = preBufferSize; - buffer.Span.Slice(0, size).Clear(); - anyPacketSent = true; - } - - lock (segmentNode) - { - KcpBuffer data = segmentNode.ValueRef.Data; - if (!_transportClosed) - { - header.EncodeHeader(_id, data.Length, buffer.Span.Slice(size), out int bytesWritten); - - size += bytesWritten; - - if (data.Length > 0) - { - data.DataRegion.CopyTo(buffer.Slice(size)); - size += data.Length; - } - } - } - } - - segmentNode = nextSegmentNode; - } - - _ackList.Clear(); - - // probe window size (if remote window size equals zero) - if (_rmt_wnd == 0) - { - if (_probe_wait == 0) - { - _probe_wait = IKCP_PROBE_INIT; - _ts_probe = current + _probe_wait; - } - else - { - if (TimeDiff(current, _ts_probe) >= 0) - { - if (_probe_wait < IKCP_PROBE_INIT) - { - _probe_wait = IKCP_PROBE_INIT; - } - _probe_wait += _probe_wait / 2; - if (_probe_wait > IKCP_PROBE_LIMIT) - { - _probe_wait = IKCP_PROBE_LIMIT; - } - _ts_probe = current + _probe_wait; - _probe |= KcpProbeType.AskSend; - } - } - } - else - { - _ts_probe = 0; - _probe_wait = 0; - } - - // flush window probing command - if ((_probe & KcpProbeType.AskSend) != 0) - { - if ((size + packetHeaderSize) > sizeLimitBeforePostBuffer) + if (size + packetHeaderSize > sizeLimitBeforePostBuffer) { buffer.Span.Slice(size, postBufferSize).Clear(); - await _transport.SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken).ConfigureAwait(false); + await _transport + .SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken) + .ConfigureAwait(false); _lastSendTick = GetTimestamp(); size = preBufferSize; buffer.Span.Slice(0, size).Clear(); anyPacketSent = true; } - KcpPacketHeader header = new(KcpCommand.WindowProbe, 0, windowSize, 0, 0, unacknowledged); - header.EncodeHeader(_id, 0, buffer.Span.Slice(size), out int bytesWritten); + + KcpPacketHeader header = new(KcpCommand.Ack, 0, windowSize, timestamp, serialNumber, unacknowledged); + header.EncodeHeader(_id, 0, buffer.Span.Slice(size), out var bytesWritten); size += bytesWritten; } + } - // flush window probing response - if (!anyPacketSent && ShouldSendWindowSize(current)) + var current = GetTimestamp(); + + // calculate window size + var cwnd = Math.Min(_snd_wnd, _rmt_wnd); + if (!_nocwnd) cwnd = Math.Min(_cwnd, cwnd); + + // move data from snd_queue to snd_buf + while (TimeDiff(_snd_nxt, _snd_una + cwnd) < 0) + { + if (!_sendQueue.TryDequeue(out var data, out var fragment)) break; + + lock (_sndBuf) { - if ((size + packetHeaderSize) > sizeLimitBeforePostBuffer) + if (TransportClosed) + { + data.Release(); + return; + } + + _sndBuf.AddLast(CreateSendBufferItem(in data, fragment, current, windowSize, + (uint)Interlocked.Increment(ref Unsafe.As(ref _snd_nxt)) - 1, unacknowledged, _rx_rto)); + } + } + + // calculate resent + var resent = _fastresend > 0 ? (uint)_fastresend : 0xffffffff; + var rtomin = !_nodelay ? _rx_rto >> 3 : 0; + + // flush data segments + var lost = false; + var change = false; + var segmentNode = _sndBuf.First; + while (segmentNode is not null && !TransportClosed) + { + var nextSegmentNode = segmentNode.Next; + + var needsend = false; + var stats = segmentNode.ValueRef.Stats; + + if (segmentNode.ValueRef.Stats.TransmitCount == 0) + { + needsend = true; + segmentNode.ValueRef.Stats = new KcpSendSegmentStats(current + segmentNode.ValueRef.Stats.Rto + rtomin, + _rx_rto, stats.FastAck, stats.TransmitCount + 1); + } + else if (TimeDiff(current, stats.ResendTimestamp) >= 0) + { + needsend = true; + var rto = stats.Rto; + if (!_nodelay) + { + rto += Math.Max(stats.Rto, _rx_rto); + } + else + { + var step = rto; //_nodelay < 2 ? segment.rto : _rx_rto; + rto += step / 2; + } + + segmentNode.ValueRef.Stats = + new KcpSendSegmentStats(current + rto, rto, stats.FastAck, stats.TransmitCount + 1); + lost = true; + } + else if (stats.FastAck > resent) + { + if (stats.TransmitCount <= _fastlimit || _fastlimit == 0) + { + needsend = true; + segmentNode.ValueRef.Stats = + new KcpSendSegmentStats(current, stats.Rto, 0, stats.TransmitCount + 1); + change = true; + } + } + + if (needsend) + { + var header = DeplicateHeader(ref segmentNode.ValueRef.Segment, current, windowSize, unacknowledged); + + var need = packetHeaderSize + segmentNode.ValueRef.Data.Length; + if (size + need > sizeLimitBeforePostBuffer) { buffer.Span.Slice(size, postBufferSize).Clear(); - await _transport.SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken).ConfigureAwait(false); + await _transport + .SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken) + .ConfigureAwait(false); _lastSendTick = GetTimestamp(); size = preBufferSize; buffer.Span.Slice(0, size).Clear(); - } - KcpPacketHeader header = new(KcpCommand.WindowSize, 0, windowSize, 0, 0, unacknowledged); - header.EncodeHeader(_id, 0, buffer.Span.Slice(size), out int bytesWritten); - size += bytesWritten; - } - - _probe = KcpProbeType.None; - - // flush remaining segments - if (size > preBufferSize) - { - buffer.Span.Slice(size, postBufferSize).Clear(); - try - { - await _transport.SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken).ConfigureAwait(false); - } - catch (Exception ex) - { - new Logger("KcpServer").Error("transport send error", ex); - } - _lastSendTick = GetTimestamp(); - } - - // update window - bool lockTaken = false; - try - { - _cwndUpdateLock.Enter(ref lockTaken); - - uint updatedCwnd = _cwnd; - uint incr = _incr; - - // update sshthresh - if (change) - { - uint inflight = _snd_nxt - _snd_una; - _ssthresh = Math.Max(inflight / 2, IKCP_THRESH_MIN); - updatedCwnd = _ssthresh + resent; - incr = updatedCwnd * (uint)_mss; + anyPacketSent = true; } - if (lost) + lock (segmentNode) { - _ssthresh = Math.Max(cwnd / 2, IKCP_THRESH_MIN); - updatedCwnd = 1; - incr = (uint)_mss; - } + var data = segmentNode.ValueRef.Data; + if (!TransportClosed) + { + header.EncodeHeader(_id, data.Length, buffer.Span.Slice(size), out var bytesWritten); - if (updatedCwnd < 1) - { - updatedCwnd = 1; - incr = (uint)_mss; - } + size += bytesWritten; - _cwnd = updatedCwnd; - _incr = incr; - } - finally - { - if (lockTaken) - { - _cwndUpdateLock.Exit(); + if (data.Length > 0) + { + data.DataRegion.CopyTo(buffer.Slice(size)); + size += data.Length; + } + } } } - // send keep-alive - if (_keepAliveEnabled) - { - if (TimeDiff(GetTimestamp(), _lastSendTick) > _keepAliveInterval) - { - KcpPacketHeader header = new(KcpCommand.WindowSize, 0, windowSize, 0, 0, unacknowledged); - header.EncodeHeader(_id, 0, buffer.Span, out int bytesWritten); - await _transport.SendPacketAsync(buffer.Slice(0, bytesWritten), _remoteEndPoint, cancellationToken).ConfigureAwait(false); - _lastSendTick = GetTimestamp(); - } - } + segmentNode = nextSegmentNode; } - private bool ShouldSendWindowSize(uint current) + _ackList.Clear(); + + // probe window size (if remote window size equals zero) + if (_rmt_wnd == 0) { - if ((_probe & KcpProbeType.AskTell) != 0) + if (_probe_wait == 0) { - return true; - } - - KcpReceiveWindowNotificationOptions? options = _receiveWindowNotificationOptions; - if (options is null) - { - return false; - } - - if (TimeDiff(current, _ts_rcv_notify) < 0) - { - return false; - } - - uint inital = (uint)options.InitialInterval; - uint maximum = (uint)options.MaximumInterval; - if (_ts_rcv_notify_wait < inital) - { - _ts_rcv_notify_wait = inital; - } - else if (_ts_rcv_notify_wait >= maximum) - { - _ts_rcv_notify_wait = maximum; + _probe_wait = IKCP_PROBE_INIT; + _ts_probe = current + _probe_wait; } else { - _ts_rcv_notify_wait = Math.Min(maximum, _ts_rcv_notify_wait + _ts_rcv_notify_wait / 2); - } - _ts_rcv_notify = current + _ts_rcv_notify_wait; - - return true; - } - - private LinkedListNodeOfBufferItem CreateSendBufferItem(in KcpBuffer data, byte fragment, uint current, ushort windowSize, uint serialNumber, uint unacknowledged, uint rto) - { - KcpSendReceiveBufferItem newseg = new() - { - Data = data, - Segment = new KcpPacketHeader(KcpCommand.Push, fragment, windowSize, current, serialNumber, unacknowledged), - Stats = new KcpSendSegmentStats(current, rto, 0, 0) - }; - return _cache.Allocate(in newseg); - } - - private static KcpPacketHeader DeplicateHeader(ref KcpPacketHeader header, uint timestamp, ushort windowSize, uint unacknowledged) - { - return new KcpPacketHeader(header.Command, header.Fragment, windowSize, timestamp, header.SerialNumber, unacknowledged); - } - - private uint GetUnusedReceiveWindow() - { - uint count = (uint)_receiveQueue.GetQueueSize(); - if (count < _rcv_wnd) - { - return _rcv_wnd - count; - } - return 0; - } - - private async void RunUpdateOnActivation() - { - CancellationToken cancellationToken = _updateLoopCts?.Token ?? new CancellationToken(true); - KcpConversationUpdateActivation? activation = _updateActivation; - if (activation is null) - { - return; - } - - while (!cancellationToken.IsCancellationRequested) - { - bool update = false; - using (KcpConversationUpdateNotification notification = await activation.WaitAsync(CancellationToken.None).ConfigureAwait(false)) + if (TimeDiff(current, _ts_probe) >= 0) { - if (_transportClosed) + if (_probe_wait < IKCP_PROBE_INIT) _probe_wait = IKCP_PROBE_INIT; + _probe_wait += _probe_wait / 2; + if (_probe_wait > IKCP_PROBE_LIMIT) _probe_wait = IKCP_PROBE_LIMIT; + _ts_probe = current + _probe_wait; + _probe |= KcpProbeType.AskSend; + } + } + } + else + { + _ts_probe = 0; + _probe_wait = 0; + } + + // flush window probing command + if ((_probe & KcpProbeType.AskSend) != 0) + { + if (size + packetHeaderSize > sizeLimitBeforePostBuffer) + { + buffer.Span.Slice(size, postBufferSize).Clear(); + await _transport + .SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken) + .ConfigureAwait(false); + _lastSendTick = GetTimestamp(); + size = preBufferSize; + buffer.Span.Slice(0, size).Clear(); + anyPacketSent = true; + } + + KcpPacketHeader header = new(KcpCommand.WindowProbe, 0, windowSize, 0, 0, unacknowledged); + header.EncodeHeader(_id, 0, buffer.Span.Slice(size), out var bytesWritten); + size += bytesWritten; + } + + // flush window probing response + if (!anyPacketSent && ShouldSendWindowSize(current)) + { + if (size + packetHeaderSize > sizeLimitBeforePostBuffer) + { + buffer.Span.Slice(size, postBufferSize).Clear(); + await _transport + .SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken) + .ConfigureAwait(false); + _lastSendTick = GetTimestamp(); + size = preBufferSize; + buffer.Span.Slice(0, size).Clear(); + } + + KcpPacketHeader header = new(KcpCommand.WindowSize, 0, windowSize, 0, 0, unacknowledged); + header.EncodeHeader(_id, 0, buffer.Span.Slice(size), out var bytesWritten); + size += bytesWritten; + } + + _probe = KcpProbeType.None; + + // flush remaining segments + if (size > preBufferSize) + { + buffer.Span.Slice(size, postBufferSize).Clear(); + try + { + await _transport + .SendPacketAsync(buffer.Slice(0, size + postBufferSize), _remoteEndPoint, cancellationToken) + .ConfigureAwait(false); + } + catch (Exception ex) + { + new Logger("KcpServer").Error("transport send error", ex); + } + + _lastSendTick = GetTimestamp(); + } + + // update window + var lockTaken = false; + try + { + _cwndUpdateLock.Enter(ref lockTaken); + + var updatedCwnd = _cwnd; + var incr = _incr; + + // update sshthresh + if (change) + { + var inflight = _snd_nxt - _snd_una; + _ssthresh = Math.Max(inflight / 2, IKCP_THRESH_MIN); + updatedCwnd = _ssthresh + resent; + incr = updatedCwnd * (uint)_mss; + } + + if (lost) + { + _ssthresh = Math.Max(cwnd / 2, IKCP_THRESH_MIN); + updatedCwnd = 1; + incr = (uint)_mss; + } + + if (updatedCwnd < 1) + { + updatedCwnd = 1; + incr = (uint)_mss; + } + + _cwnd = updatedCwnd; + _incr = incr; + } + finally + { + if (lockTaken) _cwndUpdateLock.Exit(); + } + + // send keep-alive + if (_keepAliveEnabled) + if (TimeDiff(GetTimestamp(), _lastSendTick) > _keepAliveInterval) + { + KcpPacketHeader header = new(KcpCommand.WindowSize, 0, windowSize, 0, 0, unacknowledged); + header.EncodeHeader(_id, 0, buffer.Span, out var bytesWritten); + await _transport.SendPacketAsync(buffer.Slice(0, bytesWritten), _remoteEndPoint, cancellationToken) + .ConfigureAwait(false); + _lastSendTick = GetTimestamp(); + } + } + + private bool ShouldSendWindowSize(uint current) + { + if ((_probe & KcpProbeType.AskTell) != 0) return true; + + var options = _receiveWindowNotificationOptions; + if (options is null) return false; + + if (TimeDiff(current, _ts_rcv_notify) < 0) return false; + + var inital = (uint)options.InitialInterval; + var maximum = (uint)options.MaximumInterval; + if (_ts_rcv_notify_wait < inital) + _ts_rcv_notify_wait = inital; + else if (_ts_rcv_notify_wait >= maximum) + _ts_rcv_notify_wait = maximum; + else + _ts_rcv_notify_wait = Math.Min(maximum, _ts_rcv_notify_wait + _ts_rcv_notify_wait / 2); + _ts_rcv_notify = current + _ts_rcv_notify_wait; + + return true; + } + + private LinkedListNodeOfBufferItem CreateSendBufferItem(in KcpBuffer data, byte fragment, uint current, + ushort windowSize, uint serialNumber, uint unacknowledged, uint rto) + { + KcpSendReceiveBufferItem newseg = new() + { + Data = data, + Segment = new KcpPacketHeader(KcpCommand.Push, fragment, windowSize, current, serialNumber, unacknowledged), + Stats = new KcpSendSegmentStats(current, rto, 0, 0) + }; + return _cache.Allocate(in newseg); + } + + private static KcpPacketHeader DeplicateHeader(ref KcpPacketHeader header, uint timestamp, ushort windowSize, + uint unacknowledged) + { + return new KcpPacketHeader(header.Command, header.Fragment, windowSize, timestamp, header.SerialNumber, + unacknowledged); + } + + private uint GetUnusedReceiveWindow() + { + var count = (uint)_receiveQueue.GetQueueSize(); + if (count < _rcv_wnd) return _rcv_wnd - count; + return 0; + } + + private async void RunUpdateOnActivation() + { + var cancellationToken = _updateLoopCts?.Token ?? new CancellationToken(true); + var activation = _updateActivation; + if (activation is null) return; + + while (!cancellationToken.IsCancellationRequested) + { + var update = false; + using (var notification = await activation.WaitAsync(CancellationToken.None).ConfigureAwait(false)) + { + if (TransportClosed) break; + + var packet = notification.Packet; + if (!packet.IsEmpty) + try { - break; + update = SetInput(packet.Span); + } + catch (Exception ex) + { + new Logger("KcpServer").Error("Update error", ex); } - ReadOnlyMemory packet = notification.Packet; - if (!packet.IsEmpty) - { - try - { - update = SetInput(packet.Span); - } - catch (Exception ex) - { - new Logger("KcpServer").Error("Update error", ex); - } - } + if (TransportClosed) break; - if (_transportClosed) - { - break; - } - - update |= notification.TimerNotification; - } - - try - { - if (update) - { - await UpdateCoreAsync(cancellationToken).ConfigureAwait(false); - } - } - catch (OperationCanceledException) - { - break; - } - catch (Exception ex) - { - if (!HandleFlushException(ex)) - { - break; - } - } - - if (_keepAliveEnabled && TimeDiff(GetTimestamp(), _lastReceiveTick) > _keepAliveGracePeriod) - { - SetTransportClosed(); - } - } - } - - private ValueTask UpdateCoreAsync(CancellationToken cancellationToken) - { - uint current = GetTimestamp(); - long slap = TimeDiff(current, _ts_flush); - if (slap > 10000 || slap < -10000) - { - _ts_flush = current; - slap = 0; + update |= notification.TimerNotification; } - if (slap >= 0 || _nodelay) + try { - _ts_flush += _interval; - if (TimeDiff(current, _ts_flush) >= 0) - { - _ts_flush = current + _interval; - } - return FlushCoreAsync(cancellationToken); + if (update) await UpdateCoreAsync(cancellationToken).ConfigureAwait(false); } - return default; - } - - private bool HandleFlushException(Exception ex) - { - Func? handler = _exceptionHandler; - object? state = _exceptionHandlerState; - bool result = false; - if (handler is not null) + catch (OperationCanceledException) { - try - { - result = handler.Invoke(ex, this, state); - } - catch - { - result = false; - } + break; + } + catch (Exception ex) + { + if (!HandleFlushException(ex)) break; } - if (!result) - { + if (_keepAliveEnabled && TimeDiff(GetTimestamp(), _lastReceiveTick) > _keepAliveGracePeriod) SetTransportClosed(); - } - return result; + } + } + + private ValueTask UpdateCoreAsync(CancellationToken cancellationToken) + { + var current = GetTimestamp(); + long slap = TimeDiff(current, _ts_flush); + if (slap > 10000 || slap < -10000) + { + _ts_flush = current; + slap = 0; } - /// - public ValueTask InputPakcetAsync(UdpReceiveResult packet, CancellationToken cancellationToken = default) + if (slap >= 0 || _nodelay) { - if (cancellationToken.IsCancellationRequested) + _ts_flush += _interval; + if (TimeDiff(current, _ts_flush) >= 0) _ts_flush = current + _interval; + return FlushCoreAsync(cancellationToken); + } + + return default; + } + + private bool HandleFlushException(Exception ex) + { + var handler = _exceptionHandler; + var state = _exceptionHandlerState; + var result = false; + if (handler is not null) + try { - return new ValueTask(Task.FromCanceled(cancellationToken)); + result = handler.Invoke(ex, this, state); } - int packetHeaderSize = _id.HasValue ? KcpGlobalVars.HEADER_LENGTH_WITH_CONVID : KcpGlobalVars.HEADER_LENGTH_WITHOUT_CONVID; - if (packet.Buffer.Length < packetHeaderSize) + catch { - return default; + result = false; } - ReadOnlySpan packetSpan = packet.Buffer.AsSpan(); + if (!result) SetTransportClosed(); + return result; + } + + /// + public ValueTask InputPakcetAsync(UdpReceiveResult packet, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) return new ValueTask(Task.FromCanceled(cancellationToken)); + int packetHeaderSize = _id.HasValue + ? KcpGlobalVars.HEADER_LENGTH_WITH_CONVID + : KcpGlobalVars.HEADER_LENGTH_WITHOUT_CONVID; + if (packet.Buffer.Length < packetHeaderSize) return default; + + ReadOnlySpan packetSpan = packet.Buffer.AsSpan(); + if (_id.HasValue) + { + var conversationId = BinaryPrimitives.ReadUInt64BigEndian(packet.Buffer.AsSpan()); + if (conversationId != _id.GetValueOrDefault()) return default; + packetSpan = packetSpan.Slice(8); + } + + var length = BinaryPrimitives.ReadUInt32LittleEndian(packetSpan.Slice(16)); + if (length > (uint)(packetSpan.Length - 20)) // implicitly checked for (int)length < 0 + return default; + + var activation = _updateActivation; + if (activation is null) return default; + + return activation.InputPacketAsync(packet.Buffer.AsMemory(), cancellationToken); + } + + private bool SetInput(ReadOnlySpan packet) + { + var current = GetTimestamp(); + var packetHeaderSize = _id.HasValue ? 28 : 20; + + var prev_una = _snd_una; + uint maxack = 0, latest_ts = 0; + var flag = false; + var mutated = false; + + while (true) + { + if (packet.Length < packetHeaderSize) break; + if (_id.HasValue) { - ulong conversationId = BinaryPrimitives.ReadUInt64BigEndian(packet.Buffer.AsSpan()); - if (conversationId != _id.GetValueOrDefault()) - { - return default; - } - packetSpan = packetSpan.Slice(8); + if (BinaryPrimitives.ReadUInt64BigEndian(packet) != _id.GetValueOrDefault()) return mutated; + packet = packet.Slice(8); } - uint length = BinaryPrimitives.ReadUInt32LittleEndian(packetSpan.Slice(16)); - if (length > (uint)(packetSpan.Length - 20)) // implicitly checked for (int)length < 0 + var header = KcpPacketHeader.Parse(packet); + var length = BinaryPrimitives.ReadInt32LittleEndian(packet.Slice(16)); + + packet = packet.Slice(20); + if ((uint)length > (uint)packet.Length) return mutated; + + if (header.Command != KcpCommand.Push && + header.Command != KcpCommand.Ack && + header.Command != KcpCommand.WindowProbe && + header.Command != KcpCommand.WindowSize) + return mutated; + + _lastReceiveTick = current; + _rmt_wnd = header.WindowSize; + mutated = HandleUnacknowledged(header.Unacknowledged) | mutated; + mutated = UpdateSendUnacknowledged() | mutated; + + if (header.Command == KcpCommand.Ack) { - return default; - } - - KcpConversationUpdateActivation? activation = _updateActivation; - if (activation is null) - { - return default; - } - - return activation.InputPacketAsync(packet.Buffer.AsMemory(), cancellationToken); - } - - private bool SetInput(ReadOnlySpan packet) - { - uint current = GetTimestamp(); - int packetHeaderSize = _id.HasValue ? 28 : 20; - - uint prev_una = _snd_una; - uint maxack = 0, latest_ts = 0; - bool flag = false; - bool mutated = false; - - while (true) - { - if (packet.Length < packetHeaderSize) - { - break; - } - - if (_id.HasValue) - { - if (BinaryPrimitives.ReadUInt64BigEndian(packet) != _id.GetValueOrDefault()) - { - return mutated; - } - packet = packet.Slice(8); - } - - KcpPacketHeader header = KcpPacketHeader.Parse(packet); - int length = BinaryPrimitives.ReadInt32LittleEndian(packet.Slice(16)); - - packet = packet.Slice(20); - if ((uint)length > (uint)packet.Length) - { - return mutated; - } - - if (header.Command != KcpCommand.Push && - header.Command != KcpCommand.Ack && - header.Command != KcpCommand.WindowProbe && - header.Command != KcpCommand.WindowSize) - { - return mutated; - } - - _lastReceiveTick = current; - _rmt_wnd = header.WindowSize; - mutated = HandleUnacknowledged(header.Unacknowledged) | mutated; + var rtt = TimeDiff(current, header.Timestamp); + if (rtt >= 0) UpdateRto(rtt); + mutated = HandleAck(header.SerialNumber) | mutated; mutated = UpdateSendUnacknowledged() | mutated; - if (header.Command == KcpCommand.Ack) + if (!flag) { - int rtt = TimeDiff(current, header.Timestamp); - if (rtt >= 0) + flag = true; + maxack = header.SerialNumber; + latest_ts = header.Timestamp; + } + else + { + if (TimeDiff(_snd_nxt, maxack) > 0) { - UpdateRto(rtt); - } - mutated = HandleAck(header.SerialNumber) | mutated; - mutated = UpdateSendUnacknowledged() | mutated; - - if (!flag) - { - flag = true; +#if !IKCP_FASTACK_CONSERVE maxack = header.SerialNumber; latest_ts = header.Timestamp; - } - else - { - if (TimeDiff(_snd_nxt, maxack) > 0) - { -#if !IKCP_FASTACK_CONSERVE - maxack = header.SerialNumber; - latest_ts = header.Timestamp; #else if (TimeDiff(header.Timestamp, latest_ts) > 0) { maxack = header.SerialNumber; latest_ts = header.Timestamp; } #endif - } - } - } - else if (header.Command == KcpCommand.Push) - { - if (TimeDiff(header.SerialNumber, _rcv_nxt + _rcv_wnd) < 0) - { - AckPush(header.SerialNumber, header.Timestamp); - if (TimeDiff(header.SerialNumber, _rcv_nxt) >= 0) - { - mutated = HandleData(header, packet.Slice(0, length)) | mutated; - } - - if (_receiveWindowNotificationOptions is not null) - { - if (_ts_rcv_notify_wait != 0) - { - _ts_rcv_notify_wait = 0; - _ts_rcv_notify = current + (uint)_receiveWindowNotificationOptions.InitialInterval; - } - } - } - } - else if (header.Command == KcpCommand.WindowProbe) - { - _probe |= KcpProbeType.AskTell; - } - else if (header.Command == KcpCommand.WindowSize) - { - // do nothing - } - else - { - return mutated; - } - - packet = packet.Slice(length); - } - - if (flag) - { - HandleFastAck(maxack, latest_ts); - } - - if (TimeDiff(_snd_una, prev_una) > 0) - { - bool lockTaken = false; - try - { - _cwndUpdateLock.Enter(ref lockTaken); - - uint cwnd = _cwnd; - uint incr = _incr; - - if (cwnd < _rmt_wnd) - { - uint mss = (uint)_mss; - if (cwnd < _ssthresh) - { - cwnd++; - incr += mss; - } - else - { - if (incr < mss) - { - incr = mss; - } - incr += (mss * mss) / incr + mss / 16; - cwnd = (incr + mss - 1) / (mss > 0 ? mss : 1); - } - if (cwnd > _rmt_wnd) - { - cwnd = _rmt_wnd; - incr = _rmt_wnd * mss; - } - } - - _cwnd = cwnd; - _incr = incr; - } - finally - { - if (lockTaken) - { - _cwndUpdateLock.Exit(); } } } - - return mutated; - } - - private bool HandleUnacknowledged(uint una) - { - bool mutated = false; - lock (_sndBuf) + else if (header.Command == KcpCommand.Push) { - LinkedListNodeOfBufferItem? node = _sndBuf.First; - while (node is not null) + if (TimeDiff(header.SerialNumber, _rcv_nxt + _rcv_wnd) < 0) { - LinkedListNodeOfBufferItem? next = node.Next; + AckPush(header.SerialNumber, header.Timestamp); + if (TimeDiff(header.SerialNumber, _rcv_nxt) >= 0) + mutated = HandleData(header, packet.Slice(0, length)) | mutated; - if (TimeDiff(una, node.ValueRef.Segment.SerialNumber) > 0) - { - _sndBuf.Remove(node); - ref KcpBuffer dataRef = ref node.ValueRef.Data; - _sendQueue.SubtractUnflushedBytes(dataRef.Length); - dataRef.Release(); - dataRef = default; - _cache.Return(node); - mutated = true; - } - else - { - break; - } - - node = next; + if (_receiveWindowNotificationOptions is not null) + if (_ts_rcv_notify_wait != 0) + { + _ts_rcv_notify_wait = 0; + _ts_rcv_notify = current + (uint)_receiveWindowNotificationOptions.InitialInterval; + } } } - return mutated; - } - - private bool UpdateSendUnacknowledged() - { - lock (_sndBuf) + else if (header.Command == KcpCommand.WindowProbe) { - LinkedListNodeOfBufferItem? first = _sndBuf.First; - uint snd_una = first is null ? _snd_nxt : first.ValueRef.Segment.SerialNumber; - uint old_snd_una = (uint)Interlocked.Exchange(ref Unsafe.As(ref _snd_una), (int)snd_una); - return snd_una != old_snd_una; + _probe |= KcpProbeType.AskTell; } - } - - private void UpdateRto(int rtt) - { - if (_rx_srtt == 0) + else if (header.Command == KcpCommand.WindowSize) { - _rx_srtt = rtt; - _rx_rttval = rtt / 2; + // do nothing } else { - int delta = rtt - _rx_srtt; - if (delta < 0) - { - delta = -delta; - } - _rx_rttval = (3 * _rx_rttval + delta) / 4; - _rx_srtt = (7 * _rx_srtt + rtt) / 8; - if (_rx_srtt < 1) - { - _rx_srtt = 1; - } + return mutated; } - int rto = _rx_srtt + Math.Max((int)_interval, 4 * _rx_rttval); + + packet = packet.Slice(length); + } + + if (flag) HandleFastAck(maxack, latest_ts); + + if (TimeDiff(_snd_una, prev_una) > 0) + { + var lockTaken = false; + try + { + _cwndUpdateLock.Enter(ref lockTaken); + + var cwnd = _cwnd; + var incr = _incr; + + if (cwnd < _rmt_wnd) + { + var mss = (uint)_mss; + if (cwnd < _ssthresh) + { + cwnd++; + incr += mss; + } + else + { + if (incr < mss) incr = mss; + incr += mss * mss / incr + mss / 16; + cwnd = (incr + mss - 1) / (mss > 0 ? mss : 1); + } + + if (cwnd > _rmt_wnd) + { + cwnd = _rmt_wnd; + incr = _rmt_wnd * mss; + } + } + + _cwnd = cwnd; + _incr = incr; + } + finally + { + if (lockTaken) _cwndUpdateLock.Exit(); + } + } + + return mutated; + } + + private bool HandleUnacknowledged(uint una) + { + var mutated = false; + lock (_sndBuf) + { + var node = _sndBuf.First; + while (node is not null) + { + var next = node.Next; + + if (TimeDiff(una, node.ValueRef.Segment.SerialNumber) > 0) + { + _sndBuf.Remove(node); + ref var dataRef = ref node.ValueRef.Data; + _sendQueue.SubtractUnflushedBytes(dataRef.Length); + dataRef.Release(); + dataRef = default; + _cache.Return(node); + mutated = true; + } + else + { + break; + } + + node = next; + } + } + + return mutated; + } + + private bool UpdateSendUnacknowledged() + { + lock (_sndBuf) + { + var first = _sndBuf.First; + var snd_una = first is null ? _snd_nxt : first.ValueRef.Segment.SerialNumber; + var old_snd_una = (uint)Interlocked.Exchange(ref Unsafe.As(ref _snd_una), (int)snd_una); + return snd_una != old_snd_una; + } + } + + private void UpdateRto(int rtt) + { + if (_rx_srtt == 0) + { + _rx_srtt = rtt; + _rx_rttval = rtt / 2; + } + else + { + var delta = rtt - _rx_srtt; + if (delta < 0) delta = -delta; + _rx_rttval = (3 * _rx_rttval + delta) / 4; + _rx_srtt = (7 * _rx_srtt + rtt) / 8; + if (_rx_srtt < 1) _rx_srtt = 1; + } + + var rto = _rx_srtt + Math.Max((int)_interval, 4 * _rx_rttval); #if NEED_MATH_SHIM _rx_rto = Math.Min(Math.Max((uint)rto, _rx_minrto), IKCP_RTO_MAX); #else - _rx_rto = Math.Clamp((uint)rto, _rx_minrto, IKCP_RTO_MAX); + _rx_rto = Math.Clamp((uint)rto, _rx_minrto, IKCP_RTO_MAX); #endif + } + + private bool HandleAck(uint serialNumber) + { + if (TimeDiff(serialNumber, _snd_una) < 0 || TimeDiff(serialNumber, _snd_nxt) >= 0) return false; + + lock (_sndBuf) + { + var node = _sndBuf.First; + while (node is not null) + { + var next = node.Next; + + if (serialNumber == node.ValueRef.Segment.SerialNumber) + { + _sndBuf.Remove(node); + ref var dataRef = ref node.ValueRef.Data; + _sendQueue.SubtractUnflushedBytes(dataRef.Length); + dataRef.Release(); + dataRef = default; + _cache.Return(node); + return true; + } + + if (TimeDiff(serialNumber, node.ValueRef.Segment.SerialNumber) < 0) return false; + + node = next; + } } - private bool HandleAck(uint serialNumber) + return false; + } + + private bool HandleData(KcpPacketHeader header, ReadOnlySpan data) + { + var serialNumber = header.SerialNumber; + if (TimeDiff(serialNumber, _rcv_nxt + _rcv_wnd) >= 0 || TimeDiff(serialNumber, _rcv_nxt) < 0) return false; + + var mutated = false; + var repeat = false; + LinkedListNodeOfBufferItem? node; + lock (_rcvBuf) { - if (TimeDiff(serialNumber, _snd_una) < 0 || TimeDiff(serialNumber, _snd_nxt) >= 0) + if (TransportClosed) return false; + node = _rcvBuf.Last; + while (node is not null) { - return false; - } - - lock (_sndBuf) - { - LinkedListNodeOfBufferItem? node = _sndBuf.First; - while (node is not null) + var nodeSerialNumber = node.ValueRef.Segment.SerialNumber; + if (serialNumber == nodeSerialNumber) { - LinkedListNodeOfBufferItem? next = node.Next; - - if (serialNumber == node.ValueRef.Segment.SerialNumber) - { - _sndBuf.Remove(node); - ref KcpBuffer dataRef = ref node.ValueRef.Data; - _sendQueue.SubtractUnflushedBytes(dataRef.Length); - dataRef.Release(); - dataRef = default; - _cache.Return(node); - return true; - } - - if (TimeDiff(serialNumber, node.ValueRef.Segment.SerialNumber) < 0) - { - return false; - } - - node = next; - } - } - - return false; - } - - private bool HandleData(KcpPacketHeader header, ReadOnlySpan data) - { - uint serialNumber = header.SerialNumber; - if (TimeDiff(serialNumber, _rcv_nxt + _rcv_wnd) >= 0 || TimeDiff(serialNumber, _rcv_nxt) < 0) - { - return false; - } - - bool mutated = false; - bool repeat = false; - LinkedListNodeOfBufferItem? node; - lock (_rcvBuf) - { - if (_transportClosed) - { - return false; - } - node = _rcvBuf.Last; - while (node is not null) - { - uint nodeSerialNumber = node.ValueRef.Segment.SerialNumber; - if (serialNumber == nodeSerialNumber) - { - repeat = true; - break; - } - if (TimeDiff(serialNumber, nodeSerialNumber) > 0) - { - break; - } - - node = node.Previous; + repeat = true; + break; } - if (!repeat) + if (TimeDiff(serialNumber, nodeSerialNumber) > 0) break; + + node = node.Previous; + } + + if (!repeat) + { + var buffer = _bufferPool.Rent(new KcpBufferPoolRentOptions(data.Length, false)); + KcpSendReceiveBufferItem item = new() { - KcpRentedBuffer buffer = _bufferPool.Rent(new KcpBufferPoolRentOptions(data.Length, false)); - KcpSendReceiveBufferItem item = new() - { - Data = KcpBuffer.CreateFromSpan(buffer, data), - Segment = header - }; - if (node is null) - { - _rcvBuf.AddFirst(_cache.Allocate(in item)); - } - else - { - _rcvBuf.AddAfter(node, _cache.Allocate(in item)); - } + Data = KcpBuffer.CreateFromSpan(buffer, data), + Segment = header + }; + if (node is null) + _rcvBuf.AddFirst(_cache.Allocate(in item)); + else + _rcvBuf.AddAfter(node, _cache.Allocate(in item)); + mutated = true; + } + + // move available data from rcv_buf -> rcv_queue + node = _rcvBuf.First; + while (node is not null) + { + var next = node.Next; + + if (node.ValueRef.Segment.SerialNumber == _rcv_nxt && _receiveQueue.GetQueueSize() < _rcv_wnd) + { + _rcvBuf.Remove(node); + _receiveQueue.Enqueue(node.ValueRef.Data, node.ValueRef.Segment.Fragment); + node.ValueRef.Data = default; + _cache.Return(node); + _rcv_nxt++; mutated = true; } - - // move available data from rcv_buf -> rcv_queue - node = _rcvBuf.First; - while (node is not null) + else { - LinkedListNodeOfBufferItem? next = node.Next; - - if (node.ValueRef.Segment.SerialNumber == _rcv_nxt && _receiveQueue.GetQueueSize() < _rcv_wnd) - { - _rcvBuf.Remove(node); - _receiveQueue.Enqueue(node.ValueRef.Data, node.ValueRef.Segment.Fragment); - node.ValueRef.Data = default; - _cache.Return(node); - _rcv_nxt++; - mutated = true; - } - else - { - break; - } - - node = next; + break; } - } - return mutated; + node = next; + } } - private void AckPush(uint serialNumber, uint timestamp) => _ackList.Add(serialNumber, timestamp); + return mutated; + } - private void HandleFastAck(uint serialNumber, uint timestamp) + private void AckPush(uint serialNumber, uint timestamp) + { + _ackList.Add(serialNumber, timestamp); + } + + private void HandleFastAck(uint serialNumber, uint timestamp) + { + if (TimeDiff(serialNumber, _snd_una) < 0 || TimeDiff(serialNumber, _snd_nxt) >= 0) return; + + lock (_sndBuf) { - if (TimeDiff(serialNumber, _snd_una) < 0 || TimeDiff(serialNumber, _snd_nxt) >= 0) + var node = _sndBuf.First; + while (node is not null) { - return; - } + var next = node.Next; + if (TimeDiff(serialNumber, node.ValueRef.Segment.SerialNumber) < 0) break; - lock (_sndBuf) - { - LinkedListNodeOfBufferItem? node = _sndBuf.First; - while (node is not null) + if (serialNumber != node.ValueRef.Segment.SerialNumber) { - LinkedListNodeOfBufferItem? next = node.Next; - if (TimeDiff(serialNumber, node.ValueRef.Segment.SerialNumber) < 0) - { - break; - } - else if (serialNumber != node.ValueRef.Segment.SerialNumber) - { - ref KcpSendSegmentStats stats = ref node.ValueRef.Stats; + ref var stats = ref node.ValueRef.Stats; #if !IKCP_FASTACK_CONSERVE - stats = new KcpSendSegmentStats(stats.ResendTimestamp, stats.Rto, stats.FastAck + 1, stats.TransmitCount); + stats = new KcpSendSegmentStats(stats.ResendTimestamp, stats.Rto, stats.FastAck + 1, + stats.TransmitCount); #else if (TimeDiff(timestamp, node.ValueRef.Segment.Timestamp) >= 0) { - stats = new KcpSendSegmentStats(stats.ResendTimestamp, stats.Rto, stats.FastAck + 1, stats.TransmitCount); + stats = + new KcpSendSegmentStats(stats.ResendTimestamp, stats.Rto, stats.FastAck + 1, stats.TransmitCount); } #endif - } - - node = next; } + + node = next; } } + } - private static uint GetTimestamp() => (uint)Environment.TickCount; + private static uint GetTimestamp() + { + return (uint)Environment.TickCount; + } - private static int TimeDiff(uint later, uint earlier) => (int)(later - earlier); + private static int TimeDiff(uint later, uint earlier) + { + return (int)(later - earlier); + } - /// - /// Get the size of the next available message in the receive queue. - /// - /// The transport state and the size of the next available message. - /// The receive or peek operation is initiated concurrently. - /// True if the receive queue contains at least one message. False if the receive queue is empty or the transport is closed. - public bool TryPeek(out KcpConversationReceiveResult result) - => _receiveQueue.TryPeek(out result); + /// + /// Get the size of the next available message in the receive queue. + /// + /// The transport state and the size of the next available message. + /// The receive or peek operation is initiated concurrently. + /// + /// True if the receive queue contains at least one message. False if the receive queue is empty or the transport + /// is closed. + /// + public bool TryPeek(out KcpConversationReceiveResult result) + { + return _receiveQueue.TryPeek(out result); + } - /// - /// Remove the next available message in the receive queue and copy its content into . When in stream mode, move as many bytes as possible into . - /// - /// The buffer to receive message. - /// The transport state and the count of bytes moved into . - /// The size of the next available message is larger than the size of . This exception is never thrown in stream mode. - /// The receive or peek operation is initiated concurrently. - /// True if the next available message is moved into . False if the receive queue is empty or the transport is closed. - public bool TryReceive(Span buffer, out KcpConversationReceiveResult result) - => _receiveQueue.TryReceive(buffer, out result); + /// + /// Remove the next available message in the receive queue and copy its content into . When + /// in stream mode, move as many bytes as possible into . + /// + /// The buffer to receive message. + /// The transport state and the count of bytes moved into . + /// + /// The size of the next available message is larger than the size of + /// . This exception is never thrown in stream mode. + /// + /// The receive or peek operation is initiated concurrently. + /// + /// True if the next available message is moved into . False if the receive queue is + /// empty or the transport is closed. + /// + public bool TryReceive(Span buffer, out KcpConversationReceiveResult result) + { + return _receiveQueue.TryReceive(buffer, out result); + } - /// - /// Wait until the receive queue contains at least one full message, or at least one byte in stream mode. - /// - /// The token to cancel this operation. - /// The is fired before receive operation is completed. - /// The receive or peek operation is initiated concurrently. - /// A that completes when the receive queue contains at least one full message, or at least one byte in stream mode. Its result contains the transport state and the size of the available message. - public ValueTask WaitToReceiveAsync(CancellationToken cancellationToken = default) - => _receiveQueue.WaitToReceiveAsync(cancellationToken); + /// + /// Wait until the receive queue contains at least one full message, or at least one byte in stream mode. + /// + /// The token to cancel this operation. + /// + /// The is fired before receive + /// operation is completed. + /// + /// The receive or peek operation is initiated concurrently. + /// + /// A that completes when the receive queue contains at + /// least one full message, or at least one byte in stream mode. Its result contains the transport state and the size + /// of the available message. + /// + public ValueTask WaitToReceiveAsync(CancellationToken cancellationToken = default) + { + return _receiveQueue.WaitToReceiveAsync(cancellationToken); + } - /// - /// Wait until the receive queue contains at leat bytes. - /// - /// The minimum bytes in the receive queue. - /// The token to cancel this operation. - /// is a negative integer. - /// The is fired before receive operation is completed. - /// The receive or peek operation is initiated concurrently. - /// A that completes when the receive queue contains at least bytes. The result of the task is false when the transport is closed. - public ValueTask WaitForReceiveQueueAvailableDataAsync(int minimumBytes, CancellationToken cancellationToken = default) - => _receiveQueue.WaitForAvailableDataAsync(minimumBytes, 0, cancellationToken); + /// + /// Wait until the receive queue contains at leat bytes. + /// + /// The minimum bytes in the receive queue. + /// The token to cancel this operation. + /// is a negative integer. + /// + /// The is fired before receive + /// operation is completed. + /// + /// The receive or peek operation is initiated concurrently. + /// + /// A that completes when the receive queue contains at least + /// bytes. The result of the task is false when the transport is closed. + /// + public ValueTask WaitForReceiveQueueAvailableDataAsync(int minimumBytes, + CancellationToken cancellationToken = default) + { + return _receiveQueue.WaitForAvailableDataAsync(minimumBytes, 0, cancellationToken); + } - /// - /// Wait until the receive queue contains at leat bytes, and also segments. - /// - /// The minimum bytes in the receive queue. - /// The minimum segments in the receive queue - /// The token to cancel this operation. - /// Any od and is a negative integer. - /// The is fired before receive operation is completed. - /// The receive or peek operation is initiated concurrently. - /// A that completes when the receive queue contains at least bytes. The result of the task is false when the transport is closed. - public ValueTask WaitForReceiveQueueAvailableDataAsync(int minimumBytes, int minimumSegments, CancellationToken cancellationToken = default) - => _receiveQueue.WaitForAvailableDataAsync(minimumBytes, minimumSegments, cancellationToken); + /// + /// Wait until the receive queue contains at leat bytes, and also + /// segments. + /// + /// The minimum bytes in the receive queue. + /// The minimum segments in the receive queue + /// The token to cancel this operation. + /// + /// Any od and + /// is a negative integer. + /// + /// + /// The is fired before receive + /// operation is completed. + /// + /// The receive or peek operation is initiated concurrently. + /// + /// A that completes when the receive queue contains at least + /// bytes. The result of the task is false when the transport is closed. + /// + public ValueTask WaitForReceiveQueueAvailableDataAsync(int minimumBytes, int minimumSegments, + CancellationToken cancellationToken = default) + { + return _receiveQueue.WaitForAvailableDataAsync(minimumBytes, minimumSegments, cancellationToken); + } - /// - /// Wait for the next full message to arrive if the receive queue is empty. Remove the next available message in the receive queue and copy its content into . When in stream mode, move as many bytes as possible into . - /// - /// The buffer to receive message. - /// The token to cancel this operation. - /// The size of the next available message is larger than the size of . This exception is never thrown in stream mode. - /// The is fired before send operation is completed. - /// The receive or peek operation is initiated concurrently. - /// A that completes when a full message is moved into or the transport is closed. Its result contains the transport state and the count of bytes written into . - public ValueTask ReceiveAsync(Memory buffer, CancellationToken cancellationToken = default) - => _receiveQueue.ReceiveAsync(buffer, cancellationToken); + /// + /// Wait for the next full message to arrive if the receive queue is empty. Remove the next available message in the + /// receive queue and copy its content into . When in stream mode, move as many bytes as + /// possible into . + /// + /// The buffer to receive message. + /// The token to cancel this operation. + /// + /// The size of the next available message is larger than the size of + /// . This exception is never thrown in stream mode. + /// + /// + /// The is fired before send operation + /// is completed. + /// + /// The receive or peek operation is initiated concurrently. + /// + /// A that completes when a full message is moved into + /// or the transport is closed. Its result contains the transport state and the count of + /// bytes written into . + /// + public ValueTask ReceiveAsync(Memory buffer, + CancellationToken cancellationToken = default) + { + return _receiveQueue.ReceiveAsync(buffer, cancellationToken); + } - internal ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken) - => _receiveQueue.ReadAsync(buffer, cancellationToken); + internal ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken) + { + return _receiveQueue.ReadAsync(buffer, cancellationToken); + } - /// - /// Cancel the current receive operation. - /// - /// True if the current operation is canceled. False if there is no active send operation. - public bool CancelPendingReceive() - => _receiveQueue.CancelPendingOperation(null, default); + /// + /// Cancel the current receive operation. + /// + /// True if the current operation is canceled. False if there is no active send operation. + public bool CancelPendingReceive() + { + return _receiveQueue.CancelPendingOperation(null, default); + } - /// - /// Cancel the current receive operation. - /// - /// The inner exception of the thrown by the method or method. - /// The in the thrown by the method or method. - /// True if the current operation is canceled. False if there is no active send operation. - public bool CancelPendingReceive(Exception? innerException, CancellationToken cancellationToken) - => _receiveQueue.CancelPendingOperation(innerException, cancellationToken); + /// + /// Cancel the current receive operation. + /// + /// + /// The inner exception of the thrown by the + /// method or + /// method. + /// + /// + /// The in the + /// thrown by the method or + /// method. + /// + /// True if the current operation is canceled. False if there is no active send operation. + public bool CancelPendingReceive(Exception? innerException, CancellationToken cancellationToken) + { + return _receiveQueue.CancelPendingOperation(innerException, cancellationToken); + } - /// - public void SetTransportClosed() + /// + public void SetTransportClosed() + { + TransportClosed = true; + Interlocked.Exchange(ref _updateActivation, null)?.Dispose(); + var updateLoopCts = Interlocked.Exchange(ref _updateLoopCts, null); + if (updateLoopCts is not null) { - _transportClosed = true; - Interlocked.Exchange(ref _updateActivation, null)?.Dispose(); - CancellationTokenSource? updateLoopCts = Interlocked.Exchange(ref _updateLoopCts, null); - if (updateLoopCts is not null) - { - updateLoopCts.Cancel(); - updateLoopCts.Dispose(); - } + updateLoopCts.Cancel(); + updateLoopCts.Dispose(); + } - _sendQueue.SetTransportClosed(); - _receiveQueue.SetTransportClosed(); - lock (_sndBuf) + _sendQueue.SetTransportClosed(); + _receiveQueue.SetTransportClosed(); + lock (_sndBuf) + { + var node = _sndBuf.First; + var next = node?.Next; + while (node is not null) { - LinkedListNodeOfBufferItem? node = _sndBuf.First; - LinkedListNodeOfBufferItem? next = node?.Next; - while (node is not null) - { - lock (node) - { - node.ValueRef.Data.Release(); - node.ValueRef = default; - } - - _sndBuf.Remove(node); - node = next; - next = node?.Next; - } - } - lock (_rcvBuf) - { - LinkedListNodeOfBufferItem? node = _rcvBuf.First; - while (node is not null) + lock (node) { node.ValueRef.Data.Release(); - node = node.Next; + node.ValueRef = default; } - _rcvBuf.Clear(); + + _sndBuf.Remove(node); + node = next; + next = node?.Next; } - _queueItemCache.Clear(); } - /// - public void Dispose() + lock (_rcvBuf) { - bool disposed = _disposed; - _disposed = true; - SetTransportClosed(); - if (!disposed) + var node = _rcvBuf.First; + while (node is not null) { - _sendQueue.Dispose(); - _receiveQueue.Dispose(); + node.ValueRef.Data.Release(); + node = node.Next; } + + _rcvBuf.Clear(); } + _queueItemCache.Clear(); } -} + + /// + public void Dispose() + { + var disposed = _disposed; + _disposed = true; + SetTransportClosed(); + if (!disposed) + { + _sendQueue.Dispose(); + _receiveQueue.Dispose(); + } + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpConversationOptions.cs b/GameServer/KcpSharp/KcpConversationOptions.cs index f457e764..9a55979c 100644 --- a/GameServer/KcpSharp/KcpConversationOptions.cs +++ b/GameServer/KcpSharp/KcpConversationOptions.cs @@ -1,99 +1,100 @@ using KcpSharp; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Options used to control the behaviors of . +/// +public class KcpConversationOptions { + internal const int MtuDefaultValue = 1400; + internal const uint SendWindowDefaultValue = 32; + internal const uint ReceiveWindowDefaultValue = 128; + internal const uint RemoteReceiveWindowDefaultValue = 128; + internal const uint UpdateIntervalDefaultValue = 100; + + internal const int SendQueueSizeDefaultValue = 32; + internal const int ReceiveQueueSizeDefaultValue = 32; + /// - /// Options used to control the behaviors of . + /// The buffer pool to rent buffer from. /// - public class KcpConversationOptions - { - /// - /// The buffer pool to rent buffer from. - /// - public IKcpBufferPool? BufferPool { get; set; } + public IKcpBufferPool? BufferPool { get; set; } - /// - /// The maximum packet size that can be transmitted over the underlying transport. - /// - public int Mtu { get; set; } = 1400; + /// + /// The maximum packet size that can be transmitted over the underlying transport. + /// + public int Mtu { get; set; } = 1400; - /// - /// The number of packets in the send window. - /// - public int SendWindow { get; set; } = 32; + /// + /// The number of packets in the send window. + /// + public int SendWindow { get; set; } = 32; - /// - /// The number of packets in the receive window. - /// - public int ReceiveWindow { get; set; } = 128; + /// + /// The number of packets in the receive window. + /// + public int ReceiveWindow { get; set; } = 128; - /// - /// The nuber of packets in the receive window of the remote host. - /// - public int RemoteReceiveWindow { get; set; } = 128; + /// + /// The nuber of packets in the receive window of the remote host. + /// + public int RemoteReceiveWindow { get; set; } = 128; - /// - /// The interval in milliseconds to update the internal state of . - /// - public int UpdateInterval { get; set; } = 100; + /// + /// The interval in milliseconds to update the internal state of . + /// + public int UpdateInterval { get; set; } = 100; - /// - /// Wether no-delay mode is enabled. - /// - public bool NoDelay { get; set; } + /// + /// Wether no-delay mode is enabled. + /// + public bool NoDelay { get; set; } - /// - /// The number of ACK packet skipped before a resend is triggered. - /// - public int FastResend { get; set; } + /// + /// The number of ACK packet skipped before a resend is triggered. + /// + public int FastResend { get; set; } - /// - /// Whether congestion control is disabled. - /// - public bool DisableCongestionControl { get; set; } + /// + /// Whether congestion control is disabled. + /// + public bool DisableCongestionControl { get; set; } - /// - /// Whether stream mode is enabled. - /// - public bool StreamMode { get; set; } + /// + /// Whether stream mode is enabled. + /// + public bool StreamMode { get; set; } - /// - /// The number of packets in the send queue. - /// - public int SendQueueSize { get; set; } + /// + /// The number of packets in the send queue. + /// + public int SendQueueSize { get; set; } - /// - /// The number of packets in the receive queue. - /// - public int ReceiveQueueSize { get; set; } + /// + /// The number of packets in the receive queue. + /// + public int ReceiveQueueSize { get; set; } - /// - /// The number of bytes to reserve at the start of buffer passed into the underlying transport. The transport should fill this reserved space. - /// - public int PreBufferSize { get; set; } + /// + /// The number of bytes to reserve at the start of buffer passed into the underlying transport. The transport should + /// fill this reserved space. + /// + public int PreBufferSize { get; set; } - /// - /// The number of bytes to reserve at the end of buffer passed into the underlying transport. The transport should fill this reserved space. - /// - public int PostBufferSize { get; set; } + /// + /// The number of bytes to reserve at the end of buffer passed into the underlying transport. The transport should fill + /// this reserved space. + /// + public int PostBufferSize { get; set; } - /// - /// Options for customized keep-alive functionality. - /// - public KcpKeepAliveOptions? KeepAliveOptions { get; set; } + /// + /// Options for customized keep-alive functionality. + /// + public KcpKeepAliveOptions? KeepAliveOptions { get; set; } - /// - /// Options for receive window size notification functionality. - /// - public KcpReceiveWindowNotificationOptions? ReceiveWindowNotificationOptions { get; set; } - - internal const int MtuDefaultValue = 1400; - internal const uint SendWindowDefaultValue = 32; - internal const uint ReceiveWindowDefaultValue = 128; - internal const uint RemoteReceiveWindowDefaultValue = 128; - internal const uint UpdateIntervalDefaultValue = 100; - - internal const int SendQueueSizeDefaultValue = 32; - internal const int ReceiveQueueSizeDefaultValue = 32; - } -} + /// + /// Options for receive window size notification functionality. + /// + public KcpReceiveWindowNotificationOptions? ReceiveWindowNotificationOptions { get; set; } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpConversationReceiveResult.cs b/GameServer/KcpSharp/KcpConversationReceiveResult.cs index f91d092d..861eaa1b 100644 --- a/GameServer/KcpSharp/KcpConversationReceiveResult.cs +++ b/GameServer/KcpSharp/KcpConversationReceiveResult.cs @@ -1,61 +1,77 @@ using System.Globalization; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// The result of a receive or peek operation. +/// +public readonly struct KcpConversationReceiveResult : IEquatable { + private readonly bool _connectionAlive; + /// - /// The result of a receive or peek operation. + /// The number of bytes received. /// - public readonly struct KcpConversationReceiveResult : IEquatable + public int BytesReceived { get; } + + /// + /// Whether the underlying transport is marked as closed. + /// + public bool TransportClosed => !_connectionAlive; + + /// + /// Construct a with the specified number of bytes received. + /// + /// The number of bytes received. + public KcpConversationReceiveResult(int bytesReceived) { - private readonly int _bytesReceived; - private readonly bool _connectionAlive; - - /// - /// The number of bytes received. - /// - public int BytesReceived => _bytesReceived; - - /// - /// Whether the underlying transport is marked as closed. - /// - public bool TransportClosed => !_connectionAlive; - - /// - /// Construct a with the specified number of bytes received. - /// - /// The number of bytes received. - public KcpConversationReceiveResult(int bytesReceived) - { - _bytesReceived = bytesReceived; - _connectionAlive = true; - } - - /// - /// Checks whether the two instance is equal. - /// - /// The one instance. - /// The other instance. - /// Whether the two instance is equal - public static bool operator ==(KcpConversationReceiveResult left, KcpConversationReceiveResult right) => left.Equals(right); - - /// - /// Checks whether the two instance is not equal. - /// - /// The one instance. - /// The other instance. - /// Whether the two instance is not equal - public static bool operator !=(KcpConversationReceiveResult left, KcpConversationReceiveResult right) => !left.Equals(right); - - /// - public bool Equals(KcpConversationReceiveResult other) => BytesReceived == other.BytesReceived && TransportClosed == other.TransportClosed; - - /// - public override bool Equals(object? obj) => obj is KcpConversationReceiveResult other && Equals(other); - - /// - public override int GetHashCode() => HashCode.Combine(BytesReceived, TransportClosed); - - /// - public override string ToString() => _connectionAlive ? _bytesReceived.ToString(CultureInfo.InvariantCulture) : "Transport is closed."; + BytesReceived = bytesReceived; + _connectionAlive = true; } -} + + /// + /// Checks whether the two instance is equal. + /// + /// The one instance. + /// The other instance. + /// Whether the two instance is equal + public static bool operator ==(KcpConversationReceiveResult left, KcpConversationReceiveResult right) + { + return left.Equals(right); + } + + /// + /// Checks whether the two instance is not equal. + /// + /// The one instance. + /// The other instance. + /// Whether the two instance is not equal + public static bool operator !=(KcpConversationReceiveResult left, KcpConversationReceiveResult right) + { + return !left.Equals(right); + } + + /// + public bool Equals(KcpConversationReceiveResult other) + { + return BytesReceived == other.BytesReceived && TransportClosed == other.TransportClosed; + } + + /// + public override bool Equals(object? obj) + { + return obj is KcpConversationReceiveResult other && Equals(other); + } + + /// + public override int GetHashCode() + { + return HashCode.Combine(BytesReceived, TransportClosed); + } + + /// + public override string ToString() + { + return _connectionAlive ? BytesReceived.ToString(CultureInfo.InvariantCulture) : "Transport is closed."; + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpConversationUpdateActivation.cs b/GameServer/KcpSharp/KcpConversationUpdateActivation.cs index 6e5ea16a..e61600b5 100644 --- a/GameServer/KcpSharp/KcpConversationUpdateActivation.cs +++ b/GameServer/KcpSharp/KcpConversationUpdateActivation.cs @@ -1,31 +1,274 @@ using System.Diagnostics; using System.Threading.Tasks.Sources; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class KcpConversationUpdateActivation : IValueTaskSource, IDisposable { - internal sealed class KcpConversationUpdateActivation : IValueTaskSource, IDisposable + private readonly Timer _timer; + + private readonly WaitList _waitList; + private bool _activeWait; + private CancellationTokenRegistration _cancellationRegistration; + private CancellationToken _cancellationToken; + + private bool _disposed; + private ManualResetValueTaskSourceCore _mrvtsc; + private bool _notificationPending; + private bool _signaled; + + public KcpConversationUpdateActivation(int interval) { - private readonly Timer _timer; - private ManualResetValueTaskSourceCore _mrvtsc; + _timer = new Timer(state => + { + var reference = (WeakReference?)state!; + if (reference.TryGetTarget(out var target)) target.Notify(); + }, new WeakReference(this), interval, interval); + _mrvtsc = new ManualResetValueTaskSourceCore + { RunContinuationsAsynchronously = true }; + _waitList = new WaitList(this); + } - private bool _disposed; - private bool _notificationPending; - private bool _signaled; - private bool _activeWait; - private CancellationToken _cancellationToken; + public void Dispose() + { + lock (this) + { + if (_disposed) return; + _disposed = true; + if (_activeWait && !_signaled) + { + _signaled = true; + _cancellationToken = default; + _mrvtsc.SetResult(default); + } + } + + _timer.Dispose(); + _waitList.Dispose(); + } + + ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) + { + return _mrvtsc.GetStatus(token); + } + + void IValueTaskSource.OnCompleted(Action continuation, object? state, + short token, ValueTaskSourceOnCompletedFlags flags) + { + _mrvtsc.OnCompleted(continuation, state, token, flags); + } + + KcpConversationUpdateNotification IValueTaskSource.GetResult(short token) + { + _cancellationRegistration.Dispose(); + + try + { + return _mrvtsc.GetResult(token); + } + finally + { + _mrvtsc.Reset(); + + lock (this) + { + _signaled = false; + _activeWait = false; + _cancellationRegistration = default; + } + } + } + + public void Notify() + { + if (_disposed) return; + lock (this) + { + if (_disposed || _notificationPending) return; + if (_activeWait && !_signaled) + { + _signaled = true; + _cancellationToken = default; + _mrvtsc.SetResult(default); + } + else + { + _notificationPending = true; + } + } + } + + private void NotifyPacketReceived() + { + lock (this) + { + if (_disposed) return; + if (_activeWait && !_signaled) + if (_waitList.Occupy(out var notification)) + { + _signaled = true; + _cancellationToken = default; + var timerNotification = _notificationPending; + _notificationPending = false; + _mrvtsc.SetResult(notification.WithTimerNotification(timerNotification)); + } + } + } + + public ValueTask WaitAsync(CancellationToken cancellationToken) + { + short token; + lock (this) + { + if (_disposed) return default; + if (cancellationToken.IsCancellationRequested) + return new ValueTask( + Task.FromCanceled(cancellationToken)); + if (_activeWait) throw new InvalidOperationException(); + if (_waitList.Occupy(out var notification)) + { + var timerNotification = _notificationPending; + _notificationPending = false; + return new ValueTask( + notification.WithTimerNotification(timerNotification)); + } + + if (_notificationPending) + { + _notificationPending = false; + return default; + } + + _activeWait = true; + Debug.Assert(!_signaled); + _cancellationToken = cancellationToken; + token = _mrvtsc.Version; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpConversationUpdateActivation?)state)!.CancelWaiting(), this); + return new ValueTask(this, token); + } + + private void CancelWaiting() + { + lock (this) + { + if (_activeWait && !_signaled) + { + var cancellationToken = _cancellationToken; + _signaled = true; + _cancellationToken = default; + _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); + } + } + } + + public ValueTask InputPacketAsync(ReadOnlyMemory packet, CancellationToken cancellationToken) + { + if (_disposed) return default; + return _waitList.InputPacketAsync(packet, cancellationToken); + } + + private class WaitList : IValueTaskSource, IKcpConversationUpdateNotificationSource, IDisposable + { + private readonly KcpConversationUpdateActivation _parent; + + private bool _available; // activeWait private CancellationTokenRegistration _cancellationRegistration; + private CancellationToken _cancellationToken; + private bool _disposed; + private LinkedList? _list; + private ManualResetValueTaskSourceCore _mrvtsc; + private bool _occupied; - private readonly WaitList _waitList; + private ReadOnlyMemory _packet; + private bool _signaled; - ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _mrvtsc.GetStatus(token); - void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => _mrvtsc.OnCompleted(continuation, state, token, flags); - KcpConversationUpdateNotification IValueTaskSource.GetResult(short token) + public WaitList(KcpConversationUpdateActivation parent) + { + _parent = parent; + _mrvtsc = new ManualResetValueTaskSourceCore { RunContinuationsAsynchronously = true }; + } + + public void Dispose() + { + if (_disposed) return; + lock (this) + { + _disposed = true; + if (_available && !_occupied && !_signaled) + { + _signaled = true; + _packet = default; + _cancellationToken = default; + _mrvtsc.SetResult(false); + } + + var list = _list; + if (list is not null) + { + _list = null; + + var node = list.First; + var next = node?.Next; + while (node is not null) + { + node.Value.Release(); + + list.Remove(node); + node = next; + next = node?.Next; + } + } + } + } + + public ReadOnlyMemory Packet + { + get + { + lock (this) + { + if (_available && _occupied && !_signaled) return _packet; + } + + return default; + } + } + + public void Release() + { + lock (this) + { + if (_available && _occupied && !_signaled) + { + _signaled = true; + _packet = default; + _cancellationToken = default; + _mrvtsc.SetResult(true); + } + } + } + + ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) + { + return _mrvtsc.GetStatus(token); + } + + void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, + ValueTaskSourceOnCompletedFlags flags) + { + _mrvtsc.OnCompleted(continuation, state, token, flags); + } + + void IValueTaskSource.GetResult(short token) { _cancellationRegistration.Dispose(); try { - return _mrvtsc.GetResult(token); + _mrvtsc.GetResult(token); } finally { @@ -33,458 +276,199 @@ namespace EggLink.DanhengServer.KcpSharp lock (this) { + _available = false; + _occupied = false; _signaled = false; - _activeWait = false; _cancellationRegistration = default; } } } - public KcpConversationUpdateActivation(int interval) - { - _timer = new Timer(state => - { - WeakReference? reference = (WeakReference?)state!; - if (reference.TryGetTarget(out KcpConversationUpdateActivation? target)) - { - target.Notify(); - } - }, new WeakReference(this), interval, interval); - _mrvtsc = new ManualResetValueTaskSourceCore { RunContinuationsAsynchronously = true }; - _waitList = new WaitList(this); - } - - public void Notify() - { - if (_disposed) - { - return; - } - lock (this) - { - if (_disposed || _notificationPending) - { - return; - } - if (_activeWait && !_signaled) - { - _signaled = true; - _cancellationToken = default; - _mrvtsc.SetResult(default); - } - else - { - _notificationPending = true; - } - } - } - - private void NotifyPacketReceived() - { - lock (this) - { - if (_disposed) - { - return; - } - if (_activeWait && !_signaled) - { - if (_waitList.Occupy(out KcpConversationUpdateNotification notification)) - { - _signaled = true; - _cancellationToken = default; - bool timerNotification = _notificationPending; - _notificationPending = false; - _mrvtsc.SetResult(notification.WithTimerNotification(timerNotification)); - } - } - } - } - - public ValueTask WaitAsync(CancellationToken cancellationToken) - { - short token; - lock (this) - { - if (_disposed) - { - return default; - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - if (_activeWait) - { - throw new InvalidOperationException(); - } - if (_waitList.Occupy(out KcpConversationUpdateNotification notification)) - { - bool timerNotification = _notificationPending; - _notificationPending = false; - return new ValueTask(notification.WithTimerNotification(timerNotification)); - } - if (_notificationPending) - { - _notificationPending = false; - return default; - } - - _activeWait = true; - Debug.Assert(!_signaled); - _cancellationToken = cancellationToken; - token = _mrvtsc.Version; - } - - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpConversationUpdateActivation?)state)!.CancelWaiting(), this); - return new ValueTask(this, token); - } - - private void CancelWaiting() - { - lock (this) - { - if (_activeWait && !_signaled) - { - CancellationToken cancellationToken = _cancellationToken; - _signaled = true; - _cancellationToken = default; - _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); - } - } - } - public ValueTask InputPacketAsync(ReadOnlyMemory packet, CancellationToken cancellationToken) { - if (_disposed) + WaitItem? waitItem = null; + short token = 0; + lock (this) { - return default; + if (_disposed) return default; + if (cancellationToken.IsCancellationRequested) + return new ValueTask(Task.FromCanceled(cancellationToken)); + if (_available) + { + waitItem = new WaitItem(this, packet, cancellationToken); + _list ??= new LinkedList(); + _list.AddLast(waitItem.Node); + } + else + { + token = _mrvtsc.Version; + + _available = true; + Debug.Assert(!_occupied); + Debug.Assert(!_signaled); + _packet = packet; + _cancellationToken = cancellationToken; + } } - return _waitList.InputPacketAsync(packet, cancellationToken); + + ValueTask task; + + if (waitItem is null) + { + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((WaitList?)state)!.CancelWaiting(), this); + task = new ValueTask(this, token); + } + else + { + waitItem.RegisterCancellationToken(); + task = new ValueTask(waitItem.Task); + } + + _parent.NotifyPacketReceived(); + + return task; } - public void Dispose() + private void CancelWaiting() + { + lock (this) + { + if (_available && !_occupied && !_signaled) + { + _signaled = true; + var cancellationToken = _cancellationToken; + _packet = default; + _cancellationToken = default; + _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); + } + } + } + + public bool Occupy(out KcpConversationUpdateNotification notification) { lock (this) { if (_disposed) { - return; - } - _disposed = true; - if (_activeWait && !_signaled) - { - _signaled = true; - _cancellationToken = default; - _mrvtsc.SetResult(default); - } - } - _timer.Dispose(); - _waitList.Dispose(); - } - - private class WaitList : IValueTaskSource, IKcpConversationUpdateNotificationSource, IDisposable - { - private readonly KcpConversationUpdateActivation _parent; - private LinkedList? _list; - private ManualResetValueTaskSourceCore _mrvtsc; - - private bool _available; // activeWait - private bool _occupied; - private bool _signaled; - private bool _disposed; - - private ReadOnlyMemory _packet; - private CancellationToken _cancellationToken; - private CancellationTokenRegistration _cancellationRegistration; - - public ReadOnlyMemory Packet - { - get - { - lock (this) - { - if (_available && _occupied && !_signaled) - { - return _packet; - } - } - return default; - } - } - - ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _mrvtsc.GetStatus(token); - void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => _mrvtsc.OnCompleted(continuation, state, token, flags); - void IValueTaskSource.GetResult(short token) - { - _cancellationRegistration.Dispose(); - - try - { - _mrvtsc.GetResult(token); - } - finally - { - _mrvtsc.Reset(); - - lock (this) - { - _available = false; - _occupied = false; - _signaled = false; - _cancellationRegistration = default; - } - } - } - - public WaitList(KcpConversationUpdateActivation parent) - { - _parent = parent; - _mrvtsc = new ManualResetValueTaskSourceCore { RunContinuationsAsynchronously = true }; - } - - public ValueTask InputPacketAsync(ReadOnlyMemory packet, CancellationToken cancellationToken) - { - WaitItem? waitItem = null; - short token = 0; - lock (this) - { - if (_disposed) - { - return default; - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - if (_available) - { - waitItem = new WaitItem(this, packet, cancellationToken); - _list ??= new LinkedList(); - _list.AddLast(waitItem.Node); - } - else - { - token = _mrvtsc.Version; - - _available = true; - Debug.Assert(!_occupied); - Debug.Assert(!_signaled); - _packet = packet; - _cancellationToken = cancellationToken; - } + notification = default; + return false; } - ValueTask task; - - if (waitItem is null) + if (_available && !_occupied && !_signaled) { - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((WaitList?)state)!.CancelWaiting(), this); - task = new ValueTask(this, token); - } - else - { - waitItem.RegisterCancellationToken(); - task = new ValueTask(waitItem.Task); + _occupied = true; + notification = new KcpConversationUpdateNotification(this, true); + return true; } - _parent.NotifyPacketReceived(); - - return task; - } - - private void CancelWaiting() - { - lock (this) + if (_list is null) { - if (_available && !_occupied && !_signaled) - { - _signaled = true; - CancellationToken cancellationToken = _cancellationToken; - _packet = default; - _cancellationToken = default; - _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); - } + notification = default; + return false; } - } - public bool Occupy(out KcpConversationUpdateNotification notification) - { - lock (this) + var node = _list.First; + if (node is not null) { - if (_disposed) - { - notification = default; - return false; - } - if (_available && !_occupied && !_signaled) - { - _occupied = true; - notification = new KcpConversationUpdateNotification(this, true); - return true; - } - if (_list is null) - { - notification = default; - return false; - } - LinkedListNode? node = _list.First; - if (node is not null) - { - _list.Remove(node); - notification = new KcpConversationUpdateNotification(node.Value, true); - return true; - } - } - notification = default; - return false; - } - - public void Release() - { - lock (this) - { - if (_available && _occupied && !_signaled) - { - _signaled = true; - _packet = default; - _cancellationToken = default; - _mrvtsc.SetResult(true); - } - } - } - - internal bool TryRemove(WaitItem item) - { - lock (this) - { - LinkedList? list = _list; - if (list is null) - { - return false; - } - LinkedListNode node = item.Node; - if (node.Previous is null && node.Next is null) - { - return false; - } - list.Remove(node); + _list.Remove(node); + notification = new KcpConversationUpdateNotification(node.Value, true); return true; } } - public void Dispose() - { - if (_disposed) - { - return; - } - lock (this) - { - _disposed = true; - if (_available && !_occupied && !_signaled) - { - _signaled = true; - _packet = default; - _cancellationToken = default; - _mrvtsc.SetResult(false); - } - - LinkedList? list = _list; - if (list is not null) - { - _list = null; - - LinkedListNode? node = list.First; - LinkedListNode? next = node?.Next; - while (node is not null) - { - node.Value.Release(); - - list.Remove(node); - node = next; - next = node?.Next; - } - } - - } - } - + notification = default; + return false; } - private class WaitItem : TaskCompletionSource, IKcpConversationUpdateNotificationSource + internal bool TryRemove(WaitItem item) { - private readonly WaitList _parent; - private ReadOnlyMemory _packet; - private CancellationToken _cancellationToken; - private CancellationTokenRegistration _cancellationRegistration; - private bool _released; - - public LinkedListNode Node { get; } - - public ReadOnlyMemory Packet + lock (this) { - get + var list = _list; + if (list is null) return false; + var node = item.Node; + if (node.Previous is null && node.Next is null) return false; + list.Remove(node); + return true; + } + } + } + + private class WaitItem : TaskCompletionSource, IKcpConversationUpdateNotificationSource + { + private readonly WaitList _parent; + private CancellationTokenRegistration _cancellationRegistration; + private CancellationToken _cancellationToken; + private ReadOnlyMemory _packet; + private bool _released; + + public WaitItem(WaitList parent, ReadOnlyMemory packet, CancellationToken cancellationToken) + { + _parent = parent; + _packet = packet; + _cancellationToken = cancellationToken; + + Node = new LinkedListNode(this); + } + + public LinkedListNode Node { get; } + + public ReadOnlyMemory Packet + { + get + { + lock (this) { - lock (this) - { - if (!_released) - { - return _packet; - } - } - return default; + if (!_released) return _packet; } + + return default; + } + } + + public void Release() + { + CancellationTokenRegistration cancellationRegistration; + lock (this) + { + _released = true; + cancellationRegistration = _cancellationRegistration; + _packet = default; + _cancellationToken = default; + _cancellationRegistration = default; } - public WaitItem(WaitList parent, ReadOnlyMemory packet, CancellationToken cancellationToken) - { - _parent = parent; - _packet = packet; - _cancellationToken = cancellationToken; + TrySetResult(); + cancellationRegistration.Dispose(); + } - Node = new LinkedListNode(this); - } + public void RegisterCancellationToken() + { + _cancellationRegistration = + _cancellationToken.UnsafeRegister(state => ((WaitItem?)state)!.CancelWaiting(), this); + } - public void RegisterCancellationToken() + private void CancelWaiting() + { + CancellationTokenRegistration cancellationRegistration; + if (_parent.TryRemove(this)) { - _cancellationRegistration = _cancellationToken.UnsafeRegister(state => ((WaitItem?)state)!.CancelWaiting(), this); - } - - private void CancelWaiting() - { - CancellationTokenRegistration cancellationRegistration; - if (_parent.TryRemove(this)) - { - CancellationToken cancellationToken; - lock (this) - { - _released = true; - cancellationToken = _cancellationToken; - cancellationRegistration = _cancellationRegistration; - _packet = default; - _cancellationToken = default; - _cancellationRegistration = default; - } - TrySetCanceled(cancellationToken); - } - _cancellationRegistration.Dispose(); - } - - public void Release() - { - CancellationTokenRegistration cancellationRegistration; + CancellationToken cancellationToken; lock (this) { _released = true; + cancellationToken = _cancellationToken; cancellationRegistration = _cancellationRegistration; _packet = default; _cancellationToken = default; _cancellationRegistration = default; } - TrySetResult(); - cancellationRegistration.Dispose(); + + TrySetCanceled(cancellationToken); } + + _cancellationRegistration.Dispose(); } } -} +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpConversationUpdateNotification.cs b/GameServer/KcpSharp/KcpConversationUpdateNotification.cs index 28016a10..c9564b2a 100644 --- a/GameServer/KcpSharp/KcpConversationUpdateNotification.cs +++ b/GameServer/KcpSharp/KcpConversationUpdateNotification.cs @@ -1,30 +1,27 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal readonly struct KcpConversationUpdateNotification : IDisposable { - internal readonly struct KcpConversationUpdateNotification : IDisposable + private readonly IKcpConversationUpdateNotificationSource? _source; + private readonly bool _skipTimerNotification; + + public ReadOnlyMemory Packet => _source?.Packet ?? default; + public bool TimerNotification => !_skipTimerNotification; + + public KcpConversationUpdateNotification(IKcpConversationUpdateNotificationSource? source, + bool skipTimerNotification) { - private readonly IKcpConversationUpdateNotificationSource? _source; - private readonly bool _skipTimerNotification; - - public ReadOnlyMemory Packet => _source?.Packet ?? default; - public bool TimerNotification => !_skipTimerNotification; - - public KcpConversationUpdateNotification(IKcpConversationUpdateNotificationSource? source, bool skipTimerNotification) - { - _source = source; - _skipTimerNotification = skipTimerNotification; - } - - public KcpConversationUpdateNotification WithTimerNotification(bool timerNotification) - { - return new KcpConversationUpdateNotification(_source, !_skipTimerNotification | timerNotification); - } - - public void Dispose() - { - if (_source is not null) - { - _source.Release(); - } - } + _source = source; + _skipTimerNotification = skipTimerNotification; } -} + + public KcpConversationUpdateNotification WithTimerNotification(bool timerNotification) + { + return new KcpConversationUpdateNotification(_source, !_skipTimerNotification | timerNotification); + } + + public void Dispose() + { + if (_source is not null) _source.Release(); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpExceptionProducerExtensions.cs b/GameServer/KcpSharp/KcpExceptionProducerExtensions.cs index 7d817f1e..5e229f89 100644 --- a/GameServer/KcpSharp/KcpExceptionProducerExtensions.cs +++ b/GameServer/KcpSharp/KcpExceptionProducerExtensions.cs @@ -1,134 +1,106 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Helper methods for . +/// +public static class KcpExceptionProducerExtensions { /// - /// Helper methods for . + /// Set the handler to invoke when exception is thrown. Return true in the handler to ignore the error and continue + /// running. Return false in the handler to abort the operation. /// - public static class KcpExceptionProducerExtensions + /// The producer instance. + /// The exception handler. + public static void SetExceptionHandler(this IKcpExceptionProducer producer, Func handler) { - /// - /// Set the handler to invoke when exception is thrown. Return true in the handler to ignore the error and continue running. Return false in the handler to abort the operation. - /// - /// The producer instance. - /// The exception handler. - public static void SetExceptionHandler(this IKcpExceptionProducer producer, Func handler) - { - if (producer is null) - { - throw new ArgumentNullException(nameof(producer)); - } - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } + if (producer is null) throw new ArgumentNullException(nameof(producer)); + if (handler is null) throw new ArgumentNullException(nameof(handler)); - producer.SetExceptionHandler( - (ex, conv, state) => ((Func?)state)!.Invoke(ex, conv), - handler - ); - } - - /// - /// Set the handler to invoke when exception is thrown. Return true in the handler to ignore the error and continue running. Return false in the handler to abort the operation. - /// - /// The producer instance. - /// The exception handler. - public static void SetExceptionHandler(this IKcpExceptionProducer producer, Func handler) - { - if (producer is null) - { - throw new ArgumentNullException(nameof(producer)); - } - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } - - producer.SetExceptionHandler( - (ex, conv, state) => ((Func?)state)!.Invoke(ex), - handler - ); - } - - /// - /// Set the handler to invoke when exception is thrown. - /// - /// The producer instance. - /// The exception handler. - /// The state object to pass into the exception handler. - public static void SetExceptionHandler(this IKcpExceptionProducer producer, Action handler, object? state) - { - if (producer is null) - { - throw new ArgumentNullException(nameof(producer)); - } - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } - - producer.SetExceptionHandler( - (ex, conv, state) => - { - var tuple = (Tuple, object?>)state!; - tuple.Item1.Invoke(ex, conv, tuple.Item2); - return false; - }, - Tuple.Create(handler, state) - ); - } - - /// - /// Set the handler to invoke when exception is thrown. - /// - /// The producer instance. - /// The exception handler. - public static void SetExceptionHandler(this IKcpExceptionProducer producer, Action handler) - { - if (producer is null) - { - throw new ArgumentNullException(nameof(producer)); - } - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } - - producer.SetExceptionHandler( - (ex, conv, state) => - { - var handler = (Action)state!; - handler.Invoke(ex, conv); - return false; - }, - handler - ); - } - - /// - /// Set the handler to invoke when exception is thrown. - /// - /// The producer instance. - /// The exception handler. - public static void SetExceptionHandler(this IKcpExceptionProducer producer, Action handler) - { - if (producer is null) - { - throw new ArgumentNullException(nameof(producer)); - } - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } - - producer.SetExceptionHandler( - (ex, conv, state) => - { - var handler = (Action)state!; - handler.Invoke(ex); - return false; - }, - handler - ); - } + producer.SetExceptionHandler( + (ex, conv, state) => ((Func?)state)!.Invoke(ex, conv), + handler + ); } -} + + /// + /// Set the handler to invoke when exception is thrown. Return true in the handler to ignore the error and continue + /// running. Return false in the handler to abort the operation. + /// + /// The producer instance. + /// The exception handler. + public static void SetExceptionHandler(this IKcpExceptionProducer producer, Func handler) + { + if (producer is null) throw new ArgumentNullException(nameof(producer)); + if (handler is null) throw new ArgumentNullException(nameof(handler)); + + producer.SetExceptionHandler( + (ex, conv, state) => ((Func?)state)!.Invoke(ex), + handler + ); + } + + /// + /// Set the handler to invoke when exception is thrown. + /// + /// The producer instance. + /// The exception handler. + /// The state object to pass into the exception handler. + public static void SetExceptionHandler(this IKcpExceptionProducer producer, + Action handler, object? state) + { + if (producer is null) throw new ArgumentNullException(nameof(producer)); + if (handler is null) throw new ArgumentNullException(nameof(handler)); + + producer.SetExceptionHandler( + (ex, conv, state) => + { + var tuple = (Tuple, object?>)state!; + tuple.Item1.Invoke(ex, conv, tuple.Item2); + return false; + }, + Tuple.Create(handler, state) + ); + } + + /// + /// Set the handler to invoke when exception is thrown. + /// + /// The producer instance. + /// The exception handler. + public static void SetExceptionHandler(this IKcpExceptionProducer producer, Action handler) + { + if (producer is null) throw new ArgumentNullException(nameof(producer)); + if (handler is null) throw new ArgumentNullException(nameof(handler)); + + producer.SetExceptionHandler( + (ex, conv, state) => + { + var handler = (Action)state!; + handler.Invoke(ex, conv); + return false; + }, + handler + ); + } + + /// + /// Set the handler to invoke when exception is thrown. + /// + /// The producer instance. + /// The exception handler. + public static void SetExceptionHandler(this IKcpExceptionProducer producer, Action handler) + { + if (producer is null) throw new ArgumentNullException(nameof(producer)); + if (handler is null) throw new ArgumentNullException(nameof(handler)); + + producer.SetExceptionHandler( + (ex, conv, state) => + { + var handler = (Action)state!; + handler.Invoke(ex); + return false; + }, + handler + ); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpGlobalVars.cs b/GameServer/KcpSharp/KcpGlobalVars.cs index 99ed2303..a0fbf2dd 100644 --- a/GameServer/KcpSharp/KcpGlobalVars.cs +++ b/GameServer/KcpSharp/KcpGlobalVars.cs @@ -1,14 +1,13 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal static class KcpGlobalVars { - internal static class KcpGlobalVars - { #if !CONVID32 - public const ushort CONVID_LENGTH = 8; - public const ushort HEADER_LENGTH_WITH_CONVID = 28; - public const ushort HEADER_LENGTH_WITHOUT_CONVID = 20; + public const ushort CONVID_LENGTH = 8; + public const ushort HEADER_LENGTH_WITH_CONVID = 28; + public const ushort HEADER_LENGTH_WITHOUT_CONVID = 20; #else public const ushort HEADER_LENGTH_WITH_CONVID = 24; public const ushort HEADER_LENGTH_WITHOUT_CONVID = 20; #endif - } -} +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpKeepAliveOptions.cs b/GameServer/KcpSharp/KcpKeepAliveOptions.cs index 1e7fdda5..c9387539 100644 --- a/GameServer/KcpSharp/KcpKeepAliveOptions.cs +++ b/GameServer/KcpSharp/KcpKeepAliveOptions.cs @@ -1,30 +1,26 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Options for customized keep-alive functionality. +/// +public sealed class KcpKeepAliveOptions { /// - /// Options for customized keep-alive functionality. + /// Create an instance of option object for customized keep-alive functionality. /// - public sealed class KcpKeepAliveOptions + /// The minimum interval in milliseconds between sending keep-alive messages. + /// + /// When no packets are received during this period (in milliseconds), the transport is + /// considered to be closed. + /// + public KcpKeepAliveOptions(int sendInterval, int gracePeriod) { - /// - /// Create an instance of option object for customized keep-alive functionality. - /// - /// The minimum interval in milliseconds between sending keep-alive messages. - /// When no packets are received during this period (in milliseconds), the transport is considered to be closed. - public KcpKeepAliveOptions(int sendInterval, int gracePeriod) - { - if (sendInterval <= 0) - { - throw new ArgumentOutOfRangeException(nameof(sendInterval)); - } - if (gracePeriod <= 0) - { - throw new ArgumentOutOfRangeException(nameof(gracePeriod)); - } - SendInterval = sendInterval; - GracePeriod = gracePeriod; - } - - internal int SendInterval { get; } - internal int GracePeriod { get; } + if (sendInterval <= 0) throw new ArgumentOutOfRangeException(nameof(sendInterval)); + if (gracePeriod <= 0) throw new ArgumentOutOfRangeException(nameof(gracePeriod)); + SendInterval = sendInterval; + GracePeriod = gracePeriod; } -} + + internal int SendInterval { get; } + internal int GracePeriod { get; } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpMultiplexConnection.cs b/GameServer/KcpSharp/KcpMultiplexConnection.cs index 6cf2a09d..b66af234 100644 --- a/GameServer/KcpSharp/KcpMultiplexConnection.cs +++ b/GameServer/KcpSharp/KcpMultiplexConnection.cs @@ -1,335 +1,282 @@ -using KcpSharp; -using System.Buffers.Binary; +using System.Buffers.Binary; using System.Collections.Concurrent; using System.Net; using System.Net.Sockets; +using KcpSharp; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Multiplex many channels or conversations over the same transport. +/// +/// The state of the channel. +public sealed class KcpMultiplexConnection : IKcpTransport, IKcpConversation, IKcpMultiplexConnection { + private readonly ConcurrentDictionary _conversations = new(); + + private readonly Action? _disposeAction; + private readonly IKcpTransport _transport; + private bool _disposed; + private bool _transportClosed; + /// - /// Multiplex many channels or conversations over the same transport. + /// Construct a multiplexed connection over a transport. /// - /// The state of the channel. - public sealed class KcpMultiplexConnection : IKcpTransport, IKcpConversation, IKcpMultiplexConnection + /// The underlying transport. + public KcpMultiplexConnection(IKcpTransport transport) { - private readonly IKcpTransport _transport; + _transport = transport ?? throw new ArgumentNullException(nameof(transport)); + _disposeAction = null; + } - private readonly ConcurrentDictionary _conversations = new(); - private bool _transportClosed; - private bool _disposed; + /// + /// Construct a multiplexed connection over a transport. + /// + /// The underlying transport. + /// The action to invoke when state object is removed. + public KcpMultiplexConnection(IKcpTransport transport, Action? disposeAction) + { + _transport = transport ?? throw new ArgumentNullException(nameof(transport)); + _disposeAction = disposeAction; + } - private readonly Action? _disposeAction; + /// + /// Process a newly received packet from the transport. + /// + /// The content of the packet with conversation ID. + /// A token to cancel this operation. + /// + /// A that completes when the packet is handled by the corresponding channel or + /// conversation. + /// + public ValueTask InputPakcetAsync(UdpReceiveResult packet, CancellationToken cancellationToken = default) + { + ReadOnlySpan span = packet.Buffer.AsSpan(); + if (span.Length < KcpGlobalVars.CONVID_LENGTH) return default; + if (_transportClosed || _disposed) return default; + var id = BinaryPrimitives.ReadInt64BigEndian(span); + if (_conversations.TryGetValue(id, out var value)) + return value.Conversation.InputPakcetAsync(packet, cancellationToken); + return default; + } - /// - /// Construct a multiplexed connection over a transport. - /// - /// The underlying transport. - public KcpMultiplexConnection(IKcpTransport transport) - { - _transport = transport ?? throw new ArgumentNullException(nameof(transport)); - _disposeAction = null; - } + /// + public void SetTransportClosed() + { + _transportClosed = true; + foreach ((var conversation, var _) in _conversations.Values) conversation.SetTransportClosed(); + } - /// - /// Construct a multiplexed connection over a transport. - /// - /// The underlying transport. - /// The action to invoke when state object is removed. - public KcpMultiplexConnection(IKcpTransport transport, Action? disposeAction) - { - _transport = transport ?? throw new ArgumentNullException(nameof(transport)); - _disposeAction = disposeAction; - } - - private void CheckDispose() - { - if (_disposed) - { - ThrowObjectDisposedException(); - } - } - - private static void ThrowObjectDisposedException() - { - throw new ObjectDisposedException(nameof(KcpMultiplexConnection)); - } - - /// - /// Process a newly received packet from the transport. - /// - /// The content of the packet with conversation ID. - /// A token to cancel this operation. - /// A that completes when the packet is handled by the corresponding channel or conversation. - public ValueTask InputPakcetAsync(UdpReceiveResult packet, CancellationToken cancellationToken = default) - { - ReadOnlySpan span = packet.Buffer.AsSpan(); - if (span.Length < KcpGlobalVars.CONVID_LENGTH) - { - return default; - } - if (_transportClosed || _disposed) - { - return default; - } - long id = BinaryPrimitives.ReadInt64BigEndian(span); - if (_conversations.TryGetValue(id, out (IKcpConversation Conversation, T? State) value)) - { - return value.Conversation.InputPakcetAsync(packet, cancellationToken); - } - return default; - } - - /// - /// Determine whether the multiplex connection contains a conversation with the specified id. - /// - /// The conversation ID. - /// True if the multiplex connection contains the specified conversation. Otherwise false. - public bool Contains(long id) - { - CheckDispose(); - return _conversations.ContainsKey(id); - } - - /// - /// Create a raw channel with the specified conversation ID. - /// - /// The conversation ID. - /// The remote Endpoint - /// The options of the . - /// The raw channel created. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - public KcpRawChannel CreateRawChannel(long id, IPEndPoint remoteEndpoint, KcpRawChannelOptions? options = null) - { - KcpRawChannel? channel = new(remoteEndpoint, this, id, options); - try - { - RegisterConversation(channel, id, default); - if (_transportClosed) + /// + public void Dispose() + { + if (_disposed) return; + _transportClosed = true; + _disposed = true; + while (!_conversations.IsEmpty) + foreach (var id in _conversations.Keys) + if (_conversations.TryRemove(id, out var value)) { - channel.SetTransportClosed(); + value.Conversation.Dispose(); + if (_disposeAction is not null) _disposeAction.Invoke(value.State); } - return Interlocked.Exchange(ref channel, null)!; - } - finally - { - if (channel is not null) - { - channel.Dispose(); - } - } - } + } - /// - /// Create a raw channel with the specified conversation ID. - /// - /// The conversation ID. - /// The remote Endpoint - /// The user state of this channel. - /// The options of the . - /// The raw channel created. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - public KcpRawChannel CreateRawChannel(long id, IPEndPoint remoteEndpoint, T state, KcpRawChannelOptions? options = null) + /// + /// Determine whether the multiplex connection contains a conversation with the specified id. + /// + /// The conversation ID. + /// True if the multiplex connection contains the specified conversation. Otherwise false. + public bool Contains(long id) + { + CheckDispose(); + return _conversations.ContainsKey(id); + } + + /// + /// Create a raw channel with the specified conversation ID. + /// + /// The conversation ID. + /// The remote Endpoint + /// The options of the . + /// The raw channel created. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + public KcpRawChannel CreateRawChannel(long id, IPEndPoint remoteEndpoint, KcpRawChannelOptions? options = null) + { + KcpRawChannel? channel = new(remoteEndpoint, this, id, options); + try { - KcpRawChannel? channel = new(remoteEndpoint, this, id, options); - try - { - RegisterConversation(channel, id, state); - if (_transportClosed) - { - channel.SetTransportClosed(); - } - return Interlocked.Exchange(ref channel, null)!; - } - finally - { - if (channel is not null) - { - channel.Dispose(); - } - } + RegisterConversation(channel, id, default); + if (_transportClosed) channel.SetTransportClosed(); + return Interlocked.Exchange(ref channel, null)!; } - - /// - /// Create a conversation with the specified conversation ID. - /// - /// The conversation ID. - /// The remote Endpoint - /// The options of the . - /// The KCP conversation created. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - public KcpConversation CreateConversation(long id, IPEndPoint remoteEndpoint, KcpConversationOptions? options = null) + finally { - KcpConversation? conversation = new(remoteEndpoint, this, id, options); - try - { - RegisterConversation(conversation, id, default); - if (_transportClosed) - { - conversation.SetTransportClosed(); - } - return Interlocked.Exchange(ref conversation, null)!; - } - finally - { - if (conversation is not null) - { - conversation.Dispose(); - } - } - } - - /// - /// Create a conversation with the specified conversation ID. - /// - /// The conversation ID. - /// The remote Endpoint - /// The user state of this conversation. - /// The options of the . - /// The KCP conversation created. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - public KcpConversation CreateConversation(long id, IPEndPoint remoteEndpoint, T state, KcpConversationOptions? options = null) - { - KcpConversation? conversation = new(remoteEndpoint, this, id, options); - try - { - RegisterConversation(conversation, id, state); - if (_transportClosed) - { - conversation.SetTransportClosed(); - } - return Interlocked.Exchange(ref conversation, null)!; - } - finally - { - if (conversation is not null) - { - conversation.Dispose(); - } - } - } - - /// - /// Register a conversation or channel with the specified conversation ID and user state. - /// - /// The conversation or channel to register. - /// The conversation ID. - /// is not provided. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - public void RegisterConversation(IKcpConversation conversation, long id) - => RegisterConversation(conversation, id, default); - - /// - /// Register a conversation or channel with the specified conversation ID and user state. - /// - /// The conversation or channel to register. - /// The conversation ID. - /// The user state - /// is not provided. - /// The current instance is disposed. - /// Another channel or conversation with the same ID was already registered. - public void RegisterConversation(IKcpConversation conversation, long id, T? state) - { - if (conversation is null) - { - throw new ArgumentNullException(nameof(conversation)); - } - - CheckDispose(); - (IKcpConversation addedConversation, T? _) = _conversations.GetOrAdd(id, (conversation, state)); - if (!ReferenceEquals(addedConversation, conversation)) - { - throw new InvalidOperationException("Duplicated conversation."); - } - if (_disposed) - { - if (_conversations.TryRemove(id, out (IKcpConversation Conversation, T? State) value) && _disposeAction is not null) - { - _disposeAction.Invoke(value.State); - } - ThrowObjectDisposedException(); - } - } - - /// - /// Unregister a conversation or channel with the specified conversation ID. - /// - /// The conversation ID. - /// The conversation unregistered. Returns null when the conversation with the specified ID is not found. - public IKcpConversation? UnregisterConversation(long id) - { - return UnregisterConversation(id, out _); - } - - /// - /// Unregister a conversation or channel with the specified conversation ID. - /// - /// The conversation ID. - /// The user state. - /// The conversation unregistered. Returns null when the conversation with the specified ID is not found. - public IKcpConversation? UnregisterConversation(long id, out T? state) - { - if (!_transportClosed && !_disposed && _conversations.TryRemove(id, out (IKcpConversation Conversation, T? State) value)) - { - value.Conversation.SetTransportClosed(); - state = value.State; - if (_disposeAction is not null) - { - _disposeAction.Invoke(state); - } - return value.Conversation; - } - state = default; - return default; - } - - /// - public ValueTask SendPacketAsync(Memory packet, IPEndPoint remoteEndpoint, CancellationToken cancellationToken = default) - { - if (_transportClosed || _disposed) - { - return default; - } - return _transport.SendPacketAsync(packet, remoteEndpoint, cancellationToken); - } - - /// - public void SetTransportClosed() - { - _transportClosed = true; - foreach ((IKcpConversation conversation, T? _) in _conversations.Values) - { - conversation.SetTransportClosed(); - } - } - - /// - public void Dispose() - { - if (_disposed) - { - return; - } - _transportClosed = true; - _disposed = true; - while (!_conversations.IsEmpty) - { - foreach (long id in _conversations.Keys) - { - if (_conversations.TryRemove(id, out (IKcpConversation Conversation, T? State) value)) - { - value.Conversation.Dispose(); - if (_disposeAction is not null) - { - _disposeAction.Invoke(value.State); - } - } - } - } + if (channel is not null) channel.Dispose(); } } -} + + /// + /// Create a raw channel with the specified conversation ID. + /// + /// The conversation ID. + /// The remote Endpoint + /// The user state of this channel. + /// The options of the . + /// The raw channel created. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + public KcpRawChannel CreateRawChannel(long id, IPEndPoint remoteEndpoint, T state, + KcpRawChannelOptions? options = null) + { + KcpRawChannel? channel = new(remoteEndpoint, this, id, options); + try + { + RegisterConversation(channel, id, state); + if (_transportClosed) channel.SetTransportClosed(); + return Interlocked.Exchange(ref channel, null)!; + } + finally + { + if (channel is not null) channel.Dispose(); + } + } + + /// + /// Create a conversation with the specified conversation ID. + /// + /// The conversation ID. + /// The remote Endpoint + /// The options of the . + /// The KCP conversation created. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + public KcpConversation CreateConversation(long id, IPEndPoint remoteEndpoint, + KcpConversationOptions? options = null) + { + KcpConversation? conversation = new(remoteEndpoint, this, id, options); + try + { + RegisterConversation(conversation, id, default); + if (_transportClosed) conversation.SetTransportClosed(); + return Interlocked.Exchange(ref conversation, null)!; + } + finally + { + if (conversation is not null) conversation.Dispose(); + } + } + + /// + /// Create a conversation with the specified conversation ID. + /// + /// The conversation ID. + /// The remote Endpoint + /// The user state of this conversation. + /// The options of the . + /// The KCP conversation created. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + public KcpConversation CreateConversation(long id, IPEndPoint remoteEndpoint, T state, + KcpConversationOptions? options = null) + { + KcpConversation? conversation = new(remoteEndpoint, this, id, options); + try + { + RegisterConversation(conversation, id, state); + if (_transportClosed) conversation.SetTransportClosed(); + return Interlocked.Exchange(ref conversation, null)!; + } + finally + { + if (conversation is not null) conversation.Dispose(); + } + } + + /// + /// Register a conversation or channel with the specified conversation ID and user state. + /// + /// The conversation or channel to register. + /// The conversation ID. + /// is not provided. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + public void RegisterConversation(IKcpConversation conversation, long id) + { + RegisterConversation(conversation, id, default); + } + + /// + /// Register a conversation or channel with the specified conversation ID and user state. + /// + /// The conversation or channel to register. + /// The conversation ID. + /// The user state + /// is not provided. + /// The current instance is disposed. + /// Another channel or conversation with the same ID was already registered. + public void RegisterConversation(IKcpConversation conversation, long id, T? state) + { + if (conversation is null) throw new ArgumentNullException(nameof(conversation)); + + CheckDispose(); + (var addedConversation, var _) = _conversations.GetOrAdd(id, (conversation, state)); + if (!ReferenceEquals(addedConversation, conversation)) + throw new InvalidOperationException("Duplicated conversation."); + if (_disposed) + { + if (_conversations.TryRemove(id, out var value) && _disposeAction is not null) + _disposeAction.Invoke(value.State); + ThrowObjectDisposedException(); + } + } + + /// + /// Unregister a conversation or channel with the specified conversation ID. + /// + /// The conversation ID. + /// The conversation unregistered. Returns null when the conversation with the specified ID is not found. + public IKcpConversation? UnregisterConversation(long id) + { + return UnregisterConversation(id, out _); + } + + /// + /// Unregister a conversation or channel with the specified conversation ID. + /// + /// The conversation ID. + /// The user state. + /// The conversation unregistered. Returns null when the conversation with the specified ID is not found. + public IKcpConversation? UnregisterConversation(long id, out T? state) + { + if (!_transportClosed && !_disposed && _conversations.TryRemove(id, out var value)) + { + value.Conversation.SetTransportClosed(); + state = value.State; + if (_disposeAction is not null) _disposeAction.Invoke(state); + return value.Conversation; + } + + state = default; + return default; + } + + /// + public ValueTask SendPacketAsync(Memory packet, IPEndPoint remoteEndpoint, + CancellationToken cancellationToken = default) + { + if (_transportClosed || _disposed) return default; + return _transport.SendPacketAsync(packet, remoteEndpoint, cancellationToken); + } + + private void CheckDispose() + { + if (_disposed) ThrowObjectDisposedException(); + } + + private static void ThrowObjectDisposedException() + { + throw new ObjectDisposedException(nameof(KcpMultiplexConnection)); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpPacketHeader.cs b/GameServer/KcpSharp/KcpPacketHeader.cs index 5ecc8602..f83b2def 100644 --- a/GameServer/KcpSharp/KcpPacketHeader.cs +++ b/GameServer/KcpSharp/KcpPacketHeader.cs @@ -1,75 +1,89 @@ using System.Buffers.Binary; using System.Diagnostics; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal readonly struct KcpPacketHeader : IEquatable { - internal readonly struct KcpPacketHeader : IEquatable + public KcpPacketHeader(KcpCommand command, byte fragment, ushort windowSize, uint timestamp, uint serialNumber, + uint unacknowledged) { - public KcpPacketHeader(KcpCommand command, byte fragment, ushort windowSize, uint timestamp, uint serialNumber, uint unacknowledged) - { - Command = command; - Fragment = fragment; - WindowSize = windowSize; - Timestamp = timestamp; - SerialNumber = serialNumber; - Unacknowledged = unacknowledged; - } - - internal KcpPacketHeader(byte fragment) - { - Command = 0; - Fragment = fragment; - WindowSize = 0; - Timestamp = 0; - SerialNumber = 0; - Unacknowledged = 0; - } - - public KcpCommand Command { get; } - public byte Fragment { get; } - public ushort WindowSize { get; } - public uint Timestamp { get; } - public uint SerialNumber { get; } - public uint Unacknowledged { get; } - - public bool Equals(KcpPacketHeader other) => Command == other.Command && Fragment == other.Fragment && WindowSize == other.WindowSize && Timestamp == other.Timestamp && SerialNumber == other.SerialNumber && Unacknowledged == other.Unacknowledged; - public override bool Equals(object? obj) => obj is KcpPacketHeader other && Equals(other); - public override int GetHashCode() => HashCode.Combine(Command, Fragment, WindowSize, Timestamp, SerialNumber, Unacknowledged); - - public static KcpPacketHeader Parse(ReadOnlySpan buffer) - { - Debug.Assert(buffer.Length >= 16); - return new KcpPacketHeader( - (KcpCommand)buffer[0], - buffer[1], - BinaryPrimitives.ReadUInt16LittleEndian(buffer.Slice(2)), - BinaryPrimitives.ReadUInt32LittleEndian(buffer.Slice(4)), - BinaryPrimitives.ReadUInt32LittleEndian(buffer.Slice(8)), - BinaryPrimitives.ReadUInt32LittleEndian(buffer.Slice(12)) - ); - } - - internal void EncodeHeader(ulong? conversationId, int payloadLength, Span destination, out int bytesWritten) - { - Debug.Assert(destination.Length >= 20); - if (conversationId.HasValue) - { - BinaryPrimitives.WriteUInt64BigEndian(destination, conversationId.GetValueOrDefault()); - destination = destination.Slice(8); - bytesWritten = 28; - } - else - { - bytesWritten = 20; - } - Debug.Assert(destination.Length >= 20); - destination[1] = Fragment; - destination[0] = (byte)Command; - BinaryPrimitives.WriteUInt16LittleEndian(destination.Slice(2), WindowSize); - BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(4), Timestamp); - BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(8), SerialNumber); - BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(12), Unacknowledged); - BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(16), (uint)payloadLength); - } + Command = command; + Fragment = fragment; + WindowSize = windowSize; + Timestamp = timestamp; + SerialNumber = serialNumber; + Unacknowledged = unacknowledged; } -} + + internal KcpPacketHeader(byte fragment) + { + Command = 0; + Fragment = fragment; + WindowSize = 0; + Timestamp = 0; + SerialNumber = 0; + Unacknowledged = 0; + } + + public KcpCommand Command { get; } + public byte Fragment { get; } + public ushort WindowSize { get; } + public uint Timestamp { get; } + public uint SerialNumber { get; } + public uint Unacknowledged { get; } + + public bool Equals(KcpPacketHeader other) + { + return Command == other.Command && Fragment == other.Fragment && WindowSize == other.WindowSize && + Timestamp == other.Timestamp && SerialNumber == other.SerialNumber && + Unacknowledged == other.Unacknowledged; + } + + public override bool Equals(object? obj) + { + return obj is KcpPacketHeader other && Equals(other); + } + + public override int GetHashCode() + { + return HashCode.Combine(Command, Fragment, WindowSize, Timestamp, SerialNumber, Unacknowledged); + } + + public static KcpPacketHeader Parse(ReadOnlySpan buffer) + { + Debug.Assert(buffer.Length >= 16); + return new KcpPacketHeader( + (KcpCommand)buffer[0], + buffer[1], + BinaryPrimitives.ReadUInt16LittleEndian(buffer.Slice(2)), + BinaryPrimitives.ReadUInt32LittleEndian(buffer.Slice(4)), + BinaryPrimitives.ReadUInt32LittleEndian(buffer.Slice(8)), + BinaryPrimitives.ReadUInt32LittleEndian(buffer.Slice(12)) + ); + } + + internal void EncodeHeader(ulong? conversationId, int payloadLength, Span destination, out int bytesWritten) + { + Debug.Assert(destination.Length >= 20); + if (conversationId.HasValue) + { + BinaryPrimitives.WriteUInt64BigEndian(destination, conversationId.GetValueOrDefault()); + destination = destination.Slice(8); + bytesWritten = 28; + } + else + { + bytesWritten = 20; + } + + Debug.Assert(destination.Length >= 20); + destination[1] = Fragment; + destination[0] = (byte)Command; + BinaryPrimitives.WriteUInt16LittleEndian(destination.Slice(2), WindowSize); + BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(4), Timestamp); + BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(8), SerialNumber); + BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(12), Unacknowledged); + BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(16), (uint)payloadLength); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpProbeType.cs b/GameServer/KcpSharp/KcpProbeType.cs index 34b28c2a..9ed59768 100644 --- a/GameServer/KcpSharp/KcpProbeType.cs +++ b/GameServer/KcpSharp/KcpProbeType.cs @@ -1,10 +1,9 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +[Flags] +internal enum KcpProbeType { - [Flags] - internal enum KcpProbeType - { - None = 0, - AskSend = 1, - AskTell = 2, - } -} + None = 0, + AskSend = 1, + AskTell = 2 +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpRawChannel.cs b/GameServer/KcpSharp/KcpRawChannel.cs index 2e1101f9..99e1d105 100644 --- a/GameServer/KcpSharp/KcpRawChannel.cs +++ b/GameServer/KcpSharp/KcpRawChannel.cs @@ -1,372 +1,401 @@ -using KcpSharp; -using System.Buffers.Binary; +using System.Buffers.Binary; using System.Net; using System.Net.Sockets; +using KcpSharp; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// An unreliable channel with a conversation ID. +/// +public sealed class KcpRawChannel : IKcpConversation, IKcpExceptionProducer { + private readonly IKcpBufferPool _bufferPool; + private readonly ulong? _id; + private readonly int _mtu; + private readonly int _postBufferSize; + private readonly int _preBufferSize; + private readonly KcpRawReceiveQueue _receiveQueue; + private readonly IPEndPoint _remoteEndPoint; + private readonly AsyncAutoResetEvent _sendNotification; + private readonly KcpRawSendOperation _sendOperation; + private readonly IKcpTransport _transport; + + private Func? _exceptionHandler; + private object? _exceptionHandlerState; + + private CancellationTokenSource? _sendLoopCts; + /// - /// An unreliable channel with a conversation ID. + /// Construct a unreliable channel with a conversation ID. /// - public sealed class KcpRawChannel : IKcpConversation, IKcpExceptionProducer + /// The remote Endpoint + /// The underlying transport. + /// The options of the . + public KcpRawChannel(IPEndPoint remoteEndPoint, IKcpTransport transport, KcpRawChannelOptions? options) + : this(remoteEndPoint, transport, null, options) { - private readonly IKcpBufferPool _bufferPool; - private readonly IKcpTransport _transport; - private readonly IPEndPoint _remoteEndPoint; - private readonly ulong? _id; - private readonly int _mtu; - private readonly int _preBufferSize; - private readonly int _postBufferSize; + } - private CancellationTokenSource? _sendLoopCts; - private readonly KcpRawReceiveQueue _receiveQueue; - private readonly KcpRawSendOperation _sendOperation; - private readonly AsyncAutoResetEvent _sendNotification; + /// + /// Construct a unreliable channel with a conversation ID. + /// + /// The remote Endpoint + /// The underlying transport. + /// The conversation ID. + /// The options of the . + public KcpRawChannel(IPEndPoint remoteEndPoint, IKcpTransport transport, long conversationId, + KcpRawChannelOptions? options) + : this(remoteEndPoint, transport, (ulong)conversationId, options) + { + } - private Func? _exceptionHandler; - private object? _exceptionHandlerState; + private KcpRawChannel(IPEndPoint remoteEndPoint, IKcpTransport transport, ulong? conversationId, + KcpRawChannelOptions? options) + { + _bufferPool = options?.BufferPool ?? DefaultArrayPoolBufferAllocator.Default; + _remoteEndPoint = remoteEndPoint; + _transport = transport; + _id = conversationId; - /// - /// Construct a unreliable channel with a conversation ID. - /// - /// The remote Endpoint - /// The underlying transport. - /// The options of the . - public KcpRawChannel(IPEndPoint remoteEndPoint, IKcpTransport transport, KcpRawChannelOptions? options) - : this(remoteEndPoint, transport, null, options) - { } + if (options is null) + _mtu = KcpConversationOptions.MtuDefaultValue; + else if (options.Mtu < 50) + throw new ArgumentException("MTU must be at least 50.", nameof(options)); + else + _mtu = options.Mtu; - /// - /// Construct a unreliable channel with a conversation ID. - /// - /// The remote Endpoint - /// The underlying transport. - /// The conversation ID. - /// The options of the . - public KcpRawChannel(IPEndPoint remoteEndPoint, IKcpTransport transport, long conversationId, KcpRawChannelOptions? options) - : this(remoteEndPoint, transport, (ulong)conversationId, options) - { } + _preBufferSize = options?.PreBufferSize ?? 0; + _postBufferSize = options?.PostBufferSize ?? 0; + if (_preBufferSize < 0) + throw new ArgumentException("PreBufferSize must be a non-negative integer.", nameof(options)); + if (_postBufferSize < 0) + throw new ArgumentException("PostBufferSize must be a non-negative integer.", nameof(options)); + if ((uint)(_preBufferSize + _postBufferSize) >= (uint)_mtu) + throw new ArgumentException("The sum of PreBufferSize and PostBufferSize must be less than MTU.", + nameof(options)); + if (conversationId.HasValue && (uint)(_preBufferSize + _postBufferSize) >= (uint)(_mtu - 4)) + throw new ArgumentException( + "The sum of PreBufferSize and PostBufferSize is too large. There is not enough space in the packet for the conversation ID.", + nameof(options)); - private KcpRawChannel(IPEndPoint remoteEndPoint, IKcpTransport transport, ulong? conversationId, KcpRawChannelOptions? options) + var queueSize = options?.ReceiveQueueSize ?? 32; + if (queueSize < 1) throw new ArgumentException("QueueSize must be a positive integer.", nameof(options)); + + _sendLoopCts = new CancellationTokenSource(); + _sendNotification = new AsyncAutoResetEvent(); + _receiveQueue = new KcpRawReceiveQueue(_bufferPool, queueSize); + _sendOperation = new KcpRawSendOperation(_sendNotification); + + RunSendLoop(); + } + + /// + /// Get the ID of the current conversation. + /// + public long? ConversationId => (long?)_id; + + /// + /// Get whether the transport is marked as closed. + /// + public bool TransportClosed => _sendLoopCts is null; + + /// + public ValueTask InputPakcetAsync(UdpReceiveResult packet, CancellationToken cancellationToken = default) + { + ReadOnlySpan span = packet.Buffer.AsSpan(); + var overhead = _id.HasValue ? KcpGlobalVars.CONVID_LENGTH : 0; + if (span.Length < overhead || span.Length > _mtu) return default; + if (_id.HasValue) { - _bufferPool = options?.BufferPool ?? DefaultArrayPoolBufferAllocator.Default; - _remoteEndPoint = remoteEndPoint; - _transport = transport; - _id = conversationId; - - if (options is null) - { - _mtu = KcpConversationOptions.MtuDefaultValue; - } - else if (options.Mtu < 50) - { - throw new ArgumentException("MTU must be at least 50.", nameof(options)); - } - else - { - _mtu = options.Mtu; - } - - _preBufferSize = options?.PreBufferSize ?? 0; - _postBufferSize = options?.PostBufferSize ?? 0; - if (_preBufferSize < 0) - { - throw new ArgumentException("PreBufferSize must be a non-negative integer.", nameof(options)); - } - if (_postBufferSize < 0) - { - throw new ArgumentException("PostBufferSize must be a non-negative integer.", nameof(options)); - } - if ((uint)(_preBufferSize + _postBufferSize) >= (uint)_mtu) - { - throw new ArgumentException("The sum of PreBufferSize and PostBufferSize must be less than MTU.", nameof(options)); - } - if (conversationId.HasValue && (uint)(_preBufferSize + _postBufferSize) >= (uint)(_mtu - 4)) - { - throw new ArgumentException("The sum of PreBufferSize and PostBufferSize is too large. There is not enough space in the packet for the conversation ID.", nameof(options)); - } - - int queueSize = options?.ReceiveQueueSize ?? 32; - if (queueSize < 1) - { - throw new ArgumentException("QueueSize must be a positive integer.", nameof(options)); - } - - _sendLoopCts = new CancellationTokenSource(); - _sendNotification = new AsyncAutoResetEvent(); - _receiveQueue = new KcpRawReceiveQueue(_bufferPool, queueSize); - _sendOperation = new KcpRawSendOperation(_sendNotification); - - RunSendLoop(); + if (BinaryPrimitives.ReadUInt64BigEndian(span) != _id.GetValueOrDefault()) return default; + span = span.Slice(8); } - /// - /// Set the handler to invoke when exception is thrown during flushing packets to the transport. Return true in the handler to ignore the error and continue running. Return false in the handler to abort the operation and mark the transport as closed. - /// - /// The exception handler. - /// The state object to pass into the exception handler. - public void SetExceptionHandler(Func handler, object? state) - { - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } + _receiveQueue.Enqueue(span); + return default; + } - _exceptionHandler = handler; - _exceptionHandlerState = state; + + /// + public void SetTransportClosed() + { + var cts = Interlocked.Exchange(ref _sendLoopCts, null); + if (cts is not null) + { + cts.Cancel(); + cts.Dispose(); } - /// - /// Get the ID of the current conversation. - /// - public long? ConversationId => (long?)_id; + _receiveQueue.SetTransportClosed(); + _sendOperation.SetTransportClosed(); + _sendNotification.Set(0); + } - /// - /// Get whether the transport is marked as closed. - /// - public bool TransportClosed => _sendLoopCts is null; + /// + public void Dispose() + { + SetTransportClosed(); + _receiveQueue.Dispose(); + _sendOperation.Dispose(); + } - /// - /// Send message to the underlying transport. - /// - /// The content of the message - /// The token to cancel this operation. - /// The size of the message is larger than mtu, thus it can not be sent. - /// The is fired before send operation is completed. - /// The send operation is initiated concurrently. - /// The instance is disposed. - /// A that completes when the entire message is put into the queue. The result of the task is false when the transport is closed. - public ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) - => _sendOperation.SendAsync(buffer, cancellationToken); + /// + /// Set the handler to invoke when exception is thrown during flushing packets to the transport. Return true in the + /// handler to ignore the error and continue running. Return false in the handler to abort the operation and mark the + /// transport as closed. + /// + /// The exception handler. + /// The state object to pass into the exception handler. + public void SetExceptionHandler(Func handler, object? state) + { + if (handler is null) throw new ArgumentNullException(nameof(handler)); + + _exceptionHandler = handler; + _exceptionHandlerState = state; + } + + /// + /// Send message to the underlying transport. + /// + /// The content of the message + /// The token to cancel this operation. + /// The size of the message is larger than mtu, thus it can not be sent. + /// + /// The is fired before send operation + /// is completed. + /// + /// The send operation is initiated concurrently. + /// The instance is disposed. + /// + /// A that completes when the entire message is put into the queue. The result + /// of the task is false when the transport is closed. + /// + public ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + return _sendOperation.SendAsync(buffer, cancellationToken); + } - /// - /// Cancel the current send operation or flush operation. - /// - /// True if the current operation is canceled. False if there is no active send operation. - public bool CancelPendingSend() - => _sendOperation.CancelPendingOperation(null, default); + /// + /// Cancel the current send operation or flush operation. + /// + /// True if the current operation is canceled. False if there is no active send operation. + public bool CancelPendingSend() + { + return _sendOperation.CancelPendingOperation(null, default); + } - /// - /// Cancel the current send operation or flush operation. - /// - /// The inner exception of the thrown by the method. - /// The in the thrown by the method. - /// True if the current operation is canceled. False if there is no active send operation. - public bool CancelPendingSend(Exception? innerException, CancellationToken cancellationToken) - => _sendOperation.CancelPendingOperation(innerException, cancellationToken); + /// + /// Cancel the current send operation or flush operation. + /// + /// + /// The inner exception of the thrown by the + /// method. + /// + /// + /// The in the + /// thrown by the method. + /// + /// True if the current operation is canceled. False if there is no active send operation. + public bool CancelPendingSend(Exception? innerException, CancellationToken cancellationToken) + { + return _sendOperation.CancelPendingOperation(innerException, cancellationToken); + } - private async void RunSendLoop() + private async void RunSendLoop() + { + var cancellationToken = _sendLoopCts?.Token ?? new CancellationToken(true); + var sendOperation = _sendOperation; + var ev = _sendNotification; + var mss = _mtu - _preBufferSize - _postBufferSize; + if (_id.HasValue) mss -= 8; + + try { - CancellationToken cancellationToken = _sendLoopCts?.Token ?? new CancellationToken(true); - KcpRawSendOperation sendOperation = _sendOperation; - AsyncAutoResetEvent ev = _sendNotification; - int mss = _mtu - _preBufferSize - _postBufferSize; - if (_id.HasValue) + while (!cancellationToken.IsCancellationRequested) { - mss -= 8; - } + var payloadSize = await ev.WaitAsync().ConfigureAwait(false); + if (cancellationToken.IsCancellationRequested) break; - try - { - while (!cancellationToken.IsCancellationRequested) + if (payloadSize < 0 || payloadSize > mss) { - int payloadSize = await ev.WaitAsync().ConfigureAwait(false); - if (cancellationToken.IsCancellationRequested) + _ = sendOperation.TryConsume(default, out _); + continue; + } + + var overhead = _preBufferSize + _postBufferSize; + if (_id.HasValue) overhead += 8; + { + using var owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(payloadSize + overhead, true)); + var memory = owner.Memory; + + // Fill the buffer + if (_preBufferSize != 0) { - break; + memory.Span.Slice(0, _preBufferSize).Clear(); + memory = memory.Slice(_preBufferSize); } - if (payloadSize < 0 || payloadSize > mss) - { - _ = sendOperation.TryConsume(default, out _); - continue; - } - - int overhead = _preBufferSize + _postBufferSize; if (_id.HasValue) { - overhead += 8; + BinaryPrimitives.WriteUInt64LittleEndian(memory.Span, _id.GetValueOrDefault()); + memory = memory.Slice(8); } + + if (!sendOperation.TryConsume(memory, out var bytesWritten)) continue; + payloadSize = Math.Min(payloadSize, bytesWritten); + memory = memory.Slice(payloadSize); + if (_postBufferSize != 0) memory.Span.Slice(0, _postBufferSize).Clear(); + + // Send the buffer + try { - using KcpRentedBuffer owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(payloadSize + overhead, true)); - Memory memory = owner.Memory; - - // Fill the buffer - if (_preBufferSize != 0) - { - memory.Span.Slice(0, _preBufferSize).Clear(); - memory = memory.Slice(_preBufferSize); - } - if (_id.HasValue) - { - BinaryPrimitives.WriteUInt64LittleEndian(memory.Span, _id.GetValueOrDefault()); - memory = memory.Slice(8); - } - if (!sendOperation.TryConsume(memory, out int bytesWritten)) - { - continue; - } - payloadSize = Math.Min(payloadSize, bytesWritten); - memory = memory.Slice(payloadSize); - if (_postBufferSize != 0) - { - memory.Span.Slice(0, _postBufferSize).Clear(); - } - - // Send the buffer - try - { - await _transport.SendPacketAsync(owner.Memory.Slice(0, payloadSize + overhead), _remoteEndPoint, cancellationToken).ConfigureAwait(false); - } - catch (Exception ex) - { - if (!HandleFlushException(ex)) - { - break; - } - } + await _transport.SendPacketAsync(owner.Memory.Slice(0, payloadSize + overhead), _remoteEndPoint, + cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + if (!HandleFlushException(ex)) break; } } } - catch (OperationCanceledException) - { - // Do nothing - } - catch (Exception ex) - { - HandleFlushException(ex); - } } - - - private bool HandleFlushException(Exception ex) + catch (OperationCanceledException) { - Func? handler = _exceptionHandler; - object? state = _exceptionHandlerState; - bool result = false; - if (handler is not null) - { - try - { - result = handler.Invoke(ex, this, state); - } - catch - { - result = false; - } - } - - if (!result) - { - SetTransportClosed(); - } - return result; + // Do nothing } - - /// - public ValueTask InputPakcetAsync(UdpReceiveResult packet, CancellationToken cancellationToken = default) + catch (Exception ex) { - ReadOnlySpan span = packet.Buffer.AsSpan(); - int overhead = _id.HasValue ? KcpGlobalVars.CONVID_LENGTH : 0; - if (span.Length < overhead || span.Length > _mtu) - { - return default; - } - if (_id.HasValue) - { - if (BinaryPrimitives.ReadUInt64BigEndian(span) != _id.GetValueOrDefault()) - { - return default; - } - span = span.Slice(8); - } - _receiveQueue.Enqueue(span); - return default; - } - - /// - /// Get the size of the next available message in the receive queue. - /// - /// The transport state and the size of the next available message. - /// The receive or peek operation is initiated concurrently. - /// True if the receive queue contains at least one message. False if the receive queue is empty or the transport is closed. - public bool TryPeek(out KcpConversationReceiveResult result) - => _receiveQueue.TryPeek(out result); - - /// - /// Remove the next available message in the receive queue and copy its content into . - /// - /// The buffer to receive message. - /// The transport state and the count of bytes moved into . - /// The size of the next available message is larger than the size of . - /// The receive or peek operation is initiated concurrently. - /// True if the next available message is moved into . False if the receive queue is empty or the transport is closed. - public bool TryReceive(Span buffer, out KcpConversationReceiveResult result) - => _receiveQueue.TryReceive(buffer, out result); - - /// - /// Wait until the receive queue contains at least one message. - /// - /// The token to cancel this operation. - /// The is fired before receive operation is completed. - /// The receive or peek operation is initiated concurrently. - /// A that completes when the receive queue contains at least one full message, or at least one byte in stream mode. Its result contains the transport state and the size of the available message. - public ValueTask WaitToReceiveAsync(CancellationToken cancellationToken) - => _receiveQueue.WaitToReceiveAsync(cancellationToken); - - /// - /// Wait for the next full message to arrive if the receive queue is empty. Remove the next available message in the receive queue and copy its content into . - /// - /// The buffer to receive message. - /// The token to cancel this operation. - /// The size of the next available message is larger than the size of . - /// The is fired before send operation is completed. - /// The receive or peek operation is initiated concurrently. - /// A that completes when a message is moved into or the transport is closed. Its result contains the transport state and the count of bytes written into . - public ValueTask ReceiveAsync(Memory buffer, CancellationToken cancellationToken = default) - => _receiveQueue.ReceiveAsync(buffer, cancellationToken); - - - /// - /// Cancel the current receive operation. - /// - /// True if the current operation is canceled. False if there is no active send operation. - public bool CancelPendingReceive() - => _receiveQueue.CancelPendingOperation(null, default); - - /// - /// Cancel the current send operation or flush operation. - /// - /// The inner exception of the thrown by the method or method. - /// The in the thrown by the method or method. - /// True if the current operation is canceled. False if there is no active send operation. - public bool CancelPendingReceive(Exception? innerException, CancellationToken cancellationToken) - => _receiveQueue.CancelPendingOperation(innerException, cancellationToken); - - - /// - public void SetTransportClosed() - { - CancellationTokenSource? cts = Interlocked.Exchange(ref _sendLoopCts, null); - if (cts is not null) - { - cts.Cancel(); - cts.Dispose(); - } - - _receiveQueue.SetTransportClosed(); - _sendOperation.SetTransportClosed(); - _sendNotification.Set(0); - } - - /// - public void Dispose() - { - SetTransportClosed(); - _receiveQueue.Dispose(); - _sendOperation.Dispose(); + HandleFlushException(ex); } } -} + + + private bool HandleFlushException(Exception ex) + { + var handler = _exceptionHandler; + var state = _exceptionHandlerState; + var result = false; + if (handler is not null) + try + { + result = handler.Invoke(ex, this, state); + } + catch + { + result = false; + } + + if (!result) SetTransportClosed(); + return result; + } + + /// + /// Get the size of the next available message in the receive queue. + /// + /// The transport state and the size of the next available message. + /// The receive or peek operation is initiated concurrently. + /// + /// True if the receive queue contains at least one message. False if the receive queue is empty or the transport + /// is closed. + /// + public bool TryPeek(out KcpConversationReceiveResult result) + { + return _receiveQueue.TryPeek(out result); + } + + /// + /// Remove the next available message in the receive queue and copy its content into . + /// + /// The buffer to receive message. + /// The transport state and the count of bytes moved into . + /// + /// The size of the next available message is larger than the size of + /// . + /// + /// The receive or peek operation is initiated concurrently. + /// + /// True if the next available message is moved into . False if the receive queue is + /// empty or the transport is closed. + /// + public bool TryReceive(Span buffer, out KcpConversationReceiveResult result) + { + return _receiveQueue.TryReceive(buffer, out result); + } + + /// + /// Wait until the receive queue contains at least one message. + /// + /// The token to cancel this operation. + /// + /// The is fired before receive + /// operation is completed. + /// + /// The receive or peek operation is initiated concurrently. + /// + /// A that completes when the receive queue contains at + /// least one full message, or at least one byte in stream mode. Its result contains the transport state and the size + /// of the available message. + /// + public ValueTask WaitToReceiveAsync(CancellationToken cancellationToken) + { + return _receiveQueue.WaitToReceiveAsync(cancellationToken); + } + + /// + /// Wait for the next full message to arrive if the receive queue is empty. Remove the next available message in the + /// receive queue and copy its content into . + /// + /// The buffer to receive message. + /// The token to cancel this operation. + /// + /// The size of the next available message is larger than the size of + /// . + /// + /// + /// The is fired before send operation + /// is completed. + /// + /// The receive or peek operation is initiated concurrently. + /// + /// A that completes when a message is moved into + /// or the transport is closed. Its result contains the transport state and the count of + /// bytes written into . + /// + public ValueTask ReceiveAsync(Memory buffer, + CancellationToken cancellationToken = default) + { + return _receiveQueue.ReceiveAsync(buffer, cancellationToken); + } + + + /// + /// Cancel the current receive operation. + /// + /// True if the current operation is canceled. False if there is no active send operation. + public bool CancelPendingReceive() + { + return _receiveQueue.CancelPendingOperation(null, default); + } + + /// + /// Cancel the current send operation or flush operation. + /// + /// + /// The inner exception of the thrown by the + /// method or + /// method. + /// + /// + /// The in the + /// thrown by the method or + /// method. + /// + /// True if the current operation is canceled. False if there is no active send operation. + public bool CancelPendingReceive(Exception? innerException, CancellationToken cancellationToken) + { + return _receiveQueue.CancelPendingOperation(innerException, cancellationToken); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpRawChannelOptions.cs b/GameServer/KcpSharp/KcpRawChannelOptions.cs index 5a5fc92a..4140b168 100644 --- a/GameServer/KcpSharp/KcpRawChannelOptions.cs +++ b/GameServer/KcpSharp/KcpRawChannelOptions.cs @@ -1,33 +1,34 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Options used to control the behaviors of . +/// +public sealed class KcpRawChannelOptions { /// - /// Options used to control the behaviors of . + /// The buffer pool to rent buffer from. /// - public sealed class KcpRawChannelOptions - { - /// - /// The buffer pool to rent buffer from. - /// - public IKcpBufferPool? BufferPool { get; set; } + public IKcpBufferPool? BufferPool { get; set; } - /// - /// The maximum packet size that can be transmitted over the underlying transport. - /// - public int Mtu { get; set; } = 1400; + /// + /// The maximum packet size that can be transmitted over the underlying transport. + /// + public int Mtu { get; set; } = 1400; - /// - /// The number of packets in the receive queue. - /// - public int ReceiveQueueSize { get; set; } = 32; + /// + /// The number of packets in the receive queue. + /// + public int ReceiveQueueSize { get; set; } = 32; - /// - /// The number of bytes to reserve at the start of buffer passed into the underlying transport. The transport should fill this reserved space. - /// - public int PreBufferSize { get; set; } + /// + /// The number of bytes to reserve at the start of buffer passed into the underlying transport. The transport should + /// fill this reserved space. + /// + public int PreBufferSize { get; set; } - /// - /// The number of bytes to reserve at the end of buffer passed into the underlying transport. The transport should fill this reserved space. - /// - public int PostBufferSize { get; set; } - } -} + /// + /// The number of bytes to reserve at the end of buffer passed into the underlying transport. The transport should fill + /// this reserved space. + /// + public int PostBufferSize { get; set; } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpRawReceiveQueue.cs b/GameServer/KcpSharp/KcpRawReceiveQueue.cs index 1b2c5c15..f25d5551 100644 --- a/GameServer/KcpSharp/KcpRawReceiveQueue.cs +++ b/GameServer/KcpSharp/KcpRawReceiveQueue.cs @@ -1,358 +1,342 @@ -using System.Threading.Tasks.Sources; -using System.Diagnostics; - - - - -#if NEED_LINKEDLIST_SHIM +#if NEED_LINKEDLIST_SHIM using LinkedListOfQueueItem = KcpSharp.NetstandardShim.LinkedList; using LinkedListNodeOfQueueItem = KcpSharp.NetstandardShim.LinkedListNode; #else using LinkedListOfQueueItem = System.Collections.Generic.LinkedList; using LinkedListNodeOfQueueItem = System.Collections.Generic.LinkedListNode; #endif +using System.Diagnostics; +using System.Threading.Tasks.Sources; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class KcpRawReceiveQueue : IValueTaskSource, IDisposable { - internal sealed class KcpRawReceiveQueue : IValueTaskSource, IDisposable + private readonly IKcpBufferPool _bufferPool; + private readonly int _capacity; + private readonly LinkedListOfQueueItem _queue; + private readonly LinkedListOfQueueItem _recycled; + + private bool _activeWait; + private Memory _buffer; + private bool _bufferProvided; + private CancellationTokenRegistration _cancellationRegistration; + private CancellationToken _cancellationToken; + private bool _disposed; + private ManualResetValueTaskSourceCore _mrvtsc; + private bool _signaled; + + private bool _transportClosed; + + public KcpRawReceiveQueue(IKcpBufferPool bufferPool, int capacity) { - private ManualResetValueTaskSourceCore _mrvtsc; + _bufferPool = bufferPool; + _capacity = capacity; + _queue = new LinkedListOfQueueItem(); + _recycled = new LinkedListOfQueueItem(); + } - private readonly IKcpBufferPool _bufferPool; - private readonly int _capacity; - private readonly LinkedListOfQueueItem _queue; - private readonly LinkedListOfQueueItem _recycled; - - private bool _transportClosed; - private bool _disposed; - - private bool _activeWait; - private bool _signaled; - private bool _bufferProvided; - private Memory _buffer; - private CancellationToken _cancellationToken; - private CancellationTokenRegistration _cancellationRegistration; - - public KcpRawReceiveQueue(IKcpBufferPool bufferPool, int capacity) + public void Dispose() + { + lock (_queue) { - _bufferPool = bufferPool; - _capacity = capacity; - _queue = new LinkedListOfQueueItem(); - _recycled = new LinkedListOfQueueItem(); - } - - KcpConversationReceiveResult IValueTaskSource.GetResult(short token) - { - _cancellationRegistration.Dispose(); - try + if (_disposed) return; + if (_activeWait && !_signaled) { - return _mrvtsc.GetResult(token); + ClearPreviousOperation(); + _mrvtsc.SetResult(default); } - finally + + var node = _queue.First; + while (node is not null) { - _mrvtsc.Reset(); - lock (_queue) - { - _activeWait = false; - _signaled = false; - _cancellationRegistration = default; - } + node.ValueRef.Release(); + node = node.Next; } + + _queue.Clear(); + _recycled.Clear(); + _disposed = true; + _transportClosed = true; } + } - ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _mrvtsc.GetStatus(token); - void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => _mrvtsc.OnCompleted(continuation, state, token, flags); - - public bool TryPeek(out KcpConversationReceiveResult result) + KcpConversationReceiveResult IValueTaskSource.GetResult(short token) + { + _cancellationRegistration.Dispose(); + try { + return _mrvtsc.GetResult(token); + } + finally + { + _mrvtsc.Reset(); lock (_queue) { - if (_disposed || _transportClosed) - { - result = default; - return false; - } - if (_activeWait) - { - ThrowHelper.ThrowConcurrentReceiveException(); - } - LinkedListNodeOfQueueItem? first = _queue.First; - if (first is null) - { - result = new KcpConversationReceiveResult(0); - return false; - } - - result = new KcpConversationReceiveResult(first.ValueRef.Length); - return true; + _activeWait = false; + _signaled = false; + _cancellationRegistration = default; } } + } - public ValueTask WaitToReceiveAsync(CancellationToken cancellationToken) + ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) + { + return _mrvtsc.GetStatus(token); + } + + void IValueTaskSource.OnCompleted(Action continuation, object? state, + short token, ValueTaskSourceOnCompletedFlags flags) + { + _mrvtsc.OnCompleted(continuation, state, token, flags); + } + + public bool TryPeek(out KcpConversationReceiveResult result) + { + lock (_queue) { - short token; - lock (_queue) + if (_disposed || _transportClosed) { - if (_transportClosed || _disposed) - { - return default; - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentReceiveException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - - LinkedListNodeOfQueueItem? first = _queue.First; - if (first is not null) - { - return new ValueTask(new KcpConversationReceiveResult(first.ValueRef.Length)); - } - - _activeWait = true; - Debug.Assert(!_signaled); - _bufferProvided = false; - _buffer = default; - _cancellationToken = cancellationToken; - - token = _mrvtsc.Version; + result = default; + return false; } - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpRawReceiveQueue?)state)!.SetCanceled(), this); - return new ValueTask(this, token); + if (_activeWait) ThrowHelper.ThrowConcurrentReceiveException(); + var first = _queue.First; + if (first is null) + { + result = new KcpConversationReceiveResult(0); + return false; + } + + result = new KcpConversationReceiveResult(first.ValueRef.Length); + return true; + } + } + + public ValueTask WaitToReceiveAsync(CancellationToken cancellationToken) + { + short token; + lock (_queue) + { + if (_transportClosed || _disposed) return default; + if (_activeWait) + return new ValueTask( + Task.FromException(ThrowHelper.NewConcurrentReceiveException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask( + Task.FromCanceled(cancellationToken)); + + var first = _queue.First; + if (first is not null) + return new ValueTask( + new KcpConversationReceiveResult(first.ValueRef.Length)); + + _activeWait = true; + Debug.Assert(!_signaled); + _bufferProvided = false; + _buffer = default; + _cancellationToken = cancellationToken; + + token = _mrvtsc.Version; } - public bool TryReceive(Span buffer, out KcpConversationReceiveResult result) - { - lock (_queue) - { - if (_disposed || _transportClosed) - { - result = default; - return false; - } - if (_activeWait) - { - ThrowHelper.ThrowConcurrentReceiveException(); - } - LinkedListNodeOfQueueItem? first = _queue.First; - if (first is null) - { - result = new KcpConversationReceiveResult(0); - return false; - } + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpRawReceiveQueue?)state)!.SetCanceled(), this); - ref KcpBuffer source = ref first.ValueRef; + return new ValueTask(this, token); + } + + public bool TryReceive(Span buffer, out KcpConversationReceiveResult result) + { + lock (_queue) + { + if (_disposed || _transportClosed) + { + result = default; + return false; + } + + if (_activeWait) ThrowHelper.ThrowConcurrentReceiveException(); + var first = _queue.First; + if (first is null) + { + result = new KcpConversationReceiveResult(0); + return false; + } + + ref var source = ref first.ValueRef; + if (buffer.Length < source.Length) ThrowHelper.ThrowBufferTooSmall(); + + source.DataRegion.Span.CopyTo(buffer); + result = new KcpConversationReceiveResult(source.Length); + + _queue.RemoveFirst(); + source.Release(); + source = default; + _recycled.AddLast(first); + + return true; + } + } + + public ValueTask ReceiveAsync(Memory buffer, + CancellationToken cancellationToken = default) + { + short token; + lock (_queue) + { + if (_transportClosed || _disposed) return default; + if (_activeWait) + return new ValueTask( + Task.FromException(ThrowHelper.NewConcurrentReceiveException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask( + Task.FromCanceled(cancellationToken)); + + var first = _queue.First; + if (first is not null) + { + ref var source = ref first.ValueRef; + var length = source.Length; if (buffer.Length < source.Length) - { - ThrowHelper.ThrowBufferTooSmall(); - } + return new ValueTask( + Task.FromException( + ThrowHelper.NewBufferTooSmallForBufferArgument())); + _queue.Remove(first); - source.DataRegion.Span.CopyTo(buffer); - result = new KcpConversationReceiveResult(source.Length); - - _queue.RemoveFirst(); + source.DataRegion.CopyTo(buffer); source.Release(); source = default; _recycled.AddLast(first); + return new ValueTask(new KcpConversationReceiveResult(length)); + } + + _activeWait = true; + Debug.Assert(!_signaled); + _bufferProvided = true; + _buffer = buffer; + _cancellationToken = cancellationToken; + + token = _mrvtsc.Version; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpRawReceiveQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public bool CancelPendingOperation(Exception? innerException, CancellationToken cancellationToken) + { + lock (_queue) + { + if (_activeWait && !_signaled) + { + ClearPreviousOperation(); + _mrvtsc.SetException( + ThrowHelper.NewOperationCanceledExceptionForCancelPendingReceive(innerException, + cancellationToken)); return true; } } - public ValueTask ReceiveAsync(Memory buffer, CancellationToken cancellationToken = default) + return false; + } + + private void SetCanceled() + { + lock (_queue) { - short token; - lock (_queue) + if (_activeWait && !_signaled) { - if (_transportClosed || _disposed) - { - return default; - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentReceiveException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - - LinkedListNodeOfQueueItem? first = _queue.First; - if (first is not null) - { - ref KcpBuffer source = ref first.ValueRef; - int length = source.Length; - if (buffer.Length < source.Length) - { - return new ValueTask(Task.FromException(ThrowHelper.NewBufferTooSmallForBufferArgument())); - } - _queue.Remove(first); - - source.DataRegion.CopyTo(buffer); - source.Release(); - source = default; - _recycled.AddLast(first); - - return new ValueTask(new KcpConversationReceiveResult(length)); - } - - _activeWait = true; - Debug.Assert(!_signaled); - _bufferProvided = true; - _buffer = buffer; - _cancellationToken = cancellationToken; - - token = _mrvtsc.Version; - } - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpRawReceiveQueue?)state)!.SetCanceled(), this); - - return new ValueTask(this, token); - } - - public bool CancelPendingOperation(Exception? innerException, CancellationToken cancellationToken) - { - lock (_queue) - { - if (_activeWait && !_signaled) - { - ClearPreviousOperation(); - _mrvtsc.SetException(ThrowHelper.NewOperationCanceledExceptionForCancelPendingReceive(innerException, cancellationToken)); - return true; - } - } - return false; - } - - private void SetCanceled() - { - lock (_queue) - { - if (_activeWait && !_signaled) - { - CancellationToken cancellationToken = _cancellationToken; - ClearPreviousOperation(); - _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); - } - } - } - - private void ClearPreviousOperation() - { - _signaled = true; - _bufferProvided = false; - _buffer = default; - _cancellationToken = default; - } - - public void Enqueue(ReadOnlySpan buffer) - { - lock (_queue) - { - if (_transportClosed || _disposed) - { - return; - } - - int queueSize = _queue.Count; - if (queueSize > 0 || !_activeWait) - { - if (queueSize >= _capacity) - { - return; - } - - KcpRentedBuffer owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(buffer.Length, false)); - _queue.AddLast(AllocateNode(KcpBuffer.CreateFromSpan(owner, buffer))); - return; - } - - if (!_bufferProvided) - { - KcpRentedBuffer owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(buffer.Length, false)); - _queue.AddLast(AllocateNode(KcpBuffer.CreateFromSpan(owner, buffer))); - - ClearPreviousOperation(); - _mrvtsc.SetResult(new KcpConversationReceiveResult(buffer.Length)); - return; - } - - if (buffer.Length > _buffer.Length) - { - KcpRentedBuffer owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(buffer.Length, false)); - _queue.AddLast(AllocateNode(KcpBuffer.CreateFromSpan(owner, buffer))); - - ClearPreviousOperation(); - _mrvtsc.SetException(ThrowHelper.NewBufferTooSmallForBufferArgument()); - return; - } - - buffer.CopyTo(_buffer.Span); + var cancellationToken = _cancellationToken; ClearPreviousOperation(); - _mrvtsc.SetResult(new KcpConversationReceiveResult(buffer.Length)); - } - } - - private LinkedListNodeOfQueueItem AllocateNode(KcpBuffer buffer) - { - LinkedListNodeOfQueueItem? node = _recycled.First; - if (node is null) - { - node = new LinkedListNodeOfQueueItem(buffer); - } - else - { - node.ValueRef = buffer; - _recycled.Remove(node); - } - return node; - } - - public void SetTransportClosed() - { - lock (_queue) - { - if (_transportClosed || _disposed) - { - return; - } - if (_activeWait && !_signaled) - { - ClearPreviousOperation(); - _mrvtsc.SetResult(default); - } - _recycled.Clear(); - _transportClosed = true; - } - } - - public void Dispose() - { - lock (_queue) - { - if (_disposed) - { - return; - } - if (_activeWait && !_signaled) - { - ClearPreviousOperation(); - _mrvtsc.SetResult(default); - } - LinkedListNodeOfQueueItem? node = _queue.First; - while (node is not null) - { - node.ValueRef.Release(); - node = node.Next; - } - _queue.Clear(); - _recycled.Clear(); - _disposed = true; - _transportClosed = true; + _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); } } } -} + + private void ClearPreviousOperation() + { + _signaled = true; + _bufferProvided = false; + _buffer = default; + _cancellationToken = default; + } + + public void Enqueue(ReadOnlySpan buffer) + { + lock (_queue) + { + if (_transportClosed || _disposed) return; + + var queueSize = _queue.Count; + if (queueSize > 0 || !_activeWait) + { + if (queueSize >= _capacity) return; + + var owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(buffer.Length, false)); + _queue.AddLast(AllocateNode(KcpBuffer.CreateFromSpan(owner, buffer))); + return; + } + + if (!_bufferProvided) + { + var owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(buffer.Length, false)); + _queue.AddLast(AllocateNode(KcpBuffer.CreateFromSpan(owner, buffer))); + + ClearPreviousOperation(); + _mrvtsc.SetResult(new KcpConversationReceiveResult(buffer.Length)); + return; + } + + if (buffer.Length > _buffer.Length) + { + var owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(buffer.Length, false)); + _queue.AddLast(AllocateNode(KcpBuffer.CreateFromSpan(owner, buffer))); + + ClearPreviousOperation(); + _mrvtsc.SetException(ThrowHelper.NewBufferTooSmallForBufferArgument()); + return; + } + + buffer.CopyTo(_buffer.Span); + ClearPreviousOperation(); + _mrvtsc.SetResult(new KcpConversationReceiveResult(buffer.Length)); + } + } + + private LinkedListNodeOfQueueItem AllocateNode(KcpBuffer buffer) + { + var node = _recycled.First; + if (node is null) + { + node = new LinkedListNodeOfQueueItem(buffer); + } + else + { + node.ValueRef = buffer; + _recycled.Remove(node); + } + + return node; + } + + public void SetTransportClosed() + { + lock (_queue) + { + if (_transportClosed || _disposed) return; + if (_activeWait && !_signaled) + { + ClearPreviousOperation(); + _mrvtsc.SetResult(default); + } + + _recycled.Clear(); + _transportClosed = true; + } + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpRawSendOperation.cs b/GameServer/KcpSharp/KcpRawSendOperation.cs index 3a930c52..1b6d58cd 100644 --- a/GameServer/KcpSharp/KcpRawSendOperation.cs +++ b/GameServer/KcpSharp/KcpRawSendOperation.cs @@ -1,182 +1,184 @@ using System.Diagnostics; using System.Threading.Tasks.Sources; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class KcpRawSendOperation : IValueTaskSource, IDisposable { - internal sealed class KcpRawSendOperation : IValueTaskSource, IDisposable + private readonly AsyncAutoResetEvent _notification; + + private bool _activeWait; + private ReadOnlyMemory _buffer; + private CancellationTokenRegistration _cancellationRegistration; + private CancellationToken _cancellationToken; + private bool _disposed; + private ManualResetValueTaskSourceCore _mrvtsc; + private bool _signaled; + + private bool _transportClosed; + + public KcpRawSendOperation(AsyncAutoResetEvent notification) { - private readonly AsyncAutoResetEvent _notification; - private ManualResetValueTaskSourceCore _mrvtsc; + _notification = notification; - private bool _transportClosed; - private bool _disposed; - - private bool _activeWait; - private bool _signaled; - private ReadOnlyMemory _buffer; - private CancellationToken _cancellationToken; - private CancellationTokenRegistration _cancellationRegistration; - - public KcpRawSendOperation(AsyncAutoResetEvent notification) + _mrvtsc = new ManualResetValueTaskSourceCore { - _notification = notification; + RunContinuationsAsynchronously = true + }; + } - _mrvtsc = new ManualResetValueTaskSourceCore() - { - RunContinuationsAsynchronously = true - }; - } - - bool IValueTaskSource.GetResult(short token) + public void Dispose() + { + lock (this) { - _cancellationRegistration.Dispose(); - try + if (_disposed) return; + if (_activeWait && !_signaled) { - return _mrvtsc.GetResult(token); - } - finally - { - _mrvtsc.Reset(); - lock (this) - { - _activeWait = false; - _signaled = false; - _cancellationRegistration = default; - } - } - } - - ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _mrvtsc.GetStatus(token); - void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => _mrvtsc.OnCompleted(continuation, state, token, flags); - - public ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) - { - short token; - lock (this) - { - if (_transportClosed || _disposed) - { - return new ValueTask(false); - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - - _activeWait = true; - Debug.Assert(!_signaled); - _buffer = buffer; - _cancellationToken = cancellationToken; - token = _mrvtsc.Version; - } - - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpRawSendOperation?)state)!.SetCanceled(), this); - - _notification.Set(buffer.Length); - return new ValueTask(this, token); - } - - public bool CancelPendingOperation(Exception? innerException, CancellationToken cancellationToken) - { - lock (this) - { - if (_activeWait && !_signaled) - { - ClearPreviousOperation(); - _mrvtsc.SetException(ThrowHelper.NewOperationCanceledExceptionForCancelPendingSend(innerException, cancellationToken)); - return true; - } - } - return false; - } - - private void SetCanceled() - { - lock (this) - { - if (_activeWait && !_signaled) - { - CancellationToken cancellationToken = _cancellationToken; - ClearPreviousOperation(); - _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); - } - } - } - - private void ClearPreviousOperation() - { - _signaled = true; - _buffer = default; - _cancellationToken = default; - } - - public bool TryConsume(Memory buffer, out int bytesWritten) - { - lock (this) - { - if (_transportClosed || _disposed) - { - bytesWritten = 0; - return false; - } - if (!_activeWait) - { - bytesWritten = 0; - return false; - } - ReadOnlyMemory source = _buffer; - if (source.Length > buffer.Length) - { - ClearPreviousOperation(); - _mrvtsc.SetException(ThrowHelper.NewMessageTooLargeForBufferArgument()); - bytesWritten = 0; - return false; - } - source.CopyTo(buffer); - bytesWritten = source.Length; ClearPreviousOperation(); - _mrvtsc.SetResult(true); + _mrvtsc.SetResult(false); + } + + _disposed = true; + _transportClosed = true; + } + } + + bool IValueTaskSource.GetResult(short token) + { + _cancellationRegistration.Dispose(); + try + { + return _mrvtsc.GetResult(token); + } + finally + { + _mrvtsc.Reset(); + lock (this) + { + _activeWait = false; + _signaled = false; + _cancellationRegistration = default; + } + } + } + + ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) + { + return _mrvtsc.GetStatus(token); + } + + void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, + ValueTaskSourceOnCompletedFlags flags) + { + _mrvtsc.OnCompleted(continuation, state, token, flags); + } + + public ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + short token; + lock (this) + { + if (_transportClosed || _disposed) return new ValueTask(false); + if (_activeWait) + return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask(Task.FromCanceled(cancellationToken)); + + _activeWait = true; + Debug.Assert(!_signaled); + _buffer = buffer; + _cancellationToken = cancellationToken; + token = _mrvtsc.Version; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpRawSendOperation?)state)!.SetCanceled(), this); + + _notification.Set(buffer.Length); + return new ValueTask(this, token); + } + + public bool CancelPendingOperation(Exception? innerException, CancellationToken cancellationToken) + { + lock (this) + { + if (_activeWait && !_signaled) + { + ClearPreviousOperation(); + _mrvtsc.SetException( + ThrowHelper.NewOperationCanceledExceptionForCancelPendingSend(innerException, cancellationToken)); return true; } } - public void SetTransportClosed() - { - lock (this) - { - if (_transportClosed || _disposed) - { - return; - } - if (_activeWait && !_signaled) - { - ClearPreviousOperation(); - _mrvtsc.SetResult(false); - } - _transportClosed = true; - } - } + return false; + } - public void Dispose() + private void SetCanceled() + { + lock (this) { - lock (this) + if (_activeWait && !_signaled) { - if (_disposed) - { - return; - } - if (_activeWait && !_signaled) - { - ClearPreviousOperation(); - _mrvtsc.SetResult(false); - } - _disposed = true; - _transportClosed = true; + var cancellationToken = _cancellationToken; + ClearPreviousOperation(); + _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); } } } -} + + private void ClearPreviousOperation() + { + _signaled = true; + _buffer = default; + _cancellationToken = default; + } + + public bool TryConsume(Memory buffer, out int bytesWritten) + { + lock (this) + { + if (_transportClosed || _disposed) + { + bytesWritten = 0; + return false; + } + + if (!_activeWait) + { + bytesWritten = 0; + return false; + } + + var source = _buffer; + if (source.Length > buffer.Length) + { + ClearPreviousOperation(); + _mrvtsc.SetException(ThrowHelper.NewMessageTooLargeForBufferArgument()); + bytesWritten = 0; + return false; + } + + source.CopyTo(buffer); + bytesWritten = source.Length; + ClearPreviousOperation(); + _mrvtsc.SetResult(true); + return true; + } + } + + public void SetTransportClosed() + { + lock (this) + { + if (_transportClosed || _disposed) return; + if (_activeWait && !_signaled) + { + ClearPreviousOperation(); + _mrvtsc.SetResult(false); + } + + _transportClosed = true; + } + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpReceiveQueue.cs b/GameServer/KcpSharp/KcpReceiveQueue.cs index c5858640..f3eeae6c 100644 --- a/GameServer/KcpSharp/KcpReceiveQueue.cs +++ b/GameServer/KcpSharp/KcpReceiveQueue.cs @@ -1,698 +1,637 @@ -using System.Threading.Tasks.Sources; -using System.Diagnostics; - - - - - - -#if NEED_LINKEDLIST_SHIM +#if NEED_LINKEDLIST_SHIM using LinkedListOfQueueItem = KcpSharp.NetstandardShim.LinkedList<(KcpSharp.KcpBuffer Data, byte Fragment)>; using LinkedListNodeOfQueueItem = KcpSharp.NetstandardShim.LinkedListNode<(KcpSharp.KcpBuffer Data, byte Fragment)>; #else -using LinkedListOfQueueItem = System.Collections.Generic.LinkedList<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; -using LinkedListNodeOfQueueItem = System.Collections.Generic.LinkedListNode<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; +using LinkedListOfQueueItem = + System.Collections.Generic.LinkedList<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; +using LinkedListNodeOfQueueItem = + System.Collections.Generic.LinkedListNode<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; #endif +using System.Diagnostics; +using System.Threading.Tasks.Sources; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class KcpReceiveQueue : IValueTaskSource, IValueTaskSource, + IValueTaskSource, IDisposable { - internal sealed class KcpReceiveQueue : IValueTaskSource, IValueTaskSource, IValueTaskSource, IDisposable + private readonly KcpSendReceiveQueueItemCache _cache; + + private readonly LinkedListOfQueueItem _queue; + private readonly int _queueSize; + private readonly bool _stream; + + private bool _activeWait; + private Memory _buffer; + private CancellationTokenRegistration _cancellationRegistration; + private CancellationToken _cancellationToken; + private int _completedPacketsCount; + private bool _disposed; + private int _minimumBytes; + private int _minimumSegments; + private ManualResetValueTaskSourceCore _mrvtsc; + private byte _operationMode; // 0-receive 1-wait for message 2-wait for available data + private bool _signaled; + + private bool _transportClosed; + + public KcpReceiveQueue(bool stream, int queueSize, KcpSendReceiveQueueItemCache cache) { - private ManualResetValueTaskSourceCore _mrvtsc; - - private readonly LinkedListOfQueueItem _queue; - private readonly bool _stream; - private readonly int _queueSize; - private readonly KcpSendReceiveQueueItemCache _cache; - private int _completedPacketsCount; - - private bool _transportClosed; - private bool _disposed; - - private bool _activeWait; - private bool _signaled; - private byte _operationMode; // 0-receive 1-wait for message 2-wait for available data - private Memory _buffer; - private int _minimumBytes; - private int _minimumSegments; - private CancellationToken _cancellationToken; - private CancellationTokenRegistration _cancellationRegistration; - - public KcpReceiveQueue(bool stream, int queueSize, KcpSendReceiveQueueItemCache cache) + _mrvtsc = new ManualResetValueTaskSourceCore { - _mrvtsc = new ManualResetValueTaskSourceCore() + RunContinuationsAsynchronously = true + }; + _queue = new LinkedListOfQueueItem(); + _stream = stream; + _queueSize = queueSize; + _cache = cache; + } + + public void Dispose() + { + lock (_queue) + { + if (_disposed) return; + if (_activeWait && !_signaled) { - RunContinuationsAsynchronously = true - }; - _queue = new LinkedListOfQueueItem(); - _stream = stream; - _queueSize = queueSize; - _cache = cache; + ClearPreviousOperation(true); + _mrvtsc.SetResult(default); + } + + var node = _queue.First; + while (node is not null) + { + node.ValueRef.Data.Release(); + node = node.Next; + } + + _queue.Clear(); + _disposed = true; + _transportClosed = true; } + } - public ValueTaskSourceStatus GetStatus(short token) => _mrvtsc.GetStatus(token); - public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) - => _mrvtsc.OnCompleted(continuation, state, token, flags); - - KcpConversationReceiveResult IValueTaskSource.GetResult(short token) + bool IValueTaskSource.GetResult(short token) + { + _cancellationRegistration.Dispose(); + try { - _cancellationRegistration.Dispose(); - try - { - return _mrvtsc.GetResult(token); - } - finally - { - _mrvtsc.Reset(); - lock (_queue) - { - _activeWait = false; - _signaled = false; - _cancellationRegistration = default; - } - } + return !_mrvtsc.GetResult(token).TransportClosed; } - - int IValueTaskSource.GetResult(short token) - { - _cancellationRegistration.Dispose(); - try - { - return _mrvtsc.GetResult(token).BytesReceived; - } - finally - { - _mrvtsc.Reset(); - lock (_queue) - { - _activeWait = false; - _signaled = false; - _cancellationRegistration = default; - } - } - } - - bool IValueTaskSource.GetResult(short token) - { - _cancellationRegistration.Dispose(); - try - { - return !_mrvtsc.GetResult(token).TransportClosed; - } - finally - { - _mrvtsc.Reset(); - lock (_queue) - { - _activeWait = false; - _signaled = false; - _cancellationRegistration = default; - } - } - } - - public bool TryPeek(out KcpConversationReceiveResult result) + finally { + _mrvtsc.Reset(); lock (_queue) { - if (_disposed || _transportClosed) - { - result = default; - return false; - } - if (_activeWait) - { - ThrowHelper.ThrowConcurrentReceiveException(); - } + _activeWait = false; + _signaled = false; + _cancellationRegistration = default; + } + } + } - if (_completedPacketsCount == 0) - { - result = new KcpConversationReceiveResult(0); - return false; - } + int IValueTaskSource.GetResult(short token) + { + _cancellationRegistration.Dispose(); + try + { + return _mrvtsc.GetResult(token).BytesReceived; + } + finally + { + _mrvtsc.Reset(); + lock (_queue) + { + _activeWait = false; + _signaled = false; + _cancellationRegistration = default; + } + } + } - LinkedListNodeOfQueueItem? node = _queue.First; - if (node is null) - { - result = new KcpConversationReceiveResult(0); - return false; - } + public ValueTaskSourceStatus GetStatus(short token) + { + return _mrvtsc.GetStatus(token); + } - if (CalculatePacketSize(node, out int packetSize)) - { - result = new KcpConversationReceiveResult(packetSize); - return true; - } + public void OnCompleted(Action continuation, object? state, short token, + ValueTaskSourceOnCompletedFlags flags) + { + _mrvtsc.OnCompleted(continuation, state, token, flags); + } + KcpConversationReceiveResult IValueTaskSource.GetResult(short token) + { + _cancellationRegistration.Dispose(); + try + { + return _mrvtsc.GetResult(token); + } + finally + { + _mrvtsc.Reset(); + lock (_queue) + { + _activeWait = false; + _signaled = false; + _cancellationRegistration = default; + } + } + } + + public bool TryPeek(out KcpConversationReceiveResult result) + { + lock (_queue) + { + if (_disposed || _transportClosed) + { result = default; return false; } + + if (_activeWait) ThrowHelper.ThrowConcurrentReceiveException(); + + if (_completedPacketsCount == 0) + { + result = new KcpConversationReceiveResult(0); + return false; + } + + var node = _queue.First; + if (node is null) + { + result = new KcpConversationReceiveResult(0); + return false; + } + + if (CalculatePacketSize(node, out var packetSize)) + { + result = new KcpConversationReceiveResult(packetSize); + return true; + } + + result = default; + return false; } + } - public ValueTask WaitToReceiveAsync(CancellationToken cancellationToken) + public ValueTask WaitToReceiveAsync(CancellationToken cancellationToken) + { + short token; + lock (_queue) { - short token; - lock (_queue) + if (_transportClosed || _disposed) return default; + if (_activeWait) + return new ValueTask( + Task.FromException(ThrowHelper.NewConcurrentReceiveException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask( + Task.FromCanceled(cancellationToken)); + + _operationMode = 1; + _buffer = default; + _minimumBytes = 0; + _minimumSegments = 0; + + token = _mrvtsc.Version; + if (_completedPacketsCount > 0) { - if (_transportClosed || _disposed) - { - return default; - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentReceiveException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - - _operationMode = 1; - _buffer = default; - _minimumBytes = 0; - _minimumSegments = 0; - - token = _mrvtsc.Version; - if (_completedPacketsCount > 0) - { - ConsumePacket(_buffer.Span, out KcpConversationReceiveResult result, out bool bufferTooSmall); - ClearPreviousOperation(false); - if (bufferTooSmall) - { - Debug.Assert(false, "This should never be reached."); - return new ValueTask(Task.FromException(ThrowHelper.NewBufferTooSmallForBufferArgument())); - } - else - { - return new ValueTask(result); - } - } - - _activeWait = true; - Debug.Assert(!_signaled); - _cancellationToken = cancellationToken; - } - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpReceiveQueue?)state)!.SetCanceled(), this); - - return new ValueTask(this, token); - } - - public ValueTask WaitForAvailableDataAsync(int minimumBytes, int minimumSegments, CancellationToken cancellationToken) - { - if (minimumBytes < 0) - { - return new ValueTask(Task.FromException(ThrowHelper.NewArgumentOutOfRangeException(nameof(minimumBytes)))); - } - if (minimumSegments < 0) - { - return new ValueTask(Task.FromException(ThrowHelper.NewArgumentOutOfRangeException(nameof(minimumSegments)))); - } - - short token; - lock (_queue) - { - if (_transportClosed || _disposed) - { - return default; - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentReceiveException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - - if (CheckQueeuSize(_queue, minimumBytes, minimumSegments, _stream)) - { - return new ValueTask(true); - } - - _activeWait = true; - Debug.Assert(!_signaled); - _operationMode = 2; - _buffer = default; - _minimumBytes = minimumBytes; - _minimumSegments = minimumSegments; - _cancellationToken = cancellationToken; - - token = _mrvtsc.Version; - } - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpReceiveQueue?)state)!.SetCanceled(), this); - - return new ValueTask(this, token); - } - - public bool TryReceive(Span buffer, out KcpConversationReceiveResult result) - { - lock (_queue) - { - if (_disposed || _transportClosed) - { - result = default; - return false; - } - if (_activeWait) - { - ThrowHelper.ThrowConcurrentReceiveException(); - } - - if (_completedPacketsCount == 0) - { - result = new KcpConversationReceiveResult(0); - return false; - } - - Debug.Assert(!_signaled); - _operationMode = 0; - - ConsumePacket(buffer, out result, out bool bufferTooSmall); + ConsumePacket(_buffer.Span, out var result, out var bufferTooSmall); ClearPreviousOperation(false); if (bufferTooSmall) { - ThrowHelper.ThrowBufferTooSmall(); + Debug.Assert(false, "This should never be reached."); + return new ValueTask( + Task.FromException( + ThrowHelper.NewBufferTooSmallForBufferArgument())); } + + return new ValueTask(result); + } + + _activeWait = true; + Debug.Assert(!_signaled); + _cancellationToken = cancellationToken; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpReceiveQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public ValueTask WaitForAvailableDataAsync(int minimumBytes, int minimumSegments, + CancellationToken cancellationToken) + { + if (minimumBytes < 0) + return new ValueTask( + Task.FromException(ThrowHelper.NewArgumentOutOfRangeException(nameof(minimumBytes)))); + if (minimumSegments < 0) + return new ValueTask( + Task.FromException(ThrowHelper.NewArgumentOutOfRangeException(nameof(minimumSegments)))); + + short token; + lock (_queue) + { + if (_transportClosed || _disposed) return default; + if (_activeWait) + return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentReceiveException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask(Task.FromCanceled(cancellationToken)); + + if (CheckQueeuSize(_queue, minimumBytes, minimumSegments, _stream)) return new ValueTask(true); + + _activeWait = true; + Debug.Assert(!_signaled); + _operationMode = 2; + _buffer = default; + _minimumBytes = minimumBytes; + _minimumSegments = minimumSegments; + _cancellationToken = cancellationToken; + + token = _mrvtsc.Version; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpReceiveQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public bool TryReceive(Span buffer, out KcpConversationReceiveResult result) + { + lock (_queue) + { + if (_disposed || _transportClosed) + { + result = default; + return false; + } + + if (_activeWait) ThrowHelper.ThrowConcurrentReceiveException(); + + if (_completedPacketsCount == 0) + { + result = new KcpConversationReceiveResult(0); + return false; + } + + Debug.Assert(!_signaled); + _operationMode = 0; + + ConsumePacket(buffer, out result, out var bufferTooSmall); + ClearPreviousOperation(false); + if (bufferTooSmall) ThrowHelper.ThrowBufferTooSmall(); + return true; + } + } + + public ValueTask ReceiveAsync(Memory buffer, + CancellationToken cancellationToken) + { + short token; + lock (_queue) + { + if (_transportClosed || _disposed) return default; + if (_activeWait) + return new ValueTask( + Task.FromException(ThrowHelper.NewConcurrentReceiveException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask( + Task.FromCanceled(cancellationToken)); + + _operationMode = 0; + _buffer = buffer; + + token = _mrvtsc.Version; + if (_completedPacketsCount > 0) + { + ConsumePacket(_buffer.Span, out var result, out var bufferTooSmall); + ClearPreviousOperation(false); + if (bufferTooSmall) + return new ValueTask( + Task.FromException( + ThrowHelper.NewBufferTooSmallForBufferArgument())); + return new ValueTask(result); + } + + _activeWait = true; + Debug.Assert(!_signaled); + _cancellationToken = cancellationToken; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpReceiveQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken) + { + short token; + lock (_queue) + { + if (_transportClosed || _disposed) + return new ValueTask(Task.FromException(ThrowHelper.NewTransportClosedForStreamException())); + if (_activeWait) + return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentReceiveException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask(Task.FromCanceled(cancellationToken)); + + _operationMode = 0; + _buffer = buffer; + + token = _mrvtsc.Version; + if (_completedPacketsCount > 0) + { + ConsumePacket(_buffer.Span, out var result, out var bufferTooSmall); + ClearPreviousOperation(false); + if (bufferTooSmall) + return new ValueTask( + Task.FromException(ThrowHelper.NewBufferTooSmallForBufferArgument())); + return new ValueTask(result.BytesReceived); + } + + _activeWait = true; + Debug.Assert(!_signaled); + _cancellationToken = cancellationToken; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpReceiveQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public bool CancelPendingOperation(Exception? innerException, CancellationToken cancellationToken) + { + lock (_queue) + { + if (_activeWait && !_signaled) + { + ClearPreviousOperation(true); + _mrvtsc.SetException( + ThrowHelper.NewOperationCanceledExceptionForCancelPendingReceive(innerException, + cancellationToken)); return true; } } - public ValueTask ReceiveAsync(Memory buffer, CancellationToken cancellationToken) + return false; + } + + private void SetCanceled() + { + lock (_queue) { - short token; - lock (_queue) + if (_activeWait && !_signaled) { - if (_transportClosed || _disposed) - { - return default; - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentReceiveException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - - _operationMode = 0; - _buffer = buffer; - - token = _mrvtsc.Version; - if (_completedPacketsCount > 0) - { - ConsumePacket(_buffer.Span, out KcpConversationReceiveResult result, out bool bufferTooSmall); - ClearPreviousOperation(false); - if (bufferTooSmall) - { - return new ValueTask(Task.FromException(ThrowHelper.NewBufferTooSmallForBufferArgument())); - } - else - { - return new ValueTask(result); - } - } - - _activeWait = true; - Debug.Assert(!_signaled); - _cancellationToken = cancellationToken; - } - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpReceiveQueue?)state)!.SetCanceled(), this); - - return new ValueTask(this, token); - } - - public ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken) - { - short token; - lock (_queue) - { - if (_transportClosed || _disposed) - { - return new ValueTask(Task.FromException(ThrowHelper.NewTransportClosedForStreamException())); - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentReceiveException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - - _operationMode = 0; - _buffer = buffer; - - token = _mrvtsc.Version; - if (_completedPacketsCount > 0) - { - ConsumePacket(_buffer.Span, out KcpConversationReceiveResult result, out bool bufferTooSmall); - ClearPreviousOperation(false); - if (bufferTooSmall) - { - return new ValueTask(Task.FromException(ThrowHelper.NewBufferTooSmallForBufferArgument())); - } - else - { - return new ValueTask(result.BytesReceived); - } - } - - _activeWait = true; - Debug.Assert(!_signaled); - _cancellationToken = cancellationToken; - } - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpReceiveQueue?)state)!.SetCanceled(), this); - - return new ValueTask(this, token); - } - - public bool CancelPendingOperation(Exception? innerException, CancellationToken cancellationToken) - { - lock (_queue) - { - if (_activeWait && !_signaled) - { - ClearPreviousOperation(true); - _mrvtsc.SetException(ThrowHelper.NewOperationCanceledExceptionForCancelPendingReceive(innerException, cancellationToken)); - return true; - } - } - return false; - } - - private void SetCanceled() - { - lock (_queue) - { - if (_activeWait && !_signaled) - { - CancellationToken cancellationToken = _cancellationToken; - ClearPreviousOperation(true); - _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); - } - } - } - - private void ClearPreviousOperation(bool signaled) - { - _signaled = signaled; - _operationMode = 0; - _buffer = default; - _minimumBytes = default; - _minimumSegments = default; - _cancellationToken = default; - } - - public void Enqueue(KcpBuffer buffer, byte fragment) - { - lock (_queue) - { - if (_transportClosed || _disposed) - { - return; - } - - if (_stream) - { - if (buffer.Length == 0) - { - return; - } - fragment = 0; - _queue.AddLast(_cache.Rent(buffer, 0)); - } - else - { - LinkedListNodeOfQueueItem? lastNode = _queue.Last; - if (lastNode is null || lastNode.ValueRef.Fragment == 0 || lastNode.ValueRef.Fragment - 1 == fragment) - { - _queue.AddLast(_cache.Rent(buffer, fragment)); - } - else - { - fragment = 0; - _queue.AddLast(_cache.Rent(buffer, 0)); - } - } - - if (fragment == 0) - { - _completedPacketsCount++; - if (_activeWait && !_signaled) - { - TryCompleteReceive(); - TryCompleteWaitForData(); - } - } - } - } - - private void TryCompleteReceive() - { - Debug.Assert(_activeWait && !_signaled); - - if (_operationMode <= 1) - { - Debug.Assert(_operationMode == 0 || _operationMode == 1); - ConsumePacket(_buffer.Span, out KcpConversationReceiveResult result, out bool bufferTooSmall); + var cancellationToken = _cancellationToken; ClearPreviousOperation(true); - if (bufferTooSmall) - { - _mrvtsc.SetException(ThrowHelper.NewBufferTooSmallForBufferArgument()); - } - else - { - _mrvtsc.SetResult(result); - } + _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); } } + } - private void TryCompleteWaitForData() + private void ClearPreviousOperation(bool signaled) + { + _signaled = signaled; + _operationMode = 0; + _buffer = default; + _minimumBytes = default; + _minimumSegments = default; + _cancellationToken = default; + } + + public void Enqueue(KcpBuffer buffer, byte fragment) + { + lock (_queue) { - if (_operationMode == 2) + if (_transportClosed || _disposed) return; + + if (_stream) { - if (CheckQueeuSize(_queue, _minimumBytes, _minimumSegments, _stream)) - { - ClearPreviousOperation(true); - _mrvtsc.SetResult(new KcpConversationReceiveResult(0)); - } - } - } - - private void ConsumePacket(Span buffer, out KcpConversationReceiveResult result, out bool bufferTooSmall) - { - LinkedListNodeOfQueueItem? node = _queue.First; - if (node is null) - { - result = default; - bufferTooSmall = false; - return; - } - - // peek - if (_operationMode == 1) - { - if (CalculatePacketSize(node, out int bytesRecevied)) - { - result = new KcpConversationReceiveResult(bytesRecevied); - } - else - { - result = default; - } - bufferTooSmall = false; - return; - } - - Debug.Assert(_operationMode == 0); - - // ensure buffer is big enough - int bytesInPacket = 0; - if (!_stream) - { - while (node is not null) - { - bytesInPacket += node.ValueRef.Data.Length; - if (node.ValueRef.Fragment == 0) - { - break; - } - node = node.Next; - } - - if (node is null) - { - // incomplete packet - result = default; - bufferTooSmall = false; - return; - } - - if (bytesInPacket > buffer.Length) - { - result = default; - bufferTooSmall = true; - return; - } - } - - bool anyDataReceived = false; - bytesInPacket = 0; - node = _queue.First; - LinkedListNodeOfQueueItem? next; - while (node is not null) - { - next = node.Next; - - byte fragment = node.ValueRef.Fragment; - ref KcpBuffer data = ref node.ValueRef.Data; - - int sizeToCopy = Math.Min(data.Length, buffer.Length); - data.DataRegion.Span.Slice(0, sizeToCopy).CopyTo(buffer); - buffer = buffer.Slice(sizeToCopy); - bytesInPacket += sizeToCopy; - anyDataReceived = true; - - if (sizeToCopy != data.Length) - { - // partial data is received. - node.ValueRef = (data.Consume(sizeToCopy), node.ValueRef.Fragment); - } - else - { - // full fragment is consumed - data.Release(); - _queue.Remove(node); - _cache.Return(node); - if (fragment == 0) - { - _completedPacketsCount--; - } - } - - if (!_stream && fragment == 0) - { - break; - } - - if (sizeToCopy == 0) - { - break; - } - - node = next; - } - - if (!anyDataReceived) - { - result = default; - bufferTooSmall = false; + if (buffer.Length == 0) return; + fragment = 0; + _queue.AddLast(_cache.Rent(buffer, 0)); } else { - result = new KcpConversationReceiveResult(bytesInPacket); + var lastNode = _queue.Last; + if (lastNode is null || lastNode.ValueRef.Fragment == 0 || lastNode.ValueRef.Fragment - 1 == fragment) + { + _queue.AddLast(_cache.Rent(buffer, fragment)); + } + else + { + fragment = 0; + _queue.AddLast(_cache.Rent(buffer, 0)); + } + } + + if (fragment == 0) + { + _completedPacketsCount++; + if (_activeWait && !_signaled) + { + TryCompleteReceive(); + TryCompleteWaitForData(); + } + } + } + } + + private void TryCompleteReceive() + { + Debug.Assert(_activeWait && !_signaled); + + if (_operationMode <= 1) + { + Debug.Assert(_operationMode == 0 || _operationMode == 1); + ConsumePacket(_buffer.Span, out var result, out var bufferTooSmall); + ClearPreviousOperation(true); + if (bufferTooSmall) + _mrvtsc.SetException(ThrowHelper.NewBufferTooSmallForBufferArgument()); + else + _mrvtsc.SetResult(result); + } + } + + private void TryCompleteWaitForData() + { + if (_operationMode == 2) + if (CheckQueeuSize(_queue, _minimumBytes, _minimumSegments, _stream)) + { + ClearPreviousOperation(true); + _mrvtsc.SetResult(new KcpConversationReceiveResult(0)); + } + } + + private void ConsumePacket(Span buffer, out KcpConversationReceiveResult result, out bool bufferTooSmall) + { + var node = _queue.First; + if (node is null) + { + result = default; + bufferTooSmall = false; + return; + } + + // peek + if (_operationMode == 1) + { + if (CalculatePacketSize(node, out var bytesRecevied)) + result = new KcpConversationReceiveResult(bytesRecevied); + else + result = default; + bufferTooSmall = false; + return; + } + + Debug.Assert(_operationMode == 0); + + // ensure buffer is big enough + var bytesInPacket = 0; + if (!_stream) + { + while (node is not null) + { + bytesInPacket += node.ValueRef.Data.Length; + if (node.ValueRef.Fragment == 0) break; + node = node.Next; + } + + if (node is null) + { + // incomplete packet + result = default; bufferTooSmall = false; + return; + } + + if (bytesInPacket > buffer.Length) + { + result = default; + bufferTooSmall = true; + return; } } - private static bool CalculatePacketSize(LinkedListNodeOfQueueItem first, out int packetSize) + var anyDataReceived = false; + bytesInPacket = 0; + node = _queue.First; + LinkedListNodeOfQueueItem? next; + while (node is not null) { - int bytesRecevied = first.ValueRef.Data.Length; - if (first.ValueRef.Fragment == 0) + next = node.Next; + + var fragment = node.ValueRef.Fragment; + ref var data = ref node.ValueRef.Data; + + var sizeToCopy = Math.Min(data.Length, buffer.Length); + data.DataRegion.Span.Slice(0, sizeToCopy).CopyTo(buffer); + buffer = buffer.Slice(sizeToCopy); + bytesInPacket += sizeToCopy; + anyDataReceived = true; + + if (sizeToCopy != data.Length) + { + // partial data is received. + node.ValueRef = (data.Consume(sizeToCopy), node.ValueRef.Fragment); + } + else + { + // full fragment is consumed + data.Release(); + _queue.Remove(node); + _cache.Return(node); + if (fragment == 0) _completedPacketsCount--; + } + + if (!_stream && fragment == 0) break; + + if (sizeToCopy == 0) break; + + node = next; + } + + if (!anyDataReceived) + { + result = default; + bufferTooSmall = false; + } + else + { + result = new KcpConversationReceiveResult(bytesInPacket); + bufferTooSmall = false; + } + } + + private static bool CalculatePacketSize(LinkedListNodeOfQueueItem first, out int packetSize) + { + var bytesRecevied = first.ValueRef.Data.Length; + if (first.ValueRef.Fragment == 0) + { + packetSize = bytesRecevied; + return true; + } + + var node = first.Next; + while (node is not null) + { + bytesRecevied += node.ValueRef.Data.Length; + if (node.ValueRef.Fragment == 0) { packetSize = bytesRecevied; return true; } - LinkedListNodeOfQueueItem? node = first.Next; - while (node is not null) - { - bytesRecevied += node.ValueRef.Data.Length; - if (node.ValueRef.Fragment == 0) - { - packetSize = bytesRecevied; - return true; - } - node = node.Next; - } - - // deadlink - packetSize = 0; - return false; + node = node.Next; } - private static bool CheckQueeuSize(LinkedListOfQueueItem queue, int minimumBytes, int minimumSegments, bool stream) - { - LinkedListNodeOfQueueItem? node = queue.First; - while (node is not null) - { - ref KcpBuffer buffer = ref node.ValueRef.Data; - minimumBytes = Math.Max(minimumBytes - buffer.Length, 0); - if (stream || node.ValueRef.Fragment == 0) - { - minimumSegments = Math.Max(minimumSegments - 1, 0); - } - if (minimumBytes == 0 && minimumSegments == 0) - { - return true; - } - node = node.Next; - } + // deadlink + packetSize = 0; + return false; + } - return minimumBytes == 0 && minimumSegments == 0; + private static bool CheckQueeuSize(LinkedListOfQueueItem queue, int minimumBytes, int minimumSegments, bool stream) + { + var node = queue.First; + while (node is not null) + { + ref var buffer = ref node.ValueRef.Data; + minimumBytes = Math.Max(minimumBytes - buffer.Length, 0); + if (stream || node.ValueRef.Fragment == 0) minimumSegments = Math.Max(minimumSegments - 1, 0); + if (minimumBytes == 0 && minimumSegments == 0) return true; + node = node.Next; } - public void SetTransportClosed() - { - lock (_queue) - { - if (_transportClosed || _disposed) - { - return; - } - if (_activeWait && !_signaled) - { - ClearPreviousOperation(true); - _mrvtsc.SetResult(default); - } - _transportClosed = true; - } - } + return minimumBytes == 0 && minimumSegments == 0; + } - public int GetQueueSize() + public void SetTransportClosed() + { + lock (_queue) { - int count; - lock (_queue) + if (_transportClosed || _disposed) return; + if (_activeWait && !_signaled) { - count = _queue.Count; + ClearPreviousOperation(true); + _mrvtsc.SetResult(default); } - return Math.Max(_queue.Count - _queueSize, 0); - } - public void Dispose() - { - lock (_queue) - { - if (_disposed) - { - return; - } - if (_activeWait && !_signaled) - { - ClearPreviousOperation(true); - _mrvtsc.SetResult(default); - } - LinkedListNodeOfQueueItem? node = _queue.First; - while (node is not null) - { - node.ValueRef.Data.Release(); - node = node.Next; - } - _queue.Clear(); - _disposed = true; - _transportClosed = true; - } + _transportClosed = true; } } -} + + public int GetQueueSize() + { + int count; + lock (_queue) + { + count = _queue.Count; + } + + return Math.Max(_queue.Count - _queueSize, 0); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpReceiveWindowNotificationOptions.cs b/GameServer/KcpSharp/KcpReceiveWindowNotificationOptions.cs index b7f52e39..cdd7756d 100644 --- a/GameServer/KcpSharp/KcpReceiveWindowNotificationOptions.cs +++ b/GameServer/KcpSharp/KcpReceiveWindowNotificationOptions.cs @@ -1,37 +1,30 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Options for sending receive window size notification. +/// +public sealed class KcpReceiveWindowNotificationOptions { /// - /// Options for sending receive window size notification. + /// Create an instance of option object for receive window size notification functionality. /// - public sealed class KcpReceiveWindowNotificationOptions + /// The initial interval in milliseconds of sending window size notification. + /// The maximum interval in milliseconds of sending window size notification. + public KcpReceiveWindowNotificationOptions(int initialInterval, int maximumInterval) { - /// - /// Create an instance of option object for receive window size notification functionality. - /// - /// The initial interval in milliseconds of sending window size notification. - /// The maximum interval in milliseconds of sending window size notification. - public KcpReceiveWindowNotificationOptions(int initialInterval, int maximumInterval) - { - if (initialInterval <= 0) - { - throw new ArgumentOutOfRangeException(nameof(initialInterval)); - } - if (maximumInterval < initialInterval) - { - throw new ArgumentOutOfRangeException(nameof(maximumInterval)); - } - InitialInterval = initialInterval; - MaximumInterval = maximumInterval; - } - - /// - /// The initial interval in milliseconds of sending window size notification. - /// - public int InitialInterval { get; } - - /// - /// The maximum interval in milliseconds of sending window size notification. - /// - public int MaximumInterval { get; } + if (initialInterval <= 0) throw new ArgumentOutOfRangeException(nameof(initialInterval)); + if (maximumInterval < initialInterval) throw new ArgumentOutOfRangeException(nameof(maximumInterval)); + InitialInterval = initialInterval; + MaximumInterval = maximumInterval; } -} + + /// + /// The initial interval in milliseconds of sending window size notification. + /// + public int InitialInterval { get; } + + /// + /// The maximum interval in milliseconds of sending window size notification. + /// + public int MaximumInterval { get; } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpRentedBuffer.cs b/GameServer/KcpSharp/KcpRentedBuffer.cs index 9a831b72..9059d39d 100644 --- a/GameServer/KcpSharp/KcpRentedBuffer.cs +++ b/GameServer/KcpSharp/KcpRentedBuffer.cs @@ -3,220 +3,193 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// The buffer rented and owned by KcpSharp. +/// +public readonly struct KcpRentedBuffer : IEquatable, IDisposable { + private readonly Memory _memory; + + internal object? Owner { get; } + /// - /// The buffer rented and owned by KcpSharp. + /// The rented buffer. /// - public readonly struct KcpRentedBuffer : IEquatable, IDisposable + public Memory Memory => _memory; + + /// + /// The rented buffer. + /// + public Span Span => _memory.Span; + + /// + /// Whether this struct contains buffer rented from the pool. + /// + public bool IsAllocated => Owner is not null; + + /// + /// Whether this buffer contains no data. + /// + public bool IsEmpry => _memory.IsEmpty; + + internal KcpRentedBuffer(object? owner, Memory buffer) { - private readonly object? _owner; - private readonly Memory _memory; + Owner = owner; + _memory = buffer; + } - internal object? Owner => _owner; + /// + /// Create the buffer from the specified . + /// + /// The memory region of this buffer. + /// The rented buffer. + public static KcpRentedBuffer FromMemory(Memory memory) + { + return new KcpRentedBuffer(null, memory); + } - /// - /// The rented buffer. - /// - public Memory Memory => _memory; + /// + /// Create the buffer from the shared array pool. + /// + /// The minimum size of the buffer required. + /// The rented buffer. + public static KcpRentedBuffer FromSharedArrayPool(int size) + { + if (size < 0) throw new ArgumentOutOfRangeException(nameof(size)); + var buffer = ArrayPool.Shared.Rent(size); + return new KcpRentedBuffer(ArrayPool.Shared, buffer); + } - /// - /// The rented buffer. - /// - public Span Span => _memory.Span; + /// + /// Create the buffer from the specified array pool. + /// + /// The array pool to use. + /// The byte array rented from the specified pool. + /// The rented buffer. + public static KcpRentedBuffer FromArrayPool(ArrayPool pool, byte[] buffer) + { + if (pool is null) throw new ArgumentNullException(nameof(pool)); + if (buffer is null) throw new ArgumentNullException(nameof(buffer)); + return new KcpRentedBuffer(pool, buffer); + } - /// - /// Whether this struct contains buffer rented from the pool. - /// - public bool IsAllocated => _owner is not null; + /// + /// Create the buffer from the specified array pool. + /// + /// The array pool to use. + /// The byte array segment rented from the specified pool. + /// The rented buffer. + public static KcpRentedBuffer FromArrayPool(ArrayPool pool, ArraySegment arraySegment) + { + if (pool is null) throw new ArgumentNullException(nameof(pool)); + return new KcpRentedBuffer(pool, arraySegment); + } - /// - /// Whether this buffer contains no data. - /// - public bool IsEmpry => _memory.IsEmpty; + /// + /// Create the buffer from the specified array pool. + /// + /// The array pool to use. + /// The minimum size of the buffer required. + /// The rented buffer. + public static KcpRentedBuffer FromArrayPool(ArrayPool pool, int size) + { + if (pool is null) throw new ArgumentNullException(nameof(pool)); + if (size < 0) throw new ArgumentOutOfRangeException(nameof(size)); + return new KcpRentedBuffer(pool, pool.Rent(size)); + } - internal KcpRentedBuffer(object? owner, Memory buffer) - { - _owner = owner; - _memory = buffer; - } + /// + /// Create the buffer from the memory owner. + /// + /// The owner of this memory region. + /// The rented buffer. + public static KcpRentedBuffer FromMemoryOwner(IMemoryOwner memoryOwner) + { + if (memoryOwner is null) throw new ArgumentNullException(nameof(memoryOwner)); + return new KcpRentedBuffer(memoryOwner, memoryOwner.Memory); + } - /// - /// Create the buffer from the specified . - /// - /// The memory region of this buffer. - /// The rented buffer. - public static KcpRentedBuffer FromMemory(Memory memory) - { - return new KcpRentedBuffer(null, memory); - } - /// - /// Create the buffer from the shared array pool. - /// - /// The minimum size of the buffer required. - /// The rented buffer. - public static KcpRentedBuffer FromSharedArrayPool(int size) - { - if (size < 0) - { - throw new ArgumentOutOfRangeException(nameof(size)); - } - byte[] buffer = ArrayPool.Shared.Rent(size); - return new KcpRentedBuffer(ArrayPool.Shared, buffer); - } - - /// - /// Create the buffer from the specified array pool. - /// - /// The array pool to use. - /// The byte array rented from the specified pool. - /// The rented buffer. - public static KcpRentedBuffer FromArrayPool(ArrayPool pool, byte[] buffer) - { - if (pool is null) - { - throw new ArgumentNullException(nameof(pool)); - } - if (buffer is null) - { - throw new ArgumentNullException(nameof(buffer)); - } - return new KcpRentedBuffer(pool, buffer); - } - - /// - /// Create the buffer from the specified array pool. - /// - /// The array pool to use. - /// The byte array segment rented from the specified pool. - /// The rented buffer. - public static KcpRentedBuffer FromArrayPool(ArrayPool pool, ArraySegment arraySegment) - { - if (pool is null) - { - throw new ArgumentNullException(nameof(pool)); - } - return new KcpRentedBuffer(pool, arraySegment); - } - - /// - /// Create the buffer from the specified array pool. - /// - /// The array pool to use. - /// The minimum size of the buffer required. - /// The rented buffer. - public static KcpRentedBuffer FromArrayPool(ArrayPool pool, int size) - { - if (pool is null) - { - throw new ArgumentNullException(nameof(pool)); - } - if (size < 0) - { - throw new ArgumentOutOfRangeException(nameof(size)); - } - return new KcpRentedBuffer(pool, pool.Rent(size)); - } - - /// - /// Create the buffer from the memory owner. - /// - /// The owner of this memory region. - /// The rented buffer. - public static KcpRentedBuffer FromMemoryOwner(IMemoryOwner memoryOwner) - { - if (memoryOwner is null) - { - throw new ArgumentNullException(nameof(memoryOwner)); - } - return new KcpRentedBuffer(memoryOwner, memoryOwner.Memory); - } - - - /// - /// Create the buffer from the memory owner. - /// - /// The owner of this memory region. - /// The memory region of the buffer. - /// The rented buffer. - public static KcpRentedBuffer FromMemoryOwner(IDisposable memoryOwner, Memory memory) - { - if (memoryOwner is null) - { - throw new ArgumentNullException(nameof(memoryOwner)); - } - return new KcpRentedBuffer(memoryOwner, memory); - } - - /// - /// Forms a slice out of the current buffer that begins at a specified index. - /// - /// The index at which to begin the slice. - /// An object that contains all elements of the current instance from start to the end of the instance. - public KcpRentedBuffer Slice(int start) - { - Memory memory = _memory; - if ((uint)start > (uint)memory.Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(nameof(start)); - } - return new KcpRentedBuffer(_owner, memory.Slice(start)); - } - - /// - /// Forms a slice out of the current memory starting at a specified index for a specified length. - /// - /// The index at which to begin the slice. - /// The number of elements to include in the slice. - /// An object that contains elements from the current instance starting at . - public KcpRentedBuffer Slice(int start, int length) - { - Memory memory = _memory; - if ((uint)start > (uint)memory.Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(nameof(start)); - } - if ((uint)length > (uint)(memory.Length - start)) - { - ThrowHelper.ThrowArgumentOutOfRangeException(nameof(length)); - } - return new KcpRentedBuffer(_owner, memory.Slice(start, length)); - } - - /// - public void Dispose() - { - Debug.Assert(_owner is null || _owner is ArrayPool || _owner is IDisposable); - - if (_owner is null) + /// + /// Create the buffer from the memory owner. + /// + /// The owner of this memory region. + /// The memory region of the buffer. + /// The rented buffer. + public static KcpRentedBuffer FromMemoryOwner(IDisposable memoryOwner, Memory memory) + { + if (memoryOwner is null) throw new ArgumentNullException(nameof(memoryOwner)); + return new KcpRentedBuffer(memoryOwner, memory); + } + + /// + /// Forms a slice out of the current buffer that begins at a specified index. + /// + /// The index at which to begin the slice. + /// An object that contains all elements of the current instance from start to the end of the instance. + public KcpRentedBuffer Slice(int start) + { + var memory = _memory; + if ((uint)start > (uint)memory.Length) ThrowHelper.ThrowArgumentOutOfRangeException(nameof(start)); + return new KcpRentedBuffer(Owner, memory.Slice(start)); + } + + /// + /// Forms a slice out of the current memory starting at a specified index for a specified length. + /// + /// The index at which to begin the slice. + /// The number of elements to include in the slice. + /// + /// An object that contains elements from the current instance starting at + /// . + /// + public KcpRentedBuffer Slice(int start, int length) + { + var memory = _memory; + if ((uint)start > (uint)memory.Length) ThrowHelper.ThrowArgumentOutOfRangeException(nameof(start)); + if ((uint)length > (uint)(memory.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(nameof(length)); + return new KcpRentedBuffer(Owner, memory.Slice(start, length)); + } + + /// + public void Dispose() + { + Debug.Assert(Owner is null || Owner is ArrayPool || Owner is IDisposable); + + if (Owner is null) return; + if (Owner is ArrayPool arrayPool) + if (MemoryMarshal.TryGetArray(_memory, out ArraySegment arraySegment)) { + arrayPool.Return(arraySegment.Array!); return; } - if (_owner is ArrayPool arrayPool) - { - if (MemoryMarshal.TryGetArray(_memory, out ArraySegment arraySegment)) - { - arrayPool.Return(arraySegment.Array!); - return; - } - } - if (_owner is IDisposable disposable) - { - disposable.Dispose(); - } - } - /// - public bool Equals(KcpRentedBuffer other) => ReferenceEquals(_owner, other._owner) && _memory.Equals(other._memory); - - /// - public override bool Equals(object? obj) => obj is KcpRentedBuffer other && Equals(other); - - /// - public override int GetHashCode() => _owner is null ? _memory.GetHashCode() : HashCode.Combine(RuntimeHelpers.GetHashCode(_owner), _memory); - - /// - public override string ToString() => $"KcpSharp.KcpRentedBuffer[{_memory.Length}]"; + if (Owner is IDisposable disposable) disposable.Dispose(); } -} + + /// + public bool Equals(KcpRentedBuffer other) + { + return ReferenceEquals(Owner, other.Owner) && _memory.Equals(other._memory); + } + + /// + public override bool Equals(object? obj) + { + return obj is KcpRentedBuffer other && Equals(other); + } + + /// + public override int GetHashCode() + { + return Owner is null ? _memory.GetHashCode() : HashCode.Combine(RuntimeHelpers.GetHashCode(Owner), _memory); + } + + /// + public override string ToString() + { + return $"KcpSharp.KcpRentedBuffer[{_memory.Length}]"; + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSendQueue.cs b/GameServer/KcpSharp/KcpSendQueue.cs index 2a2a6868..c26a0d90 100644 --- a/GameServer/KcpSharp/KcpSendQueue.cs +++ b/GameServer/KcpSharp/KcpSendQueue.cs @@ -1,718 +1,653 @@ -using System.Diagnostics; -using System.Threading.Tasks.Sources; - - - - -#if NEED_LINKEDLIST_SHIM +#if NEED_LINKEDLIST_SHIM using LinkedListOfQueueItem = KcpSharp.NetstandardShim.LinkedList<(KcpSharp.KcpBuffer Data, byte Fragment)>; using LinkedListNodeOfQueueItem = KcpSharp.NetstandardShim.LinkedListNode<(KcpSharp.KcpBuffer Data, byte Fragment)>; #else -using LinkedListOfQueueItem = System.Collections.Generic.LinkedList<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; -using LinkedListNodeOfQueueItem = System.Collections.Generic.LinkedListNode<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; +using LinkedListOfQueueItem = + System.Collections.Generic.LinkedList<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; #endif +using System.Diagnostics; +using System.Threading.Tasks.Sources; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class KcpSendQueue : IValueTaskSource, IValueTaskSource, IDisposable { - internal sealed class KcpSendQueue : IValueTaskSource, IValueTaskSource, IDisposable + private readonly IKcpBufferPool _bufferPool; + private readonly KcpSendReceiveQueueItemCache _cache; + private readonly int _capacity; + private readonly int _mss; + + private readonly LinkedListOfQueueItem _queue; + private readonly bool _stream; + private readonly KcpConversationUpdateActivation _updateActivation; + + private bool _ackListNotEmpty; + + private bool _activeWait; + private ReadOnlyMemory _buffer; + private CancellationTokenRegistration _cancellationRegistration; + private CancellationToken _cancellationToken; + private bool _disposed; + private bool _forStream; + private ManualResetValueTaskSourceCore _mrvtsc; + private byte _operationMode; // 0-send 1-flush 2-wait for space + private bool _signled; + + private bool _transportClosed; + private long _unflushedBytes; + private int _waitForByteCount; + private int _waitForSegmentCount; + + public KcpSendQueue(IKcpBufferPool bufferPool, KcpConversationUpdateActivation updateActivation, bool stream, + int capacity, int mss, KcpSendReceiveQueueItemCache cache) { - private readonly IKcpBufferPool _bufferPool; - private readonly KcpConversationUpdateActivation _updateActivation; - private readonly bool _stream; - private readonly int _capacity; - private readonly int _mss; - private readonly KcpSendReceiveQueueItemCache _cache; - private ManualResetValueTaskSourceCore _mrvtsc; - - private readonly LinkedListOfQueueItem _queue; - private long _unflushedBytes; - - private bool _transportClosed; - private bool _disposed; - - private bool _activeWait; - private bool _signled; - private bool _forStream; - private byte _operationMode; // 0-send 1-flush 2-wait for space - private ReadOnlyMemory _buffer; - private int _waitForByteCount; - private int _waitForSegmentCount; - private CancellationToken _cancellationToken; - private CancellationTokenRegistration _cancellationRegistration; - - private bool _ackListNotEmpty; - public KcpSendQueue(IKcpBufferPool bufferPool, KcpConversationUpdateActivation updateActivation, bool stream, int capacity, int mss, KcpSendReceiveQueueItemCache cache) + _bufferPool = bufferPool; + _updateActivation = updateActivation; + _stream = stream; + _capacity = capacity; + _mss = mss; + _cache = cache; + _mrvtsc = new ManualResetValueTaskSourceCore { - _bufferPool = bufferPool; - _updateActivation = updateActivation; - _stream = stream; - _capacity = capacity; - _mss = mss; - _cache = cache; - _mrvtsc = new ManualResetValueTaskSourceCore() - { - RunContinuationsAsynchronously = true - }; + RunContinuationsAsynchronously = true + }; - _queue = new LinkedListOfQueueItem(); - } + _queue = new LinkedListOfQueueItem(); + } - public ValueTaskSourceStatus GetStatus(short token) => _mrvtsc.GetStatus(token); - public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) - => _mrvtsc.OnCompleted(continuation, state, token, flags); - - bool IValueTaskSource.GetResult(short token) + public void Dispose() + { + lock (_queue) { - _cancellationRegistration.Dispose(); - try + if (_disposed) return; + if (_activeWait && !_signled) { - return _mrvtsc.GetResult(token); - } - finally - { - _mrvtsc.Reset(); - lock (_queue) + if (_forStream) { - _activeWait = false; - _signled = false; - _cancellationRegistration = default; + ClearPreviousOperation(); + _mrvtsc.SetException(ThrowHelper.NewTransportClosedForStreamException()); + } + else + { + ClearPreviousOperation(); + _mrvtsc.SetResult(false); } } - } - void IValueTaskSource.GetResult(short token) - { - try + var node = _queue.First; + while (node is not null) { - _mrvtsc.GetResult(token); + node.ValueRef.Data.Release(); + node = node.Next; } - finally - { - _mrvtsc.Reset(); - lock (_queue) - { - _activeWait = false; - _signled = false; - _cancellationRegistration = default; - } - } - } - public bool TryGetAvailableSpace(out int byteCount, out int segmentCount) + _queue.Clear(); + _disposed = true; + _transportClosed = true; + } + } + + void IValueTaskSource.GetResult(short token) + { + try { + _mrvtsc.GetResult(token); + } + finally + { + _mrvtsc.Reset(); lock (_queue) { - if (_transportClosed || _disposed) - { - byteCount = 0; - segmentCount = 0; - return false; - } - if (_activeWait && _operationMode == 0) - { - byteCount = 0; - segmentCount = 0; - return true; - } - GetAvailableSpaceCore(out byteCount, out segmentCount); - return true; + _activeWait = false; + _signled = false; + _cancellationRegistration = default; } } + } - private void GetAvailableSpaceCore(out int byteCount, out int segmentCount) + public ValueTaskSourceStatus GetStatus(short token) + { + return _mrvtsc.GetStatus(token); + } + + public void OnCompleted(Action continuation, object? state, short token, + ValueTaskSourceOnCompletedFlags flags) + { + _mrvtsc.OnCompleted(continuation, state, token, flags); + } + + bool IValueTaskSource.GetResult(short token) + { + _cancellationRegistration.Dispose(); + try { - int mss = _mss; - int availableFragments = _capacity - _queue.Count; - if (availableFragments < 0) + return _mrvtsc.GetResult(token); + } + finally + { + _mrvtsc.Reset(); + lock (_queue) + { + _activeWait = false; + _signled = false; + _cancellationRegistration = default; + } + } + } + + public bool TryGetAvailableSpace(out int byteCount, out int segmentCount) + { + lock (_queue) + { + if (_transportClosed || _disposed) { byteCount = 0; segmentCount = 0; - return; + return false; } - int availableBytes = availableFragments * mss; - if (_stream) + + if (_activeWait && _operationMode == 0) { - LinkedListNodeOfQueueItem? last = _queue.Last; - if (last is not null) - { - availableBytes += _mss - last.ValueRef.Data.Length; - } + byteCount = 0; + segmentCount = 0; + return true; } - byteCount = availableBytes; - segmentCount = availableFragments; + + GetAvailableSpaceCore(out byteCount, out segmentCount); + return true; + } + } + + private void GetAvailableSpaceCore(out int byteCount, out int segmentCount) + { + var mss = _mss; + var availableFragments = _capacity - _queue.Count; + if (availableFragments < 0) + { + byteCount = 0; + segmentCount = 0; + return; } - public ValueTask WaitForAvailableSpaceAsync(int minimumBytes, int minimumSegments, CancellationToken cancellationToken) + var availableBytes = availableFragments * mss; + if (_stream) { - short token; - lock (_queue) - { - if (_transportClosed || _disposed) - { - minimumBytes = 0; - minimumSegments = 0; - return default; - } - if ((uint)minimumBytes > (uint)(_mss * _capacity)) - { - return new ValueTask(Task.FromException(ThrowHelper.NewArgumentOutOfRangeException(nameof(minimumBytes)))); - } - if ((uint)minimumSegments > (uint)_capacity) - { - return new ValueTask(Task.FromException(ThrowHelper.NewArgumentOutOfRangeException(nameof(minimumSegments)))); - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - GetAvailableSpaceCore(out int currentByteCount, out int currentSegmentCount); - if (currentByteCount >= minimumBytes && currentSegmentCount >= minimumSegments) - { - return new ValueTask(true); - } - - _activeWait = true; - Debug.Assert(!_signled); - _forStream = false; - _operationMode = 2; - _waitForByteCount = minimumBytes; - _waitForSegmentCount = minimumSegments; - _cancellationToken = cancellationToken; - token = _mrvtsc.Version; - } - - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); - - return new ValueTask(this, token); + var last = _queue.Last; + if (last is not null) availableBytes += _mss - last.ValueRef.Data.Length; } - public bool TrySend(ReadOnlySpan buffer, bool allowPartialSend, out int bytesWritten) + byteCount = availableBytes; + segmentCount = availableFragments; + } + + public ValueTask WaitForAvailableSpaceAsync(int minimumBytes, int minimumSegments, + CancellationToken cancellationToken) + { + short token; + lock (_queue) { - lock (_queue) + if (_transportClosed || _disposed) { - if (allowPartialSend && !_stream) - { - ThrowHelper.ThrowAllowPartialSendArgumentException(); - } - if (_transportClosed || _disposed) + minimumBytes = 0; + minimumSegments = 0; + return default; + } + + if ((uint)minimumBytes > (uint)(_mss * _capacity)) + return new ValueTask( + Task.FromException(ThrowHelper.NewArgumentOutOfRangeException(nameof(minimumBytes)))); + if ((uint)minimumSegments > (uint)_capacity) + return new ValueTask( + Task.FromException(ThrowHelper.NewArgumentOutOfRangeException(nameof(minimumSegments)))); + if (_activeWait) + return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask(Task.FromCanceled(cancellationToken)); + GetAvailableSpaceCore(out var currentByteCount, out var currentSegmentCount); + if (currentByteCount >= minimumBytes && currentSegmentCount >= minimumSegments) + return new ValueTask(true); + + _activeWait = true; + Debug.Assert(!_signled); + _forStream = false; + _operationMode = 2; + _waitForByteCount = minimumBytes; + _waitForSegmentCount = minimumSegments; + _cancellationToken = cancellationToken; + token = _mrvtsc.Version; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public bool TrySend(ReadOnlySpan buffer, bool allowPartialSend, out int bytesWritten) + { + lock (_queue) + { + if (allowPartialSend && !_stream) ThrowHelper.ThrowAllowPartialSendArgumentException(); + if (_transportClosed || _disposed) + { + bytesWritten = 0; + return false; + } + + var mss = _mss; + // Make sure there is enough space. + if (!allowPartialSend) + { + var spaceAvailable = mss * (_capacity - _queue.Count); + if (spaceAvailable < 0) { bytesWritten = 0; return false; } - int mss = _mss; - // Make sure there is enough space. - if (!allowPartialSend) - { - int spaceAvailable = mss * (_capacity - _queue.Count); - if (spaceAvailable < 0) - { - bytesWritten = 0; - return false; - } - if (_stream) - { - LinkedListNodeOfQueueItem? last = _queue.Last; - if (last is not null) - { - spaceAvailable += mss - last.ValueRef.Data.Length; - } - } - - if (buffer.Length > spaceAvailable) - { - bytesWritten = 0; - return false; - } - } - - // Copy buffer content. - bytesWritten = 0; if (_stream) { - LinkedListNodeOfQueueItem? node = _queue.Last; - if (node is not null) - { - ref KcpBuffer data = ref node.ValueRef.Data; - int expand = mss - data.Length; - expand = Math.Min(expand, buffer.Length); - if (expand > 0) - { - data = data.AppendData(buffer.Slice(0, expand)); - buffer = buffer.Slice(expand); - Interlocked.Add(ref _unflushedBytes, expand); - bytesWritten = expand; - } - } + var last = _queue.Last; + if (last is not null) spaceAvailable += mss - last.ValueRef.Data.Length; + } - if (buffer.IsEmpty) + if (buffer.Length > spaceAvailable) + { + bytesWritten = 0; + return false; + } + } + + // Copy buffer content. + bytesWritten = 0; + if (_stream) + { + var node = _queue.Last; + if (node is not null) + { + ref var data = ref node.ValueRef.Data; + var expand = mss - data.Length; + expand = Math.Min(expand, buffer.Length); + if (expand > 0) { - return true; + data = data.AppendData(buffer.Slice(0, expand)); + buffer = buffer.Slice(expand); + Interlocked.Add(ref _unflushedBytes, expand); + bytesWritten = expand; } } - bool anySegmentAdded = false; - int count = buffer.Length <= mss ? 1 : (buffer.Length + mss - 1) / mss; - Debug.Assert(count >= 1); - while (count > 0 && _queue.Count < _capacity) - { - int fragment = --count; - - int size = buffer.Length > mss ? mss : buffer.Length; - - KcpRentedBuffer owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(mss, false)); - KcpBuffer kcpBuffer = KcpBuffer.CreateFromSpan(owner, buffer.Slice(0, size)); - buffer = buffer.Slice(size); - - _queue.AddLast(_cache.Rent(kcpBuffer, _stream ? (byte)0 : (byte)fragment)); - Interlocked.Add(ref _unflushedBytes, size); - bytesWritten += size; - anySegmentAdded = true; - } - - if (anySegmentAdded) - { - _updateActivation.Notify(); - } - return anySegmentAdded; + if (buffer.IsEmpty) return true; } - } - public ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) - { - short token; - lock (_queue) + var anySegmentAdded = false; + var count = buffer.Length <= mss ? 1 : (buffer.Length + mss - 1) / mss; + Debug.Assert(count >= 1); + while (count > 0 && _queue.Count < _capacity) { - if (_transportClosed || _disposed) - { - return new ValueTask(false); - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } + var fragment = --count; - int mss = _mss; - if (_stream) - { - LinkedListNodeOfQueueItem? node = _queue.Last; - if (node is not null) - { - ref KcpBuffer data = ref node.ValueRef.Data; - int expand = mss - data.Length; - expand = Math.Min(expand, buffer.Length); - if (expand > 0) - { - data = data.AppendData(buffer.Span.Slice(0, expand)); - buffer = buffer.Slice(expand); - Interlocked.Add(ref _unflushedBytes, expand); - } - } + var size = buffer.Length > mss ? mss : buffer.Length; - if (buffer.IsEmpty) + var owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(mss, false)); + var kcpBuffer = KcpBuffer.CreateFromSpan(owner, buffer.Slice(0, size)); + buffer = buffer.Slice(size); + + _queue.AddLast(_cache.Rent(kcpBuffer, _stream ? (byte)0 : (byte)fragment)); + Interlocked.Add(ref _unflushedBytes, size); + bytesWritten += size; + anySegmentAdded = true; + } + + if (anySegmentAdded) _updateActivation.Notify(); + return anySegmentAdded; + } + } + + public ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) + { + short token; + lock (_queue) + { + if (_transportClosed || _disposed) return new ValueTask(false); + if (_activeWait) + return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask(Task.FromCanceled(cancellationToken)); + + var mss = _mss; + if (_stream) + { + var node = _queue.Last; + if (node is not null) + { + ref var data = ref node.ValueRef.Data; + var expand = mss - data.Length; + expand = Math.Min(expand, buffer.Length); + if (expand > 0) { - return new ValueTask(true); + data = data.AppendData(buffer.Span.Slice(0, expand)); + buffer = buffer.Slice(expand); + Interlocked.Add(ref _unflushedBytes, expand); } } - int count = buffer.Length <= mss ? 1 : (buffer.Length + mss - 1) / mss; - Debug.Assert(count >= 1); - - if (!_stream && count > 256) - { - return new ValueTask(Task.FromException(ThrowHelper.NewMessageTooLargeForBufferArgument())); - } - - // synchronously put fragments into queue. - while (count > 0 && _queue.Count < _capacity) - { - int fragment = --count; - - int size = buffer.Length > mss ? mss : buffer.Length; - KcpRentedBuffer owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(mss, false)); - KcpBuffer kcpBuffer = KcpBuffer.CreateFromSpan(owner, buffer.Span.Slice(0, size)); - buffer = buffer.Slice(size); - - _queue.AddLast(_cache.Rent(kcpBuffer, _stream ? (byte)0 : (byte)fragment)); - Interlocked.Add(ref _unflushedBytes, size); - } - - _updateActivation.Notify(); - - if (count == 0) - { - return new ValueTask(true); - } - - _activeWait = true; - Debug.Assert(!_signled); - _forStream = false; - _operationMode = 0; - _buffer = buffer; - _cancellationToken = cancellationToken; - token = _mrvtsc.Version; + if (buffer.IsEmpty) return new ValueTask(true); } - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); + var count = buffer.Length <= mss ? 1 : (buffer.Length + mss - 1) / mss; + Debug.Assert(count >= 1); - return new ValueTask(this, token); - } + if (!_stream && count > 256) + return new ValueTask(Task.FromException(ThrowHelper.NewMessageTooLargeForBufferArgument())); - public ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) - { - short token; - lock (_queue) + // synchronously put fragments into queue. + while (count > 0 && _queue.Count < _capacity) { - if (_transportClosed || _disposed) - { - return new ValueTask(Task.FromException(ThrowHelper.NewTransportClosedForStreamException())); - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } + var fragment = --count; - int mss = _mss; - if (_stream) - { - LinkedListNodeOfQueueItem? node = _queue.Last; - if (node is not null) - { - ref KcpBuffer data = ref node.ValueRef.Data; - int expand = mss - data.Length; - expand = Math.Min(expand, buffer.Length); - if (expand > 0) - { - data = data.AppendData(buffer.Span.Slice(0, expand)); - buffer = buffer.Slice(expand); - Interlocked.Add(ref _unflushedBytes, expand); - } - } + var size = buffer.Length > mss ? mss : buffer.Length; + var owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(mss, false)); + var kcpBuffer = KcpBuffer.CreateFromSpan(owner, buffer.Span.Slice(0, size)); + buffer = buffer.Slice(size); - if (buffer.IsEmpty) - { - return default; - } - } - - int count = buffer.Length <= mss ? 1 : (buffer.Length + mss - 1) / mss; - Debug.Assert(count >= 1); - - Debug.Assert(_stream); - // synchronously put fragments into queue. - while (count > 0 && _queue.Count < _capacity) - { - int size = buffer.Length > mss ? mss : buffer.Length; - KcpRentedBuffer owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(mss, false)); - KcpBuffer kcpBuffer = KcpBuffer.CreateFromSpan(owner, buffer.Span.Slice(0, size)); - buffer = buffer.Slice(size); - - _queue.AddLast(_cache.Rent(kcpBuffer, 0)); - Interlocked.Add(ref _unflushedBytes, size); - } - - _updateActivation.Notify(); - - if (count == 0) - { - return default; - } - - _activeWait = true; - Debug.Assert(!_signled); - _forStream = true; - _operationMode = 0; - _buffer = buffer; - _cancellationToken = cancellationToken; - token = _mrvtsc.Version; + _queue.AddLast(_cache.Rent(kcpBuffer, _stream ? (byte)0 : (byte)fragment)); + Interlocked.Add(ref _unflushedBytes, size); } - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); + _updateActivation.Notify(); - return new ValueTask(this, token); - } + if (count == 0) return new ValueTask(true); - public ValueTask FlushAsync(CancellationToken cancellationToken) - { - short token; - lock (_queue) - { - if (_transportClosed || _disposed) - { - return new ValueTask(false); - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - - _activeWait = true; - Debug.Assert(!_signled); - _forStream = false; - _operationMode = 1; - _buffer = default; - _cancellationToken = cancellationToken; - token = _mrvtsc.Version; - } - - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); - - return new ValueTask(this, token); - } - - public ValueTask FlushForStreamAsync(CancellationToken cancellationToken) - { - short token; - lock (_queue) - { - if (_transportClosed || _disposed) - { - return new ValueTask(Task.FromException(ThrowHelper.NewTransportClosedForStreamException())); - } - if (_activeWait) - { - return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); - } - if (cancellationToken.IsCancellationRequested) - { - return new ValueTask(Task.FromCanceled(cancellationToken)); - } - - _activeWait = true; - Debug.Assert(!_signled); - _forStream = true; - _operationMode = 1; - _buffer = default; - _cancellationToken = cancellationToken; - token = _mrvtsc.Version; - } - - _cancellationRegistration = cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); - - return new ValueTask(this, token); - } - - public bool CancelPendingOperation(Exception? innerException, CancellationToken cancellationToken) - { - lock (_queue) - { - if (_activeWait && !_signled) - { - ClearPreviousOperation(); - _mrvtsc.SetException(ThrowHelper.NewOperationCanceledExceptionForCancelPendingSend(innerException, cancellationToken)); - return true; - } - } - return false; - } - - private void SetCanceled() - { - lock (_queue) - { - if (_activeWait && !_signled) - { - CancellationToken cancellationToken = _cancellationToken; - ClearPreviousOperation(); - _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); - } - } - } - - private void ClearPreviousOperation() - { - _signled = true; + _activeWait = true; + Debug.Assert(!_signled); _forStream = false; _operationMode = 0; - _buffer = default; - _waitForByteCount = default; - _waitForSegmentCount = default; - _cancellationToken = default; + _buffer = buffer; + _cancellationToken = cancellationToken; + token = _mrvtsc.Version; } - public bool TryDequeue(out KcpBuffer data, out byte fragment) + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) + { + short token; + lock (_queue) { + if (_transportClosed || _disposed) + return new ValueTask(Task.FromException(ThrowHelper.NewTransportClosedForStreamException())); + if (_activeWait) return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); + if (cancellationToken.IsCancellationRequested) return new ValueTask(Task.FromCanceled(cancellationToken)); + + var mss = _mss; + if (_stream) + { + var node = _queue.Last; + if (node is not null) + { + ref var data = ref node.ValueRef.Data; + var expand = mss - data.Length; + expand = Math.Min(expand, buffer.Length); + if (expand > 0) + { + data = data.AppendData(buffer.Span.Slice(0, expand)); + buffer = buffer.Slice(expand); + Interlocked.Add(ref _unflushedBytes, expand); + } + } + + if (buffer.IsEmpty) return default; + } + + var count = buffer.Length <= mss ? 1 : (buffer.Length + mss - 1) / mss; + Debug.Assert(count >= 1); + + Debug.Assert(_stream); + // synchronously put fragments into queue. + while (count > 0 && _queue.Count < _capacity) + { + var size = buffer.Length > mss ? mss : buffer.Length; + var owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(mss, false)); + var kcpBuffer = KcpBuffer.CreateFromSpan(owner, buffer.Span.Slice(0, size)); + buffer = buffer.Slice(size); + + _queue.AddLast(_cache.Rent(kcpBuffer, 0)); + Interlocked.Add(ref _unflushedBytes, size); + } + + _updateActivation.Notify(); + + if (count == 0) return default; + + _activeWait = true; + Debug.Assert(!_signled); + _forStream = true; + _operationMode = 0; + _buffer = buffer; + _cancellationToken = cancellationToken; + token = _mrvtsc.Version; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public ValueTask FlushAsync(CancellationToken cancellationToken) + { + short token; + lock (_queue) + { + if (_transportClosed || _disposed) return new ValueTask(false); + if (_activeWait) + return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); + if (cancellationToken.IsCancellationRequested) + return new ValueTask(Task.FromCanceled(cancellationToken)); + + _activeWait = true; + Debug.Assert(!_signled); + _forStream = false; + _operationMode = 1; + _buffer = default; + _cancellationToken = cancellationToken; + token = _mrvtsc.Version; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public ValueTask FlushForStreamAsync(CancellationToken cancellationToken) + { + short token; + lock (_queue) + { + if (_transportClosed || _disposed) + return new ValueTask(Task.FromException(ThrowHelper.NewTransportClosedForStreamException())); + if (_activeWait) return new ValueTask(Task.FromException(ThrowHelper.NewConcurrentSendException())); + if (cancellationToken.IsCancellationRequested) return new ValueTask(Task.FromCanceled(cancellationToken)); + + _activeWait = true; + Debug.Assert(!_signled); + _forStream = true; + _operationMode = 1; + _buffer = default; + _cancellationToken = cancellationToken; + token = _mrvtsc.Version; + } + + _cancellationRegistration = + cancellationToken.UnsafeRegister(state => ((KcpSendQueue?)state)!.SetCanceled(), this); + + return new ValueTask(this, token); + } + + public bool CancelPendingOperation(Exception? innerException, CancellationToken cancellationToken) + { + lock (_queue) + { + if (_activeWait && !_signled) + { + ClearPreviousOperation(); + _mrvtsc.SetException( + ThrowHelper.NewOperationCanceledExceptionForCancelPendingSend(innerException, cancellationToken)); + return true; + } + } + + return false; + } + + private void SetCanceled() + { + lock (_queue) + { + if (_activeWait && !_signled) + { + var cancellationToken = _cancellationToken; + ClearPreviousOperation(); + _mrvtsc.SetException(new OperationCanceledException(cancellationToken)); + } + } + } + + private void ClearPreviousOperation() + { + _signled = true; + _forStream = false; + _operationMode = 0; + _buffer = default; + _waitForByteCount = default; + _waitForSegmentCount = default; + _cancellationToken = default; + } + + public bool TryDequeue(out KcpBuffer data, out byte fragment) + { + lock (_queue) + { + var node = _queue.First; + if (node is null) + { + data = default; + fragment = default; + return false; + } + + (data, fragment) = node.ValueRef; + _queue.RemoveFirst(); + node.ValueRef = default; + _cache.Return(node); + + MoveOneSegmentIn(); + CheckForAvailableSpace(); + return true; + } + } + + public void NotifyAckListChanged(bool itemsListNotEmpty) + { + lock (_queue) + { + if (_transportClosed || _disposed) return; + + _ackListNotEmpty = itemsListNotEmpty; + TryCompleteFlush(Interlocked.Read(ref _unflushedBytes)); + } + } + + private void MoveOneSegmentIn() + { + if (_activeWait && !_signled && _operationMode == 0) + { + var buffer = _buffer; + var mss = _mss; + var count = buffer.Length <= mss ? 1 : (buffer.Length + mss - 1) / mss; + + var size = buffer.Length > mss ? mss : buffer.Length; + var owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(mss, false)); + var kcpBuffer = KcpBuffer.CreateFromSpan(owner, buffer.Span.Slice(0, size)); + _buffer = buffer.Slice(size); + + _queue.AddLast(_cache.Rent(kcpBuffer, _stream ? (byte)0 : (byte)(count - 1))); + Interlocked.Add(ref _unflushedBytes, size); + + if (count == 1) + { + ClearPreviousOperation(); + _mrvtsc.SetResult(true); + } + } + } + + private void CheckForAvailableSpace() + { + if (_activeWait && !_signled && _operationMode == 2) + { + GetAvailableSpaceCore(out var byteCount, out var segmentCount); + if (byteCount >= _waitForByteCount && segmentCount >= _waitForSegmentCount) + { + ClearPreviousOperation(); + _mrvtsc.SetResult(true); + } + } + } + + private void TryCompleteFlush(long unflushedBytes) + { + if (_activeWait && !_signled && _operationMode == 1) + if (_queue.Last is null && unflushedBytes == 0 && !_ackListNotEmpty) + { + ClearPreviousOperation(); + _mrvtsc.SetResult(true); + } + } + + public void SubtractUnflushedBytes(int size) + { + var unflushedBytes = Interlocked.Add(ref _unflushedBytes, -size); + if (unflushedBytes == 0) lock (_queue) { - LinkedListNodeOfQueueItem? node = _queue.First; - if (node is null) + TryCompleteFlush(0); + } + } + + public long GetUnflushedBytes() + { + if (_transportClosed || _disposed) return 0; + return Interlocked.Read(ref _unflushedBytes); + } + + public void SetTransportClosed() + { + lock (_queue) + { + if (_transportClosed || _disposed) return; + if (_activeWait && !_signled) + { + if (_forStream) { - data = default; - fragment = default; - return false; + ClearPreviousOperation(); + _mrvtsc.SetException(ThrowHelper.NewTransportClosedForStreamException()); } else - { - (data, fragment) = node.ValueRef; - _queue.RemoveFirst(); - node.ValueRef = default; - _cache.Return(node); - - MoveOneSegmentIn(); - CheckForAvailableSpace(); - return true; - } - } - } - - public void NotifyAckListChanged(bool itemsListNotEmpty) - { - lock (_queue) - { - if (_transportClosed || _disposed) - { - return; - } - - _ackListNotEmpty = itemsListNotEmpty; - TryCompleteFlush(Interlocked.Read(ref _unflushedBytes)); - } - } - - private void MoveOneSegmentIn() - { - if (_activeWait && !_signled && _operationMode == 0) - { - ReadOnlyMemory buffer = _buffer; - int mss = _mss; - int count = buffer.Length <= mss ? 1 : (buffer.Length + mss - 1) / mss; - - int size = buffer.Length > mss ? mss : buffer.Length; - KcpRentedBuffer owner = _bufferPool.Rent(new KcpBufferPoolRentOptions(mss, false)); - KcpBuffer kcpBuffer = KcpBuffer.CreateFromSpan(owner, buffer.Span.Slice(0, size)); - _buffer = buffer.Slice(size); - - _queue.AddLast(_cache.Rent(kcpBuffer, _stream ? (byte)0 : (byte)(count - 1))); - Interlocked.Add(ref _unflushedBytes, size); - - if (count == 1) { ClearPreviousOperation(); - _mrvtsc.SetResult(true); + _mrvtsc.SetResult(false); } } - } - private void CheckForAvailableSpace() - { - if (_activeWait && !_signled && _operationMode == 2) - { - GetAvailableSpaceCore(out int byteCount, out int segmentCount); - if (byteCount >= _waitForByteCount && segmentCount >= _waitForSegmentCount) - { - ClearPreviousOperation(); - _mrvtsc.SetResult(true); - } - } + _transportClosed = true; + Interlocked.Exchange(ref _unflushedBytes, 0); } - - private void TryCompleteFlush(long unflushedBytes) - { - if (_activeWait && !_signled && _operationMode == 1) - { - if (_queue.Last is null && unflushedBytes == 0 && !_ackListNotEmpty) - { - ClearPreviousOperation(); - _mrvtsc.SetResult(true); - } - } - } - - public void SubtractUnflushedBytes(int size) - { - long unflushedBytes = Interlocked.Add(ref _unflushedBytes, -size); - if (unflushedBytes == 0) - { - lock (_queue) - { - TryCompleteFlush(0); - } - } - } - - public long GetUnflushedBytes() - { - if (_transportClosed || _disposed) - { - return 0; - } - return Interlocked.Read(ref _unflushedBytes); - } - - public void SetTransportClosed() - { - lock (_queue) - { - if (_transportClosed || _disposed) - { - return; - } - if (_activeWait && !_signled) - { - if (_forStream) - { - ClearPreviousOperation(); - _mrvtsc.SetException(ThrowHelper.NewTransportClosedForStreamException()); - } - else - { - ClearPreviousOperation(); - _mrvtsc.SetResult(false); - } - } - _transportClosed = true; - Interlocked.Exchange(ref _unflushedBytes, 0); - } - } - - public void Dispose() - { - lock (_queue) - { - if (_disposed) - { - return; - } - if (_activeWait && !_signled) - { - if (_forStream) - { - ClearPreviousOperation(); - _mrvtsc.SetException(ThrowHelper.NewTransportClosedForStreamException()); - } - else - { - ClearPreviousOperation(); - _mrvtsc.SetResult(false); - } - } - LinkedListNodeOfQueueItem? node = _queue.First; - while (node is not null) - { - node.ValueRef.Data.Release(); - node = node.Next; - } - _queue.Clear(); - _disposed = true; - _transportClosed = true; - } - } - } -} +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSendReceiveBufferItem.cs b/GameServer/KcpSharp/KcpSendReceiveBufferItem.cs index 9c1ab0f4..6e78cf39 100644 --- a/GameServer/KcpSharp/KcpSendReceiveBufferItem.cs +++ b/GameServer/KcpSharp/KcpSendReceiveBufferItem.cs @@ -1,9 +1,8 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal struct KcpSendReceiveBufferItem { - internal struct KcpSendReceiveBufferItem - { - public KcpBuffer Data; - public KcpPacketHeader Segment; - public KcpSendSegmentStats Stats; - } -} + public KcpBuffer Data; + public KcpPacketHeader Segment; + public KcpSendSegmentStats Stats; +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSendReceiveBufferItemCache.cs b/GameServer/KcpSharp/KcpSendReceiveBufferItemCache.cs index f0e83d8a..220279f7 100644 --- a/GameServer/KcpSharp/KcpSendReceiveBufferItemCache.cs +++ b/GameServer/KcpSharp/KcpSendReceiveBufferItemCache.cs @@ -1,73 +1,68 @@ - -#if NEED_LINKEDLIST_SHIM +#if NEED_LINKEDLIST_SHIM using LinkedListOfBufferItem = KcpSharp.NetstandardShim.LinkedList; using LinkedListNodeOfBufferItem = KcpSharp.NetstandardShim.LinkedListNode; #else -using LinkedListNodeOfBufferItem = System.Collections.Generic.LinkedListNode; -using LinkedListOfBufferItem = System.Collections.Generic.LinkedList; +using LinkedListNodeOfBufferItem = + System.Collections.Generic.LinkedListNode; +using LinkedListOfBufferItem = + System.Collections.Generic.LinkedList; #endif -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal struct KcpSendReceiveBufferItemCache { - internal struct KcpSendReceiveBufferItemCache + private LinkedListOfBufferItem _items; + private SpinLock _lock; + + public static KcpSendReceiveBufferItemCache Create() { - private LinkedListOfBufferItem _items; - private SpinLock _lock; - - public static KcpSendReceiveBufferItemCache Create() + return new KcpSendReceiveBufferItemCache { - return new KcpSendReceiveBufferItemCache + _items = new LinkedListOfBufferItem(), + _lock = new SpinLock() + }; + } + + public LinkedListNodeOfBufferItem Allocate(in KcpSendReceiveBufferItem item) + { + var lockAcquired = false; + try + { + _lock.Enter(ref lockAcquired); + + var node = _items.First; + if (node is null) { - _items = new LinkedListOfBufferItem(), - _lock = new SpinLock() - }; + node = new LinkedListNodeOfBufferItem(item); + } + else + { + _items.Remove(node); + node.ValueRef = item; + } + + return node; } - - public LinkedListNodeOfBufferItem Allocate(in KcpSendReceiveBufferItem item) + finally { - bool lockAcquired = false; - try - { - _lock.Enter(ref lockAcquired); - - LinkedListNodeOfBufferItem? node = _items.First; - if (node is null) - { - node = new LinkedListNodeOfBufferItem(item); - } - else - { - _items.Remove(node); - node.ValueRef = item; - } - return node; - } - finally - { - if (lockAcquired) - { - _lock.Exit(); - } - } - } - - public void Return(LinkedListNodeOfBufferItem node) - { - bool lockAcquired = false; - try - { - _lock.Enter(ref lockAcquired); - - node.ValueRef = default; - _items.AddLast(node); - } - finally - { - if (lockAcquired) - { - _lock.Exit(); - } - } + if (lockAcquired) _lock.Exit(); } } -} + + public void Return(LinkedListNodeOfBufferItem node) + { + var lockAcquired = false; + try + { + _lock.Enter(ref lockAcquired); + + node.ValueRef = default; + _items.AddLast(node); + } + finally + { + if (lockAcquired) _lock.Exit(); + } + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSendReceiveQueueItemCache.cs b/GameServer/KcpSharp/KcpSendReceiveQueueItemCache.cs index 9b5be70f..a1bf9e36 100644 --- a/GameServer/KcpSharp/KcpSendReceiveQueueItemCache.cs +++ b/GameServer/KcpSharp/KcpSendReceiveQueueItemCache.cs @@ -1,84 +1,75 @@ - -#if NEED_LINKEDLIST_SHIM +#if NEED_LINKEDLIST_SHIM using LinkedListOfQueueItem = KcpSharp.NetstandardShim.LinkedList<(KcpSharp.KcpBuffer Data, byte Fragment)>; using LinkedListNodeOfQueueItem = KcpSharp.NetstandardShim.LinkedListNode<(KcpSharp.KcpBuffer Data, byte Fragment)>; #else -using LinkedListNodeOfQueueItem = System.Collections.Generic.LinkedListNode<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; -using LinkedListOfQueueItem = System.Collections.Generic.LinkedList<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; +using LinkedListNodeOfQueueItem = + System.Collections.Generic.LinkedListNode<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; +using LinkedListOfQueueItem = + System.Collections.Generic.LinkedList<(EggLink.DanhengServer.KcpSharp.KcpBuffer Data, byte Fragment)>; #endif -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class KcpSendReceiveQueueItemCache { - internal sealed class KcpSendReceiveQueueItemCache + private readonly LinkedListOfQueueItem _list = new(); + private SpinLock _lock; + + public LinkedListNodeOfQueueItem Rent(in KcpBuffer buffer, byte fragment) { - private LinkedListOfQueueItem _list = new(); - private SpinLock _lock; - - public LinkedListNodeOfQueueItem Rent(in KcpBuffer buffer, byte fragment) + var lockTaken = false; + try { - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); + _lock.Enter(ref lockTaken); - LinkedListNodeOfQueueItem? node = _list.First; - if (node is null) - { - node = new LinkedListNodeOfQueueItem((buffer, fragment)); - } - else - { - node.ValueRef = (buffer, fragment); - _list.RemoveFirst(); - } - - return node; - } - finally + var node = _list.First; + if (node is null) { - if (lockTaken) - { - _lock.Exit(); - } + node = new LinkedListNodeOfQueueItem((buffer, fragment)); } + else + { + node.ValueRef = (buffer, fragment); + _list.RemoveFirst(); + } + + return node; } - - public void Return(LinkedListNodeOfQueueItem node) + finally { - node.ValueRef = default; - - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); - - _list.AddLast(node); - } - finally - { - if (lockTaken) - { - _lock.Exit(); - } - } - } - - public void Clear() - { - bool lockTaken = false; - try - { - _lock.Enter(ref lockTaken); - - _list.Clear(); - } - finally - { - if (lockTaken) - { - _lock.Exit(); - } - } + if (lockTaken) _lock.Exit(); } } -} + + public void Return(LinkedListNodeOfQueueItem node) + { + node.ValueRef = default; + + var lockTaken = false; + try + { + _lock.Enter(ref lockTaken); + + _list.AddLast(node); + } + finally + { + if (lockTaken) _lock.Exit(); + } + } + + public void Clear() + { + var lockTaken = false; + try + { + _lock.Enter(ref lockTaken); + + _list.Clear(); + } + finally + { + if (lockTaken) _lock.Exit(); + } + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSendSegmentStats.cs b/GameServer/KcpSharp/KcpSendSegmentStats.cs index 2cec9155..67330d68 100644 --- a/GameServer/KcpSharp/KcpSendSegmentStats.cs +++ b/GameServer/KcpSharp/KcpSendSegmentStats.cs @@ -1,20 +1,17 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal readonly struct KcpSendSegmentStats { - internal readonly struct KcpSendSegmentStats + public KcpSendSegmentStats(uint resendTimestamp, uint rto, uint fastAck, uint transmitCount) { - public KcpSendSegmentStats(uint resendTimestamp, uint rto, uint fastAck, uint transmitCount) - { - ResendTimestamp = resendTimestamp; - Rto = rto; - FastAck = fastAck; - TransmitCount = transmitCount; - } - - public uint ResendTimestamp { get; } - public uint Rto { get; } - public uint FastAck { get; } - public uint TransmitCount { get; } - - + ResendTimestamp = resendTimestamp; + Rto = rto; + FastAck = fastAck; + TransmitCount = transmitCount; } -} + + public uint ResendTimestamp { get; } + public uint Rto { get; } + public uint FastAck { get; } + public uint TransmitCount { get; } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSocketTransport.cs b/GameServer/KcpSharp/KcpSocketTransport.cs index 3e5a0fdf..2ed8834a 100644 --- a/GameServer/KcpSharp/KcpSocketTransport.cs +++ b/GameServer/KcpSharp/KcpSocketTransport.cs @@ -1,159 +1,124 @@ -using KcpSharp; -using System.Net; +using System.Net; using System.Net.Sockets; +using KcpSharp; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Helper methods to create socket transports for KCP conversations. +/// +public static class KcpSocketTransport { + /// + /// Create a socket transport for KCP covnersation. + /// + /// The udp listener instance. + /// The remote endpoint. + /// The conversation ID. + /// The options of the . + /// The created socket transport instance. + public static IKcpTransport CreateConversation(UdpClient listener, IPEndPoint endPoint, + long conversationId, KcpConversationOptions? options) + { + if (listener is null) throw new ArgumentNullException(nameof(listener)); + if (endPoint is null) throw new ArgumentNullException(nameof(endPoint)); + + return new KcpSocketTransportForConversation(listener, endPoint, conversationId, options); + } /// - /// Helper methods to create socket transports for KCP conversations. + /// Create a socket transport for KCP covnersation with no conversation ID. /// - public static class KcpSocketTransport + /// The udp listener instance. + /// The remote endpoint. + /// The options of the . + /// The created socket transport instance. + public static IKcpTransport CreateConversation(UdpClient listener, IPEndPoint endPoint, + KcpConversationOptions? options) { - /// - /// Create a socket transport for KCP covnersation. - /// - /// The udp listener instance. - /// The remote endpoint. - /// The conversation ID. - /// The options of the . - /// The created socket transport instance. - public static IKcpTransport CreateConversation(UdpClient listener, IPEndPoint endPoint, long conversationId, KcpConversationOptions? options) - { - if (listener is null) - { - throw new ArgumentNullException(nameof(listener)); - } - if (endPoint is null) - { - throw new ArgumentNullException(nameof(endPoint)); - } + if (listener is null) throw new ArgumentNullException(nameof(listener)); + if (endPoint is null) throw new ArgumentNullException(nameof(endPoint)); - return new KcpSocketTransportForConversation(listener, endPoint, conversationId, options); - } - - /// - /// Create a socket transport for KCP covnersation with no conversation ID. - /// - /// The udp listener instance. - /// The remote endpoint. - /// The options of the . - /// The created socket transport instance. - public static IKcpTransport CreateConversation(UdpClient listener, IPEndPoint endPoint, KcpConversationOptions? options) - { - if (listener is null) - { - throw new ArgumentNullException(nameof(listener)); - } - if (endPoint is null) - { - throw new ArgumentNullException(nameof(endPoint)); - } - - return new KcpSocketTransportForConversation(listener, endPoint, null, options); - } - - /// - /// Create a socket transport for raw channel. - /// - /// The udp listener instance. - /// The remote endpoint. - /// The conversation ID. - /// The options of the . - /// The created socket transport instance. - public static IKcpTransport CreateRawChannel(UdpClient listener, IPEndPoint endPoint, long conversationId, KcpRawChannelOptions? options) - { - if (listener is null) - { - throw new ArgumentNullException(nameof(listener)); - } - if (endPoint is null) - { - throw new ArgumentNullException(nameof(endPoint)); - } - - return new KcpSocketTransportForRawChannel(listener, endPoint, conversationId, options); - } - - /// - /// Create a socket transport for raw channel with no conversation ID. - /// - /// The udp listener instance. - /// The remote endpoint. - /// The options of the . - /// The created socket transport instance. - public static IKcpTransport CreateRawChannel(UdpClient listener, IPEndPoint endPoint, KcpRawChannelOptions? options) - { - if (listener is null) - { - throw new ArgumentNullException(nameof(listener)); - } - if (endPoint is null) - { - throw new ArgumentNullException(nameof(endPoint)); - } - - return new KcpSocketTransportForRawChannel(listener, endPoint, null, options); - } - - /// - /// Create a socket transport for multiplex connection. - /// - /// The udp listener instance. - /// The maximum packet size that can be transmitted over the socket. - /// - public static IKcpTransport CreateMultiplexConnection(UdpClient listener, int mtu) - { - if (listener is null) - { - throw new ArgumentNullException(nameof(listener)); - } - - return new KcpSocketTransportForMultiplexConnection(listener, mtu); - } - - /// - /// Create a socket transport for multiplex connection. - /// - /// The type of the user state. - /// The udp listener instance. - /// The maximum packet size that can be transmitted over the socket. - /// - public static IKcpTransport> CreateMultiplexConnection(UdpClient listener, IPEndPoint endPoint, int mtu) - { - if (listener is null) - { - throw new ArgumentNullException(nameof(listener)); - } - if (endPoint is null) - { - throw new ArgumentNullException(nameof(endPoint)); - } - - return new KcpSocketTransportForMultiplexConnection(listener, mtu); - } - - /// - /// Create a socket transport for multiplex connection. - /// - /// The type of the user state. - /// The udp listener instance. - /// The remote endpoint. - /// The maximum packet size that can be transmitted over the socket. - /// The action to invoke when state object is removed. - /// - public static IKcpTransport> CreateMultiplexConnection(UdpClient listener, EndPoint endPoint, int mtu, Action? disposeAction) - { - if (listener is null) - { - throw new ArgumentNullException(nameof(listener)); - } - if (endPoint is null) - { - throw new ArgumentNullException(nameof(endPoint)); - } - - return new KcpSocketTransportForMultiplexConnection(listener, mtu, disposeAction); - } + return new KcpSocketTransportForConversation(listener, endPoint, null, options); } -} + + /// + /// Create a socket transport for raw channel. + /// + /// The udp listener instance. + /// The remote endpoint. + /// The conversation ID. + /// The options of the . + /// The created socket transport instance. + public static IKcpTransport CreateRawChannel(UdpClient listener, IPEndPoint endPoint, + long conversationId, KcpRawChannelOptions? options) + { + if (listener is null) throw new ArgumentNullException(nameof(listener)); + if (endPoint is null) throw new ArgumentNullException(nameof(endPoint)); + + return new KcpSocketTransportForRawChannel(listener, endPoint, conversationId, options); + } + + /// + /// Create a socket transport for raw channel with no conversation ID. + /// + /// The udp listener instance. + /// The remote endpoint. + /// The options of the . + /// The created socket transport instance. + public static IKcpTransport CreateRawChannel(UdpClient listener, IPEndPoint endPoint, + KcpRawChannelOptions? options) + { + if (listener is null) throw new ArgumentNullException(nameof(listener)); + if (endPoint is null) throw new ArgumentNullException(nameof(endPoint)); + + return new KcpSocketTransportForRawChannel(listener, endPoint, null, options); + } + + /// + /// Create a socket transport for multiplex connection. + /// + /// The udp listener instance. + /// The maximum packet size that can be transmitted over the socket. + /// + public static IKcpTransport CreateMultiplexConnection(UdpClient listener, int mtu) + { + if (listener is null) throw new ArgumentNullException(nameof(listener)); + + return new KcpSocketTransportForMultiplexConnection(listener, mtu); + } + + /// + /// Create a socket transport for multiplex connection. + /// + /// The type of the user state. + /// The udp listener instance. + /// The maximum packet size that can be transmitted over the socket. + /// + public static IKcpTransport> CreateMultiplexConnection(UdpClient listener, + IPEndPoint endPoint, int mtu) + { + if (listener is null) throw new ArgumentNullException(nameof(listener)); + if (endPoint is null) throw new ArgumentNullException(nameof(endPoint)); + + return new KcpSocketTransportForMultiplexConnection(listener, mtu); + } + + /// + /// Create a socket transport for multiplex connection. + /// + /// The type of the user state. + /// The udp listener instance. + /// The remote endpoint. + /// The maximum packet size that can be transmitted over the socket. + /// The action to invoke when state object is removed. + /// + public static IKcpTransport> CreateMultiplexConnection(UdpClient listener, + EndPoint endPoint, int mtu, Action? disposeAction) + { + if (listener is null) throw new ArgumentNullException(nameof(listener)); + if (endPoint is null) throw new ArgumentNullException(nameof(endPoint)); + + return new KcpSocketTransportForMultiplexConnection(listener, mtu, disposeAction); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSocketTransportForConversation.cs b/GameServer/KcpSharp/KcpSocketTransportForConversation.cs index 0406ed8e..24a9c349 100644 --- a/GameServer/KcpSharp/KcpSocketTransportForConversation.cs +++ b/GameServer/KcpSharp/KcpSocketTransportForConversation.cs @@ -1,46 +1,49 @@ -using KcpSharp; -using System.Net; +using System.Net; using System.Net.Sockets; +using KcpSharp; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// Socket transport for KCP conversation. +/// +internal sealed class KcpSocketTransportForConversation : KcpSocketTransport, + IKcpTransport { - /// - /// Socket transport for KCP conversation. - /// - internal sealed class KcpSocketTransportForConversation : KcpSocketTransport, IKcpTransport + private readonly long? _conversationId; + private readonly KcpConversationOptions? _options; + private readonly IPEndPoint _remoteEndPoint; + + private Func, object?, bool>? _exceptionHandler; + private object? _exceptionHandlerState; + + + internal KcpSocketTransportForConversation(UdpClient listener, IPEndPoint endPoint, long? conversationId, + KcpConversationOptions? options) + : base(listener, options?.Mtu ?? KcpConversationOptions.MtuDefaultValue) { - private readonly long? _conversationId; - private readonly IPEndPoint _remoteEndPoint; - private readonly KcpConversationOptions? _options; - - private Func, object?, bool>? _exceptionHandler; - private object? _exceptionHandlerState; - - - internal KcpSocketTransportForConversation(UdpClient listener, IPEndPoint endPoint, long? conversationId, KcpConversationOptions? options) - : base(listener, options?.Mtu ?? KcpConversationOptions.MtuDefaultValue) - { - _conversationId = conversationId; - _remoteEndPoint = endPoint; - _options = options; - } - - protected override KcpConversation Activate() => _conversationId.HasValue ? new KcpConversation(_remoteEndPoint, this, _conversationId.GetValueOrDefault(), _options) : new KcpConversation(_remoteEndPoint, this, _options); - - protected override bool HandleException(Exception ex) - { - if (_exceptionHandler is not null) - { - return _exceptionHandler.Invoke(ex, this, _exceptionHandlerState); - } - return false; - } - - public void SetExceptionHandler(Func, object?, bool> handler, object? state) - { - _exceptionHandler = handler; - _exceptionHandlerState = state; - } - + _conversationId = conversationId; + _remoteEndPoint = endPoint; + _options = options; } -} + + public void SetExceptionHandler(Func, object?, bool> handler, + object? state) + { + _exceptionHandler = handler; + _exceptionHandlerState = state; + } + + protected override KcpConversation Activate() + { + return _conversationId.HasValue + ? new KcpConversation(_remoteEndPoint, this, _conversationId.GetValueOrDefault(), _options) + : new KcpConversation(_remoteEndPoint, this, _options); + } + + protected override bool HandleException(Exception ex) + { + if (_exceptionHandler is not null) return _exceptionHandler.Invoke(ex, this, _exceptionHandlerState); + return false; + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSocketTransportForMultiplexConnection.cs b/GameServer/KcpSharp/KcpSocketTransportForMultiplexConnection.cs index 5d04ba48..0e8627b6 100644 --- a/GameServer/KcpSharp/KcpSocketTransportForMultiplexConnection.cs +++ b/GameServer/KcpSharp/KcpSocketTransportForMultiplexConnection.cs @@ -1,40 +1,42 @@ using System.Net.Sockets; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class KcpSocketTransportForMultiplexConnection : KcpSocketTransport>, + IKcpTransport> { - internal sealed class KcpSocketTransportForMultiplexConnection : KcpSocketTransport>, IKcpTransport> + private readonly Action? _disposeAction; + private Func>, object?, bool>? _exceptionHandler; + private object? _exceptionHandlerState; + + internal KcpSocketTransportForMultiplexConnection(UdpClient listener, int mtu) + : base(listener, mtu) { - private readonly Action? _disposeAction; - private Func>, object?, bool>? _exceptionHandler; - private object? _exceptionHandlerState; - - internal KcpSocketTransportForMultiplexConnection(UdpClient listener, int mtu) - : base(listener, mtu) - { } - - internal KcpSocketTransportForMultiplexConnection(UdpClient listener, int mtu, Action? disposeAction) - : base(listener, mtu) - { - _disposeAction = disposeAction; - } - - protected override KcpMultiplexConnection Activate() => new(this, _disposeAction); - - IKcpMultiplexConnection IKcpTransport>.Connection => Connection; - - protected override bool HandleException(Exception ex) - { - if (_exceptionHandler is not null) - { - return _exceptionHandler.Invoke(ex, this, _exceptionHandlerState); - } - return false; - } - - public void SetExceptionHandler(Func>, object?, bool> handler, object? state) - { - _exceptionHandler = handler; - _exceptionHandlerState = state; - } } -} + + internal KcpSocketTransportForMultiplexConnection(UdpClient listener, int mtu, Action? disposeAction) + : base(listener, mtu) + { + _disposeAction = disposeAction; + } + + IKcpMultiplexConnection IKcpTransport>.Connection => Connection; + + public void SetExceptionHandler(Func>, object?, bool> handler, + object? state) + { + _exceptionHandler = handler; + _exceptionHandlerState = state; + } + + protected override KcpMultiplexConnection Activate() + { + return new KcpMultiplexConnection(this, _disposeAction); + } + + protected override bool HandleException(Exception ex) + { + if (_exceptionHandler is not null) return _exceptionHandler.Invoke(ex, this, _exceptionHandlerState); + return false; + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSocketTransportForRawChannel.cs b/GameServer/KcpSharp/KcpSocketTransportForRawChannel.cs index d154c049..375ed38a 100644 --- a/GameServer/KcpSharp/KcpSocketTransportForRawChannel.cs +++ b/GameServer/KcpSharp/KcpSocketTransportForRawChannel.cs @@ -1,41 +1,43 @@ using System.Net; using System.Net.Sockets; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal sealed class KcpSocketTransportForRawChannel : KcpSocketTransport, IKcpTransport { - internal sealed class KcpSocketTransportForRawChannel : KcpSocketTransport, IKcpTransport + private readonly long? _conversationId; + private readonly KcpRawChannelOptions? _options; + private readonly IPEndPoint _remoteEndPoint; + + private Func, object?, bool>? _exceptionHandler; + private object? _exceptionHandlerState; + + + internal KcpSocketTransportForRawChannel(UdpClient listener, IPEndPoint endPoint, long? conversationId, + KcpRawChannelOptions? options) + : base(listener, options?.Mtu ?? KcpConversationOptions.MtuDefaultValue) { - private readonly long? _conversationId; - private readonly IPEndPoint _remoteEndPoint; - private readonly KcpRawChannelOptions? _options; - - private Func, object?, bool>? _exceptionHandler; - private object? _exceptionHandlerState; - - - internal KcpSocketTransportForRawChannel(UdpClient listener, IPEndPoint endPoint, long? conversationId, KcpRawChannelOptions? options) - : base(listener, options?.Mtu ?? KcpConversationOptions.MtuDefaultValue) - { - _conversationId = conversationId; - _remoteEndPoint = endPoint; - _options = options; - } - - protected override KcpRawChannel Activate() => _conversationId.HasValue ? new KcpRawChannel(_remoteEndPoint, this, _conversationId.GetValueOrDefault(), _options) : new KcpRawChannel(_remoteEndPoint, this, _options); - - protected override bool HandleException(Exception ex) - { - if (_exceptionHandler is not null) - { - return _exceptionHandler.Invoke(ex, this, _exceptionHandlerState); - } - return false; - } - - public void SetExceptionHandler(Func, object?, bool> handler, object? state) - { - _exceptionHandler = handler; - _exceptionHandlerState = state; - } + _conversationId = conversationId; + _remoteEndPoint = endPoint; + _options = options; } -} + + public void SetExceptionHandler(Func, object?, bool> handler, object? state) + { + _exceptionHandler = handler; + _exceptionHandlerState = state; + } + + protected override KcpRawChannel Activate() + { + return _conversationId.HasValue + ? new KcpRawChannel(_remoteEndPoint, this, _conversationId.GetValueOrDefault(), _options) + : new KcpRawChannel(_remoteEndPoint, this, _options); + } + + protected override bool HandleException(Exception ex) + { + if (_exceptionHandler is not null) return _exceptionHandler.Invoke(ex, this, _exceptionHandlerState); + return false; + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpSocketTransportOfT.cs b/GameServer/KcpSharp/KcpSocketTransportOfT.cs index 09ba6725..420dacef 100644 --- a/GameServer/KcpSharp/KcpSocketTransportOfT.cs +++ b/GameServer/KcpSharp/KcpSocketTransportOfT.cs @@ -1,216 +1,200 @@ -using EggLink.DanhengServer.Server; -using EggLink.DanhengServer.Util; -using System.Buffers; +using System.Buffers; using System.Net; using System.Net.Sockets; +using EggLink.DanhengServer.Server; +using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// A Socket transport for upper-level connections. +/// +/// +public abstract class KcpSocketTransport : IKcpTransport, IDisposable where T : class, IKcpConversation { + private readonly int _mtu; + private readonly UdpClient _udpListener; + private T? _connection; + private CancellationTokenSource? _cts; + private bool _disposed; + /// - /// A Socket transport for upper-level connections. + /// Construct a socket transport with the specified socket and remote endpoint. /// - /// - public abstract class KcpSocketTransport : IKcpTransport, IDisposable where T : class, IKcpConversation + /// The socket instance. + /// The maximum packet size that can be transmitted. + protected KcpSocketTransport(UdpClient listener, int mtu) { - private readonly UdpClient _udpListener; - private readonly int _mtu; - private T? _connection; - private CancellationTokenSource? _cts; - private bool _disposed; + _udpListener = listener ?? throw new ArgumentNullException(nameof(listener)); + _mtu = mtu; + if (mtu < 50) throw new ArgumentOutOfRangeException(nameof(mtu)); + } - /// - /// Construct a socket transport with the specified socket and remote endpoint. - /// - /// The socket instance. - /// The maximum packet size that can be transmitted. - protected KcpSocketTransport(UdpClient listener, int mtu) - { - _udpListener = listener ?? throw new ArgumentNullException(nameof(listener)); - _mtu = mtu; - if (mtu < 50) - { - throw new ArgumentOutOfRangeException(nameof(mtu)); - } - } + /// + /// Get the upper-level connection instace. If Start is not called or the transport is closed, + /// will be thrown. + /// + /// Start is not called or the transport is closed. + public T Connection => _connection ?? throw new InvalidOperationException(); - /// - /// Get the upper-level connection instace. If Start is not called or the transport is closed, will be thrown. - /// - /// Start is not called or the transport is closed. - public T Connection => _connection ?? throw new InvalidOperationException(); + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } - /// - /// Create the upper-level connection instance. - /// - /// The upper-level connection instance. - protected abstract T Activate(); + /// + public ValueTask SendPacketAsync(Memory packet, IPEndPoint endpoint, + CancellationToken cancellationToken = default) + { + if (_disposed) return default; + if (packet.Length > _mtu) return default; - /// - /// Allocate a block of memory used to receive from socket. - /// - /// The minimum size of the buffer. - /// The allocated memory buffer. - protected virtual IMemoryOwner AllocateBuffer(int size) - { + return new ValueTask(_udpListener.SendAsync(packet.ToArray(), endpoint, cancellationToken).AsTask()); + } + + /// + /// Create the upper-level connection instance. + /// + /// The upper-level connection instance. + protected abstract T Activate(); + + /// + /// Allocate a block of memory used to receive from socket. + /// + /// The minimum size of the buffer. + /// The allocated memory buffer. + protected virtual IMemoryOwner AllocateBuffer(int size) + { #if NEED_POH_SHIM return MemoryPool.Shared.Rent(size); #else - return new ArrayMemoryOwner(GC.AllocateUninitializedArray(size, pinned: true)); + return new ArrayMemoryOwner(GC.AllocateUninitializedArray(size, true)); #endif - } + } - /// - /// Handle exception thrown when receiving from remote endpoint. - /// - /// The exception thrown. - /// Whether error should be ignored. - protected virtual bool HandleException(Exception ex) => false; + /// + /// Handle exception thrown when receiving from remote endpoint. + /// + /// The exception thrown. + /// Whether error should be ignored. + protected virtual bool HandleException(Exception ex) + { + return false; + } - /// - /// Create the upper-level connection and start pumping packets from the socket to the upper-level connection. - /// - public void Start() + /// + /// Create the upper-level connection and start pumping packets from the socket to the upper-level connection. + /// + public void Start() + { + if (_disposed) throw new ObjectDisposedException(nameof(KcpSocketTransport)); + if (_connection is not null) throw new InvalidOperationException(); + + _connection = Activate(); + if (_connection is null) throw new InvalidOperationException(); + _cts = new CancellationTokenSource(); + RunReceiveLoop(); + } + + private async void RunReceiveLoop() + { + var cancellationToken = _cts?.Token ?? new CancellationToken(true); + IKcpConversation? connection = _connection; + if (connection is null || cancellationToken.IsCancellationRequested) return; + + using var memoryOwner = AllocateBuffer(_mtu); + try { - if (_disposed) + while (!cancellationToken.IsCancellationRequested) { - throw new ObjectDisposedException(nameof(KcpSocketTransport)); - } - if (_connection is not null) - { - throw new InvalidOperationException(); - } - - _connection = Activate(); - if (_connection is null) - { - throw new InvalidOperationException(); - } - _cts = new CancellationTokenSource(); - RunReceiveLoop(); - } - - /// - public ValueTask SendPacketAsync(Memory packet, IPEndPoint endpoint, CancellationToken cancellationToken = default) - { - if (_disposed) - { - return default; - } - if (packet.Length > _mtu) - { - return default; - } - - return new ValueTask(_udpListener.SendAsync(packet.ToArray(), endpoint, cancellationToken).AsTask()); - } - - private async void RunReceiveLoop() - { - CancellationToken cancellationToken = _cts?.Token ?? new CancellationToken(true); - IKcpConversation? connection = _connection; - if (connection is null || cancellationToken.IsCancellationRequested) - { - return; - } - - using IMemoryOwner memoryOwner = AllocateBuffer(_mtu); - try - { - while (!cancellationToken.IsCancellationRequested) + var bytesReceived = 0; + var error = false; + UdpReceiveResult result = default; + try { - int bytesReceived = 0; - bool error = false; - UdpReceiveResult result = default; - try - { - result = await _udpListener.ReceiveAsync(cancellationToken); - bytesReceived = result.Buffer.Length; - } - catch - { - } - - if (bytesReceived != 0 && bytesReceived <= _mtu) - { - if (bytesReceived == Listener.HANDSHAKE_SIZE) - await Listener.HandleHandshake(result); - else if (!error) - await connection.InputPakcetAsync(result, cancellationToken).ConfigureAwait(false); - } + result = await _udpListener.ReceiveAsync(cancellationToken); + bytesReceived = result.Buffer.Length; } - } - catch (OperationCanceledException) - { - // Do nothing - } - catch (Exception ex) - { - HandleExceptionWrapper(ex); - } - } - - private bool HandleExceptionWrapper(Exception ex) - { - bool result; - try - { - new Logger("KcpServer").Error("KCP Error:", ex); - result = HandleException(ex); - } - catch - { - result = false; - } - - _connection?.SetTransportClosed(); - CancellationTokenSource? cts = Interlocked.Exchange(ref _cts, null); - if (cts is not null) - { - cts.Cancel(); - cts.Dispose(); - } - - return result; - } - - /// - /// Dispose all the managed and the unmanaged resources used by this instance. - /// - /// If managed resources should be disposed. - protected virtual void Dispose(bool disposing) - { - if (!_disposed) - { - if (disposing) + catch { - CancellationTokenSource? cts = Interlocked.Exchange(ref _cts, null); - if (cts is not null) - { - cts.Cancel(); - cts.Dispose(); - } - _connection?.Dispose(); } - _connection = null; - _cts = null; - _disposed = true; + if (bytesReceived != 0 && bytesReceived <= _mtu) + { + if (bytesReceived == Listener.HANDSHAKE_SIZE) + await Listener.HandleHandshake(result); + else if (!error) + await connection.InputPakcetAsync(result, cancellationToken).ConfigureAwait(false); + } } } - - /// - /// Dispose the unmanaged resources used by this instance. - /// - ~KcpSocketTransport() + catch (OperationCanceledException) { - Dispose(disposing: false); + // Do nothing } - - /// - public void Dispose() + catch (Exception ex) { - Dispose(disposing: true); - GC.SuppressFinalize(this); + HandleExceptionWrapper(ex); } } -} + + private bool HandleExceptionWrapper(Exception ex) + { + bool result; + try + { + new Logger("KcpServer").Error("KCP Error:", ex); + result = HandleException(ex); + } + catch + { + result = false; + } + + _connection?.SetTransportClosed(); + var cts = Interlocked.Exchange(ref _cts, null); + if (cts is not null) + { + cts.Cancel(); + cts.Dispose(); + } + + return result; + } + + /// + /// Dispose all the managed and the unmanaged resources used by this instance. + /// + /// If managed resources should be disposed. + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + var cts = Interlocked.Exchange(ref _cts, null); + if (cts is not null) + { + cts.Cancel(); + cts.Dispose(); + } + + _connection?.Dispose(); + } + + _connection = null; + _cts = null; + _disposed = true; + } + } + + /// + /// Dispose the unmanaged resources used by this instance. + /// + ~KcpSocketTransport() + { + Dispose(false); + } +} \ No newline at end of file diff --git a/GameServer/KcpSharp/KcpStream.cs b/GameServer/KcpSharp/KcpStream.cs index 0bc6b8c6..6b1d49be 100644 --- a/GameServer/KcpSharp/KcpStream.cs +++ b/GameServer/KcpSharp/KcpStream.cs @@ -1,168 +1,178 @@ using KcpSharp; -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +/// +/// A stream wrapper of . +/// +public sealed class KcpStream : Stream { + private readonly bool _ownsConversation; + private KcpConversation? _conversation; + /// - /// A stream wrapper of . + /// Create a stream wrapper over an existing instance. /// - public sealed class KcpStream : Stream + /// The conversation instance. It must be in stream mode. + /// + /// Whether to dispose the instance when + /// is disposed. + /// + public KcpStream(KcpConversation conversation, bool ownsConversation) { - private KcpConversation? _conversation; - private readonly bool _ownsConversation; + if (conversation is null) throw new ArgumentNullException(nameof(conversation)); + if (!conversation.StreamMode) + throw new ArgumentException("Non-stream mode conversation is not supported.", nameof(conversation)); + _conversation = conversation; + _ownsConversation = ownsConversation; + } - /// - /// Create a stream wrapper over an existing instance. - /// - /// The conversation instance. It must be in stream mode. - /// Whether to dispose the instance when is disposed. - public KcpStream(KcpConversation conversation, bool ownsConversation) + /// + public override bool CanRead => true; + + /// + public override bool CanSeek => false; + + /// + public override bool CanWrite => true; + + /// + /// The length of the stream. This always throws . + /// + public override long Length => throw new NotSupportedException(); + + /// + /// The position of the stream. This always throws . + /// + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + /// + /// Indicates data is available on the stream to be read. This property checks to see if at least one byte of data is + /// currently available + /// + public bool DataAvailable + { + get { - if (conversation is null) - { - throw new ArgumentNullException(nameof(conversation)); - } - if (!conversation.StreamMode) - { - throw new ArgumentException("Non-stream mode conversation is not supported.", nameof(conversation)); - } - _conversation = conversation; - _ownsConversation = ownsConversation; + if (_conversation is null) ThrowHelper.ThrowObjectDisposedForKcpStreamException(); + return _conversation!.TryPeek(out var result) && result.BytesReceived != 0; } + } - /// - public override bool CanRead => true; + /// + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } - /// - public override bool CanSeek => false; + /// + public override void SetLength(long value) + { + throw new NotSupportedException(); + } - /// - public override bool CanWrite => true; + /// + public override void Flush() + { + throw new NotSupportedException(); + } - /// - /// The length of the stream. This always throws . - /// - public override long Length => throw new NotSupportedException(); + /// + public override Task FlushAsync(CancellationToken cancellationToken) + { + if (_conversation is null) return Task.FromException(ThrowHelper.NewObjectDisposedForKcpStreamException()); + return _conversation!.FlushAsync(cancellationToken).AsTask(); + } - /// - /// The position of the stream. This always throws . - /// - public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + /// + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } - /// - public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + /// + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } - /// - public override void SetLength(long value) => throw new NotSupportedException(); + /// + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + if (_conversation is null) return Task.FromException(new ObjectDisposedException(nameof(KcpStream))); + return _conversation.ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + } - /// - /// Indicates data is available on the stream to be read. This property checks to see if at least one byte of data is currently available - /// - public bool DataAvailable - { - get - { - if (_conversation is null) - { - ThrowHelper.ThrowObjectDisposedForKcpStreamException(); - } - return _conversation!.TryPeek(out KcpConversationReceiveResult result) && result.BytesReceived != 0; - } - } + /// + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + if (_conversation is null) return Task.FromException(new ObjectDisposedException(nameof(KcpStream))); + return _conversation.WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + } - /// - public override void Flush() => throw new NotSupportedException(); + /// + public override int ReadByte() + { + throw new NotSupportedException(); + } - /// - public override Task FlushAsync(CancellationToken cancellationToken) - { - if (_conversation is null) - { - return Task.FromException(ThrowHelper.NewObjectDisposedForKcpStreamException()); - } - return _conversation!.FlushAsync(cancellationToken).AsTask(); - } + /// + public override void WriteByte(byte value) + { + throw new NotSupportedException(); + } - /// - public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); - - /// - public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); - - /// - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - if (_conversation is null) - { - return Task.FromException(new ObjectDisposedException(nameof(KcpStream))); - } - return _conversation.ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); - } - - /// - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - if (_conversation is null) - { - return Task.FromException(new ObjectDisposedException(nameof(KcpStream))); - } - return _conversation.WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); - } - - /// - public override int ReadByte() => throw new NotSupportedException(); - - /// - public override void WriteByte(byte value) => throw new NotSupportedException(); - - /// - protected override void Dispose(bool disposing) - { - if (disposing && _ownsConversation) - { - _conversation?.Dispose(); - } - _conversation = null; - base.Dispose(disposing); - } + /// + protected override void Dispose(bool disposing) + { + if (disposing && _ownsConversation) _conversation?.Dispose(); + _conversation = null; + base.Dispose(disposing); + } #if !NO_FAST_SPAN - /// - public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) - { - if (_conversation is null) - { - return new ValueTask(Task.FromException(new ObjectDisposedException(nameof(KcpStream)))); - } - return _conversation.ReadAsync(buffer, cancellationToken); - } - - /// - public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) - { - if (_conversation is null) - { - return new ValueTask(Task.FromException(new ObjectDisposedException(nameof(KcpStream)))); - } - return _conversation.WriteAsync(buffer, cancellationToken); - } - - /// - public override ValueTask DisposeAsync() - { - if (_conversation is not null) - { - _conversation.Dispose(); - _conversation = null; - } - return base.DisposeAsync(); - } - - /// - public override int Read(Span buffer) => throw new NotSupportedException(); - - /// - public override void Write(ReadOnlySpan buffer) => throw new NotSupportedException(); -#endif - + /// + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_conversation is null) + return new ValueTask(Task.FromException(new ObjectDisposedException(nameof(KcpStream)))); + return _conversation.ReadAsync(buffer, cancellationToken); } -} + + /// + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + if (_conversation is null) + return new ValueTask(Task.FromException(new ObjectDisposedException(nameof(KcpStream)))); + return _conversation.WriteAsync(buffer, cancellationToken); + } + + /// + public override ValueTask DisposeAsync() + { + if (_conversation is not null) + { + _conversation.Dispose(); + _conversation = null; + } + + return base.DisposeAsync(); + } + + /// + public override int Read(Span buffer) + { + throw new NotSupportedException(); + } + + /// + public override void Write(ReadOnlySpan buffer) + { + throw new NotSupportedException(); + } +#endif +} \ No newline at end of file diff --git a/GameServer/KcpSharp/NetstandardShim/AwaitableSocketAsyncEventArgs.cs b/GameServer/KcpSharp/NetstandardShim/AwaitableSocketAsyncEventArgs.cs index a3392849..5a6d8ce5 100644 --- a/GameServer/KcpSharp/NetstandardShim/AwaitableSocketAsyncEventArgs.cs +++ b/GameServer/KcpSharp/NetstandardShim/AwaitableSocketAsyncEventArgs.cs @@ -1,5 +1,4 @@ #if NEED_SOCKET_SHIM - using System; using System.Net.Sockets; using System.Threading.Tasks; @@ -9,7 +8,8 @@ namespace KcpSharp { internal class AwaitableSocketAsyncEventArgs : SocketAsyncEventArgs, IValueTaskSource { - private ManualResetValueTaskSourceCore _mrvtsc = new ManualResetValueTaskSourceCore { RunContinuationsAsynchronously = true }; + private ManualResetValueTaskSourceCore _mrvtsc = + new ManualResetValueTaskSourceCore { RunContinuationsAsynchronously = true }; void IValueTaskSource.GetResult(short token) => _mrvtsc.GetResult(token); ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _mrvtsc.GetStatus(token); @@ -33,4 +33,4 @@ namespace KcpSharp } } -#endif +#endif \ No newline at end of file diff --git a/GameServer/KcpSharp/NetstandardShim/CancellationTokenShim.cs b/GameServer/KcpSharp/NetstandardShim/CancellationTokenShim.cs index 31ea5037..a6d202cf 100644 --- a/GameServer/KcpSharp/NetstandardShim/CancellationTokenShim.cs +++ b/GameServer/KcpSharp/NetstandardShim/CancellationTokenShim.cs @@ -1,5 +1,4 @@ #if NEED_CANCELLATIONTOKEN_SHIM - namespace System.Threading { internal static class CancellationTokenShim @@ -10,4 +9,4 @@ namespace System.Threading } -#endif +#endif \ No newline at end of file diff --git a/GameServer/KcpSharp/NetstandardShim/LinkedListNetstandard.cs b/GameServer/KcpSharp/NetstandardShim/LinkedListNetstandard.cs index 63b4658d..a291d5b4 100644 --- a/GameServer/KcpSharp/NetstandardShim/LinkedListNetstandard.cs +++ b/GameServer/KcpSharp/NetstandardShim/LinkedListNetstandard.cs @@ -1,5 +1,4 @@ #if NEED_LINKEDLIST_SHIM - using System; using System.Diagnostics; @@ -210,4 +209,4 @@ namespace KcpSharp.NetstandardShim } } -#endif +#endif \ No newline at end of file diff --git a/GameServer/KcpSharp/NetstandardShim/TaskCompletionSource.cs b/GameServer/KcpSharp/NetstandardShim/TaskCompletionSource.cs index 2a692efd..f80a2485 100644 --- a/GameServer/KcpSharp/NetstandardShim/TaskCompletionSource.cs +++ b/GameServer/KcpSharp/NetstandardShim/TaskCompletionSource.cs @@ -1,5 +1,4 @@ #if NEED_TCS_SHIM - namespace System.Threading.Tasks { internal class TaskCompletionSource : TaskCompletionSource @@ -8,4 +7,4 @@ namespace System.Threading.Tasks } } -#endif +#endif \ No newline at end of file diff --git a/GameServer/KcpSharp/ThrowHelper.cs b/GameServer/KcpSharp/ThrowHelper.cs index da673154..59362cc6 100644 --- a/GameServer/KcpSharp/ThrowHelper.cs +++ b/GameServer/KcpSharp/ThrowHelper.cs @@ -1,66 +1,84 @@ -namespace EggLink.DanhengServer.KcpSharp +namespace EggLink.DanhengServer.KcpSharp; + +internal static class ThrowHelper { - internal static class ThrowHelper + public static void ThrowArgumentOutOfRangeException(string paramName) { - public static void ThrowArgumentOutOfRangeException(string paramName) - { - throw new ArgumentOutOfRangeException(paramName); - } - public static void ThrowTransportClosedForStreanException() - { - throw new IOException("The underlying transport is closed."); - } - public static Exception NewMessageTooLargeForBufferArgument() - { - return new ArgumentException("Message is too large.", "buffer"); - } - public static Exception NewBufferTooSmallForBufferArgument() - { - return new ArgumentException("Buffer is too small.", "buffer"); - } - public static Exception ThrowBufferTooSmall() - { - throw new ArgumentException("Buffer is too small.", "buffer"); - } - public static Exception ThrowAllowPartialSendArgumentException() - { - throw new ArgumentException("allowPartialSend should not be set to true in non-stream mode.", "allowPartialSend"); - } - public static Exception NewArgumentOutOfRangeException(string paramName) - { - return new ArgumentOutOfRangeException(paramName); - } - public static Exception NewConcurrentSendException() - { - return new InvalidOperationException("Concurrent send operations are not allowed."); - } - public static Exception NewConcurrentReceiveException() - { - return new InvalidOperationException("Concurrent receive operations are not allowed."); - } - public static Exception NewTransportClosedForStreamException() - { - throw new IOException("The underlying transport is closed."); - } - public static Exception NewOperationCanceledExceptionForCancelPendingSend(Exception? innerException, CancellationToken cancellationToken) - { - return new OperationCanceledException("This operation is cancelled by a call to CancelPendingSend.", innerException, cancellationToken); - } - public static Exception NewOperationCanceledExceptionForCancelPendingReceive(Exception? innerException, CancellationToken cancellationToken) - { - return new OperationCanceledException("This operation is cancelled by a call to CancelPendingReceive.", innerException, cancellationToken); - } - public static void ThrowConcurrentReceiveException() - { - throw new InvalidOperationException("Concurrent receive operations are not allowed."); - } - public static Exception NewObjectDisposedForKcpStreamException() - { - return new ObjectDisposedException(nameof(KcpStream)); - } - public static void ThrowObjectDisposedForKcpStreamException() - { - throw new ObjectDisposedException(nameof(KcpStream)); - } + throw new ArgumentOutOfRangeException(paramName); } -} + + public static void ThrowTransportClosedForStreanException() + { + throw new IOException("The underlying transport is closed."); + } + + public static Exception NewMessageTooLargeForBufferArgument() + { + return new ArgumentException("Message is too large.", "buffer"); + } + + public static Exception NewBufferTooSmallForBufferArgument() + { + return new ArgumentException("Buffer is too small.", "buffer"); + } + + public static Exception ThrowBufferTooSmall() + { + throw new ArgumentException("Buffer is too small.", "buffer"); + } + + public static Exception ThrowAllowPartialSendArgumentException() + { + throw new ArgumentException("allowPartialSend should not be set to true in non-stream mode.", + "allowPartialSend"); + } + + public static Exception NewArgumentOutOfRangeException(string paramName) + { + return new ArgumentOutOfRangeException(paramName); + } + + public static Exception NewConcurrentSendException() + { + return new InvalidOperationException("Concurrent send operations are not allowed."); + } + + public static Exception NewConcurrentReceiveException() + { + return new InvalidOperationException("Concurrent receive operations are not allowed."); + } + + public static Exception NewTransportClosedForStreamException() + { + throw new IOException("The underlying transport is closed."); + } + + public static Exception NewOperationCanceledExceptionForCancelPendingSend(Exception? innerException, + CancellationToken cancellationToken) + { + return new OperationCanceledException("This operation is cancelled by a call to CancelPendingSend.", + innerException, cancellationToken); + } + + public static Exception NewOperationCanceledExceptionForCancelPendingReceive(Exception? innerException, + CancellationToken cancellationToken) + { + return new OperationCanceledException("This operation is cancelled by a call to CancelPendingReceive.", + innerException, cancellationToken); + } + + public static void ThrowConcurrentReceiveException() + { + throw new InvalidOperationException("Concurrent receive operations are not allowed."); + } + + public static Exception NewObjectDisposedForKcpStreamException() + { + return new ObjectDisposedException(nameof(KcpStream)); + } + + public static void ThrowObjectDisposedForKcpStreamException() + { + throw new ObjectDisposedException(nameof(KcpStream)); + } +} \ No newline at end of file diff --git a/GameServer/Plugin/Constructor/IPlugin.cs b/GameServer/Plugin/Constructor/IPlugin.cs index 76c927ef..16750941 100644 --- a/GameServer/Plugin/Constructor/IPlugin.cs +++ b/GameServer/Plugin/Constructor/IPlugin.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Plugin.Constructor; -namespace EggLink.DanhengServer.Plugin.Constructor +public interface IPlugin { - public interface IPlugin - { - public void OnLoad(); - public void OnUnload(); - } -} + public void OnLoad(); + public void OnUnload(); +} \ No newline at end of file diff --git a/GameServer/Plugin/Constructor/PluginInfo.cs b/GameServer/Plugin/Constructor/PluginInfo.cs index 19a7c632..55aa929e 100644 --- a/GameServer/Plugin/Constructor/PluginInfo.cs +++ b/GameServer/Plugin/Constructor/PluginInfo.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Plugin.Constructor; -namespace EggLink.DanhengServer.Plugin.Constructor +[AttributeUsage(AttributeTargets.Class)] +public class PluginInfo(string name, string description, string version) : Attribute { - [AttributeUsage(AttributeTargets.Class)] - public class PluginInfo(string name, string description, string version) : Attribute - { - public string Name { get; } = name; - public string Description { get; } = description; - public string Version { get; } = version; - } -} + public string Name { get; } = name; + public string Description { get; } = description; + public string Version { get; } = version; +} \ No newline at end of file diff --git a/GameServer/Plugin/Event/PluginEvent.cs b/GameServer/Plugin/Event/PluginEvent.cs index fc100c61..df664458 100644 --- a/GameServer/Plugin/Event/PluginEvent.cs +++ b/GameServer/Plugin/Event/PluginEvent.cs @@ -1,70 +1,68 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Game.Scene.Entity; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Plugin.Event +namespace EggLink.DanhengServer.Plugin.Event; + +public static class PluginEvent { - public static class PluginEvent + public static void InvokeOnPlayerHeartBeat(PlayerInstance player) { - #region Player - - public delegate void OnPlayerHeartBeatHandler(PlayerInstance player); - public delegate void OnPlayerLoginHandler(PlayerInstance player); - public delegate void OnPlayerLogoutHandler(PlayerInstance player); - public delegate void OnPlayerFinishSubMissionHandler(PlayerInstance player, int missionId); - public delegate void OnPlayerFinishMainMissionHandler(PlayerInstance player, int missionId); - public delegate void OnPlayerInteractHandler(PlayerInstance player, EntityProp prop); - - #endregion - - #region Common - - - #endregion - - #region Event - - public static event OnPlayerHeartBeatHandler? OnPlayerHeartBeat; - public static event OnPlayerLoginHandler? OnPlayerLogin; - public static event OnPlayerLogoutHandler? OnPlayerLogout; - public static event OnPlayerFinishSubMissionHandler? OnPlayerFinishSubMission; - public static event OnPlayerFinishMainMissionHandler? OnPlayerFinishMainMission; - public static event OnPlayerInteractHandler? OnPlayerInteract; - - #endregion - - public static void InvokeOnPlayerHeartBeat(PlayerInstance player) - { - OnPlayerHeartBeat?.Invoke(player); - } - - public static void InvokeOnPlayerLogin(PlayerInstance player) - { - OnPlayerLogin?.Invoke(player); - } - - public static void InvokeOnPlayerLogout(PlayerInstance player) - { - OnPlayerLogout?.Invoke(player); - } - - public static void InvokeOnPlayerFinishSubMission(PlayerInstance player, int missionId) - { - OnPlayerFinishSubMission?.Invoke(player, missionId); - } - - public static void InvokeOnPlayerFinishMainMission(PlayerInstance player, int missionId) - { - OnPlayerFinishMainMission?.Invoke(player, missionId); - } - - public static void InvokeOnPlayerInteract(PlayerInstance player, EntityProp prop) - { - OnPlayerInteract?.Invoke(player, prop); - } + OnPlayerHeartBeat?.Invoke(player); } -} + + public static void InvokeOnPlayerLogin(PlayerInstance player) + { + OnPlayerLogin?.Invoke(player); + } + + public static void InvokeOnPlayerLogout(PlayerInstance player) + { + OnPlayerLogout?.Invoke(player); + } + + public static void InvokeOnPlayerFinishSubMission(PlayerInstance player, int missionId) + { + OnPlayerFinishSubMission?.Invoke(player, missionId); + } + + public static void InvokeOnPlayerFinishMainMission(PlayerInstance player, int missionId) + { + OnPlayerFinishMainMission?.Invoke(player, missionId); + } + + public static void InvokeOnPlayerInteract(PlayerInstance player, EntityProp prop) + { + OnPlayerInteract?.Invoke(player, prop); + } + + #region Player + + public delegate void OnPlayerHeartBeatHandler(PlayerInstance player); + + public delegate void OnPlayerLoginHandler(PlayerInstance player); + + public delegate void OnPlayerLogoutHandler(PlayerInstance player); + + public delegate void OnPlayerFinishSubMissionHandler(PlayerInstance player, int missionId); + + public delegate void OnPlayerFinishMainMissionHandler(PlayerInstance player, int missionId); + + public delegate void OnPlayerInteractHandler(PlayerInstance player, EntityProp prop); + + #endregion + + #region Common + + #endregion + + #region Event + + public static event OnPlayerHeartBeatHandler? OnPlayerHeartBeat; + public static event OnPlayerLoginHandler? OnPlayerLogin; + public static event OnPlayerLogoutHandler? OnPlayerLogout; + public static event OnPlayerFinishSubMissionHandler? OnPlayerFinishSubMission; + public static event OnPlayerFinishMainMissionHandler? OnPlayerFinishMainMission; + public static event OnPlayerInteractHandler? OnPlayerInteract; + + #endregion +} \ No newline at end of file diff --git a/GameServer/Plugin/PluginManager.cs b/GameServer/Plugin/PluginManager.cs index f685d826..a5700aad 100644 --- a/GameServer/Plugin/PluginManager.cs +++ b/GameServer/Plugin/PluginManager.cs @@ -1,160 +1,137 @@ -using EggLink.DanhengServer.Internationalization; +using System.Reflection; +using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Plugin.Constructor; using EggLink.DanhengServer.Util; using McMaster.NETCore.Plugins; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Plugin +namespace EggLink.DanhengServer.Plugin; + +public class PluginManager { - public class PluginManager + private static readonly Logger logger = new("PluginManager"); + public static readonly Dictionary Plugins = []; + + public static readonly Dictionary> PluginAssemblies = []; + + public static List GetPluginAssemblies() { - private readonly static Logger logger = new("PluginManager"); - public readonly static Dictionary Plugins = []; + var assemblies = new List(); + foreach (var plugin in Plugins.Keys) + if (PluginAssemblies.TryGetValue(plugin, out var value)) + assemblies.AddRange(value); - public readonly static Dictionary> PluginAssemblies = []; + return assemblies; + } - #region Plugin Manager + #region Plugin Manager - public static void LoadPlugins() + public static void LoadPlugins() + { + // get all the plugins in the plugin directory + if (!Directory.Exists(ConfigManager.Config.Path.PluginPath)) + Directory.CreateDirectory(ConfigManager.Config.Path.PluginPath); + + if (!Directory.Exists(ConfigManager.Config.Path.PluginConfigPath)) + Directory.CreateDirectory(ConfigManager.Config.Path.PluginConfigPath); + + var plugins = Directory.GetFiles(ConfigManager.Config.Path.PluginPath, "*.dll"); + var loaders = new List(); + AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { - // get all the plugins in the plugin directory - if (!Directory.Exists(ConfigManager.Config.Path.PluginPath)) - { - Directory.CreateDirectory(ConfigManager.Config.Path.PluginPath); - } + var assemblyName = new AssemblyName(args.Name).Name + ".dll"; + var assemblyPath = Path.Combine(ConfigManager.Config.Path.PluginPath, assemblyName); - if (!Directory.Exists(ConfigManager.Config.Path.PluginConfigPath)) - { - Directory.CreateDirectory(ConfigManager.Config.Path.PluginConfigPath); - } + if (File.Exists(assemblyPath)) return Assembly.LoadFrom(assemblyPath); - var plugins = Directory.GetFiles(ConfigManager.Config.Path.PluginPath, "*.dll"); - var loaders = new List(); - AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => - { - var assemblyName = new AssemblyName(args.Name).Name + ".dll"; - var assemblyPath = Path.Combine(ConfigManager.Config.Path.PluginPath, assemblyName); - - if (File.Exists(assemblyPath)) - { - return Assembly.LoadFrom(assemblyPath); - } - - return null; - }; - foreach (var plugin in plugins) - { - var fileInfo = new FileInfo(plugin); - LoadPlugin(fileInfo.FullName); - } + return null; + }; + foreach (var plugin in plugins) + { + var fileInfo = new FileInfo(plugin); + LoadPlugin(fileInfo.FullName); } + } - public static void LoadPlugin(string plugin) + public static void LoadPlugin(string plugin) + { + try { - try + var config = new PluginConfig(plugin) { - var config = new PluginConfig(plugin) + PreferSharedTypes = true, + LoadInMemory = true + }; + + var loader = new PluginLoader(config); + + var assembly = loader.LoadDefaultAssembly(); + var types = assembly.GetTypes(); + + foreach (var type in types) + if (typeof(IPlugin).IsAssignableFrom(type)) { - PreferSharedTypes = true, - LoadInMemory = true, - }; - - var loader = new PluginLoader(config); - - var assembly = loader.LoadDefaultAssembly(); - var types = assembly.GetTypes(); - - foreach (var type in types) - { - if (typeof(IPlugin).IsAssignableFrom(type)) + if (Activator.CreateInstance(type) is IPlugin pluginInstance) { - if (Activator.CreateInstance(type) is IPlugin pluginInstance) + var pluginInfo = type.GetCustomAttribute(); + if (pluginInfo != null) { - var pluginInfo = type.GetCustomAttribute(); - if (pluginInfo != null) - { - logger.Info($"Loaded plugin {pluginInfo.Name} v{pluginInfo.Version}: {pluginInfo.Description}"); - } - else - { - logger.Info($"Loaded plugin {plugin}: No plugin info"); - continue; - } - - if (Plugins.Values.Any(p => p.Name == pluginInfo.Name)) - { - logger.Error($"Failed to load plugin {plugin}: Plugin already loaded"); - continue; - } - - Plugins.Add(pluginInstance, pluginInfo); - - if (!PluginAssemblies.TryGetValue(pluginInstance, out var pluginTypes)) - { - pluginTypes = []; - PluginAssemblies[pluginInstance] = pluginTypes; - } - - pluginTypes.AddRange(types); - - pluginInstance.OnLoad(); + logger.Info( + $"Loaded plugin {pluginInfo.Name} v{pluginInfo.Version}: {pluginInfo.Description}"); } else { - logger.Error($"Failed to load plugin {plugin}: Plugin instance is null"); + logger.Info($"Loaded plugin {plugin}: No plugin info"); + continue; } + + if (Plugins.Values.Any(p => p.Name == pluginInfo.Name)) + { + logger.Error($"Failed to load plugin {plugin}: Plugin already loaded"); + continue; + } + + Plugins.Add(pluginInstance, pluginInfo); + + if (!PluginAssemblies.TryGetValue(pluginInstance, out var pluginTypes)) + { + pluginTypes = []; + PluginAssemblies[pluginInstance] = pluginTypes; + } + + pluginTypes.AddRange(types); + + pluginInstance.OnLoad(); + } + else + { + logger.Error($"Failed to load plugin {plugin}: Plugin instance is null"); } } - } - catch (Exception ex) - { - logger.Error($"Failed to load plugin {plugin}: {ex.Message}"); - } } - - public static void UnloadPlugin(IPlugin plugin) + catch (Exception ex) { - if (Plugins.TryGetValue(plugin, out PluginInfo? value)) - { - plugin.OnUnload(); - Plugins.Remove(plugin); - PluginAssemblies.Remove(plugin); - logger.Info($"Unloaded plugin {value.Name}"); - } - } - - - public static void UnloadPlugins() - { - foreach (var plugin in Plugins.Keys) - { - UnloadPlugin(plugin); - } - - logger.Info(I18nManager.Translate("Server.ServerInfo.UnloadedItems", I18nManager.Translate("Word.Plugin"))); - } - - #endregion - - public static List GetPluginAssemblies() - { - var assemblies = new List(); - foreach (var plugin in Plugins.Keys) - { - if (PluginAssemblies.TryGetValue(plugin, out List? value)) - { - assemblies.AddRange(value); - } - } - - return assemblies; + logger.Error($"Failed to load plugin {plugin}: {ex.Message}"); } } -} + + public static void UnloadPlugin(IPlugin plugin) + { + if (Plugins.TryGetValue(plugin, out var value)) + { + plugin.OnUnload(); + Plugins.Remove(plugin); + PluginAssemblies.Remove(plugin); + logger.Info($"Unloaded plugin {value.Name}"); + } + } + + + public static void UnloadPlugins() + { + foreach (var plugin in Plugins.Keys) UnloadPlugin(plugin); + + logger.Info(I18nManager.Translate("Server.ServerInfo.UnloadedItems", I18nManager.Translate("Word.Plugin"))); + } + + #endregion +} \ No newline at end of file diff --git a/GameServer/Server/Connection.cs b/GameServer/Server/Connection.cs index bc8a32d7..685eedb3 100644 --- a/GameServer/Server/Connection.cs +++ b/GameServer/Server/Connection.cs @@ -1,35 +1,35 @@ using System.Buffers; using System.Net; -using System.Net.Sockets; using System.Reflection; using EggLink.DanhengServer.Common.Enums; using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.KcpSharp; using EggLink.DanhengServer.Server.Packet; using EggLink.DanhengServer.Util; using Google.Protobuf; using Google.Protobuf.Reflection; using KcpSharp; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace EggLink.DanhengServer.Server; -public partial class Connection + +public class Connection { - public long? ConversationID => Conversation.ConversationId; - private readonly KcpConversation Conversation; - private readonly CancellationTokenSource CancelToken; - public readonly IPEndPoint RemoteEndPoint; - public SessionStateEnum State { get; set; } = SessionStateEnum.INACTIVE; - public PlayerInstance? Player { get; set; } public static readonly List BANNED_PACKETS = []; - public bool IsOnline = true; private static readonly Logger Logger = new("GameServer"); public static readonly Dictionary LogMap = []; - public static readonly List IgnoreLog = [CmdIds.PlayerHeartBeatCsReq, CmdIds.PlayerHeartBeatScRsp, CmdIds.SceneEntityMoveCsReq, CmdIds.SceneEntityMoveScRsp, CmdIds.GetShopListCsReq, CmdIds.GetShopListScRsp]; + + public static readonly List IgnoreLog = + [ + CmdIds.PlayerHeartBeatCsReq, CmdIds.PlayerHeartBeatScRsp, CmdIds.SceneEntityMoveCsReq, + CmdIds.SceneEntityMoveScRsp, CmdIds.GetShopListCsReq, CmdIds.GetShopListScRsp + ]; + + private readonly CancellationTokenSource CancelToken; + private readonly KcpConversation Conversation; + public readonly IPEndPoint RemoteEndPoint; public string DebugFile = ""; - public StreamWriter? writer = null; + public bool IsOnline = true; + public StreamWriter? writer; public Connection(KcpConversation conversation, IPEndPoint remote) { @@ -39,12 +39,17 @@ public partial class Connection Start(); } + public long? ConversationID => Conversation.ConversationId; + public SessionStateEnum State { get; set; } = SessionStateEnum.INACTIVE; + public PlayerInstance? Player { get; set; } + private async void Start() { Logger.Info($"New connection from {RemoteEndPoint}."); State = SessionStateEnum.WAITING_FOR_TOKEN; await ReceiveLoop(); } + public void Stop() { Player?.OnLogoutAsync(); @@ -55,7 +60,10 @@ public partial class Connection CancelToken.Cancel(); CancelToken.Dispose(); } - catch { } + catch + { + } + IsOnline = false; } @@ -64,25 +72,25 @@ public partial class Connection try { //Logger.DebugWriteLine($"{sendOrRecv}: {Enum.GetName(typeof(OpCode), opcode)}({opcode})\r\n{Convert.ToHexString(payload)}"); - if (IgnoreLog.Contains(opcode)) - { - return; - } + if (IgnoreLog.Contains(opcode)) return; #pragma warning disable CS8600 - Type? typ = AppDomain.CurrentDomain.GetAssemblies(). - SingleOrDefault(assembly => assembly.GetName().Name == "DanhengCommon")!.GetTypes().First(t => t.Name == $"{LogMap[opcode.ToString()]}"); //get the type using the packet name - MessageDescriptor? descriptor = (MessageDescriptor)typ.GetProperty("Descriptor", BindingFlags.Public | BindingFlags.Static)!.GetValue(null, null); // get the static property Descriptor - IMessage? packet = descriptor!.Parser.ParseFrom(payload); + var typ = AppDomain.CurrentDomain.GetAssemblies() + .SingleOrDefault(assembly => assembly.GetName().Name == "DanhengCommon")!.GetTypes() + .First(t => t.Name == $"{LogMap[opcode.ToString()]}"); //get the type using the packet name + var descriptor = + (MessageDescriptor)typ.GetProperty("Descriptor", BindingFlags.Public | BindingFlags.Static)!.GetValue( + null, null); // get the static property Descriptor + var packet = descriptor!.Parser.ParseFrom(payload); #pragma warning restore CS8600 - JsonFormatter? formatter = JsonFormatter.Default; - string? asJson = formatter.Format(packet); + var formatter = JsonFormatter.Default; + var asJson = formatter.Format(packet); var output = $"{sendOrRecv}: {LogMap[opcode.ToString()]}({opcode})\r\n{asJson}"; #if DEBUG Logger.Debug(output); #endif if (DebugFile != "" && ConfigManager.Config.ServerOption.SavePersonalDebugFile) { - StreamWriter? sw = GetWriter(); + var sw = GetWriter(); sw.WriteLine($"[{DateTime.Now:HH:mm:ss}] [GameServer] [DEBUG] " + output); sw.Flush(); } @@ -95,7 +103,7 @@ public partial class Connection #endif if (DebugFile != "" && ConfigManager.Config.ServerOption.SavePersonalDebugFile) { - StreamWriter? sw = GetWriter(); + var sw = GetWriter(); sw.WriteLine($"[{DateTime.Now:HH:mm:ss}] [GameServer] [DEBUG] " + output); sw.Flush(); } @@ -121,12 +129,13 @@ public partial class Connection while (!CancelToken.IsCancellationRequested) { // WaitToReceiveAsync call completes when there is at least one message is received or the transport is closed. - KcpConversationReceiveResult result = await Conversation.WaitToReceiveAsync(CancelToken.Token); + var result = await Conversation.WaitToReceiveAsync(CancelToken.Token); if (result.TransportClosed) { Logger.Debug("Connection was closed"); break; } + if (result.BytesReceived > Listener.MAX_MSG_SIZE) { // The message is too large. @@ -135,7 +144,7 @@ public partial class Connection break; } - byte[] buffer = ArrayPool.Shared.Rent(result.BytesReceived); + var buffer = ArrayPool.Shared.Rent(result.BytesReceived); try { // TryReceive should not return false here, unless the transport is closed. @@ -145,6 +154,7 @@ public partial class Connection Logger.Error("Failed to receive packet"); break; } + await ProcessMessageAsync(buffer.AsMemory(0, result.BytesReceived)); } catch (Exception ex) @@ -156,13 +166,14 @@ public partial class Connection ArrayPool.Shared.Return(buffer); } } + Stop(); } // DO THE PROCESSING OF THE GAME PACKET private async Task ProcessMessageAsync(Memory data) { - byte[] gamePacket = data.ToArray(); + var gamePacket = data.ToArray(); await using MemoryStream? ms = new(gamePacket); using BinaryReader? br = new(ms); @@ -173,27 +184,24 @@ public partial class Connection while (br.BaseStream.Position < br.BaseStream.Length) { // Length - if (br.BaseStream.Length - br.BaseStream.Position < 12) - { - return; - } + if (br.BaseStream.Length - br.BaseStream.Position < 12) return; // Packet sanity check - uint Magic1 = br.ReadUInt32BE(); + var Magic1 = br.ReadUInt32BE(); if (Magic1 != 0x9D74C714) { Logger.Error($"Bad Data Package Received: got 0x{Magic1:X}, expect 0x9D74C714"); return; // Bad packet } - // Data - ushort opcode = br.ReadUInt16BE(); - ushort headerLength = br.ReadUInt16BE(); - uint payloadLength = br.ReadUInt32BE(); - byte[] header = br.ReadBytes(headerLength); - byte[] payload = br.ReadBytes((int)payloadLength); - LogPacket("Recv", opcode, payload); - HandlePacket(opcode, header, payload); - } + // Data + var opcode = br.ReadUInt16BE(); + var headerLength = br.ReadUInt16BE(); + var payloadLength = br.ReadUInt32BE(); + var header = br.ReadBytes(headerLength); + var payload = br.ReadBytes((int)payloadLength); + LogPacket("Recv", opcode, payload); + await HandlePacket(opcode, header, payload); + } } catch (Exception e) { @@ -205,44 +213,39 @@ public partial class Connection } } - private bool HandlePacket(ushort opcode, byte[] header, byte[] payload) + private async Task HandlePacket(ushort opcode, byte[] header, byte[] payload) { // Find the Handler for this opcode - Handler? handler = HandlerManager.GetHandler(opcode); + var handler = HandlerManager.GetHandler(opcode); if (handler != null) { // Handle // Make sure session is ready for packets - SessionStateEnum state = State; - switch ((int)opcode) + var state = State; + switch (opcode) { case CmdIds.PlayerGetTokenCsReq: - { - if (state != SessionStateEnum.WAITING_FOR_TOKEN) - { - return true; - } - goto default; - } + { + if (state != SessionStateEnum.WAITING_FOR_TOKEN) return true; + goto default; + } case CmdIds.PlayerLoginCsReq: - { - if (state != SessionStateEnum.WAITING_FOR_LOGIN) - { - return true; - } - goto default; - } + { + if (state != SessionStateEnum.WAITING_FOR_LOGIN) return true; + goto default; + } default: break; } - handler.OnHandle(this, header, payload); + + await handler.OnHandle(this, header, payload); return true; } return false; } - public void SendPacket(BasePacket packet) + public async Task SendPacket(BasePacket packet) { // Test if (packet.CmdId <= 0) @@ -252,27 +255,23 @@ public partial class Connection } // DO NOT REMOVE (unless we find a way to validate code before sending to client which I don't think we can) - if (BANNED_PACKETS.Contains(packet.CmdId)) - { - return; - } + if (BANNED_PACKETS.Contains(packet.CmdId)) return; LogPacket("Send", packet.CmdId, packet.Data); // Header - byte[] packetBytes = packet.BuildPacket(); + var packetBytes = packet.BuildPacket(); try { -#pragma warning disable CA2012 - _ = Conversation.SendAsync(packetBytes, CancelToken.Token); -#pragma warning restore CA2012 - } catch + _ = await Conversation.SendAsync(packetBytes, CancelToken.Token); + } + catch { // ignore } } - public void SendPacket(int cmdId) + public async Task SendPacket(int cmdId) { - SendPacket(new BasePacket((ushort)cmdId)); + await SendPacket(new BasePacket((ushort)cmdId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Listener.cs b/GameServer/Server/Listener.cs index bafa22a0..72a91d40 100644 --- a/GameServer/Server/Listener.cs +++ b/GameServer/Server/Listener.cs @@ -4,144 +4,151 @@ using EggLink.DanhengServer.Common.Enums; using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.KcpSharp; using EggLink.DanhengServer.Util; -using KcpSharp; -using Microsoft.Extensions.Logging; -namespace EggLink.DanhengServer.Server +namespace EggLink.DanhengServer.Server; + +public class Listener { - public class Listener + public const int MAX_MSG_SIZE = 16384; + public const int HANDSHAKE_SIZE = 20; + private static UdpClient? UDPClient; + private static IPEndPoint? ListenAddress; + private static IKcpTransport? KCPTransport; + private static readonly Logger Logger = new("GameServer"); + public static readonly SortedList Connections = []; + + private static readonly KcpConversationOptions ConvOpt = new() { - public const int MAX_MSG_SIZE = 16384; - public const int HANDSHAKE_SIZE = 20; - private static Socket? UDPListener => UDPClient?.Client; - private static UdpClient? UDPClient; - private static IPEndPoint? ListenAddress; - private static IKcpTransport? KCPTransport; - private static readonly Logger Logger = new("GameServer"); - private static IKcpMultiplexConnection? Multiplex => KCPTransport?.Connection; - public static readonly SortedList Connections = []; - public static Connection? GetConnectionByEndPoint(IPEndPoint ep) => Connections.Values.FirstOrDefault(c => c.RemoteEndPoint.Equals(ep)); + StreamMode = false, + Mtu = 1400, + ReceiveWindow = 256, + SendWindow = 256, + NoDelay = true, + UpdateInterval = 100, + KeepAliveOptions = new KcpKeepAliveOptions(1000, 30000) + }; - private static readonly KcpConversationOptions ConvOpt = new() - { - StreamMode = false, - Mtu = 1400, - ReceiveWindow = 256, - SendWindow = 256, - NoDelay = true, - UpdateInterval = 100, - KeepAliveOptions = new KcpKeepAliveOptions(1000, 30000) - }; - private static uint PORT => ConfigManager.Config.GameServer.PublicPort; - public static void StartListener() - { - ListenAddress = new IPEndPoint(IPAddress.Parse(ConfigManager.Config.GameServer.PublicAddress), (int)PORT); - UDPClient = new UdpClient(ListenAddress); - if (UDPListener == null) return; - KCPTransport = KcpSocketTransport.CreateMultiplexConnection(UDPClient, 1400); - KCPTransport.Start(); - Logger.Info(I18nManager.Translate("Server.ServerInfo.ServerRunning", I18nManager.Translate("Word.Game"), ConfigManager.Config.GameServer.GetDisplayAddress())); - } - - private static void RegisterConnection(Connection con) - { - if (!con.ConversationID.HasValue) return; - Connections[con.ConversationID.Value] = con; - } - public static void UnregisterConnection(Connection con) - { - if (!con.ConversationID.HasValue) return; - long convId = con.ConversationID.Value; - if (Connections.Remove(convId)) - { - Multiplex?.UnregisterConversation(convId); - Logger.Info($"Connection with {con.RemoteEndPoint} has been closed"); - } - } - - public static Connection? GetActiveConnection(int uid) - { - var con = Connections.Values.FirstOrDefault(c => c.Player?.Uid == uid && c.State == SessionStateEnum.ACTIVE); - return con; - } - - public static async Task HandleHandshake(UdpReceiveResult rcv) - { - try - { - Connection? con = GetConnectionByEndPoint(rcv.RemoteEndPoint); - await using MemoryStream? ms = new(rcv.Buffer); - using BinaryReader? br = new(ms); - int code = br.ReadInt32BE(); - br.ReadUInt32(); - br.ReadUInt32(); - int enet = br.ReadInt32BE(); - br.ReadUInt32(); - switch (code) - { - case 0x000000FF: - if (con != null) - { - Logger.Info($"Duplicate handshake from {con.RemoteEndPoint}"); - return; - } - await AcceptConnection(rcv, enet); - break; - case 0x00000194: - if (con == null) - { - Logger.Info($"Inexistent connection asked for disconnect from {rcv.RemoteEndPoint}"); - return; - } - await SendDisconnectPacket(con, 5); - break; - default: - Logger.Error($"Invalid handshake code received {code}"); - return; - } - } - catch (Exception ex) - { - Logger.Error($"Failed to handle handshake: {ex}"); - } - } - - private static async Task AcceptConnection(UdpReceiveResult rcv, int enet) - { - long convId = Connections.GetNextAvailableIndex(); - KcpConversation? convo = Multiplex?.CreateConversation(convId, rcv.RemoteEndPoint, ConvOpt); - if (convo == null) return; - Connection? con = new(convo, rcv.RemoteEndPoint); - RegisterConnection(con); - await SendHandshakeResponse(con, enet); - } - - private static async Task SendHandshakeResponse(Connection user, int enet) - { - if (user == null || UDPClient == null || !user.ConversationID.HasValue) return; - long convId = user.ConversationID.Value; - await using MemoryStream? ms = new(); - using BinaryWriter? bw = new(ms); - bw.WriteInt32BE(0x00000145); - bw.WriteConvID(convId); - bw.WriteInt32BE(enet); - bw.WriteInt32BE(0x14514545); - byte[]? data = ms.ToArray(); - await UDPClient.SendAsync(data, data.Length, user.RemoteEndPoint); - } - public static async Task SendDisconnectPacket(Connection user, int code) - { - if (user == null || UDPClient == null || !user.ConversationID.HasValue) return; - long convId = user.ConversationID.Value; - await using MemoryStream? ms = new(); - using BinaryWriter? bw = new(ms); - bw.WriteInt32BE(0x00000194); - bw.WriteConvID(convId); - bw.WriteInt32BE(code); - bw.WriteInt32BE(0x19419494); - byte[]? data = ms.ToArray(); - await UDPClient.SendAsync(data, data.Length, user.RemoteEndPoint); - } + private static Socket? UDPListener => UDPClient?.Client; + private static IKcpMultiplexConnection? Multiplex => KCPTransport?.Connection; + private static uint PORT => ConfigManager.Config.GameServer.PublicPort; + public static Connection? GetConnectionByEndPoint(IPEndPoint ep) + { + return Connections.Values.FirstOrDefault(c => c.RemoteEndPoint.Equals(ep)); } -} + + public static void StartListener() + { + ListenAddress = new IPEndPoint(IPAddress.Parse(ConfigManager.Config.GameServer.PublicAddress), (int)PORT); + UDPClient = new UdpClient(ListenAddress); + if (UDPListener == null) return; + KCPTransport = KcpSocketTransport.CreateMultiplexConnection(UDPClient, 1400); + KCPTransport.Start(); + Logger.Info(I18nManager.Translate("Server.ServerInfo.ServerRunning", I18nManager.Translate("Word.Game"), + ConfigManager.Config.GameServer.GetDisplayAddress())); + } + + private static void RegisterConnection(Connection con) + { + if (!con.ConversationID.HasValue) return; + Connections[con.ConversationID.Value] = con; + } + + public static void UnregisterConnection(Connection con) + { + if (!con.ConversationID.HasValue) return; + var convId = con.ConversationID.Value; + if (Connections.Remove(convId)) + { + Multiplex?.UnregisterConversation(convId); + Logger.Info($"Connection with {con.RemoteEndPoint} has been closed"); + } + } + + public static Connection? GetActiveConnection(int uid) + { + var con = Connections.Values.FirstOrDefault(c => c.Player?.Uid == uid && c.State == SessionStateEnum.ACTIVE); + return con; + } + + public static async Task HandleHandshake(UdpReceiveResult rcv) + { + try + { + var con = GetConnectionByEndPoint(rcv.RemoteEndPoint); + await using MemoryStream? ms = new(rcv.Buffer); + using BinaryReader? br = new(ms); + var code = br.ReadInt32BE(); + br.ReadUInt32(); + br.ReadUInt32(); + var enet = br.ReadInt32BE(); + br.ReadUInt32(); + switch (code) + { + case 0x000000FF: + if (con != null) + { + Logger.Info($"Duplicate handshake from {con.RemoteEndPoint}"); + return; + } + + await AcceptConnection(rcv, enet); + break; + case 0x00000194: + if (con == null) + { + Logger.Info($"Inexistent connection asked for disconnect from {rcv.RemoteEndPoint}"); + return; + } + + await SendDisconnectPacket(con, 5); + break; + default: + Logger.Error($"Invalid handshake code received {code}"); + return; + } + } + catch (Exception ex) + { + Logger.Error($"Failed to handle handshake: {ex}"); + } + } + + private static async Task AcceptConnection(UdpReceiveResult rcv, int enet) + { + var convId = Connections.GetNextAvailableIndex(); + var convo = Multiplex?.CreateConversation(convId, rcv.RemoteEndPoint, ConvOpt); + if (convo == null) return; + Connection? con = new(convo, rcv.RemoteEndPoint); + RegisterConnection(con); + await SendHandshakeResponse(con, enet); + } + + private static async Task SendHandshakeResponse(Connection user, int enet) + { + if (user == null || UDPClient == null || !user.ConversationID.HasValue) return; + var convId = user.ConversationID.Value; + await using MemoryStream? ms = new(); + using BinaryWriter? bw = new(ms); + bw.WriteInt32BE(0x00000145); + bw.WriteConvID(convId); + bw.WriteInt32BE(enet); + bw.WriteInt32BE(0x14514545); + var data = ms.ToArray(); + await UDPClient.SendAsync(data, data.Length, user.RemoteEndPoint); + } + + public static async Task SendDisconnectPacket(Connection user, int code) + { + if (user == null || UDPClient == null || !user.ConversationID.HasValue) return; + var convId = user.ConversationID.Value; + await using MemoryStream? ms = new(); + using BinaryWriter? bw = new(ms); + bw.WriteInt32BE(0x00000194); + bw.WriteConvID(convId); + bw.WriteInt32BE(code); + bw.WriteInt32BE(0x19419494); + var data = ms.ToArray(); + await UDPClient.SendAsync(data, data.Length, user.RemoteEndPoint); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/BasePacket.cs b/GameServer/Server/Packet/BasePacket.cs index 09b43186..5b2381cd 100644 --- a/GameServer/Server/Packet/BasePacket.cs +++ b/GameServer/Server/Packet/BasePacket.cs @@ -1,49 +1,40 @@ using EggLink.DanhengServer.Util; using Google.Protobuf; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet +namespace EggLink.DanhengServer.Server.Packet; + +public class BasePacket(ushort cmdId) { - public class BasePacket(ushort cmdId) + private const uint HEADER_CONST = 0x9d74c714; + private const uint TAIL_CONST = 0xd7a152c8; + + public ushort CmdId { get; set; } = cmdId; + public byte[] Data { get; set; } = []; + + public void SetData(byte[] data) { - private const uint HEADER_CONST = 0x9d74c714; - private const uint TAIL_CONST = 0xd7a152c8; - - public ushort CmdId { get; set; } = cmdId; - public byte[] Data { get; set; } = []; - - public void SetData(byte[] data) - { - Data = data; - } - - public void SetData(IMessage message) - { - Data = message.ToByteArray(); - } - - public byte[] BuildPacket() - { - using MemoryStream? ms = new(); - using BinaryWriter? bw = new(ms); - - bw.WriteUInt32BE(HEADER_CONST); - bw.WriteUInt16BE(CmdId); - bw.WriteUInt16BE(0); - bw.WriteUInt32BE((uint)Data.Length); - if (Data.Length > 0) - { - bw.Write(Data); - } - bw.WriteUInt32BE(TAIL_CONST); - - byte[] packet = ms.ToArray(); - - return packet; - } + Data = data; } -} + + public void SetData(IMessage message) + { + Data = message.ToByteArray(); + } + + public byte[] BuildPacket() + { + using MemoryStream? ms = new(); + using BinaryWriter? bw = new(ms); + + bw.WriteUInt32BE(HEADER_CONST); + bw.WriteUInt16BE(CmdId); + bw.WriteUInt16BE(0); + bw.WriteUInt32BE((uint)Data.Length); + if (Data.Length > 0) bw.Write(Data); + bw.WriteUInt32BE(TAIL_CONST); + + var packet = ms.ToArray(); + + return packet; + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/CmdIds.cs b/GameServer/Server/Packet/CmdIds.cs index 72452e63..9294b452 100644 --- a/GameServer/Server/Packet/CmdIds.cs +++ b/GameServer/Server/Packet/CmdIds.cs @@ -1,1490 +1,1483 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet; -namespace EggLink.DanhengServer.Server.Packet +public class CmdIds { - public class CmdIds - { - // None - public const int None = 0; + // None + public const int None = 0; - // Packet - public const int AcceptActivityExpeditionCsReq = 2527; - public const int AcceptActivityExpeditionScRsp = 2562; - public const int AcceptedPamMissionExpireCsReq = 4061; - public const int AcceptedPamMissionExpireScRsp = 4088; - public const int AcceptExpeditionCsReq = 2591; - public const int AcceptExpeditionScRsp = 2520; - public const int AcceptMainMissionCsReq = 1232; - public const int AcceptMainMissionScRsp = 1255; - public const int AcceptMissionEventCsReq = 1203; - public const int AcceptMissionEventScRsp = 1270; - public const int AcceptMultipleExpeditionCsReq = 2521; - public const int AcceptMultipleExpeditionScRsp = 2582; - public const int AceAntiCheaterCsReq = 46; - public const int AceAntiCheaterScRsp = 11; - public const int ActivateFarmElementCsReq = 1405; - public const int ActivateFarmElementScRsp = 1466; - public const int AddAvatarScNotify = 347; - public const int AddBlacklistCsReq = 2921; - public const int AddBlacklistScRsp = 2982; - public const int AddEquipmentScNotify = 537; - public const int AetherDivideFinishChallengeScNotify = 4801; - public const int AetherDivideLineupScNotify = 4855; - public const int AetherDivideRefreshEndlessCsReq = 4868; - public const int AetherDivideRefreshEndlessScNotify = 4858; - public const int AetherDivideRefreshEndlessScRsp = 4895; - public const int AetherDivideSkillItemScNotify = 4850; - public const int AetherDivideSpiritExpUpCsReq = 4809; - public const int AetherDivideSpiritExpUpScRsp = 4881; - public const int AetherDivideSpiritInfoScNotify = 4812; - public const int AetherDivideTainerInfoScNotify = 4833; - public const int AetherDivideTakeChallengeRewardCsReq = 4813; - public const int AetherDivideTakeChallengeRewardScRsp = 4885; - public const int AlleyEventChangeNotify = 4787; - public const int AlleyEventEffectNotify = 4727; - public const int AlleyFundsScNotify = 4709; - public const int AlleyGuaranteedFundsCsReq = 4768; - public const int AlleyGuaranteedFundsScRsp = 4795; - public const int AlleyOrderChangedScNotify = 4770; - public const int AlleyPlacingGameCsReq = 4747; - public const int AlleyPlacingGameScRsp = 4794; - public const int AlleyShipmentEventEffectsScNotify = 4733; - public const int AlleyShipUnlockScNotify = 4712; - public const int AlleyShipUsedCountScNotify = 4755; - public const int AlleyShopLevelScNotify = 4781; - public const int AlleyTakeEventRewardCsReq = 4758; - public const int AlleyTakeEventRewardScRsp = 4713; - public const int AntiAddictScNotify = 70; - public const int ApplyFriendCsReq = 2930; - public const int ApplyFriendScRsp = 2971; - public const int ArchiveWolfBroGameCsReq = 6591; - public const int ArchiveWolfBroGameScRsp = 6520; - public const int AvatarExpUpCsReq = 391; - public const int AvatarExpUpScRsp = 320; - public const int BatchGetQuestDataCsReq = 996; - public const int BatchGetQuestDataScRsp = 921; - public const int BatchMarkChatEmojiCsReq = 3947; - public const int BatchMarkChatEmojiScRsp = 3994; - public const int BattleCollegeDataChangeScNotify = 5791; - public const int BattleLogReportCsReq = 127; - public const int BattleLogReportScRsp = 162; - public const int BattlePassInfoNotify = 3061; - public const int BoxingClubChallengeUpdateScNotify = 4227; - public const int BoxingClubRewardScNotify = 4287; - public const int BuyBpLevelCsReq = 3073; - public const int BuyBpLevelScRsp = 3030; - public const int BuyGoodsCsReq = 1591; - public const int BuyGoodsScRsp = 1520; - public const int BuyNpcStuffCsReq = 4391; - public const int BuyNpcStuffScRsp = 4320; - public const int BuyRogueShopBuffCsReq = 5627; - public const int BuyRogueShopBuffScRsp = 5662; - public const int BuyRogueShopMiracleCsReq = 5671; - public const int BuyRogueShopMiracleScRsp = 5687; - public const int CancelActivityExpeditionCsReq = 2574; - public const int CancelActivityExpeditionScRsp = 2547; - public const int CancelCacheNotifyCsReq = 4187; - public const int CancelCacheNotifyScRsp = 4127; - public const int CancelExpeditionCsReq = 2539; - public const int CancelExpeditionScRsp = 2573; - public const int CancelMarkItemNotify = 585; - public const int CancelMatchCsReq = 7320; - public const int CancelMatchScRsp = 7313; - public const int ChallengeBossPhaseSettleNotify = 1737; - public const int ChallengeLineupNotify = 1774; - public const int ChallengeRaidNotify = 2227; - public const int ChallengeSettleNotify = 1730; - public const int ChangeLineupLeaderCsReq = 794; - public const int ChangeLineupLeaderScRsp = 796; - public const int ChangeScriptEmotionCsReq = 6391; - public const int ChangeScriptEmotionScRsp = 6320; - public const int ChangeStoryLineFinishScNotify = 6273; - public const int ChessRogueCellUpdateNotify = 5572; - public const int ChessRogueChangeyAeonDimensionNotify = 5531; - public const int ChessRogueCheatRollCsReq = 5596; - public const int ChessRogueCheatRollScRsp = 5456; - public const int ChessRogueConfirmRollCsReq = 5593; - public const int ChessRogueConfirmRollScRsp = 5555; - public const int ChessRogueEnterCellCsReq = 5532; - public const int ChessRogueEnterCellScRsp = 5562; - public const int ChessRogueEnterCsReq = 5557; - public const int ChessRogueEnterNextLayerCsReq = 5429; - public const int ChessRogueEnterNextLayerScRsp = 5598; - public const int ChessRogueEnterScRsp = 5424; - public const int ChessRogueFinishCurRoomNotify = 5426; - public const int ChessRogueGiveUpCsReq = 5481; - public const int ChessRogueGiveUpRollCsReq = 5560; - public const int ChessRogueGiveUpRollScRsp = 5406; - public const int ChessRogueGiveUpScRsp = 5479; - public const int ChessRogueGoAheadCsReq = 5472; - public const int ChessRogueGoAheadScRsp = 5574; - public const int ChessRogueLayerAccountInfoNotify = 5492; - public const int ChessRogueLeaveCsReq = 5545; - public const int ChessRogueLeaveScRsp = 5513; - public const int ChessRogueMoveCellNotify = 5582; - public const int ChessRogueNousDiceSurfaceUnlockNotify = 5514; - public const int ChessRogueNousDiceUpdateNotify = 5418; - public const int ChessRogueNousEditDiceCsReq = 5464; - public const int ChessRogueNousEditDiceScRsp = 5550; - public const int ChessRogueNousEnableRogueTalentCsReq = 5457; - public const int ChessRogueNousEnableRogueTalentScRsp = 5599; - public const int ChessRogueNousGetRogueTalentInfoCsReq = 5586; - public const int ChessRogueNousGetRogueTalentInfoScRsp = 5577; - public const int ChessRoguePickAvatarCsReq = 5558; - public const int ChessRoguePickAvatarScRsp = 5520; - public const int ChessRogueQueryAeonDimensionsCsReq = 5512; - public const int ChessRogueQueryAeonDimensionsScRsp = 5590; - public const int ChessRogueQueryBpCsReq = 5475; - public const int ChessRogueQueryBpScRsp = 5423; - public const int ChessRogueQueryCsReq = 5517; - public const int ChessRogueQueryScRsp = 5448; - public const int ChessRogueQuestFinishNotify = 5571; - public const int ChessRogueQuitCsReq = 5539; - public const int ChessRogueQuitScRsp = 5575; - public const int ChessRogueReRollDiceCsReq = 5460; - public const int ChessRogueReRollDiceScRsp = 5416; - public const int ChessRogueReviveAvatarCsReq = 5570; - public const int ChessRogueReviveAvatarScRsp = 5522; - public const int ChessRogueRollDiceCsReq = 5563; - public const int ChessRogueRollDiceScRsp = 5508; - public const int ChessRogueSelectBpCsReq = 5450; - public const int ChessRogueSelectBpScRsp = 5415; - public const int ChessRogueSelectCellCsReq = 5591; - public const int ChessRogueSelectCellScRsp = 5442; - public const int ChessRogueSkipTeachingLevelCsReq = 5440; - public const int ChessRogueSkipTeachingLevelScRsp = 5581; - public const int ChessRogueStartCsReq = 5452; - public const int ChessRogueStartScRsp = 5477; - public const int ChessRogueUpdateActionPointScNotify = 5419; - public const int ChessRogueUpdateAeonModifierValueScNotify = 5594; - public const int ChessRogueUpdateAllowedSelectCellScNotify = 5566; - public const int ChessRogueUpdateBoardScNotify = 5488; - public const int ChessRogueUpdateDiceInfoScNotify = 5435; - public const int ChessRogueUpdateDicePassiveAccumulateValueScNotify = 5498; - public const int ChessRogueUpdateLevelBaseInfoScNotify = 5499; - public const int ChessRogueUpdateMoneyInfoScNotify = 5564; - public const int ChessRogueUpdateReviveInfoScNotify = 5402; - public const int ChessRogueUpdateUnlockLevelScNotify = 5454; - public const int ChooseBoxingClubResonanceCsReq = 4262; - public const int ChooseBoxingClubResonanceScRsp = 4274; - public const int ChooseBoxingClubStageOptionalBuffCsReq = 4296; - public const int ChooseBoxingClubStageOptionalBuffScRsp = 4221; - public const int CityShopInfoScNotify = 1530; - public const int ClearAetherDividePassiveSkillCsReq = 4882; - public const int ClearAetherDividePassiveSkillScRsp = 4803; - public const int ClientDownloadDataScNotify = 5; - public const int ClientObjDownloadDataScNotify = 43; - public const int ClientObjUploadCsReq = 60; - public const int ClientObjUploadScRsp = 29; - public const int ClockParkBattleEndScNotify = 7282; - public const int ClockParkFinishScriptScNotify = 7249; - public const int ClockParkGetInfoCsReq = 7261; - public const int ClockParkGetInfoScRsp = 7288; - public const int ClockParkGetOngoingScriptInfoCsReq = 7287; - public const int ClockParkGetOngoingScriptInfoScRsp = 7227; - public const int ClockParkHandleWaitOperationCsReq = 7262; - public const int ClockParkHandleWaitOperationScRsp = 7274; - public const int ClockParkQuitScriptCsReq = 7247; - public const int ClockParkQuitScriptScRsp = 7294; - public const int ClockParkStartScriptCsReq = 7230; - public const int ClockParkStartScriptScRsp = 7271; - public const int ClockParkUnlockTalentCsReq = 7239; - public const int ClockParkUnlockTalentScRsp = 7273; - public const int ClockParkUseBuffCsReq = 7270; - public const int ClockParkUseBuffScRsp = 7256; - public const int CommonRogueComponentUpdateScNotify = 5680; - public const int CommonRogueQueryCsReq = 5644; - public const int CommonRogueQueryScRsp = 5624; - public const int CommonRogueUpdateScNotify = 5642; - public const int ComposeItemCsReq = 547; - public const int ComposeItemScRsp = 594; - public const int ComposeLimitNumCompleteNotify = 533; - public const int ComposeLimitNumUpdateNotify = 550; - public const int ComposeSelectedRelicCsReq = 581; - public const int ComposeSelectedRelicScRsp = 512; - public const int ContentPackageGetDataCsReq = 7495; - public const int ContentPackageGetDataScRsp = 7467; - public const int ContentPackageSyncDataScNotify = 7470; - public const int ContentPackageUnlockCsReq = 7463; - public const int ContentPackageUnlockScRsp = 7474; - public const int CurAssistChangedNotify = 2917; - public const int CurTrialActivityScNotify = 2689; - public const int DailyActiveInfoNotify = 3339; - public const int DailyFirstEnterMonopolyActivityCsReq = 7047; - public const int DailyFirstEnterMonopolyActivityScRsp = 7094; - public const int DailyFirstMeetPamCsReq = 3491; - public const int DailyFirstMeetPamScRsp = 3420; - public const int DailyRefreshNotify = 76; - public const int DailyTaskDataScNotify = 1271; - public const int DeactivateFarmElementCsReq = 1440; - public const int DeactivateFarmElementScRsp = 1448; - public const int DeleteBlacklistCsReq = 2912; - public const int DeleteBlacklistScRsp = 2937; - public const int DeleteFriendCsReq = 2947; - public const int DeleteFriendScRsp = 2994; - public const int DeleteSocialEventServerCacheCsReq = 7098; - public const int DeleteSocialEventServerCacheScRsp = 7086; - public const int DeleteSummonUnitCsReq = 1477; - public const int DeleteSummonUnitScRsp = 1404; - public const int DelMailCsReq = 839; - public const int DelMailScRsp = 873; - public const int DelSaveRaidScNotify = 2270; - public const int DeployRotaterCsReq = 6839; - public const int DeployRotaterScRsp = 6873; - public const int DestroyItemCsReq = 532; - public const int DestroyItemScRsp = 555; - public const int DiscardRelicCsReq = 593; - public const int DiscardRelicScRsp = 540; - public const int DoGachaCsReq = 1991; - public const int DoGachaInRollShopCsReq = 6907; - public const int DoGachaInRollShopScRsp = 6903; - public const int DoGachaScRsp = 1920; - public const int DressAvatarCsReq = 387; - public const int DressAvatarScRsp = 327; - public const int DressAvatarSkinCsReq = 351; - public const int DressAvatarSkinScRsp = 309; - public const int DressRelicAvatarCsReq = 321; - public const int DressRelicAvatarScRsp = 382; - public const int DrinkMakerChallengeCsReq = 6992; - public const int DrinkMakerChallengeScRsp = 6996; - public const int DrinkMakerDayEndScNotify = 6991; - public const int DrinkMakerUpdateTipsNotify = 6990; - public const int EnableRogueTalentCsReq = 1838; - public const int EnableRogueTalentScRsp = 1877; - public const int EndDrinkMakerSequenceCsReq = 6999; - public const int EndDrinkMakerSequenceScRsp = 6994; - public const int EnhanceChessRogueBuffCsReq = 5544; - public const int EnhanceChessRogueBuffScRsp = 5410; - public const int EnhanceCommonRogueBuffCsReq = 5609; - public const int EnhanceCommonRogueBuffScRsp = 5681; - public const int EnhanceRogueBuffCsReq = 1812; - public const int EnhanceRogueBuffScRsp = 1837; - public const int EnterAdventureCsReq = 1361; - public const int EnterAdventureScRsp = 1388; - public const int EnterAetherDivideSceneCsReq = 4861; - public const int EnterAetherDivideSceneScRsp = 4888; - public const int EnterChallengeNextPhaseCsReq = 1781; - public const int EnterChallengeNextPhaseScRsp = 1712; - public const int EnterChessRogueAeonRoomCsReq = 5433; - public const int EnterChessRogueAeonRoomScRsp = 5494; - public const int EnteredSceneChangeScNotify = 1402; - public const int EnterFantasticStoryActivityStageCsReq = 4920; - public const int EnterFantasticStoryActivityStageScRsp = 4939; - public const int EnterFeverTimeActivityStageCsReq = 7158; - public const int EnterFeverTimeActivityStageScRsp = 7151; - public const int EnterFightActivityStageCsReq = 3620; - public const int EnterFightActivityStageScRsp = 3639; - public const int EnterMapRotationRegionCsReq = 6861; - public const int EnterMapRotationRegionScRsp = 6888; - public const int EnterRogueCsReq = 1839; - public const int EnterRogueEndlessActivityStageCsReq = 6004; - public const int EnterRogueEndlessActivityStageScRsp = 6005; - public const int EnterRogueMapRoomCsReq = 1826; - public const int EnterRogueMapRoomScRsp = 1817; - public const int EnterRogueScRsp = 1873; - public const int EnterSceneByServerScNotify = 1483; - public const int EnterSceneCsReq = 1480; - public const int EnterSceneScRsp = 1478; - public const int EnterSectionCsReq = 1428; - public const int EnterSectionScRsp = 1401; - public const int EnterStrongChallengeActivityStageCsReq = 6691; - public const int EnterStrongChallengeActivityStageScRsp = 6620; - public const int EnterTelevisionActivityStageCsReq = 6963; - public const int EnterTelevisionActivityStageScRsp = 6979; - public const int EnterTreasureDungeonCsReq = 4447; - public const int EnterTreasureDungeonScRsp = 4494; - public const int EnterTrialActivityStageCsReq = 2611; - public const int EnterTrialActivityStageScRsp = 2644; - public const int EntityBindPropCsReq = 1454; - public const int EntityBindPropScRsp = 1426; - public const int EquipAetherDividePassiveSkillCsReq = 4896; - public const int EquipAetherDividePassiveSkillScRsp = 4821; - public const int EvolveBuildCoinNotify = 7136; - public const int EvolveBuildFinishScNotify = 7140; - public const int EvolveBuildGiveupCsReq = 7133; - public const int EvolveBuildGiveupScRsp = 7103; - public const int EvolveBuildLeaveCsReq = 7127; - public const int EvolveBuildLeaveScRsp = 7106; - public const int EvolveBuildQueryInfoCsReq = 7145; - public const int EvolveBuildQueryInfoScRsp = 7117; - public const int EvolveBuildReRandomStageCsReq = 7105; - public const int EvolveBuildReRandomStageScRsp = 7129; - public const int EvolveBuildShopAbilityDownCsReq = 7148; - public const int EvolveBuildShopAbilityDownScRsp = 7143; - public const int EvolveBuildShopAbilityResetCsReq = 7131; - public const int EvolveBuildShopAbilityResetScRsp = 7108; - public const int EvolveBuildShopAbilityUpCsReq = 7107; - public const int EvolveBuildShopAbilityUpScRsp = 7114; - public const int EvolveBuildStartLevelCsReq = 7120; - public const int EvolveBuildStartLevelScRsp = 7113; - public const int EvolveBuildStartStageCsReq = 7124; - public const int EvolveBuildStartStageScRsp = 7128; - public const int EvolveBuildTakeExpRewardCsReq = 7150; - public const int EvolveBuildTakeExpRewardScRsp = 7115; - public const int EvolveBuildUnlockInfoNotify = 7132; - public const int ExchangeGachaCeilingCsReq = 1930; - public const int ExchangeGachaCeilingScRsp = 1971; - public const int ExchangeHcoinCsReq = 551; - public const int ExchangeHcoinScRsp = 509; - public const int ExchangeRogueBuffWithMiracleCsReq = 5670; - public const int ExchangeRogueBuffWithMiracleScRsp = 5656; - public const int ExchangeRogueRewardKeyCsReq = 1842; - public const int ExchangeRogueRewardKeyScRsp = 1816; - public const int ExchangeStaminaCsReq = 94; - public const int ExchangeStaminaScRsp = 96; - public const int ExpeditionDataChangeScNotify = 2587; - public const int ExpUpEquipmentCsReq = 562; - public const int ExpUpEquipmentScRsp = 574; - public const int ExpUpRelicCsReq = 596; - public const int ExpUpRelicScRsp = 521; - public const int ExtraLineupDestroyNotify = 712; - public const int FantasticStoryActivityBattleEndScNotify = 4973; - public const int FeatureSwitchClosedScNotify = 57; - public const int FeverTimeActivityBattleEndScNotify = 7154; - public const int FightActivityDataChangeScNotify = 3691; - public const int FightEnterCsReq = 30061; - public const int FightEnterScRsp = 30088; - public const int FightHeartBeatCsReq = 30039; - public const int FightHeartBeatScRsp = 30073; - public const int FightKickOutScNotify = 30020; - public const int FightLeaveScNotify = 30091; - public const int FightMatch3ChatCsReq = 30187; - public const int FightMatch3ChatScNotify = 30162; - public const int FightMatch3ChatScRsp = 30127; - public const int FightMatch3DataCsReq = 30161; - public const int FightMatch3DataScRsp = 30188; - public const int FightMatch3ForceUpdateNotify = 30174; - public const int FightMatch3OpponentDataScNotify = 30171; - public const int FightMatch3StartCountDownScNotify = 30191; - public const int FightMatch3SwapCsReq = 30173; - public const int FightMatch3SwapScRsp = 30130; - public const int FightMatch3TurnEndScNotify = 30139; - public const int FightMatch3TurnStartScNotify = 30120; - public const int FightSessionStopScNotify = 30030; - public const int FightTreasureDungeonMonsterCsReq = 4482; - public const int FightTreasureDungeonMonsterScRsp = 4403; - public const int FinishAeonDialogueGroupCsReq = 1852; - public const int FinishAeonDialogueGroupScRsp = 1802; - public const int FinishChapterScNotify = 4991; - public const int FinishChessRogueNousSubStoryCsReq = 5535; - public const int FinishChessRogueNousSubStoryScRsp = 5455; - public const int FinishChessRogueSubStoryCsReq = 5405; - public const int FinishChessRogueSubStoryScRsp = 5592; - public const int FinishCosumeItemMissionCsReq = 1247; - public const int FinishCosumeItemMissionScRsp = 1294; - public const int FinishCurTurnCsReq = 4362; - public const int FinishCurTurnScRsp = 4374; - public const int FinishEmotionDialoguePerformanceCsReq = 6330; - public const int FinishEmotionDialoguePerformanceScRsp = 6371; - public const int FinishFirstTalkByPerformanceNpcCsReq = 2147; - public const int FinishFirstTalkByPerformanceNpcScRsp = 2194; - public const int FinishFirstTalkNpcCsReq = 2130; - public const int FinishFirstTalkNpcScRsp = 2171; - public const int FinishItemIdCsReq = 2739; - public const int FinishItemIdScRsp = 2773; - public const int FinishPerformSectionIdCsReq = 2787; - public const int FinishPerformSectionIdScRsp = 2727; - public const int FinishPlotCsReq = 1161; - public const int FinishPlotScRsp = 1188; - public const int FinishQuestCsReq = 927; - public const int FinishQuestScRsp = 962; - public const int FinishRogueCommonDialogueCsReq = 5689; - public const int FinishRogueCommonDialogueScRsp = 5610; - public const int FinishSectionIdCsReq = 2730; - public const int FinishSectionIdScRsp = 2771; - public const int FinishTalkMissionCsReq = 1291; - public const int FinishTalkMissionScRsp = 1220; - public const int FinishTutorialCsReq = 1687; - public const int FinishTutorialGuideCsReq = 1662; - public const int FinishTutorialGuideScRsp = 1674; - public const int FinishTutorialScRsp = 1627; - public const int GameplayCounterCountDownCsReq = 1443; - public const int GameplayCounterCountDownScRsp = 1460; - public const int GameplayCounterRecoverCsReq = 1445; - public const int GameplayCounterRecoverScRsp = 1415; - public const int GameplayCounterUpdateScNotify = 1429; - public const int GateServerScNotify = 65; - public const int GeneralVirtualItemDataNotify = 600; - public const int GetActivityScheduleConfigCsReq = 2639; - public const int GetActivityScheduleConfigScRsp = 2673; - public const int GetAetherDivideChallengeInfoCsReq = 4837; - public const int GetAetherDivideChallengeInfoScRsp = 4828; - public const int GetAetherDivideInfoCsReq = 4862; - public const int GetAetherDivideInfoScRsp = 4874; - public const int GetAlleyInfoCsReq = 4761; - public const int GetAlleyInfoScRsp = 4788; - public const int GetAllLineupDataCsReq = 756; - public const int GetAllLineupDataScRsp = 749; - public const int GetAllRedDotDataCsReq = 5961; - public const int GetAllRedDotDataScRsp = 5988; - public const int GetAllSaveRaidCsReq = 2282; - public const int GetAllSaveRaidScRsp = 2203; - public const int GetAllServerPrefsDataCsReq = 6161; - public const int GetAllServerPrefsDataScRsp = 6188; - public const int GetArchiveDataCsReq = 2361; - public const int GetArchiveDataScRsp = 2388; - public const int GetAssistHistoryCsReq = 2958; - public const int GetAssistHistoryScRsp = 2913; - public const int GetAssistListCsReq = 2933; - public const int GetAssistListScRsp = 2950; - public const int GetAuthkeyCsReq = 21; - public const int GetAuthkeyScRsp = 82; - public const int GetAvatarDataCsReq = 361; - public const int GetAvatarDataScRsp = 388; - public const int GetBagCsReq = 561; - public const int GetBagScRsp = 588; - public const int GetBasicInfoCsReq = 90; - public const int GetBasicInfoScRsp = 18; - public const int GetBattleCollegeDataCsReq = 5761; - public const int GetBattleCollegeDataScRsp = 5788; - public const int GetBoxingClubInfoCsReq = 4261; - public const int GetBoxingClubInfoScRsp = 4288; - public const int GetChallengeCsReq = 1761; - public const int GetChallengeGroupStatisticsCsReq = 1782; - public const int GetChallengeGroupStatisticsScRsp = 1703; - public const int GetChallengeRaidInfoCsReq = 2273; - public const int GetChallengeRaidInfoScRsp = 2230; - public const int GetChallengeScRsp = 1788; - public const int GetChapterCsReq = 439; - public const int GetChapterScRsp = 473; - public const int GetChatEmojiListCsReq = 3987; - public const int GetChatEmojiListScRsp = 3927; - public const int GetChatFriendHistoryCsReq = 3930; - public const int GetChatFriendHistoryScRsp = 3971; - public const int GetChessRogueBuffEnhanceInfoCsReq = 5414; - public const int GetChessRogueBuffEnhanceInfoScRsp = 5524; - public const int GetChessRogueNousStoryInfoCsReq = 5431; - public const int GetChessRogueNousStoryInfoScRsp = 5444; - public const int GetChessRogueStoryAeonTalkInfoCsReq = 5502; - public const int GetChessRogueStoryAeonTalkInfoScRsp = 5465; - public const int GetChessRogueStoryInfoCsReq = 5542; - public const int GetChessRogueStoryInfoScRsp = 5515; - public const int GetCrossInfoCsReq = 7328; - public const int GetCrossInfoScRsp = 7333; - public const int GetCurAssistCsReq = 2968; - public const int GetCurAssistScRsp = 2995; - public const int GetCurBattleInfoCsReq = 139; - public const int GetCurBattleInfoScRsp = 173; - public const int GetCurChallengeCsReq = 1727; - public const int GetCurChallengeScRsp = 1762; - public const int GetCurLineupDataCsReq = 791; - public const int GetCurLineupDataScRsp = 720; - public const int GetCurSceneInfoCsReq = 1430; - public const int GetCurSceneInfoScRsp = 1471; - public const int GetDailyActiveInfoCsReq = 3391; - public const int GetDailyActiveInfoScRsp = 3320; - public const int GetDrinkMakerDataCsReq = 6989; - public const int GetDrinkMakerDataScRsp = 6982; - public const int GetEnhanceCommonRogueBuffInfoCsReq = 5649; - public const int GetEnhanceCommonRogueBuffInfoScRsp = 5651; - public const int GetEnteredSceneCsReq = 1407; - public const int GetEnteredSceneScRsp = 1452; - public const int GetExhibitScNotify = 4327; - public const int GetExpeditionDataCsReq = 2561; - public const int GetExpeditionDataScRsp = 2588; - public const int GetFantasticStoryActivityDataCsReq = 4961; - public const int GetFantasticStoryActivityDataScRsp = 4988; - public const int GetFarmStageGachaInfoCsReq = 1391; - public const int GetFarmStageGachaInfoScRsp = 1320; - public const int GetFeverTimeActivityDataCsReq = 7155; - public const int GetFeverTimeActivityDataScRsp = 7156; - public const int GetFightActivityDataCsReq = 3661; - public const int GetFightActivityDataScRsp = 3688; - public const int GetFirstTalkByPerformanceNpcCsReq = 2162; - public const int GetFirstTalkByPerformanceNpcScRsp = 2174; - public const int GetFirstTalkNpcCsReq = 2139; - public const int GetFirstTalkNpcScRsp = 2173; - public const int GetFriendApplyListInfoCsReq = 2939; - public const int GetFriendApplyListInfoScRsp = 2973; - public const int GetFriendAssistListCsReq = 2976; - public const int GetFriendAssistListScRsp = 2964; - public const int GetFriendBattleRecordDetailCsReq = 2924; - public const int GetFriendBattleRecordDetailScRsp = 2942; - public const int GetFriendChallengeDetailCsReq = 2911; - public const int GetFriendChallengeDetailScRsp = 2944; - public const int GetFriendChallengeLineupCsReq = 2908; - public const int GetFriendChallengeLineupScRsp = 2946; - public const int GetFriendDevelopmentInfoCsReq = 2916; - public const int GetFriendDevelopmentInfoScRsp = 2965; - public const int GetFriendListInfoCsReq = 2961; - public const int GetFriendListInfoScRsp = 2988; - public const int GetFriendLoginInfoCsReq = 2940; - public const int GetFriendLoginInfoScRsp = 2948; - public const int GetFriendRecommendListInfoCsReq = 2970; - public const int GetFriendRecommendListInfoScRsp = 2956; - public const int GetGachaCeilingCsReq = 1939; - public const int GetGachaCeilingScRsp = 1973; - public const int GetGachaInfoCsReq = 1961; - public const int GetGachaInfoScRsp = 1988; - public const int GetGunPlayDataCsReq = 4112; - public const int GetGunPlayDataScRsp = 4137; - public const int GetHeartDialInfoCsReq = 6361; - public const int GetHeartDialInfoScRsp = 6388; - public const int GetHeroBasicTypeInfoCsReq = 68; - public const int GetHeroBasicTypeInfoScRsp = 95; - public const int GetJukeboxDataCsReq = 3161; - public const int GetJukeboxDataScRsp = 3188; - public const int GetKilledPunkLordMonsterDataCsReq = 3281; - public const int GetKilledPunkLordMonsterDataScRsp = 3212; - public const int GetLevelRewardCsReq = 81; - public const int GetLevelRewardScRsp = 12; - public const int GetLevelRewardTakenListCsReq = 51; - public const int GetLevelRewardTakenListScRsp = 9; - public const int GetLineupAvatarDataCsReq = 774; - public const int GetLineupAvatarDataScRsp = 747; - public const int GetLoginActivityCsReq = 2661; - public const int GetLoginActivityScRsp = 2688; - public const int GetLoginChatInfoCsReq = 3996; - public const int GetLoginChatInfoScRsp = 3921; - public const int GetMailCsReq = 861; - public const int GetMailScRsp = 888; - public const int GetMainMissionCustomValueCsReq = 1268; - public const int GetMainMissionCustomValueScRsp = 1295; - public const int GetMapRotationDataCsReq = 6862; - public const int GetMapRotationDataScRsp = 6874; - public const int GetMarkItemListCsReq = 568; - public const int GetMarkItemListScRsp = 595; - public const int GetMbtiReportCsReq = 7042; - public const int GetMbtiReportScRsp = 7016; - public const int GetMissionDataCsReq = 1261; - public const int GetMissionDataScRsp = 1288; - public const int GetMissionEventDataCsReq = 1296; - public const int GetMissionEventDataScRsp = 1221; - public const int GetMissionStatusCsReq = 1256; - public const int GetMissionStatusScRsp = 1249; - public const int GetMonopolyDailyReportCsReq = 7041; - public const int GetMonopolyDailyReportScRsp = 7035; - public const int GetMonopolyFriendRankingListCsReq = 7008; - public const int GetMonopolyFriendRankingListScRsp = 7046; - public const int GetMonopolyInfoCsReq = 7061; - public const int GetMonopolyInfoScRsp = 7088; - public const int GetMonopolyMbtiReportRewardCsReq = 7045; - public const int GetMonopolyMbtiReportRewardScRsp = 7015; - public const int GetMonsterResearchActivityDataCsReq = 2682; - public const int GetMonsterResearchActivityDataScRsp = 2603; - public const int GetMovieRacingDataCsReq = 4149; - public const int GetMovieRacingDataScRsp = 4151; - public const int GetMultipleDropInfoCsReq = 4661; - public const int GetMultipleDropInfoScRsp = 4688; - public const int GetMuseumInfoCsReq = 4361; - public const int GetMuseumInfoScRsp = 4388; - public const int GetNpcMessageGroupCsReq = 2761; - public const int GetNpcMessageGroupScRsp = 2788; - public const int GetNpcStatusCsReq = 2791; - public const int GetNpcStatusScRsp = 2720; - public const int GetNpcTakenRewardCsReq = 2161; - public const int GetNpcTakenRewardScRsp = 2188; - public const int GetOfferingInfoCsReq = 6929; - public const int GetOfferingInfoScRsp = 6922; - public const int GetPhoneDataCsReq = 5161; - public const int GetPhoneDataScRsp = 5188; - public const int GetPlatformPlayerInfoCsReq = 3000; - public const int GetPlatformPlayerInfoScRsp = 2993; - public const int GetPlayerBoardDataCsReq = 2861; - public const int GetPlayerBoardDataScRsp = 2888; - public const int GetPlayerDetailInfoCsReq = 2991; - public const int GetPlayerDetailInfoScRsp = 2920; - public const int GetPlayerReplayInfoCsReq = 3591; - public const int GetPlayerReplayInfoScRsp = 3520; - public const int GetPlayerReturnMultiDropInfoCsReq = 4620; - public const int GetPlayerReturnMultiDropInfoScRsp = 4639; - public const int GetPrivateChatHistoryCsReq = 3939; - public const int GetPrivateChatHistoryScRsp = 3973; - public const int GetPunkLordBattleRecordCsReq = 3255; - public const int GetPunkLordBattleRecordScRsp = 3268; - public const int GetPunkLordDataCsReq = 3221; - public const int GetPunkLordDataScRsp = 3282; - public const int GetPunkLordMonsterDataCsReq = 3261; - public const int GetPunkLordMonsterDataScRsp = 3288; - public const int GetQuestDataCsReq = 961; - public const int GetQuestDataScRsp = 988; - public const int GetQuestRecordCsReq = 930; - public const int GetQuestRecordScRsp = 971; - public const int GetRaidInfoCsReq = 2262; - public const int GetRaidInfoScRsp = 2274; - public const int GetRecyleTimeCsReq = 528; - public const int GetRecyleTimeScRsp = 501; - public const int GetReplayTokenCsReq = 3561; - public const int GetReplayTokenScRsp = 3588; - public const int GetRndOptionCsReq = 3461; - public const int GetRndOptionScRsp = 3488; - public const int GetRogueAdventureRoomInfoCsReq = 5694; - public const int GetRogueAdventureRoomInfoScRsp = 5696; - public const int GetRogueAeonInfoCsReq = 1899; - public const int GetRogueAeonInfoScRsp = 1807; - public const int GetRogueBuffEnhanceInfoCsReq = 1809; - public const int GetRogueBuffEnhanceInfoScRsp = 1881; - public const int GetRogueCollectionCsReq = 5669; - public const int GetRogueCollectionScRsp = 5625; - public const int GetRogueCommonDialogueDataCsReq = 5616; - public const int GetRogueCommonDialogueDataScRsp = 5665; - public const int GetRogueEndlessActivityDataCsReq = 6008; - public const int GetRogueEndlessActivityDataScRsp = 6001; - public const int GetRogueExhibitionCsReq = 5606; - public const int GetRogueExhibitionScRsp = 5614; - public const int GetRogueHandbookDataCsReq = 5685; - public const int GetRogueHandbookDataScRsp = 5654; - public const int GetRogueInfoCsReq = 1861; - public const int GetRogueInfoScRsp = 1888; - public const int GetRogueInitialScoreCsReq = 1900; - public const int GetRogueInitialScoreScRsp = 1893; - public const int GetRogueScoreRewardInfoCsReq = 1843; - public const int GetRogueScoreRewardInfoScRsp = 1860; - public const int GetRogueShopBuffInfoCsReq = 5673; - public const int GetRogueShopBuffInfoScRsp = 5630; - public const int GetRogueShopMiracleInfoCsReq = 5620; - public const int GetRogueShopMiracleInfoScRsp = 5639; - public const int GetRogueTalentInfoCsReq = 1836; - public const int GetRogueTalentInfoScRsp = 1875; - public const int GetRollShopInfoCsReq = 6909; - public const int GetRollShopInfoScRsp = 6902; - public const int GetSaveLogisticsMapCsReq = 4750; - public const int GetSaveLogisticsMapScRsp = 4732; - public const int GetSaveRaidCsReq = 2296; - public const int GetSaveRaidScRsp = 2221; - public const int GetSceneMapInfoCsReq = 1484; - public const int GetSceneMapInfoScRsp = 1469; - public const int GetSecretKeyInfoCsReq = 10; - public const int GetSecretKeyInfoScRsp = 98; - public const int GetServerPrefsDataCsReq = 6191; - public const int GetServerPrefsDataScRsp = 6120; - public const int GetShareDataCsReq = 4191; - public const int GetShareDataScRsp = 4120; - public const int GetShopListCsReq = 1561; - public const int GetShopListScRsp = 1588; - public const int GetSingleRedDotParamGroupCsReq = 5939; - public const int GetSingleRedDotParamGroupScRsp = 5973; - public const int GetSocialEventServerCacheCsReq = 7089; - public const int GetSocialEventServerCacheScRsp = 7010; - public const int GetSpringRecoverDataCsReq = 1490; - public const int GetSpringRecoverDataScRsp = 1418; - public const int GetStageLineupCsReq = 761; - public const int GetStageLineupScRsp = 788; - public const int GetStarFightDataCsReq = 7168; - public const int GetStarFightDataScRsp = 7161; - public const int GetStoryLineInfoCsReq = 6261; - public const int GetStoryLineInfoScRsp = 6288; - public const int GetStrongChallengeActivityDataCsReq = 6661; - public const int GetStrongChallengeActivityDataScRsp = 6688; - public const int GetStuffScNotify = 4387; - public const int GetTelevisionActivityDataCsReq = 6969; - public const int GetTelevisionActivityDataScRsp = 6962; - public const int GetTrainVisitorBehaviorCsReq = 3791; - public const int GetTrainVisitorBehaviorScRsp = 3720; - public const int GetTrainVisitorRegisterCsReq = 3730; - public const int GetTrainVisitorRegisterScRsp = 3771; - public const int GetTreasureDungeonActivityDataCsReq = 4462; - public const int GetTreasureDungeonActivityDataScRsp = 4474; - public const int GetTrialActivityDataCsReq = 2664; - public const int GetTrialActivityDataScRsp = 2608; - public const int GetTutorialCsReq = 1661; - public const int GetTutorialGuideCsReq = 1691; - public const int GetTutorialGuideScRsp = 1620; - public const int GetTutorialScRsp = 1688; - public const int GetUnlockTeleportCsReq = 1472; - public const int GetUnlockTeleportScRsp = 1453; - public const int GetUpdatedArchiveDataCsReq = 2391; - public const int GetUpdatedArchiveDataScRsp = 2320; - public const int GetVideoVersionKeyCsReq = 78; - public const int GetVideoVersionKeyScRsp = 83; - public const int GetWaypointCsReq = 461; - public const int GetWaypointScRsp = 488; - public const int GetWolfBroGameDataCsReq = 6587; - public const int GetWolfBroGameDataScRsp = 6527; - public const int GiveUpBoxingClubChallengeCsReq = 4230; - public const int GiveUpBoxingClubChallengeScRsp = 4271; - public const int GmTalkCsReq = 27; - public const int GmTalkScNotify = 71; - public const int GmTalkScRsp = 62; - public const int GroupStateChangeCsReq = 1441; - public const int GroupStateChangeScNotify = 1499; - public const int GroupStateChangeScRsp = 1435; - public const int HandleFriendCsReq = 2927; - public const int HandleFriendScRsp = 2962; - public const int HandleRogueCommonPendingActionCsReq = 5646; - public const int HandleRogueCommonPendingActionScRsp = 5611; - public const int HealPoolInfoNotify = 1411; - public const int HeartDialScriptChangeScNotify = 6387; - public const int HeartDialTraceScriptCsReq = 6327; - public const int HeartDialTraceScriptScRsp = 6362; - public const int HeliobusActivityDataCsReq = 5861; - public const int HeliobusActivityDataScRsp = 5888; - public const int HeliobusChallengeUpdateScNotify = 5881; - public const int HeliobusEnterBattleCsReq = 5856; - public const int HeliobusEnterBattleScRsp = 5849; - public const int HeliobusInfoChangedScNotify = 5874; - public const int HeliobusLineupUpdateScNotify = 5812; - public const int HeliobusSelectSkillCsReq = 5821; - public const int HeliobusSelectSkillScRsp = 5882; - public const int HeliobusSnsCommentCsReq = 5887; - public const int HeliobusSnsCommentScRsp = 5827; - public const int HeliobusSnsLikeCsReq = 5830; - public const int HeliobusSnsLikeScRsp = 5871; - public const int HeliobusSnsPostCsReq = 5839; - public const int HeliobusSnsPostScRsp = 5873; - public const int HeliobusSnsReadCsReq = 5891; - public const int HeliobusSnsReadScRsp = 5820; - public const int HeliobusSnsUpdateScNotify = 5862; - public const int HeliobusStartRaidCsReq = 5851; - public const int HeliobusStartRaidScRsp = 5809; - public const int HeliobusUnlockSkillScNotify = 5896; - public const int HeliobusUpgradeLevelCsReq = 5847; - public const int HeliobusUpgradeLevelScRsp = 5894; - public const int HeroBasicTypeChangedNotify = 93; - public const int InteractChargerCsReq = 6891; - public const int InteractChargerScRsp = 6820; - public const int InteractPropCsReq = 1491; - public const int InteractPropScRsp = 1420; - public const int InteractTreasureDungeonGridCsReq = 4470; - public const int InteractTreasureDungeonGridScRsp = 4456; - public const int InterruptMissionEventCsReq = 1251; - public const int InterruptMissionEventScRsp = 1209; - public const int JoinLineupCsReq = 739; - public const int JoinLineupScRsp = 773; - public const int LastSpringRefreshTimeNotify = 1456; - public const int LeaveAetherDivideSceneCsReq = 4891; - public const int LeaveAetherDivideSceneScRsp = 4820; - public const int LeaveChallengeCsReq = 1739; - public const int LeaveChallengeScRsp = 1773; - public const int LeaveMapRotationRegionCsReq = 6887; - public const int LeaveMapRotationRegionScNotify = 6896; - public const int LeaveMapRotationRegionScRsp = 6827; - public const int LeaveRaidCsReq = 2291; - public const int LeaveRaidScRsp = 2220; - public const int LeaveRogueCsReq = 1830; - public const int LeaveRogueScRsp = 1871; - public const int LeaveTrialActivityCsReq = 2657; - public const int LeaveTrialActivityScRsp = 2634; - public const int LobbyBeginCsReq = 7374; - public const int LobbyBeginScRsp = 7378; - public const int LobbyCreateCsReq = 7395; - public const int LobbyCreateScRsp = 7367; - public const int LobbyGetInfoCsReq = 7364; - public const int LobbyGetInfoScRsp = 7398; - public const int LobbyInviteCsReq = 7355; - public const int LobbyInviteScNotify = 7357; - public const int LobbyInviteScRsp = 7379; - public const int LobbyJoinCsReq = 7370; - public const int LobbyJoinScRsp = 7363; - public const int LobbyKickOutCsReq = 7377; - public const int LobbyKickOutScRsp = 7356; - public const int LobbyModifyPlayerInfoCsReq = 7383; - public const int LobbyModifyPlayerInfoScRsp = 7353; - public const int LobbyQuitCsReq = 7387; - public const int LobbyQuitScRsp = 7359; - public const int LobbySyncInfoScNotify = 7390; - public const int LockEquipmentCsReq = 539; - public const int LockEquipmentScRsp = 573; - public const int LockRelicCsReq = 582; - public const int LockRelicScRsp = 503; - public const int LogisticsDetonateStarSkiffCsReq = 4785; - public const int LogisticsDetonateStarSkiffScRsp = 4754; - public const int LogisticsGameCsReq = 4791; - public const int LogisticsGameScRsp = 4720; - public const int LogisticsInfoScNotify = 4701; - public const int LogisticsScoreRewardSyncInfoScNotify = 4726; - public const int MakeDrinkCsReq = 6987; - public const int MakeDrinkScRsp = 6983; - public const int MakeMissionDrinkCsReq = 6995; - public const int MakeMissionDrinkScRsp = 6993; - public const int MarkAvatarCsReq = 328; - public const int MarkAvatarScRsp = 301; - public const int MarkChatEmojiCsReq = 3962; - public const int MarkChatEmojiScRsp = 3974; - public const int MarkItemCsReq = 558; - public const int MarkItemScRsp = 513; - public const int MarkReadMailCsReq = 891; - public const int MarkReadMailScRsp = 820; - public const int MatchBoxingClubOpponentCsReq = 4291; - public const int MatchBoxingClubOpponentScRsp = 4220; - public const int MatchResultScNotify = 7324; - public const int MatchThreeGetDataCsReq = 7445; - public const int MatchThreeGetDataScRsp = 7417; - public const int MatchThreeLevelEndCsReq = 7420; - public const int MatchThreeLevelEndScRsp = 7413; - public const int MatchThreeSetBirdPosCsReq = 7428; - public const int MatchThreeSetBirdPosScRsp = 7433; - public const int MatchThreeSyncDataScNotify = 7424; - public const int MissionAcceptScNotify = 1258; - public const int MissionEventRewardScNotify = 1282; - public const int MissionGroupWarnScNotify = 1274; - public const int MissionRewardScNotify = 1239; - public const int MonopolyAcceptQuizCsReq = 7085; - public const int MonopolyAcceptQuizScRsp = 7054; - public const int MonopolyActionResultScNotify = 7091; - public const int MonopolyBuyGoodsCsReq = 7049; - public const int MonopolyBuyGoodsScRsp = 7051; - public const int MonopolyCellUpdateNotify = 7020; - public const int MonopolyCheatDiceCsReq = 7028; - public const int MonopolyCheatDiceScRsp = 7001; - public const int MonopolyClickCellCsReq = 7099; - public const int MonopolyClickCellScRsp = 7007; - public const int MonopolyClickMbtiReportCsReq = 7075; - public const int MonopolyClickMbtiReportScRsp = 7038; - public const int MonopolyConditionUpdateScNotify = 7036; - public const int MonopolyConfirmRandomCsReq = 7070; - public const int MonopolyConfirmRandomScRsp = 7056; - public const int MonopolyContentUpdateScNotify = 7033; - public const int MonopolyDailySettleScNotify = 7064; - public const int MonopolyEventLoadUpdateScNotify = 7029; - public const int MonopolyEventSelectFriendCsReq = 7065; - public const int MonopolyEventSelectFriendScRsp = 7057; - public const int MonopolyGameBingoFlipCardCsReq = 7058; - public const int MonopolyGameBingoFlipCardScRsp = 7013; - public const int MonopolyGameCreateScNotify = 7026; - public const int MonopolyGameGachaCsReq = 7068; - public const int MonopolyGameGachaScRsp = 7095; - public const int MonopolyGameRaiseRatioCsReq = 7050; - public const int MonopolyGameRaiseRatioScRsp = 7032; - public const int MonopolyGameSettleScNotify = 7055; - public const int MonopolyGetDailyInitItemCsReq = 7052; - public const int MonopolyGetDailyInitItemScRsp = 7002; - public const int MonopolyGetRafflePoolInfoCsReq = 7006; - public const int MonopolyGetRafflePoolInfoScRsp = 7014; - public const int MonopolyGetRaffleTicketCsReq = 7078; - public const int MonopolyGetRaffleTicketScRsp = 7083; - public const int MonopolyGetRegionProgressCsReq = 7072; - public const int MonopolyGetRegionProgressScRsp = 7053; - public const int MonopolyGiveUpCurContentCsReq = 7012; - public const int MonopolyGiveUpCurContentScRsp = 7037; - public const int MonopolyGuessBuyInformationCsReq = 7093; - public const int MonopolyGuessBuyInformationScRsp = 7040; - public const int MonopolyGuessChooseCsReq = 7017; - public const int MonopolyGuessChooseScRsp = 7100; - public const int MonopolyGuessDrawScNotify = 7048; - public const int MonopolyLikeCsReq = 7011; - public const int MonopolyLikeScNotify = 7024; - public const int MonopolyLikeScRsp = 7044; - public const int MonopolyMoveCsReq = 7071; - public const int MonopolyMoveScRsp = 7087; - public const int MonopolyQuizDurationChangeScNotify = 7005; - public const int MonopolyReRollRandomCsReq = 7082; - public const int MonopolyReRollRandomScRsp = 7003; - public const int MonopolyRollDiceCsReq = 7073; - public const int MonopolyRollDiceScRsp = 7030; - public const int MonopolyRollRandomCsReq = 7096; - public const int MonopolyRollRandomScRsp = 7021; - public const int MonopolyScrachRaffleTicketCsReq = 7069; - public const int MonopolyScrachRaffleTicketScRsp = 7025; - public const int MonopolySelectOptionCsReq = 7027; - public const int MonopolySelectOptionScRsp = 7062; - public const int MonopolySocialEventEffectScNotify = 7034; - public const int MonopolySttUpdateScNotify = 7063; - public const int MonopolyTakePhaseRewardCsReq = 7043; - public const int MonopolyTakePhaseRewardScRsp = 7060; - public const int MonopolyTakeRaffleTicketRewardCsReq = 7079; - public const int MonopolyTakeRaffleTicketRewardScRsp = 7084; - public const int MonopolyUpgradeAssetCsReq = 7009; - public const int MonopolyUpgradeAssetScRsp = 7081; - public const int MonthCardRewardNotify = 44; - public const int MultiplayerFightGameFinishScNotify = 1071; - public const int MultiplayerFightGameStartScNotify = 1030; - public const int MultiplayerFightGameStateCsReq = 1061; - public const int MultiplayerFightGameStateScRsp = 1088; - public const int MultiplayerFightGiveUpCsReq = 1039; - public const int MultiplayerFightGiveUpScRsp = 1073; - public const int MultiplayerGetFightGateCsReq = 1091; - public const int MultiplayerGetFightGateScRsp = 1020; - public const int MultiplayerMatch3FinishScNotify = 1087; - public const int MultipleDropInfoNotify = 4673; - public const int MultipleDropInfoScNotify = 4691; - public const int MuseumDispatchFinishedScNotify = 4381; - public const int MuseumFundsChangedScNotify = 4303; - public const int MuseumInfoChangedScNotify = 4382; - public const int MuseumRandomEventQueryCsReq = 4356; - public const int MuseumRandomEventQueryScRsp = 4349; - public const int MuseumRandomEventSelectCsReq = 4351; - public const int MuseumRandomEventSelectScRsp = 4309; - public const int MuseumRandomEventStartScNotify = 4370; - public const int MuseumTakeCollectRewardCsReq = 4301; - public const int MuseumTakeCollectRewardScRsp = 4333; - public const int MuseumTargetMissionFinishNotify = 4337; - public const int MuseumTargetRewardNotify = 4328; - public const int MuseumTargetStartNotify = 4312; - public const int NewAssistHistoryNotify = 2985; - public const int NewMailScNotify = 887; - public const int OfferingInfoScNotify = 6935; - public const int OpenRogueChestCsReq = 1844; - public const int OpenRogueChestScRsp = 1824; - public const int OpenTreasureDungeonGridCsReq = 4496; - public const int OpenTreasureDungeonGridScRsp = 4421; - public const int PickRogueAvatarCsReq = 1821; - public const int PickRogueAvatarScRsp = 1882; - public const int PlayBackGroundMusicCsReq = 3191; - public const int PlayBackGroundMusicScRsp = 3120; - public const int PlayerGetTokenCsReq = 39; - public const int PlayerGetTokenScRsp = 73; - public const int PlayerHeartBeatCsReq = 42; - public const int PlayerHeartBeatScRsp = 16; - public const int PlayerKickOutScNotify = 87; - public const int PlayerLoginCsReq = 61; - public const int PlayerLoginFinishCsReq = 86; - public const int PlayerLoginFinishScRsp = 80; - public const int PlayerLoginScRsp = 88; - public const int PlayerLogoutCsReq = 91; - public const int PlayerLogoutScRsp = 20; - public const int PlayerReturnForceFinishScNotify = 4562; - public const int PlayerReturnInfoQueryCsReq = 4587; - public const int PlayerReturnInfoQueryScRsp = 4527; - public const int PlayerReturnPointChangeScNotify = 4520; - public const int PlayerReturnSignCsReq = 4588; - public const int PlayerReturnSignScRsp = 4591; - public const int PlayerReturnStartScNotify = 4561; - public const int PlayerReturnTakePointRewardCsReq = 4539; - public const int PlayerReturnTakePointRewardScRsp = 4573; - public const int PlayerReturnTakeRewardCsReq = 4530; - public const int PlayerReturnTakeRewardScRsp = 4571; - public const int PlayerSyncScNotify = 661; - public const int PrepareRogueAdventureRoomCsReq = 5688; - public const int PrepareRogueAdventureRoomScRsp = 5691; - public const int PrestigeLevelUpCsReq = 4749; - public const int PrestigeLevelUpScRsp = 4751; - public const int PrivateMsgOfflineUsersScNotify = 3920; - public const int PromoteAvatarCsReq = 330; - public const int PromoteAvatarScRsp = 371; - public const int PromoteEquipmentCsReq = 591; - public const int PromoteEquipmentScRsp = 520; - public const int PunkLordBattleResultScNotify = 3209; - public const int PunkLordDataChangeNotify = 3232; - public const int PunkLordMonsterInfoScNotify = 3296; - public const int PunkLordMonsterKilledNotify = 3201; - public const int PunkLordRaidTimeOutScNotify = 3270; - public const int PVEBattleResultCsReq = 161; - public const int PVEBattleResultScRsp = 188; - public const int QueryProductInfoCsReq = 40; - public const int QueryProductInfoScRsp = 48; - public const int QuestRecordScNotify = 987; - public const int QuitBattleCsReq = 191; - public const int QuitBattleScNotify = 187; - public const int QuitBattleScRsp = 120; - public const int QuitLineupCsReq = 730; - public const int QuitLineupScRsp = 771; - public const int QuitRogueCsReq = 1855; - public const int QuitRogueScRsp = 1868; - public const int QuitTreasureDungeonCsReq = 4409; - public const int QuitTreasureDungeonScRsp = 4481; - public const int QuitWolfBroGameCsReq = 6530; - public const int QuitWolfBroGameScRsp = 6571; - public const int RaidCollectionDataCsReq = 6949; - public const int RaidCollectionDataScNotify = 6947; - public const int RaidCollectionDataScRsp = 6942; - public const int RaidInfoNotify = 2239; - public const int RaidKickByServerScNotify = 2256; - public const int RankUpAvatarCsReq = 394; - public const int RankUpAvatarScRsp = 396; - public const int RankUpEquipmentCsReq = 587; - public const int RankUpEquipmentScRsp = 527; - public const int ReBattleAfterBattleLoseCsNotify = 147; - public const int RebattleByClientCsNotify = 194; - public const int RechargeSuccNotify = 549; - public const int RecoverAllLineupCsReq = 1468; - public const int RecoverAllLineupScRsp = 1495; - public const int ReEnterLastElementStageCsReq = 1489; - public const int ReEnterLastElementStageScRsp = 1410; - public const int RefreshAlleyOrderCsReq = 4782; - public const int RefreshAlleyOrderScRsp = 4703; - public const int RefreshTriggerByClientCsReq = 1436; - public const int RefreshTriggerByClientScNotify = 1438; - public const int RefreshTriggerByClientScRsp = 1475; - public const int RegionStopScNotify = 3; - public const int RelicRecommendCsReq = 548; - public const int RelicRecommendScRsp = 505; - public const int RemoveRotaterCsReq = 6803; - public const int RemoveRotaterScRsp = 6870; - public const int RemoveStuffFromAreaCsReq = 4330; - public const int RemoveStuffFromAreaScRsp = 4371; - public const int ReplaceLineupCsReq = 709; - public const int ReplaceLineupScRsp = 781; - public const int ReportPlayerCsReq = 2909; - public const int ReportPlayerScRsp = 2981; - public const int ReserveStaminaExchangeCsReq = 25; - public const int ReserveStaminaExchangeScRsp = 72; - public const int ResetMapRotationRegionCsReq = 6847; - public const int ResetMapRotationRegionScRsp = 6894; - public const int RestartChallengePhaseCsReq = 1751; - public const int RestartChallengePhaseScRsp = 1709; - public const int RestoreWolfBroGameArchiveCsReq = 6539; - public const int RestoreWolfBroGameArchiveScRsp = 6573; - public const int RetcodeNotify = 24; - public const int ReturnLastTownCsReq = 1449; - public const int ReturnLastTownScRsp = 1451; - public const int RevcMsgScNotify = 3991; - public const int ReviveRogueAvatarCsReq = 1870; - public const int ReviveRogueAvatarScRsp = 1856; - public const int RogueDoGambleCsReq = 5699; - public const int RogueDoGambleScRsp = 5607; - public const int RogueEndlessActivityBattleEndScNotify = 6006; - public const int RogueGetGambleInfoCsReq = 5641; - public const int RogueGetGambleInfoScRsp = 5635; - public const int RogueModifierAddNotify = 5391; - public const int RogueModifierDelNotify = 5387; - public const int RogueModifierSelectCellCsReq = 5320; - public const int RogueModifierSelectCellScRsp = 5339; - public const int RogueModifierStageStartNotify = 5327; - public const int RogueModifierUpdateNotify = 5371; - public const int RogueNpcDisappearCsReq = 5674; - public const int RogueNpcDisappearScRsp = 5647; - public const int RogueTournAreaUpdateScNotify = 6019; - public const int RogueTournBattleFailSettleInfoScNotify = 6060; - public const int RogueTournClearArchiveNameScNotify = 6081; - public const int RogueTournConfirmSettleCsReq = 6026; - public const int RogueTournConfirmSettleScRsp = 6074; - public const int RogueTournDeleteArchiveCsReq = 6086; - public const int RogueTournDeleteArchiveScRsp = 6096; - public const int RogueTournDifficultyCompNotify = 6079; - public const int RogueTournEnablePermanentTalentCsReq = 6049; - public const int RogueTournEnablePermanentTalentScRsp = 6061; - public const int RogueTournEnterCsReq = 6037; - public const int RogueTournEnterLayerCsReq = 6095; - public const int RogueTournEnterLayerScRsp = 6072; - public const int RogueTournEnterRogueCocoonSceneCsReq = 6092; - public const int RogueTournEnterRogueCocoonSceneScRsp = 6027; - public const int RogueTournEnterRoomCsReq = 6094; - public const int RogueTournEnterRoomScRsp = 6099; - public const int RogueTournEnterScRsp = 6031; - public const int RogueTournExpNotify = 6068; - public const int RogueTournGetAllArchiveCsReq = 6054; - public const int RogueTournGetAllArchiveScRsp = 6022; - public const int RogueTournGetArchiveRepositoryCsReq = 6071; - public const int RogueTournGetArchiveRepositoryScRsp = 6036; - public const int RogueTournGetCurRogueCocoonInfoCsReq = 6018; - public const int RogueTournGetCurRogueCocoonInfoScRsp = 6021; - public const int RogueTournGetMiscRealTimeDataCsReq = 6076; - public const int RogueTournGetMiscRealTimeDataScRsp = 6020; - public const int RogueTournGetPermanentTalentInfoCsReq = 6066; - public const int RogueTournGetPermanentTalentInfoScRsp = 6035; - public const int RogueTournGetSettleInfoCsReq = 6034; - public const int RogueTournGetSettleInfoScRsp = 6052; - public const int RogueTournHandBookNotify = 6091; - public const int RogueTournLeaveCsReq = 6064; - public const int RogueTournLeaveRogueCocoonSceneCsReq = 6100; - public const int RogueTournLeaveRogueCocoonSceneScRsp = 6056; - public const int RogueTournLeaveScRsp = 6059; - public const int RogueTournLevelInfoUpdateScNotify = 6013; - public const int RogueTournQueryCsReq = 6058; - public const int RogueTournQueryScRsp = 6057; - public const int RogueTournReEnterRogueCocoonStageCsReq = 6083; - public const int RogueTournReEnterRogueCocoonStageScRsp = 6015; - public const int RogueTournRenameArchiveCsReq = 6090; - public const int RogueTournRenameArchiveScRsp = 6047; - public const int RogueTournResetPermanentTalentCsReq = 6011; - public const int RogueTournResetPermanentTalentScRsp = 6050; - public const int RogueTournReviveAvatarCsReq = 6038; - public const int RogueTournReviveAvatarScRsp = 6067; - public const int RogueTournRevivieCostUpdateScNotify = 6097; - public const int RogueTournSettleCsReq = 6030; - public const int RogueTournSettleScRsp = 6043; - public const int RogueTournStartCsReq = 6075; - public const int RogueTournStartScRsp = 6040; - public const int RogueTournTakeExpRewardCsReq = 6078; - public const int RogueTournTakeExpRewardScRsp = 6080; - public const int RogueTournWeekChallengeUpdateScNotify = 6044; - public const int RogueWorkbenchHandleFuncCsReq = 5679; - public const int RogueWorkbenchHandleFuncScRsp = 5684; - public const int RogueWorkbenchSelectFuncCsReq = 5678; - public const int RogueWorkbenchSelectFuncScRsp = 5683; - public const int RotateMapCsReq = 6830; - public const int RotateMapScRsp = 6871; - public const int SaveLogisticsCsReq = 4737; - public const int SaveLogisticsScRsp = 4728; - public const int SavePointsInfoNotify = 1458; - public const int SceneCastSkillCostMpCsReq = 1494; - public const int SceneCastSkillCostMpScRsp = 1496; - public const int SceneCastSkillCsReq = 1439; - public const int SceneCastSkillMpUpdateScNotify = 1421; - public const int SceneCastSkillScRsp = 1473; - public const int SceneEnterStageCsReq = 1409; - public const int SceneEnterStageScRsp = 1481; - public const int SceneEntityMoveCsReq = 1461; - public const int SceneEntityMoveScNotify = 1462; - public const int SceneEntityMoveScRsp = 1488; - public const int SceneEntityTeleportCsReq = 1498; - public const int SceneEntityTeleportScRsp = 1486; - public const int SceneGroupRefreshScNotify = 1463; - public const int ScenePlaneEventScNotify = 1479; - public const int SceneReviveAfterRebattleCsReq = 1412; - public const int SceneReviveAfterRebattleScRsp = 1437; - public const int SceneUpdatePositionVersionNotify = 1474; - public const int SearchPlayerCsReq = 2928; - public const int SearchPlayerScRsp = 2901; - public const int SecurityReportCsReq = 4162; - public const int SecurityReportScRsp = 4174; - public const int SelectChatBubbleCsReq = 5191; - public const int SelectChatBubbleScRsp = 5120; - public const int SelectChessRogueNousSubStoryCsReq = 5495; - public const int SelectChessRogueNousSubStoryScRsp = 5463; - public const int SelectChessRogueSubStoryCsReq = 5491; - public const int SelectChessRogueSubStoryScRsp = 5540; - public const int SelectInclinationTextCsReq = 2187; - public const int SelectInclinationTextScRsp = 2127; - public const int SelectPhoneThemeCsReq = 5173; - public const int SelectPhoneThemeScRsp = 5130; - public const int SelectRogueCommonDialogueOptionCsReq = 5657; - public const int SelectRogueCommonDialogueOptionScRsp = 5634; - public const int SellItemCsReq = 570; - public const int SellItemScRsp = 556; - public const int SendMsgCsReq = 3961; - public const int SendMsgScRsp = 3988; - public const int ServerAnnounceNotify = 50; - public const int ServerSimulateBattleFinishScNotify = 174; - public const int SetAetherDivideLineUpCsReq = 4847; - public const int SetAetherDivideLineUpScRsp = 4894; - public const int SetAssistAvatarCsReq = 2874; - public const int SetAssistAvatarScRsp = 2847; - public const int SetAssistCsReq = 2932; - public const int SetAssistScRsp = 2955; - public const int SetBoxingClubResonanceLineupCsReq = 4247; - public const int SetBoxingClubResonanceLineupScRsp = 4294; - public const int SetClientPausedCsReq = 1417; - public const int SetClientPausedScRsp = 1500; - public const int SetClientRaidTargetCountCsReq = 2247; - public const int SetClientRaidTargetCountScRsp = 2294; - public const int SetCurInteractEntityCsReq = 1432; - public const int SetCurInteractEntityScRsp = 1455; - public const int SetCurWaypointCsReq = 491; - public const int SetCurWaypointScRsp = 420; - public const int SetDisplayAvatarCsReq = 2839; - public const int SetDisplayAvatarScRsp = 2873; - public const int SetForbidOtherApplyFriendCsReq = 2905; - public const int SetForbidOtherApplyFriendScRsp = 2966; - public const int SetFriendMarkCsReq = 2990; - public const int SetFriendMarkScRsp = 2918; - public const int SetFriendRemarkNameCsReq = 2949; - public const int SetFriendRemarkNameScRsp = 2951; - public const int SetGameplayBirthdayCsReq = 64; - public const int SetGameplayBirthdayScRsp = 8; - public const int SetGenderCsReq = 54; - public const int SetGenderScRsp = 26; - public const int SetGroupCustomSaveDataCsReq = 1416; - public const int SetGroupCustomSaveDataScRsp = 1465; - public const int SetHeadIconCsReq = 2891; - public const int SetHeadIconScRsp = 2820; - public const int SetHeroBasicTypeCsReq = 32; - public const int SetHeroBasicTypeScRsp = 55; - public const int SetIsDisplayAvatarInfoCsReq = 2830; - public const int SetIsDisplayAvatarInfoScRsp = 2871; - public const int SetLanguageCsReq = 1; - public const int SetLanguageScRsp = 33; - public const int SetLineupNameCsReq = 703; - public const int SetLineupNameScRsp = 770; - public const int SetMissionEventProgressCsReq = 1281; - public const int SetMissionEventProgressScRsp = 1212; - public const int SetNicknameCsReq = 56; - public const int SetNicknameScRsp = 49; - public const int SetPlayerInfoCsReq = 17; - public const int SetPlayerInfoScRsp = 100; - public const int SetRedPointStatusScNotify = 79; - public const int SetRogueCollectionCsReq = 5672; - public const int SetRogueCollectionScRsp = 5653; - public const int SetRogueExhibitionCsReq = 5643; - public const int SetRogueExhibitionScRsp = 5660; - public const int SetSignatureCsReq = 2827; - public const int SetSignatureScRsp = 2862; - public const int SetSpringRecoverConfigCsReq = 1476; - public const int SetSpringRecoverConfigScRsp = 1464; - public const int SetStuffToAreaCsReq = 4339; - public const int SetStuffToAreaScRsp = 4373; - public const int SetTurnFoodSwitchCsReq = 526; - public const int SetTurnFoodSwitchScRsp = 517; - public const int ShareCsReq = 4161; - public const int SharePunkLordMonsterCsReq = 3239; - public const int SharePunkLordMonsterScRsp = 3273; - public const int ShareScRsp = 4188; - public const int ShowNewSupplementVisitorCsReq = 3762; - public const int ShowNewSupplementVisitorScRsp = 3774; - public const int SpaceZooBornCsReq = 6791; - public const int SpaceZooBornScRsp = 6720; - public const int SpaceZooCatUpdateNotify = 6762; - public const int SpaceZooDataCsReq = 6761; - public const int SpaceZooDataScRsp = 6788; - public const int SpaceZooDeleteCatCsReq = 6787; - public const int SpaceZooDeleteCatScRsp = 6727; - public const int SpaceZooExchangeItemCsReq = 6774; - public const int SpaceZooExchangeItemScRsp = 6747; - public const int SpaceZooMutateCsReq = 6739; - public const int SpaceZooMutateScRsp = 6773; - public const int SpaceZooOpCatteryCsReq = 6730; - public const int SpaceZooOpCatteryScRsp = 6771; - public const int SpaceZooTakeCsReq = 6794; - public const int SpaceZooTakeScRsp = 6796; - public const int SpringRecoverCsReq = 1408; - public const int SpringRecoverScRsp = 1446; - public const int SpringRecoverSingleAvatarCsReq = 1444; - public const int SpringRecoverSingleAvatarScRsp = 1424; - public const int SpringRefreshCsReq = 1403; - public const int SpringRefreshScRsp = 1470; - public const int StaminaInfoScNotify = 53; - public const int StarFightDataChangeNotify = 7166; - public const int StartAetherDivideChallengeBattleCsReq = 4830; - public const int StartAetherDivideChallengeBattleScRsp = 4871; - public const int StartAetherDivideSceneBattleCsReq = 4839; - public const int StartAetherDivideSceneBattleScRsp = 4873; - public const int StartAetherDivideStageBattleCsReq = 4849; - public const int StartAetherDivideStageBattleScRsp = 4851; - public const int StartAlleyEventCsReq = 4730; - public const int StartAlleyEventScRsp = 4771; - public const int StartBattleCollegeCsReq = 5720; - public const int StartBattleCollegeScRsp = 5739; - public const int StartBoxingClubBattleCsReq = 4239; - public const int StartBoxingClubBattleScRsp = 4273; - public const int StartChallengeCsReq = 1791; - public const int StartChallengeScRsp = 1720; - public const int StartCocoonStageCsReq = 1413; - public const int StartCocoonStageScRsp = 1485; - public const int StartFinishMainMissionScNotify = 1250; - public const int StartFinishSubMissionScNotify = 1233; - public const int StartMatchCsReq = 7345; - public const int StartMatchScRsp = 7317; - public const int StartPartialChallengeCsReq = 1770; - public const int StartPartialChallengeScRsp = 1756; - public const int StartPunkLordRaidCsReq = 3291; - public const int StartPunkLordRaidScRsp = 3220; - public const int StartRaidCsReq = 2261; - public const int StartRaidScRsp = 2288; - public const int StartRogueCsReq = 1891; - public const int StartRogueScRsp = 1820; - public const int StartStarFightLevelCsReq = 7164; - public const int StartStarFightLevelScRsp = 7165; - public const int StartTimedCocoonStageCsReq = 1431; - public const int StartTimedCocoonStageScRsp = 1497; - public const int StartTimedFarmElementCsReq = 1423; - public const int StartTimedFarmElementScRsp = 1419; - public const int StartTrialActivityCsReq = 2616; - public const int StartTrialActivityScRsp = 2665; - public const int StartWolfBroGameCsReq = 6561; - public const int StartWolfBroGameScRsp = 6588; - public const int StopRogueAdventureRoomCsReq = 5612; - public const int StopRogueAdventureRoomScRsp = 5637; - public const int StoryLineInfoScNotify = 6291; - public const int StoryLineTrialAvatarChangeScNotify = 6230; - public const int StrongChallengeActivityBattleEndScNotify = 6639; - public const int SubMissionRewardScNotify = 1237; - public const int SubmitEmotionItemCsReq = 6339; - public const int SubmitEmotionItemScRsp = 6373; - public const int SubmitMonsterResearchActivityMaterialCsReq = 2670; - public const int SubmitMonsterResearchActivityMaterialScRsp = 2656; - public const int SubmitOfferingItemCsReq = 6927; - public const int SubmitOfferingItemScRsp = 6923; - public const int SubmitOrigamiItemCsReq = 4196; - public const int SubmitOrigamiItemScRsp = 4121; - public const int SummonPunkLordMonsterCsReq = 3230; - public const int SummonPunkLordMonsterScRsp = 3271; - public const int SwapLineupCsReq = 787; - public const int SwapLineupScRsp = 727; - public const int SwitchAetherDivideLineUpSlotCsReq = 4870; - public const int SwitchAetherDivideLineUpSlotScRsp = 4856; - public const int SwitchLineupIndexCsReq = 721; - public const int SwitchLineupIndexScRsp = 782; - public const int SyncAcceptedPamMissionNotify = 4091; - public const int SyncAddBlacklistScNotify = 2903; - public const int SyncApplyFriendScNotify = 2987; - public const int SyncChessRogueMainStoryFinishScNotify = 5486; - public const int SyncChessRogueNousMainStoryScNotify = 5537; - public const int SyncChessRogueNousSubStoryScNotify = 5526; - public const int SyncChessRogueNousValueScNotify = 5469; - public const int SyncClientResVersionCsReq = 130; - public const int SyncClientResVersionScRsp = 171; - public const int SyncDeleteFriendScNotify = 2996; - public const int SyncEntityBuffChangeListScNotify = 1447; - public const int SyncHandleFriendScNotify = 2974; - public const int SyncLineupNotify = 762; - public const int SyncRogueAdventureRoomInfoScNotify = 5661; - public const int SyncRogueAeonLevelUpRewardScNotify = 1814; - public const int SyncRogueAeonScNotify = 1883; - public const int SyncRogueAreaUnlockScNotify = 1879; - public const int SyncRogueCommonActionResultScNotify = 5648; - public const int SyncRogueCommonDialogueDataScNotify = 5698; - public const int SyncRogueCommonDialogueOptionFinishScNotify = 5686; - public const int SyncRogueCommonPendingActionScNotify = 5605; - public const int SyncRogueCommonVirtualItemInfoScNotify = 5618; - public const int SyncRogueExploreWinScNotify = 1858; - public const int SyncRogueFinishScNotify = 1896; - public const int SyncRogueGetItemScNotify = 1884; - public const int SyncRogueHandbookDataUpdateScNotify = 5626; - public const int SyncRogueMapRoomScNotify = 1840; - public const int SyncRoguePickAvatarInfoScNotify = 1892; - public const int SyncRogueReviveInfoScNotify = 1832; - public const int SyncRogueRewardInfoScNotify = 1867; - public const int SyncRogueSeasonFinishScNotify = 1813; - public const int SyncRogueStatusScNotify = 1819; - public const int SyncRogueVirtualItemInfoScNotify = 1823; - public const int SyncServerSceneChangeNotify = 1425; - public const int SyncTaskCsReq = 1273; - public const int SyncTaskScRsp = 1230; - public const int SyncTurnFoodNotify = 554; - public const int TakeActivityExpeditionRewardCsReq = 2594; - public const int TakeActivityExpeditionRewardScRsp = 2596; - public const int TakeAllApRewardCsReq = 3373; - public const int TakeAllApRewardScRsp = 3330; - public const int TakeAllRewardCsReq = 3071; - public const int TakeAllRewardScRsp = 3087; - public const int TakeApRewardCsReq = 3361; - public const int TakeApRewardScRsp = 3388; - public const int TakeAssistRewardCsReq = 2954; - public const int TakeAssistRewardScRsp = 2926; - public const int TakeBpRewardCsReq = 3020; - public const int TakeBpRewardScRsp = 3039; - public const int TakeChallengeRaidRewardCsReq = 2271; - public const int TakeChallengeRaidRewardScRsp = 2287; - public const int TakeChallengeRewardCsReq = 1796; - public const int TakeChallengeRewardScRsp = 1721; - public const int TakeChapterRewardCsReq = 471; - public const int TakeChapterRewardScRsp = 487; - public const int TakeCityShopRewardCsReq = 1539; - public const int TakeCityShopRewardScRsp = 1573; - public const int TakeExpeditionRewardCsReq = 2530; - public const int TakeExpeditionRewardScRsp = 2571; - public const int TakeFightActivityRewardCsReq = 3673; - public const int TakeFightActivityRewardScRsp = 3630; - public const int TakeKilledPunkLordMonsterScoreCsReq = 3233; - public const int TakeKilledPunkLordMonsterScoreScRsp = 3250; - public const int TakeLoginActivityRewardCsReq = 2691; - public const int TakeLoginActivityRewardScRsp = 2620; - public const int TakeMailAttachmentCsReq = 830; - public const int TakeMailAttachmentScRsp = 871; - public const int TakeMonsterResearchActivityRewardCsReq = 2649; - public const int TakeMonsterResearchActivityRewardScRsp = 2651; - public const int TakeMultipleExpeditionRewardCsReq = 2503; - public const int TakeMultipleExpeditionRewardScRsp = 2570; - public const int TakeOffAvatarSkinCsReq = 381; - public const int TakeOffAvatarSkinScRsp = 312; - public const int TakeOffEquipmentCsReq = 362; - public const int TakeOffEquipmentScRsp = 374; - public const int TakeOfferingRewardCsReq = 6939; - public const int TakeOfferingRewardScRsp = 6934; - public const int TakeOffRelicCsReq = 303; - public const int TakeOffRelicScRsp = 370; - public const int TakePictureCsReq = 4139; - public const int TakePictureScRsp = 4173; - public const int TakePrestigeRewardCsReq = 4762; - public const int TakePrestigeRewardScRsp = 4774; - public const int TakePromotionRewardCsReq = 356; - public const int TakePromotionRewardScRsp = 349; - public const int TakePunkLordPointRewardCsReq = 3247; - public const int TakePunkLordPointRewardScRsp = 3294; - public const int TakeQuestOptionalRewardCsReq = 974; - public const int TakeQuestOptionalRewardScRsp = 947; - public const int TakeQuestRewardCsReq = 991; - public const int TakeQuestRewardScRsp = 920; - public const int TakeRogueAeonLevelRewardCsReq = 1869; - public const int TakeRogueAeonLevelRewardScRsp = 1825; - public const int TakeRogueEndlessActivityAllBonusRewardCsReq = 6010; - public const int TakeRogueEndlessActivityAllBonusRewardScRsp = 6009; - public const int TakeRogueEndlessActivityPointRewardCsReq = 6002; - public const int TakeRogueEndlessActivityPointRewardScRsp = 6007; - public const int TakeRogueEventHandbookRewardCsReq = 5693; - public const int TakeRogueEventHandbookRewardScRsp = 5640; - public const int TakeRogueMiracleHandbookRewardCsReq = 5617; - public const int TakeRogueMiracleHandbookRewardScRsp = 5700; - public const int TakeRogueScoreRewardCsReq = 1849; - public const int TakeRogueScoreRewardScRsp = 1851; - public const int TakeRollShopRewardCsReq = 6919; - public const int TakeRollShopRewardScRsp = 6914; - public const int TakeTalkRewardCsReq = 2191; - public const int TakeTalkRewardScRsp = 2120; - public const int TakeTrainVisitorUntakenBehaviorRewardCsReq = 3787; - public const int TakeTrainVisitorUntakenBehaviorRewardScRsp = 3727; - public const int TakeTrialActivityRewardCsReq = 2624; - public const int TakeTrialActivityRewardScRsp = 2642; - public const int TeleportToMissionResetPointCsReq = 1228; - public const int TeleportToMissionResetPointScRsp = 1201; - public const int TelevisionActivityBattleEndScNotify = 6974; - public const int TelevisionActivityDataChangeScNotify = 6967; - public const int TextJoinBatchSaveCsReq = 3839; - public const int TextJoinBatchSaveScRsp = 3873; - public const int TextJoinQueryCsReq = 3891; - public const int TextJoinQueryScRsp = 3820; - public const int TextJoinSaveCsReq = 3861; - public const int TextJoinSaveScRsp = 3888; - public const int TrainRefreshTimeNotify = 3739; - public const int TrainVisitorBehaviorFinishCsReq = 3761; - public const int TrainVisitorBehaviorFinishScRsp = 3788; - public const int TrainVisitorRewardSendNotify = 3773; - public const int TravelBrochureApplyPasterCsReq = 6430; - public const int TravelBrochureApplyPasterListCsReq = 6449; - public const int TravelBrochureApplyPasterListScRsp = 6451; - public const int TravelBrochureApplyPasterScRsp = 6471; - public const int TravelBrochureGetDataCsReq = 6461; - public const int TravelBrochureGetDataScRsp = 6488; - public const int TravelBrochureGetPasterScNotify = 6447; - public const int TravelBrochurePageResetCsReq = 6470; - public const int TravelBrochurePageResetScRsp = 6456; - public const int TravelBrochurePageUnlockScNotify = 6491; - public const int TravelBrochureRemovePasterCsReq = 6487; - public const int TravelBrochureRemovePasterScRsp = 6427; - public const int TravelBrochureSelectMessageCsReq = 6439; - public const int TravelBrochureSelectMessageScRsp = 6473; - public const int TravelBrochureSetCustomValueCsReq = 6496; - public const int TravelBrochureSetCustomValueScRsp = 6421; - public const int TravelBrochureSetPageDescStatusCsReq = 6482; - public const int TravelBrochureSetPageDescStatusScRsp = 6403; - public const int TravelBrochureUpdatePasterPosCsReq = 6462; - public const int TravelBrochureUpdatePasterPosScRsp = 6474; - public const int TreasureDungeonDataScNotify = 4461; - public const int TreasureDungeonFinishScNotify = 4488; - public const int TrialActivityDataChangeScNotify = 2646; - public const int TrialBackGroundMusicCsReq = 3130; - public const int TrialBackGroundMusicScRsp = 3171; - public const int TriggerVoiceCsReq = 4147; - public const int TriggerVoiceScRsp = 4194; - public const int UnlockAvatarSkinScNotify = 337; - public const int UnlockBackGroundMusicCsReq = 3139; - public const int UnlockBackGroundMusicScRsp = 3173; - public const int UnlockChatBubbleScNotify = 5139; - public const int UnlockedAreaMapScNotify = 1459; - public const int UnlockHeadIconScNotify = 2887; - public const int UnlockPhoneThemeScNotify = 5171; - public const int UnlockSkilltreeCsReq = 339; - public const int UnlockSkilltreeScRsp = 373; - public const int UnlockTeleportNotify = 1467; - public const int UnlockTutorialCsReq = 1639; - public const int UnlockTutorialGuideCsReq = 1630; - public const int UnlockTutorialGuideScRsp = 1671; - public const int UnlockTutorialScRsp = 1673; - public const int UpdateEnergyScNotify = 6821; - public const int UpdateFeatureSwitchScNotify = 66; - public const int UpdateFloorSavedValueNotify = 1414; - public const int UpdateGunPlayDataCsReq = 4128; - public const int UpdateGunPlayDataScRsp = 4101; - public const int UpdateMapRotationDataScNotify = 6882; - public const int UpdateMechanismBarScNotify = 1442; - public const int UpdateMovieRacingDataCsReq = 4109; - public const int UpdateMovieRacingDataScRsp = 4181; - public const int UpdatePlayerSettingCsReq = 6; - public const int UpdatePlayerSettingScRsp = 14; - public const int UpdatePsnSettingsInfoCsReq = 63; - public const int UpdatePsnSettingsInfoScRsp = 45; - public const int UpdateRedDotDataCsReq = 5991; - public const int UpdateRedDotDataScRsp = 5920; - public const int UpdateRogueAdventureRoomScoreCsReq = 5666; - public const int UpdateRogueAdventureRoomScoreScRsp = 5690; - public const int UpdateRotaterScNotify = 6856; - public const int UpdateServerPrefsDataCsReq = 6139; - public const int UpdateServerPrefsDataScRsp = 6173; - public const int UpdateTrackMainMissionIdCsReq = 1285; - public const int UpdateTrackMainMissionIdScRsp = 1254; - public const int UpgradeAreaCsReq = 4347; - public const int UpgradeAreaScRsp = 4394; - public const int UpgradeAreaStatCsReq = 4396; - public const int UpgradeAreaStatScRsp = 4321; - public const int UseItemCsReq = 530; - public const int UseItemScRsp = 571; - public const int UseTreasureDungeonItemCsReq = 4449; - public const int UseTreasureDungeonItemScRsp = 4451; - public const int VirtualLineupDestroyNotify = 751; - public const int WaypointShowNewCsNotify = 430; - public const int WolfBroGameActivateBulletCsReq = 6521; - public const int WolfBroGameActivateBulletScRsp = 6582; - public const int WolfBroGameDataChangeScNotify = 6562; - public const int WolfBroGameExplodeMonsterCsReq = 6503; - public const int WolfBroGameExplodeMonsterScRsp = 6570; - public const int WolfBroGamePickupBulletCsReq = 6594; - public const int WolfBroGamePickupBulletScRsp = 6596; - public const int WolfBroGameUseBulletCsReq = 6574; - public const int WolfBroGameUseBulletScRsp = 6547; - } -} + // Packet + public const int AcceptActivityExpeditionCsReq = 2527; + public const int AcceptActivityExpeditionScRsp = 2562; + public const int AcceptedPamMissionExpireCsReq = 4061; + public const int AcceptedPamMissionExpireScRsp = 4088; + public const int AcceptExpeditionCsReq = 2591; + public const int AcceptExpeditionScRsp = 2520; + public const int AcceptMainMissionCsReq = 1232; + public const int AcceptMainMissionScRsp = 1255; + public const int AcceptMissionEventCsReq = 1203; + public const int AcceptMissionEventScRsp = 1270; + public const int AcceptMultipleExpeditionCsReq = 2521; + public const int AcceptMultipleExpeditionScRsp = 2582; + public const int AceAntiCheaterCsReq = 46; + public const int AceAntiCheaterScRsp = 11; + public const int ActivateFarmElementCsReq = 1405; + public const int ActivateFarmElementScRsp = 1466; + public const int AddAvatarScNotify = 347; + public const int AddBlacklistCsReq = 2921; + public const int AddBlacklistScRsp = 2982; + public const int AddEquipmentScNotify = 537; + public const int AetherDivideFinishChallengeScNotify = 4801; + public const int AetherDivideLineupScNotify = 4855; + public const int AetherDivideRefreshEndlessCsReq = 4868; + public const int AetherDivideRefreshEndlessScNotify = 4858; + public const int AetherDivideRefreshEndlessScRsp = 4895; + public const int AetherDivideSkillItemScNotify = 4850; + public const int AetherDivideSpiritExpUpCsReq = 4809; + public const int AetherDivideSpiritExpUpScRsp = 4881; + public const int AetherDivideSpiritInfoScNotify = 4812; + public const int AetherDivideTainerInfoScNotify = 4833; + public const int AetherDivideTakeChallengeRewardCsReq = 4813; + public const int AetherDivideTakeChallengeRewardScRsp = 4885; + public const int AlleyEventChangeNotify = 4787; + public const int AlleyEventEffectNotify = 4727; + public const int AlleyFundsScNotify = 4709; + public const int AlleyGuaranteedFundsCsReq = 4768; + public const int AlleyGuaranteedFundsScRsp = 4795; + public const int AlleyOrderChangedScNotify = 4770; + public const int AlleyPlacingGameCsReq = 4747; + public const int AlleyPlacingGameScRsp = 4794; + public const int AlleyShipmentEventEffectsScNotify = 4733; + public const int AlleyShipUnlockScNotify = 4712; + public const int AlleyShipUsedCountScNotify = 4755; + public const int AlleyShopLevelScNotify = 4781; + public const int AlleyTakeEventRewardCsReq = 4758; + public const int AlleyTakeEventRewardScRsp = 4713; + public const int AntiAddictScNotify = 70; + public const int ApplyFriendCsReq = 2930; + public const int ApplyFriendScRsp = 2971; + public const int ArchiveWolfBroGameCsReq = 6591; + public const int ArchiveWolfBroGameScRsp = 6520; + public const int AvatarExpUpCsReq = 391; + public const int AvatarExpUpScRsp = 320; + public const int BatchGetQuestDataCsReq = 996; + public const int BatchGetQuestDataScRsp = 921; + public const int BatchMarkChatEmojiCsReq = 3947; + public const int BatchMarkChatEmojiScRsp = 3994; + public const int BattleCollegeDataChangeScNotify = 5791; + public const int BattleLogReportCsReq = 127; + public const int BattleLogReportScRsp = 162; + public const int BattlePassInfoNotify = 3061; + public const int BoxingClubChallengeUpdateScNotify = 4227; + public const int BoxingClubRewardScNotify = 4287; + public const int BuyBpLevelCsReq = 3073; + public const int BuyBpLevelScRsp = 3030; + public const int BuyGoodsCsReq = 1591; + public const int BuyGoodsScRsp = 1520; + public const int BuyNpcStuffCsReq = 4391; + public const int BuyNpcStuffScRsp = 4320; + public const int BuyRogueShopBuffCsReq = 5627; + public const int BuyRogueShopBuffScRsp = 5662; + public const int BuyRogueShopMiracleCsReq = 5671; + public const int BuyRogueShopMiracleScRsp = 5687; + public const int CancelActivityExpeditionCsReq = 2574; + public const int CancelActivityExpeditionScRsp = 2547; + public const int CancelCacheNotifyCsReq = 4187; + public const int CancelCacheNotifyScRsp = 4127; + public const int CancelExpeditionCsReq = 2539; + public const int CancelExpeditionScRsp = 2573; + public const int CancelMarkItemNotify = 585; + public const int CancelMatchCsReq = 7320; + public const int CancelMatchScRsp = 7313; + public const int ChallengeBossPhaseSettleNotify = 1737; + public const int ChallengeLineupNotify = 1774; + public const int ChallengeRaidNotify = 2227; + public const int ChallengeSettleNotify = 1730; + public const int ChangeLineupLeaderCsReq = 794; + public const int ChangeLineupLeaderScRsp = 796; + public const int ChangeScriptEmotionCsReq = 6391; + public const int ChangeScriptEmotionScRsp = 6320; + public const int ChangeStoryLineFinishScNotify = 6273; + public const int ChessRogueCellUpdateNotify = 5572; + public const int ChessRogueChangeyAeonDimensionNotify = 5531; + public const int ChessRogueCheatRollCsReq = 5596; + public const int ChessRogueCheatRollScRsp = 5456; + public const int ChessRogueConfirmRollCsReq = 5593; + public const int ChessRogueConfirmRollScRsp = 5555; + public const int ChessRogueEnterCellCsReq = 5532; + public const int ChessRogueEnterCellScRsp = 5562; + public const int ChessRogueEnterCsReq = 5557; + public const int ChessRogueEnterNextLayerCsReq = 5429; + public const int ChessRogueEnterNextLayerScRsp = 5598; + public const int ChessRogueEnterScRsp = 5424; + public const int ChessRogueFinishCurRoomNotify = 5426; + public const int ChessRogueGiveUpCsReq = 5481; + public const int ChessRogueGiveUpRollCsReq = 5560; + public const int ChessRogueGiveUpRollScRsp = 5406; + public const int ChessRogueGiveUpScRsp = 5479; + public const int ChessRogueGoAheadCsReq = 5472; + public const int ChessRogueGoAheadScRsp = 5574; + public const int ChessRogueLayerAccountInfoNotify = 5492; + public const int ChessRogueLeaveCsReq = 5545; + public const int ChessRogueLeaveScRsp = 5513; + public const int ChessRogueMoveCellNotify = 5582; + public const int ChessRogueNousDiceSurfaceUnlockNotify = 5514; + public const int ChessRogueNousDiceUpdateNotify = 5418; + public const int ChessRogueNousEditDiceCsReq = 5464; + public const int ChessRogueNousEditDiceScRsp = 5550; + public const int ChessRogueNousEnableRogueTalentCsReq = 5457; + public const int ChessRogueNousEnableRogueTalentScRsp = 5599; + public const int ChessRogueNousGetRogueTalentInfoCsReq = 5586; + public const int ChessRogueNousGetRogueTalentInfoScRsp = 5577; + public const int ChessRoguePickAvatarCsReq = 5558; + public const int ChessRoguePickAvatarScRsp = 5520; + public const int ChessRogueQueryAeonDimensionsCsReq = 5512; + public const int ChessRogueQueryAeonDimensionsScRsp = 5590; + public const int ChessRogueQueryBpCsReq = 5475; + public const int ChessRogueQueryBpScRsp = 5423; + public const int ChessRogueQueryCsReq = 5517; + public const int ChessRogueQueryScRsp = 5448; + public const int ChessRogueQuestFinishNotify = 5571; + public const int ChessRogueQuitCsReq = 5539; + public const int ChessRogueQuitScRsp = 5575; + public const int ChessRogueReRollDiceCsReq = 5460; + public const int ChessRogueReRollDiceScRsp = 5416; + public const int ChessRogueReviveAvatarCsReq = 5570; + public const int ChessRogueReviveAvatarScRsp = 5522; + public const int ChessRogueRollDiceCsReq = 5563; + public const int ChessRogueRollDiceScRsp = 5508; + public const int ChessRogueSelectBpCsReq = 5450; + public const int ChessRogueSelectBpScRsp = 5415; + public const int ChessRogueSelectCellCsReq = 5591; + public const int ChessRogueSelectCellScRsp = 5442; + public const int ChessRogueSkipTeachingLevelCsReq = 5440; + public const int ChessRogueSkipTeachingLevelScRsp = 5581; + public const int ChessRogueStartCsReq = 5452; + public const int ChessRogueStartScRsp = 5477; + public const int ChessRogueUpdateActionPointScNotify = 5419; + public const int ChessRogueUpdateAeonModifierValueScNotify = 5594; + public const int ChessRogueUpdateAllowedSelectCellScNotify = 5566; + public const int ChessRogueUpdateBoardScNotify = 5488; + public const int ChessRogueUpdateDiceInfoScNotify = 5435; + public const int ChessRogueUpdateDicePassiveAccumulateValueScNotify = 5498; + public const int ChessRogueUpdateLevelBaseInfoScNotify = 5499; + public const int ChessRogueUpdateMoneyInfoScNotify = 5564; + public const int ChessRogueUpdateReviveInfoScNotify = 5402; + public const int ChessRogueUpdateUnlockLevelScNotify = 5454; + public const int ChooseBoxingClubResonanceCsReq = 4262; + public const int ChooseBoxingClubResonanceScRsp = 4274; + public const int ChooseBoxingClubStageOptionalBuffCsReq = 4296; + public const int ChooseBoxingClubStageOptionalBuffScRsp = 4221; + public const int CityShopInfoScNotify = 1530; + public const int ClearAetherDividePassiveSkillCsReq = 4882; + public const int ClearAetherDividePassiveSkillScRsp = 4803; + public const int ClientDownloadDataScNotify = 5; + public const int ClientObjDownloadDataScNotify = 43; + public const int ClientObjUploadCsReq = 60; + public const int ClientObjUploadScRsp = 29; + public const int ClockParkBattleEndScNotify = 7282; + public const int ClockParkFinishScriptScNotify = 7249; + public const int ClockParkGetInfoCsReq = 7261; + public const int ClockParkGetInfoScRsp = 7288; + public const int ClockParkGetOngoingScriptInfoCsReq = 7287; + public const int ClockParkGetOngoingScriptInfoScRsp = 7227; + public const int ClockParkHandleWaitOperationCsReq = 7262; + public const int ClockParkHandleWaitOperationScRsp = 7274; + public const int ClockParkQuitScriptCsReq = 7247; + public const int ClockParkQuitScriptScRsp = 7294; + public const int ClockParkStartScriptCsReq = 7230; + public const int ClockParkStartScriptScRsp = 7271; + public const int ClockParkUnlockTalentCsReq = 7239; + public const int ClockParkUnlockTalentScRsp = 7273; + public const int ClockParkUseBuffCsReq = 7270; + public const int ClockParkUseBuffScRsp = 7256; + public const int CommonRogueComponentUpdateScNotify = 5680; + public const int CommonRogueQueryCsReq = 5644; + public const int CommonRogueQueryScRsp = 5624; + public const int CommonRogueUpdateScNotify = 5642; + public const int ComposeItemCsReq = 547; + public const int ComposeItemScRsp = 594; + public const int ComposeLimitNumCompleteNotify = 533; + public const int ComposeLimitNumUpdateNotify = 550; + public const int ComposeSelectedRelicCsReq = 581; + public const int ComposeSelectedRelicScRsp = 512; + public const int ContentPackageGetDataCsReq = 7495; + public const int ContentPackageGetDataScRsp = 7467; + public const int ContentPackageSyncDataScNotify = 7470; + public const int ContentPackageUnlockCsReq = 7463; + public const int ContentPackageUnlockScRsp = 7474; + public const int CurAssistChangedNotify = 2917; + public const int CurTrialActivityScNotify = 2689; + public const int DailyActiveInfoNotify = 3339; + public const int DailyFirstEnterMonopolyActivityCsReq = 7047; + public const int DailyFirstEnterMonopolyActivityScRsp = 7094; + public const int DailyFirstMeetPamCsReq = 3491; + public const int DailyFirstMeetPamScRsp = 3420; + public const int DailyRefreshNotify = 76; + public const int DailyTaskDataScNotify = 1271; + public const int DeactivateFarmElementCsReq = 1440; + public const int DeactivateFarmElementScRsp = 1448; + public const int DeleteBlacklistCsReq = 2912; + public const int DeleteBlacklistScRsp = 2937; + public const int DeleteFriendCsReq = 2947; + public const int DeleteFriendScRsp = 2994; + public const int DeleteSocialEventServerCacheCsReq = 7098; + public const int DeleteSocialEventServerCacheScRsp = 7086; + public const int DeleteSummonUnitCsReq = 1477; + public const int DeleteSummonUnitScRsp = 1404; + public const int DelMailCsReq = 839; + public const int DelMailScRsp = 873; + public const int DelSaveRaidScNotify = 2270; + public const int DeployRotaterCsReq = 6839; + public const int DeployRotaterScRsp = 6873; + public const int DestroyItemCsReq = 532; + public const int DestroyItemScRsp = 555; + public const int DiscardRelicCsReq = 593; + public const int DiscardRelicScRsp = 540; + public const int DoGachaCsReq = 1991; + public const int DoGachaInRollShopCsReq = 6907; + public const int DoGachaInRollShopScRsp = 6903; + public const int DoGachaScRsp = 1920; + public const int DressAvatarCsReq = 387; + public const int DressAvatarScRsp = 327; + public const int DressAvatarSkinCsReq = 351; + public const int DressAvatarSkinScRsp = 309; + public const int DressRelicAvatarCsReq = 321; + public const int DressRelicAvatarScRsp = 382; + public const int DrinkMakerChallengeCsReq = 6992; + public const int DrinkMakerChallengeScRsp = 6996; + public const int DrinkMakerDayEndScNotify = 6991; + public const int DrinkMakerUpdateTipsNotify = 6990; + public const int EnableRogueTalentCsReq = 1838; + public const int EnableRogueTalentScRsp = 1877; + public const int EndDrinkMakerSequenceCsReq = 6999; + public const int EndDrinkMakerSequenceScRsp = 6994; + public const int EnhanceChessRogueBuffCsReq = 5544; + public const int EnhanceChessRogueBuffScRsp = 5410; + public const int EnhanceCommonRogueBuffCsReq = 5609; + public const int EnhanceCommonRogueBuffScRsp = 5681; + public const int EnhanceRogueBuffCsReq = 1812; + public const int EnhanceRogueBuffScRsp = 1837; + public const int EnterAdventureCsReq = 1361; + public const int EnterAdventureScRsp = 1388; + public const int EnterAetherDivideSceneCsReq = 4861; + public const int EnterAetherDivideSceneScRsp = 4888; + public const int EnterChallengeNextPhaseCsReq = 1781; + public const int EnterChallengeNextPhaseScRsp = 1712; + public const int EnterChessRogueAeonRoomCsReq = 5433; + public const int EnterChessRogueAeonRoomScRsp = 5494; + public const int EnteredSceneChangeScNotify = 1402; + public const int EnterFantasticStoryActivityStageCsReq = 4920; + public const int EnterFantasticStoryActivityStageScRsp = 4939; + public const int EnterFeverTimeActivityStageCsReq = 7158; + public const int EnterFeverTimeActivityStageScRsp = 7151; + public const int EnterFightActivityStageCsReq = 3620; + public const int EnterFightActivityStageScRsp = 3639; + public const int EnterMapRotationRegionCsReq = 6861; + public const int EnterMapRotationRegionScRsp = 6888; + public const int EnterRogueCsReq = 1839; + public const int EnterRogueEndlessActivityStageCsReq = 6004; + public const int EnterRogueEndlessActivityStageScRsp = 6005; + public const int EnterRogueMapRoomCsReq = 1826; + public const int EnterRogueMapRoomScRsp = 1817; + public const int EnterRogueScRsp = 1873; + public const int EnterSceneByServerScNotify = 1483; + public const int EnterSceneCsReq = 1480; + public const int EnterSceneScRsp = 1478; + public const int EnterSectionCsReq = 1428; + public const int EnterSectionScRsp = 1401; + public const int EnterStrongChallengeActivityStageCsReq = 6691; + public const int EnterStrongChallengeActivityStageScRsp = 6620; + public const int EnterTelevisionActivityStageCsReq = 6963; + public const int EnterTelevisionActivityStageScRsp = 6979; + public const int EnterTreasureDungeonCsReq = 4447; + public const int EnterTreasureDungeonScRsp = 4494; + public const int EnterTrialActivityStageCsReq = 2611; + public const int EnterTrialActivityStageScRsp = 2644; + public const int EntityBindPropCsReq = 1454; + public const int EntityBindPropScRsp = 1426; + public const int EquipAetherDividePassiveSkillCsReq = 4896; + public const int EquipAetherDividePassiveSkillScRsp = 4821; + public const int EvolveBuildCoinNotify = 7136; + public const int EvolveBuildFinishScNotify = 7140; + public const int EvolveBuildGiveupCsReq = 7133; + public const int EvolveBuildGiveupScRsp = 7103; + public const int EvolveBuildLeaveCsReq = 7127; + public const int EvolveBuildLeaveScRsp = 7106; + public const int EvolveBuildQueryInfoCsReq = 7145; + public const int EvolveBuildQueryInfoScRsp = 7117; + public const int EvolveBuildReRandomStageCsReq = 7105; + public const int EvolveBuildReRandomStageScRsp = 7129; + public const int EvolveBuildShopAbilityDownCsReq = 7148; + public const int EvolveBuildShopAbilityDownScRsp = 7143; + public const int EvolveBuildShopAbilityResetCsReq = 7131; + public const int EvolveBuildShopAbilityResetScRsp = 7108; + public const int EvolveBuildShopAbilityUpCsReq = 7107; + public const int EvolveBuildShopAbilityUpScRsp = 7114; + public const int EvolveBuildStartLevelCsReq = 7120; + public const int EvolveBuildStartLevelScRsp = 7113; + public const int EvolveBuildStartStageCsReq = 7124; + public const int EvolveBuildStartStageScRsp = 7128; + public const int EvolveBuildTakeExpRewardCsReq = 7150; + public const int EvolveBuildTakeExpRewardScRsp = 7115; + public const int EvolveBuildUnlockInfoNotify = 7132; + public const int ExchangeGachaCeilingCsReq = 1930; + public const int ExchangeGachaCeilingScRsp = 1971; + public const int ExchangeHcoinCsReq = 551; + public const int ExchangeHcoinScRsp = 509; + public const int ExchangeRogueBuffWithMiracleCsReq = 5670; + public const int ExchangeRogueBuffWithMiracleScRsp = 5656; + public const int ExchangeRogueRewardKeyCsReq = 1842; + public const int ExchangeRogueRewardKeyScRsp = 1816; + public const int ExchangeStaminaCsReq = 94; + public const int ExchangeStaminaScRsp = 96; + public const int ExpeditionDataChangeScNotify = 2587; + public const int ExpUpEquipmentCsReq = 562; + public const int ExpUpEquipmentScRsp = 574; + public const int ExpUpRelicCsReq = 596; + public const int ExpUpRelicScRsp = 521; + public const int ExtraLineupDestroyNotify = 712; + public const int FantasticStoryActivityBattleEndScNotify = 4973; + public const int FeatureSwitchClosedScNotify = 57; + public const int FeverTimeActivityBattleEndScNotify = 7154; + public const int FightActivityDataChangeScNotify = 3691; + public const int FightEnterCsReq = 30061; + public const int FightEnterScRsp = 30088; + public const int FightHeartBeatCsReq = 30039; + public const int FightHeartBeatScRsp = 30073; + public const int FightKickOutScNotify = 30020; + public const int FightLeaveScNotify = 30091; + public const int FightMatch3ChatCsReq = 30187; + public const int FightMatch3ChatScNotify = 30162; + public const int FightMatch3ChatScRsp = 30127; + public const int FightMatch3DataCsReq = 30161; + public const int FightMatch3DataScRsp = 30188; + public const int FightMatch3ForceUpdateNotify = 30174; + public const int FightMatch3OpponentDataScNotify = 30171; + public const int FightMatch3StartCountDownScNotify = 30191; + public const int FightMatch3SwapCsReq = 30173; + public const int FightMatch3SwapScRsp = 30130; + public const int FightMatch3TurnEndScNotify = 30139; + public const int FightMatch3TurnStartScNotify = 30120; + public const int FightSessionStopScNotify = 30030; + public const int FightTreasureDungeonMonsterCsReq = 4482; + public const int FightTreasureDungeonMonsterScRsp = 4403; + public const int FinishAeonDialogueGroupCsReq = 1852; + public const int FinishAeonDialogueGroupScRsp = 1802; + public const int FinishChapterScNotify = 4991; + public const int FinishChessRogueNousSubStoryCsReq = 5535; + public const int FinishChessRogueNousSubStoryScRsp = 5455; + public const int FinishChessRogueSubStoryCsReq = 5405; + public const int FinishChessRogueSubStoryScRsp = 5592; + public const int FinishCosumeItemMissionCsReq = 1247; + public const int FinishCosumeItemMissionScRsp = 1294; + public const int FinishCurTurnCsReq = 4362; + public const int FinishCurTurnScRsp = 4374; + public const int FinishEmotionDialoguePerformanceCsReq = 6330; + public const int FinishEmotionDialoguePerformanceScRsp = 6371; + public const int FinishFirstTalkByPerformanceNpcCsReq = 2147; + public const int FinishFirstTalkByPerformanceNpcScRsp = 2194; + public const int FinishFirstTalkNpcCsReq = 2130; + public const int FinishFirstTalkNpcScRsp = 2171; + public const int FinishItemIdCsReq = 2739; + public const int FinishItemIdScRsp = 2773; + public const int FinishPerformSectionIdCsReq = 2787; + public const int FinishPerformSectionIdScRsp = 2727; + public const int FinishPlotCsReq = 1161; + public const int FinishPlotScRsp = 1188; + public const int FinishQuestCsReq = 927; + public const int FinishQuestScRsp = 962; + public const int FinishRogueCommonDialogueCsReq = 5689; + public const int FinishRogueCommonDialogueScRsp = 5610; + public const int FinishSectionIdCsReq = 2730; + public const int FinishSectionIdScRsp = 2771; + public const int FinishTalkMissionCsReq = 1291; + public const int FinishTalkMissionScRsp = 1220; + public const int FinishTutorialCsReq = 1687; + public const int FinishTutorialGuideCsReq = 1662; + public const int FinishTutorialGuideScRsp = 1674; + public const int FinishTutorialScRsp = 1627; + public const int GameplayCounterCountDownCsReq = 1443; + public const int GameplayCounterCountDownScRsp = 1460; + public const int GameplayCounterRecoverCsReq = 1445; + public const int GameplayCounterRecoverScRsp = 1415; + public const int GameplayCounterUpdateScNotify = 1429; + public const int GateServerScNotify = 65; + public const int GeneralVirtualItemDataNotify = 600; + public const int GetActivityScheduleConfigCsReq = 2639; + public const int GetActivityScheduleConfigScRsp = 2673; + public const int GetAetherDivideChallengeInfoCsReq = 4837; + public const int GetAetherDivideChallengeInfoScRsp = 4828; + public const int GetAetherDivideInfoCsReq = 4862; + public const int GetAetherDivideInfoScRsp = 4874; + public const int GetAlleyInfoCsReq = 4761; + public const int GetAlleyInfoScRsp = 4788; + public const int GetAllLineupDataCsReq = 756; + public const int GetAllLineupDataScRsp = 749; + public const int GetAllRedDotDataCsReq = 5961; + public const int GetAllRedDotDataScRsp = 5988; + public const int GetAllSaveRaidCsReq = 2282; + public const int GetAllSaveRaidScRsp = 2203; + public const int GetAllServerPrefsDataCsReq = 6161; + public const int GetAllServerPrefsDataScRsp = 6188; + public const int GetArchiveDataCsReq = 2361; + public const int GetArchiveDataScRsp = 2388; + public const int GetAssistHistoryCsReq = 2958; + public const int GetAssistHistoryScRsp = 2913; + public const int GetAssistListCsReq = 2933; + public const int GetAssistListScRsp = 2950; + public const int GetAuthkeyCsReq = 21; + public const int GetAuthkeyScRsp = 82; + public const int GetAvatarDataCsReq = 361; + public const int GetAvatarDataScRsp = 388; + public const int GetBagCsReq = 561; + public const int GetBagScRsp = 588; + public const int GetBasicInfoCsReq = 90; + public const int GetBasicInfoScRsp = 18; + public const int GetBattleCollegeDataCsReq = 5761; + public const int GetBattleCollegeDataScRsp = 5788; + public const int GetBoxingClubInfoCsReq = 4261; + public const int GetBoxingClubInfoScRsp = 4288; + public const int GetChallengeCsReq = 1761; + public const int GetChallengeGroupStatisticsCsReq = 1782; + public const int GetChallengeGroupStatisticsScRsp = 1703; + public const int GetChallengeRaidInfoCsReq = 2273; + public const int GetChallengeRaidInfoScRsp = 2230; + public const int GetChallengeScRsp = 1788; + public const int GetChapterCsReq = 439; + public const int GetChapterScRsp = 473; + public const int GetChatEmojiListCsReq = 3987; + public const int GetChatEmojiListScRsp = 3927; + public const int GetChatFriendHistoryCsReq = 3930; + public const int GetChatFriendHistoryScRsp = 3971; + public const int GetChessRogueBuffEnhanceInfoCsReq = 5414; + public const int GetChessRogueBuffEnhanceInfoScRsp = 5524; + public const int GetChessRogueNousStoryInfoCsReq = 5431; + public const int GetChessRogueNousStoryInfoScRsp = 5444; + public const int GetChessRogueStoryAeonTalkInfoCsReq = 5502; + public const int GetChessRogueStoryAeonTalkInfoScRsp = 5465; + public const int GetChessRogueStoryInfoCsReq = 5542; + public const int GetChessRogueStoryInfoScRsp = 5515; + public const int GetCrossInfoCsReq = 7328; + public const int GetCrossInfoScRsp = 7333; + public const int GetCurAssistCsReq = 2968; + public const int GetCurAssistScRsp = 2995; + public const int GetCurBattleInfoCsReq = 139; + public const int GetCurBattleInfoScRsp = 173; + public const int GetCurChallengeCsReq = 1727; + public const int GetCurChallengeScRsp = 1762; + public const int GetCurLineupDataCsReq = 791; + public const int GetCurLineupDataScRsp = 720; + public const int GetCurSceneInfoCsReq = 1430; + public const int GetCurSceneInfoScRsp = 1471; + public const int GetDailyActiveInfoCsReq = 3391; + public const int GetDailyActiveInfoScRsp = 3320; + public const int GetDrinkMakerDataCsReq = 6989; + public const int GetDrinkMakerDataScRsp = 6982; + public const int GetEnhanceCommonRogueBuffInfoCsReq = 5649; + public const int GetEnhanceCommonRogueBuffInfoScRsp = 5651; + public const int GetEnteredSceneCsReq = 1407; + public const int GetEnteredSceneScRsp = 1452; + public const int GetExhibitScNotify = 4327; + public const int GetExpeditionDataCsReq = 2561; + public const int GetExpeditionDataScRsp = 2588; + public const int GetFantasticStoryActivityDataCsReq = 4961; + public const int GetFantasticStoryActivityDataScRsp = 4988; + public const int GetFarmStageGachaInfoCsReq = 1391; + public const int GetFarmStageGachaInfoScRsp = 1320; + public const int GetFeverTimeActivityDataCsReq = 7155; + public const int GetFeverTimeActivityDataScRsp = 7156; + public const int GetFightActivityDataCsReq = 3661; + public const int GetFightActivityDataScRsp = 3688; + public const int GetFirstTalkByPerformanceNpcCsReq = 2162; + public const int GetFirstTalkByPerformanceNpcScRsp = 2174; + public const int GetFirstTalkNpcCsReq = 2139; + public const int GetFirstTalkNpcScRsp = 2173; + public const int GetFriendApplyListInfoCsReq = 2939; + public const int GetFriendApplyListInfoScRsp = 2973; + public const int GetFriendAssistListCsReq = 2976; + public const int GetFriendAssistListScRsp = 2964; + public const int GetFriendBattleRecordDetailCsReq = 2924; + public const int GetFriendBattleRecordDetailScRsp = 2942; + public const int GetFriendChallengeDetailCsReq = 2911; + public const int GetFriendChallengeDetailScRsp = 2944; + public const int GetFriendChallengeLineupCsReq = 2908; + public const int GetFriendChallengeLineupScRsp = 2946; + public const int GetFriendDevelopmentInfoCsReq = 2916; + public const int GetFriendDevelopmentInfoScRsp = 2965; + public const int GetFriendListInfoCsReq = 2961; + public const int GetFriendListInfoScRsp = 2988; + public const int GetFriendLoginInfoCsReq = 2940; + public const int GetFriendLoginInfoScRsp = 2948; + public const int GetFriendRecommendListInfoCsReq = 2970; + public const int GetFriendRecommendListInfoScRsp = 2956; + public const int GetGachaCeilingCsReq = 1939; + public const int GetGachaCeilingScRsp = 1973; + public const int GetGachaInfoCsReq = 1961; + public const int GetGachaInfoScRsp = 1988; + public const int GetGunPlayDataCsReq = 4112; + public const int GetGunPlayDataScRsp = 4137; + public const int GetHeartDialInfoCsReq = 6361; + public const int GetHeartDialInfoScRsp = 6388; + public const int GetHeroBasicTypeInfoCsReq = 68; + public const int GetHeroBasicTypeInfoScRsp = 95; + public const int GetJukeboxDataCsReq = 3161; + public const int GetJukeboxDataScRsp = 3188; + public const int GetKilledPunkLordMonsterDataCsReq = 3281; + public const int GetKilledPunkLordMonsterDataScRsp = 3212; + public const int GetLevelRewardCsReq = 81; + public const int GetLevelRewardScRsp = 12; + public const int GetLevelRewardTakenListCsReq = 51; + public const int GetLevelRewardTakenListScRsp = 9; + public const int GetLineupAvatarDataCsReq = 774; + public const int GetLineupAvatarDataScRsp = 747; + public const int GetLoginActivityCsReq = 2661; + public const int GetLoginActivityScRsp = 2688; + public const int GetLoginChatInfoCsReq = 3996; + public const int GetLoginChatInfoScRsp = 3921; + public const int GetMailCsReq = 861; + public const int GetMailScRsp = 888; + public const int GetMainMissionCustomValueCsReq = 1268; + public const int GetMainMissionCustomValueScRsp = 1295; + public const int GetMapRotationDataCsReq = 6862; + public const int GetMapRotationDataScRsp = 6874; + public const int GetMarkItemListCsReq = 568; + public const int GetMarkItemListScRsp = 595; + public const int GetMbtiReportCsReq = 7042; + public const int GetMbtiReportScRsp = 7016; + public const int GetMissionDataCsReq = 1261; + public const int GetMissionDataScRsp = 1288; + public const int GetMissionEventDataCsReq = 1296; + public const int GetMissionEventDataScRsp = 1221; + public const int GetMissionStatusCsReq = 1256; + public const int GetMissionStatusScRsp = 1249; + public const int GetMonopolyDailyReportCsReq = 7041; + public const int GetMonopolyDailyReportScRsp = 7035; + public const int GetMonopolyFriendRankingListCsReq = 7008; + public const int GetMonopolyFriendRankingListScRsp = 7046; + public const int GetMonopolyInfoCsReq = 7061; + public const int GetMonopolyInfoScRsp = 7088; + public const int GetMonopolyMbtiReportRewardCsReq = 7045; + public const int GetMonopolyMbtiReportRewardScRsp = 7015; + public const int GetMonsterResearchActivityDataCsReq = 2682; + public const int GetMonsterResearchActivityDataScRsp = 2603; + public const int GetMovieRacingDataCsReq = 4149; + public const int GetMovieRacingDataScRsp = 4151; + public const int GetMultipleDropInfoCsReq = 4661; + public const int GetMultipleDropInfoScRsp = 4688; + public const int GetMuseumInfoCsReq = 4361; + public const int GetMuseumInfoScRsp = 4388; + public const int GetNpcMessageGroupCsReq = 2761; + public const int GetNpcMessageGroupScRsp = 2788; + public const int GetNpcStatusCsReq = 2791; + public const int GetNpcStatusScRsp = 2720; + public const int GetNpcTakenRewardCsReq = 2161; + public const int GetNpcTakenRewardScRsp = 2188; + public const int GetOfferingInfoCsReq = 6929; + public const int GetOfferingInfoScRsp = 6922; + public const int GetPhoneDataCsReq = 5161; + public const int GetPhoneDataScRsp = 5188; + public const int GetPlatformPlayerInfoCsReq = 3000; + public const int GetPlatformPlayerInfoScRsp = 2993; + public const int GetPlayerBoardDataCsReq = 2861; + public const int GetPlayerBoardDataScRsp = 2888; + public const int GetPlayerDetailInfoCsReq = 2991; + public const int GetPlayerDetailInfoScRsp = 2920; + public const int GetPlayerReplayInfoCsReq = 3591; + public const int GetPlayerReplayInfoScRsp = 3520; + public const int GetPlayerReturnMultiDropInfoCsReq = 4620; + public const int GetPlayerReturnMultiDropInfoScRsp = 4639; + public const int GetPrivateChatHistoryCsReq = 3939; + public const int GetPrivateChatHistoryScRsp = 3973; + public const int GetPunkLordBattleRecordCsReq = 3255; + public const int GetPunkLordBattleRecordScRsp = 3268; + public const int GetPunkLordDataCsReq = 3221; + public const int GetPunkLordDataScRsp = 3282; + public const int GetPunkLordMonsterDataCsReq = 3261; + public const int GetPunkLordMonsterDataScRsp = 3288; + public const int GetQuestDataCsReq = 961; + public const int GetQuestDataScRsp = 988; + public const int GetQuestRecordCsReq = 930; + public const int GetQuestRecordScRsp = 971; + public const int GetRaidInfoCsReq = 2262; + public const int GetRaidInfoScRsp = 2274; + public const int GetRecyleTimeCsReq = 528; + public const int GetRecyleTimeScRsp = 501; + public const int GetReplayTokenCsReq = 3561; + public const int GetReplayTokenScRsp = 3588; + public const int GetRndOptionCsReq = 3461; + public const int GetRndOptionScRsp = 3488; + public const int GetRogueAdventureRoomInfoCsReq = 5694; + public const int GetRogueAdventureRoomInfoScRsp = 5696; + public const int GetRogueAeonInfoCsReq = 1899; + public const int GetRogueAeonInfoScRsp = 1807; + public const int GetRogueBuffEnhanceInfoCsReq = 1809; + public const int GetRogueBuffEnhanceInfoScRsp = 1881; + public const int GetRogueCollectionCsReq = 5669; + public const int GetRogueCollectionScRsp = 5625; + public const int GetRogueCommonDialogueDataCsReq = 5616; + public const int GetRogueCommonDialogueDataScRsp = 5665; + public const int GetRogueEndlessActivityDataCsReq = 6008; + public const int GetRogueEndlessActivityDataScRsp = 6001; + public const int GetRogueExhibitionCsReq = 5606; + public const int GetRogueExhibitionScRsp = 5614; + public const int GetRogueHandbookDataCsReq = 5685; + public const int GetRogueHandbookDataScRsp = 5654; + public const int GetRogueInfoCsReq = 1861; + public const int GetRogueInfoScRsp = 1888; + public const int GetRogueInitialScoreCsReq = 1900; + public const int GetRogueInitialScoreScRsp = 1893; + public const int GetRogueScoreRewardInfoCsReq = 1843; + public const int GetRogueScoreRewardInfoScRsp = 1860; + public const int GetRogueShopBuffInfoCsReq = 5673; + public const int GetRogueShopBuffInfoScRsp = 5630; + public const int GetRogueShopMiracleInfoCsReq = 5620; + public const int GetRogueShopMiracleInfoScRsp = 5639; + public const int GetRogueTalentInfoCsReq = 1836; + public const int GetRogueTalentInfoScRsp = 1875; + public const int GetRollShopInfoCsReq = 6909; + public const int GetRollShopInfoScRsp = 6902; + public const int GetSaveLogisticsMapCsReq = 4750; + public const int GetSaveLogisticsMapScRsp = 4732; + public const int GetSaveRaidCsReq = 2296; + public const int GetSaveRaidScRsp = 2221; + public const int GetSceneMapInfoCsReq = 1484; + public const int GetSceneMapInfoScRsp = 1469; + public const int GetSecretKeyInfoCsReq = 10; + public const int GetSecretKeyInfoScRsp = 98; + public const int GetServerPrefsDataCsReq = 6191; + public const int GetServerPrefsDataScRsp = 6120; + public const int GetShareDataCsReq = 4191; + public const int GetShareDataScRsp = 4120; + public const int GetShopListCsReq = 1561; + public const int GetShopListScRsp = 1588; + public const int GetSingleRedDotParamGroupCsReq = 5939; + public const int GetSingleRedDotParamGroupScRsp = 5973; + public const int GetSocialEventServerCacheCsReq = 7089; + public const int GetSocialEventServerCacheScRsp = 7010; + public const int GetSpringRecoverDataCsReq = 1490; + public const int GetSpringRecoverDataScRsp = 1418; + public const int GetStageLineupCsReq = 761; + public const int GetStageLineupScRsp = 788; + public const int GetStarFightDataCsReq = 7168; + public const int GetStarFightDataScRsp = 7161; + public const int GetStoryLineInfoCsReq = 6261; + public const int GetStoryLineInfoScRsp = 6288; + public const int GetStrongChallengeActivityDataCsReq = 6661; + public const int GetStrongChallengeActivityDataScRsp = 6688; + public const int GetStuffScNotify = 4387; + public const int GetTelevisionActivityDataCsReq = 6969; + public const int GetTelevisionActivityDataScRsp = 6962; + public const int GetTrainVisitorBehaviorCsReq = 3791; + public const int GetTrainVisitorBehaviorScRsp = 3720; + public const int GetTrainVisitorRegisterCsReq = 3730; + public const int GetTrainVisitorRegisterScRsp = 3771; + public const int GetTreasureDungeonActivityDataCsReq = 4462; + public const int GetTreasureDungeonActivityDataScRsp = 4474; + public const int GetTrialActivityDataCsReq = 2664; + public const int GetTrialActivityDataScRsp = 2608; + public const int GetTutorialCsReq = 1661; + public const int GetTutorialGuideCsReq = 1691; + public const int GetTutorialGuideScRsp = 1620; + public const int GetTutorialScRsp = 1688; + public const int GetUnlockTeleportCsReq = 1472; + public const int GetUnlockTeleportScRsp = 1453; + public const int GetUpdatedArchiveDataCsReq = 2391; + public const int GetUpdatedArchiveDataScRsp = 2320; + public const int GetVideoVersionKeyCsReq = 78; + public const int GetVideoVersionKeyScRsp = 83; + public const int GetWaypointCsReq = 461; + public const int GetWaypointScRsp = 488; + public const int GetWolfBroGameDataCsReq = 6587; + public const int GetWolfBroGameDataScRsp = 6527; + public const int GiveUpBoxingClubChallengeCsReq = 4230; + public const int GiveUpBoxingClubChallengeScRsp = 4271; + public const int GmTalkCsReq = 27; + public const int GmTalkScNotify = 71; + public const int GmTalkScRsp = 62; + public const int GroupStateChangeCsReq = 1441; + public const int GroupStateChangeScNotify = 1499; + public const int GroupStateChangeScRsp = 1435; + public const int HandleFriendCsReq = 2927; + public const int HandleFriendScRsp = 2962; + public const int HandleRogueCommonPendingActionCsReq = 5646; + public const int HandleRogueCommonPendingActionScRsp = 5611; + public const int HealPoolInfoNotify = 1411; + public const int HeartDialScriptChangeScNotify = 6387; + public const int HeartDialTraceScriptCsReq = 6327; + public const int HeartDialTraceScriptScRsp = 6362; + public const int HeliobusActivityDataCsReq = 5861; + public const int HeliobusActivityDataScRsp = 5888; + public const int HeliobusChallengeUpdateScNotify = 5881; + public const int HeliobusEnterBattleCsReq = 5856; + public const int HeliobusEnterBattleScRsp = 5849; + public const int HeliobusInfoChangedScNotify = 5874; + public const int HeliobusLineupUpdateScNotify = 5812; + public const int HeliobusSelectSkillCsReq = 5821; + public const int HeliobusSelectSkillScRsp = 5882; + public const int HeliobusSnsCommentCsReq = 5887; + public const int HeliobusSnsCommentScRsp = 5827; + public const int HeliobusSnsLikeCsReq = 5830; + public const int HeliobusSnsLikeScRsp = 5871; + public const int HeliobusSnsPostCsReq = 5839; + public const int HeliobusSnsPostScRsp = 5873; + public const int HeliobusSnsReadCsReq = 5891; + public const int HeliobusSnsReadScRsp = 5820; + public const int HeliobusSnsUpdateScNotify = 5862; + public const int HeliobusStartRaidCsReq = 5851; + public const int HeliobusStartRaidScRsp = 5809; + public const int HeliobusUnlockSkillScNotify = 5896; + public const int HeliobusUpgradeLevelCsReq = 5847; + public const int HeliobusUpgradeLevelScRsp = 5894; + public const int HeroBasicTypeChangedNotify = 93; + public const int InteractChargerCsReq = 6891; + public const int InteractChargerScRsp = 6820; + public const int InteractPropCsReq = 1491; + public const int InteractPropScRsp = 1420; + public const int InteractTreasureDungeonGridCsReq = 4470; + public const int InteractTreasureDungeonGridScRsp = 4456; + public const int InterruptMissionEventCsReq = 1251; + public const int InterruptMissionEventScRsp = 1209; + public const int JoinLineupCsReq = 739; + public const int JoinLineupScRsp = 773; + public const int LastSpringRefreshTimeNotify = 1456; + public const int LeaveAetherDivideSceneCsReq = 4891; + public const int LeaveAetherDivideSceneScRsp = 4820; + public const int LeaveChallengeCsReq = 1739; + public const int LeaveChallengeScRsp = 1773; + public const int LeaveMapRotationRegionCsReq = 6887; + public const int LeaveMapRotationRegionScNotify = 6896; + public const int LeaveMapRotationRegionScRsp = 6827; + public const int LeaveRaidCsReq = 2291; + public const int LeaveRaidScRsp = 2220; + public const int LeaveRogueCsReq = 1830; + public const int LeaveRogueScRsp = 1871; + public const int LeaveTrialActivityCsReq = 2657; + public const int LeaveTrialActivityScRsp = 2634; + public const int LobbyBeginCsReq = 7374; + public const int LobbyBeginScRsp = 7378; + public const int LobbyCreateCsReq = 7395; + public const int LobbyCreateScRsp = 7367; + public const int LobbyGetInfoCsReq = 7364; + public const int LobbyGetInfoScRsp = 7398; + public const int LobbyInviteCsReq = 7355; + public const int LobbyInviteScNotify = 7357; + public const int LobbyInviteScRsp = 7379; + public const int LobbyJoinCsReq = 7370; + public const int LobbyJoinScRsp = 7363; + public const int LobbyKickOutCsReq = 7377; + public const int LobbyKickOutScRsp = 7356; + public const int LobbyModifyPlayerInfoCsReq = 7383; + public const int LobbyModifyPlayerInfoScRsp = 7353; + public const int LobbyQuitCsReq = 7387; + public const int LobbyQuitScRsp = 7359; + public const int LobbySyncInfoScNotify = 7390; + public const int LockEquipmentCsReq = 539; + public const int LockEquipmentScRsp = 573; + public const int LockRelicCsReq = 582; + public const int LockRelicScRsp = 503; + public const int LogisticsDetonateStarSkiffCsReq = 4785; + public const int LogisticsDetonateStarSkiffScRsp = 4754; + public const int LogisticsGameCsReq = 4791; + public const int LogisticsGameScRsp = 4720; + public const int LogisticsInfoScNotify = 4701; + public const int LogisticsScoreRewardSyncInfoScNotify = 4726; + public const int MakeDrinkCsReq = 6987; + public const int MakeDrinkScRsp = 6983; + public const int MakeMissionDrinkCsReq = 6995; + public const int MakeMissionDrinkScRsp = 6993; + public const int MarkAvatarCsReq = 328; + public const int MarkAvatarScRsp = 301; + public const int MarkChatEmojiCsReq = 3962; + public const int MarkChatEmojiScRsp = 3974; + public const int MarkItemCsReq = 558; + public const int MarkItemScRsp = 513; + public const int MarkReadMailCsReq = 891; + public const int MarkReadMailScRsp = 820; + public const int MatchBoxingClubOpponentCsReq = 4291; + public const int MatchBoxingClubOpponentScRsp = 4220; + public const int MatchResultScNotify = 7324; + public const int MatchThreeGetDataCsReq = 7445; + public const int MatchThreeGetDataScRsp = 7417; + public const int MatchThreeLevelEndCsReq = 7420; + public const int MatchThreeLevelEndScRsp = 7413; + public const int MatchThreeSetBirdPosCsReq = 7428; + public const int MatchThreeSetBirdPosScRsp = 7433; + public const int MatchThreeSyncDataScNotify = 7424; + public const int MissionAcceptScNotify = 1258; + public const int MissionEventRewardScNotify = 1282; + public const int MissionGroupWarnScNotify = 1274; + public const int MissionRewardScNotify = 1239; + public const int MonopolyAcceptQuizCsReq = 7085; + public const int MonopolyAcceptQuizScRsp = 7054; + public const int MonopolyActionResultScNotify = 7091; + public const int MonopolyBuyGoodsCsReq = 7049; + public const int MonopolyBuyGoodsScRsp = 7051; + public const int MonopolyCellUpdateNotify = 7020; + public const int MonopolyCheatDiceCsReq = 7028; + public const int MonopolyCheatDiceScRsp = 7001; + public const int MonopolyClickCellCsReq = 7099; + public const int MonopolyClickCellScRsp = 7007; + public const int MonopolyClickMbtiReportCsReq = 7075; + public const int MonopolyClickMbtiReportScRsp = 7038; + public const int MonopolyConditionUpdateScNotify = 7036; + public const int MonopolyConfirmRandomCsReq = 7070; + public const int MonopolyConfirmRandomScRsp = 7056; + public const int MonopolyContentUpdateScNotify = 7033; + public const int MonopolyDailySettleScNotify = 7064; + public const int MonopolyEventLoadUpdateScNotify = 7029; + public const int MonopolyEventSelectFriendCsReq = 7065; + public const int MonopolyEventSelectFriendScRsp = 7057; + public const int MonopolyGameBingoFlipCardCsReq = 7058; + public const int MonopolyGameBingoFlipCardScRsp = 7013; + public const int MonopolyGameCreateScNotify = 7026; + public const int MonopolyGameGachaCsReq = 7068; + public const int MonopolyGameGachaScRsp = 7095; + public const int MonopolyGameRaiseRatioCsReq = 7050; + public const int MonopolyGameRaiseRatioScRsp = 7032; + public const int MonopolyGameSettleScNotify = 7055; + public const int MonopolyGetDailyInitItemCsReq = 7052; + public const int MonopolyGetDailyInitItemScRsp = 7002; + public const int MonopolyGetRafflePoolInfoCsReq = 7006; + public const int MonopolyGetRafflePoolInfoScRsp = 7014; + public const int MonopolyGetRaffleTicketCsReq = 7078; + public const int MonopolyGetRaffleTicketScRsp = 7083; + public const int MonopolyGetRegionProgressCsReq = 7072; + public const int MonopolyGetRegionProgressScRsp = 7053; + public const int MonopolyGiveUpCurContentCsReq = 7012; + public const int MonopolyGiveUpCurContentScRsp = 7037; + public const int MonopolyGuessBuyInformationCsReq = 7093; + public const int MonopolyGuessBuyInformationScRsp = 7040; + public const int MonopolyGuessChooseCsReq = 7017; + public const int MonopolyGuessChooseScRsp = 7100; + public const int MonopolyGuessDrawScNotify = 7048; + public const int MonopolyLikeCsReq = 7011; + public const int MonopolyLikeScNotify = 7024; + public const int MonopolyLikeScRsp = 7044; + public const int MonopolyMoveCsReq = 7071; + public const int MonopolyMoveScRsp = 7087; + public const int MonopolyQuizDurationChangeScNotify = 7005; + public const int MonopolyReRollRandomCsReq = 7082; + public const int MonopolyReRollRandomScRsp = 7003; + public const int MonopolyRollDiceCsReq = 7073; + public const int MonopolyRollDiceScRsp = 7030; + public const int MonopolyRollRandomCsReq = 7096; + public const int MonopolyRollRandomScRsp = 7021; + public const int MonopolyScrachRaffleTicketCsReq = 7069; + public const int MonopolyScrachRaffleTicketScRsp = 7025; + public const int MonopolySelectOptionCsReq = 7027; + public const int MonopolySelectOptionScRsp = 7062; + public const int MonopolySocialEventEffectScNotify = 7034; + public const int MonopolySttUpdateScNotify = 7063; + public const int MonopolyTakePhaseRewardCsReq = 7043; + public const int MonopolyTakePhaseRewardScRsp = 7060; + public const int MonopolyTakeRaffleTicketRewardCsReq = 7079; + public const int MonopolyTakeRaffleTicketRewardScRsp = 7084; + public const int MonopolyUpgradeAssetCsReq = 7009; + public const int MonopolyUpgradeAssetScRsp = 7081; + public const int MonthCardRewardNotify = 44; + public const int MultiplayerFightGameFinishScNotify = 1071; + public const int MultiplayerFightGameStartScNotify = 1030; + public const int MultiplayerFightGameStateCsReq = 1061; + public const int MultiplayerFightGameStateScRsp = 1088; + public const int MultiplayerFightGiveUpCsReq = 1039; + public const int MultiplayerFightGiveUpScRsp = 1073; + public const int MultiplayerGetFightGateCsReq = 1091; + public const int MultiplayerGetFightGateScRsp = 1020; + public const int MultiplayerMatch3FinishScNotify = 1087; + public const int MultipleDropInfoNotify = 4673; + public const int MultipleDropInfoScNotify = 4691; + public const int MuseumDispatchFinishedScNotify = 4381; + public const int MuseumFundsChangedScNotify = 4303; + public const int MuseumInfoChangedScNotify = 4382; + public const int MuseumRandomEventQueryCsReq = 4356; + public const int MuseumRandomEventQueryScRsp = 4349; + public const int MuseumRandomEventSelectCsReq = 4351; + public const int MuseumRandomEventSelectScRsp = 4309; + public const int MuseumRandomEventStartScNotify = 4370; + public const int MuseumTakeCollectRewardCsReq = 4301; + public const int MuseumTakeCollectRewardScRsp = 4333; + public const int MuseumTargetMissionFinishNotify = 4337; + public const int MuseumTargetRewardNotify = 4328; + public const int MuseumTargetStartNotify = 4312; + public const int NewAssistHistoryNotify = 2985; + public const int NewMailScNotify = 887; + public const int OfferingInfoScNotify = 6935; + public const int OpenRogueChestCsReq = 1844; + public const int OpenRogueChestScRsp = 1824; + public const int OpenTreasureDungeonGridCsReq = 4496; + public const int OpenTreasureDungeonGridScRsp = 4421; + public const int PickRogueAvatarCsReq = 1821; + public const int PickRogueAvatarScRsp = 1882; + public const int PlayBackGroundMusicCsReq = 3191; + public const int PlayBackGroundMusicScRsp = 3120; + public const int PlayerGetTokenCsReq = 39; + public const int PlayerGetTokenScRsp = 73; + public const int PlayerHeartBeatCsReq = 42; + public const int PlayerHeartBeatScRsp = 16; + public const int PlayerKickOutScNotify = 87; + public const int PlayerLoginCsReq = 61; + public const int PlayerLoginFinishCsReq = 86; + public const int PlayerLoginFinishScRsp = 80; + public const int PlayerLoginScRsp = 88; + public const int PlayerLogoutCsReq = 91; + public const int PlayerLogoutScRsp = 20; + public const int PlayerReturnForceFinishScNotify = 4562; + public const int PlayerReturnInfoQueryCsReq = 4587; + public const int PlayerReturnInfoQueryScRsp = 4527; + public const int PlayerReturnPointChangeScNotify = 4520; + public const int PlayerReturnSignCsReq = 4588; + public const int PlayerReturnSignScRsp = 4591; + public const int PlayerReturnStartScNotify = 4561; + public const int PlayerReturnTakePointRewardCsReq = 4539; + public const int PlayerReturnTakePointRewardScRsp = 4573; + public const int PlayerReturnTakeRewardCsReq = 4530; + public const int PlayerReturnTakeRewardScRsp = 4571; + public const int PlayerSyncScNotify = 661; + public const int PrepareRogueAdventureRoomCsReq = 5688; + public const int PrepareRogueAdventureRoomScRsp = 5691; + public const int PrestigeLevelUpCsReq = 4749; + public const int PrestigeLevelUpScRsp = 4751; + public const int PrivateMsgOfflineUsersScNotify = 3920; + public const int PromoteAvatarCsReq = 330; + public const int PromoteAvatarScRsp = 371; + public const int PromoteEquipmentCsReq = 591; + public const int PromoteEquipmentScRsp = 520; + public const int PunkLordBattleResultScNotify = 3209; + public const int PunkLordDataChangeNotify = 3232; + public const int PunkLordMonsterInfoScNotify = 3296; + public const int PunkLordMonsterKilledNotify = 3201; + public const int PunkLordRaidTimeOutScNotify = 3270; + public const int PVEBattleResultCsReq = 161; + public const int PVEBattleResultScRsp = 188; + public const int QueryProductInfoCsReq = 40; + public const int QueryProductInfoScRsp = 48; + public const int QuestRecordScNotify = 987; + public const int QuitBattleCsReq = 191; + public const int QuitBattleScNotify = 187; + public const int QuitBattleScRsp = 120; + public const int QuitLineupCsReq = 730; + public const int QuitLineupScRsp = 771; + public const int QuitRogueCsReq = 1855; + public const int QuitRogueScRsp = 1868; + public const int QuitTreasureDungeonCsReq = 4409; + public const int QuitTreasureDungeonScRsp = 4481; + public const int QuitWolfBroGameCsReq = 6530; + public const int QuitWolfBroGameScRsp = 6571; + public const int RaidCollectionDataCsReq = 6949; + public const int RaidCollectionDataScNotify = 6947; + public const int RaidCollectionDataScRsp = 6942; + public const int RaidInfoNotify = 2239; + public const int RaidKickByServerScNotify = 2256; + public const int RankUpAvatarCsReq = 394; + public const int RankUpAvatarScRsp = 396; + public const int RankUpEquipmentCsReq = 587; + public const int RankUpEquipmentScRsp = 527; + public const int ReBattleAfterBattleLoseCsNotify = 147; + public const int RebattleByClientCsNotify = 194; + public const int RechargeSuccNotify = 549; + public const int RecoverAllLineupCsReq = 1468; + public const int RecoverAllLineupScRsp = 1495; + public const int ReEnterLastElementStageCsReq = 1489; + public const int ReEnterLastElementStageScRsp = 1410; + public const int RefreshAlleyOrderCsReq = 4782; + public const int RefreshAlleyOrderScRsp = 4703; + public const int RefreshTriggerByClientCsReq = 1436; + public const int RefreshTriggerByClientScNotify = 1438; + public const int RefreshTriggerByClientScRsp = 1475; + public const int RegionStopScNotify = 3; + public const int RelicRecommendCsReq = 548; + public const int RelicRecommendScRsp = 505; + public const int RemoveRotaterCsReq = 6803; + public const int RemoveRotaterScRsp = 6870; + public const int RemoveStuffFromAreaCsReq = 4330; + public const int RemoveStuffFromAreaScRsp = 4371; + public const int ReplaceLineupCsReq = 709; + public const int ReplaceLineupScRsp = 781; + public const int ReportPlayerCsReq = 2909; + public const int ReportPlayerScRsp = 2981; + public const int ReserveStaminaExchangeCsReq = 25; + public const int ReserveStaminaExchangeScRsp = 72; + public const int ResetMapRotationRegionCsReq = 6847; + public const int ResetMapRotationRegionScRsp = 6894; + public const int RestartChallengePhaseCsReq = 1751; + public const int RestartChallengePhaseScRsp = 1709; + public const int RestoreWolfBroGameArchiveCsReq = 6539; + public const int RestoreWolfBroGameArchiveScRsp = 6573; + public const int RetcodeNotify = 24; + public const int ReturnLastTownCsReq = 1449; + public const int ReturnLastTownScRsp = 1451; + public const int RevcMsgScNotify = 3991; + public const int ReviveRogueAvatarCsReq = 1870; + public const int ReviveRogueAvatarScRsp = 1856; + public const int RogueDoGambleCsReq = 5699; + public const int RogueDoGambleScRsp = 5607; + public const int RogueEndlessActivityBattleEndScNotify = 6006; + public const int RogueGetGambleInfoCsReq = 5641; + public const int RogueGetGambleInfoScRsp = 5635; + public const int RogueModifierAddNotify = 5391; + public const int RogueModifierDelNotify = 5387; + public const int RogueModifierSelectCellCsReq = 5320; + public const int RogueModifierSelectCellScRsp = 5339; + public const int RogueModifierStageStartNotify = 5327; + public const int RogueModifierUpdateNotify = 5371; + public const int RogueNpcDisappearCsReq = 5674; + public const int RogueNpcDisappearScRsp = 5647; + public const int RogueTournAreaUpdateScNotify = 6019; + public const int RogueTournBattleFailSettleInfoScNotify = 6060; + public const int RogueTournClearArchiveNameScNotify = 6081; + public const int RogueTournConfirmSettleCsReq = 6026; + public const int RogueTournConfirmSettleScRsp = 6074; + public const int RogueTournDeleteArchiveCsReq = 6086; + public const int RogueTournDeleteArchiveScRsp = 6096; + public const int RogueTournDifficultyCompNotify = 6079; + public const int RogueTournEnablePermanentTalentCsReq = 6049; + public const int RogueTournEnablePermanentTalentScRsp = 6061; + public const int RogueTournEnterCsReq = 6037; + public const int RogueTournEnterLayerCsReq = 6095; + public const int RogueTournEnterLayerScRsp = 6072; + public const int RogueTournEnterRogueCocoonSceneCsReq = 6092; + public const int RogueTournEnterRogueCocoonSceneScRsp = 6027; + public const int RogueTournEnterRoomCsReq = 6094; + public const int RogueTournEnterRoomScRsp = 6099; + public const int RogueTournEnterScRsp = 6031; + public const int RogueTournExpNotify = 6068; + public const int RogueTournGetAllArchiveCsReq = 6054; + public const int RogueTournGetAllArchiveScRsp = 6022; + public const int RogueTournGetArchiveRepositoryCsReq = 6071; + public const int RogueTournGetArchiveRepositoryScRsp = 6036; + public const int RogueTournGetCurRogueCocoonInfoCsReq = 6018; + public const int RogueTournGetCurRogueCocoonInfoScRsp = 6021; + public const int RogueTournGetMiscRealTimeDataCsReq = 6076; + public const int RogueTournGetMiscRealTimeDataScRsp = 6020; + public const int RogueTournGetPermanentTalentInfoCsReq = 6066; + public const int RogueTournGetPermanentTalentInfoScRsp = 6035; + public const int RogueTournGetSettleInfoCsReq = 6034; + public const int RogueTournGetSettleInfoScRsp = 6052; + public const int RogueTournHandBookNotify = 6091; + public const int RogueTournLeaveCsReq = 6064; + public const int RogueTournLeaveRogueCocoonSceneCsReq = 6100; + public const int RogueTournLeaveRogueCocoonSceneScRsp = 6056; + public const int RogueTournLeaveScRsp = 6059; + public const int RogueTournLevelInfoUpdateScNotify = 6013; + public const int RogueTournQueryCsReq = 6058; + public const int RogueTournQueryScRsp = 6057; + public const int RogueTournReEnterRogueCocoonStageCsReq = 6083; + public const int RogueTournReEnterRogueCocoonStageScRsp = 6015; + public const int RogueTournRenameArchiveCsReq = 6090; + public const int RogueTournRenameArchiveScRsp = 6047; + public const int RogueTournResetPermanentTalentCsReq = 6011; + public const int RogueTournResetPermanentTalentScRsp = 6050; + public const int RogueTournReviveAvatarCsReq = 6038; + public const int RogueTournReviveAvatarScRsp = 6067; + public const int RogueTournRevivieCostUpdateScNotify = 6097; + public const int RogueTournSettleCsReq = 6030; + public const int RogueTournSettleScRsp = 6043; + public const int RogueTournStartCsReq = 6075; + public const int RogueTournStartScRsp = 6040; + public const int RogueTournTakeExpRewardCsReq = 6078; + public const int RogueTournTakeExpRewardScRsp = 6080; + public const int RogueTournWeekChallengeUpdateScNotify = 6044; + public const int RogueWorkbenchHandleFuncCsReq = 5679; + public const int RogueWorkbenchHandleFuncScRsp = 5684; + public const int RogueWorkbenchSelectFuncCsReq = 5678; + public const int RogueWorkbenchSelectFuncScRsp = 5683; + public const int RotateMapCsReq = 6830; + public const int RotateMapScRsp = 6871; + public const int SaveLogisticsCsReq = 4737; + public const int SaveLogisticsScRsp = 4728; + public const int SavePointsInfoNotify = 1458; + public const int SceneCastSkillCostMpCsReq = 1494; + public const int SceneCastSkillCostMpScRsp = 1496; + public const int SceneCastSkillCsReq = 1439; + public const int SceneCastSkillMpUpdateScNotify = 1421; + public const int SceneCastSkillScRsp = 1473; + public const int SceneEnterStageCsReq = 1409; + public const int SceneEnterStageScRsp = 1481; + public const int SceneEntityMoveCsReq = 1461; + public const int SceneEntityMoveScNotify = 1462; + public const int SceneEntityMoveScRsp = 1488; + public const int SceneEntityTeleportCsReq = 1498; + public const int SceneEntityTeleportScRsp = 1486; + public const int SceneGroupRefreshScNotify = 1463; + public const int ScenePlaneEventScNotify = 1479; + public const int SceneReviveAfterRebattleCsReq = 1412; + public const int SceneReviveAfterRebattleScRsp = 1437; + public const int SceneUpdatePositionVersionNotify = 1474; + public const int SearchPlayerCsReq = 2928; + public const int SearchPlayerScRsp = 2901; + public const int SecurityReportCsReq = 4162; + public const int SecurityReportScRsp = 4174; + public const int SelectChatBubbleCsReq = 5191; + public const int SelectChatBubbleScRsp = 5120; + public const int SelectChessRogueNousSubStoryCsReq = 5495; + public const int SelectChessRogueNousSubStoryScRsp = 5463; + public const int SelectChessRogueSubStoryCsReq = 5491; + public const int SelectChessRogueSubStoryScRsp = 5540; + public const int SelectInclinationTextCsReq = 2187; + public const int SelectInclinationTextScRsp = 2127; + public const int SelectPhoneThemeCsReq = 5173; + public const int SelectPhoneThemeScRsp = 5130; + public const int SelectRogueCommonDialogueOptionCsReq = 5657; + public const int SelectRogueCommonDialogueOptionScRsp = 5634; + public const int SellItemCsReq = 570; + public const int SellItemScRsp = 556; + public const int SendMsgCsReq = 3961; + public const int SendMsgScRsp = 3988; + public const int ServerAnnounceNotify = 50; + public const int ServerSimulateBattleFinishScNotify = 174; + public const int SetAetherDivideLineUpCsReq = 4847; + public const int SetAetherDivideLineUpScRsp = 4894; + public const int SetAssistAvatarCsReq = 2874; + public const int SetAssistAvatarScRsp = 2847; + public const int SetAssistCsReq = 2932; + public const int SetAssistScRsp = 2955; + public const int SetBoxingClubResonanceLineupCsReq = 4247; + public const int SetBoxingClubResonanceLineupScRsp = 4294; + public const int SetClientPausedCsReq = 1417; + public const int SetClientPausedScRsp = 1500; + public const int SetClientRaidTargetCountCsReq = 2247; + public const int SetClientRaidTargetCountScRsp = 2294; + public const int SetCurInteractEntityCsReq = 1432; + public const int SetCurInteractEntityScRsp = 1455; + public const int SetCurWaypointCsReq = 491; + public const int SetCurWaypointScRsp = 420; + public const int SetDisplayAvatarCsReq = 2839; + public const int SetDisplayAvatarScRsp = 2873; + public const int SetForbidOtherApplyFriendCsReq = 2905; + public const int SetForbidOtherApplyFriendScRsp = 2966; + public const int SetFriendMarkCsReq = 2990; + public const int SetFriendMarkScRsp = 2918; + public const int SetFriendRemarkNameCsReq = 2949; + public const int SetFriendRemarkNameScRsp = 2951; + public const int SetGameplayBirthdayCsReq = 64; + public const int SetGameplayBirthdayScRsp = 8; + public const int SetGenderCsReq = 54; + public const int SetGenderScRsp = 26; + public const int SetGroupCustomSaveDataCsReq = 1416; + public const int SetGroupCustomSaveDataScRsp = 1465; + public const int SetHeadIconCsReq = 2891; + public const int SetHeadIconScRsp = 2820; + public const int SetHeroBasicTypeCsReq = 32; + public const int SetHeroBasicTypeScRsp = 55; + public const int SetIsDisplayAvatarInfoCsReq = 2830; + public const int SetIsDisplayAvatarInfoScRsp = 2871; + public const int SetLanguageCsReq = 1; + public const int SetLanguageScRsp = 33; + public const int SetLineupNameCsReq = 703; + public const int SetLineupNameScRsp = 770; + public const int SetMissionEventProgressCsReq = 1281; + public const int SetMissionEventProgressScRsp = 1212; + public const int SetNicknameCsReq = 56; + public const int SetNicknameScRsp = 49; + public const int SetPlayerInfoCsReq = 17; + public const int SetPlayerInfoScRsp = 100; + public const int SetRedPointStatusScNotify = 79; + public const int SetRogueCollectionCsReq = 5672; + public const int SetRogueCollectionScRsp = 5653; + public const int SetRogueExhibitionCsReq = 5643; + public const int SetRogueExhibitionScRsp = 5660; + public const int SetSignatureCsReq = 2827; + public const int SetSignatureScRsp = 2862; + public const int SetSpringRecoverConfigCsReq = 1476; + public const int SetSpringRecoverConfigScRsp = 1464; + public const int SetStuffToAreaCsReq = 4339; + public const int SetStuffToAreaScRsp = 4373; + public const int SetTurnFoodSwitchCsReq = 526; + public const int SetTurnFoodSwitchScRsp = 517; + public const int ShareCsReq = 4161; + public const int SharePunkLordMonsterCsReq = 3239; + public const int SharePunkLordMonsterScRsp = 3273; + public const int ShareScRsp = 4188; + public const int ShowNewSupplementVisitorCsReq = 3762; + public const int ShowNewSupplementVisitorScRsp = 3774; + public const int SpaceZooBornCsReq = 6791; + public const int SpaceZooBornScRsp = 6720; + public const int SpaceZooCatUpdateNotify = 6762; + public const int SpaceZooDataCsReq = 6761; + public const int SpaceZooDataScRsp = 6788; + public const int SpaceZooDeleteCatCsReq = 6787; + public const int SpaceZooDeleteCatScRsp = 6727; + public const int SpaceZooExchangeItemCsReq = 6774; + public const int SpaceZooExchangeItemScRsp = 6747; + public const int SpaceZooMutateCsReq = 6739; + public const int SpaceZooMutateScRsp = 6773; + public const int SpaceZooOpCatteryCsReq = 6730; + public const int SpaceZooOpCatteryScRsp = 6771; + public const int SpaceZooTakeCsReq = 6794; + public const int SpaceZooTakeScRsp = 6796; + public const int SpringRecoverCsReq = 1408; + public const int SpringRecoverScRsp = 1446; + public const int SpringRecoverSingleAvatarCsReq = 1444; + public const int SpringRecoverSingleAvatarScRsp = 1424; + public const int SpringRefreshCsReq = 1403; + public const int SpringRefreshScRsp = 1470; + public const int StaminaInfoScNotify = 53; + public const int StarFightDataChangeNotify = 7166; + public const int StartAetherDivideChallengeBattleCsReq = 4830; + public const int StartAetherDivideChallengeBattleScRsp = 4871; + public const int StartAetherDivideSceneBattleCsReq = 4839; + public const int StartAetherDivideSceneBattleScRsp = 4873; + public const int StartAetherDivideStageBattleCsReq = 4849; + public const int StartAetherDivideStageBattleScRsp = 4851; + public const int StartAlleyEventCsReq = 4730; + public const int StartAlleyEventScRsp = 4771; + public const int StartBattleCollegeCsReq = 5720; + public const int StartBattleCollegeScRsp = 5739; + public const int StartBoxingClubBattleCsReq = 4239; + public const int StartBoxingClubBattleScRsp = 4273; + public const int StartChallengeCsReq = 1791; + public const int StartChallengeScRsp = 1720; + public const int StartCocoonStageCsReq = 1413; + public const int StartCocoonStageScRsp = 1485; + public const int StartFinishMainMissionScNotify = 1250; + public const int StartFinishSubMissionScNotify = 1233; + public const int StartMatchCsReq = 7345; + public const int StartMatchScRsp = 7317; + public const int StartPartialChallengeCsReq = 1770; + public const int StartPartialChallengeScRsp = 1756; + public const int StartPunkLordRaidCsReq = 3291; + public const int StartPunkLordRaidScRsp = 3220; + public const int StartRaidCsReq = 2261; + public const int StartRaidScRsp = 2288; + public const int StartRogueCsReq = 1891; + public const int StartRogueScRsp = 1820; + public const int StartStarFightLevelCsReq = 7164; + public const int StartStarFightLevelScRsp = 7165; + public const int StartTimedCocoonStageCsReq = 1431; + public const int StartTimedCocoonStageScRsp = 1497; + public const int StartTimedFarmElementCsReq = 1423; + public const int StartTimedFarmElementScRsp = 1419; + public const int StartTrialActivityCsReq = 2616; + public const int StartTrialActivityScRsp = 2665; + public const int StartWolfBroGameCsReq = 6561; + public const int StartWolfBroGameScRsp = 6588; + public const int StopRogueAdventureRoomCsReq = 5612; + public const int StopRogueAdventureRoomScRsp = 5637; + public const int StoryLineInfoScNotify = 6291; + public const int StoryLineTrialAvatarChangeScNotify = 6230; + public const int StrongChallengeActivityBattleEndScNotify = 6639; + public const int SubMissionRewardScNotify = 1237; + public const int SubmitEmotionItemCsReq = 6339; + public const int SubmitEmotionItemScRsp = 6373; + public const int SubmitMonsterResearchActivityMaterialCsReq = 2670; + public const int SubmitMonsterResearchActivityMaterialScRsp = 2656; + public const int SubmitOfferingItemCsReq = 6927; + public const int SubmitOfferingItemScRsp = 6923; + public const int SubmitOrigamiItemCsReq = 4196; + public const int SubmitOrigamiItemScRsp = 4121; + public const int SummonPunkLordMonsterCsReq = 3230; + public const int SummonPunkLordMonsterScRsp = 3271; + public const int SwapLineupCsReq = 787; + public const int SwapLineupScRsp = 727; + public const int SwitchAetherDivideLineUpSlotCsReq = 4870; + public const int SwitchAetherDivideLineUpSlotScRsp = 4856; + public const int SwitchLineupIndexCsReq = 721; + public const int SwitchLineupIndexScRsp = 782; + public const int SyncAcceptedPamMissionNotify = 4091; + public const int SyncAddBlacklistScNotify = 2903; + public const int SyncApplyFriendScNotify = 2987; + public const int SyncChessRogueMainStoryFinishScNotify = 5486; + public const int SyncChessRogueNousMainStoryScNotify = 5537; + public const int SyncChessRogueNousSubStoryScNotify = 5526; + public const int SyncChessRogueNousValueScNotify = 5469; + public const int SyncClientResVersionCsReq = 130; + public const int SyncClientResVersionScRsp = 171; + public const int SyncDeleteFriendScNotify = 2996; + public const int SyncEntityBuffChangeListScNotify = 1447; + public const int SyncHandleFriendScNotify = 2974; + public const int SyncLineupNotify = 762; + public const int SyncRogueAdventureRoomInfoScNotify = 5661; + public const int SyncRogueAeonLevelUpRewardScNotify = 1814; + public const int SyncRogueAeonScNotify = 1883; + public const int SyncRogueAreaUnlockScNotify = 1879; + public const int SyncRogueCommonActionResultScNotify = 5648; + public const int SyncRogueCommonDialogueDataScNotify = 5698; + public const int SyncRogueCommonDialogueOptionFinishScNotify = 5686; + public const int SyncRogueCommonPendingActionScNotify = 5605; + public const int SyncRogueCommonVirtualItemInfoScNotify = 5618; + public const int SyncRogueExploreWinScNotify = 1858; + public const int SyncRogueFinishScNotify = 1896; + public const int SyncRogueGetItemScNotify = 1884; + public const int SyncRogueHandbookDataUpdateScNotify = 5626; + public const int SyncRogueMapRoomScNotify = 1840; + public const int SyncRoguePickAvatarInfoScNotify = 1892; + public const int SyncRogueReviveInfoScNotify = 1832; + public const int SyncRogueRewardInfoScNotify = 1867; + public const int SyncRogueSeasonFinishScNotify = 1813; + public const int SyncRogueStatusScNotify = 1819; + public const int SyncRogueVirtualItemInfoScNotify = 1823; + public const int SyncServerSceneChangeNotify = 1425; + public const int SyncTaskCsReq = 1273; + public const int SyncTaskScRsp = 1230; + public const int SyncTurnFoodNotify = 554; + public const int TakeActivityExpeditionRewardCsReq = 2594; + public const int TakeActivityExpeditionRewardScRsp = 2596; + public const int TakeAllApRewardCsReq = 3373; + public const int TakeAllApRewardScRsp = 3330; + public const int TakeAllRewardCsReq = 3071; + public const int TakeAllRewardScRsp = 3087; + public const int TakeApRewardCsReq = 3361; + public const int TakeApRewardScRsp = 3388; + public const int TakeAssistRewardCsReq = 2954; + public const int TakeAssistRewardScRsp = 2926; + public const int TakeBpRewardCsReq = 3020; + public const int TakeBpRewardScRsp = 3039; + public const int TakeChallengeRaidRewardCsReq = 2271; + public const int TakeChallengeRaidRewardScRsp = 2287; + public const int TakeChallengeRewardCsReq = 1796; + public const int TakeChallengeRewardScRsp = 1721; + public const int TakeChapterRewardCsReq = 471; + public const int TakeChapterRewardScRsp = 487; + public const int TakeCityShopRewardCsReq = 1539; + public const int TakeCityShopRewardScRsp = 1573; + public const int TakeExpeditionRewardCsReq = 2530; + public const int TakeExpeditionRewardScRsp = 2571; + public const int TakeFightActivityRewardCsReq = 3673; + public const int TakeFightActivityRewardScRsp = 3630; + public const int TakeKilledPunkLordMonsterScoreCsReq = 3233; + public const int TakeKilledPunkLordMonsterScoreScRsp = 3250; + public const int TakeLoginActivityRewardCsReq = 2691; + public const int TakeLoginActivityRewardScRsp = 2620; + public const int TakeMailAttachmentCsReq = 830; + public const int TakeMailAttachmentScRsp = 871; + public const int TakeMonsterResearchActivityRewardCsReq = 2649; + public const int TakeMonsterResearchActivityRewardScRsp = 2651; + public const int TakeMultipleExpeditionRewardCsReq = 2503; + public const int TakeMultipleExpeditionRewardScRsp = 2570; + public const int TakeOffAvatarSkinCsReq = 381; + public const int TakeOffAvatarSkinScRsp = 312; + public const int TakeOffEquipmentCsReq = 362; + public const int TakeOffEquipmentScRsp = 374; + public const int TakeOfferingRewardCsReq = 6939; + public const int TakeOfferingRewardScRsp = 6934; + public const int TakeOffRelicCsReq = 303; + public const int TakeOffRelicScRsp = 370; + public const int TakePictureCsReq = 4139; + public const int TakePictureScRsp = 4173; + public const int TakePrestigeRewardCsReq = 4762; + public const int TakePrestigeRewardScRsp = 4774; + public const int TakePromotionRewardCsReq = 356; + public const int TakePromotionRewardScRsp = 349; + public const int TakePunkLordPointRewardCsReq = 3247; + public const int TakePunkLordPointRewardScRsp = 3294; + public const int TakeQuestOptionalRewardCsReq = 974; + public const int TakeQuestOptionalRewardScRsp = 947; + public const int TakeQuestRewardCsReq = 991; + public const int TakeQuestRewardScRsp = 920; + public const int TakeRogueAeonLevelRewardCsReq = 1869; + public const int TakeRogueAeonLevelRewardScRsp = 1825; + public const int TakeRogueEndlessActivityAllBonusRewardCsReq = 6010; + public const int TakeRogueEndlessActivityAllBonusRewardScRsp = 6009; + public const int TakeRogueEndlessActivityPointRewardCsReq = 6002; + public const int TakeRogueEndlessActivityPointRewardScRsp = 6007; + public const int TakeRogueEventHandbookRewardCsReq = 5693; + public const int TakeRogueEventHandbookRewardScRsp = 5640; + public const int TakeRogueMiracleHandbookRewardCsReq = 5617; + public const int TakeRogueMiracleHandbookRewardScRsp = 5700; + public const int TakeRogueScoreRewardCsReq = 1849; + public const int TakeRogueScoreRewardScRsp = 1851; + public const int TakeRollShopRewardCsReq = 6919; + public const int TakeRollShopRewardScRsp = 6914; + public const int TakeTalkRewardCsReq = 2191; + public const int TakeTalkRewardScRsp = 2120; + public const int TakeTrainVisitorUntakenBehaviorRewardCsReq = 3787; + public const int TakeTrainVisitorUntakenBehaviorRewardScRsp = 3727; + public const int TakeTrialActivityRewardCsReq = 2624; + public const int TakeTrialActivityRewardScRsp = 2642; + public const int TeleportToMissionResetPointCsReq = 1228; + public const int TeleportToMissionResetPointScRsp = 1201; + public const int TelevisionActivityBattleEndScNotify = 6974; + public const int TelevisionActivityDataChangeScNotify = 6967; + public const int TextJoinBatchSaveCsReq = 3839; + public const int TextJoinBatchSaveScRsp = 3873; + public const int TextJoinQueryCsReq = 3891; + public const int TextJoinQueryScRsp = 3820; + public const int TextJoinSaveCsReq = 3861; + public const int TextJoinSaveScRsp = 3888; + public const int TrainRefreshTimeNotify = 3739; + public const int TrainVisitorBehaviorFinishCsReq = 3761; + public const int TrainVisitorBehaviorFinishScRsp = 3788; + public const int TrainVisitorRewardSendNotify = 3773; + public const int TravelBrochureApplyPasterCsReq = 6430; + public const int TravelBrochureApplyPasterListCsReq = 6449; + public const int TravelBrochureApplyPasterListScRsp = 6451; + public const int TravelBrochureApplyPasterScRsp = 6471; + public const int TravelBrochureGetDataCsReq = 6461; + public const int TravelBrochureGetDataScRsp = 6488; + public const int TravelBrochureGetPasterScNotify = 6447; + public const int TravelBrochurePageResetCsReq = 6470; + public const int TravelBrochurePageResetScRsp = 6456; + public const int TravelBrochurePageUnlockScNotify = 6491; + public const int TravelBrochureRemovePasterCsReq = 6487; + public const int TravelBrochureRemovePasterScRsp = 6427; + public const int TravelBrochureSelectMessageCsReq = 6439; + public const int TravelBrochureSelectMessageScRsp = 6473; + public const int TravelBrochureSetCustomValueCsReq = 6496; + public const int TravelBrochureSetCustomValueScRsp = 6421; + public const int TravelBrochureSetPageDescStatusCsReq = 6482; + public const int TravelBrochureSetPageDescStatusScRsp = 6403; + public const int TravelBrochureUpdatePasterPosCsReq = 6462; + public const int TravelBrochureUpdatePasterPosScRsp = 6474; + public const int TreasureDungeonDataScNotify = 4461; + public const int TreasureDungeonFinishScNotify = 4488; + public const int TrialActivityDataChangeScNotify = 2646; + public const int TrialBackGroundMusicCsReq = 3130; + public const int TrialBackGroundMusicScRsp = 3171; + public const int TriggerVoiceCsReq = 4147; + public const int TriggerVoiceScRsp = 4194; + public const int UnlockAvatarSkinScNotify = 337; + public const int UnlockBackGroundMusicCsReq = 3139; + public const int UnlockBackGroundMusicScRsp = 3173; + public const int UnlockChatBubbleScNotify = 5139; + public const int UnlockedAreaMapScNotify = 1459; + public const int UnlockHeadIconScNotify = 2887; + public const int UnlockPhoneThemeScNotify = 5171; + public const int UnlockSkilltreeCsReq = 339; + public const int UnlockSkilltreeScRsp = 373; + public const int UnlockTeleportNotify = 1467; + public const int UnlockTutorialCsReq = 1639; + public const int UnlockTutorialGuideCsReq = 1630; + public const int UnlockTutorialGuideScRsp = 1671; + public const int UnlockTutorialScRsp = 1673; + public const int UpdateEnergyScNotify = 6821; + public const int UpdateFeatureSwitchScNotify = 66; + public const int UpdateFloorSavedValueNotify = 1414; + public const int UpdateGunPlayDataCsReq = 4128; + public const int UpdateGunPlayDataScRsp = 4101; + public const int UpdateMapRotationDataScNotify = 6882; + public const int UpdateMechanismBarScNotify = 1442; + public const int UpdateMovieRacingDataCsReq = 4109; + public const int UpdateMovieRacingDataScRsp = 4181; + public const int UpdatePlayerSettingCsReq = 6; + public const int UpdatePlayerSettingScRsp = 14; + public const int UpdatePsnSettingsInfoCsReq = 63; + public const int UpdatePsnSettingsInfoScRsp = 45; + public const int UpdateRedDotDataCsReq = 5991; + public const int UpdateRedDotDataScRsp = 5920; + public const int UpdateRogueAdventureRoomScoreCsReq = 5666; + public const int UpdateRogueAdventureRoomScoreScRsp = 5690; + public const int UpdateRotaterScNotify = 6856; + public const int UpdateServerPrefsDataCsReq = 6139; + public const int UpdateServerPrefsDataScRsp = 6173; + public const int UpdateTrackMainMissionIdCsReq = 1285; + public const int UpdateTrackMainMissionIdScRsp = 1254; + public const int UpgradeAreaCsReq = 4347; + public const int UpgradeAreaScRsp = 4394; + public const int UpgradeAreaStatCsReq = 4396; + public const int UpgradeAreaStatScRsp = 4321; + public const int UseItemCsReq = 530; + public const int UseItemScRsp = 571; + public const int UseTreasureDungeonItemCsReq = 4449; + public const int UseTreasureDungeonItemScRsp = 4451; + public const int VirtualLineupDestroyNotify = 751; + public const int WaypointShowNewCsNotify = 430; + public const int WolfBroGameActivateBulletCsReq = 6521; + public const int WolfBroGameActivateBulletScRsp = 6582; + public const int WolfBroGameDataChangeScNotify = 6562; + public const int WolfBroGameExplodeMonsterCsReq = 6503; + public const int WolfBroGameExplodeMonsterScRsp = 6570; + public const int WolfBroGamePickupBulletCsReq = 6594; + public const int WolfBroGamePickupBulletScRsp = 6596; + public const int WolfBroGameUseBulletCsReq = 6574; + public const int WolfBroGameUseBulletScRsp = 6547; +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Handler.cs b/GameServer/Server/Packet/Handler.cs index 301718ab..9b0020e5 100644 --- a/GameServer/Server/Packet/Handler.cs +++ b/GameServer/Server/Packet/Handler.cs @@ -1,7 +1,6 @@ -namespace EggLink.DanhengServer.Server.Packet +namespace EggLink.DanhengServer.Server.Packet; + +public abstract class Handler { - public abstract class Handler - { - public abstract void OnHandle(Connection connection, byte[] header, byte[] data); - } -} + public abstract Task OnHandle(Connection connection, byte[] header, byte[] data); +} \ No newline at end of file diff --git a/GameServer/Server/Packet/HandlerManager.cs b/GameServer/Server/Packet/HandlerManager.cs index eda16bcf..38dd352d 100644 --- a/GameServer/Server/Packet/HandlerManager.cs +++ b/GameServer/Server/Packet/HandlerManager.cs @@ -1,34 +1,31 @@ using System.Reflection; -namespace EggLink.DanhengServer.Server.Packet +namespace EggLink.DanhengServer.Server.Packet; + +public static class HandlerManager { - public static class HandlerManager + public static Dictionary handlers = []; + + public static void Init() { - public static Dictionary handlers = []; - - public static void Init() + var classes = Assembly.GetExecutingAssembly().GetTypes(); // Get all classes in the assembly + foreach (var cls in classes) { - var classes = Assembly.GetExecutingAssembly().GetTypes(); // Get all classes in the assembly - foreach (var cls in classes) - { - var attribute = (Opcode)Attribute.GetCustomAttribute(cls, typeof(Opcode))!; + var attribute = (Opcode)Attribute.GetCustomAttribute(cls, typeof(Opcode))!; - if (attribute != null) - { - handlers.Add(attribute.CmdId, (Handler)Activator.CreateInstance(cls)!); - } - } - } - - public static Handler? GetHandler(int cmdId) - { - try - { - return handlers[cmdId]; - } catch - { - return null; - } + if (attribute != null) handlers.Add(attribute.CmdId, (Handler)Activator.CreateInstance(cls)!); } } -} + + public static Handler? GetHandler(int cmdId) + { + try + { + return handlers[cmdId]; + } + catch + { + return null; + } + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Opcode.cs b/GameServer/Server/Packet/Opcode.cs index 5ee0b0f8..c1bcdfa4 100644 --- a/GameServer/Server/Packet/Opcode.cs +++ b/GameServer/Server/Packet/Opcode.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet; -namespace EggLink.DanhengServer.Server.Packet +[AttributeUsage(AttributeTargets.Class)] +public class Opcode(int cmdId) : Attribute { - [AttributeUsage(AttributeTargets.Class)] - public class Opcode(int cmdId) : Attribute - { - public int CmdId = cmdId; - } -} + public int CmdId = cmdId; +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Activity/HandlerGetActivityScheduleConfigCsReq.cs b/GameServer/Server/Packet/Recv/Activity/HandlerGetActivityScheduleConfigCsReq.cs index 596d22b2..f639fdaa 100644 --- a/GameServer/Server/Packet/Recv/Activity/HandlerGetActivityScheduleConfigCsReq.cs +++ b/GameServer/Server/Packet/Recv/Activity/HandlerGetActivityScheduleConfigCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Activity; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Activity +namespace EggLink.DanhengServer.Server.Packet.Recv.Activity; + +[Opcode(CmdIds.GetActivityScheduleConfigCsReq)] +public class HandlerGetActivityScheduleConfigCsReq : Handler { - [Opcode(CmdIds.GetActivityScheduleConfigCsReq)] - public class HandlerGetActivityScheduleConfigCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetActivityScheduleConfigScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetActivityScheduleConfigScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerAvatarExpUpCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerAvatarExpUpCsReq.cs index e70ac905..cedfb468 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerAvatarExpUpCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerAvatarExpUpCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Avatar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.AvatarExpUpCsReq)] +public class HandlerAvatarExpUpCsReq : Handler { - [Opcode(CmdIds.AvatarExpUpCsReq)] - public class HandlerAvatarExpUpCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = AvatarExpUpCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - var returnItem = player.InventoryManager!.LevelUpAvatar((int)req.BaseAvatarId, req.ItemCost); + var req = AvatarExpUpCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + var returnItem = await player.InventoryManager!.LevelUpAvatar((int)req.BaseAvatarId, req.ItemCost); - connection.SendPacket(new PacketAvatarExpUpScRsp(returnItem)); - } + await connection.SendPacket(new PacketAvatarExpUpScRsp(returnItem)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerDressAvatarCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerDressAvatarCsReq.cs index d29c2a47..90b9269e 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerDressAvatarCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerDressAvatarCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.DressAvatarCsReq)] +public class HandlerDressAvatarCsReq : Handler { - [Opcode(CmdIds.DressAvatarCsReq)] - public class HandlerDressAvatarCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = DressAvatarCsReq.Parser.ParseFrom(data); - var player = connection.Player!; + var req = DressAvatarCsReq.Parser.ParseFrom(data); + var player = connection.Player!; - player.InventoryManager!.EquipAvatar((int)req.DressAvatarId, (int)req.EquipmentUniqueId); + await player.InventoryManager!.EquipAvatar((int)req.DressAvatarId, (int)req.EquipmentUniqueId); - connection.SendPacket(CmdIds.DressAvatarScRsp); - } + await connection.SendPacket(CmdIds.DressAvatarScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerDressRelicAvatarCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerDressRelicAvatarCsReq.cs index 7b30fbdd..698c449f 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerDressRelicAvatarCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerDressRelicAvatarCsReq.cs @@ -1,25 +1,18 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.DressRelicAvatarCsReq)] +public class HandlerDressRelicAvatarCsReq : Handler { - [Opcode(CmdIds.DressRelicAvatarCsReq)] - public class HandlerDressRelicAvatarCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = DressRelicAvatarCsReq.Parser.ParseFrom(data); + var req = DressRelicAvatarCsReq.Parser.ParseFrom(data); - foreach (var param in req.SwitchList) - { - connection.Player!.InventoryManager!.EquipRelic((int)req.DressAvatarId, (int)param.RelicUniqueId, (int) param.RelicType); - } + foreach (var param in req.SwitchList) + await connection.Player!.InventoryManager!.EquipRelic((int)req.DressAvatarId, (int)param.RelicUniqueId, + (int)param.RelicType); - connection.SendPacket(CmdIds.DressRelicAvatarScRsp); - } + await connection.SendPacket(CmdIds.DressRelicAvatarScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerExpUpEquipmentCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerExpUpEquipmentCsReq.cs index dd5a8f43..15a8fe75 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerExpUpEquipmentCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerExpUpEquipmentCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Avatar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.ExpUpEquipmentCsReq)] +public class HandlerExpUpEquipmentCsReq : Handler { - [Opcode(CmdIds.ExpUpEquipmentCsReq)] - public class HandlerExpUpEquipmentCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ExpUpEquipmentCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - var returnItem = player.InventoryManager!.LevelUpEquipment((int)req.EquipmentUniqueId, req.CostData); + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + var req = ExpUpEquipmentCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + var returnItem = await player.InventoryManager!.LevelUpEquipment((int)req.EquipmentUniqueId, req.CostData); - connection.SendPacket(new PacketExpUpEquipmentScRsp(returnItem)); - } + await connection.SendPacket(new PacketExpUpEquipmentScRsp(returnItem)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerExpUpRelicCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerExpUpRelicCsReq.cs index c43e894f..5e6b35b6 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerExpUpRelicCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerExpUpRelicCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Avatar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.ExpUpRelicCsReq)] +public class HandlerExpUpRelicCsReq : Handler { - [Opcode(CmdIds.ExpUpRelicCsReq)] - public class HandlerExpUpRelicCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ExpUpRelicCsReq.Parser.ParseFrom(data); + var req = ExpUpRelicCsReq.Parser.ParseFrom(data); - var left = connection.Player!.InventoryManager!.LevelUpRelic((int)req.RelicUniqueId, req.CostData); + var left = await connection.Player!.InventoryManager!.LevelUpRelic((int)req.RelicUniqueId, req.CostData); - connection.SendPacket(new PacketExpUpRelicScRsp(left)); - } + await connection.SendPacket(new PacketExpUpRelicScRsp(left)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerGetAssistHistoryCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerGetAssistHistoryCsReq.cs index 0c4f615f..440df12b 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerGetAssistHistoryCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerGetAssistHistoryCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Avatar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.GetAssistHistoryCsReq)] +public class HandlerGetAssistHistoryCsReq : Handler { - [Opcode(CmdIds.GetAssistHistoryCsReq)] - public class HandlerGetAssistHistoryCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetAssistHistoryScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetAssistHistoryScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerGetAssistListCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerGetAssistListCsReq.cs index d145f6c4..480b1058 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerGetAssistListCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerGetAssistListCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Avatar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.GetAssistListCsReq)] +public class HandlerGetAssistListCsReq : Handler { - [Opcode(CmdIds.GetAssistListCsReq)] - public class HandlerGetAssistListCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetAssistListScRsp()); - } + await connection.SendPacket(new PacketGetAssistListScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerGetAvatarDataCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerGetAvatarDataCsReq.cs index b4718287..8e35126b 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerGetAvatarDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerGetAvatarDataCsReq.cs @@ -1,13 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Avatar; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.GetAvatarDataCsReq)] +public class HandlerGetAvatarDataCsReq : Handler { - [Opcode(CmdIds.GetAvatarDataCsReq)] - public class HandlerGetAvatarDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetAvatarDataScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetAvatarDataScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerGetCurAssistCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerGetCurAssistCsReq.cs index 43ba81ad..d3543c16 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerGetCurAssistCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerGetCurAssistCsReq.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +[Opcode(CmdIds.GetCurAssistCsReq)] +public class HandlerGetCurAssistCsReq : Handler { - [Opcode(CmdIds.GetCurAssistCsReq)] - public class HandlerGetCurAssistCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(CmdIds.GetCurAssistScRsp); - } + await connection.SendPacket(CmdIds.GetCurAssistScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerGetHeroBasicTypeInfoCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerGetHeroBasicTypeInfoCsReq.cs index d88be833..a06c4c01 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerGetHeroBasicTypeInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerGetHeroBasicTypeInfoCsReq.cs @@ -1,13 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Avatar; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.GetHeroBasicTypeInfoCsReq)] +public class HandlerGetHeroBasicTypeInfoCsReq : Handler { - [Opcode(CmdIds.GetHeroBasicTypeInfoCsReq)] - public class HandlerGetHeroBasicTypeInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetHeroBasicTypeInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetHeroBasicTypeInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerPromoteAvatarCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerPromoteAvatarCsReq.cs index eeffb00b..4ccea086 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerPromoteAvatarCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerPromoteAvatarCsReq.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.PromoteAvatarCsReq)] +public class HandlerPromoteAvatarCsReq : Handler { - [Opcode(CmdIds.PromoteAvatarCsReq)] - public class HandlerPromoteAvatarCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = PromoteAvatarCsReq.Parser.ParseFrom(data); + var req = PromoteAvatarCsReq.Parser.ParseFrom(data); - connection.Player!.InventoryManager!.promoteAvatar((int)req.BaseAvatarId); + await connection.Player!.InventoryManager!.PromoteAvatar((int)req.BaseAvatarId); - connection.SendPacket(CmdIds.PromoteAvatarScRsp); - } + await connection.SendPacket(CmdIds.PromoteAvatarScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerPromoteEquipmentCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerPromoteEquipmentCsReq.cs index 7bc38858..38e10512 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerPromoteEquipmentCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerPromoteEquipmentCsReq.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.PromoteEquipmentCsReq)] +public class HandlerPromoteEquipmentCsReq : Handler { - [Opcode(CmdIds.PromoteEquipmentCsReq)] - public class HandlerPromoteEquipmentCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = PromoteEquipmentCsReq.Parser.ParseFrom(data); + var req = PromoteEquipmentCsReq.Parser.ParseFrom(data); - connection.Player!.InventoryManager!.PromoteEquipment((int)req.EquipmentUniqueId); + await connection.Player!.InventoryManager!.PromoteEquipment((int)req.EquipmentUniqueId); - connection.SendPacket(CmdIds.PromoteEquipmentScRsp); - } + await connection.SendPacket(CmdIds.PromoteEquipmentScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerRankUpAvatarCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerRankUpAvatarCsReq.cs index 2ea59d11..0636e956 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerRankUpAvatarCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerRankUpAvatarCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.RankUpAvatarCsReq)] +public class HandlerRankUpAvatarCsReq : Handler { - [Opcode(CmdIds.RankUpAvatarCsReq)] - public class HandlerRankUpAvatarCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = RankUpAvatarCsReq.Parser.ParseFrom(data); - connection.Player!.InventoryManager?.RankUpAvatar((int)req.DressAvatarId, req.CostData); - connection.SendPacket(CmdIds.RankUpAvatarScRsp); - } + var req = RankUpAvatarCsReq.Parser.ParseFrom(data); + await connection.Player!.InventoryManager!.RankUpAvatar((int)req.DressAvatarId, req.CostData); + await connection.SendPacket(CmdIds.RankUpAvatarScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerRankUpEquipmentCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerRankUpEquipmentCsReq.cs index a64f5759..4858a5d7 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerRankUpEquipmentCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerRankUpEquipmentCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.RankUpEquipmentCsReq)] +public class HandlerRankUpEquipmentCsReq : Handler { - [Opcode(CmdIds.RankUpEquipmentCsReq)] - public class HandlerRankUpEquipmentCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = RankUpEquipmentCsReq.Parser.ParseFrom(data); - connection.Player!.InventoryManager?.RankUpEquipment((int)req.EquipmentUniqueId, req.CostData); - connection.SendPacket(CmdIds.RankUpEquipmentScRsp); - } + var req = RankUpEquipmentCsReq.Parser.ParseFrom(data); + await connection.Player!.InventoryManager!.RankUpEquipment((int)req.EquipmentUniqueId, req.CostData); + await connection.SendPacket(CmdIds.RankUpEquipmentScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerSetAssistAvatarCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerSetAssistAvatarCsReq.cs index d1ce2eb3..c429b6a5 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerSetAssistAvatarCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerSetAssistAvatarCsReq.cs @@ -1,26 +1,23 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Avatar; -using EggLink.DanhengServer.Server.Packet.Send.Others; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.SetAssistAvatarCsReq)] +public class HandlerSetAssistAvatarCsReq : Handler { - [Opcode(CmdIds.SetAssistAvatarCsReq)] - public class HandlerSetAssistAvatarCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = SetAssistAvatarCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + var avatars = player.AvatarManager!.AvatarData!.AssistAvatars; + avatars.Clear(); + foreach (var id in req.AvatarIdList) { - var req = SetAssistAvatarCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - var avatars = player.AvatarManager!.AvatarData!.AssistAvatars; - avatars.Clear(); - foreach (var id in req.AvatarIdList) - { - if (id == 0) continue; - avatars.Add((int)id); - } - DatabaseHelper.Instance!.UpdateInstance(player.AvatarManager.AvatarData!); - connection.SendPacket(new PacketSetAssistAvatarScRsp(req.AvatarIdList)); + if (id == 0) continue; + avatars.Add((int)id); } + + await connection.SendPacket(new PacketSetAssistAvatarScRsp(req.AvatarIdList)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerSetDisplayAvatarCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerSetDisplayAvatarCsReq.cs index ef0f486f..c4b1b4a5 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerSetDisplayAvatarCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerSetDisplayAvatarCsReq.cs @@ -1,30 +1,23 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Avatar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.SetDisplayAvatarCsReq)] +public class HandlerSetDisplayAvatarCsReq : Handler { - [Opcode(CmdIds.SetDisplayAvatarCsReq)] - public class HandlerSetDisplayAvatarCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = SetDisplayAvatarCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + var avatars = player.AvatarManager!.AvatarData!.DisplayAvatars; + avatars.Clear(); + foreach (var id in req.DisplayAvatarList) { - var req = SetDisplayAvatarCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - var avatars = player.AvatarManager!.AvatarData!.DisplayAvatars; - avatars.Clear(); - foreach (var id in req.DisplayAvatarList) - { - if (id.AvatarId == 0) continue; - avatars.Add((int)id.AvatarId); - } - DatabaseHelper.Instance!.UpdateInstance(player.AvatarManager.AvatarData!); - connection.SendPacket(new PacketSetDisplayAvatarScRsp(req.DisplayAvatarList)); + if (id.AvatarId == 0) continue; + avatars.Add((int)id.AvatarId); } + + await connection.SendPacket(new PacketSetDisplayAvatarScRsp(req.DisplayAvatarList)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerTakeOffEquipmentCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerTakeOffEquipmentCsReq.cs index aa6cee00..ca05ce4e 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerTakeOffEquipmentCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerTakeOffEquipmentCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.TakeOffEquipmentCsReq)] +public class HandlerTakeOffEquipmentCsReq : Handler { - [Opcode(CmdIds.TakeOffEquipmentCsReq)] - public class HandlerTakeOffEquipmentCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = TakeOffEquipmentCsReq.Parser.ParseFrom(data); - connection.Player!.InventoryManager!.UnequipEquipment((int)req.DressAvatarId); + var req = TakeOffEquipmentCsReq.Parser.ParseFrom(data); + await connection.Player!.InventoryManager!.UnequipEquipment((int)req.DressAvatarId); - connection.SendPacket(CmdIds.TakeOffEquipmentScRsp); - } + await connection.SendPacket(CmdIds.TakeOffEquipmentScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerTakeOffRelicCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerTakeOffRelicCsReq.cs index 10477052..961e7dc6 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerTakeOffRelicCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerTakeOffRelicCsReq.cs @@ -1,18 +1,16 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.TakeOffRelicCsReq)] +public class HandlerTakeOffRelicCsReq : Handler { - [Opcode(CmdIds.TakeOffRelicCsReq)] - public class HandlerTakeOffRelicCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = TakeOffRelicCsReq.Parser.ParseFrom(data); - foreach (var param in req.RelicTypeList) - { - connection.Player!.InventoryManager!.UnequipRelic((int)req.DressAvatarId, (int)param); - } - connection.SendPacket(CmdIds.TakeOffRelicScRsp); - } + var req = TakeOffRelicCsReq.Parser.ParseFrom(data); + foreach (var param in req.RelicTypeList) + await connection.Player!.InventoryManager!.UnequipRelic((int)req.DressAvatarId, (int)param); + + await connection.SendPacket(CmdIds.TakeOffRelicScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerTakePromotionRewardCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerTakePromotionRewardCsReq.cs index cb1746e9..b2b0a320 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerTakePromotionRewardCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerTakePromotionRewardCsReq.cs @@ -1,31 +1,22 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Avatar; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.TakePromotionRewardCsReq)] +public class HandlerTakePromotionRewardCsReq : Handler { - [Opcode(CmdIds.TakePromotionRewardCsReq)] - public class HandlerTakePromotionRewardCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = TakePromotionRewardCsReq.Parser.ParseFrom(data); + var req = TakePromotionRewardCsReq.Parser.ParseFrom(data); - var avatar = connection.Player!.AvatarManager!.GetAvatar((int)req.BaseAvatarId); - if (avatar == null) - { - return; - } - avatar.TakeReward((int)req.Promotion); - connection.Player!.InventoryManager!.AddItem(101, 1, false); - connection.SendPacket(new PacketPlayerSyncScNotify(avatar)); + var avatar = connection.Player!.AvatarManager!.GetAvatar((int)req.BaseAvatarId); + if (avatar == null) return; + avatar.TakeReward((int)req.Promotion); + await connection.Player!.InventoryManager!.AddItem(101, 1, false); + await connection.SendPacket(new PacketPlayerSyncScNotify(avatar)); - connection.SendPacket(new PacketTakePromotionRewardScRsp()); - } + await connection.SendPacket(new PacketTakePromotionRewardScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Avatar/HandlerUnlockSkilltreeCsReq.cs b/GameServer/Server/Packet/Recv/Avatar/HandlerUnlockSkilltreeCsReq.cs index c280be89..7aa842ff 100644 --- a/GameServer/Server/Packet/Recv/Avatar/HandlerUnlockSkilltreeCsReq.cs +++ b/GameServer/Server/Packet/Recv/Avatar/HandlerUnlockSkilltreeCsReq.cs @@ -3,44 +3,39 @@ using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Avatar; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar +namespace EggLink.DanhengServer.Server.Packet.Recv.Avatar; + +[Opcode(CmdIds.UnlockSkilltreeCsReq)] +public class HandlerUnlockSkilltreeCsReq : Handler { - [Opcode(CmdIds.UnlockSkilltreeCsReq)] - public class HandlerUnlockSkilltreeCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = UnlockSkilltreeCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + GameData.AvatarSkillTreeConfigData.TryGetValue((int)(req.PointId * 10 + req.Level), out var config); + if (config == null) { - var req = UnlockSkilltreeCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - GameData.AvatarSkillTreeConfigData.TryGetValue((int)(req.PointId * 10 + req.Level), out var config); - if (config == null) - { - connection.SendPacket(new PacketUnlockSkilltreeScRsp()); - return; - } - var avatar = player.AvatarManager!.GetAvatar(config.AvatarID); - if (avatar == null) - { - connection.SendPacket(new PacketUnlockSkilltreeScRsp()); - return; - } - foreach (var cost in req.ItemList) - { - connection.Player!.InventoryManager!.RemoveItem((int)cost.PileItem.ItemId, (int)cost.PileItem.ItemNum); - } - - avatar.GetSkillTree().TryGetValue((int)req.PointId, out var level); - avatar.GetSkillTree()[(int)req.PointId] = level + 1; - DatabaseHelper.Instance!.UpdateInstance(player.AvatarManager.AvatarData!); - - connection.SendPacket(new PacketPlayerSyncScNotify(avatar)); - connection.SendPacket(new PacketUnlockSkilltreeScRsp(req.PointId, req.Level)); + await connection.SendPacket(new PacketUnlockSkilltreeScRsp()); + return; } + + var avatar = player.AvatarManager!.GetAvatar(config.AvatarID); + if (avatar == null) + { + await connection.SendPacket(new PacketUnlockSkilltreeScRsp()); + return; + } + + foreach (var cost in req.ItemList) + await connection.Player!.InventoryManager!.RemoveItem((int)cost.PileItem.ItemId, + (int)cost.PileItem.ItemNum); + + avatar.GetSkillTree().TryGetValue((int)req.PointId, out var level); + avatar.GetSkillTree()[(int)req.PointId] = level + 1; + DatabaseHelper.Instance!.UpdateInstance(player.AvatarManager.AvatarData!); + + await connection.SendPacket(new PacketPlayerSyncScNotify(avatar)); + await connection.SendPacket(new PacketUnlockSkilltreeScRsp(req.PointId, req.Level)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Battle/HandlerGetCurBattleInfoCsReq.cs b/GameServer/Server/Packet/Recv/Battle/HandlerGetCurBattleInfoCsReq.cs index ebb43765..1586425d 100644 --- a/GameServer/Server/Packet/Recv/Battle/HandlerGetCurBattleInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Battle/HandlerGetCurBattleInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.Battle; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; + +[Opcode(CmdIds.GetCurBattleInfoCsReq)] +public class HandlerGetCurBattleInfoCsReq : Handler { - [Opcode(CmdIds.GetCurBattleInfoCsReq)] - public class HandlerGetCurBattleInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetCurBattleInfoScRsp()); - } + await connection.SendPacket(new PacketGetCurBattleInfoScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Battle/HandlerGetFarmStageGachaInfoCsReq.cs b/GameServer/Server/Packet/Recv/Battle/HandlerGetFarmStageGachaInfoCsReq.cs index d50245dd..475b0dfb 100644 --- a/GameServer/Server/Packet/Recv/Battle/HandlerGetFarmStageGachaInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Battle/HandlerGetFarmStageGachaInfoCsReq.cs @@ -1,15 +1,14 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Battle; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; + +[Opcode(CmdIds.GetFarmStageGachaInfoCsReq)] +public class HandlerGetFarmStageGachaInfoCsReq : Handler { - [Opcode(CmdIds.GetFarmStageGachaInfoCsReq)] - public class HandlerGetFarmStageGachaInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetFarmStageGachaInfoCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetFarmStageGachaInfoScRsp(req)); - } + var req = GetFarmStageGachaInfoCsReq.Parser.ParseFrom(data); + await connection.SendPacket(new PacketGetFarmStageGachaInfoScRsp(req)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Battle/HandlerPVEBattleResultCsReq.cs b/GameServer/Server/Packet/Recv/Battle/HandlerPVEBattleResultCsReq.cs index 8712ba6f..6d591615 100644 --- a/GameServer/Server/Packet/Recv/Battle/HandlerPVEBattleResultCsReq.cs +++ b/GameServer/Server/Packet/Recv/Battle/HandlerPVEBattleResultCsReq.cs @@ -1,14 +1,13 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; + +[Opcode(CmdIds.PVEBattleResultCsReq)] +public class HandlerPVEBattleResultCsReq : Handler { - [Opcode(CmdIds.PVEBattleResultCsReq)] - public class HandlerPVEBattleResultCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = PVEBattleResultCsReq.Parser.ParseFrom(data); - connection.Player?.BattleManager?.EndBattle(req); - } + var req = PVEBattleResultCsReq.Parser.ParseFrom(data); + await connection.Player!.BattleManager!.EndBattle(req); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Battle/HandlerQuitBattleCsReq.cs b/GameServer/Server/Packet/Recv/Battle/HandlerQuitBattleCsReq.cs index e8d9db96..b5aa029a 100644 --- a/GameServer/Server/Packet/Recv/Battle/HandlerQuitBattleCsReq.cs +++ b/GameServer/Server/Packet/Recv/Battle/HandlerQuitBattleCsReq.cs @@ -1,18 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle +[Opcode(CmdIds.QuitBattleCsReq)] +public class HandlerQuitBattleCsReq : Handler { - [Opcode(CmdIds.QuitBattleCsReq)] - public class HandlerQuitBattleCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.Player!.BattleInstance = null; - connection.SendPacket(CmdIds.QuitBattleScRsp); - } + connection.Player!.BattleInstance = null; + await connection.SendPacket(CmdIds.QuitBattleScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Battle/HandlerSceneCastSkillCsReq.cs b/GameServer/Server/Packet/Recv/Battle/HandlerSceneCastSkillCsReq.cs index de70fea7..88a56313 100644 --- a/GameServer/Server/Packet/Recv/Battle/HandlerSceneCastSkillCsReq.cs +++ b/GameServer/Server/Packet/Recv/Battle/HandlerSceneCastSkillCsReq.cs @@ -1,71 +1,55 @@ using EggLink.DanhengServer.Game.Battle.Skill; -using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Battle; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; + +[Opcode(CmdIds.SceneCastSkillCsReq)] +public class HandlerSceneCastSkillCsReq : Handler { - [Opcode(CmdIds.SceneCastSkillCsReq)] - public class HandlerSceneCastSkillCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = SceneCastSkillCsReq.Parser.ParseFrom(data); + + MazeSkill mazeSkill = new([]); + + // Get casting avatar + connection.Player!.SceneInstance!.AvatarInfo.TryGetValue((int)req.AttackedByEntityId, out var caster); + + if (caster != null) { - var req = SceneCastSkillCsReq.Parser.ParseFrom(data); - - PlayerInstance player = connection.Player!; - MazeSkill mazeSkill = new([]); - - // Get casting avatar - connection.Player!.SceneInstance!.AvatarInfo.TryGetValue((int)req.AttackedByEntityId, out var caster); - - if (caster != null) + // Check if normal attack or technique was used + if (req.SkillIndex > 0) { - // Check if normal attack or technique was used - if (req.SkillIndex > 0) + // Cast skill effects + if (caster.AvatarInfo.Excel!.MazeSkill != null) { - // Cast skill effects - if (caster.AvatarInfo.Excel!.MazeSkill != null) - { - mazeSkill = MazeSkillManager.GetSkill(caster.AvatarInfo.GetAvatarId(), (int)req.SkillIndex); - mazeSkill.OnCast(caster); - } + mazeSkill = MazeSkillManager.GetSkill(caster.AvatarInfo.GetAvatarId(), (int)req.SkillIndex); + mazeSkill.OnCast(caster); } - else - { - mazeSkill = MazeSkillManager.GetSkill(caster.AvatarInfo.GetAvatarId(), 0); - } - } - - if (req.AssistMonsterEntityIdList.Count > 0) - { - List hitTargetEntityIdList = []; - if (req.AssistMonsterEntityIdList.Count > 0) - { - foreach (uint id in req.AssistMonsterEntityIdList) - { - hitTargetEntityIdList.Add(id); - } - } - else - { - foreach (uint id in req.HitTargetEntityIdList) - { - hitTargetEntityIdList.Add(id); - } - } - // Start battle - connection.Player!.BattleManager!.StartBattle(req, mazeSkill!, [.. hitTargetEntityIdList]); } else { - // We had no targets for some reason - connection.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); + mazeSkill = MazeSkillManager.GetSkill(caster.AvatarInfo.GetAvatarId(), 0); } } + + if (req.AssistMonsterEntityIdList.Count > 0) + { + List hitTargetEntityIdList = []; + if (req.AssistMonsterEntityIdList.Count > 0) + foreach (var id in req.AssistMonsterEntityIdList) + hitTargetEntityIdList.Add(id); + else + foreach (var id in req.HitTargetEntityIdList) + hitTargetEntityIdList.Add(id); + // Start battle + await connection.Player!.BattleManager!.StartBattle(req, mazeSkill!, [.. hitTargetEntityIdList]); + } + else + { + // We had no targets for some reason + await connection.SendPacket(new PacketSceneCastSkillScRsp(req.CastEntityId)); + } } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Battle/HandlerSceneEnterStageCsReq.cs b/GameServer/Server/Packet/Recv/Battle/HandlerSceneEnterStageCsReq.cs index c9155712..4fcf938c 100644 --- a/GameServer/Server/Packet/Recv/Battle/HandlerSceneEnterStageCsReq.cs +++ b/GameServer/Server/Packet/Recv/Battle/HandlerSceneEnterStageCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; + +[Opcode(CmdIds.SceneEnterStageCsReq)] +public class HandlerSceneEnterStageCsReq : Handler { - [Opcode(CmdIds.SceneEnterStageCsReq)] - public class HandlerSceneEnterStageCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SceneEnterStageCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - player.BattleManager!.StartStage((int)req.EventId); - } + var req = SceneEnterStageCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + await player.BattleManager!.StartStage((int)req.EventId); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Battle/HandlerStartCocoonStageCsReq.cs b/GameServer/Server/Packet/Recv/Battle/HandlerStartCocoonStageCsReq.cs index 54076db3..9a5948b9 100644 --- a/GameServer/Server/Packet/Recv/Battle/HandlerStartCocoonStageCsReq.cs +++ b/GameServer/Server/Packet/Recv/Battle/HandlerStartCocoonStageCsReq.cs @@ -1,19 +1,13 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; + +[Opcode(CmdIds.StartCocoonStageCsReq)] +public class HandlerStartCocoonStageCsReq : Handler { - [Opcode(CmdIds.StartCocoonStageCsReq)] - public class HandlerStartCocoonStageCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = StartCocoonStageCsReq.Parser.ParseFrom(data); - connection.Player?.BattleManager?.StartCocoonStage((int)req.CocoonId, (int)req.Wave, (int)req.WorldLevel); - } + var req = StartCocoonStageCsReq.Parser.ParseFrom(data); + await connection.Player!.BattleManager!.StartCocoonStage((int)req.CocoonId, (int)req.Wave, (int)req.WorldLevel); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Challenge/HandlerGetChallengeCsReq.cs b/GameServer/Server/Packet/Recv/Challenge/HandlerGetChallengeCsReq.cs index c5f3b048..0470ac1e 100644 --- a/GameServer/Server/Packet/Recv/Challenge/HandlerGetChallengeCsReq.cs +++ b/GameServer/Server/Packet/Recv/Challenge/HandlerGetChallengeCsReq.cs @@ -1,13 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Battle; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; + +[Opcode(CmdIds.GetChallengeCsReq)] +public class HandlerGetChallengeCsReq : Handler { - [Opcode(CmdIds.GetChallengeCsReq)] - public class HandlerGetChallengeCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetChallengeScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetChallengeScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Challenge/HandlerGetCurChallengeCsReq.cs b/GameServer/Server/Packet/Recv/Challenge/HandlerGetCurChallengeCsReq.cs index 0d108eb4..594e18d1 100644 --- a/GameServer/Server/Packet/Recv/Challenge/HandlerGetCurChallengeCsReq.cs +++ b/GameServer/Server/Packet/Recv/Challenge/HandlerGetCurChallengeCsReq.cs @@ -1,20 +1,17 @@ using EggLink.DanhengServer.Server.Packet.Send.Battle; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle -{ - [Opcode(CmdIds.GetCurChallengeCsReq)] - public class HandlerGetCurChallengeCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - // Send packet first - connection.SendPacket(new PacketGetCurChallengeScRsp(connection.Player!)); +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; - // Update data - if (connection.Player!.ChallengeManager!.ChallengeInstance != null) - { - connection.Player.ChallengeManager.ChallengeInstance.OnUpdate(); - } - } +[Opcode(CmdIds.GetCurChallengeCsReq)] +public class HandlerGetCurChallengeCsReq : Handler +{ + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + // Send packet first + await connection.SendPacket(new PacketGetCurChallengeScRsp(connection.Player!)); + + // Update data + if (connection.Player!.ChallengeManager!.ChallengeInstance != null) + connection.Player.ChallengeManager.ChallengeInstance.OnUpdate(); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Challenge/HandlerLeaveChallengeCsReq.cs b/GameServer/Server/Packet/Recv/Challenge/HandlerLeaveChallengeCsReq.cs index 74f1ef7d..e94f30c0 100644 --- a/GameServer/Server/Packet/Recv/Challenge/HandlerLeaveChallengeCsReq.cs +++ b/GameServer/Server/Packet/Recv/Challenge/HandlerLeaveChallengeCsReq.cs @@ -1,42 +1,38 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Server.Packet.Recv.Challenge +namespace EggLink.DanhengServer.Server.Packet.Recv.Challenge; + +[Opcode(CmdIds.LeaveChallengeCsReq)] +public class HandlerLeaveChallengeCsReq : Handler { - [Opcode(CmdIds.LeaveChallengeCsReq)] - public class HandlerLeaveChallengeCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var player = connection.Player!; + + // TODO: check for plane type + if (player.SceneInstance != null) { - var player = connection.Player!; + // As of 1.5.0, the server now has to handle the player leaving battle too + await player.ForceQuitBattle(); - // TODO: check for plane type - if (player.SceneInstance != null) - { - // As of 1.5.0, the server now has to handle the player leaving battle too - player.ForceQuitBattle(); + // Reset lineup + player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupChallenge, []); + player.LineupManager.SetExtraLineup(ExtraLineupType.LineupChallenge2, []); - // Reset lineup - player.LineupManager!.SetExtraLineup(ExtraLineupType.LineupChallenge, []); - player.LineupManager.SetExtraLineup(ExtraLineupType.LineupChallenge2, []); + player.ChallengeManager!.ChallengeInstance = null; + player.ChallengeManager!.ClearInstance(); - player.ChallengeManager!.ChallengeInstance = null; - player.ChallengeManager!.ClearInstance(); + // Leave scene + await player.LineupManager.SetCurLineup(0); + // Heal avatars (temproary solution) + foreach (var avatar in player.LineupManager.GetCurLineup()!.AvatarData!.Avatars) avatar.CurrentHp = 10000; - // Leave scene - player.LineupManager.SetCurLineup(0); - // Heal avatars (temproary solution) - foreach (var avatar in player.LineupManager.GetCurLineup()!.AvatarData!.Avatars) - { - avatar.CurrentHp = 10000; - } - - int leaveEntryId = GameConstants.CHALLENGE_ENTRANCE; - if (player.SceneInstance.LeaveEntityId != 0) leaveEntryId = player.SceneInstance.LeaveEntityId; - player.EnterScene(leaveEntryId, 0, true); - } - - connection.SendPacket(CmdIds.LeaveChallengeScRsp); + var leaveEntryId = GameConstants.CHALLENGE_ENTRANCE; + if (player.SceneInstance.LeaveEntityId != 0) leaveEntryId = player.SceneInstance.LeaveEntityId; + await player.EnterScene(leaveEntryId, 0, true); } + + await connection.SendPacket(CmdIds.LeaveChallengeScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Challenge/HandlerStartChallengeCsReq.cs b/GameServer/Server/Packet/Recv/Challenge/HandlerStartChallengeCsReq.cs index c1915f06..8fa62f2e 100644 --- a/GameServer/Server/Packet/Recv/Challenge/HandlerStartChallengeCsReq.cs +++ b/GameServer/Server/Packet/Recv/Challenge/HandlerStartChallengeCsReq.cs @@ -1,37 +1,31 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Recv.Battle +namespace EggLink.DanhengServer.Server.Packet.Recv.Battle; + +[Opcode(CmdIds.StartChallengeCsReq)] +public class HandlerStartChallengeCsReq : Handler { - [Opcode(CmdIds.StartChallengeCsReq)] - public class HandlerStartChallengeCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = StartChallengeCsReq.Parser.ParseFrom(data); + var req = StartChallengeCsReq.Parser.ParseFrom(data); - StartChallengeStoryBuffInfo? storyBuffInfo = null; - if (req.PlayerInfo != null && req.PlayerInfo.StoryBuffInfo != null) - { - storyBuffInfo = req.PlayerInfo.StoryBuffInfo; - }; + StartChallengeStoryBuffInfo? storyBuffInfo = null; + if (req.PlayerInfo != null && req.PlayerInfo.StoryBuffInfo != null) + storyBuffInfo = req.PlayerInfo.StoryBuffInfo; + ; - StartChallengeBossBuffInfo? bossBuffInfo = null; - if (req.PlayerInfo != null && req.PlayerInfo.BossBuffInfo != null) - { - bossBuffInfo = req.PlayerInfo.BossBuffInfo; - }; - - if (req.TeamOne.Count > 0) - { - connection.Player!.LineupManager!.ReplaceLineup(0, req.TeamOne.Select(x => (int)x).ToList(), ExtraLineupType.LineupChallenge); - } + StartChallengeBossBuffInfo? bossBuffInfo = null; + if (req.PlayerInfo != null && req.PlayerInfo.BossBuffInfo != null) bossBuffInfo = req.PlayerInfo.BossBuffInfo; + ; - if (req.TeamTwo.Count > 0) - { - connection.Player!.LineupManager!.ReplaceLineup(0, req.TeamTwo.Select(x => (int)x).ToList(), ExtraLineupType.LineupChallenge2); - } + if (req.TeamOne.Count > 0) + await connection.Player!.LineupManager!.ReplaceLineup(0, req.TeamOne.Select(x => (int)x).ToList(), + ExtraLineupType.LineupChallenge); - connection.Player!.ChallengeManager!.StartChallenge((int)req.ChallengeId, storyBuffInfo, bossBuffInfo); - } + if (req.TeamTwo.Count > 0) + await connection.Player!.LineupManager!.ReplaceLineup(0, req.TeamTwo.Select(x => (int)x).ToList(), + ExtraLineupType.LineupChallenge2); + + await connection.Player!.ChallengeManager!.StartChallenge((int)req.ChallengeId, storyBuffInfo, bossBuffInfo); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Challenge/HandlerTakeChallengeRewardCsReq.cs b/GameServer/Server/Packet/Recv/Challenge/HandlerTakeChallengeRewardCsReq.cs index 62528244..10d7030c 100644 --- a/GameServer/Server/Packet/Recv/Challenge/HandlerTakeChallengeRewardCsReq.cs +++ b/GameServer/Server/Packet/Recv/Challenge/HandlerTakeChallengeRewardCsReq.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Challenge; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Challenge +namespace EggLink.DanhengServer.Server.Packet.Recv.Challenge; + +[Opcode(CmdIds.TakeChallengeRewardCsReq)] +public class HandlerTakeChallengeRewardCsReq : Handler { - [Opcode(CmdIds.TakeChallengeRewardCsReq)] - public class HandlerTakeChallengeRewardCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = TakeChallengeRewardCsReq.Parser.ParseFrom(data); + var req = TakeChallengeRewardCsReq.Parser.ParseFrom(data); - List? rewardInfos = connection.Player!.ChallengeManager!.TakeRewards((int)req.GroupId)!; - connection.SendPacket(new PacketTakeChallengeRewardScRsp((int)req.GroupId, rewardInfos)); - } + var rewardInfos = await connection.Player!.ChallengeManager!.TakeRewards((int)req.GroupId)!; + await connection.SendPacket(new PacketTakeChallengeRewardScRsp((int)req.GroupId, rewardInfos)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueConfirmRollCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueConfirmRollCsReq.cs index 97bee50e..1ea39a44 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueConfirmRollCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueConfirmRollCsReq.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +[Opcode(CmdIds.ChessRogueConfirmRollCsReq)] +public class HandlerChessRogueConfirmRollCsReq : Handler { - [Opcode(CmdIds.ChessRogueConfirmRollCsReq)] - public class HandlerChessRogueConfirmRollCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.Player!.ChessRogueManager!.RogueInstance?.ConfirmRoll(); - } + await connection.Player!.ChessRogueManager!.RogueInstance!.ConfirmRoll(); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueEnterCellCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueEnterCellCsReq.cs index a33238a7..7b88beeb 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueEnterCellCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueEnterCellCsReq.cs @@ -1,22 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.ChessRogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; + +[Opcode(CmdIds.ChessRogueEnterCellCsReq)] +public class HandlerChessRogueEnterCellCsReq : Handler { - [Opcode(CmdIds.ChessRogueEnterCellCsReq)] - public class HandlerChessRogueEnterCellCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ChessRogueEnterCellCsReq.Parser.ParseFrom(data); - connection.Player!.ChessRogueManager!.RogueInstance?.EnterCell((int)req.CellId, (int)req.SelectMonsterId); + var req = ChessRogueEnterCellCsReq.Parser.ParseFrom(data); + await connection.Player!.ChessRogueManager!.RogueInstance!.EnterCell((int)req.CellId, (int)req.SelectMonsterId); - connection.SendPacket(new PacketChessRogueEnterCellScRsp(req.CellId, connection.Player!.ChessRogueManager!.RogueInstance!)); - } + await connection.SendPacket(new PacketChessRogueEnterCellScRsp(req.CellId, + connection.Player!.ChessRogueManager!.RogueInstance!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueEnterNextLayerCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueEnterNextLayerCsReq.cs index c95a4687..a7cd4c02 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueEnterNextLayerCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueEnterNextLayerCsReq.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +[Opcode(CmdIds.ChessRogueEnterNextLayerCsReq)] +public class HandlerChessRogueEnterNextLayerCsReq : Handler { - [Opcode(CmdIds.ChessRogueEnterNextLayerCsReq)] - public class HandlerChessRogueEnterNextLayerCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.Player!.ChessRogueManager!.RogueInstance?.EnterNextLayer(); - } + await connection.Player!.ChessRogueManager!.RogueInstance!.EnterNextLayer(); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueLeaveCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueLeaveCsReq.cs index 63cbf3ce..a2ca9aac 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueLeaveCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueLeaveCsReq.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +[Opcode(CmdIds.ChessRogueLeaveCsReq)] +public class HandlerChessRogueLeaveCsReq : Handler { - [Opcode(CmdIds.ChessRogueLeaveCsReq)] - public class HandlerChessRogueLeaveCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.Player!.ChessRogueManager!.RogueInstance?.LeaveRogue(); - } + await connection.Player!.ChessRogueManager!.RogueInstance!.LeaveRogue(); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueNousEditDiceCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueNousEditDiceCsReq.cs index 7401f918..9a67ee27 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueNousEditDiceCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueNousEditDiceCsReq.cs @@ -1,24 +1,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.ChessRogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; + +[Opcode(CmdIds.ChessRogueNousEditDiceCsReq)] +public class HandlerChessRogueNousEditDiceCsReq : Handler { - [Opcode(CmdIds.ChessRogueNousEditDiceCsReq)] - public class HandlerChessRogueNousEditDiceCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var player = connection.Player!; - var req = ChessRogueNousEditDiceCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + var req = ChessRogueNousEditDiceCsReq.Parser.ParseFrom(data); - var diceData = player.ChessRogueManager!.SetDice(req.DiceInfo); + var diceData = player.ChessRogueManager!.SetDice(req.DiceInfo); - connection.SendPacket(new PacketChessRogueNousEditDiceScRsp(diceData)); - } + await connection.SendPacket(new PacketChessRogueNousEditDiceScRsp(diceData)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueQueryCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueQueryCsReq.cs index 0c819026..aac1a36e 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueQueryCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueQueryCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.ChessRogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; + +[Opcode(CmdIds.ChessRogueQueryCsReq)] +public class HandlerChessRogueQueryCsReq : Handler { - [Opcode(CmdIds.ChessRogueQueryCsReq)] - public class HandlerChessRogueQueryCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketChessRogueQueryScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketChessRogueQueryScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueQuitCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueQuitCsReq.cs index b27c6197..ec725537 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueQuitCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueQuitCsReq.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +[Opcode(CmdIds.ChessRogueQuitCsReq)] +public class HandlerChessRogueQuitCsReq : Handler { - [Opcode(CmdIds.ChessRogueQuitCsReq)] - public class HandlerChessRogueQuitCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.Player!.ChessRogueManager!.RogueInstance?.QuitRogue(); - } + await connection.Player!.ChessRogueManager!.RogueInstance!.QuitRogue(); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueRollDiceCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueRollDiceCsReq.cs index c1c4e64e..8e92eb34 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueRollDiceCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueRollDiceCsReq.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +[Opcode(CmdIds.ChessRogueRollDiceCsReq)] +public class HandlerChessRogueRollDiceCsReq : Handler { - [Opcode(CmdIds.ChessRogueRollDiceCsReq)] - public class HandlerChessRogueRollDiceCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.Player!.ChessRogueManager!.RogueInstance?.RollDice(); - } + await connection.Player!.ChessRogueManager!.RogueInstance!.RollDice(); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueStartCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueStartCsReq.cs index 8a100335..6df94deb 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueStartCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerChessRogueStartCsReq.cs @@ -1,40 +1,27 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; + +[Opcode(CmdIds.ChessRogueStartCsReq)] +public class HandlerChessRogueStartCsReq : Handler { - [Opcode(CmdIds.ChessRogueStartCsReq)] - public class HandlerChessRogueStartCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var player = connection.Player!; - var req = ChessRogueStartCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + var req = ChessRogueStartCsReq.Parser.ParseFrom(data); - var difficultyIdList = new List(); - var disableAeonIdList = new List(); + var difficultyIdList = new List(); + var disableAeonIdList = new List(); - if (req.DifficultyIdList != null) - { - foreach (var difficultyId in req.DifficultyIdList) - { - difficultyIdList.Add((int)difficultyId); - } - } + if (req.DifficultyIdList != null) + foreach (var difficultyId in req.DifficultyIdList) + difficultyIdList.Add((int)difficultyId); - if (req.DisableAeonIdList != null) - { - foreach (var disableAeonId in req.DisableAeonIdList) - { - disableAeonIdList.Add((int)disableAeonId); - } - } + if (req.DisableAeonIdList != null) + foreach (var disableAeonId in req.DisableAeonIdList) + disableAeonIdList.Add((int)disableAeonId); - player.ChessRogueManager!.StartRogue((int)req.AeonId, [.. req.BaseAvatarIdList], (int)req.Id, (int)req.BranchId, difficultyIdList, disableAeonIdList); - } + await player.ChessRogueManager!.StartRogue((int)req.AeonId, [.. req.BaseAvatarIdList], (int)req.Id, + (int)req.BranchId, difficultyIdList, disableAeonIdList); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerGetChessRogueBuffEnhanceInfoCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerGetChessRogueBuffEnhanceInfoCsReq.cs index eb444f1a..3f1b41c2 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerGetChessRogueBuffEnhanceInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerGetChessRogueBuffEnhanceInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.ChessRogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; + +[Opcode(CmdIds.GetChessRogueBuffEnhanceInfoCsReq)] +public class HandlerGetChessRogueBuffEnhanceInfoCsReq : Handler { - [Opcode(CmdIds.GetChessRogueBuffEnhanceInfoCsReq)] - public class HandlerGetChessRogueBuffEnhanceInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetChessRogueBuffEnhanceInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetChessRogueBuffEnhanceInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/ChessRogue/HandlerGetChessRogueNousStoryInfoCsReq.cs b/GameServer/Server/Packet/Recv/ChessRogue/HandlerGetChessRogueNousStoryInfoCsReq.cs index 68ef6f41..aef799fb 100644 --- a/GameServer/Server/Packet/Recv/ChessRogue/HandlerGetChessRogueNousStoryInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/ChessRogue/HandlerGetChessRogueNousStoryInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.ChessRogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Recv.ChessRogue; + +[Opcode(CmdIds.GetChessRogueNousStoryInfoCsReq)] +public class HandlerGetChessRogueNousStoryInfoCsReq : Handler { - [Opcode(CmdIds.GetChessRogueNousStoryInfoCsReq)] - public class HandlerGetChessRogueNousStoryInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetChessRogueNousStoryInfoScRsp()); - } + await connection.SendPacket(new PacketGetChessRogueNousStoryInfoScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Friend/HandlerApplyFriendCsReq.cs b/GameServer/Server/Packet/Recv/Friend/HandlerApplyFriendCsReq.cs index 087a53b5..8e6eeea3 100644 --- a/GameServer/Server/Packet/Recv/Friend/HandlerApplyFriendCsReq.cs +++ b/GameServer/Server/Packet/Recv/Friend/HandlerApplyFriendCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Friend; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Friend +namespace EggLink.DanhengServer.Server.Packet.Recv.Friend; + +[Opcode(CmdIds.ApplyFriendCsReq)] +public class HandlerApplyFriendCsReq : Handler { - [Opcode(CmdIds.ApplyFriendCsReq)] - public class HandlerApplyFriendCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ApplyFriendCsReq.Parser.ParseFrom(data); + var req = ApplyFriendCsReq.Parser.ParseFrom(data); - connection.Player!.FriendManager!.AddFriend((int)req.Uid); + await connection.Player!.FriendManager!.AddFriend((int)req.Uid); - connection.SendPacket(new PacketApplyFriendScRsp(req.Uid)); - } + await connection.SendPacket(new PacketApplyFriendScRsp(req.Uid)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Friend/HandlerGetChatFriendHistoryCsReq.cs b/GameServer/Server/Packet/Recv/Friend/HandlerGetChatFriendHistoryCsReq.cs index 8bc7b8e3..eba1bb20 100644 --- a/GameServer/Server/Packet/Recv/Friend/HandlerGetChatFriendHistoryCsReq.cs +++ b/GameServer/Server/Packet/Recv/Friend/HandlerGetChatFriendHistoryCsReq.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.Friend; -namespace EggLink.DanhengServer.Server.Packet.Recv.Friend +[Opcode(CmdIds.GetChatFriendHistoryCsReq)] +public class HandlerGetChatFriendHistoryCsReq : Handler { - [Opcode(CmdIds.GetChatFriendHistoryCsReq)] - public class HandlerGetChatFriendHistoryCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(CmdIds.GetChatFriendHistoryScRsp); - } + await connection.SendPacket(CmdIds.GetChatFriendHistoryScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Friend/HandlerGetFriendApplyListInfoCsReq.cs b/GameServer/Server/Packet/Recv/Friend/HandlerGetFriendApplyListInfoCsReq.cs index 26457e9f..724839de 100644 --- a/GameServer/Server/Packet/Recv/Friend/HandlerGetFriendApplyListInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Friend/HandlerGetFriendApplyListInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Gacha; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Friend +namespace EggLink.DanhengServer.Server.Packet.Recv.Friend; + +[Opcode(CmdIds.GetFriendApplyListInfoCsReq)] +public class HandlerGetFriendApplyListInfoCsReq : Handler { - [Opcode(CmdIds.GetFriendApplyListInfoCsReq)] - public class HandlerGetFriendApplyListInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetFriendApplyListInfoCsReq(connection)); - } + await connection.SendPacket(new PacketGetFriendApplyListInfoCsReq(connection)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Friend/HandlerGetFriendListInfoCsReq.cs b/GameServer/Server/Packet/Recv/Friend/HandlerGetFriendListInfoCsReq.cs index 292cfa30..d43fbdfc 100644 --- a/GameServer/Server/Packet/Recv/Friend/HandlerGetFriendListInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Friend/HandlerGetFriendListInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Gacha; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Friend +namespace EggLink.DanhengServer.Server.Packet.Recv.Friend; + +[Opcode(CmdIds.GetFriendListInfoCsReq)] +public class HandlerGetFriendListInfoCsReq : Handler { - [Opcode(CmdIds.GetFriendListInfoCsReq)] - public class HandlerGetFriendListInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetFriendListInfoScRsp(connection)); - } + await connection.SendPacket(new PacketGetFriendListInfoScRsp(connection)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Friend/HandlerGetPlayerDetailInfoCsReq.cs b/GameServer/Server/Packet/Recv/Friend/HandlerGetPlayerDetailInfoCsReq.cs index 5dc4f2ca..7f10669b 100644 --- a/GameServer/Server/Packet/Recv/Friend/HandlerGetPlayerDetailInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Friend/HandlerGetPlayerDetailInfoCsReq.cs @@ -2,47 +2,41 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Friend; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Friend +namespace EggLink.DanhengServer.Server.Packet.Recv.Friend; + +[Opcode(CmdIds.GetPlayerDetailInfoCsReq)] +public class HandlerGetPlayerDetailInfoCsReq : Handler { - [Opcode(CmdIds.GetPlayerDetailInfoCsReq)] - public class HandlerGetPlayerDetailInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = GetPlayerDetailInfoCsReq.Parser.ParseFrom(data); + + var playerData = PlayerData.GetPlayerByUid(req.Uid); + + if (playerData == null) { - var req = GetPlayerDetailInfoCsReq.Parser.ParseFrom(data); - - var playerData = PlayerData.GetPlayerByUid(req.Uid); - - if (playerData == null ) + var serverProfile = ConfigManager.Config.ServerOption.ServerProfile; + if (req.Uid == serverProfile.Uid) { - var serverProfile = ConfigManager.Config.ServerOption.ServerProfile; - if (req.Uid == serverProfile.Uid) + playerData = new PlayerData { - playerData = new() - { - Uid = serverProfile.Uid, - HeadIcon = serverProfile.HeadIcon, - Signature = serverProfile.Signature, - Level = serverProfile.Level, - WorldLevel = 0, - Name = serverProfile.Name, - ChatBubble = serverProfile.ChatBubbleId - }; - } - else - { - connection.SendPacket(new PacketGetPlayerDetailInfoScRsp()); - return; - } + Uid = serverProfile.Uid, + HeadIcon = serverProfile.HeadIcon, + Signature = serverProfile.Signature, + Level = serverProfile.Level, + WorldLevel = 0, + Name = serverProfile.Name, + ChatBubble = serverProfile.ChatBubbleId + }; + } + else + { + await connection.SendPacket(new PacketGetPlayerDetailInfoScRsp()); + return; } - - connection.SendPacket(new PacketGetPlayerDetailInfoScRsp(playerData)); } + + await connection.SendPacket(new PacketGetPlayerDetailInfoScRsp(playerData)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Friend/HandlerGetPrivateChatHistoryCsReq.cs b/GameServer/Server/Packet/Recv/Friend/HandlerGetPrivateChatHistoryCsReq.cs index 2cb8258b..f3288e0b 100644 --- a/GameServer/Server/Packet/Recv/Friend/HandlerGetPrivateChatHistoryCsReq.cs +++ b/GameServer/Server/Packet/Recv/Friend/HandlerGetPrivateChatHistoryCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Friend; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Friend +namespace EggLink.DanhengServer.Server.Packet.Recv.Friend; + +[Opcode(CmdIds.GetPrivateChatHistoryCsReq)] +public class HandlerGetPrivateChatHistoryCsReq : Handler { - [Opcode(CmdIds.GetPrivateChatHistoryCsReq)] - public class HandlerGetPrivateChatHistoryCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetPrivateChatHistoryCsReq.Parser.ParseFrom(data); + var req = GetPrivateChatHistoryCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetPrivateChatHistoryScRsp(req.ContactId, connection.Player!)); - } + await connection.SendPacket(new PacketGetPrivateChatHistoryScRsp(req.ContactId, connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Friend/HandlerHandleFriendCsReq.cs b/GameServer/Server/Packet/Recv/Friend/HandlerHandleFriendCsReq.cs index 0a70e3f5..fd7c8f7d 100644 --- a/GameServer/Server/Packet/Recv/Friend/HandlerHandleFriendCsReq.cs +++ b/GameServer/Server/Packet/Recv/Friend/HandlerHandleFriendCsReq.cs @@ -1,38 +1,25 @@ using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Friend; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Friend +namespace EggLink.DanhengServer.Server.Packet.Recv.Friend; + +[Opcode(CmdIds.HandleFriendCsReq)] +public class HandlerHandleFriendCsReq : Handler { - [Opcode(CmdIds.HandleFriendCsReq)] - public class HandlerHandleFriendCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = HandleFriendCsReq.Parser.ParseFrom(data); + var req = HandleFriendCsReq.Parser.ParseFrom(data); - PlayerData? playerData = null; - if (req.IsAccept) - { - playerData =connection.Player!.FriendManager!.ConfirmAddFriend((int)req.Uid); - } - else - { - connection.Player!.FriendManager!.RefuseAddFriend((int)req.Uid); - } + PlayerData? playerData = null; + if (req.IsAccept) + playerData = await connection.Player!.FriendManager!.ConfirmAddFriend((int)req.Uid); + else + connection.Player!.FriendManager!.RefuseAddFriend((int)req.Uid); - if (playerData != null) - { - connection.SendPacket(new PacketHandleFriendScRsp(req.Uid, req.IsAccept, playerData)); - } else - { - connection.SendPacket(new PacketHandleFriendScRsp(req.Uid, req.IsAccept)); - } - } + if (playerData != null) + await connection.SendPacket(new PacketHandleFriendScRsp(req.Uid, req.IsAccept, playerData)); + else + await connection.SendPacket(new PacketHandleFriendScRsp(req.Uid, req.IsAccept)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Friend/HandlerSearchPlayerCsReq.cs b/GameServer/Server/Packet/Recv/Friend/HandlerSearchPlayerCsReq.cs index 1c4176c9..6bb8659d 100644 --- a/GameServer/Server/Packet/Recv/Friend/HandlerSearchPlayerCsReq.cs +++ b/GameServer/Server/Packet/Recv/Friend/HandlerSearchPlayerCsReq.cs @@ -1,38 +1,26 @@ using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Friend; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Friend +namespace EggLink.DanhengServer.Server.Packet.Recv.Friend; + +[Opcode(CmdIds.SearchPlayerCsReq)] +public class HandlerSearchPlayerCsReq : Handler { - [Opcode(CmdIds.SearchPlayerCsReq)] - public class HandlerSearchPlayerCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = SearchPlayerCsReq.Parser.ParseFrom(data); + var playerList = new List(); + + foreach (var uid in req.UidList) { - var req = SearchPlayerCsReq.Parser.ParseFrom(data); - var playerList = new List(); - - foreach (var uid in req.UidList) - { - var player = PlayerData.GetPlayerByUid(uid); - if (player != null) - { - playerList.Add(player); - } - } - - if (playerList.Count == 0) - { - connection.SendPacket(new PacketSearchPlayerScRsp()); - } else - { - connection.SendPacket(new PacketSearchPlayerScRsp(playerList)); - } + var player = PlayerData.GetPlayerByUid(uid); + if (player != null) playerList.Add(player); } + + if (playerList.Count == 0) + await connection.SendPacket(new PacketSearchPlayerScRsp()); + else + await connection.SendPacket(new PacketSearchPlayerScRsp(playerList)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Friend/HandlerSendMsgCsReq.cs b/GameServer/Server/Packet/Recv/Friend/HandlerSendMsgCsReq.cs index 48d95d81..efda5b46 100644 --- a/GameServer/Server/Packet/Recv/Friend/HandlerSendMsgCsReq.cs +++ b/GameServer/Server/Packet/Recv/Friend/HandlerSendMsgCsReq.cs @@ -1,33 +1,21 @@ -using EggLink.DanhengServer.Command; -using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Server.Packet.Send.Friend; -using EggLink.DanhengServer.Server.Packet.Send.Gacha; -using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Recv.Friend +namespace EggLink.DanhengServer.Server.Packet.Recv.Friend; + +[Opcode(CmdIds.SendMsgCsReq)] +public class HandlerSendMsgCsReq : Handler { - [Opcode(CmdIds.SendMsgCsReq)] - public class HandlerSendMsgCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SendMsgCsReq.Parser.ParseFrom(data); + var req = SendMsgCsReq.Parser.ParseFrom(data); - connection.SendPacket(CmdIds.SendMsgScRsp); + await connection.SendPacket(CmdIds.SendMsgScRsp); - if (req.MessageType == MsgType.CustomText) - { - connection.Player!.FriendManager!.SendMessage(connection.Player!.Uid, (int)req.TargetList[0], req.MessageText); - } - else if (req.MessageType == MsgType.Emoji) - { - connection.Player!.FriendManager!.SendMessage(connection.Player!.Uid, (int)req.TargetList[0], null, (int)req.ExtraId); - } - } + if (req.MessageType == MsgType.CustomText) + await connection.Player!.FriendManager!.SendMessage(connection.Player!.Uid, (int)req.TargetList[0], + req.MessageText); + else if (req.MessageType == MsgType.Emoji) + await connection.Player!.FriendManager!.SendMessage(connection.Player!.Uid, (int)req.TargetList[0], null, + (int)req.ExtraId); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Gacha/HandlerDoGachaCsReq.cs b/GameServer/Server/Packet/Recv/Gacha/HandlerDoGachaCsReq.cs index f76f41a0..8f36a819 100644 --- a/GameServer/Server/Packet/Recv/Gacha/HandlerDoGachaCsReq.cs +++ b/GameServer/Server/Packet/Recv/Gacha/HandlerDoGachaCsReq.cs @@ -1,23 +1,19 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Gacha; -namespace EggLink.DanhengServer.Server.Packet.Recv.Gacha -{ - [Opcode(CmdIds.DoGachaCsReq)] - public class HandlerDoGachaCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = DoGachaCsReq.Parser.ParseFrom(data); - var gain = connection.Player!.GachaManager?.DoGacha((int)req.GachaId, (int)req.GachaNum); +namespace EggLink.DanhengServer.Server.Packet.Recv.Gacha; - if (gain != null) - { - connection.SendPacket(new PacketDoGachaScRsp(gain)); - } else - { - connection.SendPacket(new PacketDoGachaScRsp()); - } - } +[Opcode(CmdIds.DoGachaCsReq)] +public class HandlerDoGachaCsReq : Handler +{ + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + var req = DoGachaCsReq.Parser.ParseFrom(data); + var gain = await connection.Player!.GachaManager!.DoGacha((int)req.GachaId, (int)req.GachaNum); + + if (gain != null) + await connection.SendPacket(new PacketDoGachaScRsp(gain)); + else + await connection.SendPacket(new PacketDoGachaScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Gacha/HandlerGetGachaInfoCsReq.cs b/GameServer/Server/Packet/Recv/Gacha/HandlerGetGachaInfoCsReq.cs index dab9eb9f..f45e47af 100644 --- a/GameServer/Server/Packet/Recv/Gacha/HandlerGetGachaInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Gacha/HandlerGetGachaInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Gacha; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Gacha +namespace EggLink.DanhengServer.Server.Packet.Recv.Gacha; + +[Opcode(CmdIds.GetGachaInfoCsReq)] +public class HandlerGetGachaInfoCsReq : Handler { - [Opcode(CmdIds.GetGachaInfoCsReq)] - public class HandlerGetGachaInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetGachaInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetGachaInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/HeartDial/HandlerChangeScriptEmotionCsReq.cs b/GameServer/Server/Packet/Recv/HeartDial/HandlerChangeScriptEmotionCsReq.cs index 919a4844..505b7056 100644 --- a/GameServer/Server/Packet/Recv/HeartDial/HandlerChangeScriptEmotionCsReq.cs +++ b/GameServer/Server/Packet/Recv/HeartDial/HandlerChangeScriptEmotionCsReq.cs @@ -1,25 +1,21 @@ -using EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; +using EggLink.DanhengServer.Enums.Mission; +using EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.HeartDial +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.HeartDial; + +[Opcode(CmdIds.ChangeScriptEmotionCsReq)] +public class HandlerChangeScriptEmotionCsReq : Handler { - [Opcode(CmdIds.ChangeScriptEmotionCsReq)] - public class HandlerChangeScriptEmotionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ChangeScriptEmotionCsReq.Parser.ParseFrom(data); + var req = ChangeScriptEmotionCsReq.Parser.ParseFrom(data); - connection.Player!.HeartDialData!.ChangeScriptEmotion((int)req.ScriptId, (Enums.Mission.HeartDialEmoTypeEnum)req.TargetEmotionType); + connection.Player!.HeartDialData!.ChangeScriptEmotion((int)req.ScriptId, + (HeartDialEmoTypeEnum)req.TargetEmotionType); - connection.SendPacket(new PacketChangeScriptEmotionScRsp(req.ScriptId, req.TargetEmotionType)); - } + await connection.SendPacket(new PacketChangeScriptEmotionScRsp(req.ScriptId, req.TargetEmotionType)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/HeartDial/HandlerFinishEmotionDialoguePerformanceCsReq.cs b/GameServer/Server/Packet/Recv/HeartDial/HandlerFinishEmotionDialoguePerformanceCsReq.cs index c13e1d63..0983a1ec 100644 --- a/GameServer/Server/Packet/Recv/HeartDial/HandlerFinishEmotionDialoguePerformanceCsReq.cs +++ b/GameServer/Server/Packet/Recv/HeartDial/HandlerFinishEmotionDialoguePerformanceCsReq.cs @@ -3,25 +3,20 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.HeartDial +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.HeartDial; + +[Opcode(CmdIds.FinishEmotionDialoguePerformanceCsReq)] +public class HandlerFinishEmotionDialoguePerformanceCsReq : Handler { - [Opcode(CmdIds.FinishEmotionDialoguePerformanceCsReq)] - public class HandlerFinishEmotionDialoguePerformanceCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = FinishEmotionDialoguePerformanceCsReq.Parser.ParseFrom(data); + var req = FinishEmotionDialoguePerformanceCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - player.MissionManager?.HandleFinishType(MissionFinishTypeEnum.HeartDialDialoguePerformanceFinish, $"HeartDial_{req.DialogueId}"); + var player = connection.Player!; + await player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.HeartDialDialoguePerformanceFinish, + $"HeartDial_{req.DialogueId}"); - connection.SendPacket(new PacketFinishEmotionDialoguePerformanceScRsp(req.ScriptId, req.DialogueId)); - } + await connection.SendPacket(new PacketFinishEmotionDialoguePerformanceScRsp(req.ScriptId, req.DialogueId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/HeartDial/HandlerGetHeartDialInfoCsReq.cs b/GameServer/Server/Packet/Recv/HeartDial/HandlerGetHeartDialInfoCsReq.cs index afe357f4..7ed41f4d 100644 --- a/GameServer/Server/Packet/Recv/HeartDial/HandlerGetHeartDialInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/HeartDial/HandlerGetHeartDialInfoCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.HeartDial +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.HeartDial; + +[Opcode(CmdIds.GetHeartDialInfoCsReq)] +public class HandlerGetHeartDialInfoCsReq : Handler { - [Opcode(CmdIds.GetHeartDialInfoCsReq)] - public class HandlerGetHeartDialInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetHeartDialInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetHeartDialInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/HeartDial/HandlerSubmitEmotionItemCsReq.cs b/GameServer/Server/Packet/Recv/HeartDial/HandlerSubmitEmotionItemCsReq.cs index 0376965a..0de99a9c 100644 --- a/GameServer/Server/Packet/Recv/HeartDial/HandlerSubmitEmotionItemCsReq.cs +++ b/GameServer/Server/Packet/Recv/HeartDial/HandlerSubmitEmotionItemCsReq.cs @@ -1,33 +1,30 @@ using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Enums.Mission; using EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.HeartDial +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.HeartDial; + +[Opcode(CmdIds.SubmitEmotionItemCsReq)] +public class HandlerSubmitEmotionItemCsReq : Handler { - [Opcode(CmdIds.SubmitEmotionItemCsReq)] - public class HandlerSubmitEmotionItemCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = SubmitEmotionItemCsReq.Parser.ParseFrom(data); + + GameData.HeartDialScriptData.TryGetValue((int)req.ScriptId, out var scriptData); + if (scriptData != null) { - var req = SubmitEmotionItemCsReq.Parser.ParseFrom(data); - - GameData.HeartDialScriptData.TryGetValue((int)req.ScriptId, out var scriptData); - if (scriptData != null) - { - var info = connection.Player!.HeartDialData!.ChangeScriptEmotion((int)req.ScriptId, scriptData.MissingEmoList[0], HeartDialStepTypeEnum.Normal); - connection.Player!.SendPacket(new PacketHeartDialScriptChangeScNotify(HeartDialUnlockStatus.UnlockAll, info)); - connection.Player!.MissionManager?.HandleFinishType(Enums.MissionFinishTypeEnum.HeartDialScriptListStep); - } - - connection.SendPacket(new PacketSubmitEmotionItemScRsp(req.ScriptId)); + var info = connection.Player!.HeartDialData!.ChangeScriptEmotion((int)req.ScriptId, + scriptData.MissingEmoList[0], HeartDialStepTypeEnum.Normal); + await connection.Player!.SendPacket( + new PacketHeartDialScriptChangeScNotify(HeartDialUnlockStatus.UnlockAll, info)); + await connection.Player!.MissionManager!.HandleFinishType(MissionFinishTypeEnum.HeartDialScriptListStep); } + + await connection.SendPacket(new PacketSubmitEmotionItemScRsp(req.ScriptId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Lineup/HandlerChangeLineupLeaderCsReq.cs b/GameServer/Server/Packet/Recv/Lineup/HandlerChangeLineupLeaderCsReq.cs index 1170cd49..1e6a655c 100644 --- a/GameServer/Server/Packet/Recv/Lineup/HandlerChangeLineupLeaderCsReq.cs +++ b/GameServer/Server/Packet/Recv/Lineup/HandlerChangeLineupLeaderCsReq.cs @@ -1,33 +1,33 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Enums; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Lineup; -namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup -{ - [Opcode(CmdIds.ChangeLineupLeaderCsReq)] - public class HandlerChangeLineupLeaderCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ChangeLineupLeaderCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - if (player.LineupManager!.GetCurLineup() == null) - { - connection.SendPacket(new PacketChangeLineupLeaderScRsp()); - return; - } - var lineup = player.LineupManager!.GetCurLineup()!; - if (lineup.BaseAvatars?.Count <= (int)req.Slot) - { - connection.SendPacket(new PacketChangeLineupLeaderScRsp()); - return; - } - var leaderAvatarId = lineup.BaseAvatars![(int)req.Slot].BaseAvatarId; - lineup.LeaderAvatarId = leaderAvatarId; - player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.TeamLeaderChange); +namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup; - connection.SendPacket(new PacketChangeLineupLeaderScRsp(req.Slot)); +[Opcode(CmdIds.ChangeLineupLeaderCsReq)] +public class HandlerChangeLineupLeaderCsReq : Handler +{ + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + var req = ChangeLineupLeaderCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + if (player.LineupManager!.GetCurLineup() == null) + { + await connection.SendPacket(new PacketChangeLineupLeaderScRsp()); + return; } + + var lineup = player.LineupManager!.GetCurLineup()!; + if (lineup.BaseAvatars?.Count <= (int)req.Slot) + { + await connection.SendPacket(new PacketChangeLineupLeaderScRsp()); + return; + } + + var leaderAvatarId = lineup.BaseAvatars![(int)req.Slot].BaseAvatarId; + lineup.LeaderAvatarId = leaderAvatarId; + await player.MissionManager!.HandleFinishType(MissionFinishTypeEnum.TeamLeaderChange); + + await connection.SendPacket(new PacketChangeLineupLeaderScRsp(req.Slot)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Lineup/HandlerGetAllLineupDataCsReq.cs b/GameServer/Server/Packet/Recv/Lineup/HandlerGetAllLineupDataCsReq.cs index c9515201..d3c4ade1 100644 --- a/GameServer/Server/Packet/Recv/Lineup/HandlerGetAllLineupDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Lineup/HandlerGetAllLineupDataCsReq.cs @@ -1,13 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Lineup; -namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup +namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup; + +[Opcode(CmdIds.GetAllLineupDataCsReq)] +public class HandlerGetAllLineupDataCsReq : Handler { - [Opcode(CmdIds.GetAllLineupDataCsReq)] - public class HandlerGetAllLineupDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetAllLineupDataScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetAllLineupDataScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Lineup/HandlerGetCurLineupDataCsReq.cs b/GameServer/Server/Packet/Recv/Lineup/HandlerGetCurLineupDataCsReq.cs index dcf100c7..b74c7856 100644 --- a/GameServer/Server/Packet/Recv/Lineup/HandlerGetCurLineupDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Lineup/HandlerGetCurLineupDataCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup +namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup; + +[Opcode(CmdIds.GetCurLineupDataCsReq)] +public class HandlerGetCurLineupDataCsReq : Handler { - [Opcode(CmdIds.GetCurLineupDataCsReq)] - public class HandlerGetCurLineupDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetCurLineupDataScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetCurLineupDataScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Lineup/HandlerGetLineupAvatarDataCsReq.cs b/GameServer/Server/Packet/Recv/Lineup/HandlerGetLineupAvatarDataCsReq.cs index b2186afd..83a43678 100644 --- a/GameServer/Server/Packet/Recv/Lineup/HandlerGetLineupAvatarDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Lineup/HandlerGetLineupAvatarDataCsReq.cs @@ -1,14 +1,12 @@ -using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Server.Packet.Send.Lineup; +using EggLink.DanhengServer.Server.Packet.Send.Lineup; -namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup +namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup; + +[Opcode(CmdIds.GetLineupAvatarDataCsReq)] +public class HandlerGetLineupAvatarDataCsReq : Handler { - [Opcode(CmdIds.GetLineupAvatarDataCsReq)] - public class HandlerGetLineupAvatarDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetLineupAvatarDataScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetLineupAvatarDataScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Lineup/HandlerReplaceLineupCsReq.cs b/GameServer/Server/Packet/Recv/Lineup/HandlerReplaceLineupCsReq.cs index a1fadf45..a27fd122 100644 --- a/GameServer/Server/Packet/Recv/Lineup/HandlerReplaceLineupCsReq.cs +++ b/GameServer/Server/Packet/Recv/Lineup/HandlerReplaceLineupCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup +namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup; + +[Opcode(CmdIds.ReplaceLineupCsReq)] +public class HandlerReplaceLineupCsReq : Handler { - [Opcode(CmdIds.ReplaceLineupCsReq)] - public class HandlerReplaceLineupCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ReplaceLineupCsReq.Parser.ParseFrom(data); - connection.Player!.LineupManager?.ReplaceLineup(req); - connection.SendPacket(CmdIds.ReplaceLineupScRsp); - } + var req = ReplaceLineupCsReq.Parser.ParseFrom(data); + await connection.Player!.LineupManager!.ReplaceLineup(req); + await connection.SendPacket(CmdIds.ReplaceLineupScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Lineup/HandlerSceneCastSkillCostMpCsReq.cs b/GameServer/Server/Packet/Recv/Lineup/HandlerSceneCastSkillCostMpCsReq.cs index 792f68fa..018cb5b0 100644 --- a/GameServer/Server/Packet/Recv/Lineup/HandlerSceneCastSkillCostMpCsReq.cs +++ b/GameServer/Server/Packet/Recv/Lineup/HandlerSceneCastSkillCostMpCsReq.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup +namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup; + +[Opcode(CmdIds.SceneCastSkillCostMpCsReq)] +public class HandlerSceneCastSkillCostMpCsReq : Handler { - [Opcode(CmdIds.SceneCastSkillCostMpCsReq)] - public class HandlerSceneCastSkillCostMpCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SceneCastSkillCostMpCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - player.LineupManager!.CostMp(1); - connection.SendPacket(new PacketSceneCastSkillCostMpScRsp((int)req.CastEntityId)); - } + var req = SceneCastSkillCostMpCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + await player.LineupManager!.CostMp(1); + await connection.SendPacket(new PacketSceneCastSkillCostMpScRsp((int)req.CastEntityId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Lineup/HandlerSwitchLineupIndexCsReq.cs b/GameServer/Server/Packet/Recv/Lineup/HandlerSwitchLineupIndexCsReq.cs index 1bb41167..8b26ae21 100644 --- a/GameServer/Server/Packet/Recv/Lineup/HandlerSwitchLineupIndexCsReq.cs +++ b/GameServer/Server/Packet/Recv/Lineup/HandlerSwitchLineupIndexCsReq.cs @@ -1,23 +1,16 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup +namespace EggLink.DanhengServer.Server.Packet.Recv.Lineup; + +[Opcode(CmdIds.SwitchLineupIndexCsReq)] +public class HandlerSwitchLineupIndexCsReq : Handler { - [Opcode(CmdIds.SwitchLineupIndexCsReq)] - public class HandlerSwitchLineupIndexCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SwitchLineupIndexCsReq.Parser.ParseFrom(data); - if (connection.Player!.LineupManager!.SetCurLineup((int)req.Index)) // SetCurLineup returns true if the index is valid - { - connection.SendPacket(new PacketSwitchLineupIndexScRsp(req.Index)); - } - } + var req = SwitchLineupIndexCsReq.Parser.ParseFrom(data); + if (await connection.Player!.LineupManager! + .SetCurLineup((int)req.Index)) // SetCurLineup returns true if the index is valid + await connection.SendPacket(new PacketSwitchLineupIndexScRsp(req.Index)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mail/HandlerGetMailCsReq.cs b/GameServer/Server/Packet/Recv/Mail/HandlerGetMailCsReq.cs index 150b72d2..83c9e1d4 100644 --- a/GameServer/Server/Packet/Recv/Mail/HandlerGetMailCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mail/HandlerGetMailCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.Mail; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mail +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mail; + +[Opcode(CmdIds.GetMailCsReq)] +public class HandlerGetMailCsReq : Handler { - [Opcode(CmdIds.GetMailCsReq)] - public class HandlerGetMailCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetMailScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetMailScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mail/HandlerMarkReadMailCsReq.cs b/GameServer/Server/Packet/Recv/Mail/HandlerMarkReadMailCsReq.cs index 13f3e6bf..0c13041a 100644 --- a/GameServer/Server/Packet/Recv/Mail/HandlerMarkReadMailCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mail/HandlerMarkReadMailCsReq.cs @@ -2,32 +2,27 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mail +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mail; + +[Opcode(CmdIds.MarkReadMailCsReq)] +public class HandlerMarkReadMailCsReq : Handler { - [Opcode(CmdIds.MarkReadMailCsReq)] - public class HandlerMarkReadMailCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = MarkReadMailCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + + var mail = player.MailManager!.GetMail((int)req.Id); + + if (mail != null) { - var req = MarkReadMailCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - - var mail = player.MailManager!.GetMail((int)req.Id); - - if (mail != null) - { - mail.IsRead = true; - connection.SendPacket(new PacketMarkReadMailScRsp(req.Id)); - } else - { - connection.SendPacket(new PacketMarkReadMailScRsp(Retcode.RetMailMailIdInvalid)); - } + mail.IsRead = true; + await connection.SendPacket(new PacketMarkReadMailScRsp(req.Id)); + } + else + { + await connection.SendPacket(new PacketMarkReadMailScRsp(Retcode.RetMailMailIdInvalid)); } } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerAcceptMainMissionCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerAcceptMainMissionCsReq.cs index 01f45b98..5f7157de 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerAcceptMainMissionCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerAcceptMainMissionCsReq.cs @@ -1,19 +1,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.AcceptMainMissionCsReq)] +public class HandlerAcceptMainMissionCsReq : Handler { - [Opcode(CmdIds.AcceptMainMissionCsReq)] - public class HandlerAcceptMainMissionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = AcceptMainMissionCsReq.Parser.ParseFrom(data); - var missionId = req.MainMissionId; + var req = AcceptMainMissionCsReq.Parser.ParseFrom(data); + var missionId = req.MainMissionId; - connection.Player!.MissionManager!.AcceptMainMission((int)missionId); + await connection.Player!.MissionManager!.AcceptMainMission((int)missionId); - connection.SendPacket(new PacketAcceptMainMissionScRsp(missionId)); - } + await connection.SendPacket(new PacketAcceptMainMissionScRsp(missionId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerFinishCosumeItemMissionCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerFinishCosumeItemMissionCsReq.cs index 9f761426..9e4c6f06 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerFinishCosumeItemMissionCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerFinishCosumeItemMissionCsReq.cs @@ -1,36 +1,30 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.FinishCosumeItemMissionCsReq)] +public class HandlerFinishCosumeItemMissionCsReq : Handler { - [Opcode(CmdIds.FinishCosumeItemMissionCsReq)] - public class HandlerFinishCosumeItemMissionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = FinishCosumeItemMissionCsReq.Parser.ParseFrom(data); + + var player = connection.Player!; + var mission = player.MissionManager?.GetSubMissionInfo((int)req.SubMissionId); + if (mission == null) { - var req = FinishCosumeItemMissionCsReq.Parser.ParseFrom(data); - - var player = connection.Player!; - var mission = player.MissionManager?.GetSubMissionInfo((int)req.SubMissionId); - if (mission == null) - { - connection.SendPacket(new PacketFinishCosumeItemMissionScRsp()); - return; - } - - mission.ParamItemList?.ForEach(param => - { - player.InventoryManager?.RemoveItem(param.ItemID, param.ItemNum); - }); - - player.MissionManager?.FinishSubMission((int)req.SubMissionId); - - connection.SendPacket(new PacketFinishCosumeItemMissionScRsp(req.SubMissionId)); + await connection.SendPacket(new PacketFinishCosumeItemMissionScRsp()); + return; } + + mission.ParamItemList?.ForEach(async param => + { + await player.InventoryManager!.RemoveItem(param.ItemID, param.ItemNum); + }); + + await player.MissionManager!.FinishSubMission((int)req.SubMissionId); + + await connection.SendPacket(new PacketFinishCosumeItemMissionScRsp(req.SubMissionId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerFinishItemIdCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerFinishItemIdCsReq.cs index 2bf8dea6..c3deabd9 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerFinishItemIdCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerFinishItemIdCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.FinishItemIdCsReq)] +public class HandlerFinishItemIdCsReq : Handler { - [Opcode(CmdIds.FinishItemIdCsReq)] - public class HandlerFinishItemIdCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = FinishItemIdCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - player.MessageManager!.FinishMessageItem((int)req.ItemId); + var req = FinishItemIdCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + await player.MessageManager!.FinishMessageItem((int)req.ItemId); - connection.SendPacket(new PacketFinishItemIdScRsp(req.ItemId)); - } + await connection.SendPacket(new PacketFinishItemIdScRsp(req.ItemId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerFinishPerformSectionIdCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerFinishPerformSectionIdCsReq.cs index 0f0fb2aa..03ecfe1a 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerFinishPerformSectionIdCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerFinishPerformSectionIdCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.FinishPerformSectionIdCsReq)] +public class HandlerFinishPerformSectionIdCsReq : Handler { - [Opcode(CmdIds.FinishPerformSectionIdCsReq)] - public class HandlerFinishPerformSectionIdCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = FinishPerformSectionIdCsReq.Parser.ParseFrom(data); + var req = FinishPerformSectionIdCsReq.Parser.ParseFrom(data); - connection.Player!.MessageManager!.FinishSection((int)req.SectionId); + await connection.Player!.MessageManager!.FinishSection((int)req.SectionId); - connection.SendPacket(new PacketFinishPerformSectionIdScRsp(req.SectionId)); - } + await connection.SendPacket(new PacketFinishPerformSectionIdScRsp(req.SectionId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerFinishSectionIdCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerFinishSectionIdCsReq.cs index ab23080f..b0783bb9 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerFinishSectionIdCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerFinishSectionIdCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.FinishSectionIdCsReq)] +public class HandlerFinishSectionIdCsReq : Handler { - [Opcode(CmdIds.FinishSectionIdCsReq)] - public class HandlerFinishSectionIdCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = FinishSectionIdCsReq.Parser.ParseFrom(data); + var req = FinishSectionIdCsReq.Parser.ParseFrom(data); - connection.Player!.MessageManager!.FinishSection((int)req.SectionId); + await connection.Player!.MessageManager!.FinishSection((int)req.SectionId); - connection.SendPacket(new PacketFinishSectionIdScRsp(req.SectionId)); - } + await connection.SendPacket(new PacketFinishSectionIdScRsp(req.SectionId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerFinishTalkMissionCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerFinishTalkMissionCsReq.cs index 7929b38a..ce174dc0 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerFinishTalkMissionCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerFinishTalkMissionCsReq.cs @@ -1,25 +1,21 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; -using Microsoft.EntityFrameworkCore; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.FinishTalkMissionCsReq)] +public class HandlerFinishTalkMissionCsReq : Handler { - [Opcode(CmdIds.FinishTalkMissionCsReq)] - public class HandlerFinishTalkMissionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = FinishTalkMissionCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - - player.MissionManager!.HandleTalkStr(req.TalkStr); + var req = FinishTalkMissionCsReq.Parser.ParseFrom(data); + var player = connection.Player!; - if (req.CustomValueList != null && req.CustomValueList.Count > 0) - { - player.MissionManager!.HandleCustomValue([.. req.CustomValueList], (int)req.SubMissionId); - } + await player.MissionManager!.HandleTalkStr(req.TalkStr); - connection.SendPacket(new PacketFinishTalkMissionScRsp(req.TalkStr)); - } + if (req.CustomValueList != null && req.CustomValueList.Count > 0) + await player.MissionManager!.HandleCustomValue([.. req.CustomValueList], (int)req.SubMissionId); + + await connection.SendPacket(new PacketFinishTalkMissionScRsp(req.TalkStr)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerGetFirstTalkNpcCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerGetFirstTalkNpcCsReq.cs index 9bf83c5c..6573c126 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerGetFirstTalkNpcCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerGetFirstTalkNpcCsReq.cs @@ -1,19 +1,13 @@ using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.GetFirstTalkNpcCsReq)] +public class HandlerGetFirstTalkNpcCsReq : Handler { - [Opcode(CmdIds.GetFirstTalkNpcCsReq)] - public class HandlerGetFirstTalkNpcCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(CmdIds.GetFirstTalkNpcScRsp); - } + await connection.SendPacket(CmdIds.GetFirstTalkNpcScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerGetMainMissionCustomValueCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerGetMainMissionCustomValueCsReq.cs index a1b2dbba..f597271f 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerGetMainMissionCustomValueCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerGetMainMissionCustomValueCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.GetMainMissionCustomValueCsReq)] +public class HandlerGetMainMissionCustomValueCsReq : Handler { - [Opcode(CmdIds.GetMainMissionCustomValueCsReq)] - public class HandlerGetMainMissionCustomValueCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetMainMissionCustomValueCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - connection.SendPacket(new PacketGetMainMissionCustomValueScRsp(req, player)); - } + var req = GetMainMissionCustomValueCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + await connection.SendPacket(new PacketGetMainMissionCustomValueScRsp(req, player)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerGetMissionDataCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerGetMissionDataCsReq.cs index c72b0c3e..0962ddd0 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerGetMissionDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerGetMissionDataCsReq.cs @@ -1,13 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Mission; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.GetMissionDataCsReq)] +public class HandlerGetMissionDataCsReq : Handler { - [Opcode(CmdIds.GetMissionDataCsReq)] - public class HandlerGetMissionDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetMissionDataScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetMissionDataScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerGetMissionStatusCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerGetMissionStatusCsReq.cs index 7fc5d0ec..1e069373 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerGetMissionStatusCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerGetMissionStatusCsReq.cs @@ -1,18 +1,14 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.GetMissionStatusCsReq)] +public class HandlerGetMissionStatusCsReq : Handler { - [Opcode(CmdIds.GetMissionStatusCsReq)] - public class HandlerGetMissionStatusCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetMissionStatusCsReq.Parser.ParseFrom(data); - if (req != null) - { - connection.SendPacket(new PacketGetMissionStatusScRsp(req, connection.Player!)); - } - } + var req = GetMissionStatusCsReq.Parser.ParseFrom(data); + if (req != null) await connection.SendPacket(new PacketGetMissionStatusScRsp(req, connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerGetNpcMessageGroupCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerGetNpcMessageGroupCsReq.cs index fda84a00..8b6c9b46 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerGetNpcMessageGroupCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerGetNpcMessageGroupCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Mission; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.GetNpcMessageGroupCsReq)] +public class HandlerGetNpcMessageGroupCsReq : Handler { - [Opcode(CmdIds.GetNpcMessageGroupCsReq)] - public class HandlerGetNpcMessageGroupCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetNpcMessageGroupCsReq.Parser.ParseFrom(data); + var req = GetNpcMessageGroupCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetNpcMessageGroupScRsp(req.ContactIdList, connection.Player!)); - } + await connection.SendPacket(new PacketGetNpcMessageGroupScRsp(req.ContactIdList, connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerGetNpcStatusCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerGetNpcStatusCsReq.cs index 05bc9687..03d5b08e 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerGetNpcStatusCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerGetNpcStatusCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Mission; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.GetNpcStatusCsReq)] +public class HandlerGetNpcStatusCsReq : Handler { - [Opcode(CmdIds.GetNpcStatusCsReq)] - public class HandlerGetNpcStatusCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetNpcStatusScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetNpcStatusScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerGetRndOptionCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerGetRndOptionCsReq.cs index 61b91377..aa3bd5e5 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerGetRndOptionCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerGetRndOptionCsReq.cs @@ -1,19 +1,13 @@ using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.GetRndOptionCsReq)] +public class HandlerGetRndOptionCsReq : Handler { - [Opcode(CmdIds.GetRndOptionCsReq)] - public class HandlerGetRndOptionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(CmdIds.GetRndOptionScRsp); - } + await connection.SendPacket(CmdIds.GetRndOptionScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerGetStoryLineInfoCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerGetStoryLineInfoCsReq.cs index 89cac7c3..482ba47c 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerGetStoryLineInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerGetStoryLineInfoCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.GetStoryLineInfoCsReq)] +public class HandlerGetStoryLineInfoCsReq : Handler { - [Opcode(CmdIds.GetStoryLineInfoCsReq)] - public class HandlerGetStoryLineInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetStoryLineInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetStoryLineInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Mission/HandlerUpdateTrackMainMissionIdCsReq.cs b/GameServer/Server/Packet/Recv/Mission/HandlerUpdateTrackMainMissionIdCsReq.cs index 9db09165..fca751c1 100644 --- a/GameServer/Server/Packet/Recv/Mission/HandlerUpdateTrackMainMissionIdCsReq.cs +++ b/GameServer/Server/Packet/Recv/Mission/HandlerUpdateTrackMainMissionIdCsReq.cs @@ -2,25 +2,20 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mission +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Mission; + +[Opcode(CmdIds.UpdateTrackMainMissionIdCsReq)] +public class HandlerUpdateTrackMainMissionIdCsReq : Handler { - [Opcode(CmdIds.UpdateTrackMainMissionIdCsReq)] - public class HandlerUpdateTrackMainMissionIdCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = UpdateTrackMainMissionIdCsReq.Parser.ParseFrom(data); + var req = UpdateTrackMainMissionIdCsReq.Parser.ParseFrom(data); - var prev = connection.Player!.MissionManager!.Data.TrackingMainMissionId; - connection.Player!.MissionManager!.Data.TrackingMainMissionId = (int)req.TrackMissionId; + var prev = connection.Player!.MissionManager!.Data.TrackingMainMissionId; + connection.Player!.MissionManager!.Data.TrackingMainMissionId = (int)req.TrackMissionId; - connection.SendPacket(new PacketUpdateTrackMainMissionIdScRsp(prev, connection.Player!.MissionManager!.Data.TrackingMainMissionId)); - } + await connection.SendPacket(new PacketUpdateTrackMainMissionIdScRsp(prev, + connection.Player!.MissionManager!.Data.TrackingMainMissionId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Others/HandlerGetSecretKeyInfoCsReq.cs b/GameServer/Server/Packet/Recv/Others/HandlerGetSecretKeyInfoCsReq.cs index f4ca53ed..28041e13 100644 --- a/GameServer/Server/Packet/Recv/Others/HandlerGetSecretKeyInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Others/HandlerGetSecretKeyInfoCsReq.cs @@ -1,13 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Others; -namespace EggLink.DanhengServer.Server.Packet.Recv.Others +namespace EggLink.DanhengServer.Server.Packet.Recv.Others; + +[Opcode(CmdIds.GetSecretKeyInfoCsReq)] +public class HandlerGetSecretKeyInfoCsReq : Handler { - [Opcode(CmdIds.GetSecretKeyInfoCsReq)] - public class HandlerGetSecretKeyInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetSecretKeyInfoScRsp()); - } + await connection.SendPacket(new PacketGetSecretKeyInfoScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Others/HandlerGetVideoVersionKeyCsReq.cs b/GameServer/Server/Packet/Recv/Others/HandlerGetVideoVersionKeyCsReq.cs index b79368b7..0f115bde 100644 --- a/GameServer/Server/Packet/Recv/Others/HandlerGetVideoVersionKeyCsReq.cs +++ b/GameServer/Server/Packet/Recv/Others/HandlerGetVideoVersionKeyCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Others; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Others +namespace EggLink.DanhengServer.Server.Packet.Recv.Others; + +[Opcode(CmdIds.GetVideoVersionKeyCsReq)] +public class HandlerGetVideoVersionKeyCsReq : Handler { - [Opcode(CmdIds.GetVideoVersionKeyCsReq)] - public class HandlerGetVideoVersionKeyCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetVideoVersionKeyScRsp()); - } + await connection.SendPacket(new PacketGetVideoVersionKeyScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerDeployRotaterCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerDeployRotaterCsReq.cs index a441ab4d..cb851abb 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerDeployRotaterCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerDeployRotaterCsReq.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.DeployRotaterCsReq)] +public class HandlerDeployRotaterCsReq : Handler { - [Opcode(CmdIds.DeployRotaterCsReq)] - public class HandlerDeployRotaterCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = DeployRotaterCsReq.Parser.ParseFrom(data); + var req = DeployRotaterCsReq.Parser.ParseFrom(data); - connection.Player!.ChargerNum--; - connection.SendPacket(new PacketDeployRotaterScRsp(req.RotaterData, connection.Player!.ChargerNum, 5)); - } + connection.Player!.ChargerNum--; + await connection.SendPacket(new PacketDeployRotaterScRsp(req.RotaterData, connection.Player!.ChargerNum, 5)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerGetArchiveDataCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerGetArchiveDataCsReq.cs index 60fa8d2d..c0a6fcbf 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerGetArchiveDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerGetArchiveDataCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.GetArchiveDataCsReq)] +public class HandlerGetArchiveDataCsReq : Handler { - [Opcode(CmdIds.GetArchiveDataCsReq)] - public class HandlerGetArchiveDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetArchiveDataScRsp()); - } + await connection.SendPacket(new PacketGetArchiveDataScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerGetBagCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerGetBagCsReq.cs index d0fbdb61..fbc783f8 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerGetBagCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerGetBagCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.GetBagCsReq)] +public class HandlerGetBagCsReq : Handler { - [Opcode(CmdIds.GetBagCsReq)] - public class HandlerGetBagCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetBagScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetBagScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerGetBasicInfoCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerGetBasicInfoCsReq.cs index 673a057c..672ce003 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerGetBasicInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerGetBasicInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.GetBasicInfoCsReq)] +public class HandlerGetBasicInfoCsReq : Handler { - [Opcode(CmdIds.GetBasicInfoCsReq)] - public class HandlerGetBasicInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetBasicInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetBasicInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerGetJukeboxDataCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerGetJukeboxDataCsReq.cs index 6d9981c9..1b62c312 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerGetJukeboxDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerGetJukeboxDataCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.GetJukeboxDataCsReq)] +public class HandlerGetJukeboxDataCsReq : Handler { - [Opcode(CmdIds.GetJukeboxDataCsReq)] - public class HandlerGetJukeboxDataCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetJukeboxDataScRsp(connection.Player!)); - } + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + await connection.SendPacket(new PacketGetJukeboxDataScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerGetPhoneDataCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerGetPhoneDataCsReq.cs index 9593aa79..a8446cc5 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerGetPhoneDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerGetPhoneDataCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.GetPhoneDataCsReq)] +public class HandlerGetPhoneDataCsReq : Handler { - [Opcode(CmdIds.GetPhoneDataCsReq)] - public class HandlerGetPhoneDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetPhoneDataScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetPhoneDataScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerGetPlayerBoardDataCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerGetPlayerBoardDataCsReq.cs index 82e88421..fcfd7d81 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerGetPlayerBoardDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerGetPlayerBoardDataCsReq.cs @@ -1,13 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Player; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.GetPlayerBoardDataCsReq)] +public class HandlerGetPlayerBoardDataCsReq : Handler { - [Opcode(CmdIds.GetPlayerBoardDataCsReq)] - public class HandlerGetPlayerBoardDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetPlayerBoardDataScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetPlayerBoardDataScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerInteractChargerCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerInteractChargerCsReq.cs index 48c2bc48..f5b3152c 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerInteractChargerCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerInteractChargerCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.InteractChargerCsReq)] +public class HandlerInteractChargerCsReq : Handler { - [Opcode(CmdIds.InteractChargerCsReq)] - public class HandlerInteractChargerCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = InteractChargerCsReq.Parser.ParseFrom(data); + var req = InteractChargerCsReq.Parser.ParseFrom(data); - connection.Player!.ChargerNum = 5; - connection.SendPacket(new PacketInteractChargerScRsp(req.ChargerInfo)); - connection.SendPacket(new PacketUpdateEnergyScNotify(connection.Player!.ChargerNum, 5)); - } + connection.Player!.ChargerNum = 5; + await connection.SendPacket(new PacketInteractChargerScRsp(req.ChargerInfo)); + await connection.SendPacket(new PacketUpdateEnergyScNotify(connection.Player!.ChargerNum, 5)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerPlayBackGroundMusicCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerPlayBackGroundMusicCsReq.cs index a07ca652..f6996789 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerPlayBackGroundMusicCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerPlayBackGroundMusicCsReq.cs @@ -1,25 +1,17 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.PlayBackGroundMusicCsReq)] +public class HandlerPlayBackGroundMusicCsReq : Handler { - [Opcode(CmdIds.PlayBackGroundMusicCsReq)] - public class HandlerPlayBackGroundMusicCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = PlayBackGroundMusicCsReq.Parser.ParseFrom(data); + var req = PlayBackGroundMusicCsReq.Parser.ParseFrom(data); - connection.Player!.Data.CurrentBgm = (int)req.PlayMusicId; - DatabaseHelper.Instance!.UpdateInstance(connection.Player!.Data); + connection.Player!.Data.CurrentBgm = (int)req.PlayMusicId; - connection.SendPacket(new PacketPlayBackGroundMusicScRsp(req.PlayMusicId)); - } + await connection.SendPacket(new PacketPlayBackGroundMusicScRsp(req.PlayMusicId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerPlayerGetTokenCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerPlayerGetTokenCsReq.cs index 2b01d1ba..9c3efa16 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerPlayerGetTokenCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerPlayerGetTokenCsReq.cs @@ -6,42 +6,41 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; using EggLink.DanhengServer.Util; -using Microsoft.EntityFrameworkCore; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.PlayerGetTokenCsReq)] +public class HandlerPlayerGetTokenCsReq : Handler { - [Opcode(CmdIds.PlayerGetTokenCsReq)] - public class HandlerPlayerGetTokenCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = PlayerGetTokenCsReq.Parser.ParseFrom(data); + + var account = DatabaseHelper.Instance?.GetInstance(int.Parse(req.AccountUid)); + if (account == null) { - var req = PlayerGetTokenCsReq.Parser.ParseFrom(data); - - var account = DatabaseHelper.Instance?.GetInstance(int.Parse(req.AccountUid)); - if (account == null) - { - connection.SendPacket(new PacketPlayerGetTokenScRsp()); - connection.SendPacket(new PacketPlayerKickOutScNotify()); - return; - } - - var prev = Listener.GetActiveConnection(account.Uid); - if (prev != null) - { - prev.SendPacket(new PacketPlayerKickOutScNotify()); - prev.Stop(); - } - - connection.State = SessionStateEnum.WAITING_FOR_LOGIN; - var pd = DatabaseHelper.Instance?.GetInstance(int.Parse(req.AccountUid)); - if (pd == null) - connection.Player = new PlayerInstance(int.Parse(req.AccountUid)); - else - connection.Player = new PlayerInstance(pd); - connection.DebugFile = Path.Combine(ConfigManager.Config.Path.LogPath, "Debug/", $"{req.AccountUid}/", $"Debug-{DateTime.Now:yyyy-MM-dd HH-mm-ss}.log"); - connection.Player.OnLogin(); - connection.Player.Connection = connection; - connection.SendPacket(new PacketPlayerGetTokenScRsp(connection)); + await connection.SendPacket(new PacketPlayerGetTokenScRsp()); + await connection.SendPacket(new PacketPlayerKickOutScNotify()); + return; } + + var prev = Listener.GetActiveConnection(account.Uid); + if (prev != null) + { + await prev.SendPacket(new PacketPlayerKickOutScNotify()); + prev.Stop(); + } + + connection.State = SessionStateEnum.WAITING_FOR_LOGIN; + var pd = DatabaseHelper.Instance?.GetInstance(int.Parse(req.AccountUid)); + if (pd == null) + connection.Player = new PlayerInstance(int.Parse(req.AccountUid)); + else + connection.Player = new PlayerInstance(pd); + connection.DebugFile = Path.Combine(ConfigManager.Config.Path.LogPath, "Debug/", $"{req.AccountUid}/", + $"Debug-{DateTime.Now:yyyy-MM-dd HH-mm-ss}.log"); + await connection.Player.OnLogin(); + connection.Player.Connection = connection; + await connection.SendPacket(new PacketPlayerGetTokenScRsp(connection)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerPlayerHeartBeatCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerPlayerHeartBeatCsReq.cs index 5a55971f..35035cac 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerPlayerHeartBeatCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerPlayerHeartBeatCsReq.cs @@ -1,25 +1,16 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.PlayerHeartBeatCsReq)] +public class HandlerPlayerHeartBeatCsReq : Handler { - [Opcode(CmdIds.PlayerHeartBeatCsReq)] - public class HandlerPlayerHeartBeatCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = PlayerHeartBeatCsReq.Parser.ParseFrom(data); - if (req != null) - { - connection.SendPacket(new PacketPlayerHeartBeatScRsp((long)req.ClientTimeMs)); - } + var req = PlayerHeartBeatCsReq.Parser.ParseFrom(data); + if (req != null) await connection.SendPacket(new PacketPlayerHeartBeatScRsp((long)req.ClientTimeMs)); - connection.Player?.OnHeartBeat(); - } + await connection.Player!.OnHeartBeat(); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerPlayerLoginCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerPlayerLoginCsReq.cs index 270263b7..7f150721 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerPlayerLoginCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerPlayerLoginCsReq.cs @@ -2,16 +2,15 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Server.Packet.Send.Player; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.PlayerLoginCsReq)] +public class HandlerPlayerLoginCsReq : Handler { - [Opcode(CmdIds.PlayerLoginCsReq)] - public class HandlerPlayerLoginCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.State = SessionStateEnum.ACTIVE; - connection.SendPacket(new PacketPlayerLoginScRsp(connection)); - connection.SendPacket(new PacketContentPackageSyncDataScNotify()); - } + connection.State = SessionStateEnum.ACTIVE; + await connection.SendPacket(new PacketPlayerLoginScRsp(connection)); + await connection.SendPacket(new PacketContentPackageSyncDataScNotify()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerPlayerLoginFinishCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerPlayerLoginFinishCsReq.cs index bd09f64a..25a70e24 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerPlayerLoginFinishCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerPlayerLoginFinishCsReq.cs @@ -1,17 +1,12 @@ -using EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; -using EggLink.DanhengServer.Server.Packet.Send.Mission; -using EggLink.DanhengServer.Server.Packet.Send.Others; +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +[Opcode(CmdIds.PlayerLoginFinishCsReq)] +public class HandlerPlayerLoginFinishCsReq : Handler { - [Opcode(CmdIds.PlayerLoginFinishCsReq)] - public class HandlerPlayerLoginFinishCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(CmdIds.PlayerLoginFinishScRsp); - //var list = connection.Player!.MissionManager!.GetRunningSubMissionIdList(); - //connection.SendPacket(new PacketMissionAcceptScNotify(list)); - } + await connection.SendPacket(CmdIds.PlayerLoginFinishScRsp); + //var list = connection.Player!.MissionManager!.GetRunningSubMissionIdList(); + //connection.SendPacket(new PacketMissionAcceptScNotify(list)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerPlayerLogoutCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerPlayerLogoutCsReq.cs index ff1c5db6..12941ea5 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerPlayerLogoutCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerPlayerLogoutCsReq.cs @@ -1,18 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +[Opcode(CmdIds.PlayerLogoutCsReq)] +public class HandlerPlayerLogoutCsReq : Handler { - [Opcode(CmdIds.PlayerLogoutCsReq)] - public class HandlerPlayerLogoutCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(CmdIds.PlayerLogoutScRsp); - connection.Stop(); - } + await connection.SendPacket(CmdIds.PlayerLogoutScRsp); + connection.Stop(); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerSelectChatBubbleCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerSelectChatBubbleCsReq.cs index 9eddb94a..e105b9bd 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerSelectChatBubbleCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerSelectChatBubbleCsReq.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.SelectChatBubbleCsReq)] +public class HandlerSelectChatBubbleCsReq : Handler { - [Opcode(CmdIds.SelectChatBubbleCsReq)] - public class HandlerSelectChatBubbleCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SelectChatBubbleCsReq.Parser.ParseFrom(data); + var req = SelectChatBubbleCsReq.Parser.ParseFrom(data); - connection.Player!.Data.ChatBubble = (int)req.BubbleId; - DatabaseHelper.Instance!.UpdateInstance(connection.Player!.Data); + connection.Player!.Data.ChatBubble = (int)req.BubbleId; + DatabaseHelper.Instance!.UpdateInstance(connection.Player!.Data); - connection.SendPacket(new PacketSelectChatBubbleScRsp(req.BubbleId)); - } + await connection.SendPacket(new PacketSelectChatBubbleScRsp(req.BubbleId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerSelectPhoneThemeCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerSelectPhoneThemeCsReq.cs index 6def1820..b18d014a 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerSelectPhoneThemeCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerSelectPhoneThemeCsReq.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.SelectPhoneThemeCsReq)] +public class HandlerSelectPhoneThemeCsReq : Handler { - [Opcode(CmdIds.SelectPhoneThemeCsReq)] - public class HandlerSelectPhoneThemeCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SelectPhoneThemeCsReq.Parser.ParseFrom(data); + var req = SelectPhoneThemeCsReq.Parser.ParseFrom(data); - connection.Player!.Data.PhoneTheme = (int)req.ThemeId; - DatabaseHelper.Instance!.UpdateInstance(connection.Player!.Data); + connection.Player!.Data.PhoneTheme = (int)req.ThemeId; + DatabaseHelper.Instance!.UpdateInstance(connection.Player!.Data); - connection.SendPacket(new PacketSelectPhoneThemeScRsp(req.ThemeId)); - } + await connection.SendPacket(new PacketSelectPhoneThemeScRsp(req.ThemeId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerSetClientPausedCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerSetClientPausedCsReq.cs index 2001beec..741df453 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerSetClientPausedCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerSetClientPausedCsReq.cs @@ -1,48 +1,49 @@ -using System; -using System.IO; -using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Util; -using EggLink.DanhengServer.Server.Packet.Send.Player; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Others; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player -{ - [Opcode(CmdIds.SetClientPausedCsReq)] - public class HandlerSetClientPausedCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SetClientPausedCsReq.Parser.ParseFrom(data); - var paused = req.Paused; - connection.SendPacket(new PacketSetClientPausedScRsp(paused)); - if (ConfigManager.Config.ServerOption.ServerAnnounce.EnableAnnounce) - connection.SendPacket(new PacketServerAnnounceNotify()); +using EggLink.DanhengServer.Server.Packet.Send.Player; +using EggLink.DanhengServer.Util; - // DO NOT REMOVE THIS CODE - // This code is responsible for sending the client data to the player - switch (ConfigManager.Config.ServerOption.Language) - { - case "CHS": - //var data = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gdmVyc2lvbl90ZXh0KCkKICAgIGxvY2FsIHVpZCA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVmVyc2lvblRleHQiKTpHZXRDb21wb25lbnQoIlRleHQiKQogICAgaWYgbm90IHN0cmluZy5tYXRjaCh1aWQudGV4dCwgIkRhbmhlbmdTZXJ2ZXIiKSB0aGVuCiAgICAgICAgdWlkLnRleHQgPSAiRGFuaGVuZ1NlcnZlcuS4uuWNiuW8gOa6kOWFjei0ueacjeWKoeerr1xu5q2k5pyN5Yqh56uv5LuF55So5L2c5a2m5Lmg5Lqk5rWB77yM6K+35pSv5oyB5q2j54mI5ri45oiPICIgLi4gdWlkLnRleHQKICAgICAgICB1aWQuZm9udFNpemUgPSA3Ni4wCiAgICBlbmQKICAgIGxvY2FsIGJldGEgPSBDUy5Vbml0eUVuZ2luZS5HYW1lT2JqZWN0LkZpbmQoIlVJUm9vdC9BYm92ZURpYWxvZy9CZXRhSGludERpYWxvZyhDbG9uZSkiKTpHZXRDb21wb25lbnQoIlRleHQiKQplbmQKCnZlcnNpb25fdGV4dCgp")); - connection.SendPacket(new BasePacket(5) - { - Data = Convert.FromBase64String("OuIDCFEQ18u5tAYa1wNsb2NhbCBmdW5jdGlvbiB2ZXJzaW9uX3RleHQoKQogICAgbG9jYWwgdWlkID0gQ1MuVW5pdHlFbmdpbmUuR2FtZU9iamVjdC5GaW5kKCJWZXJzaW9uVGV4dCIpOkdldENvbXBvbmVudCgiVGV4dCIpCiAgICBpZiBub3Qgc3RyaW5nLm1hdGNoKHVpZC50ZXh0LCAiRGFuaGVuZ1NlcnZlciIpIHRoZW4KICAgICAgICB1aWQudGV4dCA9ICJEYW5oZW5nU2VydmVy5Li65Y2K5byA5rqQ5YWN6LS55pyN5Yqh56uvXG7mraTmnI3liqHnq6/ku4XnlKjkvZzlrabkuaDkuqTmtYHvvIzor7fmlK/mjIHmraPniYjmuLjmiI8gIiAuLiB1aWQudGV4dAogICAgICAgIHVpZC5mb250U2l6ZSA9IDc2LjAKICAgIGVuZAogICAgbG9jYWwgYmV0YSA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVUlSb290L0Fib3ZlRGlhbG9nL0JldGFIaW50RGlhbG9nKENsb25lKSIpOkdldENvbXBvbmVudCgiVGV4dCIpCmVuZAoKdmVyc2lvbl90ZXh0KCk=") - }); - break; - case "CHT": - //var data2 = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gdmVyc2lvbl90ZXh0KCkKICAgIGxvY2FsIHVpZCA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVmVyc2lvblRleHQiKTpHZXRDb21wb25lbnQoIlRleHQiKQogICAgaWYgbm90IHN0cmluZy5tYXRjaCh1aWQudGV4dCwgIkRhbmhlbmdTZXJ2ZXIiKSB0aGVuCiAgICAgICAgdWlkLnRleHQgPSAiRGFuaGVuZ1NlcnZlcueCuuWNiumWi+a6kOWFjeiyu+S8uuacjeWZqOi7n+mrlFxu5q2k5Ly65pyN5Zmo6Luf6auU5YOF55So5L2c5a2457+S5Lqk5rWB77yM6KuL5pSv5oyB5q2j54mI6YGK5oiyICIgLi4gdWlkLnRleHQKICAgICAgICB1aWQuZm9udFNpemUgPSA3Ni4wCiAgICBlbmQKICAgIGxvY2FsIGJldGEgPSBDUy5Vbml0eUVuZ2luZS5HYW1lT2JqZWN0LkZpbmQoIlVJUm9vdC9BYm92ZURpYWxvZy9CZXRhSGludERpYWxvZyhDbG9uZSkiKTpHZXRDb21wb25lbnQoIlRleHQiKQplbmQKCnZlcnNpb25fdGV4dCgp")); - connection.SendPacket(new BasePacket(5) - { - Data = Convert.FromBase64String("Ou4DCFEQ18u5tAYa4wNsb2NhbCBmdW5jdGlvbiB2ZXJzaW9uX3RleHQoKQogICAgbG9jYWwgdWlkID0gQ1MuVW5pdHlFbmdpbmUuR2FtZU9iamVjdC5GaW5kKCJWZXJzaW9uVGV4dCIpOkdldENvbXBvbmVudCgiVGV4dCIpCiAgICBpZiBub3Qgc3RyaW5nLm1hdGNoKHVpZC50ZXh0LCAiRGFuaGVuZ1NlcnZlciIpIHRoZW4KICAgICAgICB1aWQudGV4dCA9ICJEYW5oZW5nU2VydmVy54K65Y2K6ZaL5rqQ5YWN6LK75Ly65pyN5Zmo6Luf6auUXG7mraTkvLrmnI3lmajou5/pq5Tlg4XnlKjkvZzlrbjnv5LkuqTmtYHvvIzoq4vmlK/mjIHmraPniYjpgYrmiLIgIiAuLiB1aWQudGV4dAogICAgICAgIHVpZC5mb250U2l6ZSA9IDc2LjAKICAgIGVuZAogICAgbG9jYWwgYmV0YSA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVUlSb290L0Fib3ZlRGlhbG9nL0JldGFIaW50RGlhbG9nKENsb25lKSIpOkdldENvbXBvbmVudCgiVGV4dCIpCmVuZAoKdmVyc2lvbl90ZXh0KCk=") - }); - break; - default: - //var data3 = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gdmVyc2lvbl90ZXh0KCkKICAgIGxvY2FsIHVpZCA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVmVyc2lvblRleHQiKTpHZXRDb21wb25lbnQoIlRleHQiKQogICAgaWYgbm90IHN0cmluZy5tYXRjaCh1aWQudGV4dCwgIkRhbmhlbmcgU2VydmVyIikgdGhlbgogICAgICAgIHVpZC50ZXh0ID0gIkRhbmhlbmcgU2VydmVyIGlzIGEgc2VtaSBvcGVuLXNvdXJjZSBzZXJ2ZXIgc29mdHdhcmUuXG5FZHVjYXRpb25hbCBwdXJwb3NlIG9ubHksIHBsZWFzZSBzdXBwb3J0IHRoZSBnZW51aW5lIGdhbWUuICIgLi4gdWlkLnRleHQKICAgICAgICB1aWQuZm9udFNpemUgPSA3Ni4wCiAgICBlbmQKICAgIGxvY2FsIGJldGEgPSBDUy5Vbml0eUVuZ2luZS5HYW1lT2JqZWN0LkZpbmQoIlVJUm9vdC9BYm92ZURpYWxvZy9CZXRhSGludERpYWxvZyhDbG9uZSkiKTpHZXRDb21wb25lbnQoIlRleHQiKQplbmQKCnZlcnNpb25fdGV4dCgp")); - connection.SendPacket(new BasePacket(5) - { - Data = Convert.FromBase64String("OvEDCFEQ18u5tAYa5gNsb2NhbCBmdW5jdGlvbiB2ZXJzaW9uX3RleHQoKQogICAgbG9jYWwgdWlkID0gQ1MuVW5pdHlFbmdpbmUuR2FtZU9iamVjdC5GaW5kKCJWZXJzaW9uVGV4dCIpOkdldENvbXBvbmVudCgiVGV4dCIpCiAgICBpZiBub3Qgc3RyaW5nLm1hdGNoKHVpZC50ZXh0LCAiRGFuaGVuZyBTZXJ2ZXIiKSB0aGVuCiAgICAgICAgdWlkLnRleHQgPSAiRGFuaGVuZyBTZXJ2ZXIgaXMgYSBzZW1pIG9wZW4tc291cmNlIHNlcnZlciBzb2Z0d2FyZS5cbkVkdWNhdGlvbmFsIHB1cnBvc2Ugb25seSwgcGxlYXNlIHN1cHBvcnQgdGhlIGdlbnVpbmUgZ2FtZS4gIiAuLiB1aWQudGV4dAogICAgICAgIHVpZC5mb250U2l6ZSA9IDc2LjAKICAgIGVuZAogICAgbG9jYWwgYmV0YSA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVUlSb290L0Fib3ZlRGlhbG9nL0JldGFIaW50RGlhbG9nKENsb25lKSIpOkdldENvbXBvbmVudCgiVGV4dCIpCmVuZAoKdmVyc2lvbl90ZXh0KCk=") - }); - break; - } +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.SetClientPausedCsReq)] +public class HandlerSetClientPausedCsReq : Handler +{ + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + var req = SetClientPausedCsReq.Parser.ParseFrom(data); + var paused = req.Paused; + await connection.SendPacket(new PacketSetClientPausedScRsp(paused)); + if (ConfigManager.Config.ServerOption.ServerAnnounce.EnableAnnounce) + await connection.SendPacket(new PacketServerAnnounceNotify()); + + // DO NOT REMOVE THIS CODE + // This code is responsible for sending the client data to the player + switch (ConfigManager.Config.ServerOption.Language) + { + case "CHS": + //var data = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gdmVyc2lvbl90ZXh0KCkKICAgIGxvY2FsIHVpZCA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVmVyc2lvblRleHQiKTpHZXRDb21wb25lbnQoIlRleHQiKQogICAgaWYgbm90IHN0cmluZy5tYXRjaCh1aWQudGV4dCwgIkRhbmhlbmdTZXJ2ZXIiKSB0aGVuCiAgICAgICAgdWlkLnRleHQgPSAiRGFuaGVuZ1NlcnZlcuS4uuWNiuW8gOa6kOWFjei0ueacjeWKoeerr1xu5q2k5pyN5Yqh56uv5LuF55So5L2c5a2m5Lmg5Lqk5rWB77yM6K+35pSv5oyB5q2j54mI5ri45oiPICIgLi4gdWlkLnRleHQKICAgICAgICB1aWQuZm9udFNpemUgPSA3Ni4wCiAgICBlbmQKICAgIGxvY2FsIGJldGEgPSBDUy5Vbml0eUVuZ2luZS5HYW1lT2JqZWN0LkZpbmQoIlVJUm9vdC9BYm92ZURpYWxvZy9CZXRhSGludERpYWxvZyhDbG9uZSkiKTpHZXRDb21wb25lbnQoIlRleHQiKQplbmQKCnZlcnNpb25fdGV4dCgp")); + await connection.SendPacket(new BasePacket(5) + { + Data = Convert.FromBase64String( + "OuIDCFEQ18u5tAYa1wNsb2NhbCBmdW5jdGlvbiB2ZXJzaW9uX3RleHQoKQogICAgbG9jYWwgdWlkID0gQ1MuVW5pdHlFbmdpbmUuR2FtZU9iamVjdC5GaW5kKCJWZXJzaW9uVGV4dCIpOkdldENvbXBvbmVudCgiVGV4dCIpCiAgICBpZiBub3Qgc3RyaW5nLm1hdGNoKHVpZC50ZXh0LCAiRGFuaGVuZ1NlcnZlciIpIHRoZW4KICAgICAgICB1aWQudGV4dCA9ICJEYW5oZW5nU2VydmVy5Li65Y2K5byA5rqQ5YWN6LS55pyN5Yqh56uvXG7mraTmnI3liqHnq6/ku4XnlKjkvZzlrabkuaDkuqTmtYHvvIzor7fmlK/mjIHmraPniYjmuLjmiI8gIiAuLiB1aWQudGV4dAogICAgICAgIHVpZC5mb250U2l6ZSA9IDc2LjAKICAgIGVuZAogICAgbG9jYWwgYmV0YSA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVUlSb290L0Fib3ZlRGlhbG9nL0JldGFIaW50RGlhbG9nKENsb25lKSIpOkdldENvbXBvbmVudCgiVGV4dCIpCmVuZAoKdmVyc2lvbl90ZXh0KCk=") + }); + break; + case "CHT": + //var data2 = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gdmVyc2lvbl90ZXh0KCkKICAgIGxvY2FsIHVpZCA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVmVyc2lvblRleHQiKTpHZXRDb21wb25lbnQoIlRleHQiKQogICAgaWYgbm90IHN0cmluZy5tYXRjaCh1aWQudGV4dCwgIkRhbmhlbmdTZXJ2ZXIiKSB0aGVuCiAgICAgICAgdWlkLnRleHQgPSAiRGFuaGVuZ1NlcnZlcueCuuWNiumWi+a6kOWFjeiyu+S8uuacjeWZqOi7n+mrlFxu5q2k5Ly65pyN5Zmo6Luf6auU5YOF55So5L2c5a2457+S5Lqk5rWB77yM6KuL5pSv5oyB5q2j54mI6YGK5oiyICIgLi4gdWlkLnRleHQKICAgICAgICB1aWQuZm9udFNpemUgPSA3Ni4wCiAgICBlbmQKICAgIGxvY2FsIGJldGEgPSBDUy5Vbml0eUVuZ2luZS5HYW1lT2JqZWN0LkZpbmQoIlVJUm9vdC9BYm92ZURpYWxvZy9CZXRhSGludERpYWxvZyhDbG9uZSkiKTpHZXRDb21wb25lbnQoIlRleHQiKQplbmQKCnZlcnNpb25fdGV4dCgp")); + await connection.SendPacket(new BasePacket(5) + { + Data = Convert.FromBase64String( + "Ou4DCFEQ18u5tAYa4wNsb2NhbCBmdW5jdGlvbiB2ZXJzaW9uX3RleHQoKQogICAgbG9jYWwgdWlkID0gQ1MuVW5pdHlFbmdpbmUuR2FtZU9iamVjdC5GaW5kKCJWZXJzaW9uVGV4dCIpOkdldENvbXBvbmVudCgiVGV4dCIpCiAgICBpZiBub3Qgc3RyaW5nLm1hdGNoKHVpZC50ZXh0LCAiRGFuaGVuZ1NlcnZlciIpIHRoZW4KICAgICAgICB1aWQudGV4dCA9ICJEYW5oZW5nU2VydmVy54K65Y2K6ZaL5rqQ5YWN6LK75Ly65pyN5Zmo6Luf6auUXG7mraTkvLrmnI3lmajou5/pq5Tlg4XnlKjkvZzlrbjnv5LkuqTmtYHvvIzoq4vmlK/mjIHmraPniYjpgYrmiLIgIiAuLiB1aWQudGV4dAogICAgICAgIHVpZC5mb250U2l6ZSA9IDc2LjAKICAgIGVuZAogICAgbG9jYWwgYmV0YSA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVUlSb290L0Fib3ZlRGlhbG9nL0JldGFIaW50RGlhbG9nKENsb25lKSIpOkdldENvbXBvbmVudCgiVGV4dCIpCmVuZAoKdmVyc2lvbl90ZXh0KCk=") + }); + break; + default: + //var data3 = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gdmVyc2lvbl90ZXh0KCkKICAgIGxvY2FsIHVpZCA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVmVyc2lvblRleHQiKTpHZXRDb21wb25lbnQoIlRleHQiKQogICAgaWYgbm90IHN0cmluZy5tYXRjaCh1aWQudGV4dCwgIkRhbmhlbmcgU2VydmVyIikgdGhlbgogICAgICAgIHVpZC50ZXh0ID0gIkRhbmhlbmcgU2VydmVyIGlzIGEgc2VtaSBvcGVuLXNvdXJjZSBzZXJ2ZXIgc29mdHdhcmUuXG5FZHVjYXRpb25hbCBwdXJwb3NlIG9ubHksIHBsZWFzZSBzdXBwb3J0IHRoZSBnZW51aW5lIGdhbWUuICIgLi4gdWlkLnRleHQKICAgICAgICB1aWQuZm9udFNpemUgPSA3Ni4wCiAgICBlbmQKICAgIGxvY2FsIGJldGEgPSBDUy5Vbml0eUVuZ2luZS5HYW1lT2JqZWN0LkZpbmQoIlVJUm9vdC9BYm92ZURpYWxvZy9CZXRhSGludERpYWxvZyhDbG9uZSkiKTpHZXRDb21wb25lbnQoIlRleHQiKQplbmQKCnZlcnNpb25fdGV4dCgp")); + await connection.SendPacket(new BasePacket(5) + { + Data = Convert.FromBase64String( + "OvEDCFEQ18u5tAYa5gNsb2NhbCBmdW5jdGlvbiB2ZXJzaW9uX3RleHQoKQogICAgbG9jYWwgdWlkID0gQ1MuVW5pdHlFbmdpbmUuR2FtZU9iamVjdC5GaW5kKCJWZXJzaW9uVGV4dCIpOkdldENvbXBvbmVudCgiVGV4dCIpCiAgICBpZiBub3Qgc3RyaW5nLm1hdGNoKHVpZC50ZXh0LCAiRGFuaGVuZyBTZXJ2ZXIiKSB0aGVuCiAgICAgICAgdWlkLnRleHQgPSAiRGFuaGVuZyBTZXJ2ZXIgaXMgYSBzZW1pIG9wZW4tc291cmNlIHNlcnZlciBzb2Z0d2FyZS5cbkVkdWNhdGlvbmFsIHB1cnBvc2Ugb25seSwgcGxlYXNlIHN1cHBvcnQgdGhlIGdlbnVpbmUgZ2FtZS4gIiAuLiB1aWQudGV4dAogICAgICAgIHVpZC5mb250U2l6ZSA9IDc2LjAKICAgIGVuZAogICAgbG9jYWwgYmV0YSA9IENTLlVuaXR5RW5naW5lLkdhbWVPYmplY3QuRmluZCgiVUlSb290L0Fib3ZlRGlhbG9nL0JldGFIaW50RGlhbG9nKENsb25lKSIpOkdldENvbXBvbmVudCgiVGV4dCIpCmVuZAoKdmVyc2lvbl90ZXh0KCk=") + }); + break; } } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerSetGameplayBirthdayCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerSetGameplayBirthdayCsReq.cs index f75b4cf8..24f08756 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerSetGameplayBirthdayCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerSetGameplayBirthdayCsReq.cs @@ -1,36 +1,31 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.SetGameplayBirthdayCsReq)] +public class HandlerSetGameplayBirthdayCsReq : Handler { - [Opcode(CmdIds.SetGameplayBirthdayCsReq)] - public class HandlerSetGameplayBirthdayCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = SetGameplayBirthdayCsReq.Parser.ParseFrom(data); + var month = req.Birthday / 100; + var day = req.Birthday % 100; + if (month < 1 || month > 12 || day < 1 || day > 31) { - var req = SetGameplayBirthdayCsReq.Parser.ParseFrom(data); - var month = req.Birthday / 100; - var day = req.Birthday % 100; - if (month < 1 || month > 12 || day < 1 || day > 31) - { - connection.SendPacket(new PacketSetGameplayBirthdayScRsp()); - return; - } - var playerData = connection.Player!.Data; - if (playerData.Birthday != 0) - { - connection.SendPacket(new PacketSetGameplayBirthdayScRsp()); - return; - } - playerData.Birthday = (int)req.Birthday; - DatabaseHelper.Instance!.UpdateInstance(playerData); - connection.SendPacket(new PacketSetGameplayBirthdayScRsp(req.Birthday)); + await connection.SendPacket(new PacketSetGameplayBirthdayScRsp()); + return; } + + var playerData = connection.Player!.Data; + if (playerData.Birthday != 0) + { + await connection.SendPacket(new PacketSetGameplayBirthdayScRsp()); + return; + } + + playerData.Birthday = (int)req.Birthday; + + await connection.SendPacket(new PacketSetGameplayBirthdayScRsp(req.Birthday)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerSetHeadIconCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerSetHeadIconCsReq.cs index 2b3eb36f..c0bef6c0 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerSetHeadIconCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerSetHeadIconCsReq.cs @@ -1,20 +1,18 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.SetHeadIconCsReq)] +public class HandlerSetHeadIconCsReq : Handler { - [Opcode(CmdIds.SetHeadIconCsReq)] - public class HandlerSetHeadIconCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var player = connection.Player!; - var req = SetHeadIconCsReq.Parser.ParseFrom(data); - if (req == null) return; - player.Data.HeadIcon = (int)req.Id; - DatabaseHelper.Instance?.UpdateInstance(player.Data); - connection.SendPacket(new PacketSetHeadIconScRsp(player)); - } + var player = connection.Player!; + var req = SetHeadIconCsReq.Parser.ParseFrom(data); + if (req == null) return; + player.Data.HeadIcon = (int)req.Id; + + await connection.SendPacket(new PacketSetHeadIconScRsp(player)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerSetHeroBasicTypeCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerSetHeroBasicTypeCsReq.cs index 10ca2197..8dbe1c1a 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerSetHeroBasicTypeCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerSetHeroBasicTypeCsReq.cs @@ -1,34 +1,27 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.SetHeroBasicTypeCsReq)] +public class HandlerSetHeroBasicTypeCsReq : Handler { - [Opcode(CmdIds.SetHeroBasicTypeCsReq)] - public class HandlerSetHeroBasicTypeCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = SetHeroBasicTypeCsReq.Parser.ParseFrom(data); + + var player = connection.Player!; + var avatar = player.AvatarManager!.GetHero(); + if (avatar == null) { - var req = SetHeroBasicTypeCsReq.Parser.ParseFrom(data); - - var player = connection.Player!; - var avatar = player.AvatarManager!.GetHero(); - if (avatar == null) - { - connection.SendPacket(new PacketSetHeroBasicTypeScRsp()); - return; - } - - avatar.HeroId = (int)req.BasicType; - player.Data.CurBasicType = (int)req.BasicType; - - connection.SendPacket(new PacketPlayerSyncScNotify(avatar)); - connection.SendPacket(new PacketSetHeroBasicTypeScRsp((uint)req.BasicType)); + await connection.SendPacket(new PacketSetHeroBasicTypeScRsp()); + return; } + + avatar.HeroId = (int)req.BasicType; + player.Data.CurBasicType = (int)req.BasicType; + + await connection.SendPacket(new PacketPlayerSyncScNotify(avatar)); + await connection.SendPacket(new PacketSetHeroBasicTypeScRsp((uint)req.BasicType)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerSetNicknameCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerSetNicknameCsReq.cs index 7242886d..58b507b6 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerSetNicknameCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerSetNicknameCsReq.cs @@ -1,21 +1,19 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.SetNicknameCsReq)] +public class HandlerSetNicknameCsReq : Handler { - [Opcode(CmdIds.SetNicknameCsReq)] - public class HandlerSetNicknameCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var player = connection.Player!; - var req = SetNicknameCsReq.Parser.ParseFrom(data); - if (req == null) return; - player.Data.Name = req.Nickname; - DatabaseHelper.Instance?.UpdateInstance(player.Data); - connection.SendPacket(CmdIds.SetNicknameScRsp); - connection.SendPacket(new PacketPlayerSyncScNotify(player.ToProto())); - } + var player = connection.Player!; + var req = SetNicknameCsReq.Parser.ParseFrom(data); + if (req == null) return; + player.Data.Name = req.Nickname; + + await connection.SendPacket(CmdIds.SetNicknameScRsp); + await connection.SendPacket(new PacketPlayerSyncScNotify(player.ToProto())); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerSetPlayerInfoCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerSetPlayerInfoCsReq.cs index 30eab77a..e6d1148b 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerSetPlayerInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerSetPlayerInfoCsReq.cs @@ -1,38 +1,35 @@ -using EggLink.DanhengServer.Database; +using EggLink.DanhengServer.Enums.Avatar; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.SetPlayerInfoCsReq)] +public class HandlerSetPlayerInfoCsReq : Handler { - [Opcode(CmdIds.SetPlayerInfoCsReq)] - public class HandlerSetPlayerInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var player = connection.Player!; + var req = SetPlayerInfoCsReq.Parser.ParseFrom(data); + if (req == null) return; + player.Data.Name = req.Nickname; + if (req.Gender == Gender.None) { - var player = connection.Player!; - var req = SetPlayerInfoCsReq.Parser.ParseFrom(data); - if (req == null) return; - player.Data.Name = req.Nickname; - if (req.Gender == Gender.None) - { - connection.SendPacket(new PacketSetPlayerInfoScRsp(player, req.IsModify)); - return; - } - if (req.Gender == Gender.Woman) - { - player.Data.CurrentGender = Gender.Woman; - } else - { - player.Data.CurrentGender = Gender.Man; - } - player.ChangeHeroBasicType(Enums.Avatar.HeroBasicTypeEnum.Warrior); - - player.LineupManager!.AddAvatarToCurTeam(8001); - player.LineupManager!.AddAvatarToCurTeam(1001); - player.MissionManager!.FinishSubMission(100010134); - - connection.SendPacket(new PacketSetPlayerInfoScRsp(player, req.IsModify)); - connection.SendPacket(new PacketPlayerSyncScNotify(player.ToProto())); + await connection.SendPacket(new PacketSetPlayerInfoScRsp(player, req.IsModify)); + return; } + + if (req.Gender == Gender.Woman) + player.Data.CurrentGender = Gender.Woman; + else + player.Data.CurrentGender = Gender.Man; + await player.ChangeHeroBasicType(HeroBasicTypeEnum.Warrior); + + await player.LineupManager!.AddAvatarToCurTeam(8001); + await player.LineupManager!.AddAvatarToCurTeam(1001); + await player.MissionManager!.FinishSubMission(100010134); + + await connection.SendPacket(new PacketSetPlayerInfoScRsp(player, req.IsModify)); + await connection.SendPacket(new PacketPlayerSyncScNotify(player.ToProto())); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerSetSignatureCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerSetSignatureCsReq.cs index bb4473a8..bca636ae 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerSetSignatureCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerSetSignatureCsReq.cs @@ -1,25 +1,17 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Player; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.SetSignatureCsReq)] +public class HandlerSetSignatureCsReq : Handler { - [Opcode(CmdIds.SetSignatureCsReq)] - public class HandlerSetSignatureCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SetSignatureCsReq.Parser.ParseFrom(data); + var req = SetSignatureCsReq.Parser.ParseFrom(data); - connection.Player!.Data.Signature = req.Signature; - DatabaseHelper.Instance!.UpdateInstance(connection.Player!.Data); + connection.Player!.Data.Signature = req.Signature; - connection.SendPacket(new PacketSetSignatureScRsp(req.Signature)); - } + await connection.SendPacket(new PacketSetSignatureScRsp(req.Signature)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Player/HandlerUseItemCsReq.cs b/GameServer/Server/Packet/Recv/Player/HandlerUseItemCsReq.cs index 021acbb9..a016eba9 100644 --- a/GameServer/Server/Packet/Recv/Player/HandlerUseItemCsReq.cs +++ b/GameServer/Server/Packet/Recv/Player/HandlerUseItemCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Player +namespace EggLink.DanhengServer.Server.Packet.Recv.Player; + +[Opcode(CmdIds.UseItemCsReq)] +public class HandlerUseItemCsReq : Handler { - [Opcode(CmdIds.UseItemCsReq)] - public class HandlerUseItemCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = UseItemCsReq.Parser.ParseFrom(data); + var req = UseItemCsReq.Parser.ParseFrom(data); - connection.SendPacket(CmdIds.UseItemScRsp); - } + await connection.SendPacket(CmdIds.UseItemScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Quest/HandlerGetQuestDataCsReq.cs b/GameServer/Server/Packet/Recv/Quest/HandlerGetQuestDataCsReq.cs index 63dff54d..ffdb9a30 100644 --- a/GameServer/Server/Packet/Recv/Quest/HandlerGetQuestDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Quest/HandlerGetQuestDataCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Quest; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Quest +namespace EggLink.DanhengServer.Server.Packet.Recv.Quest; + +[Opcode(CmdIds.GetQuestDataCsReq)] +public class HandlerGetQuestDataCsReq : Handler { - [Opcode(CmdIds.GetQuestDataCsReq)] - public class HandlerGetQuestDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetQuestDataScRsp()); - } + await connection.SendPacket(new PacketGetQuestDataScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Raid/HandlerGetAllSaveRaidCsReq.cs b/GameServer/Server/Packet/Recv/Raid/HandlerGetAllSaveRaidCsReq.cs index 86d794e3..b348b1b5 100644 --- a/GameServer/Server/Packet/Recv/Raid/HandlerGetAllSaveRaidCsReq.cs +++ b/GameServer/Server/Packet/Recv/Raid/HandlerGetAllSaveRaidCsReq.cs @@ -1,21 +1,14 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid; -using EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid; + +[Opcode(CmdIds.GetAllSaveRaidCsReq)] +public class HandlerGetAllSaveRaidCsReq : Handler { - [Opcode(CmdIds.GetAllSaveRaidCsReq)] - public class HandlerGetAllSaveRaidCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetAllSaveRaidScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetAllSaveRaidScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Raid/HandlerGetRaidInfoCsReq.cs b/GameServer/Server/Packet/Recv/Raid/HandlerGetRaidInfoCsReq.cs index 1ce56395..aef9faec 100644 --- a/GameServer/Server/Packet/Recv/Raid/HandlerGetRaidInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Raid/HandlerGetRaidInfoCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid; + +[Opcode(CmdIds.GetRaidInfoCsReq)] +public class HandlerGetRaidInfoCsReq : Handler { - [Opcode(CmdIds.GetRaidInfoCsReq)] - public class HandlerGetRaidInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetRaidInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetRaidInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Raid/HandlerGetSaveRaidCsReq.cs b/GameServer/Server/Packet/Recv/Raid/HandlerGetSaveRaidCsReq.cs index 64cbcad5..185a221c 100644 --- a/GameServer/Server/Packet/Recv/Raid/HandlerGetSaveRaidCsReq.cs +++ b/GameServer/Server/Packet/Recv/Raid/HandlerGetSaveRaidCsReq.cs @@ -1,24 +1,18 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid; -using EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid; + +[Opcode(CmdIds.GetSaveRaidCsReq)] +public class HandlerGetSaveRaidCsReq : Handler { - [Opcode(CmdIds.GetSaveRaidCsReq)] - public class HandlerGetSaveRaidCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetSaveRaidCsReq.Parser.ParseFrom(data); + var req = GetSaveRaidCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetSaveRaidScRsp(connection.Player!, (int)req.RaidId, (int)req.WorldLevel)); - } + await connection.SendPacket( + new PacketGetSaveRaidScRsp(connection.Player!, (int)req.RaidId, (int)req.WorldLevel)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Raid/HandlerLeaveRaidCsReq.cs b/GameServer/Server/Packet/Recv/Raid/HandlerLeaveRaidCsReq.cs index c0192ff9..9a0ceec8 100644 --- a/GameServer/Server/Packet/Recv/Raid/HandlerLeaveRaidCsReq.cs +++ b/GameServer/Server/Packet/Recv/Raid/HandlerLeaveRaidCsReq.cs @@ -1,28 +1,18 @@ -using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Enums.Scene; -using EggLink.DanhengServer.Game.Lineup; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid; + +[Opcode(CmdIds.LeaveRaidCsReq)] +public class HandlerLeaveRaidCsReq : Handler { - [Opcode(CmdIds.LeaveRaidCsReq)] - public class HandlerLeaveRaidCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var player = connection.Player!; - var req = LeaveRaidCsReq.Parser.ParseFrom(data); - player.RaidManager!.LeaveRaid(req.IsSave); + var player = connection.Player!; + var req = LeaveRaidCsReq.Parser.ParseFrom(data); + await player.RaidManager!.LeaveRaid(req.IsSave); - connection.SendPacket(CmdIds.LeaveRaidScRsp); - } + await connection.SendPacket(CmdIds.LeaveRaidScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Raid/HandlerStartRaidCsReq.cs b/GameServer/Server/Packet/Recv/Raid/HandlerStartRaidCsReq.cs index be049987..7a5a802c 100644 --- a/GameServer/Server/Packet/Recv/Raid/HandlerStartRaidCsReq.cs +++ b/GameServer/Server/Packet/Recv/Raid/HandlerStartRaidCsReq.cs @@ -1,28 +1,20 @@ -using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using EggLink.DanhengServer.Server.Packet.Send.Lineup; -using EggLink.DanhengServer.Server.Packet.Send.Scene; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Raid; + +[Opcode(CmdIds.StartRaidCsReq)] +public class HandlerStartRaidCsReq : Handler { - [Opcode(CmdIds.StartRaidCsReq)] - public class HandlerStartRaidCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = StartRaidCsReq.Parser.ParseFrom(data); - var player = connection.Player!; + var req = StartRaidCsReq.Parser.ParseFrom(data); + var player = connection.Player!; - player.RaidManager!.EnterRaid((int)req.RaidId, (int)req.WorldLevel, req.AvatarList.Select(x => (int)x).ToList(), req.IsSave == 1); + await player.RaidManager!.EnterRaid((int)req.RaidId, (int)req.WorldLevel, + req.AvatarList.Select(x => (int)x).ToList(), req.IsSave == 1); - connection.SendPacket(CmdIds.StartRaidScRsp); - } + await connection.SendPacket(CmdIds.StartRaidScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueCheatRollCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueCheatRollCsReq.cs index f05f5ce0..dfeb41b8 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueCheatRollCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueCheatRollCsReq.cs @@ -1,19 +1,14 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.ChessRogueCheatRollCsReq)] +public class HandlerChessRogueCheatRollCsReq : Handler { - [Opcode(CmdIds.ChessRogueCheatRollCsReq)] - public class HandlerChessRogueCheatRollCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ChessRogueCheatRollCsReq.Parser.ParseFrom(data); - connection.Player!.ChessRogueManager!.RogueInstance?.CheatDice((int)req.SurfaceId); - } + var req = ChessRogueCheatRollCsReq.Parser.ParseFrom(data); + if (connection.Player!.ChessRogueManager?.RogueInstance == null) return; + await connection.Player!.ChessRogueManager!.RogueInstance.CheatDice((int)req.SurfaceId); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueReRollDiceCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueReRollDiceCsReq.cs index 1f3df85a..e2476622 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueReRollDiceCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueReRollDiceCsReq.cs @@ -1,17 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +[Opcode(CmdIds.ChessRogueReRollDiceCsReq)] +public class HandlerChessRogueReRollDiceCsReq : Handler { - [Opcode(CmdIds.ChessRogueReRollDiceCsReq)] - public class HandlerChessRogueReRollDiceCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.Player!.ChessRogueManager!.RogueInstance?.ReRollDice(); - } + if (connection.Player!.ChessRogueManager?.RogueInstance == null) return; + await connection.Player!.ChessRogueManager.RogueInstance.ReRollDice(); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueSelectCellCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueSelectCellCsReq.cs index a2cab7ac..6b2e8923 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueSelectCellCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerChessRogueSelectCellCsReq.cs @@ -1,20 +1,15 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.ChessRogueSelectCellCsReq)] +public class HandlerChessRogueSelectCellCsReq : Handler { - [Opcode(CmdIds.ChessRogueSelectCellCsReq)] - public class HandlerChessRogueSelectCellCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ChessRogueSelectCellCsReq.Parser.ParseFrom(data); + var req = ChessRogueSelectCellCsReq.Parser.ParseFrom(data); - connection.Player!.ChessRogueManager!.RogueInstance?.SelectCell((int)req.CellId); - } + if (connection.Player!.ChessRogueManager?.RogueInstance == null) return; + await connection.Player!.ChessRogueManager!.RogueInstance.SelectCell((int)req.CellId); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerEnhanceChessRogueBuffCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerEnhanceChessRogueBuffCsReq.cs index 922a4be0..ed0fe308 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerEnhanceChessRogueBuffCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerEnhanceChessRogueBuffCsReq.cs @@ -1,22 +1,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.ChessRogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.EnhanceChessRogueBuffCsReq)] +public class HandlerEnhanceChessRogueBuffCsReq : Handler { - [Opcode(CmdIds.EnhanceChessRogueBuffCsReq)] - public class HandlerEnhanceChessRogueBuffCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = EnhanceChessRogueBuffCsReq.Parser.ParseFrom(data); + var req = EnhanceChessRogueBuffCsReq.Parser.ParseFrom(data); - connection.Player!.ChessRogueManager!.RogueInstance!.EnhanceBuff((int)req.MazeBuffId, RogueActionSource.RogueCommonActionResultSourceTypeEnhance); - connection.SendPacket(new PacketEnhanceChessRogueBuffScRsp(connection.Player!.ChessRogueManager!.RogueInstance!, req.MazeBuffId)); - } + await connection.Player!.ChessRogueManager!.RogueInstance!.EnhanceBuff((int)req.MazeBuffId, + RogueActionSource.RogueCommonActionResultSourceTypeEnhance); + await connection.SendPacket( + new PacketEnhanceChessRogueBuffScRsp(connection.Player!.ChessRogueManager!.RogueInstance!, req.MazeBuffId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerEnhanceRogueBuffCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerEnhanceRogueBuffCsReq.cs index 6f47a893..e8246e81 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerEnhanceRogueBuffCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerEnhanceRogueBuffCsReq.cs @@ -1,26 +1,20 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.EnhanceRogueBuffCsReq)] +public class HandlerEnhanceRogueBuffCsReq : Handler { - [Opcode(CmdIds.EnhanceRogueBuffCsReq)] - public class HandlerEnhanceRogueBuffCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = EnhanceRogueBuffCsReq.Parser.ParseFrom(data); + var req = EnhanceRogueBuffCsReq.Parser.ParseFrom(data); - var rogue = connection.Player!.RogueManager?.GetRogueInstance(); - if (rogue == null) return; + var rogue = connection.Player!.RogueManager?.GetRogueInstance(); + if (rogue == null) return; - rogue.EnhanceBuff((int)req.MazeBuffId, RogueActionSource.RogueCommonActionResultSourceTypeEnhance); + await rogue.EnhanceBuff((int)req.MazeBuffId, RogueActionSource.RogueCommonActionResultSourceTypeEnhance); - connection.SendPacket(new PacketEnhanceRogueBuffScRsp(req.MazeBuffId)); - } + await connection.SendPacket(new PacketEnhanceRogueBuffScRsp(req.MazeBuffId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerEnterRogueMapRoomCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerEnterRogueMapRoomCsReq.cs index 1cbc2fc7..060263cf 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerEnterRogueMapRoomCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerEnterRogueMapRoomCsReq.cs @@ -1,23 +1,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.EnterRogueMapRoomCsReq)] +public class HandlerEnterRogueMapRoomCsReq : Handler { - [Opcode(CmdIds.EnterRogueMapRoomCsReq)] - public class HandlerEnterRogueMapRoomCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = EnterRogueMapRoomCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - player.RogueManager!.RogueInstance?.EnterRoom((int)req.SiteId); + var req = EnterRogueMapRoomCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + if (player.RogueManager?.RogueInstance == null) return; + await player.RogueManager!.RogueInstance.EnterRoom((int)req.SiteId); - connection.SendPacket(new PacketEnterRogueMapRoomScRsp(player)); - } + await connection.SendPacket(new PacketEnterRogueMapRoomScRsp(player)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerFinishRogueCommonDialogueCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerFinishRogueCommonDialogueCsReq.cs index ac970352..2485511a 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerFinishRogueCommonDialogueCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerFinishRogueCommonDialogueCsReq.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.FinishRogueCommonDialogueCsReq)] +public class HandlerFinishRogueCommonDialogueCsReq : Handler { - [Opcode(CmdIds.FinishRogueCommonDialogueCsReq)] - public class HandlerFinishRogueCommonDialogueCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = FinishRogueCommonDialogueCsReq.Parser.ParseFrom(data); + var req = FinishRogueCommonDialogueCsReq.Parser.ParseFrom(data); - var rogue = connection.Player!.RogueManager?.GetRogueInstance(); - if (rogue == null) return; + var rogue = connection.Player!.RogueManager?.GetRogueInstance(); + if (rogue == null) return; - rogue.HandleFinishDialogueGroup((int)req.EventUniqueId); + await rogue.HandleFinishDialogueGroup((int)req.EventUniqueId); - connection.SendPacket(CmdIds.FinishRogueCommonDialogueScRsp); - } + await connection.SendPacket(CmdIds.FinishRogueCommonDialogueScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueBuffEnhanceInfoCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueBuffEnhanceInfoCsReq.cs index 213a3e62..956d493a 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueBuffEnhanceInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueBuffEnhanceInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.GetRogueBuffEnhanceInfoCsReq)] +public class HandlerGetRogueBuffEnhanceInfoCsReq : Handler { - [Opcode(CmdIds.GetRogueBuffEnhanceInfoCsReq)] - public class HandlerGetRogueBuffEnhanceInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetRogueBuffEnhanceInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetRogueBuffEnhanceInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueHandbookDataCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueHandbookDataCsReq.cs index 0a1af01c..8e48e269 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueHandbookDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueHandbookDataCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.GetRogueHandbookDataCsReq)] +public class HandlerGetRogueHandbookDataCsReq : Handler { - [Opcode(CmdIds.GetRogueHandbookDataCsReq)] - public class HandlerGetRogueHandbookDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetRogueHandbookDataScRsp()); - } + await connection.SendPacket(new PacketGetRogueHandbookDataScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueInfoCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueInfoCsReq.cs index 0ef97e1b..f1df7bff 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.GetRogueInfoCsReq)] +public class HandlerGetRogueInfoCsReq : Handler { - [Opcode(CmdIds.GetRogueInfoCsReq)] - public class HandlerGetRogueInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetRogueInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetRogueInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueInitialScoreCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueInitialScoreCsReq.cs index 834a7403..7b74d0d0 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueInitialScoreCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueInitialScoreCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.GetRogueInitialScoreCsReq)] +public class HandlerGetRogueInitialScoreCsReq : Handler { - [Opcode(CmdIds.GetRogueInitialScoreCsReq)] - public class HandlerGetRogueInitialScoreCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetRogueInitialScoreScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetRogueInitialScoreScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueScoreRewardInfoCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueScoreRewardInfoCsReq.cs index 5f77a3d1..29f99810 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueScoreRewardInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueScoreRewardInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.GetRogueScoreRewardInfoCsReq)] +public class HandlerGetRogueScoreRewardInfoCsReq : Handler { - [Opcode(CmdIds.GetRogueScoreRewardInfoCsReq)] - public class HandlerGetRogueScoreRewardInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetRogueScoreRewardInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetRogueScoreRewardInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueTalentInfoCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueTalentInfoCsReq.cs index 640f647c..4c12b493 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueTalentInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerGetRogueTalentInfoCsReq.cs @@ -1,18 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.GetRogueTalentInfoCsReq)] +public class HandlerGetRogueTalentInfoCsReq : Handler { - [Opcode(CmdIds.GetRogueTalentInfoCsReq)] - public class HandlerGetRogueTalentInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetRogueTalentInfoScRsp()); - } + await connection.SendPacket(new PacketGetRogueTalentInfoScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerHandleRogueCommonPendingActionCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerHandleRogueCommonPendingActionCsReq.cs index 0f65b9ba..22c7c64d 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerHandleRogueCommonPendingActionCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerHandleRogueCommonPendingActionCsReq.cs @@ -1,38 +1,23 @@ using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Util; -using Google.Protobuf; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.HandleRogueCommonPendingActionCsReq)] +public class HandlerHandleRogueCommonPendingActionCsReq : Handler { - [Opcode(CmdIds.HandleRogueCommonPendingActionCsReq)] - public class HandlerHandleRogueCommonPendingActionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = HandleRogueCommonPendingActionCsReq.Parser.ParseFrom(data); + var req = HandleRogueCommonPendingActionCsReq.Parser.ParseFrom(data); - var rogue = connection.Player!.RogueManager?.GetRogueInstance(); - if (rogue == null) return; + var rogue = connection.Player!.RogueManager?.GetRogueInstance(); + if (rogue == null) return; - if (req.BuffSelectResult != null) - { - rogue.HandleBuffSelect((int)req.BuffSelectResult.BuffId); - } + if (req.BuffSelectResult != null) await rogue.HandleBuffSelect((int)req.BuffSelectResult.BuffId); - if (req.BuffRerollSelectResult != null) - { - rogue.HandleRerollBuff(); - } + if (req.BuffRerollSelectResult != null) await rogue.HandleRerollBuff(); - if (req.BonusSelectResult != null) - { - rogue.HandleBonusSelect((int)req.BonusSelectResult.BonusId); - } + if (req.BonusSelectResult != null) await rogue.HandleBonusSelect((int)req.BonusSelectResult.BonusId); - if (req.MiracleSelectResult != null) - { - rogue.HandleMiracleSelect(req.MiracleSelectResult.MiracleId); - } - } + if (req.MiracleSelectResult != null) await rogue.HandleMiracleSelect(req.MiracleSelectResult.MiracleId); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerLeaveRogueCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerLeaveRogueCsReq.cs index d8fdbfe6..7d9bee02 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerLeaveRogueCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerLeaveRogueCsReq.cs @@ -1,24 +1,14 @@ -using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Server.Packet.Send.Rogue; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using EggLink.DanhengServer.Server.Packet.Send.Rogue; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.LeaveRogueCsReq)] +public class HandlerLeaveRogueCsReq : Handler { - [Opcode(CmdIds.LeaveRogueCsReq)] - public class HandlerLeaveRogueCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var player = connection.Player!; - if (player.RogueManager?.RogueInstance != null) - { - player.RogueManager.RogueInstance.LeaveRogue(); - } - connection.SendPacket(new PacketLeaveRogueScRsp(player)); - } + var player = connection.Player!; + if (player.RogueManager?.RogueInstance != null) await player.RogueManager.RogueInstance.LeaveRogue(); + await connection.SendPacket(new PacketLeaveRogueScRsp(player)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerQuitRogueCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerQuitRogueCsReq.cs index 47b25d42..258a54f5 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerQuitRogueCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerQuitRogueCsReq.cs @@ -1,14 +1,14 @@ using EggLink.DanhengServer.Server.Packet.Send.Rogue; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.QuitRogueCsReq)] +public class HandlerQuitRogueCsReq : Handler { - [Opcode(CmdIds.QuitRogueCsReq)] - public class HandlerQuitRogueCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.Player!.RogueManager!.RogueInstance?.QuitRogue(); - connection.SendPacket(new PacketQuitRogueScRsp(connection.Player!)); - } + if (connection.Player!.RogueManager?.RogueInstance == null) return; + await connection.Player!.RogueManager!.RogueInstance.QuitRogue(); + await connection.SendPacket(new PacketQuitRogueScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerRogueNpcDisappearCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerRogueNpcDisappearCsReq.cs index c6c8ea14..636eee7d 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerRogueNpcDisappearCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerRogueNpcDisappearCsReq.cs @@ -1,22 +1,22 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.RogueNpcDisappearCsReq)] +public class HandlerRogueNpcDisappearCsReq : Handler { - [Opcode(CmdIds.RogueNpcDisappearCsReq)] - public class HandlerRogueNpcDisappearCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = RogueNpcDisappearCsReq.Parser.ParseFrom(data); + + if (connection.Player!.RogueManager?.GetRogueInstance() == null) { - var req = RogueNpcDisappearCsReq.Parser.ParseFrom(data); - - connection.Player!.RogueManager!.GetRogueInstance()?.HandleNpcDisappear((int)req.DisappearNpcEntityId); - - connection.SendPacket(CmdIds.RogueNpcDisappearScRsp); + await connection.SendPacket(CmdIds.RogueNpcDisappearScRsp); + return; } + + await connection.Player!.RogueManager!.GetRogueInstance()!.HandleNpcDisappear((int)req.DisappearNpcEntityId); + + await connection.SendPacket(CmdIds.RogueNpcDisappearScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerSelectRogueCommonDialogueOptionCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerSelectRogueCommonDialogueOptionCsReq.cs index a70b2449..3338a535 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerSelectRogueCommonDialogueOptionCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerSelectRogueCommonDialogueOptionCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.SelectRogueCommonDialogueOptionCsReq)] +public class HandlerSelectRogueCommonDialogueOptionCsReq : Handler { - [Opcode(CmdIds.SelectRogueCommonDialogueOptionCsReq)] - public class HandlerSelectRogueCommonDialogueOptionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SelectRogueCommonDialogueOptionCsReq.Parser.ParseFrom(data); + var req = SelectRogueCommonDialogueOptionCsReq.Parser.ParseFrom(data); - var rogue = connection.Player!.RogueManager?.GetRogueInstance(); - if (rogue == null) return; + var rogue = connection.Player!.RogueManager?.GetRogueInstance(); + if (rogue == null) return; - rogue.HandleSelectOption((int)req.EventUniqueId, (int)req.OptionId); - } + await rogue.HandleSelectOption((int)req.EventUniqueId, (int)req.OptionId); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Rogue/HandlerStartRogueCsReq.cs b/GameServer/Server/Packet/Recv/Rogue/HandlerStartRogueCsReq.cs index d6879cc8..58bb31a5 100644 --- a/GameServer/Server/Packet/Recv/Rogue/HandlerStartRogueCsReq.cs +++ b/GameServer/Server/Packet/Recv/Rogue/HandlerStartRogueCsReq.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue +namespace EggLink.DanhengServer.Server.Packet.Recv.Rogue; + +[Opcode(CmdIds.StartRogueCsReq)] +public class HandlerStartRogueCsReq : Handler { - [Opcode(CmdIds.StartRogueCsReq)] - public class HandlerStartRogueCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = StartRogueCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - var disableAeonIdList = req.DisableAeonIdList.Select(x => (int)x).ToList(); - var avatarIds = req.BaseAvatarIdList.Select(x => (int)x).ToList(); + var req = StartRogueCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + var disableAeonIdList = req.DisableAeonIdList.Select(x => (int)x).ToList(); + var avatarIds = req.BaseAvatarIdList.Select(x => (int)x).ToList(); - player.RogueManager!.StartRogue((int) req.AreaId, (int)req.AeonId, disableAeonIdList, avatarIds); - } + await player.RogueManager!.StartRogue((int)req.AreaId, (int)req.AeonId, disableAeonIdList, avatarIds); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerActivateFarmElementCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerActivateFarmElementCsReq.cs index 73225d98..8a7a75f0 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerActivateFarmElementCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerActivateFarmElementCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.ActivateFarmElementCsReq)] +public class HandlerActivateFarmElementCsReq : Handler { - [Opcode(CmdIds.ActivateFarmElementCsReq)] - public class HandlerActivateFarmElementCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ActivateFarmElementCsReq.Parser.ParseFrom(data); + var req = ActivateFarmElementCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketActivateFarmElementScRsp(req.EntityId, connection.Player!)); - } + await connection.SendPacket(new PacketActivateFarmElementScRsp(req.EntityId, connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerContentPackageGetDataCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerContentPackageGetDataCsReq.cs index e52a5b96..66e36531 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerContentPackageGetDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerContentPackageGetDataCsReq.cs @@ -2,22 +2,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.GameServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.ContentPackageGetDataCsReq)] +public class HandlerContentPackageGetDataCsReq : Handler { - [Opcode(CmdIds.ContentPackageGetDataCsReq)] - public class HandlerContentPackageGetDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = ContentPackageGetDataCsReq.Parser.ParseFrom(data); + var req = ContentPackageGetDataCsReq.Parser.ParseFrom(data); - //connection.SendPacket(new PacketContentPackageGetDataScRsp(req.ContentId)); // cause crash (not only SR but also ur PC(or other program) - } + await connection.SendPacket( + new PacketContentPackageGetDataScRsp(req + .ContentId)); // cause crash (not only SR but also ur PC(or other program) } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerDeactivateFarmElementCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerDeactivateFarmElementCsReq.cs index 20205504..78c951da 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerDeactivateFarmElementCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerDeactivateFarmElementCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.DeactivateFarmElementCsReq)] +public class HandlerDeactivateFarmElementCsReq : Handler { - [Opcode(CmdIds.DeactivateFarmElementCsReq)] - public class HandlerDeactivateFarmElementCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = DeactivateFarmElementCsReq.Parser.ParseFrom(data); + var req = DeactivateFarmElementCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketDeactivateFarmElementScRsp(req.EntityId)); - } + await connection.SendPacket(new PacketDeactivateFarmElementScRsp(req.EntityId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerEnterMapRotationRegionCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerEnterMapRotationRegionCsReq.cs index cf23ffca..a499e077 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerEnterMapRotationRegionCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerEnterMapRotationRegionCsReq.cs @@ -1,20 +1,14 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.EnterMapRotationRegionCsReq)] +public class HandlerEnterMapRotationRegionCsReq : Handler { - [Opcode(CmdIds.EnterMapRotationRegionCsReq)] - public class HandlerEnterMapRotationRegionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = EnterMapRotationRegionCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketEnterMapRotationRegionScRsp(req.Motion)); - } + var req = EnterMapRotationRegionCsReq.Parser.ParseFrom(data); + await connection.SendPacket(new PacketEnterMapRotationRegionScRsp(req.Motion)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerEnterSceneCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerEnterSceneCsReq.cs index 11495f32..c1db728f 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerEnterSceneCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerEnterSceneCsReq.cs @@ -1,22 +1,17 @@ using EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.EnterSceneCsReq)] +public class HandlerEnterSceneCsReq : Handler { - [Opcode(CmdIds.EnterSceneCsReq)] - public class HandlerEnterSceneCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = EnterSceneCsReq.Parser.ParseFrom(data); - var overMapTp = connection.Player?.EnterScene((int)req.EntryId, (int)req.TeleportId, true, storyLineId:(int)req.GameStoryLineId, mapTp:req.MapTp); + var req = EnterSceneCsReq.Parser.ParseFrom(data); + var overMapTp = await connection.Player!.EnterScene((int)req.EntryId, (int)req.TeleportId, true, + storyLineId: (int)req.GameStoryLineId, mapTp: req.MapTp); - connection.SendPacket(new PacketEnterSceneScRsp(overMapTp == true, req.MapTp, (int)req.GameStoryLineId)); - } + await connection.SendPacket(new PacketEnterSceneScRsp(overMapTp, req.MapTp, (int)req.GameStoryLineId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerEnterSectionCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerEnterSectionCsReq.cs index d0e98497..98d09fed 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerEnterSectionCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerEnterSectionCsReq.cs @@ -1,16 +1,15 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.EnterSectionCsReq)] +public class HandlerEnterSectionCsReq : Handler { - [Opcode(CmdIds.EnterSectionCsReq)] - public class HandlerEnterSectionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = EnterSectionCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - player.EnterSection((int)req.SectionId); - connection.SendPacket(CmdIds.EnterSectionScRsp); - } + var req = EnterSectionCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + player.EnterSection((int)req.SectionId); + await connection.SendPacket(CmdIds.EnterSectionScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerGetCurSceneInfoCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerGetCurSceneInfoCsReq.cs index 0fcb0236..25ce2e03 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerGetCurSceneInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerGetCurSceneInfoCsReq.cs @@ -1,13 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Scene; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.GetCurSceneInfoCsReq)] +public class HandlerGetCurSceneInfoCsReq : Handler { - [Opcode(CmdIds.GetCurSceneInfoCsReq)] - public class HandlerGetCurSceneInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetCurSceneInfoScRsp(connection.Player!)); - } + await connection.SendPacket(new PacketGetCurSceneInfoScRsp(connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerGetEnteredSceneCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerGetEnteredSceneCsReq.cs index ca3bdae3..2248aa4f 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerGetEnteredSceneCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerGetEnteredSceneCsReq.cs @@ -1,13 +1,12 @@ using EggLink.DanhengServer.Server.Packet.Send.Scene; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.GetEnteredSceneCsReq)] +public class HandlerGetEnteredSceneCsReq : Handler { - [Opcode(CmdIds.GetEnteredSceneCsReq)] - public class HandlerGetEnteredSceneCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(new PacketGetEnteredSceneScRsp()); - } + await connection.SendPacket(new PacketGetEnteredSceneScRsp()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerGetFirstTalkByPerformanceNpcCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerGetFirstTalkByPerformanceNpcCsReq.cs index e7b15723..d8cb2999 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerGetFirstTalkByPerformanceNpcCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerGetFirstTalkByPerformanceNpcCsReq.cs @@ -1,15 +1,14 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.GetFirstTalkByPerformanceNpcCsReq)] +public class HandlerGetFirstTalkByPerformanceNpcCsReq : Handler { - [Opcode(CmdIds.GetFirstTalkByPerformanceNpcCsReq)] - public class HandlerGetFirstTalkByPerformanceNpcCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetFirstTalkByPerformanceNpcCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetFirstTalkByPerformanceNpcScRsp(req)); - } + var req = GetFirstTalkByPerformanceNpcCsReq.Parser.ParseFrom(data); + await connection.SendPacket(new PacketGetFirstTalkByPerformanceNpcScRsp(req)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerGetNpcTakenRewardCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerGetNpcTakenRewardCsReq.cs index 9a43869e..4306d615 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerGetNpcTakenRewardCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerGetNpcTakenRewardCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.GetNpcTakenRewardCsReq)] +public class HandlerGetNpcTakenRewardCsReq : Handler { - [Opcode(CmdIds.GetNpcTakenRewardCsReq)] - public class HandlerGetNpcTakenRewardCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetNpcTakenRewardCsReq.Parser.ParseFrom(data); + var req = GetNpcTakenRewardCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetNpcTakenRewardScRsp(req.NpcId)); - } + await connection.SendPacket(new PacketGetNpcTakenRewardScRsp(req.NpcId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerGetSceneMapInfoCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerGetSceneMapInfoCsReq.cs index eec504fc..95f8811e 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerGetSceneMapInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerGetSceneMapInfoCsReq.cs @@ -1,15 +1,14 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.GetSceneMapInfoCsReq)] +public class HandlerGetSceneMapInfoCsReq : Handler { - [Opcode(CmdIds.GetSceneMapInfoCsReq)] - public class HandlerGetSceneMapInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetSceneMapInfoCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetSceneMapInfoScRsp(req, connection.Player!)); - } + var req = GetSceneMapInfoCsReq.Parser.ParseFrom(data); + await connection.SendPacket(new PacketGetSceneMapInfoScRsp(req, connection.Player!)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerGetUnlockTeleportCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerGetUnlockTeleportCsReq.cs index 1d8b9e06..e6161857 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerGetUnlockTeleportCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerGetUnlockTeleportCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.GetUnlockTeleportCsReq)] +public class HandlerGetUnlockTeleportCsReq : Handler { - [Opcode(CmdIds.GetUnlockTeleportCsReq)] - public class HandlerGetUnlockTeleportCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetUnlockTeleportCsReq.Parser.ParseFrom(data); + var req = GetUnlockTeleportCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetUnlockTeleportScRsp(req)); - } + await connection.SendPacket(new PacketGetUnlockTeleportScRsp(req)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerInteractPropCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerInteractPropCsReq.cs index be8eb058..316d1bf6 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerInteractPropCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerInteractPropCsReq.cs @@ -1,16 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.InteractPropCsReq)] +public class HandlerInteractPropCsReq : Handler { - [Opcode(CmdIds.InteractPropCsReq)] - public class HandlerInteractPropCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = InteractPropCsReq.Parser.ParseFrom(data); - var prop = connection.Player?.InteractProp((int)req.PropEntityId, (int)req.InteractId); - connection.SendPacket(new PacketInteractPropScRsp(prop)); - } + var req = InteractPropCsReq.Parser.ParseFrom(data); + var prop = await connection.Player!.InteractProp((int)req.PropEntityId, (int)req.InteractId); + await connection.SendPacket(new PacketInteractPropScRsp(prop)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerLeaveMapRotationRegionCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerLeaveMapRotationRegionCsReq.cs index 662ce096..c3d9a764 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerLeaveMapRotationRegionCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerLeaveMapRotationRegionCsReq.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +[Opcode(CmdIds.LeaveMapRotationRegionCsReq)] +public class HandlerLeaveMapRotationRegionCsReq : Handler { - [Opcode(CmdIds.LeaveMapRotationRegionCsReq)] - public class HandlerLeaveMapRotationRegionCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - connection.SendPacket(CmdIds.LeaveMapRotationRegionScRsp); - } + await connection.SendPacket(CmdIds.LeaveMapRotationRegionScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerSceneEntityMoveCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerSceneEntityMoveCsReq.cs index 60e20349..e0b73355 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerSceneEntityMoveCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerSceneEntityMoveCsReq.cs @@ -1,33 +1,23 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.SceneEntityMoveCsReq)] +public class HandlerSceneEntityMoveCsReq : Handler { - [Opcode(CmdIds.SceneEntityMoveCsReq)] - public class HandlerSceneEntityMoveCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SceneEntityMoveCsReq.Parser.ParseFrom(data); - if (req != null) - { - foreach (var motion in req.EntityMotionList) + var req = SceneEntityMoveCsReq.Parser.ParseFrom(data); + if (req != null) + foreach (var motion in req.EntityMotionList) + if (connection.Player!.SceneInstance!.AvatarInfo.ContainsKey((int)motion.EntityId)) { - if (connection.Player!.SceneInstance!.AvatarInfo.ContainsKey((int)motion.EntityId)) - { - connection.Player!.Data.Pos = motion.Motion.Pos.ToPosition(); - connection.Player.Data.Rot = motion.Motion.Rot.ToPosition(); - connection.Player.OnMove(); - } + connection.Player!.Data.Pos = motion.Motion.Pos.ToPosition(); + connection.Player.Data.Rot = motion.Motion.Rot.ToPosition(); + await connection.Player.OnMove(); } - } - connection.SendPacket(CmdIds.SceneEntityMoveScRsp); - } + await connection.SendPacket(CmdIds.SceneEntityMoveScRsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerSceneEntityTeleportCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerSceneEntityTeleportCsReq.cs index e3406cd7..e965bbc4 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerSceneEntityTeleportCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerSceneEntityTeleportCsReq.cs @@ -1,22 +1,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene -{ - [Opcode(CmdIds.SceneEntityTeleportCsReq)] - public class HandlerSceneEntityTeleportCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SceneEntityTeleportCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - if (req.EntryId != player.Data.EntryId) - { - player.EnterScene((int)req.EntryId, 0, false); - } - player.MoveTo(req.EntityMotion); +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; - connection.SendPacket(new PacketSceneEntityTeleportScRsp(req.EntityMotion)); - } +[Opcode(CmdIds.SceneEntityTeleportCsReq)] +public class HandlerSceneEntityTeleportCsReq : Handler +{ + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + var req = SceneEntityTeleportCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + if (req.EntryId != player.Data.EntryId) await player.EnterScene((int)req.EntryId, 0, false); + player.MoveTo(req.EntityMotion); + + await connection.SendPacket(new PacketSceneEntityTeleportScRsp(req.EntityMotion)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Scene/HandlerSetGroupCustomSaveDataCsReq.cs b/GameServer/Server/Packet/Recv/Scene/HandlerSetGroupCustomSaveDataCsReq.cs index a84b970c..d56686aa 100644 --- a/GameServer/Server/Packet/Recv/Scene/HandlerSetGroupCustomSaveDataCsReq.cs +++ b/GameServer/Server/Packet/Recv/Scene/HandlerSetGroupCustomSaveDataCsReq.cs @@ -1,17 +1,16 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Scene; -namespace EggLink.DanhengServer.Server.Packet.Recv.Scene +namespace EggLink.DanhengServer.Server.Packet.Recv.Scene; + +[Opcode(CmdIds.SetGroupCustomSaveDataCsReq)] +public class HandlerSetGroupCustomSaveDataCsReq : Handler { - [Opcode(CmdIds.SetGroupCustomSaveDataCsReq)] - public class HandlerSetGroupCustomSaveDataCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SetGroupCustomSaveDataCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - player.SetCustomSaveData((int)req.EntryId, (int)req.GroupId, req.SaveData); - connection.SendPacket(new PacketSetGroupCustomSaveDataScRsp(req.EntryId, req.GroupId)); - } + var req = SetGroupCustomSaveDataCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + player.SetCustomSaveData((int)req.EntryId, (int)req.GroupId, req.SaveData); + await connection.SendPacket(new PacketSetGroupCustomSaveDataScRsp(req.EntryId, req.GroupId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Shop/HandlerBuyGoodsCsReq.cs b/GameServer/Server/Packet/Recv/Shop/HandlerBuyGoodsCsReq.cs index 34990241..5c14c223 100644 --- a/GameServer/Server/Packet/Recv/Shop/HandlerBuyGoodsCsReq.cs +++ b/GameServer/Server/Packet/Recv/Shop/HandlerBuyGoodsCsReq.cs @@ -1,18 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Shop; -namespace EggLink.DanhengServer.Server.Packet.Recv.Shop -{ - [Opcode(CmdIds.BuyGoodsCsReq)] - public class HandlerBuyGoodsCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var player = connection.Player!; - var req = BuyGoodsCsReq.Parser.ParseFrom(data); - var items = player.ShopService!.BuyItem((int)req.ShopId, (int)req.GoodsId, (int)req.GoodsNum); +namespace EggLink.DanhengServer.Server.Packet.Recv.Shop; - connection.SendPacket(new PacketBuyGoodsScRsp(req, items)); - } +[Opcode(CmdIds.BuyGoodsCsReq)] +public class HandlerBuyGoodsCsReq : Handler +{ + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + var player = connection.Player!; + var req = BuyGoodsCsReq.Parser.ParseFrom(data); + var items = await player.ShopService!.BuyItem((int)req.ShopId, (int)req.GoodsId, (int)req.GoodsNum); + + await connection.SendPacket(new PacketBuyGoodsScRsp(req, items)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Shop/HandlerComposeItemCsReq.cs b/GameServer/Server/Packet/Recv/Shop/HandlerComposeItemCsReq.cs index f0d5ca4a..7fdc1a81 100644 --- a/GameServer/Server/Packet/Recv/Shop/HandlerComposeItemCsReq.cs +++ b/GameServer/Server/Packet/Recv/Shop/HandlerComposeItemCsReq.cs @@ -1,27 +1,22 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Shop; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Shop +namespace EggLink.DanhengServer.Server.Packet.Recv.Shop; + +[Opcode(CmdIds.ComposeItemCsReq)] +public class HandlerComposeItemCsReq : Handler { - [Opcode(CmdIds.ComposeItemCsReq)] - public class HandlerComposeItemCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = ComposeItemCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + var item = await player.InventoryManager!.ComposeItem((int)req.ComposeId, (int)req.Count); + if (item == null) { - var req = ComposeItemCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - var item = player.InventoryManager!.ComposeItem((int)req.ComposeId, (int)req.Count); - if (item == null) - { - connection.SendPacket(new PacketComposeItemScRsp()); - return; - } - connection.SendPacket(new PacketComposeItemScRsp(req.ComposeId, req.Count, item)); + await connection.SendPacket(new PacketComposeItemScRsp()); + return; } + + await connection.SendPacket(new PacketComposeItemScRsp(req.ComposeId, req.Count, item)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Shop/HandlerDoGachaInRollShopCsReq.cs b/GameServer/Server/Packet/Recv/Shop/HandlerDoGachaInRollShopCsReq.cs index 955a7cb8..c12dbccd 100644 --- a/GameServer/Server/Packet/Recv/Shop/HandlerDoGachaInRollShopCsReq.cs +++ b/GameServer/Server/Packet/Recv/Shop/HandlerDoGachaInRollShopCsReq.cs @@ -1,70 +1,57 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Server.Packet.Send.Challenge; -using EggLink.DanhengServer.Server.Packet.Send.Gacha; using EggLink.DanhengServer.Server.Packet.Send.Shop; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Shop +namespace EggLink.DanhengServer.Server.Packet.Recv.Shop; + +[Opcode(CmdIds.DoGachaInRollShopCsReq)] +public class HandlerDoGachaInRollShopCsReq : Handler { - [Opcode(CmdIds.DoGachaInRollShopCsReq)] - public class HandlerDoGachaInRollShopCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = DoGachaInRollShopCsReq.Parser.ParseFrom(data); + ItemList itemList = new(); + var count = req.JLLODFFJGDM; + uint maxtype = 3; + for (uint i = 0; i < count; i++) { - var req = DoGachaInRollShopCsReq.Parser.ParseFrom(data); - ItemList itemList = new(); - var count = req.JLLODFFJGDM; - uint maxtype = 3; - for (uint i = 0; i < count; i++) - { - Dictionary GroupIds = new(); - Dictionary RewardIds = new(); + Dictionary GroupIds = new(); + Dictionary RewardIds = new(); - GameData.RollShopConfigData.Values.ToList().ForEach(x => + GameData.RollShopConfigData.Values.ToList().ForEach(x => + { + if (x.RollShopID == req.RollShopId) { - if (x.RollShopID == req.RollShopId) - { - GroupIds.Add(x.T1GroupID,1); - GroupIds.Add(x.T2GroupID,2); - GroupIds.Add(x.T3GroupID,3); - GroupIds.Add(x.T4GroupID,4); - } - }); - GameData.RollShopRewardData.Values.ToList().ForEach(x => - { - GroupIds.Keys.ToList().ForEach(y => - { - if (x.GroupID == y) - { - RewardIds.Add(x.RewardID, GroupIds[y]); - } - }); - }); - var RewardId = RewardIds.Keys.ToList().RandomElement(); - var type = RewardIds[RewardId]; - if (type < maxtype) maxtype = type; - var rewardExcel = GameData.RewardDataData[(int)RewardId]; - var rewardItems = rewardExcel.GetItems(); - var itemData = new ItemData() - { - ItemId = rewardItems[0].Item1, - Count = rewardItems[0].Item2 - }; - var rsp = connection.Player!.InventoryManager!.AddItem(itemData.ItemId, itemData.Count); - if (rsp != null) - { - itemList.ItemList_.Add(rsp.ToProto()); + GroupIds.Add(x.T1GroupID, 1); + GroupIds.Add(x.T2GroupID, 2); + GroupIds.Add(x.T3GroupID, 3); + GroupIds.Add(x.T4GroupID, 4); } - connection.Player!.InventoryManager!.RemoveItem(122000, 1); - } - connection.SendPacket(new PacketDoGachaInRollShopScRsp(req.RollShopId, itemList, maxtype)); + }); + GameData.RollShopRewardData.Values.ToList().ForEach(x => + { + GroupIds.Keys.ToList().ForEach(y => + { + if (x.GroupID == y) RewardIds.Add(x.RewardID, GroupIds[y]); + }); + }); + var RewardId = RewardIds.Keys.ToList().RandomElement(); + var type = RewardIds[RewardId]; + if (type < maxtype) maxtype = type; + var rewardExcel = GameData.RewardDataData[(int)RewardId]; + var rewardItems = rewardExcel.GetItems(); + var itemData = new ItemData + { + ItemId = rewardItems[0].Item1, + Count = rewardItems[0].Item2 + }; + var rsp = await connection.Player!.InventoryManager!.AddItem(itemData.ItemId, itemData.Count); + if (rsp != null) itemList.ItemList_.Add(rsp.ToProto()); + await connection.Player!.InventoryManager!.RemoveItem(122000, 1); } + + await connection.SendPacket(new PacketDoGachaInRollShopScRsp(req.RollShopId, itemList, maxtype)); } } \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Shop/HandlerGetRollShopInfoCsReq.cs b/GameServer/Server/Packet/Recv/Shop/HandlerGetRollShopInfoCsReq.cs index e13e184d..a54507dc 100644 --- a/GameServer/Server/Packet/Recv/Shop/HandlerGetRollShopInfoCsReq.cs +++ b/GameServer/Server/Packet/Recv/Shop/HandlerGetRollShopInfoCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Shop; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Shop +namespace EggLink.DanhengServer.Server.Packet.Recv.Shop; + +[Opcode(CmdIds.GetRollShopInfoCsReq)] +public class HandlerGetRollShopInfoCsReq : Handler { - [Opcode(CmdIds.GetRollShopInfoCsReq)] - public class HandlerGetRollShopInfoCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetRollShopInfoCsReq.Parser.ParseFrom(data); + var req = GetRollShopInfoCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetRollShopInfoScRsp(req.RollShopId)); - } + await connection.SendPacket(new PacketGetRollShopInfoScRsp(req.RollShopId)); } } \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Shop/HandlerGetShopListCsReq.cs b/GameServer/Server/Packet/Recv/Shop/HandlerGetShopListCsReq.cs index 39ea9da1..90a9e274 100644 --- a/GameServer/Server/Packet/Recv/Shop/HandlerGetShopListCsReq.cs +++ b/GameServer/Server/Packet/Recv/Shop/HandlerGetShopListCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Shop; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Shop +namespace EggLink.DanhengServer.Server.Packet.Recv.Shop; + +[Opcode(CmdIds.GetShopListCsReq)] +public class HandlerGetShopListCsReq : Handler { - [Opcode(CmdIds.GetShopListCsReq)] - public class HandlerGetShopListCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = GetShopListCsReq.Parser.ParseFrom(data); + var req = GetShopListCsReq.Parser.ParseFrom(data); - connection.SendPacket(new PacketGetShopListScRsp(req.ShopType)); - } + await connection.SendPacket(new PacketGetShopListScRsp(req.ShopType)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Shop/HandlerSellItemCsReq.cs b/GameServer/Server/Packet/Recv/Shop/HandlerSellItemCsReq.cs index a0328301..2e958e05 100644 --- a/GameServer/Server/Packet/Recv/Shop/HandlerSellItemCsReq.cs +++ b/GameServer/Server/Packet/Recv/Shop/HandlerSellItemCsReq.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Shop; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Shop +namespace EggLink.DanhengServer.Server.Packet.Recv.Shop; + +[Opcode(CmdIds.SellItemCsReq)] +public class HandlerSellItemCsReq : Handler { - [Opcode(CmdIds.SellItemCsReq)] - public class HandlerSellItemCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = SellItemCsReq.Parser.ParseFrom(data); - var items = connection.Player!.InventoryManager!.SellItem(req.CostData); - connection.SendPacket(new PacketSellItemScRsp(items)); - } + var req = SellItemCsReq.Parser.ParseFrom(data); + var items = await connection.Player!.InventoryManager!.SellItem(req.CostData); + await connection.SendPacket(new PacketSellItemScRsp(items)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Tutorial/HandlerFinishTutorialCsReq.cs b/GameServer/Server/Packet/Recv/Tutorial/HandlerFinishTutorialCsReq.cs index 7741dd3a..186325ee 100644 --- a/GameServer/Server/Packet/Recv/Tutorial/HandlerFinishTutorialCsReq.cs +++ b/GameServer/Server/Packet/Recv/Tutorial/HandlerFinishTutorialCsReq.cs @@ -1,26 +1,19 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Tutorial; -namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial -{ - [Opcode(CmdIds.FinishTutorialCsReq)] - public class HandlerFinishTutorialCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = FinishTutorialCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - if (player.TutorialData!.Tutorials.TryGetValue((int)req.TutorialId, out var res)) - { - if (res != TutorialStatus.TutorialFinish) - { - player.TutorialData!.Tutorials[(int)req.TutorialId] = TutorialStatus.TutorialFinish; - DatabaseHelper.Instance?.UpdateInstance(player.TutorialData!); - } - } +namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial; - connection.SendPacket(new PacketFinishTutorialScRsp(req.TutorialId)); - } +[Opcode(CmdIds.FinishTutorialCsReq)] +public class HandlerFinishTutorialCsReq : Handler +{ + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + var req = FinishTutorialCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + if (player.TutorialData!.Tutorials.TryGetValue((int)req.TutorialId, out var res)) + if (res != TutorialStatus.TutorialFinish) + player.TutorialData!.Tutorials[(int)req.TutorialId] = TutorialStatus.TutorialFinish; + + await connection.SendPacket(new PacketFinishTutorialScRsp(req.TutorialId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Tutorial/HandlerFinishTutorialGuideCsReq.cs b/GameServer/Server/Packet/Recv/Tutorial/HandlerFinishTutorialGuideCsReq.cs index eb5e1449..64658b14 100644 --- a/GameServer/Server/Packet/Recv/Tutorial/HandlerFinishTutorialGuideCsReq.cs +++ b/GameServer/Server/Packet/Recv/Tutorial/HandlerFinishTutorialGuideCsReq.cs @@ -1,27 +1,22 @@ -using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Tutorial; -namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial +namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial; + +[Opcode(CmdIds.FinishTutorialGuideCsReq)] +public class HandlerFinishTutorialGuideCsReq : Handler { - [Opcode(CmdIds.FinishTutorialGuideCsReq)] - public class HandlerFinishTutorialGuideCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { - var req = FinishTutorialGuideCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - if (player.TutorialGuideData!.Tutorials.TryGetValue((int)req.GroupId, out var res)) + var req = FinishTutorialGuideCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + if (player.TutorialGuideData!.Tutorials.TryGetValue((int)req.GroupId, out var res)) + if (res != TutorialStatus.TutorialFinish) { - if (res != TutorialStatus.TutorialFinish) - { - player.InventoryManager!.AddItem(1, 1, false); - player.TutorialGuideData!.Tutorials[(int)req.GroupId] = TutorialStatus.TutorialFinish; - DatabaseHelper.Instance?.UpdateInstance(player.TutorialGuideData!); - } + await player.InventoryManager!.AddItem(1, 1, false); + player.TutorialGuideData!.Tutorials[(int)req.GroupId] = TutorialStatus.TutorialFinish; } - connection.SendPacket(new PacketFinishTutorialGuideScRsp(req.GroupId)); - } + await connection.SendPacket(new PacketFinishTutorialGuideScRsp(req.GroupId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Tutorial/HandlerGetTutorialCsReq.cs b/GameServer/Server/Packet/Recv/Tutorial/HandlerGetTutorialCsReq.cs index 95268f5e..3f82b0f8 100644 --- a/GameServer/Server/Packet/Recv/Tutorial/HandlerGetTutorialCsReq.cs +++ b/GameServer/Server/Packet/Recv/Tutorial/HandlerGetTutorialCsReq.cs @@ -1,59 +1,56 @@ using EggLink.DanhengServer.Server.Packet.Send.Others; using EggLink.DanhengServer.Server.Packet.Send.Tutorial; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial +namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial; + +[Opcode(CmdIds.GetTutorialCsReq)] +public class HandlerGetTutorialCsReq : Handler { - [Opcode(CmdIds.GetTutorialCsReq)] - public class HandlerGetTutorialCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + await SendPlayerData(connection); + if (ConfigManager.Config.ServerOption.EnableMission) // If missions are enabled + await connection.SendPacket(new PacketGetTutorialScRsp(connection.Player!)); + } + + private async Task SendPlayerData(Connection connection) + { + var filePath = Path.Combine(Environment.CurrentDirectory, "Lua", "welcome.lua"); + if (File.Exists(filePath)) { - SendPlayerData(connection); - if (ConfigManager.Config.ServerOption.EnableMission) // If missions are enabled - connection.SendPacket(new PacketGetTutorialScRsp(connection.Player!)); + var fileBytes = File.ReadAllBytes(filePath); + await connection.SendPacket(new PacketClientDownloadDataScNotify(fileBytes)); } - private void SendPlayerData(Connection connection) + // DO NOT REMOVE THIS CODE + // This code is responsible for sending the client data to the player + switch (ConfigManager.Config.ServerOption.Language) { - string filePath = Path.Combine(Environment.CurrentDirectory, "Lua", "welcome.lua"); - if (File.Exists(filePath)) - { - var fileBytes = File.ReadAllBytes(filePath); - connection.SendPacket(new PacketClientDownloadDataScNotify(fileBytes)); - } - - // DO NOT REMOVE THIS CODE - // This code is responsible for sending the client data to the player - switch (ConfigManager.Config.ServerOption.Language) - { - case "CHS": - //var data = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gb25EaWFsb2dDbG9zZWQoKQogICAgQ1MuVW5pdHlFbmdpbmUuQXBwbGljYXRpb24uT3BlblVSTCgiaHR0cHM6Ly9zci5taWhveW8uY29tLyIpCmVuZAoKbG9jYWwgZnVuY3Rpb24gc2hvd19oaW50KCkKICAgIGxvY2FsIHRleHQgPSAi5qyi6L+O5L2/55SoRGFuaGVuZ1NlcnZlcu+8gVxuIgogICAgdGV4dCA9IHRleHQgLi4gIuacrOacjeWKoeWZqOWujOWFqOWFjei0ue+8jOWmguaenOaCqOaYr+i0reS5sOW+l+WIsOeahO+8jOmCo+S5iOaCqOW3sue7j+iiq+mql+S6hu+8gVxuIgogICAgdGV4dCA9IHRleHQgLi4gIuatpOacjeWKoeerr+S7heeUqOS9nOWtpuS5oOS6pOa1ge+8jOivt+aUr+aMgeato+eJiFxuIgogICAgQ1MuUlBHLkNsaWVudC5Db25maXJtRGlhbG9nVXRpbC5TaG93Q3VzdG9tT2tDYW5jZWxIaW50KHRleHQsIG9uRGlhbG9nQ2xvc2VkKQplbmQKCnNob3dfaGludCgp")); - connection.SendPacket(new BasePacket(5) - { - Data = Convert.FromBase64String("OtYDCFEQzsq5tAYaywNsb2NhbCBmdW5jdGlvbiBvbkRpYWxvZ0Nsb3NlZCgpCiAgICBDUy5Vbml0eUVuZ2luZS5BcHBsaWNhdGlvbi5PcGVuVVJMKCJodHRwczovL3NyLm1paG95by5jb20vIikKZW5kCgpsb2NhbCBmdW5jdGlvbiBzaG93X2hpbnQoKQogICAgbG9jYWwgdGV4dCA9ICLmrKLov47kvb/nlKhEYW5oZW5nU2VydmVy77yBXG4iCiAgICB0ZXh0ID0gdGV4dCAuLiAi5pys5pyN5Yqh5Zmo5a6M5YWo5YWN6LS577yM5aaC5p6c5oKo5piv6LSt5Lmw5b6X5Yiw55qE77yM6YKj5LmI5oKo5bey57uP6KKr6aqX5LqG77yBXG4iCiAgICB0ZXh0ID0gdGV4dCAuLiAi5q2k5pyN5Yqh56uv5LuF55So5L2c5a2m5Lmg5Lqk5rWB77yM6K+35pSv5oyB5q2j54mIXG4iCiAgICBDUy5SUEcuQ2xpZW50LkNvbmZpcm1EaWFsb2dVdGlsLlNob3dDdXN0b21Pa0NhbmNlbEhpbnQodGV4dCwgb25EaWFsb2dDbG9zZWQpCmVuZAoKc2hvd19oaW50KCk=") - }); - break; - case "CHT": - //var data2 = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gb25EaWFsb2dDbG9zZWQoKQogICAgQ1MuVW5pdHlFbmdpbmUuQXBwbGljYXRpb24uT3BlblVSTCgiaHR0cHM6Ly9oc3IuaG95b3ZlcnNlLmNvbS8iKQplbmQKCmxvY2FsIGZ1bmN0aW9uIHNob3dfaGludCgpCiAgICBsb2NhbCB0ZXh0ID0gIuatoei/juS9v+eUqERhbmhlbmdTZXJ2ZXLvvIFcbiIKICAgIHRleHQgPSB0ZXh0IC4uICLmnKzkvLrmnI3lmajlrozlhajlhY3osrvvvIzlpoLmnpzmgqjmmK/os7zosrflvpfliLDnmoTjgILpgqPpurzmgqjlt7LntpPooqvpqJnkuobvvIFcbiIKICAgIHRleHQgPSB0ZXh0IC4uICLmraTkvLrmnI3lmajou5/pq5Tlg4Xkvpvlrbjnv5LkuqTmtYHkvb/nlKjvvIzoq4vmlK/mjIHmraPniYhcbiIKICAgIENTLlJQRy5DbGllbnQuQ29uZmlybURpYWxvZ1V0aWwuU2hvd0N1c3RvbU9rQ2FuY2VsSGludCh0ZXh0LCBvbkRpYWxvZ0Nsb3NlZCkKZW5kCgpzaG93X2hpbnQoKQ==")); - connection.SendPacket(new BasePacket(5) - { - Data = Convert.FromBase64String("OuMDCFEQzsq5tAYa2ANsb2NhbCBmdW5jdGlvbiBvbkRpYWxvZ0Nsb3NlZCgpCiAgICBDUy5Vbml0eUVuZ2luZS5BcHBsaWNhdGlvbi5PcGVuVVJMKCJodHRwczovL2hzci5ob3lvdmVyc2UuY29tLyIpCmVuZAoKbG9jYWwgZnVuY3Rpb24gc2hvd19oaW50KCkKICAgIGxvY2FsIHRleHQgPSAi5q2h6L+O5L2/55SoRGFuaGVuZ1NlcnZlcu+8gVxuIgogICAgdGV4dCA9IHRleHQgLi4gIuacrOS8uuacjeWZqOWujOWFqOWFjeiyu++8jOWmguaenOaCqOaYr+izvOiyt+W+l+WIsOeahOOAgumCo+m6vOaCqOW3sue2k+iiq+momeS6hu+8gVxuIgogICAgdGV4dCA9IHRleHQgLi4gIuatpOS8uuacjeWZqOi7n+mrlOWDheS+m+WtuOe/kuS6pOa1geS9v+eUqO+8jOiri+aUr+aMgeato+eJiFxuIgogICAgQ1MuUlBHLkNsaWVudC5Db25maXJtRGlhbG9nVXRpbC5TaG93Q3VzdG9tT2tDYW5jZWxIaW50KHRleHQsIG9uRGlhbG9nQ2xvc2VkKQplbmQKCnNob3dfaGludCgp") - }); - break; - default: - //var data3 = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gb25EaWFsb2dDbG9zZWQoKQogICAgQ1MuVW5pdHlFbmdpbmUuQXBwbGljYXRpb24uT3BlblVSTCgiaHR0cHM6Ly9oc3IuaG95b3ZlcnNlLmNvbS8iKQplbmQKCmxvY2FsIGZ1bmN0aW9uIHNob3dfaGludCgpCiAgICBsb2NhbCB0ZXh0ID0gIldlbGNvbWUgdG8gRGFuaGVuZ1NlcnZlciFcbiIKICAgIHRleHQgPSB0ZXh0IC4uICJUaGlzIHNlcnZlciBzb2Z0d2FyZSBpcyB0b3RhbGx5IGZyZWUuXG4iCiAgICB0ZXh0ID0gdGV4dCAuLiAiSWYgeW91IHBheSBmb3IgaXQsIHlvdSBoYXZlIGJlZW4gc2NhbW1lZC5cbiIKICAgIHRleHQgPSB0ZXh0IC4uICJFZHVjYXRpb25hbCBwdXJwb3NlIG9ubHksIHBsZWFzZSBzdXBwb3J0IHRoZSBnZW51aW5lIGdhbWUuIgogICAgQ1MuUlBHLkNsaWVudC5Db25maXJtRGlhbG9nVXRpbC5TaG93Q3VzdG9tT2tDYW5jZWxIaW50KHRleHQsIG9uRGlhbG9nQ2xvc2VkKQplbmQKCnNob3dfaGludCgp")); - connection.SendPacket(new BasePacket(5) - { - Data = Convert.FromBase64String("Ou4DCFEQzsq5tAYa4wNsb2NhbCBmdW5jdGlvbiBvbkRpYWxvZ0Nsb3NlZCgpCiAgICBDUy5Vbml0eUVuZ2luZS5BcHBsaWNhdGlvbi5PcGVuVVJMKCJodHRwczovL2hzci5ob3lvdmVyc2UuY29tLyIpCmVuZAoKbG9jYWwgZnVuY3Rpb24gc2hvd19oaW50KCkKICAgIGxvY2FsIHRleHQgPSAiV2VsY29tZSB0byBEYW5oZW5nU2VydmVyIVxuIgogICAgdGV4dCA9IHRleHQgLi4gIlRoaXMgc2VydmVyIHNvZnR3YXJlIGlzIHRvdGFsbHkgZnJlZS5cbiIKICAgIHRleHQgPSB0ZXh0IC4uICJJZiB5b3UgcGF5IGZvciBpdCwgeW91IGhhdmUgYmVlbiBzY2FtbWVkLlxuIgogICAgdGV4dCA9IHRleHQgLi4gIkVkdWNhdGlvbmFsIHB1cnBvc2Ugb25seSwgcGxlYXNlIHN1cHBvcnQgdGhlIGdlbnVpbmUgZ2FtZS4iCiAgICBDUy5SUEcuQ2xpZW50LkNvbmZpcm1EaWFsb2dVdGlsLlNob3dDdXN0b21Pa0NhbmNlbEhpbnQodGV4dCwgb25EaWFsb2dDbG9zZWQpCmVuZAoKc2hvd19oaW50KCk=") - }); - break; - } + case "CHS": + //var data = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gb25EaWFsb2dDbG9zZWQoKQogICAgQ1MuVW5pdHlFbmdpbmUuQXBwbGljYXRpb24uT3BlblVSTCgiaHR0cHM6Ly9zci5taWhveW8uY29tLyIpCmVuZAoKbG9jYWwgZnVuY3Rpb24gc2hvd19oaW50KCkKICAgIGxvY2FsIHRleHQgPSAi5qyi6L+O5L2/55SoRGFuaGVuZ1NlcnZlcu+8gVxuIgogICAgdGV4dCA9IHRleHQgLi4gIuacrOacjeWKoeWZqOWujOWFqOWFjei0ue+8jOWmguaenOaCqOaYr+i0reS5sOW+l+WIsOeahO+8jOmCo+S5iOaCqOW3sue7j+iiq+mql+S6hu+8gVxuIgogICAgdGV4dCA9IHRleHQgLi4gIuatpOacjeWKoeerr+S7heeUqOS9nOWtpuS5oOS6pOa1ge+8jOivt+aUr+aMgeato+eJiFxuIgogICAgQ1MuUlBHLkNsaWVudC5Db25maXJtRGlhbG9nVXRpbC5TaG93Q3VzdG9tT2tDYW5jZWxIaW50KHRleHQsIG9uRGlhbG9nQ2xvc2VkKQplbmQKCnNob3dfaGludCgp")); + await connection.SendPacket(new BasePacket(5) + { + Data = Convert.FromBase64String( + "OtYDCFEQzsq5tAYaywNsb2NhbCBmdW5jdGlvbiBvbkRpYWxvZ0Nsb3NlZCgpCiAgICBDUy5Vbml0eUVuZ2luZS5BcHBsaWNhdGlvbi5PcGVuVVJMKCJodHRwczovL3NyLm1paG95by5jb20vIikKZW5kCgpsb2NhbCBmdW5jdGlvbiBzaG93X2hpbnQoKQogICAgbG9jYWwgdGV4dCA9ICLmrKLov47kvb/nlKhEYW5oZW5nU2VydmVy77yBXG4iCiAgICB0ZXh0ID0gdGV4dCAuLiAi5pys5pyN5Yqh5Zmo5a6M5YWo5YWN6LS577yM5aaC5p6c5oKo5piv6LSt5Lmw5b6X5Yiw55qE77yM6YKj5LmI5oKo5bey57uP6KKr6aqX5LqG77yBXG4iCiAgICB0ZXh0ID0gdGV4dCAuLiAi5q2k5pyN5Yqh56uv5LuF55So5L2c5a2m5Lmg5Lqk5rWB77yM6K+35pSv5oyB5q2j54mIXG4iCiAgICBDUy5SUEcuQ2xpZW50LkNvbmZpcm1EaWFsb2dVdGlsLlNob3dDdXN0b21Pa0NhbmNlbEhpbnQodGV4dCwgb25EaWFsb2dDbG9zZWQpCmVuZAoKc2hvd19oaW50KCk=") + }); + break; + case "CHT": + //var data2 = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gb25EaWFsb2dDbG9zZWQoKQogICAgQ1MuVW5pdHlFbmdpbmUuQXBwbGljYXRpb24uT3BlblVSTCgiaHR0cHM6Ly9oc3IuaG95b3ZlcnNlLmNvbS8iKQplbmQKCmxvY2FsIGZ1bmN0aW9uIHNob3dfaGludCgpCiAgICBsb2NhbCB0ZXh0ID0gIuatoei/juS9v+eUqERhbmhlbmdTZXJ2ZXLvvIFcbiIKICAgIHRleHQgPSB0ZXh0IC4uICLmnKzkvLrmnI3lmajlrozlhajlhY3osrvvvIzlpoLmnpzmgqjmmK/os7zosrflvpfliLDnmoTjgILpgqPpurzmgqjlt7LntpPooqvpqJnkuobvvIFcbiIKICAgIHRleHQgPSB0ZXh0IC4uICLmraTkvLrmnI3lmajou5/pq5Tlg4Xkvpvlrbjnv5LkuqTmtYHkvb/nlKjvvIzoq4vmlK/mjIHmraPniYhcbiIKICAgIENTLlJQRy5DbGllbnQuQ29uZmlybURpYWxvZ1V0aWwuU2hvd0N1c3RvbU9rQ2FuY2VsSGludCh0ZXh0LCBvbkRpYWxvZ0Nsb3NlZCkKZW5kCgpzaG93X2hpbnQoKQ==")); + await connection.SendPacket(new BasePacket(5) + { + Data = Convert.FromBase64String( + "OuMDCFEQzsq5tAYa2ANsb2NhbCBmdW5jdGlvbiBvbkRpYWxvZ0Nsb3NlZCgpCiAgICBDUy5Vbml0eUVuZ2luZS5BcHBsaWNhdGlvbi5PcGVuVVJMKCJodHRwczovL2hzci5ob3lvdmVyc2UuY29tLyIpCmVuZAoKbG9jYWwgZnVuY3Rpb24gc2hvd19oaW50KCkKICAgIGxvY2FsIHRleHQgPSAi5q2h6L+O5L2/55SoRGFuaGVuZ1NlcnZlcu+8gVxuIgogICAgdGV4dCA9IHRleHQgLi4gIuacrOS8uuacjeWZqOWujOWFqOWFjeiyu++8jOWmguaenOaCqOaYr+izvOiyt+W+l+WIsOeahOOAgumCo+m6vOaCqOW3sue2k+iiq+momeS6hu+8gVxuIgogICAgdGV4dCA9IHRleHQgLi4gIuatpOS8uuacjeWZqOi7n+mrlOWDheS+m+WtuOe/kuS6pOa1geS9v+eUqO+8jOiri+aUr+aMgeato+eJiFxuIgogICAgQ1MuUlBHLkNsaWVudC5Db25maXJtRGlhbG9nVXRpbC5TaG93Q3VzdG9tT2tDYW5jZWxIaW50KHRleHQsIG9uRGlhbG9nQ2xvc2VkKQplbmQKCnNob3dfaGludCgp") + }); + break; + default: + //var data3 = new PacketClientDownloadDataScNotify(Convert.FromBase64String("bG9jYWwgZnVuY3Rpb24gb25EaWFsb2dDbG9zZWQoKQogICAgQ1MuVW5pdHlFbmdpbmUuQXBwbGljYXRpb24uT3BlblVSTCgiaHR0cHM6Ly9oc3IuaG95b3ZlcnNlLmNvbS8iKQplbmQKCmxvY2FsIGZ1bmN0aW9uIHNob3dfaGludCgpCiAgICBsb2NhbCB0ZXh0ID0gIldlbGNvbWUgdG8gRGFuaGVuZ1NlcnZlciFcbiIKICAgIHRleHQgPSB0ZXh0IC4uICJUaGlzIHNlcnZlciBzb2Z0d2FyZSBpcyB0b3RhbGx5IGZyZWUuXG4iCiAgICB0ZXh0ID0gdGV4dCAuLiAiSWYgeW91IHBheSBmb3IgaXQsIHlvdSBoYXZlIGJlZW4gc2NhbW1lZC5cbiIKICAgIHRleHQgPSB0ZXh0IC4uICJFZHVjYXRpb25hbCBwdXJwb3NlIG9ubHksIHBsZWFzZSBzdXBwb3J0IHRoZSBnZW51aW5lIGdhbWUuIgogICAgQ1MuUlBHLkNsaWVudC5Db25maXJtRGlhbG9nVXRpbC5TaG93Q3VzdG9tT2tDYW5jZWxIaW50KHRleHQsIG9uRGlhbG9nQ2xvc2VkKQplbmQKCnNob3dfaGludCgp")); + await connection.SendPacket(new BasePacket(5) + { + Data = Convert.FromBase64String( + "Ou4DCFEQzsq5tAYa4wNsb2NhbCBmdW5jdGlvbiBvbkRpYWxvZ0Nsb3NlZCgpCiAgICBDUy5Vbml0eUVuZ2luZS5BcHBsaWNhdGlvbi5PcGVuVVJMKCJodHRwczovL2hzci5ob3lvdmVyc2UuY29tLyIpCmVuZAoKbG9jYWwgZnVuY3Rpb24gc2hvd19oaW50KCkKICAgIGxvY2FsIHRleHQgPSAiV2VsY29tZSB0byBEYW5oZW5nU2VydmVyIVxuIgogICAgdGV4dCA9IHRleHQgLi4gIlRoaXMgc2VydmVyIHNvZnR3YXJlIGlzIHRvdGFsbHkgZnJlZS5cbiIKICAgIHRleHQgPSB0ZXh0IC4uICJJZiB5b3UgcGF5IGZvciBpdCwgeW91IGhhdmUgYmVlbiBzY2FtbWVkLlxuIgogICAgdGV4dCA9IHRleHQgLi4gIkVkdWNhdGlvbmFsIHB1cnBvc2Ugb25seSwgcGxlYXNlIHN1cHBvcnQgdGhlIGdlbnVpbmUgZ2FtZS4iCiAgICBDUy5SUEcuQ2xpZW50LkNvbmZpcm1EaWFsb2dVdGlsLlNob3dDdXN0b21Pa0NhbmNlbEhpbnQodGV4dCwgb25EaWFsb2dDbG9zZWQpCmVuZAoKc2hvd19oaW50KCk=") + }); + break; } } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Tutorial/HandlerGetTutorialGuideCsReq.cs b/GameServer/Server/Packet/Recv/Tutorial/HandlerGetTutorialGuideCsReq.cs index 332223ac..6db58419 100644 --- a/GameServer/Server/Packet/Recv/Tutorial/HandlerGetTutorialGuideCsReq.cs +++ b/GameServer/Server/Packet/Recv/Tutorial/HandlerGetTutorialGuideCsReq.cs @@ -1,16 +1,14 @@ using EggLink.DanhengServer.Server.Packet.Send.Tutorial; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial -{ - [Opcode(CmdIds.GetTutorialGuideCsReq)] - public class HandlerGetTutorialGuideCsReq : Handler - { - public override void OnHandle(Connection connection, byte[] header, byte[] data) - { +namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial; - if (ConfigManager.Config.ServerOption.EnableMission) // If missions are enabled - connection.SendPacket(new PacketGetTutorialGuideScRsp(connection.Player!)); // some bug - } +[Opcode(CmdIds.GetTutorialGuideCsReq)] +public class HandlerGetTutorialGuideCsReq : Handler +{ + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) + { + if (ConfigManager.Config.ServerOption.EnableMission) // If missions are enabled + await connection.SendPacket(new PacketGetTutorialGuideScRsp(connection.Player!)); // some bug } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Tutorial/HandlerUnlockTutorialCsReq.cs b/GameServer/Server/Packet/Recv/Tutorial/HandlerUnlockTutorialCsReq.cs index 7a810012..f4487a9e 100644 --- a/GameServer/Server/Packet/Recv/Tutorial/HandlerUnlockTutorialCsReq.cs +++ b/GameServer/Server/Packet/Recv/Tutorial/HandlerUnlockTutorialCsReq.cs @@ -1,27 +1,22 @@ using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Tutorial; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial +namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial; + +[Opcode(CmdIds.UnlockTutorialCsReq)] +public class HandlerUnlockTutorialCsReq : Handler { - [Opcode(CmdIds.UnlockTutorialCsReq)] - public class HandlerUnlockTutorialCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = UnlockTutorialCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + if (!player.TutorialData!.Tutorials.TryGetValue((int)req.TutorialId, out var _)) { - var req = UnlockTutorialCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - if (!player.TutorialData!.Tutorials.TryGetValue((int)req.TutorialId, out var _)) - { - player.TutorialData!.Tutorials.Add((int)req.TutorialId, TutorialStatus.TutorialUnlock); - DatabaseHelper.Instance?.UpdateInstance(player.TutorialData!); - } - connection.SendPacket(new PacketUnlockTutorialScRsp(req.TutorialId)); + player.TutorialData!.Tutorials.Add((int)req.TutorialId, TutorialStatus.TutorialUnlock); + DatabaseHelper.Instance?.UpdateInstance(player.TutorialData!); } + + await connection.SendPacket(new PacketUnlockTutorialScRsp(req.TutorialId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Recv/Tutorial/HandlerUnlockTutorialGuideCsReq.cs b/GameServer/Server/Packet/Recv/Tutorial/HandlerUnlockTutorialGuideCsReq.cs index c65e50a2..b1e65d1f 100644 --- a/GameServer/Server/Packet/Recv/Tutorial/HandlerUnlockTutorialGuideCsReq.cs +++ b/GameServer/Server/Packet/Recv/Tutorial/HandlerUnlockTutorialGuideCsReq.cs @@ -1,27 +1,22 @@ using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet.Send.Tutorial; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial +namespace EggLink.DanhengServer.Server.Packet.Recv.Tutorial; + +[Opcode(CmdIds.UnlockTutorialGuideCsReq)] +public class HandlerUnlockTutorialGuideCsReq : Handler { - [Opcode(CmdIds.UnlockTutorialGuideCsReq)] - public class HandlerUnlockTutorialGuideCsReq : Handler + public override async Task OnHandle(Connection connection, byte[] header, byte[] data) { - public override void OnHandle(Connection connection, byte[] header, byte[] data) + var req = UnlockTutorialGuideCsReq.Parser.ParseFrom(data); + var player = connection.Player!; + if (!player.TutorialGuideData!.Tutorials.TryGetValue((int)req.GroupId, out var _)) { - var req = UnlockTutorialGuideCsReq.Parser.ParseFrom(data); - var player = connection.Player!; - if (!player.TutorialGuideData!.Tutorials.TryGetValue((int)req.GroupId, out var _)) - { - player.TutorialGuideData!.Tutorials.Add((int)req.GroupId, TutorialStatus.TutorialUnlock); - DatabaseHelper.Instance?.UpdateInstance(player.TutorialGuideData!); - } - connection.SendPacket(new PacketUnlockTutorialGuideScRsp(req.GroupId)); + player.TutorialGuideData!.Tutorials.Add((int)req.GroupId, TutorialStatus.TutorialUnlock); + DatabaseHelper.Instance?.UpdateInstance(player.TutorialGuideData!); } + + await connection.SendPacket(new PacketUnlockTutorialGuideScRsp(req.GroupId)); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Activity/PacketGetActivityScheduleConfigScRsp.cs b/GameServer/Server/Packet/Send/Activity/PacketGetActivityScheduleConfigScRsp.cs index a2c7828a..c668a249 100644 --- a/GameServer/Server/Packet/Send/Activity/PacketGetActivityScheduleConfigScRsp.cs +++ b/GameServer/Server/Packet/Send/Activity/PacketGetActivityScheduleConfigScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Activity +namespace EggLink.DanhengServer.Server.Packet.Send.Activity; + +public class PacketGetActivityScheduleConfigScRsp : BasePacket { - public class PacketGetActivityScheduleConfigScRsp : BasePacket + public PacketGetActivityScheduleConfigScRsp(PlayerInstance player) : base(CmdIds.GetActivityScheduleConfigScRsp) { - public PacketGetActivityScheduleConfigScRsp(PlayerInstance player) : base(CmdIds.GetActivityScheduleConfigScRsp) - { - var proto = new GetActivityScheduleConfigScRsp(); + var proto = new GetActivityScheduleConfigScRsp(); - proto.ScheduleData.AddRange(player.ActivityManager!.ToProto()); + proto.ScheduleData.AddRange(player.ActivityManager!.ToProto()); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketAddAvatarScNotify.cs b/GameServer/Server/Packet/Send/Avatar/PacketAddAvatarScNotify.cs index b6205783..2bee8b59 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketAddAvatarScNotify.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketAddAvatarScNotify.cs @@ -1,24 +1,18 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketAddAvatarScNotify : BasePacket { - public class PacketAddAvatarScNotify : BasePacket + public PacketAddAvatarScNotify(int avatarId, bool isGacha) : base(CmdIds.AddAvatarScNotify) { - public PacketAddAvatarScNotify(int avatarId, bool isGacha) : base(CmdIds.AddAvatarScNotify) + var packet = new AddAvatarScNotify { - var packet = new AddAvatarScNotify() - { - BaseAvatarId = (uint)avatarId, - IsNew = true, - Src = isGacha ? AddAvatarSrcState.AddAvatarSrcGacha : AddAvatarSrcState.AddAvatarSrcNone - }; + BaseAvatarId = (uint)avatarId, + IsNew = true, + Src = isGacha ? AddAvatarSrcState.AddAvatarSrcGacha : AddAvatarSrcState.AddAvatarSrcNone + }; - SetData(packet); - } + SetData(packet); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketAvatarExpUpScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketAvatarExpUpScRsp.cs index 7485ea6d..4f70eee5 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketAvatarExpUpScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketAvatarExpUpScRsp.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketAvatarExpUpScRsp : BasePacket { - public class PacketAvatarExpUpScRsp : BasePacket + public PacketAvatarExpUpScRsp(List returnItem) : base(CmdIds.AvatarExpUpScRsp) { - public PacketAvatarExpUpScRsp(List returnItem) : base(CmdIds.AvatarExpUpScRsp) - { - var proto = new AvatarExpUpScRsp(); - proto.ReturnItemList.AddRange(returnItem.Select(item => item.ToPileProto())); + var proto = new AvatarExpUpScRsp(); + proto.ReturnItemList.AddRange(returnItem.Select(item => item.ToPileProto())); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketExpUpEquipmentScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketExpUpEquipmentScRsp.cs index e0ba0e7d..0feadebf 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketExpUpEquipmentScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketExpUpEquipmentScRsp.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketExpUpEquipmentScRsp : BasePacket { - public class PacketExpUpEquipmentScRsp : BasePacket + public PacketExpUpEquipmentScRsp(List returnItem) : base(CmdIds.ExpUpEquipmentScRsp) { - public PacketExpUpEquipmentScRsp(List returnItem) : base(CmdIds.ExpUpEquipmentScRsp) - { - var proto = new ExpUpEquipmentScRsp(); - proto.ReturnItemList.AddRange(returnItem.Select(item => item.ToPileProto())); + var proto = new ExpUpEquipmentScRsp(); + proto.ReturnItemList.AddRange(returnItem.Select(item => item.ToPileProto())); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketExpUpRelicScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketExpUpRelicScRsp.cs index 28343d79..a52abd28 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketExpUpRelicScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketExpUpRelicScRsp.cs @@ -1,25 +1,16 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketExpUpRelicScRsp : BasePacket { - public class PacketExpUpRelicScRsp : BasePacket + public PacketExpUpRelicScRsp(List leftover) : base(CmdIds.ExpUpRelicScRsp) { - public PacketExpUpRelicScRsp(List leftover) : base(CmdIds.ExpUpRelicScRsp) - { - var proto = new ExpUpRelicScRsp(); + var proto = new ExpUpRelicScRsp(); - foreach (var item in leftover) - { - proto.ReturnItemList.Add(item.ToPileProto()); - } + foreach (var item in leftover) proto.ReturnItemList.Add(item.ToPileProto()); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketGetAssistHistoryScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketGetAssistHistoryScRsp.cs index 785999f4..d4fc6495 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketGetAssistHistoryScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketGetAssistHistoryScRsp.cs @@ -1,22 +1,14 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketGetAssistHistoryScRsp : BasePacket { - public class PacketGetAssistHistoryScRsp : BasePacket + public PacketGetAssistHistoryScRsp(PlayerInstance player) : base(CmdIds.GetAssistHistoryScRsp) { - public PacketGetAssistHistoryScRsp(PlayerInstance player) : base(CmdIds.GetAssistHistoryScRsp) - { - var proto = new GetAssistHistoryScRsp - { - }; + var proto = new GetAssistHistoryScRsp(); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketGetAssistListScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketGetAssistListScRsp.cs index 9fd44960..12b0d8ef 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketGetAssistListScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketGetAssistListScRsp.cs @@ -1,19 +1,13 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketGetAssistListScRsp : BasePacket { - public class PacketGetAssistListScRsp : BasePacket + public PacketGetAssistListScRsp() : base(CmdIds.GetAssistListScRsp) { - public PacketGetAssistListScRsp() : base(CmdIds.GetAssistListScRsp) - { - var proto = new GetAssistListScRsp(); + var proto = new GetAssistListScRsp(); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketGetAvatarDataScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketGetAvatarDataScRsp.cs index 65ccbe5c..7c82d273 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketGetAvatarDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketGetAvatarDataScRsp.cs @@ -1,25 +1,24 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketGetAvatarDataScRsp : BasePacket { - public class PacketGetAvatarDataScRsp : BasePacket + public PacketGetAvatarDataScRsp(PlayerInstance player) : base(CmdIds.GetAvatarDataScRsp) { - public PacketGetAvatarDataScRsp(PlayerInstance player) : base(CmdIds.GetAvatarDataScRsp) + var proto = new GetAvatarDataScRsp { - var proto = new GetAvatarDataScRsp() - { - IsGetAll = true, - }; + IsGetAll = true + }; - player.AvatarManager?.AvatarData?.Avatars?.ForEach(avatar => - { - if (avatar.GetBaseAvatarId() != 8001) - proto.AvatarList.Add(avatar.ToProto()); - }); - proto.AvatarList.Add(player.AvatarManager!.GetHero()!.ToProto()); + player.AvatarManager?.AvatarData?.Avatars?.ForEach(avatar => + { + if (avatar.GetBaseAvatarId() != 8001) + proto.AvatarList.Add(avatar.ToProto()); + }); + proto.AvatarList.Add(player.AvatarManager!.GetHero()!.ToProto()); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketGetHeroBasicTypeInfoScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketGetHeroBasicTypeInfoScRsp.cs index 4784f793..2b5e895c 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketGetHeroBasicTypeInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketGetHeroBasicTypeInfoScRsp.cs @@ -1,22 +1,21 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketGetHeroBasicTypeInfoScRsp : BasePacket { - public class PacketGetHeroBasicTypeInfoScRsp : BasePacket + public PacketGetHeroBasicTypeInfoScRsp(PlayerInstance player) : base(CmdIds.GetHeroBasicTypeInfoScRsp) { - public PacketGetHeroBasicTypeInfoScRsp(PlayerInstance player) : base(CmdIds.GetHeroBasicTypeInfoScRsp) + var proto = new GetHeroBasicTypeInfoScRsp { - var proto = new GetHeroBasicTypeInfoScRsp() - { - Gender = player.Data.CurrentGender, - CurBasicType = (HeroBasicType)player.Data.CurBasicType, - }; + Gender = player.Data.CurrentGender, + CurBasicType = (HeroBasicType)player.Data.CurBasicType + }; - if (player.AvatarManager?.GetHero() != null) - proto.BasicTypeInfoList.AddRange(player.AvatarManager?.GetHero()?.ToHeroProto()); + if (player.AvatarManager?.GetHero() != null) + proto.BasicTypeInfoList.AddRange(player.AvatarManager?.GetHero()?.ToHeroProto()); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketHeroBasicTypeChangedNotify.cs b/GameServer/Server/Packet/Send/Avatar/PacketHeroBasicTypeChangedNotify.cs index 0763d441..05849740 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketHeroBasicTypeChangedNotify.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketHeroBasicTypeChangedNotify.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketHeroBasicTypeChangedNotify : BasePacket { - public class PacketHeroBasicTypeChangedNotify : BasePacket + public PacketHeroBasicTypeChangedNotify(int type) : base(CmdIds.HeroBasicTypeChangedNotify) { - public PacketHeroBasicTypeChangedNotify(int type) : base(CmdIds.HeroBasicTypeChangedNotify) + var proto = new HeroBasicTypeChangedNotify { - var proto = new HeroBasicTypeChangedNotify() - { - CurBasicType = (HeroBasicType)type - }; + CurBasicType = (HeroBasicType)type + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketSetAssistAvatarScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketSetAssistAvatarScRsp.cs index 6831035b..2570455c 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketSetAssistAvatarScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketSetAssistAvatarScRsp.cs @@ -1,17 +1,15 @@ -using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.Proto; +using EggLink.DanhengServer.Proto; using Google.Protobuf.Collections; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar -{ - public class PacketSetAssistAvatarScRsp : BasePacket - { - public PacketSetAssistAvatarScRsp(RepeatedField avatarId) : base(CmdIds.SetAssistAvatarScRsp) - { - var proto = new SetAssistAvatarScRsp(); - proto.AvatarIdList.AddRange(avatarId); +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; - SetData(proto); - } +public class PacketSetAssistAvatarScRsp : BasePacket +{ + public PacketSetAssistAvatarScRsp(RepeatedField avatarId) : base(CmdIds.SetAssistAvatarScRsp) + { + var proto = new SetAssistAvatarScRsp(); + proto.AvatarIdList.AddRange(avatarId); + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketSetDisplayAvatarScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketSetDisplayAvatarScRsp.cs index ff0a31d9..4d364249 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketSetDisplayAvatarScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketSetDisplayAvatarScRsp.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using Google.Protobuf.Collections; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketSetDisplayAvatarScRsp : BasePacket { - public class PacketSetDisplayAvatarScRsp : BasePacket + public PacketSetDisplayAvatarScRsp(RepeatedField avatars) : base(CmdIds.SetDisplayAvatarScRsp) { - public PacketSetDisplayAvatarScRsp(RepeatedField avatars) : base(CmdIds.SetDisplayAvatarScRsp) - { - var proto = new SetDisplayAvatarScRsp(); - proto.DisplayAvatarList.AddRange(avatars); + var proto = new SetDisplayAvatarScRsp(); + proto.DisplayAvatarList.AddRange(avatars); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketTakePromotionRewardScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketTakePromotionRewardScRsp.cs index 864b9246..50619673 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketTakePromotionRewardScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketTakePromotionRewardScRsp.cs @@ -1,31 +1,25 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketTakePromotionRewardScRsp : BasePacket { - public class PacketTakePromotionRewardScRsp : BasePacket + public PacketTakePromotionRewardScRsp() : base(CmdIds.TakePromotionRewardScRsp) { - public PacketTakePromotionRewardScRsp() : base(CmdIds.TakePromotionRewardScRsp) + var itemList = new Item { - var itemList = new Item() - { - ItemId = 101, - Num = 1 - }; + ItemId = 101, + Num = 1 + }; - var rsp = new TakePromotionRewardScRsp + var rsp = new TakePromotionRewardScRsp + { + RewardList = new ItemList { - RewardList = new() - { - ItemList_ = { itemList } - } - }; + ItemList_ = { itemList } + } + }; - SetData(rsp); - } + SetData(rsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Avatar/PacketUnlockSkilltreeScRsp.cs b/GameServer/Server/Packet/Send/Avatar/PacketUnlockSkilltreeScRsp.cs index 3605506c..59e9908a 100644 --- a/GameServer/Server/Packet/Send/Avatar/PacketUnlockSkilltreeScRsp.cs +++ b/GameServer/Server/Packet/Send/Avatar/PacketUnlockSkilltreeScRsp.cs @@ -1,33 +1,27 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Avatar +namespace EggLink.DanhengServer.Server.Packet.Send.Avatar; + +public class PacketUnlockSkilltreeScRsp : BasePacket { - public class PacketUnlockSkilltreeScRsp : BasePacket + public PacketUnlockSkilltreeScRsp() : base(CmdIds.UnlockSkilltreeScRsp) { - public PacketUnlockSkilltreeScRsp() : base(CmdIds.UnlockSkilltreeScRsp) + var proto = new UnlockSkilltreeScRsp { - var proto = new UnlockSkilltreeScRsp - { - Retcode = 1, - }; + Retcode = 1 + }; - SetData(proto); - } - - public PacketUnlockSkilltreeScRsp(uint pointId, uint level) : base(CmdIds.UnlockSkilltreeScRsp) - { - var proto = new UnlockSkilltreeScRsp - { - PointId = pointId, - Level = level, - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketUnlockSkilltreeScRsp(uint pointId, uint level) : base(CmdIds.UnlockSkilltreeScRsp) + { + var proto = new UnlockSkilltreeScRsp + { + PointId = pointId, + Level = level + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Battle/PacketGetCurBattleInfoScRsp.cs b/GameServer/Server/Packet/Send/Battle/PacketGetCurBattleInfoScRsp.cs index d0ee32b2..7fc3c851 100644 --- a/GameServer/Server/Packet/Send/Battle/PacketGetCurBattleInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Battle/PacketGetCurBattleInfoScRsp.cs @@ -1,27 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Battle +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Battle; + +public class PacketGetCurBattleInfoScRsp : BasePacket { - public class PacketGetCurBattleInfoScRsp : BasePacket + public PacketGetCurBattleInfoScRsp() : base(CmdIds.GetCurBattleInfoScRsp) { - public PacketGetCurBattleInfoScRsp() : base(CmdIds.GetCurBattleInfoScRsp) + var proto = new GetCurBattleInfoScRsp { - var proto = new GetCurBattleInfoScRsp() - { - BattleInfo = new() - { - BattleTargetInfo = {} - }, - FFKDJNEAIOG = { }, - }; + BattleInfo = new SceneBattleInfo() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Battle/PacketGetFarmStageGachaInfoScRsp.cs b/GameServer/Server/Packet/Send/Battle/PacketGetFarmStageGachaInfoScRsp.cs index a32b8c20..0d9f7c36 100644 --- a/GameServer/Server/Packet/Send/Battle/PacketGetFarmStageGachaInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Battle/PacketGetFarmStageGachaInfoScRsp.cs @@ -1,29 +1,21 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Battle +namespace EggLink.DanhengServer.Server.Packet.Send.Battle; + +public class PacketGetFarmStageGachaInfoScRsp : BasePacket { - public class PacketGetFarmStageGachaInfoScRsp : BasePacket + public PacketGetFarmStageGachaInfoScRsp(GetFarmStageGachaInfoCsReq req) : base(CmdIds.GetFarmStageGachaInfoScRsp) { - public PacketGetFarmStageGachaInfoScRsp(GetFarmStageGachaInfoCsReq req) : base(CmdIds.GetFarmStageGachaInfoScRsp) - { - var proto = new GetFarmStageGachaInfoScRsp(); + var proto = new GetFarmStageGachaInfoScRsp(); - foreach (var item in req.FarmStageGachaIdList) + foreach (var item in req.FarmStageGachaIdList) + proto.FarmStageGachaInfoList.Add(new FarmStageGachaInfo { - proto.FarmStageGachaInfoList.Add(new FarmStageGachaInfo() - { - GachaId = item, - BeginTime = 0, - EndTime = long.MaxValue - }); - } + GachaId = item, + BeginTime = 0, + EndTime = long.MaxValue + }); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Battle/PacketPVEBattleResultScRsp.cs b/GameServer/Server/Packet/Send/Battle/PacketPVEBattleResultScRsp.cs index f6c48467..df19c9dc 100644 --- a/GameServer/Server/Packet/Send/Battle/PacketPVEBattleResultScRsp.cs +++ b/GameServer/Server/Packet/Send/Battle/PacketPVEBattleResultScRsp.cs @@ -2,38 +2,38 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Battle +namespace EggLink.DanhengServer.Server.Packet.Send.Battle; + +public class PacketPVEBattleResultScRsp : BasePacket { - public class PacketPVEBattleResultScRsp : BasePacket + public PacketPVEBattleResultScRsp() : base(CmdIds.PVEBattleResultScRsp) { - public PacketPVEBattleResultScRsp() : base(CmdIds.PVEBattleResultScRsp) + var proto = new PVEBattleResultScRsp { - var proto = new PVEBattleResultScRsp() - { - Retcode = 1, - }; + Retcode = 1 + }; - SetData(proto); - } - - public PacketPVEBattleResultScRsp(PVEBattleResultCsReq req, PlayerInstance player, BattleInstance battle) : base(CmdIds.PVEBattleResultScRsp) - { - var proto = new PVEBattleResultScRsp() - { - DropData = battle.GetDropItemList(), - ResVersion = req.ResVersion.ToString(), - BinVersion = "", - StageId = req.StageId, - BattleId = req.BattleId, - EndStatus = req.EndStatus, - CheckIdentical = true, - Unk1 = new(), - Unk2 = new(), - Unk3 = new(), - EventId = (uint)battle.EventId, - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketPVEBattleResultScRsp(PVEBattleResultCsReq req, PlayerInstance player, BattleInstance battle) : base( + CmdIds.PVEBattleResultScRsp) + { + var proto = new PVEBattleResultScRsp + { + DropData = battle.GetDropItemList(), + ResVersion = req.ResVersion.ToString(), + BinVersion = "", + StageId = req.StageId, + BattleId = req.BattleId, + EndStatus = req.EndStatus, + CheckIdentical = true, + Unk1 = new ItemList(), + Unk2 = new ItemList(), + Unk3 = new ItemList(), + EventId = (uint)battle.EventId + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Battle/PacketSceneCastSkillScRsp.cs b/GameServer/Server/Packet/Send/Battle/PacketSceneCastSkillScRsp.cs index 437de20c..d0aeda2e 100644 --- a/GameServer/Server/Packet/Send/Battle/PacketSceneCastSkillScRsp.cs +++ b/GameServer/Server/Packet/Send/Battle/PacketSceneCastSkillScRsp.cs @@ -1,34 +1,28 @@ using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Battle +namespace EggLink.DanhengServer.Server.Packet.Send.Battle; + +public class PacketSceneCastSkillScRsp : BasePacket { - public class PacketSceneCastSkillScRsp : BasePacket + public PacketSceneCastSkillScRsp(uint castEntityId) : base(CmdIds.SceneCastSkillScRsp) { - public PacketSceneCastSkillScRsp(uint castEntityId) : base(CmdIds.SceneCastSkillScRsp) + var proto = new SceneCastSkillScRsp { - var proto = new SceneCastSkillScRsp() - { - CastEntityId = castEntityId, - }; + CastEntityId = castEntityId + }; - SetData(proto); - } - - public PacketSceneCastSkillScRsp(uint castEntityId, BattleInstance battle) : base(CmdIds.SceneCastSkillScRsp) - { - var proto = new SceneCastSkillScRsp() - { - CastEntityId = castEntityId, - BattleInfo = battle.ToProto(), - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketSceneCastSkillScRsp(uint castEntityId, BattleInstance battle) : base(CmdIds.SceneCastSkillScRsp) + { + var proto = new SceneCastSkillScRsp + { + CastEntityId = castEntityId, + BattleInfo = battle.ToProto() + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Battle/PacketSceneEnterStageScRsp.cs b/GameServer/Server/Packet/Send/Battle/PacketSceneEnterStageScRsp.cs index ed833fad..66fa81d6 100644 --- a/GameServer/Server/Packet/Send/Battle/PacketSceneEnterStageScRsp.cs +++ b/GameServer/Server/Packet/Send/Battle/PacketSceneEnterStageScRsp.cs @@ -1,33 +1,27 @@ using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Battle +namespace EggLink.DanhengServer.Server.Packet.Send.Battle; + +public class PacketSceneEnterStageScRsp : BasePacket { - public class PacketSceneEnterStageScRsp : BasePacket + public PacketSceneEnterStageScRsp() : base(CmdIds.SceneEnterStageScRsp) { - public PacketSceneEnterStageScRsp() : base(CmdIds.SceneEnterStageScRsp) + var proto = new SceneEnterStageScRsp { - var proto = new SceneEnterStageScRsp() - { - Retcode = 1, - }; + Retcode = 1 + }; - SetData(proto); - } - - public PacketSceneEnterStageScRsp(BattleInstance battleInstance) : base(CmdIds.SceneEnterStageScRsp) - { - var proto = new SceneEnterStageScRsp() - { - BattleInfo = battleInstance.ToProto(), - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketSceneEnterStageScRsp(BattleInstance battleInstance) : base(CmdIds.SceneEnterStageScRsp) + { + var proto = new SceneEnterStageScRsp + { + BattleInfo = battleInstance.ToProto() + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Battle/PacketStartCocoonStageScRsp.cs b/GameServer/Server/Packet/Send/Battle/PacketStartCocoonStageScRsp.cs index d29ca0a9..3c0e1101 100644 --- a/GameServer/Server/Packet/Send/Battle/PacketStartCocoonStageScRsp.cs +++ b/GameServer/Server/Packet/Send/Battle/PacketStartCocoonStageScRsp.cs @@ -1,35 +1,30 @@ using EggLink.DanhengServer.Game.Battle; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Battle +namespace EggLink.DanhengServer.Server.Packet.Send.Battle; + +public class PacketStartCocoonStageScRsp : BasePacket { - public class PacketStartCocoonStageScRsp : BasePacket + public PacketStartCocoonStageScRsp() : base(CmdIds.StartCocoonStageScRsp) { - public PacketStartCocoonStageScRsp() : base(CmdIds.StartCocoonStageScRsp) + var rsp = new StartCocoonStageScRsp { - var rsp = new StartCocoonStageScRsp() - { - Retcode = 1 - }; + Retcode = 1 + }; - SetData(rsp); - } - - public PacketStartCocoonStageScRsp(BattleInstance battle, int cocoonId, int wave) : base(CmdIds.StartCocoonStageScRsp) - { - var rsp = new StartCocoonStageScRsp() - { - CocoonId = (uint)cocoonId, - Wave = (uint)wave, - BattleInfo = battle.ToProto() - }; - - SetData(rsp); - } + SetData(rsp); } -} + + public PacketStartCocoonStageScRsp(BattleInstance battle, int cocoonId, int wave) : base( + CmdIds.StartCocoonStageScRsp) + { + var rsp = new StartCocoonStageScRsp + { + CocoonId = (uint)cocoonId, + Wave = (uint)wave, + BattleInfo = battle.ToProto() + }; + + SetData(rsp); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Challenge/PacketChallengeBossPhaseSettleNotify.cs b/GameServer/Server/Packet/Send/Challenge/PacketChallengeBossPhaseSettleNotify.cs index 659c724e..6a4dc1ab 100644 --- a/GameServer/Server/Packet/Send/Challenge/PacketChallengeBossPhaseSettleNotify.cs +++ b/GameServer/Server/Packet/Send/Challenge/PacketChallengeBossPhaseSettleNotify.cs @@ -1,31 +1,26 @@ using EggLink.DanhengServer.Game.Challenge; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Challenge +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Challenge; + +public class PacketChallengeBossPhaseSettleNotify : BasePacket { - public class PacketChallengeBossPhaseSettleNotify : BasePacket + public PacketChallengeBossPhaseSettleNotify(ChallengeInstance challenge) : base(CmdIds + .ChallengeBossPhaseSettleNotify) { - public PacketChallengeBossPhaseSettleNotify(ChallengeInstance challenge) : base(CmdIds.ChallengeBossPhaseSettleNotify) + var proto = new ChallengeBossPhaseSettleNotify { - var proto = new ChallengeBossPhaseSettleNotify - { - ChallengeId = (uint)challenge.Excel.ID, - IsWin = challenge.IsWin(), - ChallengeScore = (uint)challenge.ScoreStage1, - ScoreTwo = (uint)challenge.ScoreStage2, - Star = (uint)challenge.Stars, - Phase = (uint)challenge.CurrentStage, - IsRemainingAction = true, - HCLKAEHJCDO = true, - }; + ChallengeId = (uint)challenge.Excel.ID, + IsWin = challenge.IsWin(), + ChallengeScore = (uint)challenge.ScoreStage1, + ScoreTwo = (uint)challenge.ScoreStage2, + Star = (uint)challenge.Stars, + Phase = (uint)challenge.CurrentStage, + IsRemainingAction = true, + HCLKAEHJCDO = true + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Challenge/PacketChallengeLineupNotify.cs b/GameServer/Server/Packet/Send/Challenge/PacketChallengeLineupNotify.cs index a2fa1a01..ecad6cc5 100644 --- a/GameServer/Server/Packet/Send/Challenge/PacketChallengeLineupNotify.cs +++ b/GameServer/Server/Packet/Send/Challenge/PacketChallengeLineupNotify.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Challenge +namespace EggLink.DanhengServer.Server.Packet.Send.Challenge; + +public class PacketChallengeLineupNotify : BasePacket { - public class PacketChallengeLineupNotify : BasePacket + public PacketChallengeLineupNotify(ExtraLineupType type) : base(CmdIds.ChallengeLineupNotify) { - public PacketChallengeLineupNotify(ExtraLineupType type) : base(CmdIds.ChallengeLineupNotify) + var proto = new ChallengeLineupNotify { - var proto = new ChallengeLineupNotify() - { - ExtraLineupType = type - }; + ExtraLineupType = type + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Challenge/PacketChallengeSettleNotify.cs b/GameServer/Server/Packet/Send/Challenge/PacketChallengeSettleNotify.cs index 293b5397..eaa71251 100644 --- a/GameServer/Server/Packet/Send/Challenge/PacketChallengeSettleNotify.cs +++ b/GameServer/Server/Packet/Send/Challenge/PacketChallengeSettleNotify.cs @@ -1,23 +1,22 @@ using EggLink.DanhengServer.Game.Challenge; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Challenge -{ - public class PacketChallengeSettleNotify : BasePacket - { - public PacketChallengeSettleNotify(ChallengeInstance challenge) : base(CmdIds.ChallengeSettleNotify) - { - var proto = new ChallengeSettleNotify - { - ChallengeId = (uint)challenge.Excel.ID, - IsWin = challenge.IsWin(), - ChallengeScore = (uint)challenge.ScoreStage1, - ScoreTwo = (uint)challenge.ScoreStage2, - Star = (uint)challenge.Stars, - Reward = new(), - }; +namespace EggLink.DanhengServer.Server.Packet.Send.Challenge; - SetData(proto); - } +public class PacketChallengeSettleNotify : BasePacket +{ + public PacketChallengeSettleNotify(ChallengeInstance challenge) : base(CmdIds.ChallengeSettleNotify) + { + var proto = new ChallengeSettleNotify + { + ChallengeId = (uint)challenge.Excel.ID, + IsWin = challenge.IsWin(), + ChallengeScore = (uint)challenge.ScoreStage1, + ScoreTwo = (uint)challenge.ScoreStage2, + Star = (uint)challenge.Stars, + Reward = new ItemList() + }; + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Challenge/PacketGetChallengeScRsp.cs b/GameServer/Server/Packet/Send/Challenge/PacketGetChallengeScRsp.cs index a5f0e66d..0edab584 100644 --- a/GameServer/Server/Packet/Send/Challenge/PacketGetChallengeScRsp.cs +++ b/GameServer/Server/Packet/Send/Challenge/PacketGetChallengeScRsp.cs @@ -2,39 +2,34 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Battle +namespace EggLink.DanhengServer.Server.Packet.Send.Battle; + +public class PacketGetChallengeScRsp : BasePacket { - public class PacketGetChallengeScRsp : BasePacket + public PacketGetChallengeScRsp(PlayerInstance player) : base(CmdIds.GetChallengeScRsp) { - public PacketGetChallengeScRsp(PlayerInstance player) : base(CmdIds.GetChallengeScRsp) + var proto = new GetChallengeScRsp { - var proto = new GetChallengeScRsp() - { - Retcode = 0, - }; + Retcode = 0 + }; - foreach (var challengeExcel in GameData.ChallengeConfigData.Values) + foreach (var challengeExcel in GameData.ChallengeConfigData.Values) + if (player.ChallengeManager?.ChallengeData.History.TryGetValue(challengeExcel.ID, out var value) == true) { - if (player.ChallengeManager?.ChallengeData.History.TryGetValue(challengeExcel.ID, out Database.Challenge.ChallengeHistoryData? value) == true) + var history = value; + proto.ChallengeList.Add(history.ToProto()); + } + else + { + proto.ChallengeList.Add(new Proto.Challenge { - var history = value; - proto.ChallengeList.Add(history.ToProto()); - } - else - { - proto.ChallengeList.Add(new Proto.Challenge() - { - ChallengeId = (uint)challengeExcel.ID, - }); - } + ChallengeId = (uint)challengeExcel.ID + }); } - foreach (var reward in player.ChallengeManager?.ChallengeData?.TakenRewards.Values.ToList() ?? []) - { - proto.ChallengeGroupList.Add(reward.ToProto()); - } + foreach (var reward in player.ChallengeManager?.ChallengeData?.TakenRewards.Values.ToList() ?? []) + proto.ChallengeGroupList.Add(reward.ToProto()); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Challenge/PacketGetCurChallengeScRsp.cs b/GameServer/Server/Packet/Send/Challenge/PacketGetCurChallengeScRsp.cs index 67da56f7..135f7f30 100644 --- a/GameServer/Server/Packet/Send/Challenge/PacketGetCurChallengeScRsp.cs +++ b/GameServer/Server/Packet/Send/Challenge/PacketGetCurChallengeScRsp.cs @@ -1,26 +1,28 @@ -using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Game.Player; +using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Battle +namespace EggLink.DanhengServer.Server.Packet.Send.Battle; + +public class PacketGetCurChallengeScRsp : BasePacket { - public class PacketGetCurChallengeScRsp : BasePacket + public PacketGetCurChallengeScRsp(PlayerInstance player) : base(CmdIds.GetCurChallengeScRsp) { - public PacketGetCurChallengeScRsp(PlayerInstance player) : base(CmdIds.GetCurChallengeScRsp) + var proto = new GetCurChallengeScRsp(); + + if (player.ChallengeManager!.ChallengeInstance != null) { - var proto = new GetCurChallengeScRsp() { }; - - if (player.ChallengeManager!.ChallengeInstance != null) + proto.CurChallenge = player.ChallengeManager.ChallengeInstance.ToProto(); + Task.Run(async () => { - proto.CurChallenge = player.ChallengeManager.ChallengeInstance.ToProto(); - player.LineupManager!.SetCurLineup(player.ChallengeManager.ChallengeInstance.CurrentExtraLineup + 10); - } - else - { - proto.Retcode = 0; - } - - SetData(proto); + await player.LineupManager!.SetCurLineup(player.ChallengeManager.ChallengeInstance + .CurrentExtraLineup + 10); + }).Wait(); } + else + { + proto.Retcode = 0; + } + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Challenge/PacketStartChallengeScRsp.cs b/GameServer/Server/Packet/Send/Challenge/PacketStartChallengeScRsp.cs index 221a75d5..0fc8aafd 100644 --- a/GameServer/Server/Packet/Send/Challenge/PacketStartChallengeScRsp.cs +++ b/GameServer/Server/Packet/Send/Challenge/PacketStartChallengeScRsp.cs @@ -1,39 +1,38 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Challenge +namespace EggLink.DanhengServer.Server.Packet.Send.Challenge; + +public class PacketStartChallengeScRsp : BasePacket { - public class PacketStartChallengeScRsp : BasePacket + public PacketStartChallengeScRsp(uint Retcode) : base(CmdIds.StartChallengeScRsp) { - public PacketStartChallengeScRsp(uint Retcode) : base(CmdIds.StartChallengeScRsp) + var proto = new StartChallengeScRsp { - StartChallengeScRsp proto = new StartChallengeScRsp - { - Retcode = Retcode, - }; + Retcode = Retcode + }; - SetData(proto); - } - - public PacketStartChallengeScRsp(PlayerInstance player) : base(CmdIds.StartChallengeScRsp) - { - StartChallengeScRsp proto = new() - { - Scene = player.SceneInstance!.ToProto() - }; - - if (player.ChallengeManager!.ChallengeInstance != null) - { - proto.CurChallenge = player.ChallengeManager.ChallengeInstance.ToProto(); - proto.LineupList.Add(player.LineupManager!.GetExtraLineup(ExtraLineupType.LineupChallenge)!.ToProto()); - proto.LineupList.Add(player.LineupManager!.GetExtraLineup(ExtraLineupType.LineupChallenge2)!.ToProto()); - } - else - { - proto.Retcode = 1; - } - - SetData(proto); - } + SetData(proto); } -} + + public PacketStartChallengeScRsp(PlayerInstance player) : base(CmdIds.StartChallengeScRsp) + { + StartChallengeScRsp proto = new() + { + Scene = player.SceneInstance!.ToProto() + }; + + if (player.ChallengeManager!.ChallengeInstance != null) + { + proto.CurChallenge = player.ChallengeManager.ChallengeInstance.ToProto(); + proto.LineupList.Add(player.LineupManager!.GetExtraLineup(ExtraLineupType.LineupChallenge)!.ToProto()); + proto.LineupList.Add(player.LineupManager!.GetExtraLineup(ExtraLineupType.LineupChallenge2)!.ToProto()); + } + else + { + proto.Retcode = 1; + } + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Challenge/PacketTakeChallengeRewardScRsp.cs b/GameServer/Server/Packet/Send/Challenge/PacketTakeChallengeRewardScRsp.cs index 2f5026d9..4793a8eb 100644 --- a/GameServer/Server/Packet/Send/Challenge/PacketTakeChallengeRewardScRsp.cs +++ b/GameServer/Server/Packet/Send/Challenge/PacketTakeChallengeRewardScRsp.cs @@ -1,32 +1,25 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Challenge +namespace EggLink.DanhengServer.Server.Packet.Send.Challenge; + +public class PacketTakeChallengeRewardScRsp : BasePacket { - public class PacketTakeChallengeRewardScRsp : BasePacket + public PacketTakeChallengeRewardScRsp(int groupId, List? rewardInfos) : base( + CmdIds.TakeChallengeRewardScRsp) { - public PacketTakeChallengeRewardScRsp(int groupId, List? rewardInfos) : base(CmdIds.TakeChallengeRewardScRsp) + var proto = new TakeChallengeRewardScRsp(); + + if (rewardInfos != null) { - var proto = new TakeChallengeRewardScRsp(); + proto.GroupId = (uint)groupId; - if (rewardInfos != null) - { - proto.GroupId = (uint)groupId; - - foreach (var rewardInfo in rewardInfos) - { - proto.TakenRewardList.Add(rewardInfo); - } - } else - { - proto.Retcode = 1; - } - - SetData(proto); + foreach (var rewardInfo in rewardInfos) proto.TakenRewardList.Add(rewardInfo); } + else + { + proto.Retcode = 1; + } + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueCellUpdateNotify.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueCellUpdateNotify.cs index fd751bd8..3b1f83a1 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueCellUpdateNotify.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueCellUpdateNotify.cs @@ -1,25 +1,20 @@ using EggLink.DanhengServer.Game.ChessRogue.Cell; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueCellUpdateNotify : BasePacket { - public class PacketChessRogueCellUpdateNotify : BasePacket + public PacketChessRogueCellUpdateNotify(ChessRogueCellInstance cell, int boardId) : base( + CmdIds.ChessRogueCellUpdateNotify) { - public PacketChessRogueCellUpdateNotify(ChessRogueCellInstance cell, int boardId) : base(CmdIds.ChessRogueCellUpdateNotify) + var proto = new ChessRogueCellUpdateNotify { - var proto = new ChessRogueCellUpdateNotify() - { - BoardId = (uint)boardId, - }; + BoardId = (uint)boardId + }; - proto.CellList.Add(cell.ToProto()); + proto.CellList.Add(cell.ToProto()); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueCheatRollScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueCheatRollScRsp.cs index fb1e78e3..3b28e569 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueCheatRollScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueCheatRollScRsp.cs @@ -1,24 +1,19 @@ using EggLink.DanhengServer.Game.ChessRogue.Dice; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueCheatRollScRsp : BasePacket { - public class PacketChessRogueCheatRollScRsp : BasePacket + public PacketChessRogueCheatRollScRsp(ChessRogueDiceInstance dice, int surfaceId) : base( + CmdIds.ChessRogueCheatRollScRsp) { - public PacketChessRogueCheatRollScRsp(ChessRogueDiceInstance dice, int surfaceId) : base(CmdIds.ChessRogueCheatRollScRsp) + var proto = new ChessRogueCheatRollScRsp { - var proto = new ChessRogueCheatRollScRsp() - { - RogueDiceInfo = dice.ToProto(), - SurfaceId = (uint)surfaceId, - }; + RogueDiceInfo = dice.ToProto(), + SurfaceId = (uint)surfaceId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueConfirmRollScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueConfirmRollScRsp.cs index d38aaaa9..f664996d 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueConfirmRollScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueConfirmRollScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Game.ChessRogue.Dice; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueConfirmRollScRsp : BasePacket { - public class PacketChessRogueConfirmRollScRsp : BasePacket + public PacketChessRogueConfirmRollScRsp(ChessRogueDiceInstance dice) : base(CmdIds.ChessRogueConfirmRollScRsp) { - public PacketChessRogueConfirmRollScRsp(ChessRogueDiceInstance dice) : base(CmdIds.ChessRogueConfirmRollScRsp) + var proto = new ChessRogueConfirmRollScRsp { - var proto = new ChessRogueConfirmRollScRsp() - { - RogueDiceInfo = dice.ToProto(), - }; + RogueDiceInfo = dice.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueEnterCellScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueEnterCellScRsp.cs index 15523478..194057b0 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueEnterCellScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueEnterCellScRsp.cs @@ -1,26 +1,20 @@ using EggLink.DanhengServer.Game.ChessRogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueEnterCellScRsp : BasePacket { - public class PacketChessRogueEnterCellScRsp : BasePacket + public PacketChessRogueEnterCellScRsp(uint cellId, ChessRogueInstance rogue) : base(CmdIds.ChessRogueEnterCellScRsp) { - public PacketChessRogueEnterCellScRsp(uint cellId, ChessRogueInstance rogue) : base(CmdIds.ChessRogueEnterCellScRsp) + var proto = new ChessRogueEnterCellScRsp { - var proto = new ChessRogueEnterCellScRsp() - { - CellId = cellId, - Info = rogue.ToProto(), - PlayerInfo = rogue.ToPlayerProto(), - RogueCurrentInfo = rogue.ToRogueGameInfo(), - }; + CellId = cellId, + Info = rogue.ToProto(), + PlayerInfo = rogue.ToPlayerProto(), + RogueCurrentInfo = rogue.ToRogueGameInfo() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueEnterNextLayerScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueEnterNextLayerScRsp.cs index 547fd250..e9ae8858 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueEnterNextLayerScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueEnterNextLayerScRsp.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Game.ChessRogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueEnterNextLayerScRsp : BasePacket { - public class PacketChessRogueEnterNextLayerScRsp : BasePacket + public PacketChessRogueEnterNextLayerScRsp(ChessRogueInstance rogue) : base(CmdIds.ChessRogueEnterNextLayerScRsp) { - public PacketChessRogueEnterNextLayerScRsp(ChessRogueInstance rogue) : base(CmdIds.ChessRogueEnterNextLayerScRsp) + var proto = new ChessRogueEnterNextLayerScRsp { - var proto = new ChessRogueEnterNextLayerScRsp() - { - PlayerInfo = rogue.ToPlayerProto(), - RogueCurrentInfo = rogue.ToRogueGameInfo(), - RogueInfo = rogue.ToProto(), - }; + PlayerInfo = rogue.ToPlayerProto(), + RogueCurrentInfo = rogue.ToRogueGameInfo(), + RogueInfo = rogue.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueLayerAccountInfoNotify.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueLayerAccountInfoNotify.cs index fdfc8d31..a2c2ae1c 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueLayerAccountInfoNotify.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueLayerAccountInfoNotify.cs @@ -1,24 +1,19 @@ using EggLink.DanhengServer.Game.ChessRogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueLayerAccountInfoNotify : BasePacket { - public class PacketChessRogueLayerAccountInfoNotify : BasePacket - { - public PacketChessRogueLayerAccountInfoNotify(ChessRogueInstance rogue) : base(CmdIds.ChessRogueLayerAccountInfoNotify) + public PacketChessRogueLayerAccountInfoNotify(ChessRogueInstance rogue) : base(CmdIds + .ChessRogueLayerAccountInfoNotify) + { + var proto = new ChessRogueLayerAccountInfoNotify { - var proto = new ChessRogueLayerAccountInfoNotify() - { - FinishInfo = rogue.ToFinishInfo(), - //LayerId = (uint)rogue.CurLayer, - }; + FinishInfo = rogue.ToFinishInfo() + //LayerId = (uint)rogue.CurLayer, + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueLeaveScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueLeaveScRsp.cs index eec5da1f..c381fa82 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueLeaveScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueLeaveScRsp.cs @@ -1,26 +1,20 @@ using EggLink.DanhengServer.Game.ChessRogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueLeaveScRsp : BasePacket { - public class PacketChessRogueLeaveScRsp : BasePacket + public PacketChessRogueLeaveScRsp(ChessRogueInstance instance) : base(CmdIds.ChessRogueLeaveScRsp) { - public PacketChessRogueLeaveScRsp(ChessRogueInstance instance) : base(CmdIds.ChessRogueLeaveScRsp) + var proto = new ChessRogueLeaveScRsp { - var proto = new ChessRogueLeaveScRsp() - { - PlayerInfo = instance.ToPlayerProto(), - QueryInfo = instance.Player.ChessRogueManager!.ToQueryInfo(), - RogueAeonInfo = instance.Player.ChessRogueManager!.ToRogueAeonInfo(), - RogueGetInfo = instance.Player.ChessRogueManager!.ToGetInfo(), - }; + PlayerInfo = instance.ToPlayerProto(), + QueryInfo = instance.Player.ChessRogueManager!.ToQueryInfo(), + RogueAeonInfo = instance.Player.ChessRogueManager!.ToRogueAeonInfo(), + RogueGetInfo = instance.Player.ChessRogueManager!.ToGetInfo() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueNousEditDiceScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueNousEditDiceScRsp.cs index eb858dac..4a6eaf72 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueNousEditDiceScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueNousEditDiceScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Database.ChessRogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueNousEditDiceScRsp : BasePacket { - public class PacketChessRogueNousEditDiceScRsp : BasePacket + public PacketChessRogueNousEditDiceScRsp(ChessRogueNousDiceData diceData) : base(CmdIds.ChessRogueNousEditDiceScRsp) { - public PacketChessRogueNousEditDiceScRsp(ChessRogueNousDiceData diceData) : base(CmdIds.ChessRogueNousEditDiceScRsp) + var proto = new ChessRogueNousEditDiceScRsp { - var proto = new ChessRogueNousEditDiceScRsp() - { - DiceInfo = diceData.ToProto(), - }; + DiceInfo = diceData.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueQueryScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueQueryScRsp.cs index 880ce891..f2d827f4 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueQueryScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueQueryScRsp.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueQueryScRsp : BasePacket { - public class PacketChessRogueQueryScRsp : BasePacket + public PacketChessRogueQueryScRsp(PlayerInstance player) : base(CmdIds.ChessRogueQueryScRsp) { - public PacketChessRogueQueryScRsp(PlayerInstance player) : base(CmdIds.ChessRogueQueryScRsp) + var proto = new ChessRogueQueryScRsp { - var proto = new ChessRogueQueryScRsp() - { - RogueGetInfo = player.ChessRogueManager!.ToGetInfo(), - Info = player.ChessRogueManager!.ToCurrentInfo(), - QueryInfo = player.ChessRogueManager!.ToQueryInfo(), - }; + RogueGetInfo = player.ChessRogueManager!.ToGetInfo(), + Info = player.ChessRogueManager!.ToCurrentInfo(), + QueryInfo = player.ChessRogueManager!.ToQueryInfo() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueQuitScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueQuitScRsp.cs index f980dc68..f91b6168 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueQuitScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueQuitScRsp.cs @@ -1,29 +1,23 @@ using EggLink.DanhengServer.Game.ChessRogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueQuitScRsp : BasePacket { - public class PacketChessRogueQuitScRsp : BasePacket + public PacketChessRogueQuitScRsp(ChessRogueInstance instance) : base(CmdIds.ChessRogueQuitScRsp) { - public PacketChessRogueQuitScRsp(ChessRogueInstance instance) : base(CmdIds.ChessRogueQuitScRsp) + var proto = new ChessRogueQuitScRsp { - var proto = new ChessRogueQuitScRsp() - { - FinishInfo = instance.ToFinishInfo(), - Info = instance.ToProto(), - LevelInfo = instance.ToLevelInfo(), - PlayerInfo = instance.ToPlayerProto(), - QueryInfo = instance.Player.ChessRogueManager!.ToQueryInfo(), - RogueGetInfo = instance.Player.ChessRogueManager!.ToGetInfo(), - RogueAeonInfo = instance.Player.ChessRogueManager!.ToRogueAeonInfo(), - }; + FinishInfo = instance.ToFinishInfo(), + Info = instance.ToProto(), + LevelInfo = instance.ToLevelInfo(), + PlayerInfo = instance.ToPlayerProto(), + QueryInfo = instance.Player.ChessRogueManager!.ToQueryInfo(), + RogueGetInfo = instance.Player.ChessRogueManager!.ToGetInfo(), + RogueAeonInfo = instance.Player.ChessRogueManager!.ToRogueAeonInfo() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueReRollDiceScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueReRollDiceScRsp.cs index 20bcd308..7bb29a66 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueReRollDiceScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueReRollDiceScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Game.ChessRogue.Dice; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueReRollDiceScRsp : BasePacket { - public class PacketChessRogueReRollDiceScRsp : BasePacket + public PacketChessRogueReRollDiceScRsp(ChessRogueDiceInstance dice) : base(CmdIds.ChessRogueReRollDiceScRsp) { - public PacketChessRogueReRollDiceScRsp(ChessRogueDiceInstance dice) : base(CmdIds.ChessRogueReRollDiceScRsp) + var proto = new ChessRogueReRollDiceScRsp { - var proto = new ChessRogueReRollDiceScRsp() - { - RogueDiceInfo = dice.ToProto() - }; + RogueDiceInfo = dice.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueRollDiceScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueRollDiceScRsp.cs index de5beaca..2b529127 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueRollDiceScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueRollDiceScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Game.ChessRogue.Dice; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueRollDiceScRsp : BasePacket { - public class PacketChessRogueRollDiceScRsp : BasePacket + public PacketChessRogueRollDiceScRsp(ChessRogueDiceInstance dice) : base(CmdIds.ChessRogueRollDiceScRsp) { - public PacketChessRogueRollDiceScRsp(ChessRogueDiceInstance dice) : base(CmdIds.ChessRogueRollDiceScRsp) + var proto = new ChessRogueRollDiceScRsp { - var proto = new ChessRogueRollDiceScRsp() - { - RogueDiceInfo = dice.ToProto() - }; + RogueDiceInfo = dice.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueSelectCellScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueSelectCellScRsp.cs index 910eda0e..bced8ed6 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueSelectCellScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueSelectCellScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueSelectCellScRsp : BasePacket { - public class PacketChessRogueSelectCellScRsp : BasePacket + public PacketChessRogueSelectCellScRsp(int cellId) : base(CmdIds.ChessRogueSelectCellScRsp) { - public PacketChessRogueSelectCellScRsp(int cellId) : base(CmdIds.ChessRogueSelectCellScRsp) + var proto = new ChessRogueSelectCellScRsp { - var proto = new ChessRogueSelectCellScRsp() - { - CellId = (uint)cellId, - }; + CellId = (uint)cellId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueStartScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueStartScRsp.cs index 292030cc..2af63a8d 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueStartScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueStartScRsp.cs @@ -1,20 +1,19 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue -{ - public class PacketChessRogueStartScRsp : BasePacket - { - public PacketChessRogueStartScRsp(PlayerInstance player) : base(CmdIds.ChessRogueStartScRsp) - { - var proto = new ChessRogueStartScRsp() - { - PlayerInfo = player.ChessRogueManager!.RogueInstance!.ToPlayerProto(), - Info = player.ChessRogueManager!.RogueInstance!.ToProto(), - RogueCurrentInfo = player.ChessRogueManager!.RogueInstance!.ToRogueGameInfo() - }; +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; - SetData(proto); - } +public class PacketChessRogueStartScRsp : BasePacket +{ + public PacketChessRogueStartScRsp(PlayerInstance player) : base(CmdIds.ChessRogueStartScRsp) + { + var proto = new ChessRogueStartScRsp + { + PlayerInfo = player.ChessRogueManager!.RogueInstance!.ToPlayerProto(), + Info = player.ChessRogueManager!.RogueInstance!.ToProto(), + RogueCurrentInfo = player.ChessRogueManager!.RogueInstance!.ToRogueGameInfo() + }; + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateActionPointScNotify.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateActionPointScNotify.cs index 0a5dfead..c429d251 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateActionPointScNotify.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateActionPointScNotify.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueUpdateActionPointScNotify : BasePacket { - public class PacketChessRogueUpdateActionPointScNotify : BasePacket + public PacketChessRogueUpdateActionPointScNotify(int actionPoint) : base(CmdIds.ChessRogueUpdateActionPointScNotify) { - public PacketChessRogueUpdateActionPointScNotify(int actionPoint) : base(CmdIds.ChessRogueUpdateActionPointScNotify) + var proto = new ChessRogueUpdateActionPointScNotify { - var proto = new ChessRogueUpdateActionPointScNotify() - { - ActionPoint = actionPoint, - }; + ActionPoint = actionPoint + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateAllowedSelectCellScNotify.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateAllowedSelectCellScNotify.cs index 0de51419..f1a7bf5a 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateAllowedSelectCellScNotify.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateAllowedSelectCellScNotify.cs @@ -1,27 +1,19 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueUpdateAllowedSelectCellScNotify : BasePacket { - public class PacketChessRogueUpdateAllowedSelectCellScNotify : BasePacket + public PacketChessRogueUpdateAllowedSelectCellScNotify(int boardId, List allowed) : base( + CmdIds.ChessRogueUpdateAllowedSelectCellScNotify) { - public PacketChessRogueUpdateAllowedSelectCellScNotify(int boardId, List allowed) : base(CmdIds.ChessRogueUpdateAllowedSelectCellScNotify) + var proto = new ChessRogueUpdateAllowedSelectCellScNotify { - var proto = new ChessRogueUpdateAllowedSelectCellScNotify() - { - BoardId = (uint)boardId, - }; + BoardId = (uint)boardId + }; - foreach (var cell in allowed) - { - proto.AllowedSelectCellIdList.Add((uint)cell); - } + foreach (var cell in allowed) proto.AllowedSelectCellIdList.Add((uint)cell); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateDiceInfoScNotify.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateDiceInfoScNotify.cs index e96e21b9..60cef848 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateDiceInfoScNotify.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateDiceInfoScNotify.cs @@ -1,23 +1,18 @@ using EggLink.DanhengServer.Game.ChessRogue.Dice; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueUpdateDiceInfoScNotify : BasePacket { - public class PacketChessRogueUpdateDiceInfoScNotify : BasePacket + public PacketChessRogueUpdateDiceInfoScNotify(ChessRogueDiceInstance dice) : base( + CmdIds.ChessRogueUpdateDiceInfoScNotify) { - public PacketChessRogueUpdateDiceInfoScNotify(ChessRogueDiceInstance dice) : base(CmdIds.ChessRogueUpdateDiceInfoScNotify) + var proto = new ChessRogueUpdateDiceInfoScNotify { - var proto = new ChessRogueUpdateDiceInfoScNotify() - { - RogueDiceInfo = dice.ToProto(), - }; + RogueDiceInfo = dice.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateLevelBaseInfoScNotify.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateLevelBaseInfoScNotify.cs index 2741b0d0..effa3136 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateLevelBaseInfoScNotify.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketChessRogueUpdateLevelBaseInfoScNotify.cs @@ -1,22 +1,17 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketChessRogueUpdateLevelBaseInfoScNotify : BasePacket { - public class PacketChessRogueUpdateLevelBaseInfoScNotify : BasePacket + public PacketChessRogueUpdateLevelBaseInfoScNotify(ChessRogueLevelStatusType status) : base( + CmdIds.ChessRogueUpdateLevelBaseInfoScNotify) { - public PacketChessRogueUpdateLevelBaseInfoScNotify(ChessRogueLevelStatusType status) : base(CmdIds.ChessRogueUpdateLevelBaseInfoScNotify) + var proto = new ChessRogueUpdateLevelBaseInfoScNotify { - var proto = new ChessRogueUpdateLevelBaseInfoScNotify() - { - LevelStatus = status - }; + LevelStatus = status + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketEnhanceChessRogueBuffScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketEnhanceChessRogueBuffScRsp.cs index 016ce1f7..26dac7bb 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketEnhanceChessRogueBuffScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketEnhanceChessRogueBuffScRsp.cs @@ -1,29 +1,24 @@ using EggLink.DanhengServer.Game.ChessRogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketEnhanceChessRogueBuffScRsp : BasePacket { - public class PacketEnhanceChessRogueBuffScRsp : BasePacket + public PacketEnhanceChessRogueBuffScRsp(ChessRogueInstance rogue, uint buffId) : base( + CmdIds.EnhanceChessRogueBuffScRsp) { - public PacketEnhanceChessRogueBuffScRsp(ChessRogueInstance rogue, uint buffId) : base(CmdIds.EnhanceChessRogueBuffScRsp) + var proto = new EnhanceChessRogueBuffScRsp { - var proto = new EnhanceChessRogueBuffScRsp() + IsSuccess = true, + RogueBuff = new RogueCommonBuff { - IsSuccess = true, - RogueBuff = new() - { - BuffId = buffId, - BuffLevel = 2 - }, - BuffEnhanceInfo = rogue.ToChessEnhanceInfo() - }; + BuffId = buffId, + BuffLevel = 2 + }, + BuffEnhanceInfo = rogue.ToChessEnhanceInfo() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketGetChessRogueBuffEnhanceInfoScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketGetChessRogueBuffEnhanceInfoScRsp.cs index f347fdfa..9d1fcd98 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketGetChessRogueBuffEnhanceInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketGetChessRogueBuffEnhanceInfoScRsp.cs @@ -1,27 +1,23 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketGetChessRogueBuffEnhanceInfoScRsp : BasePacket { - public class PacketGetChessRogueBuffEnhanceInfoScRsp : BasePacket + public PacketGetChessRogueBuffEnhanceInfoScRsp(PlayerInstance player) : base(CmdIds + .GetChessRogueBuffEnhanceInfoScRsp) { - public PacketGetChessRogueBuffEnhanceInfoScRsp(PlayerInstance player) : base(CmdIds.GetChessRogueBuffEnhanceInfoScRsp) + var proto = new GetChessRogueBuffEnhanceInfoScRsp(); + if (player.ChessRogueManager!.RogueInstance == null) { - var proto = new GetChessRogueBuffEnhanceInfoScRsp(); - if (player.ChessRogueManager!.RogueInstance == null) - { - proto.Retcode = 1; - SetData(proto); - return; - } - proto.BuffEnhanceInfo = player.ChessRogueManager.RogueInstance!.ToChessEnhanceInfo(); - + proto.Retcode = 1; SetData(proto); + return; } + + proto.BuffEnhanceInfo = player.ChessRogueManager.RogueInstance!.ToChessEnhanceInfo(); + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/ChessRogue/PacketGetChessRogueNousStoryInfoScRsp.cs b/GameServer/Server/Packet/Send/ChessRogue/PacketGetChessRogueNousStoryInfoScRsp.cs index 5e20ff25..501a0bc9 100644 --- a/GameServer/Server/Packet/Send/ChessRogue/PacketGetChessRogueNousStoryInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/ChessRogue/PacketGetChessRogueNousStoryInfoScRsp.cs @@ -1,37 +1,27 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue +namespace EggLink.DanhengServer.Server.Packet.Send.ChessRogue; + +public class PacketGetChessRogueNousStoryInfoScRsp : BasePacket { - public class PacketGetChessRogueNousStoryInfoScRsp : BasePacket + public PacketGetChessRogueNousStoryInfoScRsp() : base(CmdIds.GetChessRogueNousStoryInfoScRsp) { - public PacketGetChessRogueNousStoryInfoScRsp() : base(CmdIds.GetChessRogueNousStoryInfoScRsp) - { - var proto = new GetChessRogueNousStoryInfoScRsp(); + var proto = new GetChessRogueNousStoryInfoScRsp(); - foreach (var item in GameData.RogueNousMainStoryData.Values) + foreach (var item in GameData.RogueNousMainStoryData.Values) + proto.ChessRogueMainStoryInfo.Add(new ChessRogueNousMainStoryInfo { - proto.ChessRogueMainStoryInfo.Add(new ChessRogueNousMainStoryInfo - { - ChessRogueMainStoryId = (uint)item.StoryID, - Status = ChessRogueNousMainStoryStatus.Finish - }); - } + ChessRogueMainStoryId = (uint)item.StoryID, + Status = ChessRogueNousMainStoryStatus.Finish + }); - foreach (var item in GameData.RogueNousSubStoryData.Values) + foreach (var item in GameData.RogueNousSubStoryData.Values) + proto.ChessRogueSubStoryInfo.Add(new ChessRogueNousSubStoryInfo { - proto.ChessRogueSubStoryInfo.Add(new ChessRogueNousSubStoryInfo - { - ChessRogueSubStoryId = (uint)item.StoryID, - }); - } + ChessRogueSubStoryId = (uint)item.StoryID + }); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketApplyFriendScRsp.cs b/GameServer/Server/Packet/Send/Friend/PacketApplyFriendScRsp.cs index d9d34353..60dbbde7 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketApplyFriendScRsp.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketApplyFriendScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Friend +namespace EggLink.DanhengServer.Server.Packet.Send.Friend; + +public class PacketApplyFriendScRsp : BasePacket { - public class PacketApplyFriendScRsp : BasePacket + public PacketApplyFriendScRsp(uint uid) : base(CmdIds.ApplyFriendScRsp) { - public PacketApplyFriendScRsp(uint uid) : base(CmdIds.ApplyFriendScRsp) + var proto = new ApplyFriendScRsp { - var proto = new ApplyFriendScRsp - { - Uid = uid, - }; + Uid = uid + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketGetFriendApplyListInfoCsReq.cs b/GameServer/Server/Packet/Send/Friend/PacketGetFriendApplyListInfoCsReq.cs index ff761a5c..13c1b8a3 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketGetFriendApplyListInfoCsReq.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketGetFriendApplyListInfoCsReq.cs @@ -1,18 +1,9 @@ -using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Send.Gacha; -namespace EggLink.DanhengServer.Server.Packet.Send.Gacha +public class PacketGetFriendApplyListInfoCsReq : BasePacket { - public class PacketGetFriendApplyListInfoCsReq : BasePacket + public PacketGetFriendApplyListInfoCsReq(Connection connection) : base(CmdIds.GetFriendApplyListInfoScRsp) { - public PacketGetFriendApplyListInfoCsReq(Connection connection) : base(CmdIds.GetFriendApplyListInfoScRsp) - { - - SetData(connection.Player!.FriendManager!.ToApplyListProto()); - } + SetData(connection.Player!.FriendManager!.ToApplyListProto()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketGetFriendListInfoScRsp.cs b/GameServer/Server/Packet/Send/Friend/PacketGetFriendListInfoScRsp.cs index 64669283..688096fd 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketGetFriendListInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketGetFriendListInfoScRsp.cs @@ -1,17 +1,9 @@ -using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Send.Gacha; -namespace EggLink.DanhengServer.Server.Packet.Send.Gacha +public class PacketGetFriendListInfoScRsp : BasePacket { - public class PacketGetFriendListInfoScRsp : BasePacket + public PacketGetFriendListInfoScRsp(Connection connection) : base(CmdIds.GetFriendListInfoScRsp) { - public PacketGetFriendListInfoScRsp(Connection connection) : base(CmdIds.GetFriendListInfoScRsp) - { - SetData(connection.Player!.FriendManager!.ToProto()); - } + SetData(connection.Player!.FriendManager!.ToProto()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketGetPlayerDetailInfoScRsp.cs b/GameServer/Server/Packet/Send/Friend/PacketGetPlayerDetailInfoScRsp.cs index 9f9a810a..7a9c2c26 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketGetPlayerDetailInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketGetPlayerDetailInfoScRsp.cs @@ -1,33 +1,27 @@ using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Friend +namespace EggLink.DanhengServer.Server.Packet.Send.Friend; + +public class PacketGetPlayerDetailInfoScRsp : BasePacket { - public class PacketGetPlayerDetailInfoScRsp : BasePacket + public PacketGetPlayerDetailInfoScRsp(PlayerData data) : base(CmdIds.GetPlayerDetailInfoScRsp) { - public PacketGetPlayerDetailInfoScRsp(PlayerData data) : base(CmdIds.GetPlayerDetailInfoScRsp) + var proto = new GetPlayerDetailInfoScRsp { - var proto = new GetPlayerDetailInfoScRsp() - { - DetailInfo = data.ToDetailProto(), - }; + DetailInfo = data.ToDetailProto() + }; - SetData(proto); - } - - public PacketGetPlayerDetailInfoScRsp() : base(CmdIds.GetPlayerDetailInfoScRsp) - { - var proto = new GetPlayerDetailInfoScRsp() - { - Retcode = 3612, - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketGetPlayerDetailInfoScRsp() : base(CmdIds.GetPlayerDetailInfoScRsp) + { + var proto = new GetPlayerDetailInfoScRsp + { + Retcode = 3612 + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketGetPrivateChatHistoryScRsp.cs b/GameServer/Server/Packet/Send/Friend/PacketGetPrivateChatHistoryScRsp.cs index 6805e5b9..34b49b15 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketGetPrivateChatHistoryScRsp.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketGetPrivateChatHistoryScRsp.cs @@ -1,26 +1,21 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Friend +namespace EggLink.DanhengServer.Server.Packet.Send.Friend; + +public class PacketGetPrivateChatHistoryScRsp : BasePacket { - public class PacketGetPrivateChatHistoryScRsp : BasePacket + public PacketGetPrivateChatHistoryScRsp(uint contactId, PlayerInstance player) : base( + CmdIds.GetPrivateChatHistoryScRsp) { - public PacketGetPrivateChatHistoryScRsp(uint contactId, PlayerInstance player) : base(CmdIds.GetPrivateChatHistoryScRsp) + var proto = new GetPrivateChatHistoryScRsp { - var proto = new GetPrivateChatHistoryScRsp() - { - ContactId = contactId, - }; + ContactId = contactId + }; - var infos = player.FriendManager!.GetHistoryInfo((int)contactId); - proto.ChatMessageList.AddRange(infos); + var infos = player.FriendManager!.GetHistoryInfo((int)contactId); + proto.ChatMessageList.AddRange(infos); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketHandleFriendScRsp.cs b/GameServer/Server/Packet/Send/Friend/PacketHandleFriendScRsp.cs index 48271ee5..45d5893d 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketHandleFriendScRsp.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketHandleFriendScRsp.cs @@ -1,43 +1,38 @@ using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Friend +namespace EggLink.DanhengServer.Server.Packet.Send.Friend; + +public class PacketHandleFriendScRsp : BasePacket { - public class PacketHandleFriendScRsp : BasePacket + public PacketHandleFriendScRsp(uint uid, bool isAccept) : base(CmdIds.HandleFriendScRsp) { - public PacketHandleFriendScRsp(uint uid, bool isAccept) : base(CmdIds.HandleFriendScRsp) + var proto = new HandleFriendScRsp { - var proto = new HandleFriendScRsp - { - Uid = uid, - IsAccept = isAccept - }; + Uid = uid, + IsAccept = isAccept + }; - SetData(proto); - } - - public PacketHandleFriendScRsp(uint uid, bool isAccept, PlayerData playerData) : base(CmdIds.HandleFriendScRsp) - { - var status = Listener.GetActiveConnection((int)uid) == null ? FriendOnlineStatus.Offline : FriendOnlineStatus.Online; - var proto = new HandleFriendScRsp - { - Uid = uid, - IsAccept = isAccept, - FriendInfo = new() - { - IsMarked = false, - RemarkName = "", - PlayerInfo = playerData.ToSimpleProto(status) - } - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketHandleFriendScRsp(uint uid, bool isAccept, PlayerData playerData) : base(CmdIds.HandleFriendScRsp) + { + var status = Listener.GetActiveConnection((int)uid) == null + ? FriendOnlineStatus.Offline + : FriendOnlineStatus.Online; + var proto = new HandleFriendScRsp + { + Uid = uid, + IsAccept = isAccept, + FriendInfo = new FriendSimpleInfo + { + IsMarked = false, + RemarkName = "", + PlayerInfo = playerData.ToSimpleProto(status) + } + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketRevcMsgScNotify.cs b/GameServer/Server/Packet/Send/Friend/PacketRevcMsgScNotify.cs index 75f8fab3..4b9a6387 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketRevcMsgScNotify.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketRevcMsgScNotify.cs @@ -1,40 +1,34 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Friend +namespace EggLink.DanhengServer.Server.Packet.Send.Friend; + +public class PacketRevcMsgScNotify : BasePacket { - public class PacketRevcMsgScNotify : BasePacket + public PacketRevcMsgScNotify(uint toUid, uint fromUid, string msg) : base(CmdIds.RevcMsgScNotify) { - public PacketRevcMsgScNotify(uint toUid, uint fromUid, string msg) : base(CmdIds.RevcMsgScNotify) + var proto = new RevcMsgScNotify { - RevcMsgScNotify proto = new RevcMsgScNotify() - { - ChatType = ChatType.Private, - SourceUid = fromUid, - TargetUid = toUid, - MessageText = msg, - MessageType = MsgType.CustomText, - }; + ChatType = ChatType.Private, + SourceUid = fromUid, + TargetUid = toUid, + MessageText = msg, + MessageType = MsgType.CustomText + }; - SetData(proto); - } - - public PacketRevcMsgScNotify(uint toUid, uint fromUid, uint extraId) : base(CmdIds.RevcMsgScNotify) - { - RevcMsgScNotify proto = new RevcMsgScNotify() - { - ChatType = ChatType.Private, - SourceUid = fromUid, - TargetUid = toUid, - ExtraId = extraId, - MessageType = MsgType.Emoji - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketRevcMsgScNotify(uint toUid, uint fromUid, uint extraId) : base(CmdIds.RevcMsgScNotify) + { + var proto = new RevcMsgScNotify + { + ChatType = ChatType.Private, + SourceUid = fromUid, + TargetUid = toUid, + ExtraId = extraId, + MessageType = MsgType.Emoji + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketSearchPlayerScRsp.cs b/GameServer/Server/Packet/Send/Friend/PacketSearchPlayerScRsp.cs index 376b9425..832ced5a 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketSearchPlayerScRsp.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketSearchPlayerScRsp.cs @@ -1,33 +1,27 @@ using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Friend +namespace EggLink.DanhengServer.Server.Packet.Send.Friend; + +public class PacketSearchPlayerScRsp : BasePacket { - public class PacketSearchPlayerScRsp : BasePacket + public PacketSearchPlayerScRsp() : base(CmdIds.SearchPlayerScRsp) { - public PacketSearchPlayerScRsp() : base(CmdIds.SearchPlayerScRsp) + var proto = new SearchPlayerScRsp { - var proto = new SearchPlayerScRsp() - { - Retcode = 3612 - }; + Retcode = 3612 + }; - SetData(proto); - } - - public PacketSearchPlayerScRsp(List data) : base(CmdIds.SearchPlayerScRsp) - { - var proto = new SearchPlayerScRsp(); - - proto.ResultUidList.AddRange(data.Select(x => (uint)x.Uid)); - proto.SimpleInfoList.AddRange(data.Select(x => x.ToSimpleProto(FriendOnlineStatus.Online))); - - SetData(proto); - } + SetData(proto); } -} + + public PacketSearchPlayerScRsp(List data) : base(CmdIds.SearchPlayerScRsp) + { + var proto = new SearchPlayerScRsp(); + + proto.ResultUidList.AddRange(data.Select(x => (uint)x.Uid)); + proto.SimpleInfoList.AddRange(data.Select(x => x.ToSimpleProto(FriendOnlineStatus.Online))); + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketSyncApplyFriendScNotify.cs b/GameServer/Server/Packet/Send/Friend/PacketSyncApplyFriendScNotify.cs index cbaaf282..078d57c4 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketSyncApplyFriendScNotify.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketSyncApplyFriendScNotify.cs @@ -1,28 +1,22 @@ using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Friend +namespace EggLink.DanhengServer.Server.Packet.Send.Friend; + +public class PacketSyncApplyFriendScNotify : BasePacket { - public class PacketSyncApplyFriendScNotify : BasePacket + public PacketSyncApplyFriendScNotify(PlayerData player) : base(CmdIds.SyncApplyFriendScNotify) { - public PacketSyncApplyFriendScNotify(PlayerData player) : base(CmdIds.SyncApplyFriendScNotify) + var proto = new SyncApplyFriendScNotify { - var proto = new SyncApplyFriendScNotify() + ApplyInfo = new FriendApplyInfo { - ApplyInfo = new FriendApplyInfo() - { - ApplyTime = Extensions.GetUnixSec(), - PlayerInfo = player.ToSimpleProto(FriendOnlineStatus.Online), - }, - }; + ApplyTime = Extensions.GetUnixSec(), + PlayerInfo = player.ToSimpleProto(FriendOnlineStatus.Online) + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Friend/PacketSyncHandleFriendScNotify.cs b/GameServer/Server/Packet/Send/Friend/PacketSyncHandleFriendScNotify.cs index fcef669e..787f368a 100644 --- a/GameServer/Server/Packet/Send/Friend/PacketSyncHandleFriendScNotify.cs +++ b/GameServer/Server/Packet/Send/Friend/PacketSyncHandleFriendScNotify.cs @@ -1,32 +1,28 @@ using EggLink.DanhengServer.Database.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Friend +namespace EggLink.DanhengServer.Server.Packet.Send.Friend; + +public class PacketSyncHandleFriendScNotify : BasePacket { - public class PacketSyncHandleFriendScNotify : BasePacket + public PacketSyncHandleFriendScNotify(uint uid, bool isAccept, PlayerData playerData) : base( + CmdIds.SyncHandleFriendScNotify) { - public PacketSyncHandleFriendScNotify(uint uid, bool isAccept, PlayerData playerData) : base(CmdIds.SyncHandleFriendScNotify) + var status = Listener.GetActiveConnection((int)uid) == null + ? FriendOnlineStatus.Offline + : FriendOnlineStatus.Online; + var proto = new SyncHandleFriendScNotify { - var status = Listener.GetActiveConnection((int)uid) == null ? FriendOnlineStatus.Offline : FriendOnlineStatus.Online; - var proto = new SyncHandleFriendScNotify + Uid = uid, + IsAccept = isAccept, + FriendInfo = new FriendSimpleInfo { - Uid = uid, - IsAccept = isAccept, - FriendInfo = new() - { - IsMarked = false, - RemarkName = "", - PlayerInfo = playerData.ToSimpleProto(status) - } - }; + IsMarked = false, + RemarkName = "", + PlayerInfo = playerData.ToSimpleProto(status) + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Gacha/PacketDoGachaScRsp.cs b/GameServer/Server/Packet/Send/Gacha/PacketDoGachaScRsp.cs index 071ae1d8..b6840b05 100644 --- a/GameServer/Server/Packet/Send/Gacha/PacketDoGachaScRsp.cs +++ b/GameServer/Server/Packet/Send/Gacha/PacketDoGachaScRsp.cs @@ -1,26 +1,20 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Gacha +namespace EggLink.DanhengServer.Server.Packet.Send.Gacha; + +public class PacketDoGachaScRsp : BasePacket { - public class PacketDoGachaScRsp : BasePacket + public PacketDoGachaScRsp(DoGachaScRsp rsp) : base(CmdIds.DoGachaScRsp) { - public PacketDoGachaScRsp(DoGachaScRsp rsp) : base(CmdIds.DoGachaScRsp) - { - SetData(rsp); - } - - public PacketDoGachaScRsp() : base(CmdIds.DoGachaScRsp) - { - var rsp = new DoGachaScRsp - { - Retcode = 1, - }; - SetData(rsp); - } + SetData(rsp); } -} + + public PacketDoGachaScRsp() : base(CmdIds.DoGachaScRsp) + { + var rsp = new DoGachaScRsp + { + Retcode = 1 + }; + SetData(rsp); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Gacha/PacketGetGachaInfoScRsp.cs b/GameServer/Server/Packet/Send/Gacha/PacketGetGachaInfoScRsp.cs index 55bc03ab..ea668dbb 100644 --- a/GameServer/Server/Packet/Send/Gacha/PacketGetGachaInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Gacha/PacketGetGachaInfoScRsp.cs @@ -1,18 +1,11 @@ using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Gacha +namespace EggLink.DanhengServer.Server.Packet.Send.Gacha; + +public class PacketGetGachaInfoScRsp : BasePacket { - public class PacketGetGachaInfoScRsp : BasePacket + public PacketGetGachaInfoScRsp(PlayerInstance player) : base(CmdIds.GetGachaInfoScRsp) { - public PacketGetGachaInfoScRsp(PlayerInstance player) : base(CmdIds.GetGachaInfoScRsp) - { - SetData(player.GachaManager!.ToProto()); - } + SetData(player.GachaManager!.ToProto()); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/HeartDial/PacketChangeScriptEmotionScRsp.cs b/GameServer/Server/Packet/Send/HeartDial/PacketChangeScriptEmotionScRsp.cs index ac19ee1f..8fef4b83 100644 --- a/GameServer/Server/Packet/Send/HeartDial/PacketChangeScriptEmotionScRsp.cs +++ b/GameServer/Server/Packet/Send/HeartDial/PacketChangeScriptEmotionScRsp.cs @@ -1,24 +1,19 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; + +public class PacketChangeScriptEmotionScRsp : BasePacket { - public class PacketChangeScriptEmotionScRsp : BasePacket + public PacketChangeScriptEmotionScRsp(uint scriptId, HeartDialEmotionType emotion) : base( + CmdIds.ChangeScriptEmotionScRsp) { - public PacketChangeScriptEmotionScRsp(uint scriptId, HeartDialEmotionType emotion) : base(CmdIds.ChangeScriptEmotionScRsp) + var proto = new ChangeScriptEmotionScRsp { - var proto = new ChangeScriptEmotionScRsp - { - ScriptId = scriptId, - EmotionType = emotion - }; + ScriptId = scriptId, + EmotionType = emotion + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/HeartDial/PacketFinishEmotionDialoguePerformanceScRsp.cs b/GameServer/Server/Packet/Send/HeartDial/PacketFinishEmotionDialoguePerformanceScRsp.cs index c0edc686..69d65950 100644 --- a/GameServer/Server/Packet/Send/HeartDial/PacketFinishEmotionDialoguePerformanceScRsp.cs +++ b/GameServer/Server/Packet/Send/HeartDial/PacketFinishEmotionDialoguePerformanceScRsp.cs @@ -1,25 +1,20 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; + +public class PacketFinishEmotionDialoguePerformanceScRsp : BasePacket { - public class PacketFinishEmotionDialoguePerformanceScRsp : BasePacket + public PacketFinishEmotionDialoguePerformanceScRsp(uint scriptId, uint dialogueId) : base( + CmdIds.FinishEmotionDialoguePerformanceScRsp) { - public PacketFinishEmotionDialoguePerformanceScRsp(uint scriptId, uint dialogueId) : base(CmdIds.FinishEmotionDialoguePerformanceScRsp) + var proto = new FinishEmotionDialoguePerformanceScRsp { - var proto = new FinishEmotionDialoguePerformanceScRsp - { - DialogueId = dialogueId, - ScriptId = scriptId, - RewardList = new() - }; + DialogueId = dialogueId, + ScriptId = scriptId, + RewardList = new ItemList() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/HeartDial/PacketGetHeartDialInfoScRsp.cs b/GameServer/Server/Packet/Send/HeartDial/PacketGetHeartDialInfoScRsp.cs index c1cfa349..7eaffaa0 100644 --- a/GameServer/Server/Packet/Send/HeartDial/PacketGetHeartDialInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/HeartDial/PacketGetHeartDialInfoScRsp.cs @@ -1,67 +1,49 @@ using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; + +public class PacketGetHeartDialInfoScRsp : BasePacket { - public class PacketGetHeartDialInfoScRsp : BasePacket + public PacketGetHeartDialInfoScRsp(PlayerInstance player) : base(CmdIds.GetHeartDialInfoScRsp) { - public PacketGetHeartDialInfoScRsp(PlayerInstance player) : base(CmdIds.GetHeartDialInfoScRsp) + var proto = new GetHeartDialInfoScRsp { - var proto = new GetHeartDialInfoScRsp - { - UnlockStatus = HeartDialUnlockStatus.Lock - }; + UnlockStatus = HeartDialUnlockStatus.Lock + }; - if (player.MissionManager?.GetSubMissionStatus(103040103) == Enums.MissionPhaseEnum.Finish) - { - proto.UnlockStatus = HeartDialUnlockStatus.UnlockSingle; - } + if (player.MissionManager?.GetSubMissionStatus(103040103) == MissionPhaseEnum.Finish) + proto.UnlockStatus = HeartDialUnlockStatus.UnlockSingle; - if (player.MissionManager?.GetSubMissionStatus(103040104) == Enums.MissionPhaseEnum.Finish) - { - proto.UnlockStatus = HeartDialUnlockStatus.UnlockAll; - } + if (player.MissionManager?.GetSubMissionStatus(103040104) == MissionPhaseEnum.Finish) + proto.UnlockStatus = HeartDialUnlockStatus.UnlockAll; - var heartDialData = player.HeartDialData!; + var heartDialData = player.HeartDialData!; - foreach (var script in GameData.HeartDialScriptData.Values) - { - if (heartDialData.DialList.TryGetValue(script.ScriptID, out var info)) + foreach (var script in GameData.HeartDialScriptData.Values) + if (heartDialData.DialList.TryGetValue(script.ScriptID, out var info)) + proto.ScriptInfoList.Add(new HeartDialScriptInfo { - proto.ScriptInfoList.Add(new HeartDialScriptInfo() - { - ScriptId = (uint)script.ScriptID, - CurEmotionType = (HeartDialEmotionType)info.EmoType, - Step = (HeartDialStepType)info.StepType - }); - } - else - { - proto.ScriptInfoList.Add(new HeartDialScriptInfo() - { - ScriptId = (uint)script.ScriptID, - CurEmotionType = (HeartDialEmotionType)script.DefaultEmoType, - Step = (HeartDialStepType)script.StepList.First() - }); - } - - } - foreach (var id in GameData.HeartDialDialogueData.Keys) - { - proto.DialogueInfoList.Add(new HeartDialDialogueInfo() - { - DialogueId = (uint)id, + ScriptId = (uint)script.ScriptID, + CurEmotionType = (HeartDialEmotionType)info.EmoType, + Step = (HeartDialStepType)info.StepType }); - } + else + proto.ScriptInfoList.Add(new HeartDialScriptInfo + { + ScriptId = (uint)script.ScriptID, + CurEmotionType = (HeartDialEmotionType)script.DefaultEmoType, + Step = (HeartDialStepType)script.StepList.First() + }); + foreach (var id in GameData.HeartDialDialogueData.Keys) + proto.DialogueInfoList.Add(new HeartDialDialogueInfo + { + DialogueId = (uint)id + }); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/HeartDial/PacketHeartDialScriptChangeScNotify.cs b/GameServer/Server/Packet/Send/HeartDial/PacketHeartDialScriptChangeScNotify.cs index 077bcdba..23784314 100644 --- a/GameServer/Server/Packet/Send/HeartDial/PacketHeartDialScriptChangeScNotify.cs +++ b/GameServer/Server/Packet/Send/HeartDial/PacketHeartDialScriptChangeScNotify.cs @@ -1,34 +1,27 @@ using EggLink.DanhengServer.Database.Scene; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; + +public class PacketHeartDialScriptChangeScNotify : BasePacket { - public class PacketHeartDialScriptChangeScNotify : BasePacket + public PacketHeartDialScriptChangeScNotify(HeartDialUnlockStatus status, HeartDialInfo? changedInfo = null) : base( + CmdIds.HeartDialScriptChangeScNotify) { - public PacketHeartDialScriptChangeScNotify(HeartDialUnlockStatus status, HeartDialInfo? changedInfo = null) : base(CmdIds.HeartDialScriptChangeScNotify) + var proto = new HeartDialScriptChangeScNotify { - var proto = new HeartDialScriptChangeScNotify - { - UnlockStatus = status, - }; + UnlockStatus = status + }; - if (changedInfo != null) + if (changedInfo != null) + proto.ChangedScriptInfoList.Add(new HeartDialScriptInfo { - proto.ChangedScriptInfoList.Add(new HeartDialScriptInfo - { - ScriptId = (uint)changedInfo.ScriptId, - CurEmotionType = (HeartDialEmotionType)changedInfo.EmoType, - Step = (HeartDialStepType)changedInfo.StepType, - }); - } + ScriptId = (uint)changedInfo.ScriptId, + CurEmotionType = (HeartDialEmotionType)changedInfo.EmoType, + Step = (HeartDialStepType)changedInfo.StepType + }); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/HeartDial/PacketSubmitEmotionItemScRsp.cs b/GameServer/Server/Packet/Send/HeartDial/PacketSubmitEmotionItemScRsp.cs index 12eba4d8..721d208c 100644 --- a/GameServer/Server/Packet/Send/HeartDial/PacketSubmitEmotionItemScRsp.cs +++ b/GameServer/Server/Packet/Send/HeartDial/PacketSubmitEmotionItemScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.HeartDial; + +public class PacketSubmitEmotionItemScRsp : BasePacket { - public class PacketSubmitEmotionItemScRsp : BasePacket + public PacketSubmitEmotionItemScRsp(uint scriptId) : base(CmdIds.SubmitEmotionItemScRsp) { - public PacketSubmitEmotionItemScRsp(uint scriptId) : base(CmdIds.SubmitEmotionItemScRsp) + var proto = new SubmitEmotionItemScRsp { - var proto = new SubmitEmotionItemScRsp - { - ScriptId = scriptId - }; + ScriptId = scriptId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Lineup/PacketChangeLineupLeaderScRsp.cs b/GameServer/Server/Packet/Send/Lineup/PacketChangeLineupLeaderScRsp.cs index 7d7dfbe7..6e319064 100644 --- a/GameServer/Server/Packet/Send/Lineup/PacketChangeLineupLeaderScRsp.cs +++ b/GameServer/Server/Packet/Send/Lineup/PacketChangeLineupLeaderScRsp.cs @@ -1,32 +1,26 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Lineup +namespace EggLink.DanhengServer.Server.Packet.Send.Lineup; + +public class PacketChangeLineupLeaderScRsp : BasePacket { - public class PacketChangeLineupLeaderScRsp : BasePacket + public PacketChangeLineupLeaderScRsp(uint slot) : base(CmdIds.ChangeLineupLeaderScRsp) { - public PacketChangeLineupLeaderScRsp(uint slot) : base(CmdIds.ChangeLineupLeaderScRsp) + var proto = new ChangeLineupLeaderScRsp { - var proto = new ChangeLineupLeaderScRsp() - { - Slot = slot, - }; + Slot = slot + }; - SetData(proto); - } - - public PacketChangeLineupLeaderScRsp() : base(CmdIds.ChangeLineupLeaderScRsp) - { - var proto = new ChangeLineupLeaderScRsp() - { - Retcode = 1, - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketChangeLineupLeaderScRsp() : base(CmdIds.ChangeLineupLeaderScRsp) + { + var proto = new ChangeLineupLeaderScRsp + { + Retcode = 1 + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Lineup/PacketGetAllLineupDataScRsp.cs b/GameServer/Server/Packet/Send/Lineup/PacketGetAllLineupDataScRsp.cs index 7d1ea23c..cc020cad 100644 --- a/GameServer/Server/Packet/Send/Lineup/PacketGetAllLineupDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Lineup/PacketGetAllLineupDataScRsp.cs @@ -1,22 +1,18 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Lineup -{ - public class PacketGetAllLineupDataScRsp : BasePacket - { - public PacketGetAllLineupDataScRsp(PlayerInstance player) : base(CmdIds.GetAllLineupDataScRsp) - { - var proto = new GetAllLineupDataScRsp() - { - CurIndex = (uint)player.LineupManager!.LineupData.CurLineup, - }; - foreach (var lineup in player.LineupManager.GetAllLineup()) - { - proto.LineupList.Add(lineup.ToProto()); - } +namespace EggLink.DanhengServer.Server.Packet.Send.Lineup; - SetData(proto); - } +public class PacketGetAllLineupDataScRsp : BasePacket +{ + public PacketGetAllLineupDataScRsp(PlayerInstance player) : base(CmdIds.GetAllLineupDataScRsp) + { + var proto = new GetAllLineupDataScRsp + { + CurIndex = (uint)player.LineupManager!.LineupData.CurLineup + }; + foreach (var lineup in player.LineupManager.GetAllLineup()) proto.LineupList.Add(lineup.ToProto()); + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Lineup/PacketGetCurLineupDataScRsp.cs b/GameServer/Server/Packet/Send/Lineup/PacketGetCurLineupDataScRsp.cs index 9f99aa7f..a05cf2eb 100644 --- a/GameServer/Server/Packet/Send/Lineup/PacketGetCurLineupDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Lineup/PacketGetCurLineupDataScRsp.cs @@ -1,18 +1,17 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Lineup -{ - public class PacketGetCurLineupDataScRsp : BasePacket - { - public PacketGetCurLineupDataScRsp(PlayerInstance player) : base(CmdIds.GetCurLineupDataScRsp) - { - var data = new GetCurLineupDataScRsp() - { - Lineup = player.LineupManager?.GetCurLineup()?.ToProto() ?? new(), - }; +namespace EggLink.DanhengServer.Server.Packet.Send.Lineup; - SetData(data); - } +public class PacketGetCurLineupDataScRsp : BasePacket +{ + public PacketGetCurLineupDataScRsp(PlayerInstance player) : base(CmdIds.GetCurLineupDataScRsp) + { + var data = new GetCurLineupDataScRsp + { + Lineup = player.LineupManager?.GetCurLineup()?.ToProto() ?? new LineupInfo() + }; + + SetData(data); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Lineup/PacketGetLineupAvatarDataScRsp.cs b/GameServer/Server/Packet/Send/Lineup/PacketGetLineupAvatarDataScRsp.cs index 2656cdaa..4a9e851c 100644 --- a/GameServer/Server/Packet/Send/Lineup/PacketGetLineupAvatarDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Lineup/PacketGetLineupAvatarDataScRsp.cs @@ -1,26 +1,25 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Lineup +namespace EggLink.DanhengServer.Server.Packet.Send.Lineup; + +public class PacketGetLineupAvatarDataScRsp : BasePacket { - public class PacketGetLineupAvatarDataScRsp : BasePacket + public PacketGetLineupAvatarDataScRsp(PlayerInstance player) : base(CmdIds.GetLineupAvatarDataScRsp) { - public PacketGetLineupAvatarDataScRsp(PlayerInstance player) : base(CmdIds.GetLineupAvatarDataScRsp) + var rsp = new GetLineupAvatarDataScRsp(); + + player.AvatarManager?.AvatarData?.Avatars?.ForEach(avatar => { - var rsp = new GetLineupAvatarDataScRsp(); - - player.AvatarManager?.AvatarData?.Avatars?.ForEach(avatar => + var data = new LineupAvatarData { - var data = new LineupAvatarData() - { - Id = (uint)avatar.AvatarId, - Hp = (uint)avatar.CurrentHp, - AvatarType = AvatarType.AvatarFormalType - }; - rsp.AvatarDataList.Add(data); - }); + Id = (uint)avatar.AvatarId, + Hp = (uint)avatar.CurrentHp, + AvatarType = AvatarType.AvatarFormalType + }; + rsp.AvatarDataList.Add(data); + }); - SetData(rsp); - } + SetData(rsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Lineup/PacketSceneCastSkillCostMpScRsp.cs b/GameServer/Server/Packet/Send/Lineup/PacketSceneCastSkillCostMpScRsp.cs index 7c9328e3..b58fcbe8 100644 --- a/GameServer/Server/Packet/Send/Lineup/PacketSceneCastSkillCostMpScRsp.cs +++ b/GameServer/Server/Packet/Send/Lineup/PacketSceneCastSkillCostMpScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Lineup +namespace EggLink.DanhengServer.Server.Packet.Send.Lineup; + +public class PacketSceneCastSkillCostMpScRsp : BasePacket { - public class PacketSceneCastSkillCostMpScRsp : BasePacket + public PacketSceneCastSkillCostMpScRsp(int entityId) : base(CmdIds.SceneCastSkillCostMpScRsp) { - public PacketSceneCastSkillCostMpScRsp(int entityId) : base(CmdIds.SceneCastSkillCostMpScRsp) + var proto = new SceneCastSkillCostMpScRsp { - var proto = new SceneCastSkillCostMpScRsp - { - CastEntityId = (uint)entityId, - }; + CastEntityId = (uint)entityId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Lineup/PacketSceneCastSkillMpUpdateScNotify.cs b/GameServer/Server/Packet/Send/Lineup/PacketSceneCastSkillMpUpdateScNotify.cs index dc3a821e..ab3894cb 100644 --- a/GameServer/Server/Packet/Send/Lineup/PacketSceneCastSkillMpUpdateScNotify.cs +++ b/GameServer/Server/Packet/Send/Lineup/PacketSceneCastSkillMpUpdateScNotify.cs @@ -1,23 +1,18 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Lineup +namespace EggLink.DanhengServer.Server.Packet.Send.Lineup; + +public class PacketSceneCastSkillMpUpdateScNotify : BasePacket { - public class PacketSceneCastSkillMpUpdateScNotify : BasePacket + public PacketSceneCastSkillMpUpdateScNotify(uint castEntityId, int mpCount) : base( + CmdIds.SceneCastSkillMpUpdateScNotify) { - public PacketSceneCastSkillMpUpdateScNotify(uint castEntityId, int mpCount) : base(CmdIds.SceneCastSkillMpUpdateScNotify) + var proto = new SceneCastSkillMpUpdateScNotify { - var proto = new SceneCastSkillMpUpdateScNotify() - { - CastEntityId = castEntityId, - Mp = (uint)mpCount, - }; + CastEntityId = castEntityId, + Mp = (uint)mpCount + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Lineup/PacketSwitchLineupIndexScRsp.cs b/GameServer/Server/Packet/Send/Lineup/PacketSwitchLineupIndexScRsp.cs index ec04ce12..4014b370 100644 --- a/GameServer/Server/Packet/Send/Lineup/PacketSwitchLineupIndexScRsp.cs +++ b/GameServer/Server/Packet/Send/Lineup/PacketSwitchLineupIndexScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Lineup +namespace EggLink.DanhengServer.Server.Packet.Send.Lineup; + +public class PacketSwitchLineupIndexScRsp : BasePacket { - public class PacketSwitchLineupIndexScRsp : BasePacket + public PacketSwitchLineupIndexScRsp(uint index) : base(CmdIds.SwitchLineupIndexScRsp) { - public PacketSwitchLineupIndexScRsp(uint index) : base(CmdIds.SwitchLineupIndexScRsp) + var proto = new SwitchLineupIndexScRsp { - var proto = new SwitchLineupIndexScRsp() - { - Index = index, - }; + Index = index + }; - SetData(proto); - } - } -} + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Lineup/PacketSyncLineupNotify.cs b/GameServer/Server/Packet/Send/Lineup/PacketSyncLineupNotify.cs index 0aa2e3eb..20250f63 100644 --- a/GameServer/Server/Packet/Send/Lineup/PacketSyncLineupNotify.cs +++ b/GameServer/Server/Packet/Send/Lineup/PacketSyncLineupNotify.cs @@ -1,18 +1,19 @@ using EggLink.DanhengServer.Proto; +using LineupInfo = EggLink.DanhengServer.Database.Lineup.LineupInfo; -namespace EggLink.DanhengServer.Server.Packet.Send.Lineup +namespace EggLink.DanhengServer.Server.Packet.Send.Lineup; + +public class PacketSyncLineupNotify : BasePacket { - public class PacketSyncLineupNotify : BasePacket + public PacketSyncLineupNotify(LineupInfo info, SyncLineupReason reason = SyncLineupReason.SyncReasonNone) : base( + CmdIds.SyncLineupNotify) { - public PacketSyncLineupNotify(Database.Lineup.LineupInfo info, SyncLineupReason reason = SyncLineupReason.SyncReasonNone) : base(CmdIds.SyncLineupNotify) + var proto = new SyncLineupNotify { - var proto = new SyncLineupNotify() - { - Lineup = info.ToProto(), - ReasonList = { reason } - }; + Lineup = info.ToProto(), + ReasonList = { reason } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mail/PacketGetMailScRsp.cs b/GameServer/Server/Packet/Send/Mail/PacketGetMailScRsp.cs index f0494452..1b8ac268 100644 --- a/GameServer/Server/Packet/Send/Mail/PacketGetMailScRsp.cs +++ b/GameServer/Server/Packet/Send/Mail/PacketGetMailScRsp.cs @@ -1,29 +1,23 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mail +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mail; + +public class PacketGetMailScRsp : BasePacket { - public class PacketGetMailScRsp : BasePacket + public PacketGetMailScRsp(PlayerInstance player) : base(CmdIds.GetMailScRsp) { - public PacketGetMailScRsp(PlayerInstance player) : base(CmdIds.GetMailScRsp) + var list = player.MailManager!.ToMailProto(); + var noticeList = player.MailManager!.ToNoticeMailProto(); + var proto = new GetMailScRsp { - var list = player.MailManager!.ToMailProto(); - var noticeList = player.MailManager!.ToNoticeMailProto(); - var proto = new GetMailScRsp - { - IsEnd = true, - MailList = { list }, - NoticeMailList = { noticeList }, - TotalNum = (uint)(list.Count + noticeList.Count) - }; + IsEnd = true, + MailList = { list }, + NoticeMailList = { noticeList }, + TotalNum = (uint)(list.Count + noticeList.Count) + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mail/PacketMarkReadMailScRsp.cs b/GameServer/Server/Packet/Send/Mail/PacketMarkReadMailScRsp.cs index 60327b30..687d0d5d 100644 --- a/GameServer/Server/Packet/Send/Mail/PacketMarkReadMailScRsp.cs +++ b/GameServer/Server/Packet/Send/Mail/PacketMarkReadMailScRsp.cs @@ -1,33 +1,27 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mail +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mail; + +public class PacketMarkReadMailScRsp : BasePacket { - public class PacketMarkReadMailScRsp : BasePacket + public PacketMarkReadMailScRsp(uint mailId) : base(CmdIds.MarkReadMailScRsp) { - public PacketMarkReadMailScRsp(uint mailId) : base(CmdIds.MarkReadMailScRsp) + var proto = new MarkReadMailScRsp { - var proto = new MarkReadMailScRsp() - { - Id = mailId - }; + Id = mailId + }; - SetData(proto); - } - - public PacketMarkReadMailScRsp(Retcode retcode) : base(CmdIds.MarkReadMailScRsp) - { - var proto = new MarkReadMailScRsp() - { - Retcode = (uint)retcode - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketMarkReadMailScRsp(Retcode retcode) : base(CmdIds.MarkReadMailScRsp) + { + var proto = new MarkReadMailScRsp + { + Retcode = (uint)retcode + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mail/PacketNewMailScNotify.cs b/GameServer/Server/Packet/Send/Mail/PacketNewMailScNotify.cs index 9e55282f..089bba07 100644 --- a/GameServer/Server/Packet/Send/Mail/PacketNewMailScNotify.cs +++ b/GameServer/Server/Packet/Send/Mail/PacketNewMailScNotify.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mail +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mail; + +public class PacketNewMailScNotify : BasePacket { - public class PacketNewMailScNotify : BasePacket + public PacketNewMailScNotify(int id) : base(CmdIds.NewMailScNotify) { - public PacketNewMailScNotify(int id) : base(CmdIds.NewMailScNotify) + var proto = new NewMailScNotify { - var proto = new NewMailScNotify() - { - MailIdList = { (uint)id } - }; + MailIdList = { (uint)id } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketAcceptMainMissionScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketAcceptMainMissionScRsp.cs index 3f65348e..0561a602 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketAcceptMainMissionScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketAcceptMainMissionScRsp.cs @@ -1,17 +1,16 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission -{ - public class PacketAcceptMainMissionScRsp : BasePacket - { - public PacketAcceptMainMissionScRsp(uint missionId) : base(CmdIds.AcceptMainMissionScRsp) - { - var proto = new AcceptMainMissionScRsp() - { - MainMissionId = missionId, - }; +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; - SetData(proto); - } +public class PacketAcceptMainMissionScRsp : BasePacket +{ + public PacketAcceptMainMissionScRsp(uint missionId) : base(CmdIds.AcceptMainMissionScRsp) + { + var proto = new AcceptMainMissionScRsp + { + MainMissionId = missionId + }; + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketChangeStoryLineFinishScNotify.cs b/GameServer/Server/Packet/Send/Mission/PacketChangeStoryLineFinishScNotify.cs index 73b9e8bc..18cf4ee6 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketChangeStoryLineFinishScNotify.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketChangeStoryLineFinishScNotify.cs @@ -1,24 +1,19 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission; + +public class PacketChangeStoryLineFinishScNotify : BasePacket { - public class PacketChangeStoryLineFinishScNotify : BasePacket + public PacketChangeStoryLineFinishScNotify(int curId, ChangeStoryLineAction reason) : base( + CmdIds.ChangeStoryLineFinishScNotify) { - public PacketChangeStoryLineFinishScNotify(int curId, ChangeStoryLineAction reason) : base(CmdIds.ChangeStoryLineFinishScNotify) + var proto = new ChangeStoryLineFinishScNotify { - var proto = new ChangeStoryLineFinishScNotify - { - ActionType = reason, - CurStoryLineId = (uint)curId, - }; + ActionType = reason, + CurStoryLineId = (uint)curId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketFinishCosumeItemMissionScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketFinishCosumeItemMissionScRsp.cs index 8fe90b70..a22ec716 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketFinishCosumeItemMissionScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketFinishCosumeItemMissionScRsp.cs @@ -1,31 +1,25 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketFinishCosumeItemMissionScRsp : BasePacket { - public class PacketFinishCosumeItemMissionScRsp : BasePacket + public PacketFinishCosumeItemMissionScRsp(uint subMissionId) : base(CmdIds.FinishCosumeItemMissionScRsp) { - public PacketFinishCosumeItemMissionScRsp(uint subMissionId) : base(CmdIds.FinishCosumeItemMissionScRsp) + var proto = new FinishCosumeItemMissionScRsp { - var proto = new FinishCosumeItemMissionScRsp() - { - SubMissionId = subMissionId - }; + SubMissionId = subMissionId + }; - SetData(proto); - } - - public PacketFinishCosumeItemMissionScRsp() : base(CmdIds.FinishCosumeItemMissionScRsp) - { - var proto = new FinishCosumeItemMissionScRsp() - { - Retcode = 1 - }; - SetData(proto); - } + SetData(proto); } -} + + public PacketFinishCosumeItemMissionScRsp() : base(CmdIds.FinishCosumeItemMissionScRsp) + { + var proto = new FinishCosumeItemMissionScRsp + { + Retcode = 1 + }; + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketFinishItemIdScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketFinishItemIdScRsp.cs index 59330023..39d8a1d4 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketFinishItemIdScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketFinishItemIdScRsp.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketFinishItemIdScRsp : BasePacket { - public class PacketFinishItemIdScRsp : BasePacket + public PacketFinishItemIdScRsp(uint itemId) : base(CmdIds.FinishItemIdScRsp) { - public PacketFinishItemIdScRsp(uint itemId) : base(CmdIds.FinishItemIdScRsp) + var proto = new FinishItemIdScRsp { - var proto = new FinishItemIdScRsp - { - ItemId = itemId - }; - SetData(proto); - } + ItemId = itemId + }; + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketFinishPerformSectionIdScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketFinishPerformSectionIdScRsp.cs index bf8a18a1..aeb544d9 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketFinishPerformSectionIdScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketFinishPerformSectionIdScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketFinishPerformSectionIdScRsp : BasePacket { - public class PacketFinishPerformSectionIdScRsp : BasePacket + public PacketFinishPerformSectionIdScRsp(uint sectionId) : base(CmdIds.FinishPerformSectionIdScRsp) { - public PacketFinishPerformSectionIdScRsp(uint sectionId) : base(CmdIds.FinishPerformSectionIdScRsp) + var proto = new FinishPerformSectionIdScRsp { - var proto = new FinishPerformSectionIdScRsp - { - SectionId = sectionId - }; + SectionId = sectionId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketFinishSectionIdScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketFinishSectionIdScRsp.cs index 2e3bf4b2..af0463e2 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketFinishSectionIdScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketFinishSectionIdScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketFinishSectionIdScRsp : BasePacket { - public class PacketFinishSectionIdScRsp : BasePacket + public PacketFinishSectionIdScRsp(uint sectionId) : base(CmdIds.FinishSectionIdScRsp) { - public PacketFinishSectionIdScRsp(uint sectionId) : base(CmdIds.FinishSectionIdScRsp) + var proto = new FinishSectionIdScRsp { - var proto = new FinishSectionIdScRsp - { - SectionId = sectionId - }; + SectionId = sectionId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketFinishTalkMissionScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketFinishTalkMissionScRsp.cs index d9be1cc5..956283ee 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketFinishTalkMissionScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketFinishTalkMissionScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketFinishTalkMissionScRsp : BasePacket { - public class PacketFinishTalkMissionScRsp : BasePacket + public PacketFinishTalkMissionScRsp(string talkStr) : base(CmdIds.FinishTalkMissionScRsp) { - public PacketFinishTalkMissionScRsp(string talkStr) : base(CmdIds.FinishTalkMissionScRsp) + var proto = new FinishTalkMissionScRsp { - var proto = new FinishTalkMissionScRsp() - { - TalkStr = talkStr, - }; + TalkStr = talkStr + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketGetMainMissionCustomValueScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketGetMainMissionCustomValueScRsp.cs index a231f5cb..cc57a37f 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketGetMainMissionCustomValueScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketGetMainMissionCustomValueScRsp.cs @@ -2,23 +2,21 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission -{ - public class PacketGetMainMissionCustomValueScRsp : BasePacket - { - public PacketGetMainMissionCustomValueScRsp(GetMainMissionCustomValueCsReq req, PlayerInstance player) : base(CmdIds.GetMainMissionCustomValueScRsp) - { - var proto = new GetMainMissionCustomValueScRsp(); - foreach (var mission in req.MainMissionIdList) - { - proto.MissionDataList.Add(new MissionData - { - Id = mission, - Status = player.MissionManager!.GetMainMissionStatus((int)mission).ToProto() - }); - } +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; - SetData(proto); - } +public class PacketGetMainMissionCustomValueScRsp : BasePacket +{ + public PacketGetMainMissionCustomValueScRsp(GetMainMissionCustomValueCsReq req, PlayerInstance player) : base( + CmdIds.GetMainMissionCustomValueScRsp) + { + var proto = new GetMainMissionCustomValueScRsp(); + foreach (var mission in req.MainMissionIdList) + proto.MissionDataList.Add(new MissionData + { + Id = mission, + Status = player.MissionManager!.GetMainMissionStatus((int)mission).ToProto() + }); + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketGetMissionDataScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketGetMissionDataScRsp.cs index 16ba518d..9fe4f18a 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketGetMissionDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketGetMissionDataScRsp.cs @@ -3,43 +3,34 @@ using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketGetMissionDataScRsp : BasePacket { - public class PacketGetMissionDataScRsp : BasePacket + public PacketGetMissionDataScRsp(PlayerInstance player) : base(CmdIds.GetMissionDataScRsp) { - public PacketGetMissionDataScRsp(PlayerInstance player) : base(CmdIds.GetMissionDataScRsp) + var proto = new GetMissionDataScRsp { - var proto = new GetMissionDataScRsp() - { - TrackMissionId = (uint)player.MissionManager!.Data.TrackingMainMissionId, - }; - - foreach (var mission in GameData.MainMissionData.Keys) - { - if (player.MissionManager!.GetMainMissionStatus(mission) == MissionPhaseEnum.Accept) - { - proto.MissionDataList.Add(new MissionData() - { - Id = (uint)mission, - Status = MissionStatus.MissionDoing - }); - } - } + TrackMissionId = (uint)player.MissionManager!.Data.TrackingMainMissionId + }; - foreach (var mission in GameData.SubMissionData.Keys) - { - if (player.MissionManager!.GetSubMissionStatus(mission) == MissionPhaseEnum.Accept) + foreach (var mission in GameData.MainMissionData.Keys) + if (player.MissionManager!.GetMainMissionStatus(mission) == MissionPhaseEnum.Accept) + proto.MissionDataList.Add(new MissionData { - proto.MissionList.Add(new Proto.Mission() - { - Id = (uint)mission, - Status = MissionStatus.MissionDoing, - Progress = (uint)player.MissionManager!.GetMissionProgress(mission) - }); - } - } + Id = (uint)mission, + Status = MissionStatus.MissionDoing + }); - SetData(proto); - } + foreach (var mission in GameData.SubMissionData.Keys) + if (player.MissionManager!.GetSubMissionStatus(mission) == MissionPhaseEnum.Accept) + proto.MissionList.Add(new Proto.Mission + { + Id = (uint)mission, + Status = MissionStatus.MissionDoing, + Progress = (uint)player.MissionManager!.GetMissionProgress(mission) + }); + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketGetMissionStatusScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketGetMissionStatusScRsp.cs index 0998598e..db9f53f4 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketGetMissionStatusScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketGetMissionStatusScRsp.cs @@ -2,37 +2,34 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketGetMissionStatusScRsp : BasePacket { - public class PacketGetMissionStatusScRsp : BasePacket + public PacketGetMissionStatusScRsp(GetMissionStatusCsReq req, PlayerInstance player) : base( + CmdIds.GetMissionStatusScRsp) { - public PacketGetMissionStatusScRsp(GetMissionStatusCsReq req, PlayerInstance player) : base(CmdIds.GetMissionStatusScRsp) + var proto = new GetMissionStatusScRsp(); + + foreach (var item in req.MainMissionIdList) { - var proto = new GetMissionStatusScRsp(); - - foreach (var item in req.MainMissionIdList) - { - var status = player.MissionManager!.GetMainMissionStatus((int)item); - if (status == MissionPhaseEnum.Finish) - { - proto.FinishedMainMissionIdList.Add(item); - } else - { - proto.UnfinishedMainMissionIdList.Add(item); - } - } - - foreach (var item in req.SubMissionIdList) - { - var status = player.MissionManager!.GetSubMissionStatus((int)item); - proto.SubMissionStatusList.Add(new Proto.Mission() - { - Id = item, - Status = status.ToProto(), - }); - } - - SetData(proto); + var status = player.MissionManager!.GetMainMissionStatus((int)item); + if (status == MissionPhaseEnum.Finish) + proto.FinishedMainMissionIdList.Add(item); + else + proto.UnfinishedMainMissionIdList.Add(item); } + + foreach (var item in req.SubMissionIdList) + { + var status = player.MissionManager!.GetSubMissionStatus((int)item); + proto.SubMissionStatusList.Add(new Proto.Mission + { + Id = item, + Status = status.ToProto() + }); + } + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketGetNpcMessageGroupScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketGetNpcMessageGroupScRsp.cs index 57c4060d..5cc8ff15 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketGetNpcMessageGroupScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketGetNpcMessageGroupScRsp.cs @@ -1,27 +1,22 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketGetNpcMessageGroupScRsp : BasePacket { - public class PacketGetNpcMessageGroupScRsp : BasePacket - { - public PacketGetNpcMessageGroupScRsp(IEnumerable contactIdList, PlayerInstance instance) : base(CmdIds.GetNpcMessageGroupScRsp) + public PacketGetNpcMessageGroupScRsp(IEnumerable contactIdList, PlayerInstance instance) : base( + CmdIds.GetNpcMessageGroupScRsp) + { + var proto = new GetNpcMessageGroupScRsp(); + + foreach (var contactId in contactIdList) { - var proto = new GetNpcMessageGroupScRsp(); + var contact = instance.MessageManager!.GetMessageGroup((int)contactId); - foreach (var contactId in contactIdList) - { - var contact = instance.MessageManager!.GetMessageGroup((int)contactId); - - proto.MessageGroupList.AddRange(contact); - } - - SetData(proto); + proto.MessageGroupList.AddRange(contact); } + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketGetNpcStatusScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketGetNpcStatusScRsp.cs index 81f303b7..7d1c2485 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketGetNpcStatusScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketGetNpcStatusScRsp.cs @@ -1,32 +1,22 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketGetNpcStatusScRsp : BasePacket { - public class PacketGetNpcStatusScRsp : BasePacket + public PacketGetNpcStatusScRsp(PlayerInstance player) : base(CmdIds.GetNpcStatusScRsp) { - public PacketGetNpcStatusScRsp(PlayerInstance player) : base(CmdIds.GetNpcStatusScRsp) - { - var proto = new GetNpcStatusScRsp - { - }; + var proto = new GetNpcStatusScRsp(); - foreach (var item in GameData.MessageContactsConfigData.Values) + foreach (var item in GameData.MessageContactsConfigData.Values) + proto.NpcStatusList.Add(new NpcStatus { - proto.NpcStatusList.Add(new NpcStatus() - { - NpcId = (uint)item.ID, - IsFinish = player.MessageManager!.GetMessageGroup(item.ID).Count > 0 - }); - } + NpcId = (uint)item.ID, + IsFinish = player.MessageManager!.GetMessageGroup(item.ID).Count > 0 + }); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketGetStoryLineInfoScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketGetStoryLineInfoScRsp.cs index ddaa1a67..428e0412 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketGetStoryLineInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketGetStoryLineInfoScRsp.cs @@ -1,25 +1,20 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission; + +public class PacketGetStoryLineInfoScRsp : BasePacket { - public class PacketGetStoryLineInfoScRsp : BasePacket + public PacketGetStoryLineInfoScRsp(PlayerInstance player) : base(CmdIds.GetStoryLineInfoScRsp) { - public PacketGetStoryLineInfoScRsp(PlayerInstance player) : base(CmdIds.GetStoryLineInfoScRsp) + var proto = new GetStoryLineInfoScRsp { - var proto = new GetStoryLineInfoScRsp - { - CurStoryLineId = (uint)player.StoryLineManager!.StoryLineData.CurStoryLineId, - RunningStoryLineIdList = { player.StoryLineManager!.StoryLineData.RunningStoryLines.Keys.Select(x => (uint)x) } - }; + CurStoryLineId = (uint)player.StoryLineManager!.StoryLineData.CurStoryLineId, + RunningStoryLineIdList = + { player.StoryLineManager!.StoryLineData.RunningStoryLines.Keys.Select(x => (uint)x) } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketMissionAcceptScNotify.cs b/GameServer/Server/Packet/Send/Mission/PacketMissionAcceptScNotify.cs index f18f64e7..c566e1c0 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketMissionAcceptScNotify.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketMissionAcceptScNotify.cs @@ -1,22 +1,18 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; + +public class PacketMissionAcceptScNotify : BasePacket { - public class PacketMissionAcceptScNotify : BasePacket + public PacketMissionAcceptScNotify(int missionId) : this([missionId]) { - public PacketMissionAcceptScNotify(int missionId) : this([missionId]) - { - } - - public PacketMissionAcceptScNotify(List missionIds) : base(CmdIds.MissionAcceptScNotify) - { - var proto = new MissionAcceptScNotify(); - foreach (var missionId in missionIds) - { - proto.SubMissionIdList.Add((uint)missionId); - } - - SetData(proto); - } } -} + + public PacketMissionAcceptScNotify(List missionIds) : base(CmdIds.MissionAcceptScNotify) + { + var proto = new MissionAcceptScNotify(); + foreach (var missionId in missionIds) proto.SubMissionIdList.Add((uint)missionId); + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketMissionRewardScNotify.cs b/GameServer/Server/Packet/Send/Mission/PacketMissionRewardScNotify.cs index 7329a6a0..57b0d352 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketMissionRewardScNotify.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketMissionRewardScNotify.cs @@ -1,19 +1,19 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission -{ - public class PacketMissionRewardScNotify : BasePacket - { - public PacketMissionRewardScNotify(int mainMissionId, int subMissionId, ItemList item) : base(CmdIds.MissionRewardScNotify) - { - var proto = new MissionRewardScNotify - { - MainMissionId = (uint)mainMissionId, - SubMissionId = (uint)subMissionId, - Reward = item - }; +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; - SetData(proto); - } +public class PacketMissionRewardScNotify : BasePacket +{ + public PacketMissionRewardScNotify(int mainMissionId, int subMissionId, ItemList item) : base( + CmdIds.MissionRewardScNotify) + { + var proto = new MissionRewardScNotify + { + MainMissionId = (uint)mainMissionId, + SubMissionId = (uint)subMissionId, + Reward = item + }; + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketStartFinishMainMissionScNotify.cs b/GameServer/Server/Packet/Send/Mission/PacketStartFinishMainMissionScNotify.cs index 7f4209cc..cff99b7a 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketStartFinishMainMissionScNotify.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketStartFinishMainMissionScNotify.cs @@ -1,17 +1,16 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission -{ - public class PacketStartFinishMainMissionScNotify : BasePacket - { - public PacketStartFinishMainMissionScNotify(int missionId) : base(CmdIds.StartFinishMainMissionScNotify) - { - var proto = new StartFinishMainMissionScNotify() - { - MainMissionId = (uint)missionId, - }; +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; - SetData(proto); - } +public class PacketStartFinishMainMissionScNotify : BasePacket +{ + public PacketStartFinishMainMissionScNotify(int missionId) : base(CmdIds.StartFinishMainMissionScNotify) + { + var proto = new StartFinishMainMissionScNotify + { + MainMissionId = (uint)missionId + }; + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketStartFinishSubMissionScNotify.cs b/GameServer/Server/Packet/Send/Mission/PacketStartFinishSubMissionScNotify.cs index 0e8ff018..5d20a051 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketStartFinishSubMissionScNotify.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketStartFinishSubMissionScNotify.cs @@ -1,17 +1,16 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Mission -{ - public class PacketStartFinishSubMissionScNotify : BasePacket - { - public PacketStartFinishSubMissionScNotify(int missionId) : base(CmdIds.StartFinishSubMissionScNotify) - { - var proto = new StartFinishSubMissionScNotify() - { - SubMissionId = (uint)missionId, - }; +namespace EggLink.DanhengServer.Server.Packet.Send.Mission; - SetData(proto); - } +public class PacketStartFinishSubMissionScNotify : BasePacket +{ + public PacketStartFinishSubMissionScNotify(int missionId) : base(CmdIds.StartFinishSubMissionScNotify) + { + var proto = new StartFinishSubMissionScNotify + { + SubMissionId = (uint)missionId + }; + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketStoryLineInfoScNotify.cs b/GameServer/Server/Packet/Send/Mission/PacketStoryLineInfoScNotify.cs index 96309325..307db041 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketStoryLineInfoScNotify.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketStoryLineInfoScNotify.cs @@ -1,41 +1,31 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Database.Mission; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission; + +public class PacketStoryLineInfoScNotify : BasePacket { - public class PacketStoryLineInfoScNotify : BasePacket + public PacketStoryLineInfoScNotify(PlayerInstance player) : base(CmdIds.StoryLineInfoScNotify) { - public PacketStoryLineInfoScNotify(PlayerInstance player) : base(CmdIds.StoryLineInfoScNotify) + var storyLineIdList = + player.StoryLineManager?.StoryLineData.RunningStoryLines.Keys.Select(x => (uint)x).ToList(); + storyLineIdList?.Insert(0, 0); + + var proto = new StoryLineInfoScNotify { - var storyLineIdList = player.StoryLineManager?.StoryLineData.RunningStoryLines.Keys.Select(x => (uint)x).ToList(); - storyLineIdList?.Insert(0, 0); + CurStoryLineId = (uint)(player.StoryLineManager?.StoryLineData.CurStoryLineId ?? 0), + RunningStoryLineIdList = { storyLineIdList } + }; - var proto = new StoryLineInfoScNotify - { - CurStoryLineId = (uint)(player.StoryLineManager?.StoryLineData.CurStoryLineId ?? 0), - RunningStoryLineIdList = { storyLineIdList }, - }; + if (!proto.RunningStoryLineIdList.Contains(proto.CurStoryLineId)) + proto.RunningStoryLineIdList.Add(proto.CurStoryLineId); - if (!proto.RunningStoryLineIdList.Contains(proto.CurStoryLineId)) - { - proto.RunningStoryLineIdList.Add(proto.CurStoryLineId); - } + GameData.StroyLineTrialAvatarDataData.TryGetValue(player.StoryLineManager!.StoryLineData.CurStoryLineId, + out var storyExcel); + if (storyExcel != null) proto.TrialAvatarIdList.AddRange(storyExcel.InitTrialAvatarList.Select(x => (uint)x)); - GameData.StroyLineTrialAvatarDataData.TryGetValue(player.StoryLineManager!.StoryLineData.CurStoryLineId, out var storyExcel); - if (storyExcel != null) - { - proto.TrialAvatarIdList.AddRange(storyExcel.InitTrialAvatarList.Select(x => (uint) x)); - } - - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Mission/PacketUpdateTrackMainMissionIdScRsp.cs b/GameServer/Server/Packet/Send/Mission/PacketUpdateTrackMainMissionIdScRsp.cs index c12872f5..41b82901 100644 --- a/GameServer/Server/Packet/Send/Mission/PacketUpdateTrackMainMissionIdScRsp.cs +++ b/GameServer/Server/Packet/Send/Mission/PacketUpdateTrackMainMissionIdScRsp.cs @@ -1,24 +1,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Mission; + +public class PacketUpdateTrackMainMissionIdScRsp : BasePacket { - public class PacketUpdateTrackMainMissionIdScRsp : BasePacket + public PacketUpdateTrackMainMissionIdScRsp(int prev, int cur) : base(CmdIds.UpdateTrackMainMissionIdScRsp) { - public PacketUpdateTrackMainMissionIdScRsp(int prev, int cur) : base(CmdIds.UpdateTrackMainMissionIdScRsp) + var proto = new UpdateTrackMainMissionIdScRsp { - var proto = new UpdateTrackMainMissionIdScRsp() - { - PrevTrackMissionId = (uint)prev, - TrackMissionId = (uint)cur - }; + PrevTrackMissionId = (uint)prev, + TrackMissionId = (uint)cur + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Others/PacketClientDownloadDataScNotify.cs b/GameServer/Server/Packet/Send/Others/PacketClientDownloadDataScNotify.cs index 4d610c36..76833a32 100644 --- a/GameServer/Server/Packet/Send/Others/PacketClientDownloadDataScNotify.cs +++ b/GameServer/Server/Packet/Send/Others/PacketClientDownloadDataScNotify.cs @@ -1,33 +1,28 @@ - -using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Util; +using EggLink.DanhengServer.Proto; using Google.Protobuf; -using System; -namespace EggLink.DanhengServer.Server.Packet.Send.Others +namespace EggLink.DanhengServer.Server.Packet.Send.Others; + +public class PacketClientDownloadDataScNotify : BasePacket { - public class PacketClientDownloadDataScNotify : BasePacket + public PacketClientDownloadDataScNotify(byte[] data) : base(CmdIds.ClientDownloadDataScNotify) { - public PacketClientDownloadDataScNotify(byte[] data) : base(CmdIds.ClientDownloadDataScNotify) + var downloadData = new ClientDownloadData { - var downloadData = new ClientDownloadData - { - Data = ByteString.CopyFrom(data), - Version = 81, - Time = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds - }; - var notify = new ClientDownloadDataScNotify - { - DownloadData = downloadData - }; - - SetData(notify); - } - - public PacketClientDownloadDataScNotify(string base64) : base(CmdIds.ClientDownloadDataScNotify) + Data = ByteString.CopyFrom(data), + Version = 81, + Time = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds + }; + var notify = new ClientDownloadDataScNotify { - SetData(Convert.FromBase64String(base64)); - } + DownloadData = downloadData + }; + + SetData(notify); } -} + + public PacketClientDownloadDataScNotify(string base64) : base(CmdIds.ClientDownloadDataScNotify) + { + SetData(Convert.FromBase64String(base64)); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Others/PacketGetSecretKeyInfoScRsp.cs b/GameServer/Server/Packet/Send/Others/PacketGetSecretKeyInfoScRsp.cs index c16324b3..424353e3 100644 --- a/GameServer/Server/Packet/Send/Others/PacketGetSecretKeyInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Others/PacketGetSecretKeyInfoScRsp.cs @@ -1,19 +1,18 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Others -{ - public class PacketGetSecretKeyInfoScRsp : BasePacket - { - public PacketGetSecretKeyInfoScRsp() : base(CmdIds.GetSecretKeyInfoScRsp) - { - var proto = new GetSecretKeyInfoScRsp(); - proto.SecretInfo.Add(new SecretKeyInfo() - { - Type = SecretKeyType.SecretKeyVideo, - Key = "10120425825329403", - }); +namespace EggLink.DanhengServer.Server.Packet.Send.Others; - SetData(proto); - } +public class PacketGetSecretKeyInfoScRsp : BasePacket +{ + public PacketGetSecretKeyInfoScRsp() : base(CmdIds.GetSecretKeyInfoScRsp) + { + var proto = new GetSecretKeyInfoScRsp(); + proto.SecretInfo.Add(new SecretKeyInfo + { + Type = SecretKeyType.SecretKeyVideo, + Key = "10120425825329403" + }); + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Others/PacketGetVideoVersionKeyScRsp.cs b/GameServer/Server/Packet/Send/Others/PacketGetVideoVersionKeyScRsp.cs index b04c0cf0..108e9e38 100644 --- a/GameServer/Server/Packet/Send/Others/PacketGetVideoVersionKeyScRsp.cs +++ b/GameServer/Server/Packet/Send/Others/PacketGetVideoVersionKeyScRsp.cs @@ -1,17 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EggLink.DanhengServer.Server.Packet.Send.Others; -namespace EggLink.DanhengServer.Server.Packet.Send.Others +public class PacketGetVideoVersionKeyScRsp : BasePacket { - public class PacketGetVideoVersionKeyScRsp : BasePacket + public PacketGetVideoVersionKeyScRsp() : base(CmdIds.GetVideoVersionKeyScRsp) { - public PacketGetVideoVersionKeyScRsp() : base(CmdIds.GetVideoVersionKeyScRsp) - { - // FIND A BETTER WAY - SetData(Convert.FromBase64String("Og0w+hpQ5q6Sr4e5nKYDOg0w8BpQwaWAjqjCtJoDOg0w5hpQxP35pZvryZwDOgww3xpQquDurbX3gg86DDDeGlDz9pPQqqfbCToMMN0aULbL0frc+NkJOg0w3BpQq77L1dzVqZUDOg0wyBpQ1N6A+oi225EDOg0wtBpQjbWM8KHVh5IDOg0wqhpQ8Zewn/W4yJYDOg0woBpQ3tbX/OGWs4oDOg0wlhpQrt3jwdf6tI0DOg0wjBpQvuKnxKuVhIoDOg0wghpQ7c7U+ZvG8pADOg0w+BlQmaC8qNnn1IkDOg0w5BlQn/WSvMzakJIDOg0w4BlQxKrBxd+nvpEDOg0w3RlQ1ey2uKmHwo0DOg0w3BlQyo3a2sWH9JADOg0w2xlQhZfKwtX24ogDOg0w2hlQgbb/xo/Eto0DOgww0BlQ662Xn6S4xgQ6DDDGGVCNhpyp2ffiDzoMMLwZUJPO/aun+NwDOggwiBNQ/9KCKzoIMPQSUP/Sgis6CDDGCVCq++MGOggwlBRQ47/qBToNMNIaUOa7lub+ysmSAzoIMMUJUKr74wY6CDDEGFDv5tIJOggw7BhQ8ebSCToIMKYJUKr74wY6CDC6GFCs5dIJOggw2BhQrOXSCToIMJIJUKr74wY6CDCmGFCs5dIJOggwpANQ4dTeBzoNMN4ZUJHxvNDak9uRAzoIMJgKUPLEpwY6CDDqF1Cs5dIJOggwmwNQ4dTeBzoIMNYXUO7OoQc6CDCaA1Dh1N4HOggwhgNQ4dTeBzoIMJADUOHU3gc6BzACUPfL2xw6CDDAAlCnt60FOggw2AlQqvvjBjoMMJ4ZUOfg6obxyewCOggwkhNQ99KCKzoHMGRQyb/qBToHMANQ/9TVHToIMMIXUO7OoQc6CDDlGVD25tIJOgcwZVDJv+oFOgcwBFD/1NUdOggwoBVQ7s6hBzoIMOYZUPbm0gk6CDDICVCq++MGOggw8gJQ4dTeBzoIMMcJUKr74wY6CDDeAlDh1N4HOggwygJQ4dTeBzoMMKgZUL6TqKS0s9sJOgcwAVD3y9scOggwvBRQisSnBjoIMIIVUO7OoQc6CDCuAlCQ1N4HOggwxhRQl8SnBjoIMJwTUP/Sgis6CDCwGFCs5dIJOggwzhhQrOXSCToIMIgJULf9+iE6CDCcGFDv5tIJOgcwBVD/1NUdOgcwFVD/+L0hOggw0BRQqvvjBjoIMJwJUKr74wY6CDDiGFCs5dIJOgcwCFD3+L0hOggw4hNQp7etBToNMN8ZULGllKGf/LiVAzoIMLYCUL/9+iE6CDDOCVCq++MGOgwwlBlQkIOzmr6m/Qw6CDDUAlDh1N4HOgwwshlQhae12uTSmws6CDDoAlDh1N4HOggw/AJQ4dTeBzoIMLATUP/Sgis6CDCtAlCQ1N4HOgcwZlDJv+oFOggwuhNQ/9KCKzoIMOkCUOHU3gc6CDD2E1Djv+oFOggwgBRQ/b7qBToIMIoUUP2+6gU6CDDkFFDuzqEHOggw7hRQ7s6hBzoIMPgUUO7OoQc6DTDhGVDU/JbYqtHikQM6CDD+EVDyxKcGOggwjBVQus+hBzoNMOIZUOC/pdj08rKPAzoIMI0VUO7OoQc6CDCWFVDuzqEHOggwqhVQisSnBjoIMLQVUIrEpwY6CDC+FVCKxKcGOggwyBVQisSnBjoIMMwXUO7OoQc6CDDgF1Cs5dIJOggw9BdQ7+bSCToIMP4XUKzl0gk6CDCIGFCs5dIJOggwkhhQrOXSCToIMLAJUKr74wY6DDD2GFCcx/ua8+GoDDoNML4aUPuNjOrRnsCJAzoHMAdQ/9TVHToMMPcYUP76pYzViJEQOggwuglQqvvjBjoHMBBQ9/i9IToMMIAZUJSo69TlsIUQOggwxAlQqvvjBjoMMIoZUIncxaHR/aYL")); - } + // FIND A BETTER WAY + SetData(Convert.FromBase64String( + "Og0w+hpQ5q6Sr4e5nKYDOg0w8BpQwaWAjqjCtJoDOg0w5hpQxP35pZvryZwDOgww3xpQquDurbX3gg86DDDeGlDz9pPQqqfbCToMMN0aULbL0frc+NkJOg0w3BpQq77L1dzVqZUDOg0wyBpQ1N6A+oi225EDOg0wtBpQjbWM8KHVh5IDOg0wqhpQ8Zewn/W4yJYDOg0woBpQ3tbX/OGWs4oDOg0wlhpQrt3jwdf6tI0DOg0wjBpQvuKnxKuVhIoDOg0wghpQ7c7U+ZvG8pADOg0w+BlQmaC8qNnn1IkDOg0w5BlQn/WSvMzakJIDOg0w4BlQxKrBxd+nvpEDOg0w3RlQ1ey2uKmHwo0DOg0w3BlQyo3a2sWH9JADOg0w2xlQhZfKwtX24ogDOg0w2hlQgbb/xo/Eto0DOgww0BlQ662Xn6S4xgQ6DDDGGVCNhpyp2ffiDzoMMLwZUJPO/aun+NwDOggwiBNQ/9KCKzoIMPQSUP/Sgis6CDDGCVCq++MGOggwlBRQ47/qBToNMNIaUOa7lub+ysmSAzoIMMUJUKr74wY6CDDEGFDv5tIJOggw7BhQ8ebSCToIMKYJUKr74wY6CDC6GFCs5dIJOggw2BhQrOXSCToIMJIJUKr74wY6CDCmGFCs5dIJOggwpANQ4dTeBzoNMN4ZUJHxvNDak9uRAzoIMJgKUPLEpwY6CDDqF1Cs5dIJOggwmwNQ4dTeBzoIMNYXUO7OoQc6CDCaA1Dh1N4HOggwhgNQ4dTeBzoIMJADUOHU3gc6BzACUPfL2xw6CDDAAlCnt60FOggw2AlQqvvjBjoMMJ4ZUOfg6obxyewCOggwkhNQ99KCKzoHMGRQyb/qBToHMANQ/9TVHToIMMIXUO7OoQc6CDDlGVD25tIJOgcwZVDJv+oFOgcwBFD/1NUdOggwoBVQ7s6hBzoIMOYZUPbm0gk6CDDICVCq++MGOggw8gJQ4dTeBzoIMMcJUKr74wY6CDDeAlDh1N4HOggwygJQ4dTeBzoMMKgZUL6TqKS0s9sJOgcwAVD3y9scOggwvBRQisSnBjoIMIIVUO7OoQc6CDCuAlCQ1N4HOggwxhRQl8SnBjoIMJwTUP/Sgis6CDCwGFCs5dIJOggwzhhQrOXSCToIMIgJULf9+iE6CDCcGFDv5tIJOgcwBVD/1NUdOgcwFVD/+L0hOggw0BRQqvvjBjoIMJwJUKr74wY6CDDiGFCs5dIJOgcwCFD3+L0hOggw4hNQp7etBToNMN8ZULGllKGf/LiVAzoIMLYCUL/9+iE6CDDOCVCq++MGOgwwlBlQkIOzmr6m/Qw6CDDUAlDh1N4HOgwwshlQhae12uTSmws6CDDoAlDh1N4HOggw/AJQ4dTeBzoIMLATUP/Sgis6CDCtAlCQ1N4HOgcwZlDJv+oFOggwuhNQ/9KCKzoIMOkCUOHU3gc6CDD2E1Djv+oFOggwgBRQ/b7qBToIMIoUUP2+6gU6CDDkFFDuzqEHOggw7hRQ7s6hBzoIMPgUUO7OoQc6DTDhGVDU/JbYqtHikQM6CDD+EVDyxKcGOggwjBVQus+hBzoNMOIZUOC/pdj08rKPAzoIMI0VUO7OoQc6CDCWFVDuzqEHOggwqhVQisSnBjoIMLQVUIrEpwY6CDC+FVCKxKcGOggwyBVQisSnBjoIMMwXUO7OoQc6CDDgF1Cs5dIJOggw9BdQ7+bSCToIMP4XUKzl0gk6CDCIGFCs5dIJOggwkhhQrOXSCToIMLAJUKr74wY6DDD2GFCcx/ua8+GoDDoNML4aUPuNjOrRnsCJAzoHMAdQ/9TVHToMMPcYUP76pYzViJEQOggwuglQqvvjBjoHMBBQ9/i9IToMMIAZUJSo69TlsIUQOggwxAlQqvvjBjoMMIoZUIncxaHR/aYL")); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Others/PacketRetcodeNotify.cs b/GameServer/Server/Packet/Send/Others/PacketRetcodeNotify.cs index 20d5beb3..fea20974 100644 --- a/GameServer/Server/Packet/Send/Others/PacketRetcodeNotify.cs +++ b/GameServer/Server/Packet/Send/Others/PacketRetcodeNotify.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Others +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Others; + +public class PacketRetcodeNotify : BasePacket { - public class PacketRetcodeNotify : BasePacket + public PacketRetcodeNotify(Retcode retcode) : base(CmdIds.RetcodeNotify) { - public PacketRetcodeNotify(Retcode retcode) : base(CmdIds.RetcodeNotify) + var proto = new RetcodeNotify { - var proto = new RetcodeNotify - { - Retcode = retcode // original proto is uint, i modify it to Retcode enum - }; + Retcode = retcode // original proto is uint, i modify it to Retcode enum + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Others/PacketServerAnnounceNotify.cs b/GameServer/Server/Packet/Send/Others/PacketServerAnnounceNotify.cs index f3e4d277..ab4a4e58 100644 --- a/GameServer/Server/Packet/Send/Others/PacketServerAnnounceNotify.cs +++ b/GameServer/Server/Packet/Send/Others/PacketServerAnnounceNotify.cs @@ -1,31 +1,22 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Others +namespace EggLink.DanhengServer.Server.Packet.Send.Others; + +public class PacketServerAnnounceNotify : BasePacket { - public class PacketServerAnnounceNotify : BasePacket + public PacketServerAnnounceNotify() : base(CmdIds.ServerAnnounceNotify) { - public PacketServerAnnounceNotify() : base(CmdIds.ServerAnnounceNotify) + var proto = new ServerAnnounceNotify(); + + proto.AnnounceDataList.Add(new AnnounceData { - var proto = new ServerAnnounceNotify(); + BeginTime = Extensions.GetUnixSec(), + EndTime = Extensions.GetUnixSec() + 3600, + ConfigId = 1, + CHJPFPLHJBJ = ConfigManager.Config.ServerOption.ServerAnnounce.AnnounceContent + }); - proto.AnnounceDataList.Add(new AnnounceData() - { - BeginTime = Extensions.GetUnixSec(), - EndTime = Extensions.GetUnixSec() + 3600, - ConfigId = 1, - CHJPFPLHJBJ = ConfigManager.Config.ServerOption.ServerAnnounce.AnnounceContent, - }); - - if (ConfigManager.Config.ServerOption.ServerAnnounce.EnableAnnounce) - { - SetData(proto); - } - } + if (ConfigManager.Config.ServerOption.ServerAnnounce.EnableAnnounce) SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketDeployRotaterScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketDeployRotaterScRsp.cs index 0ce0e951..8811a241 100644 --- a/GameServer/Server/Packet/Send/Player/PacketDeployRotaterScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketDeployRotaterScRsp.cs @@ -1,27 +1,21 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketDeployRotaterScRsp : BasePacket { - public class PacketDeployRotaterScRsp : BasePacket + public PacketDeployRotaterScRsp(RotaterData rotaterData, int curNum, int maxNum) : base(CmdIds.DeployRotaterScRsp) { - public PacketDeployRotaterScRsp(RotaterData rotaterData, int curNum, int maxNum) : base(CmdIds.DeployRotaterScRsp) + var proto = new DeployRotaterScRsp { - var proto = new DeployRotaterScRsp() + EnergyInfo = new RotatorEnergyInfo { - EnergyInfo = new RotatorEnergyInfo() - { - MaxNum = (uint)maxNum, - CurNum = (uint)curNum, - }, - RotaterData = rotaterData - }; + MaxNum = (uint)maxNum, + CurNum = (uint)curNum + }, + RotaterData = rotaterData + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketGetArchiveDataScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketGetArchiveDataScRsp.cs index 2eb18ca0..bcca1a44 100644 --- a/GameServer/Server/Packet/Send/Player/PacketGetArchiveDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketGetArchiveDataScRsp.cs @@ -1,49 +1,43 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketGetArchiveDataScRsp : BasePacket { - public class PacketGetArchiveDataScRsp : BasePacket + public PacketGetArchiveDataScRsp() : base(CmdIds.GetArchiveDataScRsp) { - public PacketGetArchiveDataScRsp() : base(CmdIds.GetArchiveDataScRsp) + var proto = new GetArchiveDataScRsp(); + + var info = new ArchiveData(); + + GameData.MonsterConfigData.Values.ToList().ForEach(monster => { - var proto = new GetArchiveDataScRsp(); - - var info = new ArchiveData(); - - GameData.MonsterConfigData.Values.ToList().ForEach(monster => + info.ArchiveMonsterIdList.Add(new ArchiveMonsterId { - info.ArchiveMonsterIdList.Add(new ArchiveMonsterId() - { - MonsterId = (uint)monster.GetId(), - Num = 1 - }); + MonsterId = (uint)monster.GetId(), + Num = 1 }); + }); - info.ArchiveAvatarIdList.Add(23027); + info.ArchiveAvatarIdList.Add(23027); - GameData.EquipmentConfigData.Values.ToList().ForEach(equipment => + GameData.EquipmentConfigData.Values.ToList().ForEach(equipment => + { + info.ArchiveEquipmentIdList.Add((uint)equipment.GetId()); + }); + + GameData.RelicConfigData.Values.ToList().ForEach(relic => + { + info.RelicList.Add(new RelicList { - info.ArchiveEquipmentIdList.Add((uint)equipment.GetId()); + SetId = (uint)relic.ID, + Type = (uint)relic.Type }); + }); - GameData.RelicConfigData.Values.ToList().ForEach(relic => - { - info.RelicList.Add(new RelicList() - { - SetId = (uint)relic.ID, - Type = (uint)relic.Type, - }); - }); + proto.ArchiveInfo = info; - proto.ArchiveInfo = info; - - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketGetBagScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketGetBagScRsp.cs index 806005d9..6a490357 100644 --- a/GameServer/Server/Packet/Send/Player/PacketGetBagScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketGetBagScRsp.cs @@ -1,30 +1,26 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketGetBagScRsp : BasePacket { - public class PacketGetBagScRsp : BasePacket + public PacketGetBagScRsp(PlayerInstance player) : base(CmdIds.GetBagScRsp) { - public PacketGetBagScRsp(PlayerInstance player) : base(CmdIds.GetBagScRsp) + var proto = new GetBagScRsp(); + + player.InventoryManager!.Data.MaterialItems.ForEach(item => { - var proto = new GetBagScRsp(); + proto.MaterialList.Add(item.ToMaterialProto()); + }); - player.InventoryManager!.Data.MaterialItems.ForEach(item => - { - proto.MaterialList.Add(item.ToMaterialProto()); - }); + player.InventoryManager.Data.RelicItems.ForEach(item => { proto.RelicList.Add(item.ToRelicProto()); }); - player.InventoryManager.Data.RelicItems.ForEach(item => - { - proto.RelicList.Add(item.ToRelicProto()); - }); + player.InventoryManager.Data.EquipmentItems.ForEach(item => + { + proto.EquipmentList.Add(item.ToEquipmentProto()); + }); - player.InventoryManager.Data.EquipmentItems.ForEach(item => - { - proto.EquipmentList.Add(item.ToEquipmentProto()); - }); - - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketGetBasicInfoScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketGetBasicInfoScRsp.cs index 927f4bfa..4d449cb0 100644 --- a/GameServer/Server/Packet/Send/Player/PacketGetBasicInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketGetBasicInfoScRsp.cs @@ -1,26 +1,20 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketGetBasicInfoScRsp : BasePacket { - public class PacketGetBasicInfoScRsp : BasePacket + public PacketGetBasicInfoScRsp(PlayerInstance player) : base(CmdIds.GetBasicInfoScRsp) { - public PacketGetBasicInfoScRsp(PlayerInstance player) : base(CmdIds.GetBasicInfoScRsp) + var proto = new GetBasicInfoScRsp { - var proto = new GetBasicInfoScRsp() - { - CurDay = 1, - NextRecoverTime = player.Data.NextStaminaRecover / 1000, - GameplayBirthday = (uint)player.Data.Birthday, - PlayerSettingInfo = new(), - }; + CurDay = 1, + NextRecoverTime = player.Data.NextStaminaRecover / 1000, + GameplayBirthday = (uint)player.Data.Birthday, + PlayerSettingInfo = new PlayerSettingInfo() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketGetJukeboxDataScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketGetJukeboxDataScRsp.cs index 31e2c7ba..94b61ebd 100644 --- a/GameServer/Server/Packet/Send/Player/PacketGetJukeboxDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketGetJukeboxDataScRsp.cs @@ -1,34 +1,26 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketGetJukeboxDataScRsp : BasePacket { - public class PacketGetJukeboxDataScRsp : BasePacket + public PacketGetJukeboxDataScRsp(PlayerInstance player) : base(CmdIds.GetJukeboxDataScRsp) { - public PacketGetJukeboxDataScRsp(PlayerInstance player) : base(CmdIds.GetJukeboxDataScRsp) + var proto = new GetJukeboxDataScRsp { - var proto = new GetJukeboxDataScRsp - { - CurrentMusicId = (uint)player.Data.CurrentBgm, - }; + CurrentMusicId = (uint)player.Data.CurrentBgm + }; - foreach (var music in GameData.BackGroundMusicData.Values) + foreach (var music in GameData.BackGroundMusicData.Values) + proto.UnlockedMusicList.Add(new MusicData { - proto.UnlockedMusicList.Add(new MusicData() - { - Id = (uint)music.ID, - GroupId = (uint)music.GroupID, - IsPlayed = true - }); - } + Id = (uint)music.ID, + GroupId = (uint)music.GroupID, + IsPlayed = true + }); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketGetPhoneDataScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketGetPhoneDataScRsp.cs index ea7164b3..10bb4e62 100644 --- a/GameServer/Server/Packet/Send/Player/PacketGetPhoneDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketGetPhoneDataScRsp.cs @@ -1,40 +1,26 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketGetPhoneDataScRsp : BasePacket { - public class PacketGetPhoneDataScRsp : BasePacket + public PacketGetPhoneDataScRsp(PlayerInstance player) : base(CmdIds.GetPhoneDataScRsp) { - public PacketGetPhoneDataScRsp(PlayerInstance player) : base(CmdIds.GetPhoneDataScRsp) + if (!GameData.ChatBubbleConfigData.ContainsKey(player.Data.ChatBubble)) // to avoid npe + player.Data.ChatBubble = 220000; + + var proto = new GetPhoneDataScRsp { - if (!GameData.ChatBubbleConfigData.ContainsKey(player.Data.ChatBubble)) // to avoid npe - { - player.Data.ChatBubble = 220000; - } + CurChatBubble = (uint)player.Data.ChatBubble, + CurPhoneTheme = (uint)player.Data.PhoneTheme + }; - var proto = new GetPhoneDataScRsp - { - CurChatBubble = (uint)player.Data.ChatBubble, - CurPhoneTheme = (uint)player.Data.PhoneTheme, - }; + foreach (var item in player.PlayerUnlockData!.PhoneThemes) proto.OwnedPhoneThemes.Add((uint)item); - foreach (var item in player.PlayerUnlockData!.PhoneThemes) - { - proto.OwnedPhoneThemes.Add((uint)item); - } + foreach (var item in player.PlayerUnlockData!.ChatBubbles) proto.OwnedChatBubbles.Add((uint)item); - foreach (var item in player.PlayerUnlockData!.ChatBubbles) - { - proto.OwnedChatBubbles.Add((uint)item); - } - - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketGetPlayerBoardDataScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketGetPlayerBoardDataScRsp.cs index 87d1c3ac..2310dfa8 100644 --- a/GameServer/Server/Packet/Send/Player/PacketGetPlayerBoardDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketGetPlayerBoardDataScRsp.cs @@ -1,38 +1,37 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketGetPlayerBoardDataScRsp : BasePacket { - public class PacketGetPlayerBoardDataScRsp : BasePacket + public PacketGetPlayerBoardDataScRsp(PlayerInstance player) : base(CmdIds.GetPlayerBoardDataScRsp) { - public PacketGetPlayerBoardDataScRsp(PlayerInstance player) : base(CmdIds.GetPlayerBoardDataScRsp) + var proto = new GetPlayerBoardDataScRsp { - var proto = new GetPlayerBoardDataScRsp() + CurrentHeadIconId = (uint)player.Data.HeadIcon, + Signature = player.Data.Signature + }; + + player.PlayerUnlockData?.HeadIcons.ForEach(id => + { + HeadIconData headIcon = new() { Id = (uint)id }; + proto.UnlockedHeadIconList.Add(headIcon); + }); + + proto.DisplayAvatarVec = new DisplayAvatarVec(); + var pos = 0; + player.AvatarManager?.AvatarData!.DisplayAvatars.ForEach(avatar => + { + DisplayAvatarData displayAvatar = new() { - CurrentHeadIconId = (uint)player.Data.HeadIcon, - Signature = player.Data.Signature, + AvatarId = (uint)avatar, + Pos = (uint)pos++ }; + proto.DisplayAvatarVec.DisplayAvatarList.Add(displayAvatar); + }); + player.AvatarManager?.AvatarData!.AssistAvatars.ForEach(x => proto.AssistAvatarIdList.Add((uint)x)); - player.PlayerUnlockData?.HeadIcons.ForEach(id => - { - HeadIconData headIcon = new() { Id = (uint)id }; - proto.UnlockedHeadIconList.Add(headIcon); - }); - - proto.DisplayAvatarVec = new(); - var pos = 0; - player.AvatarManager?.AvatarData!.DisplayAvatars.ForEach(avatar => - { - DisplayAvatarData displayAvatar = new() - { - AvatarId = (uint)avatar, - Pos = (uint)pos++, - }; - proto.DisplayAvatarVec.DisplayAvatarList.Add(displayAvatar); - }); - player.AvatarManager?.AvatarData!.AssistAvatars.ForEach(x => proto.AssistAvatarIdList.Add((uint)x)); - - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketInteractChargerScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketInteractChargerScRsp.cs index 1bf764bd..2cb748a6 100644 --- a/GameServer/Server/Packet/Send/Player/PacketInteractChargerScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketInteractChargerScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketInteractChargerScRsp : BasePacket { - public class PacketInteractChargerScRsp : BasePacket + public PacketInteractChargerScRsp(ChargerInfo chargerInfo) : base(CmdIds.InteractChargerScRsp) { - public PacketInteractChargerScRsp(ChargerInfo chargerInfo) : base(CmdIds.InteractChargerScRsp) + var proto = new InteractChargerScRsp { - var proto = new InteractChargerScRsp() - { - ChargerInfo = chargerInfo - }; + ChargerInfo = chargerInfo + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketPlayBackGroundMusicScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketPlayBackGroundMusicScRsp.cs index 835a39cc..df5d86a4 100644 --- a/GameServer/Server/Packet/Send/Player/PacketPlayBackGroundMusicScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketPlayBackGroundMusicScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketPlayBackGroundMusicScRsp : BasePacket { - public class PacketPlayBackGroundMusicScRsp : BasePacket + public PacketPlayBackGroundMusicScRsp(uint musicId) : base(CmdIds.PlayBackGroundMusicScRsp) { - public PacketPlayBackGroundMusicScRsp(uint musicId) : base(CmdIds.PlayBackGroundMusicScRsp) + var proto = new PlayBackGroundMusicScRsp { - var proto = new PlayBackGroundMusicScRsp - { - PlayMusicId = musicId, - CurrentMusicId = musicId - }; + PlayMusicId = musicId, + CurrentMusicId = musicId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketPlayerGetTokenScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketPlayerGetTokenScRsp.cs index 10e3a7a5..3be0f90c 100644 --- a/GameServer/Server/Packet/Send/Player/PacketPlayerGetTokenScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketPlayerGetTokenScRsp.cs @@ -1,27 +1,27 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketPlayerGetTokenScRsp : BasePacket { - public class PacketPlayerGetTokenScRsp : BasePacket + public PacketPlayerGetTokenScRsp(Connection connection) : base(CmdIds.PlayerGetTokenScRsp) { - public PacketPlayerGetTokenScRsp(Connection connection) : base(CmdIds.PlayerGetTokenScRsp) + var rsp = new PlayerGetTokenScRsp { - var rsp = new PlayerGetTokenScRsp() - { - BlackInfo = new(), - Uid = (uint)(connection.Player?.Uid ?? 0), - }; + BlackInfo = new BlackInfo(), + Uid = (uint)(connection.Player?.Uid ?? 0) + }; - SetData(rsp); - } - public PacketPlayerGetTokenScRsp() : base(CmdIds.PlayerGetTokenScRsp) - { - var rsp = new PlayerGetTokenScRsp() - { - Retcode = 0, - }; - - SetData(rsp); - } + SetData(rsp); } -} + + public PacketPlayerGetTokenScRsp() : base(CmdIds.PlayerGetTokenScRsp) + { + var rsp = new PlayerGetTokenScRsp + { + Retcode = 0 + }; + + SetData(rsp); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketPlayerHeartBeatScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketPlayerHeartBeatScRsp.cs index 3af0a6c6..310c92ca 100644 --- a/GameServer/Server/Packet/Send/Player/PacketPlayerHeartBeatScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketPlayerHeartBeatScRsp.cs @@ -1,24 +1,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketPlayerHeartBeatScRsp : BasePacket { - public class PacketPlayerHeartBeatScRsp : BasePacket + public PacketPlayerHeartBeatScRsp(long clientTime) : base(CmdIds.PlayerHeartBeatScRsp) { - public PacketPlayerHeartBeatScRsp(long clientTime) : base(CmdIds.PlayerHeartBeatScRsp) + var data = new PlayerHeartBeatScRsp { - var data = new PlayerHeartBeatScRsp() - { - ClientTimeMs = (ulong)clientTime, - ServerTimeMs = (ulong)Extensions.GetUnixMs(), - }; + ClientTimeMs = (ulong)clientTime, + ServerTimeMs = (ulong)Extensions.GetUnixMs() + }; - SetData(data); - } + SetData(data); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketPlayerKickOutScNotify.cs b/GameServer/Server/Packet/Send/Player/PacketPlayerKickOutScNotify.cs index 3662ea25..c3084b1d 100644 --- a/GameServer/Server/Packet/Send/Player/PacketPlayerKickOutScNotify.cs +++ b/GameServer/Server/Packet/Send/Player/PacketPlayerKickOutScNotify.cs @@ -1,16 +1,15 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketPlayerKickOutScNotify : BasePacket { - public class PacketPlayerKickOutScNotify : BasePacket + public PacketPlayerKickOutScNotify() : base(CmdIds.PlayerKickOutScNotify) { - public PacketPlayerKickOutScNotify() : base(CmdIds.PlayerKickOutScNotify) + var proto = new PlayerKickOutScNotify { - var proto = new PlayerKickOutScNotify() - { - KickType = KickType.KickSqueezed, - }; - SetData(proto); - } + KickType = KickType.KickSqueezed + }; + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketPlayerLoginScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketPlayerLoginScRsp.cs index e8bff12d..595b4b64 100644 --- a/GameServer/Server/Packet/Send/Player/PacketPlayerLoginScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketPlayerLoginScRsp.cs @@ -1,27 +1,20 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Policy; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketPlayerLoginScRsp : BasePacket { - public class PacketPlayerLoginScRsp : BasePacket + public PacketPlayerLoginScRsp(Connection connection) : base(CmdIds.PlayerLoginScRsp) { - public PacketPlayerLoginScRsp(Connection connection) : base(CmdIds.PlayerLoginScRsp) + var rsp = new PlayerLoginScRsp { - var rsp = new PlayerLoginScRsp() - { - CurTimezone = (int)TimeZoneInfo.Local.BaseUtcOffset.TotalHours, - ServerTimestampMs = (ulong)Extensions.GetUnixMs(), - BasicInfo = connection?.Player?.ToProto(), // should not be null - Stamina = (uint)(connection?.Player?.Data.Stamina ?? 0), - }; + CurTimezone = (int)TimeZoneInfo.Local.BaseUtcOffset.TotalHours, + ServerTimestampMs = (ulong)Extensions.GetUnixMs(), + BasicInfo = connection?.Player?.ToProto(), // should not be null + Stamina = (uint)(connection?.Player?.Data.Stamina ?? 0) + }; - SetData(rsp); - } + SetData(rsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketPlayerSyncScNotify.cs b/GameServer/Server/Packet/Send/Player/PacketPlayerSyncScNotify.cs index 47855bc1..33281c9f 100644 --- a/GameServer/Server/Packet/Send/Player/PacketPlayerSyncScNotify.cs +++ b/GameServer/Server/Packet/Send/Player/PacketPlayerSyncScNotify.cs @@ -4,162 +4,132 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Database.Message; using EggLink.DanhengServer.Enums.Item; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketPlayerSyncScNotify : BasePacket { - public class PacketPlayerSyncScNotify : BasePacket + public PacketPlayerSyncScNotify(ItemData item) : base(CmdIds.PlayerSyncScNotify) { - public PacketPlayerSyncScNotify(ItemData item) : base(CmdIds.PlayerSyncScNotify) - { - var proto = new PlayerSyncScNotify(); - AddItemToProto(item, proto); - SetData(proto); - } + var proto = new PlayerSyncScNotify(); + AddItemToProto(item, proto); + SetData(proto); + } - public PacketPlayerSyncScNotify(List item) : base(CmdIds.PlayerSyncScNotify) - { - var proto = new PlayerSyncScNotify(); - foreach (var i in item) - { - AddItemToProto(i, proto); - } - SetData(proto); - } + public PacketPlayerSyncScNotify(List item) : base(CmdIds.PlayerSyncScNotify) + { + var proto = new PlayerSyncScNotify(); + foreach (var i in item) AddItemToProto(i, proto); + SetData(proto); + } - public PacketPlayerSyncScNotify(AvatarInfo avatar) : base(CmdIds.PlayerSyncScNotify) + public PacketPlayerSyncScNotify(AvatarInfo avatar) : base(CmdIds.PlayerSyncScNotify) + { + var proto = new PlayerSyncScNotify + { + AvatarSync = new AvatarSync() + }; + proto.AvatarSync.AvatarList.Add(avatar.ToProto()); + + if (avatar.HeroId > 0) proto.BasicTypeInfoList.Add(avatar.ToHeroProto()); + + SetData(proto); + } + + public PacketPlayerSyncScNotify(List avatars) : base(CmdIds.PlayerSyncScNotify) + { + var proto = new PlayerSyncScNotify + { + AvatarSync = new AvatarSync() + }; + + foreach (var avatar in avatars) { - var proto = new PlayerSyncScNotify - { - AvatarSync = new() - }; proto.AvatarSync.AvatarList.Add(avatar.ToProto()); - - if (avatar.HeroId > 0) - { - proto.BasicTypeInfoList.Add(avatar.ToHeroProto()); - } - - SetData(proto); + if (avatar.HeroId > 0) proto.BasicTypeInfoList.Add(avatar.ToHeroProto()); } - public PacketPlayerSyncScNotify(List avatars) : base(CmdIds.PlayerSyncScNotify) + SetData(proto); + } + + public PacketPlayerSyncScNotify(AvatarInfo avatar, ItemData item) : base(CmdIds.PlayerSyncScNotify) + { + var proto = new PlayerSyncScNotify(); + AddItemToProto(item, proto); + proto.AvatarSync = new AvatarSync(); + proto.AvatarSync.AvatarList.Add(avatar.ToProto()); + + if (avatar.HeroId > 0) proto.BasicTypeInfoList.Add(avatar.ToHeroProto()); + + SetData(proto); + } + + public PacketPlayerSyncScNotify(MissionSync mission) : base(CmdIds.PlayerSyncScNotify) + { + var proto = new PlayerSyncScNotify { - var proto = new PlayerSyncScNotify - { - AvatarSync = new() - }; + MissionSync = mission + }; - foreach (var avatar in avatars) - { - proto.AvatarSync.AvatarList.Add(avatar.ToProto()); - if (avatar.HeroId > 0) - { - proto.BasicTypeInfoList.Add(avatar.ToHeroProto()); - } - } + SetData(proto); + } - SetData(proto); - } - - public PacketPlayerSyncScNotify(AvatarInfo avatar, ItemData item) : base(CmdIds.PlayerSyncScNotify) + public PacketPlayerSyncScNotify(PlayerBasicInfo info) : base(CmdIds.PlayerSyncScNotify) + { + var proto = new PlayerSyncScNotify { - var proto = new PlayerSyncScNotify(); - AddItemToProto(item, proto); - proto.AvatarSync = new(); - proto.AvatarSync.AvatarList.Add(avatar.ToProto()); + BasicInfo = info + }; - if (avatar.HeroId > 0) + SetData(proto); + } + + public PacketPlayerSyncScNotify(MessageGroupData? groupData, MessageSectionData? sectionData) : base( + CmdIds.PlayerSyncScNotify) + { + var proto = new PlayerSyncScNotify(); + + if (groupData != null) + proto.MessageGroupStatus.Add(new GroupStatus { - proto.BasicTypeInfoList.Add(avatar.ToHeroProto()); - } + GroupId = (uint)groupData.GroupId, + GroupStatus_ = groupData.Status, + RefreshTime = groupData.RefreshTime + }); - SetData(proto); - } + if (sectionData != null) + proto.SectionStatus.Add(new SectionStatus + { + SectionId = (uint)sectionData.SectionId, + SectionStatus_ = sectionData.Status + }); - public PacketPlayerSyncScNotify(MissionSync mission) : base(CmdIds.PlayerSyncScNotify) + SetData(proto); + } + + private void AddItemToProto(ItemData item, PlayerSyncScNotify notify) + { + GameData.ItemConfigData.TryGetValue(item.ItemId, out var itemConfig); + if (itemConfig == null) return; + switch (itemConfig.ItemMainType) { - var proto = new PlayerSyncScNotify - { - MissionSync = mission, - }; - - SetData(proto); - } - - public PacketPlayerSyncScNotify(PlayerBasicInfo info) : base(CmdIds.PlayerSyncScNotify) - { - var proto = new PlayerSyncScNotify() - { - BasicInfo = info, - }; - - SetData(proto); - } - - public PacketPlayerSyncScNotify(MessageGroupData? groupData, MessageSectionData? sectionData) : base(CmdIds.PlayerSyncScNotify) - { - var proto = new PlayerSyncScNotify(); - - if (groupData != null) - { - proto.MessageGroupStatus.Add(new GroupStatus - { - GroupId = (uint)groupData.GroupId, - GroupStatus_ = groupData.Status, - RefreshTime = groupData.RefreshTime, - }); - } - - if (sectionData != null) - { - proto.SectionStatus.Add(new SectionStatus - { - SectionId = (uint)sectionData.SectionId, - SectionStatus_ = sectionData.Status, - }); - } - - SetData(proto); - } - - private void AddItemToProto(ItemData item, PlayerSyncScNotify notify) - { - GameData.ItemConfigData.TryGetValue(item.ItemId, out var itemConfig); - if (itemConfig == null) return; - switch (itemConfig.ItemMainType) - { - case ItemMainTypeEnum.Equipment: - if (item.Count > 0) - { - notify.EquipmentList.Add(item.ToEquipmentProto()); - } else - { - notify.DelEquipmentList.Add((uint)item.UniqueId); - } - break; - case ItemMainTypeEnum.Relic: - if (item.Count > 0) - { - notify.RelicList.Add(item.ToRelicProto()); - } - else - { - notify.DelRelicList.Add((uint)item.UniqueId); - } - break; - case ItemMainTypeEnum.Mission: - case ItemMainTypeEnum.Material: - case ItemMainTypeEnum.Usable: - notify.MaterialList.Add(item.ToMaterialProto()); - break; - } - - return; + case ItemMainTypeEnum.Equipment: + if (item.Count > 0) + notify.EquipmentList.Add(item.ToEquipmentProto()); + else + notify.DelEquipmentList.Add((uint)item.UniqueId); + break; + case ItemMainTypeEnum.Relic: + if (item.Count > 0) + notify.RelicList.Add(item.ToRelicProto()); + else + notify.DelRelicList.Add((uint)item.UniqueId); + break; + case ItemMainTypeEnum.Mission: + case ItemMainTypeEnum.Material: + case ItemMainTypeEnum.Usable: + notify.MaterialList.Add(item.ToMaterialProto()); + break; } } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketSelectChatBubbleScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketSelectChatBubbleScRsp.cs index c44e8c7f..45faf85d 100644 --- a/GameServer/Server/Packet/Send/Player/PacketSelectChatBubbleScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketSelectChatBubbleScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketSelectChatBubbleScRsp : BasePacket { - public class PacketSelectChatBubbleScRsp : BasePacket + public PacketSelectChatBubbleScRsp(uint bubbleId) : base(CmdIds.SelectChatBubbleScRsp) { - public PacketSelectChatBubbleScRsp(uint bubbleId) : base(CmdIds.SelectChatBubbleScRsp) + var proto = new SelectChatBubbleScRsp { - var proto = new SelectChatBubbleScRsp - { - CurChatBubble = bubbleId - }; + CurChatBubble = bubbleId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketSelectPhoneThemeScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketSelectPhoneThemeScRsp.cs index 87c10060..eb1c05d0 100644 --- a/GameServer/Server/Packet/Send/Player/PacketSelectPhoneThemeScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketSelectPhoneThemeScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketSelectPhoneThemeScRsp : BasePacket { - public class PacketSelectPhoneThemeScRsp : BasePacket + public PacketSelectPhoneThemeScRsp(uint themeId) : base(CmdIds.SelectPhoneThemeScRsp) { - public PacketSelectPhoneThemeScRsp(uint themeId) : base(CmdIds.SelectPhoneThemeScRsp) + var proto = new SelectPhoneThemeScRsp { - var proto = new SelectPhoneThemeScRsp - { - CurPhoneTheme = themeId - }; + CurPhoneTheme = themeId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketSetClientPausedScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketSetClientPausedScRsp.cs index 33b6c94f..b89705ed 100644 --- a/GameServer/Server/Packet/Send/Player/PacketSetClientPausedScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketSetClientPausedScRsp.cs @@ -1,16 +1,15 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketSetClientPausedScRsp : BasePacket { - public class PacketSetClientPausedScRsp : BasePacket + public PacketSetClientPausedScRsp(bool paused) : base(CmdIds.SetClientPausedScRsp) { - public PacketSetClientPausedScRsp(bool paused) : base(CmdIds.SetClientPausedScRsp) + var rsp = new SetClientPausedScRsp { - var rsp = new SetClientPausedScRsp - { - Paused = paused - }; - SetData(rsp); - } + Paused = paused + }; + SetData(rsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketSetGameplayBirthdayScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketSetGameplayBirthdayScRsp.cs index 429f8310..2f9e0784 100644 --- a/GameServer/Server/Packet/Send/Player/PacketSetGameplayBirthdayScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketSetGameplayBirthdayScRsp.cs @@ -1,32 +1,26 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketSetGameplayBirthdayScRsp : BasePacket { - public class PacketSetGameplayBirthdayScRsp : BasePacket + public PacketSetGameplayBirthdayScRsp(uint birthday) : base(CmdIds.SetGameplayBirthdayScRsp) { - public PacketSetGameplayBirthdayScRsp(uint birthday) : base(CmdIds.SetGameplayBirthdayScRsp) + var proto = new SetGameplayBirthdayScRsp { - var proto = new SetGameplayBirthdayScRsp() - { - Birthday = birthday, - }; + Birthday = birthday + }; - SetData(proto); - } - - public PacketSetGameplayBirthdayScRsp() : base(CmdIds.SetGameplayBirthdayScRsp) - { - var proto = new SetGameplayBirthdayScRsp() - { - Retcode = 1, - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketSetGameplayBirthdayScRsp() : base(CmdIds.SetGameplayBirthdayScRsp) + { + var proto = new SetGameplayBirthdayScRsp + { + Retcode = 1 + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketSetHeadIconScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketSetHeadIconScRsp.cs index 52269df3..86bb31ee 100644 --- a/GameServer/Server/Packet/Send/Player/PacketSetHeadIconScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketSetHeadIconScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketSetHeadIconScRsp : BasePacket { - public class PacketSetHeadIconScRsp : BasePacket + public PacketSetHeadIconScRsp(PlayerInstance player) : base(CmdIds.SetHeadIconScRsp) { - public PacketSetHeadIconScRsp(PlayerInstance player) : base(CmdIds.SetHeadIconScRsp) + var proto = new SetHeadIconScRsp { - var proto = new SetHeadIconScRsp() - { - CurrentHeadIconId = (uint)player.Data.HeadIcon - }; - SetData(proto); - } + CurrentHeadIconId = (uint)player.Data.HeadIcon + }; + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketSetHeroBasicTypeScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketSetHeroBasicTypeScRsp.cs index 4ed89f52..8e6aa7d8 100644 --- a/GameServer/Server/Packet/Send/Player/PacketSetHeroBasicTypeScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketSetHeroBasicTypeScRsp.cs @@ -1,32 +1,26 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketSetHeroBasicTypeScRsp : BasePacket { - public class PacketSetHeroBasicTypeScRsp : BasePacket + public PacketSetHeroBasicTypeScRsp(uint basicType) : base(CmdIds.SetHeroBasicTypeScRsp) { - public PacketSetHeroBasicTypeScRsp(uint basicType) : base(CmdIds.SetHeroBasicTypeScRsp) + var proto = new SetHeroBasicTypeScRsp { - var proto = new SetHeroBasicTypeScRsp - { - BasicType = (HeroBasicType)basicType - }; + BasicType = (HeroBasicType)basicType + }; - SetData(proto); - } - - public PacketSetHeroBasicTypeScRsp() : base(CmdIds.SetHeroBasicTypeScRsp) - { - var proto = new SetHeroBasicTypeScRsp - { - Retcode = 1 - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketSetHeroBasicTypeScRsp() : base(CmdIds.SetHeroBasicTypeScRsp) + { + var proto = new SetHeroBasicTypeScRsp + { + Retcode = 1 + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketSetPlayerInfoScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketSetPlayerInfoScRsp.cs index f95b65ee..f1a6ff36 100644 --- a/GameServer/Server/Packet/Send/Player/PacketSetPlayerInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketSetPlayerInfoScRsp.cs @@ -1,19 +1,18 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Player -{ - public class PacketSetPlayerInfoScRsp : BasePacket - { - public PacketSetPlayerInfoScRsp(PlayerInstance player, bool IsModify) : base(CmdIds.SetPlayerInfoScRsp) - { - var proto = new SetPlayerInfoScRsp() - { - CurBasicType = (HeroBasicType)player.Data.CurBasicType, - IsModify = IsModify, - }; +namespace EggLink.DanhengServer.Server.Packet.Send.Player; - SetData(proto); - } +public class PacketSetPlayerInfoScRsp : BasePacket +{ + public PacketSetPlayerInfoScRsp(PlayerInstance player, bool IsModify) : base(CmdIds.SetPlayerInfoScRsp) + { + var proto = new SetPlayerInfoScRsp + { + CurBasicType = (HeroBasicType)player.Data.CurBasicType, + IsModify = IsModify + }; + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketSetSignatureScRsp.cs b/GameServer/Server/Packet/Send/Player/PacketSetSignatureScRsp.cs index d68dc63a..8463eec2 100644 --- a/GameServer/Server/Packet/Send/Player/PacketSetSignatureScRsp.cs +++ b/GameServer/Server/Packet/Send/Player/PacketSetSignatureScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketSetSignatureScRsp : BasePacket { - public class PacketSetSignatureScRsp : BasePacket + public PacketSetSignatureScRsp(string signature) : base(CmdIds.SetSignatureScRsp) { - public PacketSetSignatureScRsp(string signature) : base(CmdIds.SetSignatureScRsp) + var proto = new SetSignatureScRsp { - var proto = new SetSignatureScRsp() - { - Signature = signature - }; + Signature = signature + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketStaminaInfoScNotify.cs b/GameServer/Server/Packet/Send/Player/PacketStaminaInfoScNotify.cs index 809a7575..c4930360 100644 --- a/GameServer/Server/Packet/Send/Player/PacketStaminaInfoScNotify.cs +++ b/GameServer/Server/Packet/Send/Player/PacketStaminaInfoScNotify.cs @@ -1,20 +1,19 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Player -{ - public class PacketStaminaInfoScNotify : BasePacket - { - public PacketStaminaInfoScNotify(PlayerInstance player) : base(CmdIds.StaminaInfoScNotify) - { - var proto = new StaminaInfoScNotify() - { - Stamina = (uint)player.Data.Stamina, - ReserveStamina = (uint)player.Data.StaminaReserve, - NextRecoverTime = player.Data.NextStaminaRecover, - }; +namespace EggLink.DanhengServer.Server.Packet.Send.Player; - SetData(proto); - } +public class PacketStaminaInfoScNotify : BasePacket +{ + public PacketStaminaInfoScNotify(PlayerInstance player) : base(CmdIds.StaminaInfoScNotify) + { + var proto = new StaminaInfoScNotify + { + Stamina = (uint)player.Data.Stamina, + ReserveStamina = (uint)player.Data.StaminaReserve, + NextRecoverTime = player.Data.NextStaminaRecover + }; + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Player/PacketUpdateEnergyScNotify.cs b/GameServer/Server/Packet/Send/Player/PacketUpdateEnergyScNotify.cs index f0217317..61bcc72a 100644 --- a/GameServer/Server/Packet/Send/Player/PacketUpdateEnergyScNotify.cs +++ b/GameServer/Server/Packet/Send/Player/PacketUpdateEnergyScNotify.cs @@ -1,26 +1,20 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Player +namespace EggLink.DanhengServer.Server.Packet.Send.Player; + +public class PacketUpdateEnergyScNotify : BasePacket { - public class PacketUpdateEnergyScNotify : BasePacket + public PacketUpdateEnergyScNotify(int curNum, int maxNum) : base(CmdIds.UpdateEnergyScNotify) { - public PacketUpdateEnergyScNotify(int curNum, int maxNum) : base(CmdIds.UpdateEnergyScNotify) + var proto = new UpdateEnergyScNotify { - var proto = new UpdateEnergyScNotify() + EnergyInfo = new RotatorEnergyInfo { - EnergyInfo = new RotatorEnergyInfo() - { - MaxNum = (uint)maxNum, - CurNum = (uint)curNum, - } - }; + MaxNum = (uint)maxNum, + CurNum = (uint)curNum + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Quest/PacketGetQuestDataScRsp.cs b/GameServer/Server/Packet/Send/Quest/PacketGetQuestDataScRsp.cs index 7d99e23f..76171269 100644 --- a/GameServer/Server/Packet/Send/Quest/PacketGetQuestDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Quest/PacketGetQuestDataScRsp.cs @@ -1,27 +1,19 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Quest +namespace EggLink.DanhengServer.Server.Packet.Send.Quest; + +public class PacketGetQuestDataScRsp : BasePacket { - public class PacketGetQuestDataScRsp : BasePacket + public PacketGetQuestDataScRsp() : base(CmdIds.GetQuestDataScRsp) { - public PacketGetQuestDataScRsp() : base(CmdIds.GetQuestDataScRsp) - { - var proto = new GetQuestDataScRsp(); - foreach (var quest in GameData.QuestDataData.Values) + var proto = new GetQuestDataScRsp(); + foreach (var quest in GameData.QuestDataData.Values) + proto.QuestList.Add(new Proto.Quest { - proto.QuestList.Add(new Proto.Quest() - { - Id = (uint)quest.QuestID, - Status = QuestStatus.QuestDoing - }); - } - SetData(proto); - } + Id = (uint)quest.QuestID, + Status = QuestStatus.QuestDoing + }); + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Raid/PacketDelSaveRaidScNotify.cs b/GameServer/Server/Packet/Send/Raid/PacketDelSaveRaidScNotify.cs index 59fcf366..3540b6b8 100644 --- a/GameServer/Server/Packet/Send/Raid/PacketDelSaveRaidScNotify.cs +++ b/GameServer/Server/Packet/Send/Raid/PacketDelSaveRaidScNotify.cs @@ -1,24 +1,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid; + +public class PacketDelSaveRaidScNotify : BasePacket { - public class PacketDelSaveRaidScNotify : BasePacket + public PacketDelSaveRaidScNotify(int raidId, int worldLevel) : base(CmdIds.DelSaveRaidScNotify) { - public PacketDelSaveRaidScNotify(int raidId, int worldLevel) : base(CmdIds.DelSaveRaidScNotify) + var proto = new DelSaveRaidScNotify { - var proto = new DelSaveRaidScNotify() - { - RaidId = (uint)raidId, - WorldLevel = (uint)worldLevel, - }; + RaidId = (uint)raidId, + WorldLevel = (uint)worldLevel + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Raid/PacketGetAllSaveRaidScRsp.cs b/GameServer/Server/Packet/Send/Raid/PacketGetAllSaveRaidScRsp.cs index cb4fd85a..147fa29f 100644 --- a/GameServer/Server/Packet/Send/Raid/PacketGetAllSaveRaidScRsp.cs +++ b/GameServer/Server/Packet/Send/Raid/PacketGetAllSaveRaidScRsp.cs @@ -1,34 +1,23 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid; + +public class PacketGetAllSaveRaidScRsp : BasePacket { - public class PacketGetAllSaveRaidScRsp : BasePacket + public PacketGetAllSaveRaidScRsp(PlayerInstance player) : base(CmdIds.GetAllSaveRaidScRsp) { - public PacketGetAllSaveRaidScRsp(PlayerInstance player) : base(CmdIds.GetAllSaveRaidScRsp) - { - var proto = new GetAllSaveRaidScRsp(); + var proto = new GetAllSaveRaidScRsp(); - foreach (var dict in player.RaidManager!.RaidData.RaidRecordDatas.Values) + foreach (var dict in player.RaidManager!.RaidData.RaidRecordDatas.Values) + foreach (var record in dict.Values) + proto.SavedData.Add(new RaidSavedData { - foreach (var record in dict.Values) - { - proto.SavedData.Add(new RaidSavedData() - { - RaidId = (uint)record.RaidId, - WorldLevel = (uint)record.WorldLevel, - TargetInfo = { }, - }); - } - } + RaidId = (uint)record.RaidId, + WorldLevel = (uint)record.WorldLevel + }); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Raid/PacketGetRaidInfoScRsp.cs b/GameServer/Server/Packet/Send/Raid/PacketGetRaidInfoScRsp.cs index 7cbae7dd..5614c5f9 100644 --- a/GameServer/Server/Packet/Send/Raid/PacketGetRaidInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Raid/PacketGetRaidInfoScRsp.cs @@ -1,41 +1,24 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid; + +public class PacketGetRaidInfoScRsp : BasePacket { - public class PacketGetRaidInfoScRsp : BasePacket + public PacketGetRaidInfoScRsp(PlayerInstance player) : base(CmdIds.GetRaidInfoScRsp) { - public PacketGetRaidInfoScRsp(PlayerInstance player) : base(CmdIds.GetRaidInfoScRsp) - { - var proto = new GetRaidInfoScRsp() - { - ChallengeRaidList = { }, - ChallengeTakenRewardIdListFieldNumber = { }, - FinishedRaidInfoList = { }, - }; + var proto = new GetRaidInfoScRsp(); - foreach (var recordDict in player.RaidManager!.RaidData.RaidRecordDatas) - { - foreach (var record in recordDict.Value) + foreach (var recordDict in player.RaidManager!.RaidData.RaidRecordDatas) + foreach (var record in recordDict.Value) + if (record.Value.Status == RaidStatus.Finish) + proto.FinishedRaidInfoList.Add(new RaidInfo { - if (record.Value.Status == RaidStatus.Finish) - { - proto.FinishedRaidInfoList.Add(new RaidInfo() - { - RaidId = (uint)record.Value.RaidId, - WorldLevel = (uint)record.Value.WorldLevel, - }); - } - } - } + RaidId = (uint)record.Value.RaidId, + WorldLevel = (uint)record.Value.WorldLevel + }); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Raid/PacketGetSaveRaidScRsp.cs b/GameServer/Server/Packet/Send/Raid/PacketGetSaveRaidScRsp.cs index 14f0bdd6..99586173 100644 --- a/GameServer/Server/Packet/Send/Raid/PacketGetSaveRaidScRsp.cs +++ b/GameServer/Server/Packet/Send/Raid/PacketGetSaveRaidScRsp.cs @@ -1,39 +1,33 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid; + +public class PacketGetSaveRaidScRsp : BasePacket { - public class PacketGetSaveRaidScRsp : BasePacket + public PacketGetSaveRaidScRsp(PlayerInstance player, int raidId, int worldLevel) : base(CmdIds.GetSaveRaidScRsp) { - public PacketGetSaveRaidScRsp(PlayerInstance player, int raidId, int worldLevel) : base(CmdIds.GetSaveRaidScRsp) - { - var proto = new GetSaveRaidScRsp(); + var proto = new GetSaveRaidScRsp(); - if (player.RaidManager!.RaidData.RaidRecordDatas.TryGetValue(raidId, out var dict)) + if (player.RaidManager!.RaidData.RaidRecordDatas.TryGetValue(raidId, out var dict)) + { + if (dict.TryGetValue(worldLevel, out var record)) { - if (dict.TryGetValue(worldLevel, out var record)) - { - proto.RaidId = (uint)record.RaidId; - proto.WorldLevel = (uint)record.WorldLevel; - proto.IsSave = record.Status != RaidStatus.Finish && record.Status != RaidStatus.None; - } - else - { - proto.Retcode = (uint)Retcode.RetRaidNoSave; - } + proto.RaidId = (uint)record.RaidId; + proto.WorldLevel = (uint)record.WorldLevel; + proto.IsSave = record.Status != RaidStatus.Finish && record.Status != RaidStatus.None; } else { proto.Retcode = (uint)Retcode.RetRaidNoSave; } - - SetData(proto); } + else + { + proto.Retcode = (uint)Retcode.RetRaidNoSave; + } + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Raid/PacketRaidInfoNotify.cs b/GameServer/Server/Packet/Send/Raid/PacketRaidInfoNotify.cs index c7d5e40b..1424ab3b 100644 --- a/GameServer/Server/Packet/Send/Raid/PacketRaidInfoNotify.cs +++ b/GameServer/Server/Packet/Send/Raid/PacketRaidInfoNotify.cs @@ -1,40 +1,32 @@ using EggLink.DanhengServer.Database.Scene; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Raid; + +public class PacketRaidInfoNotify : BasePacket { - public class PacketRaidInfoNotify : BasePacket + public PacketRaidInfoNotify(RaidRecord record) : base(CmdIds.RaidInfoNotify) { - public PacketRaidInfoNotify(RaidRecord record) : base(CmdIds.RaidInfoNotify) + var proto = new RaidInfoNotify { - var proto = new RaidInfoNotify() - { - RaidId = (uint)record.RaidId, - Status = record.Status, - WorldLevel = (uint)record.WorldLevel, - RaidFinishTime = (ulong)record.FinishTimeStamp, - TargetInfo = { }, - ItemList = new(), - }; + RaidId = (uint)record.RaidId, + Status = record.Status, + WorldLevel = (uint)record.WorldLevel, + RaidFinishTime = (ulong)record.FinishTimeStamp, + ItemList = new ItemList() + }; - SetData(proto); - } - - public PacketRaidInfoNotify() : base(CmdIds.RaidInfoNotify) - { - var proto = new RaidInfoNotify() - { - TargetInfo = { }, - ItemList = new(), - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketRaidInfoNotify() : base(CmdIds.RaidInfoNotify) + { + var proto = new RaidInfoNotify + { + ItemList = new ItemList() + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketEnhanceRogueBuffScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketEnhanceRogueBuffScRsp.cs index 6a344f35..f6406aa4 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketEnhanceRogueBuffScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketEnhanceRogueBuffScRsp.cs @@ -1,27 +1,21 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketEnhanceRogueBuffScRsp : BasePacket { - public class PacketEnhanceRogueBuffScRsp : BasePacket + public PacketEnhanceRogueBuffScRsp(uint buffId) : base(CmdIds.EnhanceRogueBuffScRsp) { - public PacketEnhanceRogueBuffScRsp(uint buffId) : base(CmdIds.EnhanceRogueBuffScRsp) + var proto = new EnhanceRogueBuffScRsp { - var proto = new EnhanceRogueBuffScRsp + RogueBuff = new RogueBuff { - RogueBuff = new() - { - BuffId = buffId, - Level = 2 - }, - IsSuccess = true - }; + BuffId = buffId, + Level = 2 + }, + IsSuccess = true + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketEnterRogueMapRoomScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketEnterRogueMapRoomScRsp.cs index 3575e3d7..4b235b23 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketEnterRogueMapRoomScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketEnterRogueMapRoomScRsp.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketEnterRogueMapRoomScRsp : BasePacket { - public class PacketEnterRogueMapRoomScRsp : BasePacket + public PacketEnterRogueMapRoomScRsp(PlayerInstance player) : base(CmdIds.EnterRogueMapRoomScRsp) { - public PacketEnterRogueMapRoomScRsp(PlayerInstance player) : base(CmdIds.EnterRogueMapRoomScRsp) + var proto = new EnterRogueMapRoomScRsp { - var proto = new EnterRogueMapRoomScRsp - { - CurSiteId = (uint)(player.RogueManager?.RogueInstance?.CurRoom?.SiteId ?? 0), - Lineup = player.LineupManager!.GetCurLineup()!.ToProto(), - Scene = player.SceneInstance!.ToProto(), - }; + CurSiteId = (uint)(player.RogueManager?.RogueInstance?.CurRoom?.SiteId ?? 0), + Lineup = player.LineupManager!.GetCurLineup()!.ToProto(), + Scene = player.SceneInstance!.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueBuffEnhanceInfoScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueBuffEnhanceInfoScRsp.cs index 70376410..0f33973c 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueBuffEnhanceInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueBuffEnhanceInfoScRsp.cs @@ -1,27 +1,22 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketGetRogueBuffEnhanceInfoScRsp : BasePacket { - public class PacketGetRogueBuffEnhanceInfoScRsp : BasePacket + public PacketGetRogueBuffEnhanceInfoScRsp(PlayerInstance player) : base(CmdIds.GetRogueBuffEnhanceInfoScRsp) { - public PacketGetRogueBuffEnhanceInfoScRsp(PlayerInstance player) : base(CmdIds.GetRogueBuffEnhanceInfoScRsp) + var proto = new GetRogueBuffEnhanceInfoScRsp(); + if (player.RogueManager!.GetRogueInstance() == null) { - var proto = new GetRogueBuffEnhanceInfoScRsp(); - if (player.RogueManager!.GetRogueInstance() == null) - { - proto.Retcode = 1; - SetData(proto); - return; - } - proto.BuffEnhanceInfo = player.RogueManager.GetRogueInstance()!.ToEnhanceInfo(); - + proto.Retcode = 1; SetData(proto); + return; } + + proto.BuffEnhanceInfo = player.RogueManager.GetRogueInstance()!.ToEnhanceInfo(); + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueHandbookDataScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueHandbookDataScRsp.cs index 2c543996..2312d332 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueHandbookDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueHandbookDataScRsp.cs @@ -1,59 +1,53 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketGetRogueHandbookDataScRsp : BasePacket { - public class PacketGetRogueHandbookDataScRsp : BasePacket + public PacketGetRogueHandbookDataScRsp() : base(CmdIds.GetRogueHandbookDataScRsp) { - public PacketGetRogueHandbookDataScRsp() : base(CmdIds.GetRogueHandbookDataScRsp) + var proto = new GetRogueHandbookDataScRsp { - var proto = new GetRogueHandbookDataScRsp + HandbookInfo = new RogueHandbook() + }; + + //foreach (var item in GameData.RogueHandbookMiracleData) + //{ + // proto.HandbookInfo.MiracleList.Add(new EHJPAIBFIPK() + // { + // HAGLJCEAMEK = (uint)item.Value.MiracleHandbookID, + // HasTakenReward = true, + // }); + //} + + foreach (var item in GameData.RogueMazeBuffData) + { + if (item.Value.Lv != 1) + continue; + proto.HandbookInfo.BuffList.Add(new IFJPLLMDHPL { - HandbookInfo = new() - }; - - //foreach (var item in GameData.RogueHandbookMiracleData) - //{ - // proto.HandbookInfo.MiracleList.Add(new EHJPAIBFIPK() - // { - // HAGLJCEAMEK = (uint)item.Value.MiracleHandbookID, - // HasTakenReward = true, - // }); - //} - - foreach (var item in GameData.RogueMazeBuffData) - { - if (item.Value.Lv != 1) - continue; - proto.HandbookInfo.BuffList.Add(new IFJPLLMDHPL() - { - MazeBuffId = (uint)item.Value.ID, - }); - } - - //foreach (var item in GameData.RogueAeonData) - //{ - // proto.HandbookInfo.RogueAeonList.Add(new DKNNNMJKPNO() - // { - // AeonId = (uint)item.Value.AeonID, - // }); - //} - - //foreach (var item in GameData.RogueHandBookEventData) - //{ - // proto.HandbookInfo.EventList.Add(new MMEGPGAAPDG() - // { - // BFHDEKMCJJA = (uint)item.Value.EventID, - // HasTakenReward = true, - // }); - //} - - SetData(proto); + MazeBuffId = (uint)item.Value.ID + }); } + + //foreach (var item in GameData.RogueAeonData) + //{ + // proto.HandbookInfo.RogueAeonList.Add(new DKNNNMJKPNO() + // { + // AeonId = (uint)item.Value.AeonID, + // }); + //} + + //foreach (var item in GameData.RogueHandBookEventData) + //{ + // proto.HandbookInfo.EventList.Add(new MMEGPGAAPDG() + // { + // BFHDEKMCJJA = (uint)item.Value.EventID, + // HasTakenReward = true, + // }); + //} + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueInfoScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueInfoScRsp.cs index fcda62b6..e0a918a1 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueInfoScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketGetRogueInfoScRsp : BasePacket { - public class PacketGetRogueInfoScRsp : BasePacket + public PacketGetRogueInfoScRsp(PlayerInstance player) : base(CmdIds.GetRogueInfoScRsp) { - public PacketGetRogueInfoScRsp(PlayerInstance player) : base(CmdIds.GetRogueInfoScRsp) + var proto = new GetRogueInfoScRsp { - var proto = new GetRogueInfoScRsp() - { - RogueInfo = player.RogueManager!.ToProto(), - }; + RogueInfo = player.RogueManager!.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueInitialScoreScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueInitialScoreScRsp.cs index ba393fdc..afc5e6cc 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueInitialScoreScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueInitialScoreScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketGetRogueInitialScoreScRsp : BasePacket { - public class PacketGetRogueInitialScoreScRsp : BasePacket + public PacketGetRogueInitialScoreScRsp(PlayerInstance player) : base(CmdIds.GetRogueInitialScoreScRsp) { - public PacketGetRogueInitialScoreScRsp(PlayerInstance player) : base(CmdIds.GetRogueInitialScoreScRsp) + var proto = new GetRogueInitialScoreScRsp { - var proto = new GetRogueInitialScoreScRsp() - { - RogueScoreRewardInfo = player.RogueManager!.ToRewardProto() - }; + RogueScoreRewardInfo = player.RogueManager!.ToRewardProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueScoreRewardInfoScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueScoreRewardInfoScRsp.cs index 89e07749..634ee7e4 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueScoreRewardInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueScoreRewardInfoScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketGetRogueScoreRewardInfoScRsp : BasePacket { - public class PacketGetRogueScoreRewardInfoScRsp : BasePacket + public PacketGetRogueScoreRewardInfoScRsp(PlayerInstance player) : base(CmdIds.GetRogueScoreRewardInfoScRsp) { - public PacketGetRogueScoreRewardInfoScRsp(PlayerInstance player) : base(CmdIds.GetRogueScoreRewardInfoScRsp) + var proto = new GetRogueScoreRewardInfoScRsp { - var proto = new GetRogueScoreRewardInfoScRsp - { - Info = player.RogueManager!.ToRewardProto() - }; + Info = player.RogueManager!.ToRewardProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueTalentInfoScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueTalentInfoScRsp.cs index 0733784b..0de2a0bd 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketGetRogueTalentInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketGetRogueTalentInfoScRsp.cs @@ -1,24 +1,17 @@ -using EggLink.DanhengServer.Game.Player; -using EggLink.DanhengServer.Game.Rogue; +using EggLink.DanhengServer.Game.Rogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketGetRogueTalentInfoScRsp : BasePacket { - public class PacketGetRogueTalentInfoScRsp : BasePacket + public PacketGetRogueTalentInfoScRsp() : base(CmdIds.GetRogueTalentInfoScRsp) { - public PacketGetRogueTalentInfoScRsp() : base(CmdIds.GetRogueTalentInfoScRsp) + var proto = new GetRogueTalentInfoScRsp { - var proto = new GetRogueTalentInfoScRsp() - { - RogueTalentInfo = RogueManager.ToTalentProto() - }; + RogueTalentInfo = RogueManager.ToTalentProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketHandleRogueCommonPendingActionScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketHandleRogueCommonPendingActionScRsp.cs index a5c018d5..706de16a 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketHandleRogueCommonPendingActionScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketHandleRogueCommonPendingActionScRsp.cs @@ -1,47 +1,32 @@ using EggLink.DanhengServer.Game.Rogue.Buff; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketHandleRogueCommonPendingActionScRsp : BasePacket { - public class PacketHandleRogueCommonPendingActionScRsp : BasePacket + public PacketHandleRogueCommonPendingActionScRsp(int queuePosition, bool selectBuff = false, + bool selectMiracle = false, bool selectBonus = false, RogueBuffSelectMenu? menu = null) : base( + CmdIds.HandleRogueCommonPendingActionScRsp) { - public PacketHandleRogueCommonPendingActionScRsp(int queuePosition, bool selectBuff = false, bool selectMiracle = false, bool selectBonus = false, RogueBuffSelectMenu? menu = null) : base(CmdIds.HandleRogueCommonPendingActionScRsp) + var proto = new HandleRogueCommonPendingActionScRsp { - var proto = new HandleRogueCommonPendingActionScRsp + QueueLocation = (uint)queuePosition, + QueuePosition = (uint)queuePosition + }; + + if (selectBuff) proto.BuffSelectCallback = new RogueBuffSelectCallback(); + + if (selectMiracle) proto.MiracleSelectCallback = new RogueMiracleSelectCallback(); + + if (selectBonus) proto.BonusSelectCallback = new RogueBonusSelectCallback(); + + if (menu != null) + proto.BuffRerollCallback = new RogueBuffRerollCallback { - QueueLocation = (uint)queuePosition, - QueuePosition = (uint)queuePosition, + BuffSelectInfo = menu.ToProto() }; - if (selectBuff) - { - proto.BuffSelectCallback = new(); - } - - if (selectMiracle) - { - proto.MiracleSelectCallback = new(); - } - - if (selectBonus) - { - proto.BonusSelectCallback = new(); - } - - if (menu != null) - { - proto.BuffRerollCallback = new() - { - BuffSelectInfo = menu.ToProto() - }; - } - - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketLeaveRogueScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketLeaveRogueScRsp.cs index b3b5bbea..1b2f1372 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketLeaveRogueScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketLeaveRogueScRsp.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketLeaveRogueScRsp : BasePacket { - public class PacketLeaveRogueScRsp : BasePacket + public PacketLeaveRogueScRsp(PlayerInstance player) : base(CmdIds.LeaveRogueScRsp) { - public PacketLeaveRogueScRsp(PlayerInstance player) : base(CmdIds.LeaveRogueScRsp) + var proto = new LeaveRogueScRsp { - var proto = new LeaveRogueScRsp() - { - Lineup = player.LineupManager!.GetCurLineup()!.ToProto(), - Scene = player.SceneInstance!.ToProto(), - RogueInfo = player.RogueManager!.ToProto(), - }; + Lineup = player.LineupManager!.GetCurLineup()!.ToProto(), + Scene = player.SceneInstance!.ToProto(), + RogueInfo = player.RogueManager!.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketQuitRogueScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketQuitRogueScRsp.cs index f4949c9c..bae99cef 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketQuitRogueScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketQuitRogueScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketQuitRogueScRsp : BasePacket { - public class PacketQuitRogueScRsp : BasePacket + public PacketQuitRogueScRsp(PlayerInstance player) : base(CmdIds.QuitRogueScRsp) { - public PacketQuitRogueScRsp(PlayerInstance player) : base(CmdIds.QuitRogueScRsp) + var proto = new QuitRogueScRsp { - var proto = new QuitRogueScRsp - { - RogueInfo = player.RogueManager!.ToProto(), - }; + RogueInfo = player.RogueManager!.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSelectRogueCommonDialogueOptionScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketSelectRogueCommonDialogueOptionScRsp.cs index 472976b1..0b4d5ef9 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSelectRogueCommonDialogueOptionScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSelectRogueCommonDialogueOptionScRsp.cs @@ -1,35 +1,30 @@ using EggLink.DanhengServer.Game.Rogue.Event; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketSelectRogueCommonDialogueOptionScRsp : BasePacket { - public class PacketSelectRogueCommonDialogueOptionScRsp : BasePacket + public PacketSelectRogueCommonDialogueOptionScRsp(RogueEventInstance rogueEvent) : base( + CmdIds.SelectRogueCommonDialogueOptionScRsp) { - public PacketSelectRogueCommonDialogueOptionScRsp(RogueEventInstance rogueEvent) : base(CmdIds.SelectRogueCommonDialogueOptionScRsp) + var proto = new SelectRogueCommonDialogueOptionScRsp { - var proto = new SelectRogueCommonDialogueOptionScRsp() - { - EventUniqueId = (uint)rogueEvent.EventUniqueId, - DialogueData = rogueEvent.ToProto(), - OptionId = (uint)rogueEvent.SelectedOptionId, - }; + EventUniqueId = (uint)rogueEvent.EventUniqueId, + DialogueData = rogueEvent.ToProto(), + OptionId = (uint)rogueEvent.SelectedOptionId + }; - SetData(proto); - } - - public PacketSelectRogueCommonDialogueOptionScRsp() : base(CmdIds.SelectRogueCommonDialogueOptionScRsp) - { - var proto = new SelectRogueCommonDialogueOptionScRsp() - { - Retcode = 1 - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketSelectRogueCommonDialogueOptionScRsp() : base(CmdIds.SelectRogueCommonDialogueOptionScRsp) + { + var proto = new SelectRogueCommonDialogueOptionScRsp + { + Retcode = 1 + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketStartRogueScRsp.cs b/GameServer/Server/Packet/Send/Rogue/PacketStartRogueScRsp.cs index ecae4a23..8cb416f1 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketStartRogueScRsp.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketStartRogueScRsp.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketStartRogueScRsp : BasePacket { - public class PacketStartRogueScRsp : BasePacket + public PacketStartRogueScRsp(PlayerInstance player) : base(CmdIds.StartRogueScRsp) { - public PacketStartRogueScRsp(PlayerInstance player) : base(CmdIds.StartRogueScRsp) + var proto = new StartRogueScRsp { - var proto = new StartRogueScRsp - { - RogueInfo = player.RogueManager!.ToProto(), - Lineup = player.LineupManager!.GetCurLineup()!.ToProto(), - Scene = player.SceneInstance!.ToProto(), - }; + RogueInfo = player.RogueManager!.ToProto(), + Lineup = player.LineupManager!.GetCurLineup()!.ToProto(), + Scene = player.SceneInstance!.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonActionResultScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonActionResultScNotify.cs index 8a2608bc..9ea92720 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonActionResultScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonActionResultScNotify.cs @@ -1,38 +1,36 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueCommonActionResultScNotify : BasePacket { - public class PacketSyncRogueCommonActionResultScNotify : BasePacket + public PacketSyncRogueCommonActionResultScNotify(int rogueSubmode, RogueCommonActionResult result, + RogueActionDisplayType displayType = RogueActionDisplayType.RogueCommonActionResultDisplayTypeNone) : base( + CmdIds.SyncRogueCommonActionResultScNotify) { - public PacketSyncRogueCommonActionResultScNotify(int rogueSubmode, RogueCommonActionResult result, RogueActionDisplayType displayType = RogueActionDisplayType.RogueCommonActionResultDisplayTypeNone) : base(CmdIds.SyncRogueCommonActionResultScNotify) + var proto = new SyncRogueCommonActionResultScNotify { - var proto = new SyncRogueCommonActionResultScNotify - { - RogueSubMode = (uint)rogueSubmode, - DisplayType = displayType - }; + RogueSubMode = (uint)rogueSubmode, + DisplayType = displayType + }; - proto.ActionResult.Add(result); + proto.ActionResult.Add(result); - SetData(proto); - } - - public PacketSyncRogueCommonActionResultScNotify(int rogueSubmode, List results, RogueActionDisplayType displayType = RogueActionDisplayType.RogueCommonActionResultDisplayTypeNone) : base(CmdIds.SyncRogueCommonActionResultScNotify) - { - var proto = new SyncRogueCommonActionResultScNotify - { - RogueSubMode = (uint)rogueSubmode, - DisplayType = displayType - }; - - proto.ActionResult.AddRange(results); - - SetData(proto); - } + SetData(proto); } -} + + public PacketSyncRogueCommonActionResultScNotify(int rogueSubmode, List results, + RogueActionDisplayType displayType = RogueActionDisplayType.RogueCommonActionResultDisplayTypeNone) : base( + CmdIds.SyncRogueCommonActionResultScNotify) + { + var proto = new SyncRogueCommonActionResultScNotify + { + RogueSubMode = (uint)rogueSubmode, + DisplayType = displayType + }; + + proto.ActionResult.AddRange(results); + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonDialogueDataScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonDialogueDataScNotify.cs index 082206b0..bfa582a4 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonDialogueDataScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonDialogueDataScNotify.cs @@ -1,22 +1,17 @@ using EggLink.DanhengServer.Game.Rogue.Event; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueCommonDialogueDataScNotify : BasePacket { - public class PacketSyncRogueCommonDialogueDataScNotify : BasePacket + public PacketSyncRogueCommonDialogueDataScNotify(RogueEventInstance rogueEvent) : base( + CmdIds.SyncRogueCommonDialogueDataScNotify) { - public PacketSyncRogueCommonDialogueDataScNotify(RogueEventInstance rogueEvent) : base(CmdIds.SyncRogueCommonDialogueDataScNotify) - { - var proto = new SyncRogueCommonDialogueDataScNotify(); + var proto = new SyncRogueCommonDialogueDataScNotify(); - proto.DialogueEventList.Add(rogueEvent.ToProto()); + proto.DialogueEventList.Add(rogueEvent.ToProto()); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonDialogueOptionFinishScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonDialogueOptionFinishScNotify.cs index 0d553afd..cb72bae6 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonDialogueOptionFinishScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonDialogueOptionFinishScNotify.cs @@ -1,27 +1,22 @@ using EggLink.DanhengServer.Game.Rogue.Event; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueCommonDialogueOptionFinishScNotify : BasePacket { - public class PacketSyncRogueCommonDialogueOptionFinishScNotify : BasePacket + public PacketSyncRogueCommonDialogueOptionFinishScNotify(RogueEventInstance instance) : base( + CmdIds.SyncRogueCommonDialogueOptionFinishScNotify) { - public PacketSyncRogueCommonDialogueOptionFinishScNotify(RogueEventInstance instance) : base(CmdIds.SyncRogueCommonDialogueOptionFinishScNotify) + var proto = new SyncRogueCommonDialogueOptionFinishScNotify { - var proto = new SyncRogueCommonDialogueOptionFinishScNotify() - { - DialogueData = instance.ToProto(), - EventUniqueId = (uint)instance.EventUniqueId, - OptionId = (uint)instance.SelectedOptionId, - ResultOptionInfo = instance.Options.Find(o => o.OptionId == instance.SelectedOptionId)!.ToProto() - }; + DialogueData = instance.ToProto(), + EventUniqueId = (uint)instance.EventUniqueId, + OptionId = (uint)instance.SelectedOptionId, + ResultOptionInfo = instance.Options.Find(o => o.OptionId == instance.SelectedOptionId)!.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonPendingActionScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonPendingActionScNotify.cs index 2c307160..fb55848d 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonPendingActionScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonPendingActionScNotify.cs @@ -1,24 +1,19 @@ using EggLink.DanhengServer.Game.Rogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueCommonPendingActionScNotify : BasePacket { - public class PacketSyncRogueCommonPendingActionScNotify : BasePacket + public PacketSyncRogueCommonPendingActionScNotify(RogueActionInstance actionInstance, int rogueSubmode) : base( + CmdIds.SyncRogueCommonPendingActionScNotify) { - public PacketSyncRogueCommonPendingActionScNotify(RogueActionInstance actionInstance, int rogueSubmode) : base(CmdIds.SyncRogueCommonPendingActionScNotify) + var proto = new SyncRogueCommonPendingActionScNotify { - var proto = new SyncRogueCommonPendingActionScNotify - { - Action = actionInstance.ToProto(), - RogueSubMode = (uint)rogueSubmode, - }; + Action = actionInstance.ToProto(), + RogueSubMode = (uint)rogueSubmode + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonVirtualItemInfoScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonVirtualItemInfoScNotify.cs index a539a169..738d1dfc 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonVirtualItemInfoScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueCommonVirtualItemInfoScNotify.cs @@ -1,28 +1,26 @@ using EggLink.DanhengServer.Game.Rogue; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueCommonVirtualItemInfoScNotify : BasePacket { - public class PacketSyncRogueCommonVirtualItemInfoScNotify : BasePacket + public PacketSyncRogueCommonVirtualItemInfoScNotify(BaseRogueInstance instance) : base( + CmdIds.SyncRogueCommonVirtualItemInfoScNotify) { - public PacketSyncRogueCommonVirtualItemInfoScNotify(BaseRogueInstance instance) : base(CmdIds.SyncRogueCommonVirtualItemInfoScNotify) + var proto = new SyncRogueCommonVirtualItemInfoScNotify { - var proto = new SyncRogueCommonVirtualItemInfoScNotify + CommonItemInfo = { - CommonItemInfo = { new RogueCommonVirtualItemInfo() + new RogueCommonVirtualItemInfo { VirtualItemId = 31, - VirtualItemNum = (uint)instance.CurMoney, - } } - }; + VirtualItemNum = (uint)instance.CurMoney + } + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueExploreWinScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueExploreWinScNotify.cs index f1030b9b..ed23f2b1 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueExploreWinScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueExploreWinScNotify.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueExploreWinScNotify : BasePacket { - public class PacketSyncRogueExploreWinScNotify : BasePacket + public PacketSyncRogueExploreWinScNotify() : base(CmdIds.SyncRogueExploreWinScNotify) { - public PacketSyncRogueExploreWinScNotify() : base(CmdIds.SyncRogueExploreWinScNotify) + var proto = new SyncRogueExploreWinScNotify { - var proto = new SyncRogueExploreWinScNotify() - { - IsWin = true, - }; + IsWin = true + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueFinishScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueFinishScNotify.cs index 67c8f021..4184a88e 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueFinishScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueFinishScNotify.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueFinishScNotify : BasePacket { - public class PacketSyncRogueFinishScNotify : BasePacket + public PacketSyncRogueFinishScNotify(RogueFinishInfo info) : base(CmdIds.SyncRogueFinishScNotify) { - public PacketSyncRogueFinishScNotify(RogueFinishInfo info) : base(CmdIds.SyncRogueFinishScNotify) + var proto = new SyncRogueFinishScNotify { - var proto = new SyncRogueFinishScNotify - { - FinishInfo = info - }; + FinishInfo = info + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueMapRoomScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueMapRoomScNotify.cs index 99a59ca5..f09864a7 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueMapRoomScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueMapRoomScNotify.cs @@ -1,24 +1,18 @@ using EggLink.DanhengServer.Game.Rogue.Scene; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueMapRoomScNotify : BasePacket { - public class PacketSyncRogueMapRoomScNotify : BasePacket + public PacketSyncRogueMapRoomScNotify(RogueRoomInstance room, int mapId) : base(CmdIds.SyncRogueMapRoomScNotify) { - public PacketSyncRogueMapRoomScNotify(RogueRoomInstance room, int mapId) : base(CmdIds.SyncRogueMapRoomScNotify) + var proto = new SyncRogueMapRoomScNotify { - var proto = new SyncRogueMapRoomScNotify() - { - CurRoom = room.ToProto(), - MapId = (uint)mapId - }; + CurRoom = room.ToProto(), + MapId = (uint)mapId + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueStatusScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueStatusScNotify.cs index 8e57e8fc..3a8b12a1 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueStatusScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueStatusScNotify.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueStatusScNotify : BasePacket { - public class PacketSyncRogueStatusScNotify : BasePacket + public PacketSyncRogueStatusScNotify(RogueStatus status) : base(CmdIds.SyncRogueStatusScNotify) { - public PacketSyncRogueStatusScNotify(RogueStatus status) : base(CmdIds.SyncRogueStatusScNotify) + var proto = new SyncRogueStatusScNotify { - var proto = new SyncRogueStatusScNotify() - { - Status = status, - }; + Status = status + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueVirtualItemScNotify.cs b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueVirtualItemScNotify.cs index 3713bedf..48aa2229 100644 --- a/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueVirtualItemScNotify.cs +++ b/GameServer/Server/Packet/Send/Rogue/PacketSyncRogueVirtualItemScNotify.cs @@ -1,26 +1,21 @@ using EggLink.DanhengServer.Game.Rogue; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Rogue +namespace EggLink.DanhengServer.Server.Packet.Send.Rogue; + +public class PacketSyncRogueVirtualItemScNotify : BasePacket { - public class PacketSyncRogueVirtualItemScNotify : BasePacket + public PacketSyncRogueVirtualItemScNotify(BaseRogueInstance instance) : base( + CmdIds.SyncRogueVirtualItemInfoScNotify) { - public PacketSyncRogueVirtualItemScNotify(BaseRogueInstance instance): base(CmdIds.SyncRogueVirtualItemInfoScNotify) + var proto = new SyncRogueVirtualItemInfoScNotify { - var proto = new SyncRogueVirtualItemInfoScNotify + RogueVirtualItemInfo = new RogueVirtualItemInfo { - RogueVirtualItemInfo = new() - { - //RogueMoney = (uint)instance.CurMoney, - } - }; + //RogueMoney = (uint)instance.CurMoney, + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketActivateFarmElementScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketActivateFarmElementScRsp.cs index f100a4ce..3a5b31e9 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketActivateFarmElementScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketActivateFarmElementScRsp.cs @@ -1,24 +1,18 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketActivateFarmElementScRsp : BasePacket { - public class PacketActivateFarmElementScRsp : BasePacket + public PacketActivateFarmElementScRsp(uint entityId, PlayerInstance player) : base(CmdIds.ActivateFarmElementScRsp) { - public PacketActivateFarmElementScRsp(uint entityId, PlayerInstance player): base(CmdIds.ActivateFarmElementScRsp) + var proto = new ActivateFarmElementScRsp { - var proto = new ActivateFarmElementScRsp() - { - EntityId = entityId, - WorldLevel = (uint)player.Data.WorldLevel, - }; + EntityId = entityId, + WorldLevel = (uint)player.Data.WorldLevel + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketContentPackageGetDataScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketContentPackageGetDataScRsp.cs index 61cc4aec..f7b472ee 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketContentPackageGetDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketContentPackageGetDataScRsp.cs @@ -1,23 +1,18 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; + +public class PacketContentPackageGetDataScRsp : BasePacket { - public class PacketContentPackageGetDataScRsp : BasePacket + public PacketContentPackageGetDataScRsp(uint id) : base(CmdIds.ContentPackageGetDataScRsp) { - public PacketContentPackageGetDataScRsp(uint id) : base(CmdIds.ContentPackageGetDataScRsp) + var proto = new ContentPackageGetDataScRsp { - var proto = new ContentPackageGetDataScRsp - { - Data = new ContentPackageData { ContentInfoList = { new ContentInfo { ContentId = id, Status = ContentPackageStatus.Finished } } } - }; + Data = new ContentPackageData + { ContentInfoList = { new ContentInfo { ContentId = id, Status = ContentPackageStatus.Finished } } } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketContentPackageSyncDataScNotify.cs b/GameServer/Server/Packet/Send/Scene/PacketContentPackageSyncDataScNotify.cs index 8c2c8bf2..aeb82b54 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketContentPackageSyncDataScNotify.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketContentPackageSyncDataScNotify.cs @@ -1,31 +1,28 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; + +public class PacketContentPackageSyncDataScNotify : BasePacket { - public class PacketContentPackageSyncDataScNotify : BasePacket + public PacketContentPackageSyncDataScNotify() : base(CmdIds.ContentPackageSyncDataScNotify) { - public PacketContentPackageSyncDataScNotify() : base(CmdIds.ContentPackageSyncDataScNotify) + var proto = new ContentPackageSyncDataScNotify { - var proto = new ContentPackageSyncDataScNotify() + Data = new ContentPackageData { - Data = new ContentPackageData() - { - ContentInfoList = { GameData.ContentPackageConfigData.Select(x => new ContentInfo() + ContentInfoList = + { + GameData.ContentPackageConfigData.Select(x => new ContentInfo { ContentId = (uint)x.Key, Status = ContentPackageStatus.Finished - }) } - }, - }; + }) + } + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketDeactivateFarmElementScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketDeactivateFarmElementScRsp.cs index d1ad5532..7c11a0a5 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketDeactivateFarmElementScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketDeactivateFarmElementScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketDeactivateFarmElementScRsp : BasePacket { - public class PacketDeactivateFarmElementScRsp : BasePacket + public PacketDeactivateFarmElementScRsp(uint id) : base(CmdIds.DeactivateFarmElementScRsp) { - public PacketDeactivateFarmElementScRsp(uint id) : base(CmdIds.DeactivateFarmElementScRsp) + var proto = new DeactivateFarmElementScRsp { - var proto = new DeactivateFarmElementScRsp() - { - EntityId = id - }; + EntityId = id + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketEnterMapRotationRegionScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketEnterMapRotationRegionScRsp.cs index 399c6a97..f8567e38 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketEnterMapRotationRegionScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketEnterMapRotationRegionScRsp.cs @@ -1,27 +1,21 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketEnterMapRotationRegionScRsp : BasePacket { - public class PacketEnterMapRotationRegionScRsp : BasePacket + public PacketEnterMapRotationRegionScRsp(MotionInfo motion) : base(CmdIds.EnterMapRotationRegionScRsp) { - public PacketEnterMapRotationRegionScRsp(MotionInfo motion) : base(CmdIds.EnterMapRotationRegionScRsp) + var proto = new EnterMapRotationRegionScRsp { - var proto = new EnterMapRotationRegionScRsp + Motion = motion, + EnergyInfo = new RotatorEnergyInfo { - Motion = motion, - EnergyInfo = new() - { - CurNum = 5, - MaxNum = 5, - }, - }; + CurNum = 5, + MaxNum = 5 + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketEnterSceneByServerScNotify.cs b/GameServer/Server/Packet/Send/Scene/PacketEnterSceneByServerScNotify.cs index 5c8bc1c7..5231c582 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketEnterSceneByServerScNotify.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketEnterSceneByServerScNotify.cs @@ -1,23 +1,22 @@ -using EggLink.DanhengServer.Enums.Mission; -using EggLink.DanhengServer.Game.Scene; +using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketEnterSceneByServerScNotify : BasePacket { - public class PacketEnterSceneByServerScNotify : BasePacket + public PacketEnterSceneByServerScNotify(SceneInstance scene, + ChangeStoryLineAction storyLineAction = ChangeStoryLineAction.None) : base(CmdIds.EnterSceneByServerScNotify) { - public PacketEnterSceneByServerScNotify(SceneInstance scene, ChangeStoryLineAction storyLineAction = ChangeStoryLineAction.None) : base(CmdIds.EnterSceneByServerScNotify) + var sceneInfo = scene.ToProto(); + var notify = new EnterSceneByServerScNotify { - var sceneInfo = scene.ToProto(); - var notify = new EnterSceneByServerScNotify() - { - Scene = sceneInfo, - Lineup = scene.Player.LineupManager!.GetCurLineup()!.ToProto(), - }; + Scene = sceneInfo, + Lineup = scene.Player.LineupManager!.GetCurLineup()!.ToProto() + }; - notify.Scene.BONACBOIIBE = (uint) storyLineAction; + notify.Scene.BONACBOIIBE = (uint)storyLineAction; - SetData(notify); - } + SetData(notify); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketEnterSceneScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketEnterSceneScRsp.cs index dfe145de..00850d37 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketEnterSceneScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketEnterSceneScRsp.cs @@ -1,25 +1,20 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; + +public class PacketEnterSceneScRsp : BasePacket { - public class PacketEnterSceneScRsp : BasePacket + public PacketEnterSceneScRsp(bool overMapTp = false, bool tpByMap = false, int storyLineId = 0) : base( + CmdIds.EnterSceneScRsp) { - public PacketEnterSceneScRsp(bool overMapTp = false, bool tpByMap = false, int storyLineId = 0) : base(CmdIds.EnterSceneScRsp) + var proto = new EnterSceneScRsp { - var proto = new EnterSceneScRsp - { - GameStoryLineId = (uint)storyLineId, - MapTp = tpByMap, - JDALDJPFNMN = overMapTp - }; + GameStoryLineId = (uint)storyLineId, + MapTp = tpByMap, + JDALDJPFNMN = overMapTp + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketGetCurSceneInfoScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketGetCurSceneInfoScRsp.cs index 3ee27b22..c740c613 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketGetCurSceneInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketGetCurSceneInfoScRsp.cs @@ -1,23 +1,17 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketGetCurSceneInfoScRsp : BasePacket { - public class PacketGetCurSceneInfoScRsp : BasePacket + public PacketGetCurSceneInfoScRsp(PlayerInstance player) : base(CmdIds.GetCurSceneInfoScRsp) { - public PacketGetCurSceneInfoScRsp(PlayerInstance player) : base(CmdIds.GetCurSceneInfoScRsp) + var proto = new GetCurSceneInfoScRsp { - var proto = new GetCurSceneInfoScRsp() - { - Scene = player.SceneInstance!.ToProto(), - }; + Scene = player.SceneInstance!.ToProto() + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketGetEnteredSceneScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketGetEnteredSceneScRsp.cs index 50f61e11..16aae90b 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketGetEnteredSceneScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketGetEnteredSceneScRsp.cs @@ -1,33 +1,29 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketGetEnteredSceneScRsp : BasePacket { - public class PacketGetEnteredSceneScRsp : BasePacket + public PacketGetEnteredSceneScRsp() : base(CmdIds.GetEnteredSceneScRsp) { - public PacketGetEnteredSceneScRsp() : base(CmdIds.GetEnteredSceneScRsp) + var proto = new GetEnteredSceneScRsp(); + + foreach (var excel in GameData.MapEntranceData.Values) { - var proto = new GetEnteredSceneScRsp(); + // Skip these + if (excel.FinishMainMissionList.Count == 0 && excel.FinishMainMissionList.Count == 0) continue; - foreach (var excel in GameData.MapEntranceData.Values) + // Add info + var info = new EnteredScene { - // Skip these - if (excel.FinishMainMissionList.Count == 0 && excel.FinishMainMissionList.Count == 0) - { - continue; - } + FloorId = (uint)excel.FloorID, + PlaneId = (uint)excel.PlaneID + }; - // Add info - var info = new EnteredScene() - { - FloorId = (uint)excel.FloorID, - PlaneId = (uint)excel.PlaneID, - }; - - proto.EnteredSceneList.Add(info); - } - - SetData(proto); + proto.EnteredSceneList.Add(info); } + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketGetFirstTalkByPerformanceNpcScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketGetFirstTalkByPerformanceNpcScRsp.cs index 5b105885..1ab9d871 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketGetFirstTalkByPerformanceNpcScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketGetFirstTalkByPerformanceNpcScRsp.cs @@ -1,22 +1,20 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketGetFirstTalkByPerformanceNpcScRsp : BasePacket { - public class PacketGetFirstTalkByPerformanceNpcScRsp : BasePacket - { - public PacketGetFirstTalkByPerformanceNpcScRsp(GetFirstTalkByPerformanceNpcCsReq req) : base(CmdIds.GetFirstTalkByPerformanceNpcScRsp) - { - var rsp = new GetFirstTalkByPerformanceNpcScRsp(); + public PacketGetFirstTalkByPerformanceNpcScRsp(GetFirstTalkByPerformanceNpcCsReq req) : base( + CmdIds.GetFirstTalkByPerformanceNpcScRsp) + { + var rsp = new GetFirstTalkByPerformanceNpcScRsp(); - foreach (var id in req.FirstTalkIdList) + foreach (var id in req.FirstTalkIdList) + rsp.NpcMeetStatusList.Add(new NpcMeetStatusInfo { - rsp.NpcMeetStatusList.Add(new NpcMeetStatusInfo - { - MeetId = id, - }); - } + MeetId = id + }); - SetData(rsp); - } + SetData(rsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketGetNpcTakenRewardScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketGetNpcTakenRewardScRsp.cs index 42ce364c..22444b52 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketGetNpcTakenRewardScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketGetNpcTakenRewardScRsp.cs @@ -1,16 +1,15 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketGetNpcTakenRewardScRsp : BasePacket { - public class PacketGetNpcTakenRewardScRsp : BasePacket + public PacketGetNpcTakenRewardScRsp(uint npcId) : base(CmdIds.GetNpcTakenRewardScRsp) { - public PacketGetNpcTakenRewardScRsp(uint npcId) : base(CmdIds.GetNpcTakenRewardScRsp) + var proto = new GetNpcTakenRewardScRsp { - var proto = new GetNpcTakenRewardScRsp() - { - NpcId = npcId, - }; - SetData(proto); - } + NpcId = npcId + }; + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketGetSceneMapInfoScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketGetSceneMapInfoScRsp.cs index ea4fdc26..4a5f2928 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketGetSceneMapInfoScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketGetSceneMapInfoScRsp.cs @@ -1,100 +1,96 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Util; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketGetSceneMapInfoScRsp : BasePacket { - public class PacketGetSceneMapInfoScRsp : BasePacket + public PacketGetSceneMapInfoScRsp(GetSceneMapInfoCsReq req, PlayerInstance player) : base( + CmdIds.GetSceneMapInfoScRsp) { - public PacketGetSceneMapInfoScRsp(GetSceneMapInfoCsReq req, PlayerInstance player) : base(CmdIds.GetSceneMapInfoScRsp) + var rsp = new GetSceneMapInfoScRsp { - var rsp = new GetSceneMapInfoScRsp() + CGIIIEKIDJE = req.CGIIIEKIDJE + }; + + foreach (var entry in req.EntryIdList) + { + var mazeMap = new SceneMapInfo { - CGIIIEKIDJE = req.CGIIIEKIDJE, + EntryId = entry }; - - foreach (var entry in req.EntryIdList) + GameData.MapEntranceData.TryGetValue((int)entry, out var mapData); + if (mapData == null) { - var mazeMap = new SceneMapInfo() - { - EntryId = entry, - }; - GameData.MapEntranceData.TryGetValue((int)entry, out var mapData); - if (mapData == null) - { - rsp.SceneMapInfo.Add(mazeMap); - continue; - } - - GameData.GetFloorInfo(mapData.PlaneID, mapData.FloorID, out var floorInfo); - if (floorInfo == null) - { - rsp.SceneMapInfo.Add(mazeMap); - continue; - } - - mazeMap.ChestList.Add(new ChestInfo() - { - TotalAmount = 1, - MapInfoChestType = ChestType.MapInfoChestTypeNormal - }); - - mazeMap.ChestList.Add(new ChestInfo() - { - TotalAmount = 1, - MapInfoChestType = ChestType.MapInfoChestTypePuzzle - }); - - mazeMap.ChestList.Add(new ChestInfo() - { - TotalAmount = 1, - MapInfoChestType = ChestType.MapInfoChestTypeChallenge - }); - - foreach (GroupInfo groupInfo in floorInfo.Groups.Values) // all the icons on the map - { - var mazeGroup = new MazeGroup() - { - GroupId = (uint)groupInfo.Id, - }; - mazeMap.MazeGroupList.Add(mazeGroup); - } - - foreach (var teleport in floorInfo.CachedTeleports.Values) - { - mazeMap.UnlockTeleportList.Add((uint)teleport.MappingInfoID); - } - - foreach (var prop in floorInfo.UnlockedCheckpoints) - { - var mazeProp = new MazePropState() - { - GroupId = (uint)prop.AnchorGroupID, - ConfigId = (uint)prop.ID, - State = (uint)PropStateEnum.CheckPointEnable, - }; - mazeMap.MazePropList.Add(mazeProp); - } - - if (!ConfigManager.Config.ServerOption.AutoLightSection) - { - player.SceneData!.UnlockSectionIdList.TryGetValue(mapData.FloorID, out var sections); - foreach (var section in sections ?? []) - { - mazeMap.LightenSectionList.Add((uint)section); - } - } else - { - for (uint i = 0; i < 100; i++) - mazeMap.LightenSectionList.Add(i); - } - rsp.SceneMapInfo.Add(mazeMap); + continue; } - SetData(rsp); + + GameData.GetFloorInfo(mapData.PlaneID, mapData.FloorID, out var floorInfo); + if (floorInfo == null) + { + rsp.SceneMapInfo.Add(mazeMap); + continue; + } + + mazeMap.ChestList.Add(new ChestInfo + { + TotalAmount = 1, + MapInfoChestType = ChestType.MapInfoChestTypeNormal + }); + + mazeMap.ChestList.Add(new ChestInfo + { + TotalAmount = 1, + MapInfoChestType = ChestType.MapInfoChestTypePuzzle + }); + + mazeMap.ChestList.Add(new ChestInfo + { + TotalAmount = 1, + MapInfoChestType = ChestType.MapInfoChestTypeChallenge + }); + + foreach (var groupInfo in floorInfo.Groups.Values) // all the icons on the map + { + var mazeGroup = new MazeGroup + { + GroupId = (uint)groupInfo.Id + }; + mazeMap.MazeGroupList.Add(mazeGroup); + } + + foreach (var teleport in floorInfo.CachedTeleports.Values) + mazeMap.UnlockTeleportList.Add((uint)teleport.MappingInfoID); + + foreach (var prop in floorInfo.UnlockedCheckpoints) + { + var mazeProp = new MazePropState + { + GroupId = (uint)prop.AnchorGroupID, + ConfigId = (uint)prop.ID, + State = (uint)PropStateEnum.CheckPointEnable + }; + mazeMap.MazePropList.Add(mazeProp); + } + + if (!ConfigManager.Config.ServerOption.AutoLightSection) + { + player.SceneData!.UnlockSectionIdList.TryGetValue(mapData.FloorID, out var sections); + foreach (var section in sections ?? []) mazeMap.LightenSectionList.Add((uint)section); + } + else + { + for (uint i = 0; i < 100; i++) + mazeMap.LightenSectionList.Add(i); + } + + rsp.SceneMapInfo.Add(mazeMap); } + + SetData(rsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketGetUnlockTeleportScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketGetUnlockTeleportScRsp.cs index 29846e75..310a8999 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketGetUnlockTeleportScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketGetUnlockTeleportScRsp.cs @@ -1,34 +1,25 @@ using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Data.Config; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketGetUnlockTeleportScRsp : BasePacket { - public class PacketGetUnlockTeleportScRsp : BasePacket + public PacketGetUnlockTeleportScRsp(GetUnlockTeleportCsReq req) : base(CmdIds.GetUnlockTeleportScRsp) { - public PacketGetUnlockTeleportScRsp(GetUnlockTeleportCsReq req) : base(CmdIds.GetUnlockTeleportScRsp) + var rsp = new GetUnlockTeleportScRsp(); + foreach (var entranceId in req.EntryIdList) { - var rsp = new GetUnlockTeleportScRsp(); - foreach (var entranceId in req.EntryIdList) - { - GameData.MapEntranceData.TryGetValue((int)entranceId, out var excel); - if (excel == null) continue; + GameData.MapEntranceData.TryGetValue((int)entranceId, out var excel); + if (excel == null) continue; - GameData.GetFloorInfo(excel.PlaneID, excel.FloorID, out var floorInfo); - if (floorInfo == null) continue; + GameData.GetFloorInfo(excel.PlaneID, excel.FloorID, out var floorInfo); + if (floorInfo == null) continue; - foreach (var teleport in floorInfo.CachedTeleports) - { - rsp.UnlockTeleportList.Add((uint)teleport.Value.MappingInfoID); - } - } - - SetData(rsp); + foreach (var teleport in floorInfo.CachedTeleports) + rsp.UnlockTeleportList.Add((uint)teleport.Value.MappingInfoID); } + + SetData(rsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketGroupStateChangeScNotify.cs b/GameServer/Server/Packet/Send/Scene/PacketGroupStateChangeScNotify.cs index fc8b31c7..dc08c156 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketGroupStateChangeScNotify.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketGroupStateChangeScNotify.cs @@ -1,23 +1,23 @@ using EggLink.DanhengServer.Enums.Scene; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene -{ - public class PacketGroupStateChangeScNotify : BasePacket - { - public PacketGroupStateChangeScNotify(int entryId, int groupId, PropStateEnum propState) : base(CmdIds.GroupStateChangeScNotify) - { - var notify = new GroupStateChangeScNotify() - { - GroupStateInfo = new GroupStateInfo() - { - EntryId = (uint)entryId, - GroupId = (uint)groupId, - GroupState = (uint)propState, - } - }; +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; - SetData(notify); - } +public class PacketGroupStateChangeScNotify : BasePacket +{ + public PacketGroupStateChangeScNotify(int entryId, int groupId, PropStateEnum propState) : base( + CmdIds.GroupStateChangeScNotify) + { + var notify = new GroupStateChangeScNotify + { + GroupStateInfo = new GroupStateInfo + { + EntryId = (uint)entryId, + GroupId = (uint)groupId, + GroupState = (uint)propState + } + }; + + SetData(notify); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketInteractPropScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketInteractPropScRsp.cs index a45cb774..b6b34ee8 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketInteractPropScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketInteractPropScRsp.cs @@ -1,20 +1,20 @@ using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene -{ - public class PacketInteractPropScRsp : BasePacket - { - public PacketInteractPropScRsp(EntityProp? prop) : base(CmdIds.InteractPropScRsp) - { - var proto = new InteractPropScRsp(); +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; - if (prop != null) - { - proto.PropState = (uint)prop.State; - proto.PropEntityId = (uint)prop.EntityID; - } - SetData(proto); +public class PacketInteractPropScRsp : BasePacket +{ + public PacketInteractPropScRsp(EntityProp? prop) : base(CmdIds.InteractPropScRsp) + { + var proto = new InteractPropScRsp(); + + if (prop != null) + { + proto.PropState = (uint)prop.State; + proto.PropEntityId = (uint)prop.EntityID; } + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketSceneEntityMoveScNotify.cs b/GameServer/Server/Packet/Send/Scene/PacketSceneEntityMoveScNotify.cs index 079d97d8..68d2b3b5 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketSceneEntityMoveScNotify.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketSceneEntityMoveScNotify.cs @@ -1,28 +1,22 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketSceneEntityMoveScNotify : BasePacket { - public class PacketSceneEntityMoveScNotify : BasePacket + public PacketSceneEntityMoveScNotify(PlayerInstance player) : base(CmdIds.SceneEntityMoveScNotify) { - public PacketSceneEntityMoveScNotify(PlayerInstance player) : base(CmdIds.SceneEntityMoveScNotify) + var proto = new SceneEntityMoveScNotify { - var proto = new SceneEntityMoveScNotify() + EntryId = (uint)player.Data.EntryId, + Motion = new MotionInfo { - EntryId = (uint)player.Data.EntryId, - Motion = new MotionInfo() - { - Pos = player.Data.Pos!.ToProto(), - Rot = player.Data.Rot!.ToProto(), - }, - }; + Pos = player.Data.Pos!.ToProto(), + Rot = player.Data.Rot!.ToProto() + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketSceneEntityTeleportScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketSceneEntityTeleportScRsp.cs index 70b6389e..2d074e22 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketSceneEntityTeleportScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketSceneEntityTeleportScRsp.cs @@ -1,22 +1,16 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketSceneEntityTeleportScRsp : BasePacket { - public class PacketSceneEntityTeleportScRsp : BasePacket + public PacketSceneEntityTeleportScRsp(EntityMotion motion) : base(CmdIds.SceneEntityTeleportScRsp) { - public PacketSceneEntityTeleportScRsp(EntityMotion motion) : base(CmdIds.SceneEntityTeleportScRsp) + var proto = new SceneEntityTeleportScRsp { - var proto = new SceneEntityTeleportScRsp() - { - EntityMotion = motion, - }; + EntityMotion = motion + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketSceneGroupRefreshScNotify.cs b/GameServer/Server/Packet/Send/Scene/PacketSceneGroupRefreshScNotify.cs index a6c91995..2f547667 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketSceneGroupRefreshScNotify.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketSceneGroupRefreshScNotify.cs @@ -1,64 +1,56 @@ using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketSceneGroupRefreshScNotify : BasePacket { - public class PacketSceneGroupRefreshScNotify : BasePacket + public PacketSceneGroupRefreshScNotify(List? addEntity = null, List? removeEntity = null) + : base(CmdIds.SceneGroupRefreshScNotify) { - public PacketSceneGroupRefreshScNotify(List? addEntity = null, List? removeEntity = null) : base(CmdIds.SceneGroupRefreshScNotify) + var proto = new SceneGroupRefreshScNotify(); + Dictionary refreshInfo = []; + foreach (var e in addEntity ?? []) { - var proto = new SceneGroupRefreshScNotify(); - Dictionary refreshInfo = []; - foreach (var e in addEntity ?? []) + var group = new GroupRefreshInfo { - var group = new GroupRefreshInfo() - { - GroupId = (uint)e.GroupID, - }; - group.RefreshEntity.Add(new SceneEntityRefreshInfo() - { - AddEntity = e.ToProto() - }); - - if (refreshInfo.TryGetValue(e.GroupID, out GroupRefreshInfo? value)) - { - value.RefreshEntity.AddRange(group.RefreshEntity); - } - else - { - refreshInfo[e.GroupID] = group; - } - } - - foreach (var e in removeEntity ?? []) + GroupId = (uint)e.GroupID + }; + group.RefreshEntity.Add(new SceneEntityRefreshInfo { - var group = new GroupRefreshInfo() - { - GroupId = (uint)e.GroupID, - }; - group.RefreshEntity.Add(new SceneEntityRefreshInfo() - { - DeleteEntity = (uint)e.EntityID - }); + AddEntity = e.ToProto() + }); - if (refreshInfo.TryGetValue(e.GroupID, out GroupRefreshInfo? value)) - { - value.RefreshEntity.AddRange(group.RefreshEntity); - } - else - { - refreshInfo[e.GroupID] = group; - } - } - - proto.GroupRefreshList.AddRange(refreshInfo.Values); - - SetData(proto); + if (refreshInfo.TryGetValue(e.GroupID, out var value)) + value.RefreshEntity.AddRange(group.RefreshEntity); + else + refreshInfo[e.GroupID] = group; } - public PacketSceneGroupRefreshScNotify(IGameEntity? addEntity = null, IGameEntity? removeEntity = null) : - this(addEntity == null ? [] : [addEntity], removeEntity == null ? [] : [removeEntity]) + foreach (var e in removeEntity ?? []) { + var group = new GroupRefreshInfo + { + GroupId = (uint)e.GroupID + }; + group.RefreshEntity.Add(new SceneEntityRefreshInfo + { + DeleteEntity = (uint)e.EntityID + }); + + if (refreshInfo.TryGetValue(e.GroupID, out var value)) + value.RefreshEntity.AddRange(group.RefreshEntity); + else + refreshInfo[e.GroupID] = group; } + + proto.GroupRefreshList.AddRange(refreshInfo.Values); + + SetData(proto); } -} + + public PacketSceneGroupRefreshScNotify(IGameEntity? addEntity = null, IGameEntity? removeEntity = null) : + this(addEntity == null ? [] : [addEntity], removeEntity == null ? [] : [removeEntity]) + { + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketScenePlaneEventScNotify.cs b/GameServer/Server/Packet/Send/Scene/PacketScenePlaneEventScNotify.cs index 62692a22..d237a5a1 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketScenePlaneEventScNotify.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketScenePlaneEventScNotify.cs @@ -1,44 +1,34 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketScenePlaneEventScNotify : BasePacket { - public class PacketScenePlaneEventScNotify : BasePacket + public PacketScenePlaneEventScNotify(ItemData item) : this([item]) { - public PacketScenePlaneEventScNotify(ItemData item) : this([item]) - { - } - - public PacketScenePlaneEventScNotify(List itemDatas) : base(CmdIds.ScenePlaneEventScNotify) - { - var itemList = new ItemList(); - foreach (var item in itemDatas) - { - itemList.ItemList_.Add(item.ToProto()); - } - - var data = new ScenePlaneEventScNotify() - { - GetItemList = itemList, - }; - - SetData(data); - } - - public PacketScenePlaneEventScNotify(ItemList list) : base(CmdIds.ScenePlaneEventScNotify) - { - - var data = new ScenePlaneEventScNotify() - { - GetItemList = list, - }; - - SetData(data); - } } -} + + public PacketScenePlaneEventScNotify(List itemDatas) : base(CmdIds.ScenePlaneEventScNotify) + { + var itemList = new ItemList(); + foreach (var item in itemDatas) itemList.ItemList_.Add(item.ToProto()); + + var data = new ScenePlaneEventScNotify + { + GetItemList = itemList + }; + + SetData(data); + } + + public PacketScenePlaneEventScNotify(ItemList list) : base(CmdIds.ScenePlaneEventScNotify) + { + var data = new ScenePlaneEventScNotify + { + GetItemList = list + }; + + SetData(data); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketSetGroupCustomSaveDataScRsp.cs b/GameServer/Server/Packet/Send/Scene/PacketSetGroupCustomSaveDataScRsp.cs index 51652498..e2b0c4c6 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketSetGroupCustomSaveDataScRsp.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketSetGroupCustomSaveDataScRsp.cs @@ -1,17 +1,16 @@ using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketSetGroupCustomSaveDataScRsp : BasePacket { - public class PacketSetGroupCustomSaveDataScRsp : BasePacket + public PacketSetGroupCustomSaveDataScRsp(uint entryId, uint groupId) : base(CmdIds.SetGroupCustomSaveDataScRsp) { - public PacketSetGroupCustomSaveDataScRsp(uint entryId, uint groupId) : base(CmdIds.SetGroupCustomSaveDataScRsp) + var proto = new SetGroupCustomSaveDataScRsp { - var proto = new SetGroupCustomSaveDataScRsp() - { - EntryId = entryId, - GroupId = groupId - }; - SetData(proto); - } + EntryId = entryId, + GroupId = groupId + }; + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketSyncEntityBuffChangeListScNotify.cs b/GameServer/Server/Packet/Send/Scene/PacketSyncEntityBuffChangeListScNotify.cs index 06ded36f..cc03aa63 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketSyncEntityBuffChangeListScNotify.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketSyncEntityBuffChangeListScNotify.cs @@ -1,45 +1,41 @@ using EggLink.DanhengServer.Game.Scene; using EggLink.DanhengServer.Game.Scene.Entity; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.Server.Packet.Send.Scene; + +public class PacketSyncEntityBuffChangeListScNotify : BasePacket { - public class PacketSyncEntityBuffChangeListScNotify : BasePacket + public PacketSyncEntityBuffChangeListScNotify(IGameEntity entity, SceneBuff buff) : base( + CmdIds.SyncEntityBuffChangeListScNotify) { - public PacketSyncEntityBuffChangeListScNotify(IGameEntity entity, SceneBuff buff) : base(CmdIds.SyncEntityBuffChangeListScNotify) + var proto = new SyncEntityBuffChangeListScNotify(); + var change = new EntityBuffChange { - var proto = new SyncEntityBuffChangeListScNotify(); - var change = new EntityBuffChange() + EntityId = (uint)entity.EntityID, + BuffChangeInfo = buff.ToProto() + }; + proto.EntityBuffChangeList.Add(change); + + SetData(proto); + } + + public PacketSyncEntityBuffChangeListScNotify(IGameEntity entity, List buffs) : base( + CmdIds.SyncEntityBuffChangeListScNotify) + { + var proto = new SyncEntityBuffChangeListScNotify(); + + foreach (var buff in buffs) + { + buff.Duration = 0; + var change = new EntityBuffChange { EntityId = (uint)entity.EntityID, - BuffChangeInfo = buff.ToProto(), + BuffChangeInfo = buff.ToProto() }; proto.EntityBuffChangeList.Add(change); - - SetData(proto); } - public PacketSyncEntityBuffChangeListScNotify(IGameEntity entity, List buffs) : base(CmdIds.SyncEntityBuffChangeListScNotify) - { - var proto = new SyncEntityBuffChangeListScNotify(); - - foreach (var buff in buffs) - { - buff.Duration = 0; - var change = new EntityBuffChange() - { - EntityId = (uint)entity.EntityID, - BuffChangeInfo = buff.ToProto(), - }; - proto.EntityBuffChangeList.Add(change); - } - - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Scene/PacketUpdateFloorSavedValueNotify.cs b/GameServer/Server/Packet/Send/Scene/PacketUpdateFloorSavedValueNotify.cs index cdb5ff4a..89f481b8 100644 --- a/GameServer/Server/Packet/Send/Scene/PacketUpdateFloorSavedValueNotify.cs +++ b/GameServer/Server/Packet/Send/Scene/PacketUpdateFloorSavedValueNotify.cs @@ -1,21 +1,15 @@ using EggLink.DanhengServer.Proto; using EggLink.DanhengServer.Server.Packet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene +namespace EggLink.DanhengServer.GameServer.Server.Packet.Send.Scene; + +public class PacketUpdateFloorSavedValueNotify : BasePacket { - public class PacketUpdateFloorSavedValueNotify : BasePacket + public PacketUpdateFloorSavedValueNotify(string name, int savedValue) : base(CmdIds.UpdateFloorSavedValueNotify) { - public PacketUpdateFloorSavedValueNotify(string name, int savedValue) : base(CmdIds.UpdateFloorSavedValueNotify) - { - var proto = new UpdateFloorSavedValueNotify(); - proto.SavedValue.Add(name, savedValue); + var proto = new UpdateFloorSavedValueNotify(); + proto.SavedValue.Add(name, savedValue); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Shop/PacketBuyGoodsScRsp.cs b/GameServer/Server/Packet/Send/Shop/PacketBuyGoodsScRsp.cs index 10f072a6..e9f364e6 100644 --- a/GameServer/Server/Packet/Send/Shop/PacketBuyGoodsScRsp.cs +++ b/GameServer/Server/Packet/Send/Shop/PacketBuyGoodsScRsp.cs @@ -1,29 +1,23 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Shop +namespace EggLink.DanhengServer.Server.Packet.Send.Shop; + +public class PacketBuyGoodsScRsp : BasePacket { - public class PacketBuyGoodsScRsp : BasePacket + public PacketBuyGoodsScRsp(BuyGoodsCsReq req, List items) : base(CmdIds.BuyGoodsScRsp) { - public PacketBuyGoodsScRsp(BuyGoodsCsReq req, List items) : base(CmdIds.BuyGoodsScRsp) + var proto = new BuyGoodsScRsp { - var proto = new BuyGoodsScRsp() + ShopId = req.ShopId, + GoodsBuyTimes = req.GoodsNum, + GoodsId = req.GoodsId, + ReturnItemList = new ItemList { - ShopId = req.ShopId, - GoodsBuyTimes = req.GoodsNum, - GoodsId = req.GoodsId, - ReturnItemList = new() - { - ItemList_ = { items.Select(item => item.ToProto()) } - } - }; + ItemList_ = { items.Select(item => item.ToProto()) } + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Shop/PacketComposeItemScRsp.cs b/GameServer/Server/Packet/Send/Shop/PacketComposeItemScRsp.cs index 0d7b3d24..a1fae2b8 100644 --- a/GameServer/Server/Packet/Send/Shop/PacketComposeItemScRsp.cs +++ b/GameServer/Server/Packet/Send/Shop/PacketComposeItemScRsp.cs @@ -1,38 +1,32 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Shop +namespace EggLink.DanhengServer.Server.Packet.Send.Shop; + +public class PacketComposeItemScRsp : BasePacket { - public class PacketComposeItemScRsp : BasePacket + public PacketComposeItemScRsp() : base(CmdIds.ComposeItemScRsp) { - public PacketComposeItemScRsp() : base(CmdIds.ComposeItemScRsp) + var proto = new ComposeItemScRsp { - var proto = new ComposeItemScRsp() - { - Retcode = 1 - }; + Retcode = 1 + }; - SetData(proto); - } - - public PacketComposeItemScRsp(uint composeId, uint count,ItemData item) : base(CmdIds.ComposeItemScRsp) - { - var proto = new ComposeItemScRsp() - { - ReturnItemList = new() - { - ItemList_ = { item.ToProto() } - }, - ComposeId = composeId, - Count = count, - }; - - SetData(proto); - } + SetData(proto); } -} + + public PacketComposeItemScRsp(uint composeId, uint count, ItemData item) : base(CmdIds.ComposeItemScRsp) + { + var proto = new ComposeItemScRsp + { + ReturnItemList = new ItemList + { + ItemList_ = { item.ToProto() } + }, + ComposeId = composeId, + Count = count + }; + + SetData(proto); + } +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Shop/PacketDoGachaInRollShopScRsp.cs b/GameServer/Server/Packet/Send/Shop/PacketDoGachaInRollShopScRsp.cs index a06efea6..4046faf4 100644 --- a/GameServer/Server/Packet/Send/Shop/PacketDoGachaInRollShopScRsp.cs +++ b/GameServer/Server/Packet/Send/Shop/PacketDoGachaInRollShopScRsp.cs @@ -1,26 +1,21 @@ -using EggLink.DanhengServer.Data; -using EggLink.DanhengServer.Proto; -using EggLink.DanhengServer.Server.Packet.Send.Challenge; -using Org.BouncyCastle.Ocsp; -using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database; +using EggLink.DanhengServer.Proto; +namespace EggLink.DanhengServer.Server.Packet.Send.Shop; -namespace EggLink.DanhengServer.Server.Packet.Send.Shop +public class PacketDoGachaInRollShopScRsp : BasePacket { - public class PacketDoGachaInRollShopScRsp : BasePacket + public PacketDoGachaInRollShopScRsp(uint RollShopId, ItemList reward, uint type) : base( + CmdIds.DoGachaInRollShopScRsp) { - public PacketDoGachaInRollShopScRsp(uint RollShopId, ItemList reward, uint type) : base(CmdIds.DoGachaInRollShopScRsp) + var proto = new DoGachaInRollShopScRsp { - var proto = new DoGachaInRollShopScRsp - { - RollShopId = RollShopId, - MJCIOJJKGMI = type, //Reward type display - JCPIIANIDML = 0, - Reward = reward, - Retcode = 0 - }; + RollShopId = RollShopId, + MJCIOJJKGMI = type, //Reward type display + JCPIIANIDML = 0, + Reward = reward, + Retcode = 0 + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Shop/PacketGetRollShopInfoScRsp.cs.cs b/GameServer/Server/Packet/Send/Shop/PacketGetRollShopInfoScRsp.cs.cs index 6e406bfc..93dff82f 100644 --- a/GameServer/Server/Packet/Send/Shop/PacketGetRollShopInfoScRsp.cs.cs +++ b/GameServer/Server/Packet/Send/Shop/PacketGetRollShopInfoScRsp.cs.cs @@ -1,37 +1,28 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Proto; -using Microsoft.OpenApi.Writers; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Shop +namespace EggLink.DanhengServer.Server.Packet.Send.Shop; + +public class PacketGetRollShopInfoScRsp : BasePacket { - public class PacketGetRollShopInfoScRsp : BasePacket + public PacketGetRollShopInfoScRsp(uint rollShopId) : base(CmdIds.GetRollShopInfoScRsp) { - public PacketGetRollShopInfoScRsp(uint rollShopId) : base(CmdIds.GetRollShopInfoScRsp) - { - var proto = new GetRollShopInfoScRsp(); + var proto = new GetRollShopInfoScRsp(); - proto.RollShopId = rollShopId; - proto.GachaRandom = 1; + proto.RollShopId = rollShopId; + proto.GachaRandom = 1; - foreach (var item in GameData.RollShopConfigData.Values) + foreach (var item in GameData.RollShopConfigData.Values) + if (item.RollShopID == rollShopId) { - if (item.RollShopID == rollShopId) - { - proto.NOPNEOADJEI.Add(item.T1GroupID); - proto.NOPNEOADJEI.Add(item.T2GroupID); - proto.NOPNEOADJEI.Add(item.T3GroupID); - proto.NOPNEOADJEI.Add(item.T4GroupID); - } + proto.NOPNEOADJEI.Add(item.T1GroupID); + proto.NOPNEOADJEI.Add(item.T2GroupID); + proto.NOPNEOADJEI.Add(item.T3GroupID); + proto.NOPNEOADJEI.Add(item.T4GroupID); } - proto.Retcode = 0; + proto.Retcode = 0; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Shop/PacketGetShopListScRsp.cs b/GameServer/Server/Packet/Send/Shop/PacketGetShopListScRsp.cs index 4379d493..fb19b6d5 100644 --- a/GameServer/Server/Packet/Send/Shop/PacketGetShopListScRsp.cs +++ b/GameServer/Server/Packet/Send/Shop/PacketGetShopListScRsp.cs @@ -1,34 +1,24 @@ using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Shop +namespace EggLink.DanhengServer.Server.Packet.Send.Shop; + +public class PacketGetShopListScRsp : BasePacket { - public class PacketGetShopListScRsp : BasePacket + public PacketGetShopListScRsp(uint shopType) : base(CmdIds.GetShopListScRsp) { - public PacketGetShopListScRsp(uint shopType) : base(CmdIds.GetShopListScRsp) - { - var proto = new GetShopListScRsp(); + var proto = new GetShopListScRsp(); - foreach (var item in GameData.ShopConfigData.Values) - { - if (item.ShopType == shopType) + foreach (var item in GameData.ShopConfigData.Values) + if (item.ShopType == shopType) + proto.ShopList.Add(new Proto.Shop { - proto.ShopList.Add(new Proto.Shop() - { - ShopId = (uint)item.ShopID, - CityLevel = 1, - EndTime = long.MaxValue, - GoodsList = { item.Goods.Select(g => g.ToProto()) } - }); - } - } + ShopId = (uint)item.ShopID, + CityLevel = 1, + EndTime = long.MaxValue, + GoodsList = { item.Goods.Select(g => g.ToProto()) } + }); - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Shop/PacketSellItemScRsp.cs b/GameServer/Server/Packet/Send/Shop/PacketSellItemScRsp.cs index 76dd4437..c32ec63a 100644 --- a/GameServer/Server/Packet/Send/Shop/PacketSellItemScRsp.cs +++ b/GameServer/Server/Packet/Send/Shop/PacketSellItemScRsp.cs @@ -1,26 +1,20 @@ using EggLink.DanhengServer.Database.Inventory; using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Shop +namespace EggLink.DanhengServer.Server.Packet.Send.Shop; + +public class PacketSellItemScRsp : BasePacket { - public class PacketSellItemScRsp : BasePacket + public PacketSellItemScRsp(List items) : base(CmdIds.SellItemScRsp) { - public PacketSellItemScRsp(List items) : base(CmdIds.SellItemScRsp) + var proto = new SellItemScRsp { - var proto = new SellItemScRsp() + ReturnItemList = new ItemList { - ReturnItemList = new() - { - ItemList_ = { items.Select(x => x.ToProto())} - } - }; + ItemList_ = { items.Select(x => x.ToProto()) } + } + }; - SetData(proto); - } + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Tutorial/PacketFinishTutorialGuideScRsp.cs b/GameServer/Server/Packet/Send/Tutorial/PacketFinishTutorialGuideScRsp.cs index 6c5eb31e..e96c0abb 100644 --- a/GameServer/Server/Packet/Send/Tutorial/PacketFinishTutorialGuideScRsp.cs +++ b/GameServer/Server/Packet/Send/Tutorial/PacketFinishTutorialGuideScRsp.cs @@ -1,33 +1,27 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial +namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial; + +public class PacketFinishTutorialGuideScRsp : BasePacket { - public class PacketFinishTutorialGuideScRsp : BasePacket + public PacketFinishTutorialGuideScRsp(uint tutorialId) : base(CmdIds.FinishTutorialGuideScRsp) { - public PacketFinishTutorialGuideScRsp(uint tutorialId) : base(CmdIds.FinishTutorialGuideScRsp) + var rsp = new FinishTutorialGuideScRsp { - var rsp = new FinishTutorialGuideScRsp + TutorialGuide = new TutorialGuide { - TutorialGuide = new () - { - Id = tutorialId, - Status = TutorialStatus.TutorialFinish, - }, - Reward = new (), - }; + Id = tutorialId, + Status = TutorialStatus.TutorialFinish + }, + Reward = new ItemList() + }; - rsp.Reward.ItemList_.Add(new Item - { - ItemId = 1, - Num = 1, - }); + rsp.Reward.ItemList_.Add(new Item + { + ItemId = 1, + Num = 1 + }); - SetData(rsp); - } + SetData(rsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Tutorial/PacketFinishTutorialScRsp.cs b/GameServer/Server/Packet/Send/Tutorial/PacketFinishTutorialScRsp.cs index 3c47c33e..27f2b51c 100644 --- a/GameServer/Server/Packet/Send/Tutorial/PacketFinishTutorialScRsp.cs +++ b/GameServer/Server/Packet/Send/Tutorial/PacketFinishTutorialScRsp.cs @@ -1,26 +1,20 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial +namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial; + +public class PacketFinishTutorialScRsp : BasePacket { - public class PacketFinishTutorialScRsp : BasePacket + public PacketFinishTutorialScRsp(uint tutorialId) : base(CmdIds.FinishTutorialScRsp) { - public PacketFinishTutorialScRsp(uint tutorialId) : base(CmdIds.FinishTutorialScRsp) + var rsp = new FinishTutorialScRsp { - var rsp = new FinishTutorialScRsp + Tutorial = new Proto.Tutorial { - Tutorial = new Proto.Tutorial - { - Id = tutorialId, - Status = TutorialStatus.TutorialFinish, - }, - }; + Id = tutorialId, + Status = TutorialStatus.TutorialFinish + } + }; - SetData(rsp); - } + SetData(rsp); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Tutorial/PacketGetTutorialGuideScRsp.cs b/GameServer/Server/Packet/Send/Tutorial/PacketGetTutorialGuideScRsp.cs index ab3de80e..b2576c30 100644 --- a/GameServer/Server/Packet/Send/Tutorial/PacketGetTutorialGuideScRsp.cs +++ b/GameServer/Server/Packet/Send/Tutorial/PacketGetTutorialGuideScRsp.cs @@ -1,23 +1,20 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial -{ - public class PacketGetTutorialGuideScRsp : BasePacket - { - public PacketGetTutorialGuideScRsp(PlayerInstance player) : base(CmdIds.GetTutorialGuideScRsp) - { - var proto = new GetTutorialGuideScRsp { TutorialGuideList = { } }; - foreach (var data in player.TutorialGuideData?.Tutorials ?? []) - { - proto.TutorialGuideList.Add(new TutorialGuide() - { - Id = (uint)data.Key, - Status = data.Value, - }); - } +namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial; - SetData(proto); - } +public class PacketGetTutorialGuideScRsp : BasePacket +{ + public PacketGetTutorialGuideScRsp(PlayerInstance player) : base(CmdIds.GetTutorialGuideScRsp) + { + var proto = new GetTutorialGuideScRsp(); + foreach (var data in player.TutorialGuideData?.Tutorials ?? []) + proto.TutorialGuideList.Add(new TutorialGuide + { + Id = (uint)data.Key, + Status = data.Value + }); + + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Tutorial/PacketGetTutorialScRsp.cs b/GameServer/Server/Packet/Send/Tutorial/PacketGetTutorialScRsp.cs index 046d939b..c7672c12 100644 --- a/GameServer/Server/Packet/Send/Tutorial/PacketGetTutorialScRsp.cs +++ b/GameServer/Server/Packet/Send/Tutorial/PacketGetTutorialScRsp.cs @@ -1,23 +1,20 @@ using EggLink.DanhengServer.Game.Player; using EggLink.DanhengServer.Proto; -namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial -{ - public class PacketGetTutorialScRsp : BasePacket - { - public PacketGetTutorialScRsp(PlayerInstance player) : base(CmdIds.GetTutorialScRsp) - { - var proto = new GetTutorialScRsp() { TutorialList = { } }; +namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial; - foreach (var item in player.TutorialData!.Tutorials) +public class PacketGetTutorialScRsp : BasePacket +{ + public PacketGetTutorialScRsp(PlayerInstance player) : base(CmdIds.GetTutorialScRsp) + { + var proto = new GetTutorialScRsp(); + + foreach (var item in player.TutorialData!.Tutorials) + proto.TutorialList.Add(new Proto.Tutorial { - proto.TutorialList.Add(new Proto.Tutorial() - { - Id = (uint)item.Key, - Status = item.Value, - }); - } - SetData(proto); - } + Id = (uint)item.Key, + Status = item.Value + }); + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Tutorial/PacketUnlockTutorialGuideScRsp.cs b/GameServer/Server/Packet/Send/Tutorial/PacketUnlockTutorialGuideScRsp.cs index 67662300..c0d032d0 100644 --- a/GameServer/Server/Packet/Send/Tutorial/PacketUnlockTutorialGuideScRsp.cs +++ b/GameServer/Server/Packet/Send/Tutorial/PacketUnlockTutorialGuideScRsp.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial +namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial; + +public class PacketUnlockTutorialGuideScRsp : BasePacket { - public class PacketUnlockTutorialGuideScRsp : BasePacket + public PacketUnlockTutorialGuideScRsp(uint tutorialId) : base(CmdIds.UnlockTutorialGuideScRsp) { - public PacketUnlockTutorialGuideScRsp(uint tutorialId) : base(CmdIds.UnlockTutorialGuideScRsp) + var proto = new UnlockTutorialGuideScRsp { - var proto = new UnlockTutorialGuideScRsp + TutorialGuide = new TutorialGuide { - TutorialGuide = new() - { - Id = tutorialId, - Status = TutorialStatus.TutorialUnlock, - } - }; - SetData(proto); - } + Id = tutorialId, + Status = TutorialStatus.TutorialUnlock + } + }; + SetData(proto); } -} +} \ No newline at end of file diff --git a/GameServer/Server/Packet/Send/Tutorial/PacketUnlockTutorialScRsp.cs b/GameServer/Server/Packet/Send/Tutorial/PacketUnlockTutorialScRsp.cs index ad878349..79d31026 100644 --- a/GameServer/Server/Packet/Send/Tutorial/PacketUnlockTutorialScRsp.cs +++ b/GameServer/Server/Packet/Send/Tutorial/PacketUnlockTutorialScRsp.cs @@ -1,25 +1,19 @@ using EggLink.DanhengServer.Proto; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial +namespace EggLink.DanhengServer.Server.Packet.Send.Tutorial; + +public class PacketUnlockTutorialScRsp : BasePacket { - public class PacketUnlockTutorialScRsp : BasePacket + public PacketUnlockTutorialScRsp(uint tutorialId) : base(CmdIds.UnlockTutorialScRsp) { - public PacketUnlockTutorialScRsp(uint tutorialId) : base(CmdIds.UnlockTutorialScRsp) + var proto = new UnlockTutorialScRsp { - var proto = new UnlockTutorialScRsp + Tutorial = new Proto.Tutorial { - Tutorial = new() - { - Id = tutorialId, - Status = TutorialStatus.TutorialUnlock, - } - }; - SetData(proto); - } + Id = tutorialId, + Status = TutorialStatus.TutorialUnlock + } + }; + SetData(proto); } -} +} \ No newline at end of file diff --git a/Program/Handbook/HandbookGenerator.cs b/Program/Handbook/HandbookGenerator.cs index c4467c05..0f731e28 100644 --- a/Program/Handbook/HandbookGenerator.cs +++ b/Program/Handbook/HandbookGenerator.cs @@ -1,186 +1,179 @@ -using EggLink.DanhengServer.Data; +using System.Text; +using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Program; using EggLink.DanhengServer.Util; using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace EggLink.DanhengServer.Handbook +namespace EggLink.DanhengServer.Handbook; + +public static class HandbookGenerator { - public static class HandbookGenerator + public static readonly string HandbookPath = "Config/Handbook.txt"; + + public static void Generate() { - public static readonly string HandbookPath = "Config/Handbook.txt"; - - public static void Generate() + var config = ConfigManager.Config; + var textMapPath = config.Path.ResourcePath + "/TextMap/TextMap" + config.ServerOption.Language + ".json"; + if (!File.Exists(textMapPath)) { - var config = ConfigManager.Config; - var textMapPath = config.Path.ResourcePath + "/TextMap/TextMap" + config.ServerOption.Language + ".json"; - if (!File.Exists(textMapPath)) - { - Logger.GetByClassName().Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", textMapPath, I18nManager.Translate("Word.NotFound"))); - return; - } - var textMap = JsonConvert.DeserializeObject>(File.ReadAllText(textMapPath)); + Logger.GetByClassName().Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", textMapPath, + I18nManager.Translate("Word.NotFound"))); + return; + } - if (textMap == null) - { - Logger.GetByClassName().Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem",textMapPath, I18nManager.Translate("Word.Error"))); - return; - } + var textMap = JsonConvert.DeserializeObject>(File.ReadAllText(textMapPath)); - var builder = new StringBuilder(); - builder.AppendLine("Handbook generated in " + DateTime.Now.ToString("yyyy/MM/dd HH:mm")); - builder.AppendLine(); - builder.AppendLine("#Command"); - builder.AppendLine(); - GenerateCmd(builder); + if (textMap == null) + { + Logger.GetByClassName().Error(I18nManager.Translate("Server.ServerInfo.FailedToReadItem", textMapPath, + I18nManager.Translate("Word.Error"))); + return; + } - builder.AppendLine(); - builder.AppendLine("#Avatar"); - builder.AppendLine(); - GenerateAvatar(builder, textMap); + var builder = new StringBuilder(); + builder.AppendLine("Handbook generated in " + DateTime.Now.ToString("yyyy/MM/dd HH:mm")); + builder.AppendLine(); + builder.AppendLine("#Command"); + builder.AppendLine(); + GenerateCmd(builder); - builder.AppendLine(); - builder.AppendLine("#Item"); - builder.AppendLine(); - GenerateItem(builder, textMap); + builder.AppendLine(); + builder.AppendLine("#Avatar"); + builder.AppendLine(); + GenerateAvatar(builder, textMap); - builder.AppendLine(); - builder.AppendLine("#MainMission"); - builder.AppendLine(); - GenerateMainMissionId(builder, textMap); + builder.AppendLine(); + builder.AppendLine("#Item"); + builder.AppendLine(); + GenerateItem(builder, textMap); - builder.AppendLine(); - builder.AppendLine("#SubMission"); - builder.AppendLine(); - GenerateSubMissionId(builder, textMap); + builder.AppendLine(); + builder.AppendLine("#MainMission"); + builder.AppendLine(); + GenerateMainMissionId(builder, textMap); - builder.AppendLine(); - builder.AppendLine("#RogueBuff"); - builder.AppendLine(); - GenerateRogueBuff(builder, textMap); + builder.AppendLine(); + builder.AppendLine("#SubMission"); + builder.AppendLine(); + GenerateSubMissionId(builder, textMap); - builder.AppendLine(); - builder.AppendLine("#RogueMiracle"); - builder.AppendLine(); - GenerateRogueMiracleDisplay(builder, textMap); + builder.AppendLine(); + builder.AppendLine("#RogueBuff"); + builder.AppendLine(); + GenerateRogueBuff(builder, textMap); + + builder.AppendLine(); + builder.AppendLine("#RogueMiracle"); + builder.AppendLine(); + GenerateRogueMiracleDisplay(builder, textMap); #if DEBUG - builder.AppendLine(); - builder.AppendLine("#RogueDiceSurface"); - builder.AppendLine(); - GenerateRogueDiceSurfaceDisplay(builder, textMap); + builder.AppendLine(); + builder.AppendLine("#RogueDiceSurface"); + builder.AppendLine(); + GenerateRogueDiceSurfaceDisplay(builder, textMap); #endif - builder.AppendLine(); - WriteToFile(builder.ToString()); + builder.AppendLine(); + WriteToFile(builder.ToString()); - Logger.GetByClassName().Info(I18nManager.Translate("Server.ServerInfo.GeneratedItem", I18nManager.Translate("Word.Handbook"))); - } + Logger.GetByClassName() + .Info(I18nManager.Translate("Server.ServerInfo.GeneratedItem", I18nManager.Translate("Word.Handbook"))); + } - public static void GenerateCmd(StringBuilder builder) + public static void GenerateCmd(StringBuilder builder) + { + foreach (var cmd in EntryPoint.CommandManager.CommandInfo) { - foreach (var cmd in EntryPoint.CommandManager.CommandInfo) - { - builder.Append("\t" + cmd.Key); - var desc = I18nManager.Translate(cmd.Value.Description).Replace("\n", "\n\t\t"); - builder.AppendLine(": " + desc); - } - } - - public static void GenerateItem(StringBuilder builder, Dictionary map) - { - foreach (var item in GameData.ItemConfigData.Values) - { - var name = map.TryGetValue(item.ItemName.Hash, out var value) ? value : $"[{item.ItemName.Hash}]"; - builder.AppendLine(item.ID + ": " + name); - - if (name != $"[{item.ItemName.Hash}]") - { - item.Name = name; - } - } - } - - public static void GenerateAvatar(StringBuilder builder, Dictionary map) - { - foreach (var avatar in GameData.AvatarConfigData.Values) - { - var name = map.TryGetValue(avatar.AvatarName.Hash, out var value) ? value : $"[{avatar.AvatarName.Hash}]"; - builder.AppendLine(avatar.AvatarID + ": " + name); - - if (name != $"[{avatar.AvatarName.Hash}]") - { - avatar.Name = name; - } - } - } - - public static void GenerateMainMissionId(StringBuilder builder, Dictionary map) - { - foreach (var mission in GameData.MainMissionData.Values) - { - var name = map.TryGetValue(mission.Name.Hash, out var value) ? value : $"[{mission.Name.Hash}]"; - builder.AppendLine(mission.MainMissionID + ": " + name); - } - } - - public static void GenerateSubMissionId(StringBuilder builder, Dictionary map) - { - foreach (var mission in GameData.SubMissionData.Values) - { - var name = map.TryGetValue(mission.TargetText.Hash, out var value) ? value : $"[{mission.TargetText.Hash}]"; - builder.AppendLine(mission.SubMissionID + ": " + name); - } - } - - public static void GenerateRogueBuff(StringBuilder builder, Dictionary map) - { - foreach (var buff in GameData.RogueMazeBuffData) - { - var name = map.TryGetValue(buff.Value.BuffName.Hash, out var value) ? value : $"[{buff.Value.BuffName.Hash}]"; - builder.AppendLine(buff.Key + ": " + name + " --- Level:" + buff.Value.Lv); - - if (name != $"[{buff.Value.BuffName.Hash}]") - { - buff.Value.Name = name; - } - } - } - - public static void GenerateRogueMiracleDisplay(StringBuilder builder, Dictionary map) - { - foreach (var display in GameData.RogueMiracleData.Values) - { - var name = map.TryGetValue(display.MiracleName.Hash, out var value) ? value : $"[{display.MiracleName.Hash}]"; - builder.AppendLine(display.MiracleID + ": " + name); - - if (name != $"[{display.MiracleName.Hash}]") - { - display.Name = name; - } - } - } - -#if DEBUG - public static void GenerateRogueDiceSurfaceDisplay(StringBuilder builder, Dictionary map) - { - foreach (var display in GameData.RogueNousDiceSurfaceData.Values) - { - var name = map.TryGetValue(display.SurfaceName.Hash, out var value) ? value : $"[{display.SurfaceName.Hash}]"; - var desc = map.TryGetValue(display.SurfaceDesc.Hash, out var c) ? c : $"[{display.SurfaceDesc.Hash}]"; - builder.AppendLine(display.SurfaceID + ": " + name + "\n" + "Desc: " + desc); - } - } -#endif - - public static void WriteToFile(string content) - { - File.WriteAllText(HandbookPath, content); + builder.Append("\t" + cmd.Key); + var desc = I18nManager.Translate(cmd.Value.Description).Replace("\n", "\n\t\t"); + builder.AppendLine(": " + desc); } } -} + + public static void GenerateItem(StringBuilder builder, Dictionary map) + { + foreach (var item in GameData.ItemConfigData.Values) + { + var name = map.TryGetValue(item.ItemName.Hash, out var value) ? value : $"[{item.ItemName.Hash}]"; + builder.AppendLine(item.ID + ": " + name); + + if (name != $"[{item.ItemName.Hash}]") item.Name = name; + } + } + + public static void GenerateAvatar(StringBuilder builder, Dictionary map) + { + foreach (var avatar in GameData.AvatarConfigData.Values) + { + var name = map.TryGetValue(avatar.AvatarName.Hash, out var value) ? value : $"[{avatar.AvatarName.Hash}]"; + builder.AppendLine(avatar.AvatarID + ": " + name); + + if (name != $"[{avatar.AvatarName.Hash}]") avatar.Name = name; + } + } + + public static void GenerateMainMissionId(StringBuilder builder, Dictionary map) + { + foreach (var mission in GameData.MainMissionData.Values) + { + var name = map.TryGetValue(mission.Name.Hash, out var value) ? value : $"[{mission.Name.Hash}]"; + builder.AppendLine(mission.MainMissionID + ": " + name); + } + } + + public static void GenerateSubMissionId(StringBuilder builder, Dictionary map) + { + foreach (var mission in GameData.SubMissionData.Values) + { + var name = map.TryGetValue(mission.TargetText.Hash, out var value) ? value : $"[{mission.TargetText.Hash}]"; + builder.AppendLine(mission.SubMissionID + ": " + name); + } + } + + public static void GenerateRogueBuff(StringBuilder builder, Dictionary map) + { + foreach (var buff in GameData.RogueMazeBuffData) + { + var name = map.TryGetValue(buff.Value.BuffName.Hash, out var value) + ? value + : $"[{buff.Value.BuffName.Hash}]"; + builder.AppendLine(buff.Key + ": " + name + " --- Level:" + buff.Value.Lv); + + if (name != $"[{buff.Value.BuffName.Hash}]") buff.Value.Name = name; + } + } + + public static void GenerateRogueMiracleDisplay(StringBuilder builder, Dictionary map) + { + foreach (var display in GameData.RogueMiracleData.Values) + { + var name = map.TryGetValue(display.MiracleName.Hash, out var value) + ? value + : $"[{display.MiracleName.Hash}]"; + builder.AppendLine(display.MiracleID + ": " + name); + + if (name != $"[{display.MiracleName.Hash}]") display.Name = name; + } + } + +#if DEBUG + public static void GenerateRogueDiceSurfaceDisplay(StringBuilder builder, Dictionary map) + { + foreach (var display in GameData.RogueNousDiceSurfaceData.Values) + { + var name = map.TryGetValue(display.SurfaceName.Hash, out var value) + ? value + : $"[{display.SurfaceName.Hash}]"; + var desc = map.TryGetValue(display.SurfaceDesc.Hash, out var c) ? c : $"[{display.SurfaceDesc.Hash}]"; + builder.AppendLine(display.SurfaceID + ": " + name + "\n" + "Desc: " + desc); + } + } +#endif + + public static void WriteToFile(string content) + { + File.WriteAllText(HandbookPath, content); + } +} \ No newline at end of file diff --git a/Program/Program/EntryPoint.cs b/Program/Program/EntryPoint.cs index de774b3f..1cb1cdc1 100644 --- a/Program/Program/EntryPoint.cs +++ b/Program/Program/EntryPoint.cs @@ -1,257 +1,241 @@ -using EggLink.DanhengServer.Util; -using EggLink.DanhengServer.Data; +using EggLink.DanhengServer.Command; using EggLink.DanhengServer.Configuration; -using EggLink.DanhengServer.WebServer; +using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Database; -using EggLink.DanhengServer.Server; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json; +using EggLink.DanhengServer.Enums; +using EggLink.DanhengServer.GameServer.Command; using EggLink.DanhengServer.Handbook; using EggLink.DanhengServer.Internationalization; using EggLink.DanhengServer.Plugin; -using EggLink.DanhengServer.Command; +using EggLink.DanhengServer.Server; using EggLink.DanhengServer.Server.Packet; -using EggLink.DanhengServer.GameServer.Command; +using EggLink.DanhengServer.Util; +using EggLink.DanhengServer.WebServer; using EggLink.DanhengServer.WebServer.Server; -using EggLink.DanhengServer.Enums; -namespace EggLink.DanhengServer.Program +namespace EggLink.DanhengServer.Program; + +public class EntryPoint { - public partial class EntryPoint + private static readonly Logger logger = new("Program"); + public static readonly DatabaseHelper DatabaseHelper = new(); + public static readonly Listener Listener = new(); + public static readonly CommandManager CommandManager = new(); + + public static void Main(string[] args) { - private readonly static Logger logger = new("Program"); - public readonly static DatabaseHelper DatabaseHelper = new(); - public readonly static Listener Listener = new(); - public readonly static CommandManager CommandManager = new(); - - public static void Main(string[] args) + AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { - AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { - logger.Info(I18nManager.Translate("Server.ServerInfo.Shutdown")); - PerformCleanup(); - }; - Console.CancelKeyPress += (sender, eventArgs) => { - logger.Info(I18nManager.Translate("Server.ServerInfo.CancelKeyPressed")); - eventArgs.Cancel = true; - Environment.Exit(0); - }; - var time = DateTime.Now; - // Initialize the logfile - var counter = 0; - FileInfo file; - while (true) + logger.Info(I18nManager.Translate("Server.ServerInfo.Shutdown")); + PerformCleanup(); + }; + Console.CancelKeyPress += (sender, eventArgs) => + { + logger.Info(I18nManager.Translate("Server.ServerInfo.CancelKeyPressed")); + eventArgs.Cancel = true; + Environment.Exit(0); + }; + var time = DateTime.Now; + // Initialize the logfile + var counter = 0; + FileInfo file; + while (true) + { + file = new FileInfo(GetConfig().Path.LogPath + $"/{DateTime.Now:yyyy-MM-dd}-{++counter}.log"); + if (!file.Exists && file.Directory != null) { - file = new FileInfo(GetConfig().Path.LogPath + $"/{DateTime.Now:yyyy-MM-dd}-{++counter}.log"); - if (!file.Exists && file.Directory != null) + file.Directory.Create(); + break; + } + } + + Logger.SetLogFile(file); + // Starting the server + logger.Info(I18nManager.Translate("Server.ServerInfo.StartingServer")); + + // Load the config + logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.Config"))); + try + { + ConfigManager.LoadConfig(); + } + catch (Exception e) + { + logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.Config")), e); + Console.ReadLine(); + return; + } + + // Load the language + logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.Language"))); + try + { + I18nManager.LoadLanguage(); + } + catch (Exception e) + { + logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.Language")), e); + Console.ReadLine(); + return; + } + + // Load the game data + logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.GameData"))); + try + { + ResourceManager.LoadGameData(); + } + catch (Exception e) + { + logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.GameData")), e); + Console.ReadLine(); + return; + } + + // Initialize the database + try + { + DatabaseHelper.Initialize(); + + if (args.Contains("--upgrade-database")) DatabaseHelper.UpgradeDatabase(); + + if (args.Contains("--move")) DatabaseHelper.MoveFromSqlite(); + } + catch (Exception e) + { + logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.Database")), e); + Console.ReadLine(); + return; + } + + // Register the command handlers + try + { + CommandManager.RegisterCommand(); + } + catch (Exception e) + { + logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToInitializeItem", + I18nManager.Translate("Word.Command")), e); + Console.ReadLine(); + return; + } + + // Load the plugins + logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.Plugin"))); + try + { + PluginManager.LoadPlugins(); + } + catch (Exception e) + { + logger.Error( + I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.Plugin")), e); + Console.ReadLine(); + return; + } + + CommandExecutor.OnRunCommand += (sender, e) => { CommandManager.HandleCommand(e, sender); }; + + MuipManager.OnExecuteCommand += CommandManager.HandleCommand; + MuipManager.OnGetServerInformation += x => + { + foreach (var con in Listener.Connections.Values) + if (con.Player != null) + x.Add(con.Player.Uid, con.Player.Data); + }; + MuipManager.OnGetPlayerStatus += (int uid, out PlayerStatusEnum status, out PlayerSubStatusEnum subStatus) => + { + subStatus = PlayerSubStatusEnum.None; + foreach (var con in Listener.Connections.Values) + if (con.Player != null && con.Player.Uid == uid) { - file.Directory.Create(); - break; - } - } - - Logger.SetLogFile(file); - // Starting the server - logger.Info(I18nManager.Translate("Server.ServerInfo.StartingServer")); - - // Load the config - logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.Config"))); - try - { - ConfigManager.LoadConfig(); - } catch (Exception e) - { - logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.Config")), e); - Console.ReadLine(); - return; - } - - // Load the language - logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.Language"))); - try - { - I18nManager.LoadLanguage(); - } catch (Exception e) - { - logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.Language")), e); - Console.ReadLine(); - return; - } - - // Load the game data - logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.GameData"))); - try - { - ResourceManager.LoadGameData(); - } catch (Exception e) - { - logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.GameData")), e); - Console.ReadLine(); - return; - } - - // Initialize the database - try - { - DatabaseHelper.Initialize(); - - if (args.Contains("--upgrade-database")) - { - DatabaseHelper.UpgradeDatabase(); - } - - if (args.Contains("--move")) - { - DatabaseHelper.MoveFromSqlite(); - } - } catch (Exception e) - { - logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.Database")), e); - Console.ReadLine(); - return; - } - - // Register the command handlers - try - { - CommandManager.RegisterCommand(); - } catch (Exception e) - { - logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToInitializeItem", I18nManager.Translate("Word.Command")), e); - Console.ReadLine(); - return; - } - - // Load the plugins - logger.Info(I18nManager.Translate("Server.ServerInfo.LoadingItem", I18nManager.Translate("Word.Plugin"))); - try - { - PluginManager.LoadPlugins(); - } - catch (Exception e) - { - logger.Error(I18nManager.Translate("Server.ServerInfo.FailedToLoadItem", I18nManager.Translate("Word.Plugin")), e); - Console.ReadLine(); - return; - } - - CommandExecutor.OnRunCommand += (sender, e) => - { - CommandManager.HandleCommand(e, sender); - }; - - MuipManager.OnExecuteCommand += CommandManager.HandleCommand; - MuipManager.OnGetServerInformation += x => - { - foreach (var con in Listener.Connections.Values) - { - if (con.Player != null) + if (con.Player.RogueManager?.GetRogueInstance() != null) { - x.Add(con.Player.Uid, con.Player.Data); + status = PlayerStatusEnum.Rogue; + if (con.Player.ChessRogueManager?.RogueInstance?.AreaExcel.RogueVersionId == 202) + status = PlayerStatusEnum.ChessRogueNous; + else if (con.Player.ChessRogueManager?.RogueInstance?.AreaExcel.RogueVersionId == 201) + status = PlayerStatusEnum.ChessRogue; } - } - }; - MuipManager.OnGetPlayerStatus += (int uid, out PlayerStatusEnum status, out PlayerSubStatusEnum subStatus) => - { - subStatus = PlayerSubStatusEnum.None; - foreach (var con in Listener.Connections.Values) - { - if (con.Player != null && con.Player.Uid == uid) + else if (con.Player.ChallengeManager?.ChallengeInstance != null) { - if (con.Player.RogueManager?.GetRogueInstance() != null) - { - status = PlayerStatusEnum.Rogue; - if (con.Player.ChessRogueManager?.RogueInstance?.AreaExcel.RogueVersionId == 202) - { - status = PlayerStatusEnum.ChessRogueNous; - } - else if (con.Player.ChessRogueManager?.RogueInstance?.AreaExcel.RogueVersionId == 201) - { - status = PlayerStatusEnum.ChessRogue; - } - } - else if (con.Player.ChallengeManager?.ChallengeInstance != null) - { - status = PlayerStatusEnum.Challenge; - if (con.Player.ChallengeManager.ChallengeInstance.Excel.StoryExcel != null) - { - status = PlayerStatusEnum.ChallengeStory; - } - else if (con.Player.ChallengeManager.ChallengeInstance.Excel.BossExcel != null) - { - status = PlayerStatusEnum.ChallengeBoss; - } - } - else if (con.Player.RaidManager?.RaidData.CurRaidId != 0) - { - status = PlayerStatusEnum.Raid; - } - else if (con.Player.StoryLineManager?.StoryLineData.CurStoryLineId != 0) - { - status = PlayerStatusEnum.StoryLine; - } - else - { - status = PlayerStatusEnum.Explore; - } - - if (con.Player.BattleInstance != null) - { - subStatus = PlayerSubStatusEnum.Battle; - } - - return; + status = PlayerStatusEnum.Challenge; + if (con.Player.ChallengeManager.ChallengeInstance.Excel.StoryExcel != null) + status = PlayerStatusEnum.ChallengeStory; + else if (con.Player.ChallengeManager.ChallengeInstance.Excel.BossExcel != null) + status = PlayerStatusEnum.ChallengeBoss; } + else if (con.Player.RaidManager?.RaidData.CurRaidId != 0) + { + status = PlayerStatusEnum.Raid; + } + else if (con.Player.StoryLineManager?.StoryLineData.CurStoryLineId != 0) + { + status = PlayerStatusEnum.StoryLine; + } + else + { + status = PlayerStatusEnum.Explore; + } + + if (con.Player.BattleInstance != null) subStatus = PlayerSubStatusEnum.Battle; + + return; } - status = PlayerStatusEnum.Offline; - }; + status = PlayerStatusEnum.Offline; + }; - // generate the handbook - HandbookGenerator.Generate(); + // generate the handbook + HandbookGenerator.Generate(); - HandlerManager.Init(); + HandlerManager.Init(); - WebProgram.Main([], GetConfig().HttpServer.PublicPort, GetConfig().HttpServer.GetDisplayAddress()); - logger.Info(I18nManager.Translate("Server.ServerInfo.ServerRunning", I18nManager.Translate("Word.Dispatch"), GetConfig().HttpServer.GetDisplayAddress())); + WebProgram.Main([], GetConfig().HttpServer.PublicPort, GetConfig().HttpServer.GetDisplayAddress()); + logger.Info(I18nManager.Translate("Server.ServerInfo.ServerRunning", I18nManager.Translate("Word.Dispatch"), + GetConfig().HttpServer.GetDisplayAddress())); - Listener.StartListener(); + Listener.StartListener(); - var elapsed = DateTime.Now - time; - logger.Info(I18nManager.Translate("Server.ServerInfo.ServerStarted", elapsed.TotalSeconds.ToString()[..4])); + var elapsed = DateTime.Now - time; + logger.Info(I18nManager.Translate("Server.ServerInfo.ServerStarted", elapsed.TotalSeconds.ToString()[..4])); - GenerateLogMap(); + GenerateLogMap(); - if (GetConfig().ServerOption.EnableMission) - { - logger.Warn(I18nManager.Translate("Server.ServerInfo.MissionEnabled")); - } - CommandManager.Start(); - } + if (GetConfig().ServerOption.EnableMission) + logger.Warn(I18nManager.Translate("Server.ServerInfo.MissionEnabled")); + CommandManager.Start(); + } - public static ConfigContainer GetConfig() + public static ConfigContainer GetConfig() + { + return ConfigManager.Config; + } + + private static void PerformCleanup() + { + PluginManager.UnloadPlugins(); + Listener.Connections.Values.ToList().ForEach(x => x.Stop()); + + DatabaseHelper.SaveThread?.Interrupt(); + DatabaseHelper.SaveDatabase(); + } + + private static void GenerateLogMap() + { + // get opcode from CmdIds + var opcodes = typeof(CmdIds).GetFields().Where(x => x.FieldType == typeof(int)).ToList(); + foreach (var opcode in opcodes) { - return ConfigManager.Config; - } - - private static void PerformCleanup() - { - PluginManager.UnloadPlugins(); - Listener.Connections.Values.ToList().ForEach(x => x.Stop()); - - DatabaseHelper.SaveThread?.Interrupt(); - DatabaseHelper.SaveDatabase(); - } - - private static void GenerateLogMap() - { - // get opcode from CmdIds - var opcodes = typeof(CmdIds).GetFields().Where(x => x.FieldType == typeof(int)).ToList(); - foreach (var opcode in opcodes) - { - var name = opcode.Name; - var value = (int)opcode.GetValue(null)!; - Connection.LogMap.Add(value.ToString(), name); - } + var name = opcode.Name; + var value = (int)opcode.GetValue(null)!; + Connection.LogMap.Add(value.ToString(), name); } } -} +} \ No newline at end of file diff --git a/WebServer/Controllers/DispatchRoutes.cs b/WebServer/Controllers/DispatchRoutes.cs index ca64177c..f2a6cc83 100644 --- a/WebServer/Controllers/DispatchRoutes.cs +++ b/WebServer/Controllers/DispatchRoutes.cs @@ -4,86 +4,194 @@ using EggLink.DanhengServer.Util; using EggLink.DanhengServer.WebServer.Handler; using EggLink.DanhengServer.WebServer.Objects; using Google.Protobuf; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; using Microsoft.AspNetCore.Cors; -namespace EggLink.DanhengServer.WebServer.Controllers +using Microsoft.AspNetCore.Mvc; + +namespace EggLink.DanhengServer.WebServer.Controllers; + +[ApiController] +[EnableCors("AllowAll")] +[Route("/")] +public class DispatchRoutes { - [ApiController] - [EnableCors("AllowAll")] - [Route("/")] - public class DispatchRoutes + public static ConfigContainer config = ConfigManager.Config; + public static Logger Logger = new("DispatchServer"); + + [HttpGet("query_dispatch")] + public string QueryDispatch() { - public static ConfigContainer config = ConfigManager.Config; - public static Logger Logger = new("DispatchServer"); - - [HttpGet("query_dispatch")] - public string QueryDispatch() + var data = new Dispatch(); + data.RegionList.Add(new RegionInfo { - var data = new Dispatch(); - data.RegionList.Add(new RegionInfo() - { - Name = config.GameServer.GameServerId, - DispatchUrl = $"{config.HttpServer.GetDisplayAddress()}/query_gateway", - EnvType = "2", - DisplayName = config.GameServer.GameServerName - }); - Logger.Info("Client request: query_dispatch"); - return Convert.ToBase64String(data.ToByteArray()); - } - - [HttpPost("/account/risky/api/check")] - public ContentResult RiskyCheck() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}", ContentType = "application/json" }; - - // === AUTHENTICATION === - [HttpPost("/hkrpg_global/mdk/shield/api/login")] - public JsonResult Login([FromBody] LoginReqJson req) => new UsernameLoginHandler().Handle(req.account!, req.password!, req.is_crypto); - [HttpPost("/hkrpg_global/account/ma-passport/api/appLoginByPassword")] - public JsonResult Login([FromBody] NewLoginReqJson req) => new NewUsernameLoginHandler().Handle(req.account!, req.password!); - [HttpPost("/hkrpg_global/mdk/shield/api/verify")] - public JsonResult Verify([FromBody] VerifyReqJson req) => new TokenLoginHandler().Handle(req.uid!, req.token!); - [HttpPost("/hkrpg_global/combo/granter/login/v2/login")] - public JsonResult LoginV2([FromBody] LoginV2ReqJson req) => new ComboTokenGranterHandler().Handle(req.app_id, req.channel_id, req.data!, req.device!, req.sign!); - - [HttpGet("/hkrpg_global/combo/granter/api/getConfig")] - public ContentResult GetConfig() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"\",\"push_alias_type\":0,\"disable_ysdk_guard\":true,\"enable_announce_pic_popup\":false,\"app_name\":\"崩�??RPG\",\"qr_enabled_apps\":{\"bbs\":false,\"cloud\":false},\"qr_app_icons\":{\"app\":\"\",\"bbs\":\"\",\"cloud\":\"\"},\"qr_cloud_display_name\":\"\",\"enable_user_center\":true,\"functional_switch_configs\":{}}}", ContentType = "application/json" }; - - [HttpGet("/hkrpg_global/combo/red_dot/list")] - [HttpPost("/hkrpg_global/combo/red_dot/list")] - public ContentResult RedDot() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"infos\":[]}}", ContentType = "application/json" }; - - [HttpGet("/common/hkrpg_global/announcement/api/getAlertAnn")] - public ContentResult AlertAnn() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":false,\"extra_remind\":false}}", ContentType = "application/json" }; - - - [HttpGet("/common/hkrpg_global/announcement/api/getAlertPic")] - public ContentResult AlertPic() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}", ContentType = "application/json" }; - - - - - [HttpGet("/hkrpg_global/mdk/shield/api/loadConfig")] - public ContentResult LoadConfig() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":24,\"game_key\":\"hkrpg_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"崩�??RPG\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\",\"gl\",\"ap\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":2592000},\"ap\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":2592000},\"gl\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}},\"initialize_firebase\":false,\"bbs_auth_login\":false,\"bbs_auth_login_ignore\":[],\"fetch_instance_id\":false,\"enable_flash_login\":false}}", ContentType = "application/json" }; - - - // === EXTRA === - - [HttpPost("/hkrpg_global/combo/granter/api/compareProtocolVersion")] - public ContentResult CompareProtocolVer() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":false,\"protocol\":null}}", ContentType = "application/json" }; - [HttpGet("/hkrpg_global/mdk/agreement/api/getAgreementInfos")] - public ContentResult GetAgreementInfo() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}", ContentType = "application/json" }; - - [HttpGet("/combo/box/api/config/sdk/combo")] - public ContentResult Combo() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"kibana_pc_config\":\"{ \\\"enable\\\": 0, \\\"level\\\": \\\"Info\\\",\\\"modules\\\": [\\\"download\\\"] }\\n\",\"network_report_config\":\"{ \\\"enable\\\": 0, \\\"status_codes\\\": [206], \\\"url_paths\\\": [\\\"dataUpload\\\", \\\"red_dot\\\"] }\\n\",\"list_price_tierv2_enable\":\"false\\n\",\"pay_payco_centered_host\":\"bill.payco.com\",\"telemetry_config\":\"{\\n \\\"dataupload_enable\\\": 0,\\n}\",\"enable_web_dpi\":\"true\"}}}", ContentType = "application/json" }; - [HttpGet("/combo/box/api/config/sw/precache")] - public ContentResult Precache() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"url\":\"\",\"enable\":\"false\"}}}", ContentType = "application/json" }; - - [HttpGet("/device-fp/api/getFp")] - public JsonResult GetFp([FromQuery] string device_fp) => new FingerprintHandler().GetFp(device_fp); - [HttpGet("/device-fp/api/getExtList")] - public ContentResult GetExtList() => new() { Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"code\":200,\"msg\":\"ok\",\"ext_list\":[],\"pkg_list\":[],\"pkg_str\":\"/vK5WTh5SS3SAj8Zm0qPWg==\"}}", ContentType = "application/json" }; - - [HttpPost("/data_abtest_api/config/experiment/list")] - public ContentResult GetExperimentList() => new() { Content = "{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6125_197\",\"version\":\"1\",\"configs\":{\"cardType\":\"direct\"}}]}", ContentType = "application/json" }; + Name = config.GameServer.GameServerId, + DispatchUrl = $"{config.HttpServer.GetDisplayAddress()}/query_gateway", + EnvType = "2", + DisplayName = config.GameServer.GameServerName + }); + Logger.Info("Client request: query_dispatch"); + return Convert.ToBase64String(data.ToByteArray()); } -} + + [HttpPost("/account/risky/api/check")] + public ContentResult RiskyCheck() + { + return new ContentResult + { + Content = + "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}", + ContentType = "application/json" + }; + } + + // === AUTHENTICATION === + [HttpPost("/hkrpg_global/mdk/shield/api/login")] + public JsonResult Login([FromBody] LoginReqJson req) + { + return new UsernameLoginHandler().Handle(req.account!, req.password!, req.is_crypto); + } + + [HttpPost("/hkrpg_global/account/ma-passport/api/appLoginByPassword")] + public JsonResult Login([FromBody] NewLoginReqJson req) + { + return new NewUsernameLoginHandler().Handle(req.account!, req.password!); + } + + [HttpPost("/hkrpg_global/mdk/shield/api/verify")] + public JsonResult Verify([FromBody] VerifyReqJson req) + { + return new TokenLoginHandler().Handle(req.uid!, req.token!); + } + + [HttpPost("/hkrpg_global/combo/granter/login/v2/login")] + public JsonResult LoginV2([FromBody] LoginV2ReqJson req) + { + return new ComboTokenGranterHandler().Handle(req.app_id, req.channel_id, req.data!, req.device!, req.sign!); + } + + [HttpGet("/hkrpg_global/combo/granter/api/getConfig")] + public ContentResult GetConfig() + { + return new ContentResult + { + Content = + "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"\",\"push_alias_type\":0,\"disable_ysdk_guard\":true,\"enable_announce_pic_popup\":false,\"app_name\":\"崩�??RPG\",\"qr_enabled_apps\":{\"bbs\":false,\"cloud\":false},\"qr_app_icons\":{\"app\":\"\",\"bbs\":\"\",\"cloud\":\"\"},\"qr_cloud_display_name\":\"\",\"enable_user_center\":true,\"functional_switch_configs\":{}}}", + ContentType = "application/json" + }; + } + + [HttpGet("/hkrpg_global/combo/red_dot/list")] + [HttpPost("/hkrpg_global/combo/red_dot/list")] + public ContentResult RedDot() + { + return new ContentResult + { + Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"infos\":[]}}", ContentType = "application/json" + }; + } + + [HttpGet("/common/hkrpg_global/announcement/api/getAlertAnn")] + public ContentResult AlertAnn() + { + return new ContentResult + { + Content = + "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":false,\"extra_remind\":false}}", + ContentType = "application/json" + }; + } + + + [HttpGet("/common/hkrpg_global/announcement/api/getAlertPic")] + public ContentResult AlertPic() + { + return new ContentResult + { + Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}", + ContentType = "application/json" + }; + } + + + [HttpGet("/hkrpg_global/mdk/shield/api/loadConfig")] + public ContentResult LoadConfig() + { + return new ContentResult + { + Content = + "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":24,\"game_key\":\"hkrpg_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"崩�??RPG\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\",\"gl\",\"ap\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":2592000},\"ap\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":2592000},\"gl\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}},\"initialize_firebase\":false,\"bbs_auth_login\":false,\"bbs_auth_login_ignore\":[],\"fetch_instance_id\":false,\"enable_flash_login\":false}}", + ContentType = "application/json" + }; + } + + + // === EXTRA === + + [HttpPost("/hkrpg_global/combo/granter/api/compareProtocolVersion")] + public ContentResult CompareProtocolVer() + { + return new ContentResult + { + Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":false,\"protocol\":null}}", + ContentType = "application/json" + }; + } + + [HttpGet("/hkrpg_global/mdk/agreement/api/getAgreementInfos")] + public ContentResult GetAgreementInfo() + { + return new ContentResult + { + Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}", + ContentType = "application/json" + }; + } + + [HttpGet("/combo/box/api/config/sdk/combo")] + public ContentResult Combo() + { + return new ContentResult + { + Content = + "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"kibana_pc_config\":\"{ \\\"enable\\\": 0, \\\"level\\\": \\\"Info\\\",\\\"modules\\\": [\\\"download\\\"] }\\n\",\"network_report_config\":\"{ \\\"enable\\\": 0, \\\"status_codes\\\": [206], \\\"url_paths\\\": [\\\"dataUpload\\\", \\\"red_dot\\\"] }\\n\",\"list_price_tierv2_enable\":\"false\\n\",\"pay_payco_centered_host\":\"bill.payco.com\",\"telemetry_config\":\"{\\n \\\"dataupload_enable\\\": 0,\\n}\",\"enable_web_dpi\":\"true\"}}}", + ContentType = "application/json" + }; + } + + [HttpGet("/combo/box/api/config/sw/precache")] + public ContentResult Precache() + { + return new ContentResult + { + Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"url\":\"\",\"enable\":\"false\"}}}", + ContentType = "application/json" + }; + } + + [HttpGet("/device-fp/api/getFp")] + public JsonResult GetFp([FromQuery] string device_fp) + { + return new FingerprintHandler().GetFp(device_fp); + } + + [HttpGet("/device-fp/api/getExtList")] + public ContentResult GetExtList() + { + return new ContentResult + { + Content = + "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"code\":200,\"msg\":\"ok\",\"ext_list\":[],\"pkg_list\":[],\"pkg_str\":\"/vK5WTh5SS3SAj8Zm0qPWg==\"}}", + ContentType = "application/json" + }; + } + + [HttpPost("/data_abtest_api/config/experiment/list")] + public ContentResult GetExperimentList() + { + return new ContentResult + { + Content = + "{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6125_197\",\"version\":\"1\",\"configs\":{\"cardType\":\"direct\"}}]}", + ContentType = "application/json" + }; + } +} \ No newline at end of file diff --git a/WebServer/Controllers/GateServerRoutes.cs b/WebServer/Controllers/GateServerRoutes.cs index c12d88a5..60713ae8 100644 --- a/WebServer/Controllers/GateServerRoutes.cs +++ b/WebServer/Controllers/GateServerRoutes.cs @@ -1,13 +1,15 @@ using EggLink.DanhengServer.WebServer.Handler; using Microsoft.AspNetCore.Mvc; -namespace EggLink.DanhengServer.WebServer.Controllers +namespace EggLink.DanhengServer.WebServer.Controllers; + +[ApiController] +[Route("/")] +public class GateServerRoutes { - [ApiController] - [Route("/")] - public class GateServerRoutes + [HttpGet("/query_gateway")] + public string QueryGateway() { - [HttpGet("/query_gateway")] - public string QueryGateway() => new QueryGatewayHandler().Data; + return new QueryGatewayHandler().Data; } -} +} \ No newline at end of file diff --git a/WebServer/Controllers/LogServerRoutes.cs b/WebServer/Controllers/LogServerRoutes.cs index f19ec505..43f25bde 100644 --- a/WebServer/Controllers/LogServerRoutes.cs +++ b/WebServer/Controllers/LogServerRoutes.cs @@ -1,17 +1,23 @@ using Microsoft.AspNetCore.Mvc; -namespace EggLink.DanhengServer.WebServer.Controllers -{ - [ApiController] - [Route("/")] - public class LogServerRoutes - { - [HttpPost("/sdk/dataUpload")] - [HttpPost("/crashdump/dataUpload")] - [HttpPost("/apm/dataUpload")] - public ContentResult LogUpload() => new() { Content = "{\"code\":0}", ContentType = "application/json" }; +namespace EggLink.DanhengServer.WebServer.Controllers; - [HttpPost("/common/h5log/log/batch")] - public ContentResult BatchUpload() => new() { Content = "{\"retcode\":0,\"message\":\"success\",\"data\":null}", ContentType = "application/json" }; +[ApiController] +[Route("/")] +public class LogServerRoutes +{ + [HttpPost("/sdk/dataUpload")] + [HttpPost("/crashdump/dataUpload")] + [HttpPost("/apm/dataUpload")] + public ContentResult LogUpload() + { + return new ContentResult { Content = "{\"code\":0}", ContentType = "application/json" }; } -} + + [HttpPost("/common/h5log/log/batch")] + public ContentResult BatchUpload() + { + return new ContentResult + { Content = "{\"retcode\":0,\"message\":\"success\",\"data\":null}", ContentType = "application/json" }; + } +} \ No newline at end of file diff --git a/WebServer/Controllers/MuipServerRoutes.cs b/WebServer/Controllers/MuipServerRoutes.cs index 08376870..5db822a6 100644 --- a/WebServer/Controllers/MuipServerRoutes.cs +++ b/WebServer/Controllers/MuipServerRoutes.cs @@ -1,49 +1,46 @@ -using EggLink.DanhengServer.Util; -using EggLink.DanhengServer.WebServer.Request; +using EggLink.DanhengServer.WebServer.Request; using EggLink.DanhengServer.WebServer.Response; using EggLink.DanhengServer.WebServer.Server; +using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Cors; -namespace EggLink.DanhengServer.WebServer.Controllers +namespace EggLink.DanhengServer.WebServer.Controllers; + +[ApiController] +[EnableCors("AllowAll")] +[Route("/")] +public class MuipServerRoutes { - [ApiController] - [EnableCors("AllowAll")] - [Route("/")] - public class MuipServerRoutes + [HttpGet("/muip/auth_admin")] + [HttpPost("/muip/auth_admin")] + public IActionResult AuthAdminKey([FromBody] AuthAdminKeyRequestBody req) { - [HttpGet("/muip/auth_admin")] - [HttpPost("/muip/auth_admin")] - public IActionResult AuthAdminKey([FromBody] AuthAdminKeyRequestBody req) - { - var data = MuipManager.AuthAdminAndCreateSession(req.admin_key, req.key_type); - if (data == null) - { - return new JsonResult(new AuthAdminKeyResponse(1, "Admin key is invalid or the function is not enabled!", null)); - } - return new JsonResult(new AuthAdminKeyResponse(0, "Authorized admin key successfully!", data)); - } - - [HttpGet("/muip/exec_cmd")] - [HttpPost("/muip/exec_cmd")] - public IActionResult ExecuteCommand([FromBody] AdminExecRequest req) - { - var resp = MuipManager.ExecuteCommand(req.SessionId, req.Command, req.TargetUid); - return new JsonResult(resp); - } - - [HttpGet("/muip/server_information")] - public IActionResult GetServerInformation([FromQuery] ServerInformationRequest req) - { - var resp = MuipManager.GetInformation(req.SessionId); - return new JsonResult(resp); - } - - [HttpGet("/muip/player_information")] - public IActionResult GetPlayerInformation([FromQuery] PlayerInformationRequest req) - { - var resp = MuipManager.GetPlayerInformation(req.SessionId, req.Uid); - return new JsonResult(resp); - } + var data = MuipManager.AuthAdminAndCreateSession(req.admin_key, req.key_type); + if (data == null) + return new JsonResult(new AuthAdminKeyResponse(1, "Admin key is invalid or the function is not enabled!", + null)); + return new JsonResult(new AuthAdminKeyResponse(0, "Authorized admin key successfully!", data)); } -} + + [HttpGet("/muip/exec_cmd")] + [HttpPost("/muip/exec_cmd")] + public IActionResult ExecuteCommand([FromBody] AdminExecRequest req) + { + var resp = MuipManager.ExecuteCommand(req.SessionId, req.Command, req.TargetUid); + return new JsonResult(resp); + } + + [HttpGet("/muip/server_information")] + public IActionResult GetServerInformation([FromQuery] ServerInformationRequest req) + { + var resp = MuipManager.GetInformation(req.SessionId); + return new JsonResult(resp); + } + + [HttpGet("/muip/player_information")] + public IActionResult GetPlayerInformation([FromQuery] PlayerInformationRequest req) + { + var resp = MuipManager.GetPlayerInformation(req.SessionId, req.Uid); + return new JsonResult(resp); + } +} \ No newline at end of file diff --git a/WebServer/Handler/ComboTokenGranterHandler.cs b/WebServer/Handler/ComboTokenGranterHandler.cs index fa7b2cee..e58ec292 100644 --- a/WebServer/Handler/ComboTokenGranterHandler.cs +++ b/WebServer/Handler/ComboTokenGranterHandler.cs @@ -3,38 +3,38 @@ using EggLink.DanhengServer.WebServer.Objects; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -namespace EggLink.DanhengServer.WebServer.Handler +namespace EggLink.DanhengServer.WebServer.Handler; + +public class ComboTokenGranterHandler { - public class ComboTokenGranterHandler + public JsonResult Handle(int app_id, int channel_id, string data, string device, string sign) { - public JsonResult Handle(int app_id, int channel_id, string data, string device, string sign) + var tokenData = JsonConvert.DeserializeObject(data); + var res = new ComboTokenResJson(); + if (tokenData == null) { - var tokenData = JsonConvert.DeserializeObject(data); - ComboTokenResJson res = new ComboTokenResJson(); - if (tokenData == null) - { - res.retcode = -202; - res.message = "Invalid login data"; - return new JsonResult(res); - } - AccountData? account = AccountData.GetAccountByUid(int.Parse(tokenData.uid!)); - if (account == null) - { - res.retcode = -201; - res.message = "Game account cache information error"; - return new JsonResult(res); - } else - { - res.message = "OK"; - res.data = new ComboTokenResJson.LoginData(account.Uid.ToString(), account.GenerateComboToken()); - } + res.retcode = -202; + res.message = "Invalid login data"; return new JsonResult(res); } - } - public class LoginTokenData - { - public string? uid { get; set; } - public string? token { get; set; } - public bool guest { get; set; } + + var account = AccountData.GetAccountByUid(int.Parse(tokenData.uid!)); + if (account == null) + { + res.retcode = -201; + res.message = "Game account cache information error"; + return new JsonResult(res); + } + + res.message = "OK"; + res.data = new ComboTokenResJson.LoginData(account.Uid.ToString(), account.GenerateComboToken()); + return new JsonResult(res); } } + +public class LoginTokenData +{ + public string? uid { get; set; } + public string? token { get; set; } + public bool guest { get; set; } +} \ No newline at end of file diff --git a/WebServer/Handler/FingerprintHandler.cs b/WebServer/Handler/FingerprintHandler.cs index cddb46cf..f37d7aa9 100644 --- a/WebServer/Handler/FingerprintHandler.cs +++ b/WebServer/Handler/FingerprintHandler.cs @@ -1,45 +1,45 @@ using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; using static EggLink.DanhengServer.WebServer.Handler.FingerprintResJson; -namespace EggLink.DanhengServer.WebServer.Handler +namespace EggLink.DanhengServer.WebServer.Handler; + +public class FingerprintHandler { - public class FingerprintHandler + public JsonResult GetFp(string device_fp) { - public JsonResult GetFp(string device_fp) + FingerprintResJson res = new(); + if (device_fp == null) { - FingerprintResJson res = new(); - if (device_fp == null) - { - res.retcode = -202; - res.message = "Error"; - } else - { - res.message = "OK"; - res.data = new FingerprintDataJson(device_fp); - } - return new JsonResult(res); + res.retcode = -202; + res.message = "Error"; } - } - - public class FingerprintResJson - { - public string? message { get; set; } - public int retcode { get; set; } - public FingerprintDataJson? data { get; set; } - - public class FingerprintDataJson + else { - public string device_fp { get; set; } - public string message { get; set; } - public int code { get; set; } - - public FingerprintDataJson(string fp) - { - code = 200; - message = "OK"; - device_fp = fp; - } + res.message = "OK"; + res.data = new FingerprintDataJson(device_fp); } + + return new JsonResult(res); } } + +public class FingerprintResJson +{ + public string? message { get; set; } + public int retcode { get; set; } + public FingerprintDataJson? data { get; set; } + + public class FingerprintDataJson + { + public FingerprintDataJson(string fp) + { + code = 200; + message = "OK"; + device_fp = fp; + } + + public string device_fp { get; set; } + public string message { get; set; } + public int code { get; set; } + } +} \ No newline at end of file diff --git a/WebServer/Handler/NewUsernameLoginHandler.cs b/WebServer/Handler/NewUsernameLoginHandler.cs index 5a48fb1e..b7c4302b 100644 --- a/WebServer/Handler/NewUsernameLoginHandler.cs +++ b/WebServer/Handler/NewUsernameLoginHandler.cs @@ -1,37 +1,38 @@ -using Microsoft.AspNetCore.Mvc; -using EggLink.DanhengServer.Database.Account; +using EggLink.DanhengServer.Database.Account; using EggLink.DanhengServer.Util; -using static EggLink.DanhengServer.WebServer.Objects.NewLoginResJson; using EggLink.DanhengServer.WebServer.Objects; +using Microsoft.AspNetCore.Mvc; +using static EggLink.DanhengServer.WebServer.Objects.NewLoginResJson; -namespace EggLink.DanhengServer.WebServer.Handler +namespace EggLink.DanhengServer.WebServer.Handler; + +public class NewUsernameLoginHandler { - public class NewUsernameLoginHandler + public JsonResult Handle(string account, string password) { - public JsonResult Handle(string account, string password) + NewLoginResJson res = new(); + var accountData = AccountData.GetAccountByUserName(account); + + if (accountData == null) { - NewLoginResJson res = new(); - AccountData? accountData = AccountData.GetAccountByUserName(account); - - if (accountData == null) + if (ConfigManager.Config.ServerOption.AutoCreateUser) { - if (ConfigManager.Config.ServerOption.AutoCreateUser) - { - AccountHelper.CreateAccount(account, 0); - accountData = AccountData.GetAccountByUserName(account); - } - else - { - return new JsonResult(new NewLoginResJson { message = "Account not found", retcode = -201 }); - } + AccountHelper.CreateAccount(account, 0); + accountData = AccountData.GetAccountByUserName(account); } - if (accountData != null) + else { - res.message = "OK"; - res.data = new VerifyData(accountData.Uid.ToString(), accountData.Username + "@egglink.me", accountData.GenerateDispatchToken()); + return new JsonResult(new NewLoginResJson { message = "Account not found", retcode = -201 }); } - - return new JsonResult(res); } + + if (accountData != null) + { + res.message = "OK"; + res.data = new VerifyData(accountData.Uid.ToString(), accountData.Username + "@egglink.me", + accountData.GenerateDispatchToken()); + } + + return new JsonResult(res); } -} +} \ No newline at end of file diff --git a/WebServer/Handler/QueryGatewayHandler.cs b/WebServer/Handler/QueryGatewayHandler.cs index 24705b6b..0db22df9 100644 --- a/WebServer/Handler/QueryGatewayHandler.cs +++ b/WebServer/Handler/QueryGatewayHandler.cs @@ -2,55 +2,52 @@ using EggLink.DanhengServer.Util; using Google.Protobuf; -namespace EggLink.DanhengServer.WebServer.Handler +namespace EggLink.DanhengServer.WebServer.Handler; + +internal class QueryGatewayHandler { - internal class QueryGatewayHandler + public static Logger Logger = new("GatewayServer"); + public string Data; + + public QueryGatewayHandler() { - public static Logger Logger = new("GatewayServer"); - public string Data; - public QueryGatewayHandler() + var config = ConfigManager.Config; + var urlData = config.DownloadUrl; + + // build gateway proto + var gateServer = new GateServer { - var config = ConfigManager.Config; - var urlData = config.DownloadUrl; + RegionName = config.GameServer.GameServerId, + Ip = config.GameServer.PublicAddress, + Port = config.GameServer.PublicPort, + Msg = "Access verification failed. Please check if you have logged in to the correct account and server.", + B1 = true, + B2 = true, + B3 = true, + B4 = true, + B5 = true + }; - // build gateway proto - var gateServer = new GateServer() - { - RegionName = config.GameServer.GameServerId, - Ip = config.GameServer.PublicAddress, - Port = config.GameServer.PublicPort, - Msg = "Access verification failed. Please check if you have logged in to the correct account and server.", - B1 = true, - B2 = true, - B3 = true, - B4 = true, - B5 = true, - }; + if (urlData.AssetBundleUrl != null && urlData.AssetBundleUrl.Length > 0) + gateServer.AssetBundleUrl = urlData.AssetBundleUrl; - if (urlData.AssetBundleUrl != null && urlData.AssetBundleUrl.Length > 0) - { - gateServer.AssetBundleUrl = urlData.AssetBundleUrl; - } + if (urlData.ExResourceUrl != null && urlData.ExResourceUrl.Length > 0) + gateServer.ExResourceUrl = urlData.ExResourceUrl; - if (urlData.ExResourceUrl != null && urlData.ExResourceUrl.Length > 0) - { - gateServer.ExResourceUrl = urlData.ExResourceUrl; - } - - if (urlData.LuaUrl != null && urlData.LuaUrl.Length > 0) - { - gateServer.LuaUrl = urlData.LuaUrl; - gateServer.MdkResVersion = urlData.LuaUrl.Split('/')[^1].Split('_')[1]; - } - - if (urlData.IfixUrl != null && urlData.IfixUrl.Length > 0) - { - gateServer.IfixUrl = urlData.IfixUrl; - gateServer.IfixVersion = urlData.IfixUrl.Split('/')[^1].Split('_')[1]; - } - Logger.Info("Client request: query_gateway"); - - Data = Convert.ToBase64String(gateServer.ToByteArray()); + if (urlData.LuaUrl != null && urlData.LuaUrl.Length > 0) + { + gateServer.LuaUrl = urlData.LuaUrl; + gateServer.MdkResVersion = urlData.LuaUrl.Split('/')[^1].Split('_')[1]; } + + if (urlData.IfixUrl != null && urlData.IfixUrl.Length > 0) + { + gateServer.IfixUrl = urlData.IfixUrl; + gateServer.IfixVersion = urlData.IfixUrl.Split('/')[^1].Split('_')[1]; + } + + Logger.Info("Client request: query_gateway"); + + Data = Convert.ToBase64String(gateServer.ToByteArray()); } -} +} \ No newline at end of file diff --git a/WebServer/Handler/TokenLoginHandler.cs b/WebServer/Handler/TokenLoginHandler.cs index 5850d40d..1a457d89 100644 --- a/WebServer/Handler/TokenLoginHandler.cs +++ b/WebServer/Handler/TokenLoginHandler.cs @@ -3,25 +3,25 @@ using EggLink.DanhengServer.WebServer.Objects; using Microsoft.AspNetCore.Mvc; using static EggLink.DanhengServer.WebServer.Objects.LoginResJson; -namespace EggLink.DanhengServer.WebServer.Handler +namespace EggLink.DanhengServer.WebServer.Handler; + +public class TokenLoginHandler { - public class TokenLoginHandler + public JsonResult Handle(string uid, string token) { - public JsonResult Handle(string uid, string token) + var account = AccountData.GetAccountByUid(int.Parse(uid)); + var res = new LoginResJson(); + if (account == null || !account?.DispatchToken?.Equals(token) == true) { - AccountData? account = AccountData.GetAccountByUid(int.Parse(uid)); - var res = new LoginResJson(); - if (account == null || !account?.DispatchToken?.Equals(token) == true) - { - res.retcode = -201; - res.message = "Game account cache information error"; - } - else - { - res.message = "OK"; - res.data = new VerifyData(account!.Uid.ToString(), account.Username + "@egglink.me", token); - } - return new JsonResult(res); + res.retcode = -201; + res.message = "Game account cache information error"; } + else + { + res.message = "OK"; + res.data = new VerifyData(account!.Uid.ToString(), account.Username + "@egglink.me", token); + } + + return new JsonResult(res); } -} +} \ No newline at end of file diff --git a/WebServer/Handler/UsernameLoginHandler.cs b/WebServer/Handler/UsernameLoginHandler.cs index 32f11b31..baa2c116 100644 --- a/WebServer/Handler/UsernameLoginHandler.cs +++ b/WebServer/Handler/UsernameLoginHandler.cs @@ -1,37 +1,38 @@ -using Microsoft.AspNetCore.Mvc; -using EggLink.DanhengServer.Database.Account; +using EggLink.DanhengServer.Database.Account; using EggLink.DanhengServer.Util; -using static EggLink.DanhengServer.WebServer.Objects.LoginResJson; using EggLink.DanhengServer.WebServer.Objects; +using Microsoft.AspNetCore.Mvc; +using static EggLink.DanhengServer.WebServer.Objects.LoginResJson; -namespace EggLink.DanhengServer.WebServer.Handler +namespace EggLink.DanhengServer.WebServer.Handler; + +public class UsernameLoginHandler { - public class UsernameLoginHandler + public JsonResult Handle(string account, string password, bool isCrypto) { - public JsonResult Handle(string account, string password, bool isCrypto) + LoginResJson res = new(); + var accountData = AccountData.GetAccountByUserName(account); + + if (accountData == null) { - LoginResJson res = new(); - AccountData? accountData = AccountData.GetAccountByUserName(account); - - if (accountData == null) + if (ConfigManager.Config.ServerOption.AutoCreateUser) { - if (ConfigManager.Config.ServerOption.AutoCreateUser) - { - AccountHelper.CreateAccount(account, 0); - accountData = AccountData.GetAccountByUserName(account); - } - else - { - return new JsonResult(new LoginResJson { message = "Account not found", retcode = -201 }); - } + AccountHelper.CreateAccount(account, 0); + accountData = AccountData.GetAccountByUserName(account); } - if (accountData != null) + else { - res.message = "OK"; - res.data = new VerifyData(accountData.Uid.ToString(), accountData.Username + "@egglink.me", accountData.GenerateDispatchToken()); + return new JsonResult(new LoginResJson { message = "Account not found", retcode = -201 }); } - - return new JsonResult(res); } + + if (accountData != null) + { + res.message = "OK"; + res.data = new VerifyData(accountData.Uid.ToString(), accountData.Username + "@egglink.me", + accountData.GenerateDispatchToken()); + } + + return new JsonResult(res); } -} +} \ No newline at end of file diff --git a/WebServer/Objects/ComboTokenResJson.cs b/WebServer/Objects/ComboTokenResJson.cs index 4da3c736..d6504e09 100644 --- a/WebServer/Objects/ComboTokenResJson.cs +++ b/WebServer/Objects/ComboTokenResJson.cs @@ -1,26 +1,25 @@ -namespace EggLink.DanhengServer.WebServer.Objects +namespace EggLink.DanhengServer.WebServer.Objects; + +public class ComboTokenResJson { - public class ComboTokenResJson + public string? message { get; set; } + public int retcode { get; set; } + public LoginData? data { get; set; } = null; + + public class LoginData { - public string? message { get; set; } - public int retcode { get; set; } - public LoginData? data { get; set; } = null; - - public class LoginData + public LoginData(string openId, string comboToken) { - public int account_type { get; set; } = 1; - public bool heartbeat { get; set; } - public string? combo_id { get; set; } - public string? combo_token { get; set; } - public string? open_id { get; set; } - public string data { get; set; } = "{\"guest\":false}"; - public string? fatigue_remind { get; set; } = null; // ? - - public LoginData(string openId, string comboToken) - { - open_id = openId; - combo_token = comboToken; - } + open_id = openId; + combo_token = comboToken; } + + public int account_type { get; set; } = 1; + public bool heartbeat { get; set; } + public string? combo_id { get; set; } + public string? combo_token { get; set; } + public string? open_id { get; set; } + public string data { get; set; } = "{\"guest\":false}"; + public string? fatigue_remind { get; set; } = null; // ? } -} +} \ No newline at end of file diff --git a/WebServer/Objects/LoginResJson.cs b/WebServer/Objects/LoginResJson.cs index 57991e43..f3337b41 100644 --- a/WebServer/Objects/LoginResJson.cs +++ b/WebServer/Objects/LoginResJson.cs @@ -1,49 +1,48 @@ -namespace EggLink.DanhengServer.WebServer.Objects +namespace EggLink.DanhengServer.WebServer.Objects; + +public class LoginResJson { - public class LoginResJson + public string? message { get; set; } + public int retcode { get; set; } + public VerifyData? data { get; set; } + + public class VerifyData { - public string? message { get; set; } - public int retcode { get; set; } - public VerifyData? data { get; set; } - - public class VerifyData + public VerifyData(string accountUid, string email, string token) { - public VerifyAccountData account { get; set; } = new(); - public bool device_grant_required { get; set; } = false; - public string realname_operation { get; set; } = "NONE"; - public bool realperson_required { get; set; } = false; - public bool safe_mobile_required { get; set; } = false; - - public VerifyData(string accountUid, string email, string token) - { - account.uid = accountUid; - account.email = email; - account.token = token; - } + account.uid = accountUid; + account.email = email; + account.token = token; } - public class VerifyAccountData - { - public string? uid { get; set; } - public string name { get; set; } = ""; - public string email { get; set; } = ""; - public string mobile { get; set; } = ""; - public string is_email_verify { get; set; } = "0"; - public string realname { get; set; } = ""; - public string identity_card { get; set; } = ""; - public string? token { get; set; } - public string? safe_mobile { get; set; } = ""; - public string facebook_name { get; set; } = ""; - public string twitter_name { get; set; } = ""; - public string game_center_name { get; set; } = ""; - public string google_name { get; set; } = ""; - public string apple_name { get; set; } = ""; - public string sony_name { get; set; } = ""; - public string tap_name { get; set; } = ""; - public string country { get; set; } = "US"; - public string reactivate_ticket { get; set; } = ""; - public string area_code { get; set; } = "**"; - public string device_grant_ticket { get; set; } = ""; - } + public VerifyAccountData account { get; set; } = new(); + public bool device_grant_required { get; set; } = false; + public string realname_operation { get; set; } = "NONE"; + public bool realperson_required { get; set; } = false; + public bool safe_mobile_required { get; set; } = false; } -} + + public class VerifyAccountData + { + public string? uid { get; set; } + public string name { get; set; } = ""; + public string email { get; set; } = ""; + public string mobile { get; set; } = ""; + public string is_email_verify { get; set; } = "0"; + public string realname { get; set; } = ""; + public string identity_card { get; set; } = ""; + public string? token { get; set; } + public string? safe_mobile { get; set; } = ""; + public string facebook_name { get; set; } = ""; + public string twitter_name { get; set; } = ""; + public string game_center_name { get; set; } = ""; + public string google_name { get; set; } = ""; + public string apple_name { get; set; } = ""; + public string sony_name { get; set; } = ""; + public string tap_name { get; set; } = ""; + public string country { get; set; } = "US"; + public string reactivate_ticket { get; set; } = ""; + public string area_code { get; set; } = "**"; + public string device_grant_ticket { get; set; } = ""; + } +} \ No newline at end of file diff --git a/WebServer/Objects/NewLoginResJson.cs b/WebServer/Objects/NewLoginResJson.cs index dd3b9f2a..ce5792a7 100644 --- a/WebServer/Objects/NewLoginResJson.cs +++ b/WebServer/Objects/NewLoginResJson.cs @@ -1,65 +1,68 @@ -namespace EggLink.DanhengServer.WebServer.Objects +namespace EggLink.DanhengServer.WebServer.Objects; + +public class NewLoginResJson { - public class NewLoginResJson + public NewLoginResJson() { - public string? message { get; set; } - public int retcode { get; set; } - public VerifyData? data { get; set; } - - public NewLoginResJson() { } - - public NewLoginResJson(string aid, string email, string token) - { - data = new VerifyData(aid, email, token); - } - - public class VerifyData - { - public UserInfoData user_info { get; set; } = new UserInfoData(); - public TokenData token { get; set; } = new TokenData(); - - public VerifyData(string aid, string email, string token) - { - user_info.aid = aid; - user_info.email = email; - this.token.token = token; - } - } - - public class UserInfoData - { - public string account_name { get; set; } = ""; - public string aid { get; set; } = ""; - public string area_code { get; set; } = ""; - public string country { get; set; } = ""; - public string email { get; set; } = ""; - public int is_email_verify { get; set; } = 0; - public string identity_code { get; set; } = ""; - public List links { get; set; } = new List - { - new LinkData() - }; - public string mid { get; set; } = ""; - public string mobile { get; set; } = ""; - public string realname { get; set; } = ""; - public string rebind_area_code { get; set; } = ""; - public string rebind_mobile { get; set; } = ""; - public string rebind_mobile_time { get; set; } = ""; - public string safe_area_code { get; set; } = ""; - public string safe_mobile { get; set; } = ""; - } - - public class TokenData - { - public string token { get; set; } = ""; - public int token_type { get; set; } = 1; - } - - public class LinkData - { - public string nickname { get; set; } = ""; - public string thirdparty { get; set; } = ""; - public string union_id { get; set; } = ""; - } } -} + + public NewLoginResJson(string aid, string email, string token) + { + data = new VerifyData(aid, email, token); + } + + public string? message { get; set; } + public int retcode { get; set; } + public VerifyData? data { get; set; } + + public class VerifyData + { + public VerifyData(string aid, string email, string token) + { + user_info.aid = aid; + user_info.email = email; + this.token.token = token; + } + + public UserInfoData user_info { get; set; } = new(); + public TokenData token { get; set; } = new(); + } + + public class UserInfoData + { + public string account_name { get; set; } = ""; + public string aid { get; set; } = ""; + public string area_code { get; set; } = ""; + public string country { get; set; } = ""; + public string email { get; set; } = ""; + public int is_email_verify { get; set; } = 0; + public string identity_code { get; set; } = ""; + + public List links { get; set; } = new() + { + new() + }; + + public string mid { get; set; } = ""; + public string mobile { get; set; } = ""; + public string realname { get; set; } = ""; + public string rebind_area_code { get; set; } = ""; + public string rebind_mobile { get; set; } = ""; + public string rebind_mobile_time { get; set; } = ""; + public string safe_area_code { get; set; } = ""; + public string safe_mobile { get; set; } = ""; + } + + public class TokenData + { + public string token { get; set; } = ""; + public int token_type { get; set; } = 1; + } + + public class LinkData + { + public string nickname { get; set; } = ""; + public string thirdparty { get; set; } = ""; + public string union_id { get; set; } = ""; + } +} \ No newline at end of file diff --git a/WebServer/Objects/RequestBodies.cs b/WebServer/Objects/RequestBodies.cs index 55aa0866..681beb8a 100644 --- a/WebServer/Objects/RequestBodies.cs +++ b/WebServer/Objects/RequestBodies.cs @@ -1,29 +1,29 @@ -namespace EggLink.DanhengServer.WebServer.Objects +namespace EggLink.DanhengServer.WebServer.Objects; + +public class LoginReqJson { - public class LoginReqJson - { - public string? account { get; set; } - public string? password { get; set; } - public bool is_crypto { get; set; } - } - public class NewLoginReqJson - { - public string? account { get; set; } - public string? password { get; set; } - } - - public class VerifyReqJson - { - public string? uid { get; set; } - public string? token { get; set; } - } - - public class LoginV2ReqJson - { - public int app_id { get; set; } - public int channel_id { get; set; } - public string? data { get; set; } - public string? device { get; set; } - public string? sign { get; set; } - } + public string? account { get; set; } + public string? password { get; set; } + public bool is_crypto { get; set; } } + +public class NewLoginReqJson +{ + public string? account { get; set; } + public string? password { get; set; } +} + +public class VerifyReqJson +{ + public string? uid { get; set; } + public string? token { get; set; } +} + +public class LoginV2ReqJson +{ + public int app_id { get; set; } + public int channel_id { get; set; } + public string? data { get; set; } + public string? device { get; set; } + public string? sign { get; set; } +} \ No newline at end of file diff --git a/WebServer/Request/AuthRequest.cs b/WebServer/Request/AuthRequest.cs index c9fe819c..74db3eb0 100644 --- a/WebServer/Request/AuthRequest.cs +++ b/WebServer/Request/AuthRequest.cs @@ -1,8 +1,7 @@ -namespace EggLink.DanhengServer.WebServer.Request +namespace EggLink.DanhengServer.WebServer.Request; + +public class AuthAdminKeyRequestBody { - public class AuthAdminKeyRequestBody - { - public string admin_key { get; set; } = ""; - public string key_type { get; set; } = "XML"; - } -} + public string admin_key { get; set; } = ""; + public string key_type { get; set; } = "XML"; +} \ No newline at end of file diff --git a/WebServer/Request/ExecRequest.cs b/WebServer/Request/ExecRequest.cs index 1016acf5..681a9353 100644 --- a/WebServer/Request/ExecRequest.cs +++ b/WebServer/Request/ExecRequest.cs @@ -1,9 +1,8 @@ -namespace EggLink.DanhengServer.WebServer.Request +namespace EggLink.DanhengServer.WebServer.Request; + +public class AdminExecRequest { - public class AdminExecRequest - { - public string SessionId { get; set; } = ""; - public string Command { get; set; } = ""; - public int TargetUid { get; set; } = 0; - } -} + public string SessionId { get; set; } = ""; + public string Command { get; set; } = ""; + public int TargetUid { get; set; } = 0; +} \ No newline at end of file diff --git a/WebServer/Request/InformationRequest.cs b/WebServer/Request/InformationRequest.cs index 3d67f19d..ad3a80bc 100644 --- a/WebServer/Request/InformationRequest.cs +++ b/WebServer/Request/InformationRequest.cs @@ -1,13 +1,12 @@ -namespace EggLink.DanhengServer.WebServer.Request -{ - public class ServerInformationRequest - { - public string SessionId { get; set; } = ""; - } +namespace EggLink.DanhengServer.WebServer.Request; - public class PlayerInformationRequest - { - public string SessionId { get; set; } = ""; - public int Uid { get; set; } - } +public class ServerInformationRequest +{ + public string SessionId { get; set; } = ""; } + +public class PlayerInformationRequest +{ + public string SessionId { get; set; } = ""; + public int Uid { get; set; } +} \ No newline at end of file diff --git a/WebServer/Response/AuthAdminKeyResponse.cs b/WebServer/Response/AuthAdminKeyResponse.cs index 1679c651..0e7f3be2 100644 --- a/WebServer/Response/AuthAdminKeyResponse.cs +++ b/WebServer/Response/AuthAdminKeyResponse.cs @@ -1,13 +1,13 @@ -namespace EggLink.DanhengServer.WebServer.Response -{ - public class AuthAdminKeyResponse(int code, string message, AuthAdminKeyData? data) : BaseResponse(code, message, data) - { - } +namespace EggLink.DanhengServer.WebServer.Response; - public class AuthAdminKeyData - { - public string RsaPublicKey { get; set; } = ""; - public string SessionId { get; set; } = ""; - public long ExpireTimeStamp { get; set; } = 0; - } +public class AuthAdminKeyResponse(int code, string message, AuthAdminKeyData? data) + : BaseResponse(code, message, data) +{ } + +public class AuthAdminKeyData +{ + public string RsaPublicKey { get; set; } = ""; + public string SessionId { get; set; } = ""; + public long ExpireTimeStamp { get; set; } = 0; +} \ No newline at end of file diff --git a/WebServer/Response/BaseResponse.cs b/WebServer/Response/BaseResponse.cs index 69ef3a7b..c923d994 100644 --- a/WebServer/Response/BaseResponse.cs +++ b/WebServer/Response/BaseResponse.cs @@ -1,14 +1,13 @@ -namespace EggLink.DanhengServer.WebServer.Response +namespace EggLink.DanhengServer.WebServer.Response; + +public class BaseResponse(int code, string message, T? data) { - public class BaseResponse(int code, string message, T? data) - { - public int Code { get; set; } = code; - public string Message { get; set; } = message; + public int Code { get; set; } = code; + public string Message { get; set; } = message; - public T? Data { get; set; } = data; - } - - public class BasicResponse(int code, string message) : BaseResponse(code, message, null) - { - } + public T? Data { get; set; } = data; } + +public class BasicResponse(int code, string message) : BaseResponse(code, message, null) +{ +} \ No newline at end of file diff --git a/WebServer/Response/ExecuteCommandResponse.cs b/WebServer/Response/ExecuteCommandResponse.cs index 7dbd5975..e2cea31d 100644 --- a/WebServer/Response/ExecuteCommandResponse.cs +++ b/WebServer/Response/ExecuteCommandResponse.cs @@ -1,12 +1,12 @@ -namespace EggLink.DanhengServer.WebServer.Response -{ - public class ExecuteCommandResponse(int code, string message, ExecuteCommandData? data = null) : BaseResponse(code, message, data) - { - } +namespace EggLink.DanhengServer.WebServer.Response; - public class ExecuteCommandData - { - public string SessionId { get; set; } = ""; - public string Message { get; set; } = ""; - } +public class ExecuteCommandResponse(int code, string message, ExecuteCommandData? data = null) + : BaseResponse(code, message, data) +{ } + +public class ExecuteCommandData +{ + public string SessionId { get; set; } = ""; + public string Message { get; set; } = ""; +} \ No newline at end of file diff --git a/WebServer/Response/InformationResponse.cs b/WebServer/Response/InformationResponse.cs index c8c6ef0e..670865e4 100644 --- a/WebServer/Response/InformationResponse.cs +++ b/WebServer/Response/InformationResponse.cs @@ -1,76 +1,75 @@ -using EggLink.DanhengServer.Enums; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.Collections.Generic; +using System.Text.Json.Serialization; +using EggLink.DanhengServer.Enums; using EggLink.DanhengServer.WebServer.Server; +using Newtonsoft.Json.Converters; +namespace EggLink.DanhengServer.WebServer.Response; -namespace EggLink.DanhengServer.WebServer.Response +public class ServerInformationResponse(int code, string message, ServerInformationData? data = null) + : BaseResponse(code, message, data) { - public class ServerInformationResponse(int code, string message, ServerInformationData? data = null) : BaseResponse(code, message, data) - { - } +} - public class ServerInformationData - { - public List OnlinePlayers { get; set; } = []; - public long ServerTime { get; set; } = 0; - public float MaxMemory { get; set; } = 0; - public float UsedMemory { get; set; } = 0; - public float ProgramUsedMemory { get; set; } = 0; - public float CpuUsage { get; set; } = MuipManager.GetCpuUsage(); - public string CpuModel { get; set; } = MuipManager.GetCpuDetails().ModelName; - public int CpuCores { get; set; } = MuipManager.GetCpuDetails().Cores; - public float CpuFrequency { get; set; } = MuipManager.GetCpuDetails().Frequency; - public string SystemVersion { get; set; } = MuipManager.GetSystemVersion(); - } +public class ServerInformationData +{ + public List OnlinePlayers { get; set; } = []; + public long ServerTime { get; set; } = 0; + public float MaxMemory { get; set; } = 0; + public float UsedMemory { get; set; } = 0; + public float ProgramUsedMemory { get; set; } = 0; + public float CpuUsage { get; set; } = MuipManager.GetCpuUsage(); + public string CpuModel { get; set; } = MuipManager.GetCpuDetails().ModelName; + public int CpuCores { get; set; } = MuipManager.GetCpuDetails().Cores; + public float CpuFrequency { get; set; } = MuipManager.GetCpuDetails().Frequency; + public string SystemVersion { get; set; } = MuipManager.GetSystemVersion(); +} - public class SimplePlayerInformationData - { - public int Uid { get; set; } - public string Name { get; set; } = ""; - public int HeadIconId { get; set; } - } +public class SimplePlayerInformationData +{ + public int Uid { get; set; } + public string Name { get; set; } = ""; + public int HeadIconId { get; set; } +} - public class PlayerInformationResponse(int code, string message, PlayerInformationData? data = null) : BaseResponse(code, message, data) - { - } +public class PlayerInformationResponse(int code, string message, PlayerInformationData? data = null) + : BaseResponse(code, message, data) +{ +} - public class PlayerInformationData - { - // Basic info - public int Uid { get; set; } - public string Name { get; set; } = ""; - public string Signature { get; set; } = ""; - public int HeadIconId { get; set; } - public int Credit { get; set; } - public int Jade { get; set; } +public class PlayerInformationData +{ + // Basic info + public int Uid { get; set; } + public string Name { get; set; } = ""; + public string Signature { get; set; } = ""; + public int HeadIconId { get; set; } + public int Credit { get; set; } + public int Jade { get; set; } - // Scene info - public int CurPlaneId { get; set; } - public int CurFloorId { get; set; } + // Scene info + public int CurPlaneId { get; set; } + public int CurFloorId { get; set; } - // Player info - [JsonConverter(typeof(StringEnumConverter))] - [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))] - public PlayerStatusEnum PlayerStatus { get; set; } = PlayerStatusEnum.Explore; + // Player info + [Newtonsoft.Json.JsonConverter(typeof(StringEnumConverter))] + [System.Text.Json.Serialization.JsonConverter(typeof(JsonStringEnumConverter))] + public PlayerStatusEnum PlayerStatus { get; set; } = PlayerStatusEnum.Explore; - [JsonConverter(typeof(StringEnumConverter))] - [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))] - public PlayerSubStatusEnum PlayerSubStatus { get; set; } = PlayerSubStatusEnum.None; - public int Stamina { get; set; } = 0; - public int RecoveryStamina { get; set; } = 0; - public List AssistAvatarList { get; set; } = []; - public List DisplayAvatarList { get; set; } = []; + [Newtonsoft.Json.JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] + public PlayerSubStatusEnum PlayerSubStatus { get; set; } = PlayerSubStatusEnum.None; - // Mission info - public List FinishedMainMissionIdList { get; set; } = []; - public List FinishedSubMissionIdList { get; set; } = []; - public List AcceptedMainMissionIdList { get; set; } = []; - public List AcceptedSubMissionIdList { get; set; } = []; + public int Stamina { get; set; } = 0; + public int RecoveryStamina { get; set; } = 0; + public List AssistAvatarList { get; set; } = []; + public List DisplayAvatarList { get; set; } = []; - // Lineup info - public List LineupBaseAvatarIdList { get; set; } = []; + // Mission info + public List FinishedMainMissionIdList { get; set; } = []; + public List FinishedSubMissionIdList { get; set; } = []; + public List AcceptedMainMissionIdList { get; set; } = []; + public List AcceptedSubMissionIdList { get; set; } = []; - } + // Lineup info + public List LineupBaseAvatarIdList { get; set; } = []; } \ No newline at end of file diff --git a/WebServer/Server/MuipCommandSender.cs b/WebServer/Server/MuipCommandSender.cs index 62274908..7e5a6ea5 100644 --- a/WebServer/Server/MuipCommandSender.cs +++ b/WebServer/Server/MuipCommandSender.cs @@ -1,31 +1,28 @@ using EggLink.DanhengServer.Command; -namespace EggLink.DanhengServer.WebServer.Server +namespace EggLink.DanhengServer.WebServer.Server; + +public class MuipCommandSender(MuipSession session, Action action) : ICommandSender { - public class MuipCommandSender(MuipSession session, Action action) : ICommandSender + public MuipSession Session { get; } = session; + public Action MsgAction { get; } = action; + public int SenderUid { get; set; } = session.Account?.Uid ?? 0; + + public bool HasPermission(string permission) { - public MuipSession Session { get; } = session; - public Action MsgAction { get; } = action; - public int SenderUid { get; set; } = session.Account?.Uid ?? 0; + if (Session.IsAdmin) return true; - public bool HasPermission(string permission) - { - if (Session.IsAdmin) - { - return true; - } - - return Session.Account?.Permissions?.Contains(permission) ?? false; - } - - public void SendMsg(string msg) - { - MsgAction(msg); - } - - public int GetSender() - { - return SenderUid; - } + return Session.Account?.Permissions?.Contains(permission) ?? false; } -} + + public async ValueTask SendMsg(string msg) + { + MsgAction(msg); + await Task.CompletedTask; + } + + public int GetSender() + { + return SenderUid; + } +} \ No newline at end of file diff --git a/WebServer/Server/MuipManager.cs b/WebServer/Server/MuipManager.cs index 7c339cc2..44cebe3e 100644 --- a/WebServer/Server/MuipManager.cs +++ b/WebServer/Server/MuipManager.cs @@ -1,475 +1,437 @@ -using EggLink.DanhengServer.Util; -using EggLink.DanhengServer.WebServer.Response; -using Org.BouncyCastle.Crypto.Parameters; -using System.Numerics; +using System.Diagnostics; using System.Management; -using System.Security.Cryptography; -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Math; -using Org.BouncyCastle.X509; -using System.Text; -using System.Diagnostics; using System.Runtime.InteropServices; -using EggLink.DanhengServer.Database.Player; +using System.Security.Cryptography; +using System.Text; +using EggLink.DanhengServer.Data; using EggLink.DanhengServer.Database; using EggLink.DanhengServer.Database.Avatar; -using EggLink.DanhengServer.Database.Mission; -using EggLink.DanhengServer.Enums; -using Spectre.Console; using EggLink.DanhengServer.Database.Lineup; -using EggLink.DanhengServer.Data; -namespace EggLink.DanhengServer.WebServer.Server +using EggLink.DanhengServer.Database.Mission; +using EggLink.DanhengServer.Database.Player; +using EggLink.DanhengServer.Enums; +using EggLink.DanhengServer.Util; +using EggLink.DanhengServer.WebServer.Response; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Math; +using Org.BouncyCastle.X509; + +namespace EggLink.DanhengServer.WebServer.Server; + +public static class MuipManager { - public static class MuipManager + public delegate void ExecuteCommandDelegate(string message, MuipCommandSender sender); + + public delegate void GetPlayerStatusDelegate(int uid, out PlayerStatusEnum status, + out PlayerSubStatusEnum subStatus); + + public delegate void ServerInformationDelegate(Dictionary resultData); + + private static readonly Logger logger = Logger.GetByClassName(); + + public static string RsaPublicKey { get; private set; } = ""; + public static string RsaPrivateKey { get; private set; } = ""; + + public static Dictionary Sessions { get; } = []; + public static event ExecuteCommandDelegate? OnExecuteCommand; + public static event ServerInformationDelegate? OnGetServerInformation; + public static event GetPlayerStatusDelegate? OnGetPlayerStatus; + + public static AuthAdminKeyData? AuthAdminAndCreateSession(string key, string key_type) { - private static readonly Logger logger = Logger.GetByClassName(); - public delegate void ExecuteCommandDelegate(string message, MuipCommandSender sender); - public static event ExecuteCommandDelegate? OnExecuteCommand; - public delegate void ServerInformationDelegate(Dictionary resultData); - public static event ServerInformationDelegate? OnGetServerInformation; - public delegate void GetPlayerStatusDelegate(int uid, out PlayerStatusEnum status, out PlayerSubStatusEnum subStatus); - public static event GetPlayerStatusDelegate? OnGetPlayerStatus; + if (ConfigManager.Config.MuipServer.AdminKey == "" || + ConfigManager.Config.MuipServer.AdminKey != key) return null; - public static string RsaPublicKey { get; private set; } = ""; - public static string RsaPrivateKey { get; private set; } = ""; - - public static Dictionary Sessions { get; } = []; - - public static AuthAdminKeyData? AuthAdminAndCreateSession(string key, string key_type) + var session = new MuipSession { - if (ConfigManager.Config.MuipServer.AdminKey == "" || ConfigManager.Config.MuipServer.AdminKey != key) + SessionId = Guid.NewGuid().ToString(), + RsaPublicKey = GetRsaKeyPair().Item1, + ExpireTimeStamp = DateTime.Now.AddMinutes(15).ToUnixSec(), + IsAdmin = true + }; + + if (key_type == "PEM") + // convert to PEM + session.RsaPublicKey = XMLToPEM_Pub(session.RsaPublicKey); + + Sessions.Add(session.SessionId, session); + + var data = new AuthAdminKeyData + { + RsaPublicKey = session.RsaPublicKey, + SessionId = session.SessionId, + ExpireTimeStamp = session.ExpireTimeStamp + }; + + return data; + } + + public static MuipSession? GetSession(string sessionId) + { + if (Sessions.TryGetValue(sessionId, out var value)) + { + var session = value; + if (session.ExpireTimeStamp < DateTime.Now.ToUnixSec()) { + Sessions.Remove(sessionId); return null; } - var session = new MuipSession() - { - SessionId = Guid.NewGuid().ToString(), - RsaPublicKey = GetRsaKeyPair().Item1, - ExpireTimeStamp = DateTime.Now.AddMinutes(15).ToUnixSec(), - IsAdmin = true, - }; - - if (key_type == "PEM") - { - // convert to PEM - session.RsaPublicKey = XMLToPEM_Pub(session.RsaPublicKey); - } - - Sessions.Add(session.SessionId, session); - - var data = new AuthAdminKeyData - { - RsaPublicKey = session.RsaPublicKey, - SessionId = session.SessionId, - ExpireTimeStamp = session.ExpireTimeStamp, - }; - - return data; + return session; } - public static MuipSession? GetSession(string sessionId) + return null; + } + + public static ExecuteCommandResponse ExecuteCommand(string sessionId, string command, int targetUid) + { + if (Sessions.TryGetValue(sessionId, out var value)) { - if (Sessions.TryGetValue(sessionId, out MuipSession? value)) + var session = value; + if (session.ExpireTimeStamp < DateTime.Now.ToUnixSec()) { - var session = value; - if (session.ExpireTimeStamp < DateTime.Now.ToUnixSec()) - { - Sessions.Remove(sessionId); - return null; - } - return session; + Sessions.Remove(sessionId); + return new ExecuteCommandResponse(1, "Session has expired!"); } - return null; - } - public static ExecuteCommandResponse ExecuteCommand(string sessionId, string command, int targetUid) - { - if (Sessions.TryGetValue(sessionId, out MuipSession? value)) + var rsa = new RSACryptoServiceProvider(); + rsa.FromXmlString(GetRsaKeyPair().Item2); + byte[] decrypted; + + try { - var session = value; - if (session.ExpireTimeStamp < DateTime.Now.ToUnixSec()) - { - Sessions.Remove(sessionId); - return new(1, "Session has expired!"); - } + decrypted = rsa.Decrypt(Convert.FromBase64String(command), RSAEncryptionPadding.Pkcs1); + } + catch + { + return new ExecuteCommandResponse(3, "Wrong encrypted key"); + } - var rsa = new RSACryptoServiceProvider(); - rsa.FromXmlString(GetRsaKeyPair().Item2); - byte[] decrypted; + var commandStr = Encoding.UTF8.GetString(decrypted); + logger.Info($"SessionId: {sessionId}, UID: {targetUid}, ExecuteCommand: {commandStr}"); + var returnStr = ""; - try + var sync = Task.Run(() => OnExecuteCommand?.Invoke(commandStr, + new MuipCommandSender(session, msg => { returnStr += msg + "\r\n"; }) { - decrypted = rsa.Decrypt(Convert.FromBase64String(command), RSAEncryptionPadding.Pkcs1); - } catch - { - return new(3, "Wrong encrypted key"); - } - - var commandStr = Encoding.UTF8.GetString(decrypted); - logger.Info($"SessionId: {sessionId}, UID: {targetUid}, ExecuteCommand: {commandStr}"); - var returnStr = ""; - - var sync = Task.Run(() => OnExecuteCommand?.Invoke(commandStr, new MuipCommandSender(session, (msg) => - { - returnStr += msg + "\r\n"; - }) - { - SenderUid = targetUid, + SenderUid = targetUid })); - sync.Wait(); + sync.Wait(); - return new(0, "Success", new() - { - SessionId = sessionId, - Message = Convert.ToBase64String(Encoding.UTF8.GetBytes(returnStr)), - }); - } - return new(2, "Session not found!"); + return new ExecuteCommandResponse(0, "Success", new ExecuteCommandData + { + SessionId = sessionId, + Message = Convert.ToBase64String(Encoding.UTF8.GetBytes(returnStr)) + }); } - public static ServerInformationResponse GetInformation(string sessionId) - { - if (Sessions.TryGetValue(sessionId, out MuipSession? value)) - { - var session = value; - if (session.ExpireTimeStamp < DateTime.Now.ToUnixSec()) - { - Sessions.Remove(sessionId); - return new(1, "Session has expired!", null); - } - Process currentProcess = Process.GetCurrentProcess(); + return new ExecuteCommandResponse(2, "Session not found!"); + } - long currentProcessMemory = currentProcess.WorkingSet64; - - // get system info - var totalMemory = -1f; - var availableMemory = -1f; - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - totalMemory = GetTotalMemoryWindows(); - availableMemory = GetAvailableMemoryWindows(); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - totalMemory = GetTotalMemoryLinux(); - availableMemory = GetAvailableMemoryLinux(); - } - - var result = new Dictionary(); - var sync = Task.Run(() => OnGetServerInformation?.Invoke(result)); - - sync.Wait(); - - return new(0, "Success", new() - { - ServerTime = DateTime.Now.ToUnixSec(), - MaxMemory = totalMemory, - ProgramUsedMemory = currentProcessMemory / 1024 / 1024, - UsedMemory = totalMemory - availableMemory, - OnlinePlayers = result.Values.Select(x => new SimplePlayerInformationData() - { - Name = x.Name ?? "", - HeadIconId = x.HeadIcon, - Uid = x.Uid - }).ToList(), - }); - } - return new(2, "Session not found!", null); - } - - public static PlayerInformationResponse GetPlayerInformation(string sessionId, int uid) - { - if (Sessions.TryGetValue(sessionId, out MuipSession? value)) - { - var session = value; - if (session.ExpireTimeStamp < DateTime.Now.ToUnixSec()) - { - Sessions.Remove(sessionId); - return new(1, "Session has expired!", null); - } - - var result = new Dictionary(); - var player = DatabaseHelper.Instance?.GetInstance(uid); - if (player == null) return new(2, "Player not exist!", null); - - var status = PlayerStatusEnum.Offline; - var subStatus = PlayerSubStatusEnum.None; - - var statusSync = Task.Run(() => OnGetPlayerStatus?.Invoke(player.Uid, out status, out subStatus)); - - statusSync.Wait(); - - var avatarData = DatabaseHelper.Instance!.GetInstance(player.Uid)!; - var lineupData = DatabaseHelper.Instance!.GetInstance(player.Uid)!; - var missionData = DatabaseHelper.Instance!.GetInstance(player.Uid)!; - - var curLineupAvatars = new List(); - var index = lineupData.CurExtraLineup > 0 ? lineupData.CurExtraLineup : lineupData.CurLineup; - - lineupData.Lineups.TryGetValue(index, out var lineup); - - if (lineup != null) - { - foreach (var avatar in lineup.BaseAvatars ?? []) - { - GameData.AvatarConfigData.TryGetValue(avatar.BaseAvatarId, out var excel); - if (excel != null) - { - curLineupAvatars.Add(avatar.BaseAvatarId); - } - } - } - - - return new(0, "Success", new() - { - Uid = player.Uid, - Name = player.Name ?? "", - Signature = player.Signature ?? "", - Stamina = player.Stamina, - RecoveryStamina = (int)player.StaminaReserve, - HeadIconId = player.HeadIcon, - CurFloorId = player.FloorId, - CurPlaneId = player.PlaneId, - AssistAvatarList = avatarData.AssistAvatars, - DisplayAvatarList = avatarData.DisplayAvatars, - AcceptedSubMissionIdList = missionData.RunningSubMissionIds, - AcceptedMainMissionIdList = missionData.RunningMainMissionIds, - FinishedMainMissionIdList = missionData.FinishedMainMissionIds, - FinishedSubMissionIdList = missionData.FinishedSubMissionIds, - PlayerStatus = status, - PlayerSubStatus = subStatus, - Credit = player.Scoin, - Jade = player.Hcoin, - LineupBaseAvatarIdList = curLineupAvatars - }); - } - return new(3, "Session not found!", null); - } - - #region Tools - - /// - /// get rsa key pair - /// - /// item 1 is public key, item 2 is private key - public static (string, string) GetRsaKeyPair() - { - if (string.IsNullOrEmpty(RsaPublicKey) || string.IsNullOrEmpty(RsaPrivateKey)) - { - var rsa = new RSACryptoServiceProvider(2048); - RsaPublicKey = rsa.ToXmlString(false); - RsaPrivateKey = rsa.ToXmlString(true); - } - return (RsaPublicKey, RsaPrivateKey); - } - - - public static string XMLToPEM_Pub(string xmlpubkey) - { - var rsa = new RSACryptoServiceProvider(); - rsa.FromXmlString(xmlpubkey); - var p = rsa.ExportParameters(false); - RsaKeyParameters key = new RsaKeyParameters(false, new Org.BouncyCastle.Math.BigInteger(1, p.Modulus), new Org.BouncyCastle.Math.BigInteger(1, p.Exponent)); - SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key); - byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded(); - string publicKey = Convert.ToBase64String(serializedPublicBytes); - return Format(publicKey, true); - } - - - private static string Format(string key, bool type) - { - string result = string.Empty; - - int length = key.Length / 64; - for (int i = 0; i < length; i++) - { - int start = i * 64; - result = result + key.Substring(start, 64) + "\r\n"; - } - - result = result + key.Substring(length * 64); - if (type) - { - result = result.Insert(0, "-----BEGIN PUBLIC KEY-----\r\n"); - result += "\r\n-----END PUBLIC KEY-----"; - } - else - { - result = result.Insert(0, "-----BEGIN PRIVATE KEY-----\r\n"); - result += "\r\n-----END PRIVATE KEY-----"; - } - - return result; - } - - public static float GetTotalMemoryWindows() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - var searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem"); - foreach (var obj in searcher.Get()) - { - var memory = Convert.ToUInt64(obj["TotalPhysicalMemory"]); - return memory / 1024 / 1024; - } - } - return 0; - } - - public static float GetAvailableMemoryWindows() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - var pc = new PerformanceCounter("Memory", "Available MBytes"); - return pc.NextValue(); - } - return 0; - } - - public static float GetTotalMemoryLinux() - { - string[] lines = File.ReadAllLines("/proc/meminfo"); - foreach (string line in lines) - { - if (line.StartsWith("MemTotal")) - { - return float.Parse(line.Split(':')[1].Trim().Split(' ')[0]) / 1024; - } - } - return 0; - } - - public static float GetAvailableMemoryLinux() - { - string[] lines = File.ReadAllLines("/proc/meminfo"); - foreach (string line in lines) - { - if (line.StartsWith("MemAvailable")) - { - return float.Parse(line.Split(':')[1].Trim().Split(' ')[0]) / 1024; - } - } - return 0; - } - public static float GetCpuUsage() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return GetCpuUsageLinux(); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return GetCpuUsageWindows(); - } - throw new NotSupportedException("Unsupported OS platform"); - } - - private static float GetCpuUsageLinux() - { - string[] lines = File.ReadAllLines("/proc/stat"); - string[] cpuInfo = lines[0].Split(' ', StringSplitOptions.RemoveEmptyEntries); - float idleTime = float.Parse(cpuInfo[4]); - float totalTime = 0; - - for (int i = 1; i < cpuInfo.Length; i++) - { - totalTime += float.Parse(cpuInfo[i]); - } - - return 100 * (1 - idleTime / totalTime); - } - - private static float GetCpuUsageWindows() - { - if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - throw new PlatformNotSupportedException("PerformanceCounter is only supported on Windows"); - } - - var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); - cpuCounter.NextValue(); - System.Threading.Thread.Sleep(1000); - return cpuCounter.NextValue(); - } - - public static (string ModelName, int Cores, float Frequency) GetCpuDetails() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return GetCpuDetailsLinux(); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return GetCpuDetailsWindows(); - } - throw new NotSupportedException("Unsupported OS platform"); - } - - private static (string ModelName, int Cores, float Frequency) GetCpuDetailsLinux() - { - string[] lines = File.ReadAllLines("/proc/cpuinfo"); - string modelName = ""; - int cores = 0; - float frequency = 0; - - foreach (string line in lines) - { - if (line.StartsWith("model name")) - { - modelName = line.Split(':')[1].Trim(); - } - if (line.StartsWith("cpu cores")) - { - cores = int.Parse(line.Split(':')[1].Trim()); - } - if (line.StartsWith("cpu MHz")) - { - frequency = float.Parse(line.Split(':')[1].Trim()); - } - } - - return (modelName, cores, frequency); - } - - private static (string ModelName, int Cores, float Frequency) GetCpuDetailsWindows() - { - if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - throw new PlatformNotSupportedException("ManagementObjectSearcher is only supported on Windows"); - } - - string modelName = ""; - int cores = 0; - float frequency = 0; - - var searcher = new ManagementObjectSearcher("select * from Win32_Processor"); - foreach (var item in searcher.Get()) - { - modelName = item["Name"]?.ToString() ?? "Unknown"; - cores = int.Parse(item["NumberOfCores"]?.ToString() ?? "0"); - frequency = float.Parse(item["MaxClockSpeed"]?.ToString() ?? "0") / 1000; // MHz to GHz - } - - return (modelName, cores, frequency); - } - public static string GetSystemVersion() + public static ServerInformationResponse GetInformation(string sessionId) { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + if (Sessions.TryGetValue(sessionId, out var value)) { - return GetWindowsVersion(); + var session = value; + if (session.ExpireTimeStamp < DateTime.Now.ToUnixSec()) + { + Sessions.Remove(sessionId); + return new ServerInformationResponse(1, "Session has expired!"); + } + + var currentProcess = Process.GetCurrentProcess(); + + var currentProcessMemory = currentProcess.WorkingSet64; + + // get system info + var totalMemory = -1f; + var availableMemory = -1f; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + totalMemory = GetTotalMemoryWindows(); + availableMemory = GetAvailableMemoryWindows(); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + totalMemory = GetTotalMemoryLinux(); + availableMemory = GetAvailableMemoryLinux(); + } + + var result = new Dictionary(); + var sync = Task.Run(() => OnGetServerInformation?.Invoke(result)); + + sync.Wait(); + + return new ServerInformationResponse(0, "Success", new ServerInformationData + { + ServerTime = DateTime.Now.ToUnixSec(), + MaxMemory = totalMemory, + ProgramUsedMemory = currentProcessMemory / 1024 / 1024, + UsedMemory = totalMemory - availableMemory, + OnlinePlayers = result.Values.Select(x => new SimplePlayerInformationData + { + Name = x.Name ?? "", + HeadIconId = x.HeadIcon, + Uid = x.Uid + }).ToList() + }); } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + + return new ServerInformationResponse(2, "Session not found!"); + } + + public static PlayerInformationResponse GetPlayerInformation(string sessionId, int uid) + { + if (Sessions.TryGetValue(sessionId, out var value)) { - return GetLinuxVersion(); + var session = value; + if (session.ExpireTimeStamp < DateTime.Now.ToUnixSec()) + { + Sessions.Remove(sessionId); + return new PlayerInformationResponse(1, "Session has expired!"); + } + + var result = new Dictionary(); + var player = DatabaseHelper.Instance?.GetInstance(uid); + if (player == null) return new PlayerInformationResponse(2, "Player not exist!"); + + var status = PlayerStatusEnum.Offline; + var subStatus = PlayerSubStatusEnum.None; + + var statusSync = Task.Run(() => OnGetPlayerStatus?.Invoke(player.Uid, out status, out subStatus)); + + statusSync.Wait(); + + var avatarData = DatabaseHelper.Instance!.GetInstance(player.Uid)!; + var lineupData = DatabaseHelper.Instance!.GetInstance(player.Uid)!; + var missionData = DatabaseHelper.Instance!.GetInstance(player.Uid)!; + + var curLineupAvatars = new List(); + var index = lineupData.CurExtraLineup > 0 ? lineupData.CurExtraLineup : lineupData.CurLineup; + + lineupData.Lineups.TryGetValue(index, out var lineup); + + if (lineup != null) + foreach (var avatar in lineup.BaseAvatars ?? []) + { + GameData.AvatarConfigData.TryGetValue(avatar.BaseAvatarId, out var excel); + if (excel != null) curLineupAvatars.Add(avatar.BaseAvatarId); + } + + + return new PlayerInformationResponse(0, "Success", new PlayerInformationData + { + Uid = player.Uid, + Name = player.Name ?? "", + Signature = player.Signature ?? "", + Stamina = player.Stamina, + RecoveryStamina = (int)player.StaminaReserve, + HeadIconId = player.HeadIcon, + CurFloorId = player.FloorId, + CurPlaneId = player.PlaneId, + AssistAvatarList = avatarData.AssistAvatars, + DisplayAvatarList = avatarData.DisplayAvatars, + AcceptedSubMissionIdList = missionData.RunningSubMissionIds, + AcceptedMainMissionIdList = missionData.RunningMainMissionIds, + FinishedMainMissionIdList = missionData.FinishedMainMissionIds, + FinishedSubMissionIdList = missionData.FinishedSubMissionIds, + PlayerStatus = status, + PlayerSubStatus = subStatus, + Credit = player.Scoin, + Jade = player.Hcoin, + LineupBaseAvatarIdList = curLineupAvatars + }); + } + + return new PlayerInformationResponse(3, "Session not found!"); + } + + #region Tools + + /// + /// get rsa key pair + /// + /// item 1 is public key, item 2 is private key + public static (string, string) GetRsaKeyPair() + { + if (string.IsNullOrEmpty(RsaPublicKey) || string.IsNullOrEmpty(RsaPrivateKey)) + { + var rsa = new RSACryptoServiceProvider(2048); + RsaPublicKey = rsa.ToXmlString(false); + RsaPrivateKey = rsa.ToXmlString(true); + } + + return (RsaPublicKey, RsaPrivateKey); + } + + + public static string XMLToPEM_Pub(string xmlpubkey) + { + var rsa = new RSACryptoServiceProvider(); + rsa.FromXmlString(xmlpubkey); + var p = rsa.ExportParameters(false); + var key = new RsaKeyParameters(false, new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent)); + var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key); + var serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded(); + var publicKey = Convert.ToBase64String(serializedPublicBytes); + return Format(publicKey, true); + } + + + private static string Format(string key, bool type) + { + var result = string.Empty; + + var length = key.Length / 64; + for (var i = 0; i < length; i++) + { + var start = i * 64; + result = result + key.Substring(start, 64) + "\r\n"; + } + + result = result + key.Substring(length * 64); + if (type) + { + result = result.Insert(0, "-----BEGIN PUBLIC KEY-----\r\n"); + result += "\r\n-----END PUBLIC KEY-----"; } else { - throw new PlatformNotSupportedException("This method only supports Windows and Linux."); + result = result.Insert(0, "-----BEGIN PRIVATE KEY-----\r\n"); + result += "\r\n-----END PRIVATE KEY-----"; } + + return result; + } + + public static float GetTotalMemoryWindows() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem"); + foreach (var obj in searcher.Get()) + { + var memory = Convert.ToUInt64(obj["TotalPhysicalMemory"]); + return memory / 1024 / 1024; + } + } + + return 0; + } + + public static float GetAvailableMemoryWindows() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + var pc = new PerformanceCounter("Memory", "Available MBytes"); + return pc.NextValue(); + } + + return 0; + } + + public static float GetTotalMemoryLinux() + { + var lines = File.ReadAllLines("/proc/meminfo"); + foreach (var line in lines) + if (line.StartsWith("MemTotal")) + return float.Parse(line.Split(':')[1].Trim().Split(' ')[0]) / 1024; + return 0; + } + + public static float GetAvailableMemoryLinux() + { + var lines = File.ReadAllLines("/proc/meminfo"); + foreach (var line in lines) + if (line.StartsWith("MemAvailable")) + return float.Parse(line.Split(':')[1].Trim().Split(' ')[0]) / 1024; + return 0; + } + + public static float GetCpuUsage() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return GetCpuUsageLinux(); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return GetCpuUsageWindows(); + throw new NotSupportedException("Unsupported OS platform"); + } + + private static float GetCpuUsageLinux() + { + var lines = File.ReadAllLines("/proc/stat"); + var cpuInfo = lines[0].Split(' ', StringSplitOptions.RemoveEmptyEntries); + var idleTime = float.Parse(cpuInfo[4]); + float totalTime = 0; + + for (var i = 1; i < cpuInfo.Length; i++) totalTime += float.Parse(cpuInfo[i]); + + return 100 * (1 - idleTime / totalTime); + } + + private static float GetCpuUsageWindows() + { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + throw new PlatformNotSupportedException("PerformanceCounter is only supported on Windows"); + + var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); + cpuCounter.NextValue(); + Thread.Sleep(1000); + return cpuCounter.NextValue(); + } + + public static (string ModelName, int Cores, float Frequency) GetCpuDetails() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return GetCpuDetailsLinux(); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return GetCpuDetailsWindows(); + throw new NotSupportedException("Unsupported OS platform"); + } + + private static (string ModelName, int Cores, float Frequency) GetCpuDetailsLinux() + { + var lines = File.ReadAllLines("/proc/cpuinfo"); + var modelName = ""; + var cores = 0; + float frequency = 0; + + foreach (var line in lines) + { + if (line.StartsWith("model name")) modelName = line.Split(':')[1].Trim(); + if (line.StartsWith("cpu cores")) cores = int.Parse(line.Split(':')[1].Trim()); + if (line.StartsWith("cpu MHz")) frequency = float.Parse(line.Split(':')[1].Trim()); + } + + return (modelName, cores, frequency); + } + + private static (string ModelName, int Cores, float Frequency) GetCpuDetailsWindows() + { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + throw new PlatformNotSupportedException("ManagementObjectSearcher is only supported on Windows"); + + var modelName = ""; + var cores = 0; + float frequency = 0; + + var searcher = new ManagementObjectSearcher("select * from Win32_Processor"); + foreach (var item in searcher.Get()) + { + modelName = item["Name"]?.ToString() ?? "Unknown"; + cores = int.Parse(item["NumberOfCores"]?.ToString() ?? "0"); + frequency = float.Parse(item["MaxClockSpeed"]?.ToString() ?? "0") / 1000; // MHz to GHz + } + + return (modelName, cores, frequency); + } + + public static string GetSystemVersion() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return GetWindowsVersion(); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return GetLinuxVersion(); + throw new PlatformNotSupportedException("This method only supports Windows and Linux."); } private static string GetWindowsVersion() @@ -479,26 +441,24 @@ namespace EggLink.DanhengServer.WebServer.Server private static string GetLinuxVersion() { - string version = string.Empty; + var version = string.Empty; if (File.Exists("/etc/os-release")) { var lines = File.ReadAllLines("/etc/os-release"); foreach (var line in lines) - { if (line.StartsWith("PRETTY_NAME")) { version = line.Split('=')[1].Trim('"'); break; } - } } else if (File.Exists("/proc/version")) { version = File.ReadAllText("/proc/version"); } + return version; } - #endregion - } + #endregion } \ No newline at end of file diff --git a/WebServer/Server/MuipSession.cs b/WebServer/Server/MuipSession.cs index 9002e3b4..9053d399 100644 --- a/WebServer/Server/MuipSession.cs +++ b/WebServer/Server/MuipSession.cs @@ -1,14 +1,13 @@ using EggLink.DanhengServer.Database.Account; -namespace EggLink.DanhengServer.WebServer.Server -{ - public class MuipSession - { - public string RsaPublicKey { get; set; } = ""; - public string SessionId { get; set; } = ""; - public long ExpireTimeStamp { get; set; } = 0; +namespace EggLink.DanhengServer.WebServer.Server; - public bool IsAdmin { get; set; } = false; - public AccountData? Account { get; set; } = null; - } -} +public class MuipSession +{ + public string RsaPublicKey { get; set; } = ""; + public string SessionId { get; set; } = ""; + public long ExpireTimeStamp { get; set; } = 0; + + public bool IsAdmin { get; set; } = false; + public AccountData? Account { get; set; } = null; +} \ No newline at end of file diff --git a/WebServer/WebProgram.cs b/WebServer/WebProgram.cs index ce76d70e..f9786327 100644 --- a/WebServer/WebProgram.cs +++ b/WebServer/WebProgram.cs @@ -1,106 +1,85 @@ -using EggLink.DanhengServer.Util; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Server.Kestrel.Core; using System.Net; -using System.Diagnostics; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Hosting; -using System.IO; +using EggLink.DanhengServer.Util; +using Microsoft.AspNetCore; -namespace EggLink.DanhengServer.WebServer +namespace EggLink.DanhengServer.WebServer; + +public class WebProgram { - public class WebProgram + public static void Main(string[] args, int port, string address) { - public static void Main(string[] args, int port, string address) - { - BuildWebHost(args, port, address).Start(); - } - - public static IWebHost BuildWebHost(string[] args, int port, string address) - { - var b = WebHost.CreateDefaultBuilder(args) - .UseStartup() - .ConfigureLogging((hostingContext, logging) => - { - logging.ClearProviders(); - }) - .UseUrls(address); - - if (ConfigManager.Config.HttpServer.UseSSL) - { - b.UseKestrel(options => - { - options.Listen(IPAddress.Any, port, listenOptions => - { - listenOptions.UseHttps( - ConfigManager.Config.KeyStore.KeyStorePath, - ConfigManager.Config.KeyStore.KeyStorePassword - ); - }); - }); - } - - return b.Build(); - } + BuildWebHost(args, port, address).Start(); } - public class Startup + public static IWebHost BuildWebHost(string[] args, int port, string address) { - public void ConfigureServices(IServiceCollection services) - { - services.AddCors(options => + var b = WebHost.CreateDefaultBuilder(args) + .UseStartup() + .ConfigureLogging((hostingContext, logging) => { logging.ClearProviders(); }) + .UseUrls(address); + + if (ConfigManager.Config.HttpServer.UseSSL) + b.UseKestrel(options => { - options.AddPolicy("AllowAll", - builder => - { - builder.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader(); - }); + options.Listen(IPAddress.Any, port, listenOptions => + { + listenOptions.UseHttps( + ConfigManager.Config.KeyStore.KeyStorePath, + ConfigManager.Config.KeyStore.KeyStorePassword + ); + }); }); - services.AddControllers(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.Use(async (context, next) => - { - using var buffer = new MemoryStream(); - var request = context.Request; - var response = context.Response; - - var bodyStream = response.Body; - response.Body = buffer; - - await next.Invoke(); - buffer.Position = 0; - context.Response.Headers["Content-Length"] = (response.ContentLength ?? buffer.Length).ToString(); - context.Response.Headers.Remove("Transfer-Encoding"); - await buffer.CopyToAsync(bodyStream); - }); - - app.UseHttpsRedirection(); - - app.UseRouting(); - - app.UseCors("AllowAll"); - - app.UseAuthorization(); - - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } + return b.Build(); } } + +public class Startup +{ + public void ConfigureServices(IServiceCollection services) + { + services.AddCors(options => + { + options.AddPolicy("AllowAll", + builder => + { + builder.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + }); + }); + + services.AddControllers(); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); + + app.Use(async (context, next) => + { + using var buffer = new MemoryStream(); + var request = context.Request; + var response = context.Response; + + var bodyStream = response.Body; + response.Body = buffer; + + await next.Invoke(); + buffer.Position = 0; + context.Response.Headers["Content-Length"] = (response.ContentLength ?? buffer.Length).ToString(); + context.Response.Headers.Remove("Transfer-Encoding"); + await buffer.CopyToAsync(bodyStream); + }); + + app.UseHttpsRedirection(); + + app.UseRouting(); + + app.UseCors("AllowAll"); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); + } +} \ No newline at end of file