2
0

methods.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  1. import os
  2. import sys
  3. import re
  4. import glob
  5. import subprocess
  6. from collections import OrderedDict
  7. from collections.abc import Mapping
  8. from enum import Enum
  9. from typing import Iterator
  10. from pathlib import Path
  11. from os.path import normpath, basename
  12. # Get the "Godot" folder name ahead of time
  13. base_folder_path = str(os.path.abspath(Path(__file__).parent)) + "/"
  14. base_folder_only = os.path.basename(os.path.normpath(base_folder_path))
  15. # Listing all the folders we have converted
  16. # for SCU in scu_builders.py
  17. _scu_folders = set()
  18. # Colors are disabled in non-TTY environments such as pipes. This means
  19. # that if output is redirected to a file, it won't contain color codes.
  20. # Colors are always enabled on continuous integration.
  21. _colorize = bool(sys.stdout.isatty() or os.environ.get("CI"))
  22. def set_scu_folders(scu_folders):
  23. global _scu_folders
  24. _scu_folders = scu_folders
  25. class ANSI(Enum):
  26. """
  27. Enum class for adding ansi colorcodes directly into strings.
  28. Automatically converts values to strings representing their
  29. internal value, or an empty string in a non-colorized scope.
  30. """
  31. RESET = "\x1b[0m"
  32. BOLD = "\x1b[1m"
  33. ITALIC = "\x1b[3m"
  34. UNDERLINE = "\x1b[4m"
  35. STRIKETHROUGH = "\x1b[9m"
  36. REGULAR = "\x1b[22;23;24;29m"
  37. BLACK = "\x1b[30m"
  38. RED = "\x1b[31m"
  39. GREEN = "\x1b[32m"
  40. YELLOW = "\x1b[33m"
  41. BLUE = "\x1b[34m"
  42. MAGENTA = "\x1b[35m"
  43. CYAN = "\x1b[36m"
  44. WHITE = "\x1b[37m"
  45. PURPLE = "\x1b[38;5;93m"
  46. PINK = "\x1b[38;5;206m"
  47. ORANGE = "\x1b[38;5;214m"
  48. GRAY = "\x1b[38;5;244m"
  49. def __str__(self) -> str:
  50. global _colorize
  51. return str(self.value) if _colorize else ""
  52. def print_warning(*values: object) -> None:
  53. """Prints a warning message with formatting."""
  54. print(f"{ANSI.YELLOW}{ANSI.BOLD}WARNING:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr)
  55. def print_error(*values: object) -> None:
  56. """Prints an error message with formatting."""
  57. print(f"{ANSI.RED}{ANSI.BOLD}ERROR:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr)
  58. def add_source_files_orig(self, sources, files, allow_gen=False):
  59. # Convert string to list of absolute paths (including expanding wildcard)
  60. if isinstance(files, (str, bytes)):
  61. # Keep SCons project-absolute path as they are (no wildcard support)
  62. if files.startswith("#"):
  63. if "*" in files:
  64. print_error("Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  65. return
  66. files = [files]
  67. else:
  68. # Exclude .gen.cpp files from globbing, to avoid including obsolete ones.
  69. # They should instead be added manually.
  70. skip_gen_cpp = "*" in files
  71. dir_path = self.Dir(".").abspath
  72. files = sorted(glob.glob(dir_path + "/" + files))
  73. if skip_gen_cpp and not allow_gen:
  74. files = [f for f in files if not f.endswith(".gen.cpp")]
  75. # Add each path as compiled Object following environment (self) configuration
  76. for path in files:
  77. obj = self.Object(path)
  78. if obj in sources:
  79. print_warning('Object "{}" already included in environment sources.'.format(obj))
  80. continue
  81. sources.append(obj)
  82. # The section name is used for checking
  83. # the hash table to see whether the folder
  84. # is included in the SCU build.
  85. # It will be something like "core/math".
  86. def _find_scu_section_name(subdir):
  87. section_path = os.path.abspath(subdir) + "/"
  88. folders = []
  89. folder = ""
  90. for i in range(8):
  91. folder = os.path.dirname(section_path)
  92. folder = os.path.basename(folder)
  93. if folder == base_folder_only:
  94. break
  95. folders += [folder]
  96. section_path += "../"
  97. section_path = os.path.abspath(section_path) + "/"
  98. section_name = ""
  99. for n in range(len(folders)):
  100. # section_name += folders[len(folders) - n - 1] + " "
  101. section_name += folders[len(folders) - n - 1]
  102. if n != (len(folders) - 1):
  103. section_name += "/"
  104. return section_name
  105. def add_source_files_scu(self, sources, files, allow_gen=False):
  106. if self["scu_build"] and isinstance(files, str):
  107. if "*." not in files:
  108. return False
  109. # If the files are in a subdirectory, we want to create the scu gen
  110. # files inside this subdirectory.
  111. subdir = os.path.dirname(files)
  112. if subdir != "":
  113. subdir += "/"
  114. section_name = _find_scu_section_name(subdir)
  115. # if the section name is in the hash table?
  116. # i.e. is it part of the SCU build?
  117. global _scu_folders
  118. if section_name not in (_scu_folders):
  119. return False
  120. # Add all the gen.cpp files in the SCU directory
  121. add_source_files_orig(self, sources, subdir + "scu/scu_*.gen.cpp", True)
  122. return True
  123. return False
  124. # Either builds the folder using the SCU system,
  125. # or reverts to regular build.
  126. def add_source_files(self, sources, files, allow_gen=False):
  127. if not add_source_files_scu(self, sources, files, allow_gen):
  128. # Wraps the original function when scu build is not active.
  129. add_source_files_orig(self, sources, files, allow_gen)
  130. return False
  131. return True
  132. def disable_warnings(self):
  133. # 'self' is the environment
  134. if self.msvc:
  135. # We have to remove existing warning level defines before appending /w,
  136. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  137. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  138. self["CFLAGS"] = [x for x in self["CFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  139. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  140. self.AppendUnique(CCFLAGS=["/w"])
  141. else:
  142. self.AppendUnique(CCFLAGS=["-w"])
  143. def force_optimization_on_debug(self):
  144. # 'self' is the environment
  145. if self["target"] == "template_release":
  146. return
  147. if self.msvc:
  148. # We have to remove existing optimization level defines before appending /O2,
  149. # otherwise we get: "warning D9025 : overriding '/0d' with '/02'"
  150. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x.startswith("/O")]
  151. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x.startswith("/O")]
  152. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x.startswith("/O")]
  153. self.AppendUnique(CCFLAGS=["/O2"])
  154. else:
  155. self.AppendUnique(CCFLAGS=["-O3"])
  156. def add_module_version_string(self, s):
  157. self.module_version_string += "." + s
  158. def get_version_info(module_version_string="", silent=False):
  159. build_name = "custom_build"
  160. if os.getenv("BUILD_NAME") != None:
  161. build_name = str(os.getenv("BUILD_NAME"))
  162. if not silent:
  163. print(f"Using custom build name: '{build_name}'.")
  164. import version
  165. version_info = {
  166. "short_name": str(version.short_name),
  167. "name": str(version.name),
  168. "major": int(version.major),
  169. "minor": int(version.minor),
  170. "patch": int(version.patch),
  171. "status": str(version.status),
  172. "build": str(build_name),
  173. "module_config": str(version.module_config) + module_version_string,
  174. "website": str(version.website),
  175. "docs_branch": str(version.docs),
  176. }
  177. # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
  178. # so this define provides a way to override it without having to modify the source.
  179. if os.getenv("GODOT_VERSION_STATUS") != None:
  180. version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS"))
  181. if not silent:
  182. print(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.")
  183. # Parse Git hash if we're in a Git repo.
  184. githash = ""
  185. gitfolder = ".git"
  186. if os.path.isfile(".git"):
  187. with open(".git", "r", encoding="utf-8") as file:
  188. module_folder = file.readline().strip()
  189. if module_folder.startswith("gitdir: "):
  190. gitfolder = module_folder[8:]
  191. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  192. with open(os.path.join(gitfolder, "HEAD"), "r", encoding="utf8") as file:
  193. head = file.readline().strip()
  194. if head.startswith("ref: "):
  195. ref = head[5:]
  196. # If this directory is a Git worktree instead of a root clone.
  197. parts = gitfolder.split("/")
  198. if len(parts) > 2 and parts[-2] == "worktrees":
  199. gitfolder = "/".join(parts[0:-2])
  200. head = os.path.join(gitfolder, ref)
  201. packedrefs = os.path.join(gitfolder, "packed-refs")
  202. if os.path.isfile(head):
  203. with open(head, "r", encoding="utf-8") as file:
  204. githash = file.readline().strip()
  205. elif os.path.isfile(packedrefs):
  206. # Git may pack refs into a single file. This code searches .git/packed-refs file for the current ref's hash.
  207. # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-pack-refs.html
  208. for line in open(packedrefs, "r", encoding="utf-8").read().splitlines():
  209. if line.startswith("#"):
  210. continue
  211. (line_hash, line_ref) = line.split(" ")
  212. if ref == line_ref:
  213. githash = line_hash
  214. break
  215. else:
  216. githash = head
  217. version_info["git_hash"] = githash
  218. # Fallback to 0 as a timestamp (will be treated as "unknown" in the engine).
  219. version_info["git_timestamp"] = 0
  220. # Get the UNIX timestamp of the build commit.
  221. if os.path.exists(".git"):
  222. try:
  223. version_info["git_timestamp"] = subprocess.check_output(
  224. ["git", "log", "-1", "--pretty=format:%ct", githash]
  225. ).decode("utf-8")
  226. except (subprocess.CalledProcessError, OSError):
  227. # `git` not found in PATH.
  228. pass
  229. return version_info
  230. _cleanup_env = None
  231. _cleanup_bool = False
  232. def write_file_if_needed(path, string):
  233. """Generates a file only if it doesn't already exist or the content has changed.
  234. Utilizes a dedicated SCons environment to ensure the files are properly removed
  235. during cleanup; will not attempt to create files during cleanup.
  236. - `path` - Path to the file in question; used to create cleanup logic.
  237. - `string` - Content to compare against an existing file.
  238. """
  239. global _cleanup_env
  240. global _cleanup_bool
  241. if _cleanup_env is None:
  242. from SCons.Environment import Environment
  243. _cleanup_env = Environment()
  244. _cleanup_bool = _cleanup_env.GetOption("clean")
  245. _cleanup_env.Clean("#", path)
  246. if _cleanup_bool:
  247. return
  248. try:
  249. with open(path, "r", encoding="utf-8", newline="\n") as f:
  250. if f.read() == string:
  251. return
  252. except FileNotFoundError:
  253. pass
  254. with open(path, "w", encoding="utf-8", newline="\n") as f:
  255. f.write(string)
  256. def generate_version_header(module_version_string=""):
  257. version_info = get_version_info(module_version_string)
  258. version_info_header = """\
  259. /* THIS FILE IS GENERATED DO NOT EDIT */
  260. #ifndef VERSION_GENERATED_GEN_H
  261. #define VERSION_GENERATED_GEN_H
  262. #define VERSION_SHORT_NAME "{short_name}"
  263. #define VERSION_NAME "{name}"
  264. #define VERSION_MAJOR {major}
  265. #define VERSION_MINOR {minor}
  266. #define VERSION_PATCH {patch}
  267. #define VERSION_STATUS "{status}"
  268. #define VERSION_BUILD "{build}"
  269. #define VERSION_MODULE_CONFIG "{module_config}"
  270. #define VERSION_WEBSITE "{website}"
  271. #define VERSION_DOCS_BRANCH "{docs_branch}"
  272. #define VERSION_DOCS_URL "https://docs.godotengine.org/en/" VERSION_DOCS_BRANCH
  273. #endif // VERSION_GENERATED_GEN_H
  274. """.format(
  275. **version_info
  276. )
  277. version_hash_data = """\
  278. /* THIS FILE IS GENERATED DO NOT EDIT */
  279. #include "core/version.h"
  280. const char *const VERSION_HASH = "{git_hash}";
  281. const uint64_t VERSION_TIMESTAMP = {git_timestamp};
  282. """.format(
  283. **version_info
  284. )
  285. write_file_if_needed("core/version_generated.gen.h", version_info_header)
  286. write_file_if_needed("core/version_hash.gen.cpp", version_hash_data)
  287. def parse_cg_file(fname, uniforms, sizes, conditionals):
  288. with open(fname, "r", encoding="utf-8") as fs:
  289. line = fs.readline()
  290. while line:
  291. if re.match(r"^\s*uniform", line):
  292. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  293. type = res.groups(1)
  294. name = res.groups(2)
  295. uniforms.append(name)
  296. if type.find("texobj") != -1:
  297. sizes.append(1)
  298. else:
  299. t = re.match(r"float(\d)x(\d)", type)
  300. if t:
  301. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  302. else:
  303. t = re.match(r"float(\d)", type)
  304. sizes.append(int(t.groups(1)))
  305. if line.find("[branch]") != -1:
  306. conditionals.append(name)
  307. line = fs.readline()
  308. def get_cmdline_bool(option, default):
  309. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  310. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  311. """
  312. from SCons.Script import ARGUMENTS
  313. from SCons.Variables.BoolVariable import _text2bool
  314. cmdline_val = ARGUMENTS.get(option)
  315. if cmdline_val is not None:
  316. return _text2bool(cmdline_val)
  317. else:
  318. return default
  319. def detect_modules(search_path, recursive=False):
  320. """Detects and collects a list of C++ modules at specified path
  321. `search_path` - a directory path containing modules. The path may point to
  322. a single module, which may have other nested modules. A module must have
  323. "register_types.h", "SCsub", "config.py" files created to be detected.
  324. `recursive` - if `True`, then all subdirectories are searched for modules as
  325. specified by the `search_path`, otherwise collects all modules under the
  326. `search_path` directory. If the `search_path` is a module, it is collected
  327. in all cases.
  328. Returns an `OrderedDict` with module names as keys, and directory paths as
  329. values. If a path is relative, then it is a built-in module. If a path is
  330. absolute, then it is a custom module collected outside of the engine source.
  331. """
  332. modules = OrderedDict()
  333. def add_module(path):
  334. module_name = os.path.basename(path)
  335. module_path = path.replace("\\", "/") # win32
  336. modules[module_name] = module_path
  337. def is_engine(path):
  338. # Prevent recursively detecting modules in self and other
  339. # Godot sources when using `custom_modules` build option.
  340. version_path = os.path.join(path, "version.py")
  341. if os.path.exists(version_path):
  342. with open(version_path) as f:
  343. if 'short_name = "godot"' in f.read():
  344. return True
  345. return False
  346. def get_files(path):
  347. files = glob.glob(os.path.join(path, "*"))
  348. # Sort so that `register_module_types` does not change that often,
  349. # and plugins are registered in alphabetic order as well.
  350. files.sort()
  351. return files
  352. if not recursive:
  353. if is_module(search_path):
  354. add_module(search_path)
  355. for path in get_files(search_path):
  356. if is_engine(path):
  357. continue
  358. if is_module(path):
  359. add_module(path)
  360. else:
  361. to_search = [search_path]
  362. while to_search:
  363. path = to_search.pop()
  364. if is_module(path):
  365. add_module(path)
  366. for child in get_files(path):
  367. if not os.path.isdir(child):
  368. continue
  369. if is_engine(child):
  370. continue
  371. to_search.insert(0, child)
  372. return modules
  373. def is_module(path):
  374. if not os.path.isdir(path):
  375. return False
  376. must_exist = ["register_types.h", "SCsub", "config.py"]
  377. for f in must_exist:
  378. if not os.path.exists(os.path.join(path, f)):
  379. return False
  380. return True
  381. def write_disabled_classes(class_list):
  382. file_contents = ""
  383. file_contents += "/* THIS FILE IS GENERATED DO NOT EDIT */\n"
  384. file_contents += "#ifndef DISABLED_CLASSES_GEN_H\n"
  385. file_contents += "#define DISABLED_CLASSES_GEN_H\n\n"
  386. for c in class_list:
  387. cs = c.strip()
  388. if cs != "":
  389. file_contents += "#define ClassDB_Disable_" + cs + " 1\n"
  390. file_contents += "\n#endif\n"
  391. write_file_if_needed("core/disabled_classes.gen.h", file_contents)
  392. def write_modules(modules):
  393. includes_cpp = ""
  394. initialize_cpp = ""
  395. uninitialize_cpp = ""
  396. for name, path in modules.items():
  397. try:
  398. with open(os.path.join(path, "register_types.h")):
  399. includes_cpp += '#include "' + path + '/register_types.h"\n'
  400. initialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  401. initialize_cpp += "\tinitialize_" + name + "_module(p_level);\n"
  402. initialize_cpp += "#endif\n"
  403. uninitialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  404. uninitialize_cpp += "\tuninitialize_" + name + "_module(p_level);\n"
  405. uninitialize_cpp += "#endif\n"
  406. except OSError:
  407. pass
  408. modules_cpp = """// register_module_types.gen.cpp
  409. /* THIS FILE IS GENERATED DO NOT EDIT */
  410. #include "register_module_types.h"
  411. #include "modules/modules_enabled.gen.h"
  412. %s
  413. void initialize_modules(ModuleInitializationLevel p_level) {
  414. %s
  415. }
  416. void uninitialize_modules(ModuleInitializationLevel p_level) {
  417. %s
  418. }
  419. """ % (
  420. includes_cpp,
  421. initialize_cpp,
  422. uninitialize_cpp,
  423. )
  424. write_file_if_needed("modules/register_module_types.gen.cpp", modules_cpp)
  425. def convert_custom_modules_path(path):
  426. if not path:
  427. return path
  428. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  429. err_msg = "Build option 'custom_modules' must %s"
  430. if not os.path.isdir(path):
  431. raise ValueError(err_msg % "point to an existing directory.")
  432. if path == os.path.realpath("modules"):
  433. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  434. return path
  435. def disable_module(self):
  436. self.disabled_modules.append(self.current_module)
  437. def module_add_dependencies(self, module, dependencies, optional=False):
  438. """
  439. Adds dependencies for a given module.
  440. Meant to be used in module `can_build` methods.
  441. """
  442. if module not in self.module_dependencies:
  443. self.module_dependencies[module] = [[], []]
  444. if optional:
  445. self.module_dependencies[module][1].extend(dependencies)
  446. else:
  447. self.module_dependencies[module][0].extend(dependencies)
  448. def module_check_dependencies(self, module):
  449. """
  450. Checks if module dependencies are enabled for a given module,
  451. and prints a warning if they aren't.
  452. Meant to be used in module `can_build` methods.
  453. Returns a boolean (True if dependencies are satisfied).
  454. """
  455. missing_deps = []
  456. required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
  457. for dep in required_deps:
  458. opt = "module_{}_enabled".format(dep)
  459. if not opt in self or not self[opt]:
  460. missing_deps.append(dep)
  461. if missing_deps != []:
  462. print_warning(
  463. "Disabling '{}' module as the following dependencies are not satisfied: {}".format(
  464. module, ", ".join(missing_deps)
  465. )
  466. )
  467. return False
  468. else:
  469. return True
  470. def sort_module_list(env):
  471. out = OrderedDict()
  472. deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()}
  473. frontier = list(env.module_list.keys())
  474. explored = []
  475. while len(frontier):
  476. cur = frontier.pop()
  477. deps_list = deps[cur] if cur in deps else []
  478. if len(deps_list) and any([d not in explored for d in deps_list]):
  479. # Will explore later, after its dependencies
  480. frontier.insert(0, cur)
  481. continue
  482. explored.append(cur)
  483. for k in explored:
  484. env.module_list.move_to_end(k)
  485. def use_windows_spawn_fix(self, platform=None):
  486. if os.name != "nt":
  487. return # not needed, only for windows
  488. # On Windows, due to the limited command line length, when creating a static library
  489. # from a very high number of objects SCons will invoke "ar" once per object file;
  490. # that makes object files with same names to be overwritten so the last wins and
  491. # the library loses symbols defined by overwritten objects.
  492. # By enabling quick append instead of the default mode (replacing), libraries will
  493. # got built correctly regardless the invocation strategy.
  494. # Furthermore, since SCons will rebuild the library from scratch when an object file
  495. # changes, no multiple versions of the same object file will be present.
  496. self.Replace(ARFLAGS="q")
  497. def mySubProcess(cmdline, env):
  498. startupinfo = subprocess.STARTUPINFO()
  499. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  500. popen_args = {
  501. "stdin": subprocess.PIPE,
  502. "stdout": subprocess.PIPE,
  503. "stderr": subprocess.PIPE,
  504. "startupinfo": startupinfo,
  505. "shell": False,
  506. "env": env,
  507. }
  508. if sys.version_info >= (3, 7, 0):
  509. popen_args["text"] = True
  510. proc = subprocess.Popen(cmdline, **popen_args)
  511. _, err = proc.communicate()
  512. rv = proc.wait()
  513. if rv:
  514. print_error(err)
  515. return rv
  516. def mySpawn(sh, escape, cmd, args, env):
  517. newargs = " ".join(args[1:])
  518. cmdline = cmd + " " + newargs
  519. rv = 0
  520. env = {str(key): str(value) for key, value in iter(env.items())}
  521. if len(cmdline) > 32000 and cmd.endswith("ar"):
  522. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  523. for i in range(3, len(args)):
  524. rv = mySubProcess(cmdline + args[i], env)
  525. if rv:
  526. break
  527. else:
  528. rv = mySubProcess(cmdline, env)
  529. return rv
  530. self["SPAWN"] = mySpawn
  531. def no_verbose(env):
  532. colors = [ANSI.BLUE, ANSI.BOLD, ANSI.REGULAR, ANSI.RESET]
  533. # There is a space before "..." to ensure that source file names can be
  534. # Ctrl + clicked in the VS Code terminal.
  535. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  536. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  537. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(*colors)
  538. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(*colors)
  539. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(*colors)
  540. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(*colors)
  541. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(*colors)
  542. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(*colors)
  543. compiled_resource_message = "{}Creating Compiled Resource {}$TARGET{} ...{}".format(*colors)
  544. generated_file_message = "{}Generating {}$TARGET{} ...{}".format(*colors)
  545. env["CXXCOMSTR"] = compile_source_message
  546. env["CCCOMSTR"] = compile_source_message
  547. env["SHCCCOMSTR"] = compile_shared_source_message
  548. env["SHCXXCOMSTR"] = compile_shared_source_message
  549. env["ARCOMSTR"] = link_library_message
  550. env["RANLIBCOMSTR"] = ranlib_library_message
  551. env["SHLINKCOMSTR"] = link_shared_library_message
  552. env["LINKCOMSTR"] = link_program_message
  553. env["JARCOMSTR"] = java_library_message
  554. env["JAVACCOMSTR"] = java_compile_source_message
  555. env["RCCOMSTR"] = compiled_resource_message
  556. env["GENCOMSTR"] = generated_file_message
  557. def detect_visual_c_compiler_version(tools_env):
  558. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  559. # (see the SCons documentation for more information on what it does)...
  560. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  561. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  562. # the proper vc version that will be called
  563. # 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.).
  564. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  565. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  566. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  567. # the following string values:
  568. # "" Compiler not detected
  569. # "amd64" Native 64 bit compiler
  570. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  571. # "x86" Native 32 bit compiler
  572. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  573. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  574. # and similar architectures/compilers
  575. # Set chosen compiler to "not detected"
  576. vc_chosen_compiler_index = -1
  577. vc_chosen_compiler_str = ""
  578. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  579. if "VCINSTALLDIR" in tools_env:
  580. # print("Checking VCINSTALLDIR")
  581. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  582. # First test if amd64 and amd64_x86 compilers are present in the path
  583. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  584. if vc_amd64_compiler_detection_index > -1:
  585. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  586. vc_chosen_compiler_str = "amd64"
  587. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  588. if vc_amd64_x86_compiler_detection_index > -1 and (
  589. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  590. ):
  591. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  592. vc_chosen_compiler_str = "amd64_x86"
  593. # Now check the 32 bit compilers
  594. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  595. if vc_x86_compiler_detection_index > -1 and (
  596. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  597. ):
  598. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  599. vc_chosen_compiler_str = "x86"
  600. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  601. if vc_x86_amd64_compiler_detection_index > -1 and (
  602. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  603. ):
  604. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  605. vc_chosen_compiler_str = "x86_amd64"
  606. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  607. if "VCTOOLSINSTALLDIR" in tools_env:
  608. # Newer versions have a different path available
  609. vc_amd64_compiler_detection_index = (
  610. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  611. )
  612. if vc_amd64_compiler_detection_index > -1:
  613. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  614. vc_chosen_compiler_str = "amd64"
  615. vc_amd64_x86_compiler_detection_index = (
  616. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  617. )
  618. if vc_amd64_x86_compiler_detection_index > -1 and (
  619. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  620. ):
  621. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  622. vc_chosen_compiler_str = "amd64_x86"
  623. vc_x86_compiler_detection_index = (
  624. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  625. )
  626. if vc_x86_compiler_detection_index > -1 and (
  627. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  628. ):
  629. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  630. vc_chosen_compiler_str = "x86"
  631. vc_x86_amd64_compiler_detection_index = (
  632. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  633. )
  634. if vc_x86_amd64_compiler_detection_index > -1 and (
  635. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  636. ):
  637. vc_chosen_compiler_str = "x86_amd64"
  638. return vc_chosen_compiler_str
  639. def find_visual_c_batch_file(env):
  640. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file, find_vc_pdir
  641. msvc_version = get_default_version(env)
  642. # Syntax changed in SCons 4.4.0.
  643. if env.scons_version >= (4, 4, 0):
  644. (host_platform, target_platform, _) = get_host_target(env, msvc_version)
  645. else:
  646. (host_platform, target_platform, _) = get_host_target(env)
  647. if env.scons_version < (4, 6, 0):
  648. return find_batch_file(env, msvc_version, host_platform, target_platform)[0]
  649. # Scons 4.6.0+ removed passing env, so we need to get the product_dir ourselves first,
  650. # then pass that as the last param instead of env as the first param as before.
  651. # We should investigate if we can avoid relying on SCons internals here.
  652. product_dir = find_vc_pdir(env, msvc_version)
  653. return find_batch_file(msvc_version, host_platform, target_platform, product_dir)[0]
  654. def generate_cpp_hint_file(filename):
  655. if os.path.isfile(filename):
  656. # Don't overwrite an existing hint file since the user may have customized it.
  657. pass
  658. else:
  659. try:
  660. with open(filename, "w", encoding="utf-8", newline="\n") as fd:
  661. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  662. except OSError:
  663. print_warning("Could not write cpp.hint file.")
  664. def glob_recursive(pattern, node="."):
  665. from SCons import Node
  666. from SCons.Script import Glob
  667. results = []
  668. for f in Glob(str(node) + "/*", source=True):
  669. if type(f) is Node.FS.Dir:
  670. results += glob_recursive(pattern, f)
  671. results += Glob(str(node) + "/" + pattern, source=True)
  672. return results
  673. def add_to_vs_project(env, sources):
  674. for x in sources:
  675. if type(x) == type(""):
  676. fname = env.File(x).path
  677. else:
  678. fname = env.File(x)[0].path
  679. pieces = fname.split(".")
  680. if len(pieces) > 0:
  681. basename = pieces[0]
  682. basename = basename.replace("\\\\", "/")
  683. if os.path.isfile(basename + ".h"):
  684. env.vs_incs += [basename + ".h"]
  685. elif os.path.isfile(basename + ".hpp"):
  686. env.vs_incs += [basename + ".hpp"]
  687. if os.path.isfile(basename + ".c"):
  688. env.vs_srcs += [basename + ".c"]
  689. elif os.path.isfile(basename + ".cpp"):
  690. env.vs_srcs += [basename + ".cpp"]
  691. def precious_program(env, program, sources, **args):
  692. program = env.ProgramOriginal(program, sources, **args)
  693. env.Precious(program)
  694. return program
  695. def add_shared_library(env, name, sources, **args):
  696. library = env.SharedLibrary(name, sources, **args)
  697. env.NoCache(library)
  698. return library
  699. def add_library(env, name, sources, **args):
  700. library = env.Library(name, sources, **args)
  701. env.NoCache(library)
  702. return library
  703. def add_program(env, name, sources, **args):
  704. program = env.Program(name, sources, **args)
  705. env.NoCache(program)
  706. return program
  707. def CommandNoCache(env, target, sources, command, **args):
  708. result = env.Command(target, sources, command, **args)
  709. env.NoCache(result)
  710. return result
  711. def Run(env, function):
  712. from SCons.Script import Action
  713. return Action(function, "$GENCOMSTR")
  714. def detect_darwin_sdk_path(platform, env):
  715. sdk_name = ""
  716. if platform == "macos":
  717. sdk_name = "macosx"
  718. var_name = "MACOS_SDK_PATH"
  719. elif platform == "ios":
  720. sdk_name = "iphoneos"
  721. var_name = "IOS_SDK_PATH"
  722. elif platform == "iossimulator":
  723. sdk_name = "iphonesimulator"
  724. var_name = "IOS_SDK_PATH"
  725. else:
  726. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  727. if not env[var_name]:
  728. try:
  729. sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8")
  730. if sdk_path:
  731. env[var_name] = sdk_path
  732. except (subprocess.CalledProcessError, OSError):
  733. print_error("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  734. raise
  735. def is_vanilla_clang(env):
  736. if not using_clang(env):
  737. return False
  738. try:
  739. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  740. except (subprocess.CalledProcessError, OSError):
  741. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  742. return False
  743. return not version.startswith("Apple")
  744. def get_compiler_version(env):
  745. """
  746. Returns a dictionary with various version information:
  747. - major, minor, patch: Version following semantic versioning system
  748. - metadata1, metadata2: Extra information
  749. - date: Date of the build
  750. """
  751. ret = {
  752. "major": -1,
  753. "minor": -1,
  754. "patch": -1,
  755. "metadata1": None,
  756. "metadata2": None,
  757. "date": None,
  758. "apple_major": -1,
  759. "apple_minor": -1,
  760. "apple_patch1": -1,
  761. "apple_patch2": -1,
  762. "apple_patch3": -1,
  763. }
  764. if not env.msvc:
  765. # Not using -dumpversion as some GCC distros only return major, and
  766. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  767. try:
  768. version = (
  769. subprocess.check_output([env.subst(env["CXX"]), "--version"], shell=(os.name == "nt"))
  770. .strip()
  771. .decode("utf-8")
  772. )
  773. except (subprocess.CalledProcessError, OSError):
  774. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  775. return ret
  776. else:
  777. # TODO: Implement for MSVC
  778. return ret
  779. match = re.search(
  780. r"(?:(?<=version )|(?<=\) )|(?<=^))"
  781. r"(?P<major>\d+)"
  782. r"(?:\.(?P<minor>\d*))?"
  783. r"(?:\.(?P<patch>\d*))?"
  784. r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  785. r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  786. r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  787. version,
  788. )
  789. if match is not None:
  790. for key, value in match.groupdict().items():
  791. if value is not None:
  792. ret[key] = value
  793. match_apple = re.search(
  794. r"(?:(?<=clang-)|(?<=\) )|(?<=^))"
  795. r"(?P<apple_major>\d+)"
  796. r"(?:\.(?P<apple_minor>\d*))?"
  797. r"(?:\.(?P<apple_patch1>\d*))?"
  798. r"(?:\.(?P<apple_patch2>\d*))?"
  799. r"(?:\.(?P<apple_patch3>\d*))?",
  800. version,
  801. )
  802. if match_apple is not None:
  803. for key, value in match_apple.groupdict().items():
  804. if value is not None:
  805. ret[key] = value
  806. # Transform semantic versioning to integers
  807. for key in [
  808. "major",
  809. "minor",
  810. "patch",
  811. "apple_major",
  812. "apple_minor",
  813. "apple_patch1",
  814. "apple_patch2",
  815. "apple_patch3",
  816. ]:
  817. ret[key] = int(ret[key] or -1)
  818. return ret
  819. def using_gcc(env):
  820. return "gcc" in os.path.basename(env["CC"])
  821. def using_clang(env):
  822. return "clang" in os.path.basename(env["CC"])
  823. def using_emcc(env):
  824. return "emcc" in os.path.basename(env["CC"])
  825. def show_progress(env):
  826. if env["ninja"]:
  827. # Has its own progress/tracking tool that clashes with ours
  828. return
  829. import sys
  830. from SCons.Script import Progress, Command, AlwaysBuild
  831. screen = sys.stdout
  832. # Progress reporting is not available in non-TTY environments since it
  833. # messes with the output (for example, when writing to a file)
  834. show_progress = env["progress"] and sys.stdout.isatty()
  835. node_count = 0
  836. node_count_max = 0
  837. node_count_interval = 1
  838. node_count_fname = str(env.Dir("#")) + "/.scons_node_count"
  839. import time, math
  840. class cache_progress:
  841. # The default is 1 GB cache and 12 hours half life
  842. def __init__(self, path=None, limit=1073741824, half_life=43200):
  843. self.path = path
  844. self.limit = limit
  845. self.exponent_scale = math.log(2) / half_life
  846. if env["verbose"] and path != None:
  847. screen.write(
  848. "Current cache limit is {} (used: {})\n".format(
  849. self.convert_size(limit), self.convert_size(self.get_size(path))
  850. )
  851. )
  852. self.delete(self.file_list())
  853. def __call__(self, node, *args, **kw):
  854. nonlocal node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  855. if show_progress:
  856. # Print the progress percentage
  857. node_count += node_count_interval
  858. if node_count_max > 0 and node_count <= node_count_max:
  859. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  860. screen.flush()
  861. elif node_count_max > 0 and node_count > node_count_max:
  862. screen.write("\r[100%] ")
  863. screen.flush()
  864. else:
  865. screen.write("\r[Initial build] ")
  866. screen.flush()
  867. def delete(self, files):
  868. if len(files) == 0:
  869. return
  870. if env["verbose"]:
  871. # Utter something
  872. screen.write("\rPurging %d %s from cache...\n" % (len(files), len(files) > 1 and "files" or "file"))
  873. [os.remove(f) for f in files]
  874. def file_list(self):
  875. if self.path is None:
  876. # Nothing to do
  877. return []
  878. # Gather a list of (filename, (size, atime)) within the
  879. # cache directory
  880. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  881. if file_stat == []:
  882. # Nothing to do
  883. return []
  884. # Weight the cache files by size (assumed to be roughly
  885. # proportional to the recompilation time) times an exponential
  886. # decay since the ctime, and return a list with the entries
  887. # (filename, size, weight).
  888. current_time = time.time()
  889. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  890. # Sort by the most recently accessed files (most sensible to keep) first
  891. file_stat.sort(key=lambda x: x[2])
  892. # Search for the first entry where the storage limit is
  893. # reached
  894. sum, mark = 0, None
  895. for i, x in enumerate(file_stat):
  896. sum += x[1]
  897. if sum > self.limit:
  898. mark = i
  899. break
  900. if mark is None:
  901. return []
  902. else:
  903. return [x[0] for x in file_stat[mark:]]
  904. def convert_size(self, size_bytes):
  905. if size_bytes == 0:
  906. return "0 bytes"
  907. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  908. i = int(math.floor(math.log(size_bytes, 1024)))
  909. p = math.pow(1024, i)
  910. s = round(size_bytes / p, 2)
  911. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  912. def get_size(self, start_path="."):
  913. total_size = 0
  914. for dirpath, dirnames, filenames in os.walk(start_path):
  915. for f in filenames:
  916. fp = os.path.join(dirpath, f)
  917. total_size += os.path.getsize(fp)
  918. return total_size
  919. def progress_finish(target, source, env):
  920. nonlocal node_count, progressor
  921. try:
  922. with open(node_count_fname, "w", encoding="utf-8", newline="\n") as f:
  923. f.write("%d\n" % node_count)
  924. progressor.delete(progressor.file_list())
  925. except Exception:
  926. pass
  927. try:
  928. with open(node_count_fname) as f:
  929. node_count_max = int(f.readline())
  930. except Exception:
  931. pass
  932. cache_directory = os.environ.get("SCONS_CACHE")
  933. # Simple cache pruning, attached to SCons' progress callback. Trim the
  934. # cache directory to a size not larger than cache_limit.
  935. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  936. progressor = cache_progress(cache_directory, cache_limit)
  937. Progress(progressor, interval=node_count_interval)
  938. progress_finish_command = Command("progress_finish", [], progress_finish)
  939. AlwaysBuild(progress_finish_command)
  940. def dump(env):
  941. # Dumps latest build information for debugging purposes and external tools.
  942. from json import dump
  943. def non_serializable(obj):
  944. return "<<non-serializable: %s>>" % (type(obj).__qualname__)
  945. with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as f:
  946. dump(env.Dictionary(), f, indent=4, default=non_serializable)
  947. # Custom Visual Studio project generation logic that supports any platform that has a msvs.py
  948. # script, so Visual Studio can be used to run scons for any platform, with the right defines per target.
  949. # Invoked with scons vsproj=yes
  950. #
  951. # Only platforms that opt in to vs proj generation by having a msvs.py file in the platform folder are included.
  952. # Platforms with a msvs.py file will be added to the solution, but only the current active platform+target+arch
  953. # will have a build configuration generated, because we only know what the right defines/includes/flags/etc are
  954. # on the active build target.
  955. #
  956. # Platforms that don't support an editor target will have a dummy editor target that won't do anything on build,
  957. # but will have the files and configuration for the windows editor target.
  958. #
  959. # To generate build configuration files for all platforms+targets+arch combinations, users can call
  960. # scons vsproj=yes
  961. # for each combination of platform+target+arch. This will generate the relevant vs project files but
  962. # skip the build process. This lets project files be quickly generated even if there are build errors.
  963. #
  964. # To generate AND build from the command line:
  965. # scons vsproj=yes vsproj_gen_only=yes
  966. def generate_vs_project(env, original_args, project_name="godot"):
  967. # Augmented glob_recursive that also fills the dirs argument with traversed directories that have content.
  968. def glob_recursive_2(pattern, dirs, node="."):
  969. from SCons import Node
  970. from SCons.Script import Glob
  971. results = []
  972. for f in Glob(str(node) + "/*", source=True):
  973. if type(f) is Node.FS.Dir:
  974. results += glob_recursive_2(pattern, dirs, f)
  975. r = Glob(str(node) + "/" + pattern, source=True)
  976. if len(r) > 0 and not str(node) in dirs:
  977. d = ""
  978. for part in str(node).split("\\"):
  979. d += part
  980. if not d in dirs:
  981. dirs.append(d)
  982. d += "\\"
  983. results += r
  984. return results
  985. def get_bool(args, option, default):
  986. from SCons.Variables.BoolVariable import _text2bool
  987. val = args.get(option, default)
  988. if val is not None:
  989. try:
  990. return _text2bool(val)
  991. except:
  992. return default
  993. else:
  994. return default
  995. def format_key_value(v):
  996. if type(v) in [tuple, list]:
  997. return v[0] if len(v) == 1 else f"{v[0]}={v[1]}"
  998. return v
  999. filtered_args = original_args.copy()
  1000. # Ignore the "vsproj" option to not regenerate the VS project on every build
  1001. filtered_args.pop("vsproj", None)
  1002. # This flag allows users to regenerate the proj files but skip the building process.
  1003. # This lets projects be regenerated even if there are build errors.
  1004. filtered_args.pop("vsproj_gen_only", None)
  1005. # This flag allows users to regenerate only the props file without touching the sln or vcxproj files.
  1006. # This preserves any customizations users have done to the solution, while still updating the file list
  1007. # and build commands.
  1008. filtered_args.pop("vsproj_props_only", None)
  1009. # The "progress" option is ignored as the current compilation progress indication doesn't work in VS
  1010. filtered_args.pop("progress", None)
  1011. # We add these three manually because they might not be explicitly passed in, and it's important to always set them.
  1012. filtered_args.pop("platform", None)
  1013. filtered_args.pop("target", None)
  1014. filtered_args.pop("arch", None)
  1015. platform = env["platform"]
  1016. target = env["target"]
  1017. arch = env["arch"]
  1018. vs_configuration = {}
  1019. common_build_prefix = []
  1020. confs = []
  1021. for x in sorted(glob.glob("platform/*")):
  1022. # Only platforms that opt in to vs proj generation are included.
  1023. if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"):
  1024. continue
  1025. tmppath = "./" + x
  1026. sys.path.insert(0, tmppath)
  1027. import msvs
  1028. vs_plats = []
  1029. vs_confs = []
  1030. try:
  1031. platform_name = x[9:]
  1032. vs_plats = msvs.get_platforms()
  1033. vs_confs = msvs.get_configurations()
  1034. val = []
  1035. for plat in vs_plats:
  1036. val += [{"platform": plat[0], "architecture": plat[1]}]
  1037. vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val}
  1038. confs += [vsconf]
  1039. # Save additional information about the configuration for the actively selected platform,
  1040. # so we can generate the platform-specific props file with all the build commands/defines/etc
  1041. if platform == platform_name:
  1042. common_build_prefix = msvs.get_build_prefix(env)
  1043. vs_configuration = vsconf
  1044. except Exception:
  1045. pass
  1046. sys.path.remove(tmppath)
  1047. sys.modules.pop("msvs")
  1048. headers = []
  1049. headers_dirs = []
  1050. for file in glob_recursive_2("*.h", headers_dirs):
  1051. headers.append(str(file).replace("/", "\\"))
  1052. for file in glob_recursive_2("*.hpp", headers_dirs):
  1053. headers.append(str(file).replace("/", "\\"))
  1054. sources = []
  1055. sources_dirs = []
  1056. for file in glob_recursive_2("*.cpp", sources_dirs):
  1057. sources.append(str(file).replace("/", "\\"))
  1058. for file in glob_recursive_2("*.c", sources_dirs):
  1059. sources.append(str(file).replace("/", "\\"))
  1060. others = []
  1061. others_dirs = []
  1062. for file in glob_recursive_2("*.natvis", others_dirs):
  1063. others.append(str(file).replace("/", "\\"))
  1064. for file in glob_recursive_2("*.glsl", others_dirs):
  1065. others.append(str(file).replace("/", "\\"))
  1066. skip_filters = False
  1067. import hashlib
  1068. import json
  1069. md5 = hashlib.md5(
  1070. json.dumps(headers + headers_dirs + sources + sources_dirs + others + others_dirs, sort_keys=True).encode(
  1071. "utf-8"
  1072. )
  1073. ).hexdigest()
  1074. if os.path.exists(f"{project_name}.vcxproj.filters"):
  1075. with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file:
  1076. existing_filters = file.read()
  1077. match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters)
  1078. if match is not None and md5 == match.group(1):
  1079. skip_filters = True
  1080. import uuid
  1081. # Don't regenerate the filters file if nothing has changed, so we keep the existing UUIDs.
  1082. if not skip_filters:
  1083. print(f"Regenerating {project_name}.vcxproj.filters")
  1084. with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file:
  1085. filters_template = file.read()
  1086. for i in range(1, 10):
  1087. filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4()))
  1088. filters = ""
  1089. for d in headers_dirs:
  1090. filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1091. for d in sources_dirs:
  1092. filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1093. for d in others_dirs:
  1094. filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1095. filters_template = filters_template.replace("%%FILTERS%%", filters)
  1096. filters = ""
  1097. for file in headers:
  1098. filters += (
  1099. f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n'
  1100. )
  1101. filters_template = filters_template.replace("%%INCLUDES%%", filters)
  1102. filters = ""
  1103. for file in sources:
  1104. filters += (
  1105. f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n'
  1106. )
  1107. filters_template = filters_template.replace("%%COMPILES%%", filters)
  1108. filters = ""
  1109. for file in others:
  1110. filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n'
  1111. filters_template = filters_template.replace("%%OTHERS%%", filters)
  1112. filters_template = filters_template.replace("%%HASH%%", md5)
  1113. with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f:
  1114. f.write(filters_template)
  1115. envsources = []
  1116. envsources += env.core_sources
  1117. envsources += env.drivers_sources
  1118. envsources += env.main_sources
  1119. envsources += env.modules_sources
  1120. envsources += env.scene_sources
  1121. envsources += env.servers_sources
  1122. if env.editor_build:
  1123. envsources += env.editor_sources
  1124. envsources += env.platform_sources
  1125. headers_active = []
  1126. sources_active = []
  1127. others_active = []
  1128. for x in envsources:
  1129. fname = ""
  1130. if type(x) == type(""):
  1131. fname = env.File(x).path
  1132. else:
  1133. # Some object files might get added directly as a File object and not a list.
  1134. try:
  1135. fname = env.File(x)[0].path
  1136. except:
  1137. fname = x.path
  1138. pass
  1139. if fname:
  1140. fname = fname.replace("\\\\", "/")
  1141. parts = os.path.splitext(fname)
  1142. basename = parts[0]
  1143. ext = parts[1]
  1144. idx = fname.find(env["OBJSUFFIX"])
  1145. if ext in [".h", ".hpp"]:
  1146. headers_active += [fname]
  1147. elif ext in [".c", ".cpp"]:
  1148. sources_active += [fname]
  1149. elif idx > 0:
  1150. basename = fname[:idx]
  1151. if os.path.isfile(basename + ".h"):
  1152. headers_active += [basename + ".h"]
  1153. elif os.path.isfile(basename + ".hpp"):
  1154. headers_active += [basename + ".hpp"]
  1155. elif basename.endswith(".gen") and os.path.isfile(basename[:-4] + ".h"):
  1156. headers_active += [basename[:-4] + ".h"]
  1157. if os.path.isfile(basename + ".c"):
  1158. sources_active += [basename + ".c"]
  1159. elif os.path.isfile(basename + ".cpp"):
  1160. sources_active += [basename + ".cpp"]
  1161. else:
  1162. fname = os.path.relpath(os.path.abspath(fname), env.Dir("").abspath)
  1163. others_active += [fname]
  1164. all_items = []
  1165. properties = []
  1166. activeItems = []
  1167. extraItems = []
  1168. set_headers = set(headers_active)
  1169. set_sources = set(sources_active)
  1170. set_others = set(others_active)
  1171. for file in headers:
  1172. base_path = os.path.dirname(file).replace("\\", "_")
  1173. all_items.append(f'<ClInclude Include="{file}">')
  1174. all_items.append(
  1175. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1176. )
  1177. all_items.append("</ClInclude>")
  1178. if file in set_headers:
  1179. activeItems.append(file)
  1180. for file in sources:
  1181. base_path = os.path.dirname(file).replace("\\", "_")
  1182. all_items.append(f'<ClCompile Include="{file}">')
  1183. all_items.append(
  1184. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1185. )
  1186. all_items.append("</ClCompile>")
  1187. if file in set_sources:
  1188. activeItems.append(file)
  1189. for file in others:
  1190. base_path = os.path.dirname(file).replace("\\", "_")
  1191. all_items.append(f'<None Include="{file}">')
  1192. all_items.append(
  1193. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1194. )
  1195. all_items.append("</None>")
  1196. if file in set_others:
  1197. activeItems.append(file)
  1198. if vs_configuration:
  1199. vsconf = ""
  1200. for a in vs_configuration["arches"]:
  1201. if arch == a["architecture"]:
  1202. vsconf = f'{target}|{a["platform"]}'
  1203. break
  1204. condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'"
  1205. itemlist = {}
  1206. for item in activeItems:
  1207. key = os.path.dirname(item).replace("\\", "_")
  1208. if not key in itemlist:
  1209. itemlist[key] = [item]
  1210. else:
  1211. itemlist[key] += [item]
  1212. for x in itemlist.keys():
  1213. properties.append(
  1214. "<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x)
  1215. )
  1216. output = f'bin\\godot{env["PROGSUFFIX"]}'
  1217. with open("misc/msvs/props.template", "r", encoding="utf-8") as file:
  1218. props_template = file.read()
  1219. props_template = props_template.replace("%%VSCONF%%", vsconf)
  1220. props_template = props_template.replace("%%CONDITION%%", condition)
  1221. props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1222. props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems))
  1223. props_template = props_template.replace("%%OUTPUT%%", output)
  1224. proplist = [format_key_value(v) for v in list(env["CPPDEFINES"])]
  1225. proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])]
  1226. props_template = props_template.replace("%%DEFINES%%", ";".join(proplist))
  1227. proplist = [str(j) for j in env["CPPPATH"]]
  1228. proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])]
  1229. props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist))
  1230. proplist = env["CCFLAGS"]
  1231. proplist += [x for x in env["CXXFLAGS"] if not x.startswith("$")]
  1232. proplist += [str(j) for j in env.get("VSHINT_OPTIONS", [])]
  1233. props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist))
  1234. # Windows allows us to have spaces in paths, so we need
  1235. # to double quote off the directory. However, the path ends
  1236. # in a backslash, so we need to remove this, lest it escape the
  1237. # last double quote off, confusing MSBuild
  1238. common_build_postfix = [
  1239. "--directory=&quot;$(ProjectDir.TrimEnd(&apos;\\&apos;))&quot;",
  1240. "progress=no",
  1241. f"platform={platform}",
  1242. f"target={target}",
  1243. f"arch={arch}",
  1244. ]
  1245. for arg, value in filtered_args.items():
  1246. common_build_postfix.append(f"{arg}={value}")
  1247. cmd_rebuild = [
  1248. "vsproj=yes",
  1249. "vsproj_props_only=yes",
  1250. "vsproj_gen_only=no",
  1251. f"vsproj_name={project_name}",
  1252. ] + common_build_postfix
  1253. cmd_clean = [
  1254. "--clean",
  1255. ] + common_build_postfix
  1256. commands = "scons"
  1257. if len(common_build_prefix) == 0:
  1258. commands = "echo Starting SCons &amp;&amp; cmd /V /C " + commands
  1259. else:
  1260. common_build_prefix[0] = "echo Starting SCons &amp;&amp; cmd /V /C " + common_build_prefix[0]
  1261. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  1262. props_template = props_template.replace("%%BUILD%%", cmd)
  1263. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)])
  1264. props_template = props_template.replace("%%REBUILD%%", cmd)
  1265. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_clean)])
  1266. props_template = props_template.replace("%%CLEAN%%", cmd)
  1267. with open(
  1268. f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n"
  1269. ) as f:
  1270. f.write(props_template)
  1271. proj_uuid = str(uuid.uuid4())
  1272. sln_uuid = str(uuid.uuid4())
  1273. if os.path.exists(f"{project_name}.sln"):
  1274. for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines():
  1275. if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'):
  1276. proj_uuid = re.search(
  1277. 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)}\"$",
  1278. line,
  1279. ).group(1)
  1280. elif line.strip().startswith("SolutionGuid ="):
  1281. sln_uuid = re.search(
  1282. 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
  1283. ).group(1)
  1284. break
  1285. configurations = []
  1286. imports = []
  1287. properties = []
  1288. section1 = []
  1289. section2 = []
  1290. for conf in confs:
  1291. godot_platform = conf["platform"]
  1292. for p in conf["arches"]:
  1293. sln_plat = p["platform"]
  1294. proj_plat = sln_plat
  1295. godot_arch = p["architecture"]
  1296. # Redirect editor configurations for non-Windows platforms to the Windows one, so the solution has all the permutations
  1297. # and VS doesn't complain about missing project configurations.
  1298. # These configurations are disabled, so they show up but won't build.
  1299. if godot_platform != "windows":
  1300. section1 += [f"editor|{sln_plat} = editor|{proj_plat}"]
  1301. section2 += [
  1302. f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{proj_plat}",
  1303. ]
  1304. for t in conf["targets"]:
  1305. godot_target = t
  1306. # Windows x86 is a special little flower that requires a project platform == Win32 but a solution platform == x86.
  1307. if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32":
  1308. sln_plat = "x86"
  1309. configurations += [
  1310. f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">',
  1311. f" <Configuration>{godot_target}</Configuration>",
  1312. f" <Platform>{proj_plat}</Platform>",
  1313. "</ProjectConfiguration>",
  1314. ]
  1315. properties += [
  1316. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">",
  1317. f" <GodotConfiguration>{godot_target}</GodotConfiguration>",
  1318. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1319. "</PropertyGroup>",
  1320. ]
  1321. if godot_platform != "windows":
  1322. configurations += [
  1323. f'<ProjectConfiguration Include="editor|{proj_plat}">',
  1324. f" <Configuration>editor</Configuration>",
  1325. f" <Platform>{proj_plat}</Platform>",
  1326. "</ProjectConfiguration>",
  1327. ]
  1328. properties += [
  1329. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">",
  1330. f" <GodotConfiguration>editor</GodotConfiguration>",
  1331. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1332. "</PropertyGroup>",
  1333. ]
  1334. p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props"
  1335. imports += [
  1336. f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>'
  1337. ]
  1338. section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"]
  1339. section2 += [
  1340. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}",
  1341. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}",
  1342. ]
  1343. # Add an extra import for a local user props file at the end, so users can add more overrides.
  1344. imports += [
  1345. f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>'
  1346. ]
  1347. section1 = sorted(section1)
  1348. section2 = sorted(section2)
  1349. if not get_bool(original_args, "vsproj_props_only", False):
  1350. with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file:
  1351. proj_template = file.read()
  1352. proj_template = proj_template.replace("%%UUID%%", proj_uuid)
  1353. proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations))
  1354. proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports))
  1355. proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items))
  1356. proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1357. with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\n") as f:
  1358. f.write(proj_template)
  1359. if not get_bool(original_args, "vsproj_props_only", False):
  1360. with open("misc/msvs/sln.template", "r", encoding="utf-8") as file:
  1361. sln_template = file.read()
  1362. sln_template = sln_template.replace("%%NAME%%", project_name)
  1363. sln_template = sln_template.replace("%%UUID%%", proj_uuid)
  1364. sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid)
  1365. sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1))
  1366. sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2))
  1367. with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f:
  1368. f.write(sln_template)
  1369. if get_bool(original_args, "vsproj_gen_only", True):
  1370. sys.exit()