binding_generator.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. #!python
  2. import json
  3. # comment.
  4. classes = []
  5. def generate_bindings(path):
  6. global classes
  7. classes = json.load(open(path))
  8. icalls = set()
  9. for c in classes:
  10. # print c['name']
  11. used_classes = get_used_classes(c)
  12. header = generate_class_header(used_classes, c)
  13. impl = generate_class_implementation(icalls, used_classes, c)
  14. header_file = open("include/" + strip_name(c["name"]) + ".hpp", "w+")
  15. header_file.write(header)
  16. source_file = open("src/" + strip_name(c["name"]) + ".cpp", "w+")
  17. source_file.write(impl)
  18. icall_header_file = open("src/__icalls.hpp", "w+")
  19. icall_header_file.write(generate_icall_header(icalls))
  20. icall_source_file = open("src/__icalls.cpp", "w+")
  21. icall_source_file.write(generate_icall_implementation(icalls))
  22. def is_reference_type(t):
  23. for c in classes:
  24. if c['name'] != t:
  25. continue
  26. if c['is_reference']:
  27. return True
  28. return False
  29. def make_gdnative_type(t):
  30. if is_enum(t):
  31. return remove_enum_prefix(t) + " "
  32. elif is_class_type(t):
  33. if is_reference_type(t):
  34. return "Ref<" + strip_name(t) + "> "
  35. else:
  36. return strip_name(t) + " *"
  37. else:
  38. if t == "int":
  39. return "int64_t "
  40. if t == "float" or t == "real":
  41. return "double "
  42. return strip_name(t) + " "
  43. def generate_class_header(used_classes, c):
  44. source = []
  45. source.append("#ifndef GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  46. source.append("#define GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  47. source.append("")
  48. source.append("")
  49. source.append("#include <gdnative_api_struct.gen.h>")
  50. source.append("#include <stdint.h>")
  51. source.append("")
  52. source.append("#include <core/CoreTypes.hpp>")
  53. class_name = strip_name(c["name"])
  54. # Ref<T> is not included in object.h in Godot either,
  55. # so don't include it here because it's not needed
  56. if class_name != "Object" and class_name != "Reference":
  57. source.append("#include <core/Ref.hpp>")
  58. included = []
  59. for used_class in used_classes:
  60. if is_enum(used_class) and is_nested_type(used_class):
  61. used_class_name = remove_enum_prefix(extract_nested_type(used_class))
  62. if used_class_name not in included:
  63. included.append(used_class_name)
  64. source.append("#include \"" + used_class_name + ".hpp\"")
  65. elif is_enum(used_class) and is_nested_type(used_class) and not is_nested_type(used_class, class_name):
  66. used_class_name = remove_enum_prefix(used_class)
  67. if used_class_name not in included:
  68. included.append(used_class_name)
  69. source.append("#include \"" + used_class_name + ".hpp\"")
  70. source.append("")
  71. if c["base_class"] != "":
  72. source.append("#include \"" + strip_name(c["base_class"]) + ".hpp\"")
  73. source.append("namespace godot {")
  74. source.append("")
  75. for used_type in used_classes:
  76. if is_enum(used_type) or is_nested_type(used_type, class_name):
  77. continue
  78. else:
  79. source.append("class " + strip_name(used_type) + ";")
  80. source.append("")
  81. vararg_templates = ""
  82. # generate the class definition here
  83. source.append("class " + class_name + ("" if c["base_class"] == "" else (" : public " + strip_name(c["base_class"])) ) + " {")
  84. source.append("public:")
  85. source.append("")
  86. # ___get_class_name
  87. source.append("\tstatic inline char *___get_class_name() { return (char *) \"" + strip_name(c["name"]) + "\"; }")
  88. source.append("\tstatic inline Object *___get_from_variant(Variant a) { return (Object *) a; }")
  89. enum_values = []
  90. source.append("\n\t// enums")
  91. for enum in c["enums"]:
  92. source.append("\tenum " + strip_name(enum["name"]) + " {")
  93. for value in enum["values"]:
  94. source.append("\t\t" + remove_nested_type_prefix(value) + " = " + str(enum["values"][value]) + ",")
  95. enum_values.append(value)
  96. source.append("\t};")
  97. source.append("\n\t// constants")
  98. for name in c["constants"]:
  99. if name not in enum_values:
  100. source.append("\tconst static int " + name + " = " + str(c["constants"][name]) + ";")
  101. if c["instanciable"]:
  102. source.append("\tstatic void *operator new(size_t);")
  103. source.append("\tstatic void operator delete(void *);")
  104. source.append("\n\t// methods")
  105. for method in c["methods"]:
  106. method_signature = ""
  107. method_signature += "static " if c["singleton"] else ""
  108. method_signature += make_gdnative_type(method["return_type"])
  109. method_name = escape_cpp(method["name"])
  110. method_signature += method_name + "("
  111. has_default_argument = False
  112. method_arguments = ""
  113. for i, argument in enumerate(method["arguments"]):
  114. method_signature += "const " + make_gdnative_type(argument["type"])
  115. argument_name = escape_cpp(argument["name"])
  116. method_signature += argument_name
  117. method_arguments += argument_name
  118. # default arguments
  119. def escape_default_arg(_type, default_value):
  120. if _type == "Color":
  121. return "Color(" + default_value + ")"
  122. if _type == "bool" or _type == "int":
  123. return default_value.lower()
  124. if _type == "Array":
  125. return "Array()"
  126. if _type in ["PoolVector2Array", "PoolStringArray", "PoolVector3Array", "PoolColorArray"]:
  127. return _type + "()"
  128. if _type == "Vector2":
  129. return "Vector2" + default_value
  130. if _type == "Vector3":
  131. return "Vector3" + default_value
  132. if _type == "Transform":
  133. return "Transform()"
  134. if _type == "Transform2D":
  135. return "Transform2D()"
  136. if _type == "Rect2":
  137. return "Rect2" + default_value
  138. if _type == "Variant":
  139. return "Variant()" if default_value == "Null" else default_value
  140. if _type == "String":
  141. return "\"" + default_value + "\""
  142. if _type == "RID":
  143. return "RID()"
  144. if default_value == "Null" or default_value == "[Object:null]":
  145. return "nullptr"
  146. return default_value
  147. if argument["has_default_value"] or has_default_argument:
  148. method_signature += " = " + escape_default_arg(argument["type"], argument["default_value"])
  149. has_default_argument = True
  150. if i != len(method["arguments"]) - 1:
  151. method_signature += ", "
  152. method_arguments += ","
  153. if method["has_varargs"]:
  154. if len(method["arguments"]) > 0:
  155. method_signature += ", "
  156. method_arguments += ", "
  157. vararg_templates += "\ttemplate <class... Args> " + method_signature + "Args... args){\n\t\treturn " + method_name + "(" + method_arguments + "Array::make(args...));\n\t}\n"""
  158. method_signature += "const Array& __var_args = Array()"
  159. method_signature += ")" + (" const" if method["is_const"] and not c["singleton"] else "")
  160. source.append("\t" + method_signature + ";")
  161. source.append(vararg_templates)
  162. source.append("};")
  163. source.append("")
  164. source.append("}")
  165. source.append("")
  166. source.append("#endif")
  167. return "\n".join(source)
  168. def generate_class_implementation(icalls, used_classes, c):
  169. class_name = strip_name(c["name"])
  170. source = []
  171. source.append("#include \"" + class_name + ".hpp\"")
  172. source.append("")
  173. source.append("")
  174. source.append("#include <core/GodotGlobal.hpp>")
  175. source.append("#include <core/CoreTypes.hpp>")
  176. source.append("#include <core/Ref.hpp>")
  177. source.append("#include <core/Godot.hpp>")
  178. source.append("")
  179. source.append("#include \"__icalls.hpp\"")
  180. source.append("")
  181. source.append("")
  182. for used_class in used_classes:
  183. if is_enum(used_class):
  184. continue
  185. else:
  186. source.append("#include \"" + strip_name(used_class) + ".hpp\"")
  187. source.append("")
  188. source.append("")
  189. source.append("namespace godot {")
  190. core_object_name = ("___static_object_" + strip_name(c["name"])) if c["singleton"] else "this"
  191. source.append("")
  192. source.append("")
  193. if c["singleton"]:
  194. source.append("static godot_object *" + core_object_name + ";")
  195. source.append("")
  196. source.append("")
  197. # FIXME Test if inlining has a huge impact on binary size
  198. source.append("static inline void ___singleton_init()")
  199. source.append("{")
  200. source.append("\tif (" + core_object_name + " == nullptr) {")
  201. source.append("\t\t" + core_object_name + " = godot::api->godot_global_get_singleton((char *) \"" + strip_name(c["name"]) + "\");")
  202. source.append("\t}")
  203. source.append("}")
  204. source.append("")
  205. source.append("")
  206. if c["instanciable"]:
  207. source.append("void *" + strip_name(c["name"]) + "::operator new(size_t)")
  208. source.append("{")
  209. source.append("\treturn godot::api->godot_get_class_constructor((char *)\"" + c["name"] + "\")();")
  210. source.append("}")
  211. source.append("void " + strip_name(c["name"]) + "::operator delete(void *ptr)")
  212. source.append("{")
  213. source.append("\tgodot::api->godot_object_destroy((godot_object *)ptr);")
  214. source.append("}")
  215. for method in c["methods"]:
  216. method_signature = ""
  217. method_signature += make_gdnative_type(method["return_type"])
  218. method_signature += strip_name(c["name"]) + "::" + escape_cpp(method["name"]) + "("
  219. for i, argument in enumerate(method["arguments"]):
  220. method_signature += "const " + make_gdnative_type(argument["type"])
  221. method_signature += escape_cpp(argument["name"])
  222. if i != len(method["arguments"]) - 1:
  223. method_signature += ", "
  224. if method["has_varargs"]:
  225. if len(method["arguments"]) > 0:
  226. method_signature += ", "
  227. method_signature += "const Array& __var_args"
  228. method_signature += ")" + (" const" if method["is_const"] and not c["singleton"] else "")
  229. source.append(method_signature + " {")
  230. if c["singleton"]:
  231. source.append("\t___singleton_init();")
  232. source.append("\tstatic godot_method_bind *mb = nullptr;")
  233. source.append("\tif (mb == nullptr) {")
  234. source.append("\t\tmb = godot::api->godot_method_bind_get_method(\"" + c["name"] +"\", \"" + method["name"] + "\");")
  235. source.append("\t}")
  236. return_statement = ""
  237. if method["return_type"] != "void":
  238. if is_class_type(method["return_type"]):
  239. if is_enum(method["return_type"]):
  240. return_statement += "return (" + remove_enum_prefix(method["return_type"]) + ") "
  241. elif is_reference_type(method["return_type"]):
  242. return_statement += "return Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor(";
  243. else:
  244. return_statement += "return " + ("(" + strip_name(method["return_type"]) + " *) " if is_class_type(method["return_type"]) else "")
  245. else:
  246. return_statement += "return "
  247. def get_icall_type_name(name):
  248. if is_enum(name):
  249. return "int"
  250. if is_class_type(name):
  251. return "Object"
  252. return name
  253. if method["has_varargs"]:
  254. if len(method["arguments"]) != 0:
  255. source.append("\tVariant __given_args[" + str(len(method["arguments"])) + "];")
  256. for i, argument in enumerate(method["arguments"]):
  257. source.append("\tgodot::api->godot_variant_new_nil((godot_variant *) &__given_args[" + str(i) + "]);")
  258. source.append("")
  259. for i, argument in enumerate(method["arguments"]):
  260. source.append("\t__given_args[" + str(i) + "] = " + escape_cpp(argument["name"]) + ";")
  261. source.append("")
  262. size = ""
  263. if method["has_varargs"]:
  264. size = "(__var_args.size() + " + str(len(method["arguments"])) + ")"
  265. else:
  266. size = "(" + str(len(method["arguments"])) + ")"
  267. source.append("\tgodot_variant **__args = (godot_variant **) alloca(sizeof(godot_variant *) * " + size + ");")
  268. source.append("")
  269. for i, argument in enumerate(method["arguments"]):
  270. source.append("\t__args[" + str(i) + "] = (godot_variant *) &__given_args[" + str(i) + "];")
  271. source.append("")
  272. if method["has_varargs"]:
  273. source.append("\tfor (int i = 0; i < __var_args.size(); i++) {")
  274. source.append("\t\t__args[i + " + str(len(method["arguments"])) + "] = (godot_variant *) &((Array &) __var_args)[i];")
  275. source.append("\t}")
  276. source.append("")
  277. source.append("\tVariant __result;")
  278. source.append("\t*(godot_variant *) &__result = godot::api->godot_method_bind_call(mb, (godot_object *) " + core_object_name + ", (const godot_variant **) __args, " + size + ", nullptr);")
  279. source.append("")
  280. for i, argument in enumerate(method["arguments"]):
  281. source.append("\tgodot::api->godot_variant_destroy((godot_variant *) &__given_args[" + str(i) + "]);")
  282. source.append("")
  283. if method["return_type"] != "void":
  284. cast = ""
  285. if is_class_type(method["return_type"]):
  286. if is_reference_type(method["return_type"]):
  287. cast += "Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor(__result);"
  288. else:
  289. cast += "(" + strip_name(method["return_type"]) + " *) (Object *) __result;"
  290. else:
  291. cast += "__result;"
  292. source.append("\treturn " + cast)
  293. else:
  294. args = []
  295. for arg in method["arguments"]:
  296. args.append(get_icall_type_name(arg["type"]))
  297. icall_ret_type = get_icall_type_name(method["return_type"])
  298. icall_sig = tuple((icall_ret_type, tuple(args)))
  299. icalls.add(icall_sig)
  300. icall_name = get_icall_name(icall_sig)
  301. return_statement += icall_name + "(mb, (godot_object *) " + core_object_name
  302. for arg in method["arguments"]:
  303. return_statement += ", " + escape_cpp(arg["name"]) + (".ptr()" if is_reference_type(arg["type"]) else "")
  304. return_statement += ")"
  305. source.append("\t" + return_statement + (")" if is_reference_type(method["return_type"]) else "") + ";")
  306. source.append("}")
  307. source.append("")
  308. source.append("}")
  309. return "\n".join(source)
  310. def generate_icall_header(icalls):
  311. source = []
  312. source.append("#ifndef GODOT_CPP__ICALLS_HPP")
  313. source.append("#define GODOT_CPP__ICALLS_HPP")
  314. source.append("")
  315. source.append("#include <gdnative_api_struct.gen.h>")
  316. source.append("#include <stdint.h>")
  317. source.append("")
  318. source.append("#include <core/CoreTypes.hpp>")
  319. source.append("#include \"Object.hpp\"")
  320. source.append("")
  321. source.append("")
  322. source.append("namespace godot {")
  323. source.append("")
  324. for icall in icalls:
  325. ret_type = icall[0]
  326. args = icall[1]
  327. method_signature = ""
  328. method_signature += return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, godot_object *inst"
  329. for arg in args:
  330. method_signature += ", const "
  331. if is_core_type(arg):
  332. method_signature += arg + "&"
  333. elif arg == "float":
  334. method_signature += "double "
  335. elif is_primitive(arg):
  336. method_signature += arg
  337. else:
  338. method_signature += "Object *"
  339. method_signature += ");"
  340. source.append(method_signature)
  341. source.append("")
  342. source.append("}")
  343. source.append("")
  344. source.append("#endif")
  345. return "\n".join(source)
  346. def generate_icall_implementation(icalls):
  347. source = []
  348. source.append("#include \"__icalls.hpp\"")
  349. source.append("")
  350. source.append("#include <gdnative_api_struct.gen.h>")
  351. source.append("#include <stdint.h>")
  352. source.append("")
  353. source.append("#include <core/GodotGlobal.hpp>")
  354. source.append("#include <core/CoreTypes.hpp>")
  355. source.append("#include \"Object.hpp\"")
  356. source.append("")
  357. source.append("")
  358. source.append("namespace godot {")
  359. source.append("")
  360. for icall in icalls:
  361. ret_type = icall[0]
  362. args = icall[1]
  363. method_signature = ""
  364. method_signature += return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, godot_object *inst"
  365. for i, arg in enumerate(args):
  366. method_signature += ", const "
  367. if is_core_type(arg):
  368. method_signature += arg + "& "
  369. elif arg == "float":
  370. method_signature += "double "
  371. elif is_primitive(arg):
  372. method_signature += arg + " "
  373. else:
  374. method_signature += "Object *"
  375. method_signature += "arg" + str(i)
  376. method_signature += ")"
  377. source.append(method_signature + " {")
  378. if ret_type != "void":
  379. source.append("\t" + return_type(ret_type) + "ret;")
  380. if is_class_type(ret_type):
  381. source.append("\tret = nullptr;")
  382. source.append("\tconst void *args[" + ("1" if len(args) == 0 else "") + "] = {")
  383. for i, arg in enumerate(args):
  384. wrapped_argument = "\t\t"
  385. if is_primitive(arg) or is_core_type(arg):
  386. wrapped_argument += "(void *) &arg" + str(i)
  387. else:
  388. wrapped_argument += "(void *) arg" + str(i)
  389. wrapped_argument += ","
  390. source.append(wrapped_argument)
  391. source.append("\t};")
  392. source.append("")
  393. source.append("\tgodot::api->godot_method_bind_ptrcall(mb, inst, args, " + ("nullptr" if ret_type == "void" else "&ret") + ");")
  394. if ret_type != "void":
  395. source.append("\treturn ret;")
  396. source.append("}")
  397. source.append("}")
  398. source.append("")
  399. return "\n".join(source)
  400. def return_type(t):
  401. if is_class_type(t):
  402. return "Object *"
  403. if t == "int":
  404. return "int64_t "
  405. if t == "float" or t == "real":
  406. return "double "
  407. return t + " "
  408. def get_icall_name(sig):
  409. ret_type = sig[0]
  410. args = sig[1]
  411. name = "___godot_icall_"
  412. name += strip_name(ret_type)
  413. for arg in args:
  414. name += "_" + strip_name(arg)
  415. return name
  416. def get_used_classes(c):
  417. classes = []
  418. for method in c["methods"]:
  419. if is_class_type(method["return_type"]) and not (method["return_type"] in classes):
  420. classes.append(method["return_type"])
  421. for arg in method["arguments"]:
  422. if is_class_type(arg["type"]) and not (arg["type"] in classes):
  423. classes.append(arg["type"])
  424. return classes
  425. def strip_name(name):
  426. if name[0] == '_':
  427. return name[1:]
  428. return name
  429. def extract_nested_type(nested_type):
  430. return strip_name(nested_type[:nested_type.find("::")])
  431. def remove_nested_type_prefix(name):
  432. return name if name.find("::") == -1 else strip_name(name[name.find("::") + 2:])
  433. def remove_enum_prefix(name):
  434. return strip_name(name[name.find("enum.") + 5:])
  435. def is_nested_type(name, type = ""):
  436. return name.find(type + "::") != -1
  437. def is_enum(name):
  438. return name.find("enum.") == 0
  439. def is_class_type(name):
  440. return not is_core_type(name) and not is_primitive(name)
  441. def is_core_type(name):
  442. core_types = ["Array",
  443. "Basis",
  444. "Color",
  445. "Dictionary",
  446. "Error",
  447. "NodePath",
  448. "Plane",
  449. "PoolByteArray",
  450. "PoolIntArray",
  451. "PoolRealArray",
  452. "PoolStringArray",
  453. "PoolVector2Array",
  454. "PoolVector3Array",
  455. "PoolColorArray",
  456. "Quat",
  457. "Rect2",
  458. "AABB",
  459. "RID",
  460. "String",
  461. "Transform",
  462. "Transform2D",
  463. "Variant",
  464. "Vector2",
  465. "Vector3"]
  466. return name in core_types
  467. def is_primitive(name):
  468. core_types = ["int", "bool", "real", "float", "void"]
  469. return name in core_types
  470. def escape_cpp(name):
  471. escapes = {
  472. "class": "_class",
  473. "char": "_char",
  474. "short": "_short",
  475. "bool": "_bool",
  476. "int": "_int",
  477. "default": "_default",
  478. "case": "_case",
  479. "switch": "_switch",
  480. "export": "_export",
  481. "template": "_template",
  482. "new": "new_",
  483. "operator": "_operator"
  484. }
  485. if name in escapes:
  486. return escapes[name]
  487. return name