binding_generator.py 82 KB

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