SConstruct 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. #!/usr/bin/env python
  2. EnsureSConsVersion(3, 0, 0)
  3. EnsurePythonVersion(3, 6)
  4. # System
  5. import atexit
  6. import glob
  7. import os
  8. import pickle
  9. import sys
  10. import time
  11. from types import ModuleType
  12. from collections import OrderedDict
  13. from importlib.util import spec_from_file_location, module_from_spec
  14. # Explicitly resolve the helper modules, this is done to avoid clash with
  15. # modules of the same name that might be randomly added (e.g. someone adding
  16. # an `editor.py` file at the root of the module creates a clash with the editor
  17. # folder when doing `import editor.template_builder`)
  18. def _helper_module(name, path):
  19. spec = spec_from_file_location(name, path)
  20. module = module_from_spec(spec)
  21. spec.loader.exec_module(module)
  22. sys.modules[name] = module
  23. # Ensure the module's parents are in loaded to avoid loading the wrong parent
  24. # when doing "import foo.bar" while only "foo.bar" as declared as helper module
  25. child_module = module
  26. parent_name = name
  27. while True:
  28. try:
  29. parent_name, child_name = parent_name.rsplit(".", 1)
  30. except ValueError:
  31. break
  32. try:
  33. parent_module = sys.modules[parent_name]
  34. except KeyError:
  35. parent_module = ModuleType(parent_name)
  36. sys.modules[parent_name] = parent_module
  37. setattr(parent_module, child_name, child_module)
  38. _helper_module("gles3_builders", "gles3_builders.py")
  39. _helper_module("glsl_builders", "glsl_builders.py")
  40. _helper_module("methods", "methods.py")
  41. _helper_module("platform_methods", "platform_methods.py")
  42. _helper_module("version", "version.py")
  43. _helper_module("core.core_builders", "core/core_builders.py")
  44. _helper_module("main.main_builders", "main/main_builders.py")
  45. _helper_module("modules.modules_builders", "modules/modules_builders.py")
  46. # Local
  47. import methods
  48. import glsl_builders
  49. import gles3_builders
  50. from platform_methods import architectures, architecture_aliases
  51. if ARGUMENTS.get("target", "editor") == "editor":
  52. _helper_module("editor.editor_builders", "editor/editor_builders.py")
  53. _helper_module("editor.template_builders", "editor/template_builders.py")
  54. # Scan possible build platforms
  55. platform_list = [] # list of platforms
  56. platform_opts = {} # options for each platform
  57. platform_flags = {} # flags for each platform
  58. active_platforms = []
  59. active_platform_ids = []
  60. platform_exporters = []
  61. platform_apis = []
  62. time_at_start = time.time()
  63. for x in sorted(glob.glob("platform/*")):
  64. if not os.path.isdir(x) or not os.path.exists(x + "/detect.py"):
  65. continue
  66. tmppath = "./" + x
  67. sys.path.insert(0, tmppath)
  68. import detect
  69. if os.path.exists(x + "/export/export.cpp"):
  70. platform_exporters.append(x[9:])
  71. if os.path.exists(x + "/api/api.cpp"):
  72. platform_apis.append(x[9:])
  73. if detect.is_active():
  74. active_platforms.append(detect.get_name())
  75. active_platform_ids.append(x)
  76. if detect.can_build():
  77. x = x.replace("platform/", "") # rest of world
  78. x = x.replace("platform\\", "") # win32
  79. platform_list += [x]
  80. platform_opts[x] = detect.get_opts()
  81. platform_flags[x] = detect.get_flags()
  82. sys.path.remove(tmppath)
  83. sys.modules.pop("detect")
  84. methods.save_active_platforms(active_platforms, active_platform_ids)
  85. custom_tools = ["default"]
  86. platform_arg = ARGUMENTS.get("platform", ARGUMENTS.get("p", False))
  87. if platform_arg == "android":
  88. custom_tools = ["clang", "clang++", "as", "ar", "link"]
  89. elif platform_arg == "web":
  90. # Use generic POSIX build toolchain for Emscripten.
  91. custom_tools = ["cc", "c++", "ar", "link", "textfile", "zip"]
  92. elif os.name == "nt" and methods.get_cmdline_bool("use_mingw", False):
  93. custom_tools = ["mingw"]
  94. # We let SCons build its default ENV as it includes OS-specific things which we don't
  95. # want to have to pull in manually.
  96. # Then we prepend PATH to make it take precedence, while preserving SCons' own entries.
  97. env_base = Environment(tools=custom_tools)
  98. env_base.PrependENVPath("PATH", os.getenv("PATH"))
  99. env_base.PrependENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH"))
  100. if "TERM" in os.environ: # Used for colored output.
  101. env_base["ENV"]["TERM"] = os.environ["TERM"]
  102. env_base.disabled_modules = []
  103. env_base.module_version_string = ""
  104. env_base.msvc = False
  105. env_base.__class__.disable_module = methods.disable_module
  106. env_base.__class__.add_module_version_string = methods.add_module_version_string
  107. env_base.__class__.add_source_files = methods.add_source_files
  108. env_base.__class__.use_windows_spawn_fix = methods.use_windows_spawn_fix
  109. env_base.__class__.add_shared_library = methods.add_shared_library
  110. env_base.__class__.add_library = methods.add_library
  111. env_base.__class__.add_program = methods.add_program
  112. env_base.__class__.CommandNoCache = methods.CommandNoCache
  113. env_base.__class__.Run = methods.Run
  114. env_base.__class__.disable_warnings = methods.disable_warnings
  115. env_base.__class__.force_optimization_on_debug = methods.force_optimization_on_debug
  116. env_base.__class__.module_add_dependencies = methods.module_add_dependencies
  117. env_base.__class__.module_check_dependencies = methods.module_check_dependencies
  118. env_base["x86_libtheora_opt_gcc"] = False
  119. env_base["x86_libtheora_opt_vc"] = False
  120. # avoid issues when building with different versions of python out of the same directory
  121. env_base.SConsignFile(".sconsign{0}.dblite".format(pickle.HIGHEST_PROTOCOL))
  122. # Build options
  123. customs = ["custom.py"]
  124. profile = ARGUMENTS.get("profile", "")
  125. if profile:
  126. if os.path.isfile(profile):
  127. customs.append(profile)
  128. elif os.path.isfile(profile + ".py"):
  129. customs.append(profile + ".py")
  130. opts = Variables(customs, ARGUMENTS)
  131. # Target build options
  132. opts.Add("platform", "Target platform (%s)" % ("|".join(platform_list),), "")
  133. opts.Add("p", "Platform (alias for 'platform')", "")
  134. opts.Add(EnumVariable("target", "Compilation target", "editor", ("editor", "template_release", "template_debug")))
  135. opts.Add(EnumVariable("arch", "CPU architecture", "auto", ["auto"] + architectures, architecture_aliases))
  136. opts.Add(BoolVariable("dev_build", "Developer build with dev-only debugging code (DEV_ENABLED)", False))
  137. opts.Add(
  138. EnumVariable(
  139. "optimize", "Optimization level", "speed_trace", ("none", "custom", "debug", "speed", "speed_trace", "size")
  140. )
  141. )
  142. opts.Add(BoolVariable("debug_symbols", "Build with debugging symbols", False))
  143. opts.Add(BoolVariable("separate_debug_symbols", "Extract debugging symbols to a separate file", False))
  144. opts.Add(EnumVariable("lto", "Link-time optimization (production builds)", "none", ("none", "auto", "thin", "full")))
  145. opts.Add(BoolVariable("production", "Set defaults to build Godot for use in production", False))
  146. # Components
  147. opts.Add(BoolVariable("deprecated", "Enable compatibility code for deprecated and removed features", True))
  148. opts.Add(EnumVariable("precision", "Set the floating-point precision level", "single", ("single", "double")))
  149. opts.Add(BoolVariable("minizip", "Enable ZIP archive support using minizip", True))
  150. opts.Add(BoolVariable("xaudio2", "Enable the XAudio2 audio driver", False))
  151. opts.Add(BoolVariable("vulkan", "Enable the vulkan rendering driver", True))
  152. opts.Add(BoolVariable("opengl3", "Enable the OpenGL/GLES3 rendering driver", True))
  153. opts.Add(BoolVariable("openxr", "Enable the OpenXR driver", True))
  154. opts.Add(BoolVariable("use_volk", "Use the volk library to load the Vulkan loader dynamically", True))
  155. opts.Add("custom_modules", "A list of comma-separated directory paths containing custom modules to build.", "")
  156. opts.Add(BoolVariable("custom_modules_recursive", "Detect custom modules recursively for each specified path.", True))
  157. # Advanced options
  158. opts.Add(BoolVariable("dev_mode", "Alias for dev options: verbose=yes warnings=extra werror=yes tests=yes", False))
  159. opts.Add(BoolVariable("tests", "Build the unit tests", False))
  160. opts.Add(BoolVariable("fast_unsafe", "Enable unsafe options for faster rebuilds", False))
  161. opts.Add(BoolVariable("compiledb", "Generate compilation DB (`compile_commands.json`) for external tools", False))
  162. opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False))
  163. opts.Add(BoolVariable("progress", "Show a progress indicator during compilation", True))
  164. opts.Add(EnumVariable("warnings", "Level of compilation warnings", "all", ("extra", "all", "moderate", "no")))
  165. opts.Add(BoolVariable("werror", "Treat compiler warnings as errors", False))
  166. opts.Add("extra_suffix", "Custom extra suffix added to the base filename of all generated binary files", "")
  167. opts.Add(BoolVariable("vsproj", "Generate a Visual Studio solution", False))
  168. opts.Add("vsproj_name", "Name of the Visual Studio solution", "godot")
  169. opts.Add(BoolVariable("disable_3d", "Disable 3D nodes for a smaller executable", False))
  170. opts.Add(BoolVariable("disable_advanced_gui", "Disable advanced GUI nodes and behaviors", False))
  171. opts.Add("build_profile", "Path to a file containing a feature build profile", "")
  172. opts.Add(BoolVariable("modules_enabled_by_default", "If no, disable all modules except ones explicitly enabled", True))
  173. opts.Add(BoolVariable("no_editor_splash", "Don't use the custom splash screen for the editor", True))
  174. opts.Add("system_certs_path", "Use this path as SSL certificates default for editor (for package maintainers)", "")
  175. opts.Add(BoolVariable("use_precise_math_checks", "Math checks use very precise epsilon (debug option)", False))
  176. # Thirdparty libraries
  177. opts.Add(BoolVariable("builtin_certs", "Use the built-in SSL certificates bundles", True))
  178. opts.Add(BoolVariable("builtin_embree", "Use the built-in Embree library", True))
  179. opts.Add(BoolVariable("builtin_enet", "Use the built-in ENet library", True))
  180. opts.Add(BoolVariable("builtin_freetype", "Use the built-in FreeType library", True))
  181. opts.Add(BoolVariable("builtin_msdfgen", "Use the built-in MSDFgen library", True))
  182. opts.Add(BoolVariable("builtin_glslang", "Use the built-in glslang library", True))
  183. opts.Add(BoolVariable("builtin_graphite", "Use the built-in Graphite library", True))
  184. opts.Add(BoolVariable("builtin_harfbuzz", "Use the built-in HarfBuzz library", True))
  185. opts.Add(BoolVariable("builtin_icu4c", "Use the built-in ICU library", True))
  186. opts.Add(BoolVariable("builtin_libogg", "Use the built-in libogg library", True))
  187. opts.Add(BoolVariable("builtin_libpng", "Use the built-in libpng library", True))
  188. opts.Add(BoolVariable("builtin_libtheora", "Use the built-in libtheora library", True))
  189. opts.Add(BoolVariable("builtin_libvorbis", "Use the built-in libvorbis library", True))
  190. opts.Add(BoolVariable("builtin_libwebp", "Use the built-in libwebp library", True))
  191. opts.Add(BoolVariable("builtin_wslay", "Use the built-in wslay library", True))
  192. opts.Add(BoolVariable("builtin_mbedtls", "Use the built-in mbedTLS library", True))
  193. opts.Add(BoolVariable("builtin_miniupnpc", "Use the built-in miniupnpc library", True))
  194. opts.Add(BoolVariable("builtin_pcre2", "Use the built-in PCRE2 library", True))
  195. opts.Add(BoolVariable("builtin_pcre2_with_jit", "Use JIT compiler for the built-in PCRE2 library", True))
  196. opts.Add(BoolVariable("builtin_recastnavigation", "Use the built-in Recast navigation library", True))
  197. opts.Add(BoolVariable("builtin_rvo2", "Use the built-in RVO2 library", True))
  198. opts.Add(BoolVariable("builtin_squish", "Use the built-in squish library", True))
  199. opts.Add(BoolVariable("builtin_xatlas", "Use the built-in xatlas library", True))
  200. opts.Add(BoolVariable("builtin_zlib", "Use the built-in zlib library", True))
  201. opts.Add(BoolVariable("builtin_zstd", "Use the built-in Zstd library", True))
  202. # Compilation environment setup
  203. opts.Add("CXX", "C++ compiler")
  204. opts.Add("CC", "C compiler")
  205. opts.Add("LINK", "Linker")
  206. opts.Add("CCFLAGS", "Custom flags for both the C and C++ compilers")
  207. opts.Add("CFLAGS", "Custom flags for the C compiler")
  208. opts.Add("CXXFLAGS", "Custom flags for the C++ compiler")
  209. opts.Add("LINKFLAGS", "Custom flags for the linker")
  210. # Update the environment to have all above options defined
  211. # in following code (especially platform and custom_modules).
  212. opts.Update(env_base)
  213. # Platform selection: validate input, and add options.
  214. selected_platform = ""
  215. if env_base["platform"] != "":
  216. selected_platform = env_base["platform"]
  217. elif env_base["p"] != "":
  218. selected_platform = env_base["p"]
  219. else:
  220. # Missing `platform` argument, try to detect platform automatically
  221. if (
  222. sys.platform.startswith("linux")
  223. or sys.platform.startswith("dragonfly")
  224. or sys.platform.startswith("freebsd")
  225. or sys.platform.startswith("netbsd")
  226. or sys.platform.startswith("openbsd")
  227. ):
  228. selected_platform = "linuxbsd"
  229. elif sys.platform == "darwin":
  230. selected_platform = "macos"
  231. elif sys.platform == "win32":
  232. selected_platform = "windows"
  233. else:
  234. print("Could not detect platform automatically. Supported platforms:")
  235. for x in platform_list:
  236. print("\t" + x)
  237. print("\nPlease run SCons again and select a valid platform: platform=<string>")
  238. if selected_platform != "":
  239. print("Automatically detected platform: " + selected_platform)
  240. if selected_platform in ["macos", "osx"]:
  241. if selected_platform == "osx":
  242. # Deprecated alias kept for compatibility.
  243. print('Platform "osx" has been renamed to "macos" in Godot 4.0. Building for platform "macos".')
  244. # Alias for convenience.
  245. selected_platform = "macos"
  246. if selected_platform in ["ios", "iphone"]:
  247. if selected_platform == "iphone":
  248. # Deprecated alias kept for compatibility.
  249. print('Platform "iphone" has been renamed to "ios" in Godot 4.0. Building for platform "ios".')
  250. # Alias for convenience.
  251. selected_platform = "ios"
  252. if selected_platform in ["linux", "bsd", "x11"]:
  253. if selected_platform == "x11":
  254. # Deprecated alias kept for compatibility.
  255. print('Platform "x11" has been renamed to "linuxbsd" in Godot 4.0. Building for platform "linuxbsd".')
  256. # Alias for convenience.
  257. selected_platform = "linuxbsd"
  258. # Make sure to update this to the found, valid platform as it's used through the buildsystem as the reference.
  259. # It should always be re-set after calling `opts.Update()` otherwise it uses the original input value.
  260. env_base["platform"] = selected_platform
  261. # Add platform-specific options.
  262. if selected_platform in platform_opts:
  263. for opt in platform_opts[selected_platform]:
  264. opts.Add(opt)
  265. # Update the environment to take platform-specific options into account.
  266. opts.Update(env_base)
  267. env_base["platform"] = selected_platform # Must always be re-set after calling opts.Update().
  268. # Detect modules.
  269. modules_detected = OrderedDict()
  270. module_search_paths = ["modules"] # Built-in path.
  271. if env_base["custom_modules"]:
  272. paths = env_base["custom_modules"].split(",")
  273. for p in paths:
  274. try:
  275. module_search_paths.append(methods.convert_custom_modules_path(p))
  276. except ValueError as e:
  277. print(e)
  278. Exit(255)
  279. for path in module_search_paths:
  280. if path == "modules":
  281. # Built-in modules don't have nested modules,
  282. # so save the time it takes to parse directories.
  283. modules = methods.detect_modules(path, recursive=False)
  284. else: # Custom.
  285. modules = methods.detect_modules(path, env_base["custom_modules_recursive"])
  286. # Provide default include path for both the custom module search `path`
  287. # and the base directory containing custom modules, as it may be different
  288. # from the built-in "modules" name (e.g. "custom_modules/summator/summator.h"),
  289. # so it can be referenced simply as `#include "summator/summator.h"`
  290. # independently of where a module is located on user's filesystem.
  291. env_base.Prepend(CPPPATH=[path, os.path.dirname(path)])
  292. # Note: custom modules can override built-in ones.
  293. modules_detected.update(modules)
  294. # Add module options.
  295. for name, path in modules_detected.items():
  296. sys.path.insert(0, path)
  297. import config
  298. if env_base["modules_enabled_by_default"]:
  299. enabled = True
  300. try:
  301. enabled = config.is_enabled()
  302. except AttributeError:
  303. pass
  304. else:
  305. enabled = False
  306. # Add module-specific options.
  307. try:
  308. for opt in config.get_opts(selected_platform):
  309. opts.Add(opt)
  310. except AttributeError:
  311. pass
  312. sys.path.remove(path)
  313. sys.modules.pop("config")
  314. opts.Add(BoolVariable("module_" + name + "_enabled", "Enable module '%s'" % (name,), enabled))
  315. methods.write_modules(modules_detected)
  316. # Update the environment again after all the module options are added.
  317. opts.Update(env_base)
  318. env_base["platform"] = selected_platform # Must always be re-set after calling opts.Update().
  319. Help(opts.GenerateHelpText(env_base))
  320. # add default include paths
  321. env_base.Prepend(CPPPATH=["#"])
  322. # configure ENV for platform
  323. env_base.platform_exporters = platform_exporters
  324. env_base.platform_apis = platform_apis
  325. # Configuration of build targets:
  326. # - Editor or template
  327. # - Debug features (DEBUG_ENABLED code)
  328. # - Dev only code (DEV_ENABLED code)
  329. # - Optimization level
  330. # - Debug symbols for crash traces / debuggers
  331. env_base.editor_build = env_base["target"] == "editor"
  332. env_base.dev_build = env_base["dev_build"]
  333. env_base.debug_features = env_base["target"] in ["editor", "template_debug"]
  334. if env_base.dev_build:
  335. opt_level = "none"
  336. elif env_base.debug_features:
  337. opt_level = "speed_trace"
  338. else: # Release
  339. opt_level = "speed"
  340. env_base["optimize"] = ARGUMENTS.get("optimize", opt_level)
  341. env_base["debug_symbols"] = methods.get_cmdline_bool("debug_symbols", env_base.dev_build)
  342. if env_base.editor_build:
  343. env_base.Append(CPPDEFINES=["TOOLS_ENABLED"])
  344. if env_base.debug_features:
  345. # DEBUG_ENABLED enables debugging *features* and debug-only code, which is intended
  346. # to give *users* extra debugging information for their game development.
  347. env_base.Append(CPPDEFINES=["DEBUG_ENABLED"])
  348. if env_base.dev_build:
  349. # DEV_ENABLED enables *engine developer* code which should only be compiled for those
  350. # working on the engine itself.
  351. env_base.Append(CPPDEFINES=["DEV_ENABLED"])
  352. else:
  353. # Disable assert() for production targets (only used in thirdparty code).
  354. env_base.Append(CPPDEFINES=["NDEBUG"])
  355. # SCons speed optimization controlled by the `fast_unsafe` option, which provide
  356. # more than 10 s speed up for incremental rebuilds.
  357. # Unsafe as they reduce the certainty of rebuilding all changed files, so it's
  358. # enabled by default for `debug` builds, and can be overridden from command line.
  359. # Ref: https://github.com/SCons/scons/wiki/GoFastButton
  360. if methods.get_cmdline_bool("fast_unsafe", env_base.dev_build):
  361. # Renamed to `content-timestamp` in SCons >= 4.2, keeping MD5 for compat.
  362. env_base.Decider("MD5-timestamp")
  363. env_base.SetOption("implicit_cache", 1)
  364. env_base.SetOption("max_drift", 60)
  365. if env_base["use_precise_math_checks"]:
  366. env_base.Append(CPPDEFINES=["PRECISE_MATH_CHECKS"])
  367. if not env_base.File("#main/splash_editor.png").exists():
  368. # Force disabling editor splash if missing.
  369. env_base["no_editor_splash"] = True
  370. if env_base["no_editor_splash"]:
  371. env_base.Append(CPPDEFINES=["NO_EDITOR_SPLASH"])
  372. if not env_base["deprecated"]:
  373. env_base.Append(CPPDEFINES=["DISABLE_DEPRECATED"])
  374. if env_base["precision"] == "double":
  375. env_base.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  376. if selected_platform in platform_list:
  377. tmppath = "./platform/" + selected_platform
  378. sys.path.insert(0, tmppath)
  379. import detect
  380. env = env_base.Clone()
  381. # Default num_jobs to local cpu count if not user specified.
  382. # SCons has a peculiarity where user-specified options won't be overridden
  383. # by SetOption, so we can rely on this to know if we should use our default.
  384. initial_num_jobs = env.GetOption("num_jobs")
  385. altered_num_jobs = initial_num_jobs + 1
  386. env.SetOption("num_jobs", altered_num_jobs)
  387. if env.GetOption("num_jobs") == altered_num_jobs:
  388. cpu_count = os.cpu_count()
  389. if cpu_count is None:
  390. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  391. else:
  392. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  393. print(
  394. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  395. % (cpu_count, safer_cpu_count)
  396. )
  397. env.SetOption("num_jobs", safer_cpu_count)
  398. env.extra_suffix = ""
  399. if env["extra_suffix"] != "":
  400. env.extra_suffix += "." + env["extra_suffix"]
  401. # Environment flags
  402. CCFLAGS = env.get("CCFLAGS", "")
  403. env["CCFLAGS"] = ""
  404. env.Append(CCFLAGS=str(CCFLAGS).split())
  405. CFLAGS = env.get("CFLAGS", "")
  406. env["CFLAGS"] = ""
  407. env.Append(CFLAGS=str(CFLAGS).split())
  408. CXXFLAGS = env.get("CXXFLAGS", "")
  409. env["CXXFLAGS"] = ""
  410. env.Append(CXXFLAGS=str(CXXFLAGS).split())
  411. LINKFLAGS = env.get("LINKFLAGS", "")
  412. env["LINKFLAGS"] = ""
  413. env.Append(LINKFLAGS=str(LINKFLAGS).split())
  414. # Feature build profile
  415. disabled_classes = []
  416. if env["build_profile"] != "":
  417. print("Using feature build profile: " + env["build_profile"])
  418. import json
  419. try:
  420. ft = json.load(open(env["build_profile"]))
  421. if "disabled_classes" in ft:
  422. disabled_classes = ft["disabled_classes"]
  423. if "disabled_build_options" in ft:
  424. dbo = ft["disabled_build_options"]
  425. for c in dbo:
  426. env[c] = dbo[c]
  427. except:
  428. print("Error opening feature build profile: " + env["build_profile"])
  429. Exit(255)
  430. methods.write_disabled_classes(disabled_classes)
  431. # Platform specific flags.
  432. # These can sometimes override default options.
  433. flag_list = platform_flags[selected_platform]
  434. for f in flag_list:
  435. if not (f[0] in ARGUMENTS) or ARGUMENTS[f[0]] == "auto": # Allow command line to override platform flags
  436. env[f[0]] = f[1]
  437. # 'dev_mode' and 'production' are aliases to set default options if they haven't been
  438. # set manually by the user.
  439. # These need to be checked *after* platform specific flags so that different
  440. # default values can be set (e.g. to keep LTO off for `production` on some platforms).
  441. if env["dev_mode"]:
  442. env["verbose"] = methods.get_cmdline_bool("verbose", True)
  443. env["warnings"] = ARGUMENTS.get("warnings", "extra")
  444. env["werror"] = methods.get_cmdline_bool("werror", True)
  445. env["tests"] = methods.get_cmdline_bool("tests", True)
  446. if env["production"]:
  447. env["use_static_cpp"] = methods.get_cmdline_bool("use_static_cpp", True)
  448. env["debug_symbols"] = methods.get_cmdline_bool("debug_symbols", False)
  449. # LTO "auto" means we handle the preferred option in each platform detect.py.
  450. env["lto"] = ARGUMENTS.get("lto", "auto")
  451. # Must happen after the flags' definition, as configure is when most flags
  452. # are actually handled to change compile options, etc.
  453. detect.configure(env)
  454. print(f'Building for platform "{selected_platform}", architecture "{env["arch"]}", target "{env["target"]}".')
  455. if env.dev_build:
  456. print("NOTE: Developer build, with debug optimization level and debug symbols (unless overridden).")
  457. # Set optimize and debug_symbols flags.
  458. # "custom" means do nothing and let users set their own optimization flags.
  459. # Needs to happen after configure to have `env.msvc` defined.
  460. if env.msvc:
  461. if env["debug_symbols"]:
  462. env.Append(CCFLAGS=["/Zi", "/FS"])
  463. env.Append(LINKFLAGS=["/DEBUG:FULL"])
  464. if env["optimize"] == "speed" or env["optimize"] == "speed_trace":
  465. env.Append(CCFLAGS=["/O2"])
  466. env.Append(LINKFLAGS=["/OPT:REF"])
  467. elif env["optimize"] == "size":
  468. env.Append(CCFLAGS=["/O1"])
  469. env.Append(LINKFLAGS=["/OPT:REF"])
  470. elif env["optimize"] == "debug" or env["optimize"] == "none":
  471. env.Append(CCFLAGS=["/Od"])
  472. else:
  473. if env["debug_symbols"]:
  474. # Adding dwarf-4 explicitly makes stacktraces work with clang builds,
  475. # otherwise addr2line doesn't understand them
  476. env.Append(CCFLAGS=["-gdwarf-4"])
  477. if env.dev_build:
  478. env.Append(CCFLAGS=["-g3"])
  479. else:
  480. env.Append(CCFLAGS=["-g2"])
  481. else:
  482. if methods.using_clang(env) and not methods.is_vanilla_clang(env):
  483. # Apple Clang, its linker doesn't like -s.
  484. env.Append(LINKFLAGS=["-Wl,-S", "-Wl,-x", "-Wl,-dead_strip"])
  485. else:
  486. env.Append(LINKFLAGS=["-s"])
  487. if env["optimize"] == "speed":
  488. env.Append(CCFLAGS=["-O3"])
  489. # `-O2` is friendlier to debuggers than `-O3`, leading to better crash backtraces.
  490. elif env["optimize"] == "speed_trace":
  491. env.Append(CCFLAGS=["-O2"])
  492. elif env["optimize"] == "size":
  493. env.Append(CCFLAGS=["-Os"])
  494. elif env["optimize"] == "debug":
  495. env.Append(CCFLAGS=["-Og"])
  496. elif env["optimize"] == "none":
  497. env.Append(CCFLAGS=["-O0"])
  498. # Needs to happen after configure to handle "auto".
  499. if env["lto"] != "none":
  500. print("Using LTO: " + env["lto"])
  501. # Set our C and C++ standard requirements.
  502. # C++17 is required as we need guaranteed copy elision as per GH-36436.
  503. # Prepending to make it possible to override.
  504. # This needs to come after `configure`, otherwise we don't have env.msvc.
  505. if not env.msvc:
  506. # Specifying GNU extensions support explicitly, which are supported by
  507. # both GCC and Clang. Both currently default to gnu11 and gnu++14.
  508. env.Prepend(CFLAGS=["-std=gnu11"])
  509. env.Prepend(CXXFLAGS=["-std=gnu++17"])
  510. else:
  511. # MSVC doesn't have clear C standard support, /std only covers C++.
  512. # We apply it to CCFLAGS (both C and C++ code) in case it impacts C features.
  513. env.Prepend(CCFLAGS=["/std:c++17"])
  514. # Enforce our minimal compiler version requirements
  515. cc_version = methods.get_compiler_version(env) or {
  516. "major": None,
  517. "minor": None,
  518. "patch": None,
  519. "metadata1": None,
  520. "metadata2": None,
  521. "date": None,
  522. }
  523. cc_version_major = int(cc_version["major"] or -1)
  524. cc_version_minor = int(cc_version["minor"] or -1)
  525. cc_version_metadata1 = cc_version["metadata1"] or ""
  526. if methods.using_gcc(env):
  527. if cc_version_major == -1:
  528. print(
  529. "Couldn't detect compiler version, skipping version checks. "
  530. "Build may fail if the compiler doesn't support C++17 fully."
  531. )
  532. # GCC 8 before 8.4 has a regression in the support of guaranteed copy elision
  533. # which causes a build failure: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86521
  534. elif cc_version_major == 8 and cc_version_minor < 4:
  535. print(
  536. "Detected GCC 8 version < 8.4, which is not supported due to a "
  537. "regression in its C++17 guaranteed copy elision support. Use a "
  538. 'newer GCC version, or Clang 6 or later by passing "use_llvm=yes" '
  539. "to the SCons command line."
  540. )
  541. Exit(255)
  542. elif cc_version_major < 7:
  543. print(
  544. "Detected GCC version older than 7, which does not fully support "
  545. "C++17. Supported versions are GCC 7, 9 and later. Use a newer GCC "
  546. 'version, or Clang 6 or later by passing "use_llvm=yes" to the '
  547. "SCons command line."
  548. )
  549. Exit(255)
  550. elif cc_version_metadata1 == "win32":
  551. print(
  552. "Detected mingw version is not using posix threads. Only posix "
  553. "version of mingw is supported. "
  554. 'Use "update-alternatives --config x86_64-w64-mingw32-g++" '
  555. "to switch to posix threads."
  556. )
  557. Exit(255)
  558. elif methods.using_clang(env):
  559. if cc_version_major == -1:
  560. print(
  561. "Couldn't detect compiler version, skipping version checks. "
  562. "Build may fail if the compiler doesn't support C++17 fully."
  563. )
  564. # Apple LLVM versions differ from upstream LLVM version \o/, compare
  565. # in https://en.wikipedia.org/wiki/Xcode#Toolchain_versions
  566. elif env["platform"] == "macos" or env["platform"] == "ios":
  567. vanilla = methods.is_vanilla_clang(env)
  568. if vanilla and cc_version_major < 6:
  569. print(
  570. "Detected Clang version older than 6, which does not fully support "
  571. "C++17. Supported versions are Clang 6 and later."
  572. )
  573. Exit(255)
  574. elif not vanilla and cc_version_major < 10:
  575. print(
  576. "Detected Apple Clang version older than 10, which does not fully "
  577. "support C++17. Supported versions are Apple Clang 10 and later."
  578. )
  579. Exit(255)
  580. elif cc_version_major < 6:
  581. print(
  582. "Detected Clang version older than 6, which does not fully support "
  583. "C++17. Supported versions are Clang 6 and later."
  584. )
  585. Exit(255)
  586. # Configure compiler warnings
  587. if env.msvc: # MSVC
  588. if env["warnings"] == "no":
  589. env.Append(CCFLAGS=["/w"])
  590. else:
  591. if env["warnings"] == "extra":
  592. env.Append(CCFLAGS=["/W4"])
  593. elif env["warnings"] == "all":
  594. # C4458 is like -Wshadow. Part of /W4 but let's apply it for the default /W3 too.
  595. env.Append(CCFLAGS=["/W3", "/w34458"])
  596. elif env["warnings"] == "moderate":
  597. env.Append(CCFLAGS=["/W2"])
  598. # Disable warnings which we don't plan to fix.
  599. env.Append(
  600. CCFLAGS=[
  601. "/wd4100", # C4100 (unreferenced formal parameter): Doesn't play nice with polymorphism.
  602. "/wd4127", # C4127 (conditional expression is constant)
  603. "/wd4201", # C4201 (non-standard nameless struct/union): Only relevant for C89.
  604. "/wd4244", # C4244 C4245 C4267 (narrowing conversions): Unavoidable at this scale.
  605. "/wd4245",
  606. "/wd4267",
  607. "/wd4305", # C4305 (truncation): double to float or real_t, too hard to avoid.
  608. "/wd4514", # C4514 (unreferenced inline function has been removed)
  609. "/wd4714", # C4714 (function marked as __forceinline not inlined)
  610. "/wd4820", # C4820 (padding added after construct)
  611. ]
  612. )
  613. # Set exception handling model to avoid warnings caused by Windows system headers.
  614. env.Append(CCFLAGS=["/EHsc"])
  615. if env["werror"]:
  616. env.Append(CCFLAGS=["/WX"])
  617. else: # GCC, Clang
  618. common_warnings = []
  619. if methods.using_gcc(env):
  620. common_warnings += ["-Wshadow", "-Wno-misleading-indentation"]
  621. if cc_version_major == 7: # Bogus warning fixed in 8+.
  622. common_warnings += ["-Wno-strict-overflow"]
  623. if cc_version_major < 11:
  624. # Regression in GCC 9/10, spams so much in our variadic templates
  625. # that we need to outright disable it.
  626. common_warnings += ["-Wno-type-limits"]
  627. if cc_version_major >= 12: # False positives in our error macros, see GH-58747.
  628. common_warnings += ["-Wno-return-type"]
  629. elif methods.using_clang(env) or methods.using_emcc(env):
  630. common_warnings += ["-Wshadow-field-in-constructor", "-Wshadow-uncaptured-local"]
  631. # We often implement `operator<` for structs of pointers as a requirement
  632. # for putting them in `Set` or `Map`. We don't mind about unreliable ordering.
  633. common_warnings += ["-Wno-ordered-compare-function-pointers"]
  634. if env["warnings"] == "extra":
  635. env.Append(CCFLAGS=["-Wall", "-Wextra", "-Wwrite-strings", "-Wno-unused-parameter"] + common_warnings)
  636. env.Append(CXXFLAGS=["-Wctor-dtor-privacy", "-Wnon-virtual-dtor"])
  637. if methods.using_gcc(env):
  638. env.Append(
  639. CCFLAGS=[
  640. "-Walloc-zero",
  641. "-Wduplicated-branches",
  642. "-Wduplicated-cond",
  643. "-Wstringop-overflow=4",
  644. ]
  645. )
  646. env.Append(CXXFLAGS=["-Wplacement-new=1"])
  647. # Need to fix a warning with AudioServer lambdas before enabling.
  648. # if cc_version_major != 9: # GCC 9 had a regression (GH-36325).
  649. # env.Append(CXXFLAGS=["-Wnoexcept"])
  650. if cc_version_major >= 9:
  651. env.Append(CCFLAGS=["-Wattribute-alias=2"])
  652. if cc_version_major >= 11: # Broke on MethodBind templates before GCC 11.
  653. env.Append(CCFLAGS=["-Wlogical-op"])
  654. elif methods.using_clang(env) or methods.using_emcc(env):
  655. env.Append(CCFLAGS=["-Wimplicit-fallthrough"])
  656. elif env["warnings"] == "all":
  657. env.Append(CCFLAGS=["-Wall"] + common_warnings)
  658. elif env["warnings"] == "moderate":
  659. env.Append(CCFLAGS=["-Wall", "-Wno-unused"] + common_warnings)
  660. else: # 'no'
  661. env.Append(CCFLAGS=["-w"])
  662. if env["werror"]:
  663. env.Append(CCFLAGS=["-Werror"])
  664. if hasattr(detect, "get_program_suffix"):
  665. suffix = "." + detect.get_program_suffix()
  666. else:
  667. suffix = "." + selected_platform
  668. suffix += "." + env["target"]
  669. if env.dev_build:
  670. suffix += ".dev"
  671. if env_base["precision"] == "double":
  672. suffix += ".double"
  673. suffix += "." + env["arch"]
  674. suffix += env.extra_suffix
  675. sys.path.remove(tmppath)
  676. sys.modules.pop("detect")
  677. modules_enabled = OrderedDict()
  678. env.module_dependencies = {}
  679. env.module_icons_paths = []
  680. env.doc_class_path = {}
  681. for name, path in modules_detected.items():
  682. if not env["module_" + name + "_enabled"]:
  683. continue
  684. sys.path.insert(0, path)
  685. env.current_module = name
  686. import config
  687. if config.can_build(env, selected_platform):
  688. # Disable it if a required dependency is missing.
  689. if not env.module_check_dependencies(name):
  690. continue
  691. config.configure(env)
  692. # Get doc classes paths (if present)
  693. try:
  694. doc_classes = config.get_doc_classes()
  695. doc_path = config.get_doc_path()
  696. for c in doc_classes:
  697. env.doc_class_path[c] = path + "/" + doc_path
  698. except Exception:
  699. pass
  700. # Get icon paths (if present)
  701. try:
  702. icons_path = config.get_icons_path()
  703. env.module_icons_paths.append(path + "/" + icons_path)
  704. except Exception:
  705. # Default path for module icons
  706. env.module_icons_paths.append(path + "/" + "icons")
  707. modules_enabled[name] = path
  708. sys.path.remove(path)
  709. sys.modules.pop("config")
  710. env.module_list = modules_enabled
  711. methods.sort_module_list(env)
  712. if env.editor_build:
  713. # Add editor-specific dependencies to the dependency graph.
  714. env.module_add_dependencies("editor", ["freetype", "svg"])
  715. # And check if they are met.
  716. if not env.module_check_dependencies("editor"):
  717. print("Not all modules required by editor builds are enabled.")
  718. Exit(255)
  719. methods.generate_version_header(env.module_version_string)
  720. env["PROGSUFFIX_WRAP"] = suffix + env.module_version_string + ".console" + env["PROGSUFFIX"]
  721. env["PROGSUFFIX"] = suffix + env.module_version_string + env["PROGSUFFIX"]
  722. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  723. # (SH)LIBSUFFIX will be used for our own built libraries
  724. # LIBSUFFIXES contains LIBSUFFIX and SHLIBSUFFIX by default,
  725. # so we need to append the default suffixes to keep the ability
  726. # to link against thirdparty libraries (.a, .so, .lib, etc.).
  727. if os.name == "nt":
  728. # On Windows, only static libraries and import libraries can be
  729. # statically linked - both using .lib extension
  730. env["LIBSUFFIXES"] += [env["LIBSUFFIX"]]
  731. else:
  732. env["LIBSUFFIXES"] += [env["LIBSUFFIX"], env["SHLIBSUFFIX"]]
  733. env["LIBSUFFIX"] = suffix + env["LIBSUFFIX"]
  734. env["SHLIBSUFFIX"] = suffix + env["SHLIBSUFFIX"]
  735. if env["disable_3d"]:
  736. if env.editor_build:
  737. print("Build option 'disable_3d=yes' cannot be used for editor builds, only for export template builds.")
  738. Exit(255)
  739. else:
  740. env.Append(CPPDEFINES=["_3D_DISABLED"])
  741. if env["disable_advanced_gui"]:
  742. if env.editor_build:
  743. print(
  744. "Build option 'disable_advanced_gui=yes' cannot be used for editor builds, "
  745. "only for export template builds."
  746. )
  747. Exit(255)
  748. else:
  749. env.Append(CPPDEFINES=["ADVANCED_GUI_DISABLED"])
  750. if env["minizip"]:
  751. env.Append(CPPDEFINES=["MINIZIP_ENABLED"])
  752. if not env["verbose"]:
  753. methods.no_verbose(sys, env)
  754. GLSL_BUILDERS = {
  755. "RD_GLSL": env.Builder(
  756. action=env.Run(glsl_builders.build_rd_headers, 'Building RD_GLSL header: "$TARGET"'),
  757. suffix="glsl.gen.h",
  758. src_suffix=".glsl",
  759. ),
  760. "GLSL_HEADER": env.Builder(
  761. action=env.Run(glsl_builders.build_raw_headers, 'Building GLSL header: "$TARGET"'),
  762. suffix="glsl.gen.h",
  763. src_suffix=".glsl",
  764. ),
  765. "GLES3_GLSL": env.Builder(
  766. action=env.Run(gles3_builders.build_gles3_headers, 'Building GLES3 GLSL header: "$TARGET"'),
  767. suffix="glsl.gen.h",
  768. src_suffix=".glsl",
  769. ),
  770. }
  771. env.Append(BUILDERS=GLSL_BUILDERS)
  772. scons_cache_path = os.environ.get("SCONS_CACHE")
  773. if scons_cache_path != None:
  774. CacheDir(scons_cache_path)
  775. print("Scons cache enabled... (path: '" + scons_cache_path + "')")
  776. if env["vsproj"]:
  777. env.vs_incs = []
  778. env.vs_srcs = []
  779. if env["compiledb"]:
  780. # Generating the compilation DB (`compile_commands.json`) requires SCons 4.0.0 or later.
  781. from SCons import __version__ as scons_raw_version
  782. scons_ver = env._get_major_minor_revision(scons_raw_version)
  783. if scons_ver < (4, 0, 0):
  784. print("The `compiledb=yes` option requires SCons 4.0 or later, but your version is %s." % scons_raw_version)
  785. Exit(255)
  786. env.Tool("compilation_db")
  787. env.Alias("compiledb", env.CompilationDatabase())
  788. Export("env")
  789. # Build subdirs, the build order is dependent on link order.
  790. SConscript("core/SCsub")
  791. SConscript("servers/SCsub")
  792. SConscript("scene/SCsub")
  793. if env.editor_build:
  794. SConscript("editor/SCsub")
  795. SConscript("drivers/SCsub")
  796. SConscript("platform/SCsub")
  797. SConscript("modules/SCsub")
  798. if env["tests"]:
  799. SConscript("tests/SCsub")
  800. SConscript("main/SCsub")
  801. SConscript("platform/" + selected_platform + "/SCsub") # Build selected platform.
  802. # Microsoft Visual Studio Project Generation
  803. if env["vsproj"]:
  804. if os.name != "nt":
  805. print("Error: The `vsproj` option is only usable on Windows with Visual Studio.")
  806. Exit(255)
  807. env["CPPPATH"] = [Dir(path) for path in env["CPPPATH"]]
  808. methods.generate_vs_project(env, GetOption("num_jobs"), env["vsproj_name"])
  809. methods.generate_cpp_hint_file("cpp.hint")
  810. # Check for the existence of headers
  811. conf = Configure(env)
  812. if "check_c_headers" in env:
  813. for header in env["check_c_headers"]:
  814. if conf.CheckCHeader(header[0]):
  815. env.AppendUnique(CPPDEFINES=[header[1]])
  816. elif selected_platform != "":
  817. if selected_platform == "list":
  818. print("The following platforms are available:\n")
  819. else:
  820. print('Invalid target platform "' + selected_platform + '".')
  821. print("The following platforms were detected:\n")
  822. for x in platform_list:
  823. print("\t" + x)
  824. print("\nPlease run SCons again and select a valid platform: platform=<string>")
  825. if selected_platform == "list":
  826. # Exit early to suppress the rest of the built-in SCons messages
  827. Exit()
  828. else:
  829. Exit(255)
  830. # The following only makes sense when the 'env' is defined, and assumes it is.
  831. if "env" in locals():
  832. # FIXME: This method mixes both cosmetic progress stuff and cache handling...
  833. methods.show_progress(env)
  834. # TODO: replace this with `env.Dump(format="json")`
  835. # once we start requiring SCons 4.0 as min version.
  836. methods.dump(env)
  837. def print_elapsed_time():
  838. elapsed_time_sec = round(time.time() - time_at_start, 3)
  839. time_ms = round((elapsed_time_sec % 1) * 1000)
  840. print("[Time elapsed: {}.{:03}]".format(time.strftime("%H:%M:%S", time.gmtime(elapsed_time_sec)), time_ms))
  841. atexit.register(print_elapsed_time)