binding_generator.py 96 KB

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