2
0

binding_generator.py 94 KB

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