SConstruct 45 KB

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