binding_generator.py 82 KB

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