Proto2CS.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using Microsoft.Extensions.Primitives;
  6. namespace ET
  7. {
  8. internal class OpcodeInfo
  9. {
  10. public string Name;
  11. public int Opcode;
  12. }
  13. public static class Proto2CS
  14. {
  15. public static void Export()
  16. {
  17. // InnerMessage.proto生成cs代码
  18. InnerProto2CS.Proto2CS();
  19. Log.Console("proto2cs succeed!");
  20. }
  21. }
  22. public static class InnerProto2CS
  23. {
  24. private const string protoDir = "../Unity/Assets/Config/Proto";
  25. private const string clientMessagePath = "../Unity/Assets/Scripts/Codes/Model/Generate/Client/Message/";
  26. private const string serverMessagePath = "../Unity/Assets/Scripts/Codes/Model/Generate/Server/Message/";
  27. private const string clientServerMessagePath = "../Unity/Assets/Scripts/Codes/Model/Generate/ClientServer/Message/";
  28. private static readonly char[] splitChars = { ' ', '\t' };
  29. private static readonly List<OpcodeInfo> msgOpcode = new List<OpcodeInfo>();
  30. public static void Proto2CS()
  31. {
  32. msgOpcode.Clear();
  33. if (Directory.Exists(clientMessagePath))
  34. {
  35. Directory.Delete(clientMessagePath, true);
  36. }
  37. if (Directory.Exists(serverMessagePath))
  38. {
  39. Directory.Delete(serverMessagePath, true);
  40. }
  41. if (Directory.Exists(clientServerMessagePath))
  42. {
  43. Directory.Delete(clientServerMessagePath, true);
  44. }
  45. List<string> list = FileHelper.GetAllFiles(protoDir, "*proto");
  46. foreach (string s in list)
  47. {
  48. if (!s.EndsWith(".proto"))
  49. {
  50. continue;
  51. }
  52. string fileName = Path.GetFileNameWithoutExtension(s);
  53. string[] ss2 = fileName.Split('_');
  54. string protoName = ss2[0];
  55. string cs = ss2[1];
  56. int startOpcode = int.Parse(ss2[2]);
  57. ProtoFile2CS(fileName, protoName, cs, startOpcode);
  58. }
  59. }
  60. public static void ProtoFile2CS(string fileName, string protoName, string cs, int startOpcode)
  61. {
  62. string ns = "ET";
  63. msgOpcode.Clear();
  64. string proto = Path.Combine(protoDir, $"{fileName}.proto");
  65. string s = File.ReadAllText(proto);
  66. StringBuilder sb = new StringBuilder();
  67. sb.Append("using ET;\n");
  68. sb.Append("using MemoryPack;\n");
  69. sb.Append("using System.Collections.Generic;\n");
  70. sb.Append($"namespace {ns}\n");
  71. sb.Append("{\n");
  72. bool isMsgStart = false;
  73. string msgName = "";
  74. StringBuilder sbDispose = new StringBuilder();
  75. foreach (string line in s.Split('\n'))
  76. {
  77. string newline = line.Trim();
  78. if (newline == "")
  79. {
  80. continue;
  81. }
  82. if (newline.StartsWith("//ResponseType"))
  83. {
  84. string responseType = line.Split(" ")[1].TrimEnd('\r', '\n');
  85. sb.Append($"\t[ResponseType(nameof({responseType}))]\n");
  86. continue;
  87. }
  88. if (newline.StartsWith("//"))
  89. {
  90. sb.Append($"{newline}\n");
  91. continue;
  92. }
  93. if (newline.StartsWith("message"))
  94. {
  95. string parentClass = "";
  96. isMsgStart = true;
  97. msgName = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries)[1];
  98. string[] ss = newline.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
  99. if (ss.Length == 2)
  100. {
  101. parentClass = ss[1].Trim();
  102. }
  103. msgOpcode.Add(new OpcodeInfo() { Name = msgName, Opcode = ++startOpcode });
  104. sb.Append($"\t[Message({protoName}.{msgName})]\n");
  105. sb.Append($"\t[MemoryPackable]\n");
  106. sb.Append($"\tpublic partial class {msgName}: MessageObject");
  107. if (parentClass == "IActorMessage" || parentClass == "IActorRequest" || parentClass == "IActorResponse")
  108. {
  109. sb.Append($", {parentClass}\n");
  110. }
  111. else if (parentClass != "")
  112. {
  113. sb.Append($", {parentClass}\n");
  114. }
  115. else
  116. {
  117. sb.Append("\n");
  118. }
  119. continue;
  120. }
  121. if (isMsgStart)
  122. {
  123. if (newline.StartsWith("{"))
  124. {
  125. sbDispose.Clear();
  126. sb.Append("\t{\n");
  127. sb.Append($"\t\tpublic static {msgName} Create(bool isFromPool = true) \n\t\t{{ \n\t\t\treturn ObjectPool.Instance.Fetch(typeof({msgName}), isFromPool) as {msgName}; \n\t\t}}\n\n");
  128. continue;
  129. }
  130. if (newline.StartsWith("}"))
  131. {
  132. isMsgStart = false;
  133. // 加了no dispose则自己去定义dispose函数,不要自动生成
  134. if (!newline.Contains("// no dispose"))
  135. {
  136. sb.Append(
  137. $"\t\tpublic override void Dispose() \n\t\t{{\n\t\t\tif (!this.IsFromPool) return;\n\t\t\t{sbDispose.ToString()}\n\t\t\tObjectPool.Instance.Recycle(this); \n\t\t}}\n\n");
  138. }
  139. sb.Append("\t}\n\n");
  140. continue;
  141. }
  142. if (newline.Trim().StartsWith("//"))
  143. {
  144. sb.Append($"{newline}\n");
  145. continue;
  146. }
  147. if (newline.Trim() != "" && newline != "}")
  148. {
  149. if (newline.StartsWith("map<"))
  150. {
  151. Map(sb, ns, newline, sbDispose);
  152. }
  153. else if (newline.StartsWith("repeated"))
  154. {
  155. Repeated(sb, ns, newline, sbDispose);
  156. }
  157. else
  158. {
  159. Members(sb, newline, true, sbDispose);
  160. }
  161. }
  162. }
  163. }
  164. sb.Append("\tpublic static class " + protoName + "\n\t{\n");
  165. foreach (OpcodeInfo info in msgOpcode)
  166. {
  167. sb.Append($"\t\t public const ushort {info.Name} = {info.Opcode};\n");
  168. }
  169. sb.Append("\t}\n");
  170. sb.Append("}\n");
  171. if (cs.Contains("C"))
  172. {
  173. GenerateCS(sb, clientMessagePath, proto);
  174. GenerateCS(sb, serverMessagePath, proto);
  175. GenerateCS(sb, clientServerMessagePath, proto);
  176. }
  177. if (cs.Contains("S"))
  178. {
  179. GenerateCS(sb, serverMessagePath, proto);
  180. GenerateCS(sb, clientServerMessagePath, proto);
  181. }
  182. }
  183. private static void GenerateCS(StringBuilder sb, string path, string proto)
  184. {
  185. if (!Directory.Exists(path))
  186. {
  187. Directory.CreateDirectory(path);
  188. }
  189. string csPath = Path.Combine(path, Path.GetFileNameWithoutExtension(proto) + ".cs");
  190. using FileStream txt = new FileStream(csPath, FileMode.Create, FileAccess.ReadWrite);
  191. using StreamWriter sw = new StreamWriter(txt);
  192. sw.Write(sb.ToString());
  193. }
  194. private static void Map(StringBuilder sb, string ns, string newline, StringBuilder sbDispose)
  195. {
  196. int start = newline.IndexOf("<") + 1;
  197. int end = newline.IndexOf(">");
  198. string types = newline.Substring(start, end - start);
  199. string[] ss = types.Split(",");
  200. string keyType = ConvertType(ss[0].Trim());
  201. string valueType = ConvertType(ss[1].Trim());
  202. string tail = newline.Substring(end + 1);
  203. ss = tail.Trim().Replace(";", "").Split(" ");
  204. string v = ss[0];
  205. int n = int.Parse(ss[2]);
  206. sb.Append("\t\t[MongoDB.Bson.Serialization.Attributes.BsonDictionaryOptions(MongoDB.Bson.Serialization.Options.DictionaryRepresentation.ArrayOfArrays)]\n");
  207. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  208. sb.Append($"\t\tpublic Dictionary<{keyType}, {valueType}> {v} {{ get; set; }} = new();\n");
  209. sbDispose.Append($"this.{v}.Clear();\n\t\t\t");
  210. }
  211. private static void Repeated(StringBuilder sb, string ns, string newline, StringBuilder sbDispose)
  212. {
  213. try
  214. {
  215. int index = newline.IndexOf(";");
  216. newline = newline.Remove(index);
  217. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  218. string type = ss[1];
  219. type = ConvertType(type);
  220. string name = ss[2];
  221. int n = int.Parse(ss[4]);
  222. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  223. sb.Append($"\t\tpublic List<{type}> {name} {{ get; set; }} = new();\n\n");
  224. sbDispose.Append($"this.{name}.Clear();\n\t\t\t");
  225. }
  226. catch (Exception e)
  227. {
  228. Console.WriteLine($"{newline}\n {e}");
  229. }
  230. }
  231. private static string ConvertType(string type)
  232. {
  233. string typeCs = "";
  234. switch (type)
  235. {
  236. case "int16":
  237. typeCs = "short";
  238. break;
  239. case "int32":
  240. typeCs = "int";
  241. break;
  242. case "bytes":
  243. typeCs = "byte[]";
  244. break;
  245. case "uint32":
  246. typeCs = "uint";
  247. break;
  248. case "long":
  249. typeCs = "long";
  250. break;
  251. case "int64":
  252. typeCs = "long";
  253. break;
  254. case "uint64":
  255. typeCs = "ulong";
  256. break;
  257. case "uint16":
  258. typeCs = "ushort";
  259. break;
  260. default:
  261. typeCs = type;
  262. break;
  263. }
  264. return typeCs;
  265. }
  266. private static void Members(StringBuilder sb, string newline, bool isRequired, StringBuilder sbDispose)
  267. {
  268. try
  269. {
  270. int index = newline.IndexOf(";");
  271. newline = newline.Remove(index);
  272. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  273. string type = ss[0];
  274. string name = ss[1];
  275. int n = int.Parse(ss[3]);
  276. string typeCs = ConvertType(type);
  277. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  278. sb.Append($"\t\tpublic {typeCs} {name} {{ get; set; }}\n\n");
  279. switch (typeCs)
  280. {
  281. case "bytes":
  282. {
  283. break;
  284. }
  285. default:
  286. sbDispose.Append($"this.{name} = default;\n\t\t\t");
  287. break;
  288. }
  289. }
  290. catch (Exception e)
  291. {
  292. Console.WriteLine($"{newline}\n {e}");
  293. }
  294. }
  295. }
  296. }