methods.py 60 KB

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