binding_generator.py 71 KB

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