methods.py 63 KB

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