SConstruct 26 KB

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