binding_generator.py 92 KB

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