binding_generator.py 111 KB

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