methods.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  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 = (
  544. subprocess.check_output(shlex.split(env.subst(env["CXX"]), posix=False) + ["--version"])
  545. .strip()
  546. .decode("utf-8")
  547. )
  548. except (subprocess.CalledProcessError, OSError):
  549. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  550. return False
  551. return version.startswith("Apple")
  552. def get_compiler_version(env):
  553. """
  554. Returns a dictionary with various version information:
  555. - major, minor, patch: Version following semantic versioning system
  556. - metadata1, metadata2: Extra information
  557. - date: Date of the build
  558. """
  559. global compiler_version_cache
  560. if compiler_version_cache is not None:
  561. return compiler_version_cache
  562. import shlex
  563. ret = {
  564. "major": -1,
  565. "minor": -1,
  566. "patch": -1,
  567. "metadata1": "",
  568. "metadata2": "",
  569. "date": "",
  570. "apple_major": -1,
  571. "apple_minor": -1,
  572. "apple_patch1": -1,
  573. "apple_patch2": -1,
  574. "apple_patch3": -1,
  575. }
  576. if env.msvc and not using_clang(env):
  577. try:
  578. # FIXME: `-latest` works for most cases, but there are edge-cases where this would
  579. # benefit from a more nuanced search.
  580. # https://github.com/godotengine/godot/pull/91069#issuecomment-2358956731
  581. # https://github.com/godotengine/godot/pull/91069#issuecomment-2380836341
  582. args = [
  583. env["VSWHERE"],
  584. "-latest",
  585. "-prerelease",
  586. "-products",
  587. "*",
  588. "-requires",
  589. "Microsoft.Component.MSBuild",
  590. "-utf8",
  591. ]
  592. version = subprocess.check_output(args, encoding="utf-8").strip()
  593. for line in version.splitlines():
  594. split = line.split(":", 1)
  595. if split[0] == "catalog_productDisplayVersion":
  596. sem_ver = split[1].split(".")
  597. ret["major"] = int(sem_ver[0])
  598. ret["minor"] = int(sem_ver[1])
  599. ret["patch"] = int(sem_ver[2].split()[0])
  600. # Could potentially add section for determining preview version, but
  601. # that can wait until metadata is actually used for something.
  602. if split[0] == "catalog_buildVersion":
  603. ret["metadata1"] = split[1]
  604. except (subprocess.CalledProcessError, OSError):
  605. print_warning("Couldn't find vswhere to determine compiler version.")
  606. return update_compiler_version_cache(ret)
  607. # Not using -dumpversion as some GCC distros only return major, and
  608. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  609. try:
  610. version = subprocess.check_output(
  611. shlex.split(env.subst(env["CXX"]), posix=False) + ["--version"], shell=(os.name == "nt"), encoding="utf-8"
  612. ).strip()
  613. except (subprocess.CalledProcessError, OSError):
  614. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  615. return update_compiler_version_cache(ret)
  616. match = re.search(
  617. r"(?:(?<=version )|(?<=\) )|(?<=^))"
  618. r"(?P<major>\d+)"
  619. r"(?:\.(?P<minor>\d*))?"
  620. r"(?:\.(?P<patch>\d*))?"
  621. r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  622. r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  623. r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  624. version,
  625. )
  626. if match is not None:
  627. for key, value in match.groupdict().items():
  628. if value is not None:
  629. ret[key] = value
  630. match_apple = re.search(
  631. r"(?:(?<=clang-)|(?<=\) )|(?<=^))"
  632. r"(?P<apple_major>\d+)"
  633. r"(?:\.(?P<apple_minor>\d*))?"
  634. r"(?:\.(?P<apple_patch1>\d*))?"
  635. r"(?:\.(?P<apple_patch2>\d*))?"
  636. r"(?:\.(?P<apple_patch3>\d*))?",
  637. version,
  638. )
  639. if match_apple is not None:
  640. for key, value in match_apple.groupdict().items():
  641. if value is not None:
  642. ret[key] = value
  643. # Transform semantic versioning to integers
  644. for key in [
  645. "major",
  646. "minor",
  647. "patch",
  648. "apple_major",
  649. "apple_minor",
  650. "apple_patch1",
  651. "apple_patch2",
  652. "apple_patch3",
  653. ]:
  654. ret[key] = int(ret[key] or -1)
  655. return update_compiler_version_cache(ret)
  656. def update_compiler_version_cache(value):
  657. global compiler_version_cache
  658. compiler_version_cache = value
  659. return value
  660. def using_gcc(env):
  661. return "gcc" in os.path.basename(env["CC"])
  662. def using_clang(env):
  663. return "clang" in os.path.basename(env["CC"])
  664. def using_emcc(env):
  665. return "emcc" in os.path.basename(env["CC"])
  666. def show_progress(env):
  667. # Ninja has its own progress/tracking tool that clashes with ours.
  668. if env["ninja"]:
  669. return
  670. NODE_COUNT_FILENAME = base_folder / ".scons_node_count"
  671. class ShowProgress:
  672. def __init__(self):
  673. self.count = 0
  674. self.max = 0
  675. try:
  676. with open(NODE_COUNT_FILENAME, "r", encoding="utf-8") as f:
  677. self.max = int(f.readline())
  678. except OSError:
  679. pass
  680. # Progress reporting is not available in non-TTY environments since it
  681. # messes with the output (for example, when writing to a file).
  682. self.display = cast(bool, env["progress"] and sys.stdout.isatty())
  683. if self.display and not self.max:
  684. print_info("Performing initial build, progress percentage unavailable!")
  685. self.display = False
  686. def __call__(self, node, *args, **kw):
  687. self.count += 1
  688. if self.display:
  689. percent = int(min(self.count * 100 / self.max, 100))
  690. sys.stdout.write(f"\r[{percent:3d}%] ")
  691. sys.stdout.flush()
  692. from SCons.Script import Progress
  693. from SCons.Script.Main import GetBuildFailures
  694. progressor = ShowProgress()
  695. Progress(progressor)
  696. def progress_finish():
  697. if GetBuildFailures() or not progressor.count:
  698. return
  699. try:
  700. with open(NODE_COUNT_FILENAME, "w", encoding="utf-8", newline="\n") as f:
  701. f.write(f"{progressor.count}\n")
  702. except OSError:
  703. pass
  704. atexit.register(progress_finish)
  705. def convert_size(size_bytes: int) -> str:
  706. if size_bytes == 0:
  707. return "0 bytes"
  708. SIZE_NAMES = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
  709. index = math.floor(math.log(size_bytes, 1024))
  710. power = math.pow(1024, index)
  711. size = round(size_bytes / power, 2)
  712. return f"{size} {SIZE_NAMES[index]}"
  713. def get_size(start_path: str = ".") -> int:
  714. total_size = 0
  715. for dirpath, _, filenames in os.walk(start_path):
  716. for file in filenames:
  717. path = os.path.join(dirpath, file)
  718. total_size += os.path.getsize(path)
  719. return total_size
  720. def clean_cache(cache_path: str, cache_limit: int, verbose: bool) -> None:
  721. if not cache_limit:
  722. return
  723. files = glob.glob(os.path.join(cache_path, "*", "*"))
  724. if not files:
  725. return
  726. # Store files in list of (filename, size, atime).
  727. stats = []
  728. for file in files:
  729. try:
  730. stats.append((file, *os.stat(file)[6:8]))
  731. except OSError:
  732. print_error(f'Failed to access cache file "{file}"; skipping.')
  733. # Sort by most recent access (most sensible to keep) first. Search for the first entry where
  734. # the cache limit is reached.
  735. stats.sort(key=lambda x: x[2], reverse=True)
  736. sum = 0
  737. for index, stat in enumerate(stats):
  738. sum += stat[1]
  739. if sum > cache_limit:
  740. purge = [x[0] for x in stats[index:]]
  741. count = len(purge)
  742. for file in purge:
  743. try:
  744. os.remove(file)
  745. except OSError:
  746. print_error(f'Failed to remove cache file "{file}"; skipping.')
  747. count -= 1
  748. if verbose and count:
  749. print_info(f"Purged {count} file{'s' if count else ''} from cache.")
  750. break
  751. def prepare_cache(env) -> None:
  752. cache_path = ""
  753. if env["cache_path"]:
  754. cache_path = cast(str, env["cache_path"])
  755. elif os.environ.get("SCONS_CACHE"):
  756. print_warning("Environment variable `SCONS_CACHE` is deprecated; use `cache_path` argument instead.")
  757. cache_path = cast(str, os.environ.get("SCONS_CACHE"))
  758. if not cache_path:
  759. return
  760. env.CacheDir(cache_path)
  761. print(f'SCons cache enabled... (path: "{cache_path}")')
  762. if env["cache_limit"]:
  763. cache_limit = float(env["cache_limit"])
  764. elif os.environ.get("SCONS_CACHE_LIMIT"):
  765. print_warning("Environment variable `SCONS_CACHE_LIMIT` is deprecated; use `cache_limit` argument instead.")
  766. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", "0")) / 1024 # Old method used MiB, convert to GiB
  767. # Convert GiB to bytes; treat negative numbers as 0 (unlimited).
  768. cache_limit = max(0, int(cache_limit * 1024 * 1024 * 1024))
  769. if env["verbose"]:
  770. print_info(
  771. f"Current cache size is {convert_size(get_size(cache_path))}"
  772. + (f" (limit: {convert_size(cache_limit)})" if cache_limit else "")
  773. )
  774. atexit.register(clean_cache, cache_path, cache_limit, env["verbose"])
  775. def prepare_purge(env):
  776. from SCons.Script.Main import GetBuildFailures
  777. def purge_flaky_files():
  778. paths_to_keep = [env["ninja_file"]]
  779. for build_failure in GetBuildFailures():
  780. path = build_failure.node.path
  781. if os.path.isfile(path) and path not in paths_to_keep:
  782. os.remove(path)
  783. atexit.register(purge_flaky_files)
  784. def prepare_timer():
  785. import time
  786. def print_elapsed_time(time_at_start: float):
  787. time_elapsed = time.time() - time_at_start
  788. time_formatted = time.strftime("%H:%M:%S", time.gmtime(time_elapsed))
  789. time_centiseconds = (time_elapsed % 1) * 100
  790. print_info(f"Time elapsed: {time_formatted}.{time_centiseconds:02.0f}")
  791. atexit.register(print_elapsed_time, time.time())
  792. def dump(env):
  793. """
  794. Dumps latest build information for debugging purposes and external tools.
  795. """
  796. with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as file:
  797. file.write(env.Dump(format="json"))
  798. # Custom Visual Studio project generation logic that supports any platform that has a msvs.py
  799. # script, so Visual Studio can be used to run scons for any platform, with the right defines per target.
  800. # Invoked with scons vsproj=yes
  801. #
  802. # Only platforms that opt in to vs proj generation by having a msvs.py file in the platform folder are included.
  803. # Platforms with a msvs.py file will be added to the solution, but only the current active platform+target+arch
  804. # will have a build configuration generated, because we only know what the right defines/includes/flags/etc are
  805. # on the active build target.
  806. #
  807. # Platforms that don't support an editor target will have a dummy editor target that won't do anything on build,
  808. # but will have the files and configuration for the windows editor target.
  809. #
  810. # To generate build configuration files for all platforms+targets+arch combinations, users can call
  811. # scons vsproj=yes
  812. # for each combination of platform+target+arch. This will generate the relevant vs project files but
  813. # skip the build process. This lets project files be quickly generated even if there are build errors.
  814. #
  815. # To generate AND build from the command line:
  816. # scons vsproj=yes vsproj_gen_only=no
  817. def generate_vs_project(env, original_args, project_name="godot"):
  818. # Augmented glob_recursive that also fills the dirs argument with traversed directories that have content.
  819. def glob_recursive_2(pattern, dirs, node="."):
  820. from SCons import Node
  821. from SCons.Script import Glob
  822. results = []
  823. for f in Glob(str(node) + "/*", source=True):
  824. if type(f) is Node.FS.Dir:
  825. results += glob_recursive_2(pattern, dirs, f)
  826. r = Glob(str(node) + "/" + pattern, source=True)
  827. if len(r) > 0 and str(node) not in dirs:
  828. d = ""
  829. for part in str(node).split("\\"):
  830. d += part
  831. if d not in dirs:
  832. dirs.append(d)
  833. d += "\\"
  834. results += r
  835. return results
  836. def get_bool(args, option, default):
  837. from SCons.Variables.BoolVariable import _text2bool
  838. val = args.get(option, default)
  839. if val is not None:
  840. try:
  841. return _text2bool(val)
  842. except (ValueError, AttributeError):
  843. return default
  844. else:
  845. return default
  846. def format_key_value(v):
  847. if type(v) in [tuple, list]:
  848. return v[0] if len(v) == 1 else f"{v[0]}={v[1]}"
  849. return v
  850. def get_dependencies(file, env, exts, headers, sources, others):
  851. for child in file.children():
  852. if isinstance(child, str):
  853. child = env.File(x)
  854. fname = ""
  855. try:
  856. fname = child.path
  857. except AttributeError:
  858. # It's not a file.
  859. pass
  860. if fname:
  861. parts = os.path.splitext(fname)
  862. if len(parts) > 1:
  863. ext = parts[1].lower()
  864. if ext in exts["sources"]:
  865. sources += [fname]
  866. elif ext in exts["headers"]:
  867. headers += [fname]
  868. elif ext in exts["others"]:
  869. others += [fname]
  870. get_dependencies(child, env, exts, headers, sources, others)
  871. filtered_args = original_args.copy()
  872. # Ignore the "vsproj" option to not regenerate the VS project on every build
  873. filtered_args.pop("vsproj", None)
  874. # This flag allows users to regenerate the proj files but skip the building process.
  875. # This lets projects be regenerated even if there are build errors.
  876. filtered_args.pop("vsproj_gen_only", None)
  877. # This flag allows users to regenerate only the props file without touching the sln or vcxproj files.
  878. # This preserves any customizations users have done to the solution, while still updating the file list
  879. # and build commands.
  880. filtered_args.pop("vsproj_props_only", None)
  881. # The "progress" option is ignored as the current compilation progress indication doesn't work in VS
  882. filtered_args.pop("progress", None)
  883. # We add these three manually because they might not be explicitly passed in, and it's important to always set them.
  884. filtered_args.pop("platform", None)
  885. filtered_args.pop("target", None)
  886. filtered_args.pop("arch", None)
  887. platform = env["platform"]
  888. target = env["target"]
  889. arch = env["arch"]
  890. host_arch = detect_arch()
  891. host_platform = "windows"
  892. if (
  893. sys.platform.startswith("linux")
  894. or sys.platform.startswith("dragonfly")
  895. or sys.platform.startswith("freebsd")
  896. or sys.platform.startswith("netbsd")
  897. or sys.platform.startswith("openbsd")
  898. ):
  899. host_platform = "linuxbsd"
  900. elif sys.platform == "darwin":
  901. host_platform = "macos"
  902. vs_configuration = {}
  903. host_vs_configuration = {}
  904. common_build_prefix = []
  905. confs = []
  906. for x in sorted(glob.glob("platform/*")):
  907. # Only platforms that opt in to vs proj generation are included.
  908. if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"):
  909. continue
  910. tmppath = "./" + x
  911. sys.path.insert(0, tmppath)
  912. import msvs
  913. vs_plats = []
  914. vs_confs = []
  915. try:
  916. platform_name = x[9:]
  917. vs_plats = msvs.get_platforms()
  918. vs_confs = msvs.get_configurations()
  919. val = []
  920. for plat in vs_plats:
  921. val += [{"platform": plat[0], "architecture": plat[1]}]
  922. vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val}
  923. confs += [vsconf]
  924. # Save additional information about the configuration for the actively selected platform,
  925. # so we can generate the platform-specific props file with all the build commands/defines/etc
  926. if platform == platform_name:
  927. common_build_prefix = msvs.get_build_prefix(env)
  928. vs_configuration = vsconf
  929. if platform_name == host_platform:
  930. host_vs_configuration = vsconf
  931. for a in vsconf["arches"]:
  932. if host_arch == a["architecture"]:
  933. host_arch = a["platform"]
  934. break
  935. except Exception:
  936. pass
  937. sys.path.remove(tmppath)
  938. sys.modules.pop("msvs")
  939. extensions = {}
  940. extensions["headers"] = [".h", ".hh", ".hpp", ".hxx", ".inc"]
  941. extensions["sources"] = [".c", ".cc", ".cpp", ".cxx", ".m", ".mm", ".java"]
  942. extensions["others"] = [".natvis", ".glsl", ".rc"]
  943. headers = []
  944. headers_dirs = []
  945. for ext in extensions["headers"]:
  946. for file in glob_recursive_2("*" + ext, headers_dirs):
  947. headers.append(str(file).replace("/", "\\"))
  948. sources = []
  949. sources_dirs = []
  950. for ext in extensions["sources"]:
  951. for file in glob_recursive_2("*" + ext, sources_dirs):
  952. sources.append(str(file).replace("/", "\\"))
  953. others = []
  954. others_dirs = []
  955. for ext in extensions["others"]:
  956. for file in glob_recursive_2("*" + ext, others_dirs):
  957. others.append(str(file).replace("/", "\\"))
  958. skip_filters = False
  959. import hashlib
  960. import json
  961. md5 = hashlib.md5(
  962. json.dumps(sorted(headers + headers_dirs + sources + sources_dirs + others + others_dirs)).encode("utf-8")
  963. ).hexdigest()
  964. if os.path.exists(f"{project_name}.vcxproj.filters"):
  965. with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file:
  966. existing_filters = file.read()
  967. match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters)
  968. if match is not None and md5 == match.group(1):
  969. skip_filters = True
  970. import uuid
  971. # Don't regenerate the filters file if nothing has changed, so we keep the existing UUIDs.
  972. if not skip_filters:
  973. print(f"Regenerating {project_name}.vcxproj.filters")
  974. with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file:
  975. filters_template = file.read()
  976. for i in range(1, 10):
  977. filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4()))
  978. filters = ""
  979. for d in headers_dirs:
  980. filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  981. for d in sources_dirs:
  982. filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  983. for d in others_dirs:
  984. filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  985. filters_template = filters_template.replace("%%FILTERS%%", filters)
  986. filters = ""
  987. for file in headers:
  988. filters += (
  989. f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n'
  990. )
  991. filters_template = filters_template.replace("%%INCLUDES%%", filters)
  992. filters = ""
  993. for file in sources:
  994. filters += (
  995. f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n'
  996. )
  997. filters_template = filters_template.replace("%%COMPILES%%", filters)
  998. filters = ""
  999. for file in others:
  1000. filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n'
  1001. filters_template = filters_template.replace("%%OTHERS%%", filters)
  1002. filters_template = filters_template.replace("%%HASH%%", md5)
  1003. with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f:
  1004. f.write(filters_template)
  1005. headers_active = []
  1006. sources_active = []
  1007. others_active = []
  1008. get_dependencies(
  1009. env.File(f"#bin/godot{env['PROGSUFFIX']}"), env, extensions, headers_active, sources_active, others_active
  1010. )
  1011. all_items = []
  1012. properties = []
  1013. activeItems = []
  1014. extraItems = []
  1015. set_headers = set(headers_active)
  1016. set_sources = set(sources_active)
  1017. set_others = set(others_active)
  1018. for file in headers:
  1019. base_path = os.path.dirname(file).replace("\\", "_")
  1020. all_items.append(f'<ClInclude Include="{file}">')
  1021. all_items.append(
  1022. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1023. )
  1024. all_items.append("</ClInclude>")
  1025. if file in set_headers:
  1026. activeItems.append(file)
  1027. for file in sources:
  1028. base_path = os.path.dirname(file).replace("\\", "_")
  1029. all_items.append(f'<ClCompile Include="{file}">')
  1030. all_items.append(
  1031. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1032. )
  1033. all_items.append("</ClCompile>")
  1034. if file in set_sources:
  1035. activeItems.append(file)
  1036. for file in others:
  1037. base_path = os.path.dirname(file).replace("\\", "_")
  1038. all_items.append(f'<None Include="{file}">')
  1039. all_items.append(
  1040. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1041. )
  1042. all_items.append("</None>")
  1043. if file in set_others:
  1044. activeItems.append(file)
  1045. if vs_configuration:
  1046. vsconf = ""
  1047. for a in vs_configuration["arches"]:
  1048. if arch == a["architecture"]:
  1049. vsconf = f"{target}|{a['platform']}"
  1050. break
  1051. condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'"
  1052. itemlist = {}
  1053. for item in activeItems:
  1054. key = os.path.dirname(item).replace("\\", "_")
  1055. if key not in itemlist:
  1056. itemlist[key] = [item]
  1057. else:
  1058. itemlist[key] += [item]
  1059. for x in itemlist.keys():
  1060. properties.append(
  1061. "<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x)
  1062. )
  1063. output = os.path.join("bin", f"godot{env['PROGSUFFIX']}")
  1064. # The modules_enabled.gen.h header containing the defines is only generated on build, and only for the most recently built
  1065. # platform, which means VS can't properly render code that's inside module-specific ifdefs. This adds those defines to the
  1066. # platform-specific VS props file, so that VS knows which defines are enabled for the selected platform.
  1067. env.Append(VSHINT_DEFINES=[f"MODULE_{module.upper()}_ENABLED" for module in env.module_list])
  1068. with open("misc/msvs/props.template", "r", encoding="utf-8") as file:
  1069. props_template = file.read()
  1070. props_template = props_template.replace("%%CONDITION%%", condition)
  1071. props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1072. props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems))
  1073. props_template = props_template.replace("%%OUTPUT%%", output)
  1074. proplist = [format_key_value(j) for j in list(env["CPPDEFINES"])]
  1075. proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])]
  1076. props_template = props_template.replace("%%DEFINES%%", ";".join(proplist))
  1077. proplist = [str(j) for j in env["CPPPATH"]]
  1078. proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])]
  1079. proplist += [str(j) for j in get_default_include_paths(env)]
  1080. props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist))
  1081. proplist = [env.subst("$CCFLAGS")]
  1082. proplist += [env.subst("$CXXFLAGS")]
  1083. proplist += [env.subst("$VSHINT_OPTIONS")]
  1084. props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist))
  1085. # Windows allows us to have spaces in paths, so we need
  1086. # to double quote off the directory. However, the path ends
  1087. # in a backslash, so we need to remove this, lest it escape the
  1088. # last double quote off, confusing MSBuild
  1089. common_build_postfix = [
  1090. "--directory=&quot;$(ProjectDir.TrimEnd(&apos;\\&apos;))&quot;",
  1091. "progress=no",
  1092. f"platform={platform}",
  1093. f"target={target}",
  1094. f"arch={arch}",
  1095. ]
  1096. for arg, value in filtered_args.items():
  1097. common_build_postfix.append(f"{arg}={value}")
  1098. cmd_rebuild = [
  1099. "vsproj=yes",
  1100. "vsproj_props_only=yes",
  1101. "vsproj_gen_only=no",
  1102. f"vsproj_name={project_name}",
  1103. ] + common_build_postfix
  1104. cmd_clean = [
  1105. "--clean",
  1106. ] + common_build_postfix
  1107. commands = "scons"
  1108. if len(common_build_prefix) == 0:
  1109. commands = "echo Starting SCons &amp; " + commands
  1110. else:
  1111. common_build_prefix[0] = "echo Starting SCons &amp; " + common_build_prefix[0]
  1112. cmd = " ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  1113. props_template = props_template.replace("%%BUILD%%", cmd)
  1114. cmd = " ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)])
  1115. props_template = props_template.replace("%%REBUILD%%", cmd)
  1116. cmd = " ".join(common_build_prefix + [" ".join([commands] + cmd_clean)])
  1117. props_template = props_template.replace("%%CLEAN%%", cmd)
  1118. with open(
  1119. f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n"
  1120. ) as f:
  1121. f.write(props_template)
  1122. proj_uuid = str(uuid.uuid4())
  1123. sln_uuid = str(uuid.uuid4())
  1124. if os.path.exists(f"{project_name}.sln"):
  1125. for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines():
  1126. if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'):
  1127. proj_uuid = re.search(
  1128. 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)}\"$",
  1129. line,
  1130. ).group(1)
  1131. elif line.strip().startswith("SolutionGuid ="):
  1132. sln_uuid = re.search(
  1133. 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
  1134. ).group(1)
  1135. break
  1136. configurations = []
  1137. imports = []
  1138. properties = []
  1139. section1 = []
  1140. section2 = []
  1141. for conf in confs:
  1142. godot_platform = conf["platform"]
  1143. has_editor = "editor" in conf["targets"]
  1144. # Skip any platforms that can build the editor and don't match the host platform.
  1145. #
  1146. # When both Windows and Mac define an editor target, it's defined as platform+target+arch (windows+editor+x64 for example).
  1147. # VS only supports two attributes, a "Configuration" and a "Platform", and we currently map our target to the Configuration
  1148. # (i.e. editor/template_debug/template_release), and our architecture to the "Platform" (i.e. x64, arm64, etc).
  1149. # Those two are not enough to disambiguate multiple godot targets for different godot platforms with the same architecture,
  1150. # i.e. editor|x64 would currently match both windows editor intel 64 and linux editor intel 64.
  1151. #
  1152. # TODO: More work is needed in order to support generating VS projects that unambiguously support all platform+target+arch variations.
  1153. # 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.
  1154. if has_editor and godot_platform != host_vs_configuration["platform"]:
  1155. continue
  1156. for p in conf["arches"]:
  1157. sln_plat = p["platform"]
  1158. proj_plat = sln_plat
  1159. godot_arch = p["architecture"]
  1160. # Redirect editor configurations for platforms that don't support the editor target to the default editor target on the
  1161. # active host platform, so the solution has all the permutations and VS doesn't complain about missing project configurations.
  1162. # These configurations are disabled, so they show up but won't build.
  1163. if not has_editor:
  1164. section1 += [f"editor|{sln_plat} = editor|{proj_plat}"]
  1165. section2 += [f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{host_arch}"]
  1166. configurations += [
  1167. f'<ProjectConfiguration Include="editor|{proj_plat}">',
  1168. " <Configuration>editor</Configuration>",
  1169. f" <Platform>{proj_plat}</Platform>",
  1170. "</ProjectConfiguration>",
  1171. ]
  1172. properties += [
  1173. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">",
  1174. " <GodotConfiguration>editor</GodotConfiguration>",
  1175. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1176. "</PropertyGroup>",
  1177. ]
  1178. for t in conf["targets"]:
  1179. godot_target = t
  1180. # Windows x86 is a special little flower that requires a project platform == Win32 but a solution platform == x86.
  1181. if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32":
  1182. sln_plat = "x86"
  1183. configurations += [
  1184. f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">',
  1185. f" <Configuration>{godot_target}</Configuration>",
  1186. f" <Platform>{proj_plat}</Platform>",
  1187. "</ProjectConfiguration>",
  1188. ]
  1189. properties += [
  1190. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">",
  1191. f" <GodotConfiguration>{godot_target}</GodotConfiguration>",
  1192. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1193. "</PropertyGroup>",
  1194. ]
  1195. p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props"
  1196. imports += [
  1197. f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>'
  1198. ]
  1199. section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"]
  1200. section2 += [
  1201. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}",
  1202. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}",
  1203. ]
  1204. # Add an extra import for a local user props file at the end, so users can add more overrides.
  1205. imports += [
  1206. f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>'
  1207. ]
  1208. section1 = sorted(section1)
  1209. section2 = sorted(section2)
  1210. if not get_bool(original_args, "vsproj_props_only", False):
  1211. with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file:
  1212. proj_template = file.read()
  1213. proj_template = proj_template.replace("%%UUID%%", proj_uuid)
  1214. proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations))
  1215. proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports))
  1216. proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items))
  1217. proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1218. with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\r\n") as f:
  1219. f.write(proj_template)
  1220. if not get_bool(original_args, "vsproj_props_only", False):
  1221. with open("misc/msvs/sln.template", "r", encoding="utf-8") as file:
  1222. sln_template = file.read()
  1223. sln_template = sln_template.replace("%%NAME%%", project_name)
  1224. sln_template = sln_template.replace("%%UUID%%", proj_uuid)
  1225. sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid)
  1226. sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1))
  1227. sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2))
  1228. with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f:
  1229. f.write(sln_template)
  1230. if get_bool(original_args, "vsproj_gen_only", True):
  1231. sys.exit()
  1232. ############################################################
  1233. # FILE GENERATION & FORMATTING
  1234. ############################################################
  1235. def generate_copyright_header(filename: str) -> str:
  1236. MARGIN = 70
  1237. TEMPLATE = """\
  1238. /**************************************************************************/
  1239. /* %s*/
  1240. /**************************************************************************/
  1241. /* This file is part of: */
  1242. /* GODOT ENGINE */
  1243. /* https://godotengine.org */
  1244. /**************************************************************************/
  1245. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  1246. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  1247. /* */
  1248. /* Permission is hereby granted, free of charge, to any person obtaining */
  1249. /* a copy of this software and associated documentation files (the */
  1250. /* "Software"), to deal in the Software without restriction, including */
  1251. /* without limitation the rights to use, copy, modify, merge, publish, */
  1252. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1253. /* permit persons to whom the Software is furnished to do so, subject to */
  1254. /* the following conditions: */
  1255. /* */
  1256. /* The above copyright notice and this permission notice shall be */
  1257. /* included in all copies or substantial portions of the Software. */
  1258. /* */
  1259. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1260. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1261. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  1262. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1263. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1264. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1265. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1266. /**************************************************************************/
  1267. """
  1268. if len(filename := os.path.basename(filename).ljust(MARGIN)) > MARGIN:
  1269. print_warning(f'Filename "{filename}" too large for copyright header.')
  1270. return TEMPLATE % filename
  1271. @contextlib.contextmanager
  1272. def generated_wrapper(
  1273. path: str,
  1274. guard: Optional[bool] = None,
  1275. ) -> Generator[TextIOBase, None, None]:
  1276. """
  1277. Wrapper class to automatically handle copyright headers and header guards
  1278. for generated scripts. Meant to be invoked via `with` statement similar to
  1279. creating a file.
  1280. - `path`: The path of the file to be created.
  1281. - `guard`: Optional bool to determine if `#pragma once` should be added. If
  1282. unassigned, the value is determined by file extension.
  1283. """
  1284. with open(path, "wt", encoding="utf-8", newline="\n") as file:
  1285. if not path.endswith(".out"): # For test output, we only care about the content.
  1286. file.write(generate_copyright_header(path))
  1287. file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n")
  1288. if guard is None:
  1289. guard = path.endswith((".h", ".hh", ".hpp", ".hxx", ".inc"))
  1290. if guard:
  1291. file.write("#pragma once\n\n")
  1292. with StringIO(newline="\n") as str_io:
  1293. yield str_io
  1294. file.write(str_io.getvalue().strip() or "/* NO CONTENT */")
  1295. file.write("\n")
  1296. def get_buffer(path: str) -> bytes:
  1297. with open(path, "rb") as file:
  1298. return file.read()
  1299. def compress_buffer(buffer: bytes) -> bytes:
  1300. # Use maximum zlib compression level to further reduce file size
  1301. # (at the cost of initial build times).
  1302. return zlib.compress(buffer, zlib.Z_BEST_COMPRESSION)
  1303. def format_buffer(buffer: bytes, indent: int = 0, width: int = 120, initial_indent: bool = False) -> str:
  1304. return textwrap.fill(
  1305. ", ".join(str(byte) for byte in buffer),
  1306. width=width,
  1307. initial_indent="\t" * indent if initial_indent else "",
  1308. subsequent_indent="\t" * indent,
  1309. tabsize=4,
  1310. )
  1311. ############################################################
  1312. # CSTRING PARSING
  1313. ############################################################
  1314. C_ESCAPABLES = [
  1315. ("\\", "\\\\"),
  1316. ("\a", "\\a"),
  1317. ("\b", "\\b"),
  1318. ("\f", "\\f"),
  1319. ("\n", "\\n"),
  1320. ("\r", "\\r"),
  1321. ("\t", "\\t"),
  1322. ("\v", "\\v"),
  1323. # ("'", "\\'"), # Skip, as we're only dealing with full strings.
  1324. ('"', '\\"'),
  1325. ]
  1326. C_ESCAPE_TABLE = str.maketrans(dict((x, y) for x, y in C_ESCAPABLES))
  1327. def to_escaped_cstring(value: str) -> str:
  1328. return value.translate(C_ESCAPE_TABLE)
  1329. def to_raw_cstring(value: Union[str, List[str]]) -> str:
  1330. MAX_LITERAL = 16 * 1024
  1331. if isinstance(value, list):
  1332. value = "\n".join(value) + "\n"
  1333. split: List[bytes] = []
  1334. offset = 0
  1335. encoded = value.encode()
  1336. while offset <= len(encoded):
  1337. segment = encoded[offset : offset + MAX_LITERAL]
  1338. offset += MAX_LITERAL
  1339. if len(segment) == MAX_LITERAL:
  1340. # Try to segment raw strings at double newlines to keep readable.
  1341. pretty_break = segment.rfind(b"\n\n")
  1342. if pretty_break != -1:
  1343. segment = segment[: pretty_break + 1]
  1344. offset -= MAX_LITERAL - pretty_break - 1
  1345. # If none found, ensure we end with valid utf8.
  1346. # https://github.com/halloleo/unicut/blob/master/truncate.py
  1347. elif segment[-1] & 0b10000000:
  1348. last_11xxxxxx_index = [i for i in range(-1, -5, -1) if segment[i] & 0b11000000 == 0b11000000][0]
  1349. last_11xxxxxx = segment[last_11xxxxxx_index]
  1350. if not last_11xxxxxx & 0b00100000:
  1351. last_char_length = 2
  1352. elif not last_11xxxxxx & 0b0010000:
  1353. last_char_length = 3
  1354. elif not last_11xxxxxx & 0b0001000:
  1355. last_char_length = 4
  1356. if last_char_length > -last_11xxxxxx_index:
  1357. segment = segment[:last_11xxxxxx_index]
  1358. offset += last_11xxxxxx_index
  1359. split += [segment]
  1360. if len(split) == 1:
  1361. return f'R"<!>({split[0].decode()})<!>"'
  1362. else:
  1363. # Wrap multiple segments in parenthesis to suppress `string-concatenation` warnings on clang.
  1364. return "({})".format(" ".join(f'R"<!>({segment.decode()})<!>"' for segment in split))
  1365. def get_default_include_paths(env):
  1366. if env.msvc:
  1367. return []
  1368. compiler = env.subst("$CXX")
  1369. target = os.path.join(env.Dir("#main").abspath, "main.cpp")
  1370. args = [compiler, target, "-x", "c++", "-v"]
  1371. ret = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
  1372. output = ret.stdout
  1373. match = re.search(r"#include <\.\.\.> search starts here:([\S\s]*)End of search list.", output)
  1374. if not match:
  1375. print_warning("Failed to find the include paths in the compiler output.")
  1376. return []
  1377. return [x.strip() for x in match[1].strip().splitlines()]