From 259c744f231d62fd2face4b0fd7b573f79fa957d Mon Sep 17 00:00:00 2001 From: rfi Date: Sun, 10 Dec 2023 09:22:33 +0700 Subject: [PATCH] migrate everything to new tablereader --- AscNet.Common/Database/Character.cs | 21 +-- AscNet.Common/Database/Stage.cs | 5 +- AscNet.GameServer/Commands/StageCommand.cs | 7 +- AscNet.GameServer/Handlers/AccountModule.cs | 9 +- AscNet.GameServer/Handlers/ChatModule.cs | 5 +- AscNet.Table/TableGenerator.cs | 166 -------------------- 6 files changed, 26 insertions(+), 187 deletions(-) delete mode 100644 AscNet.Table/TableGenerator.cs diff --git a/AscNet.Common/Database/Character.cs b/AscNet.Common/Database/Character.cs index 0212c14f..77b64be3 100644 --- a/AscNet.Common/Database/Character.cs +++ b/AscNet.Common/Database/Character.cs @@ -1,8 +1,8 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; -using AscNet.Table.share.character; -using AscNet.Table.share.character.skill; +using AscNet.Table.V2.share.character; +using AscNet.Table.V2.share.character.skill; using AscNet.Common.MsgPack; using AscNet.Common.Util; using Newtonsoft.Json; @@ -62,8 +62,8 @@ namespace AscNet.Common.Database public AddCharacterRet AddCharacter(uint id) { AddCharacterRet ret = new(); - CharacterTable? character = CharacterTableReader.Instance.FromId((int)id); - CharacterSkillTable? characterSkill = CharacterSkillTableReader.Instance.FromCharacterId((int)id); + CharacterTable? character = TableReaderV2.Parse().Find(x => x.Id == id); + CharacterSkillTable? characterSkill = TableReaderV2.Parse().Find(x => x.CharacterId == id); CharacterQualityTable? characterQuality = TableReaderV2.Parse().OrderBy(x => x.Quality).FirstOrDefault(x => x.CharacterId == id); if (character is null || characterSkill is null || characterQuality is null) @@ -98,11 +98,14 @@ namespace AscNet.Common.Database HeadFashionType = 0 } }; + + // TODO: Don't do the ToString, query skill properly pls. characterData.SkillList.AddRange(characterSkill.SkillGroupId.Take(8).Select(x => new NotifyCharacterDataList.CharacterData.CharacterSkill() { Id = uint.Parse(x.ToString().Take(6).ToArray()), Level = 1 })); + FashionList fashion = new() { Id = character.DefaultNpcFashtionId, @@ -120,7 +123,7 @@ namespace AscNet.Common.Database public NotifyCharacterDataList.CharacterData? AddCharacterExp(int characterId, int exp, int maxLvl = 0) { - var characterData = TableReaderV2.Parse().FirstOrDefault(x => x.Id == characterId); + var characterData = TableReaderV2.Parse().FirstOrDefault(x => x.Id == characterId); var character = Characters.FirstOrDefault(x => x.Id == characterId); if (character is not null && characterData is not null) @@ -155,7 +158,7 @@ namespace AscNet.Common.Database List affectedCharacters = new(); int totalCoinCost = 0; int totalSkillPointCost = 0; - IEnumerable affectedSkills = CharacterSkillGroupTableReader.Instance.All.Where(x => x.Id == skillGroupId).SelectMany(x => x.SkillId); + IEnumerable affectedSkills = TableReaderV2.Parse().Where(x => x.Id == skillGroupId).SelectMany(x => x.SkillId); foreach (var skillId in affectedSkills) { @@ -166,10 +169,10 @@ namespace AscNet.Common.Database while (characterSkill.Level < targetLevel) { - var skillUpgrade = CharacterSkillUpgradeTableReader.Instance.All.FirstOrDefault(x => x.SkillId == skillId && Miscs.ParseIntOr(x.Level) == characterSkill.Level); + var skillUpgrade = TableReaderV2.Parse().Find(x => x.SkillId == skillId && x.Level == characterSkill.Level); - totalCoinCost += Miscs.ParseIntOr(skillUpgrade?.UseCoin); - totalSkillPointCost += Miscs.ParseIntOr(skillUpgrade?.UseSkillPoint); + totalCoinCost += skillUpgrade?.UseCoin ?? 0; + totalSkillPointCost += skillUpgrade?.UseSkillPoint ?? 0; characterSkill.Level++; } diff --git a/AscNet.Common/Database/Stage.cs b/AscNet.Common/Database/Stage.cs index 04b04a61..048fa592 100644 --- a/AscNet.Common/Database/Stage.cs +++ b/AscNet.Common/Database/Stage.cs @@ -1,5 +1,6 @@ using AscNet.Common.MsgPack; -using AscNet.Table.share.guide; +using AscNet.Common.Util; +using AscNet.Table.V2.share.guide; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Options; @@ -24,7 +25,7 @@ namespace AscNet.Common.Database Uid = uid, Stages = new() }; - foreach (var guideFight in GuideFightTableReader.Instance.All) + foreach (var guideFight in TableReaderV2.Parse()) { stage.AddStage(new StageDatum() { diff --git a/AscNet.GameServer/Commands/StageCommand.cs b/AscNet.GameServer/Commands/StageCommand.cs index b3f4b412..e0e8f2f2 100644 --- a/AscNet.GameServer/Commands/StageCommand.cs +++ b/AscNet.GameServer/Commands/StageCommand.cs @@ -1,5 +1,6 @@ using AscNet.Common.MsgPack; -using AscNet.Table.share.fuben; +using AscNet.Common.Util; +using AscNet.Table.V2.share.fuben; namespace AscNet.GameServer.Commands { @@ -18,7 +19,7 @@ namespace AscNet.GameServer.Commands if (TargetStage == "all") { session.stage.Stages.Clear(); - foreach (var stageData in StageTableReader.Instance.All) + foreach (var stageData in TableReaderV2.Parse()) { session.stage.Stages.Add(stageData.StageId, new() { @@ -43,7 +44,7 @@ namespace AscNet.GameServer.Commands } else { - StageTable? stageData = StageTableReader.Instance.FromStageId(int.Parse(TargetStage)); + StageTable? stageData = TableReaderV2.Parse().Find(x => x.StageId == int.Parse(TargetStage)); if (stageData is not null && !session.stage.Stages.ContainsKey(stageData.StageId)) { StageDatum stage = new() diff --git a/AscNet.GameServer/Handlers/AccountModule.cs b/AscNet.GameServer/Handlers/AccountModule.cs index c0632889..6d075fd3 100644 --- a/AscNet.GameServer/Handlers/AccountModule.cs +++ b/AscNet.GameServer/Handlers/AccountModule.cs @@ -1,9 +1,8 @@ using AscNet.Common.Database; using AscNet.Common.MsgPack; using AscNet.Common.Util; -using AscNet.Table.share.chat; -using AscNet.Table.share.guide; -using AscNet.Table.share.item; +using AscNet.Table.V2.share.chat; +using AscNet.Table.V2.share.guide; using MessagePack; using System.Diagnostics; @@ -146,7 +145,7 @@ namespace AscNet.GameServer.Handlers notifyLogin.FashionList.AddRange(session.character.Fashions); #if DEBUG - notifyLogin.PlayerData.GuideData = GuideGroupTableReader.Instance.All.Select(x => (long)x.Id).ToList(); + notifyLogin.PlayerData.GuideData = TableReaderV2.Parse().Select(x => (long)x.Id).ToList(); #endif NotifyStageData notifyStageData = new() @@ -192,7 +191,7 @@ namespace AscNet.GameServer.Handlers NotifyChatLoginData notifyChatLoginData = new() { RefreshTime = ((DateTimeOffset)Process.GetCurrentProcess().StartTime).ToUnixTimeSeconds(), - UnlockEmojis = EmojiTableReader.Instance.All.Select(x => new NotifyChatLoginData.NotifyChatLoginDataUnlockEmoji() { Id = (uint)x.Id }).ToList() + UnlockEmojis = TableReaderV2.Parse().Select(x => new NotifyChatLoginData.NotifyChatLoginDataUnlockEmoji() { Id = (uint)x.Id }).ToList() }; NotifyItemDataList notifyItemDataList = new() diff --git a/AscNet.GameServer/Handlers/ChatModule.cs b/AscNet.GameServer/Handlers/ChatModule.cs index cc181784..b4ec7c1b 100644 --- a/AscNet.GameServer/Handlers/ChatModule.cs +++ b/AscNet.GameServer/Handlers/ChatModule.cs @@ -1,6 +1,7 @@ using AscNet.Common.MsgPack; +using AscNet.Common.Util; using AscNet.GameServer.Commands; -using AscNet.Table.share.chat; +using AscNet.Table.V2.share.chat; using MessagePack; namespace AscNet.GameServer.Handlers @@ -219,7 +220,7 @@ namespace AscNet.GameServer.Handlers session.SendResponse(new GetEmojiPackageIdResponse() { Code = 0, - OrderEmojiPackageIds = EmojiPackTableReader.Instance.All.Select(x => x.Id).ToList() + OrderEmojiPackageIds = TableReaderV2.Parse().Select(x => x.Id).ToList() }, packet.Id); } #endregion diff --git a/AscNet.Table/TableGenerator.cs b/AscNet.Table/TableGenerator.cs deleted file mode 100644 index 78141a3a..00000000 --- a/AscNet.Table/TableGenerator.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Microsoft.CodeAnalysis; - -namespace AscNet.Table -{ - [Generator] - public class TableGenerator : ISourceGenerator - { - public void Execute(GeneratorExecutionContext context) - { - List fails = new(); - foreach (var table in context.AdditionalFiles.Where(x => x.Path.EndsWith(".tsv"))) - { - try - { - string ns = string.Join("", Path.GetDirectoryName(table.Path)?.Split(new string[] { "table" }, StringSplitOptions.None).Skip(1)!) - .Replace('\\', '/').Replace('/', '.'); - - string fileTsv = table.GetText()?.ToString() ?? string.Empty; - - IEnumerable tsvLines = fileTsv.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); - - string[] nameList = tsvLines.First().Split('\t'); - List resolvedTypes = new(); - - foreach (var items in tsvLines.Skip(1).Select(x => x.Split('\t'))) - { - List types = new(); - foreach (var item in items) - { - if (string.IsNullOrEmpty(item)) - { - types.Add("global::System.String"); - continue; - } - else if (int.TryParse(item, out var res)) - { - types.Add("global::System.Int32"); - continue; - } - types.Add("global::System.String"); - } - resolvedTypes.Add([.. types]); - } - - Dictionary properties = new(); - Dictionary listCount = new(); - - for (int i = 0; i < nameList.Length; i++) - { - string headName = nameList[i]; - if (string.IsNullOrEmpty(headName)) - continue; - - string[] types = resolvedTypes.Select(x => x[i]).ToArray(); - string propName = headName.Split('[').First(); - - - string resolvedType = types.All(x => x.Equals(types.First())) ? types.First() : "global::System.String"; - if (headName.Contains('[')) - { - if (listCount.ContainsKey(propName)) - listCount[propName] += 1; - else - listCount.Add(propName, 1); - resolvedType = $"global::System.Collections.Generic.List<{resolvedType}>"; - } - - if (!properties.ContainsKey(propName)) - properties.Add(propName, $"public {resolvedType} {propName} {{ get; set; }}"); - } - - string file = $@"// -namespace AscNet.Table{ns} -{{ - #nullable enable - #pragma warning disable CS8618, CS8602 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - public class {Path.GetFileName(table.Path).Split('.').First()}Table - {{ - {string.Join("\r\n\t\t", properties.Values)} - }} - - public class {Path.GetFileName(table.Path).Split('.').First()}TableReader : global::AscNet.Common.Util.TableReader<{Path.GetFileName(table.Path).Split('.').First()}TableReader, {Path.GetFileName(table.Path).Split('.').First()}Table> - {{ - protected override string FilePath {{ get {{ return ""{string.Join("", table.Path.Replace("\\", "/").Split(new string[] {"/Resources/"}, StringSplitOptions.None).Skip(1))}""; }} }} - - public override void Load() - {{ - string tsvStr = global::System.IO.File.ReadAllText(FilePath); - string[] tsvValues = tsvStr.Split('\t'); - string[] csvValues = new string[tsvValues.Length]; - for (int i = 0; i < tsvValues.Length; i++) - {{ - if (tsvValues[i].Contains("","")) - {{ - csvValues[i] = ""\"""" + tsvValues[i].Replace(""\"""", ""\""\"""") + ""\""""; - }} - else - {{ - csvValues[i] = tsvValues[i]; - }} - }} - using var reader = new global::System.IO.StringReader(string.Join("","", csvValues)); - using var csv = new global::CsvHelper.CsvReader(reader, new global::CsvHelper.Configuration.CsvConfiguration(global::System.Globalization.CultureInfo.InvariantCulture) {{ BadDataFound = null, HeaderValidated = null, MissingFieldFound = null }}); - csv.Context.RegisterClassMap<{Path.GetFileName(table.Path).Split('.').First()}TableMap>(); - All = csv.GetRecords<{Path.GetFileName(table.Path).Split('.').First()}Table>().ToList(); - }} -{string.Join("\r\n", properties.Values.Select(x => x.Split(' ')).Where(x => !x[1].Contains("<")).Select(property => $@" - public {Path.GetFileName(table.Path).Split('.').First()}Table? From{property[2]}({property[1]} val) - {{ - return All.FirstOrDefault(x => x.{property[2]} == val); - }} -"))} - }} - - public sealed class {Path.GetFileName(table.Path).Split('.').First()}TableMap : global::CsvHelper.Configuration.ClassMap<{Path.GetFileName(table.Path).Split('.').First()}Table> - {{ - public {Path.GetFileName(table.Path).Split('.').First()}TableMap() - {{ - {string.Join("\r\n\t\t\t", properties.Keys.Where(x => !listCount.ContainsKey(x)).Select(x => $"Map(m => m.{x}).Name(\"{x}\");"))} -{string.Join("\r\n\t\t\t", listCount.Keys.Select(x => $@" - Map(m => m.{x}).Convert(args => - {{ - {properties[x].Split(' ')[1]} tags = new {properties[x].Split(' ')[1]}(); - {(nameList.Contains($"{x}[0]") ? $"for (int i = 0; i < {listCount[x]}; i++)" : $"for (int i = 1; i <= {listCount[x]}; i++)")} - {{ - string? tagValue = args.Row.GetField($""{x}[{{i}}]""); - if (!string.IsNullOrEmpty(tagValue)) - {{ -{(properties[x].Split('<')[1].StartsWith("global::System.Int32") ? @" - if (int.TryParse(tagValue, out int tag)) - { - tags.Add(tag); - }": @" - tags.Add(tagValue); -")} - }} - }} - - return tags; - }}); -"))} - }} - }} -}}"; - context.AddSource($"AscNet.Table{ns}.{Path.GetFileName(table.Path).Split('.').First()}.g.cs", file); - } - catch (Exception ex) - { - fails.Add(new - { - msg = ex.ToString(), - file = table.Path - }); - } - } - - // File.WriteAllText("./generator_fails.json", JsonConvert.SerializeObject(fails, Formatting.Indented)); - } - - public void Initialize(GeneratorInitializationContext context) { } - } -} \ No newline at end of file