binding_generator.py 74 KB

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