binding_generator.py 105 KB

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