binding_generator.py 92 KB

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