methods.py 36 KB

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