godotcpp.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import os, sys, platform
  2. from SCons.Variables import EnumVariable, PathVariable, BoolVariable
  3. from SCons.Variables.BoolVariable import _text2bool
  4. from SCons.Tool import Tool
  5. from SCons.Builder import Builder
  6. from SCons.Errors import UserError
  7. from SCons.Script import ARGUMENTS
  8. from binding_generator import scons_generate_bindings, scons_emit_files
  9. def add_sources(sources, dir, extension):
  10. for f in os.listdir(dir):
  11. if f.endswith("." + extension):
  12. sources.append(dir + "/" + f)
  13. def get_cmdline_bool(option, default):
  14. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  15. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  16. """
  17. cmdline_val = ARGUMENTS.get(option)
  18. if cmdline_val is not None:
  19. return _text2bool(cmdline_val)
  20. else:
  21. return default
  22. def normalize_path(val, env):
  23. return val if os.path.isabs(val) else os.path.join(env.Dir("#").abspath, val)
  24. def validate_file(key, val, env):
  25. if not os.path.isfile(normalize_path(val, env)):
  26. raise UserError("'%s' is not a file: %s" % (key, val))
  27. def validate_dir(key, val, env):
  28. if not os.path.isdir(normalize_path(val, env)):
  29. raise UserError("'%s' is not a directory: %s" % (key, val))
  30. def validate_parent_dir(key, val, env):
  31. if not os.path.isdir(normalize_path(os.path.dirname(val), env)):
  32. raise UserError("'%s' is not a directory: %s" % (key, os.path.dirname(val)))
  33. def get_platform_tools_paths(env):
  34. path = env.get("custom_tools", None)
  35. if path is None:
  36. return ["tools"]
  37. return [normalize_path(path, env), "tools"]
  38. def get_custom_platforms(env):
  39. path = env.get("custom_tools", None)
  40. if path is None:
  41. return []
  42. platforms = []
  43. for x in os.listdir(normalize_path(path, env)):
  44. if not x.endswith(".py"):
  45. continue
  46. platforms.append(x.removesuffix(".py"))
  47. return platforms
  48. platforms = ["linux", "macos", "windows", "android", "ios", "web"]
  49. # CPU architecture options.
  50. architecture_array = [
  51. "",
  52. "universal",
  53. "x86_32",
  54. "x86_64",
  55. "arm32",
  56. "arm64",
  57. "rv64",
  58. "ppc32",
  59. "ppc64",
  60. "wasm32",
  61. ]
  62. architecture_aliases = {
  63. "x64": "x86_64",
  64. "amd64": "x86_64",
  65. "armv7": "arm32",
  66. "armv8": "arm64",
  67. "arm64v8": "arm64",
  68. "aarch64": "arm64",
  69. "rv": "rv64",
  70. "riscv": "rv64",
  71. "riscv64": "rv64",
  72. "ppcle": "ppc32",
  73. "ppc": "ppc32",
  74. "ppc64le": "ppc64",
  75. }
  76. def exists(env):
  77. return True
  78. def options(opts, env):
  79. # Try to detect the host platform automatically.
  80. # This is used if no `platform` argument is passed
  81. if sys.platform.startswith("linux"):
  82. default_platform = "linux"
  83. elif sys.platform == "darwin":
  84. default_platform = "macos"
  85. elif sys.platform == "win32" or sys.platform == "msys":
  86. default_platform = "windows"
  87. elif ARGUMENTS.get("platform", ""):
  88. default_platform = ARGUMENTS.get("platform")
  89. else:
  90. raise ValueError("Could not detect platform automatically, please specify with platform=<platform>")
  91. opts.Add(
  92. PathVariable(
  93. key="custom_tools",
  94. help="Path to directory containing custom tools",
  95. default=env.get("custom_tools", None),
  96. validator=validate_dir,
  97. )
  98. )
  99. opts.Update(env)
  100. custom_platforms = get_custom_platforms(env)
  101. opts.Add(
  102. EnumVariable(
  103. key="platform",
  104. help="Target platform",
  105. default=env.get("platform", default_platform),
  106. allowed_values=platforms + custom_platforms,
  107. ignorecase=2,
  108. )
  109. )
  110. # Editor and template_debug are compatible (i.e. you can use the same binary for Godot editor builds and Godot debug templates).
  111. # Godot release templates are only compatible with "template_release" builds.
  112. # For this reason, we default to template_debug builds, unlike Godot which defaults to editor builds.
  113. opts.Add(
  114. EnumVariable(
  115. key="target",
  116. help="Compilation target",
  117. default=env.get("target", "template_debug"),
  118. allowed_values=("editor", "template_release", "template_debug"),
  119. )
  120. )
  121. opts.Add(
  122. PathVariable(
  123. key="gdextension_dir",
  124. help="Path to a custom directory containing GDExtension interface header and API JSON file",
  125. default=env.get("gdextension_dir", None),
  126. validator=validate_dir,
  127. )
  128. )
  129. opts.Add(
  130. PathVariable(
  131. key="custom_api_file",
  132. help="Path to a custom GDExtension API JSON file (takes precedence over `gdextension_dir`)",
  133. default=env.get("custom_api_file", None),
  134. validator=validate_file,
  135. )
  136. )
  137. opts.Add(
  138. BoolVariable(
  139. key="generate_bindings",
  140. help="Force GDExtension API bindings generation. Auto-detected by default.",
  141. default=env.get("generate_bindings", False),
  142. )
  143. )
  144. opts.Add(
  145. BoolVariable(
  146. key="generate_template_get_node",
  147. help="Generate a template version of the Node class's get_node.",
  148. default=env.get("generate_template_get_node", True),
  149. )
  150. )
  151. opts.Add(
  152. BoolVariable(
  153. key="build_library",
  154. help="Build the godot-cpp library.",
  155. default=env.get("build_library", True),
  156. )
  157. )
  158. opts.Add(
  159. EnumVariable(
  160. key="precision",
  161. help="Set the floating-point precision level",
  162. default=env.get("precision", "single"),
  163. allowed_values=("single", "double"),
  164. )
  165. )
  166. opts.Add(
  167. EnumVariable(
  168. key="arch",
  169. help="CPU architecture",
  170. default=env.get("arch", ""),
  171. allowed_values=architecture_array,
  172. map=architecture_aliases,
  173. )
  174. )
  175. # compiledb
  176. opts.Add(
  177. BoolVariable(
  178. key="compiledb",
  179. help="Generate compilation DB (`compile_commands.json`) for external tools",
  180. default=env.get("compiledb", False),
  181. )
  182. )
  183. opts.Add(
  184. PathVariable(
  185. key="compiledb_file",
  186. help="Path to a custom `compile_commands.json` file",
  187. default=env.get("compiledb_file", "compile_commands.json"),
  188. validator=validate_parent_dir,
  189. )
  190. )
  191. opts.Add(
  192. BoolVariable(
  193. "disable_exceptions",
  194. "Force disabling exception handling code",
  195. default=env.get("disable_exceptions", False),
  196. )
  197. )
  198. opts.Add(
  199. EnumVariable(
  200. "optimize",
  201. "The desired optimization flags",
  202. "speed_trace",
  203. ("none", "custom", "debug", "speed", "speed_trace", "size"),
  204. )
  205. )
  206. opts.Add(BoolVariable("debug_symbols", "Build with debugging symbols", True))
  207. opts.Add(BoolVariable("dev_build", "Developer build with dev-only debugging code (DEV_ENABLED)", False))
  208. # Add platform options (custom tools can override platforms)
  209. for pl in sorted(set(platforms + custom_platforms)):
  210. tool = Tool(pl, toolpath=get_platform_tools_paths(env))
  211. if hasattr(tool, "options"):
  212. tool.options(opts)
  213. def generate(env):
  214. # Default num_jobs to local cpu count if not user specified.
  215. # SCons has a peculiarity where user-specified options won't be overridden
  216. # by SetOption, so we can rely on this to know if we should use our default.
  217. initial_num_jobs = env.GetOption("num_jobs")
  218. altered_num_jobs = initial_num_jobs + 1
  219. env.SetOption("num_jobs", altered_num_jobs)
  220. if env.GetOption("num_jobs") == altered_num_jobs:
  221. cpu_count = os.cpu_count()
  222. if cpu_count is None:
  223. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  224. else:
  225. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  226. print(
  227. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  228. % (cpu_count, safer_cpu_count)
  229. )
  230. env.SetOption("num_jobs", safer_cpu_count)
  231. # Process CPU architecture argument.
  232. if env["arch"] == "":
  233. # No architecture specified. Default to arm64 if building for Android,
  234. # universal if building for macOS or iOS, wasm32 if building for web,
  235. # otherwise default to the host architecture.
  236. if env["platform"] in ["macos", "ios"]:
  237. env["arch"] = "universal"
  238. elif env["platform"] == "android":
  239. env["arch"] = "arm64"
  240. elif env["platform"] == "web":
  241. env["arch"] = "wasm32"
  242. else:
  243. host_machine = platform.machine().lower()
  244. if host_machine in architecture_array:
  245. env["arch"] = host_machine
  246. elif host_machine in architecture_aliases.keys():
  247. env["arch"] = architecture_aliases[host_machine]
  248. elif "86" in host_machine:
  249. # Catches x86, i386, i486, i586, i686, etc.
  250. env["arch"] = "x86_32"
  251. else:
  252. print("Unsupported CPU architecture: " + host_machine)
  253. env.Exit(1)
  254. print("Building for architecture " + env["arch"] + " on platform " + env["platform"])
  255. # These defaults may be needed by platform tools
  256. env.editor_build = env["target"] == "editor"
  257. env.dev_build = env["dev_build"]
  258. env.debug_features = env["target"] in ["editor", "template_debug"]
  259. if env.dev_build:
  260. opt_level = "none"
  261. elif env.debug_features:
  262. opt_level = "speed_trace"
  263. else: # Release
  264. opt_level = "speed"
  265. env["optimize"] = ARGUMENTS.get("optimize", opt_level)
  266. env["debug_symbols"] = get_cmdline_bool("debug_symbols", env.dev_build)
  267. tool = Tool(env["platform"], toolpath=get_platform_tools_paths(env))
  268. if tool is None or not tool.exists(env):
  269. raise ValueError("Required toolchain not found for platform " + env["platform"])
  270. tool.generate(env)
  271. if env.editor_build:
  272. env.Append(CPPDEFINES=["TOOLS_ENABLED"])
  273. # Configuration of build targets:
  274. # - Editor or template
  275. # - Debug features (DEBUG_ENABLED code)
  276. # - Dev only code (DEV_ENABLED code)
  277. # - Optimization level
  278. # - Debug symbols for crash traces / debuggers
  279. # Keep this configuration in sync with SConstruct in upstream Godot.
  280. if env.debug_features:
  281. # DEBUG_ENABLED enables debugging *features* and debug-only code, which is intended
  282. # to give *users* extra debugging information for their game development.
  283. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  284. # In upstream Godot this is added in typedefs.h when DEBUG_ENABLED is set.
  285. env.Append(CPPDEFINES=["DEBUG_METHODS_ENABLED"])
  286. if env.dev_build:
  287. # DEV_ENABLED enables *engine developer* code which should only be compiled for those
  288. # working on the engine itself.
  289. env.Append(CPPDEFINES=["DEV_ENABLED"])
  290. else:
  291. # Disable assert() for production targets (only used in thirdparty code).
  292. env.Append(CPPDEFINES=["NDEBUG"])
  293. if env["precision"] == "double":
  294. env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  295. # Allow detecting when building as a GDExtension.
  296. env.Append(CPPDEFINES=["GDEXTENSION"])
  297. # Suffix
  298. suffix = ".{}.{}".format(env["platform"], env["target"])
  299. if env.dev_build:
  300. suffix += ".dev"
  301. if env["precision"] == "double":
  302. suffix += ".double"
  303. suffix += "." + env["arch"]
  304. if env["ios_simulator"]:
  305. suffix += ".simulator"
  306. env["suffix"] = suffix # Exposed when included from another project
  307. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  308. # compile_commands.json
  309. env.Tool("compilation_db")
  310. env.Alias("compiledb", env.CompilationDatabase(normalize_path(env["compiledb_file"], env)))
  311. # Builders
  312. env.Append(BUILDERS={"GodotCPPBindings": Builder(action=scons_generate_bindings, emitter=scons_emit_files)})
  313. env.AddMethod(_godot_cpp, "GodotCPP")
  314. def _godot_cpp(env):
  315. extension_dir = normalize_path(env.get("gdextension_dir", env.Dir("gdextension").abspath), env)
  316. api_file = normalize_path(env.get("custom_api_file", env.File(extension_dir + "/extension_api.json").abspath), env)
  317. bindings = env.GodotCPPBindings(
  318. env.Dir("."),
  319. [
  320. api_file,
  321. os.path.join(extension_dir, "gdextension_interface.h"),
  322. "binding_generator.py",
  323. ],
  324. )
  325. # Forces bindings regeneration.
  326. if env["generate_bindings"]:
  327. env.AlwaysBuild(bindings)
  328. env.NoCache(bindings)
  329. # Sources to compile
  330. sources = []
  331. add_sources(sources, "src", "cpp")
  332. add_sources(sources, "src/classes", "cpp")
  333. add_sources(sources, "src/core", "cpp")
  334. add_sources(sources, "src/variant", "cpp")
  335. sources.extend([f for f in bindings if str(f).endswith(".cpp")])
  336. # Includes
  337. env.AppendUnique(CPPPATH=[env.Dir(d) for d in [extension_dir, "include", "gen/include"]])
  338. library = None
  339. library_name = "libgodot-cpp" + env["suffix"] + env["LIBSUFFIX"]
  340. if env["build_library"]:
  341. library = env.StaticLibrary(target=env.File("bin/%s" % library_name), source=sources)
  342. default_args = [library]
  343. # Add compiledb if the option is set
  344. if env.get("compiledb", False):
  345. default_args += ["compiledb"]
  346. env.Default(*default_args)
  347. env.AppendUnique(LIBS=[env.File("bin/%s" % library_name)])
  348. return library