Proto2CS.cs 11 KB

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