Proto2CS.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  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. InnerProto2CS.Proto2CS();
  18. }
  19. }
  20. public static partial class InnerProto2CS
  21. {
  22. private const string clientMessagePath = "../Generate/Client/Proto/";
  23. private const string serverMessagePath = "../Generate/Server/Proto/";
  24. private const string clientServerMessagePath = "../Generate/ClientServer/Proto/";
  25. private static readonly char[] splitChars = [' ', '\t'];
  26. private static readonly List<OpcodeInfo> msgOpcode = [];
  27. public static void Proto2CS()
  28. {
  29. msgOpcode.Clear();
  30. if (!Directory.Exists(clientMessagePath))
  31. {
  32. Directory.CreateDirectory(clientMessagePath);
  33. }
  34. if (!Directory.Exists(serverMessagePath))
  35. {
  36. Directory.CreateDirectory(serverMessagePath);
  37. }
  38. if (!Directory.Exists(clientServerMessagePath))
  39. {
  40. Directory.CreateDirectory(clientServerMessagePath);
  41. }
  42. RemoveAllFilesExceptMeta(clientMessagePath);
  43. RemoveAllFilesExceptMeta(serverMessagePath);
  44. RemoveAllFilesExceptMeta(clientServerMessagePath);
  45. List<string> list = new List<string>();
  46. foreach (string directory in Directory.GetDirectories("../Unity/Packages", "com.et.*"))
  47. {
  48. string p = Path.Combine(directory, "Proto");
  49. if (!Directory.Exists(p))
  50. {
  51. continue;
  52. }
  53. list.Add(p);
  54. }
  55. foreach (string directory in Directory.GetDirectories("../Unity/Library/PackageCache", "com.et.*"))
  56. {
  57. string p = Path.Combine(directory, "Proto");
  58. if (!Directory.Exists(p))
  59. {
  60. continue;
  61. }
  62. list.Add(p);
  63. }
  64. List<string> protoList = new List<string>();
  65. foreach (string s in list)
  66. {
  67. protoList.AddRange(FileHelper.GetAllFiles(s, "*.proto"));
  68. }
  69. foreach (string s in protoList)
  70. {
  71. if (!s.EndsWith(".proto"))
  72. {
  73. continue;
  74. }
  75. string fileName = Path.GetFileNameWithoutExtension(s);
  76. string[] ss2 = fileName.Split('_');
  77. string protoName = ss2[0];
  78. string cs = ss2[1];
  79. int startOpcode = int.Parse(ss2[2]);
  80. ProtoFile2CS(s, fileName, protoName, cs, startOpcode);
  81. }
  82. RemoveUnusedMetaFiles(clientMessagePath);
  83. RemoveUnusedMetaFiles(serverMessagePath);
  84. RemoveUnusedMetaFiles(clientServerMessagePath);
  85. }
  86. private static void ProtoFile2CS(string path, string fileName, string protoName, string cs, int startOpcode)
  87. {
  88. msgOpcode.Clear();
  89. string proto = path;
  90. string s = File.ReadAllText(proto);
  91. StringBuilder sb = new();
  92. sb.Append("using MemoryPack;\n");
  93. sb.Append("using System.Collections.Generic;\n\n");
  94. sb.Append($"namespace ET\n");
  95. sb.Append("{\n");
  96. bool isMsgStart = false;
  97. string msgName = "";
  98. string responseType = "";
  99. StringBuilder sbDispose = new();
  100. Regex responseTypeRegex = ResponseTypeRegex();
  101. foreach (string line in s.Split('\n'))
  102. {
  103. string newline = line.Trim();
  104. if (string.IsNullOrEmpty(newline))
  105. {
  106. continue;
  107. }
  108. if (responseTypeRegex.IsMatch(newline))
  109. {
  110. responseType = responseTypeRegex.Replace(newline, string.Empty);
  111. responseType = responseType.Trim().Split(' ')[0].TrimEnd('\r', '\n');
  112. continue;
  113. }
  114. if (!isMsgStart && newline.StartsWith("//"))
  115. {
  116. if (newline.StartsWith("///"))
  117. {
  118. sb.Append("\t/// <summary>\n");
  119. sb.Append($"\t/// {newline.TrimStart('/', ' ')}\n");
  120. sb.Append("\t/// </summary>\n");
  121. }
  122. else
  123. {
  124. sb.Append($"\t// {newline.TrimStart('/', ' ')}\n");
  125. }
  126. continue;
  127. }
  128. if (newline.StartsWith("message"))
  129. {
  130. isMsgStart = true;
  131. string parentClass = "";
  132. msgName = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries)[1];
  133. string[] ss = newline.Split(["//"], StringSplitOptions.RemoveEmptyEntries);
  134. if (ss.Length == 2)
  135. {
  136. parentClass = ss[1].Trim();
  137. }
  138. msgOpcode.Add(new OpcodeInfo() { Name = msgName, Opcode = ++startOpcode });
  139. sb.Append($"\t[MemoryPackable]\n");
  140. sb.Append($"\t[Message({protoName}.{msgName})]\n");
  141. if (!string.IsNullOrEmpty(responseType))
  142. {
  143. sb.Append($"\t[ResponseType(nameof({responseType}))]\n");
  144. }
  145. sb.Append($"\tpublic partial class {msgName} : MessageObject");
  146. if (parentClass is "IActorMessage" or "IActorRequest" or "IActorResponse")
  147. {
  148. sb.Append($", {parentClass}\n");
  149. }
  150. else if (parentClass != "")
  151. {
  152. sb.Append($", {parentClass}\n");
  153. }
  154. else
  155. {
  156. sb.Append('\n');
  157. }
  158. continue;
  159. }
  160. if (isMsgStart)
  161. {
  162. if (newline.StartsWith('{'))
  163. {
  164. sbDispose.Clear();
  165. sb.Append("\t{\n");
  166. sb.Append($"\t\tpublic static {msgName} Create(bool isFromPool = false)\n\t\t{{\n\t\t\treturn ObjectPool.Fetch<{msgName}>(isFromPool);\n\t\t}}\n\n");
  167. continue;
  168. }
  169. if (newline.StartsWith('}'))
  170. {
  171. isMsgStart = false;
  172. responseType = "";
  173. // 加了no dispose则自己去定义dispose函数,不要自动生成
  174. if (!newline.Contains("// no dispose"))
  175. {
  176. sb.Append($"\t\tpublic override void Dispose()\n\t\t{{\n\t\t\tif (!this.IsFromPool)\n\t\t\t{{\n\t\t\t\treturn;\n\t\t\t}}\n\n\t\t\t{sbDispose.ToString().TrimEnd('\t')}\n\t\t\tObjectPool.Recycle(this);\n\t\t}}\n");
  177. }
  178. sb.Append("\t}\n\n");
  179. continue;
  180. }
  181. if (newline.StartsWith("//"))
  182. {
  183. sb.Append("\t\t/// <summary>\n");
  184. sb.Append($"\t\t/// {newline.TrimStart('/', ' ')}\n");
  185. sb.Append("\t\t/// </summary>\n");
  186. continue;
  187. }
  188. string memberStr;
  189. if (newline.Contains("//"))
  190. {
  191. string[] lineSplit = newline.Split("//");
  192. memberStr = lineSplit[0].Trim();
  193. sb.Append("\t\t/// <summary>\n");
  194. sb.Append($"\t\t/// {lineSplit[1].Trim()}\n");
  195. sb.Append("\t\t/// </summary>\n");
  196. }
  197. else
  198. {
  199. memberStr = newline;
  200. }
  201. if (memberStr.StartsWith("map<"))
  202. {
  203. Map(sb, memberStr, sbDispose);
  204. }
  205. else if (memberStr.StartsWith("repeated"))
  206. {
  207. Repeated(sb, memberStr, sbDispose);
  208. }
  209. else
  210. {
  211. Members(sb, memberStr, sbDispose);
  212. }
  213. }
  214. }
  215. sb.Append("\tpublic static class " + protoName + "\n\t{\n");
  216. foreach (OpcodeInfo info in msgOpcode)
  217. {
  218. sb.Append($"\t\tpublic const ushort {info.Name} = {info.Opcode};\n");
  219. }
  220. sb.Append("\t}\n");
  221. sb.Append('}');
  222. sb.Replace("\t", " ");
  223. string result = sb.ToString().ReplaceLineEndings("\r\n");
  224. if (cs.Contains('C'))
  225. {
  226. GenerateCS(result, clientMessagePath, proto);
  227. GenerateCS(result, serverMessagePath, proto);
  228. GenerateCS(result, clientServerMessagePath, proto);
  229. }
  230. if (cs.Contains('S'))
  231. {
  232. GenerateCS(result, serverMessagePath, proto);
  233. GenerateCS(result, clientServerMessagePath, proto);
  234. }
  235. }
  236. private static void GenerateCS(string result, string path, string proto)
  237. {
  238. if (!Directory.Exists(path))
  239. {
  240. Directory.CreateDirectory(path);
  241. }
  242. string csPath = Path.Combine(path, Path.GetFileNameWithoutExtension(proto) + ".cs");
  243. using FileStream txt = new(csPath, FileMode.Create, FileAccess.ReadWrite);
  244. using StreamWriter sw = new(txt);
  245. sw.Write(result);
  246. }
  247. private static void Map(StringBuilder sb, string newline, StringBuilder sbDispose)
  248. {
  249. int start = newline.IndexOf('<') + 1;
  250. int end = newline.IndexOf('>');
  251. string types = newline.Substring(start, end - start);
  252. string[] ss = types.Split(',');
  253. string keyType = ConvertType(ss[0].Trim());
  254. string valueType = ConvertType(ss[1].Trim());
  255. string tail = newline[(end + 1)..];
  256. ss = tail.Trim().Replace(";", "").Split(' ');
  257. string v = ss[0];
  258. int n = int.Parse(ss[2]);
  259. sb.Append("\t\t[MongoDB.Bson.Serialization.Attributes.BsonDictionaryOptions(MongoDB.Bson.Serialization.Options.DictionaryRepresentation.ArrayOfArrays)]\n");
  260. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  261. sb.Append($"\t\tpublic Dictionary<{keyType}, {valueType}> {v} {{ get; set; }} = new();\n");
  262. sbDispose.Append($"this.{v}.Clear();\n\t\t\t");
  263. }
  264. private static void Repeated(StringBuilder sb, string newline, StringBuilder sbDispose)
  265. {
  266. try
  267. {
  268. int index = newline.IndexOf(';');
  269. newline = newline.Remove(index);
  270. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  271. string type = ss[1];
  272. type = ConvertType(type);
  273. string name = ss[2];
  274. int n = int.Parse(ss[4]);
  275. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  276. sb.Append($"\t\tpublic List<{type}> {name} {{ get; set; }} = new();\n\n");
  277. sbDispose.Append($"this.{name}.Clear();\n\t\t\t");
  278. }
  279. catch (Exception e)
  280. {
  281. Console.WriteLine($"{newline}\n {e}");
  282. }
  283. }
  284. private static string ConvertType(string type)
  285. {
  286. return type switch
  287. {
  288. "int16" => "short",
  289. "int32" => "int",
  290. "bytes" => "byte[]",
  291. "uint32" => "uint",
  292. "long" => "long",
  293. "int64" => "long",
  294. "uint64" => "ulong",
  295. "uint16" => "ushort",
  296. _ => type
  297. };
  298. }
  299. private static void Members(StringBuilder sb, string newline, StringBuilder sbDispose)
  300. {
  301. try
  302. {
  303. int index = newline.IndexOf(';');
  304. newline = newline.Remove(index);
  305. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  306. string type = ss[0];
  307. string name = ss[1];
  308. int n = int.Parse(ss[3]);
  309. string typeCs = ConvertType(type);
  310. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  311. sb.Append($"\t\tpublic {typeCs} {name} {{ get; set; }}\n\n");
  312. switch (typeCs)
  313. {
  314. case "bytes":
  315. {
  316. break;
  317. }
  318. default:
  319. sbDispose.Append($"this.{name} = default;\n\t\t\t");
  320. break;
  321. }
  322. }
  323. catch (Exception e)
  324. {
  325. Console.WriteLine($"{newline}\n {e}");
  326. }
  327. }
  328. /// <summary>
  329. /// 删除meta以外的所有文件
  330. /// </summary>
  331. static void RemoveAllFilesExceptMeta(string directory)
  332. {
  333. if (!Directory.Exists(directory))
  334. {
  335. return;
  336. }
  337. DirectoryInfo targetDir = new(directory);
  338. FileInfo[] fileInfos = targetDir.GetFiles("*", SearchOption.AllDirectories);
  339. foreach (FileInfo info in fileInfos)
  340. {
  341. if (!info.Name.EndsWith(".meta"))
  342. {
  343. File.Delete(info.FullName);
  344. }
  345. }
  346. }
  347. /// <summary>
  348. /// 删除多余的meta文件
  349. /// </summary>
  350. static void RemoveUnusedMetaFiles(string directory)
  351. {
  352. if (!Directory.Exists(directory))
  353. {
  354. return;
  355. }
  356. DirectoryInfo targetDir = new(directory);
  357. FileInfo[] fileInfos = targetDir.GetFiles("*.meta", SearchOption.AllDirectories);
  358. foreach (FileInfo info in fileInfos)
  359. {
  360. string pathWithoutMeta = info.FullName.Remove(info.FullName.LastIndexOf(".meta", StringComparison.Ordinal));
  361. if (!File.Exists(pathWithoutMeta) && !Directory.Exists(pathWithoutMeta))
  362. {
  363. File.Delete(info.FullName);
  364. }
  365. }
  366. }
  367. [GeneratedRegex(@"//\s*ResponseType")]
  368. private static partial Regex ResponseTypeRegex();
  369. }
  370. }