binding_generator.py 95 KB

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