methods.py 31 KB

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