SConstruct 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. #!/usr/bin/env python
  2. EnsureSConsVersion(0, 98, 1)
  3. # System
  4. import glob
  5. import os
  6. import pickle
  7. import sys
  8. # Local
  9. import methods
  10. import gles_builders
  11. from platform_methods import run_in_subprocess
  12. # scan possible build platforms
  13. platform_list = [] # list of platforms
  14. platform_opts = {} # options for each platform
  15. platform_flags = {} # flags for each platform
  16. active_platforms = []
  17. active_platform_ids = []
  18. platform_exporters = []
  19. platform_apis = []
  20. for x in sorted(glob.glob("platform/*")):
  21. if (not os.path.isdir(x) or not os.path.exists(x + "/detect.py")):
  22. continue
  23. tmppath = "./" + x
  24. sys.path.insert(0, tmppath)
  25. import detect
  26. if (os.path.exists(x + "/export/export.cpp")):
  27. platform_exporters.append(x[9:])
  28. if (os.path.exists(x + "/api/api.cpp")):
  29. platform_apis.append(x[9:])
  30. if (detect.is_active()):
  31. active_platforms.append(detect.get_name())
  32. active_platform_ids.append(x)
  33. if (detect.can_build()):
  34. x = x.replace("platform/", "") # rest of world
  35. x = x.replace("platform\\", "") # win32
  36. platform_list += [x]
  37. platform_opts[x] = detect.get_opts()
  38. platform_flags[x] = detect.get_flags()
  39. sys.path.remove(tmppath)
  40. sys.modules.pop('detect')
  41. module_list = methods.detect_modules()
  42. methods.save_active_platforms(active_platforms, active_platform_ids)
  43. custom_tools = ['default']
  44. platform_arg = ARGUMENTS.get("platform", ARGUMENTS.get("p", False))
  45. if os.name == "nt" and (platform_arg == "android" or ARGUMENTS.get("use_mingw", False)):
  46. custom_tools = ['mingw']
  47. elif platform_arg == 'javascript':
  48. # Use generic POSIX build toolchain for Emscripten.
  49. custom_tools = ['cc', 'c++', 'ar', 'link', 'textfile', 'zip']
  50. env_base = Environment(tools=custom_tools)
  51. if 'TERM' in os.environ:
  52. env_base['ENV']['TERM'] = os.environ['TERM']
  53. env_base.AppendENVPath('PATH', os.getenv('PATH'))
  54. env_base.AppendENVPath('PKG_CONFIG_PATH', os.getenv('PKG_CONFIG_PATH'))
  55. env_base.disabled_modules = []
  56. env_base.use_ptrcall = False
  57. env_base.module_version_string = ""
  58. env_base.msvc = False
  59. env_base.__class__.disable_module = methods.disable_module
  60. env_base.__class__.add_module_version_string = methods.add_module_version_string
  61. env_base.__class__.add_source_files = methods.add_source_files
  62. env_base.__class__.use_windows_spawn_fix = methods.use_windows_spawn_fix
  63. env_base.__class__.split_lib = methods.split_lib
  64. env_base.__class__.add_shared_library = methods.add_shared_library
  65. env_base.__class__.add_library = methods.add_library
  66. env_base.__class__.add_program = methods.add_program
  67. env_base.__class__.CommandNoCache = methods.CommandNoCache
  68. env_base.__class__.disable_warnings = methods.disable_warnings
  69. env_base["x86_libtheora_opt_gcc"] = False
  70. env_base["x86_libtheora_opt_vc"] = False
  71. # avoid issues when building with different versions of python out of the same directory
  72. env_base.SConsignFile(".sconsign{0}.dblite".format(pickle.HIGHEST_PROTOCOL))
  73. # Build options
  74. customs = ['custom.py']
  75. profile = ARGUMENTS.get("profile", False)
  76. if profile:
  77. if os.path.isfile(profile):
  78. customs.append(profile)
  79. elif os.path.isfile(profile + ".py"):
  80. customs.append(profile + ".py")
  81. opts = Variables(customs, ARGUMENTS)
  82. # Target build options
  83. opts.Add('arch', "Platform-dependent architecture (arm/arm64/x86/x64/mips/...)", '')
  84. opts.Add(EnumVariable('bits', "Target platform bits", 'default', ('default', '32', '64')))
  85. opts.Add('p', "Platform (alias for 'platform')", '')
  86. opts.Add('platform', "Target platform (%s)" % ('|'.join(platform_list), ), '')
  87. opts.Add(EnumVariable('target', "Compilation target", 'debug', ('debug', 'release_debug', 'release')))
  88. opts.Add(EnumVariable('optimize', "Optimization type", 'speed', ('speed', 'size')))
  89. opts.Add(BoolVariable('tools', "Build the tools (a.k.a. the Godot editor)", True))
  90. opts.Add(BoolVariable('use_lto', 'Use link-time optimization', False))
  91. opts.Add(BoolVariable('use_precise_math_checks', 'Math checks use very precise epsilon (useful to debug the engine)', False))
  92. # Components
  93. opts.Add(BoolVariable('deprecated', "Enable deprecated features", True))
  94. opts.Add(BoolVariable('gdscript', "Enable GDScript support", True))
  95. opts.Add(BoolVariable('minizip', "Enable ZIP archive support using minizip", True))
  96. opts.Add(BoolVariable('xaudio2', "Enable the XAudio2 audio driver", False))
  97. # Advanced options
  98. opts.Add(BoolVariable('verbose', "Enable verbose output for the compilation", False))
  99. opts.Add(BoolVariable('progress', "Show a progress indicator during compilation", True))
  100. opts.Add(EnumVariable('warnings', "Set the level of warnings emitted during compilation", 'all', ('extra', 'all', 'moderate', 'no')))
  101. opts.Add(BoolVariable('werror', "Treat compiler warnings as errors. Depends on the level of warnings set with 'warnings'", False))
  102. opts.Add(BoolVariable('dev', "If yes, alias for verbose=yes warnings=extra werror=yes", False))
  103. opts.Add('extra_suffix', "Custom extra suffix added to the base filename of all generated binary files", '')
  104. opts.Add(BoolVariable('vsproj', "Generate a Visual Studio solution", False))
  105. opts.Add(EnumVariable('macports_clang', "Build using Clang from MacPorts", 'no', ('no', '5.0', 'devel')))
  106. opts.Add(BoolVariable('split_libmodules', "Split intermediate libmodules.a in smaller chunks to prevent exceeding linker command line size (forced to True when using MinGW)", False))
  107. opts.Add(BoolVariable('disable_3d', "Disable 3D nodes for a smaller executable", False))
  108. opts.Add(BoolVariable('disable_advanced_gui', "Disable advanced GUI nodes and behaviors", False))
  109. opts.Add(BoolVariable('no_editor_splash', "Don't use the custom splash screen for the editor", False))
  110. opts.Add('system_certs_path', "Use this path as SSL certificates default for editor (for package maintainers)", '')
  111. # Thirdparty libraries
  112. #opts.Add(BoolVariable('builtin_assimp', "Use the built-in Assimp library", True))
  113. opts.Add(BoolVariable('builtin_bullet', "Use the built-in Bullet library", True))
  114. opts.Add(BoolVariable('builtin_certs', "Bundle default SSL certificates to be used if you don't specify an override in the project settings", True))
  115. opts.Add(BoolVariable('builtin_enet', "Use the built-in ENet library", True))
  116. opts.Add(BoolVariable('builtin_freetype', "Use the built-in FreeType library", True))
  117. opts.Add(BoolVariable('builtin_libogg', "Use the built-in libogg library", True))
  118. opts.Add(BoolVariable('builtin_libpng', "Use the built-in libpng library", True))
  119. opts.Add(BoolVariable('builtin_libtheora', "Use the built-in libtheora library", True))
  120. opts.Add(BoolVariable('builtin_libvorbis', "Use the built-in libvorbis library", True))
  121. opts.Add(BoolVariable('builtin_libvpx', "Use the built-in libvpx library", True))
  122. opts.Add(BoolVariable('builtin_libwebp', "Use the built-in libwebp library", True))
  123. opts.Add(BoolVariable('builtin_wslay', "Use the built-in wslay library", True))
  124. opts.Add(BoolVariable('builtin_mbedtls', "Use the built-in mbedTLS library", True))
  125. opts.Add(BoolVariable('builtin_miniupnpc', "Use the built-in miniupnpc library", True))
  126. opts.Add(BoolVariable('builtin_opus', "Use the built-in Opus library", True))
  127. opts.Add(BoolVariable('builtin_pcre2', "Use the built-in PCRE2 library", True))
  128. opts.Add(BoolVariable('builtin_pcre2_with_jit', "Use JIT compiler for the built-in PCRE2 library", True))
  129. opts.Add(BoolVariable('builtin_recast', "Use the built-in Recast library", True))
  130. opts.Add(BoolVariable('builtin_squish', "Use the built-in squish library", True))
  131. opts.Add(BoolVariable('builtin_xatlas', "Use the built-in xatlas library", True))
  132. opts.Add(BoolVariable('builtin_zlib', "Use the built-in zlib library", True))
  133. opts.Add(BoolVariable('builtin_zstd', "Use the built-in Zstd library", True))
  134. # Compilation environment setup
  135. opts.Add("CXX", "C++ compiler")
  136. opts.Add("CC", "C compiler")
  137. opts.Add("LINK", "Linker")
  138. opts.Add("CCFLAGS", "Custom flags for both the C and C++ compilers")
  139. opts.Add("CFLAGS", "Custom flags for the C compiler")
  140. opts.Add("CXXFLAGS", "Custom flags for the C++ compiler")
  141. opts.Add("LINKFLAGS", "Custom flags for the linker")
  142. # add platform specific options
  143. for k in platform_opts.keys():
  144. opt_list = platform_opts[k]
  145. for o in opt_list:
  146. opts.Add(o)
  147. for x in module_list:
  148. module_enabled = True
  149. tmppath = "./modules/" + x
  150. sys.path.insert(0, tmppath)
  151. import config
  152. enabled_attr = getattr(config, "is_enabled", None)
  153. if (callable(enabled_attr) and not config.is_enabled()):
  154. module_enabled = False
  155. sys.path.remove(tmppath)
  156. sys.modules.pop('config')
  157. opts.Add(BoolVariable('module_' + x + '_enabled', "Enable module '%s'" % (x, ), module_enabled))
  158. opts.Update(env_base) # update environment
  159. Help(opts.GenerateHelpText(env_base)) # generate help
  160. # add default include paths
  161. env_base.Prepend(CPPPATH=['#'])
  162. # configure ENV for platform
  163. env_base.platform_exporters = platform_exporters
  164. env_base.platform_apis = platform_apis
  165. if (env_base["use_precise_math_checks"]):
  166. env_base.Append(CPPDEFINES=['PRECISE_MATH_CHECKS'])
  167. if (env_base['target'] == 'debug'):
  168. env_base.Append(CPPDEFINES=['DEBUG_MEMORY_ALLOC','DISABLE_FORCED_INLINE'])
  169. # The two options below speed up incremental builds, but reduce the certainty that all files
  170. # will properly be rebuilt. As such, we only enable them for debug (dev) builds, not release.
  171. # To decide whether to rebuild a file, use the MD5 sum only if the timestamp has changed.
  172. # http://scons.org/doc/production/HTML/scons-user/ch06.html#idm139837621851792
  173. env_base.Decider('MD5-timestamp')
  174. # Use cached implicit dependencies by default. Can be overridden by specifying `--implicit-deps-changed` in the command line.
  175. # http://scons.org/doc/production/HTML/scons-user/ch06s04.html
  176. env_base.SetOption('implicit_cache', 1)
  177. if (env_base['no_editor_splash']):
  178. env_base.Append(CPPDEFINES=['NO_EDITOR_SPLASH'])
  179. if not env_base['deprecated']:
  180. env_base.Append(CPPDEFINES=['DISABLE_DEPRECATED'])
  181. env_base.platforms = {}
  182. selected_platform = ""
  183. if env_base['platform'] != "":
  184. selected_platform = env_base['platform']
  185. elif env_base['p'] != "":
  186. selected_platform = env_base['p']
  187. env_base["platform"] = selected_platform
  188. else:
  189. # Missing `platform` argument, try to detect platform automatically
  190. if sys.platform.startswith('linux'):
  191. selected_platform = 'x11'
  192. elif sys.platform == 'darwin':
  193. selected_platform = 'osx'
  194. elif sys.platform == 'win32':
  195. selected_platform = 'windows'
  196. else:
  197. print("Could not detect platform automatically. Supported platforms:")
  198. for x in platform_list:
  199. print("\t" + x)
  200. print("\nPlease run SCons again and select a valid platform: platform=<string>")
  201. if selected_platform != "":
  202. print("Automatically detected platform: " + selected_platform)
  203. env_base["platform"] = selected_platform
  204. if selected_platform in platform_list:
  205. tmppath = "./platform/" + selected_platform
  206. sys.path.insert(0, tmppath)
  207. import detect
  208. if "create" in dir(detect):
  209. env = detect.create(env_base)
  210. else:
  211. env = env_base.Clone()
  212. if env['dev']:
  213. env['verbose'] = True
  214. env['warnings'] = "extra"
  215. env['werror'] = True
  216. if env['vsproj']:
  217. env.vs_incs = []
  218. env.vs_srcs = []
  219. def AddToVSProject(sources):
  220. for x in sources:
  221. if type(x) == type(""):
  222. fname = env.File(x).path
  223. else:
  224. fname = env.File(x)[0].path
  225. pieces = fname.split(".")
  226. if len(pieces) > 0:
  227. basename = pieces[0]
  228. basename = basename.replace('\\\\', '/')
  229. if os.path.isfile(basename + ".h"):
  230. env.vs_incs = env.vs_incs + [basename + ".h"]
  231. elif os.path.isfile(basename + ".hpp"):
  232. env.vs_incs = env.vs_incs + [basename + ".hpp"]
  233. if os.path.isfile(basename + ".c"):
  234. env.vs_srcs = env.vs_srcs + [basename + ".c"]
  235. elif os.path.isfile(basename + ".cpp"):
  236. env.vs_srcs = env.vs_srcs + [basename + ".cpp"]
  237. env.AddToVSProject = AddToVSProject
  238. env.extra_suffix = ""
  239. if env["extra_suffix"] != '':
  240. env.extra_suffix += '.' + env["extra_suffix"]
  241. # Environment flags
  242. CCFLAGS = env.get('CCFLAGS', '')
  243. env['CCFLAGS'] = ''
  244. env.Append(CCFLAGS=str(CCFLAGS).split())
  245. CFLAGS = env.get('CFLAGS', '')
  246. env['CFLAGS'] = ''
  247. env.Append(CFLAGS=str(CFLAGS).split())
  248. CXXFLAGS = env.get('CXXFLAGS', '')
  249. env['CXXFLAGS'] = ''
  250. env.Append(CXXFLAGS=str(CXXFLAGS).split())
  251. LINKFLAGS = env.get('LINKFLAGS', '')
  252. env['LINKFLAGS'] = ''
  253. env.Append(LINKFLAGS=str(LINKFLAGS).split())
  254. # Platform specific flags
  255. flag_list = platform_flags[selected_platform]
  256. for f in flag_list:
  257. if not (f[0] in ARGUMENTS): # allow command line to override platform flags
  258. env[f[0]] = f[1]
  259. # Must happen after the flags definition, so that they can be used by platform detect
  260. detect.configure(env)
  261. # Set our C and C++ standard requirements.
  262. # Prepending to make it possible to override
  263. # This needs to come after `configure`, otherwise we don't have env.msvc.
  264. if not env.msvc:
  265. # Specifying GNU extensions support explicitly, which are supported by
  266. # both GCC and Clang. This mirrors GCC and Clang's current default
  267. # compile flags if no -std is specified.
  268. env.Prepend(CFLAGS=['-std=gnu11'])
  269. env.Prepend(CXXFLAGS=['-std=gnu++14'])
  270. else:
  271. # MSVC doesn't have clear C standard support, /std only covers C++.
  272. # We apply it to CCFLAGS (both C and C++ code) in case it impacts C features.
  273. env.Prepend(CCFLAGS=['/std:c++14'])
  274. # Configure compiler warnings
  275. if env.msvc:
  276. # Truncations, narrowing conversions, signed/unsigned comparisons...
  277. disable_nonessential_warnings = ['/wd4267', '/wd4244', '/wd4305', '/wd4018', '/wd4800']
  278. if (env["warnings"] == 'extra'):
  279. env.Append(CCFLAGS=['/Wall']) # Implies /W4
  280. elif (env["warnings"] == 'all'):
  281. env.Append(CCFLAGS=['/W3'] + disable_nonessential_warnings)
  282. elif (env["warnings"] == 'moderate'):
  283. env.Append(CCFLAGS=['/W2'] + disable_nonessential_warnings)
  284. else: # 'no'
  285. env.Append(CCFLAGS=['/w'])
  286. # Set exception handling model to avoid warnings caused by Windows system headers.
  287. env.Append(CCFLAGS=['/EHsc'])
  288. if (env["werror"]):
  289. env.Append(CCFLAGS=['/WX'])
  290. # Force to use Unicode encoding
  291. env.Append(MSVC_FLAGS=['/utf8'])
  292. else: # Rest of the world
  293. version = methods.get_compiler_version(env) or [-1, -1]
  294. shadow_local_warning = []
  295. all_plus_warnings = ['-Wwrite-strings']
  296. if methods.using_gcc(env):
  297. if version[0] >= 7:
  298. shadow_local_warning = ['-Wshadow-local']
  299. if (env["warnings"] == 'extra'):
  300. # Note: enable -Wimplicit-fallthrough for Clang (already part of -Wextra for GCC)
  301. # once we switch to C++11 or later (necessary for our FALLTHROUGH macro).
  302. env.Append(CCFLAGS=['-Wall', '-Wextra', '-Wno-unused-parameter']
  303. + all_plus_warnings + shadow_local_warning)
  304. env.Append(CXXFLAGS=['-Wctor-dtor-privacy', '-Wnon-virtual-dtor'])
  305. if methods.using_gcc(env):
  306. env.Append(CCFLAGS=['-Walloc-zero',
  307. '-Wduplicated-branches', '-Wduplicated-cond',
  308. '-Wstringop-overflow=4', '-Wlogical-op'])
  309. env.Append(CXXFLAGS=['-Wnoexcept', '-Wplacement-new=1'])
  310. if version[0] >= 9:
  311. env.Append(CCFLAGS=['-Wattribute-alias=2'])
  312. elif (env["warnings"] == 'all'):
  313. env.Append(CCFLAGS=['-Wall'] + shadow_local_warning)
  314. elif (env["warnings"] == 'moderate'):
  315. env.Append(CCFLAGS=['-Wall', '-Wno-unused'] + shadow_local_warning)
  316. else: # 'no'
  317. env.Append(CCFLAGS=['-w'])
  318. if (env["werror"]):
  319. env.Append(CCFLAGS=['-Werror'])
  320. else: # always enable those errors
  321. env.Append(CCFLAGS=['-Werror=return-type'])
  322. if (hasattr(detect, 'get_program_suffix')):
  323. suffix = "." + detect.get_program_suffix()
  324. else:
  325. suffix = "." + selected_platform
  326. if (env["target"] == "release"):
  327. if env["tools"]:
  328. print("Tools can only be built with targets 'debug' and 'release_debug'.")
  329. sys.exit(255)
  330. suffix += ".opt"
  331. env.Append(CPPDEFINES=['NDEBUG'])
  332. elif (env["target"] == "release_debug"):
  333. if env["tools"]:
  334. suffix += ".opt.tools"
  335. else:
  336. suffix += ".opt.debug"
  337. else:
  338. if env["tools"]:
  339. suffix += ".tools"
  340. else:
  341. suffix += ".debug"
  342. if env["arch"] != "":
  343. suffix += "." + env["arch"]
  344. elif (env["bits"] == "32"):
  345. suffix += ".32"
  346. elif (env["bits"] == "64"):
  347. suffix += ".64"
  348. suffix += env.extra_suffix
  349. sys.path.remove(tmppath)
  350. sys.modules.pop('detect')
  351. env.module_list = []
  352. env.module_icons_paths = []
  353. env.doc_class_path = {}
  354. for x in module_list:
  355. if not env['module_' + x + '_enabled']:
  356. continue
  357. tmppath = "./modules/" + x
  358. sys.path.insert(0, tmppath)
  359. env.current_module = x
  360. import config
  361. # can_build changed number of arguments between 3.0 (1) and 3.1 (2),
  362. # so try both to preserve compatibility for 3.0 modules
  363. can_build = False
  364. try:
  365. can_build = config.can_build(env, selected_platform)
  366. except TypeError:
  367. print("Warning: module '%s' uses a deprecated `can_build` "
  368. "signature in its config.py file, it should be "
  369. "`can_build(env, platform)`." % x)
  370. can_build = config.can_build(selected_platform)
  371. if (can_build):
  372. config.configure(env)
  373. env.module_list.append(x)
  374. # Get doc classes paths (if present)
  375. try:
  376. doc_classes = config.get_doc_classes()
  377. doc_path = config.get_doc_path()
  378. for c in doc_classes:
  379. env.doc_class_path[c] = "modules/" + x + "/" + doc_path
  380. except:
  381. pass
  382. # Get icon paths (if present)
  383. try:
  384. icons_path = config.get_icons_path()
  385. env.module_icons_paths.append("modules/" + x + "/" + icons_path)
  386. except:
  387. # Default path for module icons
  388. env.module_icons_paths.append("modules/" + x + "/" + "icons")
  389. sys.path.remove(tmppath)
  390. sys.modules.pop('config')
  391. methods.update_version(env.module_version_string)
  392. env["PROGSUFFIX"] = suffix + env.module_version_string + env["PROGSUFFIX"]
  393. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  394. # (SH)LIBSUFFIX will be used for our own built libraries
  395. # LIBSUFFIXES contains LIBSUFFIX and SHLIBSUFFIX by default,
  396. # so we need to append the default suffixes to keep the ability
  397. # to link against thirdparty libraries (.a, .so, .lib, etc.).
  398. if os.name == "nt":
  399. # On Windows, only static libraries and import libraries can be
  400. # statically linked - both using .lib extension
  401. env["LIBSUFFIXES"] += [env["LIBSUFFIX"]]
  402. else:
  403. env["LIBSUFFIXES"] += [env["LIBSUFFIX"], env["SHLIBSUFFIX"]]
  404. env["LIBSUFFIX"] = suffix + env["LIBSUFFIX"]
  405. env["SHLIBSUFFIX"] = suffix + env["SHLIBSUFFIX"]
  406. if (env.use_ptrcall):
  407. env.Append(CPPDEFINES=['PTRCALL_ENABLED'])
  408. if env['tools']:
  409. env.Append(CPPDEFINES=['TOOLS_ENABLED'])
  410. if env['disable_3d']:
  411. if env['tools']:
  412. print("Build option 'disable_3d=yes' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template).")
  413. sys.exit(255)
  414. else:
  415. env.Append(CPPDEFINES=['_3D_DISABLED'])
  416. if env['gdscript']:
  417. env.Append(CPPDEFINES=['GDSCRIPT_ENABLED'])
  418. if env['disable_advanced_gui']:
  419. if env['tools']:
  420. print("Build option 'disable_advanced_gui=yes' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template).")
  421. sys.exit(255)
  422. else:
  423. env.Append(CPPDEFINES=['ADVANCED_GUI_DISABLED'])
  424. if env['minizip']:
  425. env.Append(CPPDEFINES=['MINIZIP_ENABLED'])
  426. editor_module_list = ['regex']
  427. for x in editor_module_list:
  428. if not env['module_' + x + '_enabled']:
  429. if env['tools']:
  430. print("Build option 'module_" + x + "_enabled=no' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template).")
  431. sys.exit(255)
  432. if not env['verbose']:
  433. methods.no_verbose(sys, env)
  434. if (not env["platform"] == "server"): # FIXME: detect GLES3
  435. env.Append(BUILDERS = { 'GLES3_GLSL' : env.Builder(action=run_in_subprocess(gles_builders.build_gles3_headers), suffix='glsl.gen.h', src_suffix='.glsl')})
  436. env.Append(BUILDERS = { 'GLES2_GLSL' : env.Builder(action=run_in_subprocess(gles_builders.build_gles2_headers), suffix='glsl.gen.h', src_suffix='.glsl')})
  437. scons_cache_path = os.environ.get("SCONS_CACHE")
  438. if scons_cache_path != None:
  439. CacheDir(scons_cache_path)
  440. print("Scons cache enabled... (path: '" + scons_cache_path + "')")
  441. Export('env')
  442. # build subdirs, the build order is dependent on link order.
  443. SConscript("core/SCsub")
  444. SConscript("servers/SCsub")
  445. SConscript("scene/SCsub")
  446. SConscript("editor/SCsub")
  447. SConscript("drivers/SCsub")
  448. SConscript("platform/SCsub")
  449. SConscript("modules/SCsub")
  450. SConscript("main/SCsub")
  451. SConscript("platform/" + selected_platform + "/SCsub") # build selected platform
  452. # Microsoft Visual Studio Project Generation
  453. if env['vsproj']:
  454. env['CPPPATH'] = [Dir(path) for path in env['CPPPATH']]
  455. methods.generate_vs_project(env, GetOption("num_jobs"))
  456. methods.generate_cpp_hint_file("cpp.hint")
  457. # Check for the existence of headers
  458. conf = Configure(env)
  459. if ("check_c_headers" in env):
  460. for header in env["check_c_headers"]:
  461. if (conf.CheckCHeader(header[0])):
  462. env.AppendUnique(CPPDEFINES=[header[1]])
  463. elif selected_platform != "":
  464. if selected_platform == "list":
  465. print("The following platforms are available:\n")
  466. else:
  467. print('Invalid target platform "' + selected_platform + '".')
  468. print("The following platforms were detected:\n")
  469. for x in platform_list:
  470. print("\t" + x)
  471. print("\nPlease run SCons again and select a valid platform: platform=<string>")
  472. if selected_platform == "list":
  473. # Exit early to suppress the rest of the built-in SCons messages
  474. sys.exit(0)
  475. else:
  476. sys.exit(255)
  477. # The following only makes sense when the env is defined, and assumes it is
  478. if 'env' in locals():
  479. screen = sys.stdout
  480. # Progress reporting is not available in non-TTY environments since it
  481. # messes with the output (for example, when writing to a file)
  482. show_progress = (env['progress'] and sys.stdout.isatty())
  483. node_count = 0
  484. node_count_max = 0
  485. node_count_interval = 1
  486. node_count_fname = str(env.Dir('#')) + '/.scons_node_count'
  487. import time, math
  488. class cache_progress:
  489. # The default is 1 GB cache and 12 hours half life
  490. def __init__(self, path = None, limit = 1073741824, half_life = 43200):
  491. self.path = path
  492. self.limit = limit
  493. self.exponent_scale = math.log(2) / half_life
  494. if env['verbose'] and path != None:
  495. screen.write('Current cache limit is ' + self.convert_size(limit) + ' (used: ' + self.convert_size(self.get_size(path)) + ')\n')
  496. self.delete(self.file_list())
  497. def __call__(self, node, *args, **kw):
  498. global node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  499. if show_progress:
  500. # Print the progress percentage
  501. node_count += node_count_interval
  502. if (node_count_max > 0 and node_count <= node_count_max):
  503. screen.write('\r[%3d%%] ' % (node_count * 100 / node_count_max))
  504. screen.flush()
  505. elif (node_count_max > 0 and node_count > node_count_max):
  506. screen.write('\r[100%] ')
  507. screen.flush()
  508. else:
  509. screen.write('\r[Initial build] ')
  510. screen.flush()
  511. def delete(self, files):
  512. if len(files) == 0:
  513. return
  514. if env['verbose']:
  515. # Utter something
  516. screen.write('\rPurging %d %s from cache...\n' % (len(files), len(files) > 1 and 'files' or 'file'))
  517. [os.remove(f) for f in files]
  518. def file_list(self):
  519. if self.path is None:
  520. # Nothing to do
  521. return []
  522. # Gather a list of (filename, (size, atime)) within the
  523. # cache directory
  524. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, '*', '*'))]
  525. if file_stat == []:
  526. # Nothing to do
  527. return []
  528. # Weight the cache files by size (assumed to be roughly
  529. # proportional to the recompilation time) times an exponential
  530. # decay since the ctime, and return a list with the entries
  531. # (filename, size, weight).
  532. current_time = time.time()
  533. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  534. # Sort by the most recently accessed files (most sensible to keep) first
  535. file_stat.sort(key=lambda x: x[2])
  536. # Search for the first entry where the storage limit is
  537. # reached
  538. sum, mark = 0, None
  539. for i,x in enumerate(file_stat):
  540. sum += x[1]
  541. if sum > self.limit:
  542. mark = i
  543. break
  544. if mark is None:
  545. return []
  546. else:
  547. return [x[0] for x in file_stat[mark:]]
  548. def convert_size(self, size_bytes):
  549. if size_bytes == 0:
  550. return "0 bytes"
  551. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  552. i = int(math.floor(math.log(size_bytes, 1024)))
  553. p = math.pow(1024, i)
  554. s = round(size_bytes / p, 2)
  555. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  556. def get_size(self, start_path = '.'):
  557. total_size = 0
  558. for dirpath, dirnames, filenames in os.walk(start_path):
  559. for f in filenames:
  560. fp = os.path.join(dirpath, f)
  561. total_size += os.path.getsize(fp)
  562. return total_size
  563. def progress_finish(target, source, env):
  564. global node_count, progressor
  565. with open(node_count_fname, 'w') as f:
  566. f.write('%d\n' % node_count)
  567. progressor.delete(progressor.file_list())
  568. try:
  569. with open(node_count_fname) as f:
  570. node_count_max = int(f.readline())
  571. except:
  572. pass
  573. cache_directory = os.environ.get("SCONS_CACHE")
  574. # Simple cache pruning, attached to SCons' progress callback. Trim the
  575. # cache directory to a size not larger than cache_limit.
  576. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  577. progressor = cache_progress(cache_directory, cache_limit)
  578. Progress(progressor, interval = node_count_interval)
  579. progress_finish_command = Command('progress_finish', [], progress_finish)
  580. AlwaysBuild(progress_finish_command)