godotcpp.py 16 KB

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