binding_generator.py 65 KB

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