methods.py 41 KB

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