binding_generator.py 27 KB

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