Proto2CS.cs 10 KB

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