methods.py 42 KB

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