SConstruct 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. #!/usr/bin/env python
  2. EnsureSConsVersion(0, 98, 1)
  3. import string
  4. import os
  5. import os.path
  6. import glob
  7. import sys
  8. import methods
  9. methods.update_version()
  10. # scan possible build platforms
  11. platform_list = [] # list of platforms
  12. platform_opts = {} # options for each platform
  13. platform_flags = {} # flags for each platform
  14. active_platforms = []
  15. active_platform_ids = []
  16. platform_exporters = []
  17. global_defaults = []
  18. for x in glob.glob("platform/*"):
  19. if (not os.path.isdir(x) or not os.path.exists(x + "/detect.py")):
  20. continue
  21. tmppath = "./" + x
  22. sys.path.append(tmppath)
  23. import detect
  24. if (os.path.exists(x + "/export/export.cpp")):
  25. platform_exporters.append(x[9:])
  26. if (os.path.exists(x + "/globals/global_defaults.cpp")):
  27. global_defaults.append(x[9:])
  28. if (detect.is_active()):
  29. active_platforms.append(detect.get_name())
  30. active_platform_ids.append(x)
  31. if (detect.can_build()):
  32. x = x.replace("platform/", "") # rest of world
  33. x = x.replace("platform\\", "") # win32
  34. platform_list += [x]
  35. platform_opts[x] = detect.get_opts()
  36. platform_flags[x] = detect.get_flags()
  37. sys.path.remove(tmppath)
  38. sys.modules.pop('detect')
  39. module_list = methods.detect_modules()
  40. # print "Detected Platforms: "+str(platform_list)
  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 == "posix"):
  45. pass
  46. elif (os.name == "nt"):
  47. if (os.getenv("VCINSTALLDIR") == None or platform_arg == "android" or platform_arg == "javascript"):
  48. custom_tools = ['mingw']
  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.global_defaults = global_defaults
  55. env_base.android_maven_repos = []
  56. env_base.android_flat_dirs = []
  57. env_base.android_dependencies = []
  58. env_base.android_gradle_plugins = []
  59. env_base.android_gradle_classpath = []
  60. env_base.android_java_dirs = []
  61. env_base.android_res_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.split_drivers = False
  71. # To decide whether to rebuild a file, use the MD5 sum only if the timestamp has changed.
  72. # http://scons.org/doc/production/HTML/scons-user/ch06.html#idm139837621851792
  73. env_base.Decider('MD5-timestamp')
  74. # Use cached implicit dependencies by default. Can be overridden by specifying `--implicit-deps-changed` in the command line.
  75. # http://scons.org/doc/production/HTML/scons-user/ch06s04.html
  76. env_base.SetOption('implicit_cache', 1)
  77. env_base.__class__.android_add_maven_repository = methods.android_add_maven_repository
  78. env_base.__class__.android_add_flat_dir = methods.android_add_flat_dir
  79. env_base.__class__.android_add_dependency = methods.android_add_dependency
  80. env_base.__class__.android_add_java_dir = methods.android_add_java_dir
  81. env_base.__class__.android_add_res_dir = methods.android_add_res_dir
  82. env_base.__class__.android_add_aidl_dir = methods.android_add_aidl_dir
  83. env_base.__class__.android_add_jni_dir = methods.android_add_jni_dir
  84. env_base.__class__.android_add_default_config = methods.android_add_default_config
  85. env_base.__class__.android_add_to_manifest = methods.android_add_to_manifest
  86. env_base.__class__.android_add_to_permissions = methods.android_add_to_permissions
  87. env_base.__class__.android_add_to_attributes = methods.android_add_to_attributes
  88. env_base.__class__.android_add_gradle_plugin = methods.android_add_gradle_plugin
  89. env_base.__class__.android_add_gradle_classpath = methods.android_add_gradle_classpath
  90. env_base.__class__.disable_module = methods.disable_module
  91. env_base.__class__.add_source_files = methods.add_source_files
  92. env_base.__class__.use_windows_spawn_fix = methods.use_windows_spawn_fix
  93. env_base.__class__.split_lib = methods.split_lib
  94. env_base.__class__.add_shared_library = methods.add_shared_library
  95. env_base.__class__.add_library = methods.add_library
  96. env_base.__class__.add_program = methods.add_program
  97. env_base.__class__.CommandNoCache = methods.CommandNoCache
  98. env_base["x86_libtheora_opt_gcc"] = False
  99. env_base["x86_libtheora_opt_vc"] = False
  100. # Build options
  101. customs = ['custom.py']
  102. profile = ARGUMENTS.get("profile", False)
  103. if profile:
  104. import os.path
  105. if os.path.isfile(profile):
  106. customs.append(profile)
  107. elif os.path.isfile(profile + ".py"):
  108. customs.append(profile + ".py")
  109. opts = Variables(customs, ARGUMENTS)
  110. # Target build options
  111. opts.Add('arch', "Platform-dependent architecture (arm/arm64/x86/x64/mips/etc)", '')
  112. opts.Add('bits', "Target platform bits (default/32/64)", 'default')
  113. opts.Add('p', "Platform (alias for 'platform')", '')
  114. opts.Add('platform', "Target platform: any in " + str(platform_list), '')
  115. opts.Add('target', "Compilation target (debug/release_debug/release)", 'debug')
  116. opts.Add('tools', "Build the tools a.k.a. the Godot editor (yes/no)", 'yes')
  117. # Components
  118. opts.Add('deprecated', "Enable deprecated features (yes/no)", 'yes')
  119. opts.Add('gdscript', "Build GDSCript support (yes/no)", 'yes')
  120. opts.Add('minizip', "Build minizip archive support (yes/no)", 'yes')
  121. opts.Add('xml', "XML format support for resources (yes/no)", 'yes')
  122. # Advanced options
  123. opts.Add('disable_3d', "Disable 3D nodes for smaller executable (yes/no)", 'no')
  124. opts.Add('disable_advanced_gui', "Disable advance 3D gui nodes and behaviors (yes/no)", 'no')
  125. opts.Add('extra_suffix', "Custom extra suffix added to the base filename of all generated binary files", '')
  126. opts.Add('unix_global_settings_path', "UNIX-specific path to system-wide settings. Currently only used for templates", '')
  127. opts.Add('verbose', "Enable verbose output for the compilation (yes/no)", 'no')
  128. opts.Add('vsproj', "Generate Visual Studio Project. (yes/no)", 'no')
  129. opts.Add('vsproj_jobs', "Number of parallel builds", '2')
  130. opts.Add('warnings', "Set the level of warnings emitted during compilation (extra/all/moderate/no)", 'no')
  131. opts.Add('progress', "Show a progress indicator during build (yes/no)", 'yes')
  132. opts.Add('dev', "If yes, alias for verbose=yes warnings=all", 'no')
  133. # Thirdparty libraries
  134. opts.Add('builtin_freetype', "Use the builtin freetype library (yes/no)", 'yes')
  135. opts.Add('builtin_glew', "Use the builtin glew library (yes/no)", 'yes')
  136. opts.Add('builtin_libmpcdec', "Use the builtin libmpcdec library (yes/no)", 'yes')
  137. opts.Add('builtin_libogg', "Use the builtin libogg library (yes/no)", 'yes')
  138. opts.Add('builtin_libpng', "Use the builtin libpng library (yes/no)", 'yes')
  139. opts.Add('builtin_libtheora', "Use the builtin libtheora library (yes/no)", 'yes')
  140. opts.Add('builtin_libvorbis', "Use the builtin libvorbis library (yes/no)", 'yes')
  141. opts.Add('builtin_libwebp', "Use the builtin libwebp library (yes/no)", 'yes')
  142. opts.Add('builtin_openssl', "Use the builtin openssl library (yes/no)", 'yes')
  143. opts.Add('builtin_opus', "Use the builtin opus library (yes/no)", 'yes')
  144. # (akien) Unbundling would require work in audio_stream_speex.{cpp,h}, but since speex was
  145. # removed in 3.0+ and this is only to preserve compatibility in 2.1, I haven't worked on it.
  146. # Patches welcome if anyone cares :)
  147. opts.Add('builtin_speex', "Use the builtin speex library (yes/no)", 'yes')
  148. opts.Add('builtin_squish', "Use the builtin squish library (yes/no)", 'yes')
  149. opts.Add('builtin_zlib', "Use the builtin zlib library (yes/no)", 'yes')
  150. # Environment setup
  151. opts.Add("CXX", "C++ compiler")
  152. opts.Add("CC", "C compiler")
  153. opts.Add("CCFLAGS", "Custom flags for the C and C++ compilers")
  154. opts.Add("CFLAGS", "Custom flags for the C compiler")
  155. opts.Add("LINKFLAGS", "Custom flags for the linker")
  156. # add platform specific options
  157. for k in platform_opts.keys():
  158. opt_list = platform_opts[k]
  159. for o in opt_list:
  160. opts.Add(o[0], o[1], o[2])
  161. for x in module_list:
  162. opts.Add('module_' + x + '_enabled', "Enable module '" + x + "' (yes/no)", "yes")
  163. opts.Update(env_base) # update environment
  164. Help(opts.GenerateHelpText(env_base)) # generate help
  165. # add default include paths
  166. env_base.Append(CPPPATH=['#core', '#core/math', '#editor', '#drivers', '#'])
  167. # configure ENV for platform
  168. env_base.platform_exporters = platform_exporters
  169. """
  170. sys.path.append("./platform/"+env_base["platform"])
  171. import detect
  172. detect.configure(env_base)
  173. sys.path.remove("./platform/"+env_base["platform"])
  174. sys.modules.pop('detect')
  175. """
  176. if (env_base['target'] == 'debug'):
  177. env_base.Append(CPPFLAGS=['-DDEBUG_MEMORY_ALLOC'])
  178. env_base.Append(CPPFLAGS=['-DSCI_NAMESPACE'])
  179. if (env_base['deprecated'] != 'no'):
  180. env_base.Append(CPPFLAGS=['-DENABLE_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. if selected_platform in platform_list:
  189. sys.path.append("./platform/" + selected_platform)
  190. import detect
  191. if "create" in dir(detect):
  192. env = detect.create(env_base)
  193. else:
  194. env = env_base.Clone()
  195. if (env["dev"] == "yes"):
  196. env["warnings"] = "all"
  197. env["verbose"] = "yes"
  198. if env['vsproj'] == "yes":
  199. env.vs_incs = []
  200. env.vs_srcs = []
  201. def AddToVSProject(sources):
  202. for x in sources:
  203. if type(x) == type(""):
  204. fname = env.File(x).path
  205. else:
  206. fname = env.File(x)[0].path
  207. pieces = fname.split(".")
  208. if len(pieces) > 0:
  209. basename = pieces[0]
  210. basename = basename.replace('\\\\', '/')
  211. env.vs_srcs = env.vs_srcs + [basename + ".cpp"]
  212. env.vs_incs = env.vs_incs + [basename + ".h"]
  213. # print basename
  214. env.AddToVSProject = AddToVSProject
  215. env.extra_suffix = ""
  216. if env["extra_suffix"] != '':
  217. env.extra_suffix += '.' + env["extra_suffix"]
  218. CCFLAGS = env.get('CCFLAGS', '')
  219. env['CCFLAGS'] = ''
  220. env.Append(CCFLAGS=str(CCFLAGS).split())
  221. CFLAGS = env.get('CFLAGS', '')
  222. env['CFLAGS'] = ''
  223. env.Append(CFLAGS=str(CFLAGS).split())
  224. LINKFLAGS = env.get('LINKFLAGS', '')
  225. env['LINKFLAGS'] = ''
  226. env.Append(LINKFLAGS=str(LINKFLAGS).split())
  227. flag_list = platform_flags[selected_platform]
  228. for f in flag_list:
  229. if not (f[0] in ARGUMENTS): # allow command line to override platform flags
  230. env[f[0]] = f[1]
  231. # must happen after the flags, so when flags are used by configure, stuff happens (ie, ssl on x11)
  232. detect.configure(env)
  233. if (env["warnings"] == 'yes'):
  234. print("WARNING: warnings=yes is deprecated; assuming warnings=all")
  235. if (os.name == "nt" and os.getenv("VCINSTALLDIR") and (platform_arg == "windows" or platform_arg == "uwp")): # MSVC, needs to stand out of course
  236. disable_nonessential_warnings = ['/wd4267', '/wd4244', '/wd4305', '/wd4800'] # Truncations, narrowing conversions...
  237. if (env["warnings"] == 'extra'):
  238. env.Append(CCFLAGS=['/Wall']) # Implies /W4
  239. elif (env["warnings"] == 'all' or env["warnings"] == 'yes'):
  240. env.Append(CCFLAGS=['/W3'] + disable_nonessential_warnings)
  241. elif (env["warnings"] == 'moderate'):
  242. # C4244 shouldn't be needed here being a level-3 warning, but it is
  243. env.Append(CCFLAGS=['/W2'] + disable_nonessential_warnings)
  244. else: # 'no'
  245. env.Append(CCFLAGS=['/w'])
  246. else: # Rest of the world
  247. if (env["warnings"] == 'extra'):
  248. env.Append(CCFLAGS=['-Wall', '-Wextra'])
  249. elif (env["warnings"] == 'all' or env["warnings"] == 'yes'):
  250. env.Append(CCFLAGS=['-Wall'])
  251. elif (env["warnings"] == 'moderate'):
  252. env.Append(CCFLAGS=['-Wall', '-Wno-unused'])
  253. else: # 'no'
  254. env.Append(CCFLAGS=['-w'])
  255. #env['platform_libsuffix'] = env['LIBSUFFIX']
  256. suffix = "." + selected_platform
  257. if (env["target"] == "release"):
  258. if (env["tools"] == "yes"):
  259. print("Tools can only be built with targets 'debug' and 'release_debug'.")
  260. sys.exit(255)
  261. suffix += ".opt"
  262. env.Append(CCFLAGS=['-DNDEBUG'])
  263. elif (env["target"] == "release_debug"):
  264. if (env["tools"] == "yes"):
  265. suffix += ".opt.tools"
  266. else:
  267. suffix += ".opt.debug"
  268. else:
  269. if (env["tools"] == "yes"):
  270. suffix += ".tools"
  271. else:
  272. suffix += ".debug"
  273. if env["arch"] != "":
  274. suffix += "." + env["arch"]
  275. elif (env["bits"] == "32"):
  276. suffix += ".32"
  277. elif (env["bits"] == "64"):
  278. suffix += ".64"
  279. suffix += env.extra_suffix
  280. env["PROGSUFFIX"] = suffix + env["PROGSUFFIX"]
  281. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  282. env["LIBSUFFIX"] = suffix + env["LIBSUFFIX"]
  283. env["SHLIBSUFFIX"] = suffix + env["SHLIBSUFFIX"]
  284. sys.path.remove("./platform/" + selected_platform)
  285. sys.modules.pop('detect')
  286. env.module_list = []
  287. for x in module_list:
  288. if env['module_' + x + '_enabled'] != "yes":
  289. continue
  290. tmppath = "./modules/" + x
  291. sys.path.append(tmppath)
  292. env.current_module = x
  293. import config
  294. if (config.can_build(selected_platform)):
  295. config.configure(env)
  296. env.module_list.append(x)
  297. sys.path.remove(tmppath)
  298. sys.modules.pop('config')
  299. if (env.use_ptrcall):
  300. env.Append(CPPFLAGS=['-DPTRCALL_ENABLED'])
  301. # to test 64 bits compiltion
  302. # env.Append(CPPFLAGS=['-m64'])
  303. if (env['tools'] == 'yes'):
  304. env.Append(CPPFLAGS=['-DTOOLS_ENABLED'])
  305. if (env['disable_3d'] == 'yes'):
  306. env.Append(CPPFLAGS=['-D_3D_DISABLED'])
  307. if (env['gdscript'] == 'yes'):
  308. env.Append(CPPFLAGS=['-DGDSCRIPT_ENABLED'])
  309. if (env['disable_advanced_gui'] == 'yes'):
  310. env.Append(CPPFLAGS=['-DADVANCED_GUI_DISABLED'])
  311. if (env['minizip'] == 'yes'):
  312. env.Append(CPPFLAGS=['-DMINIZIP_ENABLED'])
  313. if (env['xml'] == 'yes'):
  314. env.Append(CPPFLAGS=['-DXML_ENABLED'])
  315. if (env['verbose'] == 'no'):
  316. methods.no_verbose(sys, env)
  317. scons_cache_path = os.environ.get("SCONS_CACHE")
  318. if scons_cache_path != None:
  319. CacheDir(scons_cache_path)
  320. print("Scons cache enabled... (path: '" + scons_cache_path + "')")
  321. Export('env')
  322. # build subdirs, the build order is dependent on link order.
  323. SConscript("core/SCsub")
  324. SConscript("servers/SCsub")
  325. SConscript("scene/SCsub")
  326. SConscript("editor/SCsub")
  327. SConscript("drivers/SCsub")
  328. SConscript("modules/SCsub")
  329. SConscript("main/SCsub")
  330. SConscript("platform/" + selected_platform + "/SCsub") # build selected platform
  331. # Microsoft Visual Studio Project Generation
  332. if (env['vsproj']) == "yes":
  333. env['CPPPATH'] = [Dir(path) for path in env['CPPPATH']]
  334. methods.generate_vs_project(env, env['vsproj_jobs'])
  335. else:
  336. print("No valid target platform selected.")
  337. print("The following were detected:")
  338. for x in platform_list:
  339. print("\t" + x)
  340. print("\nPlease run scons again with argument: platform=<string>")
  341. # The following only makes sense when the env is defined, and assumes it is
  342. if 'env' in locals():
  343. screen = sys.stdout
  344. # Progress reporting is not available in non-TTY environments since it
  345. # messes with the output (for example, when writing to a file)
  346. show_progress = (env['progress'] and sys.stdout.isatty())
  347. node_count = 0
  348. node_count_max = 0
  349. node_count_interval = 1
  350. node_count_fname = str(env.Dir('#')) + '/.scons_node_count'
  351. import time, math
  352. class cache_progress:
  353. # The default is 1 GB cache and 12 hours half life
  354. def __init__(self, path = None, limit = 1073741824, half_life = 43200):
  355. self.path = path
  356. self.limit = limit
  357. self.exponent_scale = math.log(2) / half_life
  358. if env['verbose'] == 'yes' and path != None:
  359. screen.write('Current cache limit is ' + self.convert_size(limit) + ' (used: ' + self.convert_size(self.get_size(path)) + ')\n')
  360. self.delete(self.file_list())
  361. def __call__(self, node, *args, **kw):
  362. global node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  363. if show_progress:
  364. # Print the progress percentage
  365. node_count += node_count_interval
  366. if (node_count_max > 0 and node_count <= node_count_max):
  367. screen.write('\r[%3d%%] ' % (node_count * 100 / node_count_max))
  368. screen.flush()
  369. elif (node_count_max > 0 and node_count > node_count_max):
  370. screen.write('\r[100%] ')
  371. screen.flush()
  372. else:
  373. screen.write('\r[Initial build] ')
  374. screen.flush()
  375. def delete(self, files):
  376. if len(files) == 0:
  377. return
  378. if env['verbose'] == 'yes':
  379. # Utter something
  380. screen.write('\rPurging %d %s from cache...\n' % (len(files), len(files) > 1 and 'files' or 'file'))
  381. [os.remove(f) for f in files]
  382. def file_list(self):
  383. if self.path == None:
  384. # Nothing to do
  385. return []
  386. # Gather a list of (filename, (size, atime)) within the
  387. # cache directory
  388. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, '*', '*'))]
  389. if file_stat == []:
  390. # Nothing to do
  391. return []
  392. # Weight the cache files by size (assumed to be roughly
  393. # proportional to the recompilation time) times an exponential
  394. # decay since the ctime, and return a list with the entries
  395. # (filename, size, weight).
  396. current_time = time.time()
  397. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  398. # Sort by the most resently accessed files (most sensible to keep) first
  399. file_stat.sort(key=lambda x: x[2])
  400. # Search for the first entry where the storage limit is
  401. # reached
  402. sum, mark = 0, None
  403. for i,x in enumerate(file_stat):
  404. sum += x[1]
  405. if sum > self.limit:
  406. mark = i
  407. break
  408. if mark == None:
  409. return []
  410. else:
  411. return [x[0] for x in file_stat[mark:]]
  412. def convert_size(self, size_bytes):
  413. if size_bytes == 0:
  414. return "0 bytes"
  415. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  416. i = int(math.floor(math.log(size_bytes, 1024)))
  417. p = math.pow(1024, i)
  418. s = round(size_bytes / p, 2)
  419. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  420. def get_size(self, start_path = '.'):
  421. total_size = 0
  422. for dirpath, dirnames, filenames in os.walk(start_path):
  423. for f in filenames:
  424. fp = os.path.join(dirpath, f)
  425. total_size += os.path.getsize(fp)
  426. return total_size
  427. def progress_finish(target, source, env):
  428. global node_count, progressor
  429. with open(node_count_fname, 'w') as f:
  430. f.write('%d\n' % node_count)
  431. progressor.delete(progressor.file_list())
  432. try:
  433. with open(node_count_fname) as f:
  434. node_count_max = int(f.readline())
  435. except:
  436. pass
  437. cache_directory = os.environ.get("SCONS_CACHE")
  438. # Simple cache pruning, attached to SCons' progress callback. Trim the
  439. # cache directory to a size not larger than cache_limit.
  440. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  441. progressor = cache_progress(cache_directory, cache_limit)
  442. Progress(progressor, interval = node_count_interval)
  443. progress_finish_command = Command('progress_finish', [], progress_finish)
  444. AlwaysBuild(progress_finish_command)