methods.py 62 KB

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