binding_generator.py 113 KB

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