binding_generator.py 113 KB

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