SConstruct 43 KB

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