binding_generator.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import json
  4. import os
  5. import errno
  6. from pathlib import Path
  7. # Convenience function for using template get_node
  8. def correct_method_name(method_list):
  9. for method in method_list:
  10. if method["name"] == "get_node":
  11. method["name"] = "get_node_internal"
  12. classes = []
  13. def print_file_list(api_filepath, output_dir, headers=False, sources=False):
  14. global classes
  15. end = ';'
  16. with open(api_filepath) as api_file:
  17. classes = json.load(api_file)
  18. include_gen_folder = Path(output_dir) / 'include' / 'gen'
  19. source_gen_folder = Path(output_dir) / 'src' / 'gen'
  20. for _class in classes:
  21. header_filename = include_gen_folder / (strip_name(_class["name"]) + ".hpp")
  22. source_filename = source_gen_folder / (strip_name(_class["name"]) + ".cpp")
  23. if headers:
  24. print(str(header_filename.as_posix()), end=end)
  25. if sources:
  26. print(str(source_filename.as_posix()), end=end)
  27. icall_header_filename = include_gen_folder / '__icalls.hpp'
  28. register_types_filename = source_gen_folder / '__register_types.cpp'
  29. init_method_bindings_filename = source_gen_folder / '__init_method_bindings.cpp'
  30. if headers:
  31. print(str(icall_header_filename.as_posix()), end=end)
  32. if sources:
  33. print(str(register_types_filename.as_posix()), end=end)
  34. print(str(init_method_bindings_filename.as_posix()), end=end)
  35. def generate_bindings(api_filepath, use_template_get_node, output_dir="."):
  36. global classes
  37. with open(api_filepath) as api_file:
  38. classes = json.load(api_file)
  39. icalls = set()
  40. include_gen_folder = Path(output_dir) / 'include' / 'gen'
  41. source_gen_folder = Path(output_dir) / 'src' / 'gen'
  42. try:
  43. include_gen_folder.mkdir(parents=True)
  44. except os.error as e:
  45. if e.errno == errno.EEXIST:
  46. print(str(source_gen_folder) + ": " + os.strerror(e.errno))
  47. else:
  48. exit(1)
  49. try:
  50. source_gen_folder.mkdir(parents=True)
  51. except os.error as e:
  52. if e.errno == errno.EEXIST:
  53. print(str(source_gen_folder) + ": " + os.strerror(e.errno))
  54. else:
  55. exit(1)
  56. for c in classes:
  57. # print(c['name'])
  58. used_classes = get_used_classes(c)
  59. if use_template_get_node and c["name"] == "Node":
  60. correct_method_name(c["methods"])
  61. header = generate_class_header(used_classes, c, use_template_get_node)
  62. impl = generate_class_implementation(icalls, used_classes, c, use_template_get_node)
  63. header_filename = include_gen_folder / (strip_name(c["name"]) + ".hpp")
  64. with header_filename.open("w+") as header_file:
  65. header_file.write(header)
  66. source_filename = source_gen_folder / (strip_name(c["name"]) + ".cpp")
  67. with source_filename.open("w+") as source_file:
  68. source_file.write(impl)
  69. icall_header_filename = include_gen_folder / '__icalls.hpp'
  70. with icall_header_filename.open("w+") as icall_header_file:
  71. icall_header_file.write(generate_icall_header(icalls))
  72. register_types_filename = source_gen_folder / '__register_types.cpp'
  73. with register_types_filename.open("w+") as register_types_file:
  74. register_types_file.write(generate_type_registry(classes))
  75. init_method_bindings_filename = source_gen_folder / '__init_method_bindings.cpp'
  76. with init_method_bindings_filename.open("w+") as init_method_bindings_file:
  77. init_method_bindings_file.write(generate_init_method_bindings(classes))
  78. def is_reference_type(t):
  79. for c in classes:
  80. if c['name'] != t:
  81. continue
  82. if c['is_reference']:
  83. return True
  84. return False
  85. def make_gdnative_type(t, ref_allowed):
  86. if is_enum(t):
  87. return remove_enum_prefix(t) + " "
  88. elif is_class_type(t):
  89. if is_reference_type(t) and ref_allowed:
  90. return "Ref<" + strip_name(t) + "> "
  91. else:
  92. return strip_name(t) + " *"
  93. else:
  94. if t == "int":
  95. return "int64_t "
  96. if t == "float" or t == "real":
  97. return "real_t "
  98. return strip_name(t) + " "
  99. def generate_class_header(used_classes, c, use_template_get_node):
  100. source = []
  101. source.append("#ifndef GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  102. source.append("#define GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  103. source.append("")
  104. source.append("")
  105. source.append("#include <gdnative_api_struct.gen.h>")
  106. source.append("#include <cstdint>")
  107. source.append("")
  108. source.append("#include <core/CoreTypes.hpp>")
  109. class_name = strip_name(c["name"])
  110. # Ref<T> is not included in object.h in Godot either,
  111. # so don't include it here because it's not needed
  112. if class_name != "Object" and class_name != "Reference":
  113. source.append("#include <core/Ref.hpp>")
  114. ref_allowed = True
  115. else:
  116. source.append("#include <core/TagDB.hpp>")
  117. ref_allowed = False
  118. included = []
  119. for used_class in used_classes:
  120. if is_enum(used_class) and is_nested_type(used_class):
  121. used_class_name = remove_enum_prefix(extract_nested_type(used_class))
  122. if used_class_name not in included:
  123. included.append(used_class_name)
  124. source.append("#include \"" + used_class_name + ".hpp\"")
  125. elif is_enum(used_class) and is_nested_type(used_class) and not is_nested_type(used_class, class_name):
  126. used_class_name = remove_enum_prefix(used_class)
  127. if used_class_name not in included:
  128. included.append(used_class_name)
  129. source.append("#include \"" + used_class_name + ".hpp\"")
  130. source.append("")
  131. if c["base_class"] != "":
  132. source.append("#include \"" + strip_name(c["base_class"]) + ".hpp\"")
  133. source.append("namespace godot {")
  134. source.append("")
  135. for used_type in used_classes:
  136. if is_enum(used_type) or is_nested_type(used_type, class_name):
  137. continue
  138. else:
  139. source.append("class " + strip_name(used_type) + ";")
  140. source.append("")
  141. vararg_templates = ""
  142. # generate the class definition here
  143. source.append("class " + class_name + (" : public _Wrapped" if c["base_class"] == "" else (" : public " + strip_name(c["base_class"])) ) + " {")
  144. if c["base_class"] == "":
  145. source.append("public: enum { ___CLASS_IS_SCRIPT = 0, };")
  146. source.append("")
  147. source.append("private:")
  148. if c["singleton"]:
  149. source.append("\tstatic " + class_name + " *_singleton;")
  150. source.append("")
  151. source.append("\t" + class_name + "();")
  152. source.append("")
  153. # Generate method table
  154. source.append("\tstruct ___method_bindings {")
  155. for method in c["methods"]:
  156. source.append("\t\tgodot_method_bind *mb_" + method["name"] + ";")
  157. source.append("\t};")
  158. source.append("\tstatic ___method_bindings ___mb;")
  159. source.append("\tstatic void *_detail_class_tag;")
  160. source.append("")
  161. source.append("public:")
  162. source.append("\tstatic void ___init_method_bindings();")
  163. # class id from core engine for casting
  164. source.append("\tinline static size_t ___get_id() { return (size_t)_detail_class_tag; }")
  165. source.append("")
  166. if c["singleton"]:
  167. source.append("\tstatic inline " + class_name + " *get_singleton()")
  168. source.append("\t{")
  169. source.append("\t\tif (!" + class_name + "::_singleton) {")
  170. source.append("\t\t\t" + class_name + "::_singleton = new " + class_name + ";")
  171. source.append("\t\t}")
  172. source.append("\t\treturn " + class_name + "::_singleton;")
  173. source.append("\t}")
  174. source.append("")
  175. # godot::api->godot_global_get_singleton((char *) \"" + strip_name(c["name"]) + "\");"
  176. # class name:
  177. # Two versions needed needed because when the user implements a custom class,
  178. # we want to override `___get_class_name` while `___get_godot_class_name` can keep returning the base name
  179. source.append("\tstatic inline const char *___get_class_name() { return (const char *) \"" + strip_name(c["name"]) + "\"; }")
  180. source.append("\tstatic inline const char *___get_godot_class_name() { return (const char *) \"" + strip_name(c["name"]) + "\"; }")
  181. source.append("\tstatic inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }")
  182. enum_values = []
  183. source.append("\n\t// enums")
  184. for enum in c["enums"]:
  185. source.append("\tenum " + strip_name(enum["name"]) + " {")
  186. for value in enum["values"]:
  187. source.append("\t\t" + remove_nested_type_prefix(value) + " = " + str(enum["values"][value]) + ",")
  188. enum_values.append(value)
  189. source.append("\t};")
  190. source.append("\n\t// constants")
  191. for name in c["constants"]:
  192. if name not in enum_values:
  193. source.append("\tconst static int " + name + " = " + str(c["constants"][name]) + ";")
  194. if c["instanciable"]:
  195. source.append("")
  196. source.append("")
  197. source.append("\tstatic " + class_name + " *_new();")
  198. source.append("\n\t// methods")
  199. if class_name == "Object":
  200. source.append("#ifndef GODOT_CPP_NO_OBJECT_CAST")
  201. source.append("\ttemplate<class T>")
  202. source.append("\tstatic T *cast_to(const Object *obj);")
  203. source.append("#endif")
  204. source.append("")
  205. for method in c["methods"]:
  206. method_signature = ""
  207. # TODO decide what to do about virtual methods
  208. # method_signature += "virtual " if method["is_virtual"] else ""
  209. method_signature += make_gdnative_type(method["return_type"], ref_allowed)
  210. method_name = escape_cpp(method["name"])
  211. method_signature += method_name + "("
  212. has_default_argument = False
  213. method_arguments = ""
  214. for i, argument in enumerate(method["arguments"]):
  215. method_signature += "const " + make_gdnative_type(argument["type"], ref_allowed)
  216. argument_name = escape_cpp(argument["name"])
  217. method_signature += argument_name
  218. method_arguments += argument_name
  219. # default arguments
  220. def escape_default_arg(_type, default_value):
  221. if _type == "Color":
  222. return "Color(" + default_value + ")"
  223. if _type == "bool" or _type == "int":
  224. return default_value.lower()
  225. if _type == "Array":
  226. return "Array()"
  227. if _type in ["PoolVector2Array", "PoolStringArray", "PoolVector3Array", "PoolColorArray", "PoolIntArray", "PoolRealArray", "PoolByteArray"]:
  228. return _type + "()"
  229. if _type == "Vector2":
  230. return "Vector2" + default_value
  231. if _type == "Vector3":
  232. return "Vector3" + default_value
  233. if _type == "Transform":
  234. return "Transform()"
  235. if _type == "Transform2D":
  236. return "Transform2D()"
  237. if _type == "Rect2":
  238. return "Rect2" + default_value
  239. if _type == "Variant":
  240. return "Variant()" if default_value == "Null" else default_value
  241. if _type == "String" or _type == "NodePath":
  242. return "\"" + default_value + "\""
  243. if _type == "RID":
  244. return "RID()"
  245. if default_value == "Null" or default_value == "[Object:null]":
  246. return "nullptr"
  247. return default_value
  248. if argument["has_default_value"] or has_default_argument:
  249. method_signature += " = " + escape_default_arg(argument["type"], argument["default_value"])
  250. has_default_argument = True
  251. if i != len(method["arguments"]) - 1:
  252. method_signature += ", "
  253. method_arguments += ","
  254. if method["has_varargs"]:
  255. if len(method["arguments"]) > 0:
  256. method_signature += ", "
  257. method_arguments += ", "
  258. vararg_templates += "\ttemplate <class... Args> " + method_signature + "Args... args){\n\t\treturn " + method_name + "(" + method_arguments + "Array::make(args...));\n\t}\n"""
  259. method_signature += "const Array& __var_args = Array()"
  260. method_signature += ")" + (" const" if method["is_const"] else "")
  261. source.append("\t" + method_signature + ";")
  262. source.append(vararg_templates)
  263. if use_template_get_node and class_name == "Node":
  264. # Extra definition for template get_node that calls the renamed get_node_internal; has a default template parameter for backwards compatibility.
  265. source.append("\ttemplate <class T = Node>")
  266. source.append("\tT *get_node(const NodePath path) const {")
  267. source.append("\t\treturn Object::cast_to<T>(get_node_internal(path));")
  268. source.append("\t}")
  269. source.append("};")
  270. source.append("")
  271. # ...And a specialized version so we don't unnecessarily cast when using the default.
  272. source.append("template <>")
  273. source.append("inline Node *Node::get_node<Node>(const NodePath path) const {")
  274. source.append("\treturn get_node_internal(path);")
  275. source.append("}")
  276. source.append("")
  277. else:
  278. source.append("};")
  279. source.append("")
  280. source.append("}")
  281. source.append("")
  282. source.append("#endif")
  283. return "\n".join(source)
  284. def generate_class_implementation(icalls, used_classes, c, use_template_get_node):
  285. class_name = strip_name(c["name"])
  286. ref_allowed = class_name != "Object" and class_name != "Reference"
  287. source = []
  288. source.append("#include \"" + class_name + ".hpp\"")
  289. source.append("")
  290. source.append("")
  291. source.append("#include <core/GodotGlobal.hpp>")
  292. source.append("#include <core/CoreTypes.hpp>")
  293. source.append("#include <core/Ref.hpp>")
  294. source.append("#include <core/Godot.hpp>")
  295. source.append("")
  296. source.append("#include \"__icalls.hpp\"")
  297. source.append("")
  298. source.append("")
  299. for used_class in used_classes:
  300. if is_enum(used_class):
  301. continue
  302. else:
  303. source.append("#include \"" + strip_name(used_class) + ".hpp\"")
  304. source.append("")
  305. source.append("")
  306. source.append("namespace godot {")
  307. core_object_name = "this"
  308. source.append("")
  309. source.append("")
  310. if c["singleton"]:
  311. source.append("" + class_name + " *" + class_name + "::_singleton = NULL;")
  312. source.append("")
  313. source.append("")
  314. # FIXME Test if inlining has a huge impact on binary size
  315. source.append(class_name + "::" + class_name + "() {")
  316. source.append("\t_owner = godot::api->godot_global_get_singleton((char *) \"" + strip_name(c["name"]) + "\");")
  317. source.append("}")
  318. source.append("")
  319. source.append("")
  320. # Method table initialization
  321. source.append(class_name + "::___method_bindings " + class_name + "::___mb = {};")
  322. source.append("")
  323. source.append("void *" + class_name + "::_detail_class_tag = nullptr;")
  324. source.append("")
  325. source.append("void " + class_name + "::___init_method_bindings() {")
  326. for method in c["methods"]:
  327. source.append("\t___mb.mb_" + method["name"] + " = godot::api->godot_method_bind_get_method(\"" + c["name"] + "\", \"" + ("get_node" if use_template_get_node and method["name"] == "get_node_internal" else method["name"]) + "\");")
  328. source.append("\tgodot_string_name class_name;")
  329. source.append("\tgodot::api->godot_string_name_new_data(&class_name, \"" + c["name"] + "\");")
  330. source.append("\t_detail_class_tag = godot::core_1_2_api->godot_get_class_tag(&class_name);")
  331. source.append("\tgodot::api->godot_string_name_destroy(&class_name);")
  332. source.append("}")
  333. source.append("")
  334. if c["instanciable"]:
  335. source.append(class_name + " *" + strip_name(c["name"]) + "::_new()")
  336. source.append("{")
  337. source.append("\treturn (" + class_name + " *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)\"" + c["name"] + "\")());")
  338. source.append("}")
  339. for method in c["methods"]:
  340. method_signature = ""
  341. method_signature += make_gdnative_type(method["return_type"], ref_allowed)
  342. method_signature += strip_name(c["name"]) + "::" + escape_cpp(method["name"]) + "("
  343. for i, argument in enumerate(method["arguments"]):
  344. method_signature += "const " + make_gdnative_type(argument["type"], ref_allowed)
  345. method_signature += escape_cpp(argument["name"])
  346. if i != len(method["arguments"]) - 1:
  347. method_signature += ", "
  348. if method["has_varargs"]:
  349. if len(method["arguments"]) > 0:
  350. method_signature += ", "
  351. method_signature += "const Array& __var_args"
  352. method_signature += ")" + (" const" if method["is_const"] else "")
  353. source.append(method_signature + " {")
  354. if method["name"] == "free":
  355. # dirty hack because Object::free is marked virtual but doesn't actually exist...
  356. source.append("\tgodot::api->godot_object_destroy(_owner);")
  357. source.append("}")
  358. source.append("")
  359. continue
  360. return_statement = ""
  361. return_type_is_ref = is_reference_type(method["return_type"]) and ref_allowed
  362. if method["return_type"] != "void":
  363. if is_class_type(method["return_type"]):
  364. if is_enum(method["return_type"]):
  365. return_statement += "return (" + remove_enum_prefix(method["return_type"]) + ") "
  366. elif return_type_is_ref:
  367. return_statement += "return Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor("
  368. else:
  369. return_statement += "return " + ("(" + strip_name(method["return_type"]) + " *) " if is_class_type(method["return_type"]) else "")
  370. else:
  371. return_statement += "return "
  372. def get_icall_type_name(name):
  373. if is_enum(name):
  374. return "int"
  375. if is_class_type(name):
  376. return "Object"
  377. return name
  378. if method["has_varargs"]:
  379. if len(method["arguments"]) != 0:
  380. source.append("\tVariant __given_args[" + str(len(method["arguments"])) + "];")
  381. for i, argument in enumerate(method["arguments"]):
  382. source.append("\tgodot::api->godot_variant_new_nil((godot_variant *) &__given_args[" + str(i) + "]);")
  383. source.append("")
  384. for i, argument in enumerate(method["arguments"]):
  385. source.append("\t__given_args[" + str(i) + "] = " + escape_cpp(argument["name"]) + ";")
  386. source.append("")
  387. size = ""
  388. if method["has_varargs"]:
  389. size = "(__var_args.size() + " + str(len(method["arguments"])) + ")"
  390. else:
  391. size = "(" + str(len(method["arguments"])) + ")"
  392. source.append("\tgodot_variant **__args = (godot_variant **) alloca(sizeof(godot_variant *) * " + size + ");")
  393. source.append("")
  394. for i, argument in enumerate(method["arguments"]):
  395. source.append("\t__args[" + str(i) + "] = (godot_variant *) &__given_args[" + str(i) + "];")
  396. source.append("")
  397. if method["has_varargs"]:
  398. source.append("\tfor (int i = 0; i < __var_args.size(); i++) {")
  399. source.append("\t\t__args[i + " + str(len(method["arguments"])) + "] = (godot_variant *) &((Array &) __var_args)[i];")
  400. source.append("\t}")
  401. source.append("")
  402. source.append("\tVariant __result;")
  403. source.append("\t*(godot_variant *) &__result = godot::api->godot_method_bind_call(___mb.mb_" + method["name"] + ", ((const Object *) " + core_object_name + ")->_owner, (const godot_variant **) __args, " + size + ", nullptr);")
  404. source.append("")
  405. if is_class_type(method["return_type"]):
  406. source.append("\tObject *obj = Object::___get_from_variant(__result);")
  407. source.append("\tif (obj->has_method(\"reference\"))")
  408. source.append("\t\tobj->callv(\"reference\", Array());")
  409. source.append("")
  410. for i, argument in enumerate(method["arguments"]):
  411. source.append("\tgodot::api->godot_variant_destroy((godot_variant *) &__given_args[" + str(i) + "]);")
  412. source.append("")
  413. if method["return_type"] != "void":
  414. cast = ""
  415. if is_class_type(method["return_type"]):
  416. if return_type_is_ref:
  417. cast += "Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor(__result);"
  418. else:
  419. cast += "(" + strip_name(method["return_type"]) + " *) " + strip_name(method["return_type"] + "::___get_from_variant(") + "__result);"
  420. else:
  421. cast += "__result;"
  422. source.append("\treturn " + cast)
  423. else:
  424. args = []
  425. for arg in method["arguments"]:
  426. args.append(get_icall_type_name(arg["type"]))
  427. icall_ret_type = get_icall_type_name(method["return_type"])
  428. icall_sig = tuple((icall_ret_type, tuple(args)))
  429. icalls.add(icall_sig)
  430. icall_name = get_icall_name(icall_sig)
  431. return_statement += icall_name + "(___mb.mb_" + method["name"] + ", (const Object *) " + core_object_name
  432. for arg in method["arguments"]:
  433. arg_is_ref = is_reference_type(arg["type"]) and ref_allowed
  434. return_statement += ", " + escape_cpp(arg["name"]) + (".ptr()" if arg_is_ref else "")
  435. return_statement += ")"
  436. if return_type_is_ref:
  437. return_statement += ")"
  438. source.append("\t" + return_statement + ";")
  439. source.append("}")
  440. source.append("")
  441. source.append("}")
  442. return "\n".join(source)
  443. def generate_icall_header(icalls):
  444. source = []
  445. source.append("#ifndef GODOT_CPP__ICALLS_HPP")
  446. source.append("#define GODOT_CPP__ICALLS_HPP")
  447. source.append("")
  448. source.append("#include <gdnative_api_struct.gen.h>")
  449. source.append("#include <stdint.h>")
  450. source.append("")
  451. source.append("#include <core/GodotGlobal.hpp>")
  452. source.append("#include <core/CoreTypes.hpp>")
  453. source.append("#include \"Object.hpp\"")
  454. source.append("")
  455. source.append("")
  456. source.append("namespace godot {")
  457. source.append("")
  458. for icall in icalls:
  459. ret_type = icall[0]
  460. args = icall[1]
  461. method_signature = "static inline "
  462. method_signature += get_icall_return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, const Object *inst"
  463. for i, arg in enumerate(args):
  464. method_signature += ", const "
  465. if is_core_type(arg):
  466. method_signature += arg + "&"
  467. elif arg == "int":
  468. method_signature += "int64_t "
  469. elif arg == "float":
  470. method_signature += "double "
  471. elif is_primitive(arg):
  472. method_signature += arg + " "
  473. else:
  474. method_signature += "Object *"
  475. method_signature += "arg" + str(i)
  476. method_signature += ")"
  477. source.append(method_signature + " {")
  478. if ret_type != "void":
  479. source.append("\t" + ("godot_object *" if is_class_type(ret_type) else get_icall_return_type(ret_type)) + "ret;")
  480. if is_class_type(ret_type):
  481. source.append("\tret = nullptr;")
  482. source.append("\tconst void *args[" + ("1" if len(args) == 0 else "") + "] = {")
  483. for i, arg in enumerate(args):
  484. wrapped_argument = "\t\t"
  485. if is_primitive(arg) or is_core_type(arg):
  486. wrapped_argument += "(void *) &arg" + str(i)
  487. else:
  488. wrapped_argument += "(void *) (arg" + str(i) + ") ? arg" + str(i) + "->_owner : nullptr"
  489. wrapped_argument += ","
  490. source.append(wrapped_argument)
  491. source.append("\t};")
  492. source.append("")
  493. source.append("\tgodot::api->godot_method_bind_ptrcall(mb, inst->_owner, args, " + ("nullptr" if ret_type == "void" else "&ret") + ");")
  494. if ret_type != "void":
  495. if is_class_type(ret_type):
  496. source.append("\tif (ret) {")
  497. source.append("\t\treturn (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, ret);")
  498. source.append("\t}")
  499. source.append("")
  500. source.append("\treturn (Object *) ret;")
  501. else:
  502. source.append("\treturn ret;")
  503. source.append("}")
  504. source.append("")
  505. source.append("}")
  506. source.append("")
  507. source.append("#endif")
  508. return "\n".join(source)
  509. def generate_type_registry(classes):
  510. source = []
  511. source.append("#include \"TagDB.hpp\"")
  512. source.append("#include <typeinfo>")
  513. source.append("\n")
  514. for c in classes:
  515. source.append("#include <" + strip_name(c["name"]) + ".hpp>")
  516. source.append("")
  517. source.append("")
  518. source.append("namespace godot {")
  519. source.append("void ___register_types()")
  520. source.append("{")
  521. for c in classes:
  522. class_name = strip_name(c["name"])
  523. base_class_name = strip_name(c["base_class"])
  524. class_type_hash = "typeid(" + class_name + ").hash_code()"
  525. base_class_type_hash = "typeid(" + base_class_name + ").hash_code()"
  526. if base_class_name == "":
  527. base_class_type_hash = "0"
  528. source.append("\tgodot::_TagDB::register_global_type(\"" + c["name"] + "\", " + class_type_hash + ", " + base_class_type_hash + ");")
  529. source.append("}")
  530. source.append("")
  531. source.append("}")
  532. return "\n".join(source)
  533. def generate_init_method_bindings(classes):
  534. source = []
  535. for c in classes:
  536. source.append("#include <" + strip_name(c["name"]) + ".hpp>")
  537. source.append("")
  538. source.append("")
  539. source.append("namespace godot {")
  540. source.append("void ___init_method_bindings()")
  541. source.append("{")
  542. for c in classes:
  543. source.append("\t" + strip_name(c["name"]) + "::___init_method_bindings();")
  544. source.append("}")
  545. source.append("")
  546. source.append("}")
  547. return "\n".join(source)
  548. def get_icall_return_type(t):
  549. if is_class_type(t):
  550. return "Object *"
  551. if t == "int":
  552. return "int64_t "
  553. if t == "float" or t == "real":
  554. return "double "
  555. return t + " "
  556. def get_icall_name(sig):
  557. ret_type = sig[0]
  558. args = sig[1]
  559. name = "___godot_icall_"
  560. name += strip_name(ret_type)
  561. for arg in args:
  562. name += "_" + strip_name(arg)
  563. return name
  564. def get_used_classes(c):
  565. classes = []
  566. for method in c["methods"]:
  567. if is_class_type(method["return_type"]) and not (method["return_type"] in classes):
  568. classes.append(method["return_type"])
  569. for arg in method["arguments"]:
  570. if is_class_type(arg["type"]) and not (arg["type"] in classes):
  571. classes.append(arg["type"])
  572. return classes
  573. def strip_name(name):
  574. if len(name) == 0:
  575. return name
  576. if name[0] == '_':
  577. return name[1:]
  578. return name
  579. def extract_nested_type(nested_type):
  580. return strip_name(nested_type[:nested_type.find("::")])
  581. def remove_nested_type_prefix(name):
  582. return name if name.find("::") == -1 else strip_name(name[name.find("::") + 2:])
  583. def remove_enum_prefix(name):
  584. return strip_name(name[name.find("enum.") + 5:])
  585. def is_nested_type(name, type = ""):
  586. return name.find(type + "::") != -1
  587. def is_enum(name):
  588. return name.find("enum.") == 0
  589. def is_class_type(name):
  590. return not is_core_type(name) and not is_primitive(name)
  591. def is_core_type(name):
  592. core_types = ["Array",
  593. "Basis",
  594. "Color",
  595. "Dictionary",
  596. "Error",
  597. "NodePath",
  598. "Plane",
  599. "PoolByteArray",
  600. "PoolIntArray",
  601. "PoolRealArray",
  602. "PoolStringArray",
  603. "PoolVector2Array",
  604. "PoolVector3Array",
  605. "PoolColorArray",
  606. "PoolIntArray",
  607. "PoolRealArray",
  608. "Quat",
  609. "Rect2",
  610. "AABB",
  611. "RID",
  612. "String",
  613. "Transform",
  614. "Transform2D",
  615. "Variant",
  616. "Vector2",
  617. "Vector3"]
  618. return name in core_types
  619. def is_primitive(name):
  620. core_types = ["int", "bool", "real", "float", "void"]
  621. return name in core_types
  622. def escape_cpp(name):
  623. escapes = {
  624. "class": "_class",
  625. "enum": "_enum",
  626. "char": "_char",
  627. "short": "_short",
  628. "bool": "_bool",
  629. "int": "_int",
  630. "default": "_default",
  631. "case": "_case",
  632. "switch": "_switch",
  633. "export": "_export",
  634. "template": "_template",
  635. "new": "new_",
  636. "operator": "_operator",
  637. "typename": "_typename"
  638. }
  639. if name in escapes:
  640. return escapes[name]
  641. return name