binding_generator.py 74 KB

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