methods.py 62 KB

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