binding_generator.py 19 KB

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