SConstruct 44 KB

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