SConstruct 29 KB

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