binding_generator.py 84 KB

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