migrate everything to new tablereader

This commit is contained in:
rfi 2023-12-10 09:22:33 +07:00
parent 847b3efd4a
commit 259c744f23
6 changed files with 26 additions and 187 deletions

View File

@ -1,8 +1,8 @@
using MongoDB.Bson; using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver; using MongoDB.Driver;
using AscNet.Table.share.character; using AscNet.Table.V2.share.character;
using AscNet.Table.share.character.skill; using AscNet.Table.V2.share.character.skill;
using AscNet.Common.MsgPack; using AscNet.Common.MsgPack;
using AscNet.Common.Util; using AscNet.Common.Util;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -62,8 +62,8 @@ namespace AscNet.Common.Database
public AddCharacterRet AddCharacter(uint id) public AddCharacterRet AddCharacter(uint id)
{ {
AddCharacterRet ret = new(); AddCharacterRet ret = new();
CharacterTable? character = CharacterTableReader.Instance.FromId((int)id); CharacterTable? character = TableReaderV2.Parse<CharacterTable>().Find(x => x.Id == id);
CharacterSkillTable? characterSkill = CharacterSkillTableReader.Instance.FromCharacterId((int)id); CharacterSkillTable? characterSkill = TableReaderV2.Parse<CharacterSkillTable>().Find(x => x.CharacterId == id);
CharacterQualityTable? characterQuality = TableReaderV2.Parse<CharacterQualityTable>().OrderBy(x => x.Quality).FirstOrDefault(x => x.CharacterId == id); CharacterQualityTable? characterQuality = TableReaderV2.Parse<CharacterQualityTable>().OrderBy(x => x.Quality).FirstOrDefault(x => x.CharacterId == id);
if (character is null || characterSkill is null || characterQuality is null) if (character is null || characterSkill is null || characterQuality is null)
@ -98,11 +98,14 @@ namespace AscNet.Common.Database
HeadFashionType = 0 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() characterData.SkillList.AddRange(characterSkill.SkillGroupId.Take(8).Select(x => new NotifyCharacterDataList.CharacterData.CharacterSkill()
{ {
Id = uint.Parse(x.ToString().Take(6).ToArray()), Id = uint.Parse(x.ToString().Take(6).ToArray()),
Level = 1 Level = 1
})); }));
FashionList fashion = new() FashionList fashion = new()
{ {
Id = character.DefaultNpcFashtionId, Id = character.DefaultNpcFashtionId,
@ -120,7 +123,7 @@ namespace AscNet.Common.Database
public NotifyCharacterDataList.CharacterData? AddCharacterExp(int characterId, int exp, int maxLvl = 0) public NotifyCharacterDataList.CharacterData? AddCharacterExp(int characterId, int exp, int maxLvl = 0)
{ {
var characterData = TableReaderV2.Parse<Table.V2.share.character.CharacterTable>().FirstOrDefault(x => x.Id == characterId); var characterData = TableReaderV2.Parse<CharacterTable>().FirstOrDefault(x => x.Id == characterId);
var character = Characters.FirstOrDefault(x => x.Id == characterId); var character = Characters.FirstOrDefault(x => x.Id == characterId);
if (character is not null && characterData is not null) if (character is not null && characterData is not null)
@ -155,7 +158,7 @@ namespace AscNet.Common.Database
List<uint> affectedCharacters = new(); List<uint> affectedCharacters = new();
int totalCoinCost = 0; int totalCoinCost = 0;
int totalSkillPointCost = 0; int totalSkillPointCost = 0;
IEnumerable<int> affectedSkills = CharacterSkillGroupTableReader.Instance.All.Where(x => x.Id == skillGroupId).SelectMany(x => x.SkillId); IEnumerable<int> affectedSkills = TableReaderV2.Parse<CharacterSkillGroupTable>().Where(x => x.Id == skillGroupId).SelectMany(x => x.SkillId);
foreach (var skillId in affectedSkills) foreach (var skillId in affectedSkills)
{ {
@ -166,10 +169,10 @@ namespace AscNet.Common.Database
while (characterSkill.Level < targetLevel) while (characterSkill.Level < targetLevel)
{ {
var skillUpgrade = CharacterSkillUpgradeTableReader.Instance.All.FirstOrDefault(x => x.SkillId == skillId && Miscs.ParseIntOr(x.Level) == characterSkill.Level); var skillUpgrade = TableReaderV2.Parse<CharacterSkillUpgradeTable>().Find(x => x.SkillId == skillId && x.Level == characterSkill.Level);
totalCoinCost += Miscs.ParseIntOr(skillUpgrade?.UseCoin); totalCoinCost += skillUpgrade?.UseCoin ?? 0;
totalSkillPointCost += Miscs.ParseIntOr(skillUpgrade?.UseSkillPoint); totalSkillPointCost += skillUpgrade?.UseSkillPoint ?? 0;
characterSkill.Level++; characterSkill.Level++;
} }

View File

@ -1,5 +1,6 @@
using AscNet.Common.MsgPack; 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;
using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Options; using MongoDB.Bson.Serialization.Options;
@ -24,7 +25,7 @@ namespace AscNet.Common.Database
Uid = uid, Uid = uid,
Stages = new() Stages = new()
}; };
foreach (var guideFight in GuideFightTableReader.Instance.All) foreach (var guideFight in TableReaderV2.Parse<GuideFightTable>())
{ {
stage.AddStage(new StageDatum() stage.AddStage(new StageDatum()
{ {

View File

@ -1,5 +1,6 @@
using AscNet.Common.MsgPack; using AscNet.Common.MsgPack;
using AscNet.Table.share.fuben; using AscNet.Common.Util;
using AscNet.Table.V2.share.fuben;
namespace AscNet.GameServer.Commands namespace AscNet.GameServer.Commands
{ {
@ -18,7 +19,7 @@ namespace AscNet.GameServer.Commands
if (TargetStage == "all") if (TargetStage == "all")
{ {
session.stage.Stages.Clear(); session.stage.Stages.Clear();
foreach (var stageData in StageTableReader.Instance.All) foreach (var stageData in TableReaderV2.Parse<StageTable>())
{ {
session.stage.Stages.Add(stageData.StageId, new() session.stage.Stages.Add(stageData.StageId, new()
{ {
@ -43,7 +44,7 @@ namespace AscNet.GameServer.Commands
} }
else else
{ {
StageTable? stageData = StageTableReader.Instance.FromStageId(int.Parse(TargetStage)); StageTable? stageData = TableReaderV2.Parse<StageTable>().Find(x => x.StageId == int.Parse(TargetStage));
if (stageData is not null && !session.stage.Stages.ContainsKey(stageData.StageId)) if (stageData is not null && !session.stage.Stages.ContainsKey(stageData.StageId))
{ {
StageDatum stage = new() StageDatum stage = new()

View File

@ -1,9 +1,8 @@
using AscNet.Common.Database; using AscNet.Common.Database;
using AscNet.Common.MsgPack; using AscNet.Common.MsgPack;
using AscNet.Common.Util; using AscNet.Common.Util;
using AscNet.Table.share.chat; using AscNet.Table.V2.share.chat;
using AscNet.Table.share.guide; using AscNet.Table.V2.share.guide;
using AscNet.Table.share.item;
using MessagePack; using MessagePack;
using System.Diagnostics; using System.Diagnostics;
@ -146,7 +145,7 @@ namespace AscNet.GameServer.Handlers
notifyLogin.FashionList.AddRange(session.character.Fashions); notifyLogin.FashionList.AddRange(session.character.Fashions);
#if DEBUG #if DEBUG
notifyLogin.PlayerData.GuideData = GuideGroupTableReader.Instance.All.Select(x => (long)x.Id).ToList(); notifyLogin.PlayerData.GuideData = TableReaderV2.Parse<GuideGroupTable>().Select(x => (long)x.Id).ToList();
#endif #endif
NotifyStageData notifyStageData = new() NotifyStageData notifyStageData = new()
@ -192,7 +191,7 @@ namespace AscNet.GameServer.Handlers
NotifyChatLoginData notifyChatLoginData = new() NotifyChatLoginData notifyChatLoginData = new()
{ {
RefreshTime = ((DateTimeOffset)Process.GetCurrentProcess().StartTime).ToUnixTimeSeconds(), RefreshTime = ((DateTimeOffset)Process.GetCurrentProcess().StartTime).ToUnixTimeSeconds(),
UnlockEmojis = EmojiTableReader.Instance.All.Select(x => new NotifyChatLoginData.NotifyChatLoginDataUnlockEmoji() { Id = (uint)x.Id }).ToList() UnlockEmojis = TableReaderV2.Parse<EmojiTable>().Select(x => new NotifyChatLoginData.NotifyChatLoginDataUnlockEmoji() { Id = (uint)x.Id }).ToList()
}; };
NotifyItemDataList notifyItemDataList = new() NotifyItemDataList notifyItemDataList = new()

View File

@ -1,6 +1,7 @@
using AscNet.Common.MsgPack; using AscNet.Common.MsgPack;
using AscNet.Common.Util;
using AscNet.GameServer.Commands; using AscNet.GameServer.Commands;
using AscNet.Table.share.chat; using AscNet.Table.V2.share.chat;
using MessagePack; using MessagePack;
namespace AscNet.GameServer.Handlers namespace AscNet.GameServer.Handlers
@ -219,7 +220,7 @@ namespace AscNet.GameServer.Handlers
session.SendResponse(new GetEmojiPackageIdResponse() session.SendResponse(new GetEmojiPackageIdResponse()
{ {
Code = 0, Code = 0,
OrderEmojiPackageIds = EmojiPackTableReader.Instance.All.Select(x => x.Id).ToList() OrderEmojiPackageIds = TableReaderV2.Parse<EmojiPackTable>().Select(x => x.Id).ToList()
}, packet.Id); }, packet.Id);
} }
#endregion #endregion

View File

@ -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<object> 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<string> tsvLines = fileTsv.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
string[] nameList = tsvLines.First().Split('\t');
List<string[]> resolvedTypes = new();
foreach (var items in tsvLines.Skip(1).Select(x => x.Split('\t')))
{
List<string> 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<string, string> properties = new();
Dictionary<string, int> 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 = $@"// <auto-generated/>
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<string>($""{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) { }
}
}