Proto2CS.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 = "../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 System.Collections.Generic;\n");
  69. sb.Append($"namespace {ns}\n");
  70. sb.Append("{\n");
  71. bool isMsgStart = false;
  72. foreach (string line in s.Split('\n'))
  73. {
  74. string newline = line.Trim();
  75. if (newline == "")
  76. {
  77. continue;
  78. }
  79. if (newline.StartsWith("//ResponseType"))
  80. {
  81. string responseType = line.Split(" ")[1].TrimEnd('\r', '\n');
  82. sb.Append($"\t[ResponseType(nameof({responseType}))]\n");
  83. continue;
  84. }
  85. if (newline.StartsWith("//"))
  86. {
  87. sb.Append($"{newline}\n");
  88. continue;
  89. }
  90. if (newline.StartsWith("message"))
  91. {
  92. string parentClass = "";
  93. isMsgStart = true;
  94. string msgName = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries)[1];
  95. string[] ss = newline.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
  96. if (ss.Length == 2)
  97. {
  98. parentClass = ss[1].Trim();
  99. }
  100. msgOpcode.Add(new OpcodeInfo() { Name = msgName, Opcode = ++startOpcode });
  101. sb.Append($"\t[Message({protoName}.{msgName})]\n");
  102. sb.Append($"\t[ProtoContract]\n");
  103. sb.Append($"\tpublic partial class {msgName}: ProtoObject");
  104. if (parentClass == "IActorMessage" || parentClass == "IActorRequest" || parentClass == "IActorResponse")
  105. {
  106. sb.Append($", {parentClass}\n");
  107. }
  108. else if (parentClass != "")
  109. {
  110. sb.Append($", {parentClass}\n");
  111. }
  112. else
  113. {
  114. sb.Append("\n");
  115. }
  116. continue;
  117. }
  118. if (isMsgStart)
  119. {
  120. if (newline == "{")
  121. {
  122. sb.Append("\t{\n");
  123. continue;
  124. }
  125. if (newline == "}")
  126. {
  127. isMsgStart = false;
  128. sb.Append("\t}\n\n");
  129. continue;
  130. }
  131. if (newline.Trim().StartsWith("//"))
  132. {
  133. sb.Append($"{newline}\n");
  134. continue;
  135. }
  136. if (newline.Trim() != "" && newline != "}")
  137. {
  138. if (newline.StartsWith("map<"))
  139. {
  140. Map(sb, ns, newline);
  141. }
  142. else if (newline.StartsWith("repeated"))
  143. {
  144. Repeated(sb, ns, newline);
  145. }
  146. else
  147. {
  148. Members(sb, newline, true);
  149. }
  150. }
  151. }
  152. }
  153. sb.Append("\tpublic static class " + protoName + "\n\t{\n");
  154. foreach (OpcodeInfo info in msgOpcode)
  155. {
  156. sb.Append($"\t\t public const ushort {info.Name} = {info.Opcode};\n");
  157. }
  158. sb.Append("\t}\n");
  159. sb.Append("}\n");
  160. if (cs.Contains("C"))
  161. {
  162. GenerateCS(sb, clientMessagePath, proto);
  163. GenerateCS(sb, serverMessagePath, proto);
  164. GenerateCS(sb, clientServerMessagePath, proto);
  165. }
  166. if (cs.Contains("S"))
  167. {
  168. GenerateCS(sb, serverMessagePath, proto);
  169. GenerateCS(sb, clientServerMessagePath, proto);
  170. }
  171. }
  172. private static void GenerateCS(StringBuilder sb, string path, string proto)
  173. {
  174. if (!Directory.Exists(path))
  175. {
  176. Directory.CreateDirectory(path);
  177. }
  178. string csPath = Path.Combine(path, Path.GetFileNameWithoutExtension(proto) + ".cs");
  179. using FileStream txt = new FileStream(csPath, FileMode.Create, FileAccess.ReadWrite);
  180. using StreamWriter sw = new StreamWriter(txt);
  181. sw.Write(sb.ToString());
  182. }
  183. private static void Map(StringBuilder sb, string ns, string newline)
  184. {
  185. int start = newline.IndexOf("<") + 1;
  186. int end = newline.IndexOf(">");
  187. string types = newline.Substring(start, end - start);
  188. string[] ss = types.Split(",");
  189. string keyType = ConvertType(ss[0].Trim());
  190. string valueType = ConvertType(ss[1].Trim());
  191. string tail = newline.Substring(end + 1);
  192. ss = tail.Trim().Replace(";", "").Split(" ");
  193. string v = ss[0];
  194. string n = ss[2];
  195. sb.Append("\t\t[MongoDB.Bson.Serialization.Attributes.BsonDictionaryOptions(MongoDB.Bson.Serialization.Options.DictionaryRepresentation.ArrayOfArrays)]\n");
  196. sb.Append($"\t\t[ProtoMember({n})]\n");
  197. sb.Append($"\t\tpublic Dictionary<{keyType}, {valueType}> {v} {{ get; set; }}\n");
  198. }
  199. private static void Repeated(StringBuilder sb, string ns, string newline)
  200. {
  201. try
  202. {
  203. int index = newline.IndexOf(";");
  204. newline = newline.Remove(index);
  205. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  206. string type = ss[1];
  207. type = ConvertType(type);
  208. string name = ss[2];
  209. int n = int.Parse(ss[4]);
  210. sb.Append($"\t\t[ProtoMember({n})]\n");
  211. sb.Append($"\t\tpublic List<{type}> {name} {{ get; set; }}\n\n");
  212. }
  213. catch (Exception e)
  214. {
  215. Console.WriteLine($"{newline}\n {e}");
  216. }
  217. }
  218. private static string ConvertType(string type)
  219. {
  220. string typeCs = "";
  221. switch (type)
  222. {
  223. case "int16":
  224. typeCs = "short";
  225. break;
  226. case "int32":
  227. typeCs = "int";
  228. break;
  229. case "bytes":
  230. typeCs = "byte[]";
  231. break;
  232. case "uint32":
  233. typeCs = "uint";
  234. break;
  235. case "long":
  236. typeCs = "long";
  237. break;
  238. case "int64":
  239. typeCs = "long";
  240. break;
  241. case "uint64":
  242. typeCs = "ulong";
  243. break;
  244. case "uint16":
  245. typeCs = "ushort";
  246. break;
  247. default:
  248. typeCs = type;
  249. break;
  250. }
  251. return typeCs;
  252. }
  253. private static void Members(StringBuilder sb, string newline, bool isRequired)
  254. {
  255. try
  256. {
  257. int index = newline.IndexOf(";");
  258. newline = newline.Remove(index);
  259. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  260. string type = ss[0];
  261. string name = ss[1];
  262. int n = int.Parse(ss[3]);
  263. string typeCs = ConvertType(type);
  264. sb.Append($"\t\t[ProtoMember({n})]\n");
  265. sb.Append($"\t\tpublic {typeCs} {name} {{ get; set; }}\n\n");
  266. }
  267. catch (Exception e)
  268. {
  269. Console.WriteLine($"{newline}\n {e}");
  270. }
  271. }
  272. }
  273. }