binding_generator.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  1. #!/usr/bin/env python
  2. import json
  3. import re
  4. import shutil
  5. from pathlib import Path
  6. def print_file_list(api_filepath, output_dir, headers=False, sources=False):
  7. api = {}
  8. end = ";"
  9. with open(api_filepath) as api_file:
  10. api = json.load(api_file)
  11. include_gen_folder = Path(output_dir) / "gen" / "include" / "godot_cpp"
  12. source_gen_folder = Path(output_dir) / "gen" / "src"
  13. for builtin_class in api["builtin_classes"]:
  14. if is_pod_type(builtin_class["name"]):
  15. continue
  16. if is_included_type(builtin_class["name"]):
  17. continue
  18. header_filename = include_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".hpp")
  19. source_filename = source_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".cpp")
  20. if headers:
  21. print(str(header_filename.as_posix()), end=end)
  22. if sources:
  23. print(str(source_filename.as_posix()), end=end)
  24. for engine_class in api["classes"]:
  25. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  26. if engine_class["name"] == "ClassDB":
  27. continue
  28. header_filename = include_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".hpp")
  29. source_filename = source_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".cpp")
  30. if headers:
  31. print(str(header_filename.as_posix()), end=end)
  32. if sources:
  33. print(str(source_filename.as_posix()), end=end)
  34. utility_functions_header_path = include_gen_folder / "variant" / "utility_functions.hpp"
  35. utility_functions_source_path = source_gen_folder / "variant" / "utility_functions.cpp"
  36. global_constants_header_path = include_gen_folder / "classes" / "global_constants.hpp"
  37. if headers:
  38. print(str(utility_functions_header_path.as_posix()), end=end)
  39. print(str(global_constants_header_path.as_posix()), end=end)
  40. if sources:
  41. print(str(utility_functions_source_path.as_posix()), end=end)
  42. def generate_bindings(api_filepath, use_template_get_node, output_dir="."):
  43. api = None
  44. target_dir = Path(output_dir) / "gen"
  45. with open(api_filepath) as api_file:
  46. api = json.load(api_file)
  47. shutil.rmtree(target_dir, ignore_errors=True)
  48. target_dir.mkdir(parents=True)
  49. generate_global_constants(api, target_dir)
  50. generate_builtin_bindings(api, target_dir, "float_64")
  51. generate_engine_classes_bindings(api, target_dir, use_template_get_node)
  52. generate_utility_functions(api, target_dir)
  53. builtin_classes = []
  54. # Key is class name, value is boolean where True means the class is refcounted.
  55. engine_classes = {}
  56. singletons = []
  57. def generate_builtin_bindings(api, output_dir, build_config):
  58. global builtin_classes
  59. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  60. source_gen_folder = Path(output_dir) / "src" / "variant"
  61. include_gen_folder.mkdir(parents=True, exist_ok=True)
  62. source_gen_folder.mkdir(parents=True, exist_ok=True)
  63. # Store types beforehand.
  64. for builtin_api in api["builtin_classes"]:
  65. if is_pod_type(builtin_api["name"]):
  66. continue
  67. builtin_classes.append(builtin_api["name"])
  68. builtin_sizes = {}
  69. for size_list in api["builtin_class_sizes"]:
  70. if size_list["build_configuration"] == build_config:
  71. for size in size_list["sizes"]:
  72. builtin_sizes[size["name"]] = size["size"]
  73. break
  74. # Create a file for Variant size, since that class isn't generated.
  75. variant_size_filename = include_gen_folder / "variant_size.hpp"
  76. with variant_size_filename.open("+w") as variant_size_file:
  77. variant_size_source = []
  78. add_header("variant_size.hpp", variant_size_source)
  79. header_guard = "GODOT_CPP_VARIANT_SIZE_HPP"
  80. variant_size_source.append(f"#ifndef {header_guard}")
  81. variant_size_source.append(f"#define {header_guard}")
  82. variant_size_source.append(f'#define GODOT_CPP_VARIANT_SIZE {builtin_sizes["Variant"]}')
  83. variant_size_source.append(f"#endif // ! {header_guard}")
  84. variant_size_file.write("\n".join(variant_size_source))
  85. for builtin_api in api["builtin_classes"]:
  86. if is_pod_type(builtin_api["name"]):
  87. continue
  88. if is_included_type(builtin_api["name"]):
  89. continue
  90. size = builtin_sizes[builtin_api["name"]]
  91. header_filename = include_gen_folder / (camel_to_snake(builtin_api["name"]) + ".hpp")
  92. source_filename = source_gen_folder / (camel_to_snake(builtin_api["name"]) + ".cpp")
  93. # Check used classes for header include
  94. used_classes = set()
  95. fully_used_classes = set()
  96. class_name = builtin_api["name"]
  97. if "constructors" in builtin_api:
  98. for constructor in builtin_api["constructors"]:
  99. if "arguments" in constructor:
  100. for argument in constructor["arguments"]:
  101. if is_included(argument["type"], class_name):
  102. if "default_value" in argument and argument["type"] != "Variant":
  103. fully_used_classes.add(argument["type"])
  104. else:
  105. used_classes.add(argument["type"])
  106. if "methods" in builtin_api:
  107. for method in builtin_api["methods"]:
  108. if "arguments" in method:
  109. for argument in method["arguments"]:
  110. if is_included(argument["type"], class_name):
  111. if "default_value" in argument and argument["type"] != "Variant":
  112. fully_used_classes.add(argument["type"])
  113. else:
  114. used_classes.add(argument["type"])
  115. if "return_type" in method:
  116. if is_included(method["return_type"], class_name):
  117. used_classes.add(method["return_type"])
  118. if "members" in builtin_api:
  119. for member in builtin_api["members"]:
  120. if is_included(member["type"], class_name):
  121. used_classes.add(member["type"])
  122. if "indexing_return_type" in builtin_api:
  123. if is_included(builtin_api["indexing_return_type"], class_name):
  124. used_classes.add(builtin_api["indexing_return_type"])
  125. if "operators" in builtin_api:
  126. for operator in builtin_api["operators"]:
  127. if "right_type" in operator:
  128. if is_included(operator["right_type"], class_name):
  129. used_classes.add(operator["right_type"])
  130. for type_name in fully_used_classes:
  131. if type_name in used_classes:
  132. used_classes.remove(type_name)
  133. with header_filename.open("w+") as header_file:
  134. header_file.write(generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes))
  135. with source_filename.open("w+") as source_file:
  136. source_file.write(generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes))
  137. # Create a header with all builtin types for convenience.
  138. builtin_header_filename = include_gen_folder / "builtin_types.hpp"
  139. with builtin_header_filename.open("w+") as builtin_header_file:
  140. builtin_header = []
  141. add_header("builtin_types.hpp", builtin_header)
  142. builtin_header.append("#ifndef GODOT_CPP_BUILTIN_TYPES_HPP")
  143. builtin_header.append("#define GODOT_CPP_BUILTIN_TYPES_HPP")
  144. builtin_header.append("")
  145. for builtin in builtin_classes:
  146. builtin_header.append(f"#include <godot_cpp/variant/{camel_to_snake(builtin)}.hpp>")
  147. builtin_header.append("")
  148. builtin_header.append("#endif // ! GODOT_CPP_BUILTIN_TYPES_HPP")
  149. builtin_header_file.write("\n".join(builtin_header))
  150. def generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes):
  151. result = []
  152. class_name = builtin_api["name"]
  153. snake_class_name = camel_to_snake(class_name).upper()
  154. header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
  155. add_header(f"{snake_class_name.lower()}.hpp", result)
  156. result.append(f"#ifndef {header_guard}")
  157. result.append(f"#define {header_guard}")
  158. result.append("")
  159. result.append("#include <godot_cpp/core/defs.hpp>")
  160. result.append("")
  161. # Special cases.
  162. if class_name == "String":
  163. result.append("#include <godot_cpp/variant/char_string.hpp>")
  164. for include in fully_used_classes:
  165. result.append(f"#include <godot_cpp/{get_include_path(include)}>")
  166. if len(fully_used_classes) > 0:
  167. result.append("")
  168. result.append(f"#include <godot/gdnative_interface.h>")
  169. result.append("")
  170. result.append("namespace godot {")
  171. result.append("")
  172. for type_name in used_classes:
  173. result.append(f"class {type_name};")
  174. if len(used_classes) > 0:
  175. result.append("")
  176. result.append(f"class {class_name} {{")
  177. result.append(f"\tstatic constexpr size_t {snake_class_name}_SIZE = {size};")
  178. result.append(f"\tuint8_t opaque[{snake_class_name}_SIZE] {{ 0 }};")
  179. result.append(
  180. f"\t_FORCE_INLINE_ GDNativeTypePtr ptr() const {{ return const_cast<uint8_t (*)[{snake_class_name}_SIZE]>(&opaque); }}"
  181. )
  182. result.append("")
  183. result.append("\tfriend class Variant;")
  184. result.append("")
  185. result.append("\tstatic struct _MethodBindings {")
  186. if "constructors" in builtin_api:
  187. for constructor in builtin_api["constructors"]:
  188. result.append(f'\t\tGDNativePtrConstructor constructor_{constructor["index"]};')
  189. if builtin_api["has_destructor"]:
  190. result.append("\t\tGDNativePtrDestructor destructor;")
  191. if "methods" in builtin_api:
  192. for method in builtin_api["methods"]:
  193. result.append(f'\t\tGDNativePtrBuiltInMethod method_{method["name"]};')
  194. if "members" in builtin_api:
  195. for member in builtin_api["members"]:
  196. result.append(f'\t\tGDNativePtrSetter member_{member["name"]}_setter;')
  197. result.append(f'\t\tGDNativePtrGetter member_{member["name"]}_getter;')
  198. if "indexing_return_type" in builtin_api:
  199. result.append(f"\t\tGDNativePtrIndexedSetter indexed_setter;")
  200. result.append(f"\t\tGDNativePtrIndexedGetter indexed_getter;")
  201. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  202. result.append(f"\t\tGDNativePtrKeyedSetter keyed_setter;")
  203. result.append(f"\t\tGDNativePtrKeyedGetter keyed_getter;")
  204. result.append(f"\t\tGDNativePtrKeyedChecker keyed_checker;")
  205. if "operators" in builtin_api:
  206. for operator in builtin_api["operators"]:
  207. if "right_type" in operator:
  208. result.append(
  209. f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]};'
  210. )
  211. else:
  212. result.append(f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])};')
  213. result.append("\t} _method_bindings;")
  214. result.append("")
  215. result.append("\tstatic void init_bindings();")
  216. result.append("")
  217. result.append("public:")
  218. copy_constructor_index = -1
  219. if "constructors" in builtin_api:
  220. for constructor in builtin_api["constructors"]:
  221. method_signature = f"\t{class_name}("
  222. if "arguments" in constructor:
  223. method_signature += make_function_parameters(
  224. constructor["arguments"], include_default=True, for_builtin=True
  225. )
  226. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  227. copy_constructor_index = constructor["index"]
  228. method_signature += ");"
  229. result.append(method_signature)
  230. # Move constructor.
  231. result.append(f"\t{class_name}({class_name} &&other);")
  232. # Special cases.
  233. if class_name == "String" or class_name == "StringName" or class_name == "NodePath":
  234. result.append(f"\t{class_name}(const char *from);")
  235. result.append(f"\t{class_name}(const wchar_t *from);")
  236. result.append(f"\t{class_name}(const char16_t *from);")
  237. result.append(f"\t{class_name}(const char32_t *from);")
  238. if "constants" in builtin_api:
  239. axis_constants_count = 0
  240. for constant in builtin_api["constants"]:
  241. # Special case: Vector3.Axis is the only enum in the bindings.
  242. # It's technically not supported by Variant but works for direct access.
  243. if class_name == "Vector3" and constant["name"].startswith("AXIS"):
  244. if axis_constants_count == 0:
  245. result.append("\tenum Axis {")
  246. result.append(f'\t\t{constant["name"]} = {constant["value"]},')
  247. axis_constants_count += 1
  248. if axis_constants_count == 3:
  249. result.append("\t};")
  250. else:
  251. result.append(f'\tstatic const {correct_type(constant["type"])} {constant["name"]};')
  252. if builtin_api["has_destructor"]:
  253. result.append(f"\t~{class_name}();")
  254. method_list = []
  255. if "methods" in builtin_api:
  256. for method in builtin_api["methods"]:
  257. method_list.append(method["name"])
  258. vararg = method["is_vararg"]
  259. if vararg:
  260. result.append("\ttemplate<class... Args>")
  261. method_signature = "\t"
  262. if "is_static" in method and method["is_static"]:
  263. method_signature += "static "
  264. if "return_type" in method:
  265. method_signature += f'{correct_type(method["return_type"])} '
  266. else:
  267. method_signature += "void "
  268. method_signature += f'{method["name"]}('
  269. method_arguments = []
  270. if "arguments" in method:
  271. method_arguments = method["arguments"]
  272. method_signature += make_function_parameters(
  273. method_arguments, include_default=True, for_builtin=True, is_vararg=vararg
  274. )
  275. method_signature += ")"
  276. if method["is_const"]:
  277. method_signature += " const"
  278. method_signature += ";"
  279. result.append(method_signature)
  280. # Special cases.
  281. if class_name == "String":
  282. result.append("\tCharString utf8() const;")
  283. result.append("\tCharString ascii() const;")
  284. result.append("\tChar16String utf16() const;")
  285. result.append("\tChar32String utf32() const;")
  286. result.append("\tCharWideString wide_string() const;")
  287. if "members" in builtin_api:
  288. for member in builtin_api["members"]:
  289. if f'get_{member["name"]}' not in method_list:
  290. result.append(f'\t{correct_type(member["type"])} get_{member["name"]}() const;')
  291. if f'set_{member["name"]}' not in method_list:
  292. result.append(f'\tvoid set_{member["name"]}({type_for_parameter(member["type"])}value);')
  293. if "operators" in builtin_api:
  294. for operator in builtin_api["operators"]:
  295. if operator["name"] not in ["in", "xor"]:
  296. if "right_type" in operator:
  297. result.append(
  298. f'\t{correct_type(operator["return_type"])} operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const;'
  299. )
  300. else:
  301. result.append(
  302. f'\t{correct_type(operator["return_type"])} operator{operator["name"].replace("unary", "")}() const;'
  303. )
  304. # Copy assignment.
  305. if copy_constructor_index >= 0:
  306. result.append(f"\t{class_name} &operator=(const {class_name} &other);")
  307. # Move assignment.
  308. result.append(f"\t{class_name} &operator=({class_name} &&other);")
  309. # Special cases.
  310. if class_name == "String":
  311. result.append("String &operator=(const char *p_str);")
  312. result.append("String &operator=(const wchar_t *p_str);")
  313. result.append("String &operator=(const char16_t *p_str);")
  314. result.append("String &operator=(const char32_t *p_str);")
  315. result.append("bool operator==(const char *p_str) const;")
  316. result.append("bool operator==(const wchar_t *p_str) const;")
  317. result.append("bool operator==(const char16_t *p_str) const;")
  318. result.append("bool operator==(const char32_t *p_str) const;")
  319. result.append("bool operator!=(const char *p_str) const;")
  320. result.append("bool operator!=(const wchar_t *p_str) const;")
  321. result.append("bool operator!=(const char16_t *p_str) const;")
  322. result.append("bool operator!=(const char32_t *p_str) const;")
  323. result.append(f"\tconst char32_t &operator[](int p_index) const;")
  324. result.append(f"\tchar32_t &operator[](int p_index);")
  325. if is_packed_array(class_name):
  326. return_type = correct_type(builtin_api["indexing_return_type"])
  327. if class_name == "PackedByteArray":
  328. return_type = "uint8_t"
  329. elif class_name == "PackedInt32Array":
  330. return_type = "int32_t"
  331. elif class_name == "PackedFloat32Array":
  332. return_type = "float"
  333. result.append(f"\tconst " + return_type + f" &operator[](int p_index) const;")
  334. result.append(f"\t" + return_type + f" &operator[](int p_index);")
  335. result.append("};")
  336. if class_name == "String":
  337. result.append("")
  338. result.append("bool operator==(const char *p_chr, const String &p_str);")
  339. result.append("bool operator==(const wchar_t *p_chr, const String &p_str);")
  340. result.append("bool operator==(const char16_t *p_chr, const String &p_str);")
  341. result.append("bool operator==(const char32_t *p_chr, const String &p_str);")
  342. result.append("bool operator!=(const char *p_chr, const String &p_str);")
  343. result.append("bool operator!=(const wchar_t *p_chr, const String &p_str);")
  344. result.append("bool operator!=(const char16_t *p_chr, const String &p_str);")
  345. result.append("bool operator!=(const char32_t *p_chr, const String &p_str);")
  346. result.append("String operator+(const char *p_chr, const String &p_str);")
  347. result.append("String operator+(const wchar_t *p_chr, const String &p_str);")
  348. result.append("String operator+(const char16_t *p_chr, const String &p_str);")
  349. result.append("String operator+(const char32_t *p_chr, const String &p_str);")
  350. result.append("")
  351. result.append("} // namespace godot")
  352. result.append(f"#endif // ! {header_guard}")
  353. return "\n".join(result)
  354. def generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes):
  355. result = []
  356. class_name = builtin_api["name"]
  357. snake_class_name = camel_to_snake(class_name)
  358. enum_type_name = f"GDNATIVE_VARIANT_TYPE_{snake_class_name.upper()}"
  359. add_header(f"{snake_class_name}.cpp", result)
  360. result.append("")
  361. result.append(f"#include <godot_cpp/variant/{snake_class_name}.hpp>")
  362. result.append("")
  363. result.append("#include <godot_cpp/core/binder_common.hpp>")
  364. result.append("")
  365. result.append("#include <godot_cpp/godot.hpp>")
  366. result.append("")
  367. # Only used since the "fully used" is included in header already.
  368. for include in used_classes:
  369. result.append(f"#include <godot_cpp/{get_include_path(include)}>")
  370. if len(used_classes) > 0:
  371. result.append("")
  372. result.append("#include <godot_cpp/core/builtin_ptrcall.hpp>")
  373. result.append("")
  374. result.append("#include <utility>")
  375. result.append("")
  376. result.append("namespace godot {")
  377. result.append("")
  378. result.append(f"{class_name}::_MethodBindings {class_name}::_method_bindings;")
  379. result.append("")
  380. result.append(f"void {class_name}::init_bindings() {{")
  381. if "constructors" in builtin_api:
  382. for constructor in builtin_api["constructors"]:
  383. result.append(
  384. f'\t_method_bindings.constructor_{constructor["index"]} = internal::interface->variant_get_ptr_constructor({enum_type_name}, {constructor["index"]});'
  385. )
  386. if builtin_api["has_destructor"]:
  387. result.append(
  388. f"\t_method_bindings.destructor = internal::interface->variant_get_ptr_destructor({enum_type_name});"
  389. )
  390. if "methods" in builtin_api:
  391. for method in builtin_api["methods"]:
  392. # TODO: Add error check for hash mismatch.
  393. result.append(
  394. f'\t_method_bindings.method_{method["name"]} = internal::interface->variant_get_ptr_builtin_method({enum_type_name}, "{method["name"]}", {method["hash"]});'
  395. )
  396. if "members" in builtin_api:
  397. for member in builtin_api["members"]:
  398. result.append(
  399. f'\t_method_bindings.member_{member["name"]}_setter = internal::interface->variant_get_ptr_setter({enum_type_name}, "{member["name"]}");'
  400. )
  401. result.append(
  402. f'\t_method_bindings.member_{member["name"]}_getter = internal::interface->variant_get_ptr_getter({enum_type_name}, "{member["name"]}");'
  403. )
  404. if "indexing_return_type" in builtin_api:
  405. result.append(
  406. f"\t_method_bindings.indexed_setter = internal::interface->variant_get_ptr_indexed_setter({enum_type_name});"
  407. )
  408. result.append(
  409. f"\t_method_bindings.indexed_getter = internal::interface->variant_get_ptr_indexed_getter({enum_type_name});"
  410. )
  411. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  412. result.append(
  413. f"\t_method_bindings.keyed_setter = internal::interface->variant_get_ptr_keyed_setter({enum_type_name});"
  414. )
  415. result.append(
  416. f"\t_method_bindings.keyed_getter = internal::interface->variant_get_ptr_keyed_getter({enum_type_name});"
  417. )
  418. result.append(
  419. f"\t_method_bindings.keyed_checker = internal::interface->variant_get_ptr_keyed_checker({enum_type_name});"
  420. )
  421. if "operators" in builtin_api:
  422. for operator in builtin_api["operators"]:
  423. if "right_type" in operator:
  424. result.append(
  425. f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]} = internal::interface->variant_get_ptr_operator_evaluator(GDNATIVE_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, GDNATIVE_VARIANT_TYPE_{camel_to_snake(operator["right_type"]).upper()});'
  426. )
  427. else:
  428. result.append(
  429. f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])} = internal::interface->variant_get_ptr_operator_evaluator(GDNATIVE_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, GDNATIVE_VARIANT_TYPE_NIL);'
  430. )
  431. result.append("}")
  432. result.append("")
  433. copy_constructor_index = -1
  434. if "constructors" in builtin_api:
  435. for constructor in builtin_api["constructors"]:
  436. method_signature = f"{class_name}::{class_name}("
  437. if "arguments" in constructor:
  438. method_signature += make_function_parameters(
  439. constructor["arguments"], include_default=False, for_builtin=True
  440. )
  441. method_signature += ") {"
  442. result.append(method_signature)
  443. method_call = (
  444. f'\tinternal::_call_builtin_constructor(_method_bindings.constructor_{constructor["index"]}, &opaque'
  445. )
  446. if "arguments" in constructor:
  447. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  448. copy_constructor_index = constructor["index"]
  449. method_call += ", "
  450. arguments = []
  451. for argument in constructor["arguments"]:
  452. (encode, arg_name) = get_encoded_arg(
  453. argument["name"],
  454. argument["type"],
  455. argument["meta"] if "meta" in argument else None,
  456. )
  457. result += encode
  458. arguments.append(arg_name)
  459. method_call += ", ".join(arguments)
  460. method_call += ");"
  461. result.append(method_call)
  462. result.append("}")
  463. result.append("")
  464. # Move constructor.
  465. result.append(f"{class_name}::{class_name}({class_name} &&other) {{")
  466. result.append("\tstd::swap(opaque, other.opaque);")
  467. result.append("}")
  468. result.append("")
  469. if builtin_api["has_destructor"]:
  470. result.append(f"{class_name}::~{class_name}() {{")
  471. result.append("\t_method_bindings.destructor(&opaque);")
  472. result.append("}")
  473. result.append("")
  474. method_list = []
  475. if "methods" in builtin_api:
  476. for method in builtin_api["methods"]:
  477. method_list.append(method["name"])
  478. if "is_vararg" in method and method["is_vararg"]:
  479. # Done in the header because of the template.
  480. continue
  481. method_signature = make_signature(class_name, method, for_builtin=True)
  482. result.append(method_signature + "{")
  483. method_call = "\t"
  484. if "return_type" in method:
  485. method_call += f'return internal::_call_builtin_method_ptr_ret<{correct_type(method["return_type"])}>('
  486. else:
  487. method_call += f"internal::_call_builtin_method_ptr_no_ret("
  488. method_call += f'_method_bindings.method_{method["name"]}, '
  489. if "is_static" in method and method["is_static"]:
  490. method_call += "nullptr"
  491. else:
  492. method_call += "(GDNativeTypePtr)&opaque"
  493. if "arguments" in method:
  494. arguments = []
  495. method_call += ", "
  496. for argument in method["arguments"]:
  497. (encode, arg_name) = get_encoded_arg(
  498. argument["name"],
  499. argument["type"],
  500. argument["meta"] if "meta" in argument else None,
  501. )
  502. result += encode
  503. arguments.append(arg_name)
  504. method_call += ", ".join(arguments)
  505. method_call += ");"
  506. result.append(method_call)
  507. result.append("}")
  508. result.append("")
  509. if "members" in builtin_api:
  510. for member in builtin_api["members"]:
  511. if f'get_{member["name"]}' not in method_list:
  512. result.append(f'{correct_type(member["type"])} {class_name}::get_{member["name"]}() const {{')
  513. result.append(
  514. f'\treturn internal::_call_builtin_ptr_getter<{correct_type(member["type"])}>(_method_bindings.member_{member["name"]}_getter, (const GDNativeTypePtr)&opaque);'
  515. )
  516. result.append("}")
  517. if f'set_{member["name"]}' not in method_list:
  518. result.append(f'void {class_name}::set_{member["name"]}({type_for_parameter(member["type"])}value) {{')
  519. (encode, arg_name) = get_encoded_arg("value", member["type"], None)
  520. result += encode
  521. result.append(
  522. f'\t_method_bindings.member_{member["name"]}_setter((const GDNativeTypePtr)&opaque, (const GDNativeTypePtr){arg_name});'
  523. )
  524. result.append("}")
  525. result.append("")
  526. if "operators" in builtin_api:
  527. for operator in builtin_api["operators"]:
  528. if operator["name"] not in ["in", "xor"]:
  529. if "right_type" in operator:
  530. result.append(
  531. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const {{'
  532. )
  533. (encode, arg_name) = get_encoded_arg("other", operator["right_type"], None)
  534. result += encode
  535. result.append(
  536. f'\treturn internal::_call_builtin_operator_ptr<{correct_type(operator["return_type"])}>(_method_bindings.operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]}, (const GDNativeTypePtr)&opaque, (const GDNativeTypePtr){arg_name});'
  537. )
  538. result.append("}")
  539. else:
  540. result.append(
  541. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"].replace("unary", "")}() const {{'
  542. )
  543. result.append(
  544. f'\treturn internal::_call_builtin_operator_ptr<{correct_type(operator["return_type"])}>(_method_bindings.operator_{get_operator_id_name(operator["name"])}, (const GDNativeTypePtr)&opaque, (const GDNativeTypePtr)nullptr);'
  545. )
  546. result.append("}")
  547. result.append("")
  548. # Copy assignment.
  549. if copy_constructor_index >= 0:
  550. result.append(f"{class_name} &{class_name}::operator=(const {class_name} &other) {{")
  551. if builtin_api["has_destructor"]:
  552. result.append("\t_method_bindings.destructor(&opaque);")
  553. (encode, arg_name) = get_encoded_arg(
  554. "other",
  555. class_name,
  556. None,
  557. )
  558. result += encode
  559. result.append(
  560. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, {arg_name});"
  561. )
  562. result.append("\treturn *this;")
  563. result.append("}")
  564. result.append("")
  565. # Move assignment.
  566. result.append(f"{class_name} &{class_name}::operator=({class_name} &&other) {{")
  567. result.append("\tstd::swap(opaque, other.opaque);")
  568. result.append("\treturn *this;")
  569. result.append("}")
  570. result.append("")
  571. result.append("} //namespace godot")
  572. return "\n".join(result)
  573. def generate_engine_classes_bindings(api, output_dir, use_template_get_node):
  574. global engine_classes
  575. global singletons
  576. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  577. source_gen_folder = Path(output_dir) / "src" / "classes"
  578. include_gen_folder.mkdir(parents=True, exist_ok=True)
  579. source_gen_folder.mkdir(parents=True, exist_ok=True)
  580. # First create map of classes and singletons.
  581. for class_api in api["classes"]:
  582. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  583. if class_api["name"] == "ClassDB":
  584. continue
  585. engine_classes[class_api["name"]] = class_api["is_refcounted"]
  586. for native_struct in api["native_structures"]:
  587. engine_classes[native_struct["name"]] = False
  588. for singleton in api["singletons"]:
  589. singletons.append(singleton["name"])
  590. for class_api in api["classes"]:
  591. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  592. if class_api["name"] == "ClassDB":
  593. continue
  594. # Check used classes for header include.
  595. used_classes = set()
  596. fully_used_classes = set()
  597. class_name = class_api["name"]
  598. header_filename = include_gen_folder / (camel_to_snake(class_api["name"]) + ".hpp")
  599. source_filename = source_gen_folder / (camel_to_snake(class_api["name"]) + ".cpp")
  600. if "methods" in class_api:
  601. for method in class_api["methods"]:
  602. if "arguments" in method:
  603. for argument in method["arguments"]:
  604. type_name = argument["type"]
  605. if type_name.endswith("*"):
  606. type_name = type_name[:-1]
  607. if is_included(type_name, class_name):
  608. if is_enum(type_name):
  609. fully_used_classes.add(get_enum_class(type_name))
  610. elif "default_value" in argument:
  611. fully_used_classes.add(type_name)
  612. else:
  613. used_classes.add(type_name)
  614. if is_refcounted(type_name):
  615. fully_used_classes.add("Ref")
  616. if "return_value" in method:
  617. type_name = method["return_value"]["type"]
  618. if type_name.endswith("*"):
  619. type_name = type_name[:-1]
  620. if is_included(type_name, class_name):
  621. if is_enum(type_name):
  622. fully_used_classes.add(get_enum_class(type_name))
  623. elif is_variant(type_name):
  624. fully_used_classes.add(type_name)
  625. else:
  626. used_classes.add(type_name)
  627. if is_refcounted(type_name):
  628. fully_used_classes.add("Ref")
  629. if "members" in class_api:
  630. for member in class_api["members"]:
  631. if is_included(member["type"], class_name):
  632. if is_enum(member["type"]):
  633. fully_used_classes.add(get_enum_class(member["type"]))
  634. else:
  635. used_classes.add(member["type"])
  636. if is_refcounted(member["type"]):
  637. fully_used_classes.add("Ref")
  638. if "inherits" in class_api:
  639. if is_included(class_api["inherits"], class_name):
  640. fully_used_classes.add(class_api["inherits"])
  641. if is_refcounted(class_api["name"]):
  642. fully_used_classes.add("Ref")
  643. else:
  644. fully_used_classes.add("Wrapped")
  645. for type_name in fully_used_classes:
  646. if type_name in used_classes:
  647. used_classes.remove(type_name)
  648. with header_filename.open("w+") as header_file:
  649. header_file.write(
  650. generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node)
  651. )
  652. with source_filename.open("w+") as source_file:
  653. source_file.write(
  654. generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node)
  655. )
  656. for native_struct in api["native_structures"]:
  657. struct_name = native_struct["name"]
  658. snake_struct_name = camel_to_snake(struct_name)
  659. header_filename = include_gen_folder / (snake_struct_name + ".hpp")
  660. result = []
  661. add_header(f"{snake_struct_name}.hpp", result)
  662. header_guard = f"GODOT_CPP_{snake_struct_name.upper()}_HPP"
  663. result.append(f"#ifndef {header_guard}")
  664. result.append(f"#define {header_guard}")
  665. result.append("")
  666. result.append("namespace godot {")
  667. result.append("")
  668. result.append(f"struct {struct_name} {{")
  669. for field in native_struct["format"].split(","):
  670. result.append(f"\t{field};")
  671. result.append("};")
  672. result.append("")
  673. result.append("} // namespace godot")
  674. result.append("")
  675. result.append(f"#endif // ! {header_guard}")
  676. with header_filename.open("w+") as header_file:
  677. header_file.write("\n".join(result))
  678. def generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node):
  679. global singletons
  680. result = []
  681. class_name = class_api["name"]
  682. snake_class_name = camel_to_snake(class_name).upper()
  683. is_singleton = class_name in singletons
  684. add_header(f"{snake_class_name.lower()}.hpp", result)
  685. header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
  686. result.append(f"#ifndef {header_guard}")
  687. result.append(f"#define {header_guard}")
  688. result.append("")
  689. for included in fully_used_classes:
  690. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  691. if len(fully_used_classes) > 0:
  692. result.append("")
  693. if class_name != "Object":
  694. result.append("#include <godot_cpp/core/class_db.hpp>")
  695. result.append("")
  696. result.append("#include <type_traits>")
  697. result.append("")
  698. result.append("namespace godot {")
  699. result.append("")
  700. for type_name in used_classes:
  701. result.append(f"class {type_name};")
  702. if len(used_classes) > 0:
  703. result.append("")
  704. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  705. result.append(f"class {class_name} : public {inherits} {{")
  706. result.append(f"\tGDNATIVE_CLASS({class_name}, {inherits})")
  707. result.append("")
  708. result.append("public:")
  709. # Constructor override, since parent Wrapped has protected constructor.
  710. result.append(f"\t{class_name}() = default;")
  711. result.append("")
  712. if "enums" in class_api:
  713. for enum_api in class_api["enums"]:
  714. result.append(f'\tenum {enum_api["name"]} {{')
  715. for value in enum_api["values"]:
  716. result.append(f'\t\t{value["name"]} = {value["value"]},')
  717. result.append("\t};")
  718. result.append("")
  719. if is_singleton:
  720. result.append(f"\tstatic {class_name} *get_singleton();")
  721. result.append("")
  722. if "methods" in class_api:
  723. for method in class_api["methods"]:
  724. if method["is_virtual"]:
  725. # Will be done later.
  726. continue
  727. vararg = "is_vararg" in method and method["is_vararg"]
  728. method_signature = "\t"
  729. if vararg:
  730. method_signature += "private: "
  731. method_signature += make_signature(
  732. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  733. )
  734. result.append(method_signature + ";")
  735. if vararg:
  736. # Add templated version.
  737. result += make_varargs_template(method)
  738. # Virtuals now.
  739. for method in class_api["methods"]:
  740. if not method["is_virtual"]:
  741. continue
  742. method_signature = "\t"
  743. method_signature += make_signature(
  744. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  745. )
  746. result.append(method_signature + ";")
  747. result.append("protected:")
  748. result.append("\ttemplate <class T>")
  749. result.append("\tstatic void register_virtuals() {")
  750. if class_name != "Object":
  751. result.append(f"\t\t{inherits}::register_virtuals<T>();")
  752. if "methods" in class_api:
  753. for method in class_api["methods"]:
  754. if not method["is_virtual"]:
  755. continue
  756. method_name = escape_identifier(method["name"])
  757. result.append(
  758. f"\t\tif constexpr (!std::is_same_v<decltype(&{class_name}::{method_name}),decltype(&T::{method_name})>) {{"
  759. )
  760. result.append(f"\t\t\tBIND_VIRTUAL_METHOD(T, {method_name});")
  761. result.append("\t\t}")
  762. result.append("\t}")
  763. result.append("")
  764. result.append("public:")
  765. # Special cases.
  766. if class_name == "Object":
  767. result.append("")
  768. result.append("\ttemplate<class T>")
  769. result.append("\tstatic T *cast_to(Object *p_object);")
  770. elif use_template_get_node and class_name == "Node":
  771. result.append("\ttemplate<class T>")
  772. result.append(
  773. "\tT *get_node(const NodePath &p_path) const { return Object::cast_to<T>(get_node_internal(p_path)); }"
  774. )
  775. result.append("")
  776. result.append("};")
  777. result.append("")
  778. result.append("} // namespace godot")
  779. result.append(f"#endif // ! {header_guard}")
  780. return "\n".join(result)
  781. def generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node):
  782. global singletons
  783. result = []
  784. class_name = class_api["name"]
  785. snake_class_name = camel_to_snake(class_name)
  786. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  787. is_singleton = class_name in singletons
  788. add_header(f"{snake_class_name}.cpp", result)
  789. result.append(f"#include <godot_cpp/classes/{snake_class_name}.hpp>")
  790. result.append("")
  791. result.append(f"#include <godot_cpp/core/engine_ptrcall.hpp>")
  792. result.append(f"#include <godot_cpp/core/error_macros.hpp>")
  793. result.append("")
  794. for included in used_classes:
  795. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  796. if len(used_classes) > 0:
  797. result.append(f"")
  798. result.append("namespace godot {")
  799. result.append("")
  800. if is_singleton:
  801. result.append(f"{class_name} *{class_name}::get_singleton() {{")
  802. result.append(
  803. f'\tstatic GDNativeObjectPtr singleton_obj = internal::interface->global_get_singleton("{class_name}");'
  804. )
  805. result.append("#ifdef DEBUG_ENABLED")
  806. result.append("\tERR_FAIL_COND_V(singleton_obj == nullptr, nullptr);")
  807. result.append("#endif // DEBUG_ENABLED")
  808. result.append(
  809. f"\tstatic {class_name} *singleton = reinterpret_cast<{class_name} *>(internal::interface->object_get_instance_binding(singleton_obj, internal::token, &{class_name}::___binding_callbacks));"
  810. )
  811. result.append("\treturn singleton;")
  812. result.append("}")
  813. result.append("")
  814. if "methods" in class_api:
  815. for method in class_api["methods"]:
  816. if method["is_virtual"]:
  817. # Will be done later
  818. continue
  819. vararg = "is_vararg" in method and method["is_vararg"]
  820. # Method signature.
  821. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  822. result.append(method_signature + " {")
  823. # Method body.
  824. result.append(
  825. f'\tstatic GDNativeMethodBindPtr ___method_bind = internal::interface->classdb_get_method_bind("{class_name}", "{method["name"]}", {method["hash"]});'
  826. )
  827. method_call = "\t"
  828. has_return = "return_value" in method and method["return_value"]["type"] != "void"
  829. if has_return:
  830. result.append(
  831. f'\tCHECK_METHOD_BIND_RET(___method_bind, {get_default_value_for_type(method["return_value"]["type"])});'
  832. )
  833. else:
  834. result.append(f"\tCHECK_METHOD_BIND(___method_bind);")
  835. is_ref = False
  836. if not vararg:
  837. if has_return:
  838. return_type = method["return_value"]["type"]
  839. meta_type = method["return_value"]["meta"] if "meta" in method["return_value"] else None
  840. if is_pod_type(return_type) or is_variant(return_type) or is_enum(return_type):
  841. method_call += f"return internal::_call_native_mb_ret<{correct_type(return_type, meta_type)}>(___method_bind, _owner"
  842. elif is_refcounted(return_type):
  843. method_call += f"return Ref<{return_type}>::___internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  844. is_ref = True
  845. else:
  846. method_call += f"return internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  847. else:
  848. method_call += f"internal::_call_native_mb_no_ret(___method_bind, _owner"
  849. if "arguments" in method:
  850. method_call += ", "
  851. arguments = []
  852. for argument in method["arguments"]:
  853. (encode, arg_name) = get_encoded_arg(
  854. argument["name"],
  855. argument["type"],
  856. argument["meta"] if "meta" in argument else None,
  857. )
  858. result += encode
  859. arguments.append(arg_name)
  860. method_call += ", ".join(arguments)
  861. else: # vararg.
  862. result.append("\tGDNativeCallError error;")
  863. result.append("\tVariant ret;")
  864. method_call += "internal::interface->object_method_bind_call(___method_bind, _owner, (const GDNativeVariantPtr *)args, arg_count, &ret, &error"
  865. if is_ref:
  866. method_call += ")" # Close Ref<> constructor.
  867. method_call += ");"
  868. result.append(method_call)
  869. if vararg and ("return_value" in method and method["return_value"]["type"] != "void"):
  870. result.append("\treturn ret;")
  871. result.append("}")
  872. result.append("")
  873. # Virtuals now.
  874. for method in class_api["methods"]:
  875. if not method["is_virtual"]:
  876. continue
  877. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  878. method_signature += " {"
  879. if "return_value" in method and correct_type(method["return_value"]["type"]) != "void":
  880. result.append(method_signature)
  881. result.append(f'\treturn {get_default_value_for_type(method["return_value"]["type"])};')
  882. result.append("}")
  883. else:
  884. method_signature += "}"
  885. result.append(method_signature)
  886. result.append("")
  887. result.append("")
  888. result.append("} // namespace godot ")
  889. return "\n".join(result)
  890. def generate_global_constants(api, output_dir):
  891. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  892. source_gen_folder = Path(output_dir) / "src" / "classes"
  893. include_gen_folder.mkdir(parents=True, exist_ok=True)
  894. source_gen_folder.mkdir(parents=True, exist_ok=True)
  895. # Generate header
  896. header = []
  897. add_header("global_constants.hpp", header)
  898. header_filename = include_gen_folder / "global_constants.hpp"
  899. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_HPP"
  900. header.append(f"#ifndef {header_guard}")
  901. header.append(f"#define {header_guard}")
  902. header.append("")
  903. header.append("namespace godot {")
  904. header.append("")
  905. for constant in api["global_constants"]:
  906. header.append(f'\tconst int {escape_identifier(constant["name"])} = {constant["value"]};')
  907. header.append("")
  908. for enum_def in api["global_enums"]:
  909. if enum_def["name"].startswith("Variant."):
  910. continue
  911. header.append(f'\tenum {enum_def["name"]} {{')
  912. for value in enum_def["values"]:
  913. header.append(f'\t\t{value["name"]} = {value["value"]},')
  914. header.append("\t};")
  915. header.append("")
  916. header.append("} // namespace godot")
  917. header.append("")
  918. header.append(f"#endif // ! {header_guard}")
  919. with header_filename.open("w+") as header_file:
  920. header_file.write("\n".join(header))
  921. def generate_utility_functions(api, output_dir):
  922. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  923. source_gen_folder = Path(output_dir) / "src" / "variant"
  924. include_gen_folder.mkdir(parents=True, exist_ok=True)
  925. source_gen_folder.mkdir(parents=True, exist_ok=True)
  926. # Generate header.
  927. header = []
  928. add_header("utility_functions.hpp", header)
  929. header_filename = include_gen_folder / "utility_functions.hpp"
  930. header_guard = "GODOT_CPP_UTILITY_FUNCTIONS_HPP"
  931. header.append(f"#ifndef {header_guard}")
  932. header.append(f"#define {header_guard}")
  933. header.append("")
  934. header.append("#include <godot_cpp/variant/builtin_types.hpp>")
  935. header.append("#include <godot_cpp/variant/variant.hpp>")
  936. header.append("")
  937. header.append("#include <array>")
  938. header.append("")
  939. header.append("namespace godot {")
  940. header.append("")
  941. header.append("class UtilityFunctions {")
  942. header.append("public:")
  943. for function in api["utility_functions"]:
  944. vararg = "is_vararg" in function and function["is_vararg"]
  945. function_signature = "\t"
  946. function_signature += make_signature("UtilityFunctions", function, for_header=True, static=True)
  947. header.append(function_signature + ";")
  948. if vararg:
  949. # Add templated version.
  950. header += make_varargs_template(function, static=True)
  951. header.append("};")
  952. header.append("")
  953. header.append("} // namespace godot")
  954. header.append("")
  955. header.append(f"#endif // ! {header_guard}")
  956. with header_filename.open("w+") as header_file:
  957. header_file.write("\n".join(header))
  958. # Generate source.
  959. source = []
  960. add_header("utility_functions.cpp", source)
  961. source_filename = source_gen_folder / "utility_functions.cpp"
  962. source.append("#include <godot_cpp/variant/utility_functions.hpp>")
  963. source.append("")
  964. source.append("#include <godot_cpp/core/error_macros.hpp>")
  965. source.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  966. source.append("")
  967. source.append("namespace godot {")
  968. source.append("")
  969. for function in api["utility_functions"]:
  970. vararg = "is_vararg" in function and function["is_vararg"]
  971. function_signature = make_signature("UtilityFunctions", function)
  972. source.append(function_signature + " {")
  973. # Function body.
  974. source.append(
  975. f'\tstatic GDNativePtrUtilityFunction ___function = internal::interface->variant_get_ptr_utility_function("{function["name"]}", {function["hash"]});'
  976. )
  977. has_return = "return_type" in function and function["return_type"] != "void"
  978. if has_return:
  979. source.append(
  980. f'\tCHECK_METHOD_BIND_RET(___function, {get_default_value_for_type(function["return_type"])});'
  981. )
  982. else:
  983. source.append(f"\tCHECK_METHOD_BIND(___function);")
  984. function_call = "\t"
  985. if not vararg:
  986. if has_return:
  987. function_call += "return "
  988. if function["return_type"] == "Object":
  989. function_call += "internal::_call_utility_ret_obj(___function"
  990. else:
  991. function_call += f'internal::_call_utility_ret<{correct_type(function["return_type"])}>(___function'
  992. else:
  993. function_call += "internal::_call_utility_no_ret(___function"
  994. if "arguments" in function:
  995. function_call += ", "
  996. arguments = []
  997. for argument in function["arguments"]:
  998. (encode, arg_name) = get_encoded_arg(
  999. argument["name"],
  1000. argument["type"],
  1001. argument["meta"] if "meta" in argument else None,
  1002. )
  1003. source += encode
  1004. arguments.append(arg_name)
  1005. function_call += ", ".join(arguments)
  1006. else:
  1007. source.append("\tVariant ret;")
  1008. function_call += "___function(&ret, (const GDNativeVariantPtr *)args, arg_count"
  1009. function_call += ");"
  1010. source.append(function_call)
  1011. if vararg and has_return:
  1012. source.append("\treturn ret;")
  1013. source.append("}")
  1014. source.append("")
  1015. source.append("} // namespace godot")
  1016. with source_filename.open("w+") as source_file:
  1017. source_file.write("\n".join(source))
  1018. # Helper functions.
  1019. def camel_to_snake(name):
  1020. name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
  1021. name = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name)
  1022. return name.replace("2_D", "2D").replace("3_D", "3D").lower()
  1023. def make_function_parameters(parameters, include_default=False, for_builtin=False, is_vararg=False):
  1024. signature = []
  1025. for index, par in enumerate(parameters):
  1026. parameter = type_for_parameter(par["type"], par["meta"] if "meta" in par else None)
  1027. parameter_name = escape_identifier(par["name"])
  1028. if len(parameter_name) == 0:
  1029. parameter_name = "arg_" + str(index + 1)
  1030. parameter += parameter_name
  1031. if include_default and "default_value" in par and (not for_builtin or par["type"] != "Variant"):
  1032. parameter += " = "
  1033. if is_enum(par["type"]):
  1034. parameter_type = correct_type(par["type"])
  1035. if parameter_type == "void":
  1036. parameter_type = "Variant"
  1037. parameter += f"({parameter_type})"
  1038. parameter += correct_default_value(par["default_value"], par["type"])
  1039. signature.append(parameter)
  1040. if is_vararg:
  1041. signature.append("const Args&... args")
  1042. return ", ".join(signature)
  1043. def type_for_parameter(type_name, meta=None):
  1044. if type_name == "void":
  1045. return "Variant "
  1046. elif is_pod_type(type_name) and type_name != "Nil" or is_enum(type_name):
  1047. return f"{correct_type(type_name, meta)} "
  1048. elif is_variant(type_name) or is_refcounted(type_name):
  1049. return f"const {correct_type(type_name)} &"
  1050. else:
  1051. return f"{correct_type(type_name)}"
  1052. def get_include_path(type_name):
  1053. base_dir = ""
  1054. if type_name == "Object":
  1055. base_dir = "core"
  1056. elif is_variant(type_name):
  1057. base_dir = "variant"
  1058. else:
  1059. base_dir = "classes"
  1060. return f"{base_dir}/{camel_to_snake(type_name)}.hpp"
  1061. def get_encoded_arg(arg_name, type_name, type_meta):
  1062. result = []
  1063. name = escape_identifier(arg_name)
  1064. arg_type = correct_type(type_name)
  1065. if is_pod_type(arg_type):
  1066. result.append(f"\t{get_gdnative_type(arg_type)} {name}_encoded;")
  1067. result.append(f"\tPtrToArg<{correct_type(type_name)}>::encode({name}, &{name}_encoded);")
  1068. name = f"&{name}_encoded"
  1069. elif is_engine_class(type_name):
  1070. name = f"{name}->_owner"
  1071. else:
  1072. name = f"&{name}"
  1073. return (result, name)
  1074. def make_signature(
  1075. class_name, function_data, for_header=False, use_template_get_node=True, for_builtin=False, static=False
  1076. ):
  1077. function_signature = ""
  1078. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1079. if for_header:
  1080. if "is_virtual" in function_data and function_data["is_virtual"]:
  1081. function_signature += "virtual "
  1082. if is_vararg:
  1083. function_signature += "private: "
  1084. if static:
  1085. function_signature += "static "
  1086. return_type = "void"
  1087. return_meta = None
  1088. if "return_type" in function_data:
  1089. return_type = correct_type(function_data["return_type"])
  1090. elif "return_value" in function_data:
  1091. return_type = function_data["return_value"]["type"]
  1092. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1093. function_signature += correct_type(
  1094. return_type,
  1095. return_meta,
  1096. )
  1097. if not function_signature.endswith("*"):
  1098. function_signature += " "
  1099. if not for_header:
  1100. function_signature += f"{class_name}::"
  1101. function_signature += escape_identifier(function_data["name"])
  1102. if is_vararg or (
  1103. not for_builtin and use_template_get_node and class_name == "Node" and function_data["name"] == "get_node"
  1104. ):
  1105. function_signature += "_internal"
  1106. function_signature += "("
  1107. arguments = function_data["arguments"] if "arguments" in function_data else []
  1108. if not is_vararg:
  1109. function_signature += make_function_parameters(arguments, for_header, for_builtin, is_vararg)
  1110. else:
  1111. function_signature += "const Variant **args, GDNativeInt arg_count"
  1112. function_signature += ")"
  1113. if "is_const" in function_data and function_data["is_const"]:
  1114. function_signature += " const"
  1115. return function_signature
  1116. def make_varargs_template(function_data, static=False):
  1117. result = []
  1118. function_signature = "\tpublic: template<class... Args> "
  1119. if static:
  1120. function_signature += "static "
  1121. return_type = "void"
  1122. return_meta = None
  1123. if "return_type" in function_data:
  1124. return_type = correct_type(function_data["return_type"])
  1125. elif "return_value" in function_data:
  1126. return_type = function_data["return_value"]["type"]
  1127. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1128. function_signature += correct_type(
  1129. return_type,
  1130. return_meta,
  1131. )
  1132. if not function_signature.endswith("*"):
  1133. function_signature += " "
  1134. function_signature += f'{escape_identifier(function_data["name"])}'
  1135. method_arguments = []
  1136. if "arguments" in function_data:
  1137. method_arguments = function_data["arguments"]
  1138. function_signature += "("
  1139. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1140. function_signature += make_function_parameters(method_arguments, include_default=True, is_vararg=is_vararg)
  1141. function_signature += ")"
  1142. if "is_const" in function_data and function_data["is_const"]:
  1143. function_signature += " const"
  1144. function_signature += " {"
  1145. result.append(function_signature)
  1146. args_array = f"\t\tstd::array<Variant, {len(method_arguments)} + sizeof...(Args)> variant_args {{ "
  1147. for argument in method_arguments:
  1148. if argument["type"] == "Variant":
  1149. args_array += argument["name"]
  1150. else:
  1151. args_array += f'Variant({argument["name"]})'
  1152. args_array += ", "
  1153. args_array += "Variant(args)... };"
  1154. result.append(args_array)
  1155. result.append(f"\t\tstd::array<const Variant *, {len(method_arguments)} + sizeof...(Args)> call_args;")
  1156. result.append("\t\tfor(size_t i = 0; i < variant_args.size(); i++) {")
  1157. result.append("\t\t\tcall_args[i] = &variant_args[i];")
  1158. result.append("\t\t}")
  1159. call_line = "\t\t"
  1160. if return_type != "void":
  1161. call_line += "return "
  1162. call_line += f'{escape_identifier(function_data["name"])}_internal(call_args.data(), variant_args.size());'
  1163. result.append(call_line)
  1164. result.append("\t}")
  1165. return result
  1166. # Engine idiosyncrasies.
  1167. def is_pod_type(type_name):
  1168. """
  1169. Those are types for which no class should be generated.
  1170. """
  1171. return type_name in [
  1172. "Nil",
  1173. "void",
  1174. "int",
  1175. "float",
  1176. "bool",
  1177. "double",
  1178. "int32_t",
  1179. "int64_t",
  1180. "uint32_t",
  1181. "uint64_t",
  1182. ]
  1183. def is_included_type(type_name):
  1184. """
  1185. Those are types for which we already have a class file implemented.
  1186. """
  1187. return type_name in [
  1188. "AABB",
  1189. "Basis",
  1190. "Color",
  1191. "Plane",
  1192. "Quaternion",
  1193. "Rect2",
  1194. "Rect2i",
  1195. "Transform2D",
  1196. "Transform3D",
  1197. "Vector2",
  1198. "Vector2i",
  1199. "Vector3",
  1200. "Vector3i",
  1201. ]
  1202. def is_packed_array(type_name):
  1203. """
  1204. Those are types for which we add our extra packed array functions.
  1205. """
  1206. return type_name in [
  1207. "PackedByteArray",
  1208. "PackedColorArray",
  1209. "PackedFloat32Array",
  1210. "PackedFloat64Array",
  1211. "PackedInt32Array",
  1212. "PackedInt64Array",
  1213. "PackedStringArray",
  1214. "PackedVector2Array",
  1215. "PackedVector3Array",
  1216. ]
  1217. def is_enum(type_name):
  1218. return type_name.startswith("enum::")
  1219. def get_enum_class(enum_name: str):
  1220. if "." in enum_name:
  1221. return enum_name.replace("enum::", "").split(".")[0]
  1222. else:
  1223. return "GlobalConstants"
  1224. def get_enum_name(enum_name: str):
  1225. return enum_name.replace("enum::", "").split(".")[-1]
  1226. def is_variant(type_name):
  1227. return type_name == "Variant" or type_name in builtin_classes or type_name == "Nil"
  1228. def is_engine_class(type_name):
  1229. global engine_classes
  1230. return type_name == "Object" or type_name in engine_classes
  1231. def is_refcounted(type_name):
  1232. return type_name in engine_classes and engine_classes[type_name]
  1233. def is_included(type_name, current_type):
  1234. """
  1235. Check if a builtin type should be included.
  1236. This removes Variant and POD types from inclusion, and the current type.
  1237. """
  1238. to_include = get_enum_class(type_name) if is_enum(type_name) else type_name
  1239. if to_include == current_type or is_pod_type(to_include):
  1240. return False
  1241. if to_include == "GlobalConstants" or to_include == "UtilityFunctions":
  1242. return True
  1243. return is_engine_class(to_include) or is_variant(to_include)
  1244. def correct_default_value(value, type_name):
  1245. value_map = {
  1246. "null": "nullptr",
  1247. '""': "String()",
  1248. '&""': "StringName()",
  1249. "[]": "Array()",
  1250. "{}": "Dictionary()",
  1251. "Transform2D(1, 0, 0, 1, 0, 0)": "Transform2D()", # Default transform.
  1252. "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)": "Transform3D()", # Default transform.
  1253. }
  1254. if value in value_map:
  1255. return value_map[value]
  1256. if value == "":
  1257. return f"{type_name}()"
  1258. return value
  1259. def correct_type(type_name, meta=None):
  1260. type_conversion = {"float": "double", "int": "int64_t", "Nil": "Variant"}
  1261. if meta != None:
  1262. if "int" in meta:
  1263. return f"{meta}_t"
  1264. elif meta in type_conversion:
  1265. return type_conversion[type_name]
  1266. else:
  1267. return meta
  1268. if type_name in type_conversion:
  1269. return type_conversion[type_name]
  1270. if is_enum(type_name):
  1271. base_class = get_enum_class(type_name)
  1272. if base_class == "GlobalConstants":
  1273. return f"{get_enum_name(type_name)}"
  1274. return f"{base_class}::{get_enum_name(type_name)}"
  1275. if is_refcounted(type_name):
  1276. return f"Ref<{type_name}>"
  1277. if type_name == "Object" or is_engine_class(type_name):
  1278. return f"{type_name} *"
  1279. if type_name.endswith("*"):
  1280. return f"{type_name[:-1]} *"
  1281. return type_name
  1282. def get_gdnative_type(type_name):
  1283. type_conversion_map = {
  1284. "bool": "uint32_t",
  1285. "int": "int64_t",
  1286. "float": "double",
  1287. }
  1288. if type_name in type_conversion_map:
  1289. return type_conversion_map[type_name]
  1290. return type_name
  1291. def escape_identifier(id):
  1292. cpp_keywords_map = {
  1293. "class": "_class",
  1294. "char": "_char",
  1295. "short": "_short",
  1296. "bool": "_bool",
  1297. "int": "_int",
  1298. "default": "_default",
  1299. "case": "_case",
  1300. "switch": "_switch",
  1301. "export": "_export",
  1302. "template": "_template",
  1303. "new": "new_",
  1304. "operator": "_operator",
  1305. "typeof": "type_of",
  1306. "typename": "type_name",
  1307. }
  1308. if id in cpp_keywords_map:
  1309. return cpp_keywords_map[id]
  1310. return id
  1311. def get_operator_id_name(op):
  1312. op_id_map = {
  1313. "==": "equal",
  1314. "!=": "not_equal",
  1315. "<": "less",
  1316. "<=": "less_equal",
  1317. ">": "greater",
  1318. ">=": "greater_equal",
  1319. "+": "add",
  1320. "-": "subtract",
  1321. "*": "multiply",
  1322. "/": "divide",
  1323. "unary-": "negate",
  1324. "unary+": "positive",
  1325. "%": "module",
  1326. "<<": "shift_left",
  1327. ">>": "shift_right",
  1328. "&": "bit_and",
  1329. "|": "bit_or",
  1330. "^": "bit_xor",
  1331. "~": "bit_negate",
  1332. "and": "and",
  1333. "or": "or",
  1334. "xor": "xor",
  1335. "not": "not",
  1336. "and": "and",
  1337. "in": "in",
  1338. }
  1339. return op_id_map[op]
  1340. def get_default_value_for_type(type_name):
  1341. if type_name == "int":
  1342. return "0"
  1343. if type_name == "float":
  1344. return "0.0"
  1345. if type_name == "bool":
  1346. return "false"
  1347. if is_enum(type_name):
  1348. return f"{correct_type(type_name)}(0)"
  1349. if is_variant(type_name):
  1350. return f"{type_name}()"
  1351. if is_refcounted(type_name):
  1352. return f"Ref<{type_name}>()"
  1353. return "nullptr"
  1354. header = """\
  1355. /*************************************************************************/
  1356. /* $filename */
  1357. /*************************************************************************/
  1358. /* This file is part of: */
  1359. /* GODOT ENGINE */
  1360. /* https://godotengine.org */
  1361. /*************************************************************************/
  1362. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  1363. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  1364. /* */
  1365. /* Permission is hereby granted, free of charge, to any person obtaining */
  1366. /* a copy of this software and associated documentation files (the */
  1367. /* "Software"), to deal in the Software without restriction, including */
  1368. /* without limitation the rights to use, copy, modify, merge, publish, */
  1369. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1370. /* permit persons to whom the Software is furnished to do so, subject to */
  1371. /* the following conditions: */
  1372. /* */
  1373. /* The above copyright notice and this permission notice shall be */
  1374. /* included in all copies or substantial portions of the Software. */
  1375. /* */
  1376. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1377. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1378. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  1379. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1380. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1381. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1382. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1383. /*************************************************************************/
  1384. """
  1385. def add_header(filename, lines):
  1386. desired_length = len(header.split("\n")[0])
  1387. pad_spaces = desired_length - 6 - len(filename)
  1388. for num, line in enumerate(header.split("\n")):
  1389. if num == 1:
  1390. new_line = f"/* {filename}{' ' * pad_spaces}*/"
  1391. lines.append(new_line)
  1392. else:
  1393. lines.append(line)
  1394. lines.append("// THIS FILE IS GENERATED. EDITS WILL BE LOST.")
  1395. lines.append("")