binding_generator.py 22 KB

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