methods.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. import atexit
  2. import contextlib
  3. import glob
  4. import math
  5. import os
  6. import re
  7. import subprocess
  8. import sys
  9. from collections import OrderedDict
  10. from enum import Enum
  11. from io import StringIO, TextIOWrapper
  12. from pathlib import Path
  13. from typing import Generator, List, Optional, Union, cast
  14. # Get the "Godot" folder name ahead of time
  15. base_folder_path = str(os.path.abspath(Path(__file__).parent)) + "/"
  16. base_folder_only = os.path.basename(os.path.normpath(base_folder_path))
  17. # Listing all the folders we have converted
  18. # for SCU in scu_builders.py
  19. _scu_folders = set()
  20. # Colors are disabled in non-TTY environments such as pipes. This means
  21. # that if output is redirected to a file, it won't contain color codes.
  22. # Colors are always enabled on continuous integration.
  23. _colorize = bool(sys.stdout.isatty() or os.environ.get("CI"))
  24. def set_scu_folders(scu_folders):
  25. global _scu_folders
  26. _scu_folders = scu_folders
  27. class ANSI(Enum):
  28. """
  29. Enum class for adding ansi colorcodes directly into strings.
  30. Automatically converts values to strings representing their
  31. internal value, or an empty string in a non-colorized scope.
  32. """
  33. RESET = "\x1b[0m"
  34. BOLD = "\x1b[1m"
  35. ITALIC = "\x1b[3m"
  36. UNDERLINE = "\x1b[4m"
  37. STRIKETHROUGH = "\x1b[9m"
  38. REGULAR = "\x1b[22;23;24;29m"
  39. BLACK = "\x1b[30m"
  40. RED = "\x1b[31m"
  41. GREEN = "\x1b[32m"
  42. YELLOW = "\x1b[33m"
  43. BLUE = "\x1b[34m"
  44. MAGENTA = "\x1b[35m"
  45. CYAN = "\x1b[36m"
  46. WHITE = "\x1b[37m"
  47. PURPLE = "\x1b[38;5;93m"
  48. PINK = "\x1b[38;5;206m"
  49. ORANGE = "\x1b[38;5;214m"
  50. GRAY = "\x1b[38;5;244m"
  51. def __str__(self) -> str:
  52. global _colorize
  53. return str(self.value) if _colorize else ""
  54. def print_warning(*values: object) -> None:
  55. """Prints a warning message with formatting."""
  56. print(f"{ANSI.YELLOW}{ANSI.BOLD}WARNING:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr)
  57. def print_error(*values: object) -> None:
  58. """Prints an error message with formatting."""
  59. print(f"{ANSI.RED}{ANSI.BOLD}ERROR:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr)
  60. def add_source_files_orig(self, sources, files, allow_gen=False):
  61. # Convert string to list of absolute paths (including expanding wildcard)
  62. if isinstance(files, str):
  63. # Exclude .gen.cpp files from globbing, to avoid including obsolete ones.
  64. # They should instead be added manually.
  65. skip_gen_cpp = "*" in files
  66. files = self.Glob(files)
  67. if skip_gen_cpp and not allow_gen:
  68. files = [f for f in files if not str(f).endswith(".gen.cpp")]
  69. # Add each path as compiled Object following environment (self) configuration
  70. for path in files:
  71. obj = self.Object(path)
  72. if obj in sources:
  73. print_warning('Object "{}" already included in environment sources.'.format(obj))
  74. continue
  75. sources.append(obj)
  76. def add_source_files_scu(self, sources, files, allow_gen=False):
  77. if self["scu_build"] and isinstance(files, str):
  78. if "*." not in files:
  79. return False
  80. # If the files are in a subdirectory, we want to create the scu gen
  81. # files inside this subdirectory.
  82. subdir = os.path.dirname(files)
  83. subdir = subdir if subdir == "" else subdir + "/"
  84. section_name = self.Dir(subdir).tpath
  85. # if the section name is in the hash table?
  86. # i.e. is it part of the SCU build?
  87. global _scu_folders
  88. if section_name not in (_scu_folders):
  89. return False
  90. # Add all the gen.cpp files in the SCU directory
  91. add_source_files_orig(self, sources, subdir + "scu/scu_*.gen.cpp", True)
  92. return True
  93. return False
  94. # Either builds the folder using the SCU system,
  95. # or reverts to regular build.
  96. def add_source_files(self, sources, files, allow_gen=False):
  97. if not add_source_files_scu(self, sources, files, allow_gen):
  98. # Wraps the original function when scu build is not active.
  99. add_source_files_orig(self, sources, files, allow_gen)
  100. return False
  101. return True
  102. def disable_warnings(self):
  103. # 'self' is the environment
  104. if self.msvc and not using_clang(self):
  105. # We have to remove existing warning level defines before appending /w,
  106. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  107. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  108. self["CFLAGS"] = [x for x in self["CFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  109. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  110. self.AppendUnique(CCFLAGS=["/w"])
  111. else:
  112. self.AppendUnique(CCFLAGS=["-w"])
  113. def force_optimization_on_debug(self):
  114. # 'self' is the environment
  115. if self["target"] == "template_release":
  116. return
  117. if self.msvc:
  118. # We have to remove existing optimization level defines before appending /O2,
  119. # otherwise we get: "warning D9025 : overriding '/0d' with '/02'"
  120. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x.startswith("/O")]
  121. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x.startswith("/O")]
  122. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x.startswith("/O")]
  123. self.AppendUnique(CCFLAGS=["/O2"])
  124. else:
  125. self.AppendUnique(CCFLAGS=["-O3"])
  126. def add_module_version_string(self, s):
  127. self.module_version_string += "." + s
  128. def get_version_info(module_version_string="", silent=False):
  129. build_name = "custom_build"
  130. if os.getenv("BUILD_NAME") is not None:
  131. build_name = str(os.getenv("BUILD_NAME"))
  132. if not silent:
  133. print(f"Using custom build name: '{build_name}'.")
  134. import version
  135. version_info = {
  136. "short_name": str(version.short_name),
  137. "name": str(version.name),
  138. "major": int(version.major),
  139. "minor": int(version.minor),
  140. "patch": int(version.patch),
  141. "status": str(version.status),
  142. "build": str(build_name),
  143. "module_config": str(version.module_config) + module_version_string,
  144. "website": str(version.website),
  145. "docs_branch": str(version.docs),
  146. }
  147. # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
  148. # so this define provides a way to override it without having to modify the source.
  149. if os.getenv("GODOT_VERSION_STATUS") is not None:
  150. version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS"))
  151. if not silent:
  152. print(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.")
  153. # Parse Git hash if we're in a Git repo.
  154. githash = ""
  155. gitfolder = ".git"
  156. if os.path.isfile(".git"):
  157. with open(".git", "r", encoding="utf-8") as file:
  158. module_folder = file.readline().strip()
  159. if module_folder.startswith("gitdir: "):
  160. gitfolder = module_folder[8:]
  161. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  162. with open(os.path.join(gitfolder, "HEAD"), "r", encoding="utf8") as file:
  163. head = file.readline().strip()
  164. if head.startswith("ref: "):
  165. ref = head[5:]
  166. # If this directory is a Git worktree instead of a root clone.
  167. parts = gitfolder.split("/")
  168. if len(parts) > 2 and parts[-2] == "worktrees":
  169. gitfolder = "/".join(parts[0:-2])
  170. head = os.path.join(gitfolder, ref)
  171. packedrefs = os.path.join(gitfolder, "packed-refs")
  172. if os.path.isfile(head):
  173. with open(head, "r", encoding="utf-8") as file:
  174. githash = file.readline().strip()
  175. elif os.path.isfile(packedrefs):
  176. # Git may pack refs into a single file. This code searches .git/packed-refs file for the current ref's hash.
  177. # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-pack-refs.html
  178. for line in open(packedrefs, "r", encoding="utf-8").read().splitlines():
  179. if line.startswith("#"):
  180. continue
  181. (line_hash, line_ref) = line.split(" ")
  182. if ref == line_ref:
  183. githash = line_hash
  184. break
  185. else:
  186. githash = head
  187. version_info["git_hash"] = githash
  188. # Fallback to 0 as a timestamp (will be treated as "unknown" in the engine).
  189. version_info["git_timestamp"] = 0
  190. # Get the UNIX timestamp of the build commit.
  191. if os.path.exists(".git"):
  192. try:
  193. version_info["git_timestamp"] = subprocess.check_output(
  194. ["git", "log", "-1", "--pretty=format:%ct", "--no-show-signature", githash]
  195. ).decode("utf-8")
  196. except (subprocess.CalledProcessError, OSError):
  197. # `git` not found in PATH.
  198. pass
  199. return version_info
  200. def get_cmdline_bool(option, default):
  201. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  202. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  203. """
  204. from SCons.Script import ARGUMENTS
  205. from SCons.Variables.BoolVariable import _text2bool
  206. cmdline_val = ARGUMENTS.get(option)
  207. if cmdline_val is not None:
  208. return _text2bool(cmdline_val)
  209. else:
  210. return default
  211. def detect_modules(search_path, recursive=False):
  212. """Detects and collects a list of C++ modules at specified path
  213. `search_path` - a directory path containing modules. The path may point to
  214. a single module, which may have other nested modules. A module must have
  215. "register_types.h", "SCsub", "config.py" files created to be detected.
  216. `recursive` - if `True`, then all subdirectories are searched for modules as
  217. specified by the `search_path`, otherwise collects all modules under the
  218. `search_path` directory. If the `search_path` is a module, it is collected
  219. in all cases.
  220. Returns an `OrderedDict` with module names as keys, and directory paths as
  221. values. If a path is relative, then it is a built-in module. If a path is
  222. absolute, then it is a custom module collected outside of the engine source.
  223. """
  224. modules = OrderedDict()
  225. def add_module(path):
  226. module_name = os.path.basename(path)
  227. module_path = path.replace("\\", "/") # win32
  228. modules[module_name] = module_path
  229. def is_engine(path):
  230. # Prevent recursively detecting modules in self and other
  231. # Godot sources when using `custom_modules` build option.
  232. version_path = os.path.join(path, "version.py")
  233. if os.path.exists(version_path):
  234. with open(version_path, "r", encoding="utf-8") as f:
  235. if 'short_name = "godot"' in f.read():
  236. return True
  237. return False
  238. def get_files(path):
  239. files = glob.glob(os.path.join(path, "*"))
  240. # Sort so that `register_module_types` does not change that often,
  241. # and plugins are registered in alphabetic order as well.
  242. files.sort()
  243. return files
  244. if not recursive:
  245. if is_module(search_path):
  246. add_module(search_path)
  247. for path in get_files(search_path):
  248. if is_engine(path):
  249. continue
  250. if is_module(path):
  251. add_module(path)
  252. else:
  253. to_search = [search_path]
  254. while to_search:
  255. path = to_search.pop()
  256. if is_module(path):
  257. add_module(path)
  258. for child in get_files(path):
  259. if not os.path.isdir(child):
  260. continue
  261. if is_engine(child):
  262. continue
  263. to_search.insert(0, child)
  264. return modules
  265. def is_module(path):
  266. if not os.path.isdir(path):
  267. return False
  268. must_exist = ["register_types.h", "SCsub", "config.py"]
  269. for f in must_exist:
  270. if not os.path.exists(os.path.join(path, f)):
  271. return False
  272. return True
  273. def convert_custom_modules_path(path):
  274. if not path:
  275. return path
  276. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  277. err_msg = "Build option 'custom_modules' must %s"
  278. if not os.path.isdir(path):
  279. raise ValueError(err_msg % "point to an existing directory.")
  280. if path == os.path.realpath("modules"):
  281. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  282. return path
  283. def module_add_dependencies(self, module, dependencies, optional=False):
  284. """
  285. Adds dependencies for a given module.
  286. Meant to be used in module `can_build` methods.
  287. """
  288. if module not in self.module_dependencies:
  289. self.module_dependencies[module] = [[], []]
  290. if optional:
  291. self.module_dependencies[module][1].extend(dependencies)
  292. else:
  293. self.module_dependencies[module][0].extend(dependencies)
  294. def module_check_dependencies(self, module):
  295. """
  296. Checks if module dependencies are enabled for a given module,
  297. and prints a warning if they aren't.
  298. Meant to be used in module `can_build` methods.
  299. Returns a boolean (True if dependencies are satisfied).
  300. """
  301. missing_deps = set()
  302. required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
  303. for dep in required_deps:
  304. opt = "module_{}_enabled".format(dep)
  305. if opt not in self or not self[opt] or not module_check_dependencies(self, dep):
  306. missing_deps.add(dep)
  307. if missing_deps:
  308. if module not in self.disabled_modules:
  309. print_warning(
  310. "Disabling '{}' module as the following dependencies are not satisfied: {}".format(
  311. module, ", ".join(missing_deps)
  312. )
  313. )
  314. self.disabled_modules.add(module)
  315. return False
  316. else:
  317. return True
  318. def sort_module_list(env):
  319. deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()}
  320. frontier = list(env.module_list.keys())
  321. explored = []
  322. while len(frontier):
  323. cur = frontier.pop()
  324. deps_list = deps[cur] if cur in deps else []
  325. if len(deps_list) and any([d not in explored for d in deps_list]):
  326. # Will explore later, after its dependencies
  327. frontier.insert(0, cur)
  328. continue
  329. explored.append(cur)
  330. for k in explored:
  331. env.module_list.move_to_end(k)
  332. def use_windows_spawn_fix(self, platform=None):
  333. if os.name != "nt":
  334. return # not needed, only for windows
  335. def mySubProcess(cmdline, env):
  336. startupinfo = subprocess.STARTUPINFO()
  337. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  338. popen_args = {
  339. "stdin": subprocess.PIPE,
  340. "stdout": subprocess.PIPE,
  341. "stderr": subprocess.PIPE,
  342. "startupinfo": startupinfo,
  343. "shell": False,
  344. "env": env,
  345. }
  346. popen_args["text"] = True
  347. proc = subprocess.Popen(cmdline, **popen_args)
  348. _, err = proc.communicate()
  349. rv = proc.wait()
  350. if rv:
  351. print_error(err)
  352. elif len(err) > 0 and not err.isspace():
  353. print(err)
  354. return rv
  355. def mySpawn(sh, escape, cmd, args, env):
  356. # Used by TEMPFILE.
  357. if cmd == "del":
  358. os.remove(args[1])
  359. return 0
  360. newargs = " ".join(args[1:])
  361. cmdline = cmd + " " + newargs
  362. rv = 0
  363. env = {str(key): str(value) for key, value in iter(env.items())}
  364. rv = mySubProcess(cmdline, env)
  365. return rv
  366. self["SPAWN"] = mySpawn
  367. def no_verbose(env):
  368. colors = [ANSI.BLUE, ANSI.BOLD, ANSI.REGULAR, ANSI.RESET]
  369. # There is a space before "..." to ensure that source file names can be
  370. # Ctrl + clicked in the VS Code terminal.
  371. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  372. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  373. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(*colors)
  374. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(*colors)
  375. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(*colors)
  376. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(*colors)
  377. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(*colors)
  378. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(*colors)
  379. compiled_resource_message = "{}Creating Compiled Resource {}$TARGET{} ...{}".format(*colors)
  380. zip_archive_message = "{}Archiving {}$TARGET{} ...{}".format(*colors)
  381. generated_file_message = "{}Generating {}$TARGET{} ...{}".format(*colors)
  382. env["CXXCOMSTR"] = compile_source_message
  383. env["CCCOMSTR"] = compile_source_message
  384. env["SHCCCOMSTR"] = compile_shared_source_message
  385. env["SHCXXCOMSTR"] = compile_shared_source_message
  386. env["ARCOMSTR"] = link_library_message
  387. env["RANLIBCOMSTR"] = ranlib_library_message
  388. env["SHLINKCOMSTR"] = link_shared_library_message
  389. env["LINKCOMSTR"] = link_program_message
  390. env["JARCOMSTR"] = java_library_message
  391. env["JAVACCOMSTR"] = java_compile_source_message
  392. env["RCCOMSTR"] = compiled_resource_message
  393. env["ZIPCOMSTR"] = zip_archive_message
  394. env["GENCOMSTR"] = generated_file_message
  395. def detect_visual_c_compiler_version(tools_env):
  396. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  397. # (see the SCons documentation for more information on what it does)...
  398. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  399. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  400. # the proper vc version that will be called
  401. # 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.).
  402. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  403. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  404. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  405. # the following string values:
  406. # "" Compiler not detected
  407. # "amd64" Native 64 bit compiler
  408. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  409. # "x86" Native 32 bit compiler
  410. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  411. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  412. # and similar architectures/compilers
  413. # Set chosen compiler to "not detected"
  414. vc_chosen_compiler_index = -1
  415. vc_chosen_compiler_str = ""
  416. # VS 2017 and newer should set VCTOOLSINSTALLDIR
  417. if "VCTOOLSINSTALLDIR" in tools_env:
  418. # Newer versions have a different path available
  419. vc_amd64_compiler_detection_index = (
  420. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  421. )
  422. if vc_amd64_compiler_detection_index > -1:
  423. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  424. vc_chosen_compiler_str = "amd64"
  425. vc_amd64_x86_compiler_detection_index = (
  426. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  427. )
  428. if vc_amd64_x86_compiler_detection_index > -1 and (
  429. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  430. ):
  431. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  432. vc_chosen_compiler_str = "amd64_x86"
  433. vc_x86_compiler_detection_index = (
  434. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  435. )
  436. if vc_x86_compiler_detection_index > -1 and (
  437. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  438. ):
  439. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  440. vc_chosen_compiler_str = "x86"
  441. vc_x86_amd64_compiler_detection_index = (
  442. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  443. )
  444. if vc_x86_amd64_compiler_detection_index > -1 and (
  445. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  446. ):
  447. vc_chosen_compiler_str = "x86_amd64"
  448. return vc_chosen_compiler_str
  449. def find_visual_c_batch_file(env):
  450. # TODO: We should investigate if we can avoid relying on SCons internals here.
  451. from SCons.Tool.MSCommon.vc import find_batch_file, find_vc_pdir, get_default_version, get_host_target
  452. msvc_version = get_default_version(env)
  453. # Syntax changed in SCons 4.4.0.
  454. if env.scons_version >= (4, 4, 0):
  455. (host_platform, target_platform, _) = get_host_target(env, msvc_version)
  456. else:
  457. (host_platform, target_platform, _) = get_host_target(env)
  458. if env.scons_version < (4, 6, 0):
  459. return find_batch_file(env, msvc_version, host_platform, target_platform)[0]
  460. # SCons 4.6.0+ removed passing env, so we need to get the product_dir ourselves first,
  461. # then pass that as the last param instead of env as the first param as before.
  462. # Param names need to be explicit, as they were shuffled around in SCons 4.8.0.
  463. product_dir = find_vc_pdir(msvc_version=msvc_version, env=env)
  464. return find_batch_file(msvc_version, host_platform, target_platform, product_dir)[0]
  465. def generate_cpp_hint_file(filename):
  466. if os.path.isfile(filename):
  467. # Don't overwrite an existing hint file since the user may have customized it.
  468. pass
  469. else:
  470. try:
  471. with open(filename, "w", encoding="utf-8", newline="\n") as fd:
  472. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  473. for name in ["GDVIRTUAL", "EXBIND", "MODBIND"]:
  474. for count in range(13):
  475. for suffix in ["", "R", "C", "RC"]:
  476. fd.write(f"#define {name}{count}{suffix}(")
  477. if "R" in suffix:
  478. fd.write("m_ret, ")
  479. fd.write("m_name")
  480. for idx in range(1, count + 1):
  481. fd.write(f", type{idx}")
  482. fd.write(")\n")
  483. except OSError:
  484. print_warning("Could not write cpp.hint file.")
  485. def glob_recursive(pattern, node="."):
  486. from SCons import Node
  487. from SCons.Script import Glob
  488. results = []
  489. for f in Glob(str(node) + "/*", source=True):
  490. if type(f) is Node.FS.Dir:
  491. results += glob_recursive(pattern, f)
  492. results += Glob(str(node) + "/" + pattern, source=True)
  493. return results
  494. def precious_program(env, program, sources, **args):
  495. program = env.ProgramOriginal(program, sources, **args)
  496. env.Precious(program)
  497. return program
  498. def add_shared_library(env, name, sources, **args):
  499. library = env.SharedLibrary(name, sources, **args)
  500. env.NoCache(library)
  501. return library
  502. def add_library(env, name, sources, **args):
  503. library = env.Library(name, sources, **args)
  504. env.NoCache(library)
  505. return library
  506. def add_program(env, name, sources, **args):
  507. program = env.Program(name, sources, **args)
  508. env.NoCache(program)
  509. return program
  510. def CommandNoCache(env, target, sources, command, **args):
  511. result = env.Command(target, sources, command, **args)
  512. env.NoCache(result)
  513. return result
  514. def Run(env, function):
  515. from SCons.Script import Action
  516. return Action(function, "$GENCOMSTR")
  517. def detect_darwin_sdk_path(platform, env):
  518. sdk_name = ""
  519. if platform == "macos":
  520. sdk_name = "macosx"
  521. var_name = "MACOS_SDK_PATH"
  522. elif platform == "ios":
  523. sdk_name = "iphoneos"
  524. var_name = "IOS_SDK_PATH"
  525. elif platform == "iossimulator":
  526. sdk_name = "iphonesimulator"
  527. var_name = "IOS_SDK_PATH"
  528. else:
  529. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  530. if not env[var_name]:
  531. try:
  532. sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8")
  533. if sdk_path:
  534. env[var_name] = sdk_path
  535. except (subprocess.CalledProcessError, OSError):
  536. print_error("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  537. raise
  538. def is_apple_clang(env):
  539. if env["platform"] not in ["macos", "ios"]:
  540. return False
  541. if not using_clang(env):
  542. return False
  543. try:
  544. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  545. except (subprocess.CalledProcessError, OSError):
  546. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  547. return False
  548. return version.startswith("Apple")
  549. def get_compiler_version(env):
  550. """
  551. Returns a dictionary with various version information:
  552. - major, minor, patch: Version following semantic versioning system
  553. - metadata1, metadata2: Extra information
  554. - date: Date of the build
  555. """
  556. ret = {
  557. "major": -1,
  558. "minor": -1,
  559. "patch": -1,
  560. "metadata1": "",
  561. "metadata2": "",
  562. "date": "",
  563. "apple_major": -1,
  564. "apple_minor": -1,
  565. "apple_patch1": -1,
  566. "apple_patch2": -1,
  567. "apple_patch3": -1,
  568. }
  569. if env.msvc and not using_clang(env):
  570. try:
  571. # FIXME: `-latest` works for most cases, but there are edge-cases where this would
  572. # benefit from a more nuanced search.
  573. # https://github.com/godotengine/godot/pull/91069#issuecomment-2358956731
  574. # https://github.com/godotengine/godot/pull/91069#issuecomment-2380836341
  575. args = [
  576. env["VSWHERE"],
  577. "-latest",
  578. "-prerelease",
  579. "-products",
  580. "*",
  581. "-requires",
  582. "Microsoft.Component.MSBuild",
  583. "-utf8",
  584. ]
  585. version = subprocess.check_output(args, encoding="utf-8").strip()
  586. for line in version.splitlines():
  587. split = line.split(":", 1)
  588. if split[0] == "catalog_productDisplayVersion":
  589. sem_ver = split[1].split(".")
  590. ret["major"] = int(sem_ver[0])
  591. ret["minor"] = int(sem_ver[1])
  592. ret["patch"] = int(sem_ver[2].split()[0])
  593. # Could potentially add section for determining preview version, but
  594. # that can wait until metadata is actually used for something.
  595. if split[0] == "catalog_buildVersion":
  596. ret["metadata1"] = split[1]
  597. except (subprocess.CalledProcessError, OSError):
  598. print_warning("Couldn't find vswhere to determine compiler version.")
  599. return ret
  600. # Not using -dumpversion as some GCC distros only return major, and
  601. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  602. try:
  603. version = subprocess.check_output(
  604. [env.subst(env["CXX"]), "--version"], shell=(os.name == "nt"), encoding="utf-8"
  605. ).strip()
  606. except (subprocess.CalledProcessError, OSError):
  607. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  608. return ret
  609. match = re.search(
  610. r"(?:(?<=version )|(?<=\) )|(?<=^))"
  611. r"(?P<major>\d+)"
  612. r"(?:\.(?P<minor>\d*))?"
  613. r"(?:\.(?P<patch>\d*))?"
  614. r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  615. r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  616. r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  617. version,
  618. )
  619. if match is not None:
  620. for key, value in match.groupdict().items():
  621. if value is not None:
  622. ret[key] = value
  623. match_apple = re.search(
  624. r"(?:(?<=clang-)|(?<=\) )|(?<=^))"
  625. r"(?P<apple_major>\d+)"
  626. r"(?:\.(?P<apple_minor>\d*))?"
  627. r"(?:\.(?P<apple_patch1>\d*))?"
  628. r"(?:\.(?P<apple_patch2>\d*))?"
  629. r"(?:\.(?P<apple_patch3>\d*))?",
  630. version,
  631. )
  632. if match_apple is not None:
  633. for key, value in match_apple.groupdict().items():
  634. if value is not None:
  635. ret[key] = value
  636. # Transform semantic versioning to integers
  637. for key in [
  638. "major",
  639. "minor",
  640. "patch",
  641. "apple_major",
  642. "apple_minor",
  643. "apple_patch1",
  644. "apple_patch2",
  645. "apple_patch3",
  646. ]:
  647. ret[key] = int(ret[key] or -1)
  648. return ret
  649. def using_gcc(env):
  650. return "gcc" in os.path.basename(env["CC"])
  651. def using_clang(env):
  652. return "clang" in os.path.basename(env["CC"])
  653. def using_emcc(env):
  654. return "emcc" in os.path.basename(env["CC"])
  655. def show_progress(env):
  656. # Progress reporting is not available in non-TTY environments since it messes with the output
  657. # (for example, when writing to a file). Ninja has its own progress/tracking tool that clashes
  658. # with ours.
  659. if not env["progress"] or not sys.stdout.isatty() or env["ninja"]:
  660. return
  661. NODE_COUNT_FILENAME = f"{base_folder_path}.scons_node_count"
  662. class ShowProgress:
  663. def __init__(self):
  664. self.count = 0
  665. self.max = 0
  666. try:
  667. with open(NODE_COUNT_FILENAME, "r", encoding="utf-8") as f:
  668. self.max = int(f.readline())
  669. except OSError:
  670. pass
  671. if self.max == 0:
  672. print("NOTE: Performing initial build, progress percentage unavailable!")
  673. def __call__(self, node, *args, **kw):
  674. self.count += 1
  675. if self.max != 0:
  676. percent = int(min(self.count * 100 / self.max, 100))
  677. sys.stdout.write(f"\r[{percent:3d}%] ")
  678. sys.stdout.flush()
  679. from SCons.Script import Progress
  680. progressor = ShowProgress()
  681. Progress(progressor)
  682. def progress_finish(target, source, env):
  683. try:
  684. with open(NODE_COUNT_FILENAME, "w", encoding="utf-8", newline="\n") as f:
  685. f.write(f"{progressor.count}\n")
  686. except OSError:
  687. pass
  688. env.AlwaysBuild(
  689. env.CommandNoCache(
  690. "progress_finish", [], env.Action(progress_finish, "Building node count database .scons_node_count")
  691. )
  692. )
  693. def convert_size(size_bytes: int) -> str:
  694. if size_bytes == 0:
  695. return "0 bytes"
  696. SIZE_NAMES = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
  697. index = math.floor(math.log(size_bytes, 1024))
  698. power = math.pow(1024, index)
  699. size = round(size_bytes / power, 2)
  700. return f"{size} {SIZE_NAMES[index]}"
  701. def get_size(start_path: str = ".") -> int:
  702. total_size = 0
  703. for dirpath, _, filenames in os.walk(start_path):
  704. for file in filenames:
  705. path = os.path.join(dirpath, file)
  706. total_size += os.path.getsize(path)
  707. return total_size
  708. def clean_cache(cache_path: str, cache_limit: int, verbose: bool):
  709. files = glob.glob(os.path.join(cache_path, "*", "*"))
  710. if not files:
  711. return
  712. # Remove all text files, store binary files in list of (filename, size, atime).
  713. purge = []
  714. texts = []
  715. stats = []
  716. for file in files:
  717. try:
  718. # Save file stats to rewrite after modifying.
  719. tmp_stat = os.stat(file)
  720. # Failing a utf-8 decode is the easiest way to determine if a file is binary.
  721. try:
  722. with open(file, encoding="utf-8") as out:
  723. out.read(1024)
  724. except UnicodeDecodeError:
  725. stats.append((file, *tmp_stat[6:8]))
  726. # Restore file stats after reading.
  727. os.utime(file, (tmp_stat[7], tmp_stat[8]))
  728. else:
  729. texts.append(file)
  730. except OSError:
  731. print_error(f'Failed to access cache file "{file}"; skipping.')
  732. if texts:
  733. count = len(texts)
  734. for file in texts:
  735. try:
  736. os.remove(file)
  737. except OSError:
  738. print_error(f'Failed to remove cache file "{file}"; skipping.')
  739. count -= 1
  740. if verbose:
  741. print("Purging %d text %s from cache..." % (count, "files" if count > 1 else "file"))
  742. if cache_limit:
  743. # Sort by most recent access (most sensible to keep) first. Search for the first entry where
  744. # the cache limit is reached.
  745. stats.sort(key=lambda x: x[2], reverse=True)
  746. sum = 0
  747. for index, stat in enumerate(stats):
  748. sum += stat[1]
  749. if sum > cache_limit:
  750. purge.extend([x[0] for x in stats[index:]])
  751. break
  752. if purge:
  753. count = len(purge)
  754. for file in purge:
  755. try:
  756. os.remove(file)
  757. except OSError:
  758. print_error(f'Failed to remove cache file "{file}"; skipping.')
  759. count -= 1
  760. if verbose:
  761. print("Purging %d %s from cache..." % (count, "files" if count > 1 else "file"))
  762. def prepare_cache(env) -> None:
  763. if env.GetOption("clean"):
  764. return
  765. cache_path = ""
  766. if env["cache_path"]:
  767. cache_path = cast(str, env["cache_path"])
  768. elif os.environ.get("SCONS_CACHE"):
  769. print_warning("Environment variable `SCONS_CACHE` is deprecated; use `cache_path` argument instead.")
  770. cache_path = cast(str, os.environ.get("SCONS_CACHE"))
  771. if not cache_path:
  772. return
  773. env.CacheDir(cache_path)
  774. print(f'SCons cache enabled... (path: "{cache_path}")')
  775. if env["cache_limit"]:
  776. cache_limit = float(env["cache_limit"])
  777. elif os.environ.get("SCONS_CACHE_LIMIT"):
  778. print_warning("Environment variable `SCONS_CACHE_LIMIT` is deprecated; use `cache_limit` argument instead.")
  779. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", "0")) / 1024 # Old method used MiB, convert to GiB
  780. # Convert GiB to bytes; treat negative numbers as 0 (unlimited).
  781. cache_limit = max(0, int(cache_limit * 1024 * 1024 * 1024))
  782. if env["verbose"]:
  783. print(
  784. "Current cache limit is {} (used: {})".format(
  785. convert_size(cache_limit) if cache_limit else "∞",
  786. convert_size(get_size(cache_path)),
  787. )
  788. )
  789. atexit.register(clean_cache, cache_path, cache_limit, env["verbose"])
  790. def dump(env):
  791. # Dumps latest build information for debugging purposes and external tools.
  792. from json import dump
  793. def non_serializable(obj):
  794. return "<<non-serializable: %s>>" % (type(obj).__qualname__)
  795. with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as f:
  796. dump(env.Dictionary(), f, indent=4, default=non_serializable)
  797. # Custom Visual Studio project generation logic that supports any platform that has a msvs.py
  798. # script, so Visual Studio can be used to run scons for any platform, with the right defines per target.
  799. # Invoked with scons vsproj=yes
  800. #
  801. # Only platforms that opt in to vs proj generation by having a msvs.py file in the platform folder are included.
  802. # Platforms with a msvs.py file will be added to the solution, but only the current active platform+target+arch
  803. # will have a build configuration generated, because we only know what the right defines/includes/flags/etc are
  804. # on the active build target.
  805. #
  806. # Platforms that don't support an editor target will have a dummy editor target that won't do anything on build,
  807. # but will have the files and configuration for the windows editor target.
  808. #
  809. # To generate build configuration files for all platforms+targets+arch combinations, users can call
  810. # scons vsproj=yes
  811. # for each combination of platform+target+arch. This will generate the relevant vs project files but
  812. # skip the build process. This lets project files be quickly generated even if there are build errors.
  813. #
  814. # To generate AND build from the command line:
  815. # scons vsproj=yes vsproj_gen_only=no
  816. def generate_vs_project(env, original_args, project_name="godot"):
  817. # Augmented glob_recursive that also fills the dirs argument with traversed directories that have content.
  818. def glob_recursive_2(pattern, dirs, node="."):
  819. from SCons import Node
  820. from SCons.Script import Glob
  821. results = []
  822. for f in Glob(str(node) + "/*", source=True):
  823. if type(f) is Node.FS.Dir:
  824. results += glob_recursive_2(pattern, dirs, f)
  825. r = Glob(str(node) + "/" + pattern, source=True)
  826. if len(r) > 0 and str(node) not in dirs:
  827. d = ""
  828. for part in str(node).split("\\"):
  829. d += part
  830. if d not in dirs:
  831. dirs.append(d)
  832. d += "\\"
  833. results += r
  834. return results
  835. def get_bool(args, option, default):
  836. from SCons.Variables.BoolVariable import _text2bool
  837. val = args.get(option, default)
  838. if val is not None:
  839. try:
  840. return _text2bool(val)
  841. except (ValueError, AttributeError):
  842. return default
  843. else:
  844. return default
  845. def format_key_value(v):
  846. if type(v) in [tuple, list]:
  847. return v[0] if len(v) == 1 else f"{v[0]}={v[1]}"
  848. return v
  849. def get_dependencies(file, env, exts, headers, sources, others):
  850. for child in file.children():
  851. if isinstance(child, str):
  852. child = env.File(x)
  853. fname = ""
  854. try:
  855. fname = child.path
  856. except AttributeError:
  857. # It's not a file.
  858. pass
  859. if fname:
  860. parts = os.path.splitext(fname)
  861. if len(parts) > 1:
  862. ext = parts[1].lower()
  863. if ext in exts["sources"]:
  864. sources += [fname]
  865. elif ext in exts["headers"]:
  866. headers += [fname]
  867. elif ext in exts["others"]:
  868. others += [fname]
  869. get_dependencies(child, env, exts, headers, sources, others)
  870. filtered_args = original_args.copy()
  871. # Ignore the "vsproj" option to not regenerate the VS project on every build
  872. filtered_args.pop("vsproj", None)
  873. # This flag allows users to regenerate the proj files but skip the building process.
  874. # This lets projects be regenerated even if there are build errors.
  875. filtered_args.pop("vsproj_gen_only", None)
  876. # This flag allows users to regenerate only the props file without touching the sln or vcxproj files.
  877. # This preserves any customizations users have done to the solution, while still updating the file list
  878. # and build commands.
  879. filtered_args.pop("vsproj_props_only", None)
  880. # The "progress" option is ignored as the current compilation progress indication doesn't work in VS
  881. filtered_args.pop("progress", None)
  882. # We add these three manually because they might not be explicitly passed in, and it's important to always set them.
  883. filtered_args.pop("platform", None)
  884. filtered_args.pop("target", None)
  885. filtered_args.pop("arch", None)
  886. platform = env["platform"]
  887. target = env["target"]
  888. arch = env["arch"]
  889. vs_configuration = {}
  890. common_build_prefix = []
  891. confs = []
  892. for x in sorted(glob.glob("platform/*")):
  893. # Only platforms that opt in to vs proj generation are included.
  894. if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"):
  895. continue
  896. tmppath = "./" + x
  897. sys.path.insert(0, tmppath)
  898. import msvs
  899. vs_plats = []
  900. vs_confs = []
  901. try:
  902. platform_name = x[9:]
  903. vs_plats = msvs.get_platforms()
  904. vs_confs = msvs.get_configurations()
  905. val = []
  906. for plat in vs_plats:
  907. val += [{"platform": plat[0], "architecture": plat[1]}]
  908. vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val}
  909. confs += [vsconf]
  910. # Save additional information about the configuration for the actively selected platform,
  911. # so we can generate the platform-specific props file with all the build commands/defines/etc
  912. if platform == platform_name:
  913. common_build_prefix = msvs.get_build_prefix(env)
  914. vs_configuration = vsconf
  915. except Exception:
  916. pass
  917. sys.path.remove(tmppath)
  918. sys.modules.pop("msvs")
  919. extensions = {}
  920. extensions["headers"] = [".h", ".hh", ".hpp", ".hxx", ".inc"]
  921. extensions["sources"] = [".c", ".cc", ".cpp", ".cxx", ".m", ".mm", ".java"]
  922. extensions["others"] = [".natvis", ".glsl", ".rc"]
  923. headers = []
  924. headers_dirs = []
  925. for ext in extensions["headers"]:
  926. for file in glob_recursive_2("*" + ext, headers_dirs):
  927. headers.append(str(file).replace("/", "\\"))
  928. sources = []
  929. sources_dirs = []
  930. for ext in extensions["sources"]:
  931. for file in glob_recursive_2("*" + ext, sources_dirs):
  932. sources.append(str(file).replace("/", "\\"))
  933. others = []
  934. others_dirs = []
  935. for ext in extensions["others"]:
  936. for file in glob_recursive_2("*" + ext, others_dirs):
  937. others.append(str(file).replace("/", "\\"))
  938. skip_filters = False
  939. import hashlib
  940. import json
  941. md5 = hashlib.md5(
  942. json.dumps(sorted(headers + headers_dirs + sources + sources_dirs + others + others_dirs)).encode("utf-8")
  943. ).hexdigest()
  944. if os.path.exists(f"{project_name}.vcxproj.filters"):
  945. with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file:
  946. existing_filters = file.read()
  947. match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters)
  948. if match is not None and md5 == match.group(1):
  949. skip_filters = True
  950. import uuid
  951. # Don't regenerate the filters file if nothing has changed, so we keep the existing UUIDs.
  952. if not skip_filters:
  953. print(f"Regenerating {project_name}.vcxproj.filters")
  954. with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file:
  955. filters_template = file.read()
  956. for i in range(1, 10):
  957. filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4()))
  958. filters = ""
  959. for d in headers_dirs:
  960. filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  961. for d in sources_dirs:
  962. filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  963. for d in others_dirs:
  964. filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  965. filters_template = filters_template.replace("%%FILTERS%%", filters)
  966. filters = ""
  967. for file in headers:
  968. filters += (
  969. f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n'
  970. )
  971. filters_template = filters_template.replace("%%INCLUDES%%", filters)
  972. filters = ""
  973. for file in sources:
  974. filters += (
  975. f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n'
  976. )
  977. filters_template = filters_template.replace("%%COMPILES%%", filters)
  978. filters = ""
  979. for file in others:
  980. filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n'
  981. filters_template = filters_template.replace("%%OTHERS%%", filters)
  982. filters_template = filters_template.replace("%%HASH%%", md5)
  983. with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f:
  984. f.write(filters_template)
  985. headers_active = []
  986. sources_active = []
  987. others_active = []
  988. get_dependencies(
  989. env.File(f"#bin/godot{env['PROGSUFFIX']}"), env, extensions, headers_active, sources_active, others_active
  990. )
  991. all_items = []
  992. properties = []
  993. activeItems = []
  994. extraItems = []
  995. set_headers = set(headers_active)
  996. set_sources = set(sources_active)
  997. set_others = set(others_active)
  998. for file in headers:
  999. base_path = os.path.dirname(file).replace("\\", "_")
  1000. all_items.append(f'<ClInclude Include="{file}">')
  1001. all_items.append(
  1002. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1003. )
  1004. all_items.append("</ClInclude>")
  1005. if file in set_headers:
  1006. activeItems.append(file)
  1007. for file in sources:
  1008. base_path = os.path.dirname(file).replace("\\", "_")
  1009. all_items.append(f'<ClCompile Include="{file}">')
  1010. all_items.append(
  1011. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1012. )
  1013. all_items.append("</ClCompile>")
  1014. if file in set_sources:
  1015. activeItems.append(file)
  1016. for file in others:
  1017. base_path = os.path.dirname(file).replace("\\", "_")
  1018. all_items.append(f'<None Include="{file}">')
  1019. all_items.append(
  1020. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1021. )
  1022. all_items.append("</None>")
  1023. if file in set_others:
  1024. activeItems.append(file)
  1025. if vs_configuration:
  1026. vsconf = ""
  1027. for a in vs_configuration["arches"]:
  1028. if arch == a["architecture"]:
  1029. vsconf = f'{target}|{a["platform"]}'
  1030. break
  1031. condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'"
  1032. itemlist = {}
  1033. for item in activeItems:
  1034. key = os.path.dirname(item).replace("\\", "_")
  1035. if key not in itemlist:
  1036. itemlist[key] = [item]
  1037. else:
  1038. itemlist[key] += [item]
  1039. for x in itemlist.keys():
  1040. properties.append(
  1041. "<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x)
  1042. )
  1043. output = f'bin\\godot{env["PROGSUFFIX"]}'
  1044. with open("misc/msvs/props.template", "r", encoding="utf-8") as file:
  1045. props_template = file.read()
  1046. props_template = props_template.replace("%%VSCONF%%", vsconf)
  1047. props_template = props_template.replace("%%CONDITION%%", condition)
  1048. props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1049. props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems))
  1050. props_template = props_template.replace("%%OUTPUT%%", output)
  1051. proplist = [format_key_value(v) for v in list(env["CPPDEFINES"])]
  1052. proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])]
  1053. props_template = props_template.replace("%%DEFINES%%", ";".join(proplist))
  1054. proplist = [str(j) for j in env["CPPPATH"]]
  1055. proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])]
  1056. props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist))
  1057. proplist = env["CCFLAGS"]
  1058. proplist += [x for x in env["CXXFLAGS"] if not x.startswith("$")]
  1059. proplist += [str(j) for j in env.get("VSHINT_OPTIONS", [])]
  1060. props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist))
  1061. # Windows allows us to have spaces in paths, so we need
  1062. # to double quote off the directory. However, the path ends
  1063. # in a backslash, so we need to remove this, lest it escape the
  1064. # last double quote off, confusing MSBuild
  1065. common_build_postfix = [
  1066. "--directory=&quot;$(ProjectDir.TrimEnd(&apos;\\&apos;))&quot;",
  1067. "progress=no",
  1068. f"platform={platform}",
  1069. f"target={target}",
  1070. f"arch={arch}",
  1071. ]
  1072. for arg, value in filtered_args.items():
  1073. common_build_postfix.append(f"{arg}={value}")
  1074. cmd_rebuild = [
  1075. "vsproj=yes",
  1076. "vsproj_props_only=yes",
  1077. "vsproj_gen_only=no",
  1078. f"vsproj_name={project_name}",
  1079. ] + common_build_postfix
  1080. cmd_clean = [
  1081. "--clean",
  1082. ] + common_build_postfix
  1083. commands = "scons"
  1084. if len(common_build_prefix) == 0:
  1085. commands = "echo Starting SCons &amp;&amp; cmd /V /C " + commands
  1086. else:
  1087. common_build_prefix[0] = "echo Starting SCons &amp;&amp; cmd /V /C " + common_build_prefix[0]
  1088. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  1089. props_template = props_template.replace("%%BUILD%%", cmd)
  1090. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)])
  1091. props_template = props_template.replace("%%REBUILD%%", cmd)
  1092. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_clean)])
  1093. props_template = props_template.replace("%%CLEAN%%", cmd)
  1094. with open(
  1095. f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n"
  1096. ) as f:
  1097. f.write(props_template)
  1098. proj_uuid = str(uuid.uuid4())
  1099. sln_uuid = str(uuid.uuid4())
  1100. if os.path.exists(f"{project_name}.sln"):
  1101. for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines():
  1102. if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'):
  1103. proj_uuid = re.search(
  1104. r"\"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}\"$",
  1105. line,
  1106. ).group(1)
  1107. elif line.strip().startswith("SolutionGuid ="):
  1108. sln_uuid = re.search(
  1109. r"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}", line
  1110. ).group(1)
  1111. break
  1112. configurations = []
  1113. imports = []
  1114. properties = []
  1115. section1 = []
  1116. section2 = []
  1117. for conf in confs:
  1118. godot_platform = conf["platform"]
  1119. for p in conf["arches"]:
  1120. sln_plat = p["platform"]
  1121. proj_plat = sln_plat
  1122. godot_arch = p["architecture"]
  1123. # Redirect editor configurations for non-Windows platforms to the Windows one, so the solution has all the permutations
  1124. # and VS doesn't complain about missing project configurations.
  1125. # These configurations are disabled, so they show up but won't build.
  1126. if godot_platform != "windows":
  1127. section1 += [f"editor|{sln_plat} = editor|{proj_plat}"]
  1128. section2 += [
  1129. f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{proj_plat}",
  1130. ]
  1131. for t in conf["targets"]:
  1132. godot_target = t
  1133. # Windows x86 is a special little flower that requires a project platform == Win32 but a solution platform == x86.
  1134. if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32":
  1135. sln_plat = "x86"
  1136. configurations += [
  1137. f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">',
  1138. f" <Configuration>{godot_target}</Configuration>",
  1139. f" <Platform>{proj_plat}</Platform>",
  1140. "</ProjectConfiguration>",
  1141. ]
  1142. properties += [
  1143. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">",
  1144. f" <GodotConfiguration>{godot_target}</GodotConfiguration>",
  1145. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1146. "</PropertyGroup>",
  1147. ]
  1148. if godot_platform != "windows":
  1149. configurations += [
  1150. f'<ProjectConfiguration Include="editor|{proj_plat}">',
  1151. " <Configuration>editor</Configuration>",
  1152. f" <Platform>{proj_plat}</Platform>",
  1153. "</ProjectConfiguration>",
  1154. ]
  1155. properties += [
  1156. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">",
  1157. " <GodotConfiguration>editor</GodotConfiguration>",
  1158. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1159. "</PropertyGroup>",
  1160. ]
  1161. p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props"
  1162. imports += [
  1163. f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>'
  1164. ]
  1165. section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"]
  1166. section2 += [
  1167. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}",
  1168. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}",
  1169. ]
  1170. # Add an extra import for a local user props file at the end, so users can add more overrides.
  1171. imports += [
  1172. f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>'
  1173. ]
  1174. section1 = sorted(section1)
  1175. section2 = sorted(section2)
  1176. if not get_bool(original_args, "vsproj_props_only", False):
  1177. with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file:
  1178. proj_template = file.read()
  1179. proj_template = proj_template.replace("%%UUID%%", proj_uuid)
  1180. proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations))
  1181. proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports))
  1182. proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items))
  1183. proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1184. with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\r\n") as f:
  1185. f.write(proj_template)
  1186. if not get_bool(original_args, "vsproj_props_only", False):
  1187. with open("misc/msvs/sln.template", "r", encoding="utf-8") as file:
  1188. sln_template = file.read()
  1189. sln_template = sln_template.replace("%%NAME%%", project_name)
  1190. sln_template = sln_template.replace("%%UUID%%", proj_uuid)
  1191. sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid)
  1192. sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1))
  1193. sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2))
  1194. with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f:
  1195. f.write(sln_template)
  1196. if get_bool(original_args, "vsproj_gen_only", True):
  1197. sys.exit()
  1198. def generate_copyright_header(filename: str) -> str:
  1199. MARGIN = 70
  1200. TEMPLATE = """\
  1201. /**************************************************************************/
  1202. /* %s*/
  1203. /**************************************************************************/
  1204. /* This file is part of: */
  1205. /* GODOT ENGINE */
  1206. /* https://godotengine.org */
  1207. /**************************************************************************/
  1208. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  1209. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  1210. /* */
  1211. /* Permission is hereby granted, free of charge, to any person obtaining */
  1212. /* a copy of this software and associated documentation files (the */
  1213. /* "Software"), to deal in the Software without restriction, including */
  1214. /* without limitation the rights to use, copy, modify, merge, publish, */
  1215. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1216. /* permit persons to whom the Software is furnished to do so, subject to */
  1217. /* the following conditions: */
  1218. /* */
  1219. /* The above copyright notice and this permission notice shall be */
  1220. /* included in all copies or substantial portions of the Software. */
  1221. /* */
  1222. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1223. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1224. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  1225. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1226. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1227. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1228. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1229. /**************************************************************************/
  1230. """
  1231. filename = filename.split("/")[-1].ljust(MARGIN)
  1232. if len(filename) > MARGIN:
  1233. print(f'WARNING: Filename "{filename}" too large for copyright header.')
  1234. return TEMPLATE % filename
  1235. @contextlib.contextmanager
  1236. def generated_wrapper(
  1237. path, # FIXME: type with `Union[str, Node, List[Node]]` when pytest conflicts are resolved
  1238. guard: Optional[bool] = None,
  1239. prefix: str = "",
  1240. suffix: str = "",
  1241. ) -> Generator[TextIOWrapper, None, None]:
  1242. """
  1243. Wrapper class to automatically handle copyright headers and header guards
  1244. for generated scripts. Meant to be invoked via `with` statement similar to
  1245. creating a file.
  1246. - `path`: The path of the file to be created. Can be passed a raw string, an
  1247. isolated SCons target, or a full SCons target list. If a target list contains
  1248. multiple entries, produces a warning & only creates the first entry.
  1249. - `guard`: Optional bool to determine if a header guard should be added. If
  1250. unassigned, header guards are determined by the file extension.
  1251. - `prefix`: Custom prefix to prepend to a header guard. Produces a warning if
  1252. provided a value when `guard` evaluates to `False`.
  1253. - `suffix`: Custom suffix to append to a header guard. Produces a warning if
  1254. provided a value when `guard` evaluates to `False`.
  1255. """
  1256. # Handle unfiltered SCons target[s] passed as path.
  1257. if not isinstance(path, str):
  1258. if isinstance(path, list):
  1259. if len(path) > 1:
  1260. print_warning(
  1261. "Attempting to use generated wrapper with multiple targets; "
  1262. f"will only use first entry: {path[0]}"
  1263. )
  1264. path = path[0]
  1265. if not hasattr(path, "get_abspath"):
  1266. raise TypeError(f'Expected type "str", "Node" or "List[Node]"; was passed {type(path)}.')
  1267. path = path.get_abspath()
  1268. path = str(path).replace("\\", "/")
  1269. if guard is None:
  1270. guard = path.endswith((".h", ".hh", ".hpp", ".inc"))
  1271. if not guard and (prefix or suffix):
  1272. print_warning(f'Trying to assign header guard prefix/suffix while `guard` is disabled: "{path}".')
  1273. header_guard = ""
  1274. if guard:
  1275. if prefix:
  1276. prefix += "_"
  1277. if suffix:
  1278. suffix = f"_{suffix}"
  1279. split = path.split("/")[-1].split(".")
  1280. header_guard = (f"{prefix}{split[0]}{suffix}.{'.'.join(split[1:])}".upper()
  1281. .replace(".", "_").replace("-", "_").replace(" ", "_").replace("__", "_")) # fmt: skip
  1282. with open(path, "wt", encoding="utf-8", newline="\n") as file:
  1283. file.write(generate_copyright_header(path))
  1284. file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n")
  1285. if guard:
  1286. file.write(f"#ifndef {header_guard}\n")
  1287. file.write(f"#define {header_guard}\n\n")
  1288. with StringIO(newline="\n") as str_io:
  1289. yield str_io
  1290. file.write(str_io.getvalue().strip() or "/* NO CONTENT */")
  1291. if guard:
  1292. file.write(f"\n\n#endif // {header_guard}")
  1293. file.write("\n")
  1294. def to_raw_cstring(value: Union[str, List[str]]) -> str:
  1295. MAX_LITERAL = 16 * 1024
  1296. if isinstance(value, list):
  1297. value = "\n".join(value) + "\n"
  1298. split: List[bytes] = []
  1299. offset = 0
  1300. encoded = value.encode()
  1301. while offset <= len(encoded):
  1302. segment = encoded[offset : offset + MAX_LITERAL]
  1303. offset += MAX_LITERAL
  1304. if len(segment) == MAX_LITERAL:
  1305. # Try to segment raw strings at double newlines to keep readable.
  1306. pretty_break = segment.rfind(b"\n\n")
  1307. if pretty_break != -1:
  1308. segment = segment[: pretty_break + 1]
  1309. offset -= MAX_LITERAL - pretty_break - 1
  1310. # If none found, ensure we end with valid utf8.
  1311. # https://github.com/halloleo/unicut/blob/master/truncate.py
  1312. elif segment[-1] & 0b10000000:
  1313. last_11xxxxxx_index = [i for i in range(-1, -5, -1) if segment[i] & 0b11000000 == 0b11000000][0]
  1314. last_11xxxxxx = segment[last_11xxxxxx_index]
  1315. if not last_11xxxxxx & 0b00100000:
  1316. last_char_length = 2
  1317. elif not last_11xxxxxx & 0b0010000:
  1318. last_char_length = 3
  1319. elif not last_11xxxxxx & 0b0001000:
  1320. last_char_length = 4
  1321. if last_char_length > -last_11xxxxxx_index:
  1322. segment = segment[:last_11xxxxxx_index]
  1323. offset += last_11xxxxxx_index
  1324. split += [segment]
  1325. return " ".join(f'R"<!>({x.decode()})<!>"' for x in split)