binding_generator.py 75 KB

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