methods.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. import os
  2. import re
  3. import glob
  4. import subprocess
  5. from collections import OrderedDict
  6. from compat import iteritems, isbasestring, open_utf8, decode_utf8, qualname
  7. from SCons import Node
  8. from SCons.Script import Glob
  9. def add_source_files(self, sources, files, warn_duplicates=True):
  10. # Convert string to list of absolute paths (including expanding wildcard)
  11. if isbasestring(files):
  12. # Keep SCons project-absolute path as they are (no wildcard support)
  13. if files.startswith("#"):
  14. if "*" in files:
  15. print("ERROR: Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  16. return
  17. files = [files]
  18. else:
  19. dir_path = self.Dir(".").abspath
  20. files = sorted(glob.glob(dir_path + "/" + files))
  21. # Add each path as compiled Object following environment (self) configuration
  22. for path in files:
  23. obj = self.Object(path)
  24. if obj in sources:
  25. if warn_duplicates:
  26. print('WARNING: Object "{}" already included in environment sources.'.format(obj))
  27. else:
  28. continue
  29. sources.append(obj)
  30. def disable_warnings(self):
  31. # 'self' is the environment
  32. if self.msvc:
  33. # We have to remove existing warning level defines before appending /w,
  34. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  35. warn_flags = ["/Wall", "/W4", "/W3", "/W2", "/W1", "/WX"]
  36. self.Append(CCFLAGS=["/w"])
  37. self.Append(CFLAGS=["/w"])
  38. self.Append(CXXFLAGS=["/w"])
  39. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x in warn_flags]
  40. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x in warn_flags]
  41. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x in warn_flags]
  42. else:
  43. self.Append(CCFLAGS=["-w"])
  44. self.Append(CFLAGS=["-w"])
  45. self.Append(CXXFLAGS=["-w"])
  46. def add_module_version_string(self, s):
  47. self.module_version_string += "." + s
  48. def update_version(module_version_string=""):
  49. build_name = "custom_build"
  50. if os.getenv("BUILD_NAME") != None:
  51. build_name = os.getenv("BUILD_NAME")
  52. print("Using custom build name: " + build_name)
  53. import version
  54. # NOTE: It is safe to generate this file here, since this is still executed serially
  55. f = open("core/version_generated.gen.h", "w")
  56. f.write('#define VERSION_SHORT_NAME "' + str(version.short_name) + '"\n')
  57. f.write('#define VERSION_NAME "' + str(version.name) + '"\n')
  58. f.write("#define VERSION_MAJOR " + str(version.major) + "\n")
  59. f.write("#define VERSION_MINOR " + str(version.minor) + "\n")
  60. f.write("#define VERSION_PATCH " + str(version.patch) + "\n")
  61. f.write('#define VERSION_STATUS "' + str(version.status) + '"\n')
  62. f.write('#define VERSION_BUILD "' + str(build_name) + '"\n')
  63. f.write('#define VERSION_MODULE_CONFIG "' + str(version.module_config) + module_version_string + '"\n')
  64. f.write("#define VERSION_YEAR " + str(version.year) + "\n")
  65. f.write('#define VERSION_WEBSITE "' + str(version.website) + '"\n')
  66. f.close()
  67. # NOTE: It is safe to generate this file here, since this is still executed serially
  68. fhash = open("core/version_hash.gen.h", "w")
  69. githash = ""
  70. gitfolder = ".git"
  71. if os.path.isfile(".git"):
  72. module_folder = open(".git", "r").readline().strip()
  73. if module_folder.startswith("gitdir: "):
  74. gitfolder = module_folder[8:]
  75. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  76. head = open_utf8(os.path.join(gitfolder, "HEAD"), "r").readline().strip()
  77. if head.startswith("ref: "):
  78. head = os.path.join(gitfolder, head[5:])
  79. if os.path.isfile(head):
  80. githash = open(head, "r").readline().strip()
  81. else:
  82. githash = head
  83. fhash.write('#define VERSION_HASH "' + githash + '"')
  84. fhash.close()
  85. def parse_cg_file(fname, uniforms, sizes, conditionals):
  86. fs = open(fname, "r")
  87. line = fs.readline()
  88. while line:
  89. if re.match(r"^\s*uniform", line):
  90. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  91. type = res.groups(1)
  92. name = res.groups(2)
  93. uniforms.append(name)
  94. if type.find("texobj") != -1:
  95. sizes.append(1)
  96. else:
  97. t = re.match(r"float(\d)x(\d)", type)
  98. if t:
  99. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  100. else:
  101. t = re.match(r"float(\d)", type)
  102. sizes.append(int(t.groups(1)))
  103. if line.find("[branch]") != -1:
  104. conditionals.append(name)
  105. line = fs.readline()
  106. fs.close()
  107. def detect_modules(at_path):
  108. module_list = OrderedDict() # name : path
  109. modules_glob = os.path.join(at_path, "*")
  110. files = glob.glob(modules_glob)
  111. files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
  112. for x in files:
  113. if not is_module(x):
  114. continue
  115. name = os.path.basename(x)
  116. path = x.replace("\\", "/") # win32
  117. module_list[name] = path
  118. return module_list
  119. def is_module(path):
  120. return os.path.isdir(path) and os.path.exists(os.path.join(path, "SCsub"))
  121. def write_modules(module_list):
  122. includes_cpp = ""
  123. register_cpp = ""
  124. unregister_cpp = ""
  125. for name, path in module_list.items():
  126. try:
  127. with open(os.path.join(path, "register_types.h")):
  128. includes_cpp += '#include "' + path + '/register_types.h"\n'
  129. register_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  130. register_cpp += "\tregister_" + name + "_types();\n"
  131. register_cpp += "#endif\n"
  132. unregister_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  133. unregister_cpp += "\tunregister_" + name + "_types();\n"
  134. unregister_cpp += "#endif\n"
  135. except IOError:
  136. pass
  137. modules_cpp = (
  138. """
  139. // modules.cpp - THIS FILE IS GENERATED, DO NOT EDIT!!!!!!!
  140. #include "register_module_types.h"
  141. """
  142. + includes_cpp
  143. + """
  144. void register_module_types() {
  145. """
  146. + register_cpp
  147. + """
  148. }
  149. void unregister_module_types() {
  150. """
  151. + unregister_cpp
  152. + """
  153. }
  154. """
  155. )
  156. # NOTE: It is safe to generate this file here, since this is still executed serially
  157. with open("modules/register_module_types.gen.cpp", "w") as f:
  158. f.write(modules_cpp)
  159. def convert_custom_modules_path(path):
  160. if not path:
  161. return path
  162. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  163. err_msg = "Build option 'custom_modules' must %s"
  164. if not os.path.isdir(path):
  165. raise ValueError(err_msg % "point to an existing directory.")
  166. if path == os.path.realpath("modules"):
  167. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  168. if is_module(path):
  169. raise ValueError(err_msg % "point to a directory with modules, not a single module.")
  170. return path
  171. def disable_module(self):
  172. self.disabled_modules.append(self.current_module)
  173. def use_windows_spawn_fix(self, platform=None):
  174. if os.name != "nt":
  175. return # not needed, only for windows
  176. # On Windows, due to the limited command line length, when creating a static library
  177. # from a very high number of objects SCons will invoke "ar" once per object file;
  178. # that makes object files with same names to be overwritten so the last wins and
  179. # the library looses symbols defined by overwritten objects.
  180. # By enabling quick append instead of the default mode (replacing), libraries will
  181. # got built correctly regardless the invocation strategy.
  182. # Furthermore, since SCons will rebuild the library from scratch when an object file
  183. # changes, no multiple versions of the same object file will be present.
  184. self.Replace(ARFLAGS="q")
  185. def mySubProcess(cmdline, env):
  186. startupinfo = subprocess.STARTUPINFO()
  187. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  188. proc = subprocess.Popen(
  189. cmdline,
  190. stdin=subprocess.PIPE,
  191. stdout=subprocess.PIPE,
  192. stderr=subprocess.PIPE,
  193. startupinfo=startupinfo,
  194. shell=False,
  195. env=env,
  196. )
  197. _, err = proc.communicate()
  198. rv = proc.wait()
  199. if rv:
  200. print("=====")
  201. print(err)
  202. print("=====")
  203. return rv
  204. def mySpawn(sh, escape, cmd, args, env):
  205. newargs = " ".join(args[1:])
  206. cmdline = cmd + " " + newargs
  207. rv = 0
  208. env = {str(key): str(value) for key, value in iteritems(env)}
  209. if len(cmdline) > 32000 and cmd.endswith("ar"):
  210. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  211. for i in range(3, len(args)):
  212. rv = mySubProcess(cmdline + args[i], env)
  213. if rv:
  214. break
  215. else:
  216. rv = mySubProcess(cmdline, env)
  217. return rv
  218. self["SPAWN"] = mySpawn
  219. def split_lib(self, libname, src_list=None, env_lib=None):
  220. env = self
  221. num = 0
  222. cur_base = ""
  223. max_src = 64
  224. list = []
  225. lib_list = []
  226. if src_list is None:
  227. src_list = getattr(env, libname + "_sources")
  228. if type(env_lib) == type(None):
  229. env_lib = env
  230. for f in src_list:
  231. fname = ""
  232. if type(f) == type(""):
  233. fname = env.File(f).path
  234. else:
  235. fname = env.File(f)[0].path
  236. fname = fname.replace("\\", "/")
  237. base = "/".join(fname.split("/")[:2])
  238. if base != cur_base and len(list) > max_src:
  239. if num > 0:
  240. lib = env_lib.add_library(libname + str(num), list)
  241. lib_list.append(lib)
  242. list = []
  243. num = num + 1
  244. cur_base = base
  245. list.append(f)
  246. lib = env_lib.add_library(libname + str(num), list)
  247. lib_list.append(lib)
  248. lib_base = []
  249. env_lib.add_source_files(lib_base, "*.cpp")
  250. lib = env_lib.add_library(libname, lib_base)
  251. lib_list.insert(0, lib)
  252. env.Prepend(LIBS=lib_list)
  253. # When we split modules into arbitrary chunks, we end up with linking issues
  254. # due to symbol dependencies split over several libs, which may not be linked
  255. # in the required order. We use --start-group and --end-group to tell the
  256. # linker that those archives should be searched repeatedly to resolve all
  257. # undefined references.
  258. # As SCons doesn't give us much control over how inserting libs in LIBS
  259. # impacts the linker call, we need to hack our way into the linking commands
  260. # LINKCOM and SHLINKCOM to set those flags.
  261. if "-Wl,--start-group" in env["LINKCOM"] and "-Wl,--start-group" in env["SHLINKCOM"]:
  262. # Already added by a previous call, skip.
  263. return
  264. env["LINKCOM"] = str(env["LINKCOM"]).replace("$_LIBFLAGS", "-Wl,--start-group $_LIBFLAGS -Wl,--end-group")
  265. env["SHLINKCOM"] = str(env["LINKCOM"]).replace("$_LIBFLAGS", "-Wl,--start-group $_LIBFLAGS -Wl,--end-group")
  266. def save_active_platforms(apnames, ap):
  267. for x in ap:
  268. names = ["logo"]
  269. if os.path.isfile(x + "/run_icon.png"):
  270. names.append("run_icon")
  271. for name in names:
  272. pngf = open(x + "/" + name + ".png", "rb")
  273. b = pngf.read(1)
  274. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  275. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  276. while len(b) == 1:
  277. str += hex(ord(b))
  278. b = pngf.read(1)
  279. if len(b) == 1:
  280. str += ","
  281. str += "};\n"
  282. pngf.close()
  283. # NOTE: It is safe to generate this file here, since this is still executed serially
  284. wf = x + "/" + name + ".gen.h"
  285. with open(wf, "w") as pngw:
  286. pngw.write(str)
  287. def no_verbose(sys, env):
  288. colors = {}
  289. # Colors are disabled in non-TTY environments such as pipes. This means
  290. # that if output is redirected to a file, it will not contain color codes
  291. if sys.stdout.isatty():
  292. colors["cyan"] = "\033[96m"
  293. colors["purple"] = "\033[95m"
  294. colors["blue"] = "\033[94m"
  295. colors["green"] = "\033[92m"
  296. colors["yellow"] = "\033[93m"
  297. colors["red"] = "\033[91m"
  298. colors["end"] = "\033[0m"
  299. else:
  300. colors["cyan"] = ""
  301. colors["purple"] = ""
  302. colors["blue"] = ""
  303. colors["green"] = ""
  304. colors["yellow"] = ""
  305. colors["red"] = ""
  306. colors["end"] = ""
  307. compile_source_message = "%sCompiling %s==> %s$SOURCE%s" % (
  308. colors["blue"],
  309. colors["purple"],
  310. colors["yellow"],
  311. colors["end"],
  312. )
  313. java_compile_source_message = "%sCompiling %s==> %s$SOURCE%s" % (
  314. colors["blue"],
  315. colors["purple"],
  316. colors["yellow"],
  317. colors["end"],
  318. )
  319. compile_shared_source_message = "%sCompiling shared %s==> %s$SOURCE%s" % (
  320. colors["blue"],
  321. colors["purple"],
  322. colors["yellow"],
  323. colors["end"],
  324. )
  325. link_program_message = "%sLinking Program %s==> %s$TARGET%s" % (
  326. colors["red"],
  327. colors["purple"],
  328. colors["yellow"],
  329. colors["end"],
  330. )
  331. link_library_message = "%sLinking Static Library %s==> %s$TARGET%s" % (
  332. colors["red"],
  333. colors["purple"],
  334. colors["yellow"],
  335. colors["end"],
  336. )
  337. ranlib_library_message = "%sRanlib Library %s==> %s$TARGET%s" % (
  338. colors["red"],
  339. colors["purple"],
  340. colors["yellow"],
  341. colors["end"],
  342. )
  343. link_shared_library_message = "%sLinking Shared Library %s==> %s$TARGET%s" % (
  344. colors["red"],
  345. colors["purple"],
  346. colors["yellow"],
  347. colors["end"],
  348. )
  349. java_library_message = "%sCreating Java Archive %s==> %s$TARGET%s" % (
  350. colors["red"],
  351. colors["purple"],
  352. colors["yellow"],
  353. colors["end"],
  354. )
  355. env.Append(CXXCOMSTR=[compile_source_message])
  356. env.Append(CCCOMSTR=[compile_source_message])
  357. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  358. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  359. env.Append(ARCOMSTR=[link_library_message])
  360. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  361. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  362. env.Append(LINKCOMSTR=[link_program_message])
  363. env.Append(JARCOMSTR=[java_library_message])
  364. env.Append(JAVACCOMSTR=[java_compile_source_message])
  365. def detect_visual_c_compiler_version(tools_env):
  366. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  367. # (see the SCons documentation for more information on what it does)...
  368. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  369. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  370. # the proper vc version that will be called
  371. # There is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  372. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  373. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  374. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  375. # the following string values:
  376. # "" Compiler not detected
  377. # "amd64" Native 64 bit compiler
  378. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  379. # "x86" Native 32 bit compiler
  380. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  381. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  382. # and similar architectures/compilers
  383. # Set chosen compiler to "not detected"
  384. vc_chosen_compiler_index = -1
  385. vc_chosen_compiler_str = ""
  386. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  387. if "VCINSTALLDIR" in tools_env:
  388. # print("Checking VCINSTALLDIR")
  389. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  390. # First test if amd64 and amd64_x86 compilers are present in the path
  391. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  392. if vc_amd64_compiler_detection_index > -1:
  393. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  394. vc_chosen_compiler_str = "amd64"
  395. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  396. if vc_amd64_x86_compiler_detection_index > -1 and (
  397. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  398. ):
  399. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  400. vc_chosen_compiler_str = "amd64_x86"
  401. # Now check the 32 bit compilers
  402. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  403. if vc_x86_compiler_detection_index > -1 and (
  404. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  405. ):
  406. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  407. vc_chosen_compiler_str = "x86"
  408. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  409. if vc_x86_amd64_compiler_detection_index > -1 and (
  410. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  411. ):
  412. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  413. vc_chosen_compiler_str = "x86_amd64"
  414. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  415. if "VCTOOLSINSTALLDIR" in tools_env:
  416. # Newer versions have a different path available
  417. vc_amd64_compiler_detection_index = (
  418. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  419. )
  420. if vc_amd64_compiler_detection_index > -1:
  421. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  422. vc_chosen_compiler_str = "amd64"
  423. vc_amd64_x86_compiler_detection_index = (
  424. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  425. )
  426. if vc_amd64_x86_compiler_detection_index > -1 and (
  427. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  428. ):
  429. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  430. vc_chosen_compiler_str = "amd64_x86"
  431. vc_x86_compiler_detection_index = (
  432. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  433. )
  434. if vc_x86_compiler_detection_index > -1 and (
  435. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  436. ):
  437. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  438. vc_chosen_compiler_str = "x86"
  439. vc_x86_amd64_compiler_detection_index = (
  440. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  441. )
  442. if vc_x86_amd64_compiler_detection_index > -1 and (
  443. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  444. ):
  445. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  446. vc_chosen_compiler_str = "x86_amd64"
  447. return vc_chosen_compiler_str
  448. def find_visual_c_batch_file(env):
  449. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file
  450. version = get_default_version(env)
  451. (host_platform, target_platform, _) = get_host_target(env)
  452. return find_batch_file(env, version, host_platform, target_platform)[0]
  453. def generate_cpp_hint_file(filename):
  454. if os.path.isfile(filename):
  455. # Don't overwrite an existing hint file since the user may have customized it.
  456. pass
  457. else:
  458. try:
  459. with open(filename, "w") as fd:
  460. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  461. except IOError:
  462. print("Could not write cpp.hint file.")
  463. def glob_recursive(pattern, node="."):
  464. results = []
  465. for f in Glob(str(node) + "/*", source=True):
  466. if type(f) is Node.FS.Dir:
  467. results += glob_recursive(pattern, f)
  468. results += Glob(str(node) + "/" + pattern, source=True)
  469. return results
  470. def add_to_vs_project(env, sources):
  471. for x in sources:
  472. if type(x) == type(""):
  473. fname = env.File(x).path
  474. else:
  475. fname = env.File(x)[0].path
  476. pieces = fname.split(".")
  477. if len(pieces) > 0:
  478. basename = pieces[0]
  479. basename = basename.replace("\\\\", "/")
  480. if os.path.isfile(basename + ".h"):
  481. env.vs_incs += [basename + ".h"]
  482. elif os.path.isfile(basename + ".hpp"):
  483. env.vs_incs += [basename + ".hpp"]
  484. if os.path.isfile(basename + ".c"):
  485. env.vs_srcs += [basename + ".c"]
  486. elif os.path.isfile(basename + ".cpp"):
  487. env.vs_srcs += [basename + ".cpp"]
  488. def generate_vs_project(env, num_jobs):
  489. batch_file = find_visual_c_batch_file(env)
  490. if batch_file:
  491. def build_commandline(commands):
  492. common_build_prefix = [
  493. 'cmd /V /C set "plat=$(PlatformTarget)"',
  494. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  495. 'set "tools=%s"' % env["tools"],
  496. '(if "$(Configuration)"=="release" (set "tools=no"))',
  497. 'call "' + batch_file + '" !plat!',
  498. ]
  499. # windows allows us to have spaces in paths, so we need
  500. # to double quote off the directory. However, the path ends
  501. # in a backslash, so we need to remove this, lest it escape the
  502. # last double quote off, confusing MSBuild
  503. common_build_postfix = [
  504. "--directory=\"$(ProjectDir.TrimEnd('\\'))\"",
  505. "platform=windows",
  506. "target=$(Configuration)",
  507. "progress=no",
  508. "tools=!tools!",
  509. "-j%s" % num_jobs,
  510. ]
  511. if env["custom_modules"]:
  512. common_build_postfix.append("custom_modules=%s" % env["custom_modules"])
  513. result = " ^& ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  514. return result
  515. add_to_vs_project(env, env.core_sources)
  516. add_to_vs_project(env, env.drivers_sources)
  517. add_to_vs_project(env, env.main_sources)
  518. add_to_vs_project(env, env.modules_sources)
  519. add_to_vs_project(env, env.scene_sources)
  520. add_to_vs_project(env, env.servers_sources)
  521. add_to_vs_project(env, env.editor_sources)
  522. for header in glob_recursive("**/*.h"):
  523. env.vs_incs.append(str(header))
  524. env["MSVSBUILDCOM"] = build_commandline("scons")
  525. env["MSVSREBUILDCOM"] = build_commandline("scons vsproj=yes")
  526. env["MSVSCLEANCOM"] = build_commandline("scons --clean")
  527. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  528. # required for Visual Studio to understand that it needs to generate an NMAKE
  529. # project. Do not modify without knowing what you are doing.
  530. debug_variants = ["debug|Win32"] + ["debug|x64"]
  531. release_variants = ["release|Win32"] + ["release|x64"]
  532. release_debug_variants = ["release_debug|Win32"] + ["release_debug|x64"]
  533. variants = debug_variants + release_variants + release_debug_variants
  534. debug_targets = ["bin\\godot.windows.tools.32.exe"] + ["bin\\godot.windows.tools.64.exe"]
  535. release_targets = ["bin\\godot.windows.opt.32.exe"] + ["bin\\godot.windows.opt.64.exe"]
  536. release_debug_targets = ["bin\\godot.windows.opt.tools.32.exe"] + ["bin\\godot.windows.opt.tools.64.exe"]
  537. targets = debug_targets + release_targets + release_debug_targets
  538. if not env.get("MSVS"):
  539. env["MSVS"]["PROJECTSUFFIX"] = ".vcxproj"
  540. env["MSVS"]["SOLUTIONSUFFIX"] = ".sln"
  541. env.MSVSProject(
  542. target=["#godot" + env["MSVSPROJECTSUFFIX"]],
  543. incs=env.vs_incs,
  544. srcs=env.vs_srcs,
  545. runfile=targets,
  546. buildtarget=targets,
  547. auto_build_solution=1,
  548. variant=variants,
  549. )
  550. else:
  551. print(
  552. "Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project."
  553. )
  554. def precious_program(env, program, sources, **args):
  555. program = env.ProgramOriginal(program, sources, **args)
  556. env.Precious(program)
  557. return program
  558. def add_shared_library(env, name, sources, **args):
  559. library = env.SharedLibrary(name, sources, **args)
  560. env.NoCache(library)
  561. return library
  562. def add_library(env, name, sources, **args):
  563. library = env.Library(name, sources, **args)
  564. env.NoCache(library)
  565. return library
  566. def add_program(env, name, sources, **args):
  567. program = env.Program(name, sources, **args)
  568. env.NoCache(program)
  569. return program
  570. def CommandNoCache(env, target, sources, command, **args):
  571. result = env.Command(target, sources, command, **args)
  572. env.NoCache(result)
  573. return result
  574. def get_darwin_sdk_version(platform):
  575. sdk_name = ""
  576. if platform == "osx":
  577. sdk_name = "macosx"
  578. elif platform == "iphone":
  579. sdk_name = "iphoneos"
  580. elif platform == "iphonesimulator":
  581. sdk_name = "iphonesimulator"
  582. else:
  583. raise Exception("Invalid platform argument passed to get_darwin_sdk_version")
  584. try:
  585. return float(decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-version"]).strip()))
  586. except (subprocess.CalledProcessError, OSError):
  587. print("Failed to find SDK version while running xcrun --sdk {} --show-sdk-version.".format(sdk_name))
  588. return 0.0
  589. def detect_darwin_sdk_path(platform, env):
  590. sdk_name = ""
  591. if platform == "osx":
  592. sdk_name = "macosx"
  593. var_name = "MACOS_SDK_PATH"
  594. elif platform == "iphone":
  595. sdk_name = "iphoneos"
  596. var_name = "IPHONESDK"
  597. elif platform == "iphonesimulator":
  598. sdk_name = "iphonesimulator"
  599. var_name = "IPHONESDK"
  600. else:
  601. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  602. if not env[var_name]:
  603. try:
  604. sdk_path = decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip())
  605. if sdk_path:
  606. env[var_name] = sdk_path
  607. except (subprocess.CalledProcessError, OSError):
  608. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  609. raise
  610. def get_compiler_version(env):
  611. """
  612. Returns an array of version numbers as ints: [major, minor, patch].
  613. The return array should have at least two values (major, minor).
  614. """
  615. if not env.msvc:
  616. # Not using -dumpversion as some GCC distros only return major, and
  617. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  618. try:
  619. version = decode_utf8(subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip())
  620. except (subprocess.CalledProcessError, OSError):
  621. print("Couldn't parse CXX environment variable to infer compiler version.")
  622. return None
  623. else: # TODO: Implement for MSVC
  624. return None
  625. match = re.search("[0-9]+\.[0-9.]+", version)
  626. if match is not None:
  627. return list(map(int, match.group().split(".")))
  628. else:
  629. return None
  630. def using_gcc(env):
  631. return "gcc" in os.path.basename(env["CC"])
  632. def using_clang(env):
  633. return "clang" in os.path.basename(env["CC"])
  634. def show_progress(env):
  635. import sys
  636. from SCons.Script import Progress, Command, AlwaysBuild
  637. screen = sys.stdout
  638. # Progress reporting is not available in non-TTY environments since it
  639. # messes with the output (for example, when writing to a file)
  640. show_progress = env["progress"] and sys.stdout.isatty()
  641. node_count_data = {
  642. "count": 0,
  643. "max": 0,
  644. "interval": 1,
  645. "fname": str(env.Dir("#")) + "/.scons_node_count",
  646. }
  647. import time, math
  648. class cache_progress:
  649. # The default is 1 GB cache and 12 hours half life
  650. def __init__(self, path=None, limit=1073741824, half_life=43200):
  651. self.path = path
  652. self.limit = limit
  653. self.exponent_scale = math.log(2) / half_life
  654. if env["verbose"] and path != None:
  655. screen.write(
  656. "Current cache limit is {} (used: {})\n".format(
  657. self.convert_size(limit), self.convert_size(self.get_size(path))
  658. )
  659. )
  660. self.delete(self.file_list())
  661. def __call__(self, node, *args, **kw):
  662. if show_progress:
  663. # Print the progress percentage
  664. node_count_data["count"] += node_count_data["interval"]
  665. node_count = node_count_data["count"]
  666. node_count_max = node_count_data["max"]
  667. if node_count_max > 0 and node_count <= node_count_max:
  668. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  669. screen.flush()
  670. elif node_count_max > 0 and node_count > node_count_max:
  671. screen.write("\r[100%] ")
  672. screen.flush()
  673. else:
  674. screen.write("\r[Initial build] ")
  675. screen.flush()
  676. def delete(self, files):
  677. if len(files) == 0:
  678. return
  679. if env["verbose"]:
  680. # Utter something
  681. screen.write("\rPurging %d %s from cache...\n" % (len(files), len(files) > 1 and "files" or "file"))
  682. [os.remove(f) for f in files]
  683. def file_list(self):
  684. if self.path is None:
  685. # Nothing to do
  686. return []
  687. # Gather a list of (filename, (size, atime)) within the
  688. # cache directory
  689. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  690. if file_stat == []:
  691. # Nothing to do
  692. return []
  693. # Weight the cache files by size (assumed to be roughly
  694. # proportional to the recompilation time) times an exponential
  695. # decay since the ctime, and return a list with the entries
  696. # (filename, size, weight).
  697. current_time = time.time()
  698. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  699. # Sort by the most recently accessed files (most sensible to keep) first
  700. file_stat.sort(key=lambda x: x[2])
  701. # Search for the first entry where the storage limit is
  702. # reached
  703. sum, mark = 0, None
  704. for i, x in enumerate(file_stat):
  705. sum += x[1]
  706. if sum > self.limit:
  707. mark = i
  708. break
  709. if mark is None:
  710. return []
  711. else:
  712. return [x[0] for x in file_stat[mark:]]
  713. def convert_size(self, size_bytes):
  714. if size_bytes == 0:
  715. return "0 bytes"
  716. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  717. i = int(math.floor(math.log(size_bytes, 1024)))
  718. p = math.pow(1024, i)
  719. s = round(size_bytes / p, 2)
  720. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  721. def get_size(self, start_path="."):
  722. total_size = 0
  723. for dirpath, dirnames, filenames in os.walk(start_path):
  724. for f in filenames:
  725. fp = os.path.join(dirpath, f)
  726. total_size += os.path.getsize(fp)
  727. return total_size
  728. def progress_finish(target, source, env):
  729. with open(node_count_data["fname"], "w") as f:
  730. f.write("%d\n" % node_count_data["count"])
  731. progressor.delete(progressor.file_list())
  732. try:
  733. with open(node_count_data["fname"]) as f:
  734. node_count_data["max"] = int(f.readline())
  735. except Exception:
  736. pass
  737. cache_directory = os.environ.get("SCONS_CACHE")
  738. # Simple cache pruning, attached to SCons' progress callback. Trim the
  739. # cache directory to a size not larger than cache_limit.
  740. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  741. progressor = cache_progress(cache_directory, cache_limit)
  742. Progress(progressor, interval=node_count_data["interval"])
  743. progress_finish_command = Command("progress_finish", [], progress_finish)
  744. AlwaysBuild(progress_finish_command)
  745. def dump(env):
  746. # Dumps latest build information for debugging purposes and external tools.
  747. from json import dump
  748. def non_serializable(obj):
  749. return "<<non-serializable: %s>>" % (qualname(type(obj)))
  750. with open(".scons_env.json", "w") as f:
  751. dump(env.Dictionary(), f, indent=4, default=non_serializable)