methods.py 41 KB

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