binding_generator.py 80 KB

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