godotcpp.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import os, sys, platform
  2. from SCons.Variables import EnumVariable, PathVariable, BoolVariable
  3. from SCons.Tool import Tool
  4. from SCons.Builder import Builder
  5. from SCons.Errors import UserError
  6. from binding_generator import scons_generate_bindings, scons_emit_files
  7. def add_sources(sources, dir, extension):
  8. for f in os.listdir(dir):
  9. if f.endswith("." + extension):
  10. sources.append(dir + "/" + f)
  11. def normalize_path(val, env):
  12. return val if os.path.isabs(val) else os.path.join(env.Dir("#").abspath, val)
  13. def validate_file(key, val, env):
  14. if not os.path.isfile(normalize_path(val, env)):
  15. raise UserError("'%s' is not a file: %s" % (key, val))
  16. def validate_dir(key, val, env):
  17. if not os.path.isdir(normalize_path(val, env)):
  18. raise UserError("'%s' is not a directory: %s" % (key, val))
  19. def validate_parent_dir(key, val, env):
  20. if not os.path.isdir(normalize_path(os.path.dirname(val), env)):
  21. raise UserError("'%s' is not a directory: %s" % (key, os.path.dirname(val)))
  22. platforms = ("linux", "macos", "windows", "android", "ios", "web")
  23. # CPU architecture options.
  24. architecture_array = [
  25. "",
  26. "universal",
  27. "x86_32",
  28. "x86_64",
  29. "arm32",
  30. "arm64",
  31. "rv64",
  32. "ppc32",
  33. "ppc64",
  34. "wasm32",
  35. ]
  36. architecture_aliases = {
  37. "x64": "x86_64",
  38. "amd64": "x86_64",
  39. "armv7": "arm32",
  40. "armv8": "arm64",
  41. "arm64v8": "arm64",
  42. "aarch64": "arm64",
  43. "rv": "rv64",
  44. "riscv": "rv64",
  45. "riscv64": "rv64",
  46. "ppcle": "ppc32",
  47. "ppc": "ppc32",
  48. "ppc64le": "ppc64",
  49. }
  50. def exists(env):
  51. return True
  52. def options(opts, env):
  53. # Try to detect the host platform automatically.
  54. # This is used if no `platform` argument is passed
  55. if sys.platform.startswith("linux"):
  56. default_platform = "linux"
  57. elif sys.platform == "darwin":
  58. default_platform = "macos"
  59. elif sys.platform == "win32" or sys.platform == "msys":
  60. default_platform = "windows"
  61. elif ARGUMENTS.get("platform", ""):
  62. default_platform = ARGUMENTS.get("platform")
  63. else:
  64. raise ValueError("Could not detect platform automatically, please specify with platform=<platform>")
  65. opts.Add(
  66. EnumVariable(
  67. key="platform",
  68. help="Target platform",
  69. default=env.get("platform", default_platform),
  70. allowed_values=platforms,
  71. ignorecase=2,
  72. )
  73. )
  74. # Editor and template_debug are compatible (i.e. you can use the same binary for Godot editor builds and Godot debug templates).
  75. # Godot release templates are only compatible with "template_release" builds.
  76. # For this reason, we default to template_debug builds, unlike Godot which defaults to editor builds.
  77. opts.Add(
  78. EnumVariable(
  79. key="target",
  80. help="Compilation target",
  81. default=env.get("target", "template_debug"),
  82. allowed_values=("editor", "template_release", "template_debug"),
  83. )
  84. )
  85. opts.Add(
  86. PathVariable(
  87. key="gdextension_dir",
  88. help="Path to a custom directory containing GDExtension interface header and API JSON file",
  89. default=env.get("gdextension_dir", None),
  90. validator=validate_dir,
  91. )
  92. )
  93. opts.Add(
  94. PathVariable(
  95. key="custom_api_file",
  96. help="Path to a custom GDExtension API JSON file (takes precedence over `gdextension_dir`)",
  97. default=env.get("custom_api_file", None),
  98. validator=validate_file,
  99. )
  100. )
  101. opts.Add(
  102. BoolVariable(
  103. key="generate_bindings",
  104. help="Force GDExtension API bindings generation. Auto-detected by default.",
  105. default=env.get("generate_bindings", False),
  106. )
  107. )
  108. opts.Add(
  109. BoolVariable(
  110. key="generate_template_get_node",
  111. help="Generate a template version of the Node class's get_node.",
  112. default=env.get("generate_template_get_node", True),
  113. )
  114. )
  115. opts.Add(
  116. BoolVariable(
  117. key="build_library",
  118. help="Build the godot-cpp library.",
  119. default=env.get("build_library", True),
  120. )
  121. )
  122. opts.Add(
  123. EnumVariable(
  124. key="precision",
  125. help="Set the floating-point precision level",
  126. default=env.get("precision", "single"),
  127. allowed_values=("single", "double"),
  128. )
  129. )
  130. opts.Add(
  131. EnumVariable(
  132. key="arch",
  133. help="CPU architecture",
  134. default=env.get("arch", ""),
  135. allowed_values=architecture_array,
  136. map=architecture_aliases,
  137. )
  138. )
  139. # compiledb
  140. opts.Add(
  141. BoolVariable(
  142. key="compiledb",
  143. help="Generate compilation DB (`compile_commands.json`) for external tools",
  144. default=env.get("compiledb", False),
  145. )
  146. )
  147. opts.Add(
  148. PathVariable(
  149. key="compiledb_file",
  150. help="Path to a custom `compile_commands.json` file",
  151. default=env.get("compiledb_file", "compile_commands.json"),
  152. validator=validate_parent_dir,
  153. )
  154. )
  155. opts.Add(
  156. BoolVariable(
  157. key="use_hot_reload",
  158. help="Enable the extra accounting required to support hot reload.",
  159. default=env.get("use_hot_reload", None),
  160. )
  161. )
  162. opts.Add(
  163. BoolVariable(
  164. "disable_exceptions", "Force disabling exception handling code", default=env.get("disable_exceptions", True)
  165. )
  166. )
  167. opts.Add(
  168. EnumVariable(
  169. key="symbols_visibility",
  170. help="Symbols visibility on GNU platforms. Use 'auto' to apply the default value.",
  171. default=env.get("symbols_visibility", "hidden"),
  172. allowed_values=["auto", "visible", "hidden"],
  173. )
  174. )
  175. # Add platform options
  176. for pl in platforms:
  177. tool = Tool(pl, toolpath=["tools"])
  178. if hasattr(tool, "options"):
  179. tool.options(opts)
  180. # Targets flags tool (optimizations, debug symbols)
  181. target_tool = Tool("targets", toolpath=["tools"])
  182. target_tool.options(opts)
  183. def generate(env):
  184. # Default num_jobs to local cpu count if not user specified.
  185. # SCons has a peculiarity where user-specified options won't be overridden
  186. # by SetOption, so we can rely on this to know if we should use our default.
  187. initial_num_jobs = env.GetOption("num_jobs")
  188. altered_num_jobs = initial_num_jobs + 1
  189. env.SetOption("num_jobs", altered_num_jobs)
  190. if env.GetOption("num_jobs") == altered_num_jobs:
  191. cpu_count = os.cpu_count()
  192. if cpu_count is None:
  193. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  194. else:
  195. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  196. print(
  197. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  198. % (cpu_count, safer_cpu_count)
  199. )
  200. env.SetOption("num_jobs", safer_cpu_count)
  201. # Process CPU architecture argument.
  202. if env["arch"] == "":
  203. # No architecture specified. Default to arm64 if building for Android,
  204. # universal if building for macOS or iOS, wasm32 if building for web,
  205. # otherwise default to the host architecture.
  206. if env["platform"] in ["macos", "ios"]:
  207. env["arch"] = "universal"
  208. elif env["platform"] == "android":
  209. env["arch"] = "arm64"
  210. elif env["platform"] == "web":
  211. env["arch"] = "wasm32"
  212. else:
  213. host_machine = platform.machine().lower()
  214. if host_machine in architecture_array:
  215. env["arch"] = host_machine
  216. elif host_machine in architecture_aliases.keys():
  217. env["arch"] = architecture_aliases[host_machine]
  218. elif "86" in host_machine:
  219. # Catches x86, i386, i486, i586, i686, etc.
  220. env["arch"] = "x86_32"
  221. else:
  222. print("Unsupported CPU architecture: " + host_machine)
  223. env.Exit(1)
  224. print("Building for architecture " + env["arch"] + " on platform " + env["platform"])
  225. if env.get("use_hot_reload") is None:
  226. env["use_hot_reload"] = env["target"] != "template_release"
  227. if env["use_hot_reload"]:
  228. env.Append(CPPDEFINES=["HOT_RELOAD_ENABLED"])
  229. tool = Tool(env["platform"], toolpath=["tools"])
  230. if tool is None or not tool.exists(env):
  231. raise ValueError("Required toolchain not found for platform " + env["platform"])
  232. tool.generate(env)
  233. target_tool = Tool("targets", toolpath=["tools"])
  234. target_tool.generate(env)
  235. # Disable exception handling. Godot doesn't use exceptions anywhere, and this
  236. # saves around 20% of binary size and very significant build time.
  237. if env["disable_exceptions"]:
  238. if env.get("is_msvc", False):
  239. env.Append(CPPDEFINES=[("_HAS_EXCEPTIONS", 0)])
  240. else:
  241. env.Append(CXXFLAGS=["-fno-exceptions"])
  242. elif env.get("is_msvc", False):
  243. env.Append(CXXFLAGS=["/EHsc"])
  244. if not env.get("is_msvc", False):
  245. if env["symbols_visibility"] == "visible":
  246. env.Append(CCFLAGS=["-fvisibility=default"])
  247. env.Append(LINKFLAGS=["-fvisibility=default"])
  248. elif env["symbols_visibility"] == "hidden":
  249. env.Append(CCFLAGS=["-fvisibility=hidden"])
  250. env.Append(LINKFLAGS=["-fvisibility=hidden"])
  251. # Require C++17
  252. if env.get("is_msvc", False):
  253. env.Append(CXXFLAGS=["/std:c++17"])
  254. else:
  255. env.Append(CXXFLAGS=["-std=c++17"])
  256. if env["precision"] == "double":
  257. env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  258. # Suffix
  259. suffix = ".{}.{}".format(env["platform"], env["target"])
  260. if env.dev_build:
  261. suffix += ".dev"
  262. if env["precision"] == "double":
  263. suffix += ".double"
  264. suffix += "." + env["arch"]
  265. if env["ios_simulator"]:
  266. suffix += ".simulator"
  267. env["suffix"] = suffix # Exposed when included from another project
  268. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  269. # compile_commands.json
  270. env.Tool("compilation_db")
  271. env.Alias("compiledb", env.CompilationDatabase(normalize_path(env["compiledb_file"], env)))
  272. # Builders
  273. env.Append(BUILDERS={"GodotCPPBindings": Builder(action=scons_generate_bindings, emitter=scons_emit_files)})
  274. env.AddMethod(_godot_cpp, "GodotCPP")
  275. def _godot_cpp(env):
  276. extension_dir = normalize_path(env.get("gdextension_dir", env.Dir("gdextension").abspath), env)
  277. api_file = normalize_path(env.get("custom_api_file", env.File(extension_dir + "/extension_api.json").abspath), env)
  278. bindings = env.GodotCPPBindings(
  279. env.Dir("."),
  280. [
  281. api_file,
  282. os.path.join(extension_dir, "gdextension_interface.h"),
  283. "binding_generator.py",
  284. ],
  285. )
  286. # Forces bindings regeneration.
  287. if env["generate_bindings"]:
  288. env.AlwaysBuild(bindings)
  289. env.NoCache(bindings)
  290. # Sources to compile
  291. sources = []
  292. add_sources(sources, "src", "cpp")
  293. add_sources(sources, "src/classes", "cpp")
  294. add_sources(sources, "src/core", "cpp")
  295. add_sources(sources, "src/variant", "cpp")
  296. sources.extend([f for f in bindings if str(f).endswith(".cpp")])
  297. # Includes
  298. env.AppendUnique(CPPPATH=[env.Dir(d) for d in [extension_dir, "include", "gen/include"]])
  299. library = None
  300. library_name = "libgodot-cpp" + env["suffix"] + env["LIBSUFFIX"]
  301. if env["build_library"]:
  302. library = env.StaticLibrary(target=env.File("bin/%s" % library_name), source=sources)
  303. default_args = [library]
  304. # Add compiledb if the option is set
  305. if env.get("compiledb", False):
  306. default_args += ["compiledb"]
  307. env.Default(*default_args)
  308. env.AppendUnique(LIBS=[env.File("bin/%s" % library_name)])
  309. return library