binding_generator.py 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759
  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 or vararg methods, but if some appear later, lets skip them.
  1358. if vararg:
  1359. continue
  1360. if "is_static" in method and method["is_static"]:
  1361. continue
  1362. method_signature = "\tstatic "
  1363. return_type = None
  1364. if "return_type" in method:
  1365. return_type = correct_type(method["return_type"].replace("ClassDBSingleton", "ClassDB"), None, False)
  1366. elif "return_value" in method:
  1367. return_type = correct_type(
  1368. method["return_value"]["type"].replace("ClassDBSingleton", "ClassDB"),
  1369. method["return_value"].get("meta", None),
  1370. False,
  1371. )
  1372. if return_type is not None:
  1373. method_signature += return_type + " "
  1374. else:
  1375. method_signature += "void "
  1376. method_signature += f'{method["name"]}('
  1377. method_arguments = []
  1378. if "arguments" in method:
  1379. method_arguments = method["arguments"]
  1380. method_signature += make_function_parameters(
  1381. method_arguments, include_default=True, for_builtin=True, is_vararg=False
  1382. )
  1383. method_signature += ") { \\"
  1384. result.append(method_signature)
  1385. method_body = "\t\t"
  1386. if return_type is not None:
  1387. method_body += "return "
  1388. if "alias_for" in class_api and return_type.startswith(class_api["alias_for"] + "::"):
  1389. method_body += f"({return_type})"
  1390. method_body += f'ClassDBSingleton::get_singleton()->{method["name"]}('
  1391. method_body += ", ".join(map(lambda x: escape_identifier(x["name"]), method_arguments))
  1392. method_body += "); \\"
  1393. result.append(method_body)
  1394. result.append("\t} \\")
  1395. result.append("\t;")
  1396. result.append("")
  1397. result.append("#define CLASSDB_SINGLETON_VARIANT_CAST \\")
  1398. if "enums" in class_api:
  1399. for enum_api in class_api["enums"]:
  1400. if enum_api["is_bitfield"]:
  1401. result.append(f'\tVARIANT_BITFIELD_CAST({class_api["alias_for"]}::{enum_api["name"]}); \\')
  1402. else:
  1403. result.append(f'\tVARIANT_ENUM_CAST({class_api["alias_for"]}::{enum_api["name"]}); \\')
  1404. result.append("\t;")
  1405. result.append("")
  1406. result.append(f"#endif // ! {header_guard}")
  1407. return "\n".join(result)
  1408. def generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node):
  1409. global singletons
  1410. result = []
  1411. class_name = class_api["name"]
  1412. snake_class_name = camel_to_snake(class_name)
  1413. is_singleton = class_name in singletons
  1414. add_header(f"{snake_class_name}.cpp", result)
  1415. result.append(f"#include <godot_cpp/classes/{snake_class_name}.hpp>")
  1416. result.append("")
  1417. result.append("#include <godot_cpp/core/class_db.hpp>")
  1418. result.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  1419. result.append("#include <godot_cpp/core/error_macros.hpp>")
  1420. result.append("")
  1421. for included in used_classes:
  1422. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  1423. if len(used_classes) > 0:
  1424. result.append("")
  1425. result.append("namespace godot {")
  1426. result.append("")
  1427. if is_singleton:
  1428. result.append(f"{class_name} *{class_name}::singleton = nullptr;")
  1429. result.append("")
  1430. result.append(f"{class_name} *{class_name}::get_singleton() {{")
  1431. # We assume multi-threaded access is OK because each assignment will assign the same value every time
  1432. result.append("\tif (unlikely(singleton == nullptr)) {")
  1433. result.append(
  1434. f"\t\tGDExtensionObjectPtr singleton_obj = internal::gdextension_interface_global_get_singleton({class_name}::get_class_static()._native_ptr());"
  1435. )
  1436. result.append("#ifdef DEBUG_ENABLED")
  1437. result.append("\t\tERR_FAIL_NULL_V(singleton_obj, nullptr);")
  1438. result.append("#endif // DEBUG_ENABLED")
  1439. result.append(
  1440. f"\t\tsingleton = reinterpret_cast<{class_name} *>(internal::gdextension_interface_object_get_instance_binding(singleton_obj, internal::token, &{class_name}::_gde_binding_callbacks));"
  1441. )
  1442. result.append("#ifdef DEBUG_ENABLED")
  1443. result.append("\t\tERR_FAIL_NULL_V(singleton, nullptr);")
  1444. result.append("#endif // DEBUG_ENABLED")
  1445. result.append("\t\tif (likely(singleton)) {")
  1446. result.append(f"\t\t\tClassDB::_register_engine_singleton({class_name}::get_class_static(), singleton);")
  1447. result.append("\t\t}")
  1448. result.append("\t}")
  1449. result.append("\treturn singleton;")
  1450. result.append("}")
  1451. result.append("")
  1452. result.append(f"{class_name}::~{class_name}() {{")
  1453. result.append("\tif (singleton == this) {")
  1454. result.append(f"\t\tClassDB::_unregister_engine_singleton({class_name}::get_class_static());")
  1455. result.append("\t\tsingleton = nullptr;")
  1456. result.append("\t}")
  1457. result.append("}")
  1458. result.append("")
  1459. if "methods" in class_api:
  1460. for method in class_api["methods"]:
  1461. if method["is_virtual"]:
  1462. # Will be done later
  1463. continue
  1464. vararg = "is_vararg" in method and method["is_vararg"]
  1465. # Method signature.
  1466. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  1467. result.append(method_signature + " {")
  1468. # Method body.
  1469. result.append(
  1470. 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"]});'
  1471. )
  1472. method_call = "\t"
  1473. has_return = "return_value" in method and method["return_value"]["type"] != "void"
  1474. if has_return:
  1475. result.append(
  1476. f'\tCHECK_METHOD_BIND_RET(_gde_method_bind, {get_default_value_for_type(method["return_value"]["type"])});'
  1477. )
  1478. else:
  1479. result.append("\tCHECK_METHOD_BIND(_gde_method_bind);")
  1480. is_ref = False
  1481. if not vararg:
  1482. if has_return:
  1483. return_type = method["return_value"]["type"]
  1484. meta_type = method["return_value"]["meta"] if "meta" in method["return_value"] else None
  1485. if is_enum(return_type):
  1486. if method["is_static"]:
  1487. method_call += f"return ({get_gdextension_type(correct_type(return_type, meta_type))})internal::_call_native_mb_ret<int64_t>(_gde_method_bind, nullptr"
  1488. else:
  1489. method_call += f"return ({get_gdextension_type(correct_type(return_type, meta_type))})internal::_call_native_mb_ret<int64_t>(_gde_method_bind, _owner"
  1490. elif is_pod_type(return_type) or is_variant(return_type):
  1491. if method["is_static"]:
  1492. method_call += f"return internal::_call_native_mb_ret<{get_gdextension_type(correct_type(return_type, meta_type))}>(_gde_method_bind, nullptr"
  1493. else:
  1494. method_call += f"return internal::_call_native_mb_ret<{get_gdextension_type(correct_type(return_type, meta_type))}>(_gde_method_bind, _owner"
  1495. elif is_refcounted(return_type):
  1496. if method["is_static"]:
  1497. method_call += f"return Ref<{return_type}>::_gde_internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, nullptr"
  1498. else:
  1499. method_call += f"return Ref<{return_type}>::_gde_internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, _owner"
  1500. is_ref = True
  1501. else:
  1502. if method["is_static"]:
  1503. method_call += (
  1504. f"return internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, nullptr"
  1505. )
  1506. else:
  1507. method_call += (
  1508. f"return internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, _owner"
  1509. )
  1510. else:
  1511. if method["is_static"]:
  1512. method_call += "internal::_call_native_mb_no_ret(_gde_method_bind, nullptr"
  1513. else:
  1514. method_call += "internal::_call_native_mb_no_ret(_gde_method_bind, _owner"
  1515. if "arguments" in method:
  1516. method_call += ", "
  1517. arguments = []
  1518. for argument in method["arguments"]:
  1519. (encode, arg_name) = get_encoded_arg(
  1520. argument["name"],
  1521. argument["type"],
  1522. argument["meta"] if "meta" in argument else None,
  1523. )
  1524. result += encode
  1525. arguments.append(arg_name)
  1526. method_call += ", ".join(arguments)
  1527. else: # vararg.
  1528. result.append("\tGDExtensionCallError error;")
  1529. result.append("\tVariant ret;")
  1530. method_call += "internal::gdextension_interface_object_method_bind_call(_gde_method_bind, _owner, reinterpret_cast<GDExtensionConstVariantPtr *>(args), arg_count, &ret, &error"
  1531. if is_ref:
  1532. method_call += ")" # Close Ref<> constructor.
  1533. method_call += ");"
  1534. result.append(method_call)
  1535. if vararg and ("return_value" in method and method["return_value"]["type"] != "void"):
  1536. return_type = get_enum_fullname(method["return_value"]["type"])
  1537. if return_type != "Variant":
  1538. result.append(f"\treturn VariantCaster<{return_type}>::cast(ret);")
  1539. else:
  1540. result.append("\treturn ret;")
  1541. result.append("}")
  1542. result.append("")
  1543. # Virtuals now.
  1544. for method in class_api["methods"]:
  1545. if not method["is_virtual"]:
  1546. continue
  1547. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  1548. method_signature += " {"
  1549. if "return_value" in method and correct_type(method["return_value"]["type"]) != "void":
  1550. result.append(method_signature)
  1551. result.append(f'\treturn {get_default_value_for_type(method["return_value"]["type"])};')
  1552. result.append("}")
  1553. else:
  1554. method_signature += "}"
  1555. result.append(method_signature)
  1556. result.append("")
  1557. result.append("")
  1558. result.append("} // namespace godot ")
  1559. return "\n".join(result)
  1560. def generate_global_constants(api, output_dir):
  1561. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  1562. source_gen_folder = Path(output_dir) / "src" / "classes"
  1563. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1564. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1565. # Generate header
  1566. header = []
  1567. add_header("global_constants.hpp", header)
  1568. header_filename = include_gen_folder / "global_constants.hpp"
  1569. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_HPP"
  1570. header.append(f"#ifndef {header_guard}")
  1571. header.append(f"#define {header_guard}")
  1572. header.append("")
  1573. header.append("#include <cstdint>")
  1574. header.append("")
  1575. header.append("namespace godot {")
  1576. header.append("")
  1577. for constant in api["global_constants"]:
  1578. header.append(f'\tconst int64_t {escape_identifier(constant["name"])} = {constant["value"]};')
  1579. header.append("")
  1580. for enum_def in api["global_enums"]:
  1581. if enum_def["name"].startswith("Variant."):
  1582. continue
  1583. if enum_def["is_bitfield"]:
  1584. header.append(f'\tenum {enum_def["name"]} : uint64_t {{')
  1585. else:
  1586. header.append(f'\tenum {enum_def["name"]} {{')
  1587. for value in enum_def["values"]:
  1588. header.append(f'\t\t{value["name"]} = {value["value"]},')
  1589. header.append("\t};")
  1590. header.append("")
  1591. header.append("} // namespace godot")
  1592. header.append("")
  1593. header.append(f"#endif // ! {header_guard}")
  1594. with header_filename.open("w+", encoding="utf-8") as header_file:
  1595. header_file.write("\n".join(header))
  1596. def generate_version_header(api, output_dir):
  1597. header = []
  1598. header_filename = "version.hpp"
  1599. add_header(header_filename, header)
  1600. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "core"
  1601. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1602. header_file_path = include_gen_folder / header_filename
  1603. header_guard = "GODOT_CPP_VERSION_HPP"
  1604. header.append(f"#ifndef {header_guard}")
  1605. header.append(f"#define {header_guard}")
  1606. header.append("")
  1607. header.append(f"#define GODOT_VERSION_MAJOR {api['header']['version_major']}")
  1608. header.append(f"#define GODOT_VERSION_MINOR {api['header']['version_minor']}")
  1609. header.append(f"#define GODOT_VERSION_PATCH {api['header']['version_patch']}")
  1610. header.append(f"#define GODOT_VERSION_STATUS \"{api['header']['version_status']}\"")
  1611. header.append(f"#define GODOT_VERSION_BUILD \"{api['header']['version_build']}\"")
  1612. header.append("")
  1613. header.append(f"#endif // {header_guard}")
  1614. header.append("")
  1615. with header_file_path.open("w+", encoding="utf-8") as header_file:
  1616. header_file.write("\n".join(header))
  1617. def generate_global_constant_binds(api, output_dir):
  1618. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  1619. source_gen_folder = Path(output_dir) / "src" / "classes"
  1620. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1621. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1622. # Generate header
  1623. header = []
  1624. add_header("global_constants_binds.hpp", header)
  1625. header_filename = include_gen_folder / "global_constants_binds.hpp"
  1626. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_BINDS_HPP"
  1627. header.append(f"#ifndef {header_guard}")
  1628. header.append(f"#define {header_guard}")
  1629. header.append("")
  1630. header.append("#include <godot_cpp/classes/global_constants.hpp>")
  1631. header.append("")
  1632. for enum_def in api["global_enums"]:
  1633. if enum_def["name"].startswith("Variant."):
  1634. continue
  1635. if enum_def["is_bitfield"]:
  1636. header.append(f'VARIANT_BITFIELD_CAST({enum_def["name"]});')
  1637. else:
  1638. header.append(f'VARIANT_ENUM_CAST({enum_def["name"]});')
  1639. # Variant::Type is not a global enum, but only one line, it is worth to place in this file instead of creating new file.
  1640. header.append(f"VARIANT_ENUM_CAST(godot::Variant::Type);")
  1641. header.append("")
  1642. header.append(f"#endif // ! {header_guard}")
  1643. with header_filename.open("w+", encoding="utf-8") as header_file:
  1644. header_file.write("\n".join(header))
  1645. def generate_utility_functions(api, output_dir):
  1646. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  1647. source_gen_folder = Path(output_dir) / "src" / "variant"
  1648. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1649. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1650. # Generate header.
  1651. header = []
  1652. add_header("utility_functions.hpp", header)
  1653. header_filename = include_gen_folder / "utility_functions.hpp"
  1654. header_guard = "GODOT_CPP_UTILITY_FUNCTIONS_HPP"
  1655. header.append(f"#ifndef {header_guard}")
  1656. header.append(f"#define {header_guard}")
  1657. header.append("")
  1658. header.append("#include <godot_cpp/variant/builtin_types.hpp>")
  1659. header.append("#include <godot_cpp/variant/variant.hpp>")
  1660. header.append("")
  1661. header.append("#include <array>")
  1662. header.append("")
  1663. header.append("namespace godot {")
  1664. header.append("")
  1665. header.append("class UtilityFunctions {")
  1666. header.append("public:")
  1667. for function in api["utility_functions"]:
  1668. vararg = "is_vararg" in function and function["is_vararg"]
  1669. function_signature = "\t"
  1670. function_signature += make_signature("UtilityFunctions", function, for_header=True, static=True)
  1671. header.append(function_signature + ";")
  1672. if vararg:
  1673. # Add templated version.
  1674. header += make_varargs_template(function, static=True)
  1675. header.append("};")
  1676. header.append("")
  1677. header.append("} // namespace godot")
  1678. header.append("")
  1679. header.append(f"#endif // ! {header_guard}")
  1680. with header_filename.open("w+", encoding="utf-8") as header_file:
  1681. header_file.write("\n".join(header))
  1682. # Generate source.
  1683. source = []
  1684. add_header("utility_functions.cpp", source)
  1685. source_filename = source_gen_folder / "utility_functions.cpp"
  1686. source.append("#include <godot_cpp/variant/utility_functions.hpp>")
  1687. source.append("")
  1688. source.append("#include <godot_cpp/core/error_macros.hpp>")
  1689. source.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  1690. source.append("")
  1691. source.append("namespace godot {")
  1692. source.append("")
  1693. for function in api["utility_functions"]:
  1694. vararg = "is_vararg" in function and function["is_vararg"]
  1695. function_signature = make_signature("UtilityFunctions", function)
  1696. source.append(function_signature + " {")
  1697. # Function body.
  1698. source.append(
  1699. f'\tstatic GDExtensionPtrUtilityFunction _gde_function = internal::gdextension_interface_variant_get_ptr_utility_function(StringName("{function["name"]}")._native_ptr(), {function["hash"]});'
  1700. )
  1701. has_return = "return_type" in function and function["return_type"] != "void"
  1702. if has_return:
  1703. source.append(
  1704. f'\tCHECK_METHOD_BIND_RET(_gde_function, {get_default_value_for_type(function["return_type"])});'
  1705. )
  1706. else:
  1707. source.append("\tCHECK_METHOD_BIND(_gde_function);")
  1708. function_call = "\t"
  1709. if not vararg:
  1710. if has_return:
  1711. function_call += "return "
  1712. if function["return_type"] == "Object":
  1713. function_call += "internal::_call_utility_ret_obj(_gde_function"
  1714. else:
  1715. function_call += f'internal::_call_utility_ret<{get_gdextension_type(correct_type(function["return_type"]))}>(_gde_function'
  1716. else:
  1717. function_call += "internal::_call_utility_no_ret(_gde_function"
  1718. if "arguments" in function:
  1719. function_call += ", "
  1720. arguments = []
  1721. for argument in function["arguments"]:
  1722. (encode, arg_name) = get_encoded_arg(
  1723. argument["name"],
  1724. argument["type"],
  1725. argument["meta"] if "meta" in argument else None,
  1726. )
  1727. source += encode
  1728. arguments.append(arg_name)
  1729. function_call += ", ".join(arguments)
  1730. else:
  1731. if has_return:
  1732. source.append(f'\t{get_gdextension_type(correct_type(function["return_type"]))} ret;')
  1733. else:
  1734. source.append("\tVariant ret;")
  1735. function_call += "_gde_function(&ret, reinterpret_cast<GDExtensionConstVariantPtr *>(args), arg_count"
  1736. function_call += ");"
  1737. source.append(function_call)
  1738. if vararg and has_return:
  1739. source.append("\treturn ret;")
  1740. source.append("}")
  1741. source.append("")
  1742. source.append("} // namespace godot")
  1743. with source_filename.open("w+", encoding="utf-8") as source_file:
  1744. source_file.write("\n".join(source))
  1745. # Helper functions.
  1746. def camel_to_snake(name):
  1747. name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
  1748. name = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name)
  1749. return name.replace("2_D", "2D").replace("3_D", "3D").lower()
  1750. def make_function_parameters(parameters, include_default=False, for_builtin=False, is_vararg=False):
  1751. signature = []
  1752. for index, par in enumerate(parameters):
  1753. parameter = type_for_parameter(par["type"], par["meta"] if "meta" in par else None)
  1754. parameter_name = escape_identifier(par["name"])
  1755. if len(parameter_name) == 0:
  1756. parameter_name = "arg_" + str(index + 1)
  1757. parameter += parameter_name
  1758. if include_default and "default_value" in par and (not for_builtin or par["type"] != "Variant"):
  1759. parameter += " = "
  1760. if is_enum(par["type"]):
  1761. parameter_type = correct_type(par["type"])
  1762. if parameter_type == "void":
  1763. parameter_type = "Variant"
  1764. parameter += f"({parameter_type})"
  1765. parameter += correct_default_value(par["default_value"], par["type"])
  1766. signature.append(parameter)
  1767. if is_vararg:
  1768. signature.append("const Args&... args")
  1769. return ", ".join(signature)
  1770. def type_for_parameter(type_name, meta=None):
  1771. if type_name == "void":
  1772. return "Variant "
  1773. elif is_pod_type(type_name) and type_name != "Nil" or is_enum(type_name):
  1774. return f"{correct_type(type_name, meta)} "
  1775. elif is_variant(type_name) or is_refcounted(type_name):
  1776. return f"const {correct_type(type_name)} &"
  1777. else:
  1778. return f"{correct_type(type_name)}"
  1779. def get_include_path(type_name):
  1780. base_dir = ""
  1781. if type_name == "Object":
  1782. base_dir = "core"
  1783. elif is_variant(type_name):
  1784. base_dir = "variant"
  1785. else:
  1786. base_dir = "classes"
  1787. return f"{base_dir}/{camel_to_snake(type_name)}.hpp"
  1788. def get_encoded_arg(arg_name, type_name, type_meta):
  1789. result = []
  1790. name = escape_identifier(arg_name)
  1791. arg_type = correct_type(type_name)
  1792. if is_pod_type(arg_type):
  1793. result.append(f"\t{get_gdextension_type(arg_type)} {name}_encoded;")
  1794. result.append(f"\tPtrToArg<{correct_type(type_name)}>::encode({name}, &{name}_encoded);")
  1795. name = f"&{name}_encoded"
  1796. elif is_engine_class(type_name):
  1797. # `{name}` is a C++ wrapper, it contains a field which is the object's pointer Godot expects.
  1798. # We have to check `nullptr` because when the caller sends `nullptr`, the wrapper itself will be null.
  1799. name = f"({name} != nullptr ? &{name}->_owner : nullptr)"
  1800. else:
  1801. name = f"&{name}"
  1802. return (result, name)
  1803. def make_signature(
  1804. class_name, function_data, for_header=False, use_template_get_node=True, for_builtin=False, static=False
  1805. ):
  1806. function_signature = ""
  1807. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1808. if for_header:
  1809. if "is_virtual" in function_data and function_data["is_virtual"]:
  1810. function_signature += "virtual "
  1811. if is_vararg:
  1812. function_signature += "private: "
  1813. if static:
  1814. function_signature += "static "
  1815. return_type = "void"
  1816. return_meta = None
  1817. if "return_type" in function_data:
  1818. return_type = correct_type(function_data["return_type"])
  1819. elif "return_value" in function_data:
  1820. return_type = function_data["return_value"]["type"]
  1821. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1822. function_signature += correct_type(
  1823. return_type,
  1824. return_meta,
  1825. )
  1826. if not function_signature.endswith("*"):
  1827. function_signature += " "
  1828. if not for_header:
  1829. function_signature += f"{class_name}::"
  1830. function_signature += escape_identifier(function_data["name"])
  1831. if is_vararg or (
  1832. not for_builtin and use_template_get_node and class_name == "Node" and function_data["name"] == "get_node"
  1833. ):
  1834. function_signature += "_internal"
  1835. function_signature += "("
  1836. arguments = function_data["arguments"] if "arguments" in function_data else []
  1837. if not is_vararg:
  1838. function_signature += make_function_parameters(arguments, for_header, for_builtin, is_vararg)
  1839. else:
  1840. function_signature += "const Variant **args, GDExtensionInt arg_count"
  1841. function_signature += ")"
  1842. if "is_static" in function_data and function_data["is_static"] and for_header:
  1843. function_signature = "static " + function_signature
  1844. elif "is_const" in function_data and function_data["is_const"]:
  1845. function_signature += " const"
  1846. return function_signature
  1847. def make_varargs_template(
  1848. function_data,
  1849. static=False,
  1850. class_befor_signature="",
  1851. with_public_declare=True,
  1852. with_indent=True,
  1853. for_builtin_classes=False,
  1854. ):
  1855. result = []
  1856. function_signature = ""
  1857. if with_public_declare:
  1858. function_signature = "public: "
  1859. function_signature += "template<typename... Args> "
  1860. if static:
  1861. function_signature += "static "
  1862. return_type = "void"
  1863. return_meta = None
  1864. if "return_type" in function_data:
  1865. return_type = correct_type(function_data["return_type"])
  1866. elif "return_value" in function_data:
  1867. return_type = function_data["return_value"]["type"]
  1868. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1869. function_signature += correct_type(
  1870. return_type,
  1871. return_meta,
  1872. )
  1873. if not function_signature.endswith("*"):
  1874. function_signature += " "
  1875. if len(class_befor_signature) > 0:
  1876. function_signature += class_befor_signature + "::"
  1877. function_signature += f'{escape_identifier(function_data["name"])}'
  1878. method_arguments = []
  1879. if "arguments" in function_data:
  1880. method_arguments = function_data["arguments"]
  1881. function_signature += "("
  1882. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1883. function_signature += make_function_parameters(method_arguments, include_default=True, is_vararg=is_vararg)
  1884. function_signature += ")"
  1885. if "is_const" in function_data and function_data["is_const"]:
  1886. function_signature += " const"
  1887. function_signature += " {"
  1888. result.append(function_signature)
  1889. args_array = f"\tstd::array<Variant, {len(method_arguments)} + sizeof...(Args)> variant_args {{ "
  1890. for argument in method_arguments:
  1891. if argument["type"] == "Variant":
  1892. args_array += argument["name"]
  1893. else:
  1894. args_array += f'Variant({argument["name"]})'
  1895. args_array += ", "
  1896. args_array += "Variant(args)... };"
  1897. result.append(args_array)
  1898. result.append(f"\tstd::array<const Variant *, {len(method_arguments)} + sizeof...(Args)> call_args;")
  1899. result.append("\tfor(size_t i = 0; i < variant_args.size(); i++) {")
  1900. result.append("\t\tcall_args[i] = &variant_args[i];")
  1901. result.append("\t}")
  1902. call_line = "\t"
  1903. if not for_builtin_classes:
  1904. if return_type != "void":
  1905. call_line += "return "
  1906. call_line += f'{escape_identifier(function_data["name"])}_internal(call_args.data(), variant_args.size());'
  1907. result.append(call_line)
  1908. else:
  1909. base = "(GDExtensionTypePtr)&opaque"
  1910. if static:
  1911. base = "nullptr"
  1912. ret = "nullptr"
  1913. if return_type != "void":
  1914. ret = "&ret"
  1915. result.append(f'\t{correct_type(function_data["return_type"])} ret;')
  1916. function_name = function_data["name"]
  1917. result.append(
  1918. f"\t_method_bindings.method_{function_name}({base}, reinterpret_cast<GDExtensionConstTypePtr *>(call_args.data()), {ret}, {len(method_arguments)} + sizeof...(Args));"
  1919. )
  1920. if return_type != "void":
  1921. result.append("\treturn ret;")
  1922. result.append("}")
  1923. if with_indent:
  1924. for i in range(len(result)):
  1925. result[i] = "\t" + result[i]
  1926. return result
  1927. # Engine idiosyncrasies.
  1928. def is_pod_type(type_name):
  1929. """
  1930. Those are types for which no class should be generated.
  1931. """
  1932. return type_name in [
  1933. "Nil",
  1934. "void",
  1935. "bool",
  1936. "real_t",
  1937. "float",
  1938. "double",
  1939. "int",
  1940. "int8_t",
  1941. "uint8_t",
  1942. "int16_t",
  1943. "uint16_t",
  1944. "int32_t",
  1945. "int64_t",
  1946. "uint32_t",
  1947. "uint64_t",
  1948. ]
  1949. def is_included_type(type_name):
  1950. # Types which we already have implemented.
  1951. return is_included_struct_type(type_name) or type_name in ["ObjectID"]
  1952. def is_included_struct_type(type_name):
  1953. # Struct types which we already have implemented.
  1954. return type_name in [
  1955. "AABB",
  1956. "Basis",
  1957. "Color",
  1958. "Plane",
  1959. "Projection",
  1960. "Quaternion",
  1961. "Rect2",
  1962. "Rect2i",
  1963. "Transform2D",
  1964. "Transform3D",
  1965. "Vector2",
  1966. "Vector2i",
  1967. "Vector3",
  1968. "Vector3i",
  1969. "Vector4",
  1970. "Vector4i",
  1971. ]
  1972. def is_packed_array(type_name):
  1973. """
  1974. Those are types for which we add our extra packed array functions.
  1975. """
  1976. return type_name in [
  1977. "PackedByteArray",
  1978. "PackedColorArray",
  1979. "PackedFloat32Array",
  1980. "PackedFloat64Array",
  1981. "PackedInt32Array",
  1982. "PackedInt64Array",
  1983. "PackedStringArray",
  1984. "PackedVector2Array",
  1985. "PackedVector3Array",
  1986. "PackedVector4Array",
  1987. ]
  1988. def needs_copy_instead_of_move(type_name):
  1989. """
  1990. Those are types which need initialised data or we'll get warning spam so need a copy instead of move.
  1991. """
  1992. return type_name in [
  1993. "Dictionary",
  1994. ]
  1995. def is_enum(type_name):
  1996. return type_name.startswith("enum::") or type_name.startswith("bitfield::")
  1997. def is_bitfield(type_name):
  1998. return type_name.startswith("bitfield::")
  1999. def get_enum_class(enum_name: str):
  2000. if "." in enum_name:
  2001. if is_bitfield(enum_name):
  2002. return enum_name.replace("bitfield::", "").split(".")[0]
  2003. else:
  2004. return enum_name.replace("enum::", "").split(".")[0]
  2005. else:
  2006. return "GlobalConstants"
  2007. def get_enum_fullname(enum_name: str):
  2008. if is_bitfield(enum_name):
  2009. return enum_name.replace("bitfield::", "BitField<") + ">"
  2010. else:
  2011. return enum_name.replace("enum::", "")
  2012. def get_enum_name(enum_name: str):
  2013. if is_bitfield(enum_name):
  2014. return enum_name.replace("bitfield::", "").split(".")[-1]
  2015. else:
  2016. return enum_name.replace("enum::", "").split(".")[-1]
  2017. def is_variant(type_name):
  2018. return (
  2019. type_name == "Variant"
  2020. or type_name in builtin_classes
  2021. or type_name == "Nil"
  2022. or type_name.startswith("typedarray::")
  2023. )
  2024. def is_engine_class(type_name):
  2025. global engine_classes
  2026. return type_name == "Object" or type_name in engine_classes
  2027. def is_struct_type(type_name):
  2028. # This is used to determine which keyword to use for forward declarations.
  2029. global native_structures
  2030. return is_included_struct_type(type_name) or type_name in native_structures
  2031. def is_refcounted(type_name):
  2032. return type_name in engine_classes and engine_classes[type_name]
  2033. def is_included(type_name, current_type):
  2034. """
  2035. Check if a builtin type should be included.
  2036. This removes Variant and POD types from inclusion, and the current type.
  2037. """
  2038. if type_name.startswith("typedarray::"):
  2039. return True
  2040. to_include = get_enum_class(type_name) if is_enum(type_name) else type_name
  2041. if to_include == current_type or is_pod_type(to_include):
  2042. return False
  2043. if to_include == "GlobalConstants" or to_include == "UtilityFunctions":
  2044. return True
  2045. return is_engine_class(to_include) or is_variant(to_include)
  2046. def correct_default_value(value, type_name):
  2047. value_map = {
  2048. "null": "nullptr",
  2049. '""': "String()",
  2050. '&""': "StringName()",
  2051. "[]": "Array()",
  2052. "{}": "Dictionary()",
  2053. "Transform2D(1, 0, 0, 1, 0, 0)": "Transform2D()", # Default transform.
  2054. "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)": "Transform3D()", # Default transform.
  2055. }
  2056. if value in value_map:
  2057. return value_map[value]
  2058. if value == "":
  2059. return f"{type_name}()"
  2060. if value.startswith("Array["):
  2061. return f"{{}}"
  2062. if value.startswith("&"):
  2063. return value[1::]
  2064. return value
  2065. def correct_typed_array(type_name):
  2066. if type_name.startswith("typedarray::"):
  2067. return type_name.replace("typedarray::", "TypedArray<") + ">"
  2068. return type_name
  2069. def correct_type(type_name, meta=None, use_alias=True):
  2070. type_conversion = {"float": "double", "int": "int64_t", "Nil": "Variant"}
  2071. if meta != None:
  2072. if "int" in meta:
  2073. return f"{meta}_t"
  2074. elif meta in type_conversion:
  2075. return type_conversion[type_name]
  2076. else:
  2077. return meta
  2078. if type_name in type_conversion:
  2079. return type_conversion[type_name]
  2080. if type_name.startswith("typedarray::"):
  2081. return type_name.replace("typedarray::", "TypedArray<") + ">"
  2082. if is_enum(type_name):
  2083. if is_bitfield(type_name):
  2084. base_class = get_enum_class(type_name)
  2085. if use_alias and base_class in CLASS_ALIASES:
  2086. base_class = CLASS_ALIASES[base_class]
  2087. if base_class == "GlobalConstants":
  2088. return f"BitField<{get_enum_name(type_name)}>"
  2089. return f"BitField<{base_class}::{get_enum_name(type_name)}>"
  2090. else:
  2091. base_class = get_enum_class(type_name)
  2092. if use_alias and base_class in CLASS_ALIASES:
  2093. base_class = CLASS_ALIASES[base_class]
  2094. if base_class == "GlobalConstants":
  2095. return f"{get_enum_name(type_name)}"
  2096. return f"{base_class}::{get_enum_name(type_name)}"
  2097. if is_refcounted(type_name):
  2098. return f"Ref<{type_name}>"
  2099. if type_name == "Object" or is_engine_class(type_name):
  2100. return f"{type_name} *"
  2101. if type_name.endswith("*"):
  2102. return f"{type_name[:-1]} *"
  2103. return type_name
  2104. def get_gdextension_type(type_name):
  2105. type_conversion_map = {
  2106. "bool": "int8_t",
  2107. "uint8_t": "int64_t",
  2108. "int8_t": "int64_t",
  2109. "uint16_t": "int64_t",
  2110. "int16_t": "int64_t",
  2111. "uint32_t": "int64_t",
  2112. "int32_t": "int64_t",
  2113. "int": "int64_t",
  2114. "float": "double",
  2115. }
  2116. if type_name.startswith("BitField<"):
  2117. return "int64_t"
  2118. if type_name in type_conversion_map:
  2119. return type_conversion_map[type_name]
  2120. return type_name
  2121. def escape_identifier(id):
  2122. cpp_keywords_map = {
  2123. "class": "_class",
  2124. "char": "_char",
  2125. "short": "_short",
  2126. "bool": "_bool",
  2127. "int": "_int",
  2128. "default": "_default",
  2129. "case": "_case",
  2130. "switch": "_switch",
  2131. "export": "_export",
  2132. "template": "_template",
  2133. "new": "new_",
  2134. "operator": "_operator",
  2135. "typeof": "type_of",
  2136. "typename": "type_name",
  2137. "enum": "_enum",
  2138. }
  2139. if id in cpp_keywords_map:
  2140. return cpp_keywords_map[id]
  2141. return id
  2142. def get_operator_id_name(op):
  2143. op_id_map = {
  2144. "==": "equal",
  2145. "!=": "not_equal",
  2146. "<": "less",
  2147. "<=": "less_equal",
  2148. ">": "greater",
  2149. ">=": "greater_equal",
  2150. "+": "add",
  2151. "-": "subtract",
  2152. "*": "multiply",
  2153. "/": "divide",
  2154. "unary-": "negate",
  2155. "unary+": "positive",
  2156. "%": "module",
  2157. "**": "power",
  2158. "<<": "shift_left",
  2159. ">>": "shift_right",
  2160. "&": "bit_and",
  2161. "|": "bit_or",
  2162. "^": "bit_xor",
  2163. "~": "bit_negate",
  2164. "and": "and",
  2165. "or": "or",
  2166. "xor": "xor",
  2167. "not": "not",
  2168. "and": "and",
  2169. "in": "in",
  2170. }
  2171. return op_id_map[op]
  2172. def get_default_value_for_type(type_name):
  2173. if type_name == "int":
  2174. return "0"
  2175. if type_name == "float":
  2176. return "0.0"
  2177. if type_name == "bool":
  2178. return "false"
  2179. if type_name.startswith("typedarray::"):
  2180. return f"{correct_type(type_name)}()"
  2181. if is_enum(type_name):
  2182. return f"{correct_type(type_name)}(0)"
  2183. if is_variant(type_name):
  2184. return f"{type_name}()"
  2185. if is_refcounted(type_name):
  2186. return f"Ref<{type_name}>()"
  2187. return "nullptr"
  2188. header = """\
  2189. /**************************************************************************/
  2190. /* $filename */
  2191. /**************************************************************************/
  2192. /* This file is part of: */
  2193. /* GODOT ENGINE */
  2194. /* https://godotengine.org */
  2195. /**************************************************************************/
  2196. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  2197. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  2198. /* */
  2199. /* Permission is hereby granted, free of charge, to any person obtaining */
  2200. /* a copy of this software and associated documentation files (the */
  2201. /* "Software"), to deal in the Software without restriction, including */
  2202. /* without limitation the rights to use, copy, modify, merge, publish, */
  2203. /* distribute, sublicense, and/or sell copies of the Software, and to */
  2204. /* permit persons to whom the Software is furnished to do so, subject to */
  2205. /* the following conditions: */
  2206. /* */
  2207. /* The above copyright notice and this permission notice shall be */
  2208. /* included in all copies or substantial portions of the Software. */
  2209. /* */
  2210. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  2211. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  2212. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  2213. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  2214. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  2215. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  2216. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  2217. /**************************************************************************/
  2218. """
  2219. def add_header(filename, lines):
  2220. desired_length = len(header.split("\n")[0])
  2221. pad_spaces = desired_length - 6 - len(filename)
  2222. for num, line in enumerate(header.split("\n")):
  2223. if num == 1:
  2224. new_line = f"/* {filename}{' ' * pad_spaces}*/"
  2225. lines.append(new_line)
  2226. else:
  2227. lines.append(line)
  2228. lines.append("// THIS FILE IS GENERATED. EDITS WILL BE LOST.")
  2229. lines.append("")