methods.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. # TODO: We should investigate if we can avoid relying on SCons internals here.
  533. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file, find_vc_pdir
  534. # Syntax changed in SCons 4.4.0.
  535. from SCons import __version__ as scons_raw_version
  536. scons_ver = env._get_major_minor_revision(scons_raw_version)
  537. msvc_version = get_default_version(env)
  538. if scons_ver >= (4, 4, 0):
  539. (host_platform, target_platform, _) = get_host_target(env, msvc_version)
  540. else:
  541. (host_platform, target_platform, _) = get_host_target(env)
  542. if scons_ver < (4, 6, 0):
  543. return find_batch_file(env, msvc_version, host_platform, target_platform)[0]
  544. # SCons 4.6.0+ removed passing env, so we need to get the product_dir ourselves first,
  545. # then pass that as the last param instead of env as the first param as before.
  546. # Param names need to be explicit, as they were shuffled around in SCons 4.8.0.
  547. product_dir = find_vc_pdir(msvc_version=msvc_version, env=env)
  548. return find_batch_file(msvc_version, host_platform, target_platform, product_dir)[0]
  549. def generate_cpp_hint_file(filename):
  550. if os.path.isfile(filename):
  551. # Don't overwrite an existing hint file since the user may have customized it.
  552. pass
  553. else:
  554. try:
  555. with open(filename, "w") as fd:
  556. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  557. except IOError:
  558. print("Could not write cpp.hint file.")
  559. def glob_recursive(pattern, node="."):
  560. results = []
  561. for f in Glob(str(node) + "/*", source=True):
  562. if type(f) is Node.FS.Dir:
  563. results += glob_recursive(pattern, f)
  564. results += Glob(str(node) + "/" + pattern, source=True)
  565. return results
  566. def add_to_vs_project(env, sources):
  567. for x in sources:
  568. if type(x) == type(""):
  569. fname = env.File(x).path
  570. else:
  571. fname = env.File(x)[0].path
  572. pieces = fname.split(".")
  573. if len(pieces) > 0:
  574. basename = pieces[0]
  575. basename = basename.replace("\\\\", "/")
  576. if os.path.isfile(basename + ".h"):
  577. env.vs_incs += [basename + ".h"]
  578. elif os.path.isfile(basename + ".hpp"):
  579. env.vs_incs += [basename + ".hpp"]
  580. if os.path.isfile(basename + ".c"):
  581. env.vs_srcs += [basename + ".c"]
  582. elif os.path.isfile(basename + ".cpp"):
  583. env.vs_srcs += [basename + ".cpp"]
  584. def generate_vs_project(env, num_jobs):
  585. batch_file = find_visual_c_batch_file(env)
  586. if batch_file:
  587. class ModuleConfigs(Mapping):
  588. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  589. # required for Visual Studio to understand that it needs to generate an NMAKE
  590. # project. Do not modify without knowing what you are doing.
  591. PLATFORMS = ["Win32", "x64"]
  592. PLATFORM_IDS = ["32", "64"]
  593. CONFIGURATIONS = ["debug", "release", "release_debug"]
  594. CONFIGURATION_IDS = ["tools", "opt", "opt.tools"]
  595. @staticmethod
  596. def for_every_variant(value):
  597. return [value for _ in range(len(ModuleConfigs.CONFIGURATIONS) * len(ModuleConfigs.PLATFORMS))]
  598. def __init__(self):
  599. shared_targets_array = []
  600. self.names = []
  601. self.arg_dict = {
  602. "variant": [],
  603. "runfile": shared_targets_array,
  604. "buildtarget": shared_targets_array,
  605. "cpppaths": [],
  606. "cppdefines": [],
  607. "cmdargs": [],
  608. }
  609. self.add_mode() # default
  610. def add_mode(
  611. self,
  612. name: str = "",
  613. includes: str = "",
  614. cli_args: str = "",
  615. defines=None,
  616. ):
  617. if defines is None:
  618. defines = []
  619. self.names.append(name)
  620. self.arg_dict["variant"] += [
  621. f'{config}{f"_[{name}]" if name else ""}|{platform}'
  622. for config in ModuleConfigs.CONFIGURATIONS
  623. for platform in ModuleConfigs.PLATFORMS
  624. ]
  625. self.arg_dict["runfile"] += [
  626. f'bin\\godot.windows.{config_id}.{plat_id}{f".{name}" if name else ""}.exe'
  627. for config_id in ModuleConfigs.CONFIGURATION_IDS
  628. for plat_id in ModuleConfigs.PLATFORM_IDS
  629. ]
  630. self.arg_dict["cpppaths"] += ModuleConfigs.for_every_variant(env["CPPPATH"] + [includes])
  631. self.arg_dict["cppdefines"] += ModuleConfigs.for_every_variant(list(env["CPPDEFINES"]) + defines)
  632. self.arg_dict["cmdargs"] += ModuleConfigs.for_every_variant(cli_args)
  633. def build_commandline(self, commands):
  634. configuration_getter = (
  635. "$(Configuration"
  636. + "".join([f'.Replace("{name}", "")' for name in self.names[1:]])
  637. + '.Replace("_[]", "")'
  638. + ")"
  639. )
  640. common_build_prefix = [
  641. 'cmd /V /C set "plat=$(PlatformTarget)"',
  642. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  643. 'set "tools=%s"' % env["tools"],
  644. f'(if "{configuration_getter}"=="release" (set "tools=no"))',
  645. 'call "' + batch_file + '" !plat!',
  646. ]
  647. # Windows allows us to have spaces in paths, so we need
  648. # to double quote off the directory. However, the path ends
  649. # in a backslash, so we need to remove this, lest it escape the
  650. # last double quote off, confusing MSBuild
  651. common_build_postfix = [
  652. "--directory=\"$(ProjectDir.TrimEnd('\\'))\"",
  653. "platform=windows",
  654. f"target={configuration_getter}",
  655. "progress=no",
  656. "tools=!tools!",
  657. "-j%s" % num_jobs,
  658. ]
  659. if env["custom_modules"]:
  660. common_build_postfix.append("custom_modules=%s" % env["custom_modules"])
  661. if env["incremental_link"]:
  662. common_build_postfix.append("incremental_link=yes")
  663. result = " ^& ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  664. return result
  665. # Mappings interface definitions
  666. def __iter__(self) -> Iterator[str]:
  667. for x in self.arg_dict:
  668. yield x
  669. def __len__(self) -> int:
  670. return len(self.names)
  671. def __getitem__(self, k: str):
  672. return self.arg_dict[k]
  673. add_to_vs_project(env, env.core_sources)
  674. add_to_vs_project(env, env.drivers_sources)
  675. add_to_vs_project(env, env.main_sources)
  676. add_to_vs_project(env, env.modules_sources)
  677. add_to_vs_project(env, env.scene_sources)
  678. add_to_vs_project(env, env.servers_sources)
  679. add_to_vs_project(env, env.editor_sources)
  680. for header in glob_recursive("**/*.h"):
  681. env.vs_incs.append(str(header))
  682. module_configs = ModuleConfigs()
  683. import modules.mono.build_scripts.mono_reg_utils as mono_reg
  684. if env.get("module_mono_enabled"):
  685. mono_root = env.get("mono_prefix") or mono_reg.find_mono_root_dir(env["bits"])
  686. if mono_root:
  687. module_configs.add_mode(
  688. "mono",
  689. includes=os.path.join(mono_root, "include", "mono-2.0"),
  690. cli_args="module_mono_enabled=yes mono_glue=yes",
  691. defines=[("MONO_GLUE_ENABLED",)],
  692. )
  693. else:
  694. print("Mono installation directory not found. Generated project will not have build variants for Mono.")
  695. env["MSVSBUILDCOM"] = module_configs.build_commandline("scons")
  696. env["MSVSREBUILDCOM"] = module_configs.build_commandline("scons vsproj=yes")
  697. env["MSVSCLEANCOM"] = module_configs.build_commandline("scons --clean")
  698. if not env.get("MSVS"):
  699. env["MSVS"]["PROJECTSUFFIX"] = ".vcxproj"
  700. env["MSVS"]["SOLUTIONSUFFIX"] = ".sln"
  701. env.MSVSProject(
  702. target=["#godot" + env["MSVSPROJECTSUFFIX"]],
  703. incs=env.vs_incs,
  704. srcs=env.vs_srcs,
  705. auto_build_solution=1,
  706. **module_configs,
  707. )
  708. else:
  709. print(
  710. "Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project."
  711. )
  712. def precious_program(env, program, sources, **args):
  713. program = env.ProgramOriginal(program, sources, **args)
  714. env.Precious(program)
  715. return program
  716. def add_shared_library(env, name, sources, **args):
  717. library = env.SharedLibrary(name, sources, **args)
  718. env.NoCache(library)
  719. return library
  720. def add_library(env, name, sources, **args):
  721. library = env.Library(name, sources, **args)
  722. env.NoCache(library)
  723. return library
  724. def add_program(env, name, sources, **args):
  725. program = env.Program(name, sources, **args)
  726. env.NoCache(program)
  727. return program
  728. def CommandNoCache(env, target, sources, command, **args):
  729. result = env.Command(target, sources, command, **args)
  730. env.NoCache(result)
  731. return result
  732. def get_darwin_sdk_version(platform):
  733. sdk_name = ""
  734. if platform == "osx":
  735. sdk_name = "macosx"
  736. elif platform == "iphone":
  737. sdk_name = "iphoneos"
  738. elif platform == "iphonesimulator":
  739. sdk_name = "iphonesimulator"
  740. else:
  741. raise Exception("Invalid platform argument passed to get_darwin_sdk_version")
  742. try:
  743. return float(decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-version"]).strip()))
  744. except (subprocess.CalledProcessError, OSError):
  745. print("Failed to find SDK version while running xcrun --sdk {} --show-sdk-version.".format(sdk_name))
  746. return 0.0
  747. def detect_darwin_sdk_path(platform, env):
  748. sdk_name = ""
  749. if platform == "osx":
  750. sdk_name = "macosx"
  751. var_name = "MACOS_SDK_PATH"
  752. elif platform == "iphone":
  753. sdk_name = "iphoneos"
  754. var_name = "IPHONESDK"
  755. elif platform == "iphonesimulator":
  756. sdk_name = "iphonesimulator"
  757. var_name = "IPHONESDK"
  758. else:
  759. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  760. if not env[var_name]:
  761. try:
  762. sdk_path = decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip())
  763. if sdk_path:
  764. env[var_name] = sdk_path
  765. except (subprocess.CalledProcessError, OSError):
  766. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  767. raise
  768. def get_compiler_version(env):
  769. """
  770. Returns an array of version numbers as ints: [major, minor, patch].
  771. The return array should have at least two values (major, minor).
  772. """
  773. if not env.msvc:
  774. # Not using -dumpversion as some GCC distros only return major, and
  775. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  776. try:
  777. version = decode_utf8(subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip())
  778. except (subprocess.CalledProcessError, OSError):
  779. print("Couldn't parse CXX environment variable to infer compiler version.")
  780. return None
  781. else: # TODO: Implement for MSVC
  782. return None
  783. match = re.search(r"[0-9]+\.[0-9.]+", version)
  784. if match is not None:
  785. return list(map(int, match.group().split(".")))
  786. else:
  787. return None
  788. def is_vanilla_clang(env):
  789. if not using_clang(env):
  790. return False
  791. try:
  792. version = decode_utf8(subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip())
  793. except (subprocess.CalledProcessError, OSError):
  794. print("Couldn't parse CXX environment variable to infer compiler version.")
  795. return False
  796. return not version.startswith("Apple")
  797. def using_gcc(env):
  798. return "gcc" in os.path.basename(env["CC"])
  799. def using_clang(env):
  800. return "clang" in os.path.basename(env["CC"])
  801. def using_emcc(env):
  802. return "emcc" in os.path.basename(env["CC"])
  803. def show_progress(env):
  804. import sys
  805. from SCons.Script import Progress, Command, AlwaysBuild
  806. screen = sys.stdout
  807. # Progress reporting is not available in non-TTY environments since it
  808. # messes with the output (for example, when writing to a file)
  809. show_progress = env["progress"] and sys.stdout.isatty()
  810. node_count_data = {
  811. "count": 0,
  812. "max": 0,
  813. "interval": 1,
  814. "fname": str(env.Dir("#")) + "/.scons_node_count",
  815. }
  816. import time, math
  817. class cache_progress:
  818. # The default is 1 GB cache and 12 hours half life
  819. def __init__(self, path=None, limit=1073741824, half_life=43200):
  820. self.path = path
  821. self.limit = limit
  822. self.exponent_scale = math.log(2) / half_life
  823. if env["verbose"] and path != None:
  824. screen.write(
  825. "Current cache limit is {} (used: {})\n".format(
  826. self.convert_size(limit), self.convert_size(self.get_size(path))
  827. )
  828. )
  829. self.delete(self.file_list())
  830. def __call__(self, node, *args, **kw):
  831. if show_progress:
  832. # Print the progress percentage
  833. node_count_data["count"] += node_count_data["interval"]
  834. node_count = node_count_data["count"]
  835. node_count_max = node_count_data["max"]
  836. if node_count_max > 0 and node_count <= node_count_max:
  837. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  838. screen.flush()
  839. elif node_count_max > 0 and node_count > node_count_max:
  840. screen.write("\r[100%] ")
  841. screen.flush()
  842. else:
  843. screen.write("\r[Initial build] ")
  844. screen.flush()
  845. def delete(self, files):
  846. if len(files) == 0:
  847. return
  848. if env["verbose"]:
  849. # Utter something
  850. screen.write("\rPurging %d %s from cache...\n" % (len(files), len(files) > 1 and "files" or "file"))
  851. [os.remove(f) for f in files]
  852. def file_list(self):
  853. if self.path is None:
  854. # Nothing to do
  855. return []
  856. # Gather a list of (filename, (size, atime)) within the
  857. # cache directory
  858. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  859. if file_stat == []:
  860. # Nothing to do
  861. return []
  862. # Weight the cache files by size (assumed to be roughly
  863. # proportional to the recompilation time) times an exponential
  864. # decay since the ctime, and return a list with the entries
  865. # (filename, size, weight).
  866. current_time = time.time()
  867. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  868. # Sort by the most recently accessed files (most sensible to keep) first
  869. file_stat.sort(key=lambda x: x[2])
  870. # Search for the first entry where the storage limit is
  871. # reached
  872. sum, mark = 0, None
  873. for i, x in enumerate(file_stat):
  874. sum += x[1]
  875. if sum > self.limit:
  876. mark = i
  877. break
  878. if mark is None:
  879. return []
  880. else:
  881. return [x[0] for x in file_stat[mark:]]
  882. def convert_size(self, size_bytes):
  883. if size_bytes == 0:
  884. return "0 bytes"
  885. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  886. i = int(math.floor(math.log(size_bytes, 1024)))
  887. p = math.pow(1024, i)
  888. s = round(size_bytes / p, 2)
  889. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  890. def get_size(self, start_path="."):
  891. total_size = 0
  892. for dirpath, dirnames, filenames in os.walk(start_path):
  893. for f in filenames:
  894. fp = os.path.join(dirpath, f)
  895. total_size += os.path.getsize(fp)
  896. return total_size
  897. def progress_finish(target, source, env):
  898. try:
  899. with open(node_count_data["fname"], "w") as f:
  900. f.write("%d\n" % node_count_data["count"])
  901. progressor.delete(progressor.file_list())
  902. except Exception:
  903. pass
  904. try:
  905. with open(node_count_data["fname"]) as f:
  906. node_count_data["max"] = int(f.readline())
  907. except Exception:
  908. pass
  909. cache_directory = os.environ.get("SCONS_CACHE")
  910. # Simple cache pruning, attached to SCons' progress callback. Trim the
  911. # cache directory to a size not larger than cache_limit.
  912. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  913. progressor = cache_progress(cache_directory, cache_limit)
  914. Progress(progressor, interval=node_count_data["interval"])
  915. progress_finish_command = Command("progress_finish", [], progress_finish)
  916. AlwaysBuild(progress_finish_command)
  917. def dump(env):
  918. # Dumps latest build information for debugging purposes and external tools.
  919. from json import dump
  920. def non_serializable(obj):
  921. return "<<non-serializable: %s>>" % (qualname(type(obj)))
  922. with open(".scons_env.json", "w") as f:
  923. dump(env.Dictionary(), f, indent=4, default=non_serializable)