methods.py 59 KB

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