binding_generator.py 113 KB

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