SConstruct 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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 collections import OrderedDict
  12. # Local
  13. import methods
  14. import glsl_builders
  15. import gles3_builders
  16. from platform_methods import run_in_subprocess
  17. # Scan possible build platforms
  18. platform_list = [] # list of platforms
  19. platform_opts = {} # options for each platform
  20. platform_flags = {} # flags for each platform
  21. active_platforms = []
  22. active_platform_ids = []
  23. platform_exporters = []
  24. platform_apis = []
  25. time_at_start = time.time()
  26. for x in sorted(glob.glob("platform/*")):
  27. if not os.path.isdir(x) or not os.path.exists(x + "/detect.py"):
  28. continue
  29. tmppath = "./" + x
  30. sys.path.insert(0, tmppath)
  31. import detect
  32. if os.path.exists(x + "/export/export.cpp"):
  33. platform_exporters.append(x[9:])
  34. if os.path.exists(x + "/api/api.cpp"):
  35. platform_apis.append(x[9:])
  36. if detect.is_active():
  37. active_platforms.append(detect.get_name())
  38. active_platform_ids.append(x)
  39. if detect.can_build():
  40. x = x.replace("platform/", "") # rest of world
  41. x = x.replace("platform\\", "") # win32
  42. platform_list += [x]
  43. platform_opts[x] = detect.get_opts()
  44. platform_flags[x] = detect.get_flags()
  45. sys.path.remove(tmppath)
  46. sys.modules.pop("detect")
  47. methods.save_active_platforms(active_platforms, active_platform_ids)
  48. custom_tools = ["default"]
  49. platform_arg = ARGUMENTS.get("platform", ARGUMENTS.get("p", False))
  50. if os.name == "nt" and (platform_arg == "android" or methods.get_cmdline_bool("use_mingw", False)):
  51. custom_tools = ["mingw"]
  52. elif platform_arg == "javascript":
  53. # Use generic POSIX build toolchain for Emscripten.
  54. custom_tools = ["cc", "c++", "ar", "link", "textfile", "zip"]
  55. # We let SCons build its default ENV as it includes OS-specific things which we don't
  56. # want to have to pull in manually.
  57. # Then we prepend PATH to make it take precedence, while preserving SCons' own entries.
  58. env_base = Environment(tools=custom_tools)
  59. env_base.PrependENVPath("PATH", os.getenv("PATH"))
  60. env_base.PrependENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH"))
  61. if "TERM" in os.environ: # Used for colored output.
  62. env_base["ENV"]["TERM"] = os.environ["TERM"]
  63. env_base.disabled_modules = []
  64. env_base.module_version_string = ""
  65. env_base.msvc = False
  66. env_base.__class__.disable_module = methods.disable_module
  67. env_base.__class__.add_module_version_string = methods.add_module_version_string
  68. env_base.__class__.add_source_files = methods.add_source_files
  69. env_base.__class__.use_windows_spawn_fix = methods.use_windows_spawn_fix
  70. env_base.__class__.add_shared_library = methods.add_shared_library
  71. env_base.__class__.add_library = methods.add_library
  72. env_base.__class__.add_program = methods.add_program
  73. env_base.__class__.CommandNoCache = methods.CommandNoCache
  74. env_base.__class__.Run = methods.Run
  75. env_base.__class__.disable_warnings = methods.disable_warnings
  76. env_base.__class__.force_optimization_on_debug = methods.force_optimization_on_debug
  77. env_base.__class__.module_check_dependencies = methods.module_check_dependencies
  78. env_base["x86_libtheora_opt_gcc"] = False
  79. env_base["x86_libtheora_opt_vc"] = False
  80. # avoid issues when building with different versions of python out of the same directory
  81. env_base.SConsignFile(".sconsign{0}.dblite".format(pickle.HIGHEST_PROTOCOL))
  82. # Build options
  83. customs = ["custom.py"]
  84. profile = ARGUMENTS.get("profile", "")
  85. if profile:
  86. if os.path.isfile(profile):
  87. customs.append(profile)
  88. elif os.path.isfile(profile + ".py"):
  89. customs.append(profile + ".py")
  90. opts = Variables(customs, ARGUMENTS)
  91. # Target build options
  92. opts.Add("p", "Platform (alias for 'platform')", "")
  93. opts.Add("platform", "Target platform (%s)" % ("|".join(platform_list),), "")
  94. opts.Add(BoolVariable("tools", "Build the tools (a.k.a. the Godot editor)", True))
  95. opts.Add(EnumVariable("target", "Compilation target", "debug", ("debug", "release_debug", "release")))
  96. opts.Add("arch", "Platform-dependent architecture (arm/arm64/x86/x64/mips/...)", "")
  97. opts.Add(EnumVariable("bits", "Target platform bits", "default", ("default", "32", "64")))
  98. opts.Add(EnumVariable("float", "Floating-point precision", "default", ("default", "32", "64")))
  99. opts.Add(EnumVariable("optimize", "Optimization type", "speed", ("speed", "size", "none")))
  100. opts.Add(BoolVariable("production", "Set defaults to build Godot for use in production", False))
  101. opts.Add(BoolVariable("use_lto", "Use link-time optimization", False))
  102. # Components
  103. opts.Add(BoolVariable("deprecated", "Enable deprecated features", True))
  104. opts.Add(BoolVariable("minizip", "Enable ZIP archive support using minizip", True))
  105. opts.Add(BoolVariable("xaudio2", "Enable the XAudio2 audio driver", False))
  106. opts.Add(BoolVariable("vulkan", "Enable the vulkan video driver", True))
  107. opts.Add(BoolVariable("opengl3", "Enable the OpenGL/GLES3 video driver", True))
  108. opts.Add("custom_modules", "A list of comma-separated directory paths containing custom modules to build.", "")
  109. opts.Add(BoolVariable("custom_modules_recursive", "Detect custom modules recursively for each specified path.", True))
  110. opts.Add(BoolVariable("use_volk", "Use the volk library to load the Vulkan loader dynamically", True))
  111. # Advanced options
  112. opts.Add(BoolVariable("dev", "If yes, alias for verbose=yes warnings=extra werror=yes", False))
  113. opts.Add(BoolVariable("progress", "Show a progress indicator during compilation", True))
  114. opts.Add(BoolVariable("tests", "Build the unit tests", False))
  115. opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False))
  116. opts.Add(EnumVariable("warnings", "Level of compilation warnings", "all", ("extra", "all", "moderate", "no")))
  117. opts.Add(BoolVariable("werror", "Treat compiler warnings as errors", False))
  118. opts.Add("extra_suffix", "Custom extra suffix added to the base filename of all generated binary files", "")
  119. opts.Add(BoolVariable("vsproj", "Generate a Visual Studio solution", False))
  120. opts.Add(BoolVariable("disable_3d", "Disable 3D nodes for a smaller executable", False))
  121. opts.Add(BoolVariable("disable_advanced_gui", "Disable advanced GUI nodes and behaviors", False))
  122. opts.Add("disable_classes", "Disable given classes (comma separated)", "")
  123. opts.Add(BoolVariable("modules_enabled_by_default", "If no, disable all modules except ones explicitly enabled", True))
  124. opts.Add(BoolVariable("no_editor_splash", "Don't use the custom splash screen for the editor", False))
  125. opts.Add("system_certs_path", "Use this path as SSL certificates default for editor (for package maintainers)", "")
  126. opts.Add(BoolVariable("use_precise_math_checks", "Math checks use very precise epsilon (debug option)", False))
  127. # Thirdparty libraries
  128. opts.Add(BoolVariable("builtin_bullet", "Use the built-in Bullet library", True))
  129. opts.Add(BoolVariable("builtin_certs", "Use the built-in SSL certificates bundles", True))
  130. opts.Add(BoolVariable("builtin_embree", "Use the built-in Embree library", True))
  131. opts.Add(BoolVariable("builtin_enet", "Use the built-in ENet library", True))
  132. opts.Add(BoolVariable("builtin_freetype", "Use the built-in FreeType library", True))
  133. opts.Add(BoolVariable("builtin_msdfgen", "Use the built-in MSDFgen library", True))
  134. opts.Add(BoolVariable("builtin_glslang", "Use the built-in glslang library", True))
  135. opts.Add(BoolVariable("builtin_graphite", "Use the built-in Graphite library", True))
  136. opts.Add(BoolVariable("builtin_harfbuzz", "Use the built-in HarfBuzz library", True))
  137. opts.Add(BoolVariable("builtin_icu", "Use the built-in ICU library", True))
  138. opts.Add(BoolVariable("builtin_libogg", "Use the built-in libogg library", True))
  139. opts.Add(BoolVariable("builtin_libpng", "Use the built-in libpng library", True))
  140. opts.Add(BoolVariable("builtin_libtheora", "Use the built-in libtheora library", True))
  141. opts.Add(BoolVariable("builtin_libvorbis", "Use the built-in libvorbis library", True))
  142. opts.Add(BoolVariable("builtin_libwebp", "Use the built-in libwebp library", True))
  143. opts.Add(BoolVariable("builtin_wslay", "Use the built-in wslay library", True))
  144. opts.Add(BoolVariable("builtin_mbedtls", "Use the built-in mbedTLS library", True))
  145. opts.Add(BoolVariable("builtin_miniupnpc", "Use the built-in miniupnpc library", True))
  146. opts.Add(BoolVariable("builtin_pcre2", "Use the built-in PCRE2 library", True))
  147. opts.Add(BoolVariable("builtin_pcre2_with_jit", "Use JIT compiler for the built-in PCRE2 library", True))
  148. opts.Add(BoolVariable("builtin_recast", "Use the built-in Recast library", True))
  149. opts.Add(BoolVariable("builtin_rvo2", "Use the built-in RVO2 library", True))
  150. opts.Add(BoolVariable("builtin_squish", "Use the built-in squish library", True))
  151. opts.Add(BoolVariable("builtin_xatlas", "Use the built-in xatlas library", True))
  152. opts.Add(BoolVariable("builtin_zlib", "Use the built-in zlib library", True))
  153. opts.Add(BoolVariable("builtin_zstd", "Use the built-in Zstd library", True))
  154. # Compilation environment setup
  155. opts.Add("CXX", "C++ compiler")
  156. opts.Add("CC", "C compiler")
  157. opts.Add("LINK", "Linker")
  158. opts.Add("CCFLAGS", "Custom flags for both the C and C++ compilers")
  159. opts.Add("CFLAGS", "Custom flags for the C compiler")
  160. opts.Add("CXXFLAGS", "Custom flags for the C++ compiler")
  161. opts.Add("LINKFLAGS", "Custom flags for the linker")
  162. # Update the environment to have all above options defined
  163. # in following code (especially platform and custom_modules).
  164. opts.Update(env_base)
  165. # Platform selection: validate input, and add options.
  166. selected_platform = ""
  167. if env_base["platform"] != "":
  168. selected_platform = env_base["platform"]
  169. elif env_base["p"] != "":
  170. selected_platform = env_base["p"]
  171. else:
  172. # Missing `platform` argument, try to detect platform automatically
  173. if (
  174. sys.platform.startswith("linux")
  175. or sys.platform.startswith("dragonfly")
  176. or sys.platform.startswith("freebsd")
  177. or sys.platform.startswith("netbsd")
  178. or sys.platform.startswith("openbsd")
  179. ):
  180. selected_platform = "linuxbsd"
  181. elif sys.platform == "darwin":
  182. selected_platform = "osx"
  183. elif sys.platform == "win32":
  184. selected_platform = "windows"
  185. else:
  186. print("Could not detect platform automatically. Supported platforms:")
  187. for x in platform_list:
  188. print("\t" + x)
  189. print("\nPlease run SCons again and select a valid platform: platform=<string>")
  190. if selected_platform != "":
  191. print("Automatically detected platform: " + selected_platform)
  192. if selected_platform in ["linux", "bsd", "x11"]:
  193. if selected_platform == "x11":
  194. # Deprecated alias kept for compatibility.
  195. print('Platform "x11" has been renamed to "linuxbsd" in Godot 4.0. Building for platform "linuxbsd".')
  196. # Alias for convenience.
  197. selected_platform = "linuxbsd"
  198. # Make sure to update this to the found, valid platform as it's used through the buildsystem as the reference.
  199. # It should always be re-set after calling `opts.Update()` otherwise it uses the original input value.
  200. env_base["platform"] = selected_platform
  201. # Add platform-specific options.
  202. if selected_platform in platform_opts:
  203. for opt in platform_opts[selected_platform]:
  204. opts.Add(opt)
  205. # Update the environment to take platform-specific options into account.
  206. opts.Update(env_base)
  207. env_base["platform"] = selected_platform # Must always be re-set after calling opts.Update().
  208. # Detect modules.
  209. modules_detected = OrderedDict()
  210. module_search_paths = ["modules"] # Built-in path.
  211. if env_base["custom_modules"]:
  212. paths = env_base["custom_modules"].split(",")
  213. for p in paths:
  214. try:
  215. module_search_paths.append(methods.convert_custom_modules_path(p))
  216. except ValueError as e:
  217. print(e)
  218. Exit(255)
  219. for path in module_search_paths:
  220. if path == "modules":
  221. # Built-in modules don't have nested modules,
  222. # so save the time it takes to parse directories.
  223. modules = methods.detect_modules(path, recursive=False)
  224. else: # Custom.
  225. modules = methods.detect_modules(path, env_base["custom_modules_recursive"])
  226. # Provide default include path for both the custom module search `path`
  227. # and the base directory containing custom modules, as it may be different
  228. # from the built-in "modules" name (e.g. "custom_modules/summator/summator.h"),
  229. # so it can be referenced simply as `#include "summator/summator.h"`
  230. # independently of where a module is located on user's filesystem.
  231. env_base.Prepend(CPPPATH=[path, os.path.dirname(path)])
  232. # Note: custom modules can override built-in ones.
  233. modules_detected.update(modules)
  234. # Add module options.
  235. for name, path in modules_detected.items():
  236. if env_base["modules_enabled_by_default"]:
  237. enabled = True
  238. sys.path.insert(0, path)
  239. import config
  240. try:
  241. enabled = config.is_enabled()
  242. except AttributeError:
  243. pass
  244. sys.path.remove(path)
  245. sys.modules.pop("config")
  246. else:
  247. enabled = False
  248. opts.Add(BoolVariable("module_" + name + "_enabled", "Enable module '%s'" % (name,), enabled))
  249. methods.write_modules(modules_detected)
  250. # Update the environment again after all the module options are added.
  251. opts.Update(env_base)
  252. env_base["platform"] = selected_platform # Must always be re-set after calling opts.Update().
  253. Help(opts.GenerateHelpText(env_base))
  254. # add default include paths
  255. env_base.Prepend(CPPPATH=["#"])
  256. # configure ENV for platform
  257. env_base.platform_exporters = platform_exporters
  258. env_base.platform_apis = platform_apis
  259. # Build type defines - more platform-specific ones can be in detect.py.
  260. if env_base["target"] == "release_debug" or env_base["target"] == "debug":
  261. # DEBUG_ENABLED enables debugging *features* and debug-only code, which is intended
  262. # to give *users* extra debugging information for their game development.
  263. env_base.Append(CPPDEFINES=["DEBUG_ENABLED"])
  264. if env_base["target"] == "debug":
  265. # DEV_ENABLED enables *engine developer* code which should only be compiled for those
  266. # working on the engine itself.
  267. env_base.Append(CPPDEFINES=["DEV_ENABLED"])
  268. if env_base["use_precise_math_checks"]:
  269. env_base.Append(CPPDEFINES=["PRECISE_MATH_CHECKS"])
  270. if env_base["no_editor_splash"]:
  271. env_base.Append(CPPDEFINES=["NO_EDITOR_SPLASH"])
  272. if not env_base["deprecated"]:
  273. env_base.Append(CPPDEFINES=["DISABLE_DEPRECATED"])
  274. if env_base["float"] == "64":
  275. env_base.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  276. if selected_platform in platform_list:
  277. tmppath = "./platform/" + selected_platform
  278. sys.path.insert(0, tmppath)
  279. import detect
  280. if "create" in dir(detect):
  281. env = detect.create(env_base)
  282. else:
  283. env = env_base.Clone()
  284. # Generating the compilation DB (`compile_commands.json`) requires SCons 4.0.0 or later.
  285. from SCons import __version__ as scons_raw_version
  286. scons_ver = env._get_major_minor_revision(scons_raw_version)
  287. if scons_ver >= (4, 0, 0):
  288. env.Tool("compilation_db")
  289. env.Alias("compiledb", env.CompilationDatabase())
  290. # 'dev' and 'production' are aliases to set default options if they haven't been set
  291. # manually by the user.
  292. if env["dev"]:
  293. env["verbose"] = methods.get_cmdline_bool("verbose", True)
  294. env["warnings"] = ARGUMENTS.get("warnings", "extra")
  295. env["werror"] = methods.get_cmdline_bool("werror", True)
  296. if env["tools"]:
  297. env["tests"] = methods.get_cmdline_bool("tests", True)
  298. if env["production"]:
  299. env["use_static_cpp"] = methods.get_cmdline_bool("use_static_cpp", True)
  300. env["use_lto"] = methods.get_cmdline_bool("use_lto", True)
  301. env["debug_symbols"] = methods.get_cmdline_bool("debug_symbols", False)
  302. if not env["tools"] and env["target"] == "debug":
  303. print(
  304. "WARNING: Requested `production` build with `tools=no target=debug`, "
  305. "this will give you a full debug template (use `target=release_debug` "
  306. "for an optimized template with debug features)."
  307. )
  308. if env.msvc:
  309. print(
  310. "WARNING: For `production` Windows builds, you should use MinGW with GCC "
  311. "or Clang instead of Visual Studio, as they can better optimize the "
  312. "GDScript VM in a very significant way. MSVC LTO also doesn't work "
  313. "reliably for our use case."
  314. "If you want to use MSVC nevertheless for production builds, set "
  315. "`debug_symbols=no use_lto=no` instead of the `production=yes` option."
  316. )
  317. Exit(255)
  318. env.extra_suffix = ""
  319. if env["extra_suffix"] != "":
  320. env.extra_suffix += "." + env["extra_suffix"]
  321. # Environment flags
  322. CCFLAGS = env.get("CCFLAGS", "")
  323. env["CCFLAGS"] = ""
  324. env.Append(CCFLAGS=str(CCFLAGS).split())
  325. CFLAGS = env.get("CFLAGS", "")
  326. env["CFLAGS"] = ""
  327. env.Append(CFLAGS=str(CFLAGS).split())
  328. CXXFLAGS = env.get("CXXFLAGS", "")
  329. env["CXXFLAGS"] = ""
  330. env.Append(CXXFLAGS=str(CXXFLAGS).split())
  331. LINKFLAGS = env.get("LINKFLAGS", "")
  332. env["LINKFLAGS"] = ""
  333. env.Append(LINKFLAGS=str(LINKFLAGS).split())
  334. # Platform specific flags
  335. flag_list = platform_flags[selected_platform]
  336. for f in flag_list:
  337. if not (f[0] in ARGUMENTS): # allow command line to override platform flags
  338. env[f[0]] = f[1]
  339. # Must happen after the flags' definition, so that they can be used by platform detect
  340. detect.configure(env)
  341. # Set our C and C++ standard requirements.
  342. # C++17 is required as we need guaranteed copy elision as per GH-36436.
  343. # Prepending to make it possible to override.
  344. # This needs to come after `configure`, otherwise we don't have env.msvc.
  345. if not env.msvc:
  346. # Specifying GNU extensions support explicitly, which are supported by
  347. # both GCC and Clang. Both currently default to gnu11 and gnu++14.
  348. env.Prepend(CFLAGS=["-std=gnu11"])
  349. env.Prepend(CXXFLAGS=["-std=gnu++17"])
  350. else:
  351. # MSVC doesn't have clear C standard support, /std only covers C++.
  352. # We apply it to CCFLAGS (both C and C++ code) in case it impacts C features.
  353. env.Prepend(CCFLAGS=["/std:c++17"])
  354. # Enforce our minimal compiler version requirements
  355. cc_version = methods.get_compiler_version(env) or {
  356. "major": None,
  357. "minor": None,
  358. "patch": None,
  359. "metadata1": None,
  360. "metadata2": None,
  361. "date": None,
  362. }
  363. cc_version_major = int(cc_version["major"] or -1)
  364. cc_version_minor = int(cc_version["minor"] or -1)
  365. cc_version_metadata1 = cc_version["metadata1"] or ""
  366. if methods.using_gcc(env):
  367. if cc_version_major == -1:
  368. print(
  369. "Couldn't detect compiler version, skipping version checks. "
  370. "Build may fail if the compiler doesn't support C++17 fully."
  371. )
  372. # GCC 8 before 8.4 has a regression in the support of guaranteed copy elision
  373. # which causes a build failure: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86521
  374. elif cc_version_major == 8 and cc_version_minor < 4:
  375. print(
  376. "Detected GCC 8 version < 8.4, which is not supported due to a "
  377. "regression in its C++17 guaranteed copy elision support. Use a "
  378. 'newer GCC version, or Clang 6 or later by passing "use_llvm=yes" '
  379. "to the SCons command line."
  380. )
  381. Exit(255)
  382. elif cc_version_major < 7:
  383. print(
  384. "Detected GCC version older than 7, which does not fully support "
  385. "C++17. Supported versions are GCC 7, 9 and later. Use a newer GCC "
  386. 'version, or Clang 6 or later by passing "use_llvm=yes" to the '
  387. "SCons command line."
  388. )
  389. Exit(255)
  390. elif cc_version_metadata1 == "win32":
  391. print(
  392. "Detected mingw version is not using posix threads. Only posix "
  393. "version of mingw is supported. "
  394. 'Use "update-alternatives --config <platform>-w64-mingw32-[gcc|g++]" '
  395. "to switch to posix threads."
  396. )
  397. Exit(255)
  398. elif methods.using_clang(env):
  399. if cc_version_major == -1:
  400. print(
  401. "Couldn't detect compiler version, skipping version checks. "
  402. "Build may fail if the compiler doesn't support C++17 fully."
  403. )
  404. # Apple LLVM versions differ from upstream LLVM version \o/, compare
  405. # in https://en.wikipedia.org/wiki/Xcode#Toolchain_versions
  406. elif env["platform"] == "osx" or env["platform"] == "iphone":
  407. vanilla = methods.is_vanilla_clang(env)
  408. if vanilla and cc_version_major < 6:
  409. print(
  410. "Detected Clang version older than 6, which does not fully support "
  411. "C++17. Supported versions are Clang 6 and later."
  412. )
  413. Exit(255)
  414. elif not vanilla and cc_version_major < 10:
  415. print(
  416. "Detected Apple Clang version older than 10, which does not fully "
  417. "support C++17. Supported versions are Apple Clang 10 and later."
  418. )
  419. Exit(255)
  420. elif cc_version_major < 6:
  421. print(
  422. "Detected Clang version older than 6, which does not fully support "
  423. "C++17. Supported versions are Clang 6 and later."
  424. )
  425. Exit(255)
  426. # Configure compiler warnings
  427. if env.msvc: # MSVC
  428. # Truncations, narrowing conversions, signed/unsigned comparisons...
  429. disable_nonessential_warnings = ["/wd4267", "/wd4244", "/wd4305", "/wd4018", "/wd4800"]
  430. if env["warnings"] == "extra":
  431. env.Append(CCFLAGS=["/Wall"]) # Implies /W4
  432. elif env["warnings"] == "all":
  433. env.Append(CCFLAGS=["/W3"] + disable_nonessential_warnings)
  434. elif env["warnings"] == "moderate":
  435. env.Append(CCFLAGS=["/W2"] + disable_nonessential_warnings)
  436. else: # 'no'
  437. env.Append(CCFLAGS=["/w"])
  438. # Set exception handling model to avoid warnings caused by Windows system headers.
  439. env.Append(CCFLAGS=["/EHsc"])
  440. if env["werror"]:
  441. env.Append(CCFLAGS=["/WX"])
  442. else: # GCC, Clang
  443. common_warnings = []
  444. if methods.using_gcc(env):
  445. common_warnings += ["-Wshadow-local", "-Wno-misleading-indentation"]
  446. elif methods.using_clang(env) or methods.using_emcc(env):
  447. # We often implement `operator<` for structs of pointers as a requirement
  448. # for putting them in `Set` or `Map`. We don't mind about unreliable ordering.
  449. common_warnings += ["-Wno-ordered-compare-function-pointers"]
  450. if env["warnings"] == "extra":
  451. env.Append(CCFLAGS=["-Wall", "-Wextra", "-Wwrite-strings", "-Wno-unused-parameter"] + common_warnings)
  452. env.Append(CXXFLAGS=["-Wctor-dtor-privacy", "-Wnon-virtual-dtor"])
  453. if methods.using_gcc(env):
  454. env.Append(
  455. CCFLAGS=[
  456. "-Walloc-zero",
  457. "-Wduplicated-branches",
  458. "-Wduplicated-cond",
  459. "-Wstringop-overflow=4",
  460. "-Wlogical-op",
  461. ]
  462. )
  463. # -Wnoexcept was removed temporarily due to GH-36325.
  464. env.Append(CXXFLAGS=["-Wplacement-new=1"])
  465. if cc_version_major >= 9:
  466. env.Append(CCFLAGS=["-Wattribute-alias=2"])
  467. elif methods.using_clang(env) or methods.using_emcc(env):
  468. env.Append(CCFLAGS=["-Wimplicit-fallthrough"])
  469. elif env["warnings"] == "all":
  470. env.Append(CCFLAGS=["-Wall"] + common_warnings)
  471. elif env["warnings"] == "moderate":
  472. env.Append(CCFLAGS=["-Wall", "-Wno-unused"] + common_warnings)
  473. else: # 'no'
  474. env.Append(CCFLAGS=["-w"])
  475. if env["werror"]:
  476. env.Append(CCFLAGS=["-Werror"])
  477. # FIXME: Temporary workaround after the Vulkan merge, remove once warnings are fixed.
  478. if methods.using_gcc(env):
  479. env.Append(CXXFLAGS=["-Wno-error=cpp"])
  480. if cc_version_major == 7: # Bogus warning fixed in 8+.
  481. env.Append(CCFLAGS=["-Wno-error=strict-overflow"])
  482. elif methods.using_clang(env) or methods.using_emcc(env):
  483. env.Append(CXXFLAGS=["-Wno-error=#warnings"])
  484. else: # always enable those errors
  485. env.Append(CCFLAGS=["-Werror=return-type"])
  486. if hasattr(detect, "get_program_suffix"):
  487. suffix = "." + detect.get_program_suffix()
  488. else:
  489. suffix = "." + selected_platform
  490. if env_base["float"] == "64":
  491. suffix += ".double"
  492. if env["target"] == "release":
  493. if env["tools"]:
  494. print("Error: The editor can only be built with `target=debug` or `target=release_debug`.")
  495. Exit(255)
  496. suffix += ".opt"
  497. env.Append(CPPDEFINES=["NDEBUG"])
  498. elif env["target"] == "release_debug":
  499. if env["tools"]:
  500. suffix += ".opt.tools"
  501. else:
  502. suffix += ".opt.debug"
  503. else:
  504. if env["tools"]:
  505. print(
  506. "Note: Building a debug binary (which will run slowly). Use `target=release_debug` to build an optimized release binary."
  507. )
  508. suffix += ".tools"
  509. else:
  510. print(
  511. "Note: Building a debug binary (which will run slowly). Use `target=release` to build an optimized release binary."
  512. )
  513. suffix += ".debug"
  514. if env["arch"] != "":
  515. suffix += "." + env["arch"]
  516. elif env["bits"] == "32":
  517. suffix += ".32"
  518. elif env["bits"] == "64":
  519. suffix += ".64"
  520. suffix += env.extra_suffix
  521. sys.path.remove(tmppath)
  522. sys.modules.pop("detect")
  523. modules_enabled = OrderedDict()
  524. env.module_icons_paths = []
  525. env.doc_class_path = {}
  526. for name, path in modules_detected.items():
  527. if not env["module_" + name + "_enabled"]:
  528. continue
  529. sys.path.insert(0, path)
  530. env.current_module = name
  531. import config
  532. if config.can_build(env, selected_platform):
  533. config.configure(env)
  534. # Get doc classes paths (if present)
  535. try:
  536. doc_classes = config.get_doc_classes()
  537. doc_path = config.get_doc_path()
  538. for c in doc_classes:
  539. env.doc_class_path[c] = path + "/" + doc_path
  540. except Exception:
  541. pass
  542. # Get icon paths (if present)
  543. try:
  544. icons_path = config.get_icons_path()
  545. env.module_icons_paths.append(path + "/" + icons_path)
  546. except Exception:
  547. # Default path for module icons
  548. env.module_icons_paths.append(path + "/" + "icons")
  549. modules_enabled[name] = path
  550. sys.path.remove(path)
  551. sys.modules.pop("config")
  552. env.module_list = modules_enabled
  553. methods.update_version(env.module_version_string)
  554. env["PROGSUFFIX"] = suffix + env.module_version_string + env["PROGSUFFIX"]
  555. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  556. # (SH)LIBSUFFIX will be used for our own built libraries
  557. # LIBSUFFIXES contains LIBSUFFIX and SHLIBSUFFIX by default,
  558. # so we need to append the default suffixes to keep the ability
  559. # to link against thirdparty libraries (.a, .so, .lib, etc.).
  560. if os.name == "nt":
  561. # On Windows, only static libraries and import libraries can be
  562. # statically linked - both using .lib extension
  563. env["LIBSUFFIXES"] += [env["LIBSUFFIX"]]
  564. else:
  565. env["LIBSUFFIXES"] += [env["LIBSUFFIX"], env["SHLIBSUFFIX"]]
  566. env["LIBSUFFIX"] = suffix + env["LIBSUFFIX"]
  567. env["SHLIBSUFFIX"] = suffix + env["SHLIBSUFFIX"]
  568. if env["tools"]:
  569. env.Append(CPPDEFINES=["TOOLS_ENABLED"])
  570. methods.write_disabled_classes(env["disable_classes"].split(","))
  571. if env["disable_3d"]:
  572. if env["tools"]:
  573. print(
  574. "Build option 'disable_3d=yes' cannot be used with 'tools=yes' (editor), "
  575. "only with 'tools=no' (export template)."
  576. )
  577. Exit(255)
  578. else:
  579. env.Append(CPPDEFINES=["_3D_DISABLED"])
  580. if env["disable_advanced_gui"]:
  581. if env["tools"]:
  582. print(
  583. "Build option 'disable_advanced_gui=yes' cannot be used with 'tools=yes' (editor), "
  584. "only with 'tools=no' (export template)."
  585. )
  586. Exit(255)
  587. else:
  588. env.Append(CPPDEFINES=["ADVANCED_GUI_DISABLED"])
  589. if env["minizip"]:
  590. env.Append(CPPDEFINES=["MINIZIP_ENABLED"])
  591. editor_module_list = ["freetype"]
  592. if env["tools"] and not env.module_check_dependencies("tools", editor_module_list):
  593. print(
  594. "Build option 'module_"
  595. + x
  596. + "_enabled=no' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template)."
  597. )
  598. Exit(255)
  599. if not env["verbose"]:
  600. methods.no_verbose(sys, env)
  601. GLSL_BUILDERS = {
  602. "RD_GLSL": env.Builder(
  603. action=env.Run(glsl_builders.build_rd_headers, 'Building RD_GLSL header: "$TARGET"'),
  604. suffix="glsl.gen.h",
  605. src_suffix=".glsl",
  606. ),
  607. "GLSL_HEADER": env.Builder(
  608. action=env.Run(glsl_builders.build_raw_headers, 'Building GLSL header: "$TARGET"'),
  609. suffix="glsl.gen.h",
  610. src_suffix=".glsl",
  611. ),
  612. }
  613. env.Append(BUILDERS=GLSL_BUILDERS)
  614. if not env["platform"] == "server":
  615. env.Append(
  616. BUILDERS={
  617. "GLES3_GLSL": env.Builder(
  618. action=run_in_subprocess(gles3_builders.build_gles3_headers),
  619. suffix="glsl.gen.h",
  620. src_suffix=".glsl",
  621. )
  622. }
  623. )
  624. scons_cache_path = os.environ.get("SCONS_CACHE")
  625. if scons_cache_path != None:
  626. CacheDir(scons_cache_path)
  627. print("Scons cache enabled... (path: '" + scons_cache_path + "')")
  628. if env["vsproj"]:
  629. env.vs_incs = []
  630. env.vs_srcs = []
  631. Export("env")
  632. # Build subdirs, the build order is dependent on link order.
  633. SConscript("core/SCsub")
  634. SConscript("servers/SCsub")
  635. SConscript("scene/SCsub")
  636. SConscript("editor/SCsub")
  637. SConscript("drivers/SCsub")
  638. SConscript("platform/SCsub")
  639. SConscript("modules/SCsub")
  640. if env["tests"]:
  641. SConscript("tests/SCsub")
  642. SConscript("main/SCsub")
  643. SConscript("platform/" + selected_platform + "/SCsub") # Build selected platform.
  644. # Microsoft Visual Studio Project Generation
  645. if env["vsproj"]:
  646. env["CPPPATH"] = [Dir(path) for path in env["CPPPATH"]]
  647. methods.generate_vs_project(env, GetOption("num_jobs"))
  648. methods.generate_cpp_hint_file("cpp.hint")
  649. # Check for the existence of headers
  650. conf = Configure(env)
  651. if "check_c_headers" in env:
  652. for header in env["check_c_headers"]:
  653. if conf.CheckCHeader(header[0]):
  654. env.AppendUnique(CPPDEFINES=[header[1]])
  655. elif selected_platform != "":
  656. if selected_platform == "list":
  657. print("The following platforms are available:\n")
  658. else:
  659. print('Invalid target platform "' + selected_platform + '".')
  660. print("The following platforms were detected:\n")
  661. for x in platform_list:
  662. print("\t" + x)
  663. print("\nPlease run SCons again and select a valid platform: platform=<string>")
  664. if selected_platform == "list":
  665. # Exit early to suppress the rest of the built-in SCons messages
  666. Exit()
  667. else:
  668. Exit(255)
  669. # The following only makes sense when the 'env' is defined, and assumes it is.
  670. if "env" in locals():
  671. methods.show_progress(env)
  672. # TODO: replace this with `env.Dump(format="json")`
  673. # once we start requiring SCons 4.0 as min version.
  674. methods.dump(env)
  675. def print_elapsed_time():
  676. elapsed_time_sec = round(time.time() - time_at_start, 3)
  677. time_ms = round((elapsed_time_sec % 1) * 1000)
  678. print("[Time elapsed: {}.{:03}]".format(time.strftime("%H:%M:%S", time.gmtime(elapsed_time_sec)), time_ms))
  679. atexit.register(print_elapsed_time)