binding_generator.py 83 KB

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