binding_generator.py 101 KB

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