methods.py 62 KB

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