binding_generator.py 112 KB

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