binding_generator.py 82 KB

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