binding_generator.py 66 KB

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