binding_generator.py 67 KB

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