CSModuleWriter.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. //
  2. // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Atomic/IO/File.h>
  23. #include <Atomic/IO/FileSystem.h>
  24. #include "../JSBind.h"
  25. #include "../JSBPackage.h"
  26. #include "../JSBModule.h"
  27. #include "../JSBEnum.h"
  28. #include "../JSBClass.h"
  29. #include "../JSBFunction.h"
  30. #include "CSTypeHelper.h"
  31. #include "CSClassWriter.h"
  32. #include "CSModuleWriter.h"
  33. namespace ToolCore
  34. {
  35. CSModuleWriter::CSModuleWriter(JSBModule *module) : JSBModuleWriter(module)
  36. {
  37. }
  38. void CSModuleWriter::WriteIncludes(String& source)
  39. {
  40. Vector<String>& includes = module_->includes_;
  41. for (unsigned i = 0; i < includes.Size(); i++)
  42. {
  43. if (includes[i].StartsWith("<"))
  44. source.AppendWithFormat("#include %s\n", includes[i].CString());
  45. else
  46. source.AppendWithFormat("#include \"%s\"\n", includes[i].CString());
  47. }
  48. Vector<JSBHeader*> allheaders;
  49. HashMap<StringHash, SharedPtr<JSBEnum> >::Iterator eitr = module_->enums_.Begin();
  50. while (eitr != module_->enums_.End())
  51. {
  52. allheaders.Push(eitr->second_->GetHeader());
  53. eitr++;
  54. }
  55. HashMap<StringHash, SharedPtr<JSBClass> >::Iterator citr = module_->classes_.Begin();
  56. while (citr != module_->classes_.End())
  57. {
  58. allheaders.Push(citr->second_->GetHeader());
  59. citr++;
  60. }
  61. Vector<JSBHeader*> included;
  62. for (unsigned i = 0; i < allheaders.Size(); i++)
  63. {
  64. JSBHeader* header = allheaders.At(i);
  65. if (included.Contains(header))
  66. continue;
  67. String headerPath = GetPath(header->GetFilePath());
  68. String headerfile = GetFileNameAndExtension(header->GetFilePath());
  69. JSBind* jsbind = header->GetSubsystem<JSBind>();
  70. headerPath.Replace(jsbind->GetSourceRootFolder() + "Source/", "");
  71. source.AppendWithFormat("#include <%s%s>\n", headerPath.CString(), headerfile.CString());
  72. included.Push(header);
  73. }
  74. source += ToString("\n#include \"CSPackage%s.h\"\n", module_->GetPackage()->GetName().CString());
  75. }
  76. void CSModuleWriter::GenerateNativeSource()
  77. {
  78. String source = "// This file was autogenerated by JSBind, changes will be lost\n";
  79. source += "#ifdef ATOMIC_PLATFORM_WINDOWS\n";
  80. source += "#pragma warning(disable: 4244) // possible loss of data\n";
  81. source += "#define ATOMIC_EXPORT_API __declspec(dllexport)\n";
  82. source += "#else\n";
  83. source += "#define ATOMIC_EXPORT_API\n";
  84. source += "#endif\n";
  85. if (module_->Requires("3D"))
  86. {
  87. source += "#ifdef ATOMIC_3D\n";
  88. }
  89. WriteIncludes(source);
  90. source += "\n#include <AtomicNET/NETNative/NETCore.h>\n";
  91. String ns = module_->GetPackage()->GetNamespace();
  92. source += "\n\nusing namespace " + ns + ";\n\n";
  93. source += "\n\nextern \"C\" \n{\n \n";
  94. source += "// Begin Class Declarations\n";
  95. source += "// End Class Declarations\n\n";
  96. source += "// Begin Classes\n";
  97. Vector<SharedPtr<JSBClass>> classes = module_->classes_.Values();
  98. for (unsigned i = 0; i < classes.Size(); i++)
  99. {
  100. CSClassWriter clsWriter(classes[i]);
  101. clsWriter.GenerateNativeSource(source);
  102. }
  103. source += "// End Classes\n\n";
  104. // end Atomic namespace
  105. source += "\n}\n";
  106. if (module_->Requires("3D"))
  107. {
  108. source += "#endif //ATOMIC_3D\n";
  109. }
  110. JSBind* jsbind = module_->GetSubsystem<JSBind>();
  111. String filepath = jsbind->GetDestNativeFolder() + "/CSModule" + module_->name_ + ".cpp";
  112. File file(module_->GetContext());
  113. file.Open(filepath, FILE_WRITE);
  114. file.Write(source.CString(), source.Length());
  115. file.Close();
  116. }
  117. String CSModuleWriter::GetManagedPrimitiveType(JSBPrimitiveType* ptype)
  118. {
  119. if (ptype->kind_ == JSBPrimitiveType::Bool)
  120. return "bool";
  121. if (ptype->kind_ == JSBPrimitiveType::Int && ptype->isUnsigned_)
  122. return "uint";
  123. else if (ptype->kind_ == JSBPrimitiveType::Int)
  124. return "int";
  125. if (ptype->kind_ == JSBPrimitiveType::Float)
  126. return "float";
  127. return "int";
  128. }
  129. void CSModuleWriter::GenerateManagedClasses(String& source)
  130. {
  131. Vector<SharedPtr<JSBClass>> classes = module_->classes_.Values();
  132. for (unsigned i = 0; i < classes.Size(); i++)
  133. {
  134. JSBClass* klass = classes.At(i);
  135. if (klass->IsNumberArray())
  136. continue;
  137. CSClassWriter clsWriter(klass);
  138. clsWriter.GenerateManagedSource(source);
  139. }
  140. }
  141. void CSModuleWriter::GenerateManagedEnumsAndConstants(String& source)
  142. {
  143. Vector<SharedPtr<JSBEnum>> enums = module_->enums_.Values();
  144. Indent();
  145. for (unsigned i = 0; i < enums.Size(); i++)
  146. {
  147. JSBEnum* jenum = enums[i];
  148. source += "\n";
  149. String line = "public enum " + jenum->GetName() + "\n";
  150. source += IndentLine(line);
  151. source += IndentLine("{\n");
  152. HashMap<String, String>& values = jenum->GetValues();
  153. HashMap<String, String>::ConstIterator itr = values.Begin();
  154. Indent();
  155. while (itr != values.End())
  156. {
  157. String name = (*itr).first_;
  158. String value = (*itr).second_;
  159. // BodyType2D enum order is assigned in RigidBody2D.h in incorrect order
  160. if (jenum->GetName() == "BodyType2D")
  161. {
  162. if (name == "BT_KINEMATIC")
  163. value = "1";
  164. else if (name == "BT_DYNAMIC")
  165. value = "2";
  166. }
  167. if (value.Length())
  168. {
  169. line = name + " = " + value;
  170. }
  171. else
  172. {
  173. line = name;
  174. }
  175. itr++;
  176. if (itr != values.End())
  177. line += ",";
  178. line += "\n";
  179. source += IndentLine(line);
  180. }
  181. Dedent();
  182. source += IndentLine("}\n");
  183. }
  184. // constants
  185. HashMap<String, JSBModule::Constant>& constants = module_->GetConstants();
  186. if (constants.Size())
  187. {
  188. source += "\n";
  189. String line = "public static partial class Constants\n";
  190. source += IndentLine(line);
  191. source += IndentLine("{\n");
  192. const Vector<String>& constantsName = constants.Keys();
  193. Indent();
  194. for (unsigned i = 0; i < constantsName.Size(); i++)
  195. {
  196. const String& cname = constantsName.At(i);
  197. JSBModule::Constant& constant = constants[cname];
  198. String managedType = GetManagedPrimitiveType(constant.type);
  199. String value = constant.value;
  200. if (!value.Length())
  201. continue;
  202. //static const unsigned M_MIN_UNSIGNED = 0x00000000;
  203. // /static const unsigned M_MAX_UNSIGNED = 0xffffffff;
  204. if (cname == "M_MIN_INT")
  205. value = "int.MinValue";
  206. if (cname == "M_INFINITY")
  207. value = "float.MaxValue";
  208. if (value == "M_MAX_UNSIGNED")
  209. value = "0xffffffff";
  210. // Input stuff
  211. if (module_->GetName() == "Input")
  212. {
  213. if (cname.StartsWith("KEY_"))
  214. {
  215. if (value.Length() == 1 && (IsAlpha(value[0]) || IsDigit(value[0])))
  216. value = "'" + value + "'";
  217. }
  218. // https://raw.githubusercontent.com/flibitijibibo/SDL2-CS/master/src/SDL2.cs
  219. if (value.StartsWith("SDL_BUTTON_") || value.StartsWith("SDL_HAT_"))
  220. {
  221. value = "(int) SDL." + value;
  222. }
  223. else if (value.StartsWith("SDLK_"))
  224. {
  225. value = "(int) SDL.SDL_Keycode." + value;
  226. }
  227. else if (value.StartsWith("SDL_SCANCODE_"))
  228. {
  229. value = "(int) SDL.SDL_Scancode." + value;
  230. }
  231. else if (value.StartsWith("SDL_CONTROLLER_BUTTON_"))
  232. {
  233. value = "(int) SDL.SDL_GameControllerButton." + value;
  234. }
  235. else if (value.StartsWith("SDL_CONTROLLER_AXIS_"))
  236. {
  237. value = "(int) SDL.SDL_GameControllerAxis." + value;
  238. }
  239. }
  240. String line = "public const " + managedType + " " + cname + " = " + value;
  241. if (managedType == "float" && !line.EndsWith("f") && IsDigit(line[line.Length()-1]))
  242. line += "f";
  243. line += ";\n";
  244. source += IndentLine(line);
  245. }
  246. Dedent();
  247. source += "\n";
  248. line = "}\n";
  249. source += IndentLine(line);
  250. }
  251. source += "\n";
  252. Dedent();
  253. }
  254. void CSModuleWriter::GenerateManagedModuleClass(String& sourceOut)
  255. {
  256. Indent();
  257. String source;
  258. String line = ToString("public static partial class %sModule\n", module_->GetName().CString());
  259. source += IndentLine(line);
  260. source += IndentLine("{\n");
  261. Indent();
  262. source += IndentLine("public static void Initialize()\n");
  263. source += IndentLine("{\n");
  264. Indent();
  265. Vector<SharedPtr<JSBClass>> classes = module_->classes_.Values();
  266. for (unsigned i = 0; i < classes.Size(); i++)
  267. {
  268. JSBClass* klass = classes.At(i);
  269. JSBPackage* package = module_->GetPackage();
  270. if (klass->IsNumberArray() || klass->IsAbstract())
  271. continue;
  272. const char* className = klass->GetName().CString();
  273. line = ToString("new NativeType(%s.csb_%s_%s_GetClassIDStatic (), ", className, package->GetName().CString(), className);
  274. line += ToString("typeof(%s), (IntPtr x) => { return new %s (x); } );\n",className, className);
  275. source += IndentLine(line);
  276. }
  277. Dedent();
  278. source += IndentLine("}\n");
  279. Dedent();
  280. source += IndentLine("}\n");
  281. sourceOut += source;
  282. Dedent();
  283. }
  284. void CSModuleWriter::GenerateManagedSource()
  285. {
  286. String source = "// Autogenerated";
  287. String moduleName = module_->GetPackage()->GetNamespace();
  288. source += "\nusing System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\n";
  289. if (moduleName == "Atomic")
  290. moduleName = "AtomicEngine";
  291. if (moduleName != "AtomicEngine")
  292. {
  293. source += "using AtomicEngine;\n";
  294. }
  295. source += "\n\n";
  296. source += "namespace " + moduleName + "\n";
  297. source += "{\n";
  298. GenerateManagedEnumsAndConstants(source);
  299. GenerateManagedModuleClass(source);
  300. GenerateManagedClasses(source);
  301. source += "}\n";
  302. JSBind* jsbind = module_->GetSubsystem<JSBind>();
  303. String filepath = jsbind->GetDestScriptFolder() + "/CSModule" + module_->name_ + ".cs";
  304. File file(module_->GetContext());
  305. file.Open(filepath, FILE_WRITE);
  306. file.Write(source.CString(), source.Length());
  307. file.Close();
  308. }
  309. void CSModuleWriter::GenerateSource()
  310. {
  311. GenerateNativeSource();
  312. GenerateManagedSource();
  313. }
  314. }