binding_generator.py 73 KB

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