binding_generator.py 74 KB

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