binding_generator.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. #!python
  2. import json
  3. # comment.
  4. classes = []
  5. def generate_bindings(path):
  6. global classes
  7. classes = json.load(open(path))
  8. icalls = set()
  9. for c in classes:
  10. # print c['name']
  11. used_classes = get_used_classes(c)
  12. header = generate_class_header(used_classes, c)
  13. impl = generate_class_implementation(icalls, used_classes, c)
  14. header_file = open("include/" + strip_name(c["name"]) + ".hpp", "w+")
  15. header_file.write(header)
  16. source_file = open("src/" + strip_name(c["name"]) + ".cpp", "w+")
  17. source_file.write(impl)
  18. icall_header_file = open("src/__icalls.hpp", "w+")
  19. icall_header_file.write(generate_icall_header(icalls))
  20. icall_source_file = open("src/__icalls.cpp", "w+")
  21. icall_source_file.write(generate_icall_implementation(icalls))
  22. def is_reference_type(t):
  23. for c in classes:
  24. if c['name'] != t:
  25. continue
  26. if c['is_reference']:
  27. return True
  28. return False
  29. def make_gdnative_type(t):
  30. if is_class_type(t):
  31. if is_reference_type(t):
  32. return "Ref<" + strip_name(t) + "> "
  33. else:
  34. return strip_name(t) + " *"
  35. else:
  36. return strip_name(t) + " "
  37. def generate_class_header(used_classes, c):
  38. source = []
  39. source.append("#ifndef GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  40. source.append("#define GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  41. source.append("")
  42. source.append("#if defined(_WIN32) && defined(_GD_CPP_BINDING_IMPL)")
  43. source.append("# define GD_CPP_BINDING_API __declspec(dllexport)")
  44. source.append("#elif defined(_WIN32)")
  45. source.append("# define GD_CPP_BINDING_API __declspec(dllimport)")
  46. source.append("#else")
  47. source.append("# define GD_CPP_BINDING_API")
  48. source.append("#endif");
  49. source.append("")
  50. source.append("")
  51. source.append("")
  52. source.append("")
  53. source.append("#include <godot.h>")
  54. source.append("")
  55. source.append("#include <CoreTypes.hpp>")
  56. source.append("#include <Ref.hpp>")
  57. if c["base_class"] != "":
  58. source.append("#include <" + strip_name(c["base_class"]) + ".hpp>")
  59. source.append("namespace godot {")
  60. source.append("")
  61. for used_type in used_classes:
  62. source.append("class " + strip_name(used_type) + ";")
  63. source.append("")
  64. # generate the class definition here
  65. source.append("class GD_CPP_BINDING_API " + strip_name(c["name"]) + ("" if c["base_class"] == "" else (" : public " + strip_name(c["base_class"])) ) + " {")
  66. source.append("public:")
  67. source.append("")
  68. # ___get_class_name
  69. source.append("\tstatic inline char *___get_class_name() { return (char *) \"" + strip_name(c["name"]) + "\"; }")
  70. source.append("\t// constants")
  71. for name in c["constants"]:
  72. source.append("\tconst static int " + name + " = " + str(c["constants"][name]) + ";")
  73. if c["instanciable"]:
  74. source.append("\tstatic void *operator new(size_t);")
  75. source.append("\tstatic void operator delete(void *);")
  76. source.append("")
  77. source.append("\n\t// methods")
  78. for method in c["methods"]:
  79. method_signature = ""
  80. method_signature += "static " if c["singleton"] else ""
  81. method_signature += make_gdnative_type(method["return_type"])
  82. method_signature += escape_cpp(method["name"]) + "("
  83. has_default_argument = False
  84. for i, argument in enumerate(method["arguments"]):
  85. method_signature += "const " + make_gdnative_type(argument["type"])
  86. method_signature += escape_cpp(argument["name"])
  87. # default arguments
  88. def escape_default_arg(_type, default_value):
  89. if _type == "Color":
  90. return "Color(" + default_value + ")"
  91. if _type == "bool" or _type == "int":
  92. return default_value.lower()
  93. if _type == "Array":
  94. return "Array()"
  95. if _type in ["PoolVector2Array", "PoolStringArray", "PoolVector3Array", "PoolColorArray"]:
  96. return _type + "()"
  97. if _type == "Vector2":
  98. return "Vector2" + default_value
  99. if _type == "Vector3":
  100. return "Vector3" + default_value
  101. if _type == "Transform":
  102. return "Transform()"
  103. if _type == "Transform2D":
  104. return "Transform2D()"
  105. if _type == "Rect2":
  106. return "Rect2" + default_value
  107. if _type == "Variant":
  108. return "Variant()" if default_value == "Null" else default_value
  109. if _type == "String":
  110. return "\"" + default_value + "\""
  111. if _type == "RID":
  112. return "RID()"
  113. if default_value == "Null" or default_value == "[Object:null]":
  114. return "nullptr"
  115. return default_value
  116. if argument["has_default_value"] or has_default_argument:
  117. method_signature += " = " + escape_default_arg(argument["type"], argument["default_value"])
  118. has_default_argument = True
  119. if i != len(method["arguments"]) - 1:
  120. method_signature += ", "
  121. if method["has_varargs"]:
  122. if len(method["arguments"]) > 0:
  123. method_signature += ", "
  124. method_signature += "const Array& __var_args = Array()"
  125. method_signature += ")" + (" const" if method["is_const"] and not c["singleton"] else "")
  126. source.append("\t" + method_signature + ";")
  127. source.append("};")
  128. source.append("")
  129. source.append("}")
  130. source.append("")
  131. source.append("#endif")
  132. return "\n".join(source)
  133. def generate_class_implementation(icalls, used_classes, c):
  134. source = []
  135. source.append("#include <" + strip_name(c["name"]) + ".hpp>")
  136. source.append("")
  137. source.append("")
  138. source.append("#include <CoreTypes.hpp>")
  139. source.append("#include <Ref.hpp>")
  140. source.append("#include <Godot.hpp>")
  141. source.append("")
  142. source.append("#include \"__icalls.hpp\"")
  143. source.append("")
  144. source.append("")
  145. for used_class in used_classes:
  146. source.append("#include <" + strip_name(used_class) + ".hpp>")
  147. source.append("")
  148. source.append("")
  149. source.append("namespace godot {")
  150. core_object_name = ("___static_object_" + strip_name(c["name"])) if c["singleton"] else "this"
  151. source.append("")
  152. source.append("")
  153. if c["singleton"]:
  154. source.append("static godot_object *" + core_object_name + ";")
  155. source.append("")
  156. source.append("")
  157. # FIXME Test if inlining has a huge impact on binary size
  158. source.append("static inline void ___singleton_init()")
  159. source.append("{")
  160. source.append("\tif (" + core_object_name + " == nullptr) {")
  161. source.append("\t\t" + core_object_name + " = godot_global_get_singleton(\"" + strip_name(c["name"]) + "\");")
  162. source.append("\t}")
  163. source.append("}")
  164. source.append("")
  165. source.append("")
  166. if c["instanciable"]:
  167. source.append("void *" + strip_name(c["name"]) + "::operator new(size_t)")
  168. source.append("{")
  169. source.append("\treturn godot_get_class_constructor(\"" + c["name"] + "\")();")
  170. source.append("}")
  171. source.append("void " + strip_name(c["name"]) + "::operator delete(void *ptr)")
  172. source.append("{")
  173. source.append("\tgodot_object_destroy((godot_object *)ptr);")
  174. source.append("}")
  175. for method in c["methods"]:
  176. method_signature = ""
  177. method_signature += make_gdnative_type(method["return_type"])
  178. method_signature += strip_name(c["name"]) + "::" + escape_cpp(method["name"]) + "("
  179. for i, argument in enumerate(method["arguments"]):
  180. method_signature += "const " + make_gdnative_type(argument["type"])
  181. method_signature += escape_cpp(argument["name"])
  182. if i != len(method["arguments"]) - 1:
  183. method_signature += ", "
  184. if method["has_varargs"]:
  185. if len(method["arguments"]) > 0:
  186. method_signature += ", "
  187. method_signature += "const Array& __var_args"
  188. method_signature += ")" + (" const" if method["is_const"] and not c["singleton"] else "")
  189. source.append(method_signature + " {")
  190. if c["singleton"]:
  191. source.append("\t___singleton_init();")
  192. source.append("\tstatic godot_method_bind *mb = NULL;")
  193. source.append("\tif (mb == NULL) {")
  194. source.append("\t\tmb = godot_method_bind_get_method(\"" + c["name"] +"\", \"" + method["name"] + "\");")
  195. source.append("\t}")
  196. return_statement = ""
  197. if method["return_type"] != "void":
  198. if is_class_type(method["return_type"]):
  199. if is_reference_type(method["return_type"]):
  200. return_statement += "return Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor(";
  201. else:
  202. return_statement += "return " + ("(" + strip_name(method["return_type"]) + " *) " if is_class_type(method["return_type"]) else "")
  203. else:
  204. return_statement += "return "
  205. def get_icall_type_name(name):
  206. if is_class_type(name):
  207. return "Object"
  208. return name
  209. if method["has_varargs"]:
  210. if len(method["arguments"]) != 0:
  211. source.append("\tVariant __given_args[" + str(len(method["arguments"])) + "];")
  212. for i, argument in enumerate(method["arguments"]):
  213. source.append("\tgodot_variant_new_nil((godot_variant *) &__given_args[" + str(i) + "]);")
  214. source.append("")
  215. for i, argument in enumerate(method["arguments"]):
  216. source.append("\t__given_args[" + str(i) + "] = " + escape_cpp(argument["name"]) + ";")
  217. source.append("")
  218. size = ""
  219. if method["has_varargs"]:
  220. size = "(__var_args.size() + " + str(len(method["arguments"])) + ")"
  221. else:
  222. size = "(" + str(len(method["arguments"])) + ")"
  223. source.append("\tgodot_variant **__args = (godot_variant **) alloca(sizeof(godot_variant *) * " + size + ");")
  224. source.append("")
  225. for i, argument in enumerate(method["arguments"]):
  226. source.append("\t__args[" + str(i) + "] = (godot_variant *) &__given_args[" + str(i) + "];")
  227. source.append("")
  228. if method["has_varargs"]:
  229. source.append("\tfor (int i = 0; i < __var_args.size(); i++) {")
  230. source.append("\t\t__args[i + " + str(len(method["arguments"])) + "] = (godot_variant *) &((Array &) __var_args)[i];")
  231. source.append("\t}")
  232. source.append("")
  233. source.append("\tVariant __result;")
  234. source.append("\t*(godot_variant *) &__result = godot_method_bind_call(mb, (godot_object *) " + core_object_name + ", (const godot_variant **) __args, " + size + ", nullptr);")
  235. source.append("")
  236. for i, argument in enumerate(method["arguments"]):
  237. source.append("\tgodot_variant_destroy((godot_variant *) &__given_args[" + str(i) + "]);")
  238. source.append("")
  239. if method["return_type"] != "void":
  240. cast = ""
  241. if is_class_type(method["return_type"]):
  242. if is_reference_type(method["return_type"]):
  243. cast += "Ref<" + stip_name(method["return_type"]) + ">::__internal_constructor(__result);"
  244. else:
  245. cast += "(" + strip_name(method["return_type"]) + " *) (Object *) __result;"
  246. else:
  247. cast += "__result;"
  248. source.append("\treturn " + cast)
  249. else:
  250. args = []
  251. for arg in method["arguments"]:
  252. args.append(get_icall_type_name(arg["type"]))
  253. icall_ret_type = get_icall_type_name(method["return_type"])
  254. icall_sig = tuple((icall_ret_type, tuple(args)))
  255. icalls.add(icall_sig)
  256. icall_name = get_icall_name(icall_sig)
  257. return_statement += icall_name + "(mb, (godot_object *) " + core_object_name
  258. for arg in method["arguments"]:
  259. return_statement += ", " + escape_cpp(arg["name"]) + (".ptr()" if is_reference_type(arg["type"]) else "")
  260. return_statement += ")"
  261. source.append("\t" + return_statement + (")" if is_reference_type(method["return_type"]) else "") + ";")
  262. source.append("}")
  263. source.append("")
  264. source.append("}")
  265. return "\n".join(source)
  266. def generate_icall_header(icalls):
  267. source = []
  268. source.append("#ifndef GODOT_CPP__ICALLS_HPP")
  269. source.append("#define GODOT_CPP__ICALLS_HPP")
  270. source.append("")
  271. source.append("#include <godot.h>")
  272. source.append("")
  273. source.append("")
  274. source.append("#include <CoreTypes.hpp>")
  275. source.append("#include <Object.hpp>")
  276. source.append("")
  277. source.append("")
  278. source.append("namespace godot {")
  279. source.append("")
  280. for icall in icalls:
  281. ret_type = icall[0]
  282. args = icall[1]
  283. method_signature = ""
  284. method_signature += return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, godot_object *inst"
  285. for arg in args:
  286. method_signature += ", const "
  287. if is_core_type(arg):
  288. method_signature += arg + "&"
  289. elif is_primitive(arg):
  290. method_signature += arg
  291. else:
  292. method_signature += "Object *"
  293. method_signature += ");"
  294. source.append(method_signature)
  295. source.append("")
  296. source.append("}")
  297. source.append("")
  298. source.append("#endif")
  299. return "\n".join(source)
  300. def generate_icall_implementation(icalls):
  301. source = []
  302. source.append("#include \"__icalls.hpp\"")
  303. source.append("")
  304. source.append("#include <godot.h>")
  305. source.append("")
  306. source.append("")
  307. source.append("#include <CoreTypes.hpp>")
  308. source.append("#include <Object.hpp>")
  309. source.append("")
  310. source.append("")
  311. source.append("namespace godot {")
  312. source.append("")
  313. for icall in icalls:
  314. ret_type = icall[0]
  315. args = icall[1]
  316. method_signature = ""
  317. method_signature += return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, godot_object *inst"
  318. for i, arg in enumerate(args):
  319. method_signature += ", const "
  320. if is_core_type(arg):
  321. method_signature += arg + "& "
  322. elif is_primitive(arg):
  323. method_signature += arg + " "
  324. else:
  325. method_signature += "Object *"
  326. method_signature += "arg" + str(i)
  327. method_signature += ")"
  328. source.append(method_signature + " {")
  329. if ret_type != "void":
  330. source.append("\t" + strip_name(ret_type) + (" *" if is_class_type(ret_type) else " ") + "ret;")
  331. if is_class_type(ret_type):
  332. source.append("\tret = nullptr;")
  333. source.append("\tconst void *args[" + ("1" if len(args) == 0 else "") + "] = {")
  334. for i, arg in enumerate(args):
  335. wrapped_argument = "\t\t"
  336. if is_primitive(arg) or is_core_type(arg):
  337. wrapped_argument += "(void *) &arg" + str(i)
  338. else:
  339. wrapped_argument += "(void *) arg" + str(i)
  340. wrapped_argument += ","
  341. source.append(wrapped_argument)
  342. source.append("\t};")
  343. source.append("")
  344. source.append("\tgodot_method_bind_ptrcall(mb, inst, args, " + ("nullptr" if ret_type == "void" else "&ret") + ");")
  345. if ret_type != "void":
  346. source.append("\treturn ret;")
  347. source.append("}")
  348. source.append("}")
  349. source.append("")
  350. return "\n".join(source)
  351. def return_type(t):
  352. if is_class_type(t):
  353. return "Object *"
  354. return t + " "
  355. def get_icall_name(sig):
  356. ret_type = sig[0]
  357. args = sig[1]
  358. name = "___godot_icall_"
  359. name += strip_name(ret_type)
  360. for arg in args:
  361. name += "_" + strip_name(arg)
  362. return name
  363. def get_used_classes(c):
  364. classes = []
  365. for method in c["methods"]:
  366. if is_class_type(method["return_type"]) and not (method["return_type"] in classes):
  367. classes.append(method["return_type"])
  368. for arg in method["arguments"]:
  369. if is_class_type(arg["type"]) and not (arg["type"] in classes):
  370. classes.append(arg["type"])
  371. return classes
  372. def strip_name(name):
  373. if name[0] == '_':
  374. return name[1:]
  375. return name
  376. def is_class_type(name):
  377. return not is_core_type(name) and not is_primitive(name)
  378. def is_core_type(name):
  379. core_types = ["Array",
  380. "Basis",
  381. "Color",
  382. "Dictionary",
  383. "Error",
  384. "NodePath",
  385. "Plane",
  386. "PoolByteArray",
  387. "PoolIntArray",
  388. "PoolRealArray",
  389. "PoolStringArray",
  390. "PoolVector2Array",
  391. "PoolVector3Array",
  392. "PoolColorArray",
  393. "Quat",
  394. "Rect2",
  395. "Rect3",
  396. "RID",
  397. "String",
  398. "Transform",
  399. "Transform2D",
  400. "Variant",
  401. "Vector2",
  402. "Vector3"]
  403. return name in core_types
  404. def is_primitive(name):
  405. core_types = ["int", "bool", "real", "float", "void"]
  406. return name in core_types
  407. def escape_cpp(name):
  408. escapes = {
  409. "class": "_class",
  410. "char": "_char",
  411. "short": "_short",
  412. "bool": "_bool",
  413. "int": "_int",
  414. "default": "_default",
  415. "case": "_case",
  416. "switch": "_switch",
  417. "export": "_export",
  418. "template": "_template",
  419. "new": "new_"
  420. }
  421. if name in escapes:
  422. return escapes[name]
  423. return name