SConstruct 42 KB

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