methods.py 61 KB

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