methods.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  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. # Failing a utf-8 decode is the easiest way to determine if a file is binary.
  718. try:
  719. with open(file, encoding="utf-8") as out:
  720. out.read(1024)
  721. except UnicodeDecodeError:
  722. stats.append((file, *os.stat(file)[6:8]))
  723. except OSError:
  724. print_error(f'Failed to access cache file "{file}"; skipping.')
  725. else:
  726. texts.append(file)
  727. if texts:
  728. count = len(texts)
  729. for file in texts:
  730. try:
  731. os.remove(file)
  732. except OSError:
  733. print_error(f'Failed to remove cache file "{file}"; skipping.')
  734. count -= 1
  735. if verbose:
  736. print("Purging %d text %s from cache..." % (count, "files" if count > 1 else "file"))
  737. if cache_limit:
  738. # Sort by most recent access (most sensible to keep) first. Search for the first entry where
  739. # the cache limit is reached.
  740. stats.sort(key=lambda x: x[2], reverse=True)
  741. sum = 0
  742. for index, stat in enumerate(stats):
  743. sum += stat[1]
  744. if sum > cache_limit:
  745. purge.extend([x[0] for x in stats[index:]])
  746. break
  747. if purge:
  748. count = len(purge)
  749. for file in purge:
  750. try:
  751. os.remove(file)
  752. except OSError:
  753. print_error(f'Failed to remove cache file "{file}"; skipping.')
  754. count -= 1
  755. if verbose:
  756. print("Purging %d %s from cache..." % (count, "files" if count > 1 else "file"))
  757. def prepare_cache(env) -> None:
  758. if env.GetOption("clean"):
  759. return
  760. cache_path = ""
  761. if env["cache_path"]:
  762. cache_path = cast(str, env["cache_path"])
  763. elif os.environ.get("SCONS_CACHE"):
  764. print_warning("Environment variable `SCONS_CACHE` is deprecated; use `cache_path` argument instead.")
  765. cache_path = cast(str, os.environ.get("SCONS_CACHE"))
  766. if not cache_path:
  767. return
  768. env.CacheDir(cache_path)
  769. print(f'SCons cache enabled... (path: "{cache_path}")')
  770. if env["cache_limit"]:
  771. cache_limit = float(env["cache_limit"])
  772. elif os.environ.get("SCONS_CACHE_LIMIT"):
  773. print_warning("Environment variable `SCONS_CACHE_LIMIT` is deprecated; use `cache_limit` argument instead.")
  774. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", "0")) / 1024 # Old method used MiB, convert to GiB
  775. # Convert GiB to bytes; treat negative numbers as 0 (unlimited).
  776. cache_limit = max(0, int(cache_limit * 1024 * 1024 * 1024))
  777. if env["verbose"]:
  778. print(
  779. "Current cache limit is {} (used: {})".format(
  780. convert_size(cache_limit) if cache_limit else "∞",
  781. convert_size(get_size(cache_path)),
  782. )
  783. )
  784. atexit.register(clean_cache, cache_path, cache_limit, env["verbose"])
  785. def dump(env):
  786. # Dumps latest build information for debugging purposes and external tools.
  787. from json import dump
  788. def non_serializable(obj):
  789. return "<<non-serializable: %s>>" % (type(obj).__qualname__)
  790. with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as f:
  791. dump(env.Dictionary(), f, indent=4, default=non_serializable)
  792. # Custom Visual Studio project generation logic that supports any platform that has a msvs.py
  793. # script, so Visual Studio can be used to run scons for any platform, with the right defines per target.
  794. # Invoked with scons vsproj=yes
  795. #
  796. # Only platforms that opt in to vs proj generation by having a msvs.py file in the platform folder are included.
  797. # Platforms with a msvs.py file will be added to the solution, but only the current active platform+target+arch
  798. # will have a build configuration generated, because we only know what the right defines/includes/flags/etc are
  799. # on the active build target.
  800. #
  801. # Platforms that don't support an editor target will have a dummy editor target that won't do anything on build,
  802. # but will have the files and configuration for the windows editor target.
  803. #
  804. # To generate build configuration files for all platforms+targets+arch combinations, users can call
  805. # scons vsproj=yes
  806. # for each combination of platform+target+arch. This will generate the relevant vs project files but
  807. # skip the build process. This lets project files be quickly generated even if there are build errors.
  808. #
  809. # To generate AND build from the command line:
  810. # scons vsproj=yes vsproj_gen_only=no
  811. def generate_vs_project(env, original_args, project_name="godot"):
  812. # Augmented glob_recursive that also fills the dirs argument with traversed directories that have content.
  813. def glob_recursive_2(pattern, dirs, node="."):
  814. from SCons import Node
  815. from SCons.Script import Glob
  816. results = []
  817. for f in Glob(str(node) + "/*", source=True):
  818. if type(f) is Node.FS.Dir:
  819. results += glob_recursive_2(pattern, dirs, f)
  820. r = Glob(str(node) + "/" + pattern, source=True)
  821. if len(r) > 0 and str(node) not in dirs:
  822. d = ""
  823. for part in str(node).split("\\"):
  824. d += part
  825. if d not in dirs:
  826. dirs.append(d)
  827. d += "\\"
  828. results += r
  829. return results
  830. def get_bool(args, option, default):
  831. from SCons.Variables.BoolVariable import _text2bool
  832. val = args.get(option, default)
  833. if val is not None:
  834. try:
  835. return _text2bool(val)
  836. except (ValueError, AttributeError):
  837. return default
  838. else:
  839. return default
  840. def format_key_value(v):
  841. if type(v) in [tuple, list]:
  842. return v[0] if len(v) == 1 else f"{v[0]}={v[1]}"
  843. return v
  844. filtered_args = original_args.copy()
  845. # Ignore the "vsproj" option to not regenerate the VS project on every build
  846. filtered_args.pop("vsproj", None)
  847. # This flag allows users to regenerate the proj files but skip the building process.
  848. # This lets projects be regenerated even if there are build errors.
  849. filtered_args.pop("vsproj_gen_only", None)
  850. # This flag allows users to regenerate only the props file without touching the sln or vcxproj files.
  851. # This preserves any customizations users have done to the solution, while still updating the file list
  852. # and build commands.
  853. filtered_args.pop("vsproj_props_only", None)
  854. # The "progress" option is ignored as the current compilation progress indication doesn't work in VS
  855. filtered_args.pop("progress", None)
  856. # We add these three manually because they might not be explicitly passed in, and it's important to always set them.
  857. filtered_args.pop("platform", None)
  858. filtered_args.pop("target", None)
  859. filtered_args.pop("arch", None)
  860. platform = env["platform"]
  861. target = env["target"]
  862. arch = env["arch"]
  863. vs_configuration = {}
  864. common_build_prefix = []
  865. confs = []
  866. for x in sorted(glob.glob("platform/*")):
  867. # Only platforms that opt in to vs proj generation are included.
  868. if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"):
  869. continue
  870. tmppath = "./" + x
  871. sys.path.insert(0, tmppath)
  872. import msvs
  873. vs_plats = []
  874. vs_confs = []
  875. try:
  876. platform_name = x[9:]
  877. vs_plats = msvs.get_platforms()
  878. vs_confs = msvs.get_configurations()
  879. val = []
  880. for plat in vs_plats:
  881. val += [{"platform": plat[0], "architecture": plat[1]}]
  882. vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val}
  883. confs += [vsconf]
  884. # Save additional information about the configuration for the actively selected platform,
  885. # so we can generate the platform-specific props file with all the build commands/defines/etc
  886. if platform == platform_name:
  887. common_build_prefix = msvs.get_build_prefix(env)
  888. vs_configuration = vsconf
  889. except Exception:
  890. pass
  891. sys.path.remove(tmppath)
  892. sys.modules.pop("msvs")
  893. headers = []
  894. headers_dirs = []
  895. for file in glob_recursive_2("*.h", headers_dirs):
  896. headers.append(str(file).replace("/", "\\"))
  897. for file in glob_recursive_2("*.hpp", headers_dirs):
  898. headers.append(str(file).replace("/", "\\"))
  899. sources = []
  900. sources_dirs = []
  901. for file in glob_recursive_2("*.cpp", sources_dirs):
  902. sources.append(str(file).replace("/", "\\"))
  903. for file in glob_recursive_2("*.c", sources_dirs):
  904. sources.append(str(file).replace("/", "\\"))
  905. others = []
  906. others_dirs = []
  907. for file in glob_recursive_2("*.natvis", others_dirs):
  908. others.append(str(file).replace("/", "\\"))
  909. for file in glob_recursive_2("*.glsl", others_dirs):
  910. others.append(str(file).replace("/", "\\"))
  911. skip_filters = False
  912. import hashlib
  913. import json
  914. md5 = hashlib.md5(
  915. json.dumps(sorted(headers + headers_dirs + sources + sources_dirs + others + others_dirs)).encode("utf-8")
  916. ).hexdigest()
  917. if os.path.exists(f"{project_name}.vcxproj.filters"):
  918. with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file:
  919. existing_filters = file.read()
  920. match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters)
  921. if match is not None and md5 == match.group(1):
  922. skip_filters = True
  923. import uuid
  924. # Don't regenerate the filters file if nothing has changed, so we keep the existing UUIDs.
  925. if not skip_filters:
  926. print(f"Regenerating {project_name}.vcxproj.filters")
  927. with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file:
  928. filters_template = file.read()
  929. for i in range(1, 10):
  930. filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4()))
  931. filters = ""
  932. for d in headers_dirs:
  933. filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  934. for d in sources_dirs:
  935. filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  936. for d in others_dirs:
  937. filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  938. filters_template = filters_template.replace("%%FILTERS%%", filters)
  939. filters = ""
  940. for file in headers:
  941. filters += (
  942. f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n'
  943. )
  944. filters_template = filters_template.replace("%%INCLUDES%%", filters)
  945. filters = ""
  946. for file in sources:
  947. filters += (
  948. f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n'
  949. )
  950. filters_template = filters_template.replace("%%COMPILES%%", filters)
  951. filters = ""
  952. for file in others:
  953. filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n'
  954. filters_template = filters_template.replace("%%OTHERS%%", filters)
  955. filters_template = filters_template.replace("%%HASH%%", md5)
  956. with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f:
  957. f.write(filters_template)
  958. envsources = []
  959. envsources += env.core_sources
  960. envsources += env.drivers_sources
  961. envsources += env.main_sources
  962. envsources += env.modules_sources
  963. envsources += env.scene_sources
  964. envsources += env.servers_sources
  965. if env.editor_build:
  966. envsources += env.editor_sources
  967. envsources += env.platform_sources
  968. headers_active = []
  969. sources_active = []
  970. others_active = []
  971. for x in envsources:
  972. fname = ""
  973. if isinstance(x, str):
  974. fname = env.File(x).path
  975. else:
  976. # Some object files might get added directly as a File object and not a list.
  977. try:
  978. fname = env.File(x)[0].path
  979. except Exception:
  980. fname = x.path
  981. pass
  982. if fname:
  983. fname = fname.replace("\\\\", "/")
  984. parts = os.path.splitext(fname)
  985. basename = parts[0]
  986. ext = parts[1]
  987. idx = fname.find(env["OBJSUFFIX"])
  988. if ext in [".h", ".hpp"]:
  989. headers_active += [fname]
  990. elif ext in [".c", ".cpp"]:
  991. sources_active += [fname]
  992. elif idx > 0:
  993. basename = fname[:idx]
  994. if os.path.isfile(basename + ".h"):
  995. headers_active += [basename + ".h"]
  996. elif os.path.isfile(basename + ".hpp"):
  997. headers_active += [basename + ".hpp"]
  998. elif basename.endswith(".gen") and os.path.isfile(basename[:-4] + ".h"):
  999. headers_active += [basename[:-4] + ".h"]
  1000. if os.path.isfile(basename + ".c"):
  1001. sources_active += [basename + ".c"]
  1002. elif os.path.isfile(basename + ".cpp"):
  1003. sources_active += [basename + ".cpp"]
  1004. else:
  1005. fname = os.path.relpath(os.path.abspath(fname), env.Dir("").abspath)
  1006. others_active += [fname]
  1007. all_items = []
  1008. properties = []
  1009. activeItems = []
  1010. extraItems = []
  1011. set_headers = set(headers_active)
  1012. set_sources = set(sources_active)
  1013. set_others = set(others_active)
  1014. for file in headers:
  1015. base_path = os.path.dirname(file).replace("\\", "_")
  1016. all_items.append(f'<ClInclude Include="{file}">')
  1017. all_items.append(
  1018. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1019. )
  1020. all_items.append("</ClInclude>")
  1021. if file in set_headers:
  1022. activeItems.append(file)
  1023. for file in sources:
  1024. base_path = os.path.dirname(file).replace("\\", "_")
  1025. all_items.append(f'<ClCompile Include="{file}">')
  1026. all_items.append(
  1027. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1028. )
  1029. all_items.append("</ClCompile>")
  1030. if file in set_sources:
  1031. activeItems.append(file)
  1032. for file in others:
  1033. base_path = os.path.dirname(file).replace("\\", "_")
  1034. all_items.append(f'<None Include="{file}">')
  1035. all_items.append(
  1036. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1037. )
  1038. all_items.append("</None>")
  1039. if file in set_others:
  1040. activeItems.append(file)
  1041. if vs_configuration:
  1042. vsconf = ""
  1043. for a in vs_configuration["arches"]:
  1044. if arch == a["architecture"]:
  1045. vsconf = f'{target}|{a["platform"]}'
  1046. break
  1047. condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'"
  1048. itemlist = {}
  1049. for item in activeItems:
  1050. key = os.path.dirname(item).replace("\\", "_")
  1051. if key not in itemlist:
  1052. itemlist[key] = [item]
  1053. else:
  1054. itemlist[key] += [item]
  1055. for x in itemlist.keys():
  1056. properties.append(
  1057. "<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x)
  1058. )
  1059. output = f'bin\\godot{env["PROGSUFFIX"]}'
  1060. with open("misc/msvs/props.template", "r", encoding="utf-8") as file:
  1061. props_template = file.read()
  1062. props_template = props_template.replace("%%VSCONF%%", vsconf)
  1063. props_template = props_template.replace("%%CONDITION%%", condition)
  1064. props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1065. props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems))
  1066. props_template = props_template.replace("%%OUTPUT%%", output)
  1067. proplist = [format_key_value(v) for v in list(env["CPPDEFINES"])]
  1068. proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])]
  1069. props_template = props_template.replace("%%DEFINES%%", ";".join(proplist))
  1070. proplist = [str(j) for j in env["CPPPATH"]]
  1071. proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])]
  1072. props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist))
  1073. proplist = env["CCFLAGS"]
  1074. proplist += [x for x in env["CXXFLAGS"] if not x.startswith("$")]
  1075. proplist += [str(j) for j in env.get("VSHINT_OPTIONS", [])]
  1076. props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist))
  1077. # Windows allows us to have spaces in paths, so we need
  1078. # to double quote off the directory. However, the path ends
  1079. # in a backslash, so we need to remove this, lest it escape the
  1080. # last double quote off, confusing MSBuild
  1081. common_build_postfix = [
  1082. "--directory=&quot;$(ProjectDir.TrimEnd(&apos;\\&apos;))&quot;",
  1083. "progress=no",
  1084. f"platform={platform}",
  1085. f"target={target}",
  1086. f"arch={arch}",
  1087. ]
  1088. for arg, value in filtered_args.items():
  1089. common_build_postfix.append(f"{arg}={value}")
  1090. cmd_rebuild = [
  1091. "vsproj=yes",
  1092. "vsproj_props_only=yes",
  1093. "vsproj_gen_only=no",
  1094. f"vsproj_name={project_name}",
  1095. ] + common_build_postfix
  1096. cmd_clean = [
  1097. "--clean",
  1098. ] + common_build_postfix
  1099. commands = "scons"
  1100. if len(common_build_prefix) == 0:
  1101. commands = "echo Starting SCons &amp;&amp; cmd /V /C " + commands
  1102. else:
  1103. common_build_prefix[0] = "echo Starting SCons &amp;&amp; cmd /V /C " + common_build_prefix[0]
  1104. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  1105. props_template = props_template.replace("%%BUILD%%", cmd)
  1106. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)])
  1107. props_template = props_template.replace("%%REBUILD%%", cmd)
  1108. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_clean)])
  1109. props_template = props_template.replace("%%CLEAN%%", cmd)
  1110. with open(
  1111. f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n"
  1112. ) as f:
  1113. f.write(props_template)
  1114. proj_uuid = str(uuid.uuid4())
  1115. sln_uuid = str(uuid.uuid4())
  1116. if os.path.exists(f"{project_name}.sln"):
  1117. for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines():
  1118. if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'):
  1119. proj_uuid = re.search(
  1120. 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)}\"$",
  1121. line,
  1122. ).group(1)
  1123. elif line.strip().startswith("SolutionGuid ="):
  1124. sln_uuid = re.search(
  1125. 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
  1126. ).group(1)
  1127. break
  1128. configurations = []
  1129. imports = []
  1130. properties = []
  1131. section1 = []
  1132. section2 = []
  1133. for conf in confs:
  1134. godot_platform = conf["platform"]
  1135. for p in conf["arches"]:
  1136. sln_plat = p["platform"]
  1137. proj_plat = sln_plat
  1138. godot_arch = p["architecture"]
  1139. # Redirect editor configurations for non-Windows platforms to the Windows one, so the solution has all the permutations
  1140. # and VS doesn't complain about missing project configurations.
  1141. # These configurations are disabled, so they show up but won't build.
  1142. if godot_platform != "windows":
  1143. section1 += [f"editor|{sln_plat} = editor|{proj_plat}"]
  1144. section2 += [
  1145. f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{proj_plat}",
  1146. ]
  1147. for t in conf["targets"]:
  1148. godot_target = t
  1149. # Windows x86 is a special little flower that requires a project platform == Win32 but a solution platform == x86.
  1150. if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32":
  1151. sln_plat = "x86"
  1152. configurations += [
  1153. f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">',
  1154. f" <Configuration>{godot_target}</Configuration>",
  1155. f" <Platform>{proj_plat}</Platform>",
  1156. "</ProjectConfiguration>",
  1157. ]
  1158. properties += [
  1159. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">",
  1160. f" <GodotConfiguration>{godot_target}</GodotConfiguration>",
  1161. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1162. "</PropertyGroup>",
  1163. ]
  1164. if godot_platform != "windows":
  1165. configurations += [
  1166. f'<ProjectConfiguration Include="editor|{proj_plat}">',
  1167. " <Configuration>editor</Configuration>",
  1168. f" <Platform>{proj_plat}</Platform>",
  1169. "</ProjectConfiguration>",
  1170. ]
  1171. properties += [
  1172. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">",
  1173. " <GodotConfiguration>editor</GodotConfiguration>",
  1174. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1175. "</PropertyGroup>",
  1176. ]
  1177. p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props"
  1178. imports += [
  1179. f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>'
  1180. ]
  1181. section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"]
  1182. section2 += [
  1183. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}",
  1184. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}",
  1185. ]
  1186. # Add an extra import for a local user props file at the end, so users can add more overrides.
  1187. imports += [
  1188. f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>'
  1189. ]
  1190. section1 = sorted(section1)
  1191. section2 = sorted(section2)
  1192. if not get_bool(original_args, "vsproj_props_only", False):
  1193. with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file:
  1194. proj_template = file.read()
  1195. proj_template = proj_template.replace("%%UUID%%", proj_uuid)
  1196. proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations))
  1197. proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports))
  1198. proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items))
  1199. proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1200. with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\r\n") as f:
  1201. f.write(proj_template)
  1202. if not get_bool(original_args, "vsproj_props_only", False):
  1203. with open("misc/msvs/sln.template", "r", encoding="utf-8") as file:
  1204. sln_template = file.read()
  1205. sln_template = sln_template.replace("%%NAME%%", project_name)
  1206. sln_template = sln_template.replace("%%UUID%%", proj_uuid)
  1207. sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid)
  1208. sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1))
  1209. sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2))
  1210. with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f:
  1211. f.write(sln_template)
  1212. if get_bool(original_args, "vsproj_gen_only", True):
  1213. sys.exit()
  1214. def generate_copyright_header(filename: str) -> str:
  1215. MARGIN = 70
  1216. TEMPLATE = """\
  1217. /**************************************************************************/
  1218. /* %s*/
  1219. /**************************************************************************/
  1220. /* This file is part of: */
  1221. /* GODOT ENGINE */
  1222. /* https://godotengine.org */
  1223. /**************************************************************************/
  1224. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  1225. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  1226. /* */
  1227. /* Permission is hereby granted, free of charge, to any person obtaining */
  1228. /* a copy of this software and associated documentation files (the */
  1229. /* "Software"), to deal in the Software without restriction, including */
  1230. /* without limitation the rights to use, copy, modify, merge, publish, */
  1231. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1232. /* permit persons to whom the Software is furnished to do so, subject to */
  1233. /* the following conditions: */
  1234. /* */
  1235. /* The above copyright notice and this permission notice shall be */
  1236. /* included in all copies or substantial portions of the Software. */
  1237. /* */
  1238. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1239. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1240. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  1241. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1242. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1243. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1244. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1245. /**************************************************************************/
  1246. """
  1247. filename = filename.split("/")[-1].ljust(MARGIN)
  1248. if len(filename) > MARGIN:
  1249. print(f'WARNING: Filename "{filename}" too large for copyright header.')
  1250. return TEMPLATE % filename
  1251. @contextlib.contextmanager
  1252. def generated_wrapper(
  1253. path, # FIXME: type with `Union[str, Node, List[Node]]` when pytest conflicts are resolved
  1254. guard: Optional[bool] = None,
  1255. prefix: str = "",
  1256. suffix: str = "",
  1257. ) -> Generator[TextIOWrapper, None, None]:
  1258. """
  1259. Wrapper class to automatically handle copyright headers and header guards
  1260. for generated scripts. Meant to be invoked via `with` statement similar to
  1261. creating a file.
  1262. - `path`: The path of the file to be created. Can be passed a raw string, an
  1263. isolated SCons target, or a full SCons target list. If a target list contains
  1264. multiple entries, produces a warning & only creates the first entry.
  1265. - `guard`: Optional bool to determine if a header guard should be added. If
  1266. unassigned, header guards are determined by the file extension.
  1267. - `prefix`: Custom prefix to prepend to a header guard. Produces a warning if
  1268. provided a value when `guard` evaluates to `False`.
  1269. - `suffix`: Custom suffix to append to a header guard. Produces a warning if
  1270. provided a value when `guard` evaluates to `False`.
  1271. """
  1272. # Handle unfiltered SCons target[s] passed as path.
  1273. if not isinstance(path, str):
  1274. if isinstance(path, list):
  1275. if len(path) > 1:
  1276. print_warning(
  1277. "Attempting to use generated wrapper with multiple targets; "
  1278. f"will only use first entry: {path[0]}"
  1279. )
  1280. path = path[0]
  1281. if not hasattr(path, "get_abspath"):
  1282. raise TypeError(f'Expected type "str", "Node" or "List[Node]"; was passed {type(path)}.')
  1283. path = path.get_abspath()
  1284. path = str(path).replace("\\", "/")
  1285. if guard is None:
  1286. guard = path.endswith((".h", ".hh", ".hpp", ".inc"))
  1287. if not guard and (prefix or suffix):
  1288. print_warning(f'Trying to assign header guard prefix/suffix while `guard` is disabled: "{path}".')
  1289. header_guard = ""
  1290. if guard:
  1291. if prefix:
  1292. prefix += "_"
  1293. if suffix:
  1294. suffix = f"_{suffix}"
  1295. split = path.split("/")[-1].split(".")
  1296. header_guard = (f"{prefix}{split[0]}{suffix}.{'.'.join(split[1:])}".upper()
  1297. .replace(".", "_").replace("-", "_").replace(" ", "_").replace("__", "_")) # fmt: skip
  1298. with open(path, "wt", encoding="utf-8", newline="\n") as file:
  1299. file.write(generate_copyright_header(path))
  1300. file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n")
  1301. if guard:
  1302. file.write(f"#ifndef {header_guard}\n")
  1303. file.write(f"#define {header_guard}\n\n")
  1304. with StringIO(newline="\n") as str_io:
  1305. yield str_io
  1306. file.write(str_io.getvalue().strip() or "/* NO CONTENT */")
  1307. if guard:
  1308. file.write(f"\n\n#endif // {header_guard}")
  1309. file.write("\n")
  1310. def to_raw_cstring(value: Union[str, List[str]]) -> str:
  1311. MAX_LITERAL = 16 * 1024
  1312. if isinstance(value, list):
  1313. value = "\n".join(value) + "\n"
  1314. split: List[bytes] = []
  1315. offset = 0
  1316. encoded = value.encode()
  1317. while offset <= len(encoded):
  1318. segment = encoded[offset : offset + MAX_LITERAL]
  1319. offset += MAX_LITERAL
  1320. if len(segment) == MAX_LITERAL:
  1321. # Try to segment raw strings at double newlines to keep readable.
  1322. pretty_break = segment.rfind(b"\n\n")
  1323. if pretty_break != -1:
  1324. segment = segment[: pretty_break + 1]
  1325. offset -= MAX_LITERAL - pretty_break - 1
  1326. # If none found, ensure we end with valid utf8.
  1327. # https://github.com/halloleo/unicut/blob/master/truncate.py
  1328. elif segment[-1] & 0b10000000:
  1329. last_11xxxxxx_index = [i for i in range(-1, -5, -1) if segment[i] & 0b11000000 == 0b11000000][0]
  1330. last_11xxxxxx = segment[last_11xxxxxx_index]
  1331. if not last_11xxxxxx & 0b00100000:
  1332. last_char_length = 2
  1333. elif not last_11xxxxxx & 0b0010000:
  1334. last_char_length = 3
  1335. elif not last_11xxxxxx & 0b0001000:
  1336. last_char_length = 4
  1337. if last_char_length > -last_11xxxxxx_index:
  1338. segment = segment[:last_11xxxxxx_index]
  1339. offset += last_11xxxxxx_index
  1340. split += [segment]
  1341. return " ".join(f'R"<!>({x.decode()})<!>"' for x in split)