binding_generator.py 66 KB

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