binding_generator.py 22 KB

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