binding_generator.py 22 KB

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