binding_generator.py 98 KB

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