饭太稀
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Fantasy.Exporter;
|
||||
|
||||
/// <summary>
|
||||
/// 定义日志记录功能的接口。
|
||||
/// </summary>
|
||||
public interface ILog
|
||||
{
|
||||
/// <summary>
|
||||
/// 记录跟踪级别的日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息。</param>
|
||||
void Trace(string message);
|
||||
/// <summary>
|
||||
/// 记录警告级别的日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息。</param>
|
||||
void Warning(string message);
|
||||
/// <summary>
|
||||
/// 记录信息级别的日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息。</param>
|
||||
void Info(string message);
|
||||
/// <summary>
|
||||
/// 记录调试级别的日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息。</param>
|
||||
void Debug(string message);
|
||||
/// <summary>
|
||||
/// 记录错误级别的日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息。</param>
|
||||
void Error(string message);
|
||||
/// <summary>
|
||||
/// 记录跟踪级别的格式化日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息模板。</param>
|
||||
/// <param name="args">格式化参数。</param>
|
||||
void Trace(string message, params object[] args);
|
||||
/// <summary>
|
||||
/// 记录警告级别的格式化日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息模板。</param>
|
||||
/// <param name="args">格式化参数。</param>
|
||||
void Warning(string message, params object[] args);
|
||||
/// <summary>
|
||||
/// 记录信息级别的格式化日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息模板。</param>
|
||||
/// <param name="args">格式化参数。</param>
|
||||
void Info(string message, params object[] args);
|
||||
/// <summary>
|
||||
/// 记录调试级别的格式化日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息模板。</param>
|
||||
/// <param name="args">格式化参数。</param>
|
||||
void Debug(string message, params object[] args);
|
||||
/// <summary>
|
||||
/// 记录错误级别的格式化日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息模板。</param>
|
||||
/// <param name="args">格式化参数。</param>
|
||||
void Error(string message, params object[] args);
|
||||
}
|
||||
|
||||
public static class Log
|
||||
{
|
||||
private static readonly ILog LogCore;
|
||||
|
||||
static Log()
|
||||
{
|
||||
LogCore = new ConsoleLog();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记录信息级别的日志消息。
|
||||
/// </summary>
|
||||
/// <param name="msg">日志消息。</param>
|
||||
public static void Info(string msg)
|
||||
{
|
||||
LogCore.Info(msg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记录错误级别的日志消息,并附带调用栈信息。
|
||||
/// </summary>
|
||||
/// <param name="msg">日志消息。</param>
|
||||
public static void Error(string msg)
|
||||
{
|
||||
var st = new StackTrace(1, true);
|
||||
LogCore.Error($"{msg}\n{st}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记录异常的错误级别的日志消息,并附带调用栈信息。
|
||||
/// </summary>
|
||||
/// <param name="e">异常对象。</param>
|
||||
public static void Error(Exception e)
|
||||
{
|
||||
if (e.Data.Contains("StackTrace"))
|
||||
{
|
||||
LogCore.Error($"{e.Data["StackTrace"]}\n{e}");
|
||||
return;
|
||||
}
|
||||
|
||||
var str = e.ToString();
|
||||
LogCore.Error(str);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记录信息级别的格式化日志消息。
|
||||
/// </summary>
|
||||
/// <param name="message">日志消息模板。</param>
|
||||
/// <param name="args">格式化参数。</param>
|
||||
public static void Info(string message, params object[] args)
|
||||
{
|
||||
LogCore.Info(string.Format(message, args));
|
||||
}
|
||||
}
|
||||
|
||||
public class ConsoleLog : ILog
|
||||
{
|
||||
public void Info(string message)
|
||||
{
|
||||
Console.WriteLine(message);
|
||||
}
|
||||
|
||||
public void Error(string message)
|
||||
{
|
||||
ConsoleColor color = Console.ForegroundColor;
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine($"{message}\n{new StackTrace(1, true)}");
|
||||
Console.ForegroundColor = color;
|
||||
}
|
||||
|
||||
public void Trace(string message)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Warning(string message)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Debug(string message)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Trace(string message, params object[] args)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Warning(string message, params object[] args)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Info(string message, params object[] args)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Debug(string message, params object[] args)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Error(string message, params object[] args)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
namespace Fantasy.Tools.ProtocalExporter;
|
||||
|
||||
public sealed class CustomSerialize
|
||||
{
|
||||
public string NameSpace { get; set; }
|
||||
public int KeyIndex { get; set; }
|
||||
public string SerializeName { get; set; }
|
||||
public string Attribute { get; set; }
|
||||
public string Ignore { get; set; }
|
||||
public string Member { get; set; }
|
||||
public uint OpCodeType { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Fantasy.Tools;
|
||||
|
||||
/// <summary>
|
||||
/// 导出目标平台枚举,用于标识导出到哪个平台。
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum ExportPlatform : byte
|
||||
{
|
||||
None = 0,
|
||||
Client = 1,
|
||||
Server = 1 << 1,
|
||||
All = Client | Server,
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace Fantasy.Tools.ProtocalExporter;
|
||||
|
||||
public static class NetworkProtocolTemplate
|
||||
{
|
||||
public static readonly string Template ="""
|
||||
#if SERVER
|
||||
using ProtoBuf;
|
||||
(UsingNamespace)
|
||||
using System.Collections.Generic;
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
using Fantasy;
|
||||
using Fantasy.Network.Interface;
|
||||
using Fantasy.Serialize;
|
||||
// ReSharper disable InconsistentNaming
|
||||
// ReSharper disable RedundantUsingDirective
|
||||
// ReSharper disable RedundantOverriddenMember
|
||||
// ReSharper disable PartialTypeWithSinglePart
|
||||
// ReSharper disable UnusedAutoPropertyAccessor.Global
|
||||
// ReSharper disable MemberCanBePrivate.Global
|
||||
// ReSharper disable CheckNamespace
|
||||
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
|
||||
#pragma warning disable CS8618
|
||||
|
||||
namespace Fantasy
|
||||
{
|
||||
#else
|
||||
using ProtoBuf;
|
||||
(UsingNamespace)
|
||||
using System.Collections.Generic;
|
||||
using Fantasy;
|
||||
using Fantasy.Network.Interface;
|
||||
using Fantasy.Serialize;
|
||||
#pragma warning disable CS8618
|
||||
|
||||
namespace Fantasy
|
||||
{
|
||||
#endif
|
||||
(Content)}
|
||||
""";
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Fantasy.Helper;
|
||||
|
||||
namespace Fantasy.Tools.ProtocalExporter;
|
||||
|
||||
internal class OpCodeCache
|
||||
{
|
||||
private readonly List<uint> _opCodes = new List<uint>();
|
||||
private readonly Dictionary<string, uint> _opcodeCache;
|
||||
private readonly Dictionary<string, uint> _saveOpCodeCache = new();
|
||||
private readonly string _opcodeCachePath = $"{ExporterSettingsHelper.NetworkProtocolDirectory}OpCode.Cache";
|
||||
|
||||
/// <summary>
|
||||
/// 构造函数,用于初始化网络协议操作码缓存
|
||||
/// </summary>
|
||||
public OpCodeCache(bool regenerate)
|
||||
{
|
||||
if (File.Exists(_opcodeCachePath) && !regenerate)
|
||||
{
|
||||
var readAllText = File.ReadAllText(_opcodeCachePath);
|
||||
_opcodeCache = readAllText.Deserialize<Dictionary<string, uint>>();
|
||||
_opCodes.AddRange(_opcodeCache.Values);
|
||||
}
|
||||
else
|
||||
{
|
||||
_opcodeCache = new Dictionary<string, uint>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存网络协议操作码
|
||||
/// </summary>
|
||||
public void Save()
|
||||
{
|
||||
File.WriteAllText(_opcodeCachePath, _saveOpCodeCache.ToJson());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据className获得OpCode、如果是新增的会产生一个新的OpCode
|
||||
/// </summary>
|
||||
/// <param name="className">协议名</param>
|
||||
/// <param name="opcode">操作码</param>
|
||||
/// <returns></returns>
|
||||
public uint GetOpcodeCache(string className, ref uint opcode)
|
||||
{
|
||||
if (!_opcodeCache.TryGetValue(className, out var opCode))
|
||||
{
|
||||
while (_opCodes.Contains(++opcode))
|
||||
{
|
||||
|
||||
}
|
||||
opCode = opcode;
|
||||
_opCodes.Add(opCode);
|
||||
}
|
||||
|
||||
_saveOpCodeCache.Add(className, opCode);
|
||||
return opCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,891 @@
|
||||
using System.Text;
|
||||
using Fantasy.Exporter;
|
||||
using Fantasy.Helper;
|
||||
using Fantasy.Network;
|
||||
using OpCode = Fantasy.Network.OpCode;
|
||||
using OpCodeType = Fantasy.Network.OpCodeType;
|
||||
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
|
||||
#pragma warning disable CS8602 // Dereference of a possibly null reference.
|
||||
// ReSharper disable PossibleNullReferenceException
|
||||
// ReSharper disable ConditionIsAlwaysTrueOrFalse
|
||||
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
#pragma warning disable CS8604 // Possible null reference argument.
|
||||
|
||||
namespace Fantasy.Tools.ProtocalExporter;
|
||||
public enum NetworkProtocolOpCodeType
|
||||
{
|
||||
None = 0,
|
||||
Outer = 1,
|
||||
Inner = 2,
|
||||
}
|
||||
public sealed class OpcodeInfo
|
||||
{
|
||||
public uint Code;
|
||||
public string Name;
|
||||
}
|
||||
|
||||
public sealed class ProtocolExporter
|
||||
{
|
||||
private string _serverTemplate;
|
||||
private string _clientTemplate;
|
||||
private readonly List<OpcodeInfo> _opcodes = new();
|
||||
private static readonly char[] SplitChars = [' ', '\t'];
|
||||
private readonly string _networkProtocolDirectory;
|
||||
private readonly string _networkProtocolClientDirectory;
|
||||
private readonly string _networkProtocolServerDirectory;
|
||||
private readonly string _networkProtocolDirectoryOuter;
|
||||
private readonly string _networkProtocolDirectoryInner;
|
||||
|
||||
public ProtocolExporter()
|
||||
{
|
||||
Console.OutputEncoding = Encoding.UTF8;
|
||||
|
||||
if (ExporterSettingsHelper.NetworkProtocolDirectory == null || ExporterSettingsHelper.NetworkProtocolDirectory.Trim() == "")
|
||||
{
|
||||
Log.Info($"NetworkProtocolDirectory Can not be empty!");
|
||||
return;
|
||||
}
|
||||
|
||||
_networkProtocolDirectory = ExporterSettingsHelper.NetworkProtocolDirectory;
|
||||
if (ExporterAges.Instance.ExportPlatform.HasFlag(ExportPlatform.Client))
|
||||
{
|
||||
if (ExporterSettingsHelper.NetworkProtocolClientDirectory?.Trim() == "")
|
||||
{
|
||||
Log.Info($"NetworkProtocolClientDirectory Can not be empty!");
|
||||
return;
|
||||
}
|
||||
|
||||
_networkProtocolClientDirectory = ExporterSettingsHelper.NetworkProtocolClientDirectory ?? string.Empty;
|
||||
if (!Directory.Exists(_networkProtocolClientDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(_networkProtocolClientDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
if (ExporterAges.Instance.ExportPlatform.HasFlag(ExportPlatform.Server))
|
||||
{
|
||||
if (ExporterSettingsHelper.NetworkProtocolServerDirectory?.Trim() == "")
|
||||
{
|
||||
Log.Info($"NetworkProtocolServerDirectory Can not be empty!");
|
||||
return;
|
||||
}
|
||||
|
||||
_networkProtocolServerDirectory = ExporterSettingsHelper.NetworkProtocolServerDirectory ?? string.Empty;
|
||||
if (!Directory.Exists(_networkProtocolServerDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(_networkProtocolServerDirectory);
|
||||
}
|
||||
|
||||
_networkProtocolDirectoryInner = $"{_networkProtocolDirectory}Inner";
|
||||
|
||||
if (!Directory.Exists(_networkProtocolDirectoryInner))
|
||||
{
|
||||
Directory.CreateDirectory(_networkProtocolDirectoryInner);
|
||||
}
|
||||
}
|
||||
|
||||
_networkProtocolDirectoryOuter = $"{_networkProtocolDirectory}Outer";
|
||||
|
||||
if (!Directory.Exists(_networkProtocolDirectoryOuter))
|
||||
{
|
||||
Directory.CreateDirectory(_networkProtocolDirectoryOuter);
|
||||
}
|
||||
}
|
||||
|
||||
public void Run()
|
||||
{
|
||||
var tasks = new Task[3];
|
||||
tasks[0] = Task.Run(RouteType);
|
||||
tasks[1] = Task.Run(RoamingType);
|
||||
tasks[2] = Task.Run(async () =>
|
||||
{
|
||||
LoadTemplate();
|
||||
await Start(NetworkProtocolOpCodeType.Outer);
|
||||
if (ExporterAges.Instance.ExportPlatform.HasFlag(ExportPlatform.Server))
|
||||
{
|
||||
await Start(NetworkProtocolOpCodeType.Inner);
|
||||
}
|
||||
});
|
||||
Task.WaitAll(tasks);
|
||||
}
|
||||
|
||||
private async Task Start(NetworkProtocolOpCodeType opCodeType)
|
||||
{
|
||||
var className = "";
|
||||
var opCodeName = "";
|
||||
var file = new StringBuilder();
|
||||
var messageStr = new StringBuilder();
|
||||
var disposeStr = new StringBuilder();
|
||||
var errorCodeStr = new StringBuilder();
|
||||
var usingNamespace = new HashSet<string>();
|
||||
var saveDirectory = new Dictionary<string, string>();
|
||||
|
||||
OpcodeInfo opcodeInfo = null;
|
||||
ProtocolOpCode protocolOpCode = null;
|
||||
string[] protocolFiles = null;
|
||||
_opcodes.Clear();
|
||||
|
||||
switch (opCodeType)
|
||||
{
|
||||
case NetworkProtocolOpCodeType.Outer:
|
||||
{
|
||||
if (ExporterAges.Instance.ExportPlatform.HasFlag(ExportPlatform.Server))
|
||||
{
|
||||
saveDirectory.Add(_networkProtocolServerDirectory, _serverTemplate);
|
||||
}
|
||||
|
||||
if (ExporterAges.Instance.ExportPlatform.HasFlag(ExportPlatform.Client))
|
||||
{
|
||||
saveDirectory.Add(_networkProtocolClientDirectory, _clientTemplate);
|
||||
}
|
||||
|
||||
protocolOpCode = new ProtocolOpCode()
|
||||
{
|
||||
Message = OpCodeType.OuterMessage,
|
||||
Request = OpCodeType.OuterRequest,
|
||||
Response = OpCodeType.OuterResponse,
|
||||
RouteMessage = 0,
|
||||
RouteRequest = 0,
|
||||
RouteResponse = 0,
|
||||
AddressableMessage = OpCodeType.OuterAddressableMessage,
|
||||
AddressableRequest = OpCodeType.OuterAddressableRequest,
|
||||
AddressableResponse = OpCodeType.OuterAddressableResponse,
|
||||
CustomRouteMessage = OpCodeType.OuterCustomRouteMessage,
|
||||
CustomRouteRequest = OpCodeType.OuterCustomRouteRequest,
|
||||
CustomRouteResponse = OpCodeType.OuterCustomRouteResponse,
|
||||
RoamingMessage = OpCodeType.OuterRoamingMessage,
|
||||
RoamingRequest = OpCodeType.OuterRoamingRequest,
|
||||
RoamingResponse = OpCodeType.OuterRoamingResponse,
|
||||
};
|
||||
opCodeName = "OuterOpcode";
|
||||
protocolFiles = FileHelper.GetDirectoryFile(_networkProtocolDirectoryOuter, "*.proto", SearchOption.AllDirectories);
|
||||
break;
|
||||
}
|
||||
case NetworkProtocolOpCodeType.Inner:
|
||||
{
|
||||
protocolOpCode = new ProtocolOpCode()
|
||||
{
|
||||
Message = OpCodeType.InnerMessage,
|
||||
Request = OpCodeType.InnerRequest,
|
||||
Response = OpCodeType.InnerResponse,
|
||||
RouteMessage = OpCodeType.InnerRouteMessage,
|
||||
RouteRequest = OpCodeType.InnerRouteRequest,
|
||||
RouteResponse = OpCodeType.InnerRouteResponse,
|
||||
AddressableMessage = OpCodeType.InnerAddressableMessage,
|
||||
AddressableRequest = OpCodeType.InnerAddressableRequest,
|
||||
AddressableResponse = OpCodeType.InnerAddressableResponse,
|
||||
CustomRouteMessage = 0,
|
||||
CustomRouteRequest = 0,
|
||||
CustomRouteResponse = 0,
|
||||
RoamingMessage = OpCodeType.InnerRoamingMessage,
|
||||
RoamingRequest = OpCodeType.InnerRoamingRequest,
|
||||
RoamingResponse = OpCodeType.InnerRoamingResponse,
|
||||
};
|
||||
opCodeName = "InnerOpcode";
|
||||
saveDirectory.Add(_networkProtocolServerDirectory, _serverTemplate);
|
||||
protocolFiles = FileHelper.GetDirectoryFile(_networkProtocolDirectoryInner, "*.proto", SearchOption.AllDirectories);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (protocolFiles == null || protocolFiles.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
#region GenerateFiles
|
||||
|
||||
foreach (var filePath in protocolFiles)
|
||||
{
|
||||
var keyIndex = 1;
|
||||
var parameter = "";
|
||||
var hasOpCode = false;
|
||||
var isMsgHead = false;
|
||||
var isSetProtocol = false;
|
||||
string responseTypeStr = null;
|
||||
string customRouteType = null;
|
||||
string protocolMember = "ProtoMember";
|
||||
string protocolType = "\t[ProtoContract]";
|
||||
string protocolIgnore = "\t\t[ProtoIgnore]";
|
||||
var protocolOpCodeType = OpCodeProtocolType.ProtoBuf;
|
||||
var fileText = await File.ReadAllTextAsync(filePath);
|
||||
|
||||
foreach (var line in fileText.Split('\n'))
|
||||
{
|
||||
var currentLine = line.Trim();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(currentLine))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentLine.StartsWith("///"))
|
||||
{
|
||||
messageStr.AppendFormat(" /// <summary>\r\n" + " /// {0}\r\n" + " /// </summary>\r\n", currentLine.Substring("///".Length));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentLine.StartsWith("// Protocol"))
|
||||
{
|
||||
isSetProtocol = true;
|
||||
var protocol = currentLine.Substring("// Protocol".Length).Trim();
|
||||
|
||||
switch (protocol)
|
||||
{
|
||||
case "ProtoBuf":
|
||||
{
|
||||
protocolType = "\t[ProtoContract]";
|
||||
protocolIgnore = "\t\t[ProtoIgnore]";
|
||||
protocolMember = "ProtoMember";
|
||||
protocolOpCodeType = OpCodeProtocolType.ProtoBuf;
|
||||
break;
|
||||
}
|
||||
// case "MemoryPack":
|
||||
// {
|
||||
// keyIndex = 0;
|
||||
// protocolType = "\t[MemoryPackable]";
|
||||
// protocolIgnore = "\t\t[MemoryPackIgnore]";
|
||||
// protocolMember = "MemoryPackOrder";
|
||||
// // protocolOpCodeType = OpCodeProtocolType.MemoryPack;
|
||||
// break;
|
||||
// }
|
||||
case "Bson":
|
||||
{
|
||||
if (opCodeType == NetworkProtocolOpCodeType.Outer)
|
||||
{
|
||||
Log.Error("Under Outer, /// does not support the Bson protocol!");
|
||||
return;
|
||||
}
|
||||
protocolType = null;
|
||||
protocolIgnore = "\t\t[BsonIgnore]";
|
||||
protocolMember = null;
|
||||
protocolOpCodeType = OpCodeProtocolType.Bson;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
if (!ExporterSettingsHelper.CustomSerializes.TryGetValue(protocol, out var customSerialize))
|
||||
{
|
||||
Log.Error($"// Protocol {protocol} is not supported!");
|
||||
return;
|
||||
}
|
||||
|
||||
usingNamespace.Add(customSerialize.NameSpace);
|
||||
keyIndex = customSerialize.KeyIndex;
|
||||
protocolType = customSerialize.Attribute;
|
||||
protocolIgnore = customSerialize.Ignore;
|
||||
protocolMember = customSerialize.Member;
|
||||
protocolOpCodeType = customSerialize.OpCodeType;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (currentLine.StartsWith("message"))
|
||||
{
|
||||
isMsgHead = true;
|
||||
className = currentLine.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries)[1];
|
||||
var splits = currentLine.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
if (isSetProtocol)
|
||||
{
|
||||
if (protocolType != null)
|
||||
{
|
||||
messageStr.AppendLine(protocolType);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
messageStr.AppendLine("\t[ProtoContract]");
|
||||
}
|
||||
|
||||
if (splits.Length > 1)
|
||||
{
|
||||
hasOpCode = true;
|
||||
var parameterArray = currentLine.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim().Split(',');
|
||||
parameter = parameterArray[0].Trim();
|
||||
opcodeInfo = new OpcodeInfo()
|
||||
{
|
||||
Name = className
|
||||
};
|
||||
switch (parameterArray.Length)
|
||||
{
|
||||
case 2:
|
||||
{
|
||||
switch (parameter)
|
||||
{
|
||||
case "ICustomRouteMessage":
|
||||
{
|
||||
customRouteType = $"Fantasy.RouteType.{parameterArray[1].Trim()}";
|
||||
break;
|
||||
}
|
||||
case "IRoamingMessage":
|
||||
{
|
||||
customRouteType = $"Fantasy.RoamingType.{parameterArray[1].Trim()}";
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
responseTypeStr = parameterArray[1].Trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
responseTypeStr = parameterArray[1].Trim();
|
||||
customRouteType = parameter.Contains("IRoaming") ? $"Fantasy.RoamingType.{parameterArray[2].Trim()}" : $"Fantasy.RouteType.{parameterArray[2].Trim()}";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
parameter = "";
|
||||
hasOpCode = false;
|
||||
}
|
||||
|
||||
messageStr.Append(string.IsNullOrWhiteSpace(parameter)
|
||||
? $"\tpublic partial class {className} : AMessage"
|
||||
: $"\tpublic partial class {className} : AMessage, {parameter}");
|
||||
if (protocolMember == "ProtoMember")
|
||||
{
|
||||
messageStr.Append(", IProto");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isMsgHead)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (currentLine)
|
||||
{
|
||||
case "{":
|
||||
{
|
||||
messageStr.AppendLine("\n\t{");
|
||||
messageStr.AppendLine($"\t\tpublic static {className} Create(Scene scene)");
|
||||
messageStr.AppendLine($"\t\t{{\n\t\t\treturn scene.MessagePoolComponent.Rent<{className}>();\n\t\t}}");
|
||||
messageStr.AppendLine($"\t\tpublic override void Dispose()");
|
||||
messageStr.AppendLine($"\t\t{{");
|
||||
messageStr.AppendLine($"<<<<Dispose>>>#if FANTASY_NET || FANTASY_UNITY\n\t\t\tGetScene().MessagePoolComponent.Return<{className}>(this);\n#endif");
|
||||
messageStr.AppendLine($"\t\t}}");
|
||||
|
||||
if (parameter == "IMessage")
|
||||
{
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.Message, protocolOpCode.AMessage++);
|
||||
messageStr.AppendLine($"\t\tpublic uint OpCode() {{ return {opCodeName}.{className}; }}");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (responseTypeStr != null)
|
||||
{
|
||||
messageStr.AppendLine(protocolIgnore);
|
||||
messageStr.AppendLine($"\t\tpublic {responseTypeStr} ResponseType {{ get; set; }}");
|
||||
responseTypeStr = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (parameter.Contains("RouteRequest"))
|
||||
{
|
||||
Log.Error($"{opcodeInfo.Name} 没指定ResponseType");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasOpCode)
|
||||
{
|
||||
messageStr.AppendLine($"\t\tpublic uint OpCode() {{ return {opCodeName}.{className}; }}");
|
||||
}
|
||||
|
||||
if (customRouteType != null)
|
||||
{
|
||||
messageStr.AppendLine(protocolIgnore);
|
||||
messageStr.AppendLine($"\t\tpublic int RouteType => {customRouteType};");
|
||||
customRouteType = null;
|
||||
}
|
||||
|
||||
switch (parameter)
|
||||
{
|
||||
case "IRequest":
|
||||
{
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.Request, protocolOpCode.ARequest++);
|
||||
break;
|
||||
}
|
||||
case "IResponse":
|
||||
{
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.Response, protocolOpCode.AResponse++);
|
||||
if (!string.IsNullOrEmpty(protocolMember))
|
||||
{
|
||||
errorCodeStr.AppendLine($"\t\t[{protocolMember}(ErrorCodeKeyIndex)]");
|
||||
}
|
||||
errorCodeStr.AppendLine("\t\tpublic uint ErrorCode { get; set; }");
|
||||
disposeStr.AppendLine($"\t\t\tErrorCode = default;");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
switch (parameter)
|
||||
{
|
||||
case "IAddressableRouteMessage":
|
||||
{
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.AddressableMessage, protocolOpCode.AAddressableMessage++);
|
||||
break;
|
||||
}
|
||||
case "IAddressableRouteRequest":
|
||||
{
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.AddressableRequest, protocolOpCode.AAddressableRequest++);
|
||||
break;
|
||||
}
|
||||
case "IAddressableRouteResponse":
|
||||
{
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.AddressableResponse, protocolOpCode.AAddressableResponse++);
|
||||
if (!string.IsNullOrEmpty(protocolMember))
|
||||
{
|
||||
errorCodeStr.AppendLine($"\t\t[{protocolMember}(ErrorCodeKeyIndex)]");
|
||||
}
|
||||
errorCodeStr.AppendLine("\t\tpublic uint ErrorCode { get; set; }");
|
||||
disposeStr.AppendLine($"\t\t\tErrorCode = default;");
|
||||
break;
|
||||
}
|
||||
case "ICustomRouteMessage":
|
||||
{
|
||||
if (opCodeType == NetworkProtocolOpCodeType.Inner)
|
||||
{
|
||||
throw new NotSupportedException("Under Inner, /// does not support the ICustomRouteMessage!");
|
||||
}
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.CustomRouteMessage, protocolOpCode.ACustomRouteMessage++);
|
||||
break;
|
||||
}
|
||||
case "ICustomRouteRequest":
|
||||
{
|
||||
if (opCodeType == NetworkProtocolOpCodeType.Inner)
|
||||
{
|
||||
throw new NotSupportedException("Under Inner, /// does not support the ICustomRouteMessage!");
|
||||
}
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.CustomRouteRequest, protocolOpCode.ACustomRouteRequest++);
|
||||
break;
|
||||
}
|
||||
case "ICustomRouteResponse":
|
||||
{
|
||||
if (opCodeType == NetworkProtocolOpCodeType.Inner)
|
||||
{
|
||||
throw new NotSupportedException("Under Inner, /// does not support the ICustomRouteMessage!");
|
||||
}
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.CustomRouteResponse, protocolOpCode.ACustomRouteResponse++);
|
||||
if (!string.IsNullOrEmpty(protocolMember))
|
||||
{
|
||||
errorCodeStr.AppendLine($"\t\t[{protocolMember}(ErrorCodeKeyIndex)]");
|
||||
}
|
||||
errorCodeStr.AppendLine("\t\tpublic uint ErrorCode { get; set; }");
|
||||
disposeStr.AppendLine($"\t\t\tErrorCode = default;");
|
||||
break;
|
||||
}
|
||||
case "IRoamingMessage":
|
||||
{
|
||||
// if (opCodeType == NetworkProtocolOpCodeType.Inner)
|
||||
// {
|
||||
// throw new NotSupportedException("Under Inner, /// does not support the IRoamingMessage!");
|
||||
// }
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.RoamingMessage, protocolOpCode.ARoamingMessage++);
|
||||
break;
|
||||
}
|
||||
case "IRoamingRequest":
|
||||
{
|
||||
// if (opCodeType == NetworkProtocolOpCodeType.Inner)
|
||||
// {
|
||||
// throw new NotSupportedException("Under Inner, /// does not support the IRoamingRequest!");
|
||||
// }
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.RoamingRequest, protocolOpCode.ARoamingRequest++);
|
||||
break;
|
||||
}
|
||||
case "IRoamingResponse":
|
||||
{
|
||||
// if (opCodeType == NetworkProtocolOpCodeType.Inner)
|
||||
// {
|
||||
// throw new NotSupportedException("Under Inner, /// does not support the IRoamingResponse!");
|
||||
// }
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.RoamingResponse, protocolOpCode.ARoamingResponse++);
|
||||
if (!string.IsNullOrEmpty(protocolMember))
|
||||
{
|
||||
errorCodeStr.AppendLine($"\t\t[{protocolMember}(ErrorCodeKeyIndex)]");
|
||||
}
|
||||
errorCodeStr.AppendLine("\t\tpublic uint ErrorCode { get; set; }");
|
||||
disposeStr.AppendLine($"\t\t\tErrorCode = default;");
|
||||
break;
|
||||
}
|
||||
case "IRouteMessage":
|
||||
{
|
||||
if (opCodeType == NetworkProtocolOpCodeType.Outer)
|
||||
{
|
||||
throw new NotSupportedException("Under Inner, /// does not support the ICustomRouteMessage!");
|
||||
}
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.RouteMessage, protocolOpCode.ARouteMessage++);
|
||||
break;
|
||||
}
|
||||
case "IRouteRequest":
|
||||
{
|
||||
if (opCodeType == NetworkProtocolOpCodeType.Outer)
|
||||
{
|
||||
throw new NotSupportedException("Under Inner, /// does not support the ICustomRouteMessage!");
|
||||
}
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.RouteRequest, protocolOpCode.ARouteRequest++);
|
||||
break;
|
||||
}
|
||||
case "IRouteResponse":
|
||||
{
|
||||
if (opCodeType == NetworkProtocolOpCodeType.Outer)
|
||||
{
|
||||
throw new NotSupportedException("Under Inner, /// does not support the ICustomRouteMessage!");
|
||||
}
|
||||
opcodeInfo.Code = OpCode.Create(protocolOpCodeType, protocolOpCode.RouteResponse, protocolOpCode.ARouteResponse++);
|
||||
if (!string.IsNullOrEmpty(protocolMember))
|
||||
{
|
||||
errorCodeStr.AppendLine($"\t\t[{protocolMember}(ErrorCodeKeyIndex)]");
|
||||
}
|
||||
errorCodeStr.AppendLine("\t\tpublic uint ErrorCode { get; set; }");
|
||||
disposeStr.AppendLine($"\t\t\tErrorCode = default;");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasOpCode)
|
||||
{
|
||||
_opcodes.Add(opcodeInfo);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
case "}":
|
||||
{
|
||||
isMsgHead = false;
|
||||
errorCodeStr = errorCodeStr.Replace("ErrorCodeKeyIndex", keyIndex.ToString());
|
||||
messageStr = messageStr.Replace("<<<<Dispose>>>", disposeStr.ToString());
|
||||
messageStr.Append(errorCodeStr);
|
||||
messageStr.AppendLine("\t}");
|
||||
file.Append(messageStr);
|
||||
messageStr.Clear();
|
||||
disposeStr.Clear();
|
||||
errorCodeStr.Clear();
|
||||
keyIndex = 1;
|
||||
protocolType = "\t[ProtoContract]";
|
||||
protocolIgnore = "\t\t[ProtoIgnore]";
|
||||
protocolMember = "ProtoMember";
|
||||
protocolOpCodeType = OpCodeProtocolType.ProtoBuf;
|
||||
continue;
|
||||
}
|
||||
case "":
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentLine.StartsWith("//"))
|
||||
{
|
||||
messageStr.AppendFormat("\t\t///<summary>\r\n" + "\t\t/// {0}\r\n" + "\t\t///</summary>\r\n", currentLine.TrimStart('/', '/'));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentLine.StartsWith("repeated"))
|
||||
{
|
||||
Repeated(messageStr, disposeStr, currentLine, protocolMember, ref keyIndex);
|
||||
}
|
||||
else
|
||||
{
|
||||
Members(messageStr, disposeStr, currentLine, protocolMember, ref keyIndex);
|
||||
}
|
||||
}
|
||||
|
||||
var namespaceBuilder = new StringBuilder();
|
||||
|
||||
foreach (var @namespace in usingNamespace)
|
||||
{
|
||||
namespaceBuilder.Append($"using {@namespace};\n");
|
||||
}
|
||||
|
||||
var csName = $"{Path.GetFileNameWithoutExtension(filePath)}.cs";
|
||||
foreach (var (directory, template) in saveDirectory)
|
||||
{
|
||||
var csFile = Path.Combine(directory, csName);
|
||||
var content = template.Replace("(Content)", file.ToString());
|
||||
content = content.Replace("(UsingNamespace)", namespaceBuilder.ToString());
|
||||
await File.WriteAllTextAsync(csFile, content);
|
||||
}
|
||||
file.Clear();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GenerateOpCode
|
||||
|
||||
file.Clear();
|
||||
file.AppendLine("namespace Fantasy");
|
||||
file.AppendLine("{");
|
||||
file.AppendLine($"\tpublic static partial class {opCodeName}");
|
||||
file.AppendLine("\t{");
|
||||
|
||||
foreach (var opcode in _opcodes)
|
||||
{
|
||||
file.AppendLine($"\t\t public const uint {opcode.Name} = {opcode.Code};");
|
||||
}
|
||||
|
||||
_opcodes.Clear();
|
||||
file.AppendLine("\t}");
|
||||
file.AppendLine("}");
|
||||
|
||||
foreach (var (directory, _) in saveDirectory)
|
||||
{
|
||||
var csFile = Path.Combine(directory, $"{opCodeName}.cs");
|
||||
await File.WriteAllTextAsync(csFile, file.ToString());
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
private void Repeated(StringBuilder file, StringBuilder disposeStr, string newline, string protocolMember, ref int keyIndex)
|
||||
{
|
||||
try
|
||||
{
|
||||
var index = newline.IndexOf(";", StringComparison.Ordinal);
|
||||
newline = newline.Remove(index);
|
||||
var property = newline.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries);
|
||||
var type = property[1];
|
||||
var name = property[2];
|
||||
// var memberIndex = int.Parse(property[4]);
|
||||
type = ConvertType(type);
|
||||
|
||||
file.AppendLine($"\t\t[{protocolMember}({keyIndex++})]");
|
||||
file.AppendLine($"\t\tpublic List<{type}> {name} = new List<{type}>();");
|
||||
disposeStr.AppendLine($"\t\t\t{name}.Clear();");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error($"{newline}\n {e}");
|
||||
}
|
||||
}
|
||||
|
||||
private void Members(StringBuilder file, StringBuilder disposeStr, string currentLine, string protocolMember, ref int keyIndex)
|
||||
{
|
||||
try
|
||||
{
|
||||
var index = currentLine.IndexOf(";", StringComparison.Ordinal);
|
||||
currentLine = currentLine.Remove(index);
|
||||
var property = currentLine.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries);
|
||||
var type = property[0];
|
||||
var name = property[1];
|
||||
// var memberIndex = int.Parse(property[3]);
|
||||
var typeCs = ConvertType(type);
|
||||
if (protocolMember != null)
|
||||
{
|
||||
file.AppendLine($"\t\t[{protocolMember}({keyIndex++})]");
|
||||
}
|
||||
file.AppendLine($"\t\tpublic {typeCs} {name} {{ get; set; }}");
|
||||
disposeStr.AppendLine($"\t\t\t{name} = default;");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error($"{currentLine}\n {e}");
|
||||
}
|
||||
}
|
||||
|
||||
private string ConvertType(string type)
|
||||
{
|
||||
return type switch
|
||||
{
|
||||
"int[]" => "int[] { }",
|
||||
"int32[]" => "int[] { }",
|
||||
"int64[]" => "long[] { }",
|
||||
"int32" => "int",
|
||||
"uint32" => "uint",
|
||||
"int64" => "long",
|
||||
"uint64" => "ulong",
|
||||
_ => type
|
||||
};
|
||||
}
|
||||
|
||||
private async Task RoamingType()
|
||||
{
|
||||
var routeTypeFile = $"{_networkProtocolDirectory}RoamingType.Config";
|
||||
var protoFileText = "";
|
||||
if (!File.Exists(routeTypeFile))
|
||||
{
|
||||
protoFileText = "// Roaming协议定义(需要定义10000以上、因为10000以内的框架预留)\n";
|
||||
await File.WriteAllTextAsync(routeTypeFile, protoFileText);
|
||||
}
|
||||
else
|
||||
{
|
||||
protoFileText = await File.ReadAllTextAsync(routeTypeFile);
|
||||
}
|
||||
|
||||
var roamingTypes = new HashSet<int>();
|
||||
var roamingTypeFileSb = new StringBuilder();
|
||||
roamingTypeFileSb.AppendLine("using System.Collections.Generic;");
|
||||
roamingTypeFileSb.AppendLine("namespace Fantasy\n{");
|
||||
roamingTypeFileSb.AppendLine("\t// Roaming协议定义(需要定义10000以上、因为10000以内的框架预留)\t");
|
||||
roamingTypeFileSb.AppendLine("\tpublic static class RoamingType\n\t{");
|
||||
|
||||
foreach (var line in protoFileText.Split('\n'))
|
||||
{
|
||||
var currentLine = line.Trim();
|
||||
|
||||
if (currentLine == "" || currentLine.StartsWith("//"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var splits = currentLine.Split(["//"], StringSplitOptions.RemoveEmptyEntries);
|
||||
var routeTypeStr = splits[0].Split("=", StringSplitOptions.RemoveEmptyEntries);
|
||||
var roamingType = routeTypeStr[1].Trim();
|
||||
roamingTypes.Add(int.Parse(roamingType));
|
||||
roamingTypeFileSb.Append($"\t\tpublic const int {routeTypeStr[0].Trim()} = {roamingType};");
|
||||
|
||||
if (splits.Length > 1)
|
||||
{
|
||||
roamingTypeFileSb.Append($" // {splits[1].Trim()}\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
roamingTypeFileSb.Append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
if (roamingTypes.Count > 0)
|
||||
{
|
||||
roamingTypeFileSb.AppendLine("\t\tpublic static IEnumerable<int> RoamingTypes");
|
||||
roamingTypeFileSb.AppendLine("\t\t{\n\t\t\tget\n\t\t\t{");
|
||||
foreach (var roamingType in roamingTypes)
|
||||
{
|
||||
roamingTypeFileSb.AppendLine($"\t\t\t\tyield return {roamingType};");
|
||||
}
|
||||
roamingTypeFileSb.AppendLine("\t\t\t}\n\t\t}");
|
||||
}
|
||||
|
||||
|
||||
roamingTypeFileSb.AppendLine("\t}\n}");
|
||||
var file = roamingTypeFileSb.ToString();
|
||||
|
||||
if (ExporterAges.Instance.ExportPlatform.HasFlag(ExportPlatform.Server))
|
||||
{
|
||||
await File.WriteAllTextAsync($"{_networkProtocolServerDirectory}RoamingType.cs", file);
|
||||
}
|
||||
|
||||
if (ExporterAges.Instance.ExportPlatform.HasFlag(ExportPlatform.Client))
|
||||
{
|
||||
await File.WriteAllTextAsync($"{_networkProtocolClientDirectory}RoamingType.cs", file);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RouteType()
|
||||
{
|
||||
var routeTypeFile = $"{_networkProtocolDirectory}RouteType.Config";
|
||||
var protoFileText = "";
|
||||
if (!File.Exists(routeTypeFile))
|
||||
{
|
||||
protoFileText = "// Route协议定义(需要定义1000以上、因为1000以内的框架预留)\n";
|
||||
await File.WriteAllTextAsync(routeTypeFile, protoFileText);
|
||||
}
|
||||
else
|
||||
{
|
||||
protoFileText = await File.ReadAllTextAsync(routeTypeFile);
|
||||
}
|
||||
var routeTypeFileSb = new StringBuilder();
|
||||
routeTypeFileSb.AppendLine("namespace Fantasy\n{");
|
||||
routeTypeFileSb.AppendLine("\t// Route协议定义(需要定义1000以上、因为1000以内的框架预留)\t");
|
||||
routeTypeFileSb.AppendLine("\tpublic static class RouteType\n\t{");
|
||||
|
||||
foreach (var line in protoFileText.Split('\n'))
|
||||
{
|
||||
var currentLine = line.Trim();
|
||||
|
||||
if (currentLine.StartsWith("//"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var splits = currentLine.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
|
||||
var routeTypeStr = splits[0].Split("=", StringSplitOptions.RemoveEmptyEntries);
|
||||
routeTypeFileSb.Append($"\t\tpublic const int {routeTypeStr[0].Trim()} = {routeTypeStr[1].Trim()};");
|
||||
|
||||
if (splits.Length > 1)
|
||||
{
|
||||
routeTypeFileSb.Append($" // {splits[1].Trim()}\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
routeTypeFileSb.Append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
routeTypeFileSb.AppendLine("\t}\n}");
|
||||
var file = routeTypeFileSb.ToString();
|
||||
|
||||
if (ExporterAges.Instance.ExportPlatform.HasFlag(ExportPlatform.Server))
|
||||
{
|
||||
await File.WriteAllTextAsync($"{_networkProtocolServerDirectory}RouteType.cs", file);
|
||||
}
|
||||
|
||||
if (ExporterAges.Instance.ExportPlatform.HasFlag(ExportPlatform.Client))
|
||||
{
|
||||
await File.WriteAllTextAsync($"{_networkProtocolClientDirectory}RouteType.cs", file);
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadTemplate()
|
||||
{
|
||||
string[] lines = NetworkProtocolTemplate.Template.Split(["\r\n", "\n"], StringSplitOptions.None);
|
||||
|
||||
StringBuilder serverSb = new StringBuilder();
|
||||
StringBuilder clientSb = new StringBuilder();
|
||||
|
||||
int flag = 0;
|
||||
foreach (string line in lines)
|
||||
{
|
||||
string trim = line.Trim();
|
||||
|
||||
if (trim.StartsWith("#if") && trim.Contains("SERVER"))
|
||||
{
|
||||
flag = 1;
|
||||
continue;
|
||||
}
|
||||
else if (trim.StartsWith("#else"))
|
||||
{
|
||||
flag = 2;
|
||||
continue;
|
||||
}
|
||||
else if (trim.StartsWith($"#endif"))
|
||||
{
|
||||
flag = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (flag)
|
||||
{
|
||||
case 1: // 服务端
|
||||
{
|
||||
serverSb.AppendLine(line);
|
||||
break;
|
||||
}
|
||||
case 2: // 客户端
|
||||
{
|
||||
clientSb.AppendLine(line);
|
||||
break;
|
||||
}
|
||||
default: // 双端
|
||||
{
|
||||
serverSb.AppendLine(line);
|
||||
clientSb.AppendLine(line);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_serverTemplate = serverSb.Replace("(NetworkProtocol)", "ProtoBuf").ToString();
|
||||
_clientTemplate = clientSb.Replace("(NetworkProtocol)", "ProtoBuf").ToString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace Fantasy.Tools.ProtocalExporter;
|
||||
|
||||
public class ProtocolOpCode
|
||||
{
|
||||
private const int Start = 10001;
|
||||
|
||||
public uint Message;
|
||||
public uint Request;
|
||||
public uint Response;
|
||||
public uint RouteMessage;
|
||||
public uint RouteRequest;
|
||||
public uint RouteResponse;
|
||||
public uint AddressableMessage;
|
||||
public uint AddressableRequest;
|
||||
public uint AddressableResponse;
|
||||
public uint CustomRouteMessage;
|
||||
public uint CustomRouteRequest;
|
||||
public uint CustomRouteResponse;
|
||||
public uint RoamingMessage;
|
||||
public uint RoamingRequest;
|
||||
public uint RoamingResponse;
|
||||
|
||||
public uint AMessage = Start;
|
||||
public uint ARequest = Start;
|
||||
public uint AResponse = Start;
|
||||
public uint ARouteMessage = Start;
|
||||
public uint ARouteRequest = Start;
|
||||
public uint ARouteResponse = Start;
|
||||
public uint AAddressableMessage = Start;
|
||||
public uint AAddressableRequest = Start;
|
||||
public uint AAddressableResponse = Start;
|
||||
public uint ACustomRouteMessage = Start;
|
||||
public uint ACustomRouteRequest = Start;
|
||||
public uint ACustomRouteResponse = Start;
|
||||
public uint ARoamingMessage = Start;
|
||||
public uint ARoamingRequest = Start;
|
||||
public uint ARoamingResponse = Start;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using CommandLine;
|
||||
|
||||
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
|
||||
namespace Fantasy.Tools;
|
||||
|
||||
public class ExporterAges
|
||||
{
|
||||
public static ExporterAges Instance;
|
||||
/// <summary>
|
||||
/// 导出目标平台枚举,用于标识导出到哪个平台
|
||||
/// </summary>
|
||||
[Option('p',"ExportPlatform", Required = false, Default = ExportPlatform.None, HelpText = "Export target platform:\n/// Client target platform \nClient = 1\n/// Server target platform\nServer = 2\n/// Client and Server target platform\nAll = 3")]
|
||||
public ExportPlatform ExportPlatform { get; set; }
|
||||
|
||||
[Option('f',"Folder", Required = false, HelpText = "ExporterSetting.json file path")]
|
||||
public string Folder { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"Export": {
|
||||
"NetworkProtocolDirectory": {
|
||||
"Value": "../../../Examples/Config/NetworkProtocol/",
|
||||
"Comment": "ProtoBuf文件所在的文件夹位置"
|
||||
},
|
||||
"NetworkProtocolServerDirectory": {
|
||||
"Value": "../../../Examples/Server/Entity/Generate/NetworkProtocol/",
|
||||
"Comment": "ProtoBuf生成到服务端的文件夹位置"
|
||||
},
|
||||
"NetworkProtocolClientDirectory": {
|
||||
"Value": "../../../Examples/Client/Unity/Assets/Scripts/Hotfix/Generate/NetworkProtocol/",
|
||||
"Comment": "ProtoBuf生成到客户端的文件夹位置"
|
||||
},
|
||||
"Serializes": {
|
||||
"Value": [
|
||||
// {
|
||||
// "KeyIndex": 0,
|
||||
// "NameSpace" : "MemoryPack",
|
||||
// "SerializeName": "MemoryPack",
|
||||
// "Attribute": "\t[MemoryPackable]",
|
||||
// "Ignore": "\t\t[MemoryPackIgnore]",
|
||||
// "Member": "MemoryPackOrder"
|
||||
// }
|
||||
],
|
||||
"Comment": "自定义序列化器"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Fantasy.Exporter;
|
||||
using Fantasy.Helper;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
#pragma warning disable CS8601 // Possible null reference assignment.
|
||||
#pragma warning disable CS8604 // Possible null reference argument.
|
||||
|
||||
namespace Fantasy.Tools.ProtocalExporter;
|
||||
|
||||
public class ExporterSettingsHelper
|
||||
{
|
||||
public static string? NetworkProtocolDirectory { get; private set; }
|
||||
public static string NetworkProtocolServerDirectory { get; private set; }
|
||||
public static string NetworkProtocolClientDirectory { get; private set; }
|
||||
public static Dictionary<string, CustomSerialize> CustomSerializes { get; private set; }
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
const string settingsName = "ExporterSettings.json";
|
||||
var currentDirectory = ExporterAges.Instance.Folder;
|
||||
if (string.IsNullOrEmpty(currentDirectory))
|
||||
{
|
||||
currentDirectory = Directory.GetCurrentDirectory();
|
||||
}
|
||||
|
||||
if (!File.Exists(Path.Combine(currentDirectory, settingsName)))
|
||||
{
|
||||
throw new FileNotFoundException($"not found {settingsName} in OutputDirectory");
|
||||
}
|
||||
|
||||
var root = new ConfigurationBuilder().SetBasePath(currentDirectory).AddJsonFile(settingsName).Build();
|
||||
|
||||
NetworkProtocolDirectory = FileHelper.GetFullPath(root["Export:NetworkProtocolDirectory:Value"], currentDirectory);
|
||||
NetworkProtocolServerDirectory = FileHelper.GetFullPath(root["Export:NetworkProtocolServerDirectory:Value"], currentDirectory);
|
||||
NetworkProtocolClientDirectory = FileHelper.GetFullPath(root["Export:NetworkProtocolClientDirectory:Value"], currentDirectory);
|
||||
|
||||
CustomSerializes = [];
|
||||
var sort = new SortedList<long, CustomSerialize>();
|
||||
var arrayOfValuesSection = root.GetSection("Export:Serializes:Value");
|
||||
|
||||
foreach (var item in arrayOfValuesSection.GetChildren())
|
||||
{
|
||||
var serializeItem = new CustomSerialize
|
||||
{
|
||||
KeyIndex = Convert.ToInt32(item.GetSection("KeyIndex").Value),
|
||||
NameSpace = item.GetSection("NameSpace").Value,
|
||||
SerializeName = item.GetSection("SerializeName").Value,
|
||||
Attribute = item.GetSection("Attribute").Value,
|
||||
Ignore = item.GetSection("Ignore").Value,
|
||||
Member = item.GetSection("Member").Value
|
||||
};
|
||||
|
||||
sort.Add(HashCodeHelper.ComputeHash64(serializeItem.SerializeName), serializeItem);
|
||||
}
|
||||
|
||||
for (var i = 0; i < sort.Count; i++)
|
||||
{
|
||||
var customSerialize = sort.GetValueAtIndex(i);
|
||||
customSerialize.OpCodeType = (uint)(i + 2);
|
||||
CustomSerializes.Add(customSerialize.SerializeName, customSerialize);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>default</LangVersion>
|
||||
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<OutputPath>../../Exporter/NetworkProtocol/</OutputPath>
|
||||
<DefineConstants>TRACE;FANTASY_NET</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<OutputPath>../../Exporter/NetworkProtocol/</OutputPath>
|
||||
<DefineConstants>TRACE;FANTASY_NET</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CommandLineParser" Version="2.9.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.6" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Helper\FileHelper.cs">
|
||||
<Link>Core\FileHelper.cs</Link>
|
||||
</Compile>
|
||||
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Helper\HashCodeHelper.cs">
|
||||
<Link>Core\HashCodeHelper.cs</Link>
|
||||
</Compile>
|
||||
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Helper\JsonHelper.cs">
|
||||
<Link>Core\JsonHelper.cs</Link>
|
||||
</Compile>
|
||||
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Network\Message\PacketParser\OpCode.cs">
|
||||
<Link>ProtocalExporter\OpCode.cs</Link>
|
||||
</Compile>
|
||||
<Compile Update="ExporterSettingsHelper.cs">
|
||||
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="ExporterSettings.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Run.bat">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Run.sh">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
28
Tools/SourceCode/Fantasy.Tools.NetworkProtocol/Program.cs
Normal file
28
Tools/SourceCode/Fantasy.Tools.NetworkProtocol/Program.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using System.Text;
|
||||
using CommandLine;
|
||||
using Fantasy.Exporter;
|
||||
using Fantasy.Tools;
|
||||
using Fantasy.Tools.ProtocalExporter;
|
||||
// 解析命令行参数
|
||||
Parser.Default.ParseArguments<ExporterAges>(Environment.GetCommandLineArgs())
|
||||
.WithNotParsed(error => throw new Exception("Command line format error!"))
|
||||
.WithParsed(ages => ExporterAges.Instance = ages);
|
||||
try
|
||||
{
|
||||
// 初始化配置
|
||||
ExporterSettingsHelper.Initialize();
|
||||
// 加载配置
|
||||
Console.OutputEncoding = Encoding.UTF8;
|
||||
// 运行导出协议的代码
|
||||
new ProtocolExporter().Run();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error(e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Log.Info("按任意键退出程序");
|
||||
Console.ReadKey();
|
||||
Environment.Exit(0);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"Fantasy.Tools.NetworkProtocol": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {},
|
||||
"commandLineArgs": "--ExportPlatform 3"
|
||||
}
|
||||
}
|
||||
}
|
||||
21
Tools/SourceCode/Fantasy.Tools.NetworkProtocol/Run.bat
Normal file
21
Tools/SourceCode/Fantasy.Tools.NetworkProtocol/Run.bat
Normal file
@@ -0,0 +1,21 @@
|
||||
@echo off
|
||||
|
||||
echo Please select an option:
|
||||
echo 1. Client
|
||||
echo 2. Server
|
||||
echo 3. All
|
||||
|
||||
set /p choice=Please select an option:
|
||||
|
||||
if "%choice%"=="1" (
|
||||
echo Client
|
||||
dotnet Fantasy.Tools.NetworkProtocol.dll --p 1
|
||||
) else if "%choice%"=="2" (
|
||||
echo Server
|
||||
dotnet Fantasy.Tools.NetworkProtocol.dll --p 2
|
||||
) else if "%choice%"=="3" (
|
||||
echo All
|
||||
dotnet Fantasy.Tools.NetworkProtocol.dll --p 3
|
||||
) else (
|
||||
echo Invalid option
|
||||
)
|
||||
24
Tools/SourceCode/Fantasy.Tools.NetworkProtocol/Run.sh
Normal file
24
Tools/SourceCode/Fantasy.Tools.NetworkProtocol/Run.sh
Normal file
@@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "1. Client"
|
||||
echo "2. Server"
|
||||
echo "3. All"
|
||||
|
||||
read -n 1 -p "Please select an option:" choice
|
||||
echo ""
|
||||
echo ""
|
||||
script_dir=$(cd $(dirname $0) && pwd)
|
||||
case $choice in
|
||||
1)
|
||||
dotnet $script_dir/Fantasy.Tools.NetworkProtocol.dll --p 1 --f $script_dir
|
||||
;;
|
||||
2)
|
||||
dotnet $script_dir/Fantasy.Tools.NetworkProtocol.dll --p 2 --f $script_dir
|
||||
;;
|
||||
3)
|
||||
dotnet $script_dir/Fantasy.Tools.NetworkProtocol.dll --p 3 --f $script_dir
|
||||
;;
|
||||
*)
|
||||
echo "Invalid option"
|
||||
;;
|
||||
esac
|
||||
Reference in New Issue
Block a user