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