methods.py 64 KB

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